OSDN Git Service

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