OSDN Git Service

2010-06-22 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch4.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 4                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Atag; use Exp_Atag;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch6;  use Exp_Ch6;
36 with Exp_Ch7;  use Exp_Ch7;
37 with Exp_Ch9;  use Exp_Ch9;
38 with Exp_Disp; use Exp_Disp;
39 with Exp_Fixd; use Exp_Fixd;
40 with Exp_Pakd; use Exp_Pakd;
41 with Exp_Tss;  use Exp_Tss;
42 with Exp_Util; use Exp_Util;
43 with Exp_VFpt; use Exp_VFpt;
44 with Freeze;   use Freeze;
45 with Inline;   use Inline;
46 with Namet;    use Namet;
47 with Nlists;   use Nlists;
48 with Nmake;    use Nmake;
49 with Opt;      use Opt;
50 with Par_SCO;  use Par_SCO;
51 with Restrict; use Restrict;
52 with Rident;   use Rident;
53 with Rtsfind;  use Rtsfind;
54 with Sem;      use Sem;
55 with Sem_Aux;  use Sem_Aux;
56 with Sem_Cat;  use Sem_Cat;
57 with Sem_Ch3;  use Sem_Ch3;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Eval; use Sem_Eval;
61 with Sem_Res;  use Sem_Res;
62 with Sem_SCIL; use Sem_SCIL;
63 with Sem_Type; use Sem_Type;
64 with Sem_Util; use Sem_Util;
65 with Sem_Warn; use Sem_Warn;
66 with Sinfo;    use Sinfo;
67 with Snames;   use Snames;
68 with Stand;    use Stand;
69 with Targparm; use Targparm;
70 with Tbuild;   use Tbuild;
71 with Ttypes;   use Ttypes;
72 with Uintp;    use Uintp;
73 with Urealp;   use Urealp;
74 with Validsw;  use Validsw;
75
76 package body Exp_Ch4 is
77
78    -----------------------
79    -- Local Subprograms --
80    -----------------------
81
82    procedure Binary_Op_Validity_Checks (N : Node_Id);
83    pragma Inline (Binary_Op_Validity_Checks);
84    --  Performs validity checks for a binary operator
85
86    procedure Build_Boolean_Array_Proc_Call
87      (N   : Node_Id;
88       Op1 : Node_Id;
89       Op2 : Node_Id);
90    --  If a boolean array assignment can be done in place, build call to
91    --  corresponding library procedure.
92
93    procedure Displace_Allocator_Pointer (N : Node_Id);
94    --  Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
95    --  Expand_Allocator_Expression. Allocating class-wide interface objects
96    --  this routine displaces the pointer to the allocated object to reference
97    --  the component referencing the corresponding secondary dispatch table.
98
99    procedure Expand_Allocator_Expression (N : Node_Id);
100    --  Subsidiary to Expand_N_Allocator, for the case when the expression
101    --  is a qualified expression or an aggregate.
102
103    procedure Expand_Array_Comparison (N : Node_Id);
104    --  This routine handles expansion of the comparison operators (N_Op_Lt,
105    --  N_Op_Le, N_Op_Gt, N_Op_Ge) when operating on an array type. The basic
106    --  code for these operators is similar, differing only in the details of
107    --  the actual comparison call that is made. Special processing (call a
108    --  run-time routine)
109
110    function Expand_Array_Equality
111      (Nod    : Node_Id;
112       Lhs    : Node_Id;
113       Rhs    : Node_Id;
114       Bodies : List_Id;
115       Typ    : Entity_Id) return Node_Id;
116    --  Expand an array equality into a call to a function implementing this
117    --  equality, and a call to it. Loc is the location for the generated nodes.
118    --  Lhs and Rhs are the array expressions to be compared. Bodies is a list
119    --  on which to attach bodies of local functions that are created in the
120    --  process. It is the responsibility of the caller to insert those bodies
121    --  at the right place. Nod provides the Sloc value for the generated code.
122    --  Normally the types used for the generated equality routine are taken
123    --  from Lhs and Rhs. However, in some situations of generated code, the
124    --  Etype fields of Lhs and Rhs are not set yet. In such cases, Typ supplies
125    --  the type to be used for the formal parameters.
126
127    procedure Expand_Boolean_Operator (N : Node_Id);
128    --  Common expansion processing for Boolean operators (And, Or, Xor) for the
129    --  case of array type arguments.
130
131    procedure Expand_Short_Circuit_Operator (N : Node_Id);
132    --  Common expansion processing for short-circuit boolean operators
133
134    function Expand_Composite_Equality
135      (Nod    : Node_Id;
136       Typ    : Entity_Id;
137       Lhs    : Node_Id;
138       Rhs    : Node_Id;
139       Bodies : List_Id) return Node_Id;
140    --  Local recursive function used to expand equality for nested composite
141    --  types. Used by Expand_Record/Array_Equality, Bodies is a list on which
142    --  to attach bodies of local functions that are created in the process.
143    --  This is the responsibility of the caller to insert those bodies at the
144    --  right place. Nod provides the Sloc value for generated code. Lhs and Rhs
145    --  are the left and right sides for the comparison, and Typ is the type of
146    --  the arrays to compare.
147
148    procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id);
149    --  Routine to expand concatenation of a sequence of two or more operands
150    --  (in the list Operands) and replace node Cnode with the result of the
151    --  concatenation. The operands can be of any appropriate type, and can
152    --  include both arrays and singleton elements.
153
154    procedure Fixup_Universal_Fixed_Operation (N : Node_Id);
155    --  N is a N_Op_Divide or N_Op_Multiply node whose result is universal
156    --  fixed. We do not have such a type at runtime, so the purpose of this
157    --  routine is to find the real type by looking up the tree. We also
158    --  determine if the operation must be rounded.
159
160    function Get_Allocator_Final_List
161      (N    : Node_Id;
162       T    : Entity_Id;
163       PtrT : Entity_Id) return Entity_Id;
164    --  If the designated type is controlled, build final_list expression for
165    --  created object. If context is an access parameter, create a local access
166    --  type to have a usable finalization list.
167
168    function Has_Inferable_Discriminants (N : Node_Id) return Boolean;
169    --  Ada 2005 (AI-216): A view of an Unchecked_Union object has inferable
170    --  discriminants if it has a constrained nominal type, unless the object
171    --  is a component of an enclosing Unchecked_Union object that is subject
172    --  to a per-object constraint and the enclosing object lacks inferable
173    --  discriminants.
174    --
175    --  An expression of an Unchecked_Union type has inferable discriminants
176    --  if it is either a name of an object with inferable discriminants or a
177    --  qualified expression whose subtype mark denotes a constrained subtype.
178
179    procedure Insert_Dereference_Action (N : Node_Id);
180    --  N is an expression whose type is an access. When the type of the
181    --  associated storage pool is derived from Checked_Pool, generate a
182    --  call to the 'Dereference' primitive operation.
183
184    function Make_Array_Comparison_Op
185      (Typ : Entity_Id;
186       Nod : Node_Id) return Node_Id;
187    --  Comparisons between arrays are expanded in line. This function produces
188    --  the body of the implementation of (a > b), where a and b are one-
189    --  dimensional arrays of some discrete type. The original node is then
190    --  expanded into the appropriate call to this function. Nod provides the
191    --  Sloc value for the generated code.
192
193    function Make_Boolean_Array_Op
194      (Typ : Entity_Id;
195       N   : Node_Id) return Node_Id;
196    --  Boolean operations on boolean arrays are expanded in line. This function
197    --  produce the body for the node N, which is (a and b), (a or b), or (a xor
198    --  b). It is used only the normal case and not the packed case. The type
199    --  involved, Typ, is the Boolean array type, and the logical operations in
200    --  the body are simple boolean operations. Note that Typ is always a
201    --  constrained type (the caller has ensured this by using
202    --  Convert_To_Actual_Subtype if necessary).
203
204    procedure Rewrite_Comparison (N : Node_Id);
205    --  If N is the node for a comparison whose outcome can be determined at
206    --  compile time, then the node N can be rewritten with True or False. If
207    --  the outcome cannot be determined at compile time, the call has no
208    --  effect. If N is a type conversion, then this processing is applied to
209    --  its expression. If N is neither comparison nor a type conversion, the
210    --  call has no effect.
211
212    procedure Tagged_Membership
213      (N         : Node_Id;
214       SCIL_Node : out Node_Id;
215       Result    : out Node_Id);
216    --  Construct the expression corresponding to the tagged membership test.
217    --  Deals with a second operand being (or not) a class-wide type.
218
219    function Safe_In_Place_Array_Op
220      (Lhs : Node_Id;
221       Op1 : Node_Id;
222       Op2 : Node_Id) return Boolean;
223    --  In the context of an assignment, where the right-hand side is a boolean
224    --  operation on arrays, check whether operation can be performed in place.
225
226    procedure Unary_Op_Validity_Checks (N : Node_Id);
227    pragma Inline (Unary_Op_Validity_Checks);
228    --  Performs validity checks for a unary operator
229
230    -------------------------------
231    -- Binary_Op_Validity_Checks --
232    -------------------------------
233
234    procedure Binary_Op_Validity_Checks (N : Node_Id) is
235    begin
236       if Validity_Checks_On and Validity_Check_Operands then
237          Ensure_Valid (Left_Opnd (N));
238          Ensure_Valid (Right_Opnd (N));
239       end if;
240    end Binary_Op_Validity_Checks;
241
242    ------------------------------------
243    -- Build_Boolean_Array_Proc_Call --
244    ------------------------------------
245
246    procedure Build_Boolean_Array_Proc_Call
247      (N   : Node_Id;
248       Op1 : Node_Id;
249       Op2 : Node_Id)
250    is
251       Loc       : constant Source_Ptr := Sloc (N);
252       Kind      : constant Node_Kind := Nkind (Expression (N));
253       Target    : constant Node_Id   :=
254                     Make_Attribute_Reference (Loc,
255                       Prefix         => Name (N),
256                       Attribute_Name => Name_Address);
257
258       Arg1      : constant Node_Id := Op1;
259       Arg2      : Node_Id := Op2;
260       Call_Node : Node_Id;
261       Proc_Name : Entity_Id;
262
263    begin
264       if Kind = N_Op_Not then
265          if Nkind (Op1) in N_Binary_Op then
266
267             --  Use negated version of the binary operators
268
269             if Nkind (Op1) = N_Op_And then
270                Proc_Name := RTE (RE_Vector_Nand);
271
272             elsif Nkind (Op1) = N_Op_Or then
273                Proc_Name := RTE (RE_Vector_Nor);
274
275             else pragma Assert (Nkind (Op1) = N_Op_Xor);
276                Proc_Name := RTE (RE_Vector_Xor);
277             end if;
278
279             Call_Node :=
280               Make_Procedure_Call_Statement (Loc,
281                 Name => New_Occurrence_Of (Proc_Name, Loc),
282
283                 Parameter_Associations => New_List (
284                   Target,
285                   Make_Attribute_Reference (Loc,
286                     Prefix => Left_Opnd (Op1),
287                     Attribute_Name => Name_Address),
288
289                   Make_Attribute_Reference (Loc,
290                     Prefix => Right_Opnd (Op1),
291                     Attribute_Name => Name_Address),
292
293                   Make_Attribute_Reference (Loc,
294                     Prefix => Left_Opnd (Op1),
295                     Attribute_Name => Name_Length)));
296
297          else
298             Proc_Name := RTE (RE_Vector_Not);
299
300             Call_Node :=
301               Make_Procedure_Call_Statement (Loc,
302                 Name => New_Occurrence_Of (Proc_Name, Loc),
303                 Parameter_Associations => New_List (
304                   Target,
305
306                   Make_Attribute_Reference (Loc,
307                     Prefix => Op1,
308                     Attribute_Name => Name_Address),
309
310                   Make_Attribute_Reference (Loc,
311                     Prefix => Op1,
312                      Attribute_Name => Name_Length)));
313          end if;
314
315       else
316          --  We use the following equivalences:
317
318          --   (not X) or  (not Y)  =  not (X and Y)  =  Nand (X, Y)
319          --   (not X) and (not Y)  =  not (X or Y)   =  Nor  (X, Y)
320          --   (not X) xor (not Y)  =  X xor Y
321          --   X       xor (not Y)  =  not (X xor Y)  =  Nxor (X, Y)
322
323          if Nkind (Op1) = N_Op_Not then
324             if Kind = N_Op_And then
325                Proc_Name := RTE (RE_Vector_Nor);
326             elsif Kind = N_Op_Or then
327                Proc_Name := RTE (RE_Vector_Nand);
328             else
329                Proc_Name := RTE (RE_Vector_Xor);
330             end if;
331
332          else
333             if Kind = N_Op_And then
334                Proc_Name := RTE (RE_Vector_And);
335             elsif Kind = N_Op_Or then
336                Proc_Name := RTE (RE_Vector_Or);
337             elsif Nkind (Op2) = N_Op_Not then
338                Proc_Name := RTE (RE_Vector_Nxor);
339                Arg2 := Right_Opnd (Op2);
340             else
341                Proc_Name := RTE (RE_Vector_Xor);
342             end if;
343          end if;
344
345          Call_Node :=
346            Make_Procedure_Call_Statement (Loc,
347              Name => New_Occurrence_Of (Proc_Name, Loc),
348              Parameter_Associations => New_List (
349                Target,
350                Make_Attribute_Reference (Loc,
351                  Prefix         => Arg1,
352                  Attribute_Name => Name_Address),
353                Make_Attribute_Reference (Loc,
354                  Prefix         => Arg2,
355                  Attribute_Name => Name_Address),
356                Make_Attribute_Reference (Loc,
357                  Prefix         => Op1,
358                  Attribute_Name => Name_Length)));
359       end if;
360
361       Rewrite (N, Call_Node);
362       Analyze (N);
363
364    exception
365       when RE_Not_Available =>
366          return;
367    end Build_Boolean_Array_Proc_Call;
368
369    --------------------------------
370    -- Displace_Allocator_Pointer --
371    --------------------------------
372
373    procedure Displace_Allocator_Pointer (N : Node_Id) is
374       Loc       : constant Source_Ptr := Sloc (N);
375       Orig_Node : constant Node_Id := Original_Node (N);
376       Dtyp      : Entity_Id;
377       Etyp      : Entity_Id;
378       PtrT      : Entity_Id;
379
380    begin
381       --  Do nothing in case of VM targets: the virtual machine will handle
382       --  interfaces directly.
383
384       if not Tagged_Type_Expansion then
385          return;
386       end if;
387
388       pragma Assert (Nkind (N) = N_Identifier
389         and then Nkind (Orig_Node) = N_Allocator);
390
391       PtrT := Etype (Orig_Node);
392       Dtyp := Available_View (Designated_Type (PtrT));
393       Etyp := Etype (Expression (Orig_Node));
394
395       if Is_Class_Wide_Type (Dtyp)
396         and then Is_Interface (Dtyp)
397       then
398          --  If the type of the allocator expression is not an interface type
399          --  we can generate code to reference the record component containing
400          --  the pointer to the secondary dispatch table.
401
402          if not Is_Interface (Etyp) then
403             declare
404                Saved_Typ : constant Entity_Id := Etype (Orig_Node);
405
406             begin
407                --  1) Get access to the allocated object
408
409                Rewrite (N,
410                  Make_Explicit_Dereference (Loc,
411                    Relocate_Node (N)));
412                Set_Etype (N, Etyp);
413                Set_Analyzed (N);
414
415                --  2) Add the conversion to displace the pointer to reference
416                --     the secondary dispatch table.
417
418                Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
419                Analyze_And_Resolve (N, Dtyp);
420
421                --  3) The 'access to the secondary dispatch table will be used
422                --     as the value returned by the allocator.
423
424                Rewrite (N,
425                  Make_Attribute_Reference (Loc,
426                    Prefix         => Relocate_Node (N),
427                    Attribute_Name => Name_Access));
428                Set_Etype (N, Saved_Typ);
429                Set_Analyzed (N);
430             end;
431
432          --  If the type of the allocator expression is an interface type we
433          --  generate a run-time call to displace "this" to reference the
434          --  component containing the pointer to the secondary dispatch table
435          --  or else raise Constraint_Error if the actual object does not
436          --  implement the target interface. This case corresponds with the
437          --  following example:
438
439          --   function Op (Obj : Iface_1'Class) return access Iface_2'Class is
440          --   begin
441          --      return new Iface_2'Class'(Obj);
442          --   end Op;
443
444          else
445             Rewrite (N,
446               Unchecked_Convert_To (PtrT,
447                 Make_Function_Call (Loc,
448                   Name => New_Reference_To (RTE (RE_Displace), Loc),
449                   Parameter_Associations => New_List (
450                     Unchecked_Convert_To (RTE (RE_Address),
451                       Relocate_Node (N)),
452
453                     New_Occurrence_Of
454                       (Elists.Node
455                         (First_Elmt
456                           (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
457                        Loc)))));
458             Analyze_And_Resolve (N, PtrT);
459          end if;
460       end if;
461    end Displace_Allocator_Pointer;
462
463    ---------------------------------
464    -- Expand_Allocator_Expression --
465    ---------------------------------
466
467    procedure Expand_Allocator_Expression (N : Node_Id) is
468       Loc    : constant Source_Ptr := Sloc (N);
469       Exp    : constant Node_Id    := Expression (Expression (N));
470       PtrT   : constant Entity_Id  := Etype (N);
471       DesigT : constant Entity_Id  := Designated_Type (PtrT);
472
473       procedure Apply_Accessibility_Check
474         (Ref            : Node_Id;
475          Built_In_Place : Boolean := False);
476       --  Ada 2005 (AI-344): For an allocator with a class-wide designated
477       --  type, generate an accessibility check to verify that the level of the
478       --  type of the created object is not deeper than the level of the access
479       --  type. If the type of the qualified expression is class- wide, then
480       --  always generate the check (except in the case where it is known to be
481       --  unnecessary, see comment below). Otherwise, only generate the check
482       --  if the level of the qualified expression type is statically deeper
483       --  than the access type.
484       --
485       --  Although the static accessibility will generally have been performed
486       --  as a legality check, it won't have been done in cases where the
487       --  allocator appears in generic body, so a run-time check is needed in
488       --  general. One special case is when the access type is declared in the
489       --  same scope as the class-wide allocator, in which case the check can
490       --  never fail, so it need not be generated.
491       --
492       --  As an open issue, there seem to be cases where the static level
493       --  associated with the class-wide object's underlying type is not
494       --  sufficient to perform the proper accessibility check, such as for
495       --  allocators in nested subprograms or accept statements initialized by
496       --  class-wide formals when the actual originates outside at a deeper
497       --  static level. The nested subprogram case might require passing
498       --  accessibility levels along with class-wide parameters, and the task
499       --  case seems to be an actual gap in the language rules that needs to
500       --  be fixed by the ARG. ???
501
502       -------------------------------
503       -- Apply_Accessibility_Check --
504       -------------------------------
505
506       procedure Apply_Accessibility_Check
507         (Ref            : Node_Id;
508          Built_In_Place : Boolean := False)
509       is
510          Ref_Node : Node_Id;
511
512       begin
513          --  Note: we skip the accessibility check for the VM case, since
514          --  there does not seem to be any practical way of implementing it.
515
516          if Ada_Version >= Ada_05
517            and then Tagged_Type_Expansion
518            and then Is_Class_Wide_Type (DesigT)
519            and then not Scope_Suppress (Accessibility_Check)
520            and then
521              (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
522                or else
523                  (Is_Class_Wide_Type (Etype (Exp))
524                    and then Scope (PtrT) /= Current_Scope))
525          then
526             --  If the allocator was built in place Ref is already a reference
527             --  to the access object initialized to the result of the allocator
528             --  (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). Otherwise
529             --  it is the entity associated with the object containing the
530             --  address of the allocated object.
531
532             if Built_In_Place then
533                Ref_Node := New_Copy (Ref);
534             else
535                Ref_Node := New_Reference_To (Ref, Loc);
536             end if;
537
538             Insert_Action (N,
539                Make_Raise_Program_Error (Loc,
540                  Condition =>
541                    Make_Op_Gt (Loc,
542                      Left_Opnd  =>
543                        Build_Get_Access_Level (Loc,
544                          Make_Attribute_Reference (Loc,
545                            Prefix => Ref_Node,
546                            Attribute_Name => Name_Tag)),
547                      Right_Opnd =>
548                        Make_Integer_Literal (Loc,
549                          Type_Access_Level (PtrT))),
550                  Reason => PE_Accessibility_Check_Failed));
551          end if;
552       end Apply_Accessibility_Check;
553
554       --  Local variables
555
556       Indic : constant Node_Id   := Subtype_Mark (Expression (N));
557       T     : constant Entity_Id := Entity (Indic);
558       Flist : Node_Id;
559       Node  : Node_Id;
560       Temp  : Entity_Id;
561
562       TagT : Entity_Id := Empty;
563       --  Type used as source for tag assignment
564
565       TagR : Node_Id := Empty;
566       --  Target reference for tag assignment
567
568       Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
569
570       Tag_Assign : Node_Id;
571       Tmp_Node   : Node_Id;
572
573    --  Start of processing for Expand_Allocator_Expression
574
575    begin
576       if Is_Tagged_Type (T) or else Needs_Finalization (T) then
577
578          if Is_CPP_Constructor_Call (Exp) then
579
580             --  Generate:
581             --  Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn
582
583             --  Allocate the object with no expression
584
585             Node := Relocate_Node (N);
586             Set_Expression (Node, New_Reference_To (Etype (Exp), Loc));
587
588             --  Avoid its expansion to avoid generating a call to the default
589             --  C++ constructor
590
591             Set_Analyzed (Node);
592
593             Temp := Make_Temporary (Loc, 'P', N);
594
595             Insert_Action (N,
596               Make_Object_Declaration (Loc,
597                 Defining_Identifier => Temp,
598                 Constant_Present    => True,
599                 Object_Definition   => New_Reference_To (PtrT, Loc),
600                 Expression          => Node));
601
602             Apply_Accessibility_Check (Temp);
603
604             --  Locate the enclosing list and insert the C++ constructor call
605
606             declare
607                P : Node_Id;
608
609             begin
610                P := Parent (Node);
611                while not Is_List_Member (P) loop
612                   P := Parent (P);
613                end loop;
614
615                Insert_List_After_And_Analyze (P,
616                  Build_Initialization_Call (Loc,
617                    Id_Ref =>
618                      Make_Explicit_Dereference (Loc,
619                        Prefix => New_Reference_To (Temp, Loc)),
620                    Typ => Etype (Exp),
621                    Constructor_Ref => Exp));
622             end;
623
624             Rewrite (N, New_Reference_To (Temp, Loc));
625             Analyze_And_Resolve (N, PtrT);
626             return;
627          end if;
628
629          --  Ada 2005 (AI-318-02): If the initialization expression is a call
630          --  to a build-in-place function, then access to the allocated object
631          --  must be passed to the function. Currently we limit such functions
632          --  to those with constrained limited result subtypes, but eventually
633          --  we plan to expand the allowed forms of functions that are treated
634          --  as build-in-place.
635
636          if Ada_Version >= Ada_05
637            and then Is_Build_In_Place_Function_Call (Exp)
638          then
639             Make_Build_In_Place_Call_In_Allocator (N, Exp);
640             Apply_Accessibility_Check (N, Built_In_Place => True);
641             return;
642          end if;
643
644          --    Actions inserted before:
645          --              Temp : constant ptr_T := new T'(Expression);
646          --   <no CW>    Temp._tag := T'tag;
647          --   <CTRL>     Adjust (Finalizable (Temp.all));
648          --   <CTRL>     Attach_To_Final_List (Finalizable (Temp.all));
649
650          --  We analyze by hand the new internal allocator to avoid
651          --  any recursion and inappropriate call to Initialize
652
653          --  We don't want to remove side effects when the expression must be
654          --  built in place. In the case of a build-in-place function call,
655          --  that could lead to a duplication of the call, which was already
656          --  substituted for the allocator.
657
658          if not Aggr_In_Place then
659             Remove_Side_Effects (Exp);
660          end if;
661
662          Temp := Make_Temporary (Loc, 'P', N);
663
664          --  For a class wide allocation generate the following code:
665
666          --    type Equiv_Record is record ... end record;
667          --    implicit subtype CW is <Class_Wide_Subytpe>;
668          --    temp : PtrT := new CW'(CW!(expr));
669
670          if Is_Class_Wide_Type (T) then
671             Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
672
673             --  Ada 2005 (AI-251): If the expression is a class-wide interface
674             --  object we generate code to move up "this" to reference the
675             --  base of the object before allocating the new object.
676
677             --  Note that Exp'Address is recursively expanded into a call
678             --  to Base_Address (Exp.Tag)
679
680             if Is_Class_Wide_Type (Etype (Exp))
681               and then Is_Interface (Etype (Exp))
682               and then Tagged_Type_Expansion
683             then
684                Set_Expression
685                  (Expression (N),
686                   Unchecked_Convert_To (Entity (Indic),
687                     Make_Explicit_Dereference (Loc,
688                       Unchecked_Convert_To (RTE (RE_Tag_Ptr),
689                         Make_Attribute_Reference (Loc,
690                           Prefix         => Exp,
691                           Attribute_Name => Name_Address)))));
692
693             else
694                Set_Expression
695                  (Expression (N),
696                   Unchecked_Convert_To (Entity (Indic), Exp));
697             end if;
698
699             Analyze_And_Resolve (Expression (N), Entity (Indic));
700          end if;
701
702          --  Keep separate the management of allocators returning interfaces
703
704          if not Is_Interface (Directly_Designated_Type (PtrT)) then
705             if Aggr_In_Place then
706                Tmp_Node :=
707                  Make_Object_Declaration (Loc,
708                    Defining_Identifier => Temp,
709                    Object_Definition   => New_Reference_To (PtrT, Loc),
710                    Expression          =>
711                      Make_Allocator (Loc,
712                        New_Reference_To (Etype (Exp), Loc)));
713
714                --  Copy the Comes_From_Source flag for the allocator we just
715                --  built, since logically this allocator is a replacement of
716                --  the original allocator node. This is for proper handling of
717                --  restriction No_Implicit_Heap_Allocations.
718
719                Set_Comes_From_Source
720                  (Expression (Tmp_Node), Comes_From_Source (N));
721
722                Set_No_Initialization (Expression (Tmp_Node));
723                Insert_Action (N, Tmp_Node);
724
725                if Needs_Finalization (T)
726                  and then Ekind (PtrT) = E_Anonymous_Access_Type
727                then
728                   --  Create local finalization list for access parameter
729
730                   Flist := Get_Allocator_Final_List (N, Base_Type (T), PtrT);
731                end if;
732
733                Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
734
735             else
736                Node := Relocate_Node (N);
737                Set_Analyzed (Node);
738                Insert_Action (N,
739                  Make_Object_Declaration (Loc,
740                    Defining_Identifier => Temp,
741                    Constant_Present    => True,
742                    Object_Definition   => New_Reference_To (PtrT, Loc),
743                    Expression          => Node));
744             end if;
745
746          --  Ada 2005 (AI-251): Handle allocators whose designated type is an
747          --  interface type. In this case we use the type of the qualified
748          --  expression to allocate the object.
749
750          else
751             declare
752                Def_Id   : constant Entity_Id := Make_Temporary (Loc, 'T');
753                New_Decl : Node_Id;
754
755             begin
756                New_Decl :=
757                  Make_Full_Type_Declaration (Loc,
758                    Defining_Identifier => Def_Id,
759                    Type_Definition =>
760                      Make_Access_To_Object_Definition (Loc,
761                        All_Present            => True,
762                        Null_Exclusion_Present => False,
763                        Constant_Present       => False,
764                        Subtype_Indication     =>
765                          New_Reference_To (Etype (Exp), Loc)));
766
767                Insert_Action (N, New_Decl);
768
769                --  Inherit the final chain to ensure that the expansion of the
770                --  aggregate is correct in case of controlled types
771
772                if Needs_Finalization (Directly_Designated_Type (PtrT)) then
773                   Set_Associated_Final_Chain (Def_Id,
774                     Associated_Final_Chain (PtrT));
775                end if;
776
777                --  Declare the object using the previous type declaration
778
779                if Aggr_In_Place then
780                   Tmp_Node :=
781                     Make_Object_Declaration (Loc,
782                       Defining_Identifier => Temp,
783                       Object_Definition   => New_Reference_To (Def_Id, Loc),
784                       Expression          =>
785                         Make_Allocator (Loc,
786                           New_Reference_To (Etype (Exp), Loc)));
787
788                   --  Copy the Comes_From_Source flag for the allocator we just
789                   --  built, since logically this allocator is a replacement of
790                   --  the original allocator node. This is for proper handling
791                   --  of restriction No_Implicit_Heap_Allocations.
792
793                   Set_Comes_From_Source
794                     (Expression (Tmp_Node), Comes_From_Source (N));
795
796                   Set_No_Initialization (Expression (Tmp_Node));
797                   Insert_Action (N, Tmp_Node);
798
799                   if Needs_Finalization (T)
800                     and then Ekind (PtrT) = E_Anonymous_Access_Type
801                   then
802                      --  Create local finalization list for access parameter
803
804                      Flist :=
805                        Get_Allocator_Final_List (N, Base_Type (T), PtrT);
806                   end if;
807
808                   Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
809                else
810                   Node := Relocate_Node (N);
811                   Set_Analyzed (Node);
812                   Insert_Action (N,
813                     Make_Object_Declaration (Loc,
814                       Defining_Identifier => Temp,
815                       Constant_Present    => True,
816                       Object_Definition   => New_Reference_To (Def_Id, Loc),
817                       Expression          => Node));
818                end if;
819
820                --  Generate an additional object containing the address of the
821                --  returned object. The type of this second object declaration
822                --  is the correct type required for the common processing that
823                --  is still performed by this subprogram. The displacement of
824                --  this pointer to reference the component associated with the
825                --  interface type will be done at the end of common processing.
826
827                New_Decl :=
828                  Make_Object_Declaration (Loc,
829                    Defining_Identifier => Make_Temporary (Loc, 'P'),
830                    Object_Definition   => New_Reference_To (PtrT, Loc),
831                    Expression          => Unchecked_Convert_To (PtrT,
832                                             New_Reference_To (Temp, Loc)));
833
834                Insert_Action (N, New_Decl);
835
836                Tmp_Node := New_Decl;
837                Temp     := Defining_Identifier (New_Decl);
838             end;
839          end if;
840
841          Apply_Accessibility_Check (Temp);
842
843          --  Generate the tag assignment
844
845          --  Suppress the tag assignment when VM_Target because VM tags are
846          --  represented implicitly in objects.
847
848          if not Tagged_Type_Expansion then
849             null;
850
851          --  Ada 2005 (AI-251): Suppress the tag assignment with class-wide
852          --  interface objects because in this case the tag does not change.
853
854          elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
855             pragma Assert (Is_Class_Wide_Type
856                             (Directly_Designated_Type (Etype (N))));
857             null;
858
859          elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
860             TagT := T;
861             TagR := New_Reference_To (Temp, Loc);
862
863          elsif Is_Private_Type (T)
864            and then Is_Tagged_Type (Underlying_Type (T))
865          then
866             TagT := Underlying_Type (T);
867             TagR :=
868               Unchecked_Convert_To (Underlying_Type (T),
869                 Make_Explicit_Dereference (Loc,
870                   Prefix => New_Reference_To (Temp, Loc)));
871          end if;
872
873          if Present (TagT) then
874             Tag_Assign :=
875               Make_Assignment_Statement (Loc,
876                 Name =>
877                   Make_Selected_Component (Loc,
878                     Prefix => TagR,
879                     Selector_Name =>
880                       New_Reference_To (First_Tag_Component (TagT), Loc)),
881
882                 Expression =>
883                   Unchecked_Convert_To (RTE (RE_Tag),
884                     New_Reference_To
885                       (Elists.Node (First_Elmt (Access_Disp_Table (TagT))),
886                        Loc)));
887
888             --  The previous assignment has to be done in any case
889
890             Set_Assignment_OK (Name (Tag_Assign));
891             Insert_Action (N, Tag_Assign);
892          end if;
893
894          if Needs_Finalization (DesigT)
895             and then Needs_Finalization (T)
896          then
897             declare
898                Attach : Node_Id;
899                Apool  : constant Entity_Id :=
900                           Associated_Storage_Pool (PtrT);
901
902             begin
903                --  If it is an allocation on the secondary stack (i.e. a value
904                --  returned from a function), the object is attached on the
905                --  caller side as soon as the call is completed (see
906                --  Expand_Ctrl_Function_Call)
907
908                if Is_RTE (Apool, RE_SS_Pool) then
909                   declare
910                      F : constant Entity_Id := Make_Temporary (Loc, 'F');
911                   begin
912                      Insert_Action (N,
913                        Make_Object_Declaration (Loc,
914                          Defining_Identifier => F,
915                          Object_Definition   =>
916                            New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
917                      Flist := New_Reference_To (F, Loc);
918                      Attach :=  Make_Integer_Literal (Loc, 1);
919                   end;
920
921                --  Normal case, not a secondary stack allocation
922
923                else
924                   if Needs_Finalization (T)
925                     and then Ekind (PtrT) = E_Anonymous_Access_Type
926                   then
927                      --  Create local finalization list for access parameter
928
929                      Flist :=
930                        Get_Allocator_Final_List (N, Base_Type (T), PtrT);
931                   else
932                      Flist := Find_Final_List (PtrT);
933                   end if;
934
935                   Attach :=  Make_Integer_Literal (Loc, 2);
936                end if;
937
938                --  Generate an Adjust call if the object will be moved. In Ada
939                --  2005, the object may be inherently limited, in which case
940                --  there is no Adjust procedure, and the object is built in
941                --  place. In Ada 95, the object can be limited but not
942                --  inherently limited if this allocator came from a return
943                --  statement (we're allocating the result on the secondary
944                --  stack). In that case, the object will be moved, so we _do_
945                --  want to Adjust.
946
947                if not Aggr_In_Place
948                  and then not Is_Inherently_Limited_Type (T)
949                then
950                   Insert_Actions (N,
951                     Make_Adjust_Call (
952                       Ref          =>
953
954                      --  An unchecked conversion is needed in the classwide
955                      --  case because the designated type can be an ancestor of
956                      --  the subtype mark of the allocator.
957
958                       Unchecked_Convert_To (T,
959                         Make_Explicit_Dereference (Loc,
960                           Prefix => New_Reference_To (Temp, Loc))),
961
962                       Typ          => T,
963                       Flist_Ref    => Flist,
964                       With_Attach  => Attach,
965                       Allocator    => True));
966                end if;
967             end;
968          end if;
969
970          Rewrite (N, New_Reference_To (Temp, Loc));
971          Analyze_And_Resolve (N, PtrT);
972
973          --  Ada 2005 (AI-251): Displace the pointer to reference the record
974          --  component containing the secondary dispatch table of the interface
975          --  type.
976
977          if Is_Interface (Directly_Designated_Type (PtrT)) then
978             Displace_Allocator_Pointer (N);
979          end if;
980
981       elsif Aggr_In_Place then
982          Temp := Make_Temporary (Loc, 'P', N);
983          Tmp_Node :=
984            Make_Object_Declaration (Loc,
985              Defining_Identifier => Temp,
986              Object_Definition   => New_Reference_To (PtrT, Loc),
987              Expression          => Make_Allocator (Loc,
988                  New_Reference_To (Etype (Exp), Loc)));
989
990          --  Copy the Comes_From_Source flag for the allocator we just built,
991          --  since logically this allocator is a replacement of the original
992          --  allocator node. This is for proper handling of restriction
993          --  No_Implicit_Heap_Allocations.
994
995          Set_Comes_From_Source
996            (Expression (Tmp_Node), Comes_From_Source (N));
997
998          Set_No_Initialization (Expression (Tmp_Node));
999          Insert_Action (N, Tmp_Node);
1000          Convert_Aggr_In_Allocator (N, Tmp_Node, Exp);
1001          Rewrite (N, New_Reference_To (Temp, Loc));
1002          Analyze_And_Resolve (N, PtrT);
1003
1004       elsif Is_Access_Type (T)
1005         and then Can_Never_Be_Null (T)
1006       then
1007          Install_Null_Excluding_Check (Exp);
1008
1009       elsif Is_Access_Type (DesigT)
1010         and then Nkind (Exp) = N_Allocator
1011         and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1012       then
1013          --  Apply constraint to designated subtype indication
1014
1015          Apply_Constraint_Check (Expression (Exp),
1016            Designated_Type (DesigT),
1017            No_Sliding => True);
1018
1019          if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1020
1021             --  Propagate constraint_error to enclosing allocator
1022
1023             Rewrite (Exp, New_Copy (Expression (Exp)));
1024          end if;
1025       else
1026          --  If we have:
1027          --    type A is access T1;
1028          --    X : A := new T2'(...);
1029          --  T1 and T2 can be different subtypes, and we might need to check
1030          --  both constraints. First check against the type of the qualified
1031          --  expression.
1032
1033          Apply_Constraint_Check (Exp, T, No_Sliding => True);
1034
1035          if Do_Range_Check (Exp) then
1036             Set_Do_Range_Check (Exp, False);
1037             Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1038          end if;
1039
1040          --  A check is also needed in cases where the designated subtype is
1041          --  constrained and differs from the subtype given in the qualified
1042          --  expression. Note that the check on the qualified expression does
1043          --  not allow sliding, but this check does (a relaxation from Ada 83).
1044
1045          if Is_Constrained (DesigT)
1046            and then not Subtypes_Statically_Match (T, DesigT)
1047          then
1048             Apply_Constraint_Check
1049               (Exp, DesigT, No_Sliding => False);
1050
1051             if Do_Range_Check (Exp) then
1052                Set_Do_Range_Check (Exp, False);
1053                Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1054             end if;
1055          end if;
1056
1057          --  For an access to unconstrained packed array, GIGI needs to see an
1058          --  expression with a constrained subtype in order to compute the
1059          --  proper size for the allocator.
1060
1061          if Is_Array_Type (T)
1062            and then not Is_Constrained (T)
1063            and then Is_Packed (T)
1064          then
1065             declare
1066                ConstrT      : constant Entity_Id := Make_Temporary (Loc, 'A');
1067                Internal_Exp : constant Node_Id   := Relocate_Node (Exp);
1068             begin
1069                Insert_Action (Exp,
1070                  Make_Subtype_Declaration (Loc,
1071                    Defining_Identifier => ConstrT,
1072                    Subtype_Indication  =>
1073                      Make_Subtype_From_Expr (Exp, T)));
1074                Freeze_Itype (ConstrT, Exp);
1075                Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1076             end;
1077          end if;
1078
1079          --  Ada 2005 (AI-318-02): If the initialization expression is a call
1080          --  to a build-in-place function, then access to the allocated object
1081          --  must be passed to the function. Currently we limit such functions
1082          --  to those with constrained limited result subtypes, but eventually
1083          --  we plan to expand the allowed forms of functions that are treated
1084          --  as build-in-place.
1085
1086          if Ada_Version >= Ada_05
1087            and then Is_Build_In_Place_Function_Call (Exp)
1088          then
1089             Make_Build_In_Place_Call_In_Allocator (N, Exp);
1090          end if;
1091       end if;
1092
1093    exception
1094       when RE_Not_Available =>
1095          return;
1096    end Expand_Allocator_Expression;
1097
1098    -----------------------------
1099    -- Expand_Array_Comparison --
1100    -----------------------------
1101
1102    --  Expansion is only required in the case of array types. For the unpacked
1103    --  case, an appropriate runtime routine is called. For packed cases, and
1104    --  also in some other cases where a runtime routine cannot be called, the
1105    --  form of the expansion is:
1106
1107    --     [body for greater_nn; boolean_expression]
1108
1109    --  The body is built by Make_Array_Comparison_Op, and the form of the
1110    --  Boolean expression depends on the operator involved.
1111
1112    procedure Expand_Array_Comparison (N : Node_Id) is
1113       Loc  : constant Source_Ptr := Sloc (N);
1114       Op1  : Node_Id             := Left_Opnd (N);
1115       Op2  : Node_Id             := Right_Opnd (N);
1116       Typ1 : constant Entity_Id  := Base_Type (Etype (Op1));
1117       Ctyp : constant Entity_Id  := Component_Type (Typ1);
1118
1119       Expr      : Node_Id;
1120       Func_Body : Node_Id;
1121       Func_Name : Entity_Id;
1122
1123       Comp : RE_Id;
1124
1125       Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1126       --  True for byte addressable target
1127
1128       function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1129       --  Returns True if the length of the given operand is known to be less
1130       --  than 4. Returns False if this length is known to be four or greater
1131       --  or is not known at compile time.
1132
1133       ------------------------
1134       -- Length_Less_Than_4 --
1135       ------------------------
1136
1137       function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1138          Otyp : constant Entity_Id := Etype (Opnd);
1139
1140       begin
1141          if Ekind (Otyp) = E_String_Literal_Subtype then
1142             return String_Literal_Length (Otyp) < 4;
1143
1144          else
1145             declare
1146                Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1147                Lo   : constant Node_Id   := Type_Low_Bound (Ityp);
1148                Hi   : constant Node_Id   := Type_High_Bound (Ityp);
1149                Lov  : Uint;
1150                Hiv  : Uint;
1151
1152             begin
1153                if Compile_Time_Known_Value (Lo) then
1154                   Lov := Expr_Value (Lo);
1155                else
1156                   return False;
1157                end if;
1158
1159                if Compile_Time_Known_Value (Hi) then
1160                   Hiv := Expr_Value (Hi);
1161                else
1162                   return False;
1163                end if;
1164
1165                return Hiv < Lov + 3;
1166             end;
1167          end if;
1168       end Length_Less_Than_4;
1169
1170    --  Start of processing for Expand_Array_Comparison
1171
1172    begin
1173       --  Deal first with unpacked case, where we can call a runtime routine
1174       --  except that we avoid this for targets for which are not addressable
1175       --  by bytes, and for the JVM/CIL, since they do not support direct
1176       --  addressing of array components.
1177
1178       if not Is_Bit_Packed_Array (Typ1)
1179         and then Byte_Addressable
1180         and then VM_Target = No_VM
1181       then
1182          --  The call we generate is:
1183
1184          --  Compare_Array_xn[_Unaligned]
1185          --    (left'address, right'address, left'length, right'length) <op> 0
1186
1187          --  x = U for unsigned, S for signed
1188          --  n = 8,16,32,64 for component size
1189          --  Add _Unaligned if length < 4 and component size is 8.
1190          --  <op> is the standard comparison operator
1191
1192          if Component_Size (Typ1) = 8 then
1193             if Length_Less_Than_4 (Op1)
1194                  or else
1195                Length_Less_Than_4 (Op2)
1196             then
1197                if Is_Unsigned_Type (Ctyp) then
1198                   Comp := RE_Compare_Array_U8_Unaligned;
1199                else
1200                   Comp := RE_Compare_Array_S8_Unaligned;
1201                end if;
1202
1203             else
1204                if Is_Unsigned_Type (Ctyp) then
1205                   Comp := RE_Compare_Array_U8;
1206                else
1207                   Comp := RE_Compare_Array_S8;
1208                end if;
1209             end if;
1210
1211          elsif Component_Size (Typ1) = 16 then
1212             if Is_Unsigned_Type (Ctyp) then
1213                Comp := RE_Compare_Array_U16;
1214             else
1215                Comp := RE_Compare_Array_S16;
1216             end if;
1217
1218          elsif Component_Size (Typ1) = 32 then
1219             if Is_Unsigned_Type (Ctyp) then
1220                Comp := RE_Compare_Array_U32;
1221             else
1222                Comp := RE_Compare_Array_S32;
1223             end if;
1224
1225          else pragma Assert (Component_Size (Typ1) = 64);
1226             if Is_Unsigned_Type (Ctyp) then
1227                Comp := RE_Compare_Array_U64;
1228             else
1229                Comp := RE_Compare_Array_S64;
1230             end if;
1231          end if;
1232
1233          Remove_Side_Effects (Op1, Name_Req => True);
1234          Remove_Side_Effects (Op2, Name_Req => True);
1235
1236          Rewrite (Op1,
1237            Make_Function_Call (Sloc (Op1),
1238              Name => New_Occurrence_Of (RTE (Comp), Loc),
1239
1240              Parameter_Associations => New_List (
1241                Make_Attribute_Reference (Loc,
1242                  Prefix         => Relocate_Node (Op1),
1243                  Attribute_Name => Name_Address),
1244
1245                Make_Attribute_Reference (Loc,
1246                  Prefix         => Relocate_Node (Op2),
1247                  Attribute_Name => Name_Address),
1248
1249                Make_Attribute_Reference (Loc,
1250                  Prefix         => Relocate_Node (Op1),
1251                  Attribute_Name => Name_Length),
1252
1253                Make_Attribute_Reference (Loc,
1254                  Prefix         => Relocate_Node (Op2),
1255                  Attribute_Name => Name_Length))));
1256
1257          Rewrite (Op2,
1258            Make_Integer_Literal (Sloc (Op2),
1259              Intval => Uint_0));
1260
1261          Analyze_And_Resolve (Op1, Standard_Integer);
1262          Analyze_And_Resolve (Op2, Standard_Integer);
1263          return;
1264       end if;
1265
1266       --  Cases where we cannot make runtime call
1267
1268       --  For (a <= b) we convert to not (a > b)
1269
1270       if Chars (N) = Name_Op_Le then
1271          Rewrite (N,
1272            Make_Op_Not (Loc,
1273              Right_Opnd =>
1274                 Make_Op_Gt (Loc,
1275                  Left_Opnd  => Op1,
1276                  Right_Opnd => Op2)));
1277          Analyze_And_Resolve (N, Standard_Boolean);
1278          return;
1279
1280       --  For < the Boolean expression is
1281       --    greater__nn (op2, op1)
1282
1283       elsif Chars (N) = Name_Op_Lt then
1284          Func_Body := Make_Array_Comparison_Op (Typ1, N);
1285
1286          --  Switch operands
1287
1288          Op1 := Right_Opnd (N);
1289          Op2 := Left_Opnd  (N);
1290
1291       --  For (a >= b) we convert to not (a < b)
1292
1293       elsif Chars (N) = Name_Op_Ge then
1294          Rewrite (N,
1295            Make_Op_Not (Loc,
1296              Right_Opnd =>
1297                Make_Op_Lt (Loc,
1298                  Left_Opnd  => Op1,
1299                  Right_Opnd => Op2)));
1300          Analyze_And_Resolve (N, Standard_Boolean);
1301          return;
1302
1303       --  For > the Boolean expression is
1304       --    greater__nn (op1, op2)
1305
1306       else
1307          pragma Assert (Chars (N) = Name_Op_Gt);
1308          Func_Body := Make_Array_Comparison_Op (Typ1, N);
1309       end if;
1310
1311       Func_Name := Defining_Unit_Name (Specification (Func_Body));
1312       Expr :=
1313         Make_Function_Call (Loc,
1314           Name => New_Reference_To (Func_Name, Loc),
1315           Parameter_Associations => New_List (Op1, Op2));
1316
1317       Insert_Action (N, Func_Body);
1318       Rewrite (N, Expr);
1319       Analyze_And_Resolve (N, Standard_Boolean);
1320
1321    exception
1322       when RE_Not_Available =>
1323          return;
1324    end Expand_Array_Comparison;
1325
1326    ---------------------------
1327    -- Expand_Array_Equality --
1328    ---------------------------
1329
1330    --  Expand an equality function for multi-dimensional arrays. Here is an
1331    --  example of such a function for Nb_Dimension = 2
1332
1333    --  function Enn (A : atyp; B : btyp) return boolean is
1334    --  begin
1335    --     if (A'length (1) = 0 or else A'length (2) = 0)
1336    --          and then
1337    --        (B'length (1) = 0 or else B'length (2) = 0)
1338    --     then
1339    --        return True;    -- RM 4.5.2(22)
1340    --     end if;
1341
1342    --     if A'length (1) /= B'length (1)
1343    --               or else
1344    --           A'length (2) /= B'length (2)
1345    --     then
1346    --        return False;   -- RM 4.5.2(23)
1347    --     end if;
1348
1349    --     declare
1350    --        A1 : Index_T1 := A'first (1);
1351    --        B1 : Index_T1 := B'first (1);
1352    --     begin
1353    --        loop
1354    --           declare
1355    --              A2 : Index_T2 := A'first (2);
1356    --              B2 : Index_T2 := B'first (2);
1357    --           begin
1358    --              loop
1359    --                 if A (A1, A2) /= B (B1, B2) then
1360    --                    return False;
1361    --                 end if;
1362
1363    --                 exit when A2 = A'last (2);
1364    --                 A2 := Index_T2'succ (A2);
1365    --                 B2 := Index_T2'succ (B2);
1366    --              end loop;
1367    --           end;
1368
1369    --           exit when A1 = A'last (1);
1370    --           A1 := Index_T1'succ (A1);
1371    --           B1 := Index_T1'succ (B1);
1372    --        end loop;
1373    --     end;
1374
1375    --     return true;
1376    --  end Enn;
1377
1378    --  Note on the formal types used (atyp and btyp). If either of the arrays
1379    --  is of a private type, we use the underlying type, and do an unchecked
1380    --  conversion of the actual. If either of the arrays has a bound depending
1381    --  on a discriminant, then we use the base type since otherwise we have an
1382    --  escaped discriminant in the function.
1383
1384    --  If both arrays are constrained and have the same bounds, we can generate
1385    --  a loop with an explicit iteration scheme using a 'Range attribute over
1386    --  the first array.
1387
1388    function Expand_Array_Equality
1389      (Nod    : Node_Id;
1390       Lhs    : Node_Id;
1391       Rhs    : Node_Id;
1392       Bodies : List_Id;
1393       Typ    : Entity_Id) return Node_Id
1394    is
1395       Loc         : constant Source_Ptr := Sloc (Nod);
1396       Decls       : constant List_Id    := New_List;
1397       Index_List1 : constant List_Id    := New_List;
1398       Index_List2 : constant List_Id    := New_List;
1399
1400       Actuals   : List_Id;
1401       Formals   : List_Id;
1402       Func_Name : Entity_Id;
1403       Func_Body : Node_Id;
1404
1405       A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1406       B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1407
1408       Ltyp : Entity_Id;
1409       Rtyp : Entity_Id;
1410       --  The parameter types to be used for the formals
1411
1412       function Arr_Attr
1413         (Arr : Entity_Id;
1414          Nam : Name_Id;
1415          Num : Int) return Node_Id;
1416       --  This builds the attribute reference Arr'Nam (Expr)
1417
1418       function Component_Equality (Typ : Entity_Id) return Node_Id;
1419       --  Create one statement to compare corresponding components, designated
1420       --  by a full set of indices.
1421
1422       function Get_Arg_Type (N : Node_Id) return Entity_Id;
1423       --  Given one of the arguments, computes the appropriate type to be used
1424       --  for that argument in the corresponding function formal
1425
1426       function Handle_One_Dimension
1427         (N     : Int;
1428          Index : Node_Id) return Node_Id;
1429       --  This procedure returns the following code
1430       --
1431       --    declare
1432       --       Bn : Index_T := B'First (N);
1433       --    begin
1434       --       loop
1435       --          xxx
1436       --          exit when An = A'Last (N);
1437       --          An := Index_T'Succ (An)
1438       --          Bn := Index_T'Succ (Bn)
1439       --       end loop;
1440       --    end;
1441       --
1442       --  If both indices are constrained and identical, the procedure
1443       --  returns a simpler loop:
1444       --
1445       --      for An in A'Range (N) loop
1446       --         xxx
1447       --      end loop
1448       --
1449       --  N is the dimension for which we are generating a loop. Index is the
1450       --  N'th index node, whose Etype is Index_Type_n in the above code. The
1451       --  xxx statement is either the loop or declare for the next dimension
1452       --  or if this is the last dimension the comparison of corresponding
1453       --  components of the arrays.
1454       --
1455       --  The actual way the code works is to return the comparison of
1456       --  corresponding components for the N+1 call. That's neater!
1457
1458       function Test_Empty_Arrays return Node_Id;
1459       --  This function constructs the test for both arrays being empty
1460       --    (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1461       --      and then
1462       --    (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1463
1464       function Test_Lengths_Correspond return Node_Id;
1465       --  This function constructs the test for arrays having different lengths
1466       --  in at least one index position, in which case the resulting code is:
1467
1468       --     A'length (1) /= B'length (1)
1469       --       or else
1470       --     A'length (2) /= B'length (2)
1471       --       or else
1472       --       ...
1473
1474       --------------
1475       -- Arr_Attr --
1476       --------------
1477
1478       function Arr_Attr
1479         (Arr : Entity_Id;
1480          Nam : Name_Id;
1481          Num : Int) return Node_Id
1482       is
1483       begin
1484          return
1485            Make_Attribute_Reference (Loc,
1486             Attribute_Name => Nam,
1487             Prefix => New_Reference_To (Arr, Loc),
1488             Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1489       end Arr_Attr;
1490
1491       ------------------------
1492       -- Component_Equality --
1493       ------------------------
1494
1495       function Component_Equality (Typ : Entity_Id) return Node_Id is
1496          Test : Node_Id;
1497          L, R : Node_Id;
1498
1499       begin
1500          --  if a(i1...) /= b(j1...) then return false; end if;
1501
1502          L :=
1503            Make_Indexed_Component (Loc,
1504              Prefix => Make_Identifier (Loc, Chars (A)),
1505              Expressions => Index_List1);
1506
1507          R :=
1508            Make_Indexed_Component (Loc,
1509              Prefix => Make_Identifier (Loc, Chars (B)),
1510              Expressions => Index_List2);
1511
1512          Test := Expand_Composite_Equality
1513                    (Nod, Component_Type (Typ), L, R, Decls);
1514
1515          --  If some (sub)component is an unchecked_union, the whole operation
1516          --  will raise program error.
1517
1518          if Nkind (Test) = N_Raise_Program_Error then
1519
1520             --  This node is going to be inserted at a location where a
1521             --  statement is expected: clear its Etype so analysis will set
1522             --  it to the expected Standard_Void_Type.
1523
1524             Set_Etype (Test, Empty);
1525             return Test;
1526
1527          else
1528             return
1529               Make_Implicit_If_Statement (Nod,
1530                 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1531                 Then_Statements => New_List (
1532                   Make_Simple_Return_Statement (Loc,
1533                     Expression => New_Occurrence_Of (Standard_False, Loc))));
1534          end if;
1535       end Component_Equality;
1536
1537       ------------------
1538       -- Get_Arg_Type --
1539       ------------------
1540
1541       function Get_Arg_Type (N : Node_Id) return Entity_Id is
1542          T : Entity_Id;
1543          X : Node_Id;
1544
1545       begin
1546          T := Etype (N);
1547
1548          if No (T) then
1549             return Typ;
1550
1551          else
1552             T := Underlying_Type (T);
1553
1554             X := First_Index (T);
1555             while Present (X) loop
1556                if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1557                  or else
1558                    Denotes_Discriminant (Type_High_Bound (Etype (X)))
1559                then
1560                   T := Base_Type (T);
1561                   exit;
1562                end if;
1563
1564                Next_Index (X);
1565             end loop;
1566
1567             return T;
1568          end if;
1569       end Get_Arg_Type;
1570
1571       --------------------------
1572       -- Handle_One_Dimension --
1573       ---------------------------
1574
1575       function Handle_One_Dimension
1576         (N     : Int;
1577          Index : Node_Id) return Node_Id
1578       is
1579          Need_Separate_Indexes : constant Boolean :=
1580                                    Ltyp /= Rtyp
1581                                      or else not Is_Constrained (Ltyp);
1582          --  If the index types are identical, and we are working with
1583          --  constrained types, then we can use the same index for both
1584          --  of the arrays.
1585
1586          An : constant Entity_Id := Make_Temporary (Loc, 'A');
1587
1588          Bn       : Entity_Id;
1589          Index_T  : Entity_Id;
1590          Stm_List : List_Id;
1591          Loop_Stm : Node_Id;
1592
1593       begin
1594          if N > Number_Dimensions (Ltyp) then
1595             return Component_Equality (Ltyp);
1596          end if;
1597
1598          --  Case where we generate a loop
1599
1600          Index_T := Base_Type (Etype (Index));
1601
1602          if Need_Separate_Indexes then
1603             Bn := Make_Temporary (Loc, 'B');
1604          else
1605             Bn := An;
1606          end if;
1607
1608          Append (New_Reference_To (An, Loc), Index_List1);
1609          Append (New_Reference_To (Bn, Loc), Index_List2);
1610
1611          Stm_List := New_List (
1612            Handle_One_Dimension (N + 1, Next_Index (Index)));
1613
1614          if Need_Separate_Indexes then
1615
1616             --  Generate guard for loop, followed by increments of indices
1617
1618             Append_To (Stm_List,
1619                Make_Exit_Statement (Loc,
1620                  Condition =>
1621                    Make_Op_Eq (Loc,
1622                       Left_Opnd => New_Reference_To (An, Loc),
1623                       Right_Opnd => Arr_Attr (A, Name_Last, N))));
1624
1625             Append_To (Stm_List,
1626               Make_Assignment_Statement (Loc,
1627                 Name       => New_Reference_To (An, Loc),
1628                 Expression =>
1629                   Make_Attribute_Reference (Loc,
1630                     Prefix         => New_Reference_To (Index_T, Loc),
1631                     Attribute_Name => Name_Succ,
1632                     Expressions    => New_List (New_Reference_To (An, Loc)))));
1633
1634             Append_To (Stm_List,
1635               Make_Assignment_Statement (Loc,
1636                 Name       => New_Reference_To (Bn, Loc),
1637                 Expression =>
1638                   Make_Attribute_Reference (Loc,
1639                     Prefix         => New_Reference_To (Index_T, Loc),
1640                     Attribute_Name => Name_Succ,
1641                     Expressions    => New_List (New_Reference_To (Bn, Loc)))));
1642          end if;
1643
1644          --  If separate indexes, we need a declare block for An and Bn, and a
1645          --  loop without an iteration scheme.
1646
1647          if Need_Separate_Indexes then
1648             Loop_Stm :=
1649               Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
1650
1651             return
1652               Make_Block_Statement (Loc,
1653                 Declarations => New_List (
1654                   Make_Object_Declaration (Loc,
1655                     Defining_Identifier => An,
1656                     Object_Definition   => New_Reference_To (Index_T, Loc),
1657                     Expression          => Arr_Attr (A, Name_First, N)),
1658
1659                   Make_Object_Declaration (Loc,
1660                     Defining_Identifier => Bn,
1661                     Object_Definition   => New_Reference_To (Index_T, Loc),
1662                     Expression          => Arr_Attr (B, Name_First, N))),
1663
1664                 Handled_Statement_Sequence =>
1665                   Make_Handled_Sequence_Of_Statements (Loc,
1666                     Statements => New_List (Loop_Stm)));
1667
1668          --  If no separate indexes, return loop statement with explicit
1669          --  iteration scheme on its own
1670
1671          else
1672             Loop_Stm :=
1673               Make_Implicit_Loop_Statement (Nod,
1674                 Statements       => Stm_List,
1675                 Iteration_Scheme =>
1676                   Make_Iteration_Scheme (Loc,
1677                     Loop_Parameter_Specification =>
1678                       Make_Loop_Parameter_Specification (Loc,
1679                         Defining_Identifier         => An,
1680                         Discrete_Subtype_Definition =>
1681                           Arr_Attr (A, Name_Range, N))));
1682             return Loop_Stm;
1683          end if;
1684       end Handle_One_Dimension;
1685
1686       -----------------------
1687       -- Test_Empty_Arrays --
1688       -----------------------
1689
1690       function Test_Empty_Arrays return Node_Id is
1691          Alist : Node_Id;
1692          Blist : Node_Id;
1693
1694          Atest : Node_Id;
1695          Btest : Node_Id;
1696
1697       begin
1698          Alist := Empty;
1699          Blist := Empty;
1700          for J in 1 .. Number_Dimensions (Ltyp) loop
1701             Atest :=
1702               Make_Op_Eq (Loc,
1703                 Left_Opnd  => Arr_Attr (A, Name_Length, J),
1704                 Right_Opnd => Make_Integer_Literal (Loc, 0));
1705
1706             Btest :=
1707               Make_Op_Eq (Loc,
1708                 Left_Opnd  => Arr_Attr (B, Name_Length, J),
1709                 Right_Opnd => Make_Integer_Literal (Loc, 0));
1710
1711             if No (Alist) then
1712                Alist := Atest;
1713                Blist := Btest;
1714
1715             else
1716                Alist :=
1717                  Make_Or_Else (Loc,
1718                    Left_Opnd  => Relocate_Node (Alist),
1719                    Right_Opnd => Atest);
1720
1721                Blist :=
1722                  Make_Or_Else (Loc,
1723                    Left_Opnd  => Relocate_Node (Blist),
1724                    Right_Opnd => Btest);
1725             end if;
1726          end loop;
1727
1728          return
1729            Make_And_Then (Loc,
1730              Left_Opnd  => Alist,
1731              Right_Opnd => Blist);
1732       end Test_Empty_Arrays;
1733
1734       -----------------------------
1735       -- Test_Lengths_Correspond --
1736       -----------------------------
1737
1738       function Test_Lengths_Correspond return Node_Id is
1739          Result : Node_Id;
1740          Rtest  : Node_Id;
1741
1742       begin
1743          Result := Empty;
1744          for J in 1 .. Number_Dimensions (Ltyp) loop
1745             Rtest :=
1746               Make_Op_Ne (Loc,
1747                 Left_Opnd  => Arr_Attr (A, Name_Length, J),
1748                 Right_Opnd => Arr_Attr (B, Name_Length, J));
1749
1750             if No (Result) then
1751                Result := Rtest;
1752             else
1753                Result :=
1754                  Make_Or_Else (Loc,
1755                    Left_Opnd  => Relocate_Node (Result),
1756                    Right_Opnd => Rtest);
1757             end if;
1758          end loop;
1759
1760          return Result;
1761       end Test_Lengths_Correspond;
1762
1763    --  Start of processing for Expand_Array_Equality
1764
1765    begin
1766       Ltyp := Get_Arg_Type (Lhs);
1767       Rtyp := Get_Arg_Type (Rhs);
1768
1769       --  For now, if the argument types are not the same, go to the base type,
1770       --  since the code assumes that the formals have the same type. This is
1771       --  fixable in future ???
1772
1773       if Ltyp /= Rtyp then
1774          Ltyp := Base_Type (Ltyp);
1775          Rtyp := Base_Type (Rtyp);
1776          pragma Assert (Ltyp = Rtyp);
1777       end if;
1778
1779       --  Build list of formals for function
1780
1781       Formals := New_List (
1782         Make_Parameter_Specification (Loc,
1783           Defining_Identifier => A,
1784           Parameter_Type      => New_Reference_To (Ltyp, Loc)),
1785
1786         Make_Parameter_Specification (Loc,
1787           Defining_Identifier => B,
1788           Parameter_Type      => New_Reference_To (Rtyp, Loc)));
1789
1790       Func_Name := Make_Temporary (Loc, 'E');
1791
1792       --  Build statement sequence for function
1793
1794       Func_Body :=
1795         Make_Subprogram_Body (Loc,
1796           Specification =>
1797             Make_Function_Specification (Loc,
1798               Defining_Unit_Name       => Func_Name,
1799               Parameter_Specifications => Formals,
1800               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
1801
1802           Declarations =>  Decls,
1803
1804           Handled_Statement_Sequence =>
1805             Make_Handled_Sequence_Of_Statements (Loc,
1806               Statements => New_List (
1807
1808                 Make_Implicit_If_Statement (Nod,
1809                   Condition => Test_Empty_Arrays,
1810                   Then_Statements => New_List (
1811                     Make_Simple_Return_Statement (Loc,
1812                       Expression =>
1813                         New_Occurrence_Of (Standard_True, Loc)))),
1814
1815                 Make_Implicit_If_Statement (Nod,
1816                   Condition => Test_Lengths_Correspond,
1817                   Then_Statements => New_List (
1818                     Make_Simple_Return_Statement (Loc,
1819                       Expression =>
1820                         New_Occurrence_Of (Standard_False, Loc)))),
1821
1822                 Handle_One_Dimension (1, First_Index (Ltyp)),
1823
1824                 Make_Simple_Return_Statement (Loc,
1825                   Expression => New_Occurrence_Of (Standard_True, Loc)))));
1826
1827          Set_Has_Completion (Func_Name, True);
1828          Set_Is_Inlined (Func_Name);
1829
1830          --  If the array type is distinct from the type of the arguments, it
1831          --  is the full view of a private type. Apply an unchecked conversion
1832          --  to insure that analysis of the call succeeds.
1833
1834          declare
1835             L, R : Node_Id;
1836
1837          begin
1838             L := Lhs;
1839             R := Rhs;
1840
1841             if No (Etype (Lhs))
1842               or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
1843             then
1844                L := OK_Convert_To (Ltyp, Lhs);
1845             end if;
1846
1847             if No (Etype (Rhs))
1848               or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
1849             then
1850                R := OK_Convert_To (Rtyp, Rhs);
1851             end if;
1852
1853             Actuals := New_List (L, R);
1854          end;
1855
1856          Append_To (Bodies, Func_Body);
1857
1858          return
1859            Make_Function_Call (Loc,
1860              Name                   => New_Reference_To (Func_Name, Loc),
1861              Parameter_Associations => Actuals);
1862    end Expand_Array_Equality;
1863
1864    -----------------------------
1865    -- Expand_Boolean_Operator --
1866    -----------------------------
1867
1868    --  Note that we first get the actual subtypes of the operands, since we
1869    --  always want to deal with types that have bounds.
1870
1871    procedure Expand_Boolean_Operator (N : Node_Id) is
1872       Typ : constant Entity_Id  := Etype (N);
1873
1874    begin
1875       --  Special case of bit packed array where both operands are known to be
1876       --  properly aligned. In this case we use an efficient run time routine
1877       --  to carry out the operation (see System.Bit_Ops).
1878
1879       if Is_Bit_Packed_Array (Typ)
1880         and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
1881         and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
1882       then
1883          Expand_Packed_Boolean_Operator (N);
1884          return;
1885       end if;
1886
1887       --  For the normal non-packed case, the general expansion is to build
1888       --  function for carrying out the comparison (use Make_Boolean_Array_Op)
1889       --  and then inserting it into the tree. The original operator node is
1890       --  then rewritten as a call to this function. We also use this in the
1891       --  packed case if either operand is a possibly unaligned object.
1892
1893       declare
1894          Loc       : constant Source_Ptr := Sloc (N);
1895          L         : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
1896          R         : constant Node_Id    := Relocate_Node (Right_Opnd (N));
1897          Func_Body : Node_Id;
1898          Func_Name : Entity_Id;
1899
1900       begin
1901          Convert_To_Actual_Subtype (L);
1902          Convert_To_Actual_Subtype (R);
1903          Ensure_Defined (Etype (L), N);
1904          Ensure_Defined (Etype (R), N);
1905          Apply_Length_Check (R, Etype (L));
1906
1907          if Nkind (N) = N_Op_Xor then
1908             Silly_Boolean_Array_Xor_Test (N, Etype (L));
1909          end if;
1910
1911          if Nkind (Parent (N)) = N_Assignment_Statement
1912            and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
1913          then
1914             Build_Boolean_Array_Proc_Call (Parent (N), L, R);
1915
1916          elsif Nkind (Parent (N)) = N_Op_Not
1917            and then Nkind (N) = N_Op_And
1918            and then
1919              Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
1920          then
1921             return;
1922          else
1923
1924             Func_Body := Make_Boolean_Array_Op (Etype (L), N);
1925             Func_Name := Defining_Unit_Name (Specification (Func_Body));
1926             Insert_Action (N, Func_Body);
1927
1928             --  Now rewrite the expression with a call
1929
1930             Rewrite (N,
1931               Make_Function_Call (Loc,
1932                 Name                   => New_Reference_To (Func_Name, Loc),
1933                 Parameter_Associations =>
1934                   New_List (
1935                     L,
1936                     Make_Type_Conversion
1937                       (Loc, New_Reference_To (Etype (L), Loc), R))));
1938
1939             Analyze_And_Resolve (N, Typ);
1940          end if;
1941       end;
1942    end Expand_Boolean_Operator;
1943
1944    -------------------------------
1945    -- Expand_Composite_Equality --
1946    -------------------------------
1947
1948    --  This function is only called for comparing internal fields of composite
1949    --  types when these fields are themselves composites. This is a special
1950    --  case because it is not possible to respect normal Ada visibility rules.
1951
1952    function Expand_Composite_Equality
1953      (Nod    : Node_Id;
1954       Typ    : Entity_Id;
1955       Lhs    : Node_Id;
1956       Rhs    : Node_Id;
1957       Bodies : List_Id) return Node_Id
1958    is
1959       Loc       : constant Source_Ptr := Sloc (Nod);
1960       Full_Type : Entity_Id;
1961       Prim      : Elmt_Id;
1962       Eq_Op     : Entity_Id;
1963
1964    begin
1965       if Is_Private_Type (Typ) then
1966          Full_Type := Underlying_Type (Typ);
1967       else
1968          Full_Type := Typ;
1969       end if;
1970
1971       --  Defense against malformed private types with no completion the error
1972       --  will be diagnosed later by check_completion
1973
1974       if No (Full_Type) then
1975          return New_Reference_To (Standard_False, Loc);
1976       end if;
1977
1978       Full_Type := Base_Type (Full_Type);
1979
1980       if Is_Array_Type (Full_Type) then
1981
1982          --  If the operand is an elementary type other than a floating-point
1983          --  type, then we can simply use the built-in block bitwise equality,
1984          --  since the predefined equality operators always apply and bitwise
1985          --  equality is fine for all these cases.
1986
1987          if Is_Elementary_Type (Component_Type (Full_Type))
1988            and then not Is_Floating_Point_Type (Component_Type (Full_Type))
1989          then
1990             return Make_Op_Eq (Loc, Left_Opnd  => Lhs, Right_Opnd => Rhs);
1991
1992          --  For composite component types, and floating-point types, use the
1993          --  expansion. This deals with tagged component types (where we use
1994          --  the applicable equality routine) and floating-point, (where we
1995          --  need to worry about negative zeroes), and also the case of any
1996          --  composite type recursively containing such fields.
1997
1998          else
1999             return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Full_Type);
2000          end if;
2001
2002       elsif Is_Tagged_Type (Full_Type) then
2003
2004          --  Call the primitive operation "=" of this type
2005
2006          if Is_Class_Wide_Type (Full_Type) then
2007             Full_Type := Root_Type (Full_Type);
2008          end if;
2009
2010          --  If this is derived from an untagged private type completed with a
2011          --  tagged type, it does not have a full view, so we use the primitive
2012          --  operations of the private type. This check should no longer be
2013          --  necessary when these types receive their full views ???
2014
2015          if Is_Private_Type (Typ)
2016            and then not Is_Tagged_Type (Typ)
2017            and then not Is_Controlled (Typ)
2018            and then Is_Derived_Type (Typ)
2019            and then No (Full_View (Typ))
2020          then
2021             Prim := First_Elmt (Collect_Primitive_Operations (Typ));
2022          else
2023             Prim := First_Elmt (Primitive_Operations (Full_Type));
2024          end if;
2025
2026          loop
2027             Eq_Op := Node (Prim);
2028             exit when Chars (Eq_Op) = Name_Op_Eq
2029               and then Etype (First_Formal (Eq_Op)) =
2030                        Etype (Next_Formal (First_Formal (Eq_Op)))
2031               and then Base_Type (Etype (Eq_Op)) = Standard_Boolean;
2032             Next_Elmt (Prim);
2033             pragma Assert (Present (Prim));
2034          end loop;
2035
2036          Eq_Op := Node (Prim);
2037
2038          return
2039            Make_Function_Call (Loc,
2040              Name => New_Reference_To (Eq_Op, Loc),
2041              Parameter_Associations =>
2042                New_List
2043                  (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2044                   Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2045
2046       elsif Is_Record_Type (Full_Type) then
2047          Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2048
2049          if Present (Eq_Op) then
2050             if Etype (First_Formal (Eq_Op)) /= Full_Type then
2051
2052                --  Inherited equality from parent type. Convert the actuals to
2053                --  match signature of operation.
2054
2055                declare
2056                   T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2057
2058                begin
2059                   return
2060                     Make_Function_Call (Loc,
2061                       Name => New_Reference_To (Eq_Op, Loc),
2062                       Parameter_Associations =>
2063                         New_List (OK_Convert_To (T, Lhs),
2064                                   OK_Convert_To (T, Rhs)));
2065                end;
2066
2067             else
2068                --  Comparison between Unchecked_Union components
2069
2070                if Is_Unchecked_Union (Full_Type) then
2071                   declare
2072                      Lhs_Type      : Node_Id := Full_Type;
2073                      Rhs_Type      : Node_Id := Full_Type;
2074                      Lhs_Discr_Val : Node_Id;
2075                      Rhs_Discr_Val : Node_Id;
2076
2077                   begin
2078                      --  Lhs subtype
2079
2080                      if Nkind (Lhs) = N_Selected_Component then
2081                         Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2082                      end if;
2083
2084                      --  Rhs subtype
2085
2086                      if Nkind (Rhs) = N_Selected_Component then
2087                         Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2088                      end if;
2089
2090                      --  Lhs of the composite equality
2091
2092                      if Is_Constrained (Lhs_Type) then
2093
2094                         --  Since the enclosing record type can never be an
2095                         --  Unchecked_Union (this code is executed for records
2096                         --  that do not have variants), we may reference its
2097                         --  discriminant(s).
2098
2099                         if Nkind (Lhs) = N_Selected_Component
2100                           and then Has_Per_Object_Constraint (
2101                                      Entity (Selector_Name (Lhs)))
2102                         then
2103                            Lhs_Discr_Val :=
2104                              Make_Selected_Component (Loc,
2105                                Prefix => Prefix (Lhs),
2106                                Selector_Name =>
2107                                  New_Copy (
2108                                    Get_Discriminant_Value (
2109                                      First_Discriminant (Lhs_Type),
2110                                      Lhs_Type,
2111                                      Stored_Constraint (Lhs_Type))));
2112
2113                         else
2114                            Lhs_Discr_Val := New_Copy (
2115                              Get_Discriminant_Value (
2116                                First_Discriminant (Lhs_Type),
2117                                Lhs_Type,
2118                                Stored_Constraint (Lhs_Type)));
2119
2120                         end if;
2121                      else
2122                         --  It is not possible to infer the discriminant since
2123                         --  the subtype is not constrained.
2124
2125                         return
2126                           Make_Raise_Program_Error (Loc,
2127                             Reason => PE_Unchecked_Union_Restriction);
2128                      end if;
2129
2130                      --  Rhs of the composite equality
2131
2132                      if Is_Constrained (Rhs_Type) then
2133                         if Nkind (Rhs) = N_Selected_Component
2134                           and then Has_Per_Object_Constraint (
2135                                      Entity (Selector_Name (Rhs)))
2136                         then
2137                            Rhs_Discr_Val :=
2138                              Make_Selected_Component (Loc,
2139                                Prefix => Prefix (Rhs),
2140                                Selector_Name =>
2141                                  New_Copy (
2142                                    Get_Discriminant_Value (
2143                                      First_Discriminant (Rhs_Type),
2144                                      Rhs_Type,
2145                                      Stored_Constraint (Rhs_Type))));
2146
2147                         else
2148                            Rhs_Discr_Val := New_Copy (
2149                              Get_Discriminant_Value (
2150                                First_Discriminant (Rhs_Type),
2151                                Rhs_Type,
2152                                Stored_Constraint (Rhs_Type)));
2153
2154                         end if;
2155                      else
2156                         return
2157                           Make_Raise_Program_Error (Loc,
2158                             Reason => PE_Unchecked_Union_Restriction);
2159                      end if;
2160
2161                      --  Call the TSS equality function with the inferred
2162                      --  discriminant values.
2163
2164                      return
2165                        Make_Function_Call (Loc,
2166                          Name => New_Reference_To (Eq_Op, Loc),
2167                          Parameter_Associations => New_List (
2168                            Lhs,
2169                            Rhs,
2170                            Lhs_Discr_Val,
2171                            Rhs_Discr_Val));
2172                   end;
2173                end if;
2174
2175                --  Shouldn't this be an else, we can't fall through the above
2176                --  IF, right???
2177
2178                return
2179                  Make_Function_Call (Loc,
2180                    Name => New_Reference_To (Eq_Op, Loc),
2181                    Parameter_Associations => New_List (Lhs, Rhs));
2182             end if;
2183
2184          else
2185             return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2186          end if;
2187
2188       else
2189          --  It can be a simple record or the full view of a scalar private
2190
2191          return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2192       end if;
2193    end Expand_Composite_Equality;
2194
2195    ------------------------
2196    -- Expand_Concatenate --
2197    ------------------------
2198
2199    procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2200       Loc : constant Source_Ptr := Sloc (Cnode);
2201
2202       Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2203       --  Result type of concatenation
2204
2205       Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2206       --  Component type. Elements of this component type can appear as one
2207       --  of the operands of concatenation as well as arrays.
2208
2209       Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2210       --  Index subtype
2211
2212       Ityp : constant Entity_Id := Base_Type (Istyp);
2213       --  Index type. This is the base type of the index subtype, and is used
2214       --  for all computed bounds (which may be out of range of Istyp in the
2215       --  case of null ranges).
2216
2217       Artyp : Entity_Id;
2218       --  This is the type we use to do arithmetic to compute the bounds and
2219       --  lengths of operands. The choice of this type is a little subtle and
2220       --  is discussed in a separate section at the start of the body code.
2221
2222       Concatenation_Error : exception;
2223       --  Raised if concatenation is sure to raise a CE
2224
2225       Result_May_Be_Null : Boolean := True;
2226       --  Reset to False if at least one operand is encountered which is known
2227       --  at compile time to be non-null. Used for handling the special case
2228       --  of setting the high bound to the last operand high bound for a null
2229       --  result, thus ensuring a proper high bound in the super-flat case.
2230
2231       N : constant Nat := List_Length (Opnds);
2232       --  Number of concatenation operands including possibly null operands
2233
2234       NN : Nat := 0;
2235       --  Number of operands excluding any known to be null, except that the
2236       --  last operand is always retained, in case it provides the bounds for
2237       --  a null result.
2238
2239       Opnd : Node_Id;
2240       --  Current operand being processed in the loop through operands. After
2241       --  this loop is complete, always contains the last operand (which is not
2242       --  the same as Operands (NN), since null operands are skipped).
2243
2244       --  Arrays describing the operands, only the first NN entries of each
2245       --  array are set (NN < N when we exclude known null operands).
2246
2247       Is_Fixed_Length : array (1 .. N) of Boolean;
2248       --  True if length of corresponding operand known at compile time
2249
2250       Operands : array (1 .. N) of Node_Id;
2251       --  Set to the corresponding entry in the Opnds list (but note that null
2252       --  operands are excluded, so not all entries in the list are stored).
2253
2254       Fixed_Length : array (1 .. N) of Uint;
2255       --  Set to length of operand. Entries in this array are set only if the
2256       --  corresponding entry in Is_Fixed_Length is True.
2257
2258       Opnd_Low_Bound : array (1 .. N) of Node_Id;
2259       --  Set to lower bound of operand. Either an integer literal in the case
2260       --  where the bound is known at compile time, else actual lower bound.
2261       --  The operand low bound is of type Ityp.
2262
2263       Var_Length : array (1 .. N) of Entity_Id;
2264       --  Set to an entity of type Natural that contains the length of an
2265       --  operand whose length is not known at compile time. Entries in this
2266       --  array are set only if the corresponding entry in Is_Fixed_Length
2267       --  is False. The entity is of type Artyp.
2268
2269       Aggr_Length : array (0 .. N) of Node_Id;
2270       --  The J'th entry in an expression node that represents the total length
2271       --  of operands 1 through J. It is either an integer literal node, or a
2272       --  reference to a constant entity with the right value, so it is fine
2273       --  to just do a Copy_Node to get an appropriate copy. The extra zero'th
2274       --  entry always is set to zero. The length is of type Artyp.
2275
2276       Low_Bound : Node_Id;
2277       --  A tree node representing the low bound of the result (of type Ityp).
2278       --  This is either an integer literal node, or an identifier reference to
2279       --  a constant entity initialized to the appropriate value.
2280
2281       Last_Opnd_High_Bound : Node_Id;
2282       --  A tree node representing the high bound of the last operand. This
2283       --  need only be set if the result could be null. It is used for the
2284       --  special case of setting the right high bound for a null result.
2285       --  This is of type Ityp.
2286
2287       High_Bound : Node_Id;
2288       --  A tree node representing the high bound of the result (of type Ityp)
2289
2290       Result : Node_Id;
2291       --  Result of the concatenation (of type Ityp)
2292
2293       Actions : constant List_Id := New_List;
2294       --  Collect actions to be inserted if Save_Space is False
2295
2296       Save_Space : Boolean;
2297       pragma Warnings (Off, Save_Space);
2298       --  Set to True if we are saving generated code space by calling routines
2299       --  in packages System.Concat_n.
2300
2301       Known_Non_Null_Operand_Seen : Boolean;
2302       --  Set True during generation of the assignements of operands into
2303       --  result once an operand known to be non-null has been seen.
2304
2305       function Make_Artyp_Literal (Val : Nat) return Node_Id;
2306       --  This function makes an N_Integer_Literal node that is returned in
2307       --  analyzed form with the type set to Artyp. Importantly this literal
2308       --  is not flagged as static, so that if we do computations with it that
2309       --  result in statically detected out of range conditions, we will not
2310       --  generate error messages but instead warning messages.
2311
2312       function To_Artyp (X : Node_Id) return Node_Id;
2313       --  Given a node of type Ityp, returns the corresponding value of type
2314       --  Artyp. For non-enumeration types, this is a plain integer conversion.
2315       --  For enum types, the Pos of the value is returned.
2316
2317       function To_Ityp (X : Node_Id) return Node_Id;
2318       --  The inverse function (uses Val in the case of enumeration types)
2319
2320       ------------------------
2321       -- Make_Artyp_Literal --
2322       ------------------------
2323
2324       function Make_Artyp_Literal (Val : Nat) return Node_Id is
2325          Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
2326       begin
2327          Set_Etype (Result, Artyp);
2328          Set_Analyzed (Result, True);
2329          Set_Is_Static_Expression (Result, False);
2330          return Result;
2331       end Make_Artyp_Literal;
2332
2333       --------------
2334       -- To_Artyp --
2335       --------------
2336
2337       function To_Artyp (X : Node_Id) return Node_Id is
2338       begin
2339          if Ityp = Base_Type (Artyp) then
2340             return X;
2341
2342          elsif Is_Enumeration_Type (Ityp) then
2343             return
2344               Make_Attribute_Reference (Loc,
2345                 Prefix         => New_Occurrence_Of (Ityp, Loc),
2346                 Attribute_Name => Name_Pos,
2347                 Expressions    => New_List (X));
2348
2349          else
2350             return Convert_To (Artyp, X);
2351          end if;
2352       end To_Artyp;
2353
2354       -------------
2355       -- To_Ityp --
2356       -------------
2357
2358       function To_Ityp (X : Node_Id) return Node_Id is
2359       begin
2360          if Is_Enumeration_Type (Ityp) then
2361             return
2362               Make_Attribute_Reference (Loc,
2363                 Prefix         => New_Occurrence_Of (Ityp, Loc),
2364                 Attribute_Name => Name_Val,
2365                 Expressions    => New_List (X));
2366
2367          --  Case where we will do a type conversion
2368
2369          else
2370             if Ityp = Base_Type (Artyp) then
2371                return X;
2372             else
2373                return Convert_To (Ityp, X);
2374             end if;
2375          end if;
2376       end To_Ityp;
2377
2378       --  Local Declarations
2379
2380       Opnd_Typ : Entity_Id;
2381       Ent      : Entity_Id;
2382       Len      : Uint;
2383       J        : Nat;
2384       Clen     : Node_Id;
2385       Set      : Boolean;
2386
2387    begin
2388       --  Choose an appropriate computational type
2389
2390       --  We will be doing calculations of lengths and bounds in this routine
2391       --  and computing one from the other in some cases, e.g. getting the high
2392       --  bound by adding the length-1 to the low bound.
2393
2394       --  We can't just use the index type, or even its base type for this
2395       --  purpose for two reasons. First it might be an enumeration type which
2396       --  is not suitable fo computations of any kind, and second it may simply
2397       --  not have enough range. For example if the index type is -128..+127
2398       --  then lengths can be up to 256, which is out of range of the type.
2399
2400       --  For enumeration types, we can simply use Standard_Integer, this is
2401       --  sufficient since the actual number of enumeration literals cannot
2402       --  possibly exceed the range of integer (remember we will be doing the
2403       --  arithmetic with POS values, not representation values).
2404
2405       if Is_Enumeration_Type (Ityp) then
2406          Artyp := Standard_Integer;
2407
2408       --  If index type is Positive, we use the standard unsigned type, to give
2409       --  more room on the top of the range, obviating the need for an overflow
2410       --  check when creating the upper bound. This is needed to avoid junk
2411       --  overflow checks in the common case of String types.
2412
2413       --  ??? Disabled for now
2414
2415       --  elsif Istyp = Standard_Positive then
2416       --     Artyp := Standard_Unsigned;
2417
2418       --  For modular types, we use a 32-bit modular type for types whose size
2419       --  is in the range 1-31 bits. For 32-bit unsigned types, we use the
2420       --  identity type, and for larger unsigned types we use 64-bits.
2421
2422       elsif Is_Modular_Integer_Type (Ityp) then
2423          if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
2424             Artyp := Standard_Unsigned;
2425          elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
2426             Artyp := Ityp;
2427          else
2428             Artyp := RTE (RE_Long_Long_Unsigned);
2429          end if;
2430
2431       --  Similar treatment for signed types
2432
2433       else
2434          if RM_Size (Ityp) < RM_Size (Standard_Integer) then
2435             Artyp := Standard_Integer;
2436          elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
2437             Artyp := Ityp;
2438          else
2439             Artyp := Standard_Long_Long_Integer;
2440          end if;
2441       end if;
2442
2443       --  Supply dummy entry at start of length array
2444
2445       Aggr_Length (0) := Make_Artyp_Literal (0);
2446
2447       --  Go through operands setting up the above arrays
2448
2449       J := 1;
2450       while J <= N loop
2451          Opnd := Remove_Head (Opnds);
2452          Opnd_Typ := Etype (Opnd);
2453
2454          --  The parent got messed up when we put the operands in a list,
2455          --  so now put back the proper parent for the saved operand.
2456
2457          Set_Parent (Opnd, Parent (Cnode));
2458
2459          --  Set will be True when we have setup one entry in the array
2460
2461          Set := False;
2462
2463          --  Singleton element (or character literal) case
2464
2465          if Base_Type (Opnd_Typ) = Ctyp then
2466             NN := NN + 1;
2467             Operands (NN) := Opnd;
2468             Is_Fixed_Length (NN) := True;
2469             Fixed_Length (NN) := Uint_1;
2470             Result_May_Be_Null := False;
2471
2472             --  Set low bound of operand (no need to set Last_Opnd_High_Bound
2473             --  since we know that the result cannot be null).
2474
2475             Opnd_Low_Bound (NN) :=
2476               Make_Attribute_Reference (Loc,
2477                 Prefix         => New_Reference_To (Istyp, Loc),
2478                 Attribute_Name => Name_First);
2479
2480             Set := True;
2481
2482          --  String literal case (can only occur for strings of course)
2483
2484          elsif Nkind (Opnd) = N_String_Literal then
2485             Len := String_Literal_Length (Opnd_Typ);
2486
2487             if Len /= 0 then
2488                Result_May_Be_Null := False;
2489             end if;
2490
2491             --  Capture last operand high bound if result could be null
2492
2493             if J = N and then Result_May_Be_Null then
2494                Last_Opnd_High_Bound :=
2495                  Make_Op_Add (Loc,
2496                    Left_Opnd  =>
2497                      New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
2498                    Right_Opnd => Make_Integer_Literal (Loc, 1));
2499             end if;
2500
2501             --  Skip null string literal
2502
2503             if J < N and then Len = 0 then
2504                goto Continue;
2505             end if;
2506
2507             NN := NN + 1;
2508             Operands (NN) := Opnd;
2509             Is_Fixed_Length (NN) := True;
2510
2511             --  Set length and bounds
2512
2513             Fixed_Length (NN) := Len;
2514
2515             Opnd_Low_Bound (NN) :=
2516               New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
2517
2518             Set := True;
2519
2520          --  All other cases
2521
2522          else
2523             --  Check constrained case with known bounds
2524
2525             if Is_Constrained (Opnd_Typ) then
2526                declare
2527                   Index    : constant Node_Id   := First_Index (Opnd_Typ);
2528                   Indx_Typ : constant Entity_Id := Etype (Index);
2529                   Lo       : constant Node_Id   := Type_Low_Bound  (Indx_Typ);
2530                   Hi       : constant Node_Id   := Type_High_Bound (Indx_Typ);
2531
2532                begin
2533                   --  Fixed length constrained array type with known at compile
2534                   --  time bounds is last case of fixed length operand.
2535
2536                   if Compile_Time_Known_Value (Lo)
2537                        and then
2538                      Compile_Time_Known_Value (Hi)
2539                   then
2540                      declare
2541                         Loval : constant Uint := Expr_Value (Lo);
2542                         Hival : constant Uint := Expr_Value (Hi);
2543                         Len   : constant Uint :=
2544                                   UI_Max (Hival - Loval + 1, Uint_0);
2545
2546                      begin
2547                         if Len > 0 then
2548                            Result_May_Be_Null := False;
2549                         end if;
2550
2551                         --  Capture last operand bound if result could be null
2552
2553                         if J = N and then Result_May_Be_Null then
2554                            Last_Opnd_High_Bound :=
2555                              Convert_To (Ityp,
2556                                Make_Integer_Literal (Loc,
2557                                  Intval => Expr_Value (Hi)));
2558                         end if;
2559
2560                         --  Exclude null length case unless last operand
2561
2562                         if J < N and then Len = 0 then
2563                            goto Continue;
2564                         end if;
2565
2566                         NN := NN + 1;
2567                         Operands (NN) := Opnd;
2568                         Is_Fixed_Length (NN) := True;
2569                         Fixed_Length (NN)    := Len;
2570
2571                         Opnd_Low_Bound (NN) := To_Ityp (
2572                           Make_Integer_Literal (Loc,
2573                             Intval => Expr_Value (Lo)));
2574
2575                         Set := True;
2576                      end;
2577                   end if;
2578                end;
2579             end if;
2580
2581             --  All cases where the length is not known at compile time, or the
2582             --  special case of an operand which is known to be null but has a
2583             --  lower bound other than 1 or is other than a string type.
2584
2585             if not Set then
2586                NN := NN + 1;
2587
2588                --  Capture operand bounds
2589
2590                Opnd_Low_Bound (NN) :=
2591                  Make_Attribute_Reference (Loc,
2592                    Prefix         =>
2593                      Duplicate_Subexpr (Opnd, Name_Req => True),
2594                    Attribute_Name => Name_First);
2595
2596                if J = N and Result_May_Be_Null then
2597                   Last_Opnd_High_Bound :=
2598                     Convert_To (Ityp,
2599                       Make_Attribute_Reference (Loc,
2600                         Prefix         =>
2601                           Duplicate_Subexpr (Opnd, Name_Req => True),
2602                         Attribute_Name => Name_Last));
2603                end if;
2604
2605                --  Capture length of operand in entity
2606
2607                Operands (NN) := Opnd;
2608                Is_Fixed_Length (NN) := False;
2609
2610                Var_Length (NN) := Make_Temporary (Loc, 'L');
2611
2612                Append_To (Actions,
2613                  Make_Object_Declaration (Loc,
2614                    Defining_Identifier => Var_Length (NN),
2615                    Constant_Present    => True,
2616
2617                    Object_Definition   =>
2618                      New_Occurrence_Of (Artyp, Loc),
2619
2620                    Expression          =>
2621                      Make_Attribute_Reference (Loc,
2622                        Prefix         =>
2623                          Duplicate_Subexpr (Opnd, Name_Req => True),
2624                        Attribute_Name => Name_Length)));
2625             end if;
2626          end if;
2627
2628          --  Set next entry in aggregate length array
2629
2630          --  For first entry, make either integer literal for fixed length
2631          --  or a reference to the saved length for variable length.
2632
2633          if NN = 1 then
2634             if Is_Fixed_Length (1) then
2635                Aggr_Length (1) :=
2636                  Make_Integer_Literal (Loc,
2637                    Intval => Fixed_Length (1));
2638             else
2639                Aggr_Length (1) :=
2640                  New_Reference_To (Var_Length (1), Loc);
2641             end if;
2642
2643          --  If entry is fixed length and only fixed lengths so far, make
2644          --  appropriate new integer literal adding new length.
2645
2646          elsif Is_Fixed_Length (NN)
2647            and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
2648          then
2649             Aggr_Length (NN) :=
2650               Make_Integer_Literal (Loc,
2651                 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
2652
2653          --  All other cases, construct an addition node for the length and
2654          --  create an entity initialized to this length.
2655
2656          else
2657             Ent := Make_Temporary (Loc, 'L');
2658
2659             if Is_Fixed_Length (NN) then
2660                Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
2661             else
2662                Clen := New_Reference_To (Var_Length (NN), Loc);
2663             end if;
2664
2665             Append_To (Actions,
2666               Make_Object_Declaration (Loc,
2667                 Defining_Identifier => Ent,
2668                 Constant_Present    => True,
2669
2670                 Object_Definition   =>
2671                   New_Occurrence_Of (Artyp, Loc),
2672
2673                 Expression          =>
2674                   Make_Op_Add (Loc,
2675                     Left_Opnd  => New_Copy (Aggr_Length (NN - 1)),
2676                     Right_Opnd => Clen)));
2677
2678             Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
2679          end if;
2680
2681       <<Continue>>
2682          J := J + 1;
2683       end loop;
2684
2685       --  If we have only skipped null operands, return the last operand
2686
2687       if NN = 0 then
2688          Result := Opnd;
2689          goto Done;
2690       end if;
2691
2692       --  If we have only one non-null operand, return it and we are done.
2693       --  There is one case in which this cannot be done, and that is when
2694       --  the sole operand is of the element type, in which case it must be
2695       --  converted to an array, and the easiest way of doing that is to go
2696       --  through the normal general circuit.
2697
2698       if NN = 1
2699         and then Base_Type (Etype (Operands (1))) /= Ctyp
2700       then
2701          Result := Operands (1);
2702          goto Done;
2703       end if;
2704
2705       --  Cases where we have a real concatenation
2706
2707       --  Next step is to find the low bound for the result array that we
2708       --  will allocate. The rules for this are in (RM 4.5.6(5-7)).
2709
2710       --  If the ultimate ancestor of the index subtype is a constrained array
2711       --  definition, then the lower bound is that of the index subtype as
2712       --  specified by (RM 4.5.3(6)).
2713
2714       --  The right test here is to go to the root type, and then the ultimate
2715       --  ancestor is the first subtype of this root type.
2716
2717       if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
2718          Low_Bound :=
2719            Make_Attribute_Reference (Loc,
2720              Prefix         =>
2721                New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
2722              Attribute_Name => Name_First);
2723
2724       --  If the first operand in the list has known length we know that
2725       --  the lower bound of the result is the lower bound of this operand.
2726
2727       elsif Is_Fixed_Length (1) then
2728          Low_Bound := Opnd_Low_Bound (1);
2729
2730       --  OK, we don't know the lower bound, we have to build a horrible
2731       --  expression actions node of the form
2732
2733       --     if Cond1'Length /= 0 then
2734       --        Opnd1 low bound
2735       --     else
2736       --        if Opnd2'Length /= 0 then
2737       --          Opnd2 low bound
2738       --        else
2739       --           ...
2740
2741       --  The nesting ends either when we hit an operand whose length is known
2742       --  at compile time, or on reaching the last operand, whose low bound we
2743       --  take unconditionally whether or not it is null. It's easiest to do
2744       --  this with a recursive procedure:
2745
2746       else
2747          declare
2748             function Get_Known_Bound (J : Nat) return Node_Id;
2749             --  Returns the lower bound determined by operands J .. NN
2750
2751             ---------------------
2752             -- Get_Known_Bound --
2753             ---------------------
2754
2755             function Get_Known_Bound (J : Nat) return Node_Id is
2756             begin
2757                if Is_Fixed_Length (J) or else J = NN then
2758                   return New_Copy (Opnd_Low_Bound (J));
2759
2760                else
2761                   return
2762                     Make_Conditional_Expression (Loc,
2763                       Expressions => New_List (
2764
2765                         Make_Op_Ne (Loc,
2766                           Left_Opnd  => New_Reference_To (Var_Length (J), Loc),
2767                           Right_Opnd => Make_Integer_Literal (Loc, 0)),
2768
2769                         New_Copy (Opnd_Low_Bound (J)),
2770                         Get_Known_Bound (J + 1)));
2771                end if;
2772             end Get_Known_Bound;
2773
2774          begin
2775             Ent := Make_Temporary (Loc, 'L');
2776
2777             Append_To (Actions,
2778               Make_Object_Declaration (Loc,
2779                 Defining_Identifier => Ent,
2780                 Constant_Present    => True,
2781                 Object_Definition   => New_Occurrence_Of (Ityp, Loc),
2782                 Expression          => Get_Known_Bound (1)));
2783
2784             Low_Bound := New_Reference_To (Ent, Loc);
2785          end;
2786       end if;
2787
2788       --  Now we can safely compute the upper bound, normally
2789       --  Low_Bound + Length - 1.
2790
2791       High_Bound :=
2792         To_Ityp (
2793           Make_Op_Add (Loc,
2794             Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
2795             Right_Opnd =>
2796               Make_Op_Subtract (Loc,
2797                 Left_Opnd  => New_Copy (Aggr_Length (NN)),
2798                 Right_Opnd => Make_Artyp_Literal (1))));
2799
2800       --  Note that calculation of the high bound may cause overflow in some
2801       --  very weird cases, so in the general case we need an overflow check on
2802       --  the high bound. We can avoid this for the common case of string types
2803       --  and other types whose index is Positive, since we chose a wider range
2804       --  for the arithmetic type.
2805
2806       if Istyp /= Standard_Positive then
2807          Activate_Overflow_Check (High_Bound);
2808       end if;
2809
2810       --  Handle the exceptional case where the result is null, in which case
2811       --  case the bounds come from the last operand (so that we get the proper
2812       --  bounds if the last operand is super-flat).
2813
2814       if Result_May_Be_Null then
2815          High_Bound :=
2816            Make_Conditional_Expression (Loc,
2817              Expressions => New_List (
2818                Make_Op_Eq (Loc,
2819                  Left_Opnd  => New_Copy (Aggr_Length (NN)),
2820                  Right_Opnd => Make_Artyp_Literal (0)),
2821                Last_Opnd_High_Bound,
2822                High_Bound));
2823       end if;
2824
2825       --  Here is where we insert the saved up actions
2826
2827       Insert_Actions (Cnode, Actions, Suppress => All_Checks);
2828
2829       --  Now we construct an array object with appropriate bounds. We mark
2830       --  the target as internal to prevent useless initialization when
2831       --  Initialize_Scalars is enabled.
2832
2833       Ent := Make_Temporary (Loc, 'S');
2834       Set_Is_Internal (Ent);
2835
2836       --  If the bound is statically known to be out of range, we do not want
2837       --  to abort, we want a warning and a runtime constraint error. Note that
2838       --  we have arranged that the result will not be treated as a static
2839       --  constant, so we won't get an illegality during this insertion.
2840
2841       Insert_Action (Cnode,
2842         Make_Object_Declaration (Loc,
2843           Defining_Identifier => Ent,
2844           Object_Definition   =>
2845             Make_Subtype_Indication (Loc,
2846               Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
2847               Constraint   =>
2848                 Make_Index_Or_Discriminant_Constraint (Loc,
2849                   Constraints => New_List (
2850                     Make_Range (Loc,
2851                       Low_Bound  => Low_Bound,
2852                       High_Bound => High_Bound))))),
2853         Suppress => All_Checks);
2854
2855       --  If the result of the concatenation appears as the initializing
2856       --  expression of an object declaration, we can just rename the
2857       --  result, rather than copying it.
2858
2859       Set_OK_To_Rename (Ent);
2860
2861       --  Catch the static out of range case now
2862
2863       if Raises_Constraint_Error (High_Bound) then
2864          raise Concatenation_Error;
2865       end if;
2866
2867       --  Now we will generate the assignments to do the actual concatenation
2868
2869       --  There is one case in which we will not do this, namely when all the
2870       --  following conditions are met:
2871
2872       --    The result type is Standard.String
2873
2874       --    There are nine or fewer retained (non-null) operands
2875
2876       --    The optimization level is -O0
2877
2878       --    The corresponding System.Concat_n.Str_Concat_n routine is
2879       --    available in the run time.
2880
2881       --    The debug flag gnatd.c is not set
2882
2883       --  If all these conditions are met then we generate a call to the
2884       --  relevant concatenation routine. The purpose of this is to avoid
2885       --  undesirable code bloat at -O0.
2886
2887       if Atyp = Standard_String
2888         and then NN in 2 .. 9
2889         and then (Opt.Optimization_Level = 0 or else Debug_Flag_Dot_CC)
2890         and then not Debug_Flag_Dot_C
2891       then
2892          declare
2893             RR : constant array (Nat range 2 .. 9) of RE_Id :=
2894                    (RE_Str_Concat_2,
2895                     RE_Str_Concat_3,
2896                     RE_Str_Concat_4,
2897                     RE_Str_Concat_5,
2898                     RE_Str_Concat_6,
2899                     RE_Str_Concat_7,
2900                     RE_Str_Concat_8,
2901                     RE_Str_Concat_9);
2902
2903          begin
2904             if RTE_Available (RR (NN)) then
2905                declare
2906                   Opnds : constant List_Id :=
2907                             New_List (New_Occurrence_Of (Ent, Loc));
2908
2909                begin
2910                   for J in 1 .. NN loop
2911                      if Is_List_Member (Operands (J)) then
2912                         Remove (Operands (J));
2913                      end if;
2914
2915                      if Base_Type (Etype (Operands (J))) = Ctyp then
2916                         Append_To (Opnds,
2917                           Make_Aggregate (Loc,
2918                             Component_Associations => New_List (
2919                               Make_Component_Association (Loc,
2920                                 Choices => New_List (
2921                                   Make_Integer_Literal (Loc, 1)),
2922                                 Expression => Operands (J)))));
2923
2924                      else
2925                         Append_To (Opnds, Operands (J));
2926                      end if;
2927                   end loop;
2928
2929                   Insert_Action (Cnode,
2930                     Make_Procedure_Call_Statement (Loc,
2931                       Name => New_Reference_To (RTE (RR (NN)), Loc),
2932                       Parameter_Associations => Opnds));
2933
2934                   Result := New_Reference_To (Ent, Loc);
2935                   goto Done;
2936                end;
2937             end if;
2938          end;
2939       end if;
2940
2941       --  Not special case so generate the assignments
2942
2943       Known_Non_Null_Operand_Seen := False;
2944
2945       for J in 1 .. NN loop
2946          declare
2947             Lo : constant Node_Id :=
2948                    Make_Op_Add (Loc,
2949                      Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
2950                      Right_Opnd => Aggr_Length (J - 1));
2951
2952             Hi : constant Node_Id :=
2953                    Make_Op_Add (Loc,
2954                      Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
2955                      Right_Opnd =>
2956                        Make_Op_Subtract (Loc,
2957                          Left_Opnd  => Aggr_Length (J),
2958                          Right_Opnd => Make_Artyp_Literal (1)));
2959
2960          begin
2961             --  Singleton case, simple assignment
2962
2963             if Base_Type (Etype (Operands (J))) = Ctyp then
2964                Known_Non_Null_Operand_Seen := True;
2965                Insert_Action (Cnode,
2966                  Make_Assignment_Statement (Loc,
2967                    Name       =>
2968                      Make_Indexed_Component (Loc,
2969                        Prefix      => New_Occurrence_Of (Ent, Loc),
2970                        Expressions => New_List (To_Ityp (Lo))),
2971                    Expression => Operands (J)),
2972                  Suppress => All_Checks);
2973
2974             --  Array case, slice assignment, skipped when argument is fixed
2975             --  length and known to be null.
2976
2977             elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
2978                declare
2979                   Assign : Node_Id :=
2980                              Make_Assignment_Statement (Loc,
2981                                Name       =>
2982                                  Make_Slice (Loc,
2983                                    Prefix         =>
2984                                      New_Occurrence_Of (Ent, Loc),
2985                                    Discrete_Range =>
2986                                      Make_Range (Loc,
2987                                        Low_Bound  => To_Ityp (Lo),
2988                                        High_Bound => To_Ityp (Hi))),
2989                                Expression => Operands (J));
2990                begin
2991                   if Is_Fixed_Length (J) then
2992                      Known_Non_Null_Operand_Seen := True;
2993
2994                   elsif not Known_Non_Null_Operand_Seen then
2995
2996                      --  Here if operand length is not statically known and no
2997                      --  operand known to be non-null has been processed yet.
2998                      --  If operand length is 0, we do not need to perform the
2999                      --  assignment, and we must avoid the evaluation of the
3000                      --  high bound of the slice, since it may underflow if the
3001                      --  low bound is Ityp'First.
3002
3003                      Assign :=
3004                        Make_Implicit_If_Statement (Cnode,
3005                          Condition =>
3006                            Make_Op_Ne (Loc,
3007                              Left_Opnd =>
3008                                New_Occurrence_Of (Var_Length (J), Loc),
3009                              Right_Opnd => Make_Integer_Literal (Loc, 0)),
3010                          Then_Statements =>
3011                            New_List (Assign));
3012                   end if;
3013
3014                   Insert_Action (Cnode, Assign, Suppress => All_Checks);
3015                end;
3016             end if;
3017          end;
3018       end loop;
3019
3020       --  Finally we build the result, which is a reference to the array object
3021
3022       Result := New_Reference_To (Ent, Loc);
3023
3024    <<Done>>
3025       Rewrite (Cnode, Result);
3026       Analyze_And_Resolve (Cnode, Atyp);
3027
3028    exception
3029       when Concatenation_Error =>
3030
3031          --  Kill warning generated for the declaration of the static out of
3032          --  range high bound, and instead generate a Constraint_Error with
3033          --  an appropriate specific message.
3034
3035          Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3036          Apply_Compile_Time_Constraint_Error
3037            (N      => Cnode,
3038             Msg    => "concatenation result upper bound out of range?",
3039             Reason => CE_Range_Check_Failed);
3040          --  Set_Etype (Cnode, Atyp);
3041    end Expand_Concatenate;
3042
3043    ------------------------
3044    -- Expand_N_Allocator --
3045    ------------------------
3046
3047    procedure Expand_N_Allocator (N : Node_Id) is
3048       PtrT  : constant Entity_Id  := Etype (N);
3049       Dtyp  : constant Entity_Id  := Available_View (Designated_Type (PtrT));
3050       Etyp  : constant Entity_Id  := Etype (Expression (N));
3051       Loc   : constant Source_Ptr := Sloc (N);
3052       Desig : Entity_Id;
3053       Temp  : Entity_Id;
3054       Nod   : Node_Id;
3055
3056       procedure Complete_Coextension_Finalization;
3057       --  Generate finalization calls for all nested coextensions of N. This
3058       --  routine may allocate list controllers if necessary.
3059
3060       procedure Rewrite_Coextension (N : Node_Id);
3061       --  Static coextensions have the same lifetime as the entity they
3062       --  constrain. Such occurrences can be rewritten as aliased objects
3063       --  and their unrestricted access used instead of the coextension.
3064
3065       function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
3066       --  Given a constrained array type E, returns a node representing the
3067       --  code to compute the size in storage elements for the given type.
3068       --  This is done without using the attribute (which malfunctions for
3069       --  large sizes ???)
3070
3071       ---------------------------------------
3072       -- Complete_Coextension_Finalization --
3073       ---------------------------------------
3074
3075       procedure Complete_Coextension_Finalization is
3076          Coext      : Node_Id;
3077          Coext_Elmt : Elmt_Id;
3078          Flist      : Node_Id;
3079          Ref        : Node_Id;
3080
3081          function Inside_A_Return_Statement (N : Node_Id) return Boolean;
3082          --  Determine whether node N is part of a return statement
3083
3084          function Needs_Initialization_Call (N : Node_Id) return Boolean;
3085          --  Determine whether node N is a subtype indicator allocator which
3086          --  acts a coextension. Such coextensions need initialization.
3087
3088          -------------------------------
3089          -- Inside_A_Return_Statement --
3090          -------------------------------
3091
3092          function Inside_A_Return_Statement (N : Node_Id) return Boolean is
3093             P : Node_Id;
3094
3095          begin
3096             P := Parent (N);
3097             while Present (P) loop
3098                if Nkind_In
3099                    (P, N_Extended_Return_Statement, N_Simple_Return_Statement)
3100                then
3101                   return True;
3102
3103                --  Stop the traversal when we reach a subprogram body
3104
3105                elsif Nkind (P) = N_Subprogram_Body then
3106                   return False;
3107                end if;
3108
3109                P := Parent (P);
3110             end loop;
3111
3112             return False;
3113          end Inside_A_Return_Statement;
3114
3115          -------------------------------
3116          -- Needs_Initialization_Call --
3117          -------------------------------
3118
3119          function Needs_Initialization_Call (N : Node_Id) return Boolean is
3120             Obj_Decl : Node_Id;
3121
3122          begin
3123             if Nkind (N) = N_Explicit_Dereference
3124               and then Nkind (Prefix (N)) = N_Identifier
3125               and then Nkind (Parent (Entity (Prefix (N)))) =
3126                          N_Object_Declaration
3127             then
3128                Obj_Decl := Parent (Entity (Prefix (N)));
3129
3130                return
3131                  Present (Expression (Obj_Decl))
3132                    and then Nkind (Expression (Obj_Decl)) = N_Allocator
3133                    and then Nkind (Expression (Expression (Obj_Decl))) /=
3134                               N_Qualified_Expression;
3135             end if;
3136
3137             return False;
3138          end Needs_Initialization_Call;
3139
3140       --  Start of processing for Complete_Coextension_Finalization
3141
3142       begin
3143          --  When a coextension root is inside a return statement, we need to
3144          --  use the finalization chain of the function's scope. This does not
3145          --  apply for controlled named access types because in those cases we
3146          --  can use the finalization chain of the type itself.
3147
3148          if Inside_A_Return_Statement (N)
3149            and then
3150              (Ekind (PtrT) = E_Anonymous_Access_Type
3151                 or else
3152                   (Ekind (PtrT) = E_Access_Type
3153                      and then No (Associated_Final_Chain (PtrT))))
3154          then
3155             declare
3156                Decl    : Node_Id;
3157                Outer_S : Entity_Id;
3158                S       : Entity_Id := Current_Scope;
3159
3160             begin
3161                while Present (S) and then S /= Standard_Standard loop
3162                   if Ekind (S) = E_Function then
3163                      Outer_S := Scope (S);
3164
3165                      --  Retrieve the declaration of the body
3166
3167                      Decl :=
3168                        Parent
3169                          (Parent
3170                             (Corresponding_Body (Parent (Parent (S)))));
3171                      exit;
3172                   end if;
3173
3174                   S := Scope (S);
3175                end loop;
3176
3177                --  Push the scope of the function body since we are inserting
3178                --  the list before the body, but we are currently in the body
3179                --  itself. Override the finalization list of PtrT since the
3180                --  finalization context is now different.
3181
3182                Push_Scope (Outer_S);
3183                Build_Final_List (Decl, PtrT);
3184                Pop_Scope;
3185             end;
3186
3187          --  The root allocator may not be controlled, but it still needs a
3188          --  finalization list for all nested coextensions.
3189
3190          elsif No (Associated_Final_Chain (PtrT)) then
3191             Build_Final_List (N, PtrT);
3192          end if;
3193
3194          Flist :=
3195            Make_Selected_Component (Loc,
3196              Prefix =>
3197                New_Reference_To (Associated_Final_Chain (PtrT), Loc),
3198              Selector_Name =>
3199                Make_Identifier (Loc, Name_F));
3200
3201          Coext_Elmt := First_Elmt (Coextensions (N));
3202          while Present (Coext_Elmt) loop
3203             Coext := Node (Coext_Elmt);
3204
3205             --  Generate:
3206             --    typ! (coext.all)
3207
3208             if Nkind (Coext) = N_Identifier then
3209                Ref :=
3210                  Make_Unchecked_Type_Conversion (Loc,
3211                    Subtype_Mark => New_Reference_To (Etype (Coext), Loc),
3212                    Expression   =>
3213                      Make_Explicit_Dereference (Loc,
3214                        Prefix => New_Copy_Tree (Coext)));
3215             else
3216                Ref := New_Copy_Tree (Coext);
3217             end if;
3218
3219             --  No initialization call if not allowed
3220
3221             Check_Restriction (No_Default_Initialization, N);
3222
3223             if not Restriction_Active (No_Default_Initialization) then
3224
3225                --  Generate:
3226                --    initialize (Ref)
3227                --    attach_to_final_list (Ref, Flist, 2)
3228
3229                if Needs_Initialization_Call (Coext) then
3230                   Insert_Actions (N,
3231                     Make_Init_Call (
3232                       Ref         => Ref,
3233                       Typ         => Etype (Coext),
3234                       Flist_Ref   => Flist,
3235                       With_Attach => Make_Integer_Literal (Loc, Uint_2)));
3236
3237                --  Generate:
3238                --    attach_to_final_list (Ref, Flist, 2)
3239
3240                else
3241                   Insert_Action (N,
3242                     Make_Attach_Call (
3243                       Obj_Ref     => Ref,
3244                       Flist_Ref   => New_Copy_Tree (Flist),
3245                       With_Attach => Make_Integer_Literal (Loc, Uint_2)));
3246                end if;
3247             end if;
3248
3249             Next_Elmt (Coext_Elmt);
3250          end loop;
3251       end Complete_Coextension_Finalization;
3252
3253       -------------------------
3254       -- Rewrite_Coextension --
3255       -------------------------
3256
3257       procedure Rewrite_Coextension (N : Node_Id) is
3258          Temp : constant Node_Id := Make_Temporary (Loc, 'C');
3259
3260          --  Generate:
3261          --    Cnn : aliased Etyp;
3262
3263          Decl : constant Node_Id :=
3264                   Make_Object_Declaration (Loc,
3265                     Defining_Identifier => Temp,
3266                     Aliased_Present     => True,
3267                     Object_Definition   =>
3268                       New_Occurrence_Of (Etyp, Loc));
3269          Nod  : Node_Id;
3270
3271       begin
3272          if Nkind (Expression (N)) = N_Qualified_Expression then
3273             Set_Expression (Decl, Expression (Expression (N)));
3274          end if;
3275
3276          --  Find the proper insertion node for the declaration
3277
3278          Nod := Parent (N);
3279          while Present (Nod) loop
3280             exit when Nkind (Nod) in N_Statement_Other_Than_Procedure_Call
3281               or else Nkind (Nod) = N_Procedure_Call_Statement
3282               or else Nkind (Nod) in N_Declaration;
3283             Nod := Parent (Nod);
3284          end loop;
3285
3286          Insert_Before (Nod, Decl);
3287          Analyze (Decl);
3288
3289          Rewrite (N,
3290            Make_Attribute_Reference (Loc,
3291              Prefix         => New_Occurrence_Of (Temp, Loc),
3292              Attribute_Name => Name_Unrestricted_Access));
3293
3294          Analyze_And_Resolve (N, PtrT);
3295       end Rewrite_Coextension;
3296
3297       ------------------------------
3298       -- Size_In_Storage_Elements --
3299       ------------------------------
3300
3301       function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
3302       begin
3303          --  Logically this just returns E'Max_Size_In_Storage_Elements.
3304          --  However, the reason for the existence of this function is
3305          --  to construct a test for sizes too large, which means near the
3306          --  32-bit limit on a 32-bit machine, and precisely the trouble
3307          --  is that we get overflows when sizes are greater than 2**31.
3308
3309          --  So what we end up doing for array types is to use the expression:
3310
3311          --    number-of-elements * component_type'Max_Size_In_Storage_Elements
3312
3313          --  which avoids this problem. All this is a big bogus, but it does
3314          --  mean we catch common cases of trying to allocate arrays that
3315          --  are too large, and which in the absence of a check results in
3316          --  undetected chaos ???
3317
3318          declare
3319             Len : Node_Id;
3320             Res : Node_Id;
3321
3322          begin
3323             for J in 1 .. Number_Dimensions (E) loop
3324                Len :=
3325                  Make_Attribute_Reference (Loc,
3326                    Prefix         => New_Occurrence_Of (E, Loc),
3327                    Attribute_Name => Name_Length,
3328                    Expressions    => New_List (
3329                      Make_Integer_Literal (Loc, J)));
3330
3331                if J = 1 then
3332                   Res := Len;
3333
3334                else
3335                   Res :=
3336                     Make_Op_Multiply (Loc,
3337                       Left_Opnd  => Res,
3338                       Right_Opnd => Len);
3339                end if;
3340             end loop;
3341
3342             return
3343               Make_Op_Multiply (Loc,
3344                 Left_Opnd  => Len,
3345                 Right_Opnd =>
3346                   Make_Attribute_Reference (Loc,
3347                     Prefix => New_Occurrence_Of (Component_Type (E), Loc),
3348                     Attribute_Name => Name_Max_Size_In_Storage_Elements));
3349          end;
3350       end Size_In_Storage_Elements;
3351
3352    --  Start of processing for Expand_N_Allocator
3353
3354    begin
3355       --  RM E.2.3(22). We enforce that the expected type of an allocator
3356       --  shall not be a remote access-to-class-wide-limited-private type
3357
3358       --  Why is this being done at expansion time, seems clearly wrong ???
3359
3360       Validate_Remote_Access_To_Class_Wide_Type (N);
3361
3362       --  Set the Storage Pool
3363
3364       Set_Storage_Pool (N, Associated_Storage_Pool (Root_Type (PtrT)));
3365
3366       if Present (Storage_Pool (N)) then
3367          if Is_RTE (Storage_Pool (N), RE_SS_Pool) then
3368             if VM_Target = No_VM then
3369                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
3370             end if;
3371
3372          elsif Is_Class_Wide_Type (Etype (Storage_Pool (N))) then
3373             Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
3374
3375          else
3376             Set_Procedure_To_Call (N,
3377               Find_Prim_Op (Etype (Storage_Pool (N)), Name_Allocate));
3378          end if;
3379       end if;
3380
3381       --  Under certain circumstances we can replace an allocator by an access
3382       --  to statically allocated storage. The conditions, as noted in AARM
3383       --  3.10 (10c) are as follows:
3384
3385       --    Size and initial value is known at compile time
3386       --    Access type is access-to-constant
3387
3388       --  The allocator is not part of a constraint on a record component,
3389       --  because in that case the inserted actions are delayed until the
3390       --  record declaration is fully analyzed, which is too late for the
3391       --  analysis of the rewritten allocator.
3392
3393       if Is_Access_Constant (PtrT)
3394         and then Nkind (Expression (N)) = N_Qualified_Expression
3395         and then Compile_Time_Known_Value (Expression (Expression (N)))
3396         and then Size_Known_At_Compile_Time (Etype (Expression
3397                                                     (Expression (N))))
3398         and then not Is_Record_Type (Current_Scope)
3399       then
3400          --  Here we can do the optimization. For the allocator
3401
3402          --    new x'(y)
3403
3404          --  We insert an object declaration
3405
3406          --    Tnn : aliased x := y;
3407
3408          --  and replace the allocator by Tnn'Unrestricted_Access. Tnn is
3409          --  marked as requiring static allocation.
3410
3411          Temp := Make_Temporary (Loc, 'T', Expression (Expression (N)));
3412          Desig := Subtype_Mark (Expression (N));
3413
3414          --  If context is constrained, use constrained subtype directly,
3415          --  so that the constant is not labelled as having a nominally
3416          --  unconstrained subtype.
3417
3418          if Entity (Desig) = Base_Type (Dtyp) then
3419             Desig := New_Occurrence_Of (Dtyp, Loc);
3420          end if;
3421
3422          Insert_Action (N,
3423            Make_Object_Declaration (Loc,
3424              Defining_Identifier => Temp,
3425              Aliased_Present     => True,
3426              Constant_Present    => Is_Access_Constant (PtrT),
3427              Object_Definition   => Desig,
3428              Expression          => Expression (Expression (N))));
3429
3430          Rewrite (N,
3431            Make_Attribute_Reference (Loc,
3432              Prefix => New_Occurrence_Of (Temp, Loc),
3433              Attribute_Name => Name_Unrestricted_Access));
3434
3435          Analyze_And_Resolve (N, PtrT);
3436
3437          --  We set the variable as statically allocated, since we don't want
3438          --  it going on the stack of the current procedure!
3439
3440          Set_Is_Statically_Allocated (Temp);
3441          return;
3442       end if;
3443
3444       --  Same if the allocator is an access discriminant for a local object:
3445       --  instead of an allocator we create a local value and constrain the
3446       --  the enclosing object with the corresponding access attribute.
3447
3448       if Is_Static_Coextension (N) then
3449          Rewrite_Coextension (N);
3450          return;
3451       end if;
3452
3453       --  The current allocator creates an object which may contain nested
3454       --  coextensions. Use the current allocator's finalization list to
3455       --  generate finalization call for all nested coextensions.
3456
3457       if Is_Coextension_Root (N) then
3458          Complete_Coextension_Finalization;
3459       end if;
3460
3461       --  Check for size too large, we do this because the back end misses
3462       --  proper checks here and can generate rubbish allocation calls when
3463       --  we are near the limit. We only do this for the 32-bit address case
3464       --  since that is from a practical point of view where we see a problem.
3465
3466       if System_Address_Size = 32
3467         and then not Storage_Checks_Suppressed (PtrT)
3468         and then not Storage_Checks_Suppressed (Dtyp)
3469         and then not Storage_Checks_Suppressed (Etyp)
3470       then
3471          --  The check we want to generate should look like
3472
3473          --  if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
3474          --    raise Storage_Error;
3475          --  end if;
3476
3477          --  where 3.5 gigabytes is a constant large enough to accomodate any
3478          --  reasonable request for. But we can't do it this way because at
3479          --  least at the moment we don't compute this attribute right, and
3480          --  can silently give wrong results when the result gets large. Since
3481          --  this is all about large results, that's bad, so instead we only
3482          --  apply the check for constrained arrays, and manually compute the
3483          --  value of the attribute ???
3484
3485          if Is_Array_Type (Etyp) and then Is_Constrained (Etyp) then
3486             Insert_Action (N,
3487               Make_Raise_Storage_Error (Loc,
3488                 Condition =>
3489                   Make_Op_Gt (Loc,
3490                     Left_Opnd  => Size_In_Storage_Elements (Etyp),
3491                     Right_Opnd =>
3492                       Make_Integer_Literal (Loc,
3493                         Intval => Uint_7 * (Uint_2 ** 29))),
3494                 Reason    => SE_Object_Too_Large));
3495          end if;
3496       end if;
3497
3498       --  Handle case of qualified expression (other than optimization above)
3499       --  First apply constraint checks, because the bounds or discriminants
3500       --  in the aggregate might not match the subtype mark in the allocator.
3501
3502       if Nkind (Expression (N)) = N_Qualified_Expression then
3503          Apply_Constraint_Check
3504            (Expression (Expression (N)), Etype (Expression (N)));
3505
3506          Expand_Allocator_Expression (N);
3507          return;
3508       end if;
3509
3510       --  If the allocator is for a type which requires initialization, and
3511       --  there is no initial value (i.e. operand is a subtype indication
3512       --  rather than a qualified expression), then we must generate a call to
3513       --  the initialization routine using an expressions action node:
3514
3515       --     [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
3516
3517       --  Here ptr_T is the pointer type for the allocator, and T is the
3518       --  subtype of the allocator. A special case arises if the designated
3519       --  type of the access type is a task or contains tasks. In this case
3520       --  the call to Init (Temp.all ...) is replaced by code that ensures
3521       --  that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
3522       --  for details). In addition, if the type T is a task T, then the
3523       --  first argument to Init must be converted to the task record type.
3524
3525       declare
3526          T            : constant Entity_Id := Entity (Expression (N));
3527          Init         : Entity_Id;
3528          Arg1         : Node_Id;
3529          Args         : List_Id;
3530          Decls        : List_Id;
3531          Decl         : Node_Id;
3532          Discr        : Elmt_Id;
3533          Flist        : Node_Id;
3534          Temp_Decl    : Node_Id;
3535          Temp_Type    : Entity_Id;
3536          Attach_Level : Uint;
3537
3538       begin
3539          if No_Initialization (N) then
3540             null;
3541
3542          --  Case of no initialization procedure present
3543
3544          elsif not Has_Non_Null_Base_Init_Proc (T) then
3545
3546             --  Case of simple initialization required
3547
3548             if Needs_Simple_Initialization (T) then
3549                Check_Restriction (No_Default_Initialization, N);
3550                Rewrite (Expression (N),
3551                  Make_Qualified_Expression (Loc,
3552                    Subtype_Mark => New_Occurrence_Of (T, Loc),
3553                    Expression   => Get_Simple_Init_Val (T, N)));
3554
3555                Analyze_And_Resolve (Expression (Expression (N)), T);
3556                Analyze_And_Resolve (Expression (N), T);
3557                Set_Paren_Count     (Expression (Expression (N)), 1);
3558                Expand_N_Allocator  (N);
3559
3560             --  No initialization required
3561
3562             else
3563                null;
3564             end if;
3565
3566          --  Case of initialization procedure present, must be called
3567
3568          else
3569             Check_Restriction (No_Default_Initialization, N);
3570
3571             if not Restriction_Active (No_Default_Initialization) then
3572                Init := Base_Init_Proc (T);
3573                Nod  := N;
3574                Temp := Make_Temporary (Loc, 'P');
3575
3576                --  Construct argument list for the initialization routine call
3577
3578                Arg1 :=
3579                  Make_Explicit_Dereference (Loc,
3580                    Prefix => New_Reference_To (Temp, Loc));
3581                Set_Assignment_OK (Arg1);
3582                Temp_Type := PtrT;
3583
3584                --  The initialization procedure expects a specific type. if the
3585                --  context is access to class wide, indicate that the object
3586                --  being allocated has the right specific type.
3587
3588                if Is_Class_Wide_Type (Dtyp) then
3589                   Arg1 := Unchecked_Convert_To (T, Arg1);
3590                end if;
3591
3592                --  If designated type is a concurrent type or if it is private
3593                --  type whose definition is a concurrent type, the first
3594                --  argument in the Init routine has to be unchecked conversion
3595                --  to the corresponding record type. If the designated type is
3596                --  a derived type, we also convert the argument to its root
3597                --  type.
3598
3599                if Is_Concurrent_Type (T) then
3600                   Arg1 :=
3601                     Unchecked_Convert_To (Corresponding_Record_Type (T), Arg1);
3602
3603                elsif Is_Private_Type (T)
3604                  and then Present (Full_View (T))
3605                  and then Is_Concurrent_Type (Full_View (T))
3606                then
3607                   Arg1 :=
3608                     Unchecked_Convert_To
3609                       (Corresponding_Record_Type (Full_View (T)), Arg1);
3610
3611                elsif Etype (First_Formal (Init)) /= Base_Type (T) then
3612                   declare
3613                      Ftyp : constant Entity_Id := Etype (First_Formal (Init));
3614                   begin
3615                      Arg1 := OK_Convert_To (Etype (Ftyp), Arg1);
3616                      Set_Etype (Arg1, Ftyp);
3617                   end;
3618                end if;
3619
3620                Args := New_List (Arg1);
3621
3622                --  For the task case, pass the Master_Id of the access type as
3623                --  the value of the _Master parameter, and _Chain as the value
3624                --  of the _Chain parameter (_Chain will be defined as part of
3625                --  the generated code for the allocator).
3626
3627                --  In Ada 2005, the context may be a function that returns an
3628                --  anonymous access type. In that case the Master_Id has been
3629                --  created when expanding the function declaration.
3630
3631                if Has_Task (T) then
3632                   if No (Master_Id (Base_Type (PtrT))) then
3633
3634                      --  If we have a non-library level task with restriction
3635                      --  No_Task_Hierarchy set, then no point in expanding.
3636
3637                      if not Is_Library_Level_Entity (T)
3638                        and then Restriction_Active (No_Task_Hierarchy)
3639                      then
3640                         return;
3641                      end if;
3642
3643                      --  The designated type was an incomplete type, and the
3644                      --  access type did not get expanded. Salvage it now.
3645
3646                      pragma Assert (Present (Parent (Base_Type (PtrT))));
3647                      Expand_N_Full_Type_Declaration
3648                        (Parent (Base_Type (PtrT)));
3649                   end if;
3650
3651                   --  If the context of the allocator is a declaration or an
3652                   --  assignment, we can generate a meaningful image for it,
3653                   --  even though subsequent assignments might remove the
3654                   --  connection between task and entity. We build this image
3655                   --  when the left-hand side is a simple variable, a simple
3656                   --  indexed assignment or a simple selected component.
3657
3658                   if Nkind (Parent (N)) = N_Assignment_Statement then
3659                      declare
3660                         Nam : constant Node_Id := Name (Parent (N));
3661
3662                      begin
3663                         if Is_Entity_Name (Nam) then
3664                            Decls :=
3665                              Build_Task_Image_Decls
3666                                (Loc,
3667                                 New_Occurrence_Of
3668                                   (Entity (Nam), Sloc (Nam)), T);
3669
3670                         elsif Nkind_In
3671                           (Nam, N_Indexed_Component, N_Selected_Component)
3672                           and then Is_Entity_Name (Prefix (Nam))
3673                         then
3674                            Decls :=
3675                              Build_Task_Image_Decls
3676                                (Loc, Nam, Etype (Prefix (Nam)));
3677                         else
3678                            Decls := Build_Task_Image_Decls (Loc, T, T);
3679                         end if;
3680                      end;
3681
3682                   elsif Nkind (Parent (N)) = N_Object_Declaration then
3683                      Decls :=
3684                        Build_Task_Image_Decls
3685                          (Loc, Defining_Identifier (Parent (N)), T);
3686
3687                   else
3688                      Decls := Build_Task_Image_Decls (Loc, T, T);
3689                   end if;
3690
3691                   Append_To (Args,
3692                     New_Reference_To
3693                       (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
3694                   Append_To (Args, Make_Identifier (Loc, Name_uChain));
3695
3696                   Decl := Last (Decls);
3697                   Append_To (Args,
3698                     New_Occurrence_Of (Defining_Identifier (Decl), Loc));
3699
3700                   --  Has_Task is false, Decls not used
3701
3702                else
3703                   Decls := No_List;
3704                end if;
3705
3706                --  Add discriminants if discriminated type
3707
3708                declare
3709                   Dis : Boolean := False;
3710                   Typ : Entity_Id;
3711
3712                begin
3713                   if Has_Discriminants (T) then
3714                      Dis := True;
3715                      Typ := T;
3716
3717                   elsif Is_Private_Type (T)
3718                     and then Present (Full_View (T))
3719                     and then Has_Discriminants (Full_View (T))
3720                   then
3721                      Dis := True;
3722                      Typ := Full_View (T);
3723                   end if;
3724
3725                   if Dis then
3726
3727                      --  If the allocated object will be constrained by the
3728                      --  default values for discriminants, then build a subtype
3729                      --  with those defaults, and change the allocated subtype
3730                      --  to that. Note that this happens in fewer cases in Ada
3731                      --  2005 (AI-363).
3732
3733                      if not Is_Constrained (Typ)
3734                        and then Present (Discriminant_Default_Value
3735                                          (First_Discriminant (Typ)))
3736                        and then (Ada_Version < Ada_05
3737                                   or else
3738                                     not Has_Constrained_Partial_View (Typ))
3739                      then
3740                         Typ := Build_Default_Subtype (Typ, N);
3741                         Set_Expression (N, New_Reference_To (Typ, Loc));
3742                      end if;
3743
3744                      Discr := First_Elmt (Discriminant_Constraint (Typ));
3745                      while Present (Discr) loop
3746                         Nod := Node (Discr);
3747                         Append (New_Copy_Tree (Node (Discr)), Args);
3748
3749                         --  AI-416: when the discriminant constraint is an
3750                         --  anonymous access type make sure an accessibility
3751                         --  check is inserted if necessary (3.10.2(22.q/2))
3752
3753                         if Ada_Version >= Ada_05
3754                           and then
3755                             Ekind (Etype (Nod)) = E_Anonymous_Access_Type
3756                         then
3757                            Apply_Accessibility_Check
3758                              (Nod, Typ, Insert_Node => Nod);
3759                         end if;
3760
3761                         Next_Elmt (Discr);
3762                      end loop;
3763                   end if;
3764                end;
3765
3766                --  We set the allocator as analyzed so that when we analyze the
3767                --  expression actions node, we do not get an unwanted recursive
3768                --  expansion of the allocator expression.
3769
3770                Set_Analyzed (N, True);
3771                Nod := Relocate_Node (N);
3772
3773                --  Here is the transformation:
3774                --    input:  new T
3775                --    output: Temp : constant ptr_T := new T;
3776                --            Init (Temp.all, ...);
3777                --    <CTRL>  Attach_To_Final_List (Finalizable (Temp.all));
3778                --    <CTRL>  Initialize (Finalizable (Temp.all));
3779
3780                --  Here ptr_T is the pointer type for the allocator, and is the
3781                --  subtype of the allocator.
3782
3783                Temp_Decl :=
3784                  Make_Object_Declaration (Loc,
3785                    Defining_Identifier => Temp,
3786                    Constant_Present    => True,
3787                    Object_Definition   => New_Reference_To (Temp_Type, Loc),
3788                    Expression          => Nod);
3789
3790                Set_Assignment_OK (Temp_Decl);
3791                Insert_Action (N, Temp_Decl, Suppress => All_Checks);
3792
3793                --  If the designated type is a task type or contains tasks,
3794                --  create block to activate created tasks, and insert
3795                --  declaration for Task_Image variable ahead of call.
3796
3797                if Has_Task (T) then
3798                   declare
3799                      L   : constant List_Id := New_List;
3800                      Blk : Node_Id;
3801                   begin
3802                      Build_Task_Allocate_Block (L, Nod, Args);
3803                      Blk := Last (L);
3804                      Insert_List_Before (First (Declarations (Blk)), Decls);
3805                      Insert_Actions (N, L);
3806                   end;
3807
3808                else
3809                   Insert_Action (N,
3810                     Make_Procedure_Call_Statement (Loc,
3811                       Name                   => New_Reference_To (Init, Loc),
3812                       Parameter_Associations => Args));
3813                end if;
3814
3815                if Needs_Finalization (T) then
3816
3817                   --  Postpone the generation of a finalization call for the
3818                   --  current allocator if it acts as a coextension.
3819
3820                   if Is_Dynamic_Coextension (N) then
3821                      if No (Coextensions (N)) then
3822                         Set_Coextensions (N, New_Elmt_List);
3823                      end if;
3824
3825                      Append_Elmt (New_Copy_Tree (Arg1), Coextensions (N));
3826
3827                   else
3828                      Flist :=
3829                        Get_Allocator_Final_List (N, Base_Type (T), PtrT);
3830
3831                      --  Anonymous access types created for access parameters
3832                      --  are attached to an explicitly constructed controller,
3833                      --  which ensures that they can be finalized properly,
3834                      --  even if their deallocation might not happen. The list
3835                      --  associated with the controller is doubly-linked. For
3836                      --  other anonymous access types, the object may end up
3837                      --  on the global final list which is singly-linked.
3838                      --  Work needed for access discriminants in Ada 2005 ???
3839
3840                      if Ekind (PtrT) = E_Anonymous_Access_Type then
3841                         Attach_Level := Uint_1;
3842                      else
3843                         Attach_Level := Uint_2;
3844                      end if;
3845
3846                      Insert_Actions (N,
3847                        Make_Init_Call (
3848                          Ref          => New_Copy_Tree (Arg1),
3849                          Typ          => T,
3850                          Flist_Ref    => Flist,
3851                          With_Attach  => Make_Integer_Literal (Loc,
3852                                            Intval => Attach_Level)));
3853                   end if;
3854                end if;
3855
3856                Rewrite (N, New_Reference_To (Temp, Loc));
3857                Analyze_And_Resolve (N, PtrT);
3858             end if;
3859          end if;
3860       end;
3861
3862       --  Ada 2005 (AI-251): If the allocator is for a class-wide interface
3863       --  object that has been rewritten as a reference, we displace "this"
3864       --  to reference properly its secondary dispatch table.
3865
3866       if Nkind (N) = N_Identifier
3867         and then Is_Interface (Dtyp)
3868       then
3869          Displace_Allocator_Pointer (N);
3870       end if;
3871
3872    exception
3873       when RE_Not_Available =>
3874          return;
3875    end Expand_N_Allocator;
3876
3877    -----------------------
3878    -- Expand_N_And_Then --
3879    -----------------------
3880
3881    procedure Expand_N_And_Then (N : Node_Id)
3882      renames Expand_Short_Circuit_Operator;
3883
3884    ------------------------------
3885    -- Expand_N_Case_Expression --
3886    ------------------------------
3887
3888    procedure Expand_N_Case_Expression (N : Node_Id) is
3889       Loc     : constant Source_Ptr := Sloc (N);
3890       Typ     : constant Entity_Id  := Etype (N);
3891       Cstmt   : Node_Id;
3892       Tnn     : Entity_Id;
3893       Pnn     : Entity_Id;
3894       Actions : List_Id;
3895       Ttyp    : Entity_Id;
3896       Alt     : Node_Id;
3897       Fexp    : Node_Id;
3898
3899    begin
3900       --  We expand
3901
3902       --    case X is when A => AX, when B => BX ...
3903
3904       --  to
3905
3906       --    do
3907       --       Tnn : typ;
3908       --       case X is
3909       --          when A =>
3910       --             Tnn := AX;
3911       --          when B =>
3912       --             Tnn := BX;
3913       --          ...
3914       --       end case;
3915       --    in Tnn end;
3916
3917       --  However, this expansion is wrong for limited types, and also
3918       --  wrong for unconstrained types (since the bounds may not be the
3919       --  same in all branches). Furthermore it involves an extra copy
3920       --  for large objects. So we take care of this by using the following
3921       --  modified expansion for non-scalar types:
3922
3923       --    do
3924       --       type Pnn is access all typ;
3925       --       Tnn : Pnn;
3926       --       case X is
3927       --          when A =>
3928       --             T := AX'Unrestricted_Access;
3929       --          when B =>
3930       --             T := BX'Unrestricted_Access;
3931       --          ...
3932       --       end case;
3933       --    in Tnn.all end;
3934
3935       Cstmt :=
3936         Make_Case_Statement (Loc,
3937           Expression   => Expression (N),
3938           Alternatives => New_List);
3939
3940       Actions := New_List;
3941
3942       --  Scalar case
3943
3944       if Is_Scalar_Type (Typ) then
3945          Ttyp := Typ;
3946
3947       else
3948          Pnn := Make_Temporary (Loc, 'P');
3949          Append_To (Actions,
3950            Make_Full_Type_Declaration (Loc,
3951              Defining_Identifier => Pnn,
3952              Type_Definition =>
3953                Make_Access_To_Object_Definition (Loc,
3954                  All_Present => True,
3955                  Subtype_Indication =>
3956                    New_Reference_To (Typ, Loc))));
3957          Ttyp := Pnn;
3958       end if;
3959
3960       Tnn := Make_Temporary (Loc, 'T');
3961       Append_To (Actions,
3962         Make_Object_Declaration (Loc,
3963           Defining_Identifier => Tnn,
3964           Object_Definition   => New_Occurrence_Of (Ttyp, Loc)));
3965
3966       --  Now process the alternatives
3967
3968       Alt := First (Alternatives (N));
3969       while Present (Alt) loop
3970          declare
3971             Aexp : Node_Id             := Expression (Alt);
3972             Aloc : constant Source_Ptr := Sloc (Aexp);
3973
3974          begin
3975             if not Is_Scalar_Type (Typ) then
3976                Aexp :=
3977                  Make_Attribute_Reference (Aloc,
3978                    Prefix         => Relocate_Node (Aexp),
3979                    Attribute_Name => Name_Unrestricted_Access);
3980             end if;
3981
3982             Append_To
3983               (Alternatives (Cstmt),
3984                Make_Case_Statement_Alternative (Sloc (Alt),
3985                  Discrete_Choices => Discrete_Choices (Alt),
3986                  Statements       => New_List (
3987                    Make_Assignment_Statement (Aloc,
3988                      Name       => New_Occurrence_Of (Tnn, Loc),
3989                      Expression => Aexp))));
3990          end;
3991
3992          Next (Alt);
3993       end loop;
3994
3995       Append_To (Actions, Cstmt);
3996
3997       --  Construct and return final expression with actions
3998
3999       if Is_Scalar_Type (Typ) then
4000          Fexp := New_Occurrence_Of (Tnn, Loc);
4001       else
4002          Fexp :=
4003            Make_Explicit_Dereference (Loc,
4004              Prefix => New_Occurrence_Of (Tnn, Loc));
4005       end if;
4006
4007       Rewrite (N,
4008         Make_Expression_With_Actions (Loc,
4009           Expression => Fexp,
4010           Actions    => Actions));
4011
4012       Analyze_And_Resolve (N, Typ);
4013    end Expand_N_Case_Expression;
4014
4015    -------------------------------------
4016    -- Expand_N_Conditional_Expression --
4017    -------------------------------------
4018
4019    --  Deal with limited types and expression actions
4020
4021    procedure Expand_N_Conditional_Expression (N : Node_Id) is
4022       Loc    : constant Source_Ptr := Sloc (N);
4023       Cond   : constant Node_Id    := First (Expressions (N));
4024       Thenx  : constant Node_Id    := Next (Cond);
4025       Elsex  : constant Node_Id    := Next (Thenx);
4026       Typ    : constant Entity_Id  := Etype (N);
4027
4028       Cnn     : Entity_Id;
4029       Decl    : Node_Id;
4030       New_If  : Node_Id;
4031       New_N   : Node_Id;
4032       P_Decl  : Node_Id;
4033       Expr    : Node_Id;
4034       Actions : List_Id;
4035
4036    begin
4037       --  Fold at compile time if condition known. We have already folded
4038       --  static conditional expressions, but it is possible to fold any
4039       --  case in which the condition is known at compile time, even though
4040       --  the result is non-static.
4041
4042       --  Note that we don't do the fold of such cases in Sem_Elab because
4043       --  it can cause infinite loops with the expander adding a conditional
4044       --  expression, and Sem_Elab circuitry removing it repeatedly.
4045
4046       if Compile_Time_Known_Value (Cond) then
4047          if Is_True (Expr_Value (Cond)) then
4048             Expr := Thenx;
4049             Actions := Then_Actions (N);
4050          else
4051             Expr := Elsex;
4052             Actions := Else_Actions (N);
4053          end if;
4054
4055          Remove (Expr);
4056
4057          if Present (Actions) then
4058
4059             --  If we are not allowed to use Expression_With_Actions, just
4060             --  skip the optimization, it is not critical for correctness.
4061
4062             if not Use_Expression_With_Actions then
4063                goto Skip_Optimization;
4064             end if;
4065
4066             Rewrite (N,
4067               Make_Expression_With_Actions (Loc,
4068                 Expression => Relocate_Node (Expr),
4069                 Actions    => Actions));
4070             Analyze_And_Resolve (N, Typ);
4071
4072          else
4073             Rewrite (N, Relocate_Node (Expr));
4074          end if;
4075
4076          --  Note that the result is never static (legitimate cases of static
4077          --  conditional expressions were folded in Sem_Eval).
4078
4079          Set_Is_Static_Expression (N, False);
4080          return;
4081       end if;
4082
4083       <<Skip_Optimization>>
4084
4085       --  If the type is limited or unconstrained, we expand as follows to
4086       --  avoid any possibility of improper copies.
4087
4088       --  Note: it may be possible to avoid this special processing if the
4089       --  back end uses its own mechanisms for handling by-reference types ???
4090
4091       --      type Ptr is access all Typ;
4092       --      Cnn : Ptr;
4093       --      if cond then
4094       --         <<then actions>>
4095       --         Cnn := then-expr'Unrestricted_Access;
4096       --      else
4097       --         <<else actions>>
4098       --         Cnn := else-expr'Unrestricted_Access;
4099       --      end if;
4100
4101       --  and replace the conditional expresion by a reference to Cnn.all.
4102
4103       --  This special case can be skipped if the back end handles limited
4104       --  types properly and ensures that no incorrect copies are made.
4105
4106       if Is_By_Reference_Type (Typ)
4107         and then not Back_End_Handles_Limited_Types
4108       then
4109          Cnn := Make_Temporary (Loc, 'C', N);
4110
4111          P_Decl :=
4112            Make_Full_Type_Declaration (Loc,
4113              Defining_Identifier => Make_Temporary (Loc, 'A'),
4114              Type_Definition =>
4115                Make_Access_To_Object_Definition (Loc,
4116                  All_Present => True,
4117                  Subtype_Indication =>
4118                    New_Reference_To (Typ, Loc)));
4119
4120          Insert_Action (N, P_Decl);
4121
4122          Decl :=
4123             Make_Object_Declaration (Loc,
4124               Defining_Identifier => Cnn,
4125               Object_Definition   =>
4126                    New_Occurrence_Of (Defining_Identifier (P_Decl), Loc));
4127
4128          New_If :=
4129            Make_Implicit_If_Statement (N,
4130              Condition => Relocate_Node (Cond),
4131
4132              Then_Statements => New_List (
4133                Make_Assignment_Statement (Sloc (Thenx),
4134                  Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
4135                  Expression =>
4136                    Make_Attribute_Reference (Loc,
4137                      Attribute_Name => Name_Unrestricted_Access,
4138                      Prefix =>  Relocate_Node (Thenx)))),
4139
4140              Else_Statements => New_List (
4141                Make_Assignment_Statement (Sloc (Elsex),
4142                  Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
4143                  Expression =>
4144                    Make_Attribute_Reference (Loc,
4145                      Attribute_Name => Name_Unrestricted_Access,
4146                      Prefix => Relocate_Node (Elsex)))));
4147
4148          New_N :=
4149            Make_Explicit_Dereference (Loc,
4150              Prefix => New_Occurrence_Of (Cnn, Loc));
4151
4152       --  For other types, we only need to expand if there are other actions
4153       --  associated with either branch.
4154
4155       elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
4156
4157          --  We have two approaches to handling this. If we are allowed to use
4158          --  N_Expression_With_Actions, then we can just wrap the actions into
4159          --  the appropriate expression.
4160
4161          if Use_Expression_With_Actions then
4162             if Present (Then_Actions (N)) then
4163                Rewrite (Thenx,
4164                  Make_Expression_With_Actions (Sloc (Thenx),
4165                    Actions    => Then_Actions (N),
4166                    Expression => Relocate_Node (Thenx)));
4167                Set_Then_Actions (N, No_List);
4168                Analyze_And_Resolve (Thenx, Typ);
4169             end if;
4170
4171             if Present (Else_Actions (N)) then
4172                Rewrite (Elsex,
4173                  Make_Expression_With_Actions (Sloc (Elsex),
4174                    Actions    => Else_Actions (N),
4175                    Expression => Relocate_Node (Elsex)));
4176                Set_Else_Actions (N, No_List);
4177                Analyze_And_Resolve (Elsex, Typ);
4178             end if;
4179
4180             return;
4181
4182             --  if we can't use N_Expression_With_Actions nodes, then we insert
4183             --  the following sequence of actions (using Insert_Actions):
4184
4185             --      Cnn : typ;
4186             --      if cond then
4187             --         <<then actions>>
4188             --         Cnn := then-expr;
4189             --      else
4190             --         <<else actions>>
4191             --         Cnn := else-expr
4192             --      end if;
4193
4194             --  and replace the conditional expression by a reference to Cnn
4195
4196          else
4197             Cnn := Make_Temporary (Loc, 'C', N);
4198
4199             Decl :=
4200               Make_Object_Declaration (Loc,
4201                 Defining_Identifier => Cnn,
4202                 Object_Definition   => New_Occurrence_Of (Typ, Loc));
4203
4204             New_If :=
4205               Make_Implicit_If_Statement (N,
4206                 Condition       => Relocate_Node (Cond),
4207
4208                 Then_Statements => New_List (
4209                   Make_Assignment_Statement (Sloc (Thenx),
4210                     Name       => New_Occurrence_Of (Cnn, Sloc (Thenx)),
4211                     Expression => Relocate_Node (Thenx))),
4212
4213                 Else_Statements => New_List (
4214                   Make_Assignment_Statement (Sloc (Elsex),
4215                     Name       => New_Occurrence_Of (Cnn, Sloc (Elsex)),
4216                     Expression => Relocate_Node (Elsex))));
4217
4218             Set_Assignment_OK (Name (First (Then_Statements (New_If))));
4219             Set_Assignment_OK (Name (First (Else_Statements (New_If))));
4220
4221             New_N := New_Occurrence_Of (Cnn, Loc);
4222          end if;
4223
4224          --  If no actions then no expansion needed, gigi will handle it using
4225          --  the same approach as a C conditional expression.
4226
4227       else
4228          return;
4229       end if;
4230
4231       --  Fall through here for either the limited expansion, or the case of
4232       --  inserting actions for non-limited types. In both these cases, we must
4233       --  move the SLOC of the parent If statement to the newly created one and
4234       --  change it to the SLOC of the expression which, after expansion, will
4235       --  correspond to what is being evaluated.
4236
4237       if Present (Parent (N))
4238         and then Nkind (Parent (N)) = N_If_Statement
4239       then
4240          Set_Sloc (New_If, Sloc (Parent (N)));
4241          Set_Sloc (Parent (N), Loc);
4242       end if;
4243
4244       --  Make sure Then_Actions and Else_Actions are appropriately moved
4245       --  to the new if statement.
4246
4247       if Present (Then_Actions (N)) then
4248          Insert_List_Before
4249            (First (Then_Statements (New_If)), Then_Actions (N));
4250       end if;
4251
4252       if Present (Else_Actions (N)) then
4253          Insert_List_Before
4254            (First (Else_Statements (New_If)), Else_Actions (N));
4255       end if;
4256
4257       Insert_Action (N, Decl);
4258       Insert_Action (N, New_If);
4259       Rewrite (N, New_N);
4260       Analyze_And_Resolve (N, Typ);
4261    end Expand_N_Conditional_Expression;
4262
4263    -----------------------------------
4264    -- Expand_N_Explicit_Dereference --
4265    -----------------------------------
4266
4267    procedure Expand_N_Explicit_Dereference (N : Node_Id) is
4268    begin
4269       --  Insert explicit dereference call for the checked storage pool case
4270
4271       Insert_Dereference_Action (Prefix (N));
4272    end Expand_N_Explicit_Dereference;
4273
4274    -----------------
4275    -- Expand_N_In --
4276    -----------------
4277
4278    procedure Expand_N_In (N : Node_Id) is
4279       Loc    : constant Source_Ptr := Sloc (N);
4280       Rtyp   : constant Entity_Id  := Etype (N);
4281       Lop    : constant Node_Id    := Left_Opnd (N);
4282       Rop    : constant Node_Id    := Right_Opnd (N);
4283       Static : constant Boolean    := Is_OK_Static_Expression (N);
4284
4285       procedure Expand_Set_Membership;
4286       --  For each disjunct we create a simple equality or membership test.
4287       --  The whole membership is rewritten as a short-circuit disjunction.
4288
4289       ---------------------------
4290       -- Expand_Set_Membership --
4291       ---------------------------
4292
4293       procedure Expand_Set_Membership is
4294          Alt  : Node_Id;
4295          Res  : Node_Id;
4296
4297          function Make_Cond (Alt : Node_Id) return Node_Id;
4298          --  If the alternative is a subtype mark, create a simple membership
4299          --  test. Otherwise create an equality test for it.
4300
4301          ---------------
4302          -- Make_Cond --
4303          ---------------
4304
4305          function Make_Cond (Alt : Node_Id) return Node_Id is
4306             Cond : Node_Id;
4307             L    : constant Node_Id := New_Copy (Lop);
4308             R    : constant Node_Id := Relocate_Node (Alt);
4309
4310          begin
4311             if Is_Entity_Name (Alt)
4312               and then Is_Type (Entity (Alt))
4313             then
4314                Cond :=
4315                  Make_In (Sloc (Alt),
4316                    Left_Opnd  => L,
4317                    Right_Opnd => R);
4318             else
4319                Cond := Make_Op_Eq (Sloc (Alt),
4320                  Left_Opnd  => L,
4321                  Right_Opnd => R);
4322             end if;
4323
4324             return Cond;
4325          end Make_Cond;
4326
4327       --  Start of proessing for Expand_N_In
4328
4329       begin
4330          Alt := Last (Alternatives (N));
4331          Res := Make_Cond (Alt);
4332
4333          Prev (Alt);
4334          while Present (Alt) loop
4335             Res :=
4336               Make_Or_Else (Sloc (Alt),
4337                 Left_Opnd  => Make_Cond (Alt),
4338                 Right_Opnd => Res);
4339             Prev (Alt);
4340          end loop;
4341
4342          Rewrite (N, Res);
4343          Analyze_And_Resolve (N, Standard_Boolean);
4344       end Expand_Set_Membership;
4345
4346       procedure Substitute_Valid_Check;
4347       --  Replaces node N by Lop'Valid. This is done when we have an explicit
4348       --  test for the left operand being in range of its subtype.
4349
4350       ----------------------------
4351       -- Substitute_Valid_Check --
4352       ----------------------------
4353
4354       procedure Substitute_Valid_Check is
4355       begin
4356          Rewrite (N,
4357            Make_Attribute_Reference (Loc,
4358              Prefix         => Relocate_Node (Lop),
4359              Attribute_Name => Name_Valid));
4360
4361          Analyze_And_Resolve (N, Rtyp);
4362
4363          Error_Msg_N ("?explicit membership test may be optimized away", N);
4364          Error_Msg_N -- CODEFIX
4365            ("\?use ''Valid attribute instead", N);
4366          return;
4367       end Substitute_Valid_Check;
4368
4369    --  Start of processing for Expand_N_In
4370
4371    begin
4372
4373       if Present (Alternatives (N)) then
4374          Remove_Side_Effects (Lop);
4375          Expand_Set_Membership;
4376          return;
4377       end if;
4378
4379       --  Check case of explicit test for an expression in range of its
4380       --  subtype. This is suspicious usage and we replace it with a 'Valid
4381       --  test and give a warning.
4382
4383       if Is_Scalar_Type (Etype (Lop))
4384         and then Nkind (Rop) in N_Has_Entity
4385         and then Etype (Lop) = Entity (Rop)
4386         and then Comes_From_Source (N)
4387         and then VM_Target = No_VM
4388       then
4389          Substitute_Valid_Check;
4390          return;
4391       end if;
4392
4393       --  Do validity check on operands
4394
4395       if Validity_Checks_On and Validity_Check_Operands then
4396          Ensure_Valid (Left_Opnd (N));
4397          Validity_Check_Range (Right_Opnd (N));
4398       end if;
4399
4400       --  Case of explicit range
4401
4402       if Nkind (Rop) = N_Range then
4403          declare
4404             Lo : constant Node_Id := Low_Bound (Rop);
4405             Hi : constant Node_Id := High_Bound (Rop);
4406
4407             Ltyp : constant Entity_Id := Etype (Lop);
4408
4409             Lo_Orig : constant Node_Id := Original_Node (Lo);
4410             Hi_Orig : constant Node_Id := Original_Node (Hi);
4411
4412             Lcheck : Compare_Result;
4413             Ucheck : Compare_Result;
4414
4415             Warn1 : constant Boolean :=
4416                       Constant_Condition_Warnings
4417                         and then Comes_From_Source (N)
4418                         and then not In_Instance;
4419             --  This must be true for any of the optimization warnings, we
4420             --  clearly want to give them only for source with the flag on.
4421             --  We also skip these warnings in an instance since it may be
4422             --  the case that different instantiations have different ranges.
4423
4424             Warn2 : constant Boolean :=
4425                       Warn1
4426                         and then Nkind (Original_Node (Rop)) = N_Range
4427                         and then Is_Integer_Type (Etype (Lo));
4428             --  For the case where only one bound warning is elided, we also
4429             --  insist on an explicit range and an integer type. The reason is
4430             --  that the use of enumeration ranges including an end point is
4431             --  common, as is the use of a subtype name, one of whose bounds
4432             --  is the same as the type of the expression.
4433
4434          begin
4435             --  If test is explicit x'first .. x'last, replace by valid check
4436
4437             if Is_Scalar_Type (Ltyp)
4438               and then Nkind (Lo_Orig) = N_Attribute_Reference
4439               and then Attribute_Name (Lo_Orig) = Name_First
4440               and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
4441               and then Entity (Prefix (Lo_Orig)) = Ltyp
4442               and then Nkind (Hi_Orig) = N_Attribute_Reference
4443               and then Attribute_Name (Hi_Orig) = Name_Last
4444               and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
4445               and then Entity (Prefix (Hi_Orig)) = Ltyp
4446               and then Comes_From_Source (N)
4447               and then VM_Target = No_VM
4448             then
4449                Substitute_Valid_Check;
4450                return;
4451             end if;
4452
4453             --  If bounds of type are known at compile time, and the end points
4454             --  are known at compile time and identical, this is another case
4455             --  for substituting a valid test. We only do this for discrete
4456             --  types, since it won't arise in practice for float types.
4457
4458             if Comes_From_Source (N)
4459               and then Is_Discrete_Type (Ltyp)
4460               and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
4461               and then Compile_Time_Known_Value (Type_Low_Bound  (Ltyp))
4462               and then Compile_Time_Known_Value (Lo)
4463               and then Compile_Time_Known_Value (Hi)
4464               and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
4465               and then Expr_Value (Type_Low_Bound  (Ltyp)) = Expr_Value (Lo)
4466
4467                --  Kill warnings in instances, since they may be cases where we
4468                --  have a test in the generic that makes sense with some types
4469                --  and not with other types.
4470
4471               and then not In_Instance
4472             then
4473                Substitute_Valid_Check;
4474                return;
4475             end if;
4476
4477             --  If we have an explicit range, do a bit of optimization based
4478             --  on range analysis (we may be able to kill one or both checks).
4479
4480             Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
4481             Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
4482
4483             --  If either check is known to fail, replace result by False since
4484             --  the other check does not matter. Preserve the static flag for
4485             --  legality checks, because we are constant-folding beyond RM 4.9.
4486
4487             if Lcheck = LT or else Ucheck = GT then
4488                if Warn1 then
4489                   Error_Msg_N ("?range test optimized away", N);
4490                   Error_Msg_N ("\?value is known to be out of range", N);
4491                end if;
4492
4493                Rewrite (N,
4494                  New_Reference_To (Standard_False, Loc));
4495                Analyze_And_Resolve (N, Rtyp);
4496                Set_Is_Static_Expression (N, Static);
4497
4498                return;
4499
4500             --  If both checks are known to succeed, replace result by True,
4501             --  since we know we are in range.
4502
4503             elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
4504                if Warn1 then
4505                   Error_Msg_N ("?range test optimized away", N);
4506                   Error_Msg_N ("\?value is known to be in range", N);
4507                end if;
4508
4509                Rewrite (N,
4510                  New_Reference_To (Standard_True, Loc));
4511                Analyze_And_Resolve (N, Rtyp);
4512                Set_Is_Static_Expression (N, Static);
4513
4514                return;
4515
4516             --  If lower bound check succeeds and upper bound check is not
4517             --  known to succeed or fail, then replace the range check with
4518             --  a comparison against the upper bound.
4519
4520             elsif Lcheck in Compare_GE then
4521                if Warn2 and then not In_Instance then
4522                   Error_Msg_N ("?lower bound test optimized away", Lo);
4523                   Error_Msg_N ("\?value is known to be in range", Lo);
4524                end if;
4525
4526                Rewrite (N,
4527                  Make_Op_Le (Loc,
4528                    Left_Opnd  => Lop,
4529                    Right_Opnd => High_Bound (Rop)));
4530                Analyze_And_Resolve (N, Rtyp);
4531
4532                return;
4533
4534             --  If upper bound check succeeds and lower bound check is not
4535             --  known to succeed or fail, then replace the range check with
4536             --  a comparison against the lower bound.
4537
4538             elsif Ucheck in Compare_LE then
4539                if Warn2 and then not In_Instance then
4540                   Error_Msg_N ("?upper bound test optimized away", Hi);
4541                   Error_Msg_N ("\?value is known to be in range", Hi);
4542                end if;
4543
4544                Rewrite (N,
4545                  Make_Op_Ge (Loc,
4546                    Left_Opnd  => Lop,
4547                    Right_Opnd => Low_Bound (Rop)));
4548                Analyze_And_Resolve (N, Rtyp);
4549
4550                return;
4551             end if;
4552
4553             --  We couldn't optimize away the range check, but there is one
4554             --  more issue. If we are checking constant conditionals, then we
4555             --  see if we can determine the outcome assuming everything is
4556             --  valid, and if so give an appropriate warning.
4557
4558             if Warn1 and then not Assume_No_Invalid_Values then
4559                Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
4560                Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
4561
4562                --  Result is out of range for valid value
4563
4564                if Lcheck = LT or else Ucheck = GT then
4565                   Error_Msg_N
4566                     ("?value can only be in range if it is invalid", N);
4567
4568                --  Result is in range for valid value
4569
4570                elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
4571                   Error_Msg_N
4572                     ("?value can only be out of range if it is invalid", N);
4573
4574                --  Lower bound check succeeds if value is valid
4575
4576                elsif Warn2 and then Lcheck in Compare_GE then
4577                   Error_Msg_N
4578                     ("?lower bound check only fails if it is invalid", Lo);
4579
4580                --  Upper bound  check succeeds if value is valid
4581
4582                elsif Warn2 and then Ucheck in Compare_LE then
4583                   Error_Msg_N
4584                     ("?upper bound check only fails for invalid values", Hi);
4585                end if;
4586             end if;
4587          end;
4588
4589          --  For all other cases of an explicit range, nothing to be done
4590
4591          return;
4592
4593       --  Here right operand is a subtype mark
4594
4595       else
4596          declare
4597             Typ       : Entity_Id        := Etype (Rop);
4598             Is_Acc    : constant Boolean := Is_Access_Type (Typ);
4599             Cond      : Node_Id          := Empty;
4600             New_N     : Node_Id;
4601             Obj       : Node_Id          := Lop;
4602             SCIL_Node : Node_Id;
4603
4604          begin
4605             Remove_Side_Effects (Obj);
4606
4607             --  For tagged type, do tagged membership operation
4608
4609             if Is_Tagged_Type (Typ) then
4610
4611                --  No expansion will be performed when VM_Target, as the VM
4612                --  back-ends will handle the membership tests directly (tags
4613                --  are not explicitly represented in Java objects, so the
4614                --  normal tagged membership expansion is not what we want).
4615
4616                if Tagged_Type_Expansion then
4617                   Tagged_Membership (N, SCIL_Node, New_N);
4618                   Rewrite (N, New_N);
4619                   Analyze_And_Resolve (N, Rtyp);
4620
4621                   --  Update decoration of relocated node referenced by the
4622                   --  SCIL node.
4623
4624                   if Generate_SCIL
4625                     and then Present (SCIL_Node)
4626                   then
4627                      Set_SCIL_Related_Node (SCIL_Node, N);
4628                      Insert_Action (N, SCIL_Node);
4629                   end if;
4630                end if;
4631
4632                return;
4633
4634             --  If type is scalar type, rewrite as x in t'first .. t'last.
4635             --  This reason we do this is that the bounds may have the wrong
4636             --  type if they come from the original type definition. Also this
4637             --  way we get all the processing above for an explicit range.
4638
4639             elsif Is_Scalar_Type (Typ) then
4640                Rewrite (Rop,
4641                  Make_Range (Loc,
4642                    Low_Bound =>
4643                      Make_Attribute_Reference (Loc,
4644                        Attribute_Name => Name_First,
4645                        Prefix => New_Reference_To (Typ, Loc)),
4646
4647                    High_Bound =>
4648                      Make_Attribute_Reference (Loc,
4649                        Attribute_Name => Name_Last,
4650                        Prefix => New_Reference_To (Typ, Loc))));
4651                Analyze_And_Resolve (N, Rtyp);
4652                return;
4653
4654             --  Ada 2005 (AI-216): Program_Error is raised when evaluating
4655             --  a membership test if the subtype mark denotes a constrained
4656             --  Unchecked_Union subtype and the expression lacks inferable
4657             --  discriminants.
4658
4659             elsif Is_Unchecked_Union (Base_Type (Typ))
4660               and then Is_Constrained (Typ)
4661               and then not Has_Inferable_Discriminants (Lop)
4662             then
4663                Insert_Action (N,
4664                  Make_Raise_Program_Error (Loc,
4665                    Reason => PE_Unchecked_Union_Restriction));
4666
4667                --  Prevent Gigi from generating incorrect code by rewriting
4668                --  the test as a standard False.
4669
4670                Rewrite (N,
4671                  New_Occurrence_Of (Standard_False, Loc));
4672
4673                return;
4674             end if;
4675
4676             --  Here we have a non-scalar type
4677
4678             if Is_Acc then
4679                Typ := Designated_Type (Typ);
4680             end if;
4681
4682             if not Is_Constrained (Typ) then
4683                Rewrite (N,
4684                  New_Reference_To (Standard_True, Loc));
4685                Analyze_And_Resolve (N, Rtyp);
4686
4687             --  For the constrained array case, we have to check the subscripts
4688             --  for an exact match if the lengths are non-zero (the lengths
4689             --  must match in any case).
4690
4691             elsif Is_Array_Type (Typ) then
4692
4693                Check_Subscripts : declare
4694                   function Construct_Attribute_Reference
4695                     (E   : Node_Id;
4696                      Nam : Name_Id;
4697                      Dim : Nat) return Node_Id;
4698                   --  Build attribute reference E'Nam(Dim)
4699
4700                   -----------------------------------
4701                   -- Construct_Attribute_Reference --
4702                   -----------------------------------
4703
4704                   function Construct_Attribute_Reference
4705                     (E   : Node_Id;
4706                      Nam : Name_Id;
4707                      Dim : Nat) return Node_Id
4708                   is
4709                   begin
4710                      return
4711                        Make_Attribute_Reference (Loc,
4712                          Prefix => E,
4713                          Attribute_Name => Nam,
4714                          Expressions => New_List (
4715                            Make_Integer_Literal (Loc, Dim)));
4716                   end Construct_Attribute_Reference;
4717
4718                --  Start of processing for Check_Subscripts
4719
4720                begin
4721                   for J in 1 .. Number_Dimensions (Typ) loop
4722                      Evolve_And_Then (Cond,
4723                        Make_Op_Eq (Loc,
4724                          Left_Opnd  =>
4725                            Construct_Attribute_Reference
4726                              (Duplicate_Subexpr_No_Checks (Obj),
4727                               Name_First, J),
4728                          Right_Opnd =>
4729                            Construct_Attribute_Reference
4730                              (New_Occurrence_Of (Typ, Loc), Name_First, J)));
4731
4732                      Evolve_And_Then (Cond,
4733                        Make_Op_Eq (Loc,
4734                          Left_Opnd  =>
4735                            Construct_Attribute_Reference
4736                              (Duplicate_Subexpr_No_Checks (Obj),
4737                               Name_Last, J),
4738                          Right_Opnd =>
4739                            Construct_Attribute_Reference
4740                              (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
4741                   end loop;
4742
4743                   if Is_Acc then
4744                      Cond :=
4745                        Make_Or_Else (Loc,
4746                          Left_Opnd =>
4747                            Make_Op_Eq (Loc,
4748                              Left_Opnd  => Obj,
4749                              Right_Opnd => Make_Null (Loc)),
4750                          Right_Opnd => Cond);
4751                   end if;
4752
4753                   Rewrite (N, Cond);
4754                   Analyze_And_Resolve (N, Rtyp);
4755                end Check_Subscripts;
4756
4757             --  These are the cases where constraint checks may be required,
4758             --  e.g. records with possible discriminants
4759
4760             else
4761                --  Expand the test into a series of discriminant comparisons.
4762                --  The expression that is built is the negation of the one that
4763                --  is used for checking discriminant constraints.
4764
4765                Obj := Relocate_Node (Left_Opnd (N));
4766
4767                if Has_Discriminants (Typ) then
4768                   Cond := Make_Op_Not (Loc,
4769                     Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
4770
4771                   if Is_Acc then
4772                      Cond := Make_Or_Else (Loc,
4773                        Left_Opnd =>
4774                          Make_Op_Eq (Loc,
4775                            Left_Opnd  => Obj,
4776                            Right_Opnd => Make_Null (Loc)),
4777                        Right_Opnd => Cond);
4778                   end if;
4779
4780                else
4781                   Cond := New_Occurrence_Of (Standard_True, Loc);
4782                end if;
4783
4784                Rewrite (N, Cond);
4785                Analyze_And_Resolve (N, Rtyp);
4786             end if;
4787          end;
4788       end if;
4789    end Expand_N_In;
4790
4791    --------------------------------
4792    -- Expand_N_Indexed_Component --
4793    --------------------------------
4794
4795    procedure Expand_N_Indexed_Component (N : Node_Id) is
4796       Loc : constant Source_Ptr := Sloc (N);
4797       Typ : constant Entity_Id  := Etype (N);
4798       P   : constant Node_Id    := Prefix (N);
4799       T   : constant Entity_Id  := Etype (P);
4800
4801    begin
4802       --  A special optimization, if we have an indexed component that is
4803       --  selecting from a slice, then we can eliminate the slice, since, for
4804       --  example, x (i .. j)(k) is identical to x(k). The only difference is
4805       --  the range check required by the slice. The range check for the slice
4806       --  itself has already been generated. The range check for the
4807       --  subscripting operation is ensured by converting the subject to
4808       --  the subtype of the slice.
4809
4810       --  This optimization not only generates better code, avoiding slice
4811       --  messing especially in the packed case, but more importantly bypasses
4812       --  some problems in handling this peculiar case, for example, the issue
4813       --  of dealing specially with object renamings.
4814
4815       if Nkind (P) = N_Slice then
4816          Rewrite (N,
4817            Make_Indexed_Component (Loc,
4818              Prefix => Prefix (P),
4819              Expressions => New_List (
4820                Convert_To
4821                  (Etype (First_Index (Etype (P))),
4822                   First (Expressions (N))))));
4823          Analyze_And_Resolve (N, Typ);
4824          return;
4825       end if;
4826
4827       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
4828       --  function, then additional actuals must be passed.
4829
4830       if Ada_Version >= Ada_05
4831         and then Is_Build_In_Place_Function_Call (P)
4832       then
4833          Make_Build_In_Place_Call_In_Anonymous_Context (P);
4834       end if;
4835
4836       --  If the prefix is an access type, then we unconditionally rewrite if
4837       --  as an explicit dereference. This simplifies processing for several
4838       --  cases, including packed array cases and certain cases in which checks
4839       --  must be generated. We used to try to do this only when it was
4840       --  necessary, but it cleans up the code to do it all the time.
4841
4842       if Is_Access_Type (T) then
4843          Insert_Explicit_Dereference (P);
4844          Analyze_And_Resolve (P, Designated_Type (T));
4845       end if;
4846
4847       --  Generate index and validity checks
4848
4849       Generate_Index_Checks (N);
4850
4851       if Validity_Checks_On and then Validity_Check_Subscripts then
4852          Apply_Subscript_Validity_Checks (N);
4853       end if;
4854
4855       --  All done for the non-packed case
4856
4857       if not Is_Packed (Etype (Prefix (N))) then
4858          return;
4859       end if;
4860
4861       --  For packed arrays that are not bit-packed (i.e. the case of an array
4862       --  with one or more index types with a non-contiguous enumeration type),
4863       --  we can always use the normal packed element get circuit.
4864
4865       if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
4866          Expand_Packed_Element_Reference (N);
4867          return;
4868       end if;
4869
4870       --  For a reference to a component of a bit packed array, we have to
4871       --  convert it to a reference to the corresponding Packed_Array_Type.
4872       --  We only want to do this for simple references, and not for:
4873
4874       --    Left side of assignment, or prefix of left side of assignment, or
4875       --    prefix of the prefix, to handle packed arrays of packed arrays,
4876       --      This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
4877
4878       --    Renaming objects in renaming associations
4879       --      This case is handled when a use of the renamed variable occurs
4880
4881       --    Actual parameters for a procedure call
4882       --      This case is handled in Exp_Ch6.Expand_Actuals
4883
4884       --    The second expression in a 'Read attribute reference
4885
4886       --    The prefix of an address or bit or size attribute reference
4887
4888       --  The following circuit detects these exceptions
4889
4890       declare
4891          Child : Node_Id := N;
4892          Parnt : Node_Id := Parent (N);
4893
4894       begin
4895          loop
4896             if Nkind (Parnt) = N_Unchecked_Expression then
4897                null;
4898
4899             elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
4900                                    N_Procedure_Call_Statement)
4901               or else (Nkind (Parnt) = N_Parameter_Association
4902                         and then
4903                           Nkind (Parent (Parnt)) =  N_Procedure_Call_Statement)
4904             then
4905                return;
4906
4907             elsif Nkind (Parnt) = N_Attribute_Reference
4908               and then (Attribute_Name (Parnt) = Name_Address
4909                          or else
4910                         Attribute_Name (Parnt) = Name_Bit
4911                          or else
4912                         Attribute_Name (Parnt) = Name_Size)
4913               and then Prefix (Parnt) = Child
4914             then
4915                return;
4916
4917             elsif Nkind (Parnt) = N_Assignment_Statement
4918               and then Name (Parnt) = Child
4919             then
4920                return;
4921
4922             --  If the expression is an index of an indexed component, it must
4923             --  be expanded regardless of context.
4924
4925             elsif Nkind (Parnt) = N_Indexed_Component
4926               and then Child /= Prefix (Parnt)
4927             then
4928                Expand_Packed_Element_Reference (N);
4929                return;
4930
4931             elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
4932               and then Name (Parent (Parnt)) = Parnt
4933             then
4934                return;
4935
4936             elsif Nkind (Parnt) = N_Attribute_Reference
4937               and then Attribute_Name (Parnt) = Name_Read
4938               and then Next (First (Expressions (Parnt))) = Child
4939             then
4940                return;
4941
4942             elsif Nkind_In (Parnt, N_Indexed_Component, N_Selected_Component)
4943                and then Prefix (Parnt) = Child
4944             then
4945                null;
4946
4947             else
4948                Expand_Packed_Element_Reference (N);
4949                return;
4950             end if;
4951
4952             --  Keep looking up tree for unchecked expression, or if we are the
4953             --  prefix of a possible assignment left side.
4954
4955             Child := Parnt;
4956             Parnt := Parent (Child);
4957          end loop;
4958       end;
4959    end Expand_N_Indexed_Component;
4960
4961    ---------------------
4962    -- Expand_N_Not_In --
4963    ---------------------
4964
4965    --  Replace a not in b by not (a in b) so that the expansions for (a in b)
4966    --  can be done. This avoids needing to duplicate this expansion code.
4967
4968    procedure Expand_N_Not_In (N : Node_Id) is
4969       Loc : constant Source_Ptr := Sloc (N);
4970       Typ : constant Entity_Id  := Etype (N);
4971       Cfs : constant Boolean    := Comes_From_Source (N);
4972
4973    begin
4974       Rewrite (N,
4975         Make_Op_Not (Loc,
4976           Right_Opnd =>
4977             Make_In (Loc,
4978               Left_Opnd  => Left_Opnd (N),
4979               Right_Opnd => Right_Opnd (N))));
4980
4981       --  If this is a set membership, preserve list of alternatives
4982
4983       Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
4984
4985       --  We want this to appear as coming from source if original does (see
4986       --  transformations in Expand_N_In).
4987
4988       Set_Comes_From_Source (N, Cfs);
4989       Set_Comes_From_Source (Right_Opnd (N), Cfs);
4990
4991       --  Now analyze transformed node
4992
4993       Analyze_And_Resolve (N, Typ);
4994    end Expand_N_Not_In;
4995
4996    -------------------
4997    -- Expand_N_Null --
4998    -------------------
4999
5000    --  The only replacement required is for the case of a null of type that is
5001    --  an access to protected subprogram. We represent such access values as a
5002    --  record, and so we must replace the occurrence of null by the equivalent
5003    --  record (with a null address and a null pointer in it), so that the
5004    --  backend creates the proper value.
5005
5006    procedure Expand_N_Null (N : Node_Id) is
5007       Loc : constant Source_Ptr := Sloc (N);
5008       Typ : constant Entity_Id  := Etype (N);
5009       Agg : Node_Id;
5010
5011    begin
5012       if Is_Access_Protected_Subprogram_Type (Typ) then
5013          Agg :=
5014            Make_Aggregate (Loc,
5015              Expressions => New_List (
5016                New_Occurrence_Of (RTE (RE_Null_Address), Loc),
5017                Make_Null (Loc)));
5018
5019          Rewrite (N, Agg);
5020          Analyze_And_Resolve (N, Equivalent_Type (Typ));
5021
5022          --  For subsequent semantic analysis, the node must retain its type.
5023          --  Gigi in any case replaces this type by the corresponding record
5024          --  type before processing the node.
5025
5026          Set_Etype (N, Typ);
5027       end if;
5028
5029    exception
5030       when RE_Not_Available =>
5031          return;
5032    end Expand_N_Null;
5033
5034    ---------------------
5035    -- Expand_N_Op_Abs --
5036    ---------------------
5037
5038    procedure Expand_N_Op_Abs (N : Node_Id) is
5039       Loc  : constant Source_Ptr := Sloc (N);
5040       Expr : constant Node_Id := Right_Opnd (N);
5041
5042    begin
5043       Unary_Op_Validity_Checks (N);
5044
5045       --  Deal with software overflow checking
5046
5047       if not Backend_Overflow_Checks_On_Target
5048          and then Is_Signed_Integer_Type (Etype (N))
5049          and then Do_Overflow_Check (N)
5050       then
5051          --  The only case to worry about is when the argument is equal to the
5052          --  largest negative number, so what we do is to insert the check:
5053
5054          --     [constraint_error when Expr = typ'Base'First]
5055
5056          --  with the usual Duplicate_Subexpr use coding for expr
5057
5058          Insert_Action (N,
5059            Make_Raise_Constraint_Error (Loc,
5060              Condition =>
5061                Make_Op_Eq (Loc,
5062                  Left_Opnd  => Duplicate_Subexpr (Expr),
5063                  Right_Opnd =>
5064                    Make_Attribute_Reference (Loc,
5065                      Prefix =>
5066                        New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
5067                      Attribute_Name => Name_First)),
5068              Reason => CE_Overflow_Check_Failed));
5069       end if;
5070
5071       --  Vax floating-point types case
5072
5073       if Vax_Float (Etype (N)) then
5074          Expand_Vax_Arith (N);
5075       end if;
5076    end Expand_N_Op_Abs;
5077
5078    ---------------------
5079    -- Expand_N_Op_Add --
5080    ---------------------
5081
5082    procedure Expand_N_Op_Add (N : Node_Id) is
5083       Typ : constant Entity_Id := Etype (N);
5084
5085    begin
5086       Binary_Op_Validity_Checks (N);
5087
5088       --  N + 0 = 0 + N = N for integer types
5089
5090       if Is_Integer_Type (Typ) then
5091          if Compile_Time_Known_Value (Right_Opnd (N))
5092            and then Expr_Value (Right_Opnd (N)) = Uint_0
5093          then
5094             Rewrite (N, Left_Opnd (N));
5095             return;
5096
5097          elsif Compile_Time_Known_Value (Left_Opnd (N))
5098            and then Expr_Value (Left_Opnd (N)) = Uint_0
5099          then
5100             Rewrite (N, Right_Opnd (N));
5101             return;
5102          end if;
5103       end if;
5104
5105       --  Arithmetic overflow checks for signed integer/fixed point types
5106
5107       if Is_Signed_Integer_Type (Typ)
5108         or else Is_Fixed_Point_Type (Typ)
5109       then
5110          Apply_Arithmetic_Overflow_Check (N);
5111          return;
5112
5113       --  Vax floating-point types case
5114
5115       elsif Vax_Float (Typ) then
5116          Expand_Vax_Arith (N);
5117       end if;
5118    end Expand_N_Op_Add;
5119
5120    ---------------------
5121    -- Expand_N_Op_And --
5122    ---------------------
5123
5124    procedure Expand_N_Op_And (N : Node_Id) is
5125       Typ : constant Entity_Id := Etype (N);
5126
5127    begin
5128       Binary_Op_Validity_Checks (N);
5129
5130       if Is_Array_Type (Etype (N)) then
5131          Expand_Boolean_Operator (N);
5132
5133       elsif Is_Boolean_Type (Etype (N)) then
5134
5135          --  Replace AND by AND THEN if Short_Circuit_And_Or active and the
5136          --  type is standard Boolean (do not mess with AND that uses a non-
5137          --  standard Boolean type, because something strange is going on).
5138
5139          if Short_Circuit_And_Or and then Typ = Standard_Boolean then
5140             Rewrite (N,
5141               Make_And_Then (Sloc (N),
5142                 Left_Opnd  => Relocate_Node (Left_Opnd (N)),
5143                 Right_Opnd => Relocate_Node (Right_Opnd (N))));
5144             Analyze_And_Resolve (N, Typ);
5145
5146          --  Otherwise, adjust conditions
5147
5148          else
5149             Adjust_Condition (Left_Opnd (N));
5150             Adjust_Condition (Right_Opnd (N));
5151             Set_Etype (N, Standard_Boolean);
5152             Adjust_Result_Type (N, Typ);
5153          end if;
5154       end if;
5155    end Expand_N_Op_And;
5156
5157    ------------------------
5158    -- Expand_N_Op_Concat --
5159    ------------------------
5160
5161    procedure Expand_N_Op_Concat (N : Node_Id) is
5162       Opnds : List_Id;
5163       --  List of operands to be concatenated
5164
5165       Cnode : Node_Id;
5166       --  Node which is to be replaced by the result of concatenating the nodes
5167       --  in the list Opnds.
5168
5169    begin
5170       --  Ensure validity of both operands
5171
5172       Binary_Op_Validity_Checks (N);
5173
5174       --  If we are the left operand of a concatenation higher up the tree,
5175       --  then do nothing for now, since we want to deal with a series of
5176       --  concatenations as a unit.
5177
5178       if Nkind (Parent (N)) = N_Op_Concat
5179         and then N = Left_Opnd (Parent (N))
5180       then
5181          return;
5182       end if;
5183
5184       --  We get here with a concatenation whose left operand may be a
5185       --  concatenation itself with a consistent type. We need to process
5186       --  these concatenation operands from left to right, which means
5187       --  from the deepest node in the tree to the highest node.
5188
5189       Cnode := N;
5190       while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
5191          Cnode := Left_Opnd (Cnode);
5192       end loop;
5193
5194       --  Now Cnode is the deepest concatenation, and its parents are the
5195       --  concatenation nodes above, so now we process bottom up, doing the
5196       --  operations. We gather a string that is as long as possible up to five
5197       --  operands.
5198
5199       --  The outer loop runs more than once if more than one concatenation
5200       --  type is involved.
5201
5202       Outer : loop
5203          Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
5204          Set_Parent (Opnds, N);
5205
5206          --  The inner loop gathers concatenation operands
5207
5208          Inner : while Cnode /= N
5209                    and then Base_Type (Etype (Cnode)) =
5210                             Base_Type (Etype (Parent (Cnode)))
5211          loop
5212             Cnode := Parent (Cnode);
5213             Append (Right_Opnd (Cnode), Opnds);
5214          end loop Inner;
5215
5216          Expand_Concatenate (Cnode, Opnds);
5217
5218          exit Outer when Cnode = N;
5219          Cnode := Parent (Cnode);
5220       end loop Outer;
5221    end Expand_N_Op_Concat;
5222
5223    ------------------------
5224    -- Expand_N_Op_Divide --
5225    ------------------------
5226
5227    procedure Expand_N_Op_Divide (N : Node_Id) is
5228       Loc   : constant Source_Ptr := Sloc (N);
5229       Lopnd : constant Node_Id    := Left_Opnd (N);
5230       Ropnd : constant Node_Id    := Right_Opnd (N);
5231       Ltyp  : constant Entity_Id  := Etype (Lopnd);
5232       Rtyp  : constant Entity_Id  := Etype (Ropnd);
5233       Typ   : Entity_Id           := Etype (N);
5234       Rknow : constant Boolean    := Is_Integer_Type (Typ)
5235                                        and then
5236                                          Compile_Time_Known_Value (Ropnd);
5237       Rval  : Uint;
5238
5239    begin
5240       Binary_Op_Validity_Checks (N);
5241
5242       if Rknow then
5243          Rval := Expr_Value (Ropnd);
5244       end if;
5245
5246       --  N / 1 = N for integer types
5247
5248       if Rknow and then Rval = Uint_1 then
5249          Rewrite (N, Lopnd);
5250          return;
5251       end if;
5252
5253       --  Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
5254       --  Is_Power_Of_2_For_Shift is set means that we know that our left
5255       --  operand is an unsigned integer, as required for this to work.
5256
5257       if Nkind (Ropnd) = N_Op_Expon
5258         and then Is_Power_Of_2_For_Shift (Ropnd)
5259
5260       --  We cannot do this transformation in configurable run time mode if we
5261       --  have 64-bit integers and long shifts are not available.
5262
5263         and then
5264           (Esize (Ltyp) <= 32
5265              or else Support_Long_Shifts_On_Target)
5266       then
5267          Rewrite (N,
5268            Make_Op_Shift_Right (Loc,
5269              Left_Opnd  => Lopnd,
5270              Right_Opnd =>
5271                Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
5272          Analyze_And_Resolve (N, Typ);
5273          return;
5274       end if;
5275
5276       --  Do required fixup of universal fixed operation
5277
5278       if Typ = Universal_Fixed then
5279          Fixup_Universal_Fixed_Operation (N);
5280          Typ := Etype (N);
5281       end if;
5282
5283       --  Divisions with fixed-point results
5284
5285       if Is_Fixed_Point_Type (Typ) then
5286
5287          --  No special processing if Treat_Fixed_As_Integer is set, since
5288          --  from a semantic point of view such operations are simply integer
5289          --  operations and will be treated that way.
5290
5291          if not Treat_Fixed_As_Integer (N) then
5292             if Is_Integer_Type (Rtyp) then
5293                Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
5294             else
5295                Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
5296             end if;
5297          end if;
5298
5299       --  Other cases of division of fixed-point operands. Again we exclude the
5300       --  case where Treat_Fixed_As_Integer is set.
5301
5302       elsif (Is_Fixed_Point_Type (Ltyp) or else
5303              Is_Fixed_Point_Type (Rtyp))
5304         and then not Treat_Fixed_As_Integer (N)
5305       then
5306          if Is_Integer_Type (Typ) then
5307             Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
5308          else
5309             pragma Assert (Is_Floating_Point_Type (Typ));
5310             Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
5311          end if;
5312
5313       --  Mixed-mode operations can appear in a non-static universal context,
5314       --  in which case the integer argument must be converted explicitly.
5315
5316       elsif Typ = Universal_Real
5317         and then Is_Integer_Type (Rtyp)
5318       then
5319          Rewrite (Ropnd,
5320            Convert_To (Universal_Real, Relocate_Node (Ropnd)));
5321
5322          Analyze_And_Resolve (Ropnd, Universal_Real);
5323
5324       elsif Typ = Universal_Real
5325         and then Is_Integer_Type (Ltyp)
5326       then
5327          Rewrite (Lopnd,
5328            Convert_To (Universal_Real, Relocate_Node (Lopnd)));
5329
5330          Analyze_And_Resolve (Lopnd, Universal_Real);
5331
5332       --  Non-fixed point cases, do integer zero divide and overflow checks
5333
5334       elsif Is_Integer_Type (Typ) then
5335          Apply_Divide_Check (N);
5336
5337          --  Check for 64-bit division available, or long shifts if the divisor
5338          --  is a small power of 2 (since such divides will be converted into
5339          --  long shifts).
5340
5341          if Esize (Ltyp) > 32
5342            and then not Support_64_Bit_Divides_On_Target
5343            and then
5344              (not Rknow
5345                 or else not Support_Long_Shifts_On_Target
5346                 or else (Rval /= Uint_2  and then
5347                          Rval /= Uint_4  and then
5348                          Rval /= Uint_8  and then
5349                          Rval /= Uint_16 and then
5350                          Rval /= Uint_32 and then
5351                          Rval /= Uint_64))
5352          then
5353             Error_Msg_CRT ("64-bit division", N);
5354          end if;
5355
5356       --  Deal with Vax_Float
5357
5358       elsif Vax_Float (Typ) then
5359          Expand_Vax_Arith (N);
5360          return;
5361       end if;
5362    end Expand_N_Op_Divide;
5363
5364    --------------------
5365    -- Expand_N_Op_Eq --
5366    --------------------
5367
5368    procedure Expand_N_Op_Eq (N : Node_Id) is
5369       Loc    : constant Source_Ptr := Sloc (N);
5370       Typ    : constant Entity_Id  := Etype (N);
5371       Lhs    : constant Node_Id    := Left_Opnd (N);
5372       Rhs    : constant Node_Id    := Right_Opnd (N);
5373       Bodies : constant List_Id    := New_List;
5374       A_Typ  : constant Entity_Id  := Etype (Lhs);
5375
5376       Typl    : Entity_Id := A_Typ;
5377       Op_Name : Entity_Id;
5378       Prim    : Elmt_Id;
5379
5380       procedure Build_Equality_Call (Eq : Entity_Id);
5381       --  If a constructed equality exists for the type or for its parent,
5382       --  build and analyze call, adding conversions if the operation is
5383       --  inherited.
5384
5385       function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
5386       --  Determines whether a type has a subcomponent of an unconstrained
5387       --  Unchecked_Union subtype. Typ is a record type.
5388
5389       -------------------------
5390       -- Build_Equality_Call --
5391       -------------------------
5392
5393       procedure Build_Equality_Call (Eq : Entity_Id) is
5394          Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
5395          L_Exp   : Node_Id := Relocate_Node (Lhs);
5396          R_Exp   : Node_Id := Relocate_Node (Rhs);
5397
5398       begin
5399          if Base_Type (Op_Type) /= Base_Type (A_Typ)
5400            and then not Is_Class_Wide_Type (A_Typ)
5401          then
5402             L_Exp := OK_Convert_To (Op_Type, L_Exp);
5403             R_Exp := OK_Convert_To (Op_Type, R_Exp);
5404          end if;
5405
5406          --  If we have an Unchecked_Union, we need to add the inferred
5407          --  discriminant values as actuals in the function call. At this
5408          --  point, the expansion has determined that both operands have
5409          --  inferable discriminants.
5410
5411          if Is_Unchecked_Union (Op_Type) then
5412             declare
5413                Lhs_Type      : constant Node_Id := Etype (L_Exp);
5414                Rhs_Type      : constant Node_Id := Etype (R_Exp);
5415                Lhs_Discr_Val : Node_Id;
5416                Rhs_Discr_Val : Node_Id;
5417
5418             begin
5419                --  Per-object constrained selected components require special
5420                --  attention. If the enclosing scope of the component is an
5421                --  Unchecked_Union, we cannot reference its discriminants
5422                --  directly. This is why we use the two extra parameters of
5423                --  the equality function of the enclosing Unchecked_Union.
5424
5425                --  type UU_Type (Discr : Integer := 0) is
5426                --     . . .
5427                --  end record;
5428                --  pragma Unchecked_Union (UU_Type);
5429
5430                --  1. Unchecked_Union enclosing record:
5431
5432                --     type Enclosing_UU_Type (Discr : Integer := 0) is record
5433                --        . . .
5434                --        Comp : UU_Type (Discr);
5435                --        . . .
5436                --     end Enclosing_UU_Type;
5437                --     pragma Unchecked_Union (Enclosing_UU_Type);
5438
5439                --     Obj1 : Enclosing_UU_Type;
5440                --     Obj2 : Enclosing_UU_Type (1);
5441
5442                --     [. . .] Obj1 = Obj2 [. . .]
5443
5444                --     Generated code:
5445
5446                --     if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
5447
5448                --  A and B are the formal parameters of the equality function
5449                --  of Enclosing_UU_Type. The function always has two extra
5450                --  formals to capture the inferred discriminant values.
5451
5452                --  2. Non-Unchecked_Union enclosing record:
5453
5454                --     type
5455                --       Enclosing_Non_UU_Type (Discr : Integer := 0)
5456                --     is record
5457                --        . . .
5458                --        Comp : UU_Type (Discr);
5459                --        . . .
5460                --     end Enclosing_Non_UU_Type;
5461
5462                --     Obj1 : Enclosing_Non_UU_Type;
5463                --     Obj2 : Enclosing_Non_UU_Type (1);
5464
5465                --     ...  Obj1 = Obj2 ...
5466
5467                --     Generated code:
5468
5469                --     if not (uu_typeEQ (obj1.comp, obj2.comp,
5470                --                        obj1.discr, obj2.discr)) then
5471
5472                --  In this case we can directly reference the discriminants of
5473                --  the enclosing record.
5474
5475                --  Lhs of equality
5476
5477                if Nkind (Lhs) = N_Selected_Component
5478                  and then Has_Per_Object_Constraint
5479                             (Entity (Selector_Name (Lhs)))
5480                then
5481                   --  Enclosing record is an Unchecked_Union, use formal A
5482
5483                   if Is_Unchecked_Union (Scope
5484                        (Entity (Selector_Name (Lhs))))
5485                   then
5486                      Lhs_Discr_Val :=
5487                        Make_Identifier (Loc,
5488                          Chars => Name_A);
5489
5490                   --  Enclosing record is of a non-Unchecked_Union type, it is
5491                   --  possible to reference the discriminant.
5492
5493                   else
5494                      Lhs_Discr_Val :=
5495                        Make_Selected_Component (Loc,
5496                          Prefix => Prefix (Lhs),
5497                          Selector_Name =>
5498                            New_Copy
5499                              (Get_Discriminant_Value
5500                                 (First_Discriminant (Lhs_Type),
5501                                  Lhs_Type,
5502                                  Stored_Constraint (Lhs_Type))));
5503                   end if;
5504
5505                --  Comment needed here ???
5506
5507                else
5508                   --  Infer the discriminant value
5509
5510                   Lhs_Discr_Val :=
5511                     New_Copy
5512                       (Get_Discriminant_Value
5513                          (First_Discriminant (Lhs_Type),
5514                           Lhs_Type,
5515                           Stored_Constraint (Lhs_Type)));
5516                end if;
5517
5518                --  Rhs of equality
5519
5520                if Nkind (Rhs) = N_Selected_Component
5521                  and then Has_Per_Object_Constraint
5522                             (Entity (Selector_Name (Rhs)))
5523                then
5524                   if Is_Unchecked_Union
5525                        (Scope (Entity (Selector_Name (Rhs))))
5526                   then
5527                      Rhs_Discr_Val :=
5528                        Make_Identifier (Loc,
5529                          Chars => Name_B);
5530
5531                   else
5532                      Rhs_Discr_Val :=
5533                        Make_Selected_Component (Loc,
5534                          Prefix => Prefix (Rhs),
5535                          Selector_Name =>
5536                            New_Copy (Get_Discriminant_Value (
5537                              First_Discriminant (Rhs_Type),
5538                              Rhs_Type,
5539                              Stored_Constraint (Rhs_Type))));
5540
5541                   end if;
5542                else
5543                   Rhs_Discr_Val :=
5544                     New_Copy (Get_Discriminant_Value (
5545                       First_Discriminant (Rhs_Type),
5546                       Rhs_Type,
5547                       Stored_Constraint (Rhs_Type)));
5548
5549                end if;
5550
5551                Rewrite (N,
5552                  Make_Function_Call (Loc,
5553                    Name => New_Reference_To (Eq, Loc),
5554                    Parameter_Associations => New_List (
5555                      L_Exp,
5556                      R_Exp,
5557                      Lhs_Discr_Val,
5558                      Rhs_Discr_Val)));
5559             end;
5560
5561          --  Normal case, not an unchecked union
5562
5563          else
5564             Rewrite (N,
5565               Make_Function_Call (Loc,
5566                 Name => New_Reference_To (Eq, Loc),
5567                 Parameter_Associations => New_List (L_Exp, R_Exp)));
5568          end if;
5569
5570          Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
5571       end Build_Equality_Call;
5572
5573       ------------------------------------
5574       -- Has_Unconstrained_UU_Component --
5575       ------------------------------------
5576
5577       function Has_Unconstrained_UU_Component
5578         (Typ : Node_Id) return Boolean
5579       is
5580          Tdef  : constant Node_Id :=
5581                    Type_Definition (Declaration_Node (Base_Type (Typ)));
5582          Clist : Node_Id;
5583          Vpart : Node_Id;
5584
5585          function Component_Is_Unconstrained_UU
5586            (Comp : Node_Id) return Boolean;
5587          --  Determines whether the subtype of the component is an
5588          --  unconstrained Unchecked_Union.
5589
5590          function Variant_Is_Unconstrained_UU
5591            (Variant : Node_Id) return Boolean;
5592          --  Determines whether a component of the variant has an unconstrained
5593          --  Unchecked_Union subtype.
5594
5595          -----------------------------------
5596          -- Component_Is_Unconstrained_UU --
5597          -----------------------------------
5598
5599          function Component_Is_Unconstrained_UU
5600            (Comp : Node_Id) return Boolean
5601          is
5602          begin
5603             if Nkind (Comp) /= N_Component_Declaration then
5604                return False;
5605             end if;
5606
5607             declare
5608                Sindic : constant Node_Id :=
5609                           Subtype_Indication (Component_Definition (Comp));
5610
5611             begin
5612                --  Unconstrained nominal type. In the case of a constraint
5613                --  present, the node kind would have been N_Subtype_Indication.
5614
5615                if Nkind (Sindic) = N_Identifier then
5616                   return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
5617                end if;
5618
5619                return False;
5620             end;
5621          end Component_Is_Unconstrained_UU;
5622
5623          ---------------------------------
5624          -- Variant_Is_Unconstrained_UU --
5625          ---------------------------------
5626
5627          function Variant_Is_Unconstrained_UU
5628            (Variant : Node_Id) return Boolean
5629          is
5630             Clist : constant Node_Id := Component_List (Variant);
5631
5632          begin
5633             if Is_Empty_List (Component_Items (Clist)) then
5634                return False;
5635             end if;
5636
5637             --  We only need to test one component
5638
5639             declare
5640                Comp : Node_Id := First (Component_Items (Clist));
5641
5642             begin
5643                while Present (Comp) loop
5644                   if Component_Is_Unconstrained_UU (Comp) then
5645                      return True;
5646                   end if;
5647
5648                   Next (Comp);
5649                end loop;
5650             end;
5651
5652             --  None of the components withing the variant were of
5653             --  unconstrained Unchecked_Union type.
5654
5655             return False;
5656          end Variant_Is_Unconstrained_UU;
5657
5658       --  Start of processing for Has_Unconstrained_UU_Component
5659
5660       begin
5661          if Null_Present (Tdef) then
5662             return False;
5663          end if;
5664
5665          Clist := Component_List (Tdef);
5666          Vpart := Variant_Part (Clist);
5667
5668          --  Inspect available components
5669
5670          if Present (Component_Items (Clist)) then
5671             declare
5672                Comp : Node_Id := First (Component_Items (Clist));
5673
5674             begin
5675                while Present (Comp) loop
5676
5677                   --  One component is sufficient
5678
5679                   if Component_Is_Unconstrained_UU (Comp) then
5680                      return True;
5681                   end if;
5682
5683                   Next (Comp);
5684                end loop;
5685             end;
5686          end if;
5687
5688          --  Inspect available components withing variants
5689
5690          if Present (Vpart) then
5691             declare
5692                Variant : Node_Id := First (Variants (Vpart));
5693
5694             begin
5695                while Present (Variant) loop
5696
5697                   --  One component within a variant is sufficient
5698
5699                   if Variant_Is_Unconstrained_UU (Variant) then
5700                      return True;
5701                   end if;
5702
5703                   Next (Variant);
5704                end loop;
5705             end;
5706          end if;
5707
5708          --  Neither the available components, nor the components inside the
5709          --  variant parts were of an unconstrained Unchecked_Union subtype.
5710
5711          return False;
5712       end Has_Unconstrained_UU_Component;
5713
5714    --  Start of processing for Expand_N_Op_Eq
5715
5716    begin
5717       Binary_Op_Validity_Checks (N);
5718
5719       if Ekind (Typl) = E_Private_Type then
5720          Typl := Underlying_Type (Typl);
5721       elsif Ekind (Typl) = E_Private_Subtype then
5722          Typl := Underlying_Type (Base_Type (Typl));
5723       else
5724          null;
5725       end if;
5726
5727       --  It may happen in error situations that the underlying type is not
5728       --  set. The error will be detected later, here we just defend the
5729       --  expander code.
5730
5731       if No (Typl) then
5732          return;
5733       end if;
5734
5735       Typl := Base_Type (Typl);
5736
5737       --  Boolean types (requiring handling of non-standard case)
5738
5739       if Is_Boolean_Type (Typl) then
5740          Adjust_Condition (Left_Opnd (N));
5741          Adjust_Condition (Right_Opnd (N));
5742          Set_Etype (N, Standard_Boolean);
5743          Adjust_Result_Type (N, Typ);
5744
5745       --  Array types
5746
5747       elsif Is_Array_Type (Typl) then
5748
5749          --  If we are doing full validity checking, and it is possible for the
5750          --  array elements to be invalid then expand out array comparisons to
5751          --  make sure that we check the array elements.
5752
5753          if Validity_Check_Operands
5754            and then not Is_Known_Valid (Component_Type (Typl))
5755          then
5756             declare
5757                Save_Force_Validity_Checks : constant Boolean :=
5758                                               Force_Validity_Checks;
5759             begin
5760                Force_Validity_Checks := True;
5761                Rewrite (N,
5762                  Expand_Array_Equality
5763                   (N,
5764                    Relocate_Node (Lhs),
5765                    Relocate_Node (Rhs),
5766                    Bodies,
5767                    Typl));
5768                Insert_Actions (N, Bodies);
5769                Analyze_And_Resolve (N, Standard_Boolean);
5770                Force_Validity_Checks := Save_Force_Validity_Checks;
5771             end;
5772
5773          --  Packed case where both operands are known aligned
5774
5775          elsif Is_Bit_Packed_Array (Typl)
5776            and then not Is_Possibly_Unaligned_Object (Lhs)
5777            and then not Is_Possibly_Unaligned_Object (Rhs)
5778          then
5779             Expand_Packed_Eq (N);
5780
5781          --  Where the component type is elementary we can use a block bit
5782          --  comparison (if supported on the target) exception in the case
5783          --  of floating-point (negative zero issues require element by
5784          --  element comparison), and atomic types (where we must be sure
5785          --  to load elements independently) and possibly unaligned arrays.
5786
5787          elsif Is_Elementary_Type (Component_Type (Typl))
5788            and then not Is_Floating_Point_Type (Component_Type (Typl))
5789            and then not Is_Atomic (Component_Type (Typl))
5790            and then not Is_Possibly_Unaligned_Object (Lhs)
5791            and then not Is_Possibly_Unaligned_Object (Rhs)
5792            and then Support_Composite_Compare_On_Target
5793          then
5794             null;
5795
5796          --  For composite and floating-point cases, expand equality loop to
5797          --  make sure of using proper comparisons for tagged types, and
5798          --  correctly handling the floating-point case.
5799
5800          else
5801             Rewrite (N,
5802               Expand_Array_Equality
5803                 (N,
5804                  Relocate_Node (Lhs),
5805                  Relocate_Node (Rhs),
5806                  Bodies,
5807                  Typl));
5808             Insert_Actions      (N, Bodies,           Suppress => All_Checks);
5809             Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
5810          end if;
5811
5812       --  Record Types
5813
5814       elsif Is_Record_Type (Typl) then
5815
5816          --  For tagged types, use the primitive "="
5817
5818          if Is_Tagged_Type (Typl) then
5819
5820             --  No need to do anything else compiling under restriction
5821             --  No_Dispatching_Calls. During the semantic analysis we
5822             --  already notified such violation.
5823
5824             if Restriction_Active (No_Dispatching_Calls) then
5825                return;
5826             end if;
5827
5828             --  If this is derived from an untagged private type completed with
5829             --  a tagged type, it does not have a full view, so we use the
5830             --  primitive operations of the private type. This check should no
5831             --  longer be necessary when these types get their full views???
5832
5833             if Is_Private_Type (A_Typ)
5834               and then not Is_Tagged_Type (A_Typ)
5835               and then Is_Derived_Type (A_Typ)
5836               and then No (Full_View (A_Typ))
5837             then
5838                --  Search for equality operation, checking that the operands
5839                --  have the same type. Note that we must find a matching entry,
5840                --  or something is very wrong!
5841
5842                Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
5843
5844                while Present (Prim) loop
5845                   exit when Chars (Node (Prim)) = Name_Op_Eq
5846                     and then Etype (First_Formal (Node (Prim))) =
5847                              Etype (Next_Formal (First_Formal (Node (Prim))))
5848                     and then
5849                       Base_Type (Etype (Node (Prim))) = Standard_Boolean;
5850
5851                   Next_Elmt (Prim);
5852                end loop;
5853
5854                pragma Assert (Present (Prim));
5855                Op_Name := Node (Prim);
5856
5857             --  Find the type's predefined equality or an overriding
5858             --  user- defined equality. The reason for not simply calling
5859             --  Find_Prim_Op here is that there may be a user-defined
5860             --  overloaded equality op that precedes the equality that we want,
5861             --  so we have to explicitly search (e.g., there could be an
5862             --  equality with two different parameter types).
5863
5864             else
5865                if Is_Class_Wide_Type (Typl) then
5866                   Typl := Root_Type (Typl);
5867                end if;
5868
5869                Prim := First_Elmt (Primitive_Operations (Typl));
5870                while Present (Prim) loop
5871                   exit when Chars (Node (Prim)) = Name_Op_Eq
5872                     and then Etype (First_Formal (Node (Prim))) =
5873                              Etype (Next_Formal (First_Formal (Node (Prim))))
5874                     and then
5875                       Base_Type (Etype (Node (Prim))) = Standard_Boolean;
5876
5877                   Next_Elmt (Prim);
5878                end loop;
5879
5880                pragma Assert (Present (Prim));
5881                Op_Name := Node (Prim);
5882             end if;
5883
5884             Build_Equality_Call (Op_Name);
5885
5886          --  Ada 2005 (AI-216): Program_Error is raised when evaluating the
5887          --  predefined equality operator for a type which has a subcomponent
5888          --  of an Unchecked_Union type whose nominal subtype is unconstrained.
5889
5890          elsif Has_Unconstrained_UU_Component (Typl) then
5891             Insert_Action (N,
5892               Make_Raise_Program_Error (Loc,
5893                 Reason => PE_Unchecked_Union_Restriction));
5894
5895             --  Prevent Gigi from generating incorrect code by rewriting the
5896             --  equality as a standard False.
5897
5898             Rewrite (N,
5899               New_Occurrence_Of (Standard_False, Loc));
5900
5901          elsif Is_Unchecked_Union (Typl) then
5902
5903             --  If we can infer the discriminants of the operands, we make a
5904             --  call to the TSS equality function.
5905
5906             if Has_Inferable_Discriminants (Lhs)
5907                  and then
5908                Has_Inferable_Discriminants (Rhs)
5909             then
5910                Build_Equality_Call
5911                  (TSS (Root_Type (Typl), TSS_Composite_Equality));
5912
5913             else
5914                --  Ada 2005 (AI-216): Program_Error is raised when evaluating
5915                --  the predefined equality operator for an Unchecked_Union type
5916                --  if either of the operands lack inferable discriminants.
5917
5918                Insert_Action (N,
5919                  Make_Raise_Program_Error (Loc,
5920                    Reason => PE_Unchecked_Union_Restriction));
5921
5922                --  Prevent Gigi from generating incorrect code by rewriting
5923                --  the equality as a standard False.
5924
5925                Rewrite (N,
5926                  New_Occurrence_Of (Standard_False, Loc));
5927
5928             end if;
5929
5930          --  If a type support function is present (for complex cases), use it
5931
5932          elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
5933             Build_Equality_Call
5934               (TSS (Root_Type (Typl), TSS_Composite_Equality));
5935
5936          --  Otherwise expand the component by component equality. Note that
5937          --  we never use block-bit comparisons for records, because of the
5938          --  problems with gaps. The backend will often be able to recombine
5939          --  the separate comparisons that we generate here.
5940
5941          else
5942             Remove_Side_Effects (Lhs);
5943             Remove_Side_Effects (Rhs);
5944             Rewrite (N,
5945               Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
5946
5947             Insert_Actions      (N, Bodies,           Suppress => All_Checks);
5948             Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
5949          end if;
5950       end if;
5951
5952       --  Test if result is known at compile time
5953
5954       Rewrite_Comparison (N);
5955
5956       --  If we still have comparison for Vax_Float, process it
5957
5958       if Vax_Float (Typl) and then Nkind (N) in N_Op_Compare  then
5959          Expand_Vax_Comparison (N);
5960          return;
5961       end if;
5962    end Expand_N_Op_Eq;
5963
5964    -----------------------
5965    -- Expand_N_Op_Expon --
5966    -----------------------
5967
5968    procedure Expand_N_Op_Expon (N : Node_Id) is
5969       Loc    : constant Source_Ptr := Sloc (N);
5970       Typ    : constant Entity_Id  := Etype (N);
5971       Rtyp   : constant Entity_Id  := Root_Type (Typ);
5972       Base   : constant Node_Id    := Relocate_Node (Left_Opnd (N));
5973       Bastyp : constant Node_Id    := Etype (Base);
5974       Exp    : constant Node_Id    := Relocate_Node (Right_Opnd (N));
5975       Exptyp : constant Entity_Id  := Etype (Exp);
5976       Ovflo  : constant Boolean    := Do_Overflow_Check (N);
5977       Expv   : Uint;
5978       Xnode  : Node_Id;
5979       Temp   : Node_Id;
5980       Rent   : RE_Id;
5981       Ent    : Entity_Id;
5982       Etyp   : Entity_Id;
5983
5984    begin
5985       Binary_Op_Validity_Checks (N);
5986
5987       --  If either operand is of a private type, then we have the use of an
5988       --  intrinsic operator, and we get rid of the privateness, by using root
5989       --  types of underlying types for the actual operation. Otherwise the
5990       --  private types will cause trouble if we expand multiplications or
5991       --  shifts etc. We also do this transformation if the result type is
5992       --  different from the base type.
5993
5994       if Is_Private_Type (Etype (Base))
5995            or else
5996          Is_Private_Type (Typ)
5997            or else
5998          Is_Private_Type (Exptyp)
5999            or else
6000          Rtyp /= Root_Type (Bastyp)
6001       then
6002          declare
6003             Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
6004             Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
6005
6006          begin
6007             Rewrite (N,
6008               Unchecked_Convert_To (Typ,
6009                 Make_Op_Expon (Loc,
6010                   Left_Opnd  => Unchecked_Convert_To (Bt, Base),
6011                   Right_Opnd => Unchecked_Convert_To (Et, Exp))));
6012             Analyze_And_Resolve (N, Typ);
6013             return;
6014          end;
6015       end if;
6016
6017       --  Test for case of known right argument
6018
6019       if Compile_Time_Known_Value (Exp) then
6020          Expv := Expr_Value (Exp);
6021
6022          --  We only fold small non-negative exponents. You might think we
6023          --  could fold small negative exponents for the real case, but we
6024          --  can't because we are required to raise Constraint_Error for
6025          --  the case of 0.0 ** (negative) even if Machine_Overflows = False.
6026          --  See ACVC test C4A012B.
6027
6028          if Expv >= 0 and then Expv <= 4 then
6029
6030             --  X ** 0 = 1 (or 1.0)
6031
6032             if Expv = 0 then
6033
6034                --  Call Remove_Side_Effects to ensure that any side effects
6035                --  in the ignored left operand (in particular function calls
6036                --  to user defined functions) are properly executed.
6037
6038                Remove_Side_Effects (Base);
6039
6040                if Ekind (Typ) in Integer_Kind then
6041                   Xnode := Make_Integer_Literal (Loc, Intval => 1);
6042                else
6043                   Xnode := Make_Real_Literal (Loc, Ureal_1);
6044                end if;
6045
6046             --  X ** 1 = X
6047
6048             elsif Expv = 1 then
6049                Xnode := Base;
6050
6051             --  X ** 2 = X * X
6052
6053             elsif Expv = 2 then
6054                Xnode :=
6055                  Make_Op_Multiply (Loc,
6056                    Left_Opnd  => Duplicate_Subexpr (Base),
6057                    Right_Opnd => Duplicate_Subexpr_No_Checks (Base));
6058
6059             --  X ** 3 = X * X * X
6060
6061             elsif Expv = 3 then
6062                Xnode :=
6063                  Make_Op_Multiply (Loc,
6064                    Left_Opnd =>
6065                      Make_Op_Multiply (Loc,
6066                        Left_Opnd  => Duplicate_Subexpr (Base),
6067                        Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
6068                    Right_Opnd  => Duplicate_Subexpr_No_Checks (Base));
6069
6070             --  X ** 4  ->
6071             --    En : constant base'type := base * base;
6072             --    ...
6073             --    En * En
6074
6075             else -- Expv = 4
6076                Temp := Make_Temporary (Loc, 'E', Base);
6077
6078                Insert_Actions (N, New_List (
6079                  Make_Object_Declaration (Loc,
6080                    Defining_Identifier => Temp,
6081                    Constant_Present    => True,
6082                    Object_Definition   => New_Reference_To (Typ, Loc),
6083                    Expression =>
6084                      Make_Op_Multiply (Loc,
6085                        Left_Opnd  => Duplicate_Subexpr (Base),
6086                        Right_Opnd => Duplicate_Subexpr_No_Checks (Base)))));
6087
6088                Xnode :=
6089                  Make_Op_Multiply (Loc,
6090                    Left_Opnd  => New_Reference_To (Temp, Loc),
6091                    Right_Opnd => New_Reference_To (Temp, Loc));
6092             end if;
6093
6094             Rewrite (N, Xnode);
6095             Analyze_And_Resolve (N, Typ);
6096             return;
6097          end if;
6098       end if;
6099
6100       --  Case of (2 ** expression) appearing as an argument of an integer
6101       --  multiplication, or as the right argument of a division of a non-
6102       --  negative integer. In such cases we leave the node untouched, setting
6103       --  the flag Is_Natural_Power_Of_2_for_Shift set, then the expansion
6104       --  of the higher level node converts it into a shift.
6105
6106       --  Another case is 2 ** N in any other context. We simply convert
6107       --  this to 1 * 2 ** N, and then the above transformation applies.
6108
6109       --  Note: this transformation is not applicable for a modular type with
6110       --  a non-binary modulus in the multiplication case, since we get a wrong
6111       --  result if the shift causes an overflow before the modular reduction.
6112
6113       if Nkind (Base) = N_Integer_Literal
6114         and then Intval (Base) = 2
6115         and then Is_Integer_Type (Root_Type (Exptyp))
6116         and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
6117         and then Is_Unsigned_Type (Exptyp)
6118         and then not Ovflo
6119       then
6120          --  First the multiply and divide cases
6121
6122          if Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply) then
6123             declare
6124                P : constant Node_Id := Parent (N);
6125                L : constant Node_Id := Left_Opnd (P);
6126                R : constant Node_Id := Right_Opnd (P);
6127
6128             begin
6129                if (Nkind (P) = N_Op_Multiply
6130                    and then not Non_Binary_Modulus (Typ)
6131                    and then
6132                      ((Is_Integer_Type (Etype (L)) and then R = N)
6133                          or else
6134                       (Is_Integer_Type (Etype (R)) and then L = N))
6135                    and then not Do_Overflow_Check (P))
6136                  or else
6137                   (Nkind (P) = N_Op_Divide
6138                      and then Is_Integer_Type (Etype (L))
6139                      and then Is_Unsigned_Type (Etype (L))
6140                      and then R = N
6141                      and then not Do_Overflow_Check (P))
6142                then
6143                   Set_Is_Power_Of_2_For_Shift (N);
6144                   return;
6145                end if;
6146             end;
6147
6148          --  Now the other cases
6149
6150          elsif not Non_Binary_Modulus (Typ) then
6151             Rewrite (N,
6152               Make_Op_Multiply (Loc,
6153                 Left_Opnd  => Make_Integer_Literal (Loc, 1),
6154                 Right_Opnd => Relocate_Node (N)));
6155             Analyze_And_Resolve (N, Typ);
6156             return;
6157          end if;
6158       end if;
6159
6160       --  Fall through if exponentiation must be done using a runtime routine
6161
6162       --  First deal with modular case
6163
6164       if Is_Modular_Integer_Type (Rtyp) then
6165
6166          --  Non-binary case, we call the special exponentiation routine for
6167          --  the non-binary case, converting the argument to Long_Long_Integer
6168          --  and passing the modulus value. Then the result is converted back
6169          --  to the base type.
6170
6171          if Non_Binary_Modulus (Rtyp) then
6172             Rewrite (N,
6173               Convert_To (Typ,
6174                 Make_Function_Call (Loc,
6175                   Name => New_Reference_To (RTE (RE_Exp_Modular), Loc),
6176                   Parameter_Associations => New_List (
6177                     Convert_To (Standard_Integer, Base),
6178                     Make_Integer_Literal (Loc, Modulus (Rtyp)),
6179                     Exp))));
6180
6181          --  Binary case, in this case, we call one of two routines, either the
6182          --  unsigned integer case, or the unsigned long long integer case,
6183          --  with a final "and" operation to do the required mod.
6184
6185          else
6186             if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
6187                Ent := RTE (RE_Exp_Unsigned);
6188             else
6189                Ent := RTE (RE_Exp_Long_Long_Unsigned);
6190             end if;
6191
6192             Rewrite (N,
6193               Convert_To (Typ,
6194                 Make_Op_And (Loc,
6195                   Left_Opnd =>
6196                     Make_Function_Call (Loc,
6197                       Name => New_Reference_To (Ent, Loc),
6198                       Parameter_Associations => New_List (
6199                         Convert_To (Etype (First_Formal (Ent)), Base),
6200                         Exp)),
6201                    Right_Opnd =>
6202                      Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
6203
6204          end if;
6205
6206          --  Common exit point for modular type case
6207
6208          Analyze_And_Resolve (N, Typ);
6209          return;
6210
6211       --  Signed integer cases, done using either Integer or Long_Long_Integer.
6212       --  It is not worth having routines for Short_[Short_]Integer, since for
6213       --  most machines it would not help, and it would generate more code that
6214       --  might need certification when a certified run time is required.
6215
6216       --  In the integer cases, we have two routines, one for when overflow
6217       --  checks are required, and one when they are not required, since there
6218       --  is a real gain in omitting checks on many machines.
6219
6220       elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
6221         or else (Rtyp = Base_Type (Standard_Long_Integer)
6222                    and then
6223                      Esize (Standard_Long_Integer) > Esize (Standard_Integer))
6224         or else (Rtyp = Universal_Integer)
6225       then
6226          Etyp := Standard_Long_Long_Integer;
6227
6228          if Ovflo then
6229             Rent := RE_Exp_Long_Long_Integer;
6230          else
6231             Rent := RE_Exn_Long_Long_Integer;
6232          end if;
6233
6234       elsif Is_Signed_Integer_Type (Rtyp) then
6235          Etyp := Standard_Integer;
6236
6237          if Ovflo then
6238             Rent := RE_Exp_Integer;
6239          else
6240             Rent := RE_Exn_Integer;
6241          end if;
6242
6243       --  Floating-point cases, always done using Long_Long_Float. We do not
6244       --  need separate routines for the overflow case here, since in the case
6245       --  of floating-point, we generate infinities anyway as a rule (either
6246       --  that or we automatically trap overflow), and if there is an infinity
6247       --  generated and a range check is required, the check will fail anyway.
6248
6249       else
6250          pragma Assert (Is_Floating_Point_Type (Rtyp));
6251          Etyp := Standard_Long_Long_Float;
6252          Rent := RE_Exn_Long_Long_Float;
6253       end if;
6254
6255       --  Common processing for integer cases and floating-point cases.
6256       --  If we are in the right type, we can call runtime routine directly
6257
6258       if Typ = Etyp
6259         and then Rtyp /= Universal_Integer
6260         and then Rtyp /= Universal_Real
6261       then
6262          Rewrite (N,
6263            Make_Function_Call (Loc,
6264              Name => New_Reference_To (RTE (Rent), Loc),
6265              Parameter_Associations => New_List (Base, Exp)));
6266
6267       --  Otherwise we have to introduce conversions (conversions are also
6268       --  required in the universal cases, since the runtime routine is
6269       --  typed using one of the standard types).
6270
6271       else
6272          Rewrite (N,
6273            Convert_To (Typ,
6274              Make_Function_Call (Loc,
6275                Name => New_Reference_To (RTE (Rent), Loc),
6276                Parameter_Associations => New_List (
6277                  Convert_To (Etyp, Base),
6278                  Exp))));
6279       end if;
6280
6281       Analyze_And_Resolve (N, Typ);
6282       return;
6283
6284    exception
6285       when RE_Not_Available =>
6286          return;
6287    end Expand_N_Op_Expon;
6288
6289    --------------------
6290    -- Expand_N_Op_Ge --
6291    --------------------
6292
6293    procedure Expand_N_Op_Ge (N : Node_Id) is
6294       Typ  : constant Entity_Id := Etype (N);
6295       Op1  : constant Node_Id   := Left_Opnd (N);
6296       Op2  : constant Node_Id   := Right_Opnd (N);
6297       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6298
6299    begin
6300       Binary_Op_Validity_Checks (N);
6301
6302       if Is_Array_Type (Typ1) then
6303          Expand_Array_Comparison (N);
6304          return;
6305       end if;
6306
6307       if Is_Boolean_Type (Typ1) then
6308          Adjust_Condition (Op1);
6309          Adjust_Condition (Op2);
6310          Set_Etype (N, Standard_Boolean);
6311          Adjust_Result_Type (N, Typ);
6312       end if;
6313
6314       Rewrite_Comparison (N);
6315
6316       --  If we still have comparison, and Vax_Float type, process it
6317
6318       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6319          Expand_Vax_Comparison (N);
6320          return;
6321       end if;
6322    end Expand_N_Op_Ge;
6323
6324    --------------------
6325    -- Expand_N_Op_Gt --
6326    --------------------
6327
6328    procedure Expand_N_Op_Gt (N : Node_Id) is
6329       Typ  : constant Entity_Id := Etype (N);
6330       Op1  : constant Node_Id   := Left_Opnd (N);
6331       Op2  : constant Node_Id   := Right_Opnd (N);
6332       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6333
6334    begin
6335       Binary_Op_Validity_Checks (N);
6336
6337       if Is_Array_Type (Typ1) then
6338          Expand_Array_Comparison (N);
6339          return;
6340       end if;
6341
6342       if Is_Boolean_Type (Typ1) then
6343          Adjust_Condition (Op1);
6344          Adjust_Condition (Op2);
6345          Set_Etype (N, Standard_Boolean);
6346          Adjust_Result_Type (N, Typ);
6347       end if;
6348
6349       Rewrite_Comparison (N);
6350
6351       --  If we still have comparison, and Vax_Float type, process it
6352
6353       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6354          Expand_Vax_Comparison (N);
6355          return;
6356       end if;
6357    end Expand_N_Op_Gt;
6358
6359    --------------------
6360    -- Expand_N_Op_Le --
6361    --------------------
6362
6363    procedure Expand_N_Op_Le (N : Node_Id) is
6364       Typ  : constant Entity_Id := Etype (N);
6365       Op1  : constant Node_Id   := Left_Opnd (N);
6366       Op2  : constant Node_Id   := Right_Opnd (N);
6367       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6368
6369    begin
6370       Binary_Op_Validity_Checks (N);
6371
6372       if Is_Array_Type (Typ1) then
6373          Expand_Array_Comparison (N);
6374          return;
6375       end if;
6376
6377       if Is_Boolean_Type (Typ1) then
6378          Adjust_Condition (Op1);
6379          Adjust_Condition (Op2);
6380          Set_Etype (N, Standard_Boolean);
6381          Adjust_Result_Type (N, Typ);
6382       end if;
6383
6384       Rewrite_Comparison (N);
6385
6386       --  If we still have comparison, and Vax_Float type, process it
6387
6388       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6389          Expand_Vax_Comparison (N);
6390          return;
6391       end if;
6392    end Expand_N_Op_Le;
6393
6394    --------------------
6395    -- Expand_N_Op_Lt --
6396    --------------------
6397
6398    procedure Expand_N_Op_Lt (N : Node_Id) is
6399       Typ  : constant Entity_Id := Etype (N);
6400       Op1  : constant Node_Id   := Left_Opnd (N);
6401       Op2  : constant Node_Id   := Right_Opnd (N);
6402       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6403
6404    begin
6405       Binary_Op_Validity_Checks (N);
6406
6407       if Is_Array_Type (Typ1) then
6408          Expand_Array_Comparison (N);
6409          return;
6410       end if;
6411
6412       if Is_Boolean_Type (Typ1) then
6413          Adjust_Condition (Op1);
6414          Adjust_Condition (Op2);
6415          Set_Etype (N, Standard_Boolean);
6416          Adjust_Result_Type (N, Typ);
6417       end if;
6418
6419       Rewrite_Comparison (N);
6420
6421       --  If we still have comparison, and Vax_Float type, process it
6422
6423       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6424          Expand_Vax_Comparison (N);
6425          return;
6426       end if;
6427    end Expand_N_Op_Lt;
6428
6429    -----------------------
6430    -- Expand_N_Op_Minus --
6431    -----------------------
6432
6433    procedure Expand_N_Op_Minus (N : Node_Id) is
6434       Loc : constant Source_Ptr := Sloc (N);
6435       Typ : constant Entity_Id  := Etype (N);
6436
6437    begin
6438       Unary_Op_Validity_Checks (N);
6439
6440       if not Backend_Overflow_Checks_On_Target
6441          and then Is_Signed_Integer_Type (Etype (N))
6442          and then Do_Overflow_Check (N)
6443       then
6444          --  Software overflow checking expands -expr into (0 - expr)
6445
6446          Rewrite (N,
6447            Make_Op_Subtract (Loc,
6448              Left_Opnd  => Make_Integer_Literal (Loc, 0),
6449              Right_Opnd => Right_Opnd (N)));
6450
6451          Analyze_And_Resolve (N, Typ);
6452
6453       --  Vax floating-point types case
6454
6455       elsif Vax_Float (Etype (N)) then
6456          Expand_Vax_Arith (N);
6457       end if;
6458    end Expand_N_Op_Minus;
6459
6460    ---------------------
6461    -- Expand_N_Op_Mod --
6462    ---------------------
6463
6464    procedure Expand_N_Op_Mod (N : Node_Id) is
6465       Loc   : constant Source_Ptr := Sloc (N);
6466       Typ   : constant Entity_Id  := Etype (N);
6467       Left  : constant Node_Id    := Left_Opnd (N);
6468       Right : constant Node_Id    := Right_Opnd (N);
6469       DOC   : constant Boolean    := Do_Overflow_Check (N);
6470       DDC   : constant Boolean    := Do_Division_Check (N);
6471
6472       LLB : Uint;
6473       Llo : Uint;
6474       Lhi : Uint;
6475       LOK : Boolean;
6476       Rlo : Uint;
6477       Rhi : Uint;
6478       ROK : Boolean;
6479
6480       pragma Warnings (Off, Lhi);
6481
6482    begin
6483       Binary_Op_Validity_Checks (N);
6484
6485       Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
6486       Determine_Range (Left,  LOK, Llo, Lhi, Assume_Valid => True);
6487
6488       --  Convert mod to rem if operands are known non-negative. We do this
6489       --  since it is quite likely that this will improve the quality of code,
6490       --  (the operation now corresponds to the hardware remainder), and it
6491       --  does not seem likely that it could be harmful.
6492
6493       if LOK and then Llo >= 0
6494            and then
6495          ROK and then Rlo >= 0
6496       then
6497          Rewrite (N,
6498            Make_Op_Rem (Sloc (N),
6499              Left_Opnd  => Left_Opnd (N),
6500              Right_Opnd => Right_Opnd (N)));
6501
6502          --  Instead of reanalyzing the node we do the analysis manually. This
6503          --  avoids anomalies when the replacement is done in an instance and
6504          --  is epsilon more efficient.
6505
6506          Set_Entity            (N, Standard_Entity (S_Op_Rem));
6507          Set_Etype             (N, Typ);
6508          Set_Do_Overflow_Check (N, DOC);
6509          Set_Do_Division_Check (N, DDC);
6510          Expand_N_Op_Rem (N);
6511          Set_Analyzed (N);
6512
6513       --  Otherwise, normal mod processing
6514
6515       else
6516          if Is_Integer_Type (Etype (N)) then
6517             Apply_Divide_Check (N);
6518          end if;
6519
6520          --  Apply optimization x mod 1 = 0. We don't really need that with
6521          --  gcc, but it is useful with other back ends (e.g. AAMP), and is
6522          --  certainly harmless.
6523
6524          if Is_Integer_Type (Etype (N))
6525            and then Compile_Time_Known_Value (Right)
6526            and then Expr_Value (Right) = Uint_1
6527          then
6528             --  Call Remove_Side_Effects to ensure that any side effects in
6529             --  the ignored left operand (in particular function calls to
6530             --  user defined functions) are properly executed.
6531
6532             Remove_Side_Effects (Left);
6533
6534             Rewrite (N, Make_Integer_Literal (Loc, 0));
6535             Analyze_And_Resolve (N, Typ);
6536             return;
6537          end if;
6538
6539          --  Deal with annoying case of largest negative number remainder
6540          --  minus one. Gigi does not handle this case correctly, because
6541          --  it generates a divide instruction which may trap in this case.
6542
6543          --  In fact the check is quite easy, if the right operand is -1, then
6544          --  the mod value is always 0, and we can just ignore the left operand
6545          --  completely in this case.
6546
6547          --  The operand type may be private (e.g. in the expansion of an
6548          --  intrinsic operation) so we must use the underlying type to get the
6549          --  bounds, and convert the literals explicitly.
6550
6551          LLB :=
6552            Expr_Value
6553              (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
6554
6555          if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
6556            and then
6557             ((not LOK) or else (Llo = LLB))
6558          then
6559             Rewrite (N,
6560               Make_Conditional_Expression (Loc,
6561                 Expressions => New_List (
6562                   Make_Op_Eq (Loc,
6563                     Left_Opnd => Duplicate_Subexpr (Right),
6564                     Right_Opnd =>
6565                       Unchecked_Convert_To (Typ,
6566                         Make_Integer_Literal (Loc, -1))),
6567                   Unchecked_Convert_To (Typ,
6568                     Make_Integer_Literal (Loc, Uint_0)),
6569                   Relocate_Node (N))));
6570
6571             Set_Analyzed (Next (Next (First (Expressions (N)))));
6572             Analyze_And_Resolve (N, Typ);
6573          end if;
6574       end if;
6575    end Expand_N_Op_Mod;
6576
6577    --------------------------
6578    -- Expand_N_Op_Multiply --
6579    --------------------------
6580
6581    procedure Expand_N_Op_Multiply (N : Node_Id) is
6582       Loc : constant Source_Ptr := Sloc (N);
6583       Lop : constant Node_Id    := Left_Opnd (N);
6584       Rop : constant Node_Id    := Right_Opnd (N);
6585
6586       Lp2 : constant Boolean :=
6587               Nkind (Lop) = N_Op_Expon
6588                 and then Is_Power_Of_2_For_Shift (Lop);
6589
6590       Rp2 : constant Boolean :=
6591               Nkind (Rop) = N_Op_Expon
6592                 and then Is_Power_Of_2_For_Shift (Rop);
6593
6594       Ltyp : constant Entity_Id  := Etype (Lop);
6595       Rtyp : constant Entity_Id  := Etype (Rop);
6596       Typ  : Entity_Id           := Etype (N);
6597
6598    begin
6599       Binary_Op_Validity_Checks (N);
6600
6601       --  Special optimizations for integer types
6602
6603       if Is_Integer_Type (Typ) then
6604
6605          --  N * 0 = 0 for integer types
6606
6607          if Compile_Time_Known_Value (Rop)
6608            and then Expr_Value (Rop) = Uint_0
6609          then
6610             --  Call Remove_Side_Effects to ensure that any side effects in
6611             --  the ignored left operand (in particular function calls to
6612             --  user defined functions) are properly executed.
6613
6614             Remove_Side_Effects (Lop);
6615
6616             Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
6617             Analyze_And_Resolve (N, Typ);
6618             return;
6619          end if;
6620
6621          --  Similar handling for 0 * N = 0
6622
6623          if Compile_Time_Known_Value (Lop)
6624            and then Expr_Value (Lop) = Uint_0
6625          then
6626             Remove_Side_Effects (Rop);
6627             Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
6628             Analyze_And_Resolve (N, Typ);
6629             return;
6630          end if;
6631
6632          --  N * 1 = 1 * N = N for integer types
6633
6634          --  This optimisation is not done if we are going to
6635          --  rewrite the product 1 * 2 ** N to a shift.
6636
6637          if Compile_Time_Known_Value (Rop)
6638            and then Expr_Value (Rop) = Uint_1
6639            and then not Lp2
6640          then
6641             Rewrite (N, Lop);
6642             return;
6643
6644          elsif Compile_Time_Known_Value (Lop)
6645            and then Expr_Value (Lop) = Uint_1
6646            and then not Rp2
6647          then
6648             Rewrite (N, Rop);
6649             return;
6650          end if;
6651       end if;
6652
6653       --  Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
6654       --  Is_Power_Of_2_For_Shift is set means that we know that our left
6655       --  operand is an integer, as required for this to work.
6656
6657       if Rp2 then
6658          if Lp2 then
6659
6660             --  Convert 2 ** A * 2 ** B into  2 ** (A + B)
6661
6662             Rewrite (N,
6663               Make_Op_Expon (Loc,
6664                 Left_Opnd => Make_Integer_Literal (Loc, 2),
6665                 Right_Opnd =>
6666                   Make_Op_Add (Loc,
6667                     Left_Opnd  => Right_Opnd (Lop),
6668                     Right_Opnd => Right_Opnd (Rop))));
6669             Analyze_And_Resolve (N, Typ);
6670             return;
6671
6672          else
6673             Rewrite (N,
6674               Make_Op_Shift_Left (Loc,
6675                 Left_Opnd  => Lop,
6676                 Right_Opnd =>
6677                   Convert_To (Standard_Natural, Right_Opnd (Rop))));
6678             Analyze_And_Resolve (N, Typ);
6679             return;
6680          end if;
6681
6682       --  Same processing for the operands the other way round
6683
6684       elsif Lp2 then
6685          Rewrite (N,
6686            Make_Op_Shift_Left (Loc,
6687              Left_Opnd  => Rop,
6688              Right_Opnd =>
6689                Convert_To (Standard_Natural, Right_Opnd (Lop))));
6690          Analyze_And_Resolve (N, Typ);
6691          return;
6692       end if;
6693
6694       --  Do required fixup of universal fixed operation
6695
6696       if Typ = Universal_Fixed then
6697          Fixup_Universal_Fixed_Operation (N);
6698          Typ := Etype (N);
6699       end if;
6700
6701       --  Multiplications with fixed-point results
6702
6703       if Is_Fixed_Point_Type (Typ) then
6704
6705          --  No special processing if Treat_Fixed_As_Integer is set, since from
6706          --  a semantic point of view such operations are simply integer
6707          --  operations and will be treated that way.
6708
6709          if not Treat_Fixed_As_Integer (N) then
6710
6711             --  Case of fixed * integer => fixed
6712
6713             if Is_Integer_Type (Rtyp) then
6714                Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
6715
6716             --  Case of integer * fixed => fixed
6717
6718             elsif Is_Integer_Type (Ltyp) then
6719                Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
6720
6721             --  Case of fixed * fixed => fixed
6722
6723             else
6724                Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
6725             end if;
6726          end if;
6727
6728       --  Other cases of multiplication of fixed-point operands. Again we
6729       --  exclude the cases where Treat_Fixed_As_Integer flag is set.
6730
6731       elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
6732         and then not Treat_Fixed_As_Integer (N)
6733       then
6734          if Is_Integer_Type (Typ) then
6735             Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
6736          else
6737             pragma Assert (Is_Floating_Point_Type (Typ));
6738             Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
6739          end if;
6740
6741       --  Mixed-mode operations can appear in a non-static universal context,
6742       --  in which case the integer argument must be converted explicitly.
6743
6744       elsif Typ = Universal_Real
6745         and then Is_Integer_Type (Rtyp)
6746       then
6747          Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
6748
6749          Analyze_And_Resolve (Rop, Universal_Real);
6750
6751       elsif Typ = Universal_Real
6752         and then Is_Integer_Type (Ltyp)
6753       then
6754          Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
6755
6756          Analyze_And_Resolve (Lop, Universal_Real);
6757
6758       --  Non-fixed point cases, check software overflow checking required
6759
6760       elsif Is_Signed_Integer_Type (Etype (N)) then
6761          Apply_Arithmetic_Overflow_Check (N);
6762
6763       --  Deal with VAX float case
6764
6765       elsif Vax_Float (Typ) then
6766          Expand_Vax_Arith (N);
6767          return;
6768       end if;
6769    end Expand_N_Op_Multiply;
6770
6771    --------------------
6772    -- Expand_N_Op_Ne --
6773    --------------------
6774
6775    procedure Expand_N_Op_Ne (N : Node_Id) is
6776       Typ : constant Entity_Id := Etype (Left_Opnd (N));
6777
6778    begin
6779       --  Case of elementary type with standard operator
6780
6781       if Is_Elementary_Type (Typ)
6782         and then Sloc (Entity (N)) = Standard_Location
6783       then
6784          Binary_Op_Validity_Checks (N);
6785
6786          --  Boolean types (requiring handling of non-standard case)
6787
6788          if Is_Boolean_Type (Typ) then
6789             Adjust_Condition (Left_Opnd (N));
6790             Adjust_Condition (Right_Opnd (N));
6791             Set_Etype (N, Standard_Boolean);
6792             Adjust_Result_Type (N, Typ);
6793          end if;
6794
6795          Rewrite_Comparison (N);
6796
6797          --  If we still have comparison for Vax_Float, process it
6798
6799          if Vax_Float (Typ) and then Nkind (N) in N_Op_Compare  then
6800             Expand_Vax_Comparison (N);
6801             return;
6802          end if;
6803
6804       --  For all cases other than elementary types, we rewrite node as the
6805       --  negation of an equality operation, and reanalyze. The equality to be
6806       --  used is defined in the same scope and has the same signature. This
6807       --  signature must be set explicitly since in an instance it may not have
6808       --  the same visibility as in the generic unit. This avoids duplicating
6809       --  or factoring the complex code for record/array equality tests etc.
6810
6811       else
6812          declare
6813             Loc : constant Source_Ptr := Sloc (N);
6814             Neg : Node_Id;
6815             Ne  : constant Entity_Id := Entity (N);
6816
6817          begin
6818             Binary_Op_Validity_Checks (N);
6819
6820             Neg :=
6821               Make_Op_Not (Loc,
6822                 Right_Opnd =>
6823                   Make_Op_Eq (Loc,
6824                     Left_Opnd =>  Left_Opnd (N),
6825                     Right_Opnd => Right_Opnd (N)));
6826             Set_Paren_Count (Right_Opnd (Neg), 1);
6827
6828             if Scope (Ne) /= Standard_Standard then
6829                Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
6830             end if;
6831
6832             --  For navigation purposes, the inequality is treated as an
6833             --  implicit reference to the corresponding equality. Preserve the
6834             --  Comes_From_ source flag so that the proper Xref entry is
6835             --  generated.
6836
6837             Preserve_Comes_From_Source (Neg, N);
6838             Preserve_Comes_From_Source (Right_Opnd (Neg), N);
6839             Rewrite (N, Neg);
6840             Analyze_And_Resolve (N, Standard_Boolean);
6841          end;
6842       end if;
6843    end Expand_N_Op_Ne;
6844
6845    ---------------------
6846    -- Expand_N_Op_Not --
6847    ---------------------
6848
6849    --  If the argument is other than a Boolean array type, there is no special
6850    --  expansion required, except for VMS operations on signed integers.
6851
6852    --  For the packed case, we call the special routine in Exp_Pakd, except
6853    --  that if the component size is greater than one, we use the standard
6854    --  routine generating a gruesome loop (it is so peculiar to have packed
6855    --  arrays with non-standard Boolean representations anyway, so it does not
6856    --  matter that we do not handle this case efficiently).
6857
6858    --  For the unpacked case (and for the special packed case where we have non
6859    --  standard Booleans, as discussed above), we generate and insert into the
6860    --  tree the following function definition:
6861
6862    --     function Nnnn (A : arr) is
6863    --       B : arr;
6864    --     begin
6865    --       for J in a'range loop
6866    --          B (J) := not A (J);
6867    --       end loop;
6868    --       return B;
6869    --     end Nnnn;
6870
6871    --  Here arr is the actual subtype of the parameter (and hence always
6872    --  constrained). Then we replace the not with a call to this function.
6873
6874    procedure Expand_N_Op_Not (N : Node_Id) is
6875       Loc  : constant Source_Ptr := Sloc (N);
6876       Typ  : constant Entity_Id  := Etype (N);
6877       Opnd : Node_Id;
6878       Arr  : Entity_Id;
6879       A    : Entity_Id;
6880       B    : Entity_Id;
6881       J    : Entity_Id;
6882       A_J  : Node_Id;
6883       B_J  : Node_Id;
6884
6885       Func_Name      : Entity_Id;
6886       Loop_Statement : Node_Id;
6887
6888    begin
6889       Unary_Op_Validity_Checks (N);
6890
6891       --  For boolean operand, deal with non-standard booleans
6892
6893       if Is_Boolean_Type (Typ) then
6894          Adjust_Condition (Right_Opnd (N));
6895          Set_Etype (N, Standard_Boolean);
6896          Adjust_Result_Type (N, Typ);
6897          return;
6898       end if;
6899
6900       --  For the VMS "not" on signed integer types, use conversion to and
6901       --  from a predefined modular type.
6902
6903       if Is_VMS_Operator (Entity (N)) then
6904          declare
6905             LI : constant Entity_Id := RTE (RE_Unsigned_64);
6906          begin
6907             Rewrite (N,
6908               Unchecked_Convert_To (Typ,
6909                 (Make_Op_Not (Loc,
6910                    Right_Opnd => Unchecked_Convert_To (LI, Right_Opnd (N))))));
6911             Analyze_And_Resolve (N, Typ);
6912             return;
6913          end;
6914       end if;
6915
6916       --  Only array types need any other processing
6917
6918       if not Is_Array_Type (Typ) then
6919          return;
6920       end if;
6921
6922       --  Case of array operand. If bit packed with a component size of 1,
6923       --  handle it in Exp_Pakd if the operand is known to be aligned.
6924
6925       if Is_Bit_Packed_Array (Typ)
6926         and then Component_Size (Typ) = 1
6927         and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
6928       then
6929          Expand_Packed_Not (N);
6930          return;
6931       end if;
6932
6933       --  Case of array operand which is not bit-packed. If the context is
6934       --  a safe assignment, call in-place operation, If context is a larger
6935       --  boolean expression in the context of a safe assignment, expansion is
6936       --  done by enclosing operation.
6937
6938       Opnd := Relocate_Node (Right_Opnd (N));
6939       Convert_To_Actual_Subtype (Opnd);
6940       Arr := Etype (Opnd);
6941       Ensure_Defined (Arr, N);
6942       Silly_Boolean_Array_Not_Test (N, Arr);
6943
6944       if Nkind (Parent (N)) = N_Assignment_Statement then
6945          if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
6946             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
6947             return;
6948
6949          --  Special case the negation of a binary operation
6950
6951          elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
6952            and then Safe_In_Place_Array_Op
6953                       (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
6954          then
6955             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
6956             return;
6957          end if;
6958
6959       elsif Nkind (Parent (N)) in N_Binary_Op
6960         and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
6961       then
6962          declare
6963             Op1 : constant Node_Id := Left_Opnd  (Parent (N));
6964             Op2 : constant Node_Id := Right_Opnd (Parent (N));
6965             Lhs : constant Node_Id := Name (Parent (Parent (N)));
6966
6967          begin
6968             if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
6969                if N = Op1
6970                  and then Nkind (Op2) = N_Op_Not
6971                then
6972                   --  (not A) op (not B) can be reduced to a single call
6973
6974                   return;
6975
6976                elsif N = Op2
6977                  and then Nkind (Parent (N)) = N_Op_Xor
6978                then
6979                   --  A xor (not B) can also be special-cased
6980
6981                   return;
6982                end if;
6983             end if;
6984          end;
6985       end if;
6986
6987       A := Make_Defining_Identifier (Loc, Name_uA);
6988       B := Make_Defining_Identifier (Loc, Name_uB);
6989       J := Make_Defining_Identifier (Loc, Name_uJ);
6990
6991       A_J :=
6992         Make_Indexed_Component (Loc,
6993           Prefix      => New_Reference_To (A, Loc),
6994           Expressions => New_List (New_Reference_To (J, Loc)));
6995
6996       B_J :=
6997         Make_Indexed_Component (Loc,
6998           Prefix      => New_Reference_To (B, Loc),
6999           Expressions => New_List (New_Reference_To (J, Loc)));
7000
7001       Loop_Statement :=
7002         Make_Implicit_Loop_Statement (N,
7003           Identifier => Empty,
7004
7005           Iteration_Scheme =>
7006             Make_Iteration_Scheme (Loc,
7007               Loop_Parameter_Specification =>
7008                 Make_Loop_Parameter_Specification (Loc,
7009                   Defining_Identifier => J,
7010                   Discrete_Subtype_Definition =>
7011                     Make_Attribute_Reference (Loc,
7012                       Prefix => Make_Identifier (Loc, Chars (A)),
7013                       Attribute_Name => Name_Range))),
7014
7015           Statements => New_List (
7016             Make_Assignment_Statement (Loc,
7017               Name       => B_J,
7018               Expression => Make_Op_Not (Loc, A_J))));
7019
7020       Func_Name := Make_Temporary (Loc, 'N');
7021       Set_Is_Inlined (Func_Name);
7022
7023       Insert_Action (N,
7024         Make_Subprogram_Body (Loc,
7025           Specification =>
7026             Make_Function_Specification (Loc,
7027               Defining_Unit_Name => Func_Name,
7028               Parameter_Specifications => New_List (
7029                 Make_Parameter_Specification (Loc,
7030                   Defining_Identifier => A,
7031                   Parameter_Type      => New_Reference_To (Typ, Loc))),
7032               Result_Definition => New_Reference_To (Typ, Loc)),
7033
7034           Declarations => New_List (
7035             Make_Object_Declaration (Loc,
7036               Defining_Identifier => B,
7037               Object_Definition   => New_Reference_To (Arr, Loc))),
7038
7039           Handled_Statement_Sequence =>
7040             Make_Handled_Sequence_Of_Statements (Loc,
7041               Statements => New_List (
7042                 Loop_Statement,
7043                 Make_Simple_Return_Statement (Loc,
7044                   Expression =>
7045                     Make_Identifier (Loc, Chars (B)))))));
7046
7047       Rewrite (N,
7048         Make_Function_Call (Loc,
7049           Name => New_Reference_To (Func_Name, Loc),
7050           Parameter_Associations => New_List (Opnd)));
7051
7052       Analyze_And_Resolve (N, Typ);
7053    end Expand_N_Op_Not;
7054
7055    --------------------
7056    -- Expand_N_Op_Or --
7057    --------------------
7058
7059    procedure Expand_N_Op_Or (N : Node_Id) is
7060       Typ : constant Entity_Id := Etype (N);
7061
7062    begin
7063       Binary_Op_Validity_Checks (N);
7064
7065       if Is_Array_Type (Etype (N)) then
7066          Expand_Boolean_Operator (N);
7067
7068       elsif Is_Boolean_Type (Etype (N)) then
7069
7070          --  Replace OR by OR ELSE if Short_Circuit_And_Or active and the
7071          --  type is standard Boolean (do not mess with AND that uses a non-
7072          --  standard Boolean type, because something strange is going on).
7073
7074          if Short_Circuit_And_Or and then Typ = Standard_Boolean then
7075             Rewrite (N,
7076               Make_Or_Else (Sloc (N),
7077                 Left_Opnd  => Relocate_Node (Left_Opnd (N)),
7078                 Right_Opnd => Relocate_Node (Right_Opnd (N))));
7079             Analyze_And_Resolve (N, Typ);
7080
7081          --  Otherwise, adjust conditions
7082
7083          else
7084             Adjust_Condition (Left_Opnd (N));
7085             Adjust_Condition (Right_Opnd (N));
7086             Set_Etype (N, Standard_Boolean);
7087             Adjust_Result_Type (N, Typ);
7088          end if;
7089       end if;
7090    end Expand_N_Op_Or;
7091
7092    ----------------------
7093    -- Expand_N_Op_Plus --
7094    ----------------------
7095
7096    procedure Expand_N_Op_Plus (N : Node_Id) is
7097    begin
7098       Unary_Op_Validity_Checks (N);
7099    end Expand_N_Op_Plus;
7100
7101    ---------------------
7102    -- Expand_N_Op_Rem --
7103    ---------------------
7104
7105    procedure Expand_N_Op_Rem (N : Node_Id) is
7106       Loc : constant Source_Ptr := Sloc (N);
7107       Typ : constant Entity_Id  := Etype (N);
7108
7109       Left  : constant Node_Id := Left_Opnd (N);
7110       Right : constant Node_Id := Right_Opnd (N);
7111
7112       Lo : Uint;
7113       Hi : Uint;
7114       OK : Boolean;
7115
7116       Lneg : Boolean;
7117       Rneg : Boolean;
7118       --  Set if corresponding operand can be negative
7119
7120       pragma Unreferenced (Hi);
7121
7122    begin
7123       Binary_Op_Validity_Checks (N);
7124
7125       if Is_Integer_Type (Etype (N)) then
7126          Apply_Divide_Check (N);
7127       end if;
7128
7129       --  Apply optimization x rem 1 = 0. We don't really need that with gcc,
7130       --  but it is useful with other back ends (e.g. AAMP), and is certainly
7131       --  harmless.
7132
7133       if Is_Integer_Type (Etype (N))
7134         and then Compile_Time_Known_Value (Right)
7135         and then Expr_Value (Right) = Uint_1
7136       then
7137          --  Call Remove_Side_Effects to ensure that any side effects in the
7138          --  ignored left operand (in particular function calls to user defined
7139          --  functions) are properly executed.
7140
7141          Remove_Side_Effects (Left);
7142
7143          Rewrite (N, Make_Integer_Literal (Loc, 0));
7144          Analyze_And_Resolve (N, Typ);
7145          return;
7146       end if;
7147
7148       --  Deal with annoying case of largest negative number remainder minus
7149       --  one. Gigi does not handle this case correctly, because it generates
7150       --  a divide instruction which may trap in this case.
7151
7152       --  In fact the check is quite easy, if the right operand is -1, then
7153       --  the remainder is always 0, and we can just ignore the left operand
7154       --  completely in this case.
7155
7156       Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
7157       Lneg := (not OK) or else Lo < 0;
7158
7159       Determine_Range (Left,  OK, Lo, Hi, Assume_Valid => True);
7160       Rneg := (not OK) or else Lo < 0;
7161
7162       --  We won't mess with trying to find out if the left operand can really
7163       --  be the largest negative number (that's a pain in the case of private
7164       --  types and this is really marginal). We will just assume that we need
7165       --  the test if the left operand can be negative at all.
7166
7167       if Lneg and Rneg then
7168          Rewrite (N,
7169            Make_Conditional_Expression (Loc,
7170              Expressions => New_List (
7171                Make_Op_Eq (Loc,
7172                  Left_Opnd => Duplicate_Subexpr (Right),
7173                  Right_Opnd =>
7174                    Unchecked_Convert_To (Typ,
7175                      Make_Integer_Literal (Loc, -1))),
7176
7177                Unchecked_Convert_To (Typ,
7178                  Make_Integer_Literal (Loc, Uint_0)),
7179
7180                Relocate_Node (N))));
7181
7182          Set_Analyzed (Next (Next (First (Expressions (N)))));
7183          Analyze_And_Resolve (N, Typ);
7184       end if;
7185    end Expand_N_Op_Rem;
7186
7187    -----------------------------
7188    -- Expand_N_Op_Rotate_Left --
7189    -----------------------------
7190
7191    procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
7192    begin
7193       Binary_Op_Validity_Checks (N);
7194    end Expand_N_Op_Rotate_Left;
7195
7196    ------------------------------
7197    -- Expand_N_Op_Rotate_Right --
7198    ------------------------------
7199
7200    procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
7201    begin
7202       Binary_Op_Validity_Checks (N);
7203    end Expand_N_Op_Rotate_Right;
7204
7205    ----------------------------
7206    -- Expand_N_Op_Shift_Left --
7207    ----------------------------
7208
7209    procedure Expand_N_Op_Shift_Left (N : Node_Id) is
7210    begin
7211       Binary_Op_Validity_Checks (N);
7212    end Expand_N_Op_Shift_Left;
7213
7214    -----------------------------
7215    -- Expand_N_Op_Shift_Right --
7216    -----------------------------
7217
7218    procedure Expand_N_Op_Shift_Right (N : Node_Id) is
7219    begin
7220       Binary_Op_Validity_Checks (N);
7221    end Expand_N_Op_Shift_Right;
7222
7223    ----------------------------------------
7224    -- Expand_N_Op_Shift_Right_Arithmetic --
7225    ----------------------------------------
7226
7227    procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
7228    begin
7229       Binary_Op_Validity_Checks (N);
7230    end Expand_N_Op_Shift_Right_Arithmetic;
7231
7232    --------------------------
7233    -- Expand_N_Op_Subtract --
7234    --------------------------
7235
7236    procedure Expand_N_Op_Subtract (N : Node_Id) is
7237       Typ : constant Entity_Id := Etype (N);
7238
7239    begin
7240       Binary_Op_Validity_Checks (N);
7241
7242       --  N - 0 = N for integer types
7243
7244       if Is_Integer_Type (Typ)
7245         and then Compile_Time_Known_Value (Right_Opnd (N))
7246         and then Expr_Value (Right_Opnd (N)) = 0
7247       then
7248          Rewrite (N, Left_Opnd (N));
7249          return;
7250       end if;
7251
7252       --  Arithmetic overflow checks for signed integer/fixed point types
7253
7254       if Is_Signed_Integer_Type (Typ)
7255         or else Is_Fixed_Point_Type (Typ)
7256       then
7257          Apply_Arithmetic_Overflow_Check (N);
7258
7259       --  Vax floating-point types case
7260
7261       elsif Vax_Float (Typ) then
7262          Expand_Vax_Arith (N);
7263       end if;
7264    end Expand_N_Op_Subtract;
7265
7266    ---------------------
7267    -- Expand_N_Op_Xor --
7268    ---------------------
7269
7270    procedure Expand_N_Op_Xor (N : Node_Id) is
7271       Typ : constant Entity_Id := Etype (N);
7272
7273    begin
7274       Binary_Op_Validity_Checks (N);
7275
7276       if Is_Array_Type (Etype (N)) then
7277          Expand_Boolean_Operator (N);
7278
7279       elsif Is_Boolean_Type (Etype (N)) then
7280          Adjust_Condition (Left_Opnd (N));
7281          Adjust_Condition (Right_Opnd (N));
7282          Set_Etype (N, Standard_Boolean);
7283          Adjust_Result_Type (N, Typ);
7284       end if;
7285    end Expand_N_Op_Xor;
7286
7287    ----------------------
7288    -- Expand_N_Or_Else --
7289    ----------------------
7290
7291    procedure Expand_N_Or_Else (N : Node_Id)
7292      renames Expand_Short_Circuit_Operator;
7293
7294    -----------------------------------
7295    -- Expand_N_Qualified_Expression --
7296    -----------------------------------
7297
7298    procedure Expand_N_Qualified_Expression (N : Node_Id) is
7299       Operand     : constant Node_Id   := Expression (N);
7300       Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
7301
7302    begin
7303       --  Do validity check if validity checking operands
7304
7305       if Validity_Checks_On
7306         and then Validity_Check_Operands
7307       then
7308          Ensure_Valid (Operand);
7309       end if;
7310
7311       --  Apply possible constraint check
7312
7313       Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
7314
7315       if Do_Range_Check (Operand) then
7316          Set_Do_Range_Check (Operand, False);
7317          Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
7318       end if;
7319    end Expand_N_Qualified_Expression;
7320
7321    ---------------------------------
7322    -- Expand_N_Selected_Component --
7323    ---------------------------------
7324
7325    --  If the selector is a discriminant of a concurrent object, rewrite the
7326    --  prefix to denote the corresponding record type.
7327
7328    procedure Expand_N_Selected_Component (N : Node_Id) is
7329       Loc   : constant Source_Ptr := Sloc (N);
7330       Par   : constant Node_Id    := Parent (N);
7331       P     : constant Node_Id    := Prefix (N);
7332       Ptyp  : Entity_Id           := Underlying_Type (Etype (P));
7333       Disc  : Entity_Id;
7334       New_N : Node_Id;
7335       Dcon  : Elmt_Id;
7336
7337       function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
7338       --  Gigi needs a temporary for prefixes that depend on a discriminant,
7339       --  unless the context of an assignment can provide size information.
7340       --  Don't we have a general routine that does this???
7341
7342       -----------------------
7343       -- In_Left_Hand_Side --
7344       -----------------------
7345
7346       function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
7347       begin
7348          return (Nkind (Parent (Comp)) = N_Assignment_Statement
7349                    and then Comp = Name (Parent (Comp)))
7350            or else (Present (Parent (Comp))
7351                       and then Nkind (Parent (Comp)) in N_Subexpr
7352                       and then In_Left_Hand_Side (Parent (Comp)));
7353       end In_Left_Hand_Side;
7354
7355    --  Start of processing for Expand_N_Selected_Component
7356
7357    begin
7358       --  Insert explicit dereference if required
7359
7360       if Is_Access_Type (Ptyp) then
7361          Insert_Explicit_Dereference (P);
7362          Analyze_And_Resolve (P, Designated_Type (Ptyp));
7363
7364          if Ekind (Etype (P)) = E_Private_Subtype
7365            and then Is_For_Access_Subtype (Etype (P))
7366          then
7367             Set_Etype (P, Base_Type (Etype (P)));
7368          end if;
7369
7370          Ptyp := Etype (P);
7371       end if;
7372
7373       --  Deal with discriminant check required
7374
7375       if Do_Discriminant_Check (N) then
7376
7377          --  Present the discriminant checking function to the backend, so that
7378          --  it can inline the call to the function.
7379
7380          Add_Inlined_Body
7381            (Discriminant_Checking_Func
7382              (Original_Record_Component (Entity (Selector_Name (N)))));
7383
7384          --  Now reset the flag and generate the call
7385
7386          Set_Do_Discriminant_Check (N, False);
7387          Generate_Discriminant_Check (N);
7388       end if;
7389
7390       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
7391       --  function, then additional actuals must be passed.
7392
7393       if Ada_Version >= Ada_05
7394         and then Is_Build_In_Place_Function_Call (P)
7395       then
7396          Make_Build_In_Place_Call_In_Anonymous_Context (P);
7397       end if;
7398
7399       --  Gigi cannot handle unchecked conversions that are the prefix of a
7400       --  selected component with discriminants. This must be checked during
7401       --  expansion, because during analysis the type of the selector is not
7402       --  known at the point the prefix is analyzed. If the conversion is the
7403       --  target of an assignment, then we cannot force the evaluation.
7404
7405       if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
7406         and then Has_Discriminants (Etype (N))
7407         and then not In_Left_Hand_Side (N)
7408       then
7409          Force_Evaluation (Prefix (N));
7410       end if;
7411
7412       --  Remaining processing applies only if selector is a discriminant
7413
7414       if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
7415
7416          --  If the selector is a discriminant of a constrained record type,
7417          --  we may be able to rewrite the expression with the actual value
7418          --  of the discriminant, a useful optimization in some cases.
7419
7420          if Is_Record_Type (Ptyp)
7421            and then Has_Discriminants (Ptyp)
7422            and then Is_Constrained (Ptyp)
7423          then
7424             --  Do this optimization for discrete types only, and not for
7425             --  access types (access discriminants get us into trouble!)
7426
7427             if not Is_Discrete_Type (Etype (N)) then
7428                null;
7429
7430             --  Don't do this on the left hand of an assignment statement.
7431             --  Normally one would think that references like this would
7432             --  not occur, but they do in generated code, and mean that
7433             --  we really do want to assign the discriminant!
7434
7435             elsif Nkind (Par) = N_Assignment_Statement
7436               and then Name (Par) = N
7437             then
7438                null;
7439
7440             --  Don't do this optimization for the prefix of an attribute or
7441             --  the operand of an object renaming declaration since these are
7442             --  contexts where we do not want the value anyway.
7443
7444             elsif (Nkind (Par) = N_Attribute_Reference
7445                      and then Prefix (Par) = N)
7446               or else Is_Renamed_Object (N)
7447             then
7448                null;
7449
7450             --  Don't do this optimization if we are within the code for a
7451             --  discriminant check, since the whole point of such a check may
7452             --  be to verify the condition on which the code below depends!
7453
7454             elsif Is_In_Discriminant_Check (N) then
7455                null;
7456
7457             --  Green light to see if we can do the optimization. There is
7458             --  still one condition that inhibits the optimization below but
7459             --  now is the time to check the particular discriminant.
7460
7461             else
7462                --  Loop through discriminants to find the matching discriminant
7463                --  constraint to see if we can copy it.
7464
7465                Disc := First_Discriminant (Ptyp);
7466                Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
7467                Discr_Loop : while Present (Dcon) loop
7468
7469                   --  Check if this is the matching discriminant
7470
7471                   if Disc = Entity (Selector_Name (N)) then
7472
7473                      --  Here we have the matching discriminant. Check for
7474                      --  the case of a discriminant of a component that is
7475                      --  constrained by an outer discriminant, which cannot
7476                      --  be optimized away.
7477
7478                      if
7479                        Denotes_Discriminant
7480                         (Node (Dcon), Check_Concurrent => True)
7481                      then
7482                         exit Discr_Loop;
7483
7484                      --  In the context of a case statement, the expression may
7485                      --  have the base type of the discriminant, and we need to
7486                      --  preserve the constraint to avoid spurious errors on
7487                      --  missing cases.
7488
7489                      elsif Nkind (Parent (N)) = N_Case_Statement
7490                        and then Etype (Node (Dcon)) /= Etype (Disc)
7491                      then
7492                         Rewrite (N,
7493                           Make_Qualified_Expression (Loc,
7494                             Subtype_Mark =>
7495                               New_Occurrence_Of (Etype (Disc), Loc),
7496                             Expression   =>
7497                               New_Copy_Tree (Node (Dcon))));
7498                         Analyze_And_Resolve (N, Etype (Disc));
7499
7500                         --  In case that comes out as a static expression,
7501                         --  reset it (a selected component is never static).
7502
7503                         Set_Is_Static_Expression (N, False);
7504                         return;
7505
7506                      --  Otherwise we can just copy the constraint, but the
7507                      --  result is certainly not static! In some cases the
7508                      --  discriminant constraint has been analyzed in the
7509                      --  context of the original subtype indication, but for
7510                      --  itypes the constraint might not have been analyzed
7511                      --  yet, and this must be done now.
7512
7513                      else
7514                         Rewrite (N, New_Copy_Tree (Node (Dcon)));
7515                         Analyze_And_Resolve (N);
7516                         Set_Is_Static_Expression (N, False);
7517                         return;
7518                      end if;
7519                   end if;
7520
7521                   Next_Elmt (Dcon);
7522                   Next_Discriminant (Disc);
7523                end loop Discr_Loop;
7524
7525                --  Note: the above loop should always find a matching
7526                --  discriminant, but if it does not, we just missed an
7527                --  optimization due to some glitch (perhaps a previous error),
7528                --  so ignore.
7529
7530             end if;
7531          end if;
7532
7533          --  The only remaining processing is in the case of a discriminant of
7534          --  a concurrent object, where we rewrite the prefix to denote the
7535          --  corresponding record type. If the type is derived and has renamed
7536          --  discriminants, use corresponding discriminant, which is the one
7537          --  that appears in the corresponding record.
7538
7539          if not Is_Concurrent_Type (Ptyp) then
7540             return;
7541          end if;
7542
7543          Disc := Entity (Selector_Name (N));
7544
7545          if Is_Derived_Type (Ptyp)
7546            and then Present (Corresponding_Discriminant (Disc))
7547          then
7548             Disc := Corresponding_Discriminant (Disc);
7549          end if;
7550
7551          New_N :=
7552            Make_Selected_Component (Loc,
7553              Prefix =>
7554                Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
7555                  New_Copy_Tree (P)),
7556              Selector_Name => Make_Identifier (Loc, Chars (Disc)));
7557
7558          Rewrite (N, New_N);
7559          Analyze (N);
7560       end if;
7561    end Expand_N_Selected_Component;
7562
7563    --------------------
7564    -- Expand_N_Slice --
7565    --------------------
7566
7567    procedure Expand_N_Slice (N : Node_Id) is
7568       Loc  : constant Source_Ptr := Sloc (N);
7569       Typ  : constant Entity_Id  := Etype (N);
7570       Pfx  : constant Node_Id    := Prefix (N);
7571       Ptp  : Entity_Id           := Etype (Pfx);
7572
7573       function Is_Procedure_Actual (N : Node_Id) return Boolean;
7574       --  Check whether the argument is an actual for a procedure call, in
7575       --  which case the expansion of a bit-packed slice is deferred until the
7576       --  call itself is expanded. The reason this is required is that we might
7577       --  have an IN OUT or OUT parameter, and the copy out is essential, and
7578       --  that copy out would be missed if we created a temporary here in
7579       --  Expand_N_Slice. Note that we don't bother to test specifically for an
7580       --  IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
7581       --  is harmless to defer expansion in the IN case, since the call
7582       --  processing will still generate the appropriate copy in operation,
7583       --  which will take care of the slice.
7584
7585       procedure Make_Temporary_For_Slice;
7586       --  Create a named variable for the value of the slice, in cases where
7587       --  the back-end cannot handle it properly, e.g. when packed types or
7588       --  unaligned slices are involved.
7589
7590       -------------------------
7591       -- Is_Procedure_Actual --
7592       -------------------------
7593
7594       function Is_Procedure_Actual (N : Node_Id) return Boolean is
7595          Par : Node_Id := Parent (N);
7596
7597       begin
7598          loop
7599             --  If our parent is a procedure call we can return
7600
7601             if Nkind (Par) = N_Procedure_Call_Statement then
7602                return True;
7603
7604             --  If our parent is a type conversion, keep climbing the tree,
7605             --  since a type conversion can be a procedure actual. Also keep
7606             --  climbing if parameter association or a qualified expression,
7607             --  since these are additional cases that do can appear on
7608             --  procedure actuals.
7609
7610             elsif Nkind_In (Par, N_Type_Conversion,
7611                                  N_Parameter_Association,
7612                                  N_Qualified_Expression)
7613             then
7614                Par := Parent (Par);
7615
7616                --  Any other case is not what we are looking for
7617
7618             else
7619                return False;
7620             end if;
7621          end loop;
7622       end Is_Procedure_Actual;
7623
7624       ------------------------------
7625       -- Make_Temporary_For_Slice --
7626       ------------------------------
7627
7628       procedure Make_Temporary_For_Slice is
7629          Decl : Node_Id;
7630          Ent  : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7631       begin
7632          Decl :=
7633            Make_Object_Declaration (Loc,
7634              Defining_Identifier => Ent,
7635              Object_Definition   => New_Occurrence_Of (Typ, Loc));
7636
7637          Set_No_Initialization (Decl);
7638
7639          Insert_Actions (N, New_List (
7640            Decl,
7641            Make_Assignment_Statement (Loc,
7642              Name => New_Occurrence_Of (Ent, Loc),
7643              Expression => Relocate_Node (N))));
7644
7645          Rewrite (N, New_Occurrence_Of (Ent, Loc));
7646          Analyze_And_Resolve (N, Typ);
7647       end Make_Temporary_For_Slice;
7648
7649    --  Start of processing for Expand_N_Slice
7650
7651    begin
7652       --  Special handling for access types
7653
7654       if Is_Access_Type (Ptp) then
7655
7656          Ptp := Designated_Type (Ptp);
7657
7658          Rewrite (Pfx,
7659            Make_Explicit_Dereference (Sloc (N),
7660             Prefix => Relocate_Node (Pfx)));
7661
7662          Analyze_And_Resolve (Pfx, Ptp);
7663       end if;
7664
7665       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
7666       --  function, then additional actuals must be passed.
7667
7668       if Ada_Version >= Ada_05
7669         and then Is_Build_In_Place_Function_Call (Pfx)
7670       then
7671          Make_Build_In_Place_Call_In_Anonymous_Context (Pfx);
7672       end if;
7673
7674       --  The remaining case to be handled is packed slices. We can leave
7675       --  packed slices as they are in the following situations:
7676
7677       --    1. Right or left side of an assignment (we can handle this
7678       --       situation correctly in the assignment statement expansion).
7679
7680       --    2. Prefix of indexed component (the slide is optimized away in this
7681       --       case, see the start of Expand_N_Slice.)
7682
7683       --    3. Object renaming declaration, since we want the name of the
7684       --       slice, not the value.
7685
7686       --    4. Argument to procedure call, since copy-in/copy-out handling may
7687       --       be required, and this is handled in the expansion of call
7688       --       itself.
7689
7690       --    5. Prefix of an address attribute (this is an error which is caught
7691       --       elsewhere, and the expansion would interfere with generating the
7692       --       error message).
7693
7694       if not Is_Packed (Typ) then
7695
7696          --  Apply transformation for actuals of a function call, where
7697          --  Expand_Actuals is not used.
7698
7699          if Nkind (Parent (N)) = N_Function_Call
7700            and then Is_Possibly_Unaligned_Slice (N)
7701          then
7702             Make_Temporary_For_Slice;
7703          end if;
7704
7705       elsif Nkind (Parent (N)) = N_Assignment_Statement
7706         or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
7707                    and then Parent (N) = Name (Parent (Parent (N))))
7708       then
7709          return;
7710
7711       elsif Nkind (Parent (N)) = N_Indexed_Component
7712         or else Is_Renamed_Object (N)
7713         or else Is_Procedure_Actual (N)
7714       then
7715          return;
7716
7717       elsif Nkind (Parent (N)) = N_Attribute_Reference
7718         and then Attribute_Name (Parent (N)) = Name_Address
7719       then
7720          return;
7721
7722       else
7723          Make_Temporary_For_Slice;
7724       end if;
7725    end Expand_N_Slice;
7726
7727    ------------------------------
7728    -- Expand_N_Type_Conversion --
7729    ------------------------------
7730
7731    procedure Expand_N_Type_Conversion (N : Node_Id) is
7732       Loc          : constant Source_Ptr := Sloc (N);
7733       Operand      : constant Node_Id    := Expression (N);
7734       Target_Type  : constant Entity_Id  := Etype (N);
7735       Operand_Type : Entity_Id           := Etype (Operand);
7736
7737       procedure Handle_Changed_Representation;
7738       --  This is called in the case of record and array type conversions to
7739       --  see if there is a change of representation to be handled. Change of
7740       --  representation is actually handled at the assignment statement level,
7741       --  and what this procedure does is rewrite node N conversion as an
7742       --  assignment to temporary. If there is no change of representation,
7743       --  then the conversion node is unchanged.
7744
7745       procedure Raise_Accessibility_Error;
7746       --  Called when we know that an accessibility check will fail. Rewrites
7747       --  node N to an appropriate raise statement and outputs warning msgs.
7748       --  The Etype of the raise node is set to Target_Type.
7749
7750       procedure Real_Range_Check;
7751       --  Handles generation of range check for real target value
7752
7753       -----------------------------------
7754       -- Handle_Changed_Representation --
7755       -----------------------------------
7756
7757       procedure Handle_Changed_Representation is
7758          Temp : Entity_Id;
7759          Decl : Node_Id;
7760          Odef : Node_Id;
7761          Disc : Node_Id;
7762          N_Ix : Node_Id;
7763          Cons : List_Id;
7764
7765       begin
7766
7767          --  Nothing else to do if no change of representation
7768
7769          if Same_Representation (Operand_Type, Target_Type) then
7770             return;
7771
7772          --  The real change of representation work is done by the assignment
7773          --  statement processing. So if this type conversion is appearing as
7774          --  the expression of an assignment statement, nothing needs to be
7775          --  done to the conversion.
7776
7777          elsif Nkind (Parent (N)) = N_Assignment_Statement then
7778             return;
7779
7780          --  Otherwise we need to generate a temporary variable, and do the
7781          --  change of representation assignment into that temporary variable.
7782          --  The conversion is then replaced by a reference to this variable.
7783
7784          else
7785             Cons := No_List;
7786
7787             --  If type is unconstrained we have to add a constraint, copied
7788             --  from the actual value of the left hand side.
7789
7790             if not Is_Constrained (Target_Type) then
7791                if Has_Discriminants (Operand_Type) then
7792                   Disc := First_Discriminant (Operand_Type);
7793
7794                   if Disc /= First_Stored_Discriminant (Operand_Type) then
7795                      Disc := First_Stored_Discriminant (Operand_Type);
7796                   end if;
7797
7798                   Cons := New_List;
7799                   while Present (Disc) loop
7800                      Append_To (Cons,
7801                        Make_Selected_Component (Loc,
7802                          Prefix => Duplicate_Subexpr_Move_Checks (Operand),
7803                          Selector_Name =>
7804                            Make_Identifier (Loc, Chars (Disc))));
7805                      Next_Discriminant (Disc);
7806                   end loop;
7807
7808                elsif Is_Array_Type (Operand_Type) then
7809                   N_Ix := First_Index (Target_Type);
7810                   Cons := New_List;
7811
7812                   for J in 1 .. Number_Dimensions (Operand_Type) loop
7813
7814                      --  We convert the bounds explicitly. We use an unchecked
7815                      --  conversion because bounds checks are done elsewhere.
7816
7817                      Append_To (Cons,
7818                        Make_Range (Loc,
7819                          Low_Bound =>
7820                            Unchecked_Convert_To (Etype (N_Ix),
7821                              Make_Attribute_Reference (Loc,
7822                                Prefix =>
7823                                  Duplicate_Subexpr_No_Checks
7824                                    (Operand, Name_Req => True),
7825                                Attribute_Name => Name_First,
7826                                Expressions    => New_List (
7827                                  Make_Integer_Literal (Loc, J)))),
7828
7829                          High_Bound =>
7830                            Unchecked_Convert_To (Etype (N_Ix),
7831                              Make_Attribute_Reference (Loc,
7832                                Prefix =>
7833                                  Duplicate_Subexpr_No_Checks
7834                                    (Operand, Name_Req => True),
7835                                Attribute_Name => Name_Last,
7836                                Expressions    => New_List (
7837                                  Make_Integer_Literal (Loc, J))))));
7838
7839                      Next_Index (N_Ix);
7840                   end loop;
7841                end if;
7842             end if;
7843
7844             Odef := New_Occurrence_Of (Target_Type, Loc);
7845
7846             if Present (Cons) then
7847                Odef :=
7848                  Make_Subtype_Indication (Loc,
7849                    Subtype_Mark => Odef,
7850                    Constraint =>
7851                      Make_Index_Or_Discriminant_Constraint (Loc,
7852                        Constraints => Cons));
7853             end if;
7854
7855             Temp := Make_Temporary (Loc, 'C');
7856             Decl :=
7857               Make_Object_Declaration (Loc,
7858                 Defining_Identifier => Temp,
7859                 Object_Definition   => Odef);
7860
7861             Set_No_Initialization (Decl, True);
7862
7863             --  Insert required actions. It is essential to suppress checks
7864             --  since we have suppressed default initialization, which means
7865             --  that the variable we create may have no discriminants.
7866
7867             Insert_Actions (N,
7868               New_List (
7869                 Decl,
7870                 Make_Assignment_Statement (Loc,
7871                   Name => New_Occurrence_Of (Temp, Loc),
7872                   Expression => Relocate_Node (N))),
7873                 Suppress => All_Checks);
7874
7875             Rewrite (N, New_Occurrence_Of (Temp, Loc));
7876             return;
7877          end if;
7878       end Handle_Changed_Representation;
7879
7880       -------------------------------
7881       -- Raise_Accessibility_Error --
7882       -------------------------------
7883
7884       procedure Raise_Accessibility_Error is
7885       begin
7886          Rewrite (N,
7887            Make_Raise_Program_Error (Sloc (N),
7888              Reason => PE_Accessibility_Check_Failed));
7889          Set_Etype (N, Target_Type);
7890
7891          Error_Msg_N ("?accessibility check failure", N);
7892          Error_Msg_NE
7893            ("\?& will be raised at run time", N, Standard_Program_Error);
7894       end Raise_Accessibility_Error;
7895
7896       ----------------------
7897       -- Real_Range_Check --
7898       ----------------------
7899
7900       --  Case of conversions to floating-point or fixed-point. If range checks
7901       --  are enabled and the target type has a range constraint, we convert:
7902
7903       --     typ (x)
7904
7905       --       to
7906
7907       --     Tnn : typ'Base := typ'Base (x);
7908       --     [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
7909       --     Tnn
7910
7911       --  This is necessary when there is a conversion of integer to float or
7912       --  to fixed-point to ensure that the correct checks are made. It is not
7913       --  necessary for float to float where it is enough to simply set the
7914       --  Do_Range_Check flag.
7915
7916       procedure Real_Range_Check is
7917          Btyp : constant Entity_Id := Base_Type (Target_Type);
7918          Lo   : constant Node_Id   := Type_Low_Bound  (Target_Type);
7919          Hi   : constant Node_Id   := Type_High_Bound (Target_Type);
7920          Xtyp : constant Entity_Id := Etype (Operand);
7921          Conv : Node_Id;
7922          Tnn  : Entity_Id;
7923
7924       begin
7925          --  Nothing to do if conversion was rewritten
7926
7927          if Nkind (N) /= N_Type_Conversion then
7928             return;
7929          end if;
7930
7931          --  Nothing to do if range checks suppressed, or target has the same
7932          --  range as the base type (or is the base type).
7933
7934          if Range_Checks_Suppressed (Target_Type)
7935            or else (Lo = Type_Low_Bound (Btyp)
7936                       and then
7937                     Hi = Type_High_Bound (Btyp))
7938          then
7939             return;
7940          end if;
7941
7942          --  Nothing to do if expression is an entity on which checks have been
7943          --  suppressed.
7944
7945          if Is_Entity_Name (Operand)
7946            and then Range_Checks_Suppressed (Entity (Operand))
7947          then
7948             return;
7949          end if;
7950
7951          --  Nothing to do if bounds are all static and we can tell that the
7952          --  expression is within the bounds of the target. Note that if the
7953          --  operand is of an unconstrained floating-point type, then we do
7954          --  not trust it to be in range (might be infinite)
7955
7956          declare
7957             S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
7958             S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
7959
7960          begin
7961             if (not Is_Floating_Point_Type (Xtyp)
7962                  or else Is_Constrained (Xtyp))
7963               and then Compile_Time_Known_Value (S_Lo)
7964               and then Compile_Time_Known_Value (S_Hi)
7965               and then Compile_Time_Known_Value (Hi)
7966               and then Compile_Time_Known_Value (Lo)
7967             then
7968                declare
7969                   D_Lov : constant Ureal := Expr_Value_R (Lo);
7970                   D_Hiv : constant Ureal := Expr_Value_R (Hi);
7971                   S_Lov : Ureal;
7972                   S_Hiv : Ureal;
7973
7974                begin
7975                   if Is_Real_Type (Xtyp) then
7976                      S_Lov := Expr_Value_R (S_Lo);
7977                      S_Hiv := Expr_Value_R (S_Hi);
7978                   else
7979                      S_Lov := UR_From_Uint (Expr_Value (S_Lo));
7980                      S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
7981                   end if;
7982
7983                   if D_Hiv > D_Lov
7984                     and then S_Lov >= D_Lov
7985                     and then S_Hiv <= D_Hiv
7986                   then
7987                      Set_Do_Range_Check (Operand, False);
7988                      return;
7989                   end if;
7990                end;
7991             end if;
7992          end;
7993
7994          --  For float to float conversions, we are done
7995
7996          if Is_Floating_Point_Type (Xtyp)
7997               and then
7998             Is_Floating_Point_Type (Btyp)
7999          then
8000             return;
8001          end if;
8002
8003          --  Otherwise rewrite the conversion as described above
8004
8005          Conv := Relocate_Node (N);
8006          Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
8007          Set_Etype (Conv, Btyp);
8008
8009          --  Enable overflow except for case of integer to float conversions,
8010          --  where it is never required, since we can never have overflow in
8011          --  this case.
8012
8013          if not Is_Integer_Type (Etype (Operand)) then
8014             Enable_Overflow_Check (Conv);
8015          end if;
8016
8017          Tnn := Make_Temporary (Loc, 'T', Conv);
8018
8019          Insert_Actions (N, New_List (
8020            Make_Object_Declaration (Loc,
8021              Defining_Identifier => Tnn,
8022              Object_Definition   => New_Occurrence_Of (Btyp, Loc),
8023              Expression => Conv),
8024
8025            Make_Raise_Constraint_Error (Loc,
8026              Condition =>
8027               Make_Or_Else (Loc,
8028                 Left_Opnd =>
8029                   Make_Op_Lt (Loc,
8030                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
8031                     Right_Opnd =>
8032                       Make_Attribute_Reference (Loc,
8033                         Attribute_Name => Name_First,
8034                         Prefix =>
8035                           New_Occurrence_Of (Target_Type, Loc))),
8036
8037                 Right_Opnd =>
8038                   Make_Op_Gt (Loc,
8039                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
8040                     Right_Opnd =>
8041                       Make_Attribute_Reference (Loc,
8042                         Attribute_Name => Name_Last,
8043                         Prefix =>
8044                           New_Occurrence_Of (Target_Type, Loc)))),
8045              Reason => CE_Range_Check_Failed)));
8046
8047          Rewrite (N, New_Occurrence_Of (Tnn, Loc));
8048          Analyze_And_Resolve (N, Btyp);
8049       end Real_Range_Check;
8050
8051    --  Start of processing for Expand_N_Type_Conversion
8052
8053    begin
8054       --  Nothing at all to do if conversion is to the identical type so remove
8055       --  the conversion completely, it is useless, except that it may carry
8056       --  an Assignment_OK attribute, which must be propagated to the operand.
8057
8058       if Operand_Type = Target_Type then
8059          if Assignment_OK (N) then
8060             Set_Assignment_OK (Operand);
8061          end if;
8062
8063          Rewrite (N, Relocate_Node (Operand));
8064          return;
8065       end if;
8066
8067       --  Nothing to do if this is the second argument of read. This is a
8068       --  "backwards" conversion that will be handled by the specialized code
8069       --  in attribute processing.
8070
8071       if Nkind (Parent (N)) = N_Attribute_Reference
8072         and then Attribute_Name (Parent (N)) = Name_Read
8073         and then Next (First (Expressions (Parent (N)))) = N
8074       then
8075          return;
8076       end if;
8077
8078       --  Here if we may need to expand conversion
8079
8080       --  If the operand of the type conversion is an arithmetic operation on
8081       --  signed integers, and the based type of the signed integer type in
8082       --  question is smaller than Standard.Integer, we promote both of the
8083       --  operands to type Integer.
8084
8085       --  For example, if we have
8086
8087       --     target-type (opnd1 + opnd2)
8088
8089       --  and opnd1 and opnd2 are of type short integer, then we rewrite
8090       --  this as:
8091
8092       --     target-type (integer(opnd1) + integer(opnd2))
8093
8094       --  We do this because we are always allowed to compute in a larger type
8095       --  if we do the right thing with the result, and in this case we are
8096       --  going to do a conversion which will do an appropriate check to make
8097       --  sure that things are in range of the target type in any case. This
8098       --  avoids some unnecessary intermediate overflows.
8099
8100       --  We might consider a similar transformation in the case where the
8101       --  target is a real type or a 64-bit integer type, and the operand
8102       --  is an arithmetic operation using a 32-bit integer type. However,
8103       --  we do not bother with this case, because it could cause significant
8104       --  ineffiencies on 32-bit machines. On a 64-bit machine it would be
8105       --  much cheaper, but we don't want different behavior on 32-bit and
8106       --  64-bit machines. Note that the exclusion of the 64-bit case also
8107       --  handles the configurable run-time cases where 64-bit arithmetic
8108       --  may simply be unavailable.
8109
8110       --  Note: this circuit is partially redundant with respect to the circuit
8111       --  in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
8112       --  the processing here. Also we still need the Checks circuit, since we
8113       --  have to be sure not to generate junk overflow checks in the first
8114       --  place, since it would be trick to remove them here!
8115
8116       if Integer_Promotion_Possible (N) then
8117
8118          --  All conditions met, go ahead with transformation
8119
8120          declare
8121             Opnd : Node_Id;
8122             L, R : Node_Id;
8123
8124          begin
8125             R :=
8126               Make_Type_Conversion (Loc,
8127                 Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
8128                 Expression   => Relocate_Node (Right_Opnd (Operand)));
8129
8130             Opnd := New_Op_Node (Nkind (Operand), Loc);
8131             Set_Right_Opnd (Opnd, R);
8132
8133             if Nkind (Operand) in N_Binary_Op then
8134                L :=
8135                  Make_Type_Conversion (Loc,
8136                    Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
8137                    Expression   => Relocate_Node (Left_Opnd (Operand)));
8138
8139                Set_Left_Opnd  (Opnd, L);
8140             end if;
8141
8142             Rewrite (N,
8143               Make_Type_Conversion (Loc,
8144                 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
8145                 Expression   => Opnd));
8146
8147             Analyze_And_Resolve (N, Target_Type);
8148             return;
8149          end;
8150       end if;
8151
8152       --  Do validity check if validity checking operands
8153
8154       if Validity_Checks_On
8155         and then Validity_Check_Operands
8156       then
8157          Ensure_Valid (Operand);
8158       end if;
8159
8160       --  Special case of converting from non-standard boolean type
8161
8162       if Is_Boolean_Type (Operand_Type)
8163         and then (Nonzero_Is_True (Operand_Type))
8164       then
8165          Adjust_Condition (Operand);
8166          Set_Etype (Operand, Standard_Boolean);
8167          Operand_Type := Standard_Boolean;
8168       end if;
8169
8170       --  Case of converting to an access type
8171
8172       if Is_Access_Type (Target_Type) then
8173
8174          --  Apply an accessibility check when the conversion operand is an
8175          --  access parameter (or a renaming thereof), unless conversion was
8176          --  expanded from an Unchecked_ or Unrestricted_Access attribute.
8177          --  Note that other checks may still need to be applied below (such
8178          --  as tagged type checks).
8179
8180          if Is_Entity_Name (Operand)
8181            and then
8182              (Is_Formal (Entity (Operand))
8183                or else
8184                  (Present (Renamed_Object (Entity (Operand)))
8185                    and then Is_Entity_Name (Renamed_Object (Entity (Operand)))
8186                    and then Is_Formal
8187                               (Entity (Renamed_Object (Entity (Operand))))))
8188            and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
8189            and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
8190                       or else Attribute_Name (Original_Node (N)) = Name_Access)
8191          then
8192             Apply_Accessibility_Check
8193               (Operand, Target_Type, Insert_Node => Operand);
8194
8195          --  If the level of the operand type is statically deeper than the
8196          --  level of the target type, then force Program_Error. Note that this
8197          --  can only occur for cases where the attribute is within the body of
8198          --  an instantiation (otherwise the conversion will already have been
8199          --  rejected as illegal). Note: warnings are issued by the analyzer
8200          --  for the instance cases.
8201
8202          elsif In_Instance_Body
8203            and then Type_Access_Level (Operand_Type) >
8204                     Type_Access_Level (Target_Type)
8205          then
8206             Raise_Accessibility_Error;
8207
8208          --  When the operand is a selected access discriminant the check needs
8209          --  to be made against the level of the object denoted by the prefix
8210          --  of the selected name. Force Program_Error for this case as well
8211          --  (this accessibility violation can only happen if within the body
8212          --  of an instantiation).
8213
8214          elsif In_Instance_Body
8215            and then Ekind (Operand_Type) = E_Anonymous_Access_Type
8216            and then Nkind (Operand) = N_Selected_Component
8217            and then Object_Access_Level (Operand) >
8218                       Type_Access_Level (Target_Type)
8219          then
8220             Raise_Accessibility_Error;
8221             return;
8222          end if;
8223       end if;
8224
8225       --  Case of conversions of tagged types and access to tagged types
8226
8227       --  When needed, that is to say when the expression is class-wide, Add
8228       --  runtime a tag check for (strict) downward conversion by using the
8229       --  membership test, generating:
8230
8231       --      [constraint_error when Operand not in Target_Type'Class]
8232
8233       --  or in the access type case
8234
8235       --      [constraint_error
8236       --        when Operand /= null
8237       --          and then Operand.all not in
8238       --            Designated_Type (Target_Type)'Class]
8239
8240       if (Is_Access_Type (Target_Type)
8241            and then Is_Tagged_Type (Designated_Type (Target_Type)))
8242         or else Is_Tagged_Type (Target_Type)
8243       then
8244          --  Do not do any expansion in the access type case if the parent is a
8245          --  renaming, since this is an error situation which will be caught by
8246          --  Sem_Ch8, and the expansion can interfere with this error check.
8247
8248          if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
8249             return;
8250          end if;
8251
8252          --  Otherwise, proceed with processing tagged conversion
8253
8254          Tagged_Conversion : declare
8255             Actual_Op_Typ   : Entity_Id;
8256             Actual_Targ_Typ : Entity_Id;
8257             Make_Conversion : Boolean := False;
8258             Root_Op_Typ     : Entity_Id;
8259
8260             procedure Make_Tag_Check (Targ_Typ : Entity_Id);
8261             --  Create a membership check to test whether Operand is a member
8262             --  of Targ_Typ. If the original Target_Type is an access, include
8263             --  a test for null value. The check is inserted at N.
8264
8265             --------------------
8266             -- Make_Tag_Check --
8267             --------------------
8268
8269             procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
8270                Cond : Node_Id;
8271
8272             begin
8273                --  Generate:
8274                --    [Constraint_Error
8275                --       when Operand /= null
8276                --         and then Operand.all not in Targ_Typ]
8277
8278                if Is_Access_Type (Target_Type) then
8279                   Cond :=
8280                     Make_And_Then (Loc,
8281                       Left_Opnd =>
8282                         Make_Op_Ne (Loc,
8283                           Left_Opnd  => Duplicate_Subexpr_No_Checks (Operand),
8284                           Right_Opnd => Make_Null (Loc)),
8285
8286                       Right_Opnd =>
8287                         Make_Not_In (Loc,
8288                           Left_Opnd  =>
8289                             Make_Explicit_Dereference (Loc,
8290                               Prefix => Duplicate_Subexpr_No_Checks (Operand)),
8291                           Right_Opnd => New_Reference_To (Targ_Typ, Loc)));
8292
8293                --  Generate:
8294                --    [Constraint_Error when Operand not in Targ_Typ]
8295
8296                else
8297                   Cond :=
8298                     Make_Not_In (Loc,
8299                       Left_Opnd  => Duplicate_Subexpr_No_Checks (Operand),
8300                       Right_Opnd => New_Reference_To (Targ_Typ, Loc));
8301                end if;
8302
8303                Insert_Action (N,
8304                  Make_Raise_Constraint_Error (Loc,
8305                    Condition => Cond,
8306                    Reason    => CE_Tag_Check_Failed));
8307             end Make_Tag_Check;
8308
8309          --  Start of processing for Tagged_Conversion
8310
8311          begin
8312             if Is_Access_Type (Target_Type) then
8313
8314                --  Handle entities from the limited view
8315
8316                Actual_Op_Typ :=
8317                  Available_View (Designated_Type (Operand_Type));
8318                Actual_Targ_Typ :=
8319                  Available_View (Designated_Type (Target_Type));
8320             else
8321                Actual_Op_Typ   := Operand_Type;
8322                Actual_Targ_Typ := Target_Type;
8323             end if;
8324
8325             Root_Op_Typ := Root_Type (Actual_Op_Typ);
8326
8327             --  Ada 2005 (AI-251): Handle interface type conversion
8328
8329             if Is_Interface (Actual_Op_Typ) then
8330                Expand_Interface_Conversion (N, Is_Static => False);
8331                return;
8332             end if;
8333
8334             if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
8335
8336                --  Create a runtime tag check for a downward class-wide type
8337                --  conversion.
8338
8339                if Is_Class_Wide_Type (Actual_Op_Typ)
8340                  and then Actual_Op_Typ /= Actual_Targ_Typ
8341                  and then Root_Op_Typ /= Actual_Targ_Typ
8342                  and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ)
8343                then
8344                   Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
8345                   Make_Conversion := True;
8346                end if;
8347
8348                --  AI05-0073: If the result subtype of the function is defined
8349                --  by an access_definition designating a specific tagged type
8350                --  T, a check is made that the result value is null or the tag
8351                --  of the object designated by the result value identifies T.
8352                --  Constraint_Error is raised if this check fails.
8353
8354                if Nkind (Parent (N)) = Sinfo.N_Return_Statement then
8355                   declare
8356                      Func     : Entity_Id;
8357                      Func_Typ : Entity_Id;
8358
8359                   begin
8360                      --  Climb scope stack looking for the enclosing function
8361
8362                      Func := Current_Scope;
8363                      while Present (Func)
8364                        and then Ekind (Func) /= E_Function
8365                      loop
8366                         Func := Scope (Func);
8367                      end loop;
8368
8369                      --  The function's return subtype must be defined using
8370                      --  an access definition.
8371
8372                      if Nkind (Result_Definition (Parent (Func))) =
8373                           N_Access_Definition
8374                      then
8375                         Func_Typ := Directly_Designated_Type (Etype (Func));
8376
8377                         --  The return subtype denotes a specific tagged type,
8378                         --  in other words, a non class-wide type.
8379
8380                         if Is_Tagged_Type (Func_Typ)
8381                           and then not Is_Class_Wide_Type (Func_Typ)
8382                         then
8383                            Make_Tag_Check (Actual_Targ_Typ);
8384                            Make_Conversion := True;
8385                         end if;
8386                      end if;
8387                   end;
8388                end if;
8389
8390                --  We have generated a tag check for either a class-wide type
8391                --  conversion or for AI05-0073.
8392
8393                if Make_Conversion then
8394                   declare
8395                      Conv : Node_Id;
8396                   begin
8397                      Conv :=
8398                        Make_Unchecked_Type_Conversion (Loc,
8399                          Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
8400                          Expression   => Relocate_Node (Expression (N)));
8401                      Rewrite (N, Conv);
8402                      Analyze_And_Resolve (N, Target_Type);
8403                   end;
8404                end if;
8405             end if;
8406          end Tagged_Conversion;
8407
8408       --  Case of other access type conversions
8409
8410       elsif Is_Access_Type (Target_Type) then
8411          Apply_Constraint_Check (Operand, Target_Type);
8412
8413       --  Case of conversions from a fixed-point type
8414
8415       --  These conversions require special expansion and processing, found in
8416       --  the Exp_Fixd package. We ignore cases where Conversion_OK is set,
8417       --  since from a semantic point of view, these are simple integer
8418       --  conversions, which do not need further processing.
8419
8420       elsif Is_Fixed_Point_Type (Operand_Type)
8421         and then not Conversion_OK (N)
8422       then
8423          --  We should never see universal fixed at this case, since the
8424          --  expansion of the constituent divide or multiply should have
8425          --  eliminated the explicit mention of universal fixed.
8426
8427          pragma Assert (Operand_Type /= Universal_Fixed);
8428
8429          --  Check for special case of the conversion to universal real that
8430          --  occurs as a result of the use of a round attribute. In this case,
8431          --  the real type for the conversion is taken from the target type of
8432          --  the Round attribute and the result must be marked as rounded.
8433
8434          if Target_Type = Universal_Real
8435            and then Nkind (Parent (N)) = N_Attribute_Reference
8436            and then Attribute_Name (Parent (N)) = Name_Round
8437          then
8438             Set_Rounded_Result (N);
8439             Set_Etype (N, Etype (Parent (N)));
8440          end if;
8441
8442          --  Otherwise do correct fixed-conversion, but skip these if the
8443          --  Conversion_OK flag is set, because from a semantic point of view
8444          --  these are simple integer conversions needing no further processing
8445          --  (the backend will simply treat them as integers).
8446
8447          if not Conversion_OK (N) then
8448             if Is_Fixed_Point_Type (Etype (N)) then
8449                Expand_Convert_Fixed_To_Fixed (N);
8450                Real_Range_Check;
8451
8452             elsif Is_Integer_Type (Etype (N)) then
8453                Expand_Convert_Fixed_To_Integer (N);
8454
8455             else
8456                pragma Assert (Is_Floating_Point_Type (Etype (N)));
8457                Expand_Convert_Fixed_To_Float (N);
8458                Real_Range_Check;
8459             end if;
8460          end if;
8461
8462       --  Case of conversions to a fixed-point type
8463
8464       --  These conversions require special expansion and processing, found in
8465       --  the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
8466       --  since from a semantic point of view, these are simple integer
8467       --  conversions, which do not need further processing.
8468
8469       elsif Is_Fixed_Point_Type (Target_Type)
8470         and then not Conversion_OK (N)
8471       then
8472          if Is_Integer_Type (Operand_Type) then
8473             Expand_Convert_Integer_To_Fixed (N);
8474             Real_Range_Check;
8475          else
8476             pragma Assert (Is_Floating_Point_Type (Operand_Type));
8477             Expand_Convert_Float_To_Fixed (N);
8478             Real_Range_Check;
8479          end if;
8480
8481       --  Case of float-to-integer conversions
8482
8483       --  We also handle float-to-fixed conversions with Conversion_OK set
8484       --  since semantically the fixed-point target is treated as though it
8485       --  were an integer in such cases.
8486
8487       elsif Is_Floating_Point_Type (Operand_Type)
8488         and then
8489           (Is_Integer_Type (Target_Type)
8490             or else
8491           (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
8492       then
8493          --  One more check here, gcc is still not able to do conversions of
8494          --  this type with proper overflow checking, and so gigi is doing an
8495          --  approximation of what is required by doing floating-point compares
8496          --  with the end-point. But that can lose precision in some cases, and
8497          --  give a wrong result. Converting the operand to Universal_Real is
8498          --  helpful, but still does not catch all cases with 64-bit integers
8499          --  on targets with only 64-bit floats.
8500
8501          --  The above comment seems obsoleted by Apply_Float_Conversion_Check
8502          --  Can this code be removed ???
8503
8504          if Do_Range_Check (Operand) then
8505             Rewrite (Operand,
8506               Make_Type_Conversion (Loc,
8507                 Subtype_Mark =>
8508                   New_Occurrence_Of (Universal_Real, Loc),
8509                 Expression =>
8510                   Relocate_Node (Operand)));
8511
8512             Set_Etype (Operand, Universal_Real);
8513             Enable_Range_Check (Operand);
8514             Set_Do_Range_Check (Expression (Operand), False);
8515          end if;
8516
8517       --  Case of array conversions
8518
8519       --  Expansion of array conversions, add required length/range checks but
8520       --  only do this if there is no change of representation. For handling of
8521       --  this case, see Handle_Changed_Representation.
8522
8523       elsif Is_Array_Type (Target_Type) then
8524
8525          if Is_Constrained (Target_Type) then
8526             Apply_Length_Check (Operand, Target_Type);
8527          else
8528             Apply_Range_Check (Operand, Target_Type);
8529          end if;
8530
8531          Handle_Changed_Representation;
8532
8533       --  Case of conversions of discriminated types
8534
8535       --  Add required discriminant checks if target is constrained. Again this
8536       --  change is skipped if we have a change of representation.
8537
8538       elsif Has_Discriminants (Target_Type)
8539         and then Is_Constrained (Target_Type)
8540       then
8541          Apply_Discriminant_Check (Operand, Target_Type);
8542          Handle_Changed_Representation;
8543
8544       --  Case of all other record conversions. The only processing required
8545       --  is to check for a change of representation requiring the special
8546       --  assignment processing.
8547
8548       elsif Is_Record_Type (Target_Type) then
8549
8550          --  Ada 2005 (AI-216): Program_Error is raised when converting from
8551          --  a derived Unchecked_Union type to an unconstrained type that is
8552          --  not Unchecked_Union if the operand lacks inferable discriminants.
8553
8554          if Is_Derived_Type (Operand_Type)
8555            and then Is_Unchecked_Union (Base_Type (Operand_Type))
8556            and then not Is_Constrained (Target_Type)
8557            and then not Is_Unchecked_Union (Base_Type (Target_Type))
8558            and then not Has_Inferable_Discriminants (Operand)
8559          then
8560             --  To prevent Gigi from generating illegal code, we generate a
8561             --  Program_Error node, but we give it the target type of the
8562             --  conversion.
8563
8564             declare
8565                PE : constant Node_Id := Make_Raise_Program_Error (Loc,
8566                       Reason => PE_Unchecked_Union_Restriction);
8567
8568             begin
8569                Set_Etype (PE, Target_Type);
8570                Rewrite (N, PE);
8571
8572             end;
8573          else
8574             Handle_Changed_Representation;
8575          end if;
8576
8577       --  Case of conversions of enumeration types
8578
8579       elsif Is_Enumeration_Type (Target_Type) then
8580
8581          --  Special processing is required if there is a change of
8582          --  representation (from enumeration representation clauses).
8583
8584          if not Same_Representation (Target_Type, Operand_Type) then
8585
8586             --  Convert: x(y) to x'val (ytyp'val (y))
8587
8588             Rewrite (N,
8589                Make_Attribute_Reference (Loc,
8590                  Prefix => New_Occurrence_Of (Target_Type, Loc),
8591                  Attribute_Name => Name_Val,
8592                  Expressions => New_List (
8593                    Make_Attribute_Reference (Loc,
8594                      Prefix => New_Occurrence_Of (Operand_Type, Loc),
8595                      Attribute_Name => Name_Pos,
8596                      Expressions => New_List (Operand)))));
8597
8598             Analyze_And_Resolve (N, Target_Type);
8599          end if;
8600
8601       --  Case of conversions to floating-point
8602
8603       elsif Is_Floating_Point_Type (Target_Type) then
8604          Real_Range_Check;
8605       end if;
8606
8607       --  At this stage, either the conversion node has been transformed into
8608       --  some other equivalent expression, or left as a conversion that can be
8609       --  handled by Gigi, in the following cases:
8610
8611       --    Conversions with no change of representation or type
8612
8613       --    Numeric conversions involving integer, floating- and fixed-point
8614       --    values. Fixed-point values are allowed only if Conversion_OK is
8615       --    set, i.e. if the fixed-point values are to be treated as integers.
8616
8617       --  No other conversions should be passed to Gigi
8618
8619       --  Check: are these rules stated in sinfo??? if so, why restate here???
8620
8621       --  The only remaining step is to generate a range check if we still have
8622       --  a type conversion at this stage and Do_Range_Check is set. For now we
8623       --  do this only for conversions of discrete types.
8624
8625       if Nkind (N) = N_Type_Conversion
8626         and then Is_Discrete_Type (Etype (N))
8627       then
8628          declare
8629             Expr : constant Node_Id := Expression (N);
8630             Ftyp : Entity_Id;
8631             Ityp : Entity_Id;
8632
8633          begin
8634             if Do_Range_Check (Expr)
8635               and then Is_Discrete_Type (Etype (Expr))
8636             then
8637                Set_Do_Range_Check (Expr, False);
8638
8639                --  Before we do a range check, we have to deal with treating a
8640                --  fixed-point operand as an integer. The way we do this is
8641                --  simply to do an unchecked conversion to an appropriate
8642                --  integer type large enough to hold the result.
8643
8644                --  This code is not active yet, because we are only dealing
8645                --  with discrete types so far ???
8646
8647                if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
8648                  and then Treat_Fixed_As_Integer (Expr)
8649                then
8650                   Ftyp := Base_Type (Etype (Expr));
8651
8652                   if Esize (Ftyp) >= Esize (Standard_Integer) then
8653                      Ityp := Standard_Long_Long_Integer;
8654                   else
8655                      Ityp := Standard_Integer;
8656                   end if;
8657
8658                   Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
8659                end if;
8660
8661                --  Reset overflow flag, since the range check will include
8662                --  dealing with possible overflow, and generate the check. If
8663                --  Address is either a source type or target type, suppress
8664                --  range check to avoid typing anomalies when it is a visible
8665                --  integer type.
8666
8667                Set_Do_Overflow_Check (N, False);
8668                if not Is_Descendent_Of_Address (Etype (Expr))
8669                  and then not Is_Descendent_Of_Address (Target_Type)
8670                then
8671                   Generate_Range_Check
8672                     (Expr, Target_Type, CE_Range_Check_Failed);
8673                end if;
8674             end if;
8675          end;
8676       end if;
8677
8678       --  Final step, if the result is a type conversion involving Vax_Float
8679       --  types, then it is subject for further special processing.
8680
8681       if Nkind (N) = N_Type_Conversion
8682         and then (Vax_Float (Operand_Type) or else Vax_Float (Target_Type))
8683       then
8684          Expand_Vax_Conversion (N);
8685          return;
8686       end if;
8687    end Expand_N_Type_Conversion;
8688
8689    -----------------------------------
8690    -- Expand_N_Unchecked_Expression --
8691    -----------------------------------
8692
8693    --  Remove the unchecked expression node from the tree. Its job was simply
8694    --  to make sure that its constituent expression was handled with checks
8695    --  off, and now that that is done, we can remove it from the tree, and
8696    --  indeed must, since Gigi does not expect to see these nodes.
8697
8698    procedure Expand_N_Unchecked_Expression (N : Node_Id) is
8699       Exp : constant Node_Id := Expression (N);
8700
8701    begin
8702       Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
8703       Rewrite (N, Exp);
8704    end Expand_N_Unchecked_Expression;
8705
8706    ----------------------------------------
8707    -- Expand_N_Unchecked_Type_Conversion --
8708    ----------------------------------------
8709
8710    --  If this cannot be handled by Gigi and we haven't already made a
8711    --  temporary for it, do it now.
8712
8713    procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
8714       Target_Type  : constant Entity_Id := Etype (N);
8715       Operand      : constant Node_Id   := Expression (N);
8716       Operand_Type : constant Entity_Id := Etype (Operand);
8717
8718    begin
8719       --  Nothing at all to do if conversion is to the identical type so remove
8720       --  the conversion completely, it is useless, except that it may carry
8721       --  an Assignment_OK indication which must be propagated to the operand.
8722
8723       if Operand_Type = Target_Type then
8724          --  Code duplicates Expand_N_Unchecked_Expression above, factor???
8725
8726          if Assignment_OK (N) then
8727             Set_Assignment_OK (Operand);
8728          end if;
8729
8730          Rewrite (N, Relocate_Node (Operand));
8731          return;
8732       end if;
8733
8734       --  If we have a conversion of a compile time known value to a target
8735       --  type and the value is in range of the target type, then we can simply
8736       --  replace the construct by an integer literal of the correct type. We
8737       --  only apply this to integer types being converted. Possibly it may
8738       --  apply in other cases, but it is too much trouble to worry about.
8739
8740       --  Note that we do not do this transformation if the Kill_Range_Check
8741       --  flag is set, since then the value may be outside the expected range.
8742       --  This happens in the Normalize_Scalars case.
8743
8744       --  We also skip this if either the target or operand type is biased
8745       --  because in this case, the unchecked conversion is supposed to
8746       --  preserve the bit pattern, not the integer value.
8747
8748       if Is_Integer_Type (Target_Type)
8749         and then not Has_Biased_Representation (Target_Type)
8750         and then Is_Integer_Type (Operand_Type)
8751         and then not Has_Biased_Representation (Operand_Type)
8752         and then Compile_Time_Known_Value (Operand)
8753         and then not Kill_Range_Check (N)
8754       then
8755          declare
8756             Val : constant Uint := Expr_Value (Operand);
8757
8758          begin
8759             if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
8760                  and then
8761                Compile_Time_Known_Value (Type_High_Bound (Target_Type))
8762                  and then
8763                Val >= Expr_Value (Type_Low_Bound (Target_Type))
8764                  and then
8765                Val <= Expr_Value (Type_High_Bound (Target_Type))
8766             then
8767                Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
8768
8769                --  If Address is the target type, just set the type to avoid a
8770                --  spurious type error on the literal when Address is a visible
8771                --  integer type.
8772
8773                if Is_Descendent_Of_Address (Target_Type) then
8774                   Set_Etype (N, Target_Type);
8775                else
8776                   Analyze_And_Resolve (N, Target_Type);
8777                end if;
8778
8779                return;
8780             end if;
8781          end;
8782       end if;
8783
8784       --  Nothing to do if conversion is safe
8785
8786       if Safe_Unchecked_Type_Conversion (N) then
8787          return;
8788       end if;
8789
8790       --  Otherwise force evaluation unless Assignment_OK flag is set (this
8791       --  flag indicates ??? -- more comments needed here)
8792
8793       if Assignment_OK (N) then
8794          null;
8795       else
8796          Force_Evaluation (N);
8797       end if;
8798    end Expand_N_Unchecked_Type_Conversion;
8799
8800    ----------------------------
8801    -- Expand_Record_Equality --
8802    ----------------------------
8803
8804    --  For non-variant records, Equality is expanded when needed into:
8805
8806    --      and then Lhs.Discr1 = Rhs.Discr1
8807    --      and then ...
8808    --      and then Lhs.Discrn = Rhs.Discrn
8809    --      and then Lhs.Cmp1 = Rhs.Cmp1
8810    --      and then ...
8811    --      and then Lhs.Cmpn = Rhs.Cmpn
8812
8813    --  The expression is folded by the back-end for adjacent fields. This
8814    --  function is called for tagged record in only one occasion: for imple-
8815    --  menting predefined primitive equality (see Predefined_Primitives_Bodies)
8816    --  otherwise the primitive "=" is used directly.
8817
8818    function Expand_Record_Equality
8819      (Nod    : Node_Id;
8820       Typ    : Entity_Id;
8821       Lhs    : Node_Id;
8822       Rhs    : Node_Id;
8823       Bodies : List_Id) return Node_Id
8824    is
8825       Loc : constant Source_Ptr := Sloc (Nod);
8826
8827       Result : Node_Id;
8828       C      : Entity_Id;
8829
8830       First_Time : Boolean := True;
8831
8832       function Suitable_Element (C : Entity_Id) return Entity_Id;
8833       --  Return the first field to compare beginning with C, skipping the
8834       --  inherited components.
8835
8836       ----------------------
8837       -- Suitable_Element --
8838       ----------------------
8839
8840       function Suitable_Element (C : Entity_Id) return Entity_Id is
8841       begin
8842          if No (C) then
8843             return Empty;
8844
8845          elsif Ekind (C) /= E_Discriminant
8846            and then Ekind (C) /= E_Component
8847          then
8848             return Suitable_Element (Next_Entity (C));
8849
8850          elsif Is_Tagged_Type (Typ)
8851            and then C /= Original_Record_Component (C)
8852          then
8853             return Suitable_Element (Next_Entity (C));
8854
8855          elsif Chars (C) = Name_uController
8856            or else Chars (C) = Name_uTag
8857          then
8858             return Suitable_Element (Next_Entity (C));
8859
8860          elsif Is_Interface (Etype (C)) then
8861             return Suitable_Element (Next_Entity (C));
8862
8863          else
8864             return C;
8865          end if;
8866       end Suitable_Element;
8867
8868    --  Start of processing for Expand_Record_Equality
8869
8870    begin
8871       --  Generates the following code: (assuming that Typ has one Discr and
8872       --  component C2 is also a record)
8873
8874       --   True
8875       --     and then Lhs.Discr1 = Rhs.Discr1
8876       --     and then Lhs.C1 = Rhs.C1
8877       --     and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
8878       --     and then ...
8879       --     and then Lhs.Cmpn = Rhs.Cmpn
8880
8881       Result := New_Reference_To (Standard_True, Loc);
8882       C := Suitable_Element (First_Entity (Typ));
8883       while Present (C) loop
8884          declare
8885             New_Lhs : Node_Id;
8886             New_Rhs : Node_Id;
8887             Check   : Node_Id;
8888
8889          begin
8890             if First_Time then
8891                First_Time := False;
8892                New_Lhs := Lhs;
8893                New_Rhs := Rhs;
8894             else
8895                New_Lhs := New_Copy_Tree (Lhs);
8896                New_Rhs := New_Copy_Tree (Rhs);
8897             end if;
8898
8899             Check :=
8900               Expand_Composite_Equality (Nod, Etype (C),
8901                Lhs =>
8902                  Make_Selected_Component (Loc,
8903                    Prefix => New_Lhs,
8904                    Selector_Name => New_Reference_To (C, Loc)),
8905                Rhs =>
8906                  Make_Selected_Component (Loc,
8907                    Prefix => New_Rhs,
8908                    Selector_Name => New_Reference_To (C, Loc)),
8909                Bodies => Bodies);
8910
8911             --  If some (sub)component is an unchecked_union, the whole
8912             --  operation will raise program error.
8913
8914             if Nkind (Check) = N_Raise_Program_Error then
8915                Result := Check;
8916                Set_Etype (Result, Standard_Boolean);
8917                exit;
8918             else
8919                Result :=
8920                  Make_And_Then (Loc,
8921                    Left_Opnd  => Result,
8922                    Right_Opnd => Check);
8923             end if;
8924          end;
8925
8926          C := Suitable_Element (Next_Entity (C));
8927       end loop;
8928
8929       return Result;
8930    end Expand_Record_Equality;
8931
8932    -----------------------------------
8933    -- Expand_Short_Circuit_Operator --
8934    -----------------------------------
8935
8936    --  Deal with special expansion if actions are present for the right operand
8937    --  and deal with optimizing case of arguments being True or False. We also
8938    --  deal with the special case of non-standard boolean values.
8939
8940    procedure Expand_Short_Circuit_Operator (N : Node_Id) is
8941       Loc     : constant Source_Ptr := Sloc (N);
8942       Typ     : constant Entity_Id  := Etype (N);
8943       Kind    : constant Node_Kind  := Nkind (N);
8944       Left    : constant Node_Id    := Left_Opnd (N);
8945       Right   : constant Node_Id    := Right_Opnd (N);
8946       LocR    : constant Source_Ptr := Sloc (Right);
8947       Actlist : List_Id;
8948
8949       Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
8950       Shortcut_Ent   : constant Entity_Id := Boolean_Literals (Shortcut_Value);
8951       --  If Left = Shortcut_Value then Right need not be evaluated
8952
8953       function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
8954       --  For Opnd a boolean expression, return a Boolean expression equivalent
8955       --  to Opnd /= Shortcut_Value.
8956
8957       --------------------
8958       -- Make_Test_Expr --
8959       --------------------
8960
8961       function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
8962       begin
8963          if Shortcut_Value then
8964             return Make_Op_Not (Sloc (Opnd), Opnd);
8965          else
8966             return Opnd;
8967          end if;
8968       end Make_Test_Expr;
8969
8970       Op_Var : Entity_Id;
8971       --  Entity for a temporary variable holding the value of the operator,
8972       --  used for expansion in the case where actions are present.
8973
8974    --  Start of processing for Expand_Short_Circuit_Operator
8975
8976    begin
8977       --  Deal with non-standard booleans
8978
8979       if Is_Boolean_Type (Typ) then
8980          Adjust_Condition (Left);
8981          Adjust_Condition (Right);
8982          Set_Etype (N, Standard_Boolean);
8983       end if;
8984
8985       --  Check for cases where left argument is known to be True or False
8986
8987       if Compile_Time_Known_Value (Left) then
8988
8989          --  Mark SCO for left condition as compile time known
8990
8991          if Generate_SCO and then Comes_From_Source (Left) then
8992             Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
8993          end if;
8994
8995          --  Rewrite True AND THEN Right / False OR ELSE Right to Right.
8996          --  Any actions associated with Right will be executed unconditionally
8997          --  and can thus be inserted into the tree unconditionally.
8998
8999          if Expr_Value_E (Left) /= Shortcut_Ent then
9000             if Present (Actions (N)) then
9001                Insert_Actions (N, Actions (N));
9002             end if;
9003
9004             Rewrite (N, Right);
9005
9006          --  Rewrite False AND THEN Right / True OR ELSE Right to Left.
9007          --  In this case we can forget the actions associated with Right,
9008          --  since they will never be executed.
9009
9010          else
9011             Kill_Dead_Code (Right);
9012             Kill_Dead_Code (Actions (N));
9013             Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
9014          end if;
9015
9016          Adjust_Result_Type (N, Typ);
9017          return;
9018       end if;
9019
9020       --  If Actions are present for the right operand, we have to do some
9021       --  special processing. We can't just let these actions filter back into
9022       --  code preceding the short circuit (which is what would have happened
9023       --  if we had not trapped them in the short-circuit form), since they
9024       --  must only be executed if the right operand of the short circuit is
9025       --  executed and not otherwise.
9026
9027       --  the temporary variable C.
9028
9029       if Present (Actions (N)) then
9030          Actlist := Actions (N);
9031
9032          --  The old approach is to expand:
9033
9034          --     left AND THEN right
9035
9036          --  into
9037
9038          --     C : Boolean := False;
9039          --     IF left THEN
9040          --        Actions;
9041          --        IF right THEN
9042          --           C := True;
9043          --        END IF;
9044          --     END IF;
9045
9046          --  and finally rewrite the operator into a reference to C. Similarly
9047          --  for left OR ELSE right, with negated values. Note that this
9048          --  rewrite causes some difficulties for coverage analysis because
9049          --  of the introduction of the new variable C, which obscures the
9050          --  structure of the test.
9051
9052          --  We use this "old approach" if use of N_Expression_With_Actions
9053          --  is False (see description in Opt of when this is or is not set).
9054
9055          if not Use_Expression_With_Actions then
9056             Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
9057
9058             Insert_Action (N,
9059               Make_Object_Declaration (Loc,
9060                 Defining_Identifier =>
9061                   Op_Var,
9062                 Object_Definition   =>
9063                   New_Occurrence_Of (Standard_Boolean, Loc),
9064                 Expression          =>
9065                   New_Occurrence_Of (Shortcut_Ent, Loc)));
9066
9067             Append_To (Actlist,
9068               Make_Implicit_If_Statement (Right,
9069                 Condition       => Make_Test_Expr (Right),
9070                 Then_Statements => New_List (
9071                   Make_Assignment_Statement (LocR,
9072                     Name       => New_Occurrence_Of (Op_Var, LocR),
9073                     Expression =>
9074                       New_Occurrence_Of
9075                         (Boolean_Literals (not Shortcut_Value), LocR)))));
9076
9077             Insert_Action (N,
9078               Make_Implicit_If_Statement (Left,
9079                 Condition       => Make_Test_Expr (Left),
9080                 Then_Statements => Actlist));
9081
9082             Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
9083             Analyze_And_Resolve (N, Standard_Boolean);
9084
9085          --  The new approach, activated for now by the use of debug flag
9086          --  -gnatd.X is to use the new Expression_With_Actions node for the
9087          --  right operand of the short-circuit form. This should solve the
9088          --  traceability problems for coverage analysis.
9089
9090          else
9091             Rewrite (Right,
9092               Make_Expression_With_Actions (LocR,
9093                 Expression => Relocate_Node (Right),
9094                 Actions    => Actlist));
9095             Set_Actions (N, No_List);
9096             Analyze_And_Resolve (Right, Standard_Boolean);
9097          end if;
9098
9099          --  Special processing necessary for SCIL generation for AND THEN
9100          --  with a function call as the right operand.
9101
9102          --  What is this about, and is it needed for both cases above???
9103
9104          if Generate_SCIL
9105            and then Kind = N_And_Then
9106            and then Nkind (Right) = N_Function_Call
9107          then
9108             Adjust_SCIL_Node (N, Right);
9109          end if;
9110
9111          Adjust_Result_Type (N, Typ);
9112          return;
9113       end if;
9114
9115       --  No actions present, check for cases of right argument True/False
9116
9117       if Compile_Time_Known_Value (Right) then
9118
9119          --  Mark SCO for left condition as compile time known
9120
9121          if Generate_SCO and then Comes_From_Source (Right) then
9122             Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
9123          end if;
9124
9125          --  Change (Left and then True), (Left or else False) to Left.
9126          --  Note that we know there are no actions associated with the right
9127          --  operand, since we just checked for this case above.
9128
9129          if Expr_Value_E (Right) /= Shortcut_Ent then
9130             Rewrite (N, Left);
9131
9132          --  Change (Left and then False), (Left or else True) to Right,
9133          --  making sure to preserve any side effects associated with the Left
9134          --  operand.
9135
9136          else
9137             Remove_Side_Effects (Left);
9138             Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
9139          end if;
9140       end if;
9141
9142       Adjust_Result_Type (N, Typ);
9143    end Expand_Short_Circuit_Operator;
9144
9145    -------------------------------------
9146    -- Fixup_Universal_Fixed_Operation --
9147    -------------------------------------
9148
9149    procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
9150       Conv : constant Node_Id := Parent (N);
9151
9152    begin
9153       --  We must have a type conversion immediately above us
9154
9155       pragma Assert (Nkind (Conv) = N_Type_Conversion);
9156
9157       --  Normally the type conversion gives our target type. The exception
9158       --  occurs in the case of the Round attribute, where the conversion
9159       --  will be to universal real, and our real type comes from the Round
9160       --  attribute (as well as an indication that we must round the result)
9161
9162       if Nkind (Parent (Conv)) = N_Attribute_Reference
9163         and then Attribute_Name (Parent (Conv)) = Name_Round
9164       then
9165          Set_Etype (N, Etype (Parent (Conv)));
9166          Set_Rounded_Result (N);
9167
9168       --  Normal case where type comes from conversion above us
9169
9170       else
9171          Set_Etype (N, Etype (Conv));
9172       end if;
9173    end Fixup_Universal_Fixed_Operation;
9174
9175    ------------------------------
9176    -- Get_Allocator_Final_List --
9177    ------------------------------
9178
9179    function Get_Allocator_Final_List
9180      (N    : Node_Id;
9181       T    : Entity_Id;
9182       PtrT : Entity_Id) return Entity_Id
9183    is
9184       Loc : constant Source_Ptr := Sloc (N);
9185
9186       Owner : Entity_Id := PtrT;
9187       --  The entity whose finalization list must be used to attach the
9188       --  allocated object.
9189
9190    begin
9191       if Ekind (PtrT) = E_Anonymous_Access_Type then
9192
9193          --  If the context is an access parameter, we need to create a
9194          --  non-anonymous access type in order to have a usable final list,
9195          --  because there is otherwise no pool to which the allocated object
9196          --  can belong. We create both the type and the finalization chain
9197          --  here, because freezing an internal type does not create such a
9198          --  chain. The Final_Chain that is thus created is shared by the
9199          --  access parameter. The access type is tested against the result
9200          --  type of the function to exclude allocators whose type is an
9201          --  anonymous access result type. We freeze the type at once to
9202          --  ensure that it is properly decorated for the back-end, even
9203          --  if the context and current scope is a loop.
9204
9205          if Nkind (Associated_Node_For_Itype (PtrT))
9206               in N_Subprogram_Specification
9207            and then
9208              PtrT /=
9209                Etype (Defining_Unit_Name (Associated_Node_For_Itype (PtrT)))
9210          then
9211             Owner := Make_Temporary (Loc, 'J');
9212             Insert_Action (N,
9213               Make_Full_Type_Declaration (Loc,
9214                 Defining_Identifier => Owner,
9215                 Type_Definition =>
9216                    Make_Access_To_Object_Definition (Loc,
9217                      Subtype_Indication =>
9218                        New_Occurrence_Of (T, Loc))));
9219
9220             Freeze_Before (N, Owner);
9221             Build_Final_List (N, Owner);
9222             Set_Associated_Final_Chain (PtrT, Associated_Final_Chain (Owner));
9223
9224          --  Ada 2005 (AI-318-02): If the context is a return object
9225          --  declaration, then the anonymous return subtype is defined to have
9226          --  the same accessibility level as that of the function's result
9227          --  subtype, which means that we want the scope where the function is
9228          --  declared.
9229
9230          elsif Nkind (Associated_Node_For_Itype (PtrT)) = N_Object_Declaration
9231            and then Ekind (Scope (PtrT)) = E_Return_Statement
9232          then
9233             Owner := Scope (Return_Applies_To (Scope (PtrT)));
9234
9235          --  Case of an access discriminant, or (Ada 2005) of an anonymous
9236          --  access component or anonymous access function result: find the
9237          --  final list associated with the scope of the type. (In the
9238          --  anonymous access component kind, a list controller will have
9239          --  been allocated when freezing the record type, and PtrT has an
9240          --  Associated_Final_Chain attribute designating it.)
9241
9242          elsif No (Associated_Final_Chain (PtrT)) then
9243             Owner := Scope (PtrT);
9244          end if;
9245       end if;
9246
9247       return Find_Final_List (Owner);
9248    end Get_Allocator_Final_List;
9249
9250    ---------------------------------
9251    -- Has_Inferable_Discriminants --
9252    ---------------------------------
9253
9254    function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
9255
9256       function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
9257       --  Determines whether the left-most prefix of a selected component is a
9258       --  formal parameter in a subprogram. Assumes N is a selected component.
9259
9260       --------------------------------
9261       -- Prefix_Is_Formal_Parameter --
9262       --------------------------------
9263
9264       function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
9265          Sel_Comp : Node_Id := N;
9266
9267       begin
9268          --  Move to the left-most prefix by climbing up the tree
9269
9270          while Present (Parent (Sel_Comp))
9271            and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
9272          loop
9273             Sel_Comp := Parent (Sel_Comp);
9274          end loop;
9275
9276          return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
9277       end Prefix_Is_Formal_Parameter;
9278
9279    --  Start of processing for Has_Inferable_Discriminants
9280
9281    begin
9282       --  For identifiers and indexed components, it is sufficient to have a
9283       --  constrained Unchecked_Union nominal subtype.
9284
9285       if Nkind_In (N, N_Identifier, N_Indexed_Component) then
9286          return Is_Unchecked_Union (Base_Type (Etype (N)))
9287                   and then
9288                 Is_Constrained (Etype (N));
9289
9290       --  For selected components, the subtype of the selector must be a
9291       --  constrained Unchecked_Union. If the component is subject to a
9292       --  per-object constraint, then the enclosing object must have inferable
9293       --  discriminants.
9294
9295       elsif Nkind (N) = N_Selected_Component then
9296          if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
9297
9298             --  A small hack. If we have a per-object constrained selected
9299             --  component of a formal parameter, return True since we do not
9300             --  know the actual parameter association yet.
9301
9302             if Prefix_Is_Formal_Parameter (N) then
9303                return True;
9304             end if;
9305
9306             --  Otherwise, check the enclosing object and the selector
9307
9308             return Has_Inferable_Discriminants (Prefix (N))
9309                      and then
9310                    Has_Inferable_Discriminants (Selector_Name (N));
9311          end if;
9312
9313          --  The call to Has_Inferable_Discriminants will determine whether
9314          --  the selector has a constrained Unchecked_Union nominal type.
9315
9316          return Has_Inferable_Discriminants (Selector_Name (N));
9317
9318       --  A qualified expression has inferable discriminants if its subtype
9319       --  mark is a constrained Unchecked_Union subtype.
9320
9321       elsif Nkind (N) = N_Qualified_Expression then
9322          return Is_Unchecked_Union (Subtype_Mark (N))
9323                   and then
9324                 Is_Constrained (Subtype_Mark (N));
9325
9326       end if;
9327
9328       return False;
9329    end Has_Inferable_Discriminants;
9330
9331    -------------------------------
9332    -- Insert_Dereference_Action --
9333    -------------------------------
9334
9335    procedure Insert_Dereference_Action (N : Node_Id) is
9336       Loc  : constant Source_Ptr := Sloc (N);
9337       Typ  : constant Entity_Id  := Etype (N);
9338       Pool : constant Entity_Id  := Associated_Storage_Pool (Typ);
9339       Pnod : constant Node_Id    := Parent (N);
9340
9341       function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
9342       --  Return true if type of P is derived from Checked_Pool;
9343
9344       -----------------------------
9345       -- Is_Checked_Storage_Pool --
9346       -----------------------------
9347
9348       function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
9349          T : Entity_Id;
9350
9351       begin
9352          if No (P) then
9353             return False;
9354          end if;
9355
9356          T := Etype (P);
9357          while T /= Etype (T) loop
9358             if Is_RTE (T, RE_Checked_Pool) then
9359                return True;
9360             else
9361                T := Etype (T);
9362             end if;
9363          end loop;
9364
9365          return False;
9366       end Is_Checked_Storage_Pool;
9367
9368    --  Start of processing for Insert_Dereference_Action
9369
9370    begin
9371       pragma Assert (Nkind (Pnod) = N_Explicit_Dereference);
9372
9373       if not (Is_Checked_Storage_Pool (Pool)
9374               and then Comes_From_Source (Original_Node (Pnod)))
9375       then
9376          return;
9377       end if;
9378
9379       Insert_Action (N,
9380         Make_Procedure_Call_Statement (Loc,
9381           Name => New_Reference_To (
9382             Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
9383
9384           Parameter_Associations => New_List (
9385
9386             --  Pool
9387
9388              New_Reference_To (Pool, Loc),
9389
9390             --  Storage_Address. We use the attribute Pool_Address, which uses
9391             --  the pointer itself to find the address of the object, and which
9392             --  handles unconstrained arrays properly by computing the address
9393             --  of the template. i.e. the correct address of the corresponding
9394             --  allocation.
9395
9396              Make_Attribute_Reference (Loc,
9397                Prefix         => Duplicate_Subexpr_Move_Checks (N),
9398                Attribute_Name => Name_Pool_Address),
9399
9400             --  Size_In_Storage_Elements
9401
9402              Make_Op_Divide (Loc,
9403                Left_Opnd  =>
9404                 Make_Attribute_Reference (Loc,
9405                   Prefix         =>
9406                     Make_Explicit_Dereference (Loc,
9407                       Duplicate_Subexpr_Move_Checks (N)),
9408                   Attribute_Name => Name_Size),
9409                Right_Opnd =>
9410                  Make_Integer_Literal (Loc, System_Storage_Unit)),
9411
9412             --  Alignment
9413
9414              Make_Attribute_Reference (Loc,
9415                Prefix         =>
9416                  Make_Explicit_Dereference (Loc,
9417                    Duplicate_Subexpr_Move_Checks (N)),
9418                Attribute_Name => Name_Alignment))));
9419
9420    exception
9421       when RE_Not_Available =>
9422          return;
9423    end Insert_Dereference_Action;
9424
9425    --------------------------------
9426    -- Integer_Promotion_Possible --
9427    --------------------------------
9428
9429    function Integer_Promotion_Possible (N : Node_Id) return Boolean is
9430       Operand           : constant Node_Id   := Expression (N);
9431       Operand_Type      : constant Entity_Id := Etype (Operand);
9432       Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
9433
9434    begin
9435       pragma Assert (Nkind (N) = N_Type_Conversion);
9436
9437       return
9438
9439            --  We only do the transformation for source constructs. We assume
9440            --  that the expander knows what it is doing when it generates code.
9441
9442            Comes_From_Source (N)
9443
9444            --  If the operand type is Short_Integer or Short_Short_Integer,
9445            --  then we will promote to Integer, which is available on all
9446            --  targets, and is sufficient to ensure no intermediate overflow.
9447            --  Furthermore it is likely to be as efficient or more efficient
9448            --  than using the smaller type for the computation so we do this
9449            --  unconditionally.
9450
9451            and then
9452              (Root_Operand_Type = Base_Type (Standard_Short_Integer)
9453                or else
9454               Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
9455
9456            --  Test for interesting operation, which includes addition,
9457            --  division, exponentiation, multiplication, subtraction, absolute
9458            --  value and unary negation. Unary "+" is omitted since it is a
9459            --  no-op and thus can't overflow.
9460
9461            and then Nkind_In (Operand, N_Op_Abs,
9462                                        N_Op_Add,
9463                                        N_Op_Divide,
9464                                        N_Op_Expon,
9465                                        N_Op_Minus,
9466                                        N_Op_Multiply,
9467                                        N_Op_Subtract);
9468    end Integer_Promotion_Possible;
9469
9470    ------------------------------
9471    -- Make_Array_Comparison_Op --
9472    ------------------------------
9473
9474    --  This is a hand-coded expansion of the following generic function:
9475
9476    --  generic
9477    --    type elem is  (<>);
9478    --    type index is (<>);
9479    --    type a is array (index range <>) of elem;
9480
9481    --  function Gnnn (X : a; Y: a) return boolean is
9482    --    J : index := Y'first;
9483
9484    --  begin
9485    --    if X'length = 0 then
9486    --       return false;
9487
9488    --    elsif Y'length = 0 then
9489    --       return true;
9490
9491    --    else
9492    --      for I in X'range loop
9493    --        if X (I) = Y (J) then
9494    --          if J = Y'last then
9495    --            exit;
9496    --          else
9497    --            J := index'succ (J);
9498    --          end if;
9499
9500    --        else
9501    --           return X (I) > Y (J);
9502    --        end if;
9503    --      end loop;
9504
9505    --      return X'length > Y'length;
9506    --    end if;
9507    --  end Gnnn;
9508
9509    --  Note that since we are essentially doing this expansion by hand, we
9510    --  do not need to generate an actual or formal generic part, just the
9511    --  instantiated function itself.
9512
9513    function Make_Array_Comparison_Op
9514      (Typ : Entity_Id;
9515       Nod : Node_Id) return Node_Id
9516    is
9517       Loc : constant Source_Ptr := Sloc (Nod);
9518
9519       X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
9520       Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
9521       I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
9522       J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
9523
9524       Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
9525
9526       Loop_Statement : Node_Id;
9527       Loop_Body      : Node_Id;
9528       If_Stat        : Node_Id;
9529       Inner_If       : Node_Id;
9530       Final_Expr     : Node_Id;
9531       Func_Body      : Node_Id;
9532       Func_Name      : Entity_Id;
9533       Formals        : List_Id;
9534       Length1        : Node_Id;
9535       Length2        : Node_Id;
9536
9537    begin
9538       --  if J = Y'last then
9539       --     exit;
9540       --  else
9541       --     J := index'succ (J);
9542       --  end if;
9543
9544       Inner_If :=
9545         Make_Implicit_If_Statement (Nod,
9546           Condition =>
9547             Make_Op_Eq (Loc,
9548               Left_Opnd => New_Reference_To (J, Loc),
9549               Right_Opnd =>
9550                 Make_Attribute_Reference (Loc,
9551                   Prefix => New_Reference_To (Y, Loc),
9552                   Attribute_Name => Name_Last)),
9553
9554           Then_Statements => New_List (
9555                 Make_Exit_Statement (Loc)),
9556
9557           Else_Statements =>
9558             New_List (
9559               Make_Assignment_Statement (Loc,
9560                 Name => New_Reference_To (J, Loc),
9561                 Expression =>
9562                   Make_Attribute_Reference (Loc,
9563                     Prefix => New_Reference_To (Index, Loc),
9564                     Attribute_Name => Name_Succ,
9565                     Expressions => New_List (New_Reference_To (J, Loc))))));
9566
9567       --  if X (I) = Y (J) then
9568       --     if ... end if;
9569       --  else
9570       --     return X (I) > Y (J);
9571       --  end if;
9572
9573       Loop_Body :=
9574         Make_Implicit_If_Statement (Nod,
9575           Condition =>
9576             Make_Op_Eq (Loc,
9577               Left_Opnd =>
9578                 Make_Indexed_Component (Loc,
9579                   Prefix      => New_Reference_To (X, Loc),
9580                   Expressions => New_List (New_Reference_To (I, Loc))),
9581
9582               Right_Opnd =>
9583                 Make_Indexed_Component (Loc,
9584                   Prefix      => New_Reference_To (Y, Loc),
9585                   Expressions => New_List (New_Reference_To (J, Loc)))),
9586
9587           Then_Statements => New_List (Inner_If),
9588
9589           Else_Statements => New_List (
9590             Make_Simple_Return_Statement (Loc,
9591               Expression =>
9592                 Make_Op_Gt (Loc,
9593                   Left_Opnd =>
9594                     Make_Indexed_Component (Loc,
9595                       Prefix      => New_Reference_To (X, Loc),
9596                       Expressions => New_List (New_Reference_To (I, Loc))),
9597
9598                   Right_Opnd =>
9599                     Make_Indexed_Component (Loc,
9600                       Prefix      => New_Reference_To (Y, Loc),
9601                       Expressions => New_List (
9602                         New_Reference_To (J, Loc)))))));
9603
9604       --  for I in X'range loop
9605       --     if ... end if;
9606       --  end loop;
9607
9608       Loop_Statement :=
9609         Make_Implicit_Loop_Statement (Nod,
9610           Identifier => Empty,
9611
9612           Iteration_Scheme =>
9613             Make_Iteration_Scheme (Loc,
9614               Loop_Parameter_Specification =>
9615                 Make_Loop_Parameter_Specification (Loc,
9616                   Defining_Identifier => I,
9617                   Discrete_Subtype_Definition =>
9618                     Make_Attribute_Reference (Loc,
9619                       Prefix => New_Reference_To (X, Loc),
9620                       Attribute_Name => Name_Range))),
9621
9622           Statements => New_List (Loop_Body));
9623
9624       --    if X'length = 0 then
9625       --       return false;
9626       --    elsif Y'length = 0 then
9627       --       return true;
9628       --    else
9629       --      for ... loop ... end loop;
9630       --      return X'length > Y'length;
9631       --    end if;
9632
9633       Length1 :=
9634         Make_Attribute_Reference (Loc,
9635           Prefix => New_Reference_To (X, Loc),
9636           Attribute_Name => Name_Length);
9637
9638       Length2 :=
9639         Make_Attribute_Reference (Loc,
9640           Prefix => New_Reference_To (Y, Loc),
9641           Attribute_Name => Name_Length);
9642
9643       Final_Expr :=
9644         Make_Op_Gt (Loc,
9645           Left_Opnd  => Length1,
9646           Right_Opnd => Length2);
9647
9648       If_Stat :=
9649         Make_Implicit_If_Statement (Nod,
9650           Condition =>
9651             Make_Op_Eq (Loc,
9652               Left_Opnd =>
9653                 Make_Attribute_Reference (Loc,
9654                   Prefix => New_Reference_To (X, Loc),
9655                   Attribute_Name => Name_Length),
9656               Right_Opnd =>
9657                 Make_Integer_Literal (Loc, 0)),
9658
9659           Then_Statements =>
9660             New_List (
9661               Make_Simple_Return_Statement (Loc,
9662                 Expression => New_Reference_To (Standard_False, Loc))),
9663
9664           Elsif_Parts => New_List (
9665             Make_Elsif_Part (Loc,
9666               Condition =>
9667                 Make_Op_Eq (Loc,
9668                   Left_Opnd =>
9669                     Make_Attribute_Reference (Loc,
9670                       Prefix => New_Reference_To (Y, Loc),
9671                       Attribute_Name => Name_Length),
9672                   Right_Opnd =>
9673                     Make_Integer_Literal (Loc, 0)),
9674
9675               Then_Statements =>
9676                 New_List (
9677                   Make_Simple_Return_Statement (Loc,
9678                      Expression => New_Reference_To (Standard_True, Loc))))),
9679
9680           Else_Statements => New_List (
9681             Loop_Statement,
9682             Make_Simple_Return_Statement (Loc,
9683               Expression => Final_Expr)));
9684
9685       --  (X : a; Y: a)
9686
9687       Formals := New_List (
9688         Make_Parameter_Specification (Loc,
9689           Defining_Identifier => X,
9690           Parameter_Type      => New_Reference_To (Typ, Loc)),
9691
9692         Make_Parameter_Specification (Loc,
9693           Defining_Identifier => Y,
9694           Parameter_Type      => New_Reference_To (Typ, Loc)));
9695
9696       --  function Gnnn (...) return boolean is
9697       --    J : index := Y'first;
9698       --  begin
9699       --    if ... end if;
9700       --  end Gnnn;
9701
9702       Func_Name := Make_Temporary (Loc, 'G');
9703
9704       Func_Body :=
9705         Make_Subprogram_Body (Loc,
9706           Specification =>
9707             Make_Function_Specification (Loc,
9708               Defining_Unit_Name       => Func_Name,
9709               Parameter_Specifications => Formals,
9710               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
9711
9712           Declarations => New_List (
9713             Make_Object_Declaration (Loc,
9714               Defining_Identifier => J,
9715               Object_Definition   => New_Reference_To (Index, Loc),
9716               Expression =>
9717                 Make_Attribute_Reference (Loc,
9718                   Prefix => New_Reference_To (Y, Loc),
9719                   Attribute_Name => Name_First))),
9720
9721           Handled_Statement_Sequence =>
9722             Make_Handled_Sequence_Of_Statements (Loc,
9723               Statements => New_List (If_Stat)));
9724
9725       return Func_Body;
9726    end Make_Array_Comparison_Op;
9727
9728    ---------------------------
9729    -- Make_Boolean_Array_Op --
9730    ---------------------------
9731
9732    --  For logical operations on boolean arrays, expand in line the following,
9733    --  replacing 'and' with 'or' or 'xor' where needed:
9734
9735    --    function Annn (A : typ; B: typ) return typ is
9736    --       C : typ;
9737    --    begin
9738    --       for J in A'range loop
9739    --          C (J) := A (J) op B (J);
9740    --       end loop;
9741    --       return C;
9742    --    end Annn;
9743
9744    --  Here typ is the boolean array type
9745
9746    function Make_Boolean_Array_Op
9747      (Typ : Entity_Id;
9748       N   : Node_Id) return Node_Id
9749    is
9750       Loc : constant Source_Ptr := Sloc (N);
9751
9752       A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
9753       B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
9754       C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
9755       J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
9756
9757       A_J : Node_Id;
9758       B_J : Node_Id;
9759       C_J : Node_Id;
9760       Op  : Node_Id;
9761
9762       Formals        : List_Id;
9763       Func_Name      : Entity_Id;
9764       Func_Body      : Node_Id;
9765       Loop_Statement : Node_Id;
9766
9767    begin
9768       A_J :=
9769         Make_Indexed_Component (Loc,
9770           Prefix      => New_Reference_To (A, Loc),
9771           Expressions => New_List (New_Reference_To (J, Loc)));
9772
9773       B_J :=
9774         Make_Indexed_Component (Loc,
9775           Prefix      => New_Reference_To (B, Loc),
9776           Expressions => New_List (New_Reference_To (J, Loc)));
9777
9778       C_J :=
9779         Make_Indexed_Component (Loc,
9780           Prefix      => New_Reference_To (C, Loc),
9781           Expressions => New_List (New_Reference_To (J, Loc)));
9782
9783       if Nkind (N) = N_Op_And then
9784          Op :=
9785            Make_Op_And (Loc,
9786              Left_Opnd  => A_J,
9787              Right_Opnd => B_J);
9788
9789       elsif Nkind (N) = N_Op_Or then
9790          Op :=
9791            Make_Op_Or (Loc,
9792              Left_Opnd  => A_J,
9793              Right_Opnd => B_J);
9794
9795       else
9796          Op :=
9797            Make_Op_Xor (Loc,
9798              Left_Opnd  => A_J,
9799              Right_Opnd => B_J);
9800       end if;
9801
9802       Loop_Statement :=
9803         Make_Implicit_Loop_Statement (N,
9804           Identifier => Empty,
9805
9806           Iteration_Scheme =>
9807             Make_Iteration_Scheme (Loc,
9808               Loop_Parameter_Specification =>
9809                 Make_Loop_Parameter_Specification (Loc,
9810                   Defining_Identifier => J,
9811                   Discrete_Subtype_Definition =>
9812                     Make_Attribute_Reference (Loc,
9813                       Prefix => New_Reference_To (A, Loc),
9814                       Attribute_Name => Name_Range))),
9815
9816           Statements => New_List (
9817             Make_Assignment_Statement (Loc,
9818               Name       => C_J,
9819               Expression => Op)));
9820
9821       Formals := New_List (
9822         Make_Parameter_Specification (Loc,
9823           Defining_Identifier => A,
9824           Parameter_Type      => New_Reference_To (Typ, Loc)),
9825
9826         Make_Parameter_Specification (Loc,
9827           Defining_Identifier => B,
9828           Parameter_Type      => New_Reference_To (Typ, Loc)));
9829
9830       Func_Name := Make_Temporary (Loc, 'A');
9831       Set_Is_Inlined (Func_Name);
9832
9833       Func_Body :=
9834         Make_Subprogram_Body (Loc,
9835           Specification =>
9836             Make_Function_Specification (Loc,
9837               Defining_Unit_Name       => Func_Name,
9838               Parameter_Specifications => Formals,
9839               Result_Definition        => New_Reference_To (Typ, Loc)),
9840
9841           Declarations => New_List (
9842             Make_Object_Declaration (Loc,
9843               Defining_Identifier => C,
9844               Object_Definition   => New_Reference_To (Typ, Loc))),
9845
9846           Handled_Statement_Sequence =>
9847             Make_Handled_Sequence_Of_Statements (Loc,
9848               Statements => New_List (
9849                 Loop_Statement,
9850                 Make_Simple_Return_Statement (Loc,
9851                   Expression => New_Reference_To (C, Loc)))));
9852
9853       return Func_Body;
9854    end Make_Boolean_Array_Op;
9855
9856    ------------------------
9857    -- Rewrite_Comparison --
9858    ------------------------
9859
9860    procedure Rewrite_Comparison (N : Node_Id) is
9861       Warning_Generated : Boolean := False;
9862       --  Set to True if first pass with Assume_Valid generates a warning in
9863       --  which case we skip the second pass to avoid warning overloaded.
9864
9865       Result : Node_Id;
9866       --  Set to Standard_True or Standard_False
9867
9868    begin
9869       if Nkind (N) = N_Type_Conversion then
9870          Rewrite_Comparison (Expression (N));
9871          return;
9872
9873       elsif Nkind (N) not in N_Op_Compare then
9874          return;
9875       end if;
9876
9877       --  Now start looking at the comparison in detail. We potentially go
9878       --  through this loop twice. The first time, Assume_Valid is set False
9879       --  in the call to Compile_Time_Compare. If this call results in a
9880       --  clear result of always True or Always False, that's decisive and
9881       --  we are done. Otherwise we repeat the processing with Assume_Valid
9882       --  set to True to generate additional warnings. We can skip that step
9883       --  if Constant_Condition_Warnings is False.
9884
9885       for AV in False .. True loop
9886          declare
9887             Typ : constant Entity_Id := Etype (N);
9888             Op1 : constant Node_Id   := Left_Opnd (N);
9889             Op2 : constant Node_Id   := Right_Opnd (N);
9890
9891             Res : constant Compare_Result :=
9892                     Compile_Time_Compare (Op1, Op2, Assume_Valid => AV);
9893             --  Res indicates if compare outcome can be compile time determined
9894
9895             True_Result  : Boolean;
9896             False_Result : Boolean;
9897
9898          begin
9899             case N_Op_Compare (Nkind (N)) is
9900             when N_Op_Eq =>
9901                True_Result  := Res = EQ;
9902                False_Result := Res = LT or else Res = GT or else Res = NE;
9903
9904             when N_Op_Ge =>
9905                True_Result  := Res in Compare_GE;
9906                False_Result := Res = LT;
9907
9908                if Res = LE
9909                  and then Constant_Condition_Warnings
9910                  and then Comes_From_Source (Original_Node (N))
9911                  and then Nkind (Original_Node (N)) = N_Op_Ge
9912                  and then not In_Instance
9913                  and then Is_Integer_Type (Etype (Left_Opnd (N)))
9914                  and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
9915                then
9916                   Error_Msg_N
9917                     ("can never be greater than, could replace by ""'=""?", N);
9918                   Warning_Generated := True;
9919                end if;
9920
9921             when N_Op_Gt =>
9922                True_Result  := Res = GT;
9923                False_Result := Res in Compare_LE;
9924
9925             when N_Op_Lt =>
9926                True_Result  := Res = LT;
9927                False_Result := Res in Compare_GE;
9928
9929             when N_Op_Le =>
9930                True_Result  := Res in Compare_LE;
9931                False_Result := Res = GT;
9932
9933                if Res = GE
9934                  and then Constant_Condition_Warnings
9935                  and then Comes_From_Source (Original_Node (N))
9936                  and then Nkind (Original_Node (N)) = N_Op_Le
9937                  and then not In_Instance
9938                  and then Is_Integer_Type (Etype (Left_Opnd (N)))
9939                  and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
9940                then
9941                   Error_Msg_N
9942                     ("can never be less than, could replace by ""'=""?", N);
9943                   Warning_Generated := True;
9944                end if;
9945
9946             when N_Op_Ne =>
9947                True_Result  := Res = NE or else Res = GT or else Res = LT;
9948                False_Result := Res = EQ;
9949             end case;
9950
9951             --  If this is the first iteration, then we actually convert the
9952             --  comparison into True or False, if the result is certain.
9953
9954             if AV = False then
9955                if True_Result or False_Result then
9956                   if True_Result then
9957                      Result := Standard_True;
9958                   else
9959                      Result := Standard_False;
9960                   end if;
9961
9962                   Rewrite (N,
9963                     Convert_To (Typ,
9964                       New_Occurrence_Of (Result, Sloc (N))));
9965                   Analyze_And_Resolve (N, Typ);
9966                   Warn_On_Known_Condition (N);
9967                   return;
9968                end if;
9969
9970             --  If this is the second iteration (AV = True), and the original
9971             --  node comes from source and we are not in an instance, then give
9972             --  a warning if we know result would be True or False. Note: we
9973             --  know Constant_Condition_Warnings is set if we get here.
9974
9975             elsif Comes_From_Source (Original_Node (N))
9976               and then not In_Instance
9977             then
9978                if True_Result then
9979                   Error_Msg_N
9980                     ("condition can only be False if invalid values present?",
9981                      N);
9982                elsif False_Result then
9983                   Error_Msg_N
9984                     ("condition can only be True if invalid values present?",
9985                      N);
9986                end if;
9987             end if;
9988          end;
9989
9990          --  Skip second iteration if not warning on constant conditions or
9991          --  if the first iteration already generated a warning of some kind or
9992          --  if we are in any case assuming all values are valid (so that the
9993          --  first iteration took care of the valid case).
9994
9995          exit when not Constant_Condition_Warnings;
9996          exit when Warning_Generated;
9997          exit when Assume_No_Invalid_Values;
9998       end loop;
9999    end Rewrite_Comparison;
10000
10001    ----------------------------
10002    -- Safe_In_Place_Array_Op --
10003    ----------------------------
10004
10005    function Safe_In_Place_Array_Op
10006      (Lhs : Node_Id;
10007       Op1 : Node_Id;
10008       Op2 : Node_Id) return Boolean
10009    is
10010       Target : Entity_Id;
10011
10012       function Is_Safe_Operand (Op : Node_Id) return Boolean;
10013       --  Operand is safe if it cannot overlap part of the target of the
10014       --  operation. If the operand and the target are identical, the operand
10015       --  is safe. The operand can be empty in the case of negation.
10016
10017       function Is_Unaliased (N : Node_Id) return Boolean;
10018       --  Check that N is a stand-alone entity
10019
10020       ------------------
10021       -- Is_Unaliased --
10022       ------------------
10023
10024       function Is_Unaliased (N : Node_Id) return Boolean is
10025       begin
10026          return
10027            Is_Entity_Name (N)
10028              and then No (Address_Clause (Entity (N)))
10029              and then No (Renamed_Object (Entity (N)));
10030       end Is_Unaliased;
10031
10032       ---------------------
10033       -- Is_Safe_Operand --
10034       ---------------------
10035
10036       function Is_Safe_Operand (Op : Node_Id) return Boolean is
10037       begin
10038          if No (Op) then
10039             return True;
10040
10041          elsif Is_Entity_Name (Op) then
10042             return Is_Unaliased (Op);
10043
10044          elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
10045             return Is_Unaliased (Prefix (Op));
10046
10047          elsif Nkind (Op) = N_Slice then
10048             return
10049               Is_Unaliased (Prefix (Op))
10050                 and then Entity (Prefix (Op)) /= Target;
10051
10052          elsif Nkind (Op) = N_Op_Not then
10053             return Is_Safe_Operand (Right_Opnd (Op));
10054
10055          else
10056             return False;
10057          end if;
10058       end Is_Safe_Operand;
10059
10060    --  Start of processing for Is_Safe_In_Place_Array_Op
10061
10062    begin
10063       --  Skip this processing if the component size is different from system
10064       --  storage unit (since at least for NOT this would cause problems).
10065
10066       if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
10067          return False;
10068
10069       --  Cannot do in place stuff on VM_Target since cannot pass addresses
10070
10071       elsif VM_Target /= No_VM then
10072          return False;
10073
10074       --  Cannot do in place stuff if non-standard Boolean representation
10075
10076       elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
10077          return False;
10078
10079       elsif not Is_Unaliased (Lhs) then
10080          return False;
10081
10082       else
10083          Target := Entity (Lhs);
10084          return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
10085       end if;
10086    end Safe_In_Place_Array_Op;
10087
10088    -----------------------
10089    -- Tagged_Membership --
10090    -----------------------
10091
10092    --  There are two different cases to consider depending on whether the right
10093    --  operand is a class-wide type or not. If not we just compare the actual
10094    --  tag of the left expr to the target type tag:
10095    --
10096    --     Left_Expr.Tag = Right_Type'Tag;
10097    --
10098    --  If it is a class-wide type we use the RT function CW_Membership which is
10099    --  usually implemented by looking in the ancestor tables contained in the
10100    --  dispatch table pointed by Left_Expr.Tag for Typ'Tag
10101
10102    --  Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
10103    --  function IW_Membership which is usually implemented by looking in the
10104    --  table of abstract interface types plus the ancestor table contained in
10105    --  the dispatch table pointed by Left_Expr.Tag for Typ'Tag
10106
10107    procedure Tagged_Membership
10108      (N         : Node_Id;
10109       SCIL_Node : out Node_Id;
10110       Result    : out Node_Id)
10111    is
10112       Left  : constant Node_Id    := Left_Opnd  (N);
10113       Right : constant Node_Id    := Right_Opnd (N);
10114       Loc   : constant Source_Ptr := Sloc (N);
10115
10116       Left_Type  : Entity_Id;
10117       New_Node   : Node_Id;
10118       Right_Type : Entity_Id;
10119       Obj_Tag    : Node_Id;
10120
10121    begin
10122       SCIL_Node := Empty;
10123
10124       --  Handle entities from the limited view
10125
10126       Left_Type  := Available_View (Etype (Left));
10127       Right_Type := Available_View (Etype (Right));
10128
10129       if Is_Class_Wide_Type (Left_Type) then
10130          Left_Type := Root_Type (Left_Type);
10131       end if;
10132
10133       Obj_Tag :=
10134         Make_Selected_Component (Loc,
10135           Prefix        => Relocate_Node (Left),
10136           Selector_Name =>
10137             New_Reference_To (First_Tag_Component (Left_Type), Loc));
10138
10139       if Is_Class_Wide_Type (Right_Type) then
10140
10141          --  No need to issue a run-time check if we statically know that the
10142          --  result of this membership test is always true. For example,
10143          --  considering the following declarations:
10144
10145          --    type Iface is interface;
10146          --    type T     is tagged null record;
10147          --    type DT    is new T and Iface with null record;
10148
10149          --    Obj1 : T;
10150          --    Obj2 : DT;
10151
10152          --  These membership tests are always true:
10153
10154          --    Obj1 in T'Class
10155          --    Obj2 in T'Class;
10156          --    Obj2 in Iface'Class;
10157
10158          --  We do not need to handle cases where the membership is illegal.
10159          --  For example:
10160
10161          --    Obj1 in DT'Class;     --  Compile time error
10162          --    Obj1 in Iface'Class;  --  Compile time error
10163
10164          if not Is_Class_Wide_Type (Left_Type)
10165            and then (Is_Ancestor (Etype (Right_Type), Left_Type)
10166                        or else (Is_Interface (Etype (Right_Type))
10167                                  and then Interface_Present_In_Ancestor
10168                                            (Typ   => Left_Type,
10169                                             Iface => Etype (Right_Type))))
10170          then
10171             Result := New_Reference_To (Standard_True, Loc);
10172             return;
10173          end if;
10174
10175          --  Ada 2005 (AI-251): Class-wide applied to interfaces
10176
10177          if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
10178
10179             --   Support to: "Iface_CW_Typ in Typ'Class"
10180
10181            or else Is_Interface (Left_Type)
10182          then
10183             --  Issue error if IW_Membership operation not available in a
10184             --  configurable run time setting.
10185
10186             if not RTE_Available (RE_IW_Membership) then
10187                Error_Msg_CRT
10188                  ("dynamic membership test on interface types", N);
10189                Result := Empty;
10190                return;
10191             end if;
10192
10193             Result :=
10194               Make_Function_Call (Loc,
10195                  Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
10196                  Parameter_Associations => New_List (
10197                    Make_Attribute_Reference (Loc,
10198                      Prefix => Obj_Tag,
10199                      Attribute_Name => Name_Address),
10200                    New_Reference_To (
10201                      Node (First_Elmt
10202                             (Access_Disp_Table (Root_Type (Right_Type)))),
10203                      Loc)));
10204
10205          --  Ada 95: Normal case
10206
10207          else
10208             Build_CW_Membership (Loc,
10209               Obj_Tag_Node => Obj_Tag,
10210               Typ_Tag_Node =>
10211                  New_Reference_To (
10212                    Node (First_Elmt
10213                           (Access_Disp_Table (Root_Type (Right_Type)))),
10214                    Loc),
10215               Related_Nod => N,
10216               New_Node    => New_Node);
10217
10218             --  Generate the SCIL node for this class-wide membership test.
10219             --  Done here because the previous call to Build_CW_Membership
10220             --  relocates Obj_Tag.
10221
10222             if Generate_SCIL then
10223                SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
10224                Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
10225                Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
10226             end if;
10227
10228             Result := New_Node;
10229          end if;
10230
10231       --  Right_Type is not a class-wide type
10232
10233       else
10234          --  No need to check the tag of the object if Right_Typ is abstract
10235
10236          if Is_Abstract_Type (Right_Type) then
10237             Result := New_Reference_To (Standard_False, Loc);
10238
10239          else
10240             Result :=
10241               Make_Op_Eq (Loc,
10242                 Left_Opnd  => Obj_Tag,
10243                 Right_Opnd =>
10244                   New_Reference_To
10245                     (Node (First_Elmt (Access_Disp_Table (Right_Type))), Loc));
10246          end if;
10247       end if;
10248    end Tagged_Membership;
10249
10250    ------------------------------
10251    -- Unary_Op_Validity_Checks --
10252    ------------------------------
10253
10254    procedure Unary_Op_Validity_Checks (N : Node_Id) is
10255    begin
10256       if Validity_Checks_On and Validity_Check_Operands then
10257          Ensure_Valid (Right_Opnd (N));
10258       end if;
10259    end Unary_Op_Validity_Checks;
10260
10261 end Exp_Ch4;