OSDN Git Service

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