OSDN Git Service

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