OSDN Git Service

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