OSDN Git Service

2010-06-17 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_util.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ U T I L                              --
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_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Inline;   use Inline;
36 with Itypes;   use Itypes;
37 with Lib;      use Lib;
38 with Nlists;   use Nlists;
39 with Nmake;    use Nmake;
40 with Opt;      use Opt;
41 with Restrict; use Restrict;
42 with Rident;   use Rident;
43 with Sem;      use Sem;
44 with Sem_Aux;  use Sem_Aux;
45 with Sem_Ch8;  use Sem_Ch8;
46 with Sem_SCIL; use Sem_SCIL;
47 with Sem_Eval; use Sem_Eval;
48 with Sem_Res;  use Sem_Res;
49 with Sem_Type; use Sem_Type;
50 with Sem_Util; use Sem_Util;
51 with Snames;   use Snames;
52 with Stand;    use Stand;
53 with Stringt;  use Stringt;
54 with Targparm; use Targparm;
55 with Tbuild;   use Tbuild;
56 with Ttypes;   use Ttypes;
57 with Uintp;    use Uintp;
58 with Urealp;   use Urealp;
59 with Validsw;  use Validsw;
60
61 package body Exp_Util is
62
63    -----------------------
64    -- Local Subprograms --
65    -----------------------
66
67    function Build_Task_Array_Image
68      (Loc    : Source_Ptr;
69       Id_Ref : Node_Id;
70       A_Type : Entity_Id;
71       Dyn    : Boolean := False) return Node_Id;
72    --  Build function to generate the image string for a task that is an
73    --  array component, concatenating the images of each index. To avoid
74    --  storage leaks, the string is built with successive slice assignments.
75    --  The flag Dyn indicates whether this is called for the initialization
76    --  procedure of an array of tasks, or for the name of a dynamically
77    --  created task that is assigned to an indexed component.
78
79    function Build_Task_Image_Function
80      (Loc   : Source_Ptr;
81       Decls : List_Id;
82       Stats : List_Id;
83       Res   : Entity_Id) return Node_Id;
84    --  Common processing for Task_Array_Image and Task_Record_Image.
85    --  Build function body that computes image.
86
87    procedure Build_Task_Image_Prefix
88       (Loc    : Source_Ptr;
89        Len    : out Entity_Id;
90        Res    : out Entity_Id;
91        Pos    : out Entity_Id;
92        Prefix : Entity_Id;
93        Sum    : Node_Id;
94        Decls  : List_Id;
95        Stats  : List_Id);
96    --  Common processing for Task_Array_Image and Task_Record_Image.
97    --  Create local variables and assign prefix of name to result string.
98
99    function Build_Task_Record_Image
100      (Loc    : Source_Ptr;
101       Id_Ref : Node_Id;
102       Dyn    : Boolean := False) return Node_Id;
103    --  Build function to generate the image string for a task that is a
104    --  record component. Concatenate name of variable with that of selector.
105    --  The flag Dyn indicates whether this is called for the initialization
106    --  procedure of record with task components, or for a dynamically
107    --  created task that is assigned to a selected component.
108
109    function Make_CW_Equivalent_Type
110      (T : Entity_Id;
111       E : Node_Id) return Entity_Id;
112    --  T is a class-wide type entity, E is the initial expression node that
113    --  constrains T in case such as: " X: T := E" or "new T'(E)"
114    --  This function returns the entity of the Equivalent type and inserts
115    --  on the fly the necessary declaration such as:
116    --
117    --    type anon is record
118    --       _parent : Root_Type (T); constrained with E discriminants (if any)
119    --       Extension : String (1 .. expr to match size of E);
120    --    end record;
121    --
122    --  This record is compatible with any object of the class of T thanks
123    --  to the first field and has the same size as E thanks to the second.
124
125    function Make_Literal_Range
126      (Loc         : Source_Ptr;
127       Literal_Typ : Entity_Id) return Node_Id;
128    --  Produce a Range node whose bounds are:
129    --    Low_Bound (Literal_Type) ..
130    --        Low_Bound (Literal_Type) + (Length (Literal_Typ) - 1)
131    --  this is used for expanding declarations like X : String := "sdfgdfg";
132    --
133    --  If the index type of the target array is not integer, we generate:
134    --     Low_Bound (Literal_Type) ..
135    --        Literal_Type'Val
136    --          (Literal_Type'Pos (Low_Bound (Literal_Type))
137    --             + (Length (Literal_Typ) -1))
138
139    function Make_Non_Empty_Check
140      (Loc : Source_Ptr;
141       N   : Node_Id) return Node_Id;
142    --  Produce a boolean expression checking that the unidimensional array
143    --  node N is not empty.
144
145    function New_Class_Wide_Subtype
146      (CW_Typ : Entity_Id;
147       N      : Node_Id) return Entity_Id;
148    --  Create an implicit subtype of CW_Typ attached to node N
149
150    ----------------------
151    -- Adjust_Condition --
152    ----------------------
153
154    procedure Adjust_Condition (N : Node_Id) is
155    begin
156       if No (N) then
157          return;
158       end if;
159
160       declare
161          Loc : constant Source_Ptr := Sloc (N);
162          T   : constant Entity_Id  := Etype (N);
163          Ti  : Entity_Id;
164
165       begin
166          --  For now, we simply ignore a call where the argument has no
167          --  type (probably case of unanalyzed condition), or has a type
168          --  that is not Boolean. This is because this is a pretty marginal
169          --  piece of functionality, and violations of these rules are
170          --  likely to be truly marginal (how much code uses Fortran Logical
171          --  as the barrier to a protected entry?) and we do not want to
172          --  blow up existing programs. We can change this to an assertion
173          --  after 3.12a is released ???
174
175          if No (T) or else not Is_Boolean_Type (T) then
176             return;
177          end if;
178
179          --  Apply validity checking if needed
180
181          if Validity_Checks_On and Validity_Check_Tests then
182             Ensure_Valid (N);
183          end if;
184
185          --  Immediate return if standard boolean, the most common case,
186          --  where nothing needs to be done.
187
188          if Base_Type (T) = Standard_Boolean then
189             return;
190          end if;
191
192          --  Case of zero/non-zero semantics or non-standard enumeration
193          --  representation. In each case, we rewrite the node as:
194
195          --      ityp!(N) /= False'Enum_Rep
196
197          --  where ityp is an integer type with large enough size to hold
198          --  any value of type T.
199
200          if Nonzero_Is_True (T) or else Has_Non_Standard_Rep (T) then
201             if Esize (T) <= Esize (Standard_Integer) then
202                Ti := Standard_Integer;
203             else
204                Ti := Standard_Long_Long_Integer;
205             end if;
206
207             Rewrite (N,
208               Make_Op_Ne (Loc,
209                 Left_Opnd  => Unchecked_Convert_To (Ti, N),
210                 Right_Opnd =>
211                   Make_Attribute_Reference (Loc,
212                     Attribute_Name => Name_Enum_Rep,
213                     Prefix         =>
214                       New_Occurrence_Of (First_Literal (T), Loc))));
215             Analyze_And_Resolve (N, Standard_Boolean);
216
217          else
218             Rewrite (N, Convert_To (Standard_Boolean, N));
219             Analyze_And_Resolve (N, Standard_Boolean);
220          end if;
221       end;
222    end Adjust_Condition;
223
224    ------------------------
225    -- Adjust_Result_Type --
226    ------------------------
227
228    procedure Adjust_Result_Type (N : Node_Id; T : Entity_Id) is
229    begin
230       --  Ignore call if current type is not Standard.Boolean
231
232       if Etype (N) /= Standard_Boolean then
233          return;
234       end if;
235
236       --  If result is already of correct type, nothing to do. Note that
237       --  this will get the most common case where everything has a type
238       --  of Standard.Boolean.
239
240       if Base_Type (T) = Standard_Boolean then
241          return;
242
243       else
244          declare
245             KP : constant Node_Kind := Nkind (Parent (N));
246
247          begin
248             --  If result is to be used as a Condition in the syntax, no need
249             --  to convert it back, since if it was changed to Standard.Boolean
250             --  using Adjust_Condition, that is just fine for this usage.
251
252             if KP in N_Raise_xxx_Error or else KP in N_Has_Condition then
253                return;
254
255             --  If result is an operand of another logical operation, no need
256             --  to reset its type, since Standard.Boolean is just fine, and
257             --  such operations always do Adjust_Condition on their operands.
258
259             elsif     KP in N_Op_Boolean
260               or else KP in N_Short_Circuit
261               or else KP = N_Op_Not
262             then
263                return;
264
265             --  Otherwise we perform a conversion from the current type,
266             --  which must be Standard.Boolean, to the desired type.
267
268             else
269                Set_Analyzed (N);
270                Rewrite (N, Convert_To (T, N));
271                Analyze_And_Resolve (N, T);
272             end if;
273          end;
274       end if;
275    end Adjust_Result_Type;
276
277    --------------------------
278    -- Append_Freeze_Action --
279    --------------------------
280
281    procedure Append_Freeze_Action (T : Entity_Id; N : Node_Id) is
282       Fnode : Node_Id;
283
284    begin
285       Ensure_Freeze_Node (T);
286       Fnode := Freeze_Node (T);
287
288       if No (Actions (Fnode)) then
289          Set_Actions (Fnode, New_List);
290       end if;
291
292       Append (N, Actions (Fnode));
293    end Append_Freeze_Action;
294
295    ---------------------------
296    -- Append_Freeze_Actions --
297    ---------------------------
298
299    procedure Append_Freeze_Actions (T : Entity_Id; L : List_Id) is
300       Fnode : constant Node_Id := Freeze_Node (T);
301
302    begin
303       if No (L) then
304          return;
305
306       else
307          if No (Actions (Fnode)) then
308             Set_Actions (Fnode, L);
309
310          else
311             Append_List (L, Actions (Fnode));
312          end if;
313
314       end if;
315    end Append_Freeze_Actions;
316
317    ------------------------
318    -- Build_Runtime_Call --
319    ------------------------
320
321    function Build_Runtime_Call (Loc : Source_Ptr; RE : RE_Id) return Node_Id is
322    begin
323       --  If entity is not available, we can skip making the call (this avoids
324       --  junk duplicated error messages in a number of cases).
325
326       if not RTE_Available (RE) then
327          return Make_Null_Statement (Loc);
328       else
329          return
330            Make_Procedure_Call_Statement (Loc,
331              Name => New_Reference_To (RTE (RE), Loc));
332       end if;
333    end Build_Runtime_Call;
334
335    ----------------------------
336    -- Build_Task_Array_Image --
337    ----------------------------
338
339    --  This function generates the body for a function that constructs the
340    --  image string for a task that is an array component. The function is
341    --  local to the init proc for the array type, and is called for each one
342    --  of the components. The constructed image has the form of an indexed
343    --  component, whose prefix is the outer variable of the array type.
344    --  The n-dimensional array type has known indices Index, Index2...
345    --  Id_Ref is an indexed component form created by the enclosing init proc.
346    --  Its successive indices are Val1, Val2, ... which are the loop variables
347    --  in the loops that call the individual task init proc on each component.
348
349    --  The generated function has the following structure:
350
351    --  function F return String is
352    --     Pref : string renames Task_Name;
353    --     T1   : String := Index1'Image (Val1);
354    --     ...
355    --     Tn   : String := indexn'image (Valn);
356    --     Len  : Integer := T1'Length + ... + Tn'Length + n + 1;
357    --     --  Len includes commas and the end parentheses.
358    --     Res  : String (1..Len);
359    --     Pos  : Integer := Pref'Length;
360    --
361    --  begin
362    --     Res (1 .. Pos) := Pref;
363    --     Pos := Pos + 1;
364    --     Res (Pos)    := '(';
365    --     Pos := Pos + 1;
366    --     Res (Pos .. Pos + T1'Length - 1) := T1;
367    --     Pos := Pos + T1'Length;
368    --     Res (Pos) := '.';
369    --     Pos := Pos + 1;
370    --     ...
371    --     Res (Pos .. Pos + Tn'Length - 1) := Tn;
372    --     Res (Len) := ')';
373    --
374    --     return Res;
375    --  end F;
376    --
377    --  Needless to say, multidimensional arrays of tasks are rare enough
378    --  that the bulkiness of this code is not really a concern.
379
380    function Build_Task_Array_Image
381      (Loc    : Source_Ptr;
382       Id_Ref : Node_Id;
383       A_Type : Entity_Id;
384       Dyn    : Boolean := False) return Node_Id
385    is
386       Dims : constant Nat := Number_Dimensions (A_Type);
387       --  Number of dimensions for array of tasks
388
389       Temps : array (1 .. Dims) of Entity_Id;
390       --  Array of temporaries to hold string for each index
391
392       Indx : Node_Id;
393       --  Index expression
394
395       Len : Entity_Id;
396       --  Total length of generated name
397
398       Pos : Entity_Id;
399       --  Running index for substring assignments
400
401       Pref : constant Entity_Id := Make_Temporary (Loc, 'P');
402       --  Name of enclosing variable, prefix of resulting name
403
404       Res : Entity_Id;
405       --  String to hold result
406
407       Val : Node_Id;
408       --  Value of successive indices
409
410       Sum : Node_Id;
411       --  Expression to compute total size of string
412
413       T : Entity_Id;
414       --  Entity for name at one index position
415
416       Decls : constant List_Id := New_List;
417       Stats : constant List_Id := New_List;
418
419    begin
420       --  For a dynamic task, the name comes from the target variable.
421       --  For a static one it is a formal of the enclosing init proc.
422
423       if Dyn then
424          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
425          Append_To (Decls,
426            Make_Object_Declaration (Loc,
427              Defining_Identifier => Pref,
428              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
429              Expression =>
430                Make_String_Literal (Loc,
431                  Strval => String_From_Name_Buffer)));
432
433       else
434          Append_To (Decls,
435            Make_Object_Renaming_Declaration (Loc,
436              Defining_Identifier => Pref,
437              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
438              Name                => Make_Identifier (Loc, Name_uTask_Name)));
439       end if;
440
441       Indx := First_Index (A_Type);
442       Val  := First (Expressions (Id_Ref));
443
444       for J in 1 .. Dims loop
445          T := Make_Temporary (Loc, 'T');
446          Temps (J) := T;
447
448          Append_To (Decls,
449             Make_Object_Declaration (Loc,
450                Defining_Identifier => T,
451                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
452                Expression =>
453                  Make_Attribute_Reference (Loc,
454                    Attribute_Name => Name_Image,
455                    Prefix         => New_Occurrence_Of (Etype (Indx), Loc),
456                    Expressions    => New_List (New_Copy_Tree (Val)))));
457
458          Next_Index (Indx);
459          Next (Val);
460       end loop;
461
462       Sum := Make_Integer_Literal (Loc, Dims + 1);
463
464       Sum :=
465         Make_Op_Add (Loc,
466           Left_Opnd => Sum,
467           Right_Opnd =>
468            Make_Attribute_Reference (Loc,
469              Attribute_Name => Name_Length,
470              Prefix =>
471                New_Occurrence_Of (Pref, Loc),
472              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
473
474       for J in 1 .. Dims loop
475          Sum :=
476             Make_Op_Add (Loc,
477              Left_Opnd => Sum,
478              Right_Opnd =>
479               Make_Attribute_Reference (Loc,
480                 Attribute_Name => Name_Length,
481                 Prefix =>
482                   New_Occurrence_Of (Temps (J), Loc),
483                 Expressions => New_List (Make_Integer_Literal (Loc, 1))));
484       end loop;
485
486       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
487
488       Set_Character_Literal_Name (Char_Code (Character'Pos ('(')));
489
490       Append_To (Stats,
491          Make_Assignment_Statement (Loc,
492            Name => Make_Indexed_Component (Loc,
493               Prefix => New_Occurrence_Of (Res, Loc),
494               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
495            Expression =>
496              Make_Character_Literal (Loc,
497                Chars => Name_Find,
498                Char_Literal_Value =>
499                  UI_From_Int (Character'Pos ('(')))));
500
501       Append_To (Stats,
502          Make_Assignment_Statement (Loc,
503             Name => New_Occurrence_Of (Pos, Loc),
504             Expression =>
505               Make_Op_Add (Loc,
506                 Left_Opnd => New_Occurrence_Of (Pos, Loc),
507                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
508
509       for J in 1 .. Dims loop
510
511          Append_To (Stats,
512             Make_Assignment_Statement (Loc,
513               Name => Make_Slice (Loc,
514                  Prefix => New_Occurrence_Of (Res, Loc),
515                  Discrete_Range  =>
516                    Make_Range (Loc,
517                       Low_Bound => New_Occurrence_Of  (Pos, Loc),
518                       High_Bound => Make_Op_Subtract (Loc,
519                         Left_Opnd =>
520                           Make_Op_Add (Loc,
521                             Left_Opnd => New_Occurrence_Of (Pos, Loc),
522                             Right_Opnd =>
523                               Make_Attribute_Reference (Loc,
524                                 Attribute_Name => Name_Length,
525                                 Prefix =>
526                                   New_Occurrence_Of (Temps (J), Loc),
527                                 Expressions =>
528                                   New_List (Make_Integer_Literal (Loc, 1)))),
529                          Right_Opnd => Make_Integer_Literal (Loc, 1)))),
530
531               Expression => New_Occurrence_Of (Temps (J), Loc)));
532
533          if J < Dims then
534             Append_To (Stats,
535                Make_Assignment_Statement (Loc,
536                   Name => New_Occurrence_Of (Pos, Loc),
537                   Expression =>
538                     Make_Op_Add (Loc,
539                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
540                       Right_Opnd =>
541                         Make_Attribute_Reference (Loc,
542                           Attribute_Name => Name_Length,
543                             Prefix => New_Occurrence_Of (Temps (J), Loc),
544                             Expressions =>
545                               New_List (Make_Integer_Literal (Loc, 1))))));
546
547             Set_Character_Literal_Name (Char_Code (Character'Pos (',')));
548
549             Append_To (Stats,
550                Make_Assignment_Statement (Loc,
551                  Name => Make_Indexed_Component (Loc,
552                     Prefix => New_Occurrence_Of (Res, Loc),
553                     Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
554                  Expression =>
555                    Make_Character_Literal (Loc,
556                      Chars => Name_Find,
557                      Char_Literal_Value =>
558                        UI_From_Int (Character'Pos (',')))));
559
560             Append_To (Stats,
561               Make_Assignment_Statement (Loc,
562                 Name => New_Occurrence_Of (Pos, Loc),
563                   Expression =>
564                     Make_Op_Add (Loc,
565                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
566                       Right_Opnd => Make_Integer_Literal (Loc, 1))));
567          end if;
568       end loop;
569
570       Set_Character_Literal_Name (Char_Code (Character'Pos (')')));
571
572       Append_To (Stats,
573          Make_Assignment_Statement (Loc,
574            Name => Make_Indexed_Component (Loc,
575               Prefix => New_Occurrence_Of (Res, Loc),
576               Expressions => New_List (New_Occurrence_Of (Len, Loc))),
577            Expression =>
578              Make_Character_Literal (Loc,
579                Chars => Name_Find,
580                Char_Literal_Value =>
581                  UI_From_Int (Character'Pos (')')))));
582       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
583    end Build_Task_Array_Image;
584
585    ----------------------------
586    -- Build_Task_Image_Decls --
587    ----------------------------
588
589    function Build_Task_Image_Decls
590      (Loc          : Source_Ptr;
591       Id_Ref       : Node_Id;
592       A_Type       : Entity_Id;
593       In_Init_Proc : Boolean := False) return List_Id
594    is
595       Decls  : constant List_Id   := New_List;
596       T_Id   : Entity_Id := Empty;
597       Decl   : Node_Id;
598       Expr   : Node_Id   := Empty;
599       Fun    : Node_Id   := Empty;
600       Is_Dyn : constant Boolean :=
601                  Nkind (Parent (Id_Ref)) = N_Assignment_Statement
602                    and then
603                  Nkind (Expression (Parent (Id_Ref))) = N_Allocator;
604
605    begin
606       --  If Discard_Names or No_Implicit_Heap_Allocations are in effect,
607       --  generate a dummy declaration only.
608
609       if Restriction_Active (No_Implicit_Heap_Allocations)
610         or else Global_Discard_Names
611       then
612          T_Id := Make_Temporary (Loc, 'J');
613          Name_Len := 0;
614
615          return
616            New_List (
617              Make_Object_Declaration (Loc,
618                Defining_Identifier => T_Id,
619                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
620                Expression =>
621                  Make_String_Literal (Loc,
622                    Strval => String_From_Name_Buffer)));
623
624       else
625          if Nkind (Id_Ref) = N_Identifier
626            or else Nkind (Id_Ref) = N_Defining_Identifier
627          then
628             --  For a simple variable, the image of the task is built from
629             --  the name of the variable. To avoid possible conflict with
630             --  the anonymous type created for a single protected object,
631             --  add a numeric suffix.
632
633             T_Id :=
634               Make_Defining_Identifier (Loc,
635                 New_External_Name (Chars (Id_Ref), 'T', 1));
636
637             Get_Name_String (Chars (Id_Ref));
638
639             Expr :=
640               Make_String_Literal (Loc,
641                 Strval => String_From_Name_Buffer);
642
643          elsif Nkind (Id_Ref) = N_Selected_Component then
644             T_Id :=
645               Make_Defining_Identifier (Loc,
646                 New_External_Name (Chars (Selector_Name (Id_Ref)), 'T'));
647             Fun := Build_Task_Record_Image (Loc, Id_Ref, Is_Dyn);
648
649          elsif Nkind (Id_Ref) = N_Indexed_Component then
650             T_Id :=
651               Make_Defining_Identifier (Loc,
652                 New_External_Name (Chars (A_Type), 'N'));
653
654             Fun := Build_Task_Array_Image (Loc, Id_Ref, A_Type, Is_Dyn);
655          end if;
656       end if;
657
658       if Present (Fun) then
659          Append (Fun, Decls);
660          Expr := Make_Function_Call (Loc,
661            Name => New_Occurrence_Of (Defining_Entity (Fun), Loc));
662
663          if not In_Init_Proc and then VM_Target = No_VM then
664             Set_Uses_Sec_Stack (Defining_Entity (Fun));
665          end if;
666       end if;
667
668       Decl := Make_Object_Declaration (Loc,
669         Defining_Identifier => T_Id,
670         Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
671         Constant_Present    => True,
672         Expression          => Expr);
673
674       Append (Decl, Decls);
675       return Decls;
676    end Build_Task_Image_Decls;
677
678    -------------------------------
679    -- Build_Task_Image_Function --
680    -------------------------------
681
682    function Build_Task_Image_Function
683      (Loc   : Source_Ptr;
684       Decls : List_Id;
685       Stats : List_Id;
686       Res   : Entity_Id) return Node_Id
687    is
688       Spec : Node_Id;
689
690    begin
691       Append_To (Stats,
692         Make_Simple_Return_Statement (Loc,
693           Expression => New_Occurrence_Of (Res, Loc)));
694
695       Spec := Make_Function_Specification (Loc,
696         Defining_Unit_Name => Make_Temporary (Loc, 'F'),
697         Result_Definition  => New_Occurrence_Of (Standard_String, Loc));
698
699       --  Calls to 'Image use the secondary stack, which must be cleaned
700       --  up after the task name is built.
701
702       return Make_Subprogram_Body (Loc,
703          Specification => Spec,
704          Declarations => Decls,
705          Handled_Statement_Sequence =>
706            Make_Handled_Sequence_Of_Statements (Loc, Statements => Stats));
707    end Build_Task_Image_Function;
708
709    -----------------------------
710    -- Build_Task_Image_Prefix --
711    -----------------------------
712
713    procedure Build_Task_Image_Prefix
714       (Loc    : Source_Ptr;
715        Len    : out Entity_Id;
716        Res    : out Entity_Id;
717        Pos    : out Entity_Id;
718        Prefix : Entity_Id;
719        Sum    : Node_Id;
720        Decls  : List_Id;
721        Stats  : List_Id)
722    is
723    begin
724       Len := Make_Temporary (Loc, 'L', Sum);
725
726       Append_To (Decls,
727         Make_Object_Declaration (Loc,
728           Defining_Identifier => Len,
729           Object_Definition   => New_Occurrence_Of (Standard_Integer, Loc),
730           Expression          => Sum));
731
732       Res := Make_Temporary (Loc, 'R');
733
734       Append_To (Decls,
735          Make_Object_Declaration (Loc,
736             Defining_Identifier => Res,
737             Object_Definition =>
738                Make_Subtype_Indication (Loc,
739                   Subtype_Mark => New_Occurrence_Of (Standard_String, Loc),
740                Constraint =>
741                  Make_Index_Or_Discriminant_Constraint (Loc,
742                    Constraints =>
743                      New_List (
744                        Make_Range (Loc,
745                          Low_Bound => Make_Integer_Literal (Loc, 1),
746                          High_Bound => New_Occurrence_Of (Len, Loc)))))));
747
748       Pos := Make_Temporary (Loc, 'P');
749
750       Append_To (Decls,
751          Make_Object_Declaration (Loc,
752             Defining_Identifier => Pos,
753             Object_Definition   => New_Occurrence_Of (Standard_Integer, Loc)));
754
755       --  Pos := Prefix'Length;
756
757       Append_To (Stats,
758          Make_Assignment_Statement (Loc,
759             Name => New_Occurrence_Of (Pos, Loc),
760             Expression =>
761               Make_Attribute_Reference (Loc,
762                 Attribute_Name => Name_Length,
763                 Prefix         => New_Occurrence_Of (Prefix, Loc),
764                 Expressions    => New_List (Make_Integer_Literal (Loc, 1)))));
765
766       --  Res (1 .. Pos) := Prefix;
767
768       Append_To (Stats,
769         Make_Assignment_Statement (Loc,
770           Name =>
771             Make_Slice (Loc,
772               Prefix          => New_Occurrence_Of (Res, Loc),
773               Discrete_Range  =>
774                 Make_Range (Loc,
775                    Low_Bound  => Make_Integer_Literal (Loc, 1),
776                    High_Bound => New_Occurrence_Of (Pos, Loc))),
777
778           Expression => New_Occurrence_Of (Prefix, Loc)));
779
780       Append_To (Stats,
781          Make_Assignment_Statement (Loc,
782             Name       => New_Occurrence_Of (Pos, Loc),
783             Expression =>
784               Make_Op_Add (Loc,
785                 Left_Opnd  => New_Occurrence_Of (Pos, Loc),
786                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
787    end Build_Task_Image_Prefix;
788
789    -----------------------------
790    -- Build_Task_Record_Image --
791    -----------------------------
792
793    function Build_Task_Record_Image
794      (Loc    : Source_Ptr;
795       Id_Ref : Node_Id;
796       Dyn    : Boolean := False) return Node_Id
797    is
798       Len : Entity_Id;
799       --  Total length of generated name
800
801       Pos : Entity_Id;
802       --  Index into result
803
804       Res : Entity_Id;
805       --  String to hold result
806
807       Pref : constant Entity_Id := Make_Temporary (Loc, 'P');
808       --  Name of enclosing variable, prefix of resulting name
809
810       Sum : Node_Id;
811       --  Expression to compute total size of string
812
813       Sel : Entity_Id;
814       --  Entity for selector name
815
816       Decls : constant List_Id := New_List;
817       Stats : constant List_Id := New_List;
818
819    begin
820       --  For a dynamic task, the name comes from the target variable.
821       --  For a static one it is a formal of the enclosing init proc.
822
823       if Dyn then
824          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
825          Append_To (Decls,
826            Make_Object_Declaration (Loc,
827              Defining_Identifier => Pref,
828              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
829              Expression =>
830                Make_String_Literal (Loc,
831                  Strval => String_From_Name_Buffer)));
832
833       else
834          Append_To (Decls,
835            Make_Object_Renaming_Declaration (Loc,
836              Defining_Identifier => Pref,
837              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
838              Name                => Make_Identifier (Loc, Name_uTask_Name)));
839       end if;
840
841       Sel := Make_Temporary (Loc, 'S');
842
843       Get_Name_String (Chars (Selector_Name (Id_Ref)));
844
845       Append_To (Decls,
846          Make_Object_Declaration (Loc,
847            Defining_Identifier => Sel,
848            Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
849            Expression          =>
850              Make_String_Literal (Loc,
851                Strval => String_From_Name_Buffer)));
852
853       Sum := Make_Integer_Literal (Loc, Nat (Name_Len + 1));
854
855       Sum :=
856         Make_Op_Add (Loc,
857           Left_Opnd => Sum,
858           Right_Opnd =>
859            Make_Attribute_Reference (Loc,
860              Attribute_Name => Name_Length,
861              Prefix =>
862                New_Occurrence_Of (Pref, Loc),
863              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
864
865       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
866
867       Set_Character_Literal_Name (Char_Code (Character'Pos ('.')));
868
869       --  Res (Pos) := '.';
870
871       Append_To (Stats,
872          Make_Assignment_Statement (Loc,
873            Name => Make_Indexed_Component (Loc,
874               Prefix => New_Occurrence_Of (Res, Loc),
875               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
876            Expression =>
877              Make_Character_Literal (Loc,
878                Chars => Name_Find,
879                Char_Literal_Value =>
880                  UI_From_Int (Character'Pos ('.')))));
881
882       Append_To (Stats,
883         Make_Assignment_Statement (Loc,
884           Name => New_Occurrence_Of (Pos, Loc),
885           Expression =>
886             Make_Op_Add (Loc,
887               Left_Opnd => New_Occurrence_Of (Pos, Loc),
888               Right_Opnd => Make_Integer_Literal (Loc, 1))));
889
890       --  Res (Pos .. Len) := Selector;
891
892       Append_To (Stats,
893         Make_Assignment_Statement (Loc,
894           Name => Make_Slice (Loc,
895              Prefix => New_Occurrence_Of (Res, Loc),
896              Discrete_Range  =>
897                Make_Range (Loc,
898                  Low_Bound  => New_Occurrence_Of (Pos, Loc),
899                  High_Bound => New_Occurrence_Of (Len, Loc))),
900           Expression => New_Occurrence_Of (Sel, Loc)));
901
902       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
903    end Build_Task_Record_Image;
904
905    ----------------------------------
906    -- Component_May_Be_Bit_Aligned --
907    ----------------------------------
908
909    function Component_May_Be_Bit_Aligned (Comp : Entity_Id) return Boolean is
910       UT : constant Entity_Id := Underlying_Type (Etype (Comp));
911
912    begin
913       --  If no component clause, then everything is fine, since the back end
914       --  never bit-misaligns by default, even if there is a pragma Packed for
915       --  the record.
916
917       if No (Component_Clause (Comp)) then
918          return False;
919       end if;
920
921       --  It is only array and record types that cause trouble
922
923       if not Is_Record_Type (UT)
924         and then not Is_Array_Type (UT)
925       then
926          return False;
927
928       --  If we know that we have a small (64 bits or less) record or small
929       --  bit-packed array, then everything is fine, since the back end can
930       --  handle these cases correctly.
931
932       elsif Esize (Comp) <= 64
933         and then (Is_Record_Type (UT)
934                    or else Is_Bit_Packed_Array (UT))
935       then
936          return False;
937
938       --  Otherwise if the component is not byte aligned, we know we have the
939       --  nasty unaligned case.
940
941       elsif Normalized_First_Bit (Comp) /= Uint_0
942         or else Esize (Comp) mod System_Storage_Unit /= Uint_0
943       then
944          return True;
945
946       --  If we are large and byte aligned, then OK at this level
947
948       else
949          return False;
950       end if;
951    end Component_May_Be_Bit_Aligned;
952
953    -----------------------------------
954    -- Corresponding_Runtime_Package --
955    -----------------------------------
956
957    function Corresponding_Runtime_Package (Typ : Entity_Id) return RTU_Id is
958       Pkg_Id : RTU_Id := RTU_Null;
959
960    begin
961       pragma Assert (Is_Concurrent_Type (Typ));
962
963       if Ekind (Typ) in Protected_Kind then
964          if Has_Entries (Typ)
965            or else Has_Interrupt_Handler (Typ)
966            or else (Has_Attach_Handler (Typ)
967                       and then not Restricted_Profile)
968
969             --  A protected type without entries that covers an interface and
970             --  overrides the abstract routines with protected procedures is
971             --  considered equivalent to a protected type with entries in the
972             --  context of dispatching select statements. It is sufficient to
973             --  check for the presence of an interface list in the declaration
974             --  node to recognize this case.
975
976            or else Present (Interface_List (Parent (Typ)))
977          then
978             if Abort_Allowed
979               or else Restriction_Active (No_Entry_Queue) = False
980               or else Number_Entries (Typ) > 1
981               or else (Has_Attach_Handler (Typ)
982                          and then not Restricted_Profile)
983             then
984                Pkg_Id := System_Tasking_Protected_Objects_Entries;
985             else
986                Pkg_Id := System_Tasking_Protected_Objects_Single_Entry;
987             end if;
988
989          else
990             Pkg_Id := System_Tasking_Protected_Objects;
991          end if;
992       end if;
993
994       return Pkg_Id;
995    end Corresponding_Runtime_Package;
996
997    -------------------------------
998    -- Convert_To_Actual_Subtype --
999    -------------------------------
1000
1001    procedure Convert_To_Actual_Subtype (Exp : Entity_Id) is
1002       Act_ST : Entity_Id;
1003
1004    begin
1005       Act_ST := Get_Actual_Subtype (Exp);
1006
1007       if Act_ST = Etype (Exp) then
1008          return;
1009
1010       else
1011          Rewrite (Exp,
1012            Convert_To (Act_ST, Relocate_Node (Exp)));
1013          Analyze_And_Resolve (Exp, Act_ST);
1014       end if;
1015    end Convert_To_Actual_Subtype;
1016
1017    -----------------------------------
1018    -- Current_Sem_Unit_Declarations --
1019    -----------------------------------
1020
1021    function Current_Sem_Unit_Declarations return List_Id is
1022       U     : Node_Id := Unit (Cunit (Current_Sem_Unit));
1023       Decls : List_Id;
1024
1025    begin
1026       --  If the current unit is a package body, locate the visible
1027       --  declarations of the package spec.
1028
1029       if Nkind (U) = N_Package_Body then
1030          U := Unit (Library_Unit (Cunit (Current_Sem_Unit)));
1031       end if;
1032
1033       if Nkind (U) = N_Package_Declaration then
1034          U := Specification (U);
1035          Decls := Visible_Declarations (U);
1036
1037          if No (Decls) then
1038             Decls := New_List;
1039             Set_Visible_Declarations (U, Decls);
1040          end if;
1041
1042       else
1043          Decls := Declarations (U);
1044
1045          if No (Decls) then
1046             Decls := New_List;
1047             Set_Declarations (U, Decls);
1048          end if;
1049       end if;
1050
1051       return Decls;
1052    end Current_Sem_Unit_Declarations;
1053
1054    -----------------------
1055    -- Duplicate_Subexpr --
1056    -----------------------
1057
1058    function Duplicate_Subexpr
1059      (Exp      : Node_Id;
1060       Name_Req : Boolean := False) return Node_Id
1061    is
1062    begin
1063       Remove_Side_Effects (Exp, Name_Req);
1064       return New_Copy_Tree (Exp);
1065    end Duplicate_Subexpr;
1066
1067    ---------------------------------
1068    -- Duplicate_Subexpr_No_Checks --
1069    ---------------------------------
1070
1071    function Duplicate_Subexpr_No_Checks
1072      (Exp      : Node_Id;
1073       Name_Req : Boolean := False) return Node_Id
1074    is
1075       New_Exp : Node_Id;
1076
1077    begin
1078       Remove_Side_Effects (Exp, Name_Req);
1079       New_Exp := New_Copy_Tree (Exp);
1080       Remove_Checks (New_Exp);
1081       return New_Exp;
1082    end Duplicate_Subexpr_No_Checks;
1083
1084    -----------------------------------
1085    -- Duplicate_Subexpr_Move_Checks --
1086    -----------------------------------
1087
1088    function Duplicate_Subexpr_Move_Checks
1089      (Exp      : Node_Id;
1090       Name_Req : Boolean := False) return Node_Id
1091    is
1092       New_Exp : Node_Id;
1093
1094    begin
1095       Remove_Side_Effects (Exp, Name_Req);
1096       New_Exp := New_Copy_Tree (Exp);
1097       Remove_Checks (Exp);
1098       return New_Exp;
1099    end Duplicate_Subexpr_Move_Checks;
1100
1101    --------------------
1102    -- Ensure_Defined --
1103    --------------------
1104
1105    procedure Ensure_Defined (Typ : Entity_Id; N : Node_Id) is
1106       IR : Node_Id;
1107
1108    begin
1109       --  An itype reference must only be created if this is a local
1110       --  itype, so that gigi can elaborate it on the proper objstack.
1111
1112       if Is_Itype (Typ)
1113         and then Scope (Typ) = Current_Scope
1114       then
1115          IR := Make_Itype_Reference (Sloc (N));
1116          Set_Itype (IR, Typ);
1117          Insert_Action (N, IR);
1118       end if;
1119    end Ensure_Defined;
1120
1121    --------------------
1122    -- Entry_Names_OK --
1123    --------------------
1124
1125    function Entry_Names_OK return Boolean is
1126    begin
1127       return
1128         not Restricted_Profile
1129           and then not Global_Discard_Names
1130           and then not Restriction_Active (No_Implicit_Heap_Allocations)
1131           and then not Restriction_Active (No_Local_Allocators);
1132    end Entry_Names_OK;
1133
1134    ---------------------
1135    -- Evolve_And_Then --
1136    ---------------------
1137
1138    procedure Evolve_And_Then (Cond : in out Node_Id; Cond1 : Node_Id) is
1139    begin
1140       if No (Cond) then
1141          Cond := Cond1;
1142       else
1143          Cond :=
1144            Make_And_Then (Sloc (Cond1),
1145              Left_Opnd  => Cond,
1146              Right_Opnd => Cond1);
1147       end if;
1148    end Evolve_And_Then;
1149
1150    --------------------
1151    -- Evolve_Or_Else --
1152    --------------------
1153
1154    procedure Evolve_Or_Else (Cond : in out Node_Id; Cond1 : Node_Id) is
1155    begin
1156       if No (Cond) then
1157          Cond := Cond1;
1158       else
1159          Cond :=
1160            Make_Or_Else (Sloc (Cond1),
1161              Left_Opnd  => Cond,
1162              Right_Opnd => Cond1);
1163       end if;
1164    end Evolve_Or_Else;
1165
1166    ------------------------------
1167    -- Expand_Subtype_From_Expr --
1168    ------------------------------
1169
1170    --  This function is applicable for both static and dynamic allocation of
1171    --  objects which are constrained by an initial expression. Basically it
1172    --  transforms an unconstrained subtype indication into a constrained one.
1173    --  The expression may also be transformed in certain cases in order to
1174    --  avoid multiple evaluation. In the static allocation case, the general
1175    --  scheme is:
1176
1177    --     Val : T := Expr;
1178
1179    --        is transformed into
1180
1181    --     Val : Constrained_Subtype_of_T := Maybe_Modified_Expr;
1182    --
1183    --  Here are the main cases :
1184    --
1185    --  <if Expr is a Slice>
1186    --    Val : T ([Index_Subtype (Expr)]) := Expr;
1187    --
1188    --  <elsif Expr is a String Literal>
1189    --    Val : T (T'First .. T'First + Length (string literal) - 1) := Expr;
1190    --
1191    --  <elsif Expr is Constrained>
1192    --    subtype T is Type_Of_Expr
1193    --    Val : T := Expr;
1194    --
1195    --  <elsif Expr is an entity_name>
1196    --    Val : T (constraints taken from Expr) := Expr;
1197    --
1198    --  <else>
1199    --    type Axxx is access all T;
1200    --    Rval : Axxx := Expr'ref;
1201    --    Val  : T (constraints taken from Rval) := Rval.all;
1202
1203    --    ??? note: when the Expression is allocated in the secondary stack
1204    --              we could use it directly instead of copying it by declaring
1205    --              Val : T (...) renames Rval.all
1206
1207    procedure Expand_Subtype_From_Expr
1208      (N             : Node_Id;
1209       Unc_Type      : Entity_Id;
1210       Subtype_Indic : Node_Id;
1211       Exp           : Node_Id)
1212    is
1213       Loc     : constant Source_Ptr := Sloc (N);
1214       Exp_Typ : constant Entity_Id  := Etype (Exp);
1215       T       : Entity_Id;
1216
1217    begin
1218       --  In general we cannot build the subtype if expansion is disabled,
1219       --  because internal entities may not have been defined. However, to
1220       --  avoid some cascaded errors, we try to continue when the expression
1221       --  is an array (or string), because it is safe to compute the bounds.
1222       --  It is in fact required to do so even in a generic context, because
1223       --  there may be constants that depend on bounds of string literal.
1224
1225       if not Expander_Active
1226         and then (No (Etype (Exp))
1227                    or else Base_Type (Etype (Exp)) /= Standard_String)
1228       then
1229          return;
1230       end if;
1231
1232       if Nkind (Exp) = N_Slice then
1233          declare
1234             Slice_Type : constant Entity_Id := Etype (First_Index (Exp_Typ));
1235
1236          begin
1237             Rewrite (Subtype_Indic,
1238               Make_Subtype_Indication (Loc,
1239                 Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1240                 Constraint =>
1241                   Make_Index_Or_Discriminant_Constraint (Loc,
1242                     Constraints => New_List
1243                       (New_Reference_To (Slice_Type, Loc)))));
1244
1245             --  This subtype indication may be used later for constraint checks
1246             --  we better make sure that if a variable was used as a bound of
1247             --  of the original slice, its value is frozen.
1248
1249             Force_Evaluation (Low_Bound (Scalar_Range (Slice_Type)));
1250             Force_Evaluation (High_Bound (Scalar_Range (Slice_Type)));
1251          end;
1252
1253       elsif Ekind (Exp_Typ) = E_String_Literal_Subtype then
1254          Rewrite (Subtype_Indic,
1255            Make_Subtype_Indication (Loc,
1256              Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1257              Constraint =>
1258                Make_Index_Or_Discriminant_Constraint (Loc,
1259                  Constraints => New_List (
1260                    Make_Literal_Range (Loc,
1261                      Literal_Typ => Exp_Typ)))));
1262
1263       elsif Is_Constrained (Exp_Typ)
1264         and then not Is_Class_Wide_Type (Unc_Type)
1265       then
1266          if Is_Itype (Exp_Typ) then
1267
1268             --  Within an initialization procedure, a selected component
1269             --  denotes a component of the enclosing record, and it appears
1270             --  as an actual in a call to its own initialization procedure.
1271             --  If this component depends on the outer discriminant, we must
1272             --  generate the proper actual subtype for it.
1273
1274             if Nkind (Exp) = N_Selected_Component
1275               and then Within_Init_Proc
1276             then
1277                declare
1278                   Decl : constant Node_Id :=
1279                            Build_Actual_Subtype_Of_Component (Exp_Typ, Exp);
1280                begin
1281                   if Present (Decl) then
1282                      Insert_Action (N, Decl);
1283                      T := Defining_Identifier (Decl);
1284                   else
1285                      T := Exp_Typ;
1286                   end if;
1287                end;
1288
1289             --  No need to generate a new one (new what???)
1290
1291             else
1292                T := Exp_Typ;
1293             end if;
1294
1295          else
1296             T := Make_Temporary (Loc, 'T');
1297
1298             Insert_Action (N,
1299               Make_Subtype_Declaration (Loc,
1300                 Defining_Identifier => T,
1301                 Subtype_Indication  => New_Reference_To (Exp_Typ, Loc)));
1302
1303             --  This type is marked as an itype even though it has an
1304             --  explicit declaration because otherwise it can be marked
1305             --  with Is_Generic_Actual_Type and generate spurious errors.
1306             --  (see sem_ch8.Analyze_Package_Renaming and sem_type.covers)
1307
1308             Set_Is_Itype (T);
1309             Set_Associated_Node_For_Itype (T, Exp);
1310          end if;
1311
1312          Rewrite (Subtype_Indic, New_Reference_To (T, Loc));
1313
1314       --  Nothing needs to be done for private types with unknown discriminants
1315       --  if the underlying type is not an unconstrained composite type or it
1316       --  is an unchecked union.
1317
1318       elsif Is_Private_Type (Unc_Type)
1319         and then Has_Unknown_Discriminants (Unc_Type)
1320         and then (not Is_Composite_Type (Underlying_Type (Unc_Type))
1321                    or else Is_Constrained (Underlying_Type (Unc_Type))
1322                    or else Is_Unchecked_Union (Underlying_Type (Unc_Type)))
1323       then
1324          null;
1325
1326       --  Case of derived type with unknown discriminants where the parent type
1327       --  also has unknown discriminants.
1328
1329       elsif Is_Record_Type (Unc_Type)
1330         and then not Is_Class_Wide_Type (Unc_Type)
1331         and then Has_Unknown_Discriminants (Unc_Type)
1332         and then Has_Unknown_Discriminants (Underlying_Type (Unc_Type))
1333       then
1334          --  Nothing to be done if no underlying record view available
1335
1336          if No (Underlying_Record_View (Unc_Type)) then
1337             null;
1338
1339          --  Otherwise use the Underlying_Record_View to create the proper
1340          --  constrained subtype for an object of a derived type with unknown
1341          --  discriminants.
1342
1343          else
1344             Remove_Side_Effects (Exp);
1345             Rewrite (Subtype_Indic,
1346               Make_Subtype_From_Expr (Exp, Underlying_Record_View (Unc_Type)));
1347          end if;
1348
1349       --  Renamings of class-wide interface types require no equivalent
1350       --  constrained type declarations because we only need to reference
1351       --  the tag component associated with the interface.
1352
1353       elsif Present (N)
1354         and then Nkind (N) = N_Object_Renaming_Declaration
1355         and then Is_Interface (Unc_Type)
1356       then
1357          pragma Assert (Is_Class_Wide_Type (Unc_Type));
1358          null;
1359
1360       --  In Ada95, nothing to be done if the type of the expression is
1361       --  limited, because in this case the expression cannot be copied,
1362       --  and its use can only be by reference.
1363
1364       --  In Ada2005, the context can be an object declaration whose expression
1365       --  is a function that returns in place. If the nominal subtype has
1366       --  unknown discriminants, the call still provides constraints on the
1367       --  object, and we have to create an actual subtype from it.
1368
1369       --  If the type is class-wide, the expression is dynamically tagged and
1370       --  we do not create an actual subtype either. Ditto for an interface.
1371
1372       elsif Is_Limited_Type (Exp_Typ)
1373         and then
1374          (Is_Class_Wide_Type (Exp_Typ)
1375            or else Is_Interface (Exp_Typ)
1376            or else not Has_Unknown_Discriminants (Exp_Typ)
1377            or else not Is_Composite_Type (Unc_Type))
1378       then
1379          null;
1380
1381       --  For limited objects initialized with build in place function calls,
1382       --  nothing to be done; otherwise we prematurely introduce an N_Reference
1383       --  node in the expression initializing the object, which breaks the
1384       --  circuitry that detects and adds the additional arguments to the
1385       --  called function.
1386
1387       elsif Is_Build_In_Place_Function_Call (Exp) then
1388          null;
1389
1390       else
1391          Remove_Side_Effects (Exp);
1392          Rewrite (Subtype_Indic,
1393            Make_Subtype_From_Expr (Exp, Unc_Type));
1394       end if;
1395    end Expand_Subtype_From_Expr;
1396
1397    --------------------
1398    -- Find_Init_Call --
1399    --------------------
1400
1401    function Find_Init_Call
1402      (Var        : Entity_Id;
1403       Rep_Clause : Node_Id) return Node_Id
1404    is
1405       Typ : constant Entity_Id := Etype (Var);
1406
1407       Init_Proc : Entity_Id;
1408       --  Initialization procedure for Typ
1409
1410       function Find_Init_Call_In_List (From : Node_Id) return Node_Id;
1411       --  Look for init call for Var starting at From and scanning the
1412       --  enclosing list until Rep_Clause or the end of the list is reached.
1413
1414       ----------------------------
1415       -- Find_Init_Call_In_List --
1416       ----------------------------
1417
1418       function Find_Init_Call_In_List (From : Node_Id) return Node_Id is
1419          Init_Call : Node_Id;
1420       begin
1421          Init_Call := From;
1422
1423          while Present (Init_Call) and then Init_Call /= Rep_Clause loop
1424             if Nkind (Init_Call) = N_Procedure_Call_Statement
1425                  and then Is_Entity_Name (Name (Init_Call))
1426                  and then Entity (Name (Init_Call)) = Init_Proc
1427             then
1428                return Init_Call;
1429             end if;
1430             Next (Init_Call);
1431          end loop;
1432
1433          return Empty;
1434       end Find_Init_Call_In_List;
1435
1436       Init_Call : Node_Id;
1437
1438    --  Start of processing for Find_Init_Call
1439
1440    begin
1441       if not Has_Non_Null_Base_Init_Proc (Typ) then
1442          --  No init proc for the type, so obviously no call to be found
1443
1444          return Empty;
1445       end if;
1446
1447       Init_Proc := Base_Init_Proc (Typ);
1448
1449       --  First scan the list containing the declaration of Var
1450
1451       Init_Call := Find_Init_Call_In_List (From => Next (Parent (Var)));
1452
1453       --  If not found, also look on Var's freeze actions list, if any, since
1454       --  the init call may have been moved there (case of an address clause
1455       --  applying to Var).
1456
1457       if No (Init_Call) and then Present (Freeze_Node (Var)) then
1458          Init_Call := Find_Init_Call_In_List
1459                         (First (Actions (Freeze_Node (Var))));
1460       end if;
1461
1462       return Init_Call;
1463    end Find_Init_Call;
1464
1465    ------------------------
1466    -- Find_Interface_ADT --
1467    ------------------------
1468
1469    function Find_Interface_ADT
1470      (T     : Entity_Id;
1471       Iface : Entity_Id) return Elmt_Id
1472    is
1473       ADT : Elmt_Id;
1474       Typ : Entity_Id := T;
1475
1476    begin
1477       pragma Assert (Is_Interface (Iface));
1478
1479       --  Handle private types
1480
1481       if Has_Private_Declaration (Typ)
1482         and then Present (Full_View (Typ))
1483       then
1484          Typ := Full_View (Typ);
1485       end if;
1486
1487       --  Handle access types
1488
1489       if Is_Access_Type (Typ) then
1490          Typ := Directly_Designated_Type (Typ);
1491       end if;
1492
1493       --  Handle task and protected types implementing interfaces
1494
1495       if Is_Concurrent_Type (Typ) then
1496          Typ := Corresponding_Record_Type (Typ);
1497       end if;
1498
1499       pragma Assert
1500         (not Is_Class_Wide_Type (Typ)
1501           and then Ekind (Typ) /= E_Incomplete_Type);
1502
1503       if Is_Ancestor (Iface, Typ) then
1504          return First_Elmt (Access_Disp_Table (Typ));
1505
1506       else
1507          ADT :=
1508            Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ))));
1509          while Present (ADT)
1510            and then Present (Related_Type (Node (ADT)))
1511            and then Related_Type (Node (ADT)) /= Iface
1512            and then not Is_Ancestor (Iface, Related_Type (Node (ADT)))
1513          loop
1514             Next_Elmt (ADT);
1515          end loop;
1516
1517          pragma Assert (Present (Related_Type (Node (ADT))));
1518          return ADT;
1519       end if;
1520    end Find_Interface_ADT;
1521
1522    ------------------------
1523    -- Find_Interface_Tag --
1524    ------------------------
1525
1526    function Find_Interface_Tag
1527      (T     : Entity_Id;
1528       Iface : Entity_Id) return Entity_Id
1529    is
1530       AI_Tag : Entity_Id;
1531       Found  : Boolean   := False;
1532       Typ    : Entity_Id := T;
1533
1534       procedure Find_Tag (Typ : Entity_Id);
1535       --  Internal subprogram used to recursively climb to the ancestors
1536
1537       --------------
1538       -- Find_Tag --
1539       --------------
1540
1541       procedure Find_Tag (Typ : Entity_Id) is
1542          AI_Elmt : Elmt_Id;
1543          AI      : Node_Id;
1544
1545       begin
1546          --  This routine does not handle the case in which the interface is an
1547          --  ancestor of Typ. That case is handled by the enclosing subprogram.
1548
1549          pragma Assert (Typ /= Iface);
1550
1551          --  Climb to the root type handling private types
1552
1553          if Present (Full_View (Etype (Typ))) then
1554             if Full_View (Etype (Typ)) /= Typ then
1555                Find_Tag (Full_View (Etype (Typ)));
1556             end if;
1557
1558          elsif Etype (Typ) /= Typ then
1559             Find_Tag (Etype (Typ));
1560          end if;
1561
1562          --  Traverse the list of interfaces implemented by the type
1563
1564          if not Found
1565            and then Present (Interfaces (Typ))
1566            and then not (Is_Empty_Elmt_List (Interfaces (Typ)))
1567          then
1568             --  Skip the tag associated with the primary table
1569
1570             pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1571             AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1572             pragma Assert (Present (AI_Tag));
1573
1574             AI_Elmt := First_Elmt (Interfaces (Typ));
1575             while Present (AI_Elmt) loop
1576                AI := Node (AI_Elmt);
1577
1578                if AI = Iface or else Is_Ancestor (Iface, AI) then
1579                   Found := True;
1580                   return;
1581                end if;
1582
1583                AI_Tag := Next_Tag_Component (AI_Tag);
1584                Next_Elmt (AI_Elmt);
1585             end loop;
1586          end if;
1587       end Find_Tag;
1588
1589    --  Start of processing for Find_Interface_Tag
1590
1591    begin
1592       pragma Assert (Is_Interface (Iface));
1593
1594       --  Handle access types
1595
1596       if Is_Access_Type (Typ) then
1597          Typ := Directly_Designated_Type (Typ);
1598       end if;
1599
1600       --  Handle class-wide types
1601
1602       if Is_Class_Wide_Type (Typ) then
1603          Typ := Root_Type (Typ);
1604       end if;
1605
1606       --  Handle private types
1607
1608       if Has_Private_Declaration (Typ)
1609         and then Present (Full_View (Typ))
1610       then
1611          Typ := Full_View (Typ);
1612       end if;
1613
1614       --  Handle entities from the limited view
1615
1616       if Ekind (Typ) = E_Incomplete_Type then
1617          pragma Assert (Present (Non_Limited_View (Typ)));
1618          Typ := Non_Limited_View (Typ);
1619       end if;
1620
1621       --  Handle task and protected types implementing interfaces
1622
1623       if Is_Concurrent_Type (Typ) then
1624          Typ := Corresponding_Record_Type (Typ);
1625       end if;
1626
1627       --  If the interface is an ancestor of the type, then it shared the
1628       --  primary dispatch table.
1629
1630       if Is_Ancestor (Iface, Typ) then
1631          pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1632          return First_Tag_Component (Typ);
1633
1634       --  Otherwise we need to search for its associated tag component
1635
1636       else
1637          Find_Tag (Typ);
1638          pragma Assert (Found);
1639          return AI_Tag;
1640       end if;
1641    end Find_Interface_Tag;
1642
1643    ------------------
1644    -- Find_Prim_Op --
1645    ------------------
1646
1647    function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is
1648       Prim : Elmt_Id;
1649       Typ  : Entity_Id := T;
1650       Op   : Entity_Id;
1651
1652    begin
1653       if Is_Class_Wide_Type (Typ) then
1654          Typ := Root_Type (Typ);
1655       end if;
1656
1657       Typ := Underlying_Type (Typ);
1658
1659       --  Loop through primitive operations
1660
1661       Prim := First_Elmt (Primitive_Operations (Typ));
1662       while Present (Prim) loop
1663          Op := Node (Prim);
1664
1665          --  We can retrieve primitive operations by name if it is an internal
1666          --  name. For equality we must check that both of its operands have
1667          --  the same type, to avoid confusion with user-defined equalities
1668          --  than may have a non-symmetric signature.
1669
1670          exit when Chars (Op) = Name
1671            and then
1672              (Name /= Name_Op_Eq
1673                 or else Etype (First_Entity (Op)) = Etype (Last_Entity (Op)));
1674
1675          Next_Elmt (Prim);
1676
1677          --  Raise Program_Error if no primitive found
1678
1679          if No (Prim) then
1680             raise Program_Error;
1681          end if;
1682       end loop;
1683
1684       return Node (Prim);
1685    end Find_Prim_Op;
1686
1687    ------------------
1688    -- Find_Prim_Op --
1689    ------------------
1690
1691    function Find_Prim_Op
1692      (T    : Entity_Id;
1693       Name : TSS_Name_Type) return Entity_Id
1694    is
1695       Prim : Elmt_Id;
1696       Typ  : Entity_Id := T;
1697
1698    begin
1699       if Is_Class_Wide_Type (Typ) then
1700          Typ := Root_Type (Typ);
1701       end if;
1702
1703       Typ := Underlying_Type (Typ);
1704
1705       Prim := First_Elmt (Primitive_Operations (Typ));
1706       while not Is_TSS (Node (Prim), Name) loop
1707          Next_Elmt (Prim);
1708
1709          --  Raise program error if no primitive found
1710
1711          if No (Prim) then
1712             raise Program_Error;
1713          end if;
1714       end loop;
1715
1716       return Node (Prim);
1717    end Find_Prim_Op;
1718
1719    ----------------------------
1720    -- Find_Protection_Object --
1721    ----------------------------
1722
1723    function Find_Protection_Object (Scop : Entity_Id) return Entity_Id is
1724       S : Entity_Id;
1725
1726    begin
1727       S := Scop;
1728       while Present (S) loop
1729          if (Ekind (S) = E_Entry
1730                or else Ekind (S) = E_Entry_Family
1731                or else Ekind (S) = E_Function
1732                or else Ekind (S) = E_Procedure)
1733            and then Present (Protection_Object (S))
1734          then
1735             return Protection_Object (S);
1736          end if;
1737
1738          S := Scope (S);
1739       end loop;
1740
1741       --  If we do not find a Protection object in the scope chain, then
1742       --  something has gone wrong, most likely the object was never created.
1743
1744       raise Program_Error;
1745    end Find_Protection_Object;
1746
1747    ----------------------
1748    -- Force_Evaluation --
1749    ----------------------
1750
1751    procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False) is
1752    begin
1753       Remove_Side_Effects (Exp, Name_Req, Variable_Ref => True);
1754    end Force_Evaluation;
1755
1756    ------------------------
1757    -- Generate_Poll_Call --
1758    ------------------------
1759
1760    procedure Generate_Poll_Call (N : Node_Id) is
1761    begin
1762       --  No poll call if polling not active
1763
1764       if not Polling_Required then
1765          return;
1766
1767       --  Otherwise generate require poll call
1768
1769       else
1770          Insert_Before_And_Analyze (N,
1771            Make_Procedure_Call_Statement (Sloc (N),
1772              Name => New_Occurrence_Of (RTE (RE_Poll), Sloc (N))));
1773       end if;
1774    end Generate_Poll_Call;
1775
1776    ---------------------------------
1777    -- Get_Current_Value_Condition --
1778    ---------------------------------
1779
1780    --  Note: the implementation of this procedure is very closely tied to the
1781    --  implementation of Set_Current_Value_Condition. In the Get procedure, we
1782    --  interpret Current_Value fields set by the Set procedure, so the two
1783    --  procedures need to be closely coordinated.
1784
1785    procedure Get_Current_Value_Condition
1786      (Var : Node_Id;
1787       Op  : out Node_Kind;
1788       Val : out Node_Id)
1789    is
1790       Loc : constant Source_Ptr := Sloc (Var);
1791       Ent : constant Entity_Id  := Entity (Var);
1792
1793       procedure Process_Current_Value_Condition
1794         (N : Node_Id;
1795          S : Boolean);
1796       --  N is an expression which holds either True (S = True) or False (S =
1797       --  False) in the condition. This procedure digs out the expression and
1798       --  if it refers to Ent, sets Op and Val appropriately.
1799
1800       -------------------------------------
1801       -- Process_Current_Value_Condition --
1802       -------------------------------------
1803
1804       procedure Process_Current_Value_Condition
1805         (N : Node_Id;
1806          S : Boolean)
1807       is
1808          Cond : Node_Id;
1809          Sens : Boolean;
1810
1811       begin
1812          Cond := N;
1813          Sens := S;
1814
1815          --  Deal with NOT operators, inverting sense
1816
1817          while Nkind (Cond) = N_Op_Not loop
1818             Cond := Right_Opnd (Cond);
1819             Sens := not Sens;
1820          end loop;
1821
1822          --  Deal with AND THEN and AND cases
1823
1824          if Nkind (Cond) = N_And_Then
1825            or else Nkind (Cond) = N_Op_And
1826          then
1827             --  Don't ever try to invert a condition that is of the form
1828             --  of an AND or AND THEN (since we are not doing sufficiently
1829             --  general processing to allow this).
1830
1831             if Sens = False then
1832                Op  := N_Empty;
1833                Val := Empty;
1834                return;
1835             end if;
1836
1837             --  Recursively process AND and AND THEN branches
1838
1839             Process_Current_Value_Condition (Left_Opnd (Cond), True);
1840
1841             if Op /= N_Empty then
1842                return;
1843             end if;
1844
1845             Process_Current_Value_Condition (Right_Opnd (Cond), True);
1846             return;
1847
1848          --  Case of relational operator
1849
1850          elsif Nkind (Cond) in N_Op_Compare then
1851             Op := Nkind (Cond);
1852
1853             --  Invert sense of test if inverted test
1854
1855             if Sens = False then
1856                case Op is
1857                   when N_Op_Eq => Op := N_Op_Ne;
1858                   when N_Op_Ne => Op := N_Op_Eq;
1859                   when N_Op_Lt => Op := N_Op_Ge;
1860                   when N_Op_Gt => Op := N_Op_Le;
1861                   when N_Op_Le => Op := N_Op_Gt;
1862                   when N_Op_Ge => Op := N_Op_Lt;
1863                   when others  => raise Program_Error;
1864                end case;
1865             end if;
1866
1867             --  Case of entity op value
1868
1869             if Is_Entity_Name (Left_Opnd (Cond))
1870               and then Ent = Entity (Left_Opnd (Cond))
1871               and then Compile_Time_Known_Value (Right_Opnd (Cond))
1872             then
1873                Val := Right_Opnd (Cond);
1874
1875             --  Case of value op entity
1876
1877             elsif Is_Entity_Name (Right_Opnd (Cond))
1878               and then Ent = Entity (Right_Opnd (Cond))
1879               and then Compile_Time_Known_Value (Left_Opnd (Cond))
1880             then
1881                Val := Left_Opnd (Cond);
1882
1883                --  We are effectively swapping operands
1884
1885                case Op is
1886                   when N_Op_Eq => null;
1887                   when N_Op_Ne => null;
1888                   when N_Op_Lt => Op := N_Op_Gt;
1889                   when N_Op_Gt => Op := N_Op_Lt;
1890                   when N_Op_Le => Op := N_Op_Ge;
1891                   when N_Op_Ge => Op := N_Op_Le;
1892                   when others  => raise Program_Error;
1893                end case;
1894
1895             else
1896                Op := N_Empty;
1897             end if;
1898
1899             return;
1900
1901             --  Case of Boolean variable reference, return as though the
1902             --  reference had said var = True.
1903
1904          else
1905             if Is_Entity_Name (Cond)
1906               and then Ent = Entity (Cond)
1907             then
1908                Val := New_Occurrence_Of (Standard_True, Sloc (Cond));
1909
1910                if Sens = False then
1911                   Op := N_Op_Ne;
1912                else
1913                   Op := N_Op_Eq;
1914                end if;
1915             end if;
1916          end if;
1917       end Process_Current_Value_Condition;
1918
1919    --  Start of processing for Get_Current_Value_Condition
1920
1921    begin
1922       Op  := N_Empty;
1923       Val := Empty;
1924
1925       --  Immediate return, nothing doing, if this is not an object
1926
1927       if Ekind (Ent) not in Object_Kind then
1928          return;
1929       end if;
1930
1931       --  Otherwise examine current value
1932
1933       declare
1934          CV   : constant Node_Id := Current_Value (Ent);
1935          Sens : Boolean;
1936          Stm  : Node_Id;
1937
1938       begin
1939          --  If statement. Condition is known true in THEN section, known False
1940          --  in any ELSIF or ELSE part, and unknown outside the IF statement.
1941
1942          if Nkind (CV) = N_If_Statement then
1943
1944             --  Before start of IF statement
1945
1946             if Loc < Sloc (CV) then
1947                return;
1948
1949                --  After end of IF statement
1950
1951             elsif Loc >= Sloc (CV) + Text_Ptr (UI_To_Int (End_Span (CV))) then
1952                return;
1953             end if;
1954
1955             --  At this stage we know that we are within the IF statement, but
1956             --  unfortunately, the tree does not record the SLOC of the ELSE so
1957             --  we cannot use a simple SLOC comparison to distinguish between
1958             --  the then/else statements, so we have to climb the tree.
1959
1960             declare
1961                N : Node_Id;
1962
1963             begin
1964                N := Parent (Var);
1965                while Parent (N) /= CV loop
1966                   N := Parent (N);
1967
1968                   --  If we fall off the top of the tree, then that's odd, but
1969                   --  perhaps it could occur in some error situation, and the
1970                   --  safest response is simply to assume that the outcome of
1971                   --  the condition is unknown. No point in bombing during an
1972                   --  attempt to optimize things.
1973
1974                   if No (N) then
1975                      return;
1976                   end if;
1977                end loop;
1978
1979                --  Now we have N pointing to a node whose parent is the IF
1980                --  statement in question, so now we can tell if we are within
1981                --  the THEN statements.
1982
1983                if Is_List_Member (N)
1984                  and then List_Containing (N) = Then_Statements (CV)
1985                then
1986                   Sens := True;
1987
1988                --  If the variable reference does not come from source, we
1989                --  cannot reliably tell whether it appears in the else part.
1990                --  In particular, if it appears in generated code for a node
1991                --  that requires finalization, it may be attached to a list
1992                --  that has not been yet inserted into the code. For now,
1993                --  treat it as unknown.
1994
1995                elsif not Comes_From_Source (N) then
1996                   return;
1997
1998                --  Otherwise we must be in ELSIF or ELSE part
1999
2000                else
2001                   Sens := False;
2002                end if;
2003             end;
2004
2005             --  ELSIF part. Condition is known true within the referenced
2006             --  ELSIF, known False in any subsequent ELSIF or ELSE part, and
2007             --  unknown before the ELSE part or after the IF statement.
2008
2009          elsif Nkind (CV) = N_Elsif_Part then
2010             Stm := Parent (CV);
2011
2012             --  Before start of ELSIF part
2013
2014             if Loc < Sloc (CV) then
2015                return;
2016
2017                --  After end of IF statement
2018
2019             elsif Loc >= Sloc (Stm) +
2020               Text_Ptr (UI_To_Int (End_Span (Stm)))
2021             then
2022                return;
2023             end if;
2024
2025             --  Again we lack the SLOC of the ELSE, so we need to climb the
2026             --  tree to see if we are within the ELSIF part in question.
2027
2028             declare
2029                N : Node_Id;
2030
2031             begin
2032                N := Parent (Var);
2033                while Parent (N) /= Stm loop
2034                   N := Parent (N);
2035
2036                   --  If we fall off the top of the tree, then that's odd, but
2037                   --  perhaps it could occur in some error situation, and the
2038                   --  safest response is simply to assume that the outcome of
2039                   --  the condition is unknown. No point in bombing during an
2040                   --  attempt to optimize things.
2041
2042                   if No (N) then
2043                      return;
2044                   end if;
2045                end loop;
2046
2047                --  Now we have N pointing to a node whose parent is the IF
2048                --  statement in question, so see if is the ELSIF part we want.
2049                --  the THEN statements.
2050
2051                if N = CV then
2052                   Sens := True;
2053
2054                   --  Otherwise we must be in subsequent ELSIF or ELSE part
2055
2056                else
2057                   Sens := False;
2058                end if;
2059             end;
2060
2061          --  Iteration scheme of while loop. The condition is known to be
2062          --  true within the body of the loop.
2063
2064          elsif Nkind (CV) = N_Iteration_Scheme then
2065             declare
2066                Loop_Stmt : constant Node_Id := Parent (CV);
2067
2068             begin
2069                --  Before start of body of loop
2070
2071                if Loc < Sloc (Loop_Stmt) then
2072                   return;
2073
2074                --  After end of LOOP statement
2075
2076                elsif Loc >= Sloc (End_Label (Loop_Stmt)) then
2077                   return;
2078
2079                --  We are within the body of the loop
2080
2081                else
2082                   Sens := True;
2083                end if;
2084             end;
2085
2086          --  All other cases of Current_Value settings
2087
2088          else
2089             return;
2090          end if;
2091
2092          --  If we fall through here, then we have a reportable condition, Sens
2093          --  is True if the condition is true and False if it needs inverting.
2094
2095          Process_Current_Value_Condition (Condition (CV), Sens);
2096       end;
2097    end Get_Current_Value_Condition;
2098
2099    ---------------------------------
2100    -- Has_Controlled_Coextensions --
2101    ---------------------------------
2102
2103    function Has_Controlled_Coextensions (Typ : Entity_Id) return Boolean is
2104       D_Typ : Entity_Id;
2105       Discr : Entity_Id;
2106
2107    begin
2108       --  Only consider record types
2109
2110       if Ekind (Typ) /= E_Record_Type
2111         and then Ekind (Typ) /= E_Record_Subtype
2112       then
2113          return False;
2114       end if;
2115
2116       if Has_Discriminants (Typ) then
2117          Discr := First_Discriminant (Typ);
2118          while Present (Discr) loop
2119             D_Typ := Etype (Discr);
2120
2121             if Ekind (D_Typ) = E_Anonymous_Access_Type
2122               and then
2123                 (Is_Controlled (Directly_Designated_Type (D_Typ))
2124                    or else
2125                  Is_Concurrent_Type (Directly_Designated_Type (D_Typ)))
2126             then
2127                return True;
2128             end if;
2129
2130             Next_Discriminant (Discr);
2131          end loop;
2132       end if;
2133
2134       return False;
2135    end Has_Controlled_Coextensions;
2136
2137    ------------------------
2138    -- Has_Address_Clause --
2139    ------------------------
2140
2141    --  Should this function check the private part in a package ???
2142
2143    function Has_Following_Address_Clause (D : Node_Id) return Boolean is
2144       Id   : constant Entity_Id := Defining_Identifier (D);
2145       Decl : Node_Id;
2146
2147    begin
2148       Decl := Next (D);
2149       while Present (Decl) loop
2150          if Nkind (Decl) = N_At_Clause
2151            and then Chars (Identifier (Decl)) = Chars (Id)
2152          then
2153             return True;
2154
2155          elsif Nkind (Decl) = N_Attribute_Definition_Clause
2156            and then Chars (Decl) = Name_Address
2157            and then Chars (Name (Decl)) = Chars (Id)
2158          then
2159             return True;
2160          end if;
2161
2162          Next (Decl);
2163       end loop;
2164
2165       return False;
2166    end Has_Following_Address_Clause;
2167
2168    --------------------
2169    -- Homonym_Number --
2170    --------------------
2171
2172    function Homonym_Number (Subp : Entity_Id) return Nat is
2173       Count : Nat;
2174       Hom   : Entity_Id;
2175
2176    begin
2177       Count := 1;
2178       Hom := Homonym (Subp);
2179       while Present (Hom) loop
2180          if Scope (Hom) = Scope (Subp) then
2181             Count := Count + 1;
2182          end if;
2183
2184          Hom := Homonym (Hom);
2185       end loop;
2186
2187       return Count;
2188    end Homonym_Number;
2189
2190    ------------------------------
2191    -- In_Unconditional_Context --
2192    ------------------------------
2193
2194    function In_Unconditional_Context (Node : Node_Id) return Boolean is
2195       P : Node_Id;
2196
2197    begin
2198       P := Node;
2199       while Present (P) loop
2200          case Nkind (P) is
2201             when N_Subprogram_Body =>
2202                return True;
2203
2204             when N_If_Statement =>
2205                return False;
2206
2207             when N_Loop_Statement =>
2208                return False;
2209
2210             when N_Case_Statement =>
2211                return False;
2212
2213             when others =>
2214                P := Parent (P);
2215          end case;
2216       end loop;
2217
2218       return False;
2219    end In_Unconditional_Context;
2220
2221    -------------------
2222    -- Insert_Action --
2223    -------------------
2224
2225    procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id) is
2226    begin
2227       if Present (Ins_Action) then
2228          Insert_Actions (Assoc_Node, New_List (Ins_Action));
2229       end if;
2230    end Insert_Action;
2231
2232    --  Version with check(s) suppressed
2233
2234    procedure Insert_Action
2235      (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id)
2236    is
2237    begin
2238       Insert_Actions (Assoc_Node, New_List (Ins_Action), Suppress);
2239    end Insert_Action;
2240
2241    --------------------
2242    -- Insert_Actions --
2243    --------------------
2244
2245    procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id) is
2246       N : Node_Id;
2247       P : Node_Id;
2248
2249       Wrapped_Node : Node_Id := Empty;
2250
2251    begin
2252       if No (Ins_Actions) or else Is_Empty_List (Ins_Actions) then
2253          return;
2254       end if;
2255
2256       --  Ignore insert of actions from inside default expression (or other
2257       --  similar "spec expression") in the special spec-expression analyze
2258       --  mode. Any insertions at this point have no relevance, since we are
2259       --  only doing the analyze to freeze the types of any static expressions.
2260       --  See section "Handling of Default Expressions" in the spec of package
2261       --  Sem for further details.
2262
2263       if In_Spec_Expression then
2264          return;
2265       end if;
2266
2267       --  If the action derives from stuff inside a record, then the actions
2268       --  are attached to the current scope, to be inserted and analyzed on
2269       --  exit from the scope. The reason for this is that we may also
2270       --  be generating freeze actions at the same time, and they must
2271       --  eventually be elaborated in the correct order.
2272
2273       if Is_Record_Type (Current_Scope)
2274         and then not Is_Frozen (Current_Scope)
2275       then
2276          if No (Scope_Stack.Table
2277            (Scope_Stack.Last).Pending_Freeze_Actions)
2278          then
2279             Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions :=
2280               Ins_Actions;
2281          else
2282             Append_List
2283               (Ins_Actions,
2284                Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions);
2285          end if;
2286
2287          return;
2288       end if;
2289
2290       --  We now intend to climb up the tree to find the right point to
2291       --  insert the actions. We start at Assoc_Node, unless this node is
2292       --  a subexpression in which case we start with its parent. We do this
2293       --  for two reasons. First it speeds things up. Second, if Assoc_Node
2294       --  is itself one of the special nodes like N_And_Then, then we assume
2295       --  that an initial request to insert actions for such a node does not
2296       --  expect the actions to get deposited in the node for later handling
2297       --  when the node is expanded, since clearly the node is being dealt
2298       --  with by the caller. Note that in the subexpression case, N is
2299       --  always the child we came from.
2300
2301       --  N_Raise_xxx_Error is an annoying special case, it is a statement
2302       --  if it has type Standard_Void_Type, and a subexpression otherwise.
2303       --  otherwise. Procedure attribute references are also statements.
2304
2305       if Nkind (Assoc_Node) in N_Subexpr
2306         and then (Nkind (Assoc_Node) in N_Raise_xxx_Error
2307                    or else Etype (Assoc_Node) /= Standard_Void_Type)
2308         and then (Nkind (Assoc_Node) /= N_Attribute_Reference
2309                    or else
2310                      not Is_Procedure_Attribute_Name
2311                            (Attribute_Name (Assoc_Node)))
2312       then
2313          P := Assoc_Node;             -- ??? does not agree with above!
2314          N := Parent (Assoc_Node);
2315
2316       --  Non-subexpression case. Note that N is initially Empty in this
2317       --  case (N is only guaranteed Non-Empty in the subexpr case).
2318
2319       else
2320          P := Assoc_Node;
2321          N := Empty;
2322       end if;
2323
2324       --  Capture root of the transient scope
2325
2326       if Scope_Is_Transient then
2327          Wrapped_Node := Node_To_Be_Wrapped;
2328       end if;
2329
2330       loop
2331          pragma Assert (Present (P));
2332
2333          case Nkind (P) is
2334
2335             --  Case of right operand of AND THEN or OR ELSE. Put the actions
2336             --  in the Actions field of the right operand. They will be moved
2337             --  out further when the AND THEN or OR ELSE operator is expanded.
2338             --  Nothing special needs to be done for the left operand since
2339             --  in that case the actions are executed unconditionally.
2340
2341             when N_Short_Circuit =>
2342                if N = Right_Opnd (P) then
2343
2344                   --  We are now going to either append the actions to the
2345                   --  actions field of the short-circuit operation. We will
2346                   --  also analyze the actions now.
2347
2348                   --  This analysis is really too early, the proper thing would
2349                   --  be to just park them there now, and only analyze them if
2350                   --  we find we really need them, and to it at the proper
2351                   --  final insertion point. However attempting to this proved
2352                   --  tricky, so for now we just kill current values before and
2353                   --  after the analyze call to make sure we avoid peculiar
2354                   --  optimizations from this out of order insertion.
2355
2356                   Kill_Current_Values;
2357
2358                   if Present (Actions (P)) then
2359                      Insert_List_After_And_Analyze
2360                        (Last (Actions (P)), Ins_Actions);
2361                   else
2362                      Set_Actions (P, Ins_Actions);
2363                      Analyze_List (Actions (P));
2364                   end if;
2365
2366                   Kill_Current_Values;
2367
2368                   return;
2369                end if;
2370
2371             --  Then or Else operand of conditional expression. Add actions to
2372             --  Then_Actions or Else_Actions field as appropriate. The actions
2373             --  will be moved further out when the conditional is expanded.
2374
2375             when N_Conditional_Expression =>
2376                declare
2377                   ThenX : constant Node_Id := Next (First (Expressions (P)));
2378                   ElseX : constant Node_Id := Next (ThenX);
2379
2380                begin
2381                   --  Actions belong to the then expression, temporarily
2382                   --  place them as Then_Actions of the conditional expr.
2383                   --  They will be moved to the proper place later when
2384                   --  the conditional expression is expanded.
2385
2386                   if N = ThenX then
2387                      if Present (Then_Actions (P)) then
2388                         Insert_List_After_And_Analyze
2389                           (Last (Then_Actions (P)), Ins_Actions);
2390                      else
2391                         Set_Then_Actions (P, Ins_Actions);
2392                         Analyze_List (Then_Actions (P));
2393                      end if;
2394
2395                      return;
2396
2397                   --  Actions belong to the else expression, temporarily
2398                   --  place them as Else_Actions of the conditional expr.
2399                   --  They will be moved to the proper place later when
2400                   --  the conditional expression is expanded.
2401
2402                   elsif N = ElseX then
2403                      if Present (Else_Actions (P)) then
2404                         Insert_List_After_And_Analyze
2405                           (Last (Else_Actions (P)), Ins_Actions);
2406                      else
2407                         Set_Else_Actions (P, Ins_Actions);
2408                         Analyze_List (Else_Actions (P));
2409                      end if;
2410
2411                      return;
2412
2413                   --  Actions belong to the condition. In this case they are
2414                   --  unconditionally executed, and so we can continue the
2415                   --  search for the proper insert point.
2416
2417                   else
2418                      null;
2419                   end if;
2420                end;
2421
2422             --  Case of appearing in the condition of a while expression or
2423             --  elsif. We insert the actions into the Condition_Actions field.
2424             --  They will be moved further out when the while loop or elsif
2425             --  is analyzed.
2426
2427             when N_Iteration_Scheme |
2428                  N_Elsif_Part
2429             =>
2430                if N = Condition (P) then
2431                   if Present (Condition_Actions (P)) then
2432                      Insert_List_After_And_Analyze
2433                        (Last (Condition_Actions (P)), Ins_Actions);
2434                   else
2435                      Set_Condition_Actions (P, Ins_Actions);
2436
2437                      --  Set the parent of the insert actions explicitly.
2438                      --  This is not a syntactic field, but we need the
2439                      --  parent field set, in particular so that freeze
2440                      --  can understand that it is dealing with condition
2441                      --  actions, and properly insert the freezing actions.
2442
2443                      Set_Parent (Ins_Actions, P);
2444                      Analyze_List (Condition_Actions (P));
2445                   end if;
2446
2447                   return;
2448                end if;
2449
2450             --  Statements, declarations, pragmas, representation clauses
2451
2452             when
2453                --  Statements
2454
2455                N_Procedure_Call_Statement               |
2456                N_Statement_Other_Than_Procedure_Call    |
2457
2458                --  Pragmas
2459
2460                N_Pragma                                 |
2461
2462                --  Representation_Clause
2463
2464                N_At_Clause                              |
2465                N_Attribute_Definition_Clause            |
2466                N_Enumeration_Representation_Clause      |
2467                N_Record_Representation_Clause           |
2468
2469                --  Declarations
2470
2471                N_Abstract_Subprogram_Declaration        |
2472                N_Entry_Body                             |
2473                N_Exception_Declaration                  |
2474                N_Exception_Renaming_Declaration         |
2475                N_Formal_Abstract_Subprogram_Declaration |
2476                N_Formal_Concrete_Subprogram_Declaration |
2477                N_Formal_Object_Declaration              |
2478                N_Formal_Type_Declaration                |
2479                N_Full_Type_Declaration                  |
2480                N_Function_Instantiation                 |
2481                N_Generic_Function_Renaming_Declaration  |
2482                N_Generic_Package_Declaration            |
2483                N_Generic_Package_Renaming_Declaration   |
2484                N_Generic_Procedure_Renaming_Declaration |
2485                N_Generic_Subprogram_Declaration         |
2486                N_Implicit_Label_Declaration             |
2487                N_Incomplete_Type_Declaration            |
2488                N_Number_Declaration                     |
2489                N_Object_Declaration                     |
2490                N_Object_Renaming_Declaration            |
2491                N_Package_Body                           |
2492                N_Package_Body_Stub                      |
2493                N_Package_Declaration                    |
2494                N_Package_Instantiation                  |
2495                N_Package_Renaming_Declaration           |
2496                N_Private_Extension_Declaration          |
2497                N_Private_Type_Declaration               |
2498                N_Procedure_Instantiation                |
2499                N_Protected_Body                         |
2500                N_Protected_Body_Stub                    |
2501                N_Protected_Type_Declaration             |
2502                N_Single_Task_Declaration                |
2503                N_Subprogram_Body                        |
2504                N_Subprogram_Body_Stub                   |
2505                N_Subprogram_Declaration                 |
2506                N_Subprogram_Renaming_Declaration        |
2507                N_Subtype_Declaration                    |
2508                N_Task_Body                              |
2509                N_Task_Body_Stub                         |
2510                N_Task_Type_Declaration                  |
2511
2512                --  Freeze entity behaves like a declaration or statement
2513
2514                N_Freeze_Entity
2515             =>
2516                --  Do not insert here if the item is not a list member (this
2517                --  happens for example with a triggering statement, and the
2518                --  proper approach is to insert before the entire select).
2519
2520                if not Is_List_Member (P) then
2521                   null;
2522
2523                --  Do not insert if parent of P is an N_Component_Association
2524                --  node (i.e. we are in the context of an N_Aggregate or
2525                --  N_Extension_Aggregate node. In this case we want to insert
2526                --  before the entire aggregate.
2527
2528                elsif Nkind (Parent (P)) = N_Component_Association then
2529                   null;
2530
2531                --  Do not insert if the parent of P is either an N_Variant
2532                --  node or an N_Record_Definition node, meaning in either
2533                --  case that P is a member of a component list, and that
2534                --  therefore the actions should be inserted outside the
2535                --  complete record declaration.
2536
2537                elsif Nkind (Parent (P)) = N_Variant
2538                  or else Nkind (Parent (P)) = N_Record_Definition
2539                then
2540                   null;
2541
2542                --  Do not insert freeze nodes within the loop generated for
2543                --  an aggregate, because they may be elaborated too late for
2544                --  subsequent use in the back end: within a package spec the
2545                --  loop is part of the elaboration procedure and is only
2546                --  elaborated during the second pass.
2547                --  If the loop comes from source, or the entity is local to
2548                --  the loop itself it must remain within.
2549
2550                elsif Nkind (Parent (P)) = N_Loop_Statement
2551                  and then not Comes_From_Source (Parent (P))
2552                  and then Nkind (First (Ins_Actions)) = N_Freeze_Entity
2553                  and then
2554                    Scope (Entity (First (Ins_Actions))) /= Current_Scope
2555                then
2556                   null;
2557
2558                --  Otherwise we can go ahead and do the insertion
2559
2560                elsif P = Wrapped_Node then
2561                   Store_Before_Actions_In_Scope (Ins_Actions);
2562                   return;
2563
2564                else
2565                   Insert_List_Before_And_Analyze (P, Ins_Actions);
2566                   return;
2567                end if;
2568
2569             --  A special case, N_Raise_xxx_Error can act either as a
2570             --  statement or a subexpression. We tell the difference
2571             --  by looking at the Etype. It is set to Standard_Void_Type
2572             --  in the statement case.
2573
2574             when
2575                N_Raise_xxx_Error =>
2576                   if Etype (P) = Standard_Void_Type then
2577                      if  P = Wrapped_Node then
2578                         Store_Before_Actions_In_Scope (Ins_Actions);
2579                      else
2580                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2581                      end if;
2582
2583                      return;
2584
2585                   --  In the subexpression case, keep climbing
2586
2587                   else
2588                      null;
2589                   end if;
2590
2591             --  If a component association appears within a loop created for
2592             --  an array aggregate, attach the actions to the association so
2593             --  they can be subsequently inserted within the loop. For other
2594             --  component associations insert outside of the aggregate. For
2595             --  an association that will generate a loop, its Loop_Actions
2596             --  attribute is already initialized (see exp_aggr.adb).
2597
2598             --  The list of loop_actions can in turn generate additional ones,
2599             --  that are inserted before the associated node. If the associated
2600             --  node is outside the aggregate, the new actions are collected
2601             --  at the end of the loop actions, to respect the order in which
2602             --  they are to be elaborated.
2603
2604             when
2605                N_Component_Association =>
2606                   if Nkind (Parent (P)) = N_Aggregate
2607                     and then Present (Loop_Actions (P))
2608                   then
2609                      if Is_Empty_List (Loop_Actions (P)) then
2610                         Set_Loop_Actions (P, Ins_Actions);
2611                         Analyze_List (Ins_Actions);
2612
2613                      else
2614                         declare
2615                            Decl : Node_Id;
2616
2617                         begin
2618                            --  Check whether these actions were generated
2619                            --  by a declaration that is part of the loop_
2620                            --  actions for the component_association.
2621
2622                            Decl := Assoc_Node;
2623                            while Present (Decl) loop
2624                               exit when Parent (Decl) = P
2625                                 and then Is_List_Member (Decl)
2626                                 and then
2627                                   List_Containing (Decl) = Loop_Actions (P);
2628                               Decl := Parent (Decl);
2629                            end loop;
2630
2631                            if Present (Decl) then
2632                               Insert_List_Before_And_Analyze
2633                                 (Decl, Ins_Actions);
2634                            else
2635                               Insert_List_After_And_Analyze
2636                                 (Last (Loop_Actions (P)), Ins_Actions);
2637                            end if;
2638                         end;
2639                      end if;
2640
2641                      return;
2642
2643                   else
2644                      null;
2645                   end if;
2646
2647             --  Another special case, an attribute denoting a procedure call
2648
2649             when
2650                N_Attribute_Reference =>
2651                   if Is_Procedure_Attribute_Name (Attribute_Name (P)) then
2652                      if P = Wrapped_Node then
2653                         Store_Before_Actions_In_Scope (Ins_Actions);
2654                      else
2655                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2656                      end if;
2657
2658                      return;
2659
2660                   --  In the subexpression case, keep climbing
2661
2662                   else
2663                      null;
2664                   end if;
2665
2666             --  For all other node types, keep climbing tree
2667
2668             when
2669                N_Abortable_Part                         |
2670                N_Accept_Alternative                     |
2671                N_Access_Definition                      |
2672                N_Access_Function_Definition             |
2673                N_Access_Procedure_Definition            |
2674                N_Access_To_Object_Definition            |
2675                N_Aggregate                              |
2676                N_Allocator                              |
2677                N_Case_Statement_Alternative             |
2678                N_Character_Literal                      |
2679                N_Compilation_Unit                       |
2680                N_Compilation_Unit_Aux                   |
2681                N_Component_Clause                       |
2682                N_Component_Declaration                  |
2683                N_Component_Definition                   |
2684                N_Component_List                         |
2685                N_Constrained_Array_Definition           |
2686                N_Decimal_Fixed_Point_Definition         |
2687                N_Defining_Character_Literal             |
2688                N_Defining_Identifier                    |
2689                N_Defining_Operator_Symbol               |
2690                N_Defining_Program_Unit_Name             |
2691                N_Delay_Alternative                      |
2692                N_Delta_Constraint                       |
2693                N_Derived_Type_Definition                |
2694                N_Designator                             |
2695                N_Digits_Constraint                      |
2696                N_Discriminant_Association               |
2697                N_Discriminant_Specification             |
2698                N_Empty                                  |
2699                N_Entry_Body_Formal_Part                 |
2700                N_Entry_Call_Alternative                 |
2701                N_Entry_Declaration                      |
2702                N_Entry_Index_Specification              |
2703                N_Enumeration_Type_Definition            |
2704                N_Error                                  |
2705                N_Exception_Handler                      |
2706                N_Expanded_Name                          |
2707                N_Explicit_Dereference                   |
2708                N_Extension_Aggregate                    |
2709                N_Floating_Point_Definition              |
2710                N_Formal_Decimal_Fixed_Point_Definition  |
2711                N_Formal_Derived_Type_Definition         |
2712                N_Formal_Discrete_Type_Definition        |
2713                N_Formal_Floating_Point_Definition       |
2714                N_Formal_Modular_Type_Definition         |
2715                N_Formal_Ordinary_Fixed_Point_Definition |
2716                N_Formal_Package_Declaration             |
2717                N_Formal_Private_Type_Definition         |
2718                N_Formal_Signed_Integer_Type_Definition  |
2719                N_Function_Call                          |
2720                N_Function_Specification                 |
2721                N_Generic_Association                    |
2722                N_Handled_Sequence_Of_Statements         |
2723                N_Identifier                             |
2724                N_In                                     |
2725                N_Index_Or_Discriminant_Constraint       |
2726                N_Indexed_Component                      |
2727                N_Integer_Literal                        |
2728                N_Itype_Reference                        |
2729                N_Label                                  |
2730                N_Loop_Parameter_Specification           |
2731                N_Mod_Clause                             |
2732                N_Modular_Type_Definition                |
2733                N_Not_In                                 |
2734                N_Null                                   |
2735                N_Op_Abs                                 |
2736                N_Op_Add                                 |
2737                N_Op_And                                 |
2738                N_Op_Concat                              |
2739                N_Op_Divide                              |
2740                N_Op_Eq                                  |
2741                N_Op_Expon                               |
2742                N_Op_Ge                                  |
2743                N_Op_Gt                                  |
2744                N_Op_Le                                  |
2745                N_Op_Lt                                  |
2746                N_Op_Minus                               |
2747                N_Op_Mod                                 |
2748                N_Op_Multiply                            |
2749                N_Op_Ne                                  |
2750                N_Op_Not                                 |
2751                N_Op_Or                                  |
2752                N_Op_Plus                                |
2753                N_Op_Rem                                 |
2754                N_Op_Rotate_Left                         |
2755                N_Op_Rotate_Right                        |
2756                N_Op_Shift_Left                          |
2757                N_Op_Shift_Right                         |
2758                N_Op_Shift_Right_Arithmetic              |
2759                N_Op_Subtract                            |
2760                N_Op_Xor                                 |
2761                N_Operator_Symbol                        |
2762                N_Ordinary_Fixed_Point_Definition        |
2763                N_Others_Choice                          |
2764                N_Package_Specification                  |
2765                N_Parameter_Association                  |
2766                N_Parameter_Specification                |
2767                N_Pop_Constraint_Error_Label             |
2768                N_Pop_Program_Error_Label                |
2769                N_Pop_Storage_Error_Label                |
2770                N_Pragma_Argument_Association            |
2771                N_Procedure_Specification                |
2772                N_Protected_Definition                   |
2773                N_Push_Constraint_Error_Label            |
2774                N_Push_Program_Error_Label               |
2775                N_Push_Storage_Error_Label               |
2776                N_Qualified_Expression                   |
2777                N_Range                                  |
2778                N_Range_Constraint                       |
2779                N_Real_Literal                           |
2780                N_Real_Range_Specification               |
2781                N_Record_Definition                      |
2782                N_Reference                              |
2783                N_SCIL_Dispatch_Table_Object_Init        |
2784                N_SCIL_Dispatch_Table_Tag_Init           |
2785                N_SCIL_Dispatching_Call                  |
2786                N_SCIL_Membership_Test                   |
2787                N_SCIL_Tag_Init                          |
2788                N_Selected_Component                     |
2789                N_Signed_Integer_Type_Definition         |
2790                N_Single_Protected_Declaration           |
2791                N_Slice                                  |
2792                N_String_Literal                         |
2793                N_Subprogram_Info                        |
2794                N_Subtype_Indication                     |
2795                N_Subunit                                |
2796                N_Task_Definition                        |
2797                N_Terminate_Alternative                  |
2798                N_Triggering_Alternative                 |
2799                N_Type_Conversion                        |
2800                N_Unchecked_Expression                   |
2801                N_Unchecked_Type_Conversion              |
2802                N_Unconstrained_Array_Definition         |
2803                N_Unused_At_End                          |
2804                N_Unused_At_Start                        |
2805                N_Use_Package_Clause                     |
2806                N_Use_Type_Clause                        |
2807                N_Variant                                |
2808                N_Variant_Part                           |
2809                N_Validate_Unchecked_Conversion          |
2810                N_With_Clause
2811             =>
2812                null;
2813
2814          end case;
2815
2816          --  Make sure that inserted actions stay in the transient scope
2817
2818          if P = Wrapped_Node then
2819             Store_Before_Actions_In_Scope (Ins_Actions);
2820             return;
2821          end if;
2822
2823          --  If we fall through above tests, keep climbing tree
2824
2825          N := P;
2826
2827          if Nkind (Parent (N)) = N_Subunit then
2828
2829             --  This is the proper body corresponding to a stub. Insertion
2830             --  must be done at the point of the stub, which is in the decla-
2831             --  rative part of the parent unit.
2832
2833             P := Corresponding_Stub (Parent (N));
2834
2835          else
2836             P := Parent (N);
2837          end if;
2838       end loop;
2839    end Insert_Actions;
2840
2841    --  Version with check(s) suppressed
2842
2843    procedure Insert_Actions
2844      (Assoc_Node  : Node_Id;
2845       Ins_Actions : List_Id;
2846       Suppress    : Check_Id)
2847    is
2848    begin
2849       if Suppress = All_Checks then
2850          declare
2851             Svg : constant Suppress_Array := Scope_Suppress;
2852          begin
2853             Scope_Suppress := (others => True);
2854             Insert_Actions (Assoc_Node, Ins_Actions);
2855             Scope_Suppress := Svg;
2856          end;
2857
2858       else
2859          declare
2860             Svg : constant Boolean := Scope_Suppress (Suppress);
2861          begin
2862             Scope_Suppress (Suppress) := True;
2863             Insert_Actions (Assoc_Node, Ins_Actions);
2864             Scope_Suppress (Suppress) := Svg;
2865          end;
2866       end if;
2867    end Insert_Actions;
2868
2869    --------------------------
2870    -- Insert_Actions_After --
2871    --------------------------
2872
2873    procedure Insert_Actions_After
2874      (Assoc_Node  : Node_Id;
2875       Ins_Actions : List_Id)
2876    is
2877    begin
2878       if Scope_Is_Transient
2879         and then Assoc_Node = Node_To_Be_Wrapped
2880       then
2881          Store_After_Actions_In_Scope (Ins_Actions);
2882       else
2883          Insert_List_After_And_Analyze (Assoc_Node, Ins_Actions);
2884       end if;
2885    end Insert_Actions_After;
2886
2887    ---------------------------------
2888    -- Insert_Library_Level_Action --
2889    ---------------------------------
2890
2891    procedure Insert_Library_Level_Action (N : Node_Id) is
2892       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2893
2894    begin
2895       Push_Scope (Cunit_Entity (Main_Unit));
2896       --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2897
2898       if No (Actions (Aux)) then
2899          Set_Actions (Aux, New_List (N));
2900       else
2901          Append (N, Actions (Aux));
2902       end if;
2903
2904       Analyze (N);
2905       Pop_Scope;
2906    end Insert_Library_Level_Action;
2907
2908    ----------------------------------
2909    -- Insert_Library_Level_Actions --
2910    ----------------------------------
2911
2912    procedure Insert_Library_Level_Actions (L : List_Id) is
2913       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2914
2915    begin
2916       if Is_Non_Empty_List (L) then
2917          Push_Scope (Cunit_Entity (Main_Unit));
2918          --  ??? should this be Current_Sem_Unit instead of Main_Unit?
2919
2920          if No (Actions (Aux)) then
2921             Set_Actions (Aux, L);
2922             Analyze_List (L);
2923          else
2924             Insert_List_After_And_Analyze (Last (Actions (Aux)), L);
2925          end if;
2926
2927          Pop_Scope;
2928       end if;
2929    end Insert_Library_Level_Actions;
2930
2931    ----------------------
2932    -- Inside_Init_Proc --
2933    ----------------------
2934
2935    function Inside_Init_Proc return Boolean is
2936       S : Entity_Id;
2937
2938    begin
2939       S := Current_Scope;
2940       while Present (S)
2941         and then S /= Standard_Standard
2942       loop
2943          if Is_Init_Proc (S) then
2944             return True;
2945          else
2946             S := Scope (S);
2947          end if;
2948       end loop;
2949
2950       return False;
2951    end Inside_Init_Proc;
2952
2953    ----------------------------
2954    -- Is_All_Null_Statements --
2955    ----------------------------
2956
2957    function Is_All_Null_Statements (L : List_Id) return Boolean is
2958       Stm : Node_Id;
2959
2960    begin
2961       Stm := First (L);
2962       while Present (Stm) loop
2963          if Nkind (Stm) /= N_Null_Statement then
2964             return False;
2965          end if;
2966
2967          Next (Stm);
2968       end loop;
2969
2970       return True;
2971    end Is_All_Null_Statements;
2972
2973    ---------------------------------
2974    -- Is_Fully_Repped_Tagged_Type --
2975    ---------------------------------
2976
2977    function Is_Fully_Repped_Tagged_Type (T : Entity_Id) return Boolean is
2978       U    : constant Entity_Id := Underlying_Type (T);
2979       Comp : Entity_Id;
2980
2981    begin
2982       if No (U) or else not Is_Tagged_Type (U) then
2983          return False;
2984       elsif Has_Discriminants (U) then
2985          return False;
2986       elsif not Has_Specified_Layout (U) then
2987          return False;
2988       end if;
2989
2990       --  Here we have a tagged type, see if it has any unlayed out fields
2991       --  other than a possible tag and parent fields. If so, we return False.
2992
2993       Comp := First_Component (U);
2994       while Present (Comp) loop
2995          if not Is_Tag (Comp)
2996            and then Chars (Comp) /= Name_uParent
2997            and then No (Component_Clause (Comp))
2998          then
2999             return False;
3000          else
3001             Next_Component (Comp);
3002          end if;
3003       end loop;
3004
3005       --  All components are layed out
3006
3007       return True;
3008    end Is_Fully_Repped_Tagged_Type;
3009
3010    ----------------------------------
3011    -- Is_Library_Level_Tagged_Type --
3012    ----------------------------------
3013
3014    function Is_Library_Level_Tagged_Type (Typ : Entity_Id) return Boolean is
3015    begin
3016       return Is_Tagged_Type (Typ)
3017         and then Is_Library_Level_Entity (Typ);
3018    end Is_Library_Level_Tagged_Type;
3019
3020    ----------------------------------
3021    -- Is_Possibly_Unaligned_Object --
3022    ----------------------------------
3023
3024    function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean is
3025       T  : constant Entity_Id := Etype (N);
3026
3027    begin
3028       --  If renamed object, apply test to underlying object
3029
3030       if Is_Entity_Name (N)
3031         and then Is_Object (Entity (N))
3032         and then Present (Renamed_Object (Entity (N)))
3033       then
3034          return Is_Possibly_Unaligned_Object (Renamed_Object (Entity (N)));
3035       end if;
3036
3037       --  Tagged and controlled types and aliased types are always aligned,
3038       --  as are concurrent types.
3039
3040       if Is_Aliased (T)
3041         or else Has_Controlled_Component (T)
3042         or else Is_Concurrent_Type (T)
3043         or else Is_Tagged_Type (T)
3044         or else Is_Controlled (T)
3045       then
3046          return False;
3047       end if;
3048
3049       --  If this is an element of a packed array, may be unaligned
3050
3051       if Is_Ref_To_Bit_Packed_Array (N) then
3052          return True;
3053       end if;
3054
3055       --  Case of component reference
3056
3057       if Nkind (N) = N_Selected_Component then
3058          declare
3059             P : constant Node_Id   := Prefix (N);
3060             C : constant Entity_Id := Entity (Selector_Name (N));
3061             M : Nat;
3062             S : Nat;
3063
3064          begin
3065             --  If component reference is for an array with non-static bounds,
3066             --  then it is always aligned: we can only process unaligned
3067             --  arrays with static bounds (more accurately bounds known at
3068             --  compile time).
3069
3070             if Is_Array_Type (T)
3071               and then not Compile_Time_Known_Bounds (T)
3072             then
3073                return False;
3074             end if;
3075
3076             --  If component is aliased, it is definitely properly aligned
3077
3078             if Is_Aliased (C) then
3079                return False;
3080             end if;
3081
3082             --  If component is for a type implemented as a scalar, and the
3083             --  record is packed, and the component is other than the first
3084             --  component of the record, then the component may be unaligned.
3085
3086             if Is_Packed (Etype (P))
3087               and then Represented_As_Scalar (Etype (C))
3088               and then First_Entity (Scope (C)) /= C
3089             then
3090                return True;
3091             end if;
3092
3093             --  Compute maximum possible alignment for T
3094
3095             --  If alignment is known, then that settles things
3096
3097             if Known_Alignment (T) then
3098                M := UI_To_Int (Alignment (T));
3099
3100             --  If alignment is not known, tentatively set max alignment
3101
3102             else
3103                M := Ttypes.Maximum_Alignment;
3104
3105                --  We can reduce this if the Esize is known since the default
3106                --  alignment will never be more than the smallest power of 2
3107                --  that does not exceed this Esize value.
3108
3109                if Known_Esize (T) then
3110                   S := UI_To_Int (Esize (T));
3111
3112                   while (M / 2) >= S loop
3113                      M := M / 2;
3114                   end loop;
3115                end if;
3116             end if;
3117
3118             --  If the component reference is for a record that has a specified
3119             --  alignment, and we either know it is too small, or cannot tell,
3120             --  then the component may be unaligned
3121
3122             if Known_Alignment (Etype (P))
3123               and then Alignment (Etype (P)) < Ttypes.Maximum_Alignment
3124               and then M > Alignment (Etype (P))
3125             then
3126                return True;
3127             end if;
3128
3129             --  Case of component clause present which may specify an
3130             --  unaligned position.
3131
3132             if Present (Component_Clause (C)) then
3133
3134                --  Otherwise we can do a test to make sure that the actual
3135                --  start position in the record, and the length, are both
3136                --  consistent with the required alignment. If not, we know
3137                --  that we are unaligned.
3138
3139                declare
3140                   Align_In_Bits : constant Nat := M * System_Storage_Unit;
3141                begin
3142                   if Component_Bit_Offset (C) mod Align_In_Bits /= 0
3143                     or else Esize (C) mod Align_In_Bits /= 0
3144                   then
3145                      return True;
3146                   end if;
3147                end;
3148             end if;
3149
3150             --  Otherwise, for a component reference, test prefix
3151
3152             return Is_Possibly_Unaligned_Object (P);
3153          end;
3154
3155       --  If not a component reference, must be aligned
3156
3157       else
3158          return False;
3159       end if;
3160    end Is_Possibly_Unaligned_Object;
3161
3162    ---------------------------------
3163    -- Is_Possibly_Unaligned_Slice --
3164    ---------------------------------
3165
3166    function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean is
3167    begin
3168       --  Go to renamed object
3169
3170       if Is_Entity_Name (N)
3171         and then Is_Object (Entity (N))
3172         and then Present (Renamed_Object (Entity (N)))
3173       then
3174          return Is_Possibly_Unaligned_Slice (Renamed_Object (Entity (N)));
3175       end if;
3176
3177       --  The reference must be a slice
3178
3179       if Nkind (N) /= N_Slice then
3180          return False;
3181       end if;
3182
3183       --  Always assume the worst for a nested record component with a
3184       --  component clause, which gigi/gcc does not appear to handle well.
3185       --  It is not clear why this special test is needed at all ???
3186
3187       if Nkind (Prefix (N)) = N_Selected_Component
3188         and then Nkind (Prefix (Prefix (N))) = N_Selected_Component
3189         and then
3190           Present (Component_Clause (Entity (Selector_Name (Prefix (N)))))
3191       then
3192          return True;
3193       end if;
3194
3195       --  We only need to worry if the target has strict alignment
3196
3197       if not Target_Strict_Alignment then
3198          return False;
3199       end if;
3200
3201       --  If it is a slice, then look at the array type being sliced
3202
3203       declare
3204          Sarr : constant Node_Id := Prefix (N);
3205          --  Prefix of the slice, i.e. the array being sliced
3206
3207          Styp : constant Entity_Id := Etype (Prefix (N));
3208          --  Type of the array being sliced
3209
3210          Pref : Node_Id;
3211          Ptyp : Entity_Id;
3212
3213       begin
3214          --  The problems arise if the array object that is being sliced
3215          --  is a component of a record or array, and we cannot guarantee
3216          --  the alignment of the array within its containing object.
3217
3218          --  To investigate this, we look at successive prefixes to see
3219          --  if we have a worrisome indexed or selected component.
3220
3221          Pref := Sarr;
3222          loop
3223             --  Case of array is part of an indexed component reference
3224
3225             if Nkind (Pref) = N_Indexed_Component then
3226                Ptyp := Etype (Prefix (Pref));
3227
3228                --  The only problematic case is when the array is packed,
3229                --  in which case we really know nothing about the alignment
3230                --  of individual components.
3231
3232                if Is_Bit_Packed_Array (Ptyp) then
3233                   return True;
3234                end if;
3235
3236             --  Case of array is part of a selected component reference
3237
3238             elsif Nkind (Pref) = N_Selected_Component then
3239                Ptyp := Etype (Prefix (Pref));
3240
3241                --  We are definitely in trouble if the record in question
3242                --  has an alignment, and either we know this alignment is
3243                --  inconsistent with the alignment of the slice, or we
3244                --  don't know what the alignment of the slice should be.
3245
3246                if Known_Alignment (Ptyp)
3247                  and then (Unknown_Alignment (Styp)
3248                              or else Alignment (Styp) > Alignment (Ptyp))
3249                then
3250                   return True;
3251                end if;
3252
3253                --  We are in potential trouble if the record type is packed.
3254                --  We could special case when we know that the array is the
3255                --  first component, but that's not such a simple case ???
3256
3257                if Is_Packed (Ptyp) then
3258                   return True;
3259                end if;
3260
3261                --  We are in trouble if there is a component clause, and
3262                --  either we do not know the alignment of the slice, or
3263                --  the alignment of the slice is inconsistent with the
3264                --  bit position specified by the component clause.
3265
3266                declare
3267                   Field : constant Entity_Id := Entity (Selector_Name (Pref));
3268                begin
3269                   if Present (Component_Clause (Field))
3270                     and then
3271                       (Unknown_Alignment (Styp)
3272                         or else
3273                          (Component_Bit_Offset (Field) mod
3274                            (System_Storage_Unit * Alignment (Styp))) /= 0)
3275                   then
3276                      return True;
3277                   end if;
3278                end;
3279
3280             --  For cases other than selected or indexed components we
3281             --  know we are OK, since no issues arise over alignment.
3282
3283             else
3284                return False;
3285             end if;
3286
3287             --  We processed an indexed component or selected component
3288             --  reference that looked safe, so keep checking prefixes.
3289
3290             Pref := Prefix (Pref);
3291          end loop;
3292       end;
3293    end Is_Possibly_Unaligned_Slice;
3294
3295    --------------------------------
3296    -- Is_Ref_To_Bit_Packed_Array --
3297    --------------------------------
3298
3299    function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean is
3300       Result : Boolean;
3301       Expr   : Node_Id;
3302
3303    begin
3304       if Is_Entity_Name (N)
3305         and then Is_Object (Entity (N))
3306         and then Present (Renamed_Object (Entity (N)))
3307       then
3308          return Is_Ref_To_Bit_Packed_Array (Renamed_Object (Entity (N)));
3309       end if;
3310
3311       if Nkind (N) = N_Indexed_Component
3312            or else
3313          Nkind (N) = N_Selected_Component
3314       then
3315          if Is_Bit_Packed_Array (Etype (Prefix (N))) then
3316             Result := True;
3317          else
3318             Result := Is_Ref_To_Bit_Packed_Array (Prefix (N));
3319          end if;
3320
3321          if Result and then Nkind (N) = N_Indexed_Component then
3322             Expr := First (Expressions (N));
3323             while Present (Expr) loop
3324                Force_Evaluation (Expr);
3325                Next (Expr);
3326             end loop;
3327          end if;
3328
3329          return Result;
3330
3331       else
3332          return False;
3333       end if;
3334    end Is_Ref_To_Bit_Packed_Array;
3335
3336    --------------------------------
3337    -- Is_Ref_To_Bit_Packed_Slice --
3338    --------------------------------
3339
3340    function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean is
3341    begin
3342       if Nkind (N) = N_Type_Conversion then
3343          return Is_Ref_To_Bit_Packed_Slice (Expression (N));
3344
3345       elsif Is_Entity_Name (N)
3346         and then Is_Object (Entity (N))
3347         and then Present (Renamed_Object (Entity (N)))
3348       then
3349          return Is_Ref_To_Bit_Packed_Slice (Renamed_Object (Entity (N)));
3350
3351       elsif Nkind (N) = N_Slice
3352         and then Is_Bit_Packed_Array (Etype (Prefix (N)))
3353       then
3354          return True;
3355
3356       elsif Nkind (N) = N_Indexed_Component
3357            or else
3358          Nkind (N) = N_Selected_Component
3359       then
3360          return Is_Ref_To_Bit_Packed_Slice (Prefix (N));
3361
3362       else
3363          return False;
3364       end if;
3365    end Is_Ref_To_Bit_Packed_Slice;
3366
3367    -----------------------
3368    -- Is_Renamed_Object --
3369    -----------------------
3370
3371    function Is_Renamed_Object (N : Node_Id) return Boolean is
3372       Pnod : constant Node_Id   := Parent (N);
3373       Kind : constant Node_Kind := Nkind (Pnod);
3374    begin
3375       if Kind = N_Object_Renaming_Declaration then
3376          return True;
3377       elsif Nkind_In (Kind, N_Indexed_Component, N_Selected_Component) then
3378          return Is_Renamed_Object (Pnod);
3379       else
3380          return False;
3381       end if;
3382    end Is_Renamed_Object;
3383
3384    ----------------------------
3385    -- Is_Untagged_Derivation --
3386    ----------------------------
3387
3388    function Is_Untagged_Derivation (T : Entity_Id) return Boolean is
3389    begin
3390       return (not Is_Tagged_Type (T) and then Is_Derived_Type (T))
3391                or else
3392              (Is_Private_Type (T) and then Present (Full_View (T))
3393                and then not Is_Tagged_Type (Full_View (T))
3394                and then Is_Derived_Type (Full_View (T))
3395                and then Etype (Full_View (T)) /= T);
3396    end Is_Untagged_Derivation;
3397
3398    ---------------------------
3399    -- Is_Volatile_Reference --
3400    ---------------------------
3401
3402    function Is_Volatile_Reference (N : Node_Id) return Boolean is
3403    begin
3404       if Nkind (N) in N_Has_Etype
3405         and then Present (Etype (N))
3406         and then Treat_As_Volatile (Etype (N))
3407       then
3408          return True;
3409
3410       elsif Is_Entity_Name (N) then
3411          return Treat_As_Volatile (Entity (N));
3412
3413       elsif Nkind (N) = N_Slice then
3414          return Is_Volatile_Reference (Prefix (N));
3415
3416       elsif Nkind_In (N, N_Indexed_Component, N_Selected_Component) then
3417          if (Is_Entity_Name (Prefix (N))
3418                and then Has_Volatile_Components (Entity (Prefix (N))))
3419            or else (Present (Etype (Prefix (N)))
3420                       and then Has_Volatile_Components (Etype (Prefix (N))))
3421          then
3422             return True;
3423          else
3424             return Is_Volatile_Reference (Prefix (N));
3425          end if;
3426
3427       else
3428          return False;
3429       end if;
3430    end Is_Volatile_Reference;
3431
3432    --------------------
3433    -- Kill_Dead_Code --
3434    --------------------
3435
3436    procedure Kill_Dead_Code (N : Node_Id; Warn : Boolean := False) is
3437       W : Boolean := Warn;
3438       --  Set False if warnings suppressed
3439
3440    begin
3441       if Present (N) then
3442          Remove_Warning_Messages (N);
3443
3444          --  Generate warning if appropriate
3445
3446          if W then
3447
3448             --  We suppress the warning if this code is under control of an
3449             --  if statement, whose condition is a simple identifier, and
3450             --  either we are in an instance, or warnings off is set for this
3451             --  identifier. The reason for killing it in the instance case is
3452             --  that it is common and reasonable for code to be deleted in
3453             --  instances for various reasons.
3454
3455             if Nkind (Parent (N)) = N_If_Statement then
3456                declare
3457                   C : constant Node_Id := Condition (Parent (N));
3458                begin
3459                   if Nkind (C) = N_Identifier
3460                     and then
3461                       (In_Instance
3462                         or else (Present (Entity (C))
3463                                    and then Has_Warnings_Off (Entity (C))))
3464                   then
3465                      W := False;
3466                   end if;
3467                end;
3468             end if;
3469
3470             --  Generate warning if not suppressed
3471
3472             if W then
3473                Error_Msg_F
3474                  ("?this code can never be executed and has been deleted!", N);
3475             end if;
3476          end if;
3477
3478          --  Recurse into block statements and bodies to process declarations
3479          --  and statements.
3480
3481          if Nkind (N) = N_Block_Statement
3482            or else Nkind (N) = N_Subprogram_Body
3483            or else Nkind (N) = N_Package_Body
3484          then
3485             Kill_Dead_Code (Declarations (N), False);
3486             Kill_Dead_Code (Statements (Handled_Statement_Sequence (N)));
3487
3488             if Nkind (N) = N_Subprogram_Body then
3489                Set_Is_Eliminated (Defining_Entity (N));
3490             end if;
3491
3492          elsif Nkind (N) = N_Package_Declaration then
3493             Kill_Dead_Code (Visible_Declarations (Specification (N)));
3494             Kill_Dead_Code (Private_Declarations (Specification (N)));
3495
3496             --  ??? After this point, Delete_Tree has been called on all
3497             --  declarations in Specification (N), so references to
3498             --  entities therein look suspicious.
3499
3500             declare
3501                E : Entity_Id := First_Entity (Defining_Entity (N));
3502             begin
3503                while Present (E) loop
3504                   if Ekind (E) = E_Operator then
3505                      Set_Is_Eliminated (E);
3506                   end if;
3507
3508                   Next_Entity (E);
3509                end loop;
3510             end;
3511
3512          --  Recurse into composite statement to kill individual statements,
3513          --  in particular instantiations.
3514
3515          elsif Nkind (N) = N_If_Statement then
3516             Kill_Dead_Code (Then_Statements (N));
3517             Kill_Dead_Code (Elsif_Parts (N));
3518             Kill_Dead_Code (Else_Statements (N));
3519
3520          elsif Nkind (N) = N_Loop_Statement then
3521             Kill_Dead_Code (Statements (N));
3522
3523          elsif Nkind (N) = N_Case_Statement then
3524             declare
3525                Alt : Node_Id;
3526             begin
3527                Alt := First (Alternatives (N));
3528                while Present (Alt) loop
3529                   Kill_Dead_Code (Statements (Alt));
3530                   Next (Alt);
3531                end loop;
3532             end;
3533
3534          elsif Nkind (N) = N_Case_Statement_Alternative then
3535             Kill_Dead_Code (Statements (N));
3536
3537          --  Deal with dead instances caused by deleting instantiations
3538
3539          elsif Nkind (N) in N_Generic_Instantiation then
3540             Remove_Dead_Instance (N);
3541          end if;
3542       end if;
3543    end Kill_Dead_Code;
3544
3545    --  Case where argument is a list of nodes to be killed
3546
3547    procedure Kill_Dead_Code (L : List_Id; Warn : Boolean := False) is
3548       N : Node_Id;
3549       W : Boolean;
3550    begin
3551       W := Warn;
3552       if Is_Non_Empty_List (L) then
3553          N := First (L);
3554          while Present (N) loop
3555             Kill_Dead_Code (N, W);
3556             W := False;
3557             Next (N);
3558          end loop;
3559       end if;
3560    end Kill_Dead_Code;
3561
3562    ------------------------
3563    -- Known_Non_Negative --
3564    ------------------------
3565
3566    function Known_Non_Negative (Opnd : Node_Id) return Boolean is
3567    begin
3568       if Is_OK_Static_Expression (Opnd)
3569         and then Expr_Value (Opnd) >= 0
3570       then
3571          return True;
3572
3573       else
3574          declare
3575             Lo : constant Node_Id := Type_Low_Bound (Etype (Opnd));
3576
3577          begin
3578             return
3579               Is_OK_Static_Expression (Lo) and then Expr_Value (Lo) >= 0;
3580          end;
3581       end if;
3582    end Known_Non_Negative;
3583
3584    --------------------
3585    -- Known_Non_Null --
3586    --------------------
3587
3588    function Known_Non_Null (N : Node_Id) return Boolean is
3589    begin
3590       --  Checks for case where N is an entity reference
3591
3592       if Is_Entity_Name (N) and then Present (Entity (N)) then
3593          declare
3594             E   : constant Entity_Id := Entity (N);
3595             Op  : Node_Kind;
3596             Val : Node_Id;
3597
3598          begin
3599             --  First check if we are in decisive conditional
3600
3601             Get_Current_Value_Condition (N, Op, Val);
3602
3603             if Known_Null (Val) then
3604                if Op = N_Op_Eq then
3605                   return False;
3606                elsif Op = N_Op_Ne then
3607                   return True;
3608                end if;
3609             end if;
3610
3611             --  If OK to do replacement, test Is_Known_Non_Null flag
3612
3613             if OK_To_Do_Constant_Replacement (E) then
3614                return Is_Known_Non_Null (E);
3615
3616             --  Otherwise if not safe to do replacement, then say so
3617
3618             else
3619                return False;
3620             end if;
3621          end;
3622
3623       --  True if access attribute
3624
3625       elsif Nkind (N) = N_Attribute_Reference
3626         and then (Attribute_Name (N) = Name_Access
3627                     or else
3628                   Attribute_Name (N) = Name_Unchecked_Access
3629                     or else
3630                   Attribute_Name (N) = Name_Unrestricted_Access)
3631       then
3632          return True;
3633
3634       --  True if allocator
3635
3636       elsif Nkind (N) = N_Allocator then
3637          return True;
3638
3639       --  For a conversion, true if expression is known non-null
3640
3641       elsif Nkind (N) = N_Type_Conversion then
3642          return Known_Non_Null (Expression (N));
3643
3644       --  Above are all cases where the value could be determined to be
3645       --  non-null. In all other cases, we don't know, so return False.
3646
3647       else
3648          return False;
3649       end if;
3650    end Known_Non_Null;
3651
3652    ----------------
3653    -- Known_Null --
3654    ----------------
3655
3656    function Known_Null (N : Node_Id) return Boolean is
3657    begin
3658       --  Checks for case where N is an entity reference
3659
3660       if Is_Entity_Name (N) and then Present (Entity (N)) then
3661          declare
3662             E   : constant Entity_Id := Entity (N);
3663             Op  : Node_Kind;
3664             Val : Node_Id;
3665
3666          begin
3667             --  Constant null value is for sure null
3668
3669             if Ekind (E) = E_Constant
3670               and then Known_Null (Constant_Value (E))
3671             then
3672                return True;
3673             end if;
3674
3675             --  First check if we are in decisive conditional
3676
3677             Get_Current_Value_Condition (N, Op, Val);
3678
3679             if Known_Null (Val) then
3680                if Op = N_Op_Eq then
3681                   return True;
3682                elsif Op = N_Op_Ne then
3683                   return False;
3684                end if;
3685             end if;
3686
3687             --  If OK to do replacement, test Is_Known_Null flag
3688
3689             if OK_To_Do_Constant_Replacement (E) then
3690                return Is_Known_Null (E);
3691
3692             --  Otherwise if not safe to do replacement, then say so
3693
3694             else
3695                return False;
3696             end if;
3697          end;
3698
3699       --  True if explicit reference to null
3700
3701       elsif Nkind (N) = N_Null then
3702          return True;
3703
3704       --  For a conversion, true if expression is known null
3705
3706       elsif Nkind (N) = N_Type_Conversion then
3707          return Known_Null (Expression (N));
3708
3709       --  Above are all cases where the value could be determined to be null.
3710       --  In all other cases, we don't know, so return False.
3711
3712       else
3713          return False;
3714       end if;
3715    end Known_Null;
3716
3717    -----------------------------
3718    -- Make_CW_Equivalent_Type --
3719    -----------------------------
3720
3721    --  Create a record type used as an equivalent of any member of the class
3722    --  which takes its size from exp.
3723
3724    --  Generate the following code:
3725
3726    --   type Equiv_T is record
3727    --     _parent :  T (List of discriminant constraints taken from Exp);
3728    --     Ext__50 : Storage_Array (1 .. (Exp'size - Typ'object_size)/8);
3729    --   end Equiv_T;
3730    --
3731    --   ??? Note that this type does not guarantee same alignment as all
3732    --   derived types
3733
3734    function Make_CW_Equivalent_Type
3735      (T : Entity_Id;
3736       E : Node_Id) return Entity_Id
3737    is
3738       Loc         : constant Source_Ptr := Sloc (E);
3739       Root_Typ    : constant Entity_Id  := Root_Type (T);
3740       List_Def    : constant List_Id    := Empty_List;
3741       Comp_List   : constant List_Id    := New_List;
3742       Equiv_Type  : Entity_Id;
3743       Range_Type  : Entity_Id;
3744       Str_Type    : Entity_Id;
3745       Constr_Root : Entity_Id;
3746       Sizexpr     : Node_Id;
3747
3748    begin
3749       if not Has_Discriminants (Root_Typ) then
3750          Constr_Root := Root_Typ;
3751       else
3752          Constr_Root := Make_Temporary (Loc, 'R');
3753
3754          --  subtype cstr__n is T (List of discr constraints taken from Exp)
3755
3756          Append_To (List_Def,
3757            Make_Subtype_Declaration (Loc,
3758              Defining_Identifier => Constr_Root,
3759              Subtype_Indication  => Make_Subtype_From_Expr (E, Root_Typ)));
3760       end if;
3761
3762       --  Generate the range subtype declaration
3763
3764       Range_Type := Make_Temporary (Loc, 'G');
3765
3766       if not Is_Interface (Root_Typ) then
3767
3768          --  subtype rg__xx is
3769          --    Storage_Offset range 1 .. (Expr'size - typ'size) / Storage_Unit
3770
3771          Sizexpr :=
3772            Make_Op_Subtract (Loc,
3773              Left_Opnd =>
3774                Make_Attribute_Reference (Loc,
3775                  Prefix =>
3776                    OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3777                  Attribute_Name => Name_Size),
3778              Right_Opnd =>
3779                Make_Attribute_Reference (Loc,
3780                  Prefix => New_Reference_To (Constr_Root, Loc),
3781                  Attribute_Name => Name_Object_Size));
3782       else
3783          --  subtype rg__xx is
3784          --    Storage_Offset range 1 .. Expr'size / Storage_Unit
3785
3786          Sizexpr :=
3787            Make_Attribute_Reference (Loc,
3788              Prefix =>
3789                OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3790              Attribute_Name => Name_Size);
3791       end if;
3792
3793       Set_Paren_Count (Sizexpr, 1);
3794
3795       Append_To (List_Def,
3796         Make_Subtype_Declaration (Loc,
3797           Defining_Identifier => Range_Type,
3798           Subtype_Indication =>
3799             Make_Subtype_Indication (Loc,
3800               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Offset), Loc),
3801               Constraint => Make_Range_Constraint (Loc,
3802                 Range_Expression =>
3803                   Make_Range (Loc,
3804                     Low_Bound => Make_Integer_Literal (Loc, 1),
3805                     High_Bound =>
3806                       Make_Op_Divide (Loc,
3807                         Left_Opnd => Sizexpr,
3808                         Right_Opnd => Make_Integer_Literal (Loc,
3809                             Intval => System_Storage_Unit)))))));
3810
3811       --  subtype str__nn is Storage_Array (rg__x);
3812
3813       Str_Type := Make_Temporary (Loc, 'S');
3814       Append_To (List_Def,
3815         Make_Subtype_Declaration (Loc,
3816           Defining_Identifier => Str_Type,
3817           Subtype_Indication =>
3818             Make_Subtype_Indication (Loc,
3819               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Array), Loc),
3820               Constraint =>
3821                 Make_Index_Or_Discriminant_Constraint (Loc,
3822                   Constraints =>
3823                     New_List (New_Reference_To (Range_Type, Loc))))));
3824
3825       --  type Equiv_T is record
3826       --    [ _parent : Tnn; ]
3827       --    E : Str_Type;
3828       --  end Equiv_T;
3829
3830       Equiv_Type := Make_Temporary (Loc, 'T');
3831       Set_Ekind (Equiv_Type, E_Record_Type);
3832       Set_Parent_Subtype (Equiv_Type, Constr_Root);
3833
3834       --  Set Is_Class_Wide_Equivalent_Type very early to trigger the special
3835       --  treatment for this type. In particular, even though _parent's type
3836       --  is a controlled type or contains controlled components, we do not
3837       --  want to set Has_Controlled_Component on it to avoid making it gain
3838       --  an unwanted _controller component.
3839
3840       Set_Is_Class_Wide_Equivalent_Type (Equiv_Type);
3841
3842       if not Is_Interface (Root_Typ) then
3843          Append_To (Comp_List,
3844            Make_Component_Declaration (Loc,
3845              Defining_Identifier =>
3846                Make_Defining_Identifier (Loc, Name_uParent),
3847              Component_Definition =>
3848                Make_Component_Definition (Loc,
3849                  Aliased_Present    => False,
3850                  Subtype_Indication => New_Reference_To (Constr_Root, Loc))));
3851       end if;
3852
3853       Append_To (Comp_List,
3854         Make_Component_Declaration (Loc,
3855           Defining_Identifier  => Make_Temporary (Loc, 'C'),
3856           Component_Definition =>
3857             Make_Component_Definition (Loc,
3858               Aliased_Present    => False,
3859               Subtype_Indication => New_Reference_To (Str_Type, Loc))));
3860
3861       Append_To (List_Def,
3862         Make_Full_Type_Declaration (Loc,
3863           Defining_Identifier => Equiv_Type,
3864           Type_Definition =>
3865             Make_Record_Definition (Loc,
3866               Component_List =>
3867                 Make_Component_List (Loc,
3868                   Component_Items => Comp_List,
3869                   Variant_Part    => Empty))));
3870
3871       --  Suppress all checks during the analysis of the expanded code
3872       --  to avoid the generation of spurious warnings under ZFP run-time.
3873
3874       Insert_Actions (E, List_Def, Suppress => All_Checks);
3875       return Equiv_Type;
3876    end Make_CW_Equivalent_Type;
3877
3878    ------------------------
3879    -- Make_Literal_Range --
3880    ------------------------
3881
3882    function Make_Literal_Range
3883      (Loc         : Source_Ptr;
3884       Literal_Typ : Entity_Id) return Node_Id
3885    is
3886       Lo          : constant Node_Id :=
3887                       New_Copy_Tree (String_Literal_Low_Bound (Literal_Typ));
3888       Index       : constant Entity_Id := Etype (Lo);
3889
3890       Hi          : Node_Id;
3891       Length_Expr : constant Node_Id :=
3892                       Make_Op_Subtract (Loc,
3893                         Left_Opnd =>
3894                           Make_Integer_Literal (Loc,
3895                             Intval => String_Literal_Length (Literal_Typ)),
3896                         Right_Opnd =>
3897                           Make_Integer_Literal (Loc, 1));
3898
3899    begin
3900       Set_Analyzed (Lo, False);
3901
3902          if Is_Integer_Type (Index) then
3903             Hi :=
3904               Make_Op_Add (Loc,
3905                 Left_Opnd  => New_Copy_Tree (Lo),
3906                 Right_Opnd => Length_Expr);
3907          else
3908             Hi :=
3909               Make_Attribute_Reference (Loc,
3910                 Attribute_Name => Name_Val,
3911                 Prefix => New_Occurrence_Of (Index, Loc),
3912                 Expressions => New_List (
3913                  Make_Op_Add (Loc,
3914                    Left_Opnd =>
3915                      Make_Attribute_Reference (Loc,
3916                        Attribute_Name => Name_Pos,
3917                        Prefix => New_Occurrence_Of (Index, Loc),
3918                        Expressions => New_List (New_Copy_Tree (Lo))),
3919                   Right_Opnd => Length_Expr)));
3920          end if;
3921
3922          return
3923            Make_Range (Loc,
3924              Low_Bound  => Lo,
3925              High_Bound => Hi);
3926    end Make_Literal_Range;
3927
3928    --------------------------
3929    -- Make_Non_Empty_Check --
3930    --------------------------
3931
3932    function Make_Non_Empty_Check
3933      (Loc : Source_Ptr;
3934       N   : Node_Id) return Node_Id
3935    is
3936    begin
3937       return
3938         Make_Op_Ne (Loc,
3939           Left_Opnd =>
3940             Make_Attribute_Reference (Loc,
3941               Attribute_Name => Name_Length,
3942               Prefix => Duplicate_Subexpr_No_Checks (N, Name_Req => True)),
3943           Right_Opnd =>
3944             Make_Integer_Literal (Loc, 0));
3945    end Make_Non_Empty_Check;
3946
3947    ----------------------------
3948    -- Make_Subtype_From_Expr --
3949    ----------------------------
3950
3951    --  1. If Expr is an unconstrained array expression, creates
3952    --    Unc_Type(Expr'first(1)..Expr'last(1),..., Expr'first(n)..Expr'last(n))
3953
3954    --  2. If Expr is a unconstrained discriminated type expression, creates
3955    --    Unc_Type(Expr.Discr1, ... , Expr.Discr_n)
3956
3957    --  3. If Expr is class-wide, creates an implicit class wide subtype
3958
3959    function Make_Subtype_From_Expr
3960      (E       : Node_Id;
3961       Unc_Typ : Entity_Id) return Node_Id
3962    is
3963       Loc         : constant Source_Ptr := Sloc (E);
3964       List_Constr : constant List_Id    := New_List;
3965       D           : Entity_Id;
3966
3967       Full_Subtyp  : Entity_Id;
3968       Priv_Subtyp  : Entity_Id;
3969       Utyp         : Entity_Id;
3970       Full_Exp     : Node_Id;
3971
3972    begin
3973       if Is_Private_Type (Unc_Typ)
3974         and then Has_Unknown_Discriminants (Unc_Typ)
3975       then
3976          --  Prepare the subtype completion, Go to base type to
3977          --  find underlying type, because the type may be a generic
3978          --  actual or an explicit subtype.
3979
3980          Utyp        := Underlying_Type (Base_Type (Unc_Typ));
3981          Full_Subtyp := Make_Temporary (Loc, 'C');
3982          Full_Exp    :=
3983            Unchecked_Convert_To (Utyp, Duplicate_Subexpr_No_Checks (E));
3984          Set_Parent (Full_Exp, Parent (E));
3985
3986          Priv_Subtyp := Make_Temporary (Loc, 'P');
3987
3988          Insert_Action (E,
3989            Make_Subtype_Declaration (Loc,
3990              Defining_Identifier => Full_Subtyp,
3991              Subtype_Indication  => Make_Subtype_From_Expr (Full_Exp, Utyp)));
3992
3993          --  Define the dummy private subtype
3994
3995          Set_Ekind          (Priv_Subtyp, Subtype_Kind (Ekind (Unc_Typ)));
3996          Set_Etype          (Priv_Subtyp, Base_Type (Unc_Typ));
3997          Set_Scope          (Priv_Subtyp, Full_Subtyp);
3998          Set_Is_Constrained (Priv_Subtyp);
3999          Set_Is_Tagged_Type (Priv_Subtyp, Is_Tagged_Type (Unc_Typ));
4000          Set_Is_Itype       (Priv_Subtyp);
4001          Set_Associated_Node_For_Itype (Priv_Subtyp, E);
4002
4003          if Is_Tagged_Type  (Priv_Subtyp) then
4004             Set_Class_Wide_Type
4005               (Base_Type (Priv_Subtyp), Class_Wide_Type (Unc_Typ));
4006             Set_Primitive_Operations (Priv_Subtyp,
4007               Primitive_Operations (Unc_Typ));
4008          end if;
4009
4010          Set_Full_View (Priv_Subtyp, Full_Subtyp);
4011
4012          return New_Reference_To (Priv_Subtyp, Loc);
4013
4014       elsif Is_Array_Type (Unc_Typ) then
4015          for J in 1 .. Number_Dimensions (Unc_Typ) loop
4016             Append_To (List_Constr,
4017               Make_Range (Loc,
4018                 Low_Bound =>
4019                   Make_Attribute_Reference (Loc,
4020                     Prefix => Duplicate_Subexpr_No_Checks (E),
4021                     Attribute_Name => Name_First,
4022                     Expressions => New_List (
4023                       Make_Integer_Literal (Loc, J))),
4024
4025                 High_Bound =>
4026                   Make_Attribute_Reference (Loc,
4027                     Prefix         => Duplicate_Subexpr_No_Checks (E),
4028                     Attribute_Name => Name_Last,
4029                     Expressions    => New_List (
4030                       Make_Integer_Literal (Loc, J)))));
4031          end loop;
4032
4033       elsif Is_Class_Wide_Type (Unc_Typ) then
4034          declare
4035             CW_Subtype : Entity_Id;
4036             EQ_Typ     : Entity_Id := Empty;
4037
4038          begin
4039             --  A class-wide equivalent type is not needed when VM_Target
4040             --  because the VM back-ends handle the class-wide object
4041             --  initialization itself (and doesn't need or want the
4042             --  additional intermediate type to handle the assignment).
4043
4044             if Expander_Active and then Tagged_Type_Expansion then
4045                EQ_Typ := Make_CW_Equivalent_Type (Unc_Typ, E);
4046             end if;
4047
4048             CW_Subtype := New_Class_Wide_Subtype (Unc_Typ, E);
4049             Set_Equivalent_Type (CW_Subtype, EQ_Typ);
4050             Set_Cloned_Subtype (CW_Subtype, Base_Type (Unc_Typ));
4051
4052             return New_Occurrence_Of (CW_Subtype, Loc);
4053          end;
4054
4055       --  Indefinite record type with discriminants
4056
4057       else
4058          D := First_Discriminant (Unc_Typ);
4059          while Present (D) loop
4060             Append_To (List_Constr,
4061               Make_Selected_Component (Loc,
4062                 Prefix        => Duplicate_Subexpr_No_Checks (E),
4063                 Selector_Name => New_Reference_To (D, Loc)));
4064
4065             Next_Discriminant (D);
4066          end loop;
4067       end if;
4068
4069       return
4070         Make_Subtype_Indication (Loc,
4071           Subtype_Mark => New_Reference_To (Unc_Typ, Loc),
4072           Constraint   =>
4073             Make_Index_Or_Discriminant_Constraint (Loc,
4074               Constraints => List_Constr));
4075    end Make_Subtype_From_Expr;
4076
4077    -----------------------------
4078    -- May_Generate_Large_Temp --
4079    -----------------------------
4080
4081    --  At the current time, the only types that we return False for (i.e.
4082    --  where we decide we know they cannot generate large temps) are ones
4083    --  where we know the size is 256 bits or less at compile time, and we
4084    --  are still not doing a thorough job on arrays and records ???
4085
4086    function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean is
4087    begin
4088       if not Size_Known_At_Compile_Time (Typ) then
4089          return False;
4090
4091       elsif Esize (Typ) /= 0 and then Esize (Typ) <= 256 then
4092          return False;
4093
4094       elsif Is_Array_Type (Typ)
4095         and then Present (Packed_Array_Type (Typ))
4096       then
4097          return May_Generate_Large_Temp (Packed_Array_Type (Typ));
4098
4099       --  We could do more here to find other small types ???
4100
4101       else
4102          return True;
4103       end if;
4104    end May_Generate_Large_Temp;
4105
4106    ----------------------------
4107    -- New_Class_Wide_Subtype --
4108    ----------------------------
4109
4110    function New_Class_Wide_Subtype
4111      (CW_Typ : Entity_Id;
4112       N      : Node_Id) return Entity_Id
4113    is
4114       Res       : constant Entity_Id := Create_Itype (E_Void, N);
4115       Res_Name  : constant Name_Id   := Chars (Res);
4116       Res_Scope : constant Entity_Id := Scope (Res);
4117
4118    begin
4119       Copy_Node (CW_Typ, Res);
4120       Set_Comes_From_Source (Res, False);
4121       Set_Sloc (Res, Sloc (N));
4122       Set_Is_Itype (Res);
4123       Set_Associated_Node_For_Itype (Res, N);
4124       Set_Is_Public (Res, False);   --  By default, may be changed below.
4125       Set_Public_Status (Res);
4126       Set_Chars (Res, Res_Name);
4127       Set_Scope (Res, Res_Scope);
4128       Set_Ekind (Res, E_Class_Wide_Subtype);
4129       Set_Next_Entity (Res, Empty);
4130       Set_Etype (Res, Base_Type (CW_Typ));
4131       Set_Is_Frozen (Res, False);
4132       Set_Freeze_Node (Res, Empty);
4133       return (Res);
4134    end New_Class_Wide_Subtype;
4135
4136    --------------------------------
4137    -- Non_Limited_Designated_Type --
4138    ---------------------------------
4139
4140    function Non_Limited_Designated_Type (T : Entity_Id) return Entity_Id is
4141       Desig : constant Entity_Id := Designated_Type (T);
4142    begin
4143       if Ekind (Desig) = E_Incomplete_Type
4144         and then Present (Non_Limited_View (Desig))
4145       then
4146          return Non_Limited_View (Desig);
4147       else
4148          return Desig;
4149       end if;
4150    end Non_Limited_Designated_Type;
4151
4152    -----------------------------------
4153    -- OK_To_Do_Constant_Replacement --
4154    -----------------------------------
4155
4156    function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean is
4157       ES : constant Entity_Id := Scope (E);
4158       CS : Entity_Id;
4159
4160    begin
4161       --  Do not replace statically allocated objects, because they may be
4162       --  modified outside the current scope.
4163
4164       if Is_Statically_Allocated (E) then
4165          return False;
4166
4167       --  Do not replace aliased or volatile objects, since we don't know what
4168       --  else might change the value.
4169
4170       elsif Is_Aliased (E) or else Treat_As_Volatile (E) then
4171          return False;
4172
4173       --  Debug flag -gnatdM disconnects this optimization
4174
4175       elsif Debug_Flag_MM then
4176          return False;
4177
4178       --  Otherwise check scopes
4179
4180       else
4181          CS := Current_Scope;
4182
4183          loop
4184             --  If we are in right scope, replacement is safe
4185
4186             if CS = ES then
4187                return True;
4188
4189             --  Packages do not affect the determination of safety
4190
4191             elsif Ekind (CS) = E_Package then
4192                exit when CS = Standard_Standard;
4193                CS := Scope (CS);
4194
4195             --  Blocks do not affect the determination of safety
4196
4197             elsif Ekind (CS) = E_Block then
4198                CS := Scope (CS);
4199
4200             --  Loops do not affect the determination of safety. Note that we
4201             --  kill all current values on entry to a loop, so we are just
4202             --  talking about processing within a loop here.
4203
4204             elsif Ekind (CS) = E_Loop then
4205                CS := Scope (CS);
4206
4207             --  Otherwise, the reference is dubious, and we cannot be sure that
4208             --  it is safe to do the replacement.
4209
4210             else
4211                exit;
4212             end if;
4213          end loop;
4214
4215          return False;
4216       end if;
4217    end OK_To_Do_Constant_Replacement;
4218
4219    ------------------------------------
4220    -- Possible_Bit_Aligned_Component --
4221    ------------------------------------
4222
4223    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is
4224    begin
4225       case Nkind (N) is
4226
4227          --  Case of indexed component
4228
4229          when N_Indexed_Component =>
4230             declare
4231                P    : constant Node_Id   := Prefix (N);
4232                Ptyp : constant Entity_Id := Etype (P);
4233
4234             begin
4235                --  If we know the component size and it is less than 64, then
4236                --  we are definitely OK. The back end always does assignment of
4237                --  misaligned small objects correctly.
4238
4239                if Known_Static_Component_Size (Ptyp)
4240                  and then Component_Size (Ptyp) <= 64
4241                then
4242                   return False;
4243
4244                --  Otherwise, we need to test the prefix, to see if we are
4245                --  indexing from a possibly unaligned component.
4246
4247                else
4248                   return Possible_Bit_Aligned_Component (P);
4249                end if;
4250             end;
4251
4252          --  Case of selected component
4253
4254          when N_Selected_Component =>
4255             declare
4256                P    : constant Node_Id   := Prefix (N);
4257                Comp : constant Entity_Id := Entity (Selector_Name (N));
4258
4259             begin
4260                --  If there is no component clause, then we are in the clear
4261                --  since the back end will never misalign a large component
4262                --  unless it is forced to do so. In the clear means we need
4263                --  only the recursive test on the prefix.
4264
4265                if Component_May_Be_Bit_Aligned (Comp) then
4266                   return True;
4267                else
4268                   return Possible_Bit_Aligned_Component (P);
4269                end if;
4270             end;
4271
4272          --  For a slice, test the prefix, if that is possibly misaligned,
4273          --  then for sure the slice is!
4274
4275          when N_Slice =>
4276             return Possible_Bit_Aligned_Component (Prefix (N));
4277
4278          --  If we have none of the above, it means that we have fallen off the
4279          --  top testing prefixes recursively, and we now have a stand alone
4280          --  object, where we don't have a problem.
4281
4282          when others =>
4283             return False;
4284
4285       end case;
4286    end Possible_Bit_Aligned_Component;
4287
4288    -------------------------
4289    -- Remove_Side_Effects --
4290    -------------------------
4291
4292    procedure Remove_Side_Effects
4293      (Exp          : Node_Id;
4294       Name_Req     : Boolean := False;
4295       Variable_Ref : Boolean := False)
4296    is
4297       Loc          : constant Source_Ptr     := Sloc (Exp);
4298       Exp_Type     : constant Entity_Id      := Etype (Exp);
4299       Svg_Suppress : constant Suppress_Array := Scope_Suppress;
4300       Def_Id       : Entity_Id;
4301       Ref_Type     : Entity_Id;
4302       Res          : Node_Id;
4303       Ptr_Typ_Decl : Node_Id;
4304       New_Exp      : Node_Id;
4305       E            : Node_Id;
4306
4307       function Side_Effect_Free (N : Node_Id) return Boolean;
4308       --  Determines if the tree N represents an expression that is known not
4309       --  to have side effects, and for which no processing is required.
4310
4311       function Side_Effect_Free (L : List_Id) return Boolean;
4312       --  Determines if all elements of the list L are side effect free
4313
4314       function Safe_Prefixed_Reference (N : Node_Id) return Boolean;
4315       --  The argument N is a construct where the Prefix is dereferenced if it
4316       --  is an access type and the result is a variable. The call returns True
4317       --  if the construct is side effect free (not considering side effects in
4318       --  other than the prefix which are to be tested by the caller).
4319
4320       function Within_In_Parameter (N : Node_Id) return Boolean;
4321       --  Determines if N is a subcomponent of a composite in-parameter. If so,
4322       --  N is not side-effect free when the actual is global and modifiable
4323       --  indirectly from within a subprogram, because it may be passed by
4324       --  reference. The front-end must be conservative here and assume that
4325       --  this may happen with any array or record type. On the other hand, we
4326       --  cannot create temporaries for all expressions for which this
4327       --  condition is true, for various reasons that might require clearing up
4328       --  ??? For example, discriminant references that appear out of place, or
4329       --  spurious type errors with class-wide expressions. As a result, we
4330       --  limit the transformation to loop bounds, which is so far the only
4331       --  case that requires it.
4332
4333       -----------------------------
4334       -- Safe_Prefixed_Reference --
4335       -----------------------------
4336
4337       function Safe_Prefixed_Reference (N : Node_Id) return Boolean is
4338       begin
4339          --  If prefix is not side effect free, definitely not safe
4340
4341          if not Side_Effect_Free (Prefix (N)) then
4342             return False;
4343
4344          --  If the prefix is of an access type that is not access-to-constant,
4345          --  then this construct is a variable reference, which means it is to
4346          --  be considered to have side effects if Variable_Ref is set True
4347          --  Exception is an access to an entity that is a constant or an
4348          --  in-parameter which does not come from source, and is the result
4349          --  of a previous removal of side-effects.
4350
4351          elsif Is_Access_Type (Etype (Prefix (N)))
4352            and then not Is_Access_Constant (Etype (Prefix (N)))
4353            and then Variable_Ref
4354          then
4355             if not Is_Entity_Name (Prefix (N)) then
4356                return False;
4357             else
4358                return Ekind (Entity (Prefix (N))) = E_Constant
4359                  or else Ekind (Entity (Prefix (N))) = E_In_Parameter;
4360             end if;
4361
4362          --  The following test is the simplest way of solving a complex
4363          --  problem uncovered by BB08-010: Side effect on loop bound that
4364          --  is a subcomponent of a global variable:
4365          --    If a loop bound is a subcomponent of a global variable, a
4366          --    modification of that variable within the loop may incorrectly
4367          --    affect the execution of the loop.
4368
4369          elsif not
4370            (Nkind (Parent (Parent (N))) /= N_Loop_Parameter_Specification
4371               or else not Within_In_Parameter (Prefix (N)))
4372          then
4373             return False;
4374
4375          --  All other cases are side effect free
4376
4377          else
4378             return True;
4379          end if;
4380       end Safe_Prefixed_Reference;
4381
4382       ----------------------
4383       -- Side_Effect_Free --
4384       ----------------------
4385
4386       function Side_Effect_Free (N : Node_Id) return Boolean is
4387       begin
4388          --  Note on checks that could raise Constraint_Error. Strictly, if
4389          --  we take advantage of 11.6, these checks do not count as side
4390          --  effects. However, we would just as soon consider that they are
4391          --  side effects, since the backend CSE does not work very well on
4392          --  expressions which can raise Constraint_Error. On the other
4393          --  hand, if we do not consider them to be side effect free, then
4394          --  we get some awkward expansions in -gnato mode, resulting in
4395          --  code insertions at a point where we do not have a clear model
4396          --  for performing the insertions.
4397
4398          --  Special handling for entity names
4399
4400          if Is_Entity_Name (N) then
4401
4402             --  If the entity is a constant, it is definitely side effect
4403             --  free. Note that the test of Is_Variable (N) below might
4404             --  be expected to catch this case, but it does not, because
4405             --  this test goes to the original tree, and we may have
4406             --  already rewritten a variable node with a constant as
4407             --  a result of an earlier Force_Evaluation call.
4408
4409             if Ekind (Entity (N)) = E_Constant
4410               or else Ekind (Entity (N)) = E_In_Parameter
4411             then
4412                return True;
4413
4414             --  Functions are not side effect free
4415
4416             elsif Ekind (Entity (N)) = E_Function then
4417                return False;
4418
4419             --  Variables are considered to be a side effect if Variable_Ref
4420             --  is set or if we have a volatile reference and Name_Req is off.
4421             --  If Name_Req is True then we can't help returning a name which
4422             --  effectively allows multiple references in any case.
4423
4424             elsif Is_Variable (N) then
4425                return not Variable_Ref
4426                  and then (not Is_Volatile_Reference (N) or else Name_Req);
4427
4428             --  Any other entity (e.g. a subtype name) is definitely side
4429             --  effect free.
4430
4431             else
4432                return True;
4433             end if;
4434
4435          --  A value known at compile time is always side effect free
4436
4437          elsif Compile_Time_Known_Value (N) then
4438             return True;
4439
4440          --  A variable renaming is not side-effect free, because the
4441          --  renaming will function like a macro in the front-end in
4442          --  some cases, and an assignment can modify the component
4443          --  designated by N, so we need to create a temporary for it.
4444
4445          elsif Is_Entity_Name (Original_Node (N))
4446            and then Is_Renaming_Of_Object (Entity (Original_Node (N)))
4447            and then Ekind (Entity (Original_Node (N))) /= E_Constant
4448          then
4449             return False;
4450          end if;
4451
4452          --  For other than entity names and compile time known values,
4453          --  check the node kind for special processing.
4454
4455          case Nkind (N) is
4456
4457             --  An attribute reference is side effect free if its expressions
4458             --  are side effect free and its prefix is side effect free or
4459             --  is an entity reference.
4460
4461             --  Is this right? what about x'first where x is a variable???
4462
4463             when N_Attribute_Reference =>
4464                return Side_Effect_Free (Expressions (N))
4465                  and then Attribute_Name (N) /= Name_Input
4466                  and then (Is_Entity_Name (Prefix (N))
4467                             or else Side_Effect_Free (Prefix (N)));
4468
4469             --  A binary operator is side effect free if and both operands
4470             --  are side effect free. For this purpose binary operators
4471             --  include membership tests and short circuit forms
4472
4473             when N_Binary_Op | N_Membership_Test | N_Short_Circuit =>
4474                return Side_Effect_Free (Left_Opnd  (N))
4475                         and then
4476                       Side_Effect_Free (Right_Opnd (N));
4477
4478             --  An explicit dereference is side effect free only if it is
4479             --  a side effect free prefixed reference.
4480
4481             when N_Explicit_Dereference =>
4482                return Safe_Prefixed_Reference (N);
4483
4484             --  A call to _rep_to_pos is side effect free, since we generate
4485             --  this pure function call ourselves. Moreover it is critically
4486             --  important to make this exception, since otherwise we can
4487             --  have discriminants in array components which don't look
4488             --  side effect free in the case of an array whose index type
4489             --  is an enumeration type with an enumeration rep clause.
4490
4491             --  All other function calls are not side effect free
4492
4493             when N_Function_Call =>
4494                return Nkind (Name (N)) = N_Identifier
4495                  and then Is_TSS (Name (N), TSS_Rep_To_Pos)
4496                  and then
4497                    Side_Effect_Free (First (Parameter_Associations (N)));
4498
4499             --  An indexed component is side effect free if it is a side
4500             --  effect free prefixed reference and all the indexing
4501             --  expressions are side effect free.
4502
4503             when N_Indexed_Component =>
4504                return Side_Effect_Free (Expressions (N))
4505                  and then Safe_Prefixed_Reference (N);
4506
4507             --  A type qualification is side effect free if the expression
4508             --  is side effect free.
4509
4510             when N_Qualified_Expression =>
4511                return Side_Effect_Free (Expression (N));
4512
4513             --  A selected component is side effect free only if it is a
4514             --  side effect free prefixed reference. If it designates a
4515             --  component with a rep. clause it must be treated has having
4516             --  a potential side effect, because it may be modified through
4517             --  a renaming, and a subsequent use of the renaming as a macro
4518             --  will yield the wrong value. This complex interaction between
4519             --  renaming and removing side effects is a reminder that the
4520             --  latter has become a headache to maintain, and that it should
4521             --  be removed in favor of the gcc mechanism to capture values ???
4522
4523             when N_Selected_Component =>
4524                if Nkind (Parent (N)) = N_Explicit_Dereference
4525                  and then Has_Non_Standard_Rep (Designated_Type (Etype (N)))
4526                then
4527                   return False;
4528                else
4529                   return Safe_Prefixed_Reference (N);
4530                end if;
4531
4532             --  A range is side effect free if the bounds are side effect free
4533
4534             when N_Range =>
4535                return Side_Effect_Free (Low_Bound (N))
4536                  and then Side_Effect_Free (High_Bound (N));
4537
4538             --  A slice is side effect free if it is a side effect free
4539             --  prefixed reference and the bounds are side effect free.
4540
4541             when N_Slice =>
4542                return Side_Effect_Free (Discrete_Range (N))
4543                  and then Safe_Prefixed_Reference (N);
4544
4545             --  A type conversion is side effect free if the expression to be
4546             --  converted is side effect free.
4547
4548             when N_Type_Conversion =>
4549                return Side_Effect_Free (Expression (N));
4550
4551             --  A unary operator is side effect free if the operand
4552             --  is side effect free.
4553
4554             when N_Unary_Op =>
4555                return Side_Effect_Free (Right_Opnd (N));
4556
4557             --  An unchecked type conversion is side effect free only if it
4558             --  is safe and its argument is side effect free.
4559
4560             when N_Unchecked_Type_Conversion =>
4561                return Safe_Unchecked_Type_Conversion (N)
4562                  and then Side_Effect_Free (Expression (N));
4563
4564             --  An unchecked expression is side effect free if its expression
4565             --  is side effect free.
4566
4567             when N_Unchecked_Expression =>
4568                return Side_Effect_Free (Expression (N));
4569
4570             --  A literal is side effect free
4571
4572             when N_Character_Literal    |
4573                  N_Integer_Literal      |
4574                  N_Real_Literal         |
4575                  N_String_Literal       =>
4576                return True;
4577
4578             --  We consider that anything else has side effects. This is a bit
4579             --  crude, but we are pretty close for most common cases, and we
4580             --  are certainly correct (i.e. we never return True when the
4581             --  answer should be False).
4582
4583             when others =>
4584                return False;
4585          end case;
4586       end Side_Effect_Free;
4587
4588       --  A list is side effect free if all elements of the list are
4589       --  side effect free.
4590
4591       function Side_Effect_Free (L : List_Id) return Boolean is
4592          N : Node_Id;
4593
4594       begin
4595          if L = No_List or else L = Error_List then
4596             return True;
4597
4598          else
4599             N := First (L);
4600             while Present (N) loop
4601                if not Side_Effect_Free (N) then
4602                   return False;
4603                else
4604                   Next (N);
4605                end if;
4606             end loop;
4607
4608             return True;
4609          end if;
4610       end Side_Effect_Free;
4611
4612       -------------------------
4613       -- Within_In_Parameter --
4614       -------------------------
4615
4616       function Within_In_Parameter (N : Node_Id) return Boolean is
4617       begin
4618          if not Comes_From_Source (N) then
4619             return False;
4620
4621          elsif Is_Entity_Name (N) then
4622             return Ekind (Entity (N)) = E_In_Parameter;
4623
4624          elsif Nkind (N) = N_Indexed_Component
4625            or else Nkind (N) = N_Selected_Component
4626          then
4627             return Within_In_Parameter (Prefix (N));
4628          else
4629
4630             return False;
4631          end if;
4632       end Within_In_Parameter;
4633
4634    --  Start of processing for Remove_Side_Effects
4635
4636    begin
4637       --  If we are side effect free already or expansion is disabled,
4638       --  there is nothing to do.
4639
4640       if Side_Effect_Free (Exp) or else not Expander_Active then
4641          return;
4642       end if;
4643
4644       --  All this must not have any checks
4645
4646       Scope_Suppress := (others => True);
4647
4648       --  If it is a scalar type and we need to capture the value, just make
4649       --  a copy. Likewise for a function call, an attribute reference or an
4650       --  operator. And if we have a volatile reference and Name_Req is not
4651       --  set (see comments above for Side_Effect_Free).
4652
4653       if Is_Elementary_Type (Exp_Type)
4654         and then (Variable_Ref
4655                    or else Nkind (Exp) = N_Function_Call
4656                    or else Nkind (Exp) = N_Attribute_Reference
4657                    or else Nkind (Exp) in N_Op
4658                    or else (not Name_Req and then Is_Volatile_Reference (Exp)))
4659       then
4660          Def_Id := Make_Temporary (Loc, 'R', Exp);
4661          Set_Etype (Def_Id, Exp_Type);
4662          Res := New_Reference_To (Def_Id, Loc);
4663
4664          E :=
4665            Make_Object_Declaration (Loc,
4666              Defining_Identifier => Def_Id,
4667              Object_Definition   => New_Reference_To (Exp_Type, Loc),
4668              Constant_Present    => True,
4669              Expression          => Relocate_Node (Exp));
4670
4671          --  Check if the previous node relocation requires readjustment of
4672          --  some SCIL Dispatching node.
4673
4674          if Generate_SCIL
4675            and then Nkind (Exp) = N_Function_Call
4676          then
4677             Adjust_SCIL_Node (Exp, Expression (E));
4678          end if;
4679
4680          Set_Assignment_OK (E);
4681          Insert_Action (Exp, E);
4682
4683       --  If the expression has the form v.all then we can just capture
4684       --  the pointer, and then do an explicit dereference on the result.
4685
4686       elsif Nkind (Exp) = N_Explicit_Dereference then
4687          Def_Id := Make_Temporary (Loc, 'R', Exp);
4688          Res :=
4689            Make_Explicit_Dereference (Loc, New_Reference_To (Def_Id, Loc));
4690
4691          Insert_Action (Exp,
4692            Make_Object_Declaration (Loc,
4693              Defining_Identifier => Def_Id,
4694              Object_Definition   =>
4695                New_Reference_To (Etype (Prefix (Exp)), Loc),
4696              Constant_Present    => True,
4697              Expression          => Relocate_Node (Prefix (Exp))));
4698
4699       --  Similar processing for an unchecked conversion of an expression
4700       --  of the form v.all, where we want the same kind of treatment.
4701
4702       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4703         and then Nkind (Expression (Exp)) = N_Explicit_Dereference
4704       then
4705          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4706          Scope_Suppress := Svg_Suppress;
4707          return;
4708
4709       --  If this is a type conversion, leave the type conversion and remove
4710       --  the side effects in the expression. This is important in several
4711       --  circumstances: for change of representations, and also when this is
4712       --  a view conversion to a smaller object, where gigi can end up creating
4713       --  its own temporary of the wrong size.
4714
4715       elsif Nkind (Exp) = N_Type_Conversion then
4716          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4717          Scope_Suppress := Svg_Suppress;
4718          return;
4719
4720       --  If this is an unchecked conversion that Gigi can't handle, make
4721       --  a copy or a use a renaming to capture the value.
4722
4723       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4724         and then not Safe_Unchecked_Type_Conversion (Exp)
4725       then
4726          if CW_Or_Has_Controlled_Part (Exp_Type) then
4727
4728             --  Use a renaming to capture the expression, rather than create
4729             --  a controlled temporary.
4730
4731             Def_Id := Make_Temporary (Loc, 'R', Exp);
4732             Res := New_Reference_To (Def_Id, Loc);
4733
4734             Insert_Action (Exp,
4735               Make_Object_Renaming_Declaration (Loc,
4736                 Defining_Identifier => Def_Id,
4737                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4738                 Name                => Relocate_Node (Exp)));
4739
4740          else
4741             Def_Id := Make_Temporary (Loc, 'R', Exp);
4742             Set_Etype (Def_Id, Exp_Type);
4743             Res := New_Reference_To (Def_Id, Loc);
4744
4745             E :=
4746               Make_Object_Declaration (Loc,
4747                 Defining_Identifier => Def_Id,
4748                 Object_Definition   => New_Reference_To (Exp_Type, Loc),
4749                 Constant_Present    => not Is_Variable (Exp),
4750                 Expression          => Relocate_Node (Exp));
4751
4752             Set_Assignment_OK (E);
4753             Insert_Action (Exp, E);
4754          end if;
4755
4756       --  For expressions that denote objects, we can use a renaming scheme.
4757       --  We skip using this if we have a volatile reference and we do not
4758       --  have Name_Req set true (see comments above for Side_Effect_Free).
4759
4760       elsif Is_Object_Reference (Exp)
4761         and then Nkind (Exp) /= N_Function_Call
4762         and then (Name_Req or else not Is_Volatile_Reference (Exp))
4763       then
4764          Def_Id := Make_Temporary (Loc, 'R', Exp);
4765
4766          if Nkind (Exp) = N_Selected_Component
4767            and then Nkind (Prefix (Exp)) = N_Function_Call
4768            and then Is_Array_Type (Exp_Type)
4769          then
4770             --  Avoid generating a variable-sized temporary, by generating
4771             --  the renaming declaration just for the function call. The
4772             --  transformation could be refined to apply only when the array
4773             --  component is constrained by a discriminant???
4774
4775             Res :=
4776               Make_Selected_Component (Loc,
4777                 Prefix => New_Occurrence_Of (Def_Id, Loc),
4778                 Selector_Name => Selector_Name (Exp));
4779
4780             Insert_Action (Exp,
4781               Make_Object_Renaming_Declaration (Loc,
4782                 Defining_Identifier => Def_Id,
4783                 Subtype_Mark        =>
4784                   New_Reference_To (Base_Type (Etype (Prefix (Exp))), Loc),
4785                 Name                => Relocate_Node (Prefix (Exp))));
4786
4787          else
4788             Res := New_Reference_To (Def_Id, Loc);
4789
4790             Insert_Action (Exp,
4791               Make_Object_Renaming_Declaration (Loc,
4792                 Defining_Identifier => Def_Id,
4793                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4794                 Name                => Relocate_Node (Exp)));
4795          end if;
4796
4797          --  If this is a packed reference, or a selected component with a
4798          --  non-standard representation, a reference to the temporary will
4799          --  be replaced by a copy of the original expression (see
4800          --  Exp_Ch2.Expand_Renaming). Otherwise the temporary must be
4801          --  elaborated by gigi, and is of course not to be replaced in-line
4802          --  by the expression it renames, which would defeat the purpose of
4803          --  removing the side-effect.
4804
4805          if (Nkind (Exp) = N_Selected_Component
4806               or else Nkind (Exp) = N_Indexed_Component)
4807            and then Has_Non_Standard_Rep (Etype (Prefix (Exp)))
4808          then
4809             null;
4810          else
4811             Set_Is_Renaming_Of_Object (Def_Id, False);
4812          end if;
4813
4814       --  Otherwise we generate a reference to the value
4815
4816       else
4817          --  Special processing for function calls that return a limited type.
4818          --  We need to build a declaration that will enable build-in-place
4819          --  expansion of the call. This is not done if the context is already
4820          --  an object declaration, to prevent infinite recursion.
4821
4822          --  This is relevant only in Ada 2005 mode. In Ada 95 programs we have
4823          --  to accommodate functions returning limited objects by reference.
4824
4825          if Nkind (Exp) = N_Function_Call
4826            and then Is_Inherently_Limited_Type (Etype (Exp))
4827            and then Nkind (Parent (Exp)) /= N_Object_Declaration
4828            and then Ada_Version >= Ada_05
4829          then
4830             declare
4831                Obj  : constant Entity_Id := Make_Temporary (Loc, 'F', Exp);
4832                Decl : Node_Id;
4833
4834             begin
4835                Decl :=
4836                  Make_Object_Declaration (Loc,
4837                    Defining_Identifier => Obj,
4838                    Object_Definition   => New_Occurrence_Of (Exp_Type, Loc),
4839                    Expression          => Relocate_Node (Exp));
4840
4841                --  Check if the previous node relocation requires readjustment
4842                --  of some SCIL Dispatching node.
4843
4844                if Generate_SCIL
4845                  and then Nkind (Exp) = N_Function_Call
4846                then
4847                   Adjust_SCIL_Node (Exp, Expression (Decl));
4848                end if;
4849
4850                Insert_Action (Exp, Decl);
4851                Set_Etype (Obj, Exp_Type);
4852                Rewrite (Exp, New_Occurrence_Of (Obj, Loc));
4853                return;
4854             end;
4855          end if;
4856
4857          Ref_Type := Make_Temporary (Loc, 'A');
4858
4859          Ptr_Typ_Decl :=
4860            Make_Full_Type_Declaration (Loc,
4861              Defining_Identifier => Ref_Type,
4862              Type_Definition =>
4863                Make_Access_To_Object_Definition (Loc,
4864                  All_Present => True,
4865                  Subtype_Indication =>
4866                    New_Reference_To (Exp_Type, Loc)));
4867
4868          E := Exp;
4869          Insert_Action (Exp, Ptr_Typ_Decl);
4870
4871          Def_Id := Make_Temporary (Loc, 'R', Exp);
4872          Set_Etype (Def_Id, Exp_Type);
4873
4874          Res :=
4875            Make_Explicit_Dereference (Loc,
4876              Prefix => New_Reference_To (Def_Id, Loc));
4877
4878          if Nkind (E) = N_Explicit_Dereference then
4879             New_Exp := Relocate_Node (Prefix (E));
4880          else
4881             E := Relocate_Node (E);
4882             New_Exp := Make_Reference (Loc, E);
4883          end if;
4884
4885          if Is_Delayed_Aggregate (E) then
4886
4887             --  The expansion of nested aggregates is delayed until the
4888             --  enclosing aggregate is expanded. As aggregates are often
4889             --  qualified, the predicate applies to qualified expressions
4890             --  as well, indicating that the enclosing aggregate has not
4891             --  been expanded yet. At this point the aggregate is part of
4892             --  a stand-alone declaration, and must be fully expanded.
4893
4894             if Nkind (E) = N_Qualified_Expression then
4895                Set_Expansion_Delayed (Expression (E), False);
4896                Set_Analyzed (Expression (E), False);
4897             else
4898                Set_Expansion_Delayed (E, False);
4899             end if;
4900
4901             Set_Analyzed (E, False);
4902          end if;
4903
4904          Insert_Action (Exp,
4905            Make_Object_Declaration (Loc,
4906              Defining_Identifier => Def_Id,
4907              Object_Definition   => New_Reference_To (Ref_Type, Loc),
4908              Expression          => New_Exp));
4909
4910          --  Check if the previous node relocation requires readjustment
4911          --  of some SCIL Dispatching node.
4912
4913          if Generate_SCIL
4914            and then Nkind (Exp) = N_Function_Call
4915          then
4916             Adjust_SCIL_Node (Exp, Prefix (New_Exp));
4917          end if;
4918       end if;
4919
4920       --  Preserve the Assignment_OK flag in all copies, since at least
4921       --  one copy may be used in a context where this flag must be set
4922       --  (otherwise why would the flag be set in the first place).
4923
4924       Set_Assignment_OK (Res, Assignment_OK (Exp));
4925
4926       --  Finally rewrite the original expression and we are done
4927
4928       Rewrite (Exp, Res);
4929       Analyze_And_Resolve (Exp, Exp_Type);
4930       Scope_Suppress := Svg_Suppress;
4931    end Remove_Side_Effects;
4932
4933    ---------------------------
4934    -- Represented_As_Scalar --
4935    ---------------------------
4936
4937    function Represented_As_Scalar (T : Entity_Id) return Boolean is
4938       UT : constant Entity_Id := Underlying_Type (T);
4939    begin
4940       return Is_Scalar_Type (UT)
4941         or else (Is_Bit_Packed_Array (UT)
4942                    and then Is_Scalar_Type (Packed_Array_Type (UT)));
4943    end Represented_As_Scalar;
4944
4945    ------------------------------------
4946    -- Safe_Unchecked_Type_Conversion --
4947    ------------------------------------
4948
4949    --  Note: this function knows quite a bit about the exact requirements
4950    --  of Gigi with respect to unchecked type conversions, and its code
4951    --  must be coordinated with any changes in Gigi in this area.
4952
4953    --  The above requirements should be documented in Sinfo ???
4954
4955    function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean is
4956       Otyp   : Entity_Id;
4957       Ityp   : Entity_Id;
4958       Oalign : Uint;
4959       Ialign : Uint;
4960       Pexp   : constant Node_Id := Parent (Exp);
4961
4962    begin
4963       --  If the expression is the RHS of an assignment or object declaration
4964       --   we are always OK because there will always be a target.
4965
4966       --  Object renaming declarations, (generated for view conversions of
4967       --  actuals in inlined calls), like object declarations, provide an
4968       --  explicit type, and are safe as well.
4969
4970       if (Nkind (Pexp) = N_Assignment_Statement
4971            and then Expression (Pexp) = Exp)
4972         or else Nkind (Pexp) = N_Object_Declaration
4973         or else Nkind (Pexp) = N_Object_Renaming_Declaration
4974       then
4975          return True;
4976
4977       --  If the expression is the prefix of an N_Selected_Component
4978       --  we should also be OK because GCC knows to look inside the
4979       --  conversion except if the type is discriminated. We assume
4980       --  that we are OK anyway if the type is not set yet or if it is
4981       --  controlled since we can't afford to introduce a temporary in
4982       --  this case.
4983
4984       elsif Nkind (Pexp) = N_Selected_Component
4985          and then Prefix (Pexp) = Exp
4986       then
4987          if No (Etype (Pexp)) then
4988             return True;
4989          else
4990             return
4991               not Has_Discriminants (Etype (Pexp))
4992                 or else Is_Constrained (Etype (Pexp));
4993          end if;
4994       end if;
4995
4996       --  Set the output type, this comes from Etype if it is set, otherwise
4997       --  we take it from the subtype mark, which we assume was already
4998       --  fully analyzed.
4999
5000       if Present (Etype (Exp)) then
5001          Otyp := Etype (Exp);
5002       else
5003          Otyp := Entity (Subtype_Mark (Exp));
5004       end if;
5005
5006       --  The input type always comes from the expression, and we assume
5007       --  this is indeed always analyzed, so we can simply get the Etype.
5008
5009       Ityp := Etype (Expression (Exp));
5010
5011       --  Initialize alignments to unknown so far
5012
5013       Oalign := No_Uint;
5014       Ialign := No_Uint;
5015
5016       --  Replace a concurrent type by its corresponding record type
5017       --  and each type by its underlying type and do the tests on those.
5018       --  The original type may be a private type whose completion is a
5019       --  concurrent type, so find the underlying type first.
5020
5021       if Present (Underlying_Type (Otyp)) then
5022          Otyp := Underlying_Type (Otyp);
5023       end if;
5024
5025       if Present (Underlying_Type (Ityp)) then
5026          Ityp := Underlying_Type (Ityp);
5027       end if;
5028
5029       if Is_Concurrent_Type (Otyp) then
5030          Otyp := Corresponding_Record_Type (Otyp);
5031       end if;
5032
5033       if Is_Concurrent_Type (Ityp) then
5034          Ityp := Corresponding_Record_Type (Ityp);
5035       end if;
5036
5037       --  If the base types are the same, we know there is no problem since
5038       --  this conversion will be a noop.
5039
5040       if Implementation_Base_Type (Otyp) = Implementation_Base_Type (Ityp) then
5041          return True;
5042
5043       --  Same if this is an upwards conversion of an untagged type, and there
5044       --  are no constraints involved (could be more general???)
5045
5046       elsif Etype (Ityp) = Otyp
5047         and then not Is_Tagged_Type (Ityp)
5048         and then not Has_Discriminants (Ityp)
5049         and then No (First_Rep_Item (Base_Type (Ityp)))
5050       then
5051          return True;
5052
5053       --  If the expression has an access type (object or subprogram) we
5054       --  assume that the conversion is safe, because the size of the target
5055       --  is safe, even if it is a record (which might be treated as having
5056       --  unknown size at this point).
5057
5058       elsif Is_Access_Type (Ityp) then
5059          return True;
5060
5061       --  If the size of output type is known at compile time, there is
5062       --  never a problem.  Note that unconstrained records are considered
5063       --  to be of known size, but we can't consider them that way here,
5064       --  because we are talking about the actual size of the object.
5065
5066       --  We also make sure that in addition to the size being known, we do
5067       --  not have a case which might generate an embarrassingly large temp
5068       --  in stack checking mode.
5069
5070       elsif Size_Known_At_Compile_Time (Otyp)
5071         and then
5072           (not Stack_Checking_Enabled
5073              or else not May_Generate_Large_Temp (Otyp))
5074         and then not (Is_Record_Type (Otyp) and then not Is_Constrained (Otyp))
5075       then
5076          return True;
5077
5078       --  If either type is tagged, then we know the alignment is OK so
5079       --  Gigi will be able to use pointer punning.
5080
5081       elsif Is_Tagged_Type (Otyp) or else Is_Tagged_Type (Ityp) then
5082          return True;
5083
5084       --  If either type is a limited record type, we cannot do a copy, so
5085       --  say safe since there's nothing else we can do.
5086
5087       elsif Is_Limited_Record (Otyp) or else Is_Limited_Record (Ityp) then
5088          return True;
5089
5090       --  Conversions to and from packed array types are always ignored and
5091       --  hence are safe.
5092
5093       elsif Is_Packed_Array_Type (Otyp)
5094         or else Is_Packed_Array_Type (Ityp)
5095       then
5096          return True;
5097       end if;
5098
5099       --  The only other cases known to be safe is if the input type's
5100       --  alignment is known to be at least the maximum alignment for the
5101       --  target or if both alignments are known and the output type's
5102       --  alignment is no stricter than the input's.  We can use the alignment
5103       --  of the component type of an array if a type is an unpacked
5104       --  array type.
5105
5106       if Present (Alignment_Clause (Otyp)) then
5107          Oalign := Expr_Value (Expression (Alignment_Clause (Otyp)));
5108
5109       elsif Is_Array_Type (Otyp)
5110         and then Present (Alignment_Clause (Component_Type (Otyp)))
5111       then
5112          Oalign := Expr_Value (Expression (Alignment_Clause
5113                                            (Component_Type (Otyp))));
5114       end if;
5115
5116       if Present (Alignment_Clause (Ityp)) then
5117          Ialign := Expr_Value (Expression (Alignment_Clause (Ityp)));
5118
5119       elsif Is_Array_Type (Ityp)
5120         and then Present (Alignment_Clause (Component_Type (Ityp)))
5121       then
5122          Ialign := Expr_Value (Expression (Alignment_Clause
5123                                            (Component_Type (Ityp))));
5124       end if;
5125
5126       if Ialign /= No_Uint and then Ialign > Maximum_Alignment then
5127          return True;
5128
5129       elsif Ialign /= No_Uint and then Oalign /= No_Uint
5130         and then Ialign <= Oalign
5131       then
5132          return True;
5133
5134       --   Otherwise, Gigi cannot handle this and we must make a temporary
5135
5136       else
5137          return False;
5138       end if;
5139    end Safe_Unchecked_Type_Conversion;
5140
5141    ---------------------------------
5142    -- Set_Current_Value_Condition --
5143    ---------------------------------
5144
5145    --  Note: the implementation of this procedure is very closely tied to the
5146    --  implementation of Get_Current_Value_Condition. Here we set required
5147    --  Current_Value fields, and in Get_Current_Value_Condition, we interpret
5148    --  them, so they must have a consistent view.
5149
5150    procedure Set_Current_Value_Condition (Cnode : Node_Id) is
5151
5152       procedure Set_Entity_Current_Value (N : Node_Id);
5153       --  If N is an entity reference, where the entity is of an appropriate
5154       --  kind, then set the current value of this entity to Cnode, unless
5155       --  there is already a definite value set there.
5156
5157       procedure Set_Expression_Current_Value (N : Node_Id);
5158       --  If N is of an appropriate form, sets an appropriate entry in current
5159       --  value fields of relevant entities. Multiple entities can be affected
5160       --  in the case of an AND or AND THEN.
5161
5162       ------------------------------
5163       -- Set_Entity_Current_Value --
5164       ------------------------------
5165
5166       procedure Set_Entity_Current_Value (N : Node_Id) is
5167       begin
5168          if Is_Entity_Name (N) then
5169             declare
5170                Ent : constant Entity_Id := Entity (N);
5171
5172             begin
5173                --  Don't capture if not safe to do so
5174
5175                if not Safe_To_Capture_Value (N, Ent, Cond => True) then
5176                   return;
5177                end if;
5178
5179                --  Here we have a case where the Current_Value field may
5180                --  need to be set. We set it if it is not already set to a
5181                --  compile time expression value.
5182
5183                --  Note that this represents a decision that one condition
5184                --  blots out another previous one. That's certainly right
5185                --  if they occur at the same level. If the second one is
5186                --  nested, then the decision is neither right nor wrong (it
5187                --  would be equally OK to leave the outer one in place, or
5188                --  take the new inner one. Really we should record both, but
5189                --  our data structures are not that elaborate.
5190
5191                if Nkind (Current_Value (Ent)) not in N_Subexpr then
5192                   Set_Current_Value (Ent, Cnode);
5193                end if;
5194             end;
5195          end if;
5196       end Set_Entity_Current_Value;
5197
5198       ----------------------------------
5199       -- Set_Expression_Current_Value --
5200       ----------------------------------
5201
5202       procedure Set_Expression_Current_Value (N : Node_Id) is
5203          Cond : Node_Id;
5204
5205       begin
5206          Cond := N;
5207
5208          --  Loop to deal with (ignore for now) any NOT operators present. The
5209          --  presence of NOT operators will be handled properly when we call
5210          --  Get_Current_Value_Condition.
5211
5212          while Nkind (Cond) = N_Op_Not loop
5213             Cond := Right_Opnd (Cond);
5214          end loop;
5215
5216          --  For an AND or AND THEN, recursively process operands
5217
5218          if Nkind (Cond) = N_Op_And or else Nkind (Cond) = N_And_Then then
5219             Set_Expression_Current_Value (Left_Opnd (Cond));
5220             Set_Expression_Current_Value (Right_Opnd (Cond));
5221             return;
5222          end if;
5223
5224          --  Check possible relational operator
5225
5226          if Nkind (Cond) in N_Op_Compare then
5227             if Compile_Time_Known_Value (Right_Opnd (Cond)) then
5228                Set_Entity_Current_Value (Left_Opnd (Cond));
5229             elsif Compile_Time_Known_Value (Left_Opnd (Cond)) then
5230                Set_Entity_Current_Value (Right_Opnd (Cond));
5231             end if;
5232
5233             --  Check possible boolean variable reference
5234
5235          else
5236             Set_Entity_Current_Value (Cond);
5237          end if;
5238       end Set_Expression_Current_Value;
5239
5240    --  Start of processing for Set_Current_Value_Condition
5241
5242    begin
5243       Set_Expression_Current_Value (Condition (Cnode));
5244    end Set_Current_Value_Condition;
5245
5246    --------------------------
5247    -- Set_Elaboration_Flag --
5248    --------------------------
5249
5250    procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id) is
5251       Loc : constant Source_Ptr := Sloc (N);
5252       Ent : constant Entity_Id  := Elaboration_Entity (Spec_Id);
5253       Asn : Node_Id;
5254
5255    begin
5256       if Present (Ent) then
5257
5258          --  Nothing to do if at the compilation unit level, because in this
5259          --  case the flag is set by the binder generated elaboration routine.
5260
5261          if Nkind (Parent (N)) = N_Compilation_Unit then
5262             null;
5263
5264          --  Here we do need to generate an assignment statement
5265
5266          else
5267             Check_Restriction (No_Elaboration_Code, N);
5268             Asn :=
5269               Make_Assignment_Statement (Loc,
5270                 Name       => New_Occurrence_Of (Ent, Loc),
5271                 Expression => New_Occurrence_Of (Standard_True, Loc));
5272
5273             if Nkind (Parent (N)) = N_Subunit then
5274                Insert_After (Corresponding_Stub (Parent (N)), Asn);
5275             else
5276                Insert_After (N, Asn);
5277             end if;
5278
5279             Analyze (Asn);
5280
5281             --  Kill current value indication. This is necessary because the
5282             --  tests of this flag are inserted out of sequence and must not
5283             --  pick up bogus indications of the wrong constant value.
5284
5285             Set_Current_Value (Ent, Empty);
5286          end if;
5287       end if;
5288    end Set_Elaboration_Flag;
5289
5290    ----------------------------
5291    -- Set_Renamed_Subprogram --
5292    ----------------------------
5293
5294    procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id) is
5295    begin
5296       --  If input node is an identifier, we can just reset it
5297
5298       if Nkind (N) = N_Identifier then
5299          Set_Chars  (N, Chars (E));
5300          Set_Entity (N, E);
5301
5302          --  Otherwise we have to do a rewrite, preserving Comes_From_Source
5303
5304       else
5305          declare
5306             CS : constant Boolean := Comes_From_Source (N);
5307          begin
5308             Rewrite (N, Make_Identifier (Sloc (N), Chars => Chars (E)));
5309             Set_Entity (N, E);
5310             Set_Comes_From_Source (N, CS);
5311             Set_Analyzed (N, True);
5312          end;
5313       end if;
5314    end Set_Renamed_Subprogram;
5315
5316    ----------------------------------
5317    -- Silly_Boolean_Array_Not_Test --
5318    ----------------------------------
5319
5320    --  This procedure implements an odd and silly test. We explicitly check
5321    --  for the case where the 'First of the component type is equal to the
5322    --  'Last of this component type, and if this is the case, we make sure
5323    --  that constraint error is raised. The reason is that the NOT is bound
5324    --  to cause CE in this case, and we will not otherwise catch it.
5325
5326    --  No such check is required for AND and OR, since for both these cases
5327    --  False op False = False, and True op True = True. For the XOR case,
5328    --  see Silly_Boolean_Array_Xor_Test.
5329
5330    --  Believe it or not, this was reported as a bug. Note that nearly
5331    --  always, the test will evaluate statically to False, so the code will
5332    --  be statically removed, and no extra overhead caused.
5333
5334    procedure Silly_Boolean_Array_Not_Test (N : Node_Id; T : Entity_Id) is
5335       Loc : constant Source_Ptr := Sloc (N);
5336       CT  : constant Entity_Id  := Component_Type (T);
5337
5338    begin
5339       --  The check we install is
5340
5341       --    constraint_error when
5342       --      component_type'first = component_type'last
5343       --        and then array_type'Length /= 0)
5344
5345       --  We need the last guard because we don't want to raise CE for empty
5346       --  arrays since no out of range values result. (Empty arrays with a
5347       --  component type of True .. True -- very useful -- even the ACATS
5348       --  does not test that marginal case!)
5349
5350       Insert_Action (N,
5351         Make_Raise_Constraint_Error (Loc,
5352           Condition =>
5353             Make_And_Then (Loc,
5354               Left_Opnd =>
5355                 Make_Op_Eq (Loc,
5356                   Left_Opnd =>
5357                     Make_Attribute_Reference (Loc,
5358                       Prefix         => New_Occurrence_Of (CT, Loc),
5359                       Attribute_Name => Name_First),
5360
5361                   Right_Opnd =>
5362                     Make_Attribute_Reference (Loc,
5363                       Prefix         => New_Occurrence_Of (CT, Loc),
5364                       Attribute_Name => Name_Last)),
5365
5366               Right_Opnd => Make_Non_Empty_Check (Loc, Right_Opnd (N))),
5367           Reason => CE_Range_Check_Failed));
5368    end Silly_Boolean_Array_Not_Test;
5369
5370    ----------------------------------
5371    -- Silly_Boolean_Array_Xor_Test --
5372    ----------------------------------
5373
5374    --  This procedure implements an odd and silly test. We explicitly check
5375    --  for the XOR case where the component type is True .. True, since this
5376    --  will raise constraint error. A special check is required since CE
5377    --  will not be generated otherwise (cf Expand_Packed_Not).
5378
5379    --  No such check is required for AND and OR, since for both these cases
5380    --  False op False = False, and True op True = True, and no check is
5381    --  required for the case of False .. False, since False xor False = False.
5382    --  See also Silly_Boolean_Array_Not_Test
5383
5384    procedure Silly_Boolean_Array_Xor_Test (N : Node_Id; T : Entity_Id) is
5385       Loc : constant Source_Ptr := Sloc (N);
5386       CT  : constant Entity_Id  := Component_Type (T);
5387
5388    begin
5389       --  The check we install is
5390
5391       --    constraint_error when
5392       --      Boolean (component_type'First)
5393       --        and then Boolean (component_type'Last)
5394       --        and then array_type'Length /= 0)
5395
5396       --  We need the last guard because we don't want to raise CE for empty
5397       --  arrays since no out of range values result (Empty arrays with a
5398       --  component type of True .. True -- very useful -- even the ACATS
5399       --  does not test that marginal case!).
5400
5401       Insert_Action (N,
5402         Make_Raise_Constraint_Error (Loc,
5403           Condition =>
5404             Make_And_Then (Loc,
5405               Left_Opnd =>
5406                 Make_And_Then (Loc,
5407                   Left_Opnd =>
5408                     Convert_To (Standard_Boolean,
5409                       Make_Attribute_Reference (Loc,
5410                         Prefix         => New_Occurrence_Of (CT, Loc),
5411                         Attribute_Name => Name_First)),
5412
5413                   Right_Opnd =>
5414                     Convert_To (Standard_Boolean,
5415                       Make_Attribute_Reference (Loc,
5416                         Prefix         => New_Occurrence_Of (CT, Loc),
5417                         Attribute_Name => Name_Last))),
5418
5419               Right_Opnd => Make_Non_Empty_Check (Loc, Right_Opnd (N))),
5420           Reason => CE_Range_Check_Failed));
5421    end Silly_Boolean_Array_Xor_Test;
5422
5423    --------------------------
5424    -- Target_Has_Fixed_Ops --
5425    --------------------------
5426
5427    Integer_Sized_Small : Ureal;
5428    --  Set to 2.0 ** -(Integer'Size - 1) the first time that this
5429    --  function is called (we don't want to compute it more than once!)
5430
5431    Long_Integer_Sized_Small : Ureal;
5432    --  Set to 2.0 ** -(Long_Integer'Size - 1) the first time that this
5433    --  function is called (we don't want to compute it more than once)
5434
5435    First_Time_For_THFO : Boolean := True;
5436    --  Set to False after first call (if Fractional_Fixed_Ops_On_Target)
5437
5438    function Target_Has_Fixed_Ops
5439      (Left_Typ   : Entity_Id;
5440       Right_Typ  : Entity_Id;
5441       Result_Typ : Entity_Id) return Boolean
5442    is
5443       function Is_Fractional_Type (Typ : Entity_Id) return Boolean;
5444       --  Return True if the given type is a fixed-point type with a small
5445       --  value equal to 2 ** (-(T'Object_Size - 1)) and whose values have
5446       --  an absolute value less than 1.0. This is currently limited
5447       --  to fixed-point types that map to Integer or Long_Integer.
5448
5449       ------------------------
5450       -- Is_Fractional_Type --
5451       ------------------------
5452
5453       function Is_Fractional_Type (Typ : Entity_Id) return Boolean is
5454       begin
5455          if Esize (Typ) = Standard_Integer_Size then
5456             return Small_Value (Typ) = Integer_Sized_Small;
5457
5458          elsif Esize (Typ) = Standard_Long_Integer_Size then
5459             return Small_Value (Typ) = Long_Integer_Sized_Small;
5460
5461          else
5462             return False;
5463          end if;
5464       end Is_Fractional_Type;
5465
5466    --  Start of processing for Target_Has_Fixed_Ops
5467
5468    begin
5469       --  Return False if Fractional_Fixed_Ops_On_Target is false
5470
5471       if not Fractional_Fixed_Ops_On_Target then
5472          return False;
5473       end if;
5474
5475       --  Here the target has Fractional_Fixed_Ops, if first time, compute
5476       --  standard constants used by Is_Fractional_Type.
5477
5478       if First_Time_For_THFO then
5479          First_Time_For_THFO := False;
5480
5481          Integer_Sized_Small :=
5482            UR_From_Components
5483              (Num   => Uint_1,
5484               Den   => UI_From_Int (Standard_Integer_Size - 1),
5485               Rbase => 2);
5486
5487          Long_Integer_Sized_Small :=
5488            UR_From_Components
5489              (Num   => Uint_1,
5490               Den   => UI_From_Int (Standard_Long_Integer_Size - 1),
5491               Rbase => 2);
5492       end if;
5493
5494       --  Return True if target supports fixed-by-fixed multiply/divide
5495       --  for fractional fixed-point types (see Is_Fractional_Type) and
5496       --  the operand and result types are equivalent fractional types.
5497
5498       return Is_Fractional_Type (Base_Type (Left_Typ))
5499         and then Is_Fractional_Type (Base_Type (Right_Typ))
5500         and then Is_Fractional_Type (Base_Type (Result_Typ))
5501         and then Esize (Left_Typ) = Esize (Right_Typ)
5502         and then Esize (Left_Typ) = Esize (Result_Typ);
5503    end Target_Has_Fixed_Ops;
5504
5505    ------------------------------------------
5506    -- Type_May_Have_Bit_Aligned_Components --
5507    ------------------------------------------
5508
5509    function Type_May_Have_Bit_Aligned_Components
5510      (Typ : Entity_Id) return Boolean
5511    is
5512    begin
5513       --  Array type, check component type
5514
5515       if Is_Array_Type (Typ) then
5516          return
5517            Type_May_Have_Bit_Aligned_Components (Component_Type (Typ));
5518
5519       --  Record type, check components
5520
5521       elsif Is_Record_Type (Typ) then
5522          declare
5523             E : Entity_Id;
5524
5525          begin
5526             E := First_Component_Or_Discriminant (Typ);
5527             while Present (E) loop
5528                if Component_May_Be_Bit_Aligned (E)
5529                  or else Type_May_Have_Bit_Aligned_Components (Etype (E))
5530                then
5531                   return True;
5532                end if;
5533
5534                Next_Component_Or_Discriminant (E);
5535             end loop;
5536
5537             return False;
5538          end;
5539
5540       --  Type other than array or record is always OK
5541
5542       else
5543          return False;
5544       end if;
5545    end Type_May_Have_Bit_Aligned_Components;
5546
5547    ----------------------------
5548    -- Wrap_Cleanup_Procedure --
5549    ----------------------------
5550
5551    procedure Wrap_Cleanup_Procedure (N : Node_Id) is
5552       Loc   : constant Source_Ptr := Sloc (N);
5553       Stseq : constant Node_Id    := Handled_Statement_Sequence (N);
5554       Stmts : constant List_Id    := Statements (Stseq);
5555
5556    begin
5557       if Abort_Allowed then
5558          Prepend_To (Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer));
5559          Append_To  (Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer));
5560       end if;
5561    end Wrap_Cleanup_Procedure;
5562
5563 end Exp_Util;