OSDN Git Service

01f240fc03489aef93ccfac43bd1bdbd856d761d
[pf3gnuchains/gcc-fork.git] / gcc / ada / checks.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                               C H E C K S                                --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Debug;    use Debug;
28 with Einfo;    use Einfo;
29 with Errout;   use Errout;
30 with Exp_Ch2;  use Exp_Ch2;
31 with Exp_Ch4;  use Exp_Ch4;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Pakd; use Exp_Pakd;
34 with Exp_Util; use Exp_Util;
35 with Elists;   use Elists;
36 with Eval_Fat; use Eval_Fat;
37 with Freeze;   use Freeze;
38 with Lib;      use Lib;
39 with Nlists;   use Nlists;
40 with Nmake;    use Nmake;
41 with Opt;      use Opt;
42 with Output;   use Output;
43 with Restrict; use Restrict;
44 with Rident;   use Rident;
45 with Rtsfind;  use Rtsfind;
46 with Sem;      use Sem;
47 with Sem_Aux;  use Sem_Aux;
48 with Sem_Eval; use Sem_Eval;
49 with Sem_Ch3;  use Sem_Ch3;
50 with Sem_Ch8;  use Sem_Ch8;
51 with Sem_Res;  use Sem_Res;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinfo;    use Sinfo;
55 with Sinput;   use Sinput;
56 with Snames;   use Snames;
57 with Sprint;   use Sprint;
58 with Stand;    use Stand;
59 with Targparm; use Targparm;
60 with Tbuild;   use Tbuild;
61 with Ttypes;   use Ttypes;
62 with Urealp;   use Urealp;
63 with Validsw;  use Validsw;
64
65 package body Checks is
66
67    --  General note: many of these routines are concerned with generating
68    --  checking code to make sure that constraint error is raised at runtime.
69    --  Clearly this code is only needed if the expander is active, since
70    --  otherwise we will not be generating code or going into the runtime
71    --  execution anyway.
72
73    --  We therefore disconnect most of these checks if the expander is
74    --  inactive. This has the additional benefit that we do not need to
75    --  worry about the tree being messed up by previous errors (since errors
76    --  turn off expansion anyway).
77
78    --  There are a few exceptions to the above rule. For instance routines
79    --  such as Apply_Scalar_Range_Check that do not insert any code can be
80    --  safely called even when the Expander is inactive (but Errors_Detected
81    --  is 0). The benefit of executing this code when expansion is off, is
82    --  the ability to emit constraint error warning for static expressions
83    --  even when we are not generating code.
84
85    -------------------------------------
86    -- Suppression of Redundant Checks --
87    -------------------------------------
88
89    --  This unit implements a limited circuit for removal of redundant
90    --  checks. The processing is based on a tracing of simple sequential
91    --  flow. For any sequence of statements, we save expressions that are
92    --  marked to be checked, and then if the same expression appears later
93    --  with the same check, then under certain circumstances, the second
94    --  check can be suppressed.
95
96    --  Basically, we can suppress the check if we know for certain that
97    --  the previous expression has been elaborated (together with its
98    --  check), and we know that the exception frame is the same, and that
99    --  nothing has happened to change the result of the exception.
100
101    --  Let us examine each of these three conditions in turn to describe
102    --  how we ensure that this condition is met.
103
104    --  First, we need to know for certain that the previous expression has
105    --  been executed. This is done principally by the mechanism of calling
106    --  Conditional_Statements_Begin at the start of any statement sequence
107    --  and Conditional_Statements_End at the end. The End call causes all
108    --  checks remembered since the Begin call to be discarded. This does
109    --  miss a few cases, notably the case of a nested BEGIN-END block with
110    --  no exception handlers. But the important thing is to be conservative.
111    --  The other protection is that all checks are discarded if a label
112    --  is encountered, since then the assumption of sequential execution
113    --  is violated, and we don't know enough about the flow.
114
115    --  Second, we need to know that the exception frame is the same. We
116    --  do this by killing all remembered checks when we enter a new frame.
117    --  Again, that's over-conservative, but generally the cases we can help
118    --  with are pretty local anyway (like the body of a loop for example).
119
120    --  Third, we must be sure to forget any checks which are no longer valid.
121    --  This is done by two mechanisms, first the Kill_Checks_Variable call is
122    --  used to note any changes to local variables. We only attempt to deal
123    --  with checks involving local variables, so we do not need to worry
124    --  about global variables. Second, a call to any non-global procedure
125    --  causes us to abandon all stored checks, since such a all may affect
126    --  the values of any local variables.
127
128    --  The following define the data structures used to deal with remembering
129    --  checks so that redundant checks can be eliminated as described above.
130
131    --  Right now, the only expressions that we deal with are of the form of
132    --  simple local objects (either declared locally, or IN parameters) or
133    --  such objects plus/minus a compile time known constant. We can do
134    --  more later on if it seems worthwhile, but this catches many simple
135    --  cases in practice.
136
137    --  The following record type reflects a single saved check. An entry
138    --  is made in the stack of saved checks if and only if the expression
139    --  has been elaborated with the indicated checks.
140
141    type Saved_Check is record
142       Killed : Boolean;
143       --  Set True if entry is killed by Kill_Checks
144
145       Entity : Entity_Id;
146       --  The entity involved in the expression that is checked
147
148       Offset : Uint;
149       --  A compile time value indicating the result of adding or
150       --  subtracting a compile time value. This value is to be
151       --  added to the value of the Entity. A value of zero is
152       --  used for the case of a simple entity reference.
153
154       Check_Type : Character;
155       --  This is set to 'R' for a range check (in which case Target_Type
156       --  is set to the target type for the range check) or to 'O' for an
157       --  overflow check (in which case Target_Type is set to Empty).
158
159       Target_Type : Entity_Id;
160       --  Used only if Do_Range_Check is set. Records the target type for
161       --  the check. We need this, because a check is a duplicate only if
162       --  it has the same target type (or more accurately one with a
163       --  range that is smaller or equal to the stored target type of a
164       --  saved check).
165    end record;
166
167    --  The following table keeps track of saved checks. Rather than use an
168    --  extensible table. We just use a table of fixed size, and we discard
169    --  any saved checks that do not fit. That's very unlikely to happen and
170    --  this is only an optimization in any case.
171
172    Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
173    --  Array of saved checks
174
175    Num_Saved_Checks : Nat := 0;
176    --  Number of saved checks
177
178    --  The following stack keeps track of statement ranges. It is treated
179    --  as a stack. When Conditional_Statements_Begin is called, an entry
180    --  is pushed onto this stack containing the value of Num_Saved_Checks
181    --  at the time of the call. Then when Conditional_Statements_End is
182    --  called, this value is popped off and used to reset Num_Saved_Checks.
183
184    --  Note: again, this is a fixed length stack with a size that should
185    --  always be fine. If the value of the stack pointer goes above the
186    --  limit, then we just forget all saved checks.
187
188    Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
189    Saved_Checks_TOS : Nat := 0;
190
191    -----------------------
192    -- Local Subprograms --
193    -----------------------
194
195    procedure Apply_Float_Conversion_Check
196      (Ck_Node    : Node_Id;
197       Target_Typ : Entity_Id);
198    --  The checks on a conversion from a floating-point type to an integer
199    --  type are delicate. They have to be performed before conversion, they
200    --  have to raise an exception when the operand is a NaN, and rounding must
201    --  be taken into account to determine the safe bounds of the operand.
202
203    procedure Apply_Selected_Length_Checks
204      (Ck_Node    : Node_Id;
205       Target_Typ : Entity_Id;
206       Source_Typ : Entity_Id;
207       Do_Static  : Boolean);
208    --  This is the subprogram that does all the work for Apply_Length_Check
209    --  and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
210    --  described for the above routines. The Do_Static flag indicates that
211    --  only a static check is to be done.
212
213    procedure Apply_Selected_Range_Checks
214      (Ck_Node    : Node_Id;
215       Target_Typ : Entity_Id;
216       Source_Typ : Entity_Id;
217       Do_Static  : Boolean);
218    --  This is the subprogram that does all the work for Apply_Range_Check.
219    --  Expr, Target_Typ and Source_Typ are as described for the above
220    --  routine. The Do_Static flag indicates that only a static check is
221    --  to be done.
222
223    type Check_Type is new Check_Id range Access_Check .. Division_Check;
224    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
225    --  This function is used to see if an access or division by zero check is
226    --  needed. The check is to be applied to a single variable appearing in the
227    --  source, and N is the node for the reference. If N is not of this form,
228    --  True is returned with no further processing. If N is of the right form,
229    --  then further processing determines if the given Check is needed.
230    --
231    --  The particular circuit is to see if we have the case of a check that is
232    --  not needed because it appears in the right operand of a short circuited
233    --  conditional where the left operand guards the check. For example:
234    --
235    --    if Var = 0 or else Q / Var > 12 then
236    --       ...
237    --    end if;
238    --
239    --  In this example, the division check is not required. At the same time
240    --  we can issue warnings for suspicious use of non-short-circuited forms,
241    --  such as:
242    --
243    --    if Var = 0 or Q / Var > 12 then
244    --       ...
245    --    end if;
246
247    procedure Find_Check
248      (Expr        : Node_Id;
249       Check_Type  : Character;
250       Target_Type : Entity_Id;
251       Entry_OK    : out Boolean;
252       Check_Num   : out Nat;
253       Ent         : out Entity_Id;
254       Ofs         : out Uint);
255    --  This routine is used by Enable_Range_Check and Enable_Overflow_Check
256    --  to see if a check is of the form for optimization, and if so, to see
257    --  if it has already been performed. Expr is the expression to check,
258    --  and Check_Type is 'R' for a range check, 'O' for an overflow check.
259    --  Target_Type is the target type for a range check, and Empty for an
260    --  overflow check. If the entry is not of the form for optimization,
261    --  then Entry_OK is set to False, and the remaining out parameters
262    --  are undefined. If the entry is OK, then Ent/Ofs are set to the
263    --  entity and offset from the expression. Check_Num is the number of
264    --  a matching saved entry in Saved_Checks, or zero if no such entry
265    --  is located.
266
267    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
268    --  If a discriminal is used in constraining a prival, Return reference
269    --  to the discriminal of the protected body (which renames the parameter
270    --  of the enclosing protected operation). This clumsy transformation is
271    --  needed because privals are created too late and their actual subtypes
272    --  are not available when analysing the bodies of the protected operations.
273    --  This function is called whenever the bound is an entity and the scope
274    --  indicates a protected operation. If the bound is an in-parameter of
275    --  a protected operation that is not a prival, the function returns the
276    --  bound itself.
277    --  To be cleaned up???
278
279    function Guard_Access
280      (Cond    : Node_Id;
281       Loc     : Source_Ptr;
282       Ck_Node : Node_Id) return Node_Id;
283    --  In the access type case, guard the test with a test to ensure
284    --  that the access value is non-null, since the checks do not
285    --  not apply to null access values.
286
287    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
288    --  Called by Apply_{Length,Range}_Checks to rewrite the tree with the
289    --  Constraint_Error node.
290
291    function Range_Or_Validity_Checks_Suppressed
292      (Expr : Node_Id) return Boolean;
293    --  Returns True if either range or validity checks or both are suppressed
294    --  for the type of the given expression, or, if the expression is the name
295    --  of an entity, if these checks are suppressed for the entity.
296
297    function Selected_Length_Checks
298      (Ck_Node    : Node_Id;
299       Target_Typ : Entity_Id;
300       Source_Typ : Entity_Id;
301       Warn_Node  : Node_Id) return Check_Result;
302    --  Like Apply_Selected_Length_Checks, except it doesn't modify
303    --  anything, just returns a list of nodes as described in the spec of
304    --  this package for the Range_Check function.
305
306    function Selected_Range_Checks
307      (Ck_Node    : Node_Id;
308       Target_Typ : Entity_Id;
309       Source_Typ : Entity_Id;
310       Warn_Node  : Node_Id) return Check_Result;
311    --  Like Apply_Selected_Range_Checks, except it doesn't modify anything,
312    --  just returns a list of nodes as described in the spec of this package
313    --  for the Range_Check function.
314
315    ------------------------------
316    -- Access_Checks_Suppressed --
317    ------------------------------
318
319    function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
320    begin
321       if Present (E) and then Checks_May_Be_Suppressed (E) then
322          return Is_Check_Suppressed (E, Access_Check);
323       else
324          return Scope_Suppress (Access_Check);
325       end if;
326    end Access_Checks_Suppressed;
327
328    -------------------------------------
329    -- Accessibility_Checks_Suppressed --
330    -------------------------------------
331
332    function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
333    begin
334       if Present (E) and then Checks_May_Be_Suppressed (E) then
335          return Is_Check_Suppressed (E, Accessibility_Check);
336       else
337          return Scope_Suppress (Accessibility_Check);
338       end if;
339    end Accessibility_Checks_Suppressed;
340
341    -----------------------------
342    -- Activate_Division_Check --
343    -----------------------------
344
345    procedure Activate_Division_Check (N : Node_Id) is
346    begin
347       Set_Do_Division_Check (N, True);
348       Possible_Local_Raise (N, Standard_Constraint_Error);
349    end Activate_Division_Check;
350
351    -----------------------------
352    -- Activate_Overflow_Check --
353    -----------------------------
354
355    procedure Activate_Overflow_Check (N : Node_Id) is
356    begin
357       Set_Do_Overflow_Check (N, True);
358       Possible_Local_Raise (N, Standard_Constraint_Error);
359    end Activate_Overflow_Check;
360
361    --------------------------
362    -- Activate_Range_Check --
363    --------------------------
364
365    procedure Activate_Range_Check (N : Node_Id) is
366    begin
367       Set_Do_Range_Check (N, True);
368       Possible_Local_Raise (N, Standard_Constraint_Error);
369    end Activate_Range_Check;
370
371    ---------------------------------
372    -- Alignment_Checks_Suppressed --
373    ---------------------------------
374
375    function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
376    begin
377       if Present (E) and then Checks_May_Be_Suppressed (E) then
378          return Is_Check_Suppressed (E, Alignment_Check);
379       else
380          return Scope_Suppress (Alignment_Check);
381       end if;
382    end Alignment_Checks_Suppressed;
383
384    -------------------------
385    -- Append_Range_Checks --
386    -------------------------
387
388    procedure Append_Range_Checks
389      (Checks       : Check_Result;
390       Stmts        : List_Id;
391       Suppress_Typ : Entity_Id;
392       Static_Sloc  : Source_Ptr;
393       Flag_Node    : Node_Id)
394    is
395       Internal_Flag_Node   : constant Node_Id    := Flag_Node;
396       Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
397
398       Checks_On : constant Boolean :=
399                     (not Index_Checks_Suppressed (Suppress_Typ))
400                        or else
401                     (not Range_Checks_Suppressed (Suppress_Typ));
402
403    begin
404       --  For now we just return if Checks_On is false, however this should
405       --  be enhanced to check for an always True value in the condition
406       --  and to generate a compilation warning???
407
408       if not Checks_On then
409          return;
410       end if;
411
412       for J in 1 .. 2 loop
413          exit when No (Checks (J));
414
415          if Nkind (Checks (J)) = N_Raise_Constraint_Error
416            and then Present (Condition (Checks (J)))
417          then
418             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
419                Append_To (Stmts, Checks (J));
420                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
421             end if;
422
423          else
424             Append_To
425               (Stmts,
426                 Make_Raise_Constraint_Error (Internal_Static_Sloc,
427                   Reason => CE_Range_Check_Failed));
428          end if;
429       end loop;
430    end Append_Range_Checks;
431
432    ------------------------
433    -- Apply_Access_Check --
434    ------------------------
435
436    procedure Apply_Access_Check (N : Node_Id) is
437       P : constant Node_Id := Prefix (N);
438
439    begin
440       --  We do not need checks if we are not generating code (i.e. the
441       --  expander is not active). This is not just an optimization, there
442       --  are cases (e.g. with pragma Debug) where generating the checks
443       --  can cause real trouble).
444
445       if not Full_Expander_Active then
446          return;
447       end if;
448
449       --  No check if short circuiting makes check unnecessary
450
451       if not Check_Needed (P, Access_Check) then
452          return;
453       end if;
454
455       --  No check if accessing the Offset_To_Top component of a dispatch
456       --  table. They are safe by construction.
457
458       if Tagged_Type_Expansion
459         and then Present (Etype (P))
460         and then RTU_Loaded (Ada_Tags)
461         and then RTE_Available (RE_Offset_To_Top_Ptr)
462         and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
463       then
464          return;
465       end if;
466
467       --  Otherwise go ahead and install the check
468
469       Install_Null_Excluding_Check (P);
470    end Apply_Access_Check;
471
472    -------------------------------
473    -- Apply_Accessibility_Check --
474    -------------------------------
475
476    procedure Apply_Accessibility_Check
477      (N           : Node_Id;
478       Typ         : Entity_Id;
479       Insert_Node : Node_Id)
480    is
481       Loc         : constant Source_Ptr := Sloc (N);
482       Param_Ent   : Entity_Id           := Param_Entity (N);
483       Param_Level : Node_Id;
484       Type_Level  : Node_Id;
485
486    begin
487       if Ada_Version >= Ada_2012
488          and then not Present (Param_Ent)
489          and then Is_Entity_Name (N)
490          and then Ekind_In (Entity (N), E_Constant, E_Variable)
491          and then Present (Effective_Extra_Accessibility (Entity (N)))
492       then
493          Param_Ent := Entity (N);
494          while Present (Renamed_Object (Param_Ent)) loop
495
496             --  Renamed_Object must return an Entity_Name here
497             --  because of preceding "Present (E_E_A (...))" test.
498
499             Param_Ent := Entity (Renamed_Object (Param_Ent));
500          end loop;
501       end if;
502
503       if Inside_A_Generic then
504          return;
505
506       --  Only apply the run-time check if the access parameter has an
507       --  associated extra access level parameter and when the level of the
508       --  type is less deep than the level of the access parameter, and
509       --  accessibility checks are not suppressed.
510
511       elsif Present (Param_Ent)
512          and then Present (Extra_Accessibility (Param_Ent))
513          and then UI_Gt (Object_Access_Level (N),
514                          Deepest_Type_Access_Level (Typ))
515          and then not Accessibility_Checks_Suppressed (Param_Ent)
516          and then not Accessibility_Checks_Suppressed (Typ)
517       then
518          Param_Level :=
519            New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
520
521          Type_Level :=
522            Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
523
524          --  Raise Program_Error if the accessibility level of the access
525          --  parameter is deeper than the level of the target access type.
526
527          Insert_Action (Insert_Node,
528            Make_Raise_Program_Error (Loc,
529              Condition =>
530                Make_Op_Gt (Loc,
531                  Left_Opnd  => Param_Level,
532                  Right_Opnd => Type_Level),
533              Reason => PE_Accessibility_Check_Failed));
534
535          Analyze_And_Resolve (N);
536       end if;
537    end Apply_Accessibility_Check;
538
539    --------------------------------
540    -- Apply_Address_Clause_Check --
541    --------------------------------
542
543    procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
544       AC   : constant Node_Id    := Address_Clause (E);
545       Loc  : constant Source_Ptr := Sloc (AC);
546       Typ  : constant Entity_Id  := Etype (E);
547       Aexp : constant Node_Id    := Expression (AC);
548
549       Expr : Node_Id;
550       --  Address expression (not necessarily the same as Aexp, for example
551       --  when Aexp is a reference to a constant, in which case Expr gets
552       --  reset to reference the value expression of the constant.
553
554       procedure Compile_Time_Bad_Alignment;
555       --  Post error warnings when alignment is known to be incompatible. Note
556       --  that we do not go as far as inserting a raise of Program_Error since
557       --  this is an erroneous case, and it may happen that we are lucky and an
558       --  underaligned address turns out to be OK after all.
559
560       --------------------------------
561       -- Compile_Time_Bad_Alignment --
562       --------------------------------
563
564       procedure Compile_Time_Bad_Alignment is
565       begin
566          if Address_Clause_Overlay_Warnings then
567             Error_Msg_FE
568               ("?specified address for& may be inconsistent with alignment ",
569                Aexp, E);
570             Error_Msg_FE
571               ("\?program execution may be erroneous (RM 13.3(27))",
572                Aexp, E);
573             Set_Address_Warning_Posted (AC);
574          end if;
575       end Compile_Time_Bad_Alignment;
576
577    --  Start of processing for Apply_Address_Clause_Check
578
579    begin
580       --  See if alignment check needed. Note that we never need a check if the
581       --  maximum alignment is one, since the check will always succeed.
582
583       --  Note: we do not check for checks suppressed here, since that check
584       --  was done in Sem_Ch13 when the address clause was processed. We are
585       --  only called if checks were not suppressed. The reason for this is
586       --  that we have to delay the call to Apply_Alignment_Check till freeze
587       --  time (so that all types etc are elaborated), but we have to check
588       --  the status of check suppressing at the point of the address clause.
589
590       if No (AC)
591         or else not Check_Address_Alignment (AC)
592         or else Maximum_Alignment = 1
593       then
594          return;
595       end if;
596
597       --  Obtain expression from address clause
598
599       Expr := Expression (AC);
600
601       --  The following loop digs for the real expression to use in the check
602
603       loop
604          --  For constant, get constant expression
605
606          if Is_Entity_Name (Expr)
607            and then Ekind (Entity (Expr)) = E_Constant
608          then
609             Expr := Constant_Value (Entity (Expr));
610
611          --  For unchecked conversion, get result to convert
612
613          elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
614             Expr := Expression (Expr);
615
616          --  For (common case) of To_Address call, get argument
617
618          elsif Nkind (Expr) = N_Function_Call
619            and then Is_Entity_Name (Name (Expr))
620            and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
621          then
622             Expr := First (Parameter_Associations (Expr));
623
624             if Nkind (Expr) = N_Parameter_Association then
625                Expr := Explicit_Actual_Parameter (Expr);
626             end if;
627
628          --  We finally have the real expression
629
630          else
631             exit;
632          end if;
633       end loop;
634
635       --  See if we know that Expr has a bad alignment at compile time
636
637       if Compile_Time_Known_Value (Expr)
638         and then (Known_Alignment (E) or else Known_Alignment (Typ))
639       then
640          declare
641             AL : Uint := Alignment (Typ);
642
643          begin
644             --  The object alignment might be more restrictive than the
645             --  type alignment.
646
647             if Known_Alignment (E) then
648                AL := Alignment (E);
649             end if;
650
651             if Expr_Value (Expr) mod AL /= 0 then
652                Compile_Time_Bad_Alignment;
653             else
654                return;
655             end if;
656          end;
657
658       --  If the expression has the form X'Address, then we can find out if
659       --  the object X has an alignment that is compatible with the object E.
660       --  If it hasn't or we don't know, we defer issuing the warning until
661       --  the end of the compilation to take into account back end annotations.
662
663       elsif Nkind (Expr) = N_Attribute_Reference
664         and then Attribute_Name (Expr) = Name_Address
665         and then Has_Compatible_Alignment (E, Prefix (Expr)) = Known_Compatible
666       then
667          return;
668       end if;
669
670       --  Here we do not know if the value is acceptable. Strictly we don't
671       --  have to do anything, since if the alignment is bad, we have an
672       --  erroneous program. However we are allowed to check for erroneous
673       --  conditions and we decide to do this by default if the check is not
674       --  suppressed.
675
676       --  However, don't do the check if elaboration code is unwanted
677
678       if Restriction_Active (No_Elaboration_Code) then
679          return;
680
681       --  Generate a check to raise PE if alignment may be inappropriate
682
683       else
684          --  If the original expression is a non-static constant, use the
685          --  name of the constant itself rather than duplicating its
686          --  defining expression, which was extracted above.
687
688          --  Note: Expr is empty if the address-clause is applied to in-mode
689          --  actuals (allowed by 13.1(22)).
690
691          if not Present (Expr)
692            or else
693              (Is_Entity_Name (Expression (AC))
694                and then Ekind (Entity (Expression (AC))) = E_Constant
695                and then Nkind (Parent (Entity (Expression (AC))))
696                                  = N_Object_Declaration)
697          then
698             Expr := New_Copy_Tree (Expression (AC));
699          else
700             Remove_Side_Effects (Expr);
701          end if;
702
703          Insert_After_And_Analyze (N,
704            Make_Raise_Program_Error (Loc,
705              Condition =>
706                Make_Op_Ne (Loc,
707                  Left_Opnd =>
708                    Make_Op_Mod (Loc,
709                      Left_Opnd =>
710                        Unchecked_Convert_To
711                          (RTE (RE_Integer_Address), Expr),
712                      Right_Opnd =>
713                        Make_Attribute_Reference (Loc,
714                          Prefix => New_Occurrence_Of (E, Loc),
715                          Attribute_Name => Name_Alignment)),
716                  Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
717              Reason => PE_Misaligned_Address_Value),
718            Suppress => All_Checks);
719          return;
720       end if;
721
722    exception
723       --  If we have some missing run time component in configurable run time
724       --  mode then just skip the check (it is not required in any case).
725
726       when RE_Not_Available =>
727          return;
728    end Apply_Address_Clause_Check;
729
730    -------------------------------------
731    -- Apply_Arithmetic_Overflow_Check --
732    -------------------------------------
733
734    --  This routine is called only if the type is an integer type, and a
735    --  software arithmetic overflow check may be needed for op (add, subtract,
736    --  or multiply). This check is performed only if Software_Overflow_Checking
737    --  is enabled and Do_Overflow_Check is set. In this case we expand the
738    --  operation into a more complex sequence of tests that ensures that
739    --  overflow is properly caught.
740
741    procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
742       Loc   : constant Source_Ptr := Sloc (N);
743       Typ   : constant Entity_Id  := Etype (N);
744       Rtyp  : constant Entity_Id  := Root_Type (Typ);
745
746    begin
747       --  An interesting special case. If the arithmetic operation appears as
748       --  the operand of a type conversion:
749
750       --    type1 (x op y)
751
752       --  and all the following conditions apply:
753
754       --    arithmetic operation is for a signed integer type
755       --    target type type1 is a static integer subtype
756       --    range of x and y are both included in the range of type1
757       --    range of x op y is included in the range of type1
758       --    size of type1 is at least twice the result size of op
759
760       --  then we don't do an overflow check in any case, instead we transform
761       --  the operation so that we end up with:
762
763       --    type1 (type1 (x) op type1 (y))
764
765       --  This avoids intermediate overflow before the conversion. It is
766       --  explicitly permitted by RM 3.5.4(24):
767
768       --    For the execution of a predefined operation of a signed integer
769       --    type, the implementation need not raise Constraint_Error if the
770       --    result is outside the base range of the type, so long as the
771       --    correct result is produced.
772
773       --  It's hard to imagine that any programmer counts on the exception
774       --  being raised in this case, and in any case it's wrong coding to
775       --  have this expectation, given the RM permission. Furthermore, other
776       --  Ada compilers do allow such out of range results.
777
778       --  Note that we do this transformation even if overflow checking is
779       --  off, since this is precisely about giving the "right" result and
780       --  avoiding the need for an overflow check.
781
782       --  Note: this circuit is partially redundant with respect to the similar
783       --  processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
784       --  with cases that do not come through here. We still need the following
785       --  processing even with the Exp_Ch4 code in place, since we want to be
786       --  sure not to generate the arithmetic overflow check in these cases
787       --  (Exp_Ch4 would have a hard time removing them once generated).
788
789       if Is_Signed_Integer_Type (Typ)
790         and then Nkind (Parent (N)) = N_Type_Conversion
791       then
792          declare
793             Target_Type : constant Entity_Id :=
794                             Base_Type (Entity (Subtype_Mark (Parent (N))));
795
796             Llo, Lhi : Uint;
797             Rlo, Rhi : Uint;
798             LOK, ROK : Boolean;
799
800             Vlo : Uint;
801             Vhi : Uint;
802             VOK : Boolean;
803
804             Tlo : Uint;
805             Thi : Uint;
806
807          begin
808             if Is_Integer_Type (Target_Type)
809               and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
810             then
811                Tlo := Expr_Value (Type_Low_Bound  (Target_Type));
812                Thi := Expr_Value (Type_High_Bound (Target_Type));
813
814                Determine_Range
815                  (Left_Opnd  (N), LOK, Llo, Lhi, Assume_Valid => True);
816                Determine_Range
817                  (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
818
819                if (LOK and ROK)
820                  and then Tlo <= Llo and then Lhi <= Thi
821                  and then Tlo <= Rlo and then Rhi <= Thi
822                then
823                   Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
824
825                   if VOK and then Tlo <= Vlo and then Vhi <= Thi then
826                      Rewrite (Left_Opnd (N),
827                        Make_Type_Conversion (Loc,
828                          Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
829                          Expression   => Relocate_Node (Left_Opnd (N))));
830
831                      Rewrite (Right_Opnd (N),
832                        Make_Type_Conversion (Loc,
833                         Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
834                         Expression   => Relocate_Node (Right_Opnd (N))));
835
836                      --  Rewrite the conversion operand so that the original
837                      --  node is retained, in order to avoid the warning for
838                      --  redundant conversions in Resolve_Type_Conversion.
839
840                      Rewrite (N, Relocate_Node (N));
841
842                      Set_Etype (N, Target_Type);
843
844                      Analyze_And_Resolve (Left_Opnd  (N), Target_Type);
845                      Analyze_And_Resolve (Right_Opnd (N), Target_Type);
846
847                      --  Given that the target type is twice the size of the
848                      --  source type, overflow is now impossible, so we can
849                      --  safely kill the overflow check and return.
850
851                      Set_Do_Overflow_Check (N, False);
852                      return;
853                   end if;
854                end if;
855             end if;
856          end;
857       end if;
858
859       --  Now see if an overflow check is required
860
861       declare
862          Siz   : constant Int := UI_To_Int (Esize (Rtyp));
863          Dsiz  : constant Int := Siz * 2;
864          Opnod : Node_Id;
865          Ctyp  : Entity_Id;
866          Opnd  : Node_Id;
867          Cent  : RE_Id;
868
869       begin
870          --  Skip check if back end does overflow checks, or the overflow flag
871          --  is not set anyway, or we are not doing code expansion, or the
872          --  parent node is a type conversion whose operand is an arithmetic
873          --  operation on signed integers on which the expander can promote
874          --  later the operands to type Integer (see Expand_N_Type_Conversion).
875
876          --  Special case CLI target, where arithmetic overflow checks can be
877          --  performed for integer and long_integer
878
879          if Backend_Overflow_Checks_On_Target
880            or else not Do_Overflow_Check (N)
881            or else not Full_Expander_Active
882            or else (Present (Parent (N))
883                      and then Nkind (Parent (N)) = N_Type_Conversion
884                      and then Integer_Promotion_Possible (Parent (N)))
885            or else
886              (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
887          then
888             return;
889          end if;
890
891          --  Otherwise, generate the full general code for front end overflow
892          --  detection, which works by doing arithmetic in a larger type:
893
894          --    x op y
895
896          --  is expanded into
897
898          --    Typ (Checktyp (x) op Checktyp (y));
899
900          --  where Typ is the type of the original expression, and Checktyp is
901          --  an integer type of sufficient length to hold the largest possible
902          --  result.
903
904          --  If the size of check type exceeds the size of Long_Long_Integer,
905          --  we use a different approach, expanding to:
906
907          --    typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
908
909          --  where xxx is Add, Multiply or Subtract as appropriate
910
911          --  Find check type if one exists
912
913          if Dsiz <= Standard_Integer_Size then
914             Ctyp := Standard_Integer;
915
916          elsif Dsiz <= Standard_Long_Long_Integer_Size then
917             Ctyp := Standard_Long_Long_Integer;
918
919             --  No check type exists, use runtime call
920
921          else
922             if Nkind (N) = N_Op_Add then
923                Cent := RE_Add_With_Ovflo_Check;
924
925             elsif Nkind (N) = N_Op_Multiply then
926                Cent := RE_Multiply_With_Ovflo_Check;
927
928             else
929                pragma Assert (Nkind (N) = N_Op_Subtract);
930                Cent := RE_Subtract_With_Ovflo_Check;
931             end if;
932
933             Rewrite (N,
934               OK_Convert_To (Typ,
935                 Make_Function_Call (Loc,
936                   Name => New_Reference_To (RTE (Cent), Loc),
937                   Parameter_Associations => New_List (
938                     OK_Convert_To (RTE (RE_Integer_64), Left_Opnd  (N)),
939                     OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
940
941             Analyze_And_Resolve (N, Typ);
942             return;
943          end if;
944
945          --  If we fall through, we have the case where we do the arithmetic
946          --  in the next higher type and get the check by conversion. In these
947          --  cases Ctyp is set to the type to be used as the check type.
948
949          Opnod := Relocate_Node (N);
950
951          Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
952
953          Analyze (Opnd);
954          Set_Etype (Opnd, Ctyp);
955          Set_Analyzed (Opnd, True);
956          Set_Left_Opnd (Opnod, Opnd);
957
958          Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
959
960          Analyze (Opnd);
961          Set_Etype (Opnd, Ctyp);
962          Set_Analyzed (Opnd, True);
963          Set_Right_Opnd (Opnod, Opnd);
964
965          --  The type of the operation changes to the base type of the check
966          --  type, and we reset the overflow check indication, since clearly no
967          --  overflow is possible now that we are using a double length type.
968          --  We also set the Analyzed flag to avoid a recursive attempt to
969          --  expand the node.
970
971          Set_Etype             (Opnod, Base_Type (Ctyp));
972          Set_Do_Overflow_Check (Opnod, False);
973          Set_Analyzed          (Opnod, True);
974
975          --  Now build the outer conversion
976
977          Opnd := OK_Convert_To (Typ, Opnod);
978          Analyze (Opnd);
979          Set_Etype (Opnd, Typ);
980
981          --  In the discrete type case, we directly generate the range check
982          --  for the outer operand. This range check will implement the
983          --  required overflow check.
984
985          if Is_Discrete_Type (Typ) then
986             Rewrite (N, Opnd);
987             Generate_Range_Check
988               (Expression (N), Typ, CE_Overflow_Check_Failed);
989
990          --  For other types, we enable overflow checking on the conversion,
991          --  after setting the node as analyzed to prevent recursive attempts
992          --  to expand the conversion node.
993
994          else
995             Set_Analyzed (Opnd, True);
996             Enable_Overflow_Check (Opnd);
997             Rewrite (N, Opnd);
998          end if;
999
1000       exception
1001          when RE_Not_Available =>
1002             return;
1003       end;
1004    end Apply_Arithmetic_Overflow_Check;
1005
1006    ----------------------------
1007    -- Apply_Constraint_Check --
1008    ----------------------------
1009
1010    procedure Apply_Constraint_Check
1011      (N          : Node_Id;
1012       Typ        : Entity_Id;
1013       No_Sliding : Boolean := False)
1014    is
1015       Desig_Typ : Entity_Id;
1016
1017    begin
1018       --  No checks inside a generic (check the instantiations)
1019
1020       if Inside_A_Generic then
1021          return;
1022       end if;
1023
1024       --  Apply required constraint checks
1025
1026       if Is_Scalar_Type (Typ) then
1027          Apply_Scalar_Range_Check (N, Typ);
1028
1029       elsif Is_Array_Type (Typ) then
1030
1031          --  A useful optimization: an aggregate with only an others clause
1032          --  always has the right bounds.
1033
1034          if Nkind (N) = N_Aggregate
1035            and then No (Expressions (N))
1036            and then Nkind
1037             (First (Choices (First (Component_Associations (N)))))
1038               = N_Others_Choice
1039          then
1040             return;
1041          end if;
1042
1043          if Is_Constrained (Typ) then
1044             Apply_Length_Check (N, Typ);
1045
1046             if No_Sliding then
1047                Apply_Range_Check (N, Typ);
1048             end if;
1049          else
1050             Apply_Range_Check (N, Typ);
1051          end if;
1052
1053       elsif (Is_Record_Type (Typ)
1054                or else Is_Private_Type (Typ))
1055         and then Has_Discriminants (Base_Type (Typ))
1056         and then Is_Constrained (Typ)
1057       then
1058          Apply_Discriminant_Check (N, Typ);
1059
1060       elsif Is_Access_Type (Typ) then
1061
1062          Desig_Typ := Designated_Type (Typ);
1063
1064          --  No checks necessary if expression statically null
1065
1066          if Known_Null (N) then
1067             if Can_Never_Be_Null (Typ) then
1068                Install_Null_Excluding_Check (N);
1069             end if;
1070
1071          --  No sliding possible on access to arrays
1072
1073          elsif Is_Array_Type (Desig_Typ) then
1074             if Is_Constrained (Desig_Typ) then
1075                Apply_Length_Check (N, Typ);
1076             end if;
1077
1078             Apply_Range_Check (N, Typ);
1079
1080          elsif Has_Discriminants (Base_Type (Desig_Typ))
1081             and then Is_Constrained (Desig_Typ)
1082          then
1083             Apply_Discriminant_Check (N, Typ);
1084          end if;
1085
1086          --  Apply the 2005 Null_Excluding check. Note that we do not apply
1087          --  this check if the constraint node is illegal, as shown by having
1088          --  an error posted. This additional guard prevents cascaded errors
1089          --  and compiler aborts on illegal programs involving Ada 2005 checks.
1090
1091          if Can_Never_Be_Null (Typ)
1092            and then not Can_Never_Be_Null (Etype (N))
1093            and then not Error_Posted (N)
1094          then
1095             Install_Null_Excluding_Check (N);
1096          end if;
1097       end if;
1098    end Apply_Constraint_Check;
1099
1100    ------------------------------
1101    -- Apply_Discriminant_Check --
1102    ------------------------------
1103
1104    procedure Apply_Discriminant_Check
1105      (N   : Node_Id;
1106       Typ : Entity_Id;
1107       Lhs : Node_Id := Empty)
1108    is
1109       Loc       : constant Source_Ptr := Sloc (N);
1110       Do_Access : constant Boolean    := Is_Access_Type (Typ);
1111       S_Typ     : Entity_Id  := Etype (N);
1112       Cond      : Node_Id;
1113       T_Typ     : Entity_Id;
1114
1115       function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1116       --  A heap object with an indefinite subtype is constrained by its
1117       --  initial value, and assigning to it requires a constraint_check.
1118       --  The target may be an explicit dereference, or a renaming of one.
1119
1120       function Is_Aliased_Unconstrained_Component return Boolean;
1121       --  It is possible for an aliased component to have a nominal
1122       --  unconstrained subtype (through instantiation). If this is a
1123       --  discriminated component assigned in the expansion of an aggregate
1124       --  in an initialization, the check must be suppressed. This unusual
1125       --  situation requires a predicate of its own.
1126
1127       ----------------------------------
1128       -- Denotes_Explicit_Dereference --
1129       ----------------------------------
1130
1131       function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1132       begin
1133          return
1134            Nkind (Obj) = N_Explicit_Dereference
1135              or else
1136                (Is_Entity_Name (Obj)
1137                  and then Present (Renamed_Object (Entity (Obj)))
1138                  and then Nkind (Renamed_Object (Entity (Obj))) =
1139                                               N_Explicit_Dereference);
1140       end Denotes_Explicit_Dereference;
1141
1142       ----------------------------------------
1143       -- Is_Aliased_Unconstrained_Component --
1144       ----------------------------------------
1145
1146       function Is_Aliased_Unconstrained_Component return Boolean is
1147          Comp : Entity_Id;
1148          Pref : Node_Id;
1149
1150       begin
1151          if Nkind (Lhs) /= N_Selected_Component then
1152             return False;
1153          else
1154             Comp := Entity (Selector_Name (Lhs));
1155             Pref := Prefix (Lhs);
1156          end if;
1157
1158          if Ekind (Comp) /= E_Component
1159            or else not Is_Aliased (Comp)
1160          then
1161             return False;
1162          end if;
1163
1164          return not Comes_From_Source (Pref)
1165            and then In_Instance
1166            and then not Is_Constrained (Etype (Comp));
1167       end Is_Aliased_Unconstrained_Component;
1168
1169    --  Start of processing for Apply_Discriminant_Check
1170
1171    begin
1172       if Do_Access then
1173          T_Typ := Designated_Type (Typ);
1174       else
1175          T_Typ := Typ;
1176       end if;
1177
1178       --  Nothing to do if discriminant checks are suppressed or else no code
1179       --  is to be generated
1180
1181       if not Full_Expander_Active
1182         or else Discriminant_Checks_Suppressed (T_Typ)
1183       then
1184          return;
1185       end if;
1186
1187       --  No discriminant checks necessary for an access when expression is
1188       --  statically Null. This is not only an optimization, it is fundamental
1189       --  because otherwise discriminant checks may be generated in init procs
1190       --  for types containing an access to a not-yet-frozen record, causing a
1191       --  deadly forward reference.
1192
1193       --  Also, if the expression is of an access type whose designated type is
1194       --  incomplete, then the access value must be null and we suppress the
1195       --  check.
1196
1197       if Known_Null (N) then
1198          return;
1199
1200       elsif Is_Access_Type (S_Typ) then
1201          S_Typ := Designated_Type (S_Typ);
1202
1203          if Ekind (S_Typ) = E_Incomplete_Type then
1204             return;
1205          end if;
1206       end if;
1207
1208       --  If an assignment target is present, then we need to generate the
1209       --  actual subtype if the target is a parameter or aliased object with
1210       --  an unconstrained nominal subtype.
1211
1212       --  Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1213       --  subtype to the parameter and dereference cases, since other aliased
1214       --  objects are unconstrained (unless the nominal subtype is explicitly
1215       --  constrained).
1216
1217       if Present (Lhs)
1218         and then (Present (Param_Entity (Lhs))
1219                    or else (Ada_Version < Ada_2005
1220                              and then not Is_Constrained (T_Typ)
1221                              and then Is_Aliased_View (Lhs)
1222                              and then not Is_Aliased_Unconstrained_Component)
1223                    or else (Ada_Version >= Ada_2005
1224                              and then not Is_Constrained (T_Typ)
1225                              and then Denotes_Explicit_Dereference (Lhs)
1226                              and then Nkind (Original_Node (Lhs)) /=
1227                                         N_Function_Call))
1228       then
1229          T_Typ := Get_Actual_Subtype (Lhs);
1230       end if;
1231
1232       --  Nothing to do if the type is unconstrained (this is the case where
1233       --  the actual subtype in the RM sense of N is unconstrained and no check
1234       --  is required).
1235
1236       if not Is_Constrained (T_Typ) then
1237          return;
1238
1239       --  Ada 2005: nothing to do if the type is one for which there is a
1240       --  partial view that is constrained.
1241
1242       elsif Ada_Version >= Ada_2005
1243         and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1244       then
1245          return;
1246       end if;
1247
1248       --  Nothing to do if the type is an Unchecked_Union
1249
1250       if Is_Unchecked_Union (Base_Type (T_Typ)) then
1251          return;
1252       end if;
1253
1254       --  Suppress checks if the subtypes are the same. the check must be
1255       --  preserved in an assignment to a formal, because the constraint is
1256       --  given by the actual.
1257
1258       if Nkind (Original_Node (N)) /= N_Allocator
1259         and then (No (Lhs)
1260           or else not Is_Entity_Name (Lhs)
1261           or else No (Param_Entity (Lhs)))
1262       then
1263          if (Etype (N) = Typ
1264               or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1265            and then not Is_Aliased_View (Lhs)
1266          then
1267             return;
1268          end if;
1269
1270       --  We can also eliminate checks on allocators with a subtype mark that
1271       --  coincides with the context type. The context type may be a subtype
1272       --  without a constraint (common case, a generic actual).
1273
1274       elsif Nkind (Original_Node (N)) = N_Allocator
1275         and then Is_Entity_Name (Expression (Original_Node (N)))
1276       then
1277          declare
1278             Alloc_Typ : constant Entity_Id :=
1279                           Entity (Expression (Original_Node (N)));
1280
1281          begin
1282             if Alloc_Typ = T_Typ
1283               or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1284                         and then Is_Entity_Name (
1285                           Subtype_Indication (Parent (T_Typ)))
1286                         and then Alloc_Typ = Base_Type (T_Typ))
1287
1288             then
1289                return;
1290             end if;
1291          end;
1292       end if;
1293
1294       --  See if we have a case where the types are both constrained, and all
1295       --  the constraints are constants. In this case, we can do the check
1296       --  successfully at compile time.
1297
1298       --  We skip this check for the case where the node is a rewritten`
1299       --  allocator, because it already carries the context subtype, and
1300       --  extracting the discriminants from the aggregate is messy.
1301
1302       if Is_Constrained (S_Typ)
1303         and then Nkind (Original_Node (N)) /= N_Allocator
1304       then
1305          declare
1306             DconT : Elmt_Id;
1307             Discr : Entity_Id;
1308             DconS : Elmt_Id;
1309             ItemS : Node_Id;
1310             ItemT : Node_Id;
1311
1312          begin
1313             --  S_Typ may not have discriminants in the case where it is a
1314             --  private type completed by a default discriminated type. In that
1315             --  case, we need to get the constraints from the underlying_type.
1316             --  If the underlying type is unconstrained (i.e. has no default
1317             --  discriminants) no check is needed.
1318
1319             if Has_Discriminants (S_Typ) then
1320                Discr := First_Discriminant (S_Typ);
1321                DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1322
1323             else
1324                Discr := First_Discriminant (Underlying_Type (S_Typ));
1325                DconS :=
1326                  First_Elmt
1327                    (Discriminant_Constraint (Underlying_Type (S_Typ)));
1328
1329                if No (DconS) then
1330                   return;
1331                end if;
1332
1333                --  A further optimization: if T_Typ is derived from S_Typ
1334                --  without imposing a constraint, no check is needed.
1335
1336                if Nkind (Original_Node (Parent (T_Typ))) =
1337                  N_Full_Type_Declaration
1338                then
1339                   declare
1340                      Type_Def : constant Node_Id :=
1341                                  Type_Definition
1342                                    (Original_Node (Parent (T_Typ)));
1343                   begin
1344                      if Nkind (Type_Def) = N_Derived_Type_Definition
1345                        and then Is_Entity_Name (Subtype_Indication (Type_Def))
1346                        and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1347                      then
1348                         return;
1349                      end if;
1350                   end;
1351                end if;
1352             end if;
1353
1354             DconT  := First_Elmt (Discriminant_Constraint (T_Typ));
1355
1356             while Present (Discr) loop
1357                ItemS := Node (DconS);
1358                ItemT := Node (DconT);
1359
1360                --  For a discriminated component type constrained by the
1361                --  current instance of an enclosing type, there is no
1362                --  applicable discriminant check.
1363
1364                if Nkind (ItemT) = N_Attribute_Reference
1365                  and then Is_Access_Type (Etype (ItemT))
1366                  and then Is_Entity_Name (Prefix (ItemT))
1367                  and then Is_Type (Entity (Prefix (ItemT)))
1368                then
1369                   return;
1370                end if;
1371
1372                --  If the expressions for the discriminants are identical
1373                --  and it is side-effect free (for now just an entity),
1374                --  this may be a shared constraint, e.g. from a subtype
1375                --  without a constraint introduced as a generic actual.
1376                --  Examine other discriminants if any.
1377
1378                if ItemS = ItemT
1379                  and then Is_Entity_Name (ItemS)
1380                then
1381                   null;
1382
1383                elsif not Is_OK_Static_Expression (ItemS)
1384                  or else not Is_OK_Static_Expression (ItemT)
1385                then
1386                   exit;
1387
1388                elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1389                   if Do_Access then   --  needs run-time check.
1390                      exit;
1391                   else
1392                      Apply_Compile_Time_Constraint_Error
1393                        (N, "incorrect value for discriminant&?",
1394                         CE_Discriminant_Check_Failed, Ent => Discr);
1395                      return;
1396                   end if;
1397                end if;
1398
1399                Next_Elmt (DconS);
1400                Next_Elmt (DconT);
1401                Next_Discriminant (Discr);
1402             end loop;
1403
1404             if No (Discr) then
1405                return;
1406             end if;
1407          end;
1408       end if;
1409
1410       --  Here we need a discriminant check. First build the expression
1411       --  for the comparisons of the discriminants:
1412
1413       --    (n.disc1 /= typ.disc1) or else
1414       --    (n.disc2 /= typ.disc2) or else
1415       --     ...
1416       --    (n.discn /= typ.discn)
1417
1418       Cond := Build_Discriminant_Checks (N, T_Typ);
1419
1420       --  If Lhs is set and is a parameter, then the condition is
1421       --  guarded by: lhs'constrained and then (condition built above)
1422
1423       if Present (Param_Entity (Lhs)) then
1424          Cond :=
1425            Make_And_Then (Loc,
1426              Left_Opnd =>
1427                Make_Attribute_Reference (Loc,
1428                  Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1429                  Attribute_Name => Name_Constrained),
1430              Right_Opnd => Cond);
1431       end if;
1432
1433       if Do_Access then
1434          Cond := Guard_Access (Cond, Loc, N);
1435       end if;
1436
1437       Insert_Action (N,
1438         Make_Raise_Constraint_Error (Loc,
1439           Condition => Cond,
1440           Reason    => CE_Discriminant_Check_Failed));
1441    end Apply_Discriminant_Check;
1442
1443    ------------------------
1444    -- Apply_Divide_Check --
1445    ------------------------
1446
1447    procedure Apply_Divide_Check (N : Node_Id) is
1448       Loc   : constant Source_Ptr := Sloc (N);
1449       Typ   : constant Entity_Id  := Etype (N);
1450       Left  : constant Node_Id    := Left_Opnd (N);
1451       Right : constant Node_Id    := Right_Opnd (N);
1452
1453       LLB : Uint;
1454       Llo : Uint;
1455       Lhi : Uint;
1456       LOK : Boolean;
1457       Rlo : Uint;
1458       Rhi : Uint;
1459       ROK   : Boolean;
1460
1461       pragma Warnings (Off, Lhi);
1462       --  Don't actually use this value
1463
1464    begin
1465       if Full_Expander_Active
1466         and then not Backend_Divide_Checks_On_Target
1467         and then Check_Needed (Right, Division_Check)
1468       then
1469          Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1470
1471          --  See if division by zero possible, and if so generate test. This
1472          --  part of the test is not controlled by the -gnato switch.
1473
1474          if Do_Division_Check (N) then
1475             if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1476                Insert_Action (N,
1477                  Make_Raise_Constraint_Error (Loc,
1478                    Condition =>
1479                      Make_Op_Eq (Loc,
1480                        Left_Opnd  => Duplicate_Subexpr_Move_Checks (Right),
1481                        Right_Opnd => Make_Integer_Literal (Loc, 0)),
1482                    Reason => CE_Divide_By_Zero));
1483             end if;
1484          end if;
1485
1486          --  Test for extremely annoying case of xxx'First divided by -1
1487
1488          if Do_Overflow_Check (N) then
1489             if Nkind (N) = N_Op_Divide
1490               and then Is_Signed_Integer_Type (Typ)
1491             then
1492                Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1493                LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1494
1495                if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1496                  and then
1497                  ((not LOK) or else (Llo = LLB))
1498                then
1499                   Insert_Action (N,
1500                     Make_Raise_Constraint_Error (Loc,
1501                       Condition =>
1502                         Make_And_Then (Loc,
1503
1504                            Make_Op_Eq (Loc,
1505                              Left_Opnd  =>
1506                                Duplicate_Subexpr_Move_Checks (Left),
1507                              Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1508
1509                            Make_Op_Eq (Loc,
1510                              Left_Opnd =>
1511                                Duplicate_Subexpr (Right),
1512                              Right_Opnd =>
1513                                Make_Integer_Literal (Loc, -1))),
1514                       Reason => CE_Overflow_Check_Failed));
1515                end if;
1516             end if;
1517          end if;
1518       end if;
1519    end Apply_Divide_Check;
1520
1521    ----------------------------------
1522    -- Apply_Float_Conversion_Check --
1523    ----------------------------------
1524
1525    --  Let F and I be the source and target types of the conversion. The RM
1526    --  specifies that a floating-point value X is rounded to the nearest
1527    --  integer, with halfway cases being rounded away from zero. The rounded
1528    --  value of X is checked against I'Range.
1529
1530    --  The catch in the above paragraph is that there is no good way to know
1531    --  whether the round-to-integer operation resulted in overflow. A remedy is
1532    --  to perform a range check in the floating-point domain instead, however:
1533
1534    --      (1)  The bounds may not be known at compile time
1535    --      (2)  The check must take into account rounding or truncation.
1536    --      (3)  The range of type I may not be exactly representable in F.
1537    --      (4)  For the rounding case, The end-points I'First - 0.5 and
1538    --           I'Last + 0.5 may or may not be in range, depending on the
1539    --           sign of  I'First and I'Last.
1540    --      (5)  X may be a NaN, which will fail any comparison
1541
1542    --  The following steps correctly convert X with rounding:
1543
1544    --      (1) If either I'First or I'Last is not known at compile time, use
1545    --          I'Base instead of I in the next three steps and perform a
1546    --          regular range check against I'Range after conversion.
1547    --      (2) If I'First - 0.5 is representable in F then let Lo be that
1548    --          value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1549    --          F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1550    --          In other words, take one of the closest floating-point numbers
1551    --          (which is an integer value) to I'First, and see if it is in
1552    --          range or not.
1553    --      (3) If I'Last + 0.5 is representable in F then let Hi be that value
1554    --          and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1555    --          F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1556    --      (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1557    --                     or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1558
1559    --  For the truncating case, replace steps (2) and (3) as follows:
1560    --      (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1561    --          be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1562    --          Lo_OK be True.
1563    --      (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1564    --          be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1565    --          Hi_OK be True.
1566
1567    procedure Apply_Float_Conversion_Check
1568      (Ck_Node    : Node_Id;
1569       Target_Typ : Entity_Id)
1570    is
1571       LB          : constant Node_Id    := Type_Low_Bound (Target_Typ);
1572       HB          : constant Node_Id    := Type_High_Bound (Target_Typ);
1573       Loc         : constant Source_Ptr := Sloc (Ck_Node);
1574       Expr_Type   : constant Entity_Id  := Base_Type (Etype (Ck_Node));
1575       Target_Base : constant Entity_Id  :=
1576                       Implementation_Base_Type (Target_Typ);
1577
1578       Par : constant Node_Id := Parent (Ck_Node);
1579       pragma Assert (Nkind (Par) = N_Type_Conversion);
1580       --  Parent of check node, must be a type conversion
1581
1582       Truncate  : constant Boolean := Float_Truncate (Par);
1583       Max_Bound : constant Uint :=
1584                     UI_Expon
1585                       (Machine_Radix_Value (Expr_Type),
1586                        Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1587
1588       --  Largest bound, so bound plus or minus half is a machine number of F
1589
1590       Ifirst, Ilast : Uint;
1591       --  Bounds of integer type
1592
1593       Lo, Hi : Ureal;
1594       --  Bounds to check in floating-point domain
1595
1596       Lo_OK, Hi_OK : Boolean;
1597       --  True iff Lo resp. Hi belongs to I'Range
1598
1599       Lo_Chk, Hi_Chk : Node_Id;
1600       --  Expressions that are False iff check fails
1601
1602       Reason : RT_Exception_Code;
1603
1604    begin
1605       if not Compile_Time_Known_Value (LB)
1606           or not Compile_Time_Known_Value (HB)
1607       then
1608          declare
1609             --  First check that the value falls in the range of the base type,
1610             --  to prevent overflow during conversion and then perform a
1611             --  regular range check against the (dynamic) bounds.
1612
1613             pragma Assert (Target_Base /= Target_Typ);
1614
1615             Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
1616
1617          begin
1618             Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1619             Set_Etype (Temp, Target_Base);
1620
1621             Insert_Action (Parent (Par),
1622               Make_Object_Declaration (Loc,
1623                 Defining_Identifier => Temp,
1624                 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1625                 Expression => New_Copy_Tree (Par)),
1626                 Suppress => All_Checks);
1627
1628             Insert_Action (Par,
1629               Make_Raise_Constraint_Error (Loc,
1630                 Condition =>
1631                   Make_Not_In (Loc,
1632                     Left_Opnd  => New_Occurrence_Of (Temp, Loc),
1633                     Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1634                 Reason => CE_Range_Check_Failed));
1635             Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1636
1637             return;
1638          end;
1639       end if;
1640
1641       --  Get the (static) bounds of the target type
1642
1643       Ifirst := Expr_Value (LB);
1644       Ilast  := Expr_Value (HB);
1645
1646       --  A simple optimization: if the expression is a universal literal,
1647       --  we can do the comparison with the bounds and the conversion to
1648       --  an integer type statically. The range checks are unchanged.
1649
1650       if Nkind (Ck_Node) = N_Real_Literal
1651         and then Etype (Ck_Node) = Universal_Real
1652         and then Is_Integer_Type (Target_Typ)
1653         and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
1654       then
1655          declare
1656             Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
1657
1658          begin
1659             if Int_Val <= Ilast and then Int_Val >= Ifirst then
1660
1661                --  Conversion is safe
1662
1663                Rewrite (Parent (Ck_Node),
1664                  Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
1665                Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
1666                return;
1667             end if;
1668          end;
1669       end if;
1670
1671       --  Check against lower bound
1672
1673       if Truncate and then Ifirst > 0 then
1674          Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1675          Lo_OK := False;
1676
1677       elsif Truncate then
1678          Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1679          Lo_OK := True;
1680
1681       elsif abs (Ifirst) < Max_Bound then
1682          Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1683          Lo_OK := (Ifirst > 0);
1684
1685       else
1686          Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1687          Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1688       end if;
1689
1690       if Lo_OK then
1691
1692          --  Lo_Chk := (X >= Lo)
1693
1694          Lo_Chk := Make_Op_Ge (Loc,
1695                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1696                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1697
1698       else
1699          --  Lo_Chk := (X > Lo)
1700
1701          Lo_Chk := Make_Op_Gt (Loc,
1702                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1703                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1704       end if;
1705
1706       --  Check against higher bound
1707
1708       if Truncate and then Ilast < 0 then
1709          Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1710          Hi_OK := False;
1711
1712       elsif Truncate then
1713          Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1714          Hi_OK := True;
1715
1716       elsif abs (Ilast) < Max_Bound then
1717          Hi := UR_From_Uint (Ilast) + Ureal_Half;
1718          Hi_OK := (Ilast < 0);
1719       else
1720          Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1721          Hi_OK := (Hi <= UR_From_Uint (Ilast));
1722       end if;
1723
1724       if Hi_OK then
1725
1726          --  Hi_Chk := (X <= Hi)
1727
1728          Hi_Chk := Make_Op_Le (Loc,
1729                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1730                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1731
1732       else
1733          --  Hi_Chk := (X < Hi)
1734
1735          Hi_Chk := Make_Op_Lt (Loc,
1736                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1737                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1738       end if;
1739
1740       --  If the bounds of the target type are the same as those of the base
1741       --  type, the check is an overflow check as a range check is not
1742       --  performed in these cases.
1743
1744       if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1745         and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1746       then
1747          Reason := CE_Overflow_Check_Failed;
1748       else
1749          Reason := CE_Range_Check_Failed;
1750       end if;
1751
1752       --  Raise CE if either conditions does not hold
1753
1754       Insert_Action (Ck_Node,
1755         Make_Raise_Constraint_Error (Loc,
1756           Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1757           Reason    => Reason));
1758    end Apply_Float_Conversion_Check;
1759
1760    ------------------------
1761    -- Apply_Length_Check --
1762    ------------------------
1763
1764    procedure Apply_Length_Check
1765      (Ck_Node    : Node_Id;
1766       Target_Typ : Entity_Id;
1767       Source_Typ : Entity_Id := Empty)
1768    is
1769    begin
1770       Apply_Selected_Length_Checks
1771         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1772    end Apply_Length_Check;
1773
1774    ---------------------------
1775    -- Apply_Predicate_Check --
1776    ---------------------------
1777
1778    procedure Apply_Predicate_Check (N : Node_Id; Typ : Entity_Id) is
1779    begin
1780       if Present (Predicate_Function (Typ)) then
1781          Insert_Action (N,
1782            Make_Predicate_Check (Typ, Duplicate_Subexpr (N)));
1783       end if;
1784    end Apply_Predicate_Check;
1785
1786    -----------------------
1787    -- Apply_Range_Check --
1788    -----------------------
1789
1790    procedure Apply_Range_Check
1791      (Ck_Node    : Node_Id;
1792       Target_Typ : Entity_Id;
1793       Source_Typ : Entity_Id := Empty)
1794    is
1795    begin
1796       Apply_Selected_Range_Checks
1797         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1798    end Apply_Range_Check;
1799
1800    ------------------------------
1801    -- Apply_Scalar_Range_Check --
1802    ------------------------------
1803
1804    --  Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1805    --  off if it is already set on.
1806
1807    procedure Apply_Scalar_Range_Check
1808      (Expr       : Node_Id;
1809       Target_Typ : Entity_Id;
1810       Source_Typ : Entity_Id := Empty;
1811       Fixed_Int  : Boolean   := False)
1812    is
1813       Parnt   : constant Node_Id := Parent (Expr);
1814       S_Typ   : Entity_Id;
1815       Arr     : Node_Id   := Empty;  -- initialize to prevent warning
1816       Arr_Typ : Entity_Id := Empty;  -- initialize to prevent warning
1817       OK      : Boolean;
1818
1819       Is_Subscr_Ref : Boolean;
1820       --  Set true if Expr is a subscript
1821
1822       Is_Unconstrained_Subscr_Ref : Boolean;
1823       --  Set true if Expr is a subscript of an unconstrained array. In this
1824       --  case we do not attempt to do an analysis of the value against the
1825       --  range of the subscript, since we don't know the actual subtype.
1826
1827       Int_Real : Boolean;
1828       --  Set to True if Expr should be regarded as a real value even though
1829       --  the type of Expr might be discrete.
1830
1831       procedure Bad_Value;
1832       --  Procedure called if value is determined to be out of range
1833
1834       ---------------
1835       -- Bad_Value --
1836       ---------------
1837
1838       procedure Bad_Value is
1839       begin
1840          Apply_Compile_Time_Constraint_Error
1841            (Expr, "value not in range of}?", CE_Range_Check_Failed,
1842             Ent => Target_Typ,
1843             Typ => Target_Typ);
1844       end Bad_Value;
1845
1846    --  Start of processing for Apply_Scalar_Range_Check
1847
1848    begin
1849       --  Return if check obviously not needed
1850
1851       if
1852          --  Not needed inside generic
1853
1854          Inside_A_Generic
1855
1856          --  Not needed if previous error
1857
1858          or else Target_Typ = Any_Type
1859          or else Nkind (Expr) = N_Error
1860
1861          --  Not needed for non-scalar type
1862
1863          or else not Is_Scalar_Type (Target_Typ)
1864
1865          --  Not needed if we know node raises CE already
1866
1867          or else Raises_Constraint_Error (Expr)
1868       then
1869          return;
1870       end if;
1871
1872       --  Now, see if checks are suppressed
1873
1874       Is_Subscr_Ref :=
1875         Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1876
1877       if Is_Subscr_Ref then
1878          Arr := Prefix (Parnt);
1879          Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1880
1881          if Is_Access_Type (Arr_Typ) then
1882             Arr_Typ := Designated_Type (Arr_Typ);
1883          end if;
1884       end if;
1885
1886       if not Do_Range_Check (Expr) then
1887
1888          --  Subscript reference. Check for Index_Checks suppressed
1889
1890          if Is_Subscr_Ref then
1891
1892             --  Check array type and its base type
1893
1894             if Index_Checks_Suppressed (Arr_Typ)
1895               or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1896             then
1897                return;
1898
1899             --  Check array itself if it is an entity name
1900
1901             elsif Is_Entity_Name (Arr)
1902               and then Index_Checks_Suppressed (Entity (Arr))
1903             then
1904                return;
1905
1906             --  Check expression itself if it is an entity name
1907
1908             elsif Is_Entity_Name (Expr)
1909               and then Index_Checks_Suppressed (Entity (Expr))
1910             then
1911                return;
1912             end if;
1913
1914          --  All other cases, check for Range_Checks suppressed
1915
1916          else
1917             --  Check target type and its base type
1918
1919             if Range_Checks_Suppressed (Target_Typ)
1920               or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1921             then
1922                return;
1923
1924             --  Check expression itself if it is an entity name
1925
1926             elsif Is_Entity_Name (Expr)
1927               and then Range_Checks_Suppressed (Entity (Expr))
1928             then
1929                return;
1930
1931             --  If Expr is part of an assignment statement, then check left
1932             --  side of assignment if it is an entity name.
1933
1934             elsif Nkind (Parnt) = N_Assignment_Statement
1935               and then Is_Entity_Name (Name (Parnt))
1936               and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1937             then
1938                return;
1939             end if;
1940          end if;
1941       end if;
1942
1943       --  Do not set range checks if they are killed
1944
1945       if Nkind (Expr) = N_Unchecked_Type_Conversion
1946         and then Kill_Range_Check (Expr)
1947       then
1948          return;
1949       end if;
1950
1951       --  Do not set range checks for any values from System.Scalar_Values
1952       --  since the whole idea of such values is to avoid checking them!
1953
1954       if Is_Entity_Name (Expr)
1955         and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1956       then
1957          return;
1958       end if;
1959
1960       --  Now see if we need a check
1961
1962       if No (Source_Typ) then
1963          S_Typ := Etype (Expr);
1964       else
1965          S_Typ := Source_Typ;
1966       end if;
1967
1968       if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1969          return;
1970       end if;
1971
1972       Is_Unconstrained_Subscr_Ref :=
1973         Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1974
1975       --  Always do a range check if the source type includes infinities and
1976       --  the target type does not include infinities. We do not do this if
1977       --  range checks are killed.
1978
1979       if Is_Floating_Point_Type (S_Typ)
1980         and then Has_Infinities (S_Typ)
1981         and then not Has_Infinities (Target_Typ)
1982       then
1983          Enable_Range_Check (Expr);
1984       end if;
1985
1986       --  Return if we know expression is definitely in the range of the target
1987       --  type as determined by Determine_Range. Right now we only do this for
1988       --  discrete types, and not fixed-point or floating-point types.
1989
1990       --  The additional less-precise tests below catch these cases
1991
1992       --  Note: skip this if we are given a source_typ, since the point of
1993       --  supplying a Source_Typ is to stop us looking at the expression.
1994       --  We could sharpen this test to be out parameters only ???
1995
1996       if Is_Discrete_Type (Target_Typ)
1997         and then Is_Discrete_Type (Etype (Expr))
1998         and then not Is_Unconstrained_Subscr_Ref
1999         and then No (Source_Typ)
2000       then
2001          declare
2002             Tlo : constant Node_Id := Type_Low_Bound  (Target_Typ);
2003             Thi : constant Node_Id := Type_High_Bound (Target_Typ);
2004             Lo  : Uint;
2005             Hi  : Uint;
2006
2007          begin
2008             if Compile_Time_Known_Value (Tlo)
2009               and then Compile_Time_Known_Value (Thi)
2010             then
2011                declare
2012                   Lov : constant Uint := Expr_Value (Tlo);
2013                   Hiv : constant Uint := Expr_Value (Thi);
2014
2015                begin
2016                   --  If range is null, we for sure have a constraint error
2017                   --  (we don't even need to look at the value involved,
2018                   --  since all possible values will raise CE).
2019
2020                   if Lov > Hiv then
2021                      Bad_Value;
2022                      return;
2023                   end if;
2024
2025                   --  Otherwise determine range of value
2026
2027                   Determine_Range (Expr, OK, Lo, Hi, Assume_Valid => True);
2028
2029                   if OK then
2030
2031                      --  If definitely in range, all OK
2032
2033                      if Lo >= Lov and then Hi <= Hiv then
2034                         return;
2035
2036                      --  If definitely not in range, warn
2037
2038                      elsif Lov > Hi or else Hiv < Lo then
2039                         Bad_Value;
2040                         return;
2041
2042                      --  Otherwise we don't know
2043
2044                      else
2045                         null;
2046                      end if;
2047                   end if;
2048                end;
2049             end if;
2050          end;
2051       end if;
2052
2053       Int_Real :=
2054         Is_Floating_Point_Type (S_Typ)
2055           or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2056
2057       --  Check if we can determine at compile time whether Expr is in the
2058       --  range of the target type. Note that if S_Typ is within the bounds
2059       --  of Target_Typ then this must be the case. This check is meaningful
2060       --  only if this is not a conversion between integer and real types.
2061
2062       if not Is_Unconstrained_Subscr_Ref
2063         and then
2064            Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2065         and then
2066           (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2067              or else
2068                Is_In_Range (Expr, Target_Typ,
2069                             Assume_Valid => True,
2070                             Fixed_Int => Fixed_Int,
2071                             Int_Real  => Int_Real))
2072       then
2073          return;
2074
2075       elsif Is_Out_Of_Range (Expr, Target_Typ,
2076                              Assume_Valid => True,
2077                              Fixed_Int    => Fixed_Int,
2078                              Int_Real     => Int_Real)
2079       then
2080          Bad_Value;
2081          return;
2082
2083       --  In the floating-point case, we only do range checks if the type is
2084       --  constrained. We definitely do NOT want range checks for unconstrained
2085       --  types, since we want to have infinities
2086
2087       elsif Is_Floating_Point_Type (S_Typ) then
2088          if Is_Constrained (S_Typ) then
2089             Enable_Range_Check (Expr);
2090          end if;
2091
2092       --  For all other cases we enable a range check unconditionally
2093
2094       else
2095          Enable_Range_Check (Expr);
2096          return;
2097       end if;
2098    end Apply_Scalar_Range_Check;
2099
2100    ----------------------------------
2101    -- Apply_Selected_Length_Checks --
2102    ----------------------------------
2103
2104    procedure Apply_Selected_Length_Checks
2105      (Ck_Node    : Node_Id;
2106       Target_Typ : Entity_Id;
2107       Source_Typ : Entity_Id;
2108       Do_Static  : Boolean)
2109    is
2110       Cond     : Node_Id;
2111       R_Result : Check_Result;
2112       R_Cno    : Node_Id;
2113
2114       Loc         : constant Source_Ptr := Sloc (Ck_Node);
2115       Checks_On   : constant Boolean :=
2116                       (not Index_Checks_Suppressed (Target_Typ))
2117                         or else
2118                       (not Length_Checks_Suppressed (Target_Typ));
2119
2120    begin
2121       if not Full_Expander_Active then
2122          return;
2123       end if;
2124
2125       R_Result :=
2126         Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2127
2128       for J in 1 .. 2 loop
2129          R_Cno := R_Result (J);
2130          exit when No (R_Cno);
2131
2132          --  A length check may mention an Itype which is attached to a
2133          --  subsequent node. At the top level in a package this can cause
2134          --  an order-of-elaboration problem, so we make sure that the itype
2135          --  is referenced now.
2136
2137          if Ekind (Current_Scope) = E_Package
2138            and then Is_Compilation_Unit (Current_Scope)
2139          then
2140             Ensure_Defined (Target_Typ, Ck_Node);
2141
2142             if Present (Source_Typ) then
2143                Ensure_Defined (Source_Typ, Ck_Node);
2144
2145             elsif Is_Itype (Etype (Ck_Node)) then
2146                Ensure_Defined (Etype (Ck_Node), Ck_Node);
2147             end if;
2148          end if;
2149
2150          --  If the item is a conditional raise of constraint error, then have
2151          --  a look at what check is being performed and ???
2152
2153          if Nkind (R_Cno) = N_Raise_Constraint_Error
2154            and then Present (Condition (R_Cno))
2155          then
2156             Cond := Condition (R_Cno);
2157
2158             --  Case where node does not now have a dynamic check
2159
2160             if not Has_Dynamic_Length_Check (Ck_Node) then
2161
2162                --  If checks are on, just insert the check
2163
2164                if Checks_On then
2165                   Insert_Action (Ck_Node, R_Cno);
2166
2167                   if not Do_Static then
2168                      Set_Has_Dynamic_Length_Check (Ck_Node);
2169                   end if;
2170
2171                --  If checks are off, then analyze the length check after
2172                --  temporarily attaching it to the tree in case the relevant
2173                --  condition can be evaluated at compile time. We still want a
2174                --  compile time warning in this case.
2175
2176                else
2177                   Set_Parent (R_Cno, Ck_Node);
2178                   Analyze (R_Cno);
2179                end if;
2180             end if;
2181
2182             --  Output a warning if the condition is known to be True
2183
2184             if Is_Entity_Name (Cond)
2185               and then Entity (Cond) = Standard_True
2186             then
2187                Apply_Compile_Time_Constraint_Error
2188                  (Ck_Node, "wrong length for array of}?",
2189                   CE_Length_Check_Failed,
2190                   Ent => Target_Typ,
2191                   Typ => Target_Typ);
2192
2193             --  If we were only doing a static check, or if checks are not
2194             --  on, then we want to delete the check, since it is not needed.
2195             --  We do this by replacing the if statement by a null statement
2196
2197             elsif Do_Static or else not Checks_On then
2198                Remove_Warning_Messages (R_Cno);
2199                Rewrite (R_Cno, Make_Null_Statement (Loc));
2200             end if;
2201
2202          else
2203             Install_Static_Check (R_Cno, Loc);
2204          end if;
2205       end loop;
2206    end Apply_Selected_Length_Checks;
2207
2208    ---------------------------------
2209    -- Apply_Selected_Range_Checks --
2210    ---------------------------------
2211
2212    procedure Apply_Selected_Range_Checks
2213      (Ck_Node    : Node_Id;
2214       Target_Typ : Entity_Id;
2215       Source_Typ : Entity_Id;
2216       Do_Static  : Boolean)
2217    is
2218       Cond     : Node_Id;
2219       R_Result : Check_Result;
2220       R_Cno    : Node_Id;
2221
2222       Loc       : constant Source_Ptr := Sloc (Ck_Node);
2223       Checks_On : constant Boolean :=
2224                     (not Index_Checks_Suppressed (Target_Typ))
2225                       or else
2226                     (not Range_Checks_Suppressed (Target_Typ));
2227
2228    begin
2229       if not Full_Expander_Active or else not Checks_On then
2230          return;
2231       end if;
2232
2233       R_Result :=
2234         Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2235
2236       for J in 1 .. 2 loop
2237
2238          R_Cno := R_Result (J);
2239          exit when No (R_Cno);
2240
2241          --  If the item is a conditional raise of constraint error, then have
2242          --  a look at what check is being performed and ???
2243
2244          if Nkind (R_Cno) = N_Raise_Constraint_Error
2245            and then Present (Condition (R_Cno))
2246          then
2247             Cond := Condition (R_Cno);
2248
2249             if not Has_Dynamic_Range_Check (Ck_Node) then
2250                Insert_Action (Ck_Node, R_Cno);
2251
2252                if not Do_Static then
2253                   Set_Has_Dynamic_Range_Check (Ck_Node);
2254                end if;
2255             end if;
2256
2257             --  Output a warning if the condition is known to be True
2258
2259             if Is_Entity_Name (Cond)
2260               and then Entity (Cond) = Standard_True
2261             then
2262                --  Since an N_Range is technically not an expression, we have
2263                --  to set one of the bounds to C_E and then just flag the
2264                --  N_Range. The warning message will point to the lower bound
2265                --  and complain about a range, which seems OK.
2266
2267                if Nkind (Ck_Node) = N_Range then
2268                   Apply_Compile_Time_Constraint_Error
2269                     (Low_Bound (Ck_Node), "static range out of bounds of}?",
2270                      CE_Range_Check_Failed,
2271                      Ent => Target_Typ,
2272                      Typ => Target_Typ);
2273
2274                   Set_Raises_Constraint_Error (Ck_Node);
2275
2276                else
2277                   Apply_Compile_Time_Constraint_Error
2278                     (Ck_Node, "static value out of range of}?",
2279                      CE_Range_Check_Failed,
2280                      Ent => Target_Typ,
2281                      Typ => Target_Typ);
2282                end if;
2283
2284             --  If we were only doing a static check, or if checks are not
2285             --  on, then we want to delete the check, since it is not needed.
2286             --  We do this by replacing the if statement by a null statement
2287
2288             elsif Do_Static or else not Checks_On then
2289                Remove_Warning_Messages (R_Cno);
2290                Rewrite (R_Cno, Make_Null_Statement (Loc));
2291             end if;
2292
2293          else
2294             Install_Static_Check (R_Cno, Loc);
2295          end if;
2296       end loop;
2297    end Apply_Selected_Range_Checks;
2298
2299    -------------------------------
2300    -- Apply_Static_Length_Check --
2301    -------------------------------
2302
2303    procedure Apply_Static_Length_Check
2304      (Expr       : Node_Id;
2305       Target_Typ : Entity_Id;
2306       Source_Typ : Entity_Id := Empty)
2307    is
2308    begin
2309       Apply_Selected_Length_Checks
2310         (Expr, Target_Typ, Source_Typ, Do_Static => True);
2311    end Apply_Static_Length_Check;
2312
2313    -------------------------------------
2314    -- Apply_Subscript_Validity_Checks --
2315    -------------------------------------
2316
2317    procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2318       Sub : Node_Id;
2319
2320    begin
2321       pragma Assert (Nkind (Expr) = N_Indexed_Component);
2322
2323       --  Loop through subscripts
2324
2325       Sub := First (Expressions (Expr));
2326       while Present (Sub) loop
2327
2328          --  Check one subscript. Note that we do not worry about enumeration
2329          --  type with holes, since we will convert the value to a Pos value
2330          --  for the subscript, and that convert will do the necessary validity
2331          --  check.
2332
2333          Ensure_Valid (Sub, Holes_OK => True);
2334
2335          --  Move to next subscript
2336
2337          Sub := Next (Sub);
2338       end loop;
2339    end Apply_Subscript_Validity_Checks;
2340
2341    ----------------------------------
2342    -- Apply_Type_Conversion_Checks --
2343    ----------------------------------
2344
2345    procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2346       Target_Type : constant Entity_Id := Etype (N);
2347       Target_Base : constant Entity_Id := Base_Type (Target_Type);
2348       Expr        : constant Node_Id   := Expression (N);
2349
2350       Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
2351       --  Note: if Etype (Expr) is a private type without discriminants, its
2352       --  full view might have discriminants with defaults, so we need the
2353       --  full view here to retrieve the constraints.
2354
2355    begin
2356       if Inside_A_Generic then
2357          return;
2358
2359       --  Skip these checks if serious errors detected, there are some nasty
2360       --  situations of incomplete trees that blow things up.
2361
2362       elsif Serious_Errors_Detected > 0 then
2363          return;
2364
2365       --  Scalar type conversions of the form Target_Type (Expr) require a
2366       --  range check if we cannot be sure that Expr is in the base type of
2367       --  Target_Typ and also that Expr is in the range of Target_Typ. These
2368       --  are not quite the same condition from an implementation point of
2369       --  view, but clearly the second includes the first.
2370
2371       elsif Is_Scalar_Type (Target_Type) then
2372          declare
2373             Conv_OK  : constant Boolean := Conversion_OK (N);
2374             --  If the Conversion_OK flag on the type conversion is set and no
2375             --  floating point type is involved in the type conversion then
2376             --  fixed point values must be read as integral values.
2377
2378             Float_To_Int : constant Boolean :=
2379                              Is_Floating_Point_Type (Expr_Type)
2380                                and then Is_Integer_Type (Target_Type);
2381
2382          begin
2383             if not Overflow_Checks_Suppressed (Target_Base)
2384               and then not
2385                 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
2386               and then not Float_To_Int
2387             then
2388                Activate_Overflow_Check (N);
2389             end if;
2390
2391             if not Range_Checks_Suppressed (Target_Type)
2392               and then not Range_Checks_Suppressed (Expr_Type)
2393             then
2394                if Float_To_Int then
2395                   Apply_Float_Conversion_Check (Expr, Target_Type);
2396                else
2397                   Apply_Scalar_Range_Check
2398                     (Expr, Target_Type, Fixed_Int => Conv_OK);
2399                end if;
2400             end if;
2401          end;
2402
2403       elsif Comes_From_Source (N)
2404         and then not Discriminant_Checks_Suppressed (Target_Type)
2405         and then Is_Record_Type (Target_Type)
2406         and then Is_Derived_Type (Target_Type)
2407         and then not Is_Tagged_Type (Target_Type)
2408         and then not Is_Constrained (Target_Type)
2409         and then Present (Stored_Constraint (Target_Type))
2410       then
2411          --  An unconstrained derived type may have inherited discriminant.
2412          --  Build an actual discriminant constraint list using the stored
2413          --  constraint, to verify that the expression of the parent type
2414          --  satisfies the constraints imposed by the (unconstrained!)
2415          --  derived type. This applies to value conversions, not to view
2416          --  conversions of tagged types.
2417
2418          declare
2419             Loc         : constant Source_Ptr := Sloc (N);
2420             Cond        : Node_Id;
2421             Constraint  : Elmt_Id;
2422             Discr_Value : Node_Id;
2423             Discr       : Entity_Id;
2424
2425             New_Constraints : constant Elist_Id := New_Elmt_List;
2426             Old_Constraints : constant Elist_Id :=
2427                                 Discriminant_Constraint (Expr_Type);
2428
2429          begin
2430             Constraint := First_Elmt (Stored_Constraint (Target_Type));
2431             while Present (Constraint) loop
2432                Discr_Value := Node (Constraint);
2433
2434                if Is_Entity_Name (Discr_Value)
2435                  and then Ekind (Entity (Discr_Value)) = E_Discriminant
2436                then
2437                   Discr := Corresponding_Discriminant (Entity (Discr_Value));
2438
2439                   if Present (Discr)
2440                     and then Scope (Discr) = Base_Type (Expr_Type)
2441                   then
2442                      --  Parent is constrained by new discriminant. Obtain
2443                      --  Value of original discriminant in expression. If the
2444                      --  new discriminant has been used to constrain more than
2445                      --  one of the stored discriminants, this will provide the
2446                      --  required consistency check.
2447
2448                      Append_Elmt
2449                        (Make_Selected_Component (Loc,
2450                           Prefix        =>
2451                             Duplicate_Subexpr_No_Checks
2452                               (Expr, Name_Req => True),
2453                           Selector_Name =>
2454                             Make_Identifier (Loc, Chars (Discr))),
2455                         New_Constraints);
2456
2457                   else
2458                      --  Discriminant of more remote ancestor ???
2459
2460                      return;
2461                   end if;
2462
2463                --  Derived type definition has an explicit value for this
2464                --  stored discriminant.
2465
2466                else
2467                   Append_Elmt
2468                     (Duplicate_Subexpr_No_Checks (Discr_Value),
2469                      New_Constraints);
2470                end if;
2471
2472                Next_Elmt (Constraint);
2473             end loop;
2474
2475             --  Use the unconstrained expression type to retrieve the
2476             --  discriminants of the parent, and apply momentarily the
2477             --  discriminant constraint synthesized above.
2478
2479             Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2480             Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2481             Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2482
2483             Insert_Action (N,
2484               Make_Raise_Constraint_Error (Loc,
2485                 Condition => Cond,
2486                 Reason    => CE_Discriminant_Check_Failed));
2487          end;
2488
2489       --  For arrays, conversions are applied during expansion, to take into
2490       --  accounts changes of representation. The checks become range checks on
2491       --  the base type or length checks on the subtype, depending on whether
2492       --  the target type is unconstrained or constrained.
2493
2494       else
2495          null;
2496       end if;
2497    end Apply_Type_Conversion_Checks;
2498
2499    ----------------------------------------------
2500    -- Apply_Universal_Integer_Attribute_Checks --
2501    ----------------------------------------------
2502
2503    procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2504       Loc : constant Source_Ptr := Sloc (N);
2505       Typ : constant Entity_Id  := Etype (N);
2506
2507    begin
2508       if Inside_A_Generic then
2509          return;
2510
2511       --  Nothing to do if checks are suppressed
2512
2513       elsif Range_Checks_Suppressed (Typ)
2514         and then Overflow_Checks_Suppressed (Typ)
2515       then
2516          return;
2517
2518       --  Nothing to do if the attribute does not come from source. The
2519       --  internal attributes we generate of this type do not need checks,
2520       --  and furthermore the attempt to check them causes some circular
2521       --  elaboration orders when dealing with packed types.
2522
2523       elsif not Comes_From_Source (N) then
2524          return;
2525
2526       --  If the prefix is a selected component that depends on a discriminant
2527       --  the check may improperly expose a discriminant instead of using
2528       --  the bounds of the object itself. Set the type of the attribute to
2529       --  the base type of the context, so that a check will be imposed when
2530       --  needed (e.g. if the node appears as an index).
2531
2532       elsif Nkind (Prefix (N)) = N_Selected_Component
2533         and then Ekind (Typ) = E_Signed_Integer_Subtype
2534         and then Depends_On_Discriminant (Scalar_Range (Typ))
2535       then
2536          Set_Etype (N, Base_Type (Typ));
2537
2538       --  Otherwise, replace the attribute node with a type conversion node
2539       --  whose expression is the attribute, retyped to universal integer, and
2540       --  whose subtype mark is the target type. The call to analyze this
2541       --  conversion will set range and overflow checks as required for proper
2542       --  detection of an out of range value.
2543
2544       else
2545          Set_Etype    (N, Universal_Integer);
2546          Set_Analyzed (N, True);
2547
2548          Rewrite (N,
2549            Make_Type_Conversion (Loc,
2550              Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2551              Expression   => Relocate_Node (N)));
2552
2553          Analyze_And_Resolve (N, Typ);
2554          return;
2555       end if;
2556    end Apply_Universal_Integer_Attribute_Checks;
2557
2558    -------------------------------------
2559    -- Atomic_Synchronization_Disabled --
2560    -------------------------------------
2561
2562    --  Note: internally Disable/Enable_Atomic_Synchronization is implemented
2563    --  using a bogus check called Atomic_Synchronization. This is to make it
2564    --  more convenient to get exactly the same semantics as [Un]Suppress.
2565
2566    function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
2567    begin
2568       --  If debug flag d.e is set, always return False, i.e. all atomic sync
2569       --  looks enabled, since it is never disabled.
2570
2571       if Debug_Flag_Dot_E then
2572          return False;
2573
2574       --  If debug flag d.d is set then always return True, i.e. all atomic
2575       --  sync looks disabled, since it always tests True.
2576
2577       elsif Debug_Flag_Dot_D then
2578          return True;
2579
2580       --  If entity present, then check result for that entity
2581
2582       elsif Present (E) and then Checks_May_Be_Suppressed (E) then
2583          return Is_Check_Suppressed (E, Atomic_Synchronization);
2584
2585       --  Otherwise result depends on current scope setting
2586
2587       else
2588          return Scope_Suppress (Atomic_Synchronization);
2589       end if;
2590    end Atomic_Synchronization_Disabled;
2591
2592    -------------------------------
2593    -- Build_Discriminant_Checks --
2594    -------------------------------
2595
2596    function Build_Discriminant_Checks
2597      (N     : Node_Id;
2598       T_Typ : Entity_Id) return Node_Id
2599    is
2600       Loc      : constant Source_Ptr := Sloc (N);
2601       Cond     : Node_Id;
2602       Disc     : Elmt_Id;
2603       Disc_Ent : Entity_Id;
2604       Dref     : Node_Id;
2605       Dval     : Node_Id;
2606
2607       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2608
2609       ----------------------------------
2610       -- Aggregate_Discriminant_Value --
2611       ----------------------------------
2612
2613       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2614          Assoc : Node_Id;
2615
2616       begin
2617          --  The aggregate has been normalized with named associations. We use
2618          --  the Chars field to locate the discriminant to take into account
2619          --  discriminants in derived types, which carry the same name as those
2620          --  in the parent.
2621
2622          Assoc := First (Component_Associations (N));
2623          while Present (Assoc) loop
2624             if Chars (First (Choices (Assoc))) = Chars (Disc) then
2625                return Expression (Assoc);
2626             else
2627                Next (Assoc);
2628             end if;
2629          end loop;
2630
2631          --  Discriminant must have been found in the loop above
2632
2633          raise Program_Error;
2634       end Aggregate_Discriminant_Val;
2635
2636    --  Start of processing for Build_Discriminant_Checks
2637
2638    begin
2639       --  Loop through discriminants evolving the condition
2640
2641       Cond := Empty;
2642       Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2643
2644       --  For a fully private type, use the discriminants of the parent type
2645
2646       if Is_Private_Type (T_Typ)
2647         and then No (Full_View (T_Typ))
2648       then
2649          Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2650       else
2651          Disc_Ent := First_Discriminant (T_Typ);
2652       end if;
2653
2654       while Present (Disc) loop
2655          Dval := Node (Disc);
2656
2657          if Nkind (Dval) = N_Identifier
2658            and then Ekind (Entity (Dval)) = E_Discriminant
2659          then
2660             Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2661          else
2662             Dval := Duplicate_Subexpr_No_Checks (Dval);
2663          end if;
2664
2665          --  If we have an Unchecked_Union node, we can infer the discriminants
2666          --  of the node.
2667
2668          if Is_Unchecked_Union (Base_Type (T_Typ)) then
2669             Dref := New_Copy (
2670               Get_Discriminant_Value (
2671                 First_Discriminant (T_Typ),
2672                 T_Typ,
2673                 Stored_Constraint (T_Typ)));
2674
2675          elsif Nkind (N) = N_Aggregate then
2676             Dref :=
2677                Duplicate_Subexpr_No_Checks
2678                  (Aggregate_Discriminant_Val (Disc_Ent));
2679
2680          else
2681             Dref :=
2682               Make_Selected_Component (Loc,
2683                 Prefix =>
2684                   Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2685                 Selector_Name =>
2686                   Make_Identifier (Loc, Chars (Disc_Ent)));
2687
2688             Set_Is_In_Discriminant_Check (Dref);
2689          end if;
2690
2691          Evolve_Or_Else (Cond,
2692            Make_Op_Ne (Loc,
2693              Left_Opnd => Dref,
2694              Right_Opnd => Dval));
2695
2696          Next_Elmt (Disc);
2697          Next_Discriminant (Disc_Ent);
2698       end loop;
2699
2700       return Cond;
2701    end Build_Discriminant_Checks;
2702
2703    ------------------
2704    -- Check_Needed --
2705    ------------------
2706
2707    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2708       N : Node_Id;
2709       P : Node_Id;
2710       K : Node_Kind;
2711       L : Node_Id;
2712       R : Node_Id;
2713
2714    begin
2715       --  Always check if not simple entity
2716
2717       if Nkind (Nod) not in N_Has_Entity
2718         or else not Comes_From_Source (Nod)
2719       then
2720          return True;
2721       end if;
2722
2723       --  Look up tree for short circuit
2724
2725       N := Nod;
2726       loop
2727          P := Parent (N);
2728          K := Nkind (P);
2729
2730          --  Done if out of subexpression (note that we allow generated stuff
2731          --  such as itype declarations in this context, to keep the loop going
2732          --  since we may well have generated such stuff in complex situations.
2733          --  Also done if no parent (probably an error condition, but no point
2734          --  in behaving nasty if we find it!)
2735
2736          if No (P)
2737            or else (K not in N_Subexpr and then Comes_From_Source (P))
2738          then
2739             return True;
2740
2741          --  Or/Or Else case, where test is part of the right operand, or is
2742          --  part of one of the actions associated with the right operand, and
2743          --  the left operand is an equality test.
2744
2745          elsif K = N_Op_Or then
2746             exit when N = Right_Opnd (P)
2747               and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2748
2749          elsif K = N_Or_Else then
2750             exit when (N = Right_Opnd (P)
2751                         or else
2752                           (Is_List_Member (N)
2753                              and then List_Containing (N) = Actions (P)))
2754               and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2755
2756          --  Similar test for the And/And then case, where the left operand
2757          --  is an inequality test.
2758
2759          elsif K = N_Op_And then
2760             exit when N = Right_Opnd (P)
2761               and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2762
2763          elsif K = N_And_Then then
2764             exit when (N = Right_Opnd (P)
2765                         or else
2766                           (Is_List_Member (N)
2767                              and then List_Containing (N) = Actions (P)))
2768               and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2769          end if;
2770
2771          N := P;
2772       end loop;
2773
2774       --  If we fall through the loop, then we have a conditional with an
2775       --  appropriate test as its left operand. So test further.
2776
2777       L := Left_Opnd (P);
2778       R := Right_Opnd (L);
2779       L := Left_Opnd (L);
2780
2781       --  Left operand of test must match original variable
2782
2783       if Nkind (L) not in N_Has_Entity
2784         or else Entity (L) /= Entity (Nod)
2785       then
2786          return True;
2787       end if;
2788
2789       --  Right operand of test must be key value (zero or null)
2790
2791       case Check is
2792          when Access_Check =>
2793             if not Known_Null (R) then
2794                return True;
2795             end if;
2796
2797          when Division_Check =>
2798             if not Compile_Time_Known_Value (R)
2799               or else Expr_Value (R) /= Uint_0
2800             then
2801                return True;
2802             end if;
2803
2804          when others =>
2805             raise Program_Error;
2806       end case;
2807
2808       --  Here we have the optimizable case, warn if not short-circuited
2809
2810       if K = N_Op_And or else K = N_Op_Or then
2811          case Check is
2812             when Access_Check =>
2813                Error_Msg_N
2814                  ("Constraint_Error may be raised (access check)?",
2815                   Parent (Nod));
2816             when Division_Check =>
2817                Error_Msg_N
2818                  ("Constraint_Error may be raised (zero divide)?",
2819                   Parent (Nod));
2820
2821             when others =>
2822                raise Program_Error;
2823          end case;
2824
2825          if K = N_Op_And then
2826             Error_Msg_N -- CODEFIX
2827               ("use `AND THEN` instead of AND?", P);
2828          else
2829             Error_Msg_N -- CODEFIX
2830               ("use `OR ELSE` instead of OR?", P);
2831          end if;
2832
2833          --  If not short-circuited, we need the check
2834
2835          return True;
2836
2837       --  If short-circuited, we can omit the check
2838
2839       else
2840          return False;
2841       end if;
2842    end Check_Needed;
2843
2844    -----------------------------------
2845    -- Check_Valid_Lvalue_Subscripts --
2846    -----------------------------------
2847
2848    procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2849    begin
2850       --  Skip this if range checks are suppressed
2851
2852       if Range_Checks_Suppressed (Etype (Expr)) then
2853          return;
2854
2855       --  Only do this check for expressions that come from source. We assume
2856       --  that expander generated assignments explicitly include any necessary
2857       --  checks. Note that this is not just an optimization, it avoids
2858       --  infinite recursions!
2859
2860       elsif not Comes_From_Source (Expr) then
2861          return;
2862
2863       --  For a selected component, check the prefix
2864
2865       elsif Nkind (Expr) = N_Selected_Component then
2866          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2867          return;
2868
2869       --  Case of indexed component
2870
2871       elsif Nkind (Expr) = N_Indexed_Component then
2872          Apply_Subscript_Validity_Checks (Expr);
2873
2874          --  Prefix may itself be or contain an indexed component, and these
2875          --  subscripts need checking as well.
2876
2877          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2878       end if;
2879    end Check_Valid_Lvalue_Subscripts;
2880
2881    ----------------------------------
2882    -- Null_Exclusion_Static_Checks --
2883    ----------------------------------
2884
2885    procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2886       Error_Node : Node_Id;
2887       Expr       : Node_Id;
2888       Has_Null   : constant Boolean := Has_Null_Exclusion (N);
2889       K          : constant Node_Kind := Nkind (N);
2890       Typ        : Entity_Id;
2891
2892    begin
2893       pragma Assert
2894         (K = N_Component_Declaration
2895            or else K = N_Discriminant_Specification
2896            or else K = N_Function_Specification
2897            or else K = N_Object_Declaration
2898            or else K = N_Parameter_Specification);
2899
2900       if K = N_Function_Specification then
2901          Typ := Etype (Defining_Entity (N));
2902       else
2903          Typ := Etype (Defining_Identifier (N));
2904       end if;
2905
2906       case K is
2907          when N_Component_Declaration =>
2908             if Present (Access_Definition (Component_Definition (N))) then
2909                Error_Node := Component_Definition (N);
2910             else
2911                Error_Node := Subtype_Indication (Component_Definition (N));
2912             end if;
2913
2914          when N_Discriminant_Specification =>
2915             Error_Node    := Discriminant_Type (N);
2916
2917          when N_Function_Specification =>
2918             Error_Node    := Result_Definition (N);
2919
2920          when N_Object_Declaration =>
2921             Error_Node    := Object_Definition (N);
2922
2923          when N_Parameter_Specification =>
2924             Error_Node    := Parameter_Type (N);
2925
2926          when others =>
2927             raise Program_Error;
2928       end case;
2929
2930       if Has_Null then
2931
2932          --  Enforce legality rule 3.10 (13): A null exclusion can only be
2933          --  applied to an access [sub]type.
2934
2935          if not Is_Access_Type (Typ) then
2936             Error_Msg_N
2937               ("`NOT NULL` allowed only for an access type", Error_Node);
2938
2939          --  Enforce legality rule RM 3.10(14/1): A null exclusion can only
2940          --  be applied to a [sub]type that does not exclude null already.
2941
2942          elsif Can_Never_Be_Null (Typ)
2943            and then Comes_From_Source (Typ)
2944          then
2945             Error_Msg_NE
2946               ("`NOT NULL` not allowed (& already excludes null)",
2947                Error_Node, Typ);
2948          end if;
2949       end if;
2950
2951       --  Check that null-excluding objects are always initialized, except for
2952       --  deferred constants, for which the expression will appear in the full
2953       --  declaration.
2954
2955       if K = N_Object_Declaration
2956         and then No (Expression (N))
2957         and then not Constant_Present (N)
2958         and then not No_Initialization (N)
2959       then
2960          --  Add an expression that assigns null. This node is needed by
2961          --  Apply_Compile_Time_Constraint_Error, which will replace this with
2962          --  a Constraint_Error node.
2963
2964          Set_Expression (N, Make_Null (Sloc (N)));
2965          Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2966
2967          Apply_Compile_Time_Constraint_Error
2968            (N      => Expression (N),
2969             Msg    => "(Ada 2005) null-excluding objects must be initialized?",
2970             Reason => CE_Null_Not_Allowed);
2971       end if;
2972
2973       --  Check that a null-excluding component, formal or object is not being
2974       --  assigned a null value. Otherwise generate a warning message and
2975       --  replace Expression (N) by an N_Constraint_Error node.
2976
2977       if K /= N_Function_Specification then
2978          Expr := Expression (N);
2979
2980          if Present (Expr) and then Known_Null (Expr) then
2981             case K is
2982                when N_Component_Declaration      |
2983                     N_Discriminant_Specification =>
2984                   Apply_Compile_Time_Constraint_Error
2985                     (N      => Expr,
2986                      Msg    => "(Ada 2005) null not allowed " &
2987                                "in null-excluding components?",
2988                      Reason => CE_Null_Not_Allowed);
2989
2990                when N_Object_Declaration =>
2991                   Apply_Compile_Time_Constraint_Error
2992                     (N      => Expr,
2993                      Msg    => "(Ada 2005) null not allowed " &
2994                                "in null-excluding objects?",
2995                      Reason => CE_Null_Not_Allowed);
2996
2997                when N_Parameter_Specification =>
2998                   Apply_Compile_Time_Constraint_Error
2999                     (N      => Expr,
3000                      Msg    => "(Ada 2005) null not allowed " &
3001                                "in null-excluding formals?",
3002                      Reason => CE_Null_Not_Allowed);
3003
3004                when others =>
3005                   null;
3006             end case;
3007          end if;
3008       end if;
3009    end Null_Exclusion_Static_Checks;
3010
3011    ----------------------------------
3012    -- Conditional_Statements_Begin --
3013    ----------------------------------
3014
3015    procedure Conditional_Statements_Begin is
3016    begin
3017       Saved_Checks_TOS := Saved_Checks_TOS + 1;
3018
3019       --  If stack overflows, kill all checks, that way we know to simply reset
3020       --  the number of saved checks to zero on return. This should never occur
3021       --  in practice.
3022
3023       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
3024          Kill_All_Checks;
3025
3026       --  In the normal case, we just make a new stack entry saving the current
3027       --  number of saved checks for a later restore.
3028
3029       else
3030          Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
3031
3032          if Debug_Flag_CC then
3033             w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
3034                Num_Saved_Checks);
3035          end if;
3036       end if;
3037    end Conditional_Statements_Begin;
3038
3039    --------------------------------
3040    -- Conditional_Statements_End --
3041    --------------------------------
3042
3043    procedure Conditional_Statements_End is
3044    begin
3045       pragma Assert (Saved_Checks_TOS > 0);
3046
3047       --  If the saved checks stack overflowed, then we killed all checks, so
3048       --  setting the number of saved checks back to zero is correct. This
3049       --  should never occur in practice.
3050
3051       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
3052          Num_Saved_Checks := 0;
3053
3054       --  In the normal case, restore the number of saved checks from the top
3055       --  stack entry.
3056
3057       else
3058          Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
3059          if Debug_Flag_CC then
3060             w ("Conditional_Statements_End: Num_Saved_Checks = ",
3061                Num_Saved_Checks);
3062          end if;
3063       end if;
3064
3065       Saved_Checks_TOS := Saved_Checks_TOS - 1;
3066    end Conditional_Statements_End;
3067
3068    ---------------------
3069    -- Determine_Range --
3070    ---------------------
3071
3072    Cache_Size : constant := 2 ** 10;
3073    type Cache_Index is range 0 .. Cache_Size - 1;
3074    --  Determine size of below cache (power of 2 is more efficient!)
3075
3076    Determine_Range_Cache_N  : array (Cache_Index) of Node_Id;
3077    Determine_Range_Cache_V  : array (Cache_Index) of Boolean;
3078    Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
3079    Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
3080    --  The above arrays are used to implement a small direct cache for
3081    --  Determine_Range calls. Because of the way Determine_Range recursively
3082    --  traces subexpressions, and because overflow checking calls the routine
3083    --  on the way up the tree, a quadratic behavior can otherwise be
3084    --  encountered in large expressions. The cache entry for node N is stored
3085    --  in the (N mod Cache_Size) entry, and can be validated by checking the
3086    --  actual node value stored there. The Range_Cache_V array records the
3087    --  setting of Assume_Valid for the cache entry.
3088
3089    procedure Determine_Range
3090      (N            : Node_Id;
3091       OK           : out Boolean;
3092       Lo           : out Uint;
3093       Hi           : out Uint;
3094       Assume_Valid : Boolean := False)
3095    is
3096       Typ : Entity_Id := Etype (N);
3097       --  Type to use, may get reset to base type for possibly invalid entity
3098
3099       Lo_Left : Uint;
3100       Hi_Left : Uint;
3101       --  Lo and Hi bounds of left operand
3102
3103       Lo_Right : Uint;
3104       Hi_Right : Uint;
3105       --  Lo and Hi bounds of right (or only) operand
3106
3107       Bound : Node_Id;
3108       --  Temp variable used to hold a bound node
3109
3110       Hbound : Uint;
3111       --  High bound of base type of expression
3112
3113       Lor : Uint;
3114       Hir : Uint;
3115       --  Refined values for low and high bounds, after tightening
3116
3117       OK1 : Boolean;
3118       --  Used in lower level calls to indicate if call succeeded
3119
3120       Cindex : Cache_Index;
3121       --  Used to search cache
3122
3123       function OK_Operands return Boolean;
3124       --  Used for binary operators. Determines the ranges of the left and
3125       --  right operands, and if they are both OK, returns True, and puts
3126       --  the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
3127
3128       -----------------
3129       -- OK_Operands --
3130       -----------------
3131
3132       function OK_Operands return Boolean is
3133       begin
3134          Determine_Range
3135            (Left_Opnd  (N), OK1, Lo_Left,  Hi_Left, Assume_Valid);
3136
3137          if not OK1 then
3138             return False;
3139          end if;
3140
3141          Determine_Range
3142            (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3143          return OK1;
3144       end OK_Operands;
3145
3146    --  Start of processing for Determine_Range
3147
3148    begin
3149       --  For temporary constants internally generated to remove side effects
3150       --  we must use the corresponding expression to determine the range of
3151       --  the expression.
3152
3153       if Is_Entity_Name (N)
3154         and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3155         and then Ekind (Entity (N)) = E_Constant
3156         and then Is_Internal_Name (Chars (Entity (N)))
3157       then
3158          Determine_Range
3159            (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
3160          return;
3161       end if;
3162
3163       --  Prevent junk warnings by initializing range variables
3164
3165       Lo  := No_Uint;
3166       Hi  := No_Uint;
3167       Lor := No_Uint;
3168       Hir := No_Uint;
3169
3170       --  If type is not defined, we can't determine its range
3171
3172       if No (Typ)
3173
3174         --  We don't deal with anything except discrete types
3175
3176         or else not Is_Discrete_Type (Typ)
3177
3178         --  Ignore type for which an error has been posted, since range in
3179         --  this case may well be a bogosity deriving from the error. Also
3180         --  ignore if error posted on the reference node.
3181
3182         or else Error_Posted (N) or else Error_Posted (Typ)
3183       then
3184          OK := False;
3185          return;
3186       end if;
3187
3188       --  For all other cases, we can determine the range
3189
3190       OK := True;
3191
3192       --  If value is compile time known, then the possible range is the one
3193       --  value that we know this expression definitely has!
3194
3195       if Compile_Time_Known_Value (N) then
3196          Lo := Expr_Value (N);
3197          Hi := Lo;
3198          return;
3199       end if;
3200
3201       --  Return if already in the cache
3202
3203       Cindex := Cache_Index (N mod Cache_Size);
3204
3205       if Determine_Range_Cache_N (Cindex) = N
3206            and then
3207          Determine_Range_Cache_V (Cindex) = Assume_Valid
3208       then
3209          Lo := Determine_Range_Cache_Lo (Cindex);
3210          Hi := Determine_Range_Cache_Hi (Cindex);
3211          return;
3212       end if;
3213
3214       --  Otherwise, start by finding the bounds of the type of the expression,
3215       --  the value cannot be outside this range (if it is, then we have an
3216       --  overflow situation, which is a separate check, we are talking here
3217       --  only about the expression value).
3218
3219       --  First a check, never try to find the bounds of a generic type, since
3220       --  these bounds are always junk values, and it is only valid to look at
3221       --  the bounds in an instance.
3222
3223       if Is_Generic_Type (Typ) then
3224          OK := False;
3225          return;
3226       end if;
3227
3228       --  First step, change to use base type unless we know the value is valid
3229
3230       if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
3231         or else Assume_No_Invalid_Values
3232         or else Assume_Valid
3233       then
3234          null;
3235       else
3236          Typ := Underlying_Type (Base_Type (Typ));
3237       end if;
3238
3239       --  We use the actual bound unless it is dynamic, in which case use the
3240       --  corresponding base type bound if possible. If we can't get a bound
3241       --  then we figure we can't determine the range (a peculiar case, that
3242       --  perhaps cannot happen, but there is no point in bombing in this
3243       --  optimization circuit.
3244
3245       --  First the low bound
3246
3247       Bound := Type_Low_Bound (Typ);
3248
3249       if Compile_Time_Known_Value (Bound) then
3250          Lo := Expr_Value (Bound);
3251
3252       elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
3253          Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
3254
3255       else
3256          OK := False;
3257          return;
3258       end if;
3259
3260       --  Now the high bound
3261
3262       Bound := Type_High_Bound (Typ);
3263
3264       --  We need the high bound of the base type later on, and this should
3265       --  always be compile time known. Again, it is not clear that this
3266       --  can ever be false, but no point in bombing.
3267
3268       if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
3269          Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
3270          Hi := Hbound;
3271
3272       else
3273          OK := False;
3274          return;
3275       end if;
3276
3277       --  If we have a static subtype, then that may have a tighter bound so
3278       --  use the upper bound of the subtype instead in this case.
3279
3280       if Compile_Time_Known_Value (Bound) then
3281          Hi := Expr_Value (Bound);
3282       end if;
3283
3284       --  We may be able to refine this value in certain situations. If any
3285       --  refinement is possible, then Lor and Hir are set to possibly tighter
3286       --  bounds, and OK1 is set to True.
3287
3288       case Nkind (N) is
3289
3290          --  For unary plus, result is limited by range of operand
3291
3292          when N_Op_Plus =>
3293             Determine_Range
3294               (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
3295
3296          --  For unary minus, determine range of operand, and negate it
3297
3298          when N_Op_Minus =>
3299             Determine_Range
3300               (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3301
3302             if OK1 then
3303                Lor := -Hi_Right;
3304                Hir := -Lo_Right;
3305             end if;
3306
3307          --  For binary addition, get range of each operand and do the
3308          --  addition to get the result range.
3309
3310          when N_Op_Add =>
3311             if OK_Operands then
3312                Lor := Lo_Left + Lo_Right;
3313                Hir := Hi_Left + Hi_Right;
3314             end if;
3315
3316          --  Division is tricky. The only case we consider is where the right
3317          --  operand is a positive constant, and in this case we simply divide
3318          --  the bounds of the left operand
3319
3320          when N_Op_Divide =>
3321             if OK_Operands then
3322                if Lo_Right = Hi_Right
3323                  and then Lo_Right > 0
3324                then
3325                   Lor := Lo_Left / Lo_Right;
3326                   Hir := Hi_Left / Lo_Right;
3327
3328                else
3329                   OK1 := False;
3330                end if;
3331             end if;
3332
3333          --  For binary subtraction, get range of each operand and do the worst
3334          --  case subtraction to get the result range.
3335
3336          when N_Op_Subtract =>
3337             if OK_Operands then
3338                Lor := Lo_Left - Hi_Right;
3339                Hir := Hi_Left - Lo_Right;
3340             end if;
3341
3342          --  For MOD, if right operand is a positive constant, then result must
3343          --  be in the allowable range of mod results.
3344
3345          when N_Op_Mod =>
3346             if OK_Operands then
3347                if Lo_Right = Hi_Right
3348                  and then Lo_Right /= 0
3349                then
3350                   if Lo_Right > 0 then
3351                      Lor := Uint_0;
3352                      Hir := Lo_Right - 1;
3353
3354                   else -- Lo_Right < 0
3355                      Lor := Lo_Right + 1;
3356                      Hir := Uint_0;
3357                   end if;
3358
3359                else
3360                   OK1 := False;
3361                end if;
3362             end if;
3363
3364          --  For REM, if right operand is a positive constant, then result must
3365          --  be in the allowable range of mod results.
3366
3367          when N_Op_Rem =>
3368             if OK_Operands then
3369                if Lo_Right = Hi_Right
3370                  and then Lo_Right /= 0
3371                then
3372                   declare
3373                      Dval : constant Uint := (abs Lo_Right) - 1;
3374
3375                   begin
3376                      --  The sign of the result depends on the sign of the
3377                      --  dividend (but not on the sign of the divisor, hence
3378                      --  the abs operation above).
3379
3380                      if Lo_Left < 0 then
3381                         Lor := -Dval;
3382                      else
3383                         Lor := Uint_0;
3384                      end if;
3385
3386                      if Hi_Left < 0 then
3387                         Hir := Uint_0;
3388                      else
3389                         Hir := Dval;
3390                      end if;
3391                   end;
3392
3393                else
3394                   OK1 := False;
3395                end if;
3396             end if;
3397
3398          --  Attribute reference cases
3399
3400          when N_Attribute_Reference =>
3401             case Attribute_Name (N) is
3402
3403                --  For Pos/Val attributes, we can refine the range using the
3404                --  possible range of values of the attribute expression.
3405
3406                when Name_Pos | Name_Val =>
3407                   Determine_Range
3408                     (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
3409
3410                --  For Length attribute, use the bounds of the corresponding
3411                --  index type to refine the range.
3412
3413                when Name_Length =>
3414                   declare
3415                      Atyp : Entity_Id := Etype (Prefix (N));
3416                      Inum : Nat;
3417                      Indx : Node_Id;
3418
3419                      LL, LU : Uint;
3420                      UL, UU : Uint;
3421
3422                   begin
3423                      if Is_Access_Type (Atyp) then
3424                         Atyp := Designated_Type (Atyp);
3425                      end if;
3426
3427                      --  For string literal, we know exact value
3428
3429                      if Ekind (Atyp) = E_String_Literal_Subtype then
3430                         OK := True;
3431                         Lo := String_Literal_Length (Atyp);
3432                         Hi := String_Literal_Length (Atyp);
3433                         return;
3434                      end if;
3435
3436                      --  Otherwise check for expression given
3437
3438                      if No (Expressions (N)) then
3439                         Inum := 1;
3440                      else
3441                         Inum :=
3442                           UI_To_Int (Expr_Value (First (Expressions (N))));
3443                      end if;
3444
3445                      Indx := First_Index (Atyp);
3446                      for J in 2 .. Inum loop
3447                         Indx := Next_Index (Indx);
3448                      end loop;
3449
3450                      --  If the index type is a formal type or derived from
3451                      --  one, the bounds are not static.
3452
3453                      if Is_Generic_Type (Root_Type (Etype (Indx))) then
3454                         OK := False;
3455                         return;
3456                      end if;
3457
3458                      Determine_Range
3459                        (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
3460                         Assume_Valid);
3461
3462                      if OK1 then
3463                         Determine_Range
3464                           (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
3465                            Assume_Valid);
3466
3467                         if OK1 then
3468
3469                            --  The maximum value for Length is the biggest
3470                            --  possible gap between the values of the bounds.
3471                            --  But of course, this value cannot be negative.
3472
3473                            Hir := UI_Max (Uint_0, UU - LL + 1);
3474
3475                            --  For constrained arrays, the minimum value for
3476                            --  Length is taken from the actual value of the
3477                            --  bounds, since the index will be exactly of this
3478                            --  subtype.
3479
3480                            if Is_Constrained (Atyp) then
3481                               Lor := UI_Max (Uint_0, UL - LU + 1);
3482
3483                            --  For an unconstrained array, the minimum value
3484                            --  for length is always zero.
3485
3486                            else
3487                               Lor := Uint_0;
3488                            end if;
3489                         end if;
3490                      end if;
3491                   end;
3492
3493                --  No special handling for other attributes
3494                --  Probably more opportunities exist here???
3495
3496                when others =>
3497                   OK1 := False;
3498
3499             end case;
3500
3501          --  For type conversion from one discrete type to another, we can
3502          --  refine the range using the converted value.
3503
3504          when N_Type_Conversion =>
3505             Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
3506
3507          --  Nothing special to do for all other expression kinds
3508
3509          when others =>
3510             OK1 := False;
3511             Lor := No_Uint;
3512             Hir := No_Uint;
3513       end case;
3514
3515       --  At this stage, if OK1 is true, then we know that the actual result of
3516       --  the computed expression is in the range Lor .. Hir. We can use this
3517       --  to restrict the possible range of results.
3518
3519       --  If one of the computed bounds is outside the range of the base type,
3520       --  the expression may raise an exception and we had better indicate that
3521       --  the evaluation has failed, at least if checks are enabled.
3522
3523       if OK1
3524         and then Enable_Overflow_Checks
3525         and then not Is_Entity_Name (N)
3526         and then (Lor < Lo or else Hir > Hi)
3527       then
3528          OK := False;
3529          return;
3530       end if;
3531
3532       if OK1 then
3533
3534          --  If the refined value of the low bound is greater than the type
3535          --  high bound, then reset it to the more restrictive value. However,
3536          --  we do NOT do this for the case of a modular type where the
3537          --  possible upper bound on the value is above the base type high
3538          --  bound, because that means the result could wrap.
3539
3540          if Lor > Lo
3541            and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
3542          then
3543             Lo := Lor;
3544          end if;
3545
3546          --  Similarly, if the refined value of the high bound is less than the
3547          --  value so far, then reset it to the more restrictive value. Again,
3548          --  we do not do this if the refined low bound is negative for a
3549          --  modular type, since this would wrap.
3550
3551          if Hir < Hi
3552            and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
3553          then
3554             Hi := Hir;
3555          end if;
3556       end if;
3557
3558       --  Set cache entry for future call and we are all done
3559
3560       Determine_Range_Cache_N  (Cindex) := N;
3561       Determine_Range_Cache_V  (Cindex) := Assume_Valid;
3562       Determine_Range_Cache_Lo (Cindex) := Lo;
3563       Determine_Range_Cache_Hi (Cindex) := Hi;
3564       return;
3565
3566    --  If any exception occurs, it means that we have some bug in the compiler,
3567    --  possibly triggered by a previous error, or by some unforeseen peculiar
3568    --  occurrence. However, this is only an optimization attempt, so there is
3569    --  really no point in crashing the compiler. Instead we just decide, too
3570    --  bad, we can't figure out a range in this case after all.
3571
3572    exception
3573       when others =>
3574
3575          --  Debug flag K disables this behavior (useful for debugging)
3576
3577          if Debug_Flag_K then
3578             raise;
3579          else
3580             OK := False;
3581             Lo := No_Uint;
3582             Hi := No_Uint;
3583             return;
3584          end if;
3585    end Determine_Range;
3586
3587    ------------------------------------
3588    -- Discriminant_Checks_Suppressed --
3589    ------------------------------------
3590
3591    function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3592    begin
3593       if Present (E) then
3594          if Is_Unchecked_Union (E) then
3595             return True;
3596          elsif Checks_May_Be_Suppressed (E) then
3597             return Is_Check_Suppressed (E, Discriminant_Check);
3598          end if;
3599       end if;
3600
3601       return Scope_Suppress (Discriminant_Check);
3602    end Discriminant_Checks_Suppressed;
3603
3604    --------------------------------
3605    -- Division_Checks_Suppressed --
3606    --------------------------------
3607
3608    function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3609    begin
3610       if Present (E) and then Checks_May_Be_Suppressed (E) then
3611          return Is_Check_Suppressed (E, Division_Check);
3612       else
3613          return Scope_Suppress (Division_Check);
3614       end if;
3615    end Division_Checks_Suppressed;
3616
3617    -----------------------------------
3618    -- Elaboration_Checks_Suppressed --
3619    -----------------------------------
3620
3621    function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3622    begin
3623       --  The complication in this routine is that if we are in the dynamic
3624       --  model of elaboration, we also check All_Checks, since All_Checks
3625       --  does not set Elaboration_Check explicitly.
3626
3627       if Present (E) then
3628          if Kill_Elaboration_Checks (E) then
3629             return True;
3630
3631          elsif Checks_May_Be_Suppressed (E) then
3632             if Is_Check_Suppressed (E, Elaboration_Check) then
3633                return True;
3634             elsif Dynamic_Elaboration_Checks then
3635                return Is_Check_Suppressed (E, All_Checks);
3636             else
3637                return False;
3638             end if;
3639          end if;
3640       end if;
3641
3642       if Scope_Suppress (Elaboration_Check) then
3643          return True;
3644       elsif Dynamic_Elaboration_Checks then
3645          return Scope_Suppress (All_Checks);
3646       else
3647          return False;
3648       end if;
3649    end Elaboration_Checks_Suppressed;
3650
3651    ---------------------------
3652    -- Enable_Overflow_Check --
3653    ---------------------------
3654
3655    procedure Enable_Overflow_Check (N : Node_Id) is
3656       Typ : constant Entity_Id  := Base_Type (Etype (N));
3657       Chk : Nat;
3658       OK  : Boolean;
3659       Ent : Entity_Id;
3660       Ofs : Uint;
3661       Lo  : Uint;
3662       Hi  : Uint;
3663
3664    begin
3665       if Debug_Flag_CC then
3666          w ("Enable_Overflow_Check for node ", Int (N));
3667          Write_Str ("  Source location = ");
3668          wl (Sloc (N));
3669          pg (Union_Id (N));
3670       end if;
3671
3672       --  No check if overflow checks suppressed for type of node
3673
3674       if Present (Etype (N))
3675         and then Overflow_Checks_Suppressed (Etype (N))
3676       then
3677          return;
3678
3679       --  Nothing to do for unsigned integer types, which do not overflow
3680
3681       elsif Is_Modular_Integer_Type (Typ) then
3682          return;
3683
3684       --  Nothing to do if the range of the result is known OK. We skip this
3685       --  for conversions, since the caller already did the check, and in any
3686       --  case the condition for deleting the check for a type conversion is
3687       --  different.
3688
3689       elsif Nkind (N) /= N_Type_Conversion then
3690          Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
3691
3692          --  Note in the test below that we assume that the range is not OK
3693          --  if a bound of the range is equal to that of the type. That's not
3694          --  quite accurate but we do this for the following reasons:
3695
3696          --   a) The way that Determine_Range works, it will typically report
3697          --      the bounds of the value as being equal to the bounds of the
3698          --      type, because it either can't tell anything more precise, or
3699          --      does not think it is worth the effort to be more precise.
3700
3701          --   b) It is very unusual to have a situation in which this would
3702          --      generate an unnecessary overflow check (an example would be
3703          --      a subtype with a range 0 .. Integer'Last - 1 to which the
3704          --      literal value one is added).
3705
3706          --   c) The alternative is a lot of special casing in this routine
3707          --      which would partially duplicate Determine_Range processing.
3708
3709          if OK
3710            and then Lo > Expr_Value (Type_Low_Bound  (Typ))
3711            and then Hi < Expr_Value (Type_High_Bound (Typ))
3712          then
3713             if Debug_Flag_CC then
3714                w ("No overflow check required");
3715             end if;
3716
3717             return;
3718          end if;
3719       end if;
3720
3721       --  If not in optimizing mode, set flag and we are done. We are also done
3722       --  (and just set the flag) if the type is not a discrete type, since it
3723       --  is not worth the effort to eliminate checks for other than discrete
3724       --  types. In addition, we take this same path if we have stored the
3725       --  maximum number of checks possible already (a very unlikely situation,
3726       --  but we do not want to blow up!)
3727
3728       if Optimization_Level = 0
3729         or else not Is_Discrete_Type (Etype (N))
3730         or else Num_Saved_Checks = Saved_Checks'Last
3731       then
3732          Activate_Overflow_Check (N);
3733
3734          if Debug_Flag_CC then
3735             w ("Optimization off");
3736          end if;
3737
3738          return;
3739       end if;
3740
3741       --  Otherwise evaluate and check the expression
3742
3743       Find_Check
3744         (Expr        => N,
3745          Check_Type  => 'O',
3746          Target_Type => Empty,
3747          Entry_OK    => OK,
3748          Check_Num   => Chk,
3749          Ent         => Ent,
3750          Ofs         => Ofs);
3751
3752       if Debug_Flag_CC then
3753          w ("Called Find_Check");
3754          w ("  OK = ", OK);
3755
3756          if OK then
3757             w ("  Check_Num = ", Chk);
3758             w ("  Ent       = ", Int (Ent));
3759             Write_Str ("  Ofs       = ");
3760             pid (Ofs);
3761          end if;
3762       end if;
3763
3764       --  If check is not of form to optimize, then set flag and we are done
3765
3766       if not OK then
3767          Activate_Overflow_Check (N);
3768          return;
3769       end if;
3770
3771       --  If check is already performed, then return without setting flag
3772
3773       if Chk /= 0 then
3774          if Debug_Flag_CC then
3775             w ("Check suppressed!");
3776          end if;
3777
3778          return;
3779       end if;
3780
3781       --  Here we will make a new entry for the new check
3782
3783       Activate_Overflow_Check (N);
3784       Num_Saved_Checks := Num_Saved_Checks + 1;
3785       Saved_Checks (Num_Saved_Checks) :=
3786         (Killed      => False,
3787          Entity      => Ent,
3788          Offset      => Ofs,
3789          Check_Type  => 'O',
3790          Target_Type => Empty);
3791
3792       if Debug_Flag_CC then
3793          w ("Make new entry, check number = ", Num_Saved_Checks);
3794          w ("  Entity = ", Int (Ent));
3795          Write_Str ("  Offset = ");
3796          pid (Ofs);
3797          w ("  Check_Type = O");
3798          w ("  Target_Type = Empty");
3799       end if;
3800
3801    --  If we get an exception, then something went wrong, probably because of
3802    --  an error in the structure of the tree due to an incorrect program. Or it
3803    --  may be a bug in the optimization circuit. In either case the safest
3804    --  thing is simply to set the check flag unconditionally.
3805
3806    exception
3807       when others =>
3808          Activate_Overflow_Check (N);
3809
3810          if Debug_Flag_CC then
3811             w ("  exception occurred, overflow flag set");
3812          end if;
3813
3814          return;
3815    end Enable_Overflow_Check;
3816
3817    ------------------------
3818    -- Enable_Range_Check --
3819    ------------------------
3820
3821    procedure Enable_Range_Check (N : Node_Id) is
3822       Chk  : Nat;
3823       OK   : Boolean;
3824       Ent  : Entity_Id;
3825       Ofs  : Uint;
3826       Ttyp : Entity_Id;
3827       P    : Node_Id;
3828
3829    begin
3830       --  Return if unchecked type conversion with range check killed. In this
3831       --  case we never set the flag (that's what Kill_Range_Check is about!)
3832
3833       if Nkind (N) = N_Unchecked_Type_Conversion
3834         and then Kill_Range_Check (N)
3835       then
3836          return;
3837       end if;
3838
3839       --  Do not set range check flag if parent is assignment statement or
3840       --  object declaration with Suppress_Assignment_Checks flag set
3841
3842       if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
3843         and then Suppress_Assignment_Checks (Parent (N))
3844       then
3845          return;
3846       end if;
3847
3848       --  Check for various cases where we should suppress the range check
3849
3850       --  No check if range checks suppressed for type of node
3851
3852       if Present (Etype (N))
3853         and then Range_Checks_Suppressed (Etype (N))
3854       then
3855          return;
3856
3857       --  No check if node is an entity name, and range checks are suppressed
3858       --  for this entity, or for the type of this entity.
3859
3860       elsif Is_Entity_Name (N)
3861         and then (Range_Checks_Suppressed (Entity (N))
3862                     or else Range_Checks_Suppressed (Etype (Entity (N))))
3863       then
3864          return;
3865
3866       --  No checks if index of array, and index checks are suppressed for
3867       --  the array object or the type of the array.
3868
3869       elsif Nkind (Parent (N)) = N_Indexed_Component then
3870          declare
3871             Pref : constant Node_Id := Prefix (Parent (N));
3872          begin
3873             if Is_Entity_Name (Pref)
3874               and then Index_Checks_Suppressed (Entity (Pref))
3875             then
3876                return;
3877             elsif Index_Checks_Suppressed (Etype (Pref)) then
3878                return;
3879             end if;
3880          end;
3881       end if;
3882
3883       --  Debug trace output
3884
3885       if Debug_Flag_CC then
3886          w ("Enable_Range_Check for node ", Int (N));
3887          Write_Str ("  Source location = ");
3888          wl (Sloc (N));
3889          pg (Union_Id (N));
3890       end if;
3891
3892       --  If not in optimizing mode, set flag and we are done. We are also done
3893       --  (and just set the flag) if the type is not a discrete type, since it
3894       --  is not worth the effort to eliminate checks for other than discrete
3895       --  types. In addition, we take this same path if we have stored the
3896       --  maximum number of checks possible already (a very unlikely situation,
3897       --  but we do not want to blow up!)
3898
3899       if Optimization_Level = 0
3900         or else No (Etype (N))
3901         or else not Is_Discrete_Type (Etype (N))
3902         or else Num_Saved_Checks = Saved_Checks'Last
3903       then
3904          Activate_Range_Check (N);
3905
3906          if Debug_Flag_CC then
3907             w ("Optimization off");
3908          end if;
3909
3910          return;
3911       end if;
3912
3913       --  Otherwise find out the target type
3914
3915       P := Parent (N);
3916
3917       --  For assignment, use left side subtype
3918
3919       if Nkind (P) = N_Assignment_Statement
3920         and then Expression (P) = N
3921       then
3922          Ttyp := Etype (Name (P));
3923
3924       --  For indexed component, use subscript subtype
3925
3926       elsif Nkind (P) = N_Indexed_Component then
3927          declare
3928             Atyp : Entity_Id;
3929             Indx : Node_Id;
3930             Subs : Node_Id;
3931
3932          begin
3933             Atyp := Etype (Prefix (P));
3934
3935             if Is_Access_Type (Atyp) then
3936                Atyp := Designated_Type (Atyp);
3937
3938                --  If the prefix is an access to an unconstrained array,
3939                --  perform check unconditionally: it depends on the bounds of
3940                --  an object and we cannot currently recognize whether the test
3941                --  may be redundant.
3942
3943                if not Is_Constrained (Atyp) then
3944                   Activate_Range_Check (N);
3945                   return;
3946                end if;
3947
3948             --  Ditto if the prefix is an explicit dereference whose designated
3949             --  type is unconstrained.
3950
3951             elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3952               and then not Is_Constrained (Atyp)
3953             then
3954                Activate_Range_Check (N);
3955                return;
3956             end if;
3957
3958             Indx := First_Index (Atyp);
3959             Subs := First (Expressions (P));
3960             loop
3961                if Subs = N then
3962                   Ttyp := Etype (Indx);
3963                   exit;
3964                end if;
3965
3966                Next_Index (Indx);
3967                Next (Subs);
3968             end loop;
3969          end;
3970
3971       --  For now, ignore all other cases, they are not so interesting
3972
3973       else
3974          if Debug_Flag_CC then
3975             w ("  target type not found, flag set");
3976          end if;
3977
3978          Activate_Range_Check (N);
3979          return;
3980       end if;
3981
3982       --  Evaluate and check the expression
3983
3984       Find_Check
3985         (Expr        => N,
3986          Check_Type  => 'R',
3987          Target_Type => Ttyp,
3988          Entry_OK    => OK,
3989          Check_Num   => Chk,
3990          Ent         => Ent,
3991          Ofs         => Ofs);
3992
3993       if Debug_Flag_CC then
3994          w ("Called Find_Check");
3995          w ("Target_Typ = ", Int (Ttyp));
3996          w ("  OK = ", OK);
3997
3998          if OK then
3999             w ("  Check_Num = ", Chk);
4000             w ("  Ent       = ", Int (Ent));
4001             Write_Str ("  Ofs       = ");
4002             pid (Ofs);
4003          end if;
4004       end if;
4005
4006       --  If check is not of form to optimize, then set flag and we are done
4007
4008       if not OK then
4009          if Debug_Flag_CC then
4010             w ("  expression not of optimizable type, flag set");
4011          end if;
4012
4013          Activate_Range_Check (N);
4014          return;
4015       end if;
4016
4017       --  If check is already performed, then return without setting flag
4018
4019       if Chk /= 0 then
4020          if Debug_Flag_CC then
4021             w ("Check suppressed!");
4022          end if;
4023
4024          return;
4025       end if;
4026
4027       --  Here we will make a new entry for the new check
4028
4029       Activate_Range_Check (N);
4030       Num_Saved_Checks := Num_Saved_Checks + 1;
4031       Saved_Checks (Num_Saved_Checks) :=
4032         (Killed      => False,
4033          Entity      => Ent,
4034          Offset      => Ofs,
4035          Check_Type  => 'R',
4036          Target_Type => Ttyp);
4037
4038       if Debug_Flag_CC then
4039          w ("Make new entry, check number = ", Num_Saved_Checks);
4040          w ("  Entity = ", Int (Ent));
4041          Write_Str ("  Offset = ");
4042          pid (Ofs);
4043          w ("  Check_Type = R");
4044          w ("  Target_Type = ", Int (Ttyp));
4045          pg (Union_Id (Ttyp));
4046       end if;
4047
4048    --  If we get an exception, then something went wrong, probably because of
4049    --  an error in the structure of the tree due to an incorrect program. Or
4050    --  it may be a bug in the optimization circuit. In either case the safest
4051    --  thing is simply to set the check flag unconditionally.
4052
4053    exception
4054       when others =>
4055          Activate_Range_Check (N);
4056
4057          if Debug_Flag_CC then
4058             w ("  exception occurred, range flag set");
4059          end if;
4060
4061          return;
4062    end Enable_Range_Check;
4063
4064    ------------------
4065    -- Ensure_Valid --
4066    ------------------
4067
4068    procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
4069       Typ : constant Entity_Id  := Etype (Expr);
4070
4071    begin
4072       --  Ignore call if we are not doing any validity checking
4073
4074       if not Validity_Checks_On then
4075          return;
4076
4077       --  Ignore call if range or validity checks suppressed on entity or type
4078
4079       elsif Range_Or_Validity_Checks_Suppressed (Expr) then
4080          return;
4081
4082       --  No check required if expression is from the expander, we assume the
4083       --  expander will generate whatever checks are needed. Note that this is
4084       --  not just an optimization, it avoids infinite recursions!
4085
4086       --  Unchecked conversions must be checked, unless they are initialized
4087       --  scalar values, as in a component assignment in an init proc.
4088
4089       --  In addition, we force a check if Force_Validity_Checks is set
4090
4091       elsif not Comes_From_Source (Expr)
4092         and then not Force_Validity_Checks
4093         and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
4094                     or else Kill_Range_Check (Expr))
4095       then
4096          return;
4097
4098       --  No check required if expression is known to have valid value
4099
4100       elsif Expr_Known_Valid (Expr) then
4101          return;
4102
4103       --  Ignore case of enumeration with holes where the flag is set not to
4104       --  worry about holes, since no special validity check is needed
4105
4106       elsif Is_Enumeration_Type (Typ)
4107         and then Has_Non_Standard_Rep (Typ)
4108         and then Holes_OK
4109       then
4110          return;
4111
4112       --  No check required on the left-hand side of an assignment
4113
4114       elsif Nkind (Parent (Expr)) = N_Assignment_Statement
4115         and then Expr = Name (Parent (Expr))
4116       then
4117          return;
4118
4119       --  No check on a universal real constant. The context will eventually
4120       --  convert it to a machine number for some target type, or report an
4121       --  illegality.
4122
4123       elsif Nkind (Expr) = N_Real_Literal
4124         and then Etype (Expr) = Universal_Real
4125       then
4126          return;
4127
4128       --  If the expression denotes a component of a packed boolean array,
4129       --  no possible check applies. We ignore the old ACATS chestnuts that
4130       --  involve Boolean range True..True.
4131
4132       --  Note: validity checks are generated for expressions that yield a
4133       --  scalar type, when it is possible to create a value that is outside of
4134       --  the type. If this is a one-bit boolean no such value exists. This is
4135       --  an optimization, and it also prevents compiler blowing up during the
4136       --  elaboration of improperly expanded packed array references.
4137
4138       elsif Nkind (Expr) = N_Indexed_Component
4139         and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
4140         and then Root_Type (Etype (Expr)) = Standard_Boolean
4141       then
4142          return;
4143
4144       --  An annoying special case. If this is an out parameter of a scalar
4145       --  type, then the value is not going to be accessed, therefore it is
4146       --  inappropriate to do any validity check at the call site.
4147
4148       else
4149          --  Only need to worry about scalar types
4150
4151          if Is_Scalar_Type (Typ) then
4152             declare
4153                P : Node_Id;
4154                N : Node_Id;
4155                E : Entity_Id;
4156                F : Entity_Id;
4157                A : Node_Id;
4158                L : List_Id;
4159
4160             begin
4161                --  Find actual argument (which may be a parameter association)
4162                --  and the parent of the actual argument (the call statement)
4163
4164                N := Expr;
4165                P := Parent (Expr);
4166
4167                if Nkind (P) = N_Parameter_Association then
4168                   N := P;
4169                   P := Parent (N);
4170                end if;
4171
4172                --  Only need to worry if we are argument of a procedure call
4173                --  since functions don't have out parameters. If this is an
4174                --  indirect or dispatching call, get signature from the
4175                --  subprogram type.
4176
4177                if Nkind (P) = N_Procedure_Call_Statement then
4178                   L := Parameter_Associations (P);
4179
4180                   if Is_Entity_Name (Name (P)) then
4181                      E := Entity (Name (P));
4182                   else
4183                      pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
4184                      E := Etype (Name (P));
4185                   end if;
4186
4187                   --  Only need to worry if there are indeed actuals, and if
4188                   --  this could be a procedure call, otherwise we cannot get a
4189                   --  match (either we are not an argument, or the mode of the
4190                   --  formal is not OUT). This test also filters out the
4191                   --  generic case.
4192
4193                   if Is_Non_Empty_List (L)
4194                     and then Is_Subprogram (E)
4195                   then
4196                      --  This is the loop through parameters, looking for an
4197                      --  OUT parameter for which we are the argument.
4198
4199                      F := First_Formal (E);
4200                      A := First (L);
4201                      while Present (F) loop
4202                         if Ekind (F) = E_Out_Parameter and then A = N then
4203                            return;
4204                         end if;
4205
4206                         Next_Formal (F);
4207                         Next (A);
4208                      end loop;
4209                   end if;
4210                end if;
4211             end;
4212          end if;
4213       end if;
4214
4215       --  If this is a boolean expression, only its elementary operands need
4216       --  checking: if they are valid, a boolean or short-circuit operation
4217       --  with them will be valid as well.
4218
4219       if Base_Type (Typ) = Standard_Boolean
4220         and then
4221          (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
4222       then
4223          return;
4224       end if;
4225
4226       --  If we fall through, a validity check is required
4227
4228       Insert_Valid_Check (Expr);
4229
4230       if Is_Entity_Name (Expr)
4231         and then Safe_To_Capture_Value (Expr, Entity (Expr))
4232       then
4233          Set_Is_Known_Valid (Entity (Expr));
4234       end if;
4235    end Ensure_Valid;
4236
4237    ----------------------
4238    -- Expr_Known_Valid --
4239    ----------------------
4240
4241    function Expr_Known_Valid (Expr : Node_Id) return Boolean is
4242       Typ : constant Entity_Id := Etype (Expr);
4243
4244    begin
4245       --  Non-scalar types are always considered valid, since they never give
4246       --  rise to the issues of erroneous or bounded error behavior that are
4247       --  the concern. In formal reference manual terms the notion of validity
4248       --  only applies to scalar types. Note that even when packed arrays are
4249       --  represented using modular types, they are still arrays semantically,
4250       --  so they are also always valid (in particular, the unused bits can be
4251       --  random rubbish without affecting the validity of the array value).
4252
4253       if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
4254          return True;
4255
4256       --  If no validity checking, then everything is considered valid
4257
4258       elsif not Validity_Checks_On then
4259          return True;
4260
4261       --  Floating-point types are considered valid unless floating-point
4262       --  validity checks have been specifically turned on.
4263
4264       elsif Is_Floating_Point_Type (Typ)
4265         and then not Validity_Check_Floating_Point
4266       then
4267          return True;
4268
4269       --  If the expression is the value of an object that is known to be
4270       --  valid, then clearly the expression value itself is valid.
4271
4272       elsif Is_Entity_Name (Expr)
4273         and then Is_Known_Valid (Entity (Expr))
4274       then
4275          return True;
4276
4277       --  References to discriminants are always considered valid. The value
4278       --  of a discriminant gets checked when the object is built. Within the
4279       --  record, we consider it valid, and it is important to do so, since
4280       --  otherwise we can try to generate bogus validity checks which
4281       --  reference discriminants out of scope. Discriminants of concurrent
4282       --  types are excluded for the same reason.
4283
4284       elsif Is_Entity_Name (Expr)
4285         and then Denotes_Discriminant (Expr, Check_Concurrent => True)
4286       then
4287          return True;
4288
4289       --  If the type is one for which all values are known valid, then we are
4290       --  sure that the value is valid except in the slightly odd case where
4291       --  the expression is a reference to a variable whose size has been
4292       --  explicitly set to a value greater than the object size.
4293
4294       elsif Is_Known_Valid (Typ) then
4295          if Is_Entity_Name (Expr)
4296            and then Ekind (Entity (Expr)) = E_Variable
4297            and then Esize (Entity (Expr)) > Esize (Typ)
4298          then
4299             return False;
4300          else
4301             return True;
4302          end if;
4303
4304       --  Integer and character literals always have valid values, where
4305       --  appropriate these will be range checked in any case.
4306
4307       elsif Nkind (Expr) = N_Integer_Literal
4308               or else
4309             Nkind (Expr) = N_Character_Literal
4310       then
4311          return True;
4312
4313       --  If we have a type conversion or a qualification of a known valid
4314       --  value, then the result will always be valid.
4315
4316       elsif Nkind (Expr) = N_Type_Conversion
4317               or else
4318             Nkind (Expr) = N_Qualified_Expression
4319       then
4320          return Expr_Known_Valid (Expression (Expr));
4321
4322       --  The result of any operator is always considered valid, since we
4323       --  assume the necessary checks are done by the operator. For operators
4324       --  on floating-point operations, we must also check when the operation
4325       --  is the right-hand side of an assignment, or is an actual in a call.
4326
4327       elsif Nkind (Expr) in N_Op then
4328          if Is_Floating_Point_Type (Typ)
4329             and then Validity_Check_Floating_Point
4330             and then
4331               (Nkind (Parent (Expr)) = N_Assignment_Statement
4332                 or else Nkind (Parent (Expr)) = N_Function_Call
4333                 or else Nkind (Parent (Expr)) = N_Parameter_Association)
4334          then
4335             return False;
4336          else
4337             return True;
4338          end if;
4339
4340       --  The result of a membership test is always valid, since it is true or
4341       --  false, there are no other possibilities.
4342
4343       elsif Nkind (Expr) in N_Membership_Test then
4344          return True;
4345
4346       --  For all other cases, we do not know the expression is valid
4347
4348       else
4349          return False;
4350       end if;
4351    end Expr_Known_Valid;
4352
4353    ----------------
4354    -- Find_Check --
4355    ----------------
4356
4357    procedure Find_Check
4358      (Expr        : Node_Id;
4359       Check_Type  : Character;
4360       Target_Type : Entity_Id;
4361       Entry_OK    : out Boolean;
4362       Check_Num   : out Nat;
4363       Ent         : out Entity_Id;
4364       Ofs         : out Uint)
4365    is
4366       function Within_Range_Of
4367         (Target_Type : Entity_Id;
4368          Check_Type  : Entity_Id) return Boolean;
4369       --  Given a requirement for checking a range against Target_Type, and
4370       --  and a range Check_Type against which a check has already been made,
4371       --  determines if the check against check type is sufficient to ensure
4372       --  that no check against Target_Type is required.
4373
4374       ---------------------
4375       -- Within_Range_Of --
4376       ---------------------
4377
4378       function Within_Range_Of
4379         (Target_Type : Entity_Id;
4380          Check_Type  : Entity_Id) return Boolean
4381       is
4382       begin
4383          if Target_Type = Check_Type then
4384             return True;
4385
4386          else
4387             declare
4388                Tlo : constant Node_Id := Type_Low_Bound  (Target_Type);
4389                Thi : constant Node_Id := Type_High_Bound (Target_Type);
4390                Clo : constant Node_Id := Type_Low_Bound  (Check_Type);
4391                Chi : constant Node_Id := Type_High_Bound (Check_Type);
4392
4393             begin
4394                if (Tlo = Clo
4395                      or else (Compile_Time_Known_Value (Tlo)
4396                                 and then
4397                               Compile_Time_Known_Value (Clo)
4398                                 and then
4399                               Expr_Value (Clo) >= Expr_Value (Tlo)))
4400                  and then
4401                   (Thi = Chi
4402                      or else (Compile_Time_Known_Value (Thi)
4403                                 and then
4404                               Compile_Time_Known_Value (Chi)
4405                                 and then
4406                               Expr_Value (Chi) <= Expr_Value (Clo)))
4407                then
4408                   return True;
4409                else
4410                   return False;
4411                end if;
4412             end;
4413          end if;
4414       end Within_Range_Of;
4415
4416    --  Start of processing for Find_Check
4417
4418    begin
4419       --  Establish default, in case no entry is found
4420
4421       Check_Num := 0;
4422
4423       --  Case of expression is simple entity reference
4424
4425       if Is_Entity_Name (Expr) then
4426          Ent := Entity (Expr);
4427          Ofs := Uint_0;
4428
4429       --  Case of expression is entity + known constant
4430
4431       elsif Nkind (Expr) = N_Op_Add
4432         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4433         and then Is_Entity_Name (Left_Opnd (Expr))
4434       then
4435          Ent := Entity (Left_Opnd (Expr));
4436          Ofs := Expr_Value (Right_Opnd (Expr));
4437
4438       --  Case of expression is entity - known constant
4439
4440       elsif Nkind (Expr) = N_Op_Subtract
4441         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4442         and then Is_Entity_Name (Left_Opnd (Expr))
4443       then
4444          Ent := Entity (Left_Opnd (Expr));
4445          Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4446
4447       --  Any other expression is not of the right form
4448
4449       else
4450          Ent := Empty;
4451          Ofs := Uint_0;
4452          Entry_OK := False;
4453          return;
4454       end if;
4455
4456       --  Come here with expression of appropriate form, check if entity is an
4457       --  appropriate one for our purposes.
4458
4459       if (Ekind (Ent) = E_Variable
4460             or else Is_Constant_Object (Ent))
4461         and then not Is_Library_Level_Entity (Ent)
4462       then
4463          Entry_OK := True;
4464       else
4465          Entry_OK := False;
4466          return;
4467       end if;
4468
4469       --  See if there is matching check already
4470
4471       for J in reverse 1 .. Num_Saved_Checks loop
4472          declare
4473             SC : Saved_Check renames Saved_Checks (J);
4474
4475          begin
4476             if SC.Killed = False
4477               and then SC.Entity = Ent
4478               and then SC.Offset = Ofs
4479               and then SC.Check_Type = Check_Type
4480               and then Within_Range_Of (Target_Type, SC.Target_Type)
4481             then
4482                Check_Num := J;
4483                return;
4484             end if;
4485          end;
4486       end loop;
4487
4488       --  If we fall through entry was not found
4489
4490       return;
4491    end Find_Check;
4492
4493    ---------------------------------
4494    -- Generate_Discriminant_Check --
4495    ---------------------------------
4496
4497    --  Note: the code for this procedure is derived from the
4498    --  Emit_Discriminant_Check Routine in trans.c.
4499
4500    procedure Generate_Discriminant_Check (N : Node_Id) is
4501       Loc  : constant Source_Ptr := Sloc (N);
4502       Pref : constant Node_Id    := Prefix (N);
4503       Sel  : constant Node_Id    := Selector_Name (N);
4504
4505       Orig_Comp : constant Entity_Id :=
4506                     Original_Record_Component (Entity (Sel));
4507       --  The original component to be checked
4508
4509       Discr_Fct : constant Entity_Id :=
4510                     Discriminant_Checking_Func (Orig_Comp);
4511       --  The discriminant checking function
4512
4513       Discr : Entity_Id;
4514       --  One discriminant to be checked in the type
4515
4516       Real_Discr : Entity_Id;
4517       --  Actual discriminant in the call
4518
4519       Pref_Type : Entity_Id;
4520       --  Type of relevant prefix (ignoring private/access stuff)
4521
4522       Args : List_Id;
4523       --  List of arguments for function call
4524
4525       Formal : Entity_Id;
4526       --  Keep track of the formal corresponding to the actual we build for
4527       --  each discriminant, in order to be able to perform the necessary type
4528       --  conversions.
4529
4530       Scomp : Node_Id;
4531       --  Selected component reference for checking function argument
4532
4533    begin
4534       Pref_Type := Etype (Pref);
4535
4536       --  Force evaluation of the prefix, so that it does not get evaluated
4537       --  twice (once for the check, once for the actual reference). Such a
4538       --  double evaluation is always a potential source of inefficiency,
4539       --  and is functionally incorrect in the volatile case, or when the
4540       --  prefix may have side-effects. An entity or a component of an
4541       --  entity requires no evaluation.
4542
4543       if Is_Entity_Name (Pref) then
4544          if Treat_As_Volatile (Entity (Pref)) then
4545             Force_Evaluation (Pref, Name_Req => True);
4546          end if;
4547
4548       elsif Treat_As_Volatile (Etype (Pref)) then
4549             Force_Evaluation (Pref, Name_Req => True);
4550
4551       elsif Nkind (Pref) = N_Selected_Component
4552         and then Is_Entity_Name (Prefix (Pref))
4553       then
4554          null;
4555
4556       else
4557          Force_Evaluation (Pref, Name_Req => True);
4558       end if;
4559
4560       --  For a tagged type, use the scope of the original component to
4561       --  obtain the type, because ???
4562
4563       if Is_Tagged_Type (Scope (Orig_Comp)) then
4564          Pref_Type := Scope (Orig_Comp);
4565
4566       --  For an untagged derived type, use the discriminants of the parent
4567       --  which have been renamed in the derivation, possibly by a one-to-many
4568       --  discriminant constraint. For non-tagged type, initially get the Etype
4569       --  of the prefix
4570
4571       else
4572          if Is_Derived_Type (Pref_Type)
4573            and then Number_Discriminants (Pref_Type) /=
4574                     Number_Discriminants (Etype (Base_Type (Pref_Type)))
4575          then
4576             Pref_Type := Etype (Base_Type (Pref_Type));
4577          end if;
4578       end if;
4579
4580       --  We definitely should have a checking function, This routine should
4581       --  not be called if no discriminant checking function is present.
4582
4583       pragma Assert (Present (Discr_Fct));
4584
4585       --  Create the list of the actual parameters for the call. This list
4586       --  is the list of the discriminant fields of the record expression to
4587       --  be discriminant checked.
4588
4589       Args   := New_List;
4590       Formal := First_Formal (Discr_Fct);
4591       Discr  := First_Discriminant (Pref_Type);
4592       while Present (Discr) loop
4593
4594          --  If we have a corresponding discriminant field, and a parent
4595          --  subtype is present, then we want to use the corresponding
4596          --  discriminant since this is the one with the useful value.
4597
4598          if Present (Corresponding_Discriminant (Discr))
4599            and then Ekind (Pref_Type) = E_Record_Type
4600            and then Present (Parent_Subtype (Pref_Type))
4601          then
4602             Real_Discr := Corresponding_Discriminant (Discr);
4603          else
4604             Real_Discr := Discr;
4605          end if;
4606
4607          --  Construct the reference to the discriminant
4608
4609          Scomp :=
4610            Make_Selected_Component (Loc,
4611              Prefix =>
4612                Unchecked_Convert_To (Pref_Type,
4613                  Duplicate_Subexpr (Pref)),
4614              Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4615
4616          --  Manually analyze and resolve this selected component. We really
4617          --  want it just as it appears above, and do not want the expander
4618          --  playing discriminal games etc with this reference. Then we append
4619          --  the argument to the list we are gathering.
4620
4621          Set_Etype (Scomp, Etype (Real_Discr));
4622          Set_Analyzed (Scomp, True);
4623          Append_To (Args, Convert_To (Etype (Formal), Scomp));
4624
4625          Next_Formal_With_Extras (Formal);
4626          Next_Discriminant (Discr);
4627       end loop;
4628
4629       --  Now build and insert the call
4630
4631       Insert_Action (N,
4632         Make_Raise_Constraint_Error (Loc,
4633           Condition =>
4634             Make_Function_Call (Loc,
4635               Name => New_Occurrence_Of (Discr_Fct, Loc),
4636               Parameter_Associations => Args),
4637           Reason => CE_Discriminant_Check_Failed));
4638    end Generate_Discriminant_Check;
4639
4640    ---------------------------
4641    -- Generate_Index_Checks --
4642    ---------------------------
4643
4644    procedure Generate_Index_Checks (N : Node_Id) is
4645
4646       function Entity_Of_Prefix return Entity_Id;
4647       --  Returns the entity of the prefix of N (or Empty if not found)
4648
4649       ----------------------
4650       -- Entity_Of_Prefix --
4651       ----------------------
4652
4653       function Entity_Of_Prefix return Entity_Id is
4654          P : Node_Id;
4655
4656       begin
4657          P := Prefix (N);
4658          while not Is_Entity_Name (P) loop
4659             if not Nkind_In (P, N_Selected_Component,
4660                                 N_Indexed_Component)
4661             then
4662                return Empty;
4663             end if;
4664
4665             P := Prefix (P);
4666          end loop;
4667
4668          return Entity (P);
4669       end Entity_Of_Prefix;
4670
4671       --  Local variables
4672
4673       Loc   : constant Source_Ptr := Sloc (N);
4674       A     : constant Node_Id    := Prefix (N);
4675       A_Ent : constant Entity_Id  := Entity_Of_Prefix;
4676       Sub   : Node_Id;
4677
4678    --  Start of processing for Generate_Index_Checks
4679
4680    begin
4681       --  Ignore call if the prefix is not an array since we have a serious
4682       --  error in the sources. Ignore it also if index checks are suppressed
4683       --  for array object or type.
4684
4685       if not Is_Array_Type (Etype (A))
4686         or else (Present (A_Ent)
4687                   and then Index_Checks_Suppressed (A_Ent))
4688         or else Index_Checks_Suppressed (Etype (A))
4689       then
4690          return;
4691       end if;
4692
4693       --  Generate a raise of constraint error with the appropriate reason and
4694       --  a condition of the form:
4695
4696       --    Base_Type (Sub) not in Array'Range (Subscript)
4697
4698       --  Note that the reason we generate the conversion to the base type here
4699       --  is that we definitely want the range check to take place, even if it
4700       --  looks like the subtype is OK. Optimization considerations that allow
4701       --  us to omit the check have already been taken into account in the
4702       --  setting of the Do_Range_Check flag earlier on.
4703
4704       Sub := First (Expressions (N));
4705
4706       --  Handle string literals
4707
4708       if Ekind (Etype (A)) = E_String_Literal_Subtype then
4709          if Do_Range_Check (Sub) then
4710             Set_Do_Range_Check (Sub, False);
4711
4712             --  For string literals we obtain the bounds of the string from the
4713             --  associated subtype.
4714
4715             Insert_Action (N,
4716                Make_Raise_Constraint_Error (Loc,
4717                  Condition =>
4718                     Make_Not_In (Loc,
4719                       Left_Opnd  =>
4720                         Convert_To (Base_Type (Etype (Sub)),
4721                           Duplicate_Subexpr_Move_Checks (Sub)),
4722                       Right_Opnd =>
4723                         Make_Attribute_Reference (Loc,
4724                           Prefix         => New_Reference_To (Etype (A), Loc),
4725                           Attribute_Name => Name_Range)),
4726                  Reason => CE_Index_Check_Failed));
4727          end if;
4728
4729       --  General case
4730
4731       else
4732          declare
4733             A_Idx   : Node_Id := Empty;
4734             A_Range : Node_Id;
4735             Ind     : Nat;
4736             Num     : List_Id;
4737             Range_N : Node_Id;
4738
4739          begin
4740             A_Idx := First_Index (Etype (A));
4741             Ind   := 1;
4742             while Present (Sub) loop
4743                if Do_Range_Check (Sub) then
4744                   Set_Do_Range_Check (Sub, False);
4745
4746                   --  Force evaluation except for the case of a simple name of
4747                   --  a non-volatile entity.
4748
4749                   if not Is_Entity_Name (Sub)
4750                     or else Treat_As_Volatile (Entity (Sub))
4751                   then
4752                      Force_Evaluation (Sub);
4753                   end if;
4754
4755                   if Nkind (A_Idx) = N_Range then
4756                      A_Range := A_Idx;
4757
4758                   elsif Nkind (A_Idx) = N_Identifier
4759                     or else Nkind (A_Idx) = N_Expanded_Name
4760                   then
4761                      A_Range := Scalar_Range (Entity (A_Idx));
4762
4763                   else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
4764                      A_Range := Range_Expression (Constraint (A_Idx));
4765                   end if;
4766
4767                   --  For array objects with constant bounds we can generate
4768                   --  the index check using the bounds of the type of the index
4769
4770                   if Present (A_Ent)
4771                     and then Ekind (A_Ent) = E_Variable
4772                     and then Is_Constant_Bound (Low_Bound (A_Range))
4773                     and then Is_Constant_Bound (High_Bound (A_Range))
4774                   then
4775                      Range_N :=
4776                        Make_Attribute_Reference (Loc,
4777                          Prefix         =>
4778                            New_Reference_To (Etype (A_Idx), Loc),
4779                          Attribute_Name => Name_Range);
4780
4781                   --  For arrays with non-constant bounds we cannot generate
4782                   --  the index check using the bounds of the type of the index
4783                   --  since it may reference discriminants of some enclosing
4784                   --  type. We obtain the bounds directly from the prefix
4785                   --  object.
4786
4787                   else
4788                      if Ind = 1 then
4789                         Num := No_List;
4790                      else
4791                         Num := New_List (Make_Integer_Literal (Loc, Ind));
4792                      end if;
4793
4794                      Range_N :=
4795                        Make_Attribute_Reference (Loc,
4796                          Prefix =>
4797                            Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
4798                          Attribute_Name => Name_Range,
4799                          Expressions    => Num);
4800                   end if;
4801
4802                   Insert_Action (N,
4803                      Make_Raise_Constraint_Error (Loc,
4804                        Condition =>
4805                           Make_Not_In (Loc,
4806                             Left_Opnd  =>
4807                               Convert_To (Base_Type (Etype (Sub)),
4808                                 Duplicate_Subexpr_Move_Checks (Sub)),
4809                             Right_Opnd => Range_N),
4810                        Reason => CE_Index_Check_Failed));
4811                end if;
4812
4813                A_Idx := Next_Index (A_Idx);
4814                Ind := Ind + 1;
4815                Next (Sub);
4816             end loop;
4817          end;
4818       end if;
4819    end Generate_Index_Checks;
4820
4821    --------------------------
4822    -- Generate_Range_Check --
4823    --------------------------
4824
4825    procedure Generate_Range_Check
4826      (N           : Node_Id;
4827       Target_Type : Entity_Id;
4828       Reason      : RT_Exception_Code)
4829    is
4830       Loc              : constant Source_Ptr := Sloc (N);
4831       Source_Type      : constant Entity_Id  := Etype (N);
4832       Source_Base_Type : constant Entity_Id  := Base_Type (Source_Type);
4833       Target_Base_Type : constant Entity_Id  := Base_Type (Target_Type);
4834
4835    begin
4836       --  First special case, if the source type is already within the range
4837       --  of the target type, then no check is needed (probably we should have
4838       --  stopped Do_Range_Check from being set in the first place, but better
4839       --  late than later in preventing junk code!
4840
4841       --  We do NOT apply this if the source node is a literal, since in this
4842       --  case the literal has already been labeled as having the subtype of
4843       --  the target.
4844
4845       if In_Subrange_Of (Source_Type, Target_Type)
4846         and then not
4847           (Nkind (N) = N_Integer_Literal
4848              or else
4849            Nkind (N) = N_Real_Literal
4850              or else
4851            Nkind (N) = N_Character_Literal
4852              or else
4853            (Is_Entity_Name (N)
4854               and then Ekind (Entity (N)) = E_Enumeration_Literal))
4855       then
4856          return;
4857       end if;
4858
4859       --  We need a check, so force evaluation of the node, so that it does
4860       --  not get evaluated twice (once for the check, once for the actual
4861       --  reference). Such a double evaluation is always a potential source
4862       --  of inefficiency, and is functionally incorrect in the volatile case.
4863
4864       if not Is_Entity_Name (N)
4865         or else Treat_As_Volatile (Entity (N))
4866       then
4867          Force_Evaluation (N);
4868       end if;
4869
4870       --  The easiest case is when Source_Base_Type and Target_Base_Type are
4871       --  the same since in this case we can simply do a direct check of the
4872       --  value of N against the bounds of Target_Type.
4873
4874       --    [constraint_error when N not in Target_Type]
4875
4876       --  Note: this is by far the most common case, for example all cases of
4877       --  checks on the RHS of assignments are in this category, but not all
4878       --  cases are like this. Notably conversions can involve two types.
4879
4880       if Source_Base_Type = Target_Base_Type then
4881          Insert_Action (N,
4882            Make_Raise_Constraint_Error (Loc,
4883              Condition =>
4884                Make_Not_In (Loc,
4885                  Left_Opnd  => Duplicate_Subexpr (N),
4886                  Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4887              Reason => Reason));
4888
4889       --  Next test for the case where the target type is within the bounds
4890       --  of the base type of the source type, since in this case we can
4891       --  simply convert these bounds to the base type of T to do the test.
4892
4893       --    [constraint_error when N not in
4894       --       Source_Base_Type (Target_Type'First)
4895       --         ..
4896       --       Source_Base_Type(Target_Type'Last))]
4897
4898       --  The conversions will always work and need no check
4899
4900       --  Unchecked_Convert_To is used instead of Convert_To to handle the case
4901       --  of converting from an enumeration value to an integer type, such as
4902       --  occurs for the case of generating a range check on Enum'Val(Exp)
4903       --  (which used to be handled by gigi). This is OK, since the conversion
4904       --  itself does not require a check.
4905
4906       elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4907          Insert_Action (N,
4908            Make_Raise_Constraint_Error (Loc,
4909              Condition =>
4910                Make_Not_In (Loc,
4911                  Left_Opnd  => Duplicate_Subexpr (N),
4912
4913                  Right_Opnd =>
4914                    Make_Range (Loc,
4915                      Low_Bound =>
4916                        Unchecked_Convert_To (Source_Base_Type,
4917                          Make_Attribute_Reference (Loc,
4918                            Prefix =>
4919                              New_Occurrence_Of (Target_Type, Loc),
4920                            Attribute_Name => Name_First)),
4921
4922                      High_Bound =>
4923                        Unchecked_Convert_To (Source_Base_Type,
4924                          Make_Attribute_Reference (Loc,
4925                            Prefix =>
4926                              New_Occurrence_Of (Target_Type, Loc),
4927                            Attribute_Name => Name_Last)))),
4928              Reason => Reason));
4929
4930       --  Note that at this stage we now that the Target_Base_Type is not in
4931       --  the range of the Source_Base_Type (since even the Target_Type itself
4932       --  is not in this range). It could still be the case that Source_Type is
4933       --  in range of the target base type since we have not checked that case.
4934
4935       --  If that is the case, we can freely convert the source to the target,
4936       --  and then test the target result against the bounds.
4937
4938       elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4939
4940          --  We make a temporary to hold the value of the converted value
4941          --  (converted to the base type), and then we will do the test against
4942          --  this temporary.
4943
4944          --     Tnn : constant Target_Base_Type := Target_Base_Type (N);
4945          --     [constraint_error when Tnn not in Target_Type]
4946
4947          --  Then the conversion itself is replaced by an occurrence of Tnn
4948
4949          declare
4950             Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4951
4952          begin
4953             Insert_Actions (N, New_List (
4954               Make_Object_Declaration (Loc,
4955                 Defining_Identifier => Tnn,
4956                 Object_Definition   =>
4957                   New_Occurrence_Of (Target_Base_Type, Loc),
4958                 Constant_Present    => True,
4959                 Expression          =>
4960                   Make_Type_Conversion (Loc,
4961                     Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4962                     Expression   => Duplicate_Subexpr (N))),
4963
4964               Make_Raise_Constraint_Error (Loc,
4965                 Condition =>
4966                   Make_Not_In (Loc,
4967                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
4968                     Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4969
4970                 Reason => Reason)));
4971
4972             Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4973
4974             --  Set the type of N, because the declaration for Tnn might not
4975             --  be analyzed yet, as is the case if N appears within a record
4976             --  declaration, as a discriminant constraint or expression.
4977
4978             Set_Etype (N, Target_Base_Type);
4979          end;
4980
4981       --  At this stage, we know that we have two scalar types, which are
4982       --  directly convertible, and where neither scalar type has a base
4983       --  range that is in the range of the other scalar type.
4984
4985       --  The only way this can happen is with a signed and unsigned type.
4986       --  So test for these two cases:
4987
4988       else
4989          --  Case of the source is unsigned and the target is signed
4990
4991          if Is_Unsigned_Type (Source_Base_Type)
4992            and then not Is_Unsigned_Type (Target_Base_Type)
4993          then
4994             --  If the source is unsigned and the target is signed, then we
4995             --  know that the source is not shorter than the target (otherwise
4996             --  the source base type would be in the target base type range).
4997
4998             --  In other words, the unsigned type is either the same size as
4999             --  the target, or it is larger. It cannot be smaller.
5000
5001             pragma Assert
5002               (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
5003
5004             --  We only need to check the low bound if the low bound of the
5005             --  target type is non-negative. If the low bound of the target
5006             --  type is negative, then we know that we will fit fine.
5007
5008             --  If the high bound of the target type is negative, then we
5009             --  know we have a constraint error, since we can't possibly
5010             --  have a negative source.
5011
5012             --  With these two checks out of the way, we can do the check
5013             --  using the source type safely
5014
5015             --  This is definitely the most annoying case!
5016
5017             --    [constraint_error
5018             --       when (Target_Type'First >= 0
5019             --               and then
5020             --                 N < Source_Base_Type (Target_Type'First))
5021             --         or else Target_Type'Last < 0
5022             --         or else N > Source_Base_Type (Target_Type'Last)];
5023
5024             --  We turn off all checks since we know that the conversions
5025             --  will work fine, given the guards for negative values.
5026
5027             Insert_Action (N,
5028               Make_Raise_Constraint_Error (Loc,
5029                 Condition =>
5030                   Make_Or_Else (Loc,
5031                     Make_Or_Else (Loc,
5032                       Left_Opnd =>
5033                         Make_And_Then (Loc,
5034                           Left_Opnd => Make_Op_Ge (Loc,
5035                             Left_Opnd =>
5036                               Make_Attribute_Reference (Loc,
5037                                 Prefix =>
5038                                   New_Occurrence_Of (Target_Type, Loc),
5039                                 Attribute_Name => Name_First),
5040                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
5041
5042                           Right_Opnd =>
5043                             Make_Op_Lt (Loc,
5044                               Left_Opnd => Duplicate_Subexpr (N),
5045                               Right_Opnd =>
5046                                 Convert_To (Source_Base_Type,
5047                                   Make_Attribute_Reference (Loc,
5048                                     Prefix =>
5049                                       New_Occurrence_Of (Target_Type, Loc),
5050                                     Attribute_Name => Name_First)))),
5051
5052                       Right_Opnd =>
5053                         Make_Op_Lt (Loc,
5054                           Left_Opnd =>
5055                             Make_Attribute_Reference (Loc,
5056                               Prefix => New_Occurrence_Of (Target_Type, Loc),
5057                               Attribute_Name => Name_Last),
5058                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
5059
5060                     Right_Opnd =>
5061                       Make_Op_Gt (Loc,
5062                         Left_Opnd => Duplicate_Subexpr (N),
5063                         Right_Opnd =>
5064                           Convert_To (Source_Base_Type,
5065                             Make_Attribute_Reference (Loc,
5066                               Prefix => New_Occurrence_Of (Target_Type, Loc),
5067                               Attribute_Name => Name_Last)))),
5068
5069                 Reason => Reason),
5070               Suppress  => All_Checks);
5071
5072          --  Only remaining possibility is that the source is signed and
5073          --  the target is unsigned.
5074
5075          else
5076             pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
5077                              and then Is_Unsigned_Type (Target_Base_Type));
5078
5079             --  If the source is signed and the target is unsigned, then we
5080             --  know that the target is not shorter than the source (otherwise
5081             --  the target base type would be in the source base type range).
5082
5083             --  In other words, the unsigned type is either the same size as
5084             --  the target, or it is larger. It cannot be smaller.
5085
5086             --  Clearly we have an error if the source value is negative since
5087             --  no unsigned type can have negative values. If the source type
5088             --  is non-negative, then the check can be done using the target
5089             --  type.
5090
5091             --    Tnn : constant Target_Base_Type (N) := Target_Type;
5092
5093             --    [constraint_error
5094             --       when N < 0 or else Tnn not in Target_Type];
5095
5096             --  We turn off all checks for the conversion of N to the target
5097             --  base type, since we generate the explicit check to ensure that
5098             --  the value is non-negative
5099
5100             declare
5101                Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
5102
5103             begin
5104                Insert_Actions (N, New_List (
5105                  Make_Object_Declaration (Loc,
5106                    Defining_Identifier => Tnn,
5107                    Object_Definition   =>
5108                      New_Occurrence_Of (Target_Base_Type, Loc),
5109                    Constant_Present    => True,
5110                    Expression          =>
5111                      Make_Unchecked_Type_Conversion (Loc,
5112                        Subtype_Mark =>
5113                          New_Occurrence_Of (Target_Base_Type, Loc),
5114                        Expression   => Duplicate_Subexpr (N))),
5115
5116                  Make_Raise_Constraint_Error (Loc,
5117                    Condition =>
5118                      Make_Or_Else (Loc,
5119                        Left_Opnd =>
5120                          Make_Op_Lt (Loc,
5121                            Left_Opnd  => Duplicate_Subexpr (N),
5122                            Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
5123
5124                        Right_Opnd =>
5125                          Make_Not_In (Loc,
5126                            Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
5127                            Right_Opnd =>
5128                              New_Occurrence_Of (Target_Type, Loc))),
5129
5130                    Reason => Reason)),
5131                  Suppress => All_Checks);
5132
5133                --  Set the Etype explicitly, because Insert_Actions may have
5134                --  placed the declaration in the freeze list for an enclosing
5135                --  construct, and thus it is not analyzed yet.
5136
5137                Set_Etype (Tnn, Target_Base_Type);
5138                Rewrite (N, New_Occurrence_Of (Tnn, Loc));
5139             end;
5140          end if;
5141       end if;
5142    end Generate_Range_Check;
5143
5144    ------------------
5145    -- Get_Check_Id --
5146    ------------------
5147
5148    function Get_Check_Id (N : Name_Id) return Check_Id is
5149    begin
5150       --  For standard check name, we can do a direct computation
5151
5152       if N in First_Check_Name .. Last_Check_Name then
5153          return Check_Id (N - (First_Check_Name - 1));
5154
5155       --  For non-standard names added by pragma Check_Name, search table
5156
5157       else
5158          for J in All_Checks + 1 .. Check_Names.Last loop
5159             if Check_Names.Table (J) = N then
5160                return J;
5161             end if;
5162          end loop;
5163       end if;
5164
5165       --  No matching name found
5166
5167       return No_Check_Id;
5168    end Get_Check_Id;
5169
5170    ---------------------
5171    -- Get_Discriminal --
5172    ---------------------
5173
5174    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
5175       Loc : constant Source_Ptr := Sloc (E);
5176       D   : Entity_Id;
5177       Sc  : Entity_Id;
5178
5179    begin
5180       --  The bound can be a bona fide parameter of a protected operation,
5181       --  rather than a prival encoded as an in-parameter.
5182
5183       if No (Discriminal_Link (Entity (Bound))) then
5184          return Bound;
5185       end if;
5186
5187       --  Climb the scope stack looking for an enclosing protected type. If
5188       --  we run out of scopes, return the bound itself.
5189
5190       Sc := Scope (E);
5191       while Present (Sc) loop
5192          if Sc = Standard_Standard then
5193             return Bound;
5194
5195          elsif Ekind (Sc) = E_Protected_Type then
5196             exit;
5197          end if;
5198
5199          Sc := Scope (Sc);
5200       end loop;
5201
5202       D := First_Discriminant (Sc);
5203       while Present (D) loop
5204          if Chars (D) = Chars (Bound) then
5205             return New_Occurrence_Of (Discriminal (D), Loc);
5206          end if;
5207
5208          Next_Discriminant (D);
5209       end loop;
5210
5211       return Bound;
5212    end Get_Discriminal;
5213
5214    ----------------------
5215    -- Get_Range_Checks --
5216    ----------------------
5217
5218    function Get_Range_Checks
5219      (Ck_Node    : Node_Id;
5220       Target_Typ : Entity_Id;
5221       Source_Typ : Entity_Id := Empty;
5222       Warn_Node  : Node_Id   := Empty) return Check_Result
5223    is
5224    begin
5225       return Selected_Range_Checks
5226         (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
5227    end Get_Range_Checks;
5228
5229    ------------------
5230    -- Guard_Access --
5231    ------------------
5232
5233    function Guard_Access
5234      (Cond    : Node_Id;
5235       Loc     : Source_Ptr;
5236       Ck_Node : Node_Id) return Node_Id
5237    is
5238    begin
5239       if Nkind (Cond) = N_Or_Else then
5240          Set_Paren_Count (Cond, 1);
5241       end if;
5242
5243       if Nkind (Ck_Node) = N_Allocator then
5244          return Cond;
5245       else
5246          return
5247            Make_And_Then (Loc,
5248              Left_Opnd =>
5249                Make_Op_Ne (Loc,
5250                  Left_Opnd  => Duplicate_Subexpr_No_Checks (Ck_Node),
5251                  Right_Opnd => Make_Null (Loc)),
5252              Right_Opnd => Cond);
5253       end if;
5254    end Guard_Access;
5255
5256    -----------------------------
5257    -- Index_Checks_Suppressed --
5258    -----------------------------
5259
5260    function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
5261    begin
5262       if Present (E) and then Checks_May_Be_Suppressed (E) then
5263          return Is_Check_Suppressed (E, Index_Check);
5264       else
5265          return Scope_Suppress (Index_Check);
5266       end if;
5267    end Index_Checks_Suppressed;
5268
5269    ----------------
5270    -- Initialize --
5271    ----------------
5272
5273    procedure Initialize is
5274    begin
5275       for J in Determine_Range_Cache_N'Range loop
5276          Determine_Range_Cache_N (J) := Empty;
5277       end loop;
5278
5279       Check_Names.Init;
5280
5281       for J in Int range 1 .. All_Checks loop
5282          Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
5283       end loop;
5284    end Initialize;
5285
5286    -------------------------
5287    -- Insert_Range_Checks --
5288    -------------------------
5289
5290    procedure Insert_Range_Checks
5291      (Checks       : Check_Result;
5292       Node         : Node_Id;
5293       Suppress_Typ : Entity_Id;
5294       Static_Sloc  : Source_Ptr := No_Location;
5295       Flag_Node    : Node_Id    := Empty;
5296       Do_Before    : Boolean    := False)
5297    is
5298       Internal_Flag_Node   : Node_Id    := Flag_Node;
5299       Internal_Static_Sloc : Source_Ptr := Static_Sloc;
5300
5301       Check_Node : Node_Id;
5302       Checks_On  : constant Boolean :=
5303                      (not Index_Checks_Suppressed (Suppress_Typ))
5304                        or else
5305                      (not Range_Checks_Suppressed (Suppress_Typ));
5306
5307    begin
5308       --  For now we just return if Checks_On is false, however this should be
5309       --  enhanced to check for an always True value in the condition and to
5310       --  generate a compilation warning???
5311
5312       if not Full_Expander_Active or else not Checks_On then
5313          return;
5314       end if;
5315
5316       if Static_Sloc = No_Location then
5317          Internal_Static_Sloc := Sloc (Node);
5318       end if;
5319
5320       if No (Flag_Node) then
5321          Internal_Flag_Node := Node;
5322       end if;
5323
5324       for J in 1 .. 2 loop
5325          exit when No (Checks (J));
5326
5327          if Nkind (Checks (J)) = N_Raise_Constraint_Error
5328            and then Present (Condition (Checks (J)))
5329          then
5330             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
5331                Check_Node := Checks (J);
5332                Mark_Rewrite_Insertion (Check_Node);
5333
5334                if Do_Before then
5335                   Insert_Before_And_Analyze (Node, Check_Node);
5336                else
5337                   Insert_After_And_Analyze (Node, Check_Node);
5338                end if;
5339
5340                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
5341             end if;
5342
5343          else
5344             Check_Node :=
5345               Make_Raise_Constraint_Error (Internal_Static_Sloc,
5346                 Reason => CE_Range_Check_Failed);
5347             Mark_Rewrite_Insertion (Check_Node);
5348
5349             if Do_Before then
5350                Insert_Before_And_Analyze (Node, Check_Node);
5351             else
5352                Insert_After_And_Analyze (Node, Check_Node);
5353             end if;
5354          end if;
5355       end loop;
5356    end Insert_Range_Checks;
5357
5358    ------------------------
5359    -- Insert_Valid_Check --
5360    ------------------------
5361
5362    procedure Insert_Valid_Check (Expr : Node_Id) is
5363       Loc : constant Source_Ptr := Sloc (Expr);
5364       Exp : Node_Id;
5365
5366    begin
5367       --  Do not insert if checks off, or if not checking validity or
5368       --  if expression is known to be valid
5369
5370       if not Validity_Checks_On
5371         or else Range_Or_Validity_Checks_Suppressed (Expr)
5372         or else Expr_Known_Valid (Expr)
5373       then
5374          return;
5375       end if;
5376
5377       --  If we have a checked conversion, then validity check applies to
5378       --  the expression inside the conversion, not the result, since if
5379       --  the expression inside is valid, then so is the conversion result.
5380
5381       Exp := Expr;
5382       while Nkind (Exp) = N_Type_Conversion loop
5383          Exp := Expression (Exp);
5384       end loop;
5385
5386       --  We are about to insert the validity check for Exp. We save and
5387       --  reset the Do_Range_Check flag over this validity check, and then
5388       --  put it back for the final original reference (Exp may be rewritten).
5389
5390       declare
5391          DRC : constant Boolean := Do_Range_Check (Exp);
5392
5393       begin
5394          Set_Do_Range_Check (Exp, False);
5395
5396          --  Force evaluation to avoid multiple reads for atomic/volatile
5397
5398          if Is_Entity_Name (Exp)
5399            and then Is_Volatile (Entity (Exp))
5400          then
5401             Force_Evaluation (Exp, Name_Req => True);
5402          end if;
5403
5404          --  Insert the validity check. Note that we do this with validity
5405          --  checks turned off, to avoid recursion, we do not want validity
5406          --  checks on the validity checking code itself!
5407
5408          Insert_Action
5409            (Expr,
5410             Make_Raise_Constraint_Error (Loc,
5411               Condition =>
5412                 Make_Op_Not (Loc,
5413                   Right_Opnd =>
5414                     Make_Attribute_Reference (Loc,
5415                       Prefix =>
5416                         Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
5417                       Attribute_Name => Name_Valid)),
5418               Reason => CE_Invalid_Data),
5419             Suppress => Validity_Check);
5420
5421          --  If the expression is a reference to an element of a bit-packed
5422          --  array, then it is rewritten as a renaming declaration. If the
5423          --  expression is an actual in a call, it has not been expanded,
5424          --  waiting for the proper point at which to do it. The same happens
5425          --  with renamings, so that we have to force the expansion now. This
5426          --  non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
5427          --  and exp_ch6.adb.
5428
5429          if Is_Entity_Name (Exp)
5430            and then Nkind (Parent (Entity (Exp))) =
5431                       N_Object_Renaming_Declaration
5432          then
5433             declare
5434                Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
5435             begin
5436                if Nkind (Old_Exp) = N_Indexed_Component
5437                  and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
5438                then
5439                   Expand_Packed_Element_Reference (Old_Exp);
5440                end if;
5441             end;
5442          end if;
5443
5444          --  Put back the Do_Range_Check flag on the resulting (possibly
5445          --  rewritten) expression.
5446
5447          --  Note: it might be thought that a validity check is not required
5448          --  when a range check is present, but that's not the case, because
5449          --  the back end is allowed to assume for the range check that the
5450          --  operand is within its declared range (an assumption that validity
5451          --  checking is all about NOT assuming!)
5452
5453          --  Note: no need to worry about Possible_Local_Raise here, it will
5454          --  already have been called if original node has Do_Range_Check set.
5455
5456          Set_Do_Range_Check (Exp, DRC);
5457       end;
5458    end Insert_Valid_Check;
5459
5460    ----------------------------------
5461    -- Install_Null_Excluding_Check --
5462    ----------------------------------
5463
5464    procedure Install_Null_Excluding_Check (N : Node_Id) is
5465       Loc : constant Source_Ptr := Sloc (Parent (N));
5466       Typ : constant Entity_Id  := Etype (N);
5467
5468       function Safe_To_Capture_In_Parameter_Value return Boolean;
5469       --  Determines if it is safe to capture Known_Non_Null status for an
5470       --  the entity referenced by node N. The caller ensures that N is indeed
5471       --  an entity name. It is safe to capture the non-null status for an IN
5472       --  parameter when the reference occurs within a declaration that is sure
5473       --  to be executed as part of the declarative region.
5474
5475       procedure Mark_Non_Null;
5476       --  After installation of check, if the node in question is an entity
5477       --  name, then mark this entity as non-null if possible.
5478
5479       function Safe_To_Capture_In_Parameter_Value return Boolean is
5480          E     : constant Entity_Id := Entity (N);
5481          S     : constant Entity_Id := Current_Scope;
5482          S_Par : Node_Id;
5483
5484       begin
5485          if Ekind (E) /= E_In_Parameter then
5486             return False;
5487          end if;
5488
5489          --  Two initial context checks. We must be inside a subprogram body
5490          --  with declarations and reference must not appear in nested scopes.
5491
5492          if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
5493            or else Scope (E) /= S
5494          then
5495             return False;
5496          end if;
5497
5498          S_Par := Parent (Parent (S));
5499
5500          if Nkind (S_Par) /= N_Subprogram_Body
5501            or else No (Declarations (S_Par))
5502          then
5503             return False;
5504          end if;
5505
5506          declare
5507             N_Decl : Node_Id;
5508             P      : Node_Id;
5509
5510          begin
5511             --  Retrieve the declaration node of N (if any). Note that N
5512             --  may be a part of a complex initialization expression.
5513
5514             P := Parent (N);
5515             N_Decl := Empty;
5516             while Present (P) loop
5517
5518                --  If we have a short circuit form, and we are within the right
5519                --  hand expression, we return false, since the right hand side
5520                --  is not guaranteed to be elaborated.
5521
5522                if Nkind (P) in N_Short_Circuit
5523                  and then N = Right_Opnd (P)
5524                then
5525                   return False;
5526                end if;
5527
5528                --  Similarly, if we are in a conditional expression and not
5529                --  part of the condition, then we return False, since neither
5530                --  the THEN or ELSE expressions will always be elaborated.
5531
5532                if Nkind (P) = N_Conditional_Expression
5533                  and then N /= First (Expressions (P))
5534                then
5535                   return False;
5536                end if;
5537
5538                --  If we are in a case expression, and not part of the
5539                --  expression, then we return False, since a particular
5540                --  branch may not always be elaborated
5541
5542                if Nkind (P) = N_Case_Expression
5543                  and then N /= Expression (P)
5544                then
5545                   return False;
5546                end if;
5547
5548                --  While traversing the parent chain, we find that N
5549                --  belongs to a statement, thus it may never appear in
5550                --  a declarative region.
5551
5552                if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5553                  or else Nkind (P) = N_Procedure_Call_Statement
5554                then
5555                   return False;
5556                end if;
5557
5558                --  If we are at a declaration, record it and exit
5559
5560                if Nkind (P) in N_Declaration
5561                  and then Nkind (P) not in N_Subprogram_Specification
5562                then
5563                   N_Decl := P;
5564                   exit;
5565                end if;
5566
5567                P := Parent (P);
5568             end loop;
5569
5570             if No (N_Decl) then
5571                return False;
5572             end if;
5573
5574             return List_Containing (N_Decl) = Declarations (S_Par);
5575          end;
5576       end Safe_To_Capture_In_Parameter_Value;
5577
5578       -------------------
5579       -- Mark_Non_Null --
5580       -------------------
5581
5582       procedure Mark_Non_Null is
5583       begin
5584          --  Only case of interest is if node N is an entity name
5585
5586          if Is_Entity_Name (N) then
5587
5588             --  For sure, we want to clear an indication that this is known to
5589             --  be null, since if we get past this check, it definitely is not!
5590
5591             Set_Is_Known_Null (Entity (N), False);
5592
5593             --  We can mark the entity as known to be non-null if either it is
5594             --  safe to capture the value, or in the case of an IN parameter,
5595             --  which is a constant, if the check we just installed is in the
5596             --  declarative region of the subprogram body. In this latter case,
5597             --  a check is decisive for the rest of the body if the expression
5598             --  is sure to be elaborated, since we know we have to elaborate
5599             --  all declarations before executing the body.
5600
5601             --  Couldn't this always be part of Safe_To_Capture_Value ???
5602
5603             if Safe_To_Capture_Value (N, Entity (N))
5604               or else Safe_To_Capture_In_Parameter_Value
5605             then
5606                Set_Is_Known_Non_Null (Entity (N));
5607             end if;
5608          end if;
5609       end Mark_Non_Null;
5610
5611    --  Start of processing for Install_Null_Excluding_Check
5612
5613    begin
5614       pragma Assert (Is_Access_Type (Typ));
5615
5616       --  No check inside a generic (why not???)
5617
5618       if Inside_A_Generic then
5619          return;
5620       end if;
5621
5622       --  No check needed if known to be non-null
5623
5624       if Known_Non_Null (N) then
5625          return;
5626       end if;
5627
5628       --  If known to be null, here is where we generate a compile time check
5629
5630       if Known_Null (N) then
5631
5632          --  Avoid generating warning message inside init procs
5633
5634          if not Inside_Init_Proc then
5635             Apply_Compile_Time_Constraint_Error
5636               (N,
5637                "null value not allowed here?",
5638                CE_Access_Check_Failed);
5639          else
5640             Insert_Action (N,
5641               Make_Raise_Constraint_Error (Loc,
5642                 Reason => CE_Access_Check_Failed));
5643          end if;
5644
5645          Mark_Non_Null;
5646          return;
5647       end if;
5648
5649       --  If entity is never assigned, for sure a warning is appropriate
5650
5651       if Is_Entity_Name (N) then
5652          Check_Unset_Reference (N);
5653       end if;
5654
5655       --  No check needed if checks are suppressed on the range. Note that we
5656       --  don't set Is_Known_Non_Null in this case (we could legitimately do
5657       --  so, since the program is erroneous, but we don't like to casually
5658       --  propagate such conclusions from erroneosity).
5659
5660       if Access_Checks_Suppressed (Typ) then
5661          return;
5662       end if;
5663
5664       --  No check needed for access to concurrent record types generated by
5665       --  the expander. This is not just an optimization (though it does indeed
5666       --  remove junk checks). It also avoids generation of junk warnings.
5667
5668       if Nkind (N) in N_Has_Chars
5669         and then Chars (N) = Name_uObject
5670         and then Is_Concurrent_Record_Type
5671                    (Directly_Designated_Type (Etype (N)))
5672       then
5673          return;
5674       end if;
5675
5676       --  No check needed for the Get_Current_Excep.all.all idiom generated by
5677       --  the expander within exception handlers, since we know that the value
5678       --  can never be null.
5679
5680       --  Is this really the right way to do this? Normally we generate such
5681       --  code in the expander with checks off, and that's how we suppress this
5682       --  kind of junk check ???
5683
5684       if Nkind (N) = N_Function_Call
5685         and then Nkind (Name (N)) = N_Explicit_Dereference
5686         and then Nkind (Prefix (Name (N))) = N_Identifier
5687         and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
5688       then
5689          return;
5690       end if;
5691
5692       --  Otherwise install access check
5693
5694       Insert_Action (N,
5695         Make_Raise_Constraint_Error (Loc,
5696           Condition =>
5697             Make_Op_Eq (Loc,
5698               Left_Opnd  => Duplicate_Subexpr_Move_Checks (N),
5699               Right_Opnd => Make_Null (Loc)),
5700           Reason => CE_Access_Check_Failed));
5701
5702       Mark_Non_Null;
5703    end Install_Null_Excluding_Check;
5704
5705    --------------------------
5706    -- Install_Static_Check --
5707    --------------------------
5708
5709    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5710       Stat : constant Boolean   := Is_Static_Expression (R_Cno);
5711       Typ  : constant Entity_Id := Etype (R_Cno);
5712
5713    begin
5714       Rewrite (R_Cno,
5715         Make_Raise_Constraint_Error (Loc,
5716           Reason => CE_Range_Check_Failed));
5717       Set_Analyzed (R_Cno);
5718       Set_Etype (R_Cno, Typ);
5719       Set_Raises_Constraint_Error (R_Cno);
5720       Set_Is_Static_Expression (R_Cno, Stat);
5721
5722       --  Now deal with possible local raise handling
5723
5724       Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
5725    end Install_Static_Check;
5726
5727    ---------------------
5728    -- Kill_All_Checks --
5729    ---------------------
5730
5731    procedure Kill_All_Checks is
5732    begin
5733       if Debug_Flag_CC then
5734          w ("Kill_All_Checks");
5735       end if;
5736
5737       --  We reset the number of saved checks to zero, and also modify all
5738       --  stack entries for statement ranges to indicate that the number of
5739       --  checks at each level is now zero.
5740
5741       Num_Saved_Checks := 0;
5742
5743       --  Note: the Int'Min here avoids any possibility of J being out of
5744       --  range when called from e.g. Conditional_Statements_Begin.
5745
5746       for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
5747          Saved_Checks_Stack (J) := 0;
5748       end loop;
5749    end Kill_All_Checks;
5750
5751    -----------------
5752    -- Kill_Checks --
5753    -----------------
5754
5755    procedure Kill_Checks (V : Entity_Id) is
5756    begin
5757       if Debug_Flag_CC then
5758          w ("Kill_Checks for entity", Int (V));
5759       end if;
5760
5761       for J in 1 .. Num_Saved_Checks loop
5762          if Saved_Checks (J).Entity = V then
5763             if Debug_Flag_CC then
5764                w ("   Checks killed for saved check ", J);
5765             end if;
5766
5767             Saved_Checks (J).Killed := True;
5768          end if;
5769       end loop;
5770    end Kill_Checks;
5771
5772    ------------------------------
5773    -- Length_Checks_Suppressed --
5774    ------------------------------
5775
5776    function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5777    begin
5778       if Present (E) and then Checks_May_Be_Suppressed (E) then
5779          return Is_Check_Suppressed (E, Length_Check);
5780       else
5781          return Scope_Suppress (Length_Check);
5782       end if;
5783    end Length_Checks_Suppressed;
5784
5785    --------------------------------
5786    -- Overflow_Checks_Suppressed --
5787    --------------------------------
5788
5789    function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5790    begin
5791       if Present (E) and then Checks_May_Be_Suppressed (E) then
5792          return Is_Check_Suppressed (E, Overflow_Check);
5793       else
5794          return Scope_Suppress (Overflow_Check);
5795       end if;
5796    end Overflow_Checks_Suppressed;
5797
5798    -----------------------------
5799    -- Range_Checks_Suppressed --
5800    -----------------------------
5801
5802    function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5803    begin
5804       if Present (E) then
5805
5806          --  Note: for now we always suppress range checks on Vax float types,
5807          --  since Gigi does not know how to generate these checks.
5808
5809          if Vax_Float (E) then
5810             return True;
5811          elsif Kill_Range_Checks (E) then
5812             return True;
5813          elsif Checks_May_Be_Suppressed (E) then
5814             return Is_Check_Suppressed (E, Range_Check);
5815          end if;
5816       end if;
5817
5818       return Scope_Suppress (Range_Check);
5819    end Range_Checks_Suppressed;
5820
5821    -----------------------------------------
5822    -- Range_Or_Validity_Checks_Suppressed --
5823    -----------------------------------------
5824
5825    --  Note: the coding would be simpler here if we simply made appropriate
5826    --  calls to Range/Validity_Checks_Suppressed, but that would result in
5827    --  duplicated checks which we prefer to avoid.
5828
5829    function Range_Or_Validity_Checks_Suppressed
5830      (Expr : Node_Id) return Boolean
5831    is
5832    begin
5833       --  Immediate return if scope checks suppressed for either check
5834
5835       if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5836          return True;
5837       end if;
5838
5839       --  If no expression, that's odd, decide that checks are suppressed,
5840       --  since we don't want anyone trying to do checks in this case, which
5841       --  is most likely the result of some other error.
5842
5843       if No (Expr) then
5844          return True;
5845       end if;
5846
5847       --  Expression is present, so perform suppress checks on type
5848
5849       declare
5850          Typ : constant Entity_Id := Etype (Expr);
5851       begin
5852          if Vax_Float (Typ) then
5853             return True;
5854          elsif Checks_May_Be_Suppressed (Typ)
5855            and then (Is_Check_Suppressed (Typ, Range_Check)
5856                        or else
5857                      Is_Check_Suppressed (Typ, Validity_Check))
5858          then
5859             return True;
5860          end if;
5861       end;
5862
5863       --  If expression is an entity name, perform checks on this entity
5864
5865       if Is_Entity_Name (Expr) then
5866          declare
5867             Ent : constant Entity_Id := Entity (Expr);
5868          begin
5869             if Checks_May_Be_Suppressed (Ent) then
5870                return Is_Check_Suppressed (Ent, Range_Check)
5871                  or else Is_Check_Suppressed (Ent, Validity_Check);
5872             end if;
5873          end;
5874       end if;
5875
5876       --  If we fall through, no checks suppressed
5877
5878       return False;
5879    end Range_Or_Validity_Checks_Suppressed;
5880
5881    -------------------
5882    -- Remove_Checks --
5883    -------------------
5884
5885    procedure Remove_Checks (Expr : Node_Id) is
5886       function Process (N : Node_Id) return Traverse_Result;
5887       --  Process a single node during the traversal
5888
5889       procedure Traverse is new Traverse_Proc (Process);
5890       --  The traversal procedure itself
5891
5892       -------------
5893       -- Process --
5894       -------------
5895
5896       function Process (N : Node_Id) return Traverse_Result is
5897       begin
5898          if Nkind (N) not in N_Subexpr then
5899             return Skip;
5900          end if;
5901
5902          Set_Do_Range_Check (N, False);
5903
5904          case Nkind (N) is
5905             when N_And_Then =>
5906                Traverse (Left_Opnd (N));
5907                return Skip;
5908
5909             when N_Attribute_Reference =>
5910                Set_Do_Overflow_Check (N, False);
5911
5912             when N_Function_Call =>
5913                Set_Do_Tag_Check (N, False);
5914
5915             when N_Op =>
5916                Set_Do_Overflow_Check (N, False);
5917
5918                case Nkind (N) is
5919                   when N_Op_Divide =>
5920                      Set_Do_Division_Check (N, False);
5921
5922                   when N_Op_And =>
5923                      Set_Do_Length_Check (N, False);
5924
5925                   when N_Op_Mod =>
5926                      Set_Do_Division_Check (N, False);
5927
5928                   when N_Op_Or =>
5929                      Set_Do_Length_Check (N, False);
5930
5931                   when N_Op_Rem =>
5932                      Set_Do_Division_Check (N, False);
5933
5934                   when N_Op_Xor =>
5935                      Set_Do_Length_Check (N, False);
5936
5937                   when others =>
5938                      null;
5939                end case;
5940
5941             when N_Or_Else =>
5942                Traverse (Left_Opnd (N));
5943                return Skip;
5944
5945             when N_Selected_Component =>
5946                Set_Do_Discriminant_Check (N, False);
5947
5948             when N_Type_Conversion =>
5949                Set_Do_Length_Check   (N, False);
5950                Set_Do_Tag_Check      (N, False);
5951                Set_Do_Overflow_Check (N, False);
5952
5953             when others =>
5954                null;
5955          end case;
5956
5957          return OK;
5958       end Process;
5959
5960    --  Start of processing for Remove_Checks
5961
5962    begin
5963       Traverse (Expr);
5964    end Remove_Checks;
5965
5966    ----------------------------
5967    -- Selected_Length_Checks --
5968    ----------------------------
5969
5970    function Selected_Length_Checks
5971      (Ck_Node    : Node_Id;
5972       Target_Typ : Entity_Id;
5973       Source_Typ : Entity_Id;
5974       Warn_Node  : Node_Id) return Check_Result
5975    is
5976       Loc         : constant Source_Ptr := Sloc (Ck_Node);
5977       S_Typ       : Entity_Id;
5978       T_Typ       : Entity_Id;
5979       Expr_Actual : Node_Id;
5980       Exptyp      : Entity_Id;
5981       Cond        : Node_Id := Empty;
5982       Do_Access   : Boolean := False;
5983       Wnode       : Node_Id := Warn_Node;
5984       Ret_Result  : Check_Result := (Empty, Empty);
5985       Num_Checks  : Natural := 0;
5986
5987       procedure Add_Check (N : Node_Id);
5988       --  Adds the action given to Ret_Result if N is non-Empty
5989
5990       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5991       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5992       --  Comments required ???
5993
5994       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5995       --  True for equal literals and for nodes that denote the same constant
5996       --  entity, even if its value is not a static constant. This includes the
5997       --  case of a discriminal reference within an init proc. Removes some
5998       --  obviously superfluous checks.
5999
6000       function Length_E_Cond
6001         (Exptyp : Entity_Id;
6002          Typ    : Entity_Id;
6003          Indx   : Nat) return Node_Id;
6004       --  Returns expression to compute:
6005       --    Typ'Length /= Exptyp'Length
6006
6007       function Length_N_Cond
6008         (Expr : Node_Id;
6009          Typ  : Entity_Id;
6010          Indx : Nat) return Node_Id;
6011       --  Returns expression to compute:
6012       --    Typ'Length /= Expr'Length
6013
6014       ---------------
6015       -- Add_Check --
6016       ---------------
6017
6018       procedure Add_Check (N : Node_Id) is
6019       begin
6020          if Present (N) then
6021
6022             --  For now, ignore attempt to place more than 2 checks ???
6023
6024             if Num_Checks = 2 then
6025                return;
6026             end if;
6027
6028             pragma Assert (Num_Checks <= 1);
6029             Num_Checks := Num_Checks + 1;
6030             Ret_Result (Num_Checks) := N;
6031          end if;
6032       end Add_Check;
6033
6034       ------------------
6035       -- Get_E_Length --
6036       ------------------
6037
6038       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
6039          SE : constant Entity_Id := Scope (E);
6040          N  : Node_Id;
6041          E1 : Entity_Id := E;
6042
6043       begin
6044          if Ekind (Scope (E)) = E_Record_Type
6045            and then Has_Discriminants (Scope (E))
6046          then
6047             N := Build_Discriminal_Subtype_Of_Component (E);
6048
6049             if Present (N) then
6050                Insert_Action (Ck_Node, N);
6051                E1 := Defining_Identifier (N);
6052             end if;
6053          end if;
6054
6055          if Ekind (E1) = E_String_Literal_Subtype then
6056             return
6057               Make_Integer_Literal (Loc,
6058                 Intval => String_Literal_Length (E1));
6059
6060          elsif SE /= Standard_Standard
6061            and then Ekind (Scope (SE)) = E_Protected_Type
6062            and then Has_Discriminants (Scope (SE))
6063            and then Has_Completion (Scope (SE))
6064            and then not Inside_Init_Proc
6065          then
6066             --  If the type whose length is needed is a private component
6067             --  constrained by a discriminant, we must expand the 'Length
6068             --  attribute into an explicit computation, using the discriminal
6069             --  of the current protected operation. This is because the actual
6070             --  type of the prival is constructed after the protected opera-
6071             --  tion has been fully expanded.
6072
6073             declare
6074                Indx_Type : Node_Id;
6075                Lo        : Node_Id;
6076                Hi        : Node_Id;
6077                Do_Expand : Boolean := False;
6078
6079             begin
6080                Indx_Type := First_Index (E);
6081
6082                for J in 1 .. Indx - 1 loop
6083                   Next_Index (Indx_Type);
6084                end loop;
6085
6086                Get_Index_Bounds (Indx_Type, Lo, Hi);
6087
6088                if Nkind (Lo) = N_Identifier
6089                  and then Ekind (Entity (Lo)) = E_In_Parameter
6090                then
6091                   Lo := Get_Discriminal (E, Lo);
6092                   Do_Expand := True;
6093                end if;
6094
6095                if Nkind (Hi) = N_Identifier
6096                  and then Ekind (Entity (Hi)) = E_In_Parameter
6097                then
6098                   Hi := Get_Discriminal (E, Hi);
6099                   Do_Expand := True;
6100                end if;
6101
6102                if Do_Expand then
6103                   if not Is_Entity_Name (Lo) then
6104                      Lo := Duplicate_Subexpr_No_Checks (Lo);
6105                   end if;
6106
6107                   if not Is_Entity_Name (Hi) then
6108                      Lo := Duplicate_Subexpr_No_Checks (Hi);
6109                   end if;
6110
6111                   N :=
6112                     Make_Op_Add (Loc,
6113                       Left_Opnd =>
6114                         Make_Op_Subtract (Loc,
6115                           Left_Opnd  => Hi,
6116                           Right_Opnd => Lo),
6117
6118                       Right_Opnd => Make_Integer_Literal (Loc, 1));
6119                   return N;
6120
6121                else
6122                   N :=
6123                     Make_Attribute_Reference (Loc,
6124                       Attribute_Name => Name_Length,
6125                       Prefix =>
6126                         New_Occurrence_Of (E1, Loc));
6127
6128                   if Indx > 1 then
6129                      Set_Expressions (N, New_List (
6130                        Make_Integer_Literal (Loc, Indx)));
6131                   end if;
6132
6133                   return N;
6134                end if;
6135             end;
6136
6137          else
6138             N :=
6139               Make_Attribute_Reference (Loc,
6140                 Attribute_Name => Name_Length,
6141                 Prefix =>
6142                   New_Occurrence_Of (E1, Loc));
6143
6144             if Indx > 1 then
6145                Set_Expressions (N, New_List (
6146                  Make_Integer_Literal (Loc, Indx)));
6147             end if;
6148
6149             return N;
6150          end if;
6151       end Get_E_Length;
6152
6153       ------------------
6154       -- Get_N_Length --
6155       ------------------
6156
6157       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
6158       begin
6159          return
6160            Make_Attribute_Reference (Loc,
6161              Attribute_Name => Name_Length,
6162              Prefix =>
6163                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6164              Expressions => New_List (
6165                Make_Integer_Literal (Loc, Indx)));
6166       end Get_N_Length;
6167
6168       -------------------
6169       -- Length_E_Cond --
6170       -------------------
6171
6172       function Length_E_Cond
6173         (Exptyp : Entity_Id;
6174          Typ    : Entity_Id;
6175          Indx   : Nat) return Node_Id
6176       is
6177       begin
6178          return
6179            Make_Op_Ne (Loc,
6180              Left_Opnd  => Get_E_Length (Typ, Indx),
6181              Right_Opnd => Get_E_Length (Exptyp, Indx));
6182       end Length_E_Cond;
6183
6184       -------------------
6185       -- Length_N_Cond --
6186       -------------------
6187
6188       function Length_N_Cond
6189         (Expr : Node_Id;
6190          Typ  : Entity_Id;
6191          Indx : Nat) return Node_Id
6192       is
6193       begin
6194          return
6195            Make_Op_Ne (Loc,
6196              Left_Opnd  => Get_E_Length (Typ, Indx),
6197              Right_Opnd => Get_N_Length (Expr, Indx));
6198       end Length_N_Cond;
6199
6200       -----------------
6201       -- Same_Bounds --
6202       -----------------
6203
6204       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
6205       begin
6206          return
6207            (Nkind (L) = N_Integer_Literal
6208              and then Nkind (R) = N_Integer_Literal
6209              and then Intval (L) = Intval (R))
6210
6211           or else
6212             (Is_Entity_Name (L)
6213               and then Ekind (Entity (L)) = E_Constant
6214               and then ((Is_Entity_Name (R)
6215                          and then Entity (L) = Entity (R))
6216                         or else
6217                        (Nkind (R) = N_Type_Conversion
6218                          and then Is_Entity_Name (Expression (R))
6219                          and then Entity (L) = Entity (Expression (R)))))
6220
6221           or else
6222             (Is_Entity_Name (R)
6223               and then Ekind (Entity (R)) = E_Constant
6224               and then Nkind (L) = N_Type_Conversion
6225               and then Is_Entity_Name (Expression (L))
6226               and then Entity (R) = Entity (Expression (L)))
6227
6228          or else
6229             (Is_Entity_Name (L)
6230               and then Is_Entity_Name (R)
6231               and then Entity (L) = Entity (R)
6232               and then Ekind (Entity (L)) = E_In_Parameter
6233               and then Inside_Init_Proc);
6234       end Same_Bounds;
6235
6236    --  Start of processing for Selected_Length_Checks
6237
6238    begin
6239       if not Full_Expander_Active then
6240          return Ret_Result;
6241       end if;
6242
6243       if Target_Typ = Any_Type
6244         or else Target_Typ = Any_Composite
6245         or else Raises_Constraint_Error (Ck_Node)
6246       then
6247          return Ret_Result;
6248       end if;
6249
6250       if No (Wnode) then
6251          Wnode := Ck_Node;
6252       end if;
6253
6254       T_Typ := Target_Typ;
6255
6256       if No (Source_Typ) then
6257          S_Typ := Etype (Ck_Node);
6258       else
6259          S_Typ := Source_Typ;
6260       end if;
6261
6262       if S_Typ = Any_Type or else S_Typ = Any_Composite then
6263          return Ret_Result;
6264       end if;
6265
6266       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6267          S_Typ := Designated_Type (S_Typ);
6268          T_Typ := Designated_Type (T_Typ);
6269          Do_Access := True;
6270
6271          --  A simple optimization for the null case
6272
6273          if Known_Null (Ck_Node) then
6274             return Ret_Result;
6275          end if;
6276       end if;
6277
6278       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6279          if Is_Constrained (T_Typ) then
6280
6281             --  The checking code to be generated will freeze the
6282             --  corresponding array type. However, we must freeze the
6283             --  type now, so that the freeze node does not appear within
6284             --  the generated conditional expression, but ahead of it.
6285
6286             Freeze_Before (Ck_Node, T_Typ);
6287
6288             Expr_Actual := Get_Referenced_Object (Ck_Node);
6289             Exptyp      := Get_Actual_Subtype (Ck_Node);
6290
6291             if Is_Access_Type (Exptyp) then
6292                Exptyp := Designated_Type (Exptyp);
6293             end if;
6294
6295             --  String_Literal case. This needs to be handled specially be-
6296             --  cause no index types are available for string literals. The
6297             --  condition is simply:
6298
6299             --    T_Typ'Length = string-literal-length
6300
6301             if Nkind (Expr_Actual) = N_String_Literal
6302               and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
6303             then
6304                Cond :=
6305                  Make_Op_Ne (Loc,
6306                    Left_Opnd  => Get_E_Length (T_Typ, 1),
6307                    Right_Opnd =>
6308                      Make_Integer_Literal (Loc,
6309                        Intval =>
6310                          String_Literal_Length (Etype (Expr_Actual))));
6311
6312             --  General array case. Here we have a usable actual subtype for
6313             --  the expression, and the condition is built from the two types
6314             --  (Do_Length):
6315
6316             --     T_Typ'Length     /= Exptyp'Length     or else
6317             --     T_Typ'Length (2) /= Exptyp'Length (2) or else
6318             --     T_Typ'Length (3) /= Exptyp'Length (3) or else
6319             --     ...
6320
6321             elsif Is_Constrained (Exptyp) then
6322                declare
6323                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6324
6325                   L_Index  : Node_Id;
6326                   R_Index  : Node_Id;
6327                   L_Low    : Node_Id;
6328                   L_High   : Node_Id;
6329                   R_Low    : Node_Id;
6330                   R_High   : Node_Id;
6331                   L_Length : Uint;
6332                   R_Length : Uint;
6333                   Ref_Node : Node_Id;
6334
6335                begin
6336                   --  At the library level, we need to ensure that the type of
6337                   --  the object is elaborated before the check itself is
6338                   --  emitted. This is only done if the object is in the
6339                   --  current compilation unit, otherwise the type is frozen
6340                   --  and elaborated in its unit.
6341
6342                   if Is_Itype (Exptyp)
6343                     and then
6344                       Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
6345                     and then
6346                       not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
6347                     and then In_Open_Scopes (Scope (Exptyp))
6348                   then
6349                      Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
6350                      Set_Itype (Ref_Node, Exptyp);
6351                      Insert_Action (Ck_Node, Ref_Node);
6352                   end if;
6353
6354                   L_Index := First_Index (T_Typ);
6355                   R_Index := First_Index (Exptyp);
6356
6357                   for Indx in 1 .. Ndims loop
6358                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
6359                                or else
6360                              Nkind (R_Index) = N_Raise_Constraint_Error)
6361                      then
6362                         Get_Index_Bounds (L_Index, L_Low, L_High);
6363                         Get_Index_Bounds (R_Index, R_Low, R_High);
6364
6365                         --  Deal with compile time length check. Note that we
6366                         --  skip this in the access case, because the access
6367                         --  value may be null, so we cannot know statically.
6368
6369                         if not Do_Access
6370                           and then Compile_Time_Known_Value (L_Low)
6371                           and then Compile_Time_Known_Value (L_High)
6372                           and then Compile_Time_Known_Value (R_Low)
6373                           and then Compile_Time_Known_Value (R_High)
6374                         then
6375                            if Expr_Value (L_High) >= Expr_Value (L_Low) then
6376                               L_Length := Expr_Value (L_High) -
6377                                           Expr_Value (L_Low) + 1;
6378                            else
6379                               L_Length := UI_From_Int (0);
6380                            end if;
6381
6382                            if Expr_Value (R_High) >= Expr_Value (R_Low) then
6383                               R_Length := Expr_Value (R_High) -
6384                                           Expr_Value (R_Low) + 1;
6385                            else
6386                               R_Length := UI_From_Int (0);
6387                            end if;
6388
6389                            if L_Length > R_Length then
6390                               Add_Check
6391                                 (Compile_Time_Constraint_Error
6392                                   (Wnode, "too few elements for}?", T_Typ));
6393
6394                            elsif  L_Length < R_Length then
6395                               Add_Check
6396                                 (Compile_Time_Constraint_Error
6397                                   (Wnode, "too many elements for}?", T_Typ));
6398                            end if;
6399
6400                         --  The comparison for an individual index subtype
6401                         --  is omitted if the corresponding index subtypes
6402                         --  statically match, since the result is known to
6403                         --  be true. Note that this test is worth while even
6404                         --  though we do static evaluation, because non-static
6405                         --  subtypes can statically match.
6406
6407                         elsif not
6408                           Subtypes_Statically_Match
6409                             (Etype (L_Index), Etype (R_Index))
6410
6411                           and then not
6412                             (Same_Bounds (L_Low, R_Low)
6413                               and then Same_Bounds (L_High, R_High))
6414                         then
6415                            Evolve_Or_Else
6416                              (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
6417                         end if;
6418
6419                         Next (L_Index);
6420                         Next (R_Index);
6421                      end if;
6422                   end loop;
6423                end;
6424
6425             --  Handle cases where we do not get a usable actual subtype that
6426             --  is constrained. This happens for example in the function call
6427             --  and explicit dereference cases. In these cases, we have to get
6428             --  the length or range from the expression itself, making sure we
6429             --  do not evaluate it more than once.
6430
6431             --  Here Ck_Node is the original expression, or more properly the
6432             --  result of applying Duplicate_Expr to the original tree, forcing
6433             --  the result to be a name.
6434
6435             else
6436                declare
6437                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6438
6439                begin
6440                   --  Build the condition for the explicit dereference case
6441
6442                   for Indx in 1 .. Ndims loop
6443                      Evolve_Or_Else
6444                        (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
6445                   end loop;
6446                end;
6447             end if;
6448          end if;
6449       end if;
6450
6451       --  Construct the test and insert into the tree
6452
6453       if Present (Cond) then
6454          if Do_Access then
6455             Cond := Guard_Access (Cond, Loc, Ck_Node);
6456          end if;
6457
6458          Add_Check
6459            (Make_Raise_Constraint_Error (Loc,
6460               Condition => Cond,
6461               Reason => CE_Length_Check_Failed));
6462       end if;
6463
6464       return Ret_Result;
6465    end Selected_Length_Checks;
6466
6467    ---------------------------
6468    -- Selected_Range_Checks --
6469    ---------------------------
6470
6471    function Selected_Range_Checks
6472      (Ck_Node    : Node_Id;
6473       Target_Typ : Entity_Id;
6474       Source_Typ : Entity_Id;
6475       Warn_Node  : Node_Id) return Check_Result
6476    is
6477       Loc         : constant Source_Ptr := Sloc (Ck_Node);
6478       S_Typ       : Entity_Id;
6479       T_Typ       : Entity_Id;
6480       Expr_Actual : Node_Id;
6481       Exptyp      : Entity_Id;
6482       Cond        : Node_Id := Empty;
6483       Do_Access   : Boolean := False;
6484       Wnode       : Node_Id  := Warn_Node;
6485       Ret_Result  : Check_Result := (Empty, Empty);
6486       Num_Checks  : Integer := 0;
6487
6488       procedure Add_Check (N : Node_Id);
6489       --  Adds the action given to Ret_Result if N is non-Empty
6490
6491       function Discrete_Range_Cond
6492         (Expr : Node_Id;
6493          Typ  : Entity_Id) return Node_Id;
6494       --  Returns expression to compute:
6495       --    Low_Bound (Expr) < Typ'First
6496       --      or else
6497       --    High_Bound (Expr) > Typ'Last
6498
6499       function Discrete_Expr_Cond
6500         (Expr : Node_Id;
6501          Typ  : Entity_Id) return Node_Id;
6502       --  Returns expression to compute:
6503       --    Expr < Typ'First
6504       --      or else
6505       --    Expr > Typ'Last
6506
6507       function Get_E_First_Or_Last
6508         (Loc  : Source_Ptr;
6509          E    : Entity_Id;
6510          Indx : Nat;
6511          Nam  : Name_Id) return Node_Id;
6512       --  Returns an attribute reference
6513       --    E'First or E'Last
6514       --  with a source location of Loc.
6515       --
6516       --  Nam is Name_First or Name_Last, according to which attribute is
6517       --  desired. If Indx is non-zero, it is passed as a literal in the
6518       --  Expressions of the attribute reference (identifying the desired
6519       --  array dimension).
6520
6521       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
6522       function Get_N_Last  (N : Node_Id; Indx : Nat) return Node_Id;
6523       --  Returns expression to compute:
6524       --    N'First or N'Last using Duplicate_Subexpr_No_Checks
6525
6526       function Range_E_Cond
6527         (Exptyp : Entity_Id;
6528          Typ    : Entity_Id;
6529          Indx   : Nat)
6530          return   Node_Id;
6531       --  Returns expression to compute:
6532       --    Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
6533
6534       function Range_Equal_E_Cond
6535         (Exptyp : Entity_Id;
6536          Typ    : Entity_Id;
6537          Indx   : Nat) return Node_Id;
6538       --  Returns expression to compute:
6539       --    Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
6540
6541       function Range_N_Cond
6542         (Expr : Node_Id;
6543          Typ  : Entity_Id;
6544          Indx : Nat) return Node_Id;
6545       --  Return expression to compute:
6546       --    Expr'First < Typ'First or else Expr'Last > Typ'Last
6547
6548       ---------------
6549       -- Add_Check --
6550       ---------------
6551
6552       procedure Add_Check (N : Node_Id) is
6553       begin
6554          if Present (N) then
6555
6556             --  For now, ignore attempt to place more than 2 checks ???
6557
6558             if Num_Checks = 2 then
6559                return;
6560             end if;
6561
6562             pragma Assert (Num_Checks <= 1);
6563             Num_Checks := Num_Checks + 1;
6564             Ret_Result (Num_Checks) := N;
6565          end if;
6566       end Add_Check;
6567
6568       -------------------------
6569       -- Discrete_Expr_Cond --
6570       -------------------------
6571
6572       function Discrete_Expr_Cond
6573         (Expr : Node_Id;
6574          Typ  : Entity_Id) return Node_Id
6575       is
6576       begin
6577          return
6578            Make_Or_Else (Loc,
6579              Left_Opnd =>
6580                Make_Op_Lt (Loc,
6581                  Left_Opnd =>
6582                    Convert_To (Base_Type (Typ),
6583                      Duplicate_Subexpr_No_Checks (Expr)),
6584                  Right_Opnd =>
6585                    Convert_To (Base_Type (Typ),
6586                                Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
6587
6588              Right_Opnd =>
6589                Make_Op_Gt (Loc,
6590                  Left_Opnd =>
6591                    Convert_To (Base_Type (Typ),
6592                      Duplicate_Subexpr_No_Checks (Expr)),
6593                  Right_Opnd =>
6594                    Convert_To
6595                      (Base_Type (Typ),
6596                       Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
6597       end Discrete_Expr_Cond;
6598
6599       -------------------------
6600       -- Discrete_Range_Cond --
6601       -------------------------
6602
6603       function Discrete_Range_Cond
6604         (Expr : Node_Id;
6605          Typ  : Entity_Id) return Node_Id
6606       is
6607          LB : Node_Id := Low_Bound (Expr);
6608          HB : Node_Id := High_Bound (Expr);
6609
6610          Left_Opnd  : Node_Id;
6611          Right_Opnd : Node_Id;
6612
6613       begin
6614          if Nkind (LB) = N_Identifier
6615            and then Ekind (Entity (LB)) = E_Discriminant
6616          then
6617             LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6618          end if;
6619
6620          if Nkind (HB) = N_Identifier
6621            and then Ekind (Entity (HB)) = E_Discriminant
6622          then
6623             HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6624          end if;
6625
6626          Left_Opnd :=
6627            Make_Op_Lt (Loc,
6628              Left_Opnd  =>
6629                Convert_To
6630                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6631
6632              Right_Opnd =>
6633                Convert_To
6634                  (Base_Type (Typ),
6635                   Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
6636
6637          if Base_Type (Typ) = Typ then
6638             return Left_Opnd;
6639
6640          elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6641             and then
6642                Compile_Time_Known_Value (High_Bound (Scalar_Range
6643                                                      (Base_Type (Typ))))
6644          then
6645             if Is_Floating_Point_Type (Typ) then
6646                if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6647                   Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6648                then
6649                   return Left_Opnd;
6650                end if;
6651
6652             else
6653                if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6654                   Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6655                then
6656                   return Left_Opnd;
6657                end if;
6658             end if;
6659          end if;
6660
6661          Right_Opnd :=
6662            Make_Op_Gt (Loc,
6663              Left_Opnd  =>
6664                Convert_To
6665                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6666
6667              Right_Opnd =>
6668                Convert_To
6669                  (Base_Type (Typ),
6670                   Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
6671
6672          return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6673       end Discrete_Range_Cond;
6674
6675       -------------------------
6676       -- Get_E_First_Or_Last --
6677       -------------------------
6678
6679       function Get_E_First_Or_Last
6680         (Loc  : Source_Ptr;
6681          E    : Entity_Id;
6682          Indx : Nat;
6683          Nam  : Name_Id) return Node_Id
6684       is
6685          Exprs : List_Id;
6686       begin
6687          if Indx > 0 then
6688             Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
6689          else
6690             Exprs := No_List;
6691          end if;
6692
6693          return Make_Attribute_Reference (Loc,
6694                   Prefix         => New_Occurrence_Of (E, Loc),
6695                   Attribute_Name => Nam,
6696                   Expressions    => Exprs);
6697       end Get_E_First_Or_Last;
6698
6699       -----------------
6700       -- Get_N_First --
6701       -----------------
6702
6703       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6704       begin
6705          return
6706            Make_Attribute_Reference (Loc,
6707              Attribute_Name => Name_First,
6708              Prefix =>
6709                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6710              Expressions => New_List (
6711                Make_Integer_Literal (Loc, Indx)));
6712       end Get_N_First;
6713
6714       ----------------
6715       -- Get_N_Last --
6716       ----------------
6717
6718       function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6719       begin
6720          return
6721            Make_Attribute_Reference (Loc,
6722              Attribute_Name => Name_Last,
6723              Prefix =>
6724                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6725              Expressions => New_List (
6726               Make_Integer_Literal (Loc, Indx)));
6727       end Get_N_Last;
6728
6729       ------------------
6730       -- Range_E_Cond --
6731       ------------------
6732
6733       function Range_E_Cond
6734         (Exptyp : Entity_Id;
6735          Typ    : Entity_Id;
6736          Indx   : Nat) return Node_Id
6737       is
6738       begin
6739          return
6740            Make_Or_Else (Loc,
6741              Left_Opnd =>
6742                Make_Op_Lt (Loc,
6743                  Left_Opnd   =>
6744                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6745                  Right_Opnd  =>
6746                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6747
6748              Right_Opnd =>
6749                Make_Op_Gt (Loc,
6750                  Left_Opnd   =>
6751                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6752                  Right_Opnd  =>
6753                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6754       end Range_E_Cond;
6755
6756       ------------------------
6757       -- Range_Equal_E_Cond --
6758       ------------------------
6759
6760       function Range_Equal_E_Cond
6761         (Exptyp : Entity_Id;
6762          Typ    : Entity_Id;
6763          Indx   : Nat) return Node_Id
6764       is
6765       begin
6766          return
6767            Make_Or_Else (Loc,
6768              Left_Opnd =>
6769                Make_Op_Ne (Loc,
6770                  Left_Opnd   =>
6771                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6772                  Right_Opnd  =>
6773                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6774
6775              Right_Opnd =>
6776                Make_Op_Ne (Loc,
6777                  Left_Opnd   =>
6778                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6779                  Right_Opnd  =>
6780                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6781       end Range_Equal_E_Cond;
6782
6783       ------------------
6784       -- Range_N_Cond --
6785       ------------------
6786
6787       function Range_N_Cond
6788         (Expr : Node_Id;
6789          Typ  : Entity_Id;
6790          Indx : Nat) return Node_Id
6791       is
6792       begin
6793          return
6794            Make_Or_Else (Loc,
6795              Left_Opnd =>
6796                Make_Op_Lt (Loc,
6797                  Left_Opnd  =>
6798                    Get_N_First (Expr, Indx),
6799                  Right_Opnd =>
6800                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6801
6802              Right_Opnd =>
6803                Make_Op_Gt (Loc,
6804                  Left_Opnd  =>
6805                    Get_N_Last (Expr, Indx),
6806                  Right_Opnd =>
6807                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6808       end Range_N_Cond;
6809
6810    --  Start of processing for Selected_Range_Checks
6811
6812    begin
6813       if not Full_Expander_Active then
6814          return Ret_Result;
6815       end if;
6816
6817       if Target_Typ = Any_Type
6818         or else Target_Typ = Any_Composite
6819         or else Raises_Constraint_Error (Ck_Node)
6820       then
6821          return Ret_Result;
6822       end if;
6823
6824       if No (Wnode) then
6825          Wnode := Ck_Node;
6826       end if;
6827
6828       T_Typ := Target_Typ;
6829
6830       if No (Source_Typ) then
6831          S_Typ := Etype (Ck_Node);
6832       else
6833          S_Typ := Source_Typ;
6834       end if;
6835
6836       if S_Typ = Any_Type or else S_Typ = Any_Composite then
6837          return Ret_Result;
6838       end if;
6839
6840       --  The order of evaluating T_Typ before S_Typ seems to be critical
6841       --  because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6842       --  in, and since Node can be an N_Range node, it might be invalid.
6843       --  Should there be an assert check somewhere for taking the Etype of
6844       --  an N_Range node ???
6845
6846       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6847          S_Typ := Designated_Type (S_Typ);
6848          T_Typ := Designated_Type (T_Typ);
6849          Do_Access := True;
6850
6851          --  A simple optimization for the null case
6852
6853          if Known_Null (Ck_Node) then
6854             return Ret_Result;
6855          end if;
6856       end if;
6857
6858       --  For an N_Range Node, check for a null range and then if not
6859       --  null generate a range check action.
6860
6861       if Nkind (Ck_Node) = N_Range then
6862
6863          --  There's no point in checking a range against itself
6864
6865          if Ck_Node = Scalar_Range (T_Typ) then
6866             return Ret_Result;
6867          end if;
6868
6869          declare
6870             T_LB       : constant Node_Id := Type_Low_Bound  (T_Typ);
6871             T_HB       : constant Node_Id := Type_High_Bound (T_Typ);
6872             Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
6873             Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
6874
6875             LB         : Node_Id := Low_Bound (Ck_Node);
6876             HB         : Node_Id := High_Bound (Ck_Node);
6877             Known_LB   : Boolean;
6878             Known_HB   : Boolean;
6879
6880             Null_Range     : Boolean;
6881             Out_Of_Range_L : Boolean;
6882             Out_Of_Range_H : Boolean;
6883
6884          begin
6885             --  Compute what is known at compile time
6886
6887             if Known_T_LB and Known_T_HB then
6888                if Compile_Time_Known_Value (LB) then
6889                   Known_LB := True;
6890
6891                --  There's no point in checking that a bound is within its
6892                --  own range so pretend that it is known in this case. First
6893                --  deal with low bound.
6894
6895                elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
6896                  and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
6897                then
6898                   LB := T_LB;
6899                   Known_LB := True;
6900
6901                else
6902                   Known_LB := False;
6903                end if;
6904
6905                --  Likewise for the high bound
6906
6907                if Compile_Time_Known_Value (HB) then
6908                   Known_HB := True;
6909
6910                elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
6911                  and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
6912                then
6913                   HB := T_HB;
6914                   Known_HB := True;
6915
6916                else
6917                   Known_HB := False;
6918                end if;
6919             end if;
6920
6921             --  Check for case where everything is static and we can do the
6922             --  check at compile time. This is skipped if we have an access
6923             --  type, since the access value may be null.
6924
6925             --  ??? This code can be improved since you only need to know that
6926             --  the two respective bounds (LB & T_LB or HB & T_HB) are known at
6927             --  compile time to emit pertinent messages.
6928
6929             if Known_T_LB and Known_T_HB and Known_LB and Known_HB
6930               and not Do_Access
6931             then
6932                --  Floating-point case
6933
6934                if Is_Floating_Point_Type (S_Typ) then
6935                   Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6936                   Out_Of_Range_L :=
6937                     (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6938                       or else
6939                     (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6940
6941                   Out_Of_Range_H :=
6942                     (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6943                       or else
6944                     (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6945
6946                --  Fixed or discrete type case
6947
6948                else
6949                   Null_Range := Expr_Value (HB) < Expr_Value (LB);
6950                   Out_Of_Range_L :=
6951                     (Expr_Value (LB) < Expr_Value (T_LB))
6952                       or else
6953                     (Expr_Value (LB) > Expr_Value (T_HB));
6954
6955                   Out_Of_Range_H :=
6956                     (Expr_Value (HB) > Expr_Value (T_HB))
6957                       or else
6958                     (Expr_Value (HB) < Expr_Value (T_LB));
6959                end if;
6960
6961                if not Null_Range then
6962                   if Out_Of_Range_L then
6963                      if No (Warn_Node) then
6964                         Add_Check
6965                           (Compile_Time_Constraint_Error
6966                              (Low_Bound (Ck_Node),
6967                               "static value out of range of}?", T_Typ));
6968
6969                      else
6970                         Add_Check
6971                           (Compile_Time_Constraint_Error
6972                             (Wnode,
6973                              "static range out of bounds of}?", T_Typ));
6974                      end if;
6975                   end if;
6976
6977                   if Out_Of_Range_H then
6978                      if No (Warn_Node) then
6979                         Add_Check
6980                           (Compile_Time_Constraint_Error
6981                              (High_Bound (Ck_Node),
6982                               "static value out of range of}?", T_Typ));
6983
6984                      else
6985                         Add_Check
6986                           (Compile_Time_Constraint_Error
6987                              (Wnode,
6988                               "static range out of bounds of}?", T_Typ));
6989                      end if;
6990                   end if;
6991                end if;
6992
6993             else
6994                declare
6995                   LB : Node_Id := Low_Bound (Ck_Node);
6996                   HB : Node_Id := High_Bound (Ck_Node);
6997
6998                begin
6999                   --  If either bound is a discriminant and we are within the
7000                   --  record declaration, it is a use of the discriminant in a
7001                   --  constraint of a component, and nothing can be checked
7002                   --  here. The check will be emitted within the init proc.
7003                   --  Before then, the discriminal has no real meaning.
7004                   --  Similarly, if the entity is a discriminal, there is no
7005                   --  check to perform yet.
7006
7007                   --  The same holds within a discriminated synchronized type,
7008                   --  where the discriminant may constrain a component or an
7009                   --  entry family.
7010
7011                   if Nkind (LB) = N_Identifier
7012                     and then Denotes_Discriminant (LB, True)
7013                   then
7014                      if Current_Scope = Scope (Entity (LB))
7015                        or else Is_Concurrent_Type (Current_Scope)
7016                        or else Ekind (Entity (LB)) /= E_Discriminant
7017                      then
7018                         return Ret_Result;
7019                      else
7020                         LB :=
7021                           New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
7022                      end if;
7023                   end if;
7024
7025                   if Nkind (HB) = N_Identifier
7026                     and then Denotes_Discriminant (HB, True)
7027                   then
7028                      if Current_Scope = Scope (Entity (HB))
7029                        or else Is_Concurrent_Type (Current_Scope)
7030                        or else Ekind (Entity (HB)) /= E_Discriminant
7031                      then
7032                         return Ret_Result;
7033                      else
7034                         HB :=
7035                           New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
7036                      end if;
7037                   end if;
7038
7039                   Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
7040                   Set_Paren_Count (Cond, 1);
7041
7042                   Cond :=
7043                     Make_And_Then (Loc,
7044                       Left_Opnd =>
7045                         Make_Op_Ge (Loc,
7046                           Left_Opnd  => Duplicate_Subexpr_No_Checks (HB),
7047                           Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
7048                       Right_Opnd => Cond);
7049                end;
7050             end if;
7051          end;
7052
7053       elsif Is_Scalar_Type (S_Typ) then
7054
7055          --  This somewhat duplicates what Apply_Scalar_Range_Check does,
7056          --  except the above simply sets a flag in the node and lets
7057          --  gigi generate the check base on the Etype of the expression.
7058          --  Sometimes, however we want to do a dynamic check against an
7059          --  arbitrary target type, so we do that here.
7060
7061          if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
7062             Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
7063
7064          --  For literals, we can tell if the constraint error will be
7065          --  raised at compile time, so we never need a dynamic check, but
7066          --  if the exception will be raised, then post the usual warning,
7067          --  and replace the literal with a raise constraint error
7068          --  expression. As usual, skip this for access types
7069
7070          elsif Compile_Time_Known_Value (Ck_Node)
7071            and then not Do_Access
7072          then
7073             declare
7074                LB : constant Node_Id := Type_Low_Bound (T_Typ);
7075                UB : constant Node_Id := Type_High_Bound (T_Typ);
7076
7077                Out_Of_Range  : Boolean;
7078                Static_Bounds : constant Boolean :=
7079                                  Compile_Time_Known_Value (LB)
7080                                    and Compile_Time_Known_Value (UB);
7081
7082             begin
7083                --  Following range tests should use Sem_Eval routine ???
7084
7085                if Static_Bounds then
7086                   if Is_Floating_Point_Type (S_Typ) then
7087                      Out_Of_Range :=
7088                        (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
7089                          or else
7090                        (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
7091
7092                   --  Fixed or discrete type
7093
7094                   else
7095                      Out_Of_Range :=
7096                        Expr_Value (Ck_Node) < Expr_Value (LB)
7097                          or else
7098                        Expr_Value (Ck_Node) > Expr_Value (UB);
7099                   end if;
7100
7101                   --  Bounds of the type are static and the literal is out of
7102                   --  range so output a warning message.
7103
7104                   if Out_Of_Range then
7105                      if No (Warn_Node) then
7106                         Add_Check
7107                           (Compile_Time_Constraint_Error
7108                              (Ck_Node,
7109                               "static value out of range of}?", T_Typ));
7110
7111                      else
7112                         Add_Check
7113                           (Compile_Time_Constraint_Error
7114                              (Wnode,
7115                               "static value out of range of}?", T_Typ));
7116                      end if;
7117                   end if;
7118
7119                else
7120                   Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
7121                end if;
7122             end;
7123
7124          --  Here for the case of a non-static expression, we need a runtime
7125          --  check unless the source type range is guaranteed to be in the
7126          --  range of the target type.
7127
7128          else
7129             if not In_Subrange_Of (S_Typ, T_Typ) then
7130                Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
7131             end if;
7132          end if;
7133       end if;
7134
7135       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
7136          if Is_Constrained (T_Typ) then
7137
7138             Expr_Actual := Get_Referenced_Object (Ck_Node);
7139             Exptyp      := Get_Actual_Subtype (Expr_Actual);
7140
7141             if Is_Access_Type (Exptyp) then
7142                Exptyp := Designated_Type (Exptyp);
7143             end if;
7144
7145             --  String_Literal case. This needs to be handled specially be-
7146             --  cause no index types are available for string literals. The
7147             --  condition is simply:
7148
7149             --    T_Typ'Length = string-literal-length
7150
7151             if Nkind (Expr_Actual) = N_String_Literal then
7152                null;
7153
7154             --  General array case. Here we have a usable actual subtype for
7155             --  the expression, and the condition is built from the two types
7156
7157             --     T_Typ'First     < Exptyp'First     or else
7158             --     T_Typ'Last      > Exptyp'Last      or else
7159             --     T_Typ'First(1)  < Exptyp'First(1)  or else
7160             --     T_Typ'Last(1)   > Exptyp'Last(1)   or else
7161             --     ...
7162
7163             elsif Is_Constrained (Exptyp) then
7164                declare
7165                   Ndims : constant Nat := Number_Dimensions (T_Typ);
7166
7167                   L_Index : Node_Id;
7168                   R_Index : Node_Id;
7169
7170                begin
7171                   L_Index := First_Index (T_Typ);
7172                   R_Index := First_Index (Exptyp);
7173
7174                   for Indx in 1 .. Ndims loop
7175                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
7176                                or else
7177                              Nkind (R_Index) = N_Raise_Constraint_Error)
7178                      then
7179                         --  Deal with compile time length check. Note that we
7180                         --  skip this in the access case, because the access
7181                         --  value may be null, so we cannot know statically.
7182
7183                         if not
7184                           Subtypes_Statically_Match
7185                             (Etype (L_Index), Etype (R_Index))
7186                         then
7187                            --  If the target type is constrained then we
7188                            --  have to check for exact equality of bounds
7189                            --  (required for qualified expressions).
7190
7191                            if Is_Constrained (T_Typ) then
7192                               Evolve_Or_Else
7193                                 (Cond,
7194                                  Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
7195                            else
7196                               Evolve_Or_Else
7197                                 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
7198                            end if;
7199                         end if;
7200
7201                         Next (L_Index);
7202                         Next (R_Index);
7203                      end if;
7204                   end loop;
7205                end;
7206
7207             --  Handle cases where we do not get a usable actual subtype that
7208             --  is constrained. This happens for example in the function call
7209             --  and explicit dereference cases. In these cases, we have to get
7210             --  the length or range from the expression itself, making sure we
7211             --  do not evaluate it more than once.
7212
7213             --  Here Ck_Node is the original expression, or more properly the
7214             --  result of applying Duplicate_Expr to the original tree,
7215             --  forcing the result to be a name.
7216
7217             else
7218                declare
7219                   Ndims : constant Nat := Number_Dimensions (T_Typ);
7220
7221                begin
7222                   --  Build the condition for the explicit dereference case
7223
7224                   for Indx in 1 .. Ndims loop
7225                      Evolve_Or_Else
7226                        (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
7227                   end loop;
7228                end;
7229             end if;
7230
7231          else
7232             --  For a conversion to an unconstrained array type, generate an
7233             --  Action to check that the bounds of the source value are within
7234             --  the constraints imposed by the target type (RM 4.6(38)). No
7235             --  check is needed for a conversion to an access to unconstrained
7236             --  array type, as 4.6(24.15/2) requires the designated subtypes
7237             --  of the two access types to statically match.
7238
7239             if Nkind (Parent (Ck_Node)) = N_Type_Conversion
7240               and then not Do_Access
7241             then
7242                declare
7243                   Opnd_Index : Node_Id;
7244                   Targ_Index : Node_Id;
7245                   Opnd_Range : Node_Id;
7246
7247                begin
7248                   Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
7249                   Targ_Index := First_Index (T_Typ);
7250                   while Present (Opnd_Index) loop
7251
7252                      --  If the index is a range, use its bounds. If it is an
7253                      --  entity (as will be the case if it is a named subtype
7254                      --  or an itype created for a slice) retrieve its range.
7255
7256                      if Is_Entity_Name (Opnd_Index)
7257                        and then Is_Type (Entity (Opnd_Index))
7258                      then
7259                         Opnd_Range := Scalar_Range (Entity (Opnd_Index));
7260                      else
7261                         Opnd_Range := Opnd_Index;
7262                      end if;
7263
7264                      if Nkind (Opnd_Range) = N_Range then
7265                         if  Is_In_Range
7266                              (Low_Bound (Opnd_Range), Etype (Targ_Index),
7267                               Assume_Valid => True)
7268                           and then
7269                             Is_In_Range
7270                              (High_Bound (Opnd_Range), Etype (Targ_Index),
7271                               Assume_Valid => True)
7272                         then
7273                            null;
7274
7275                         --  If null range, no check needed
7276
7277                         elsif
7278                           Compile_Time_Known_Value (High_Bound (Opnd_Range))
7279                             and then
7280                           Compile_Time_Known_Value (Low_Bound (Opnd_Range))
7281                             and then
7282                               Expr_Value (High_Bound (Opnd_Range)) <
7283                                   Expr_Value (Low_Bound (Opnd_Range))
7284                         then
7285                            null;
7286
7287                         elsif Is_Out_Of_Range
7288                                 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7289                                  Assume_Valid => True)
7290                           or else
7291                               Is_Out_Of_Range
7292                                 (High_Bound (Opnd_Range), Etype (Targ_Index),
7293                                  Assume_Valid => True)
7294                         then
7295                            Add_Check
7296                              (Compile_Time_Constraint_Error
7297                                (Wnode, "value out of range of}?", T_Typ));
7298
7299                         else
7300                            Evolve_Or_Else
7301                              (Cond,
7302                               Discrete_Range_Cond
7303                                 (Opnd_Range, Etype (Targ_Index)));
7304                         end if;
7305                      end if;
7306
7307                      Next_Index (Opnd_Index);
7308                      Next_Index (Targ_Index);
7309                   end loop;
7310                end;
7311             end if;
7312          end if;
7313       end if;
7314
7315       --  Construct the test and insert into the tree
7316
7317       if Present (Cond) then
7318          if Do_Access then
7319             Cond := Guard_Access (Cond, Loc, Ck_Node);
7320          end if;
7321
7322          Add_Check
7323            (Make_Raise_Constraint_Error (Loc,
7324              Condition => Cond,
7325              Reason    => CE_Range_Check_Failed));
7326       end if;
7327
7328       return Ret_Result;
7329    end Selected_Range_Checks;
7330
7331    -------------------------------
7332    -- Storage_Checks_Suppressed --
7333    -------------------------------
7334
7335    function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
7336    begin
7337       if Present (E) and then Checks_May_Be_Suppressed (E) then
7338          return Is_Check_Suppressed (E, Storage_Check);
7339       else
7340          return Scope_Suppress (Storage_Check);
7341       end if;
7342    end Storage_Checks_Suppressed;
7343
7344    ---------------------------
7345    -- Tag_Checks_Suppressed --
7346    ---------------------------
7347
7348    function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
7349    begin
7350       if Present (E) then
7351          if Kill_Tag_Checks (E) then
7352             return True;
7353          elsif Checks_May_Be_Suppressed (E) then
7354             return Is_Check_Suppressed (E, Tag_Check);
7355          end if;
7356       end if;
7357
7358       return Scope_Suppress (Tag_Check);
7359    end Tag_Checks_Suppressed;
7360
7361    --------------------------
7362    -- Validity_Check_Range --
7363    --------------------------
7364
7365    procedure Validity_Check_Range (N : Node_Id) is
7366    begin
7367       if Validity_Checks_On and Validity_Check_Operands then
7368          if Nkind (N) = N_Range then
7369             Ensure_Valid (Low_Bound (N));
7370             Ensure_Valid (High_Bound (N));
7371          end if;
7372       end if;
7373    end Validity_Check_Range;
7374
7375    --------------------------------
7376    -- Validity_Checks_Suppressed --
7377    --------------------------------
7378
7379    function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
7380    begin
7381       if Present (E) and then Checks_May_Be_Suppressed (E) then
7382          return Is_Check_Suppressed (E, Validity_Check);
7383       else
7384          return Scope_Suppress (Validity_Check);
7385       end if;
7386    end Validity_Checks_Suppressed;
7387
7388 end Checks;