OSDN Git Service

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