1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             G N A T 1 D R V                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2021, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26with Atree;          use Atree;
27with Back_End;       use Back_End;
28with Checks;
29with Comperr;
30with Csets;
31with Debug;          use Debug;
32with Elists;
33with Errout;         use Errout;
34with Exp_CG;
35with Fmap;
36with Fname;          use Fname;
37with Fname.UF;       use Fname.UF;
38with Frontend;
39with Ghost;          use Ghost;
40with Gnatvsn;        use Gnatvsn;
41with Inline;
42with Lib;            use Lib;
43with Lib.Writ;       use Lib.Writ;
44with Lib.Xref;
45with Namet;          use Namet;
46with Nlists;
47with Opt;            use Opt;
48with Osint;          use Osint;
49with Osint.C;        use Osint.C;
50with Output;         use Output;
51with Par_SCO;
52with Prepcomp;
53with Repinfo;
54with Repinfo.Input;
55with Restrict;
56with Rident;         use Rident;
57with Rtsfind;
58with SCOs;
59with Sem;
60with Sem_Ch8;
61with Sem_Ch12;
62with Sem_Ch13;
63with Sem_Elim;
64with Sem_Eval;
65with Sem_Prag;
66with Sem_Type;
67with Set_Targ;
68with Sinfo;          use Sinfo;
69with Sinfo.Nodes;    use Sinfo.Nodes;
70with Sinput;         use Sinput;
71with Sinput.L;       use Sinput.L;
72with Snames;         use Snames;
73with Sprint;         use Sprint;
74with Stringt;
75with Stylesw;        use Stylesw;
76with Targparm;       use Targparm;
77with Tbuild;
78with Treepr;         use Treepr;
79with Ttypes;
80with Types;          use Types;
81with Uintp;
82with Uname;          use Uname;
83with Urealp;
84with Usage;
85with Validsw;        use Validsw;
86with Warnsw;         use Warnsw;
87
88with System.Assertions;
89with System.OS_Lib;
90
91--------------
92-- Gnat1drv --
93--------------
94
95procedure Gnat1drv is
96   procedure Adjust_Global_Switches;
97   --  There are various interactions between front-end switch settings,
98   --  including debug switch settings and target dependent parameters.
99   --  This procedure takes care of properly handling these interactions.
100   --  We do it after scanning out all the switches, so that we are not
101   --  depending on the order in which switches appear.
102
103   procedure Check_Bad_Body (Unit_Node : Node_Id; Unit_Kind : Node_Kind);
104   --  Called to check whether a unit described by its compilation unit node
105   --  and kind has a bad body.
106
107   procedure Check_Rep_Info;
108   --  Called when we are not generating code, to check if -gnatR was requested
109   --  and if so, explain that we will not be honoring the request.
110
111   procedure Post_Compilation_Validation_Checks;
112   --  This procedure performs various validation checks that have to be left
113   --  to the end of the compilation process, after generating code but before
114   --  issuing error messages. In particular, these checks generally require
115   --  the information provided by the back end in back annotation of declared
116   --  entities (e.g. actual size and alignment values chosen by the back end).
117
118   procedure Read_JSON_Files_For_Repinfo;
119   --  This procedure exercises the JSON parser of Repinfo by reading back the
120   --  JSON files generated by -gnatRjs in a previous compilation session. It
121   --  is intended to make sure that the JSON generator and the JSON parser are
122   --  kept synchronized when the JSON format evolves.
123
124   ----------------------------
125   -- Adjust_Global_Switches --
126   ----------------------------
127
128   procedure Adjust_Global_Switches is
129      procedure SPARK_Library_Warning (Kind : String);
130      --  Issue a warning in GNATprove mode if the run-time library does not
131      --  fully support IEEE-754 floating-point semantics.
132
133      ---------------------------
134      -- SPARK_Library_Warning --
135      ---------------------------
136
137      procedure SPARK_Library_Warning (Kind : String) is
138      begin
139         Write_Line
140           ("warning: run-time library may be configured incorrectly");
141         Write_Line
142           ("warning: (SPARK analysis requires support for " & Kind & ')');
143      end SPARK_Library_Warning;
144
145   --  Start of processing for Adjust_Global_Switches
146
147   begin
148
149      --  -gnatd_U disables prepending error messages with "error:"
150
151      if Debug_Flag_Underscore_UU then
152         Unique_Error_Tag := False;
153      end if;
154
155      --  -gnatd.M enables Relaxed_RM_Semantics
156
157      if Debug_Flag_Dot_MM then
158         Relaxed_RM_Semantics := True;
159      end if;
160
161      --  -gnatd.1 enables unnesting of subprograms
162
163      if Debug_Flag_Dot_1 then
164         Unnest_Subprogram_Mode := True;
165      end if;
166
167      --  -gnatd.u enables special C expansion mode
168
169      if Debug_Flag_Dot_U then
170         Modify_Tree_For_C := True;
171         Transform_Function_Array := True;
172      end if;
173
174      --  -gnatd_A disables generation of ALI files
175
176      if Debug_Flag_Underscore_AA then
177         Disable_ALI_File := True;
178      end if;
179
180      --  Set all flags required when generating C code
181
182      if Generate_C_Code then
183         Modify_Tree_For_C := True;
184         Transform_Function_Array := True;
185         Unnest_Subprogram_Mode := True;
186         Building_Static_Dispatch_Tables := False;
187         Minimize_Expression_With_Actions := True;
188         Expand_Nonbinary_Modular_Ops := True;
189
190         --  Set operating mode to Generate_Code to benefit from full front-end
191         --  expansion (e.g. generics).
192
193         Operating_Mode := Generate_Code;
194
195         --  Suppress alignment checks since we do not have access to alignment
196         --  info on the target.
197
198         Suppress_Options.Suppress (Alignment_Check) := False;
199      end if;
200
201      --  -gnatd.E sets Error_To_Warning mode, causing selected error messages
202      --  to be treated as warnings instead of errors.
203
204      if Debug_Flag_Dot_EE then
205         Error_To_Warning := True;
206      end if;
207
208      --  -gnatdJ sets Include_Subprogram_In_Messages, adding the related
209      --  subprogram as part of the error and warning messages.
210
211      if Debug_Flag_JJ then
212         Include_Subprogram_In_Messages := True;
213      end if;
214
215      --  Disable CodePeer_Mode in Check_Syntax, since we need front-end
216      --  expansion.
217
218      if Operating_Mode = Check_Syntax then
219         CodePeer_Mode := False;
220      end if;
221
222      --  SCIL mode needs to disable front-end inlining since the generated
223      --  trees (in particular order and consistency between specs compiled
224      --  as part of a main unit or as part of a with-clause) are causing
225      --  troubles.
226
227      if Generate_SCIL then
228         Front_End_Inlining := False;
229      end if;
230
231      --  Tune settings for optimal SCIL generation in CodePeer mode
232
233      if CodePeer_Mode then
234
235         --  Turn off gnatprove mode (which can be set via e.g. -gnatd.F), not
236         --  compatible with CodePeer mode.
237
238         GNATprove_Mode := False;
239         Debug_Flag_Dot_FF := False;
240
241         --  Turn off length expansion. CodePeer has its own mechanism to
242         --  handle length attribute.
243
244         Debug_Flag_Dot_PP := True;
245
246         --  Turn off C tree generation, not compatible with CodePeer mode. We
247         --  do not expect this to happen in normal use, since both modes are
248         --  enabled by special tools, but it is useful to turn off these flags
249         --  this way when we are doing CodePeer tests on existing test suites
250         --  that may have -gnateg set, to avoid the need for special casing.
251
252         Modify_Tree_For_C        := False;
253         Transform_Function_Array := False;
254         Generate_C_Code          := False;
255         Unnest_Subprogram_Mode   := False;
256
257         --  Turn off inlining, confuses CodePeer output and gains nothing
258
259         Front_End_Inlining := False;
260         Inline_Active      := False;
261
262         --  Disable front-end optimizations, to keep the tree as close to the
263         --  source code as possible, and also to avoid inconsistencies between
264         --  trees when using different optimization switches.
265
266         Optimization_Level := 0;
267
268         --  Enable some restrictions systematically to simplify the generated
269         --  code (and ease analysis). Note that restriction checks are also
270         --  disabled in CodePeer mode, see Restrict.Check_Restriction, and
271         --  user specified Restrictions pragmas are ignored, see
272         --  Sem_Prag.Process_Restrictions_Or_Restriction_Warnings.
273
274         Restrict.Restrictions.Set   (No_Exception_Registration)       := True;
275         Restrict.Restrictions.Set   (No_Initialize_Scalars)           := True;
276         Restrict.Restrictions.Set   (No_Task_Hierarchy)               := True;
277         Restrict.Restrictions.Set   (No_Abort_Statements)             := True;
278         Restrict.Restrictions.Set   (Max_Asynchronous_Select_Nesting) := True;
279         Restrict.Restrictions.Value (Max_Asynchronous_Select_Nesting) := 0;
280
281         --  Enable pragma Ignore_Pragma (Global) to support legacy code. As a
282         --  consequence, Refined_Global pragma should be ignored as well, as
283         --  it is only allowed on a body when pragma Global is given for the
284         --  spec.
285
286         Set_Name_Table_Boolean3 (Name_Global, True);
287         Set_Name_Table_Boolean3 (Name_Refined_Global, True);
288
289         --  Suppress division by zero checks since they are handled
290         --  implicitly by CodePeer.
291
292         --  Turn off dynamic elaboration checks: generates inconsistencies in
293         --  trees between specs compiled as part of a main unit or as part of
294         --  a with-clause.
295
296         --  Turn off alignment checks: these cannot be proved statically by
297         --  CodePeer and generate false positives.
298
299         --  Enable all other language checks
300
301         Suppress_Options.Suppress :=
302           (Alignment_Check   => True,
303            Division_Check    => True,
304            Elaboration_Check => True,
305            others            => False);
306
307         --  Need to enable dynamic elaboration checks to disable strict
308         --  static checking performed by gnatbind. We are at the same time
309         --  suppressing actual compile time elaboration checks to simplify
310         --  the generated code.
311
312         Dynamic_Elaboration_Checks := True;
313
314         --  Set STRICT mode for overflow checks if not set explicitly. This
315         --  prevents suppressing of overflow checks by default, in code down
316         --  below.
317
318         if Suppress_Options.Overflow_Mode_General = Not_Set then
319            Suppress_Options.Overflow_Mode_General    := Strict;
320            Suppress_Options.Overflow_Mode_Assertions := Strict;
321         end if;
322
323         --  CodePeer handles division and overflow checks directly, based on
324         --  the marks set by the frontend, hence no special expansion should
325         --  be performed in the frontend for division and overflow checks.
326
327         Backend_Divide_Checks_On_Target   := True;
328         Backend_Overflow_Checks_On_Target := True;
329
330         --  Kill debug of generated code, since it messes up sloc values
331
332         Debug_Generated_Code := False;
333
334         --  Ditto for -gnateG which interacts badly with handling of pragma
335         --  Annotate in gnat2scil.
336
337         Generate_Processed_File := False;
338
339         --  Disable Exception_Extra_Info (-gnateE) which generates more
340         --  complex trees with no added value, and may confuse CodePeer.
341
342         Exception_Extra_Info := False;
343
344         --  Turn cross-referencing on in case it was disabled (e.g. by -gnatD)
345         --  to support source navigation.
346
347         Xref_Active := True;
348
349         --  Set operating mode to Generate_Code to benefit from full front-end
350         --  expansion (e.g. generics).
351
352         Operating_Mode := Generate_Code;
353
354         --  We need SCIL generation of course
355
356         Generate_SCIL := True;
357
358         --  Enable assertions, since they give CodePeer valuable extra info
359
360         Assertions_Enabled := True;
361
362         --  Set normal RM validity checking and checking of copies (to catch
363         --  e.g. wrong values used in unchecked conversions).
364         --  All other validity checking is turned off, since this can generate
365         --  very complex trees that only confuse CodePeer and do not bring
366         --  enough useful info.
367
368         Reset_Validity_Check_Options;
369         Set_Validity_Check_Options ("dc");
370         Check_Validity_Of_Parameters := False;
371
372         --  Turn off style check options and ignore any style check pragmas
373         --  since we are not interested in any front-end warnings when we are
374         --  getting CodePeer output.
375
376         Reset_Style_Check_Options;
377         Ignore_Style_Checks_Pragmas := True;
378
379         --  Always perform semantics and generate ali files in CodePeer mode,
380         --  so that a gnatmake -c -k will proceed further when possible.
381
382         Force_ALI_File := True;
383         Try_Semantics := True;
384
385         --  Make the Ada front end more liberal so that the compiler will
386         --  allow illegal code that is allowed by other compilers. CodePeer
387         --  is in the business of finding problems, not enforcing rules.
388         --  This is useful when using CodePeer mode with other compilers.
389
390         Relaxed_RM_Semantics := True;
391
392         if Generate_CodePeer_Messages then
393
394            --  We do want to emit GNAT warnings when using -gnateC. But,
395            --  in CodePeer mode, warnings about memory representation are not
396            --  meaningful, thus, suppress them.
397
398            Warn_On_Biased_Representation := False; -- -gnatw.b
399            Warn_On_Unrepped_Components := False;   -- -gnatw.c
400            Warn_On_Record_Holes := False;          -- -gnatw.h
401            Warn_On_Unchecked_Conversion := False;  -- -gnatwz
402            Warn_On_Size_Alignment := False;        -- -gnatw.z
403            Warn_On_Questionable_Layout := False;   -- -gnatw.q
404            Warn_On_Overridden_Size := False;       -- -gnatw.s
405            Warn_On_Reverse_Bit_Order := False;     -- -gnatw.v
406
407         else
408
409            --  Suppress compiler warnings by default when generating SCIL for
410            --  CodePeer, except when combined with -gnateC where we do want to
411            --  emit GNAT warnings.
412
413            Warning_Mode := Suppress;
414         end if;
415
416         --  Disable all simple value propagation. This is an optimization
417         --  which is valuable for code optimization, and also for generation
418         --  of compiler warnings, but these are being turned off by default,
419         --  and CodePeer generates better messages (referencing original
420         --  variables) this way.
421         --  Do this only if -gnatws is set (the default with -gnatcC), so that
422         --  if warnings are enabled, we'll get better messages from GNAT.
423
424         if Warning_Mode = Suppress then
425            Debug_Flag_MM := True;
426         end if;
427
428         --  The implementation of 'Value that uses a perfect hash function
429         --  is significantly more complex and harder to initialize than the
430         --  old implementation. Deactivate it for CodePeer.
431
432         Debug_Flag_Underscore_H := True;
433      end if;
434
435      --  Enable some individual switches that are implied by relaxed RM
436      --  semantics mode.
437
438      if Relaxed_RM_Semantics then
439         Opt.Allow_Integer_Address := True;
440         Overriding_Renamings := True;
441         Treat_Categorization_Errors_As_Warnings := True;
442      end if;
443
444      --  Enable GNATprove_Mode when using -gnatd.F switch
445
446      if Debug_Flag_Dot_FF then
447         GNATprove_Mode := True;
448      end if;
449
450      --  GNATprove_Mode is also activated by default in the gnat2why
451      --  executable.
452
453      if GNATprove_Mode then
454
455         --  Turn off CodePeer mode (which can be set via e.g. -gnatC or
456         --  -gnateC), not compatible with GNATprove mode.
457
458         CodePeer_Mode := False;
459         Generate_SCIL := False;
460
461         --  Turn off C tree generation, not compatible with GNATprove mode. We
462         --  do not expect this to happen in normal use, since both modes are
463         --  enabled by special tools, but it is useful to turn off these flags
464         --  this way when we are doing GNATprove tests on existing test suites
465         --  that may have -gnateg set, to avoid the need for special casing.
466
467         Modify_Tree_For_C        := False;
468         Transform_Function_Array := False;
469         Generate_C_Code          := False;
470         Unnest_Subprogram_Mode   := False;
471
472         --  Turn off inlining, which would confuse formal verification output
473         --  and gain nothing.
474
475         Front_End_Inlining := False;
476         Inline_Active      := False;
477
478         --  Issue warnings for failure to inline subprograms, as otherwise
479         --  expected in GNATprove mode for the local subprograms without
480         --  contracts.
481
482         Ineffective_Inline_Warnings := True;
483
484         --  Do not issue warnings for possible propagation of exception.
485         --  GNATprove already issues messages about possible exceptions.
486
487         No_Warn_On_Non_Local_Exception := True;
488         Warn_On_Non_Local_Exception := False;
489
490         --  Disable front-end optimizations, to keep the tree as close to the
491         --  source code as possible, and also to avoid inconsistencies between
492         --  trees when using different optimization switches.
493
494         Optimization_Level := 0;
495
496         --  Enable some restrictions systematically to simplify the generated
497         --  code (and ease analysis).
498
499         Restrict.Restrictions.Set (No_Initialize_Scalars) := True;
500
501         --  Note: at this point we used to suppress various checks, but that
502         --  is not what we want. We need the semantic processing for these
503         --  checks (which will set flags like Do_Overflow_Check, showing the
504         --  points at which potential checks are required semantically). We
505         --  don't want the expansion associated with these checks, but that
506         --  happens anyway because this expansion is simply not done in the
507         --  SPARK version of the expander.
508
509         --  On the contrary, we need to enable explicitly all language checks,
510         --  as they may have been suppressed by the use of switch -gnatp.
511
512         Suppress_Options.Suppress := (others => False);
513
514         --  Detect overflow on unconstrained floating-point types, such as
515         --  the predefined types Float, Long_Float and Long_Long_Float from
516         --  package Standard. Not necessary if float overflows are checked
517         --  (Machine_Overflow true), since appropriate Do_Overflow_Check flags
518         --  will be set in any case.
519
520         Check_Float_Overflow := not Machine_Overflows_On_Target;
521
522         --  Set STRICT mode for overflow checks if not set explicitly. This
523         --  prevents suppressing of overflow checks by default, in code down
524         --  below.
525
526         if Suppress_Options.Overflow_Mode_General = Not_Set then
527            Suppress_Options.Overflow_Mode_General    := Strict;
528            Suppress_Options.Overflow_Mode_Assertions := Strict;
529         end if;
530
531         --  Kill debug of generated code, since it messes up sloc values
532
533         Debug_Generated_Code := False;
534
535         --  Turn cross-referencing on in case it was disabled (e.g. by -gnatD)
536         --  as it is needed for computing effects of subprograms in the formal
537         --  verification backend.
538
539         Xref_Active := True;
540
541         --  Set operating mode to Check_Semantics, but a light front-end
542         --  expansion is still performed.
543
544         Operating_Mode := Check_Semantics;
545
546         --  Enable assertions, since they give valuable extra information for
547         --  formal verification.
548
549         Assertions_Enabled := True;
550
551         --  Disable validity checks, since it generates code raising
552         --  exceptions for invalid data, which confuses GNATprove. Invalid
553         --  data is directly detected by GNATprove's flow analysis.
554
555         Validity_Checks_On := False;
556         Check_Validity_Of_Parameters := False;
557
558         --  Turn off style check options since we are not interested in any
559         --  front-end warnings when we are getting SPARK output.
560
561         Reset_Style_Check_Options;
562
563         --  Suppress the generation of name tables for enumerations, which are
564         --  not needed for formal verification, and fall outside the SPARK
565         --  subset (use of pointers).
566
567         Global_Discard_Names := True;
568
569         --  Suppress the expansion of tagged types and dispatching calls,
570         --  which lead to the generation of non-SPARK code (use of pointers),
571         --  which is more complex to formally verify than the original source.
572
573         Tagged_Type_Expansion := False;
574
575         --  Force the use of "error:" prefix for error messages
576
577         Unique_Error_Tag := True;
578
579         --  Detect that the runtime library support for floating-point numbers
580         --  may not be compatible with SPARK analysis of IEEE-754 floats.
581
582         if Denorm_On_Target = False then
583            SPARK_Library_Warning ("float subnormals");
584
585         elsif Machine_Rounds_On_Target = False then
586            SPARK_Library_Warning ("float rounding");
587
588         elsif Signed_Zeros_On_Target = False then
589            SPARK_Library_Warning ("signed zeros");
590         end if;
591      end if;
592
593      --  Set Configurable_Run_Time mode if system.ads flag set or if the
594      --  special debug flag -gnatdY is set.
595
596      if Targparm.Configurable_Run_Time_On_Target or Debug_Flag_YY then
597         Configurable_Run_Time_Mode := True;
598      end if;
599
600      --  Set -gnatRm mode if debug flag A set
601
602      if Debug_Flag_AA then
603         Back_Annotate_Rep_Info := True;
604         List_Representation_Info := 1;
605         List_Representation_Info_Mechanisms := True;
606      end if;
607
608      --  Force Target_Strict_Alignment true if debug flag -gnatd.a is set
609
610      if Debug_Flag_Dot_A then
611         Ttypes.Target_Strict_Alignment := True;
612      end if;
613
614      --  Disable static allocation of dispatch tables if -gnatd.t is enabled.
615      --  The front end's layout phase currently treats types that have
616      --  discriminant-dependent arrays as not being static even when a
617      --  discriminant constraint on the type is static, and this leads to
618      --  problems with subtypes of type Ada.Tags.Dispatch_Table_Wrapper. ???
619
620      if Debug_Flag_Dot_T then
621         Building_Static_Dispatch_Tables := False;
622      end if;
623
624      --  Flip endian mode if -gnatd8 set
625
626      if Debug_Flag_8 then
627         Ttypes.Bytes_Big_Endian := not Ttypes.Bytes_Big_Endian;
628      end if;
629
630      --  Set and check exception mechanism. This is only meaningful when
631      --  generating code.
632
633      if Operating_Mode = Generate_Code then
634         case Targparm.Frontend_Exceptions_On_Target is
635            when True =>
636               case Targparm.ZCX_By_Default_On_Target is
637                  when True =>
638                     Write_Line
639                       ("Run-time library configured incorrectly");
640                     Write_Line
641                       ("(requesting support for Frontend ZCX exceptions)");
642                     raise Unrecoverable_Error;
643
644                  when False =>
645                     Exception_Mechanism := Front_End_SJLJ;
646               end case;
647
648            when False =>
649               case Targparm.ZCX_By_Default_On_Target is
650                  when True =>
651                     Exception_Mechanism := Back_End_ZCX;
652                  when False =>
653                     Exception_Mechanism := Back_End_SJLJ;
654               end case;
655         end case;
656      end if;
657
658      --  Set proper status for overflow check mechanism
659
660      --  If already set (by -gnato or above in SPARK or CodePeer mode) then we
661      --  have nothing to do.
662
663      if Opt.Suppress_Options.Overflow_Mode_General /= Not_Set then
664         null;
665
666      --  Otherwise set overflow mode defaults
667
668      else
669         --  Overflow checks are on by default (Suppress set False) except in
670         --  GNAT_Mode, where we want them off by default (we are not ready to
671         --  enable overflow checks in the compiler yet, for one thing the case
672         --  of 64-bit checks needs System.Arith_64 which is not a compiler
673         --  unit and it is a pain to try to include it in the compiler.
674
675         Suppress_Options.Suppress (Overflow_Check) := GNAT_Mode;
676
677         --  Set appropriate default overflow handling mode. Note: at present
678         --  we set STRICT in all three of the following cases. They are
679         --  separated because in the future we may make different choices.
680
681         --  By default set STRICT mode if -gnatg in effect
682
683         if GNAT_Mode then
684            Suppress_Options.Overflow_Mode_General    := Strict;
685            Suppress_Options.Overflow_Mode_Assertions := Strict;
686
687         --  If we have backend divide and overflow checks, then by default
688         --  overflow checks are STRICT. Historically this code used to also
689         --  activate overflow checks, although no target currently has these
690         --  flags set, so this was dead code anyway.
691
692         elsif Targparm.Backend_Divide_Checks_On_Target
693                 and
694               Targparm.Backend_Overflow_Checks_On_Target
695         then
696            Suppress_Options.Overflow_Mode_General    := Strict;
697            Suppress_Options.Overflow_Mode_Assertions := Strict;
698
699         --  Otherwise for now, default is STRICT mode. This may change in the
700         --  future, but for now this is the compatible behavior with previous
701         --  versions of GNAT.
702
703         else
704            Suppress_Options.Overflow_Mode_General    := Strict;
705            Suppress_Options.Overflow_Mode_Assertions := Strict;
706         end if;
707      end if;
708
709      --  Set default for atomic synchronization. As this synchronization
710      --  between atomic accesses can be expensive, and not typically needed
711      --  on some targets, an optional target parameter can turn the option
712      --  off. Note Atomic Synchronization is implemented as check.
713
714      Suppress_Options.Suppress (Atomic_Synchronization) :=
715        not Atomic_Sync_Default_On_Target;
716
717      --  Set default for Alignment_Check, if we are on a machine with non-
718      --  strict alignment, then we suppress this check, since it is over-
719      --  zealous for such machines.
720
721      if not Ttypes.Target_Strict_Alignment then
722         Suppress_Options.Suppress (Alignment_Check) := True;
723      end if;
724
725      --  Set switch indicating if back end can handle limited types, and
726      --  guarantee that no incorrect copies are made (e.g. in the context
727      --  of an if or case expression).
728
729      --  Debug flag -gnatd.L decisively sets usage on
730
731      if Debug_Flag_Dot_LL then
732         Back_End_Handles_Limited_Types := True;
733
734      --  If no debug flag, usage off for SCIL cases
735
736      elsif Generate_SCIL then
737         Back_End_Handles_Limited_Types := False;
738
739      --  Otherwise normal gcc back end, for now still turn flag off by
740      --  default, since there are unresolved problems in the front end.
741
742      else
743         Back_End_Handles_Limited_Types := False;
744      end if;
745
746      --  If the inlining level has not been set by the user, compute it from
747      --  the optimization level: 1 at -O1/-O2 (and -Os), 2 at -O3 and above.
748
749      if Inline_Level = 0 then
750         if Optimization_Level < 3 then
751            Inline_Level := 1;
752         else
753            Inline_Level := 2;
754         end if;
755      end if;
756
757      --  Treat -gnatn as equivalent to -gnatN for non-GCC targets
758
759      if Inline_Active and not Front_End_Inlining then
760
761         --  We really should have a tag for this, what if we added a new
762         --  back end some day, it would not be true for this test, but it
763         --  would be non-GCC, so this is a bit troublesome ???
764
765         Front_End_Inlining := Generate_C_Code;
766      end if;
767
768      --  Set back-end inlining indication
769
770      Back_End_Inlining :=
771
772        --  No back-end inlining available on C generation
773
774        not Generate_C_Code
775
776        --  No back-end inlining in GNATprove mode, since it just confuses
777        --  the formal verification process.
778
779        and then not GNATprove_Mode
780
781        --  No back-end inlining if front-end inlining explicitly enabled.
782        --  Done to minimize the output differences to customers still using
783        --  this deprecated switch; in addition, this behavior reduces the
784        --  output differences in old tests.
785
786        and then not Front_End_Inlining
787
788        --  Back-end inlining is disabled if debug flag .z is set
789
790        and then not Debug_Flag_Dot_Z;
791
792      --  Output warning if -gnateE specified and cannot be supported
793
794      if Exception_Extra_Info
795        and then Restrict.No_Exception_Handlers_Set
796      then
797         Set_Standard_Error;
798         Write_Str
799           ("warning: extra exception information (-gnateE) was specified");
800         Write_Eol;
801         Write_Str
802           ("warning: this capability is not available in this configuration");
803         Write_Eol;
804         Set_Standard_Output;
805      end if;
806
807      --  Enable or disable the support for 128-bit types. It is automatically
808      --  enabled if the back end supports them, unless -gnatd.H is specified.
809
810      Enable_128bit_Types := Ttypes.Standard_Long_Long_Long_Integer_Size = 128;
811
812      if Enable_128bit_Types and then Debug_Flag_Dot_HH then
813         Enable_128bit_Types := False;
814
815         Ttypes.Standard_Long_Long_Long_Integer_Size :=
816           Ttypes.Standard_Long_Long_Integer_Size;
817         Ttypes.System_Max_Integer_Size :=
818           Ttypes.Standard_Long_Long_Integer_Size;
819         Ttypes.System_Max_Binary_Modulus_Power :=
820           Ttypes.Standard_Long_Long_Integer_Size;
821      end if;
822
823      --  Forcefully use a 32-bit Duration with only 32-bit integer types
824
825      if Ttypes.System_Max_Integer_Size < 64 then
826         Targparm.Duration_32_Bits_On_Target := True;
827      end if;
828
829      --  Finally capture adjusted value of Suppress_Options as the initial
830      --  value for Scope_Suppress, which will be modified as we move from
831      --  scope to scope (by Suppress/Unsuppress/Overflow_Checks pragmas).
832
833      Sem.Scope_Suppress := Opt.Suppress_Options;
834   end Adjust_Global_Switches;
835
836   --------------------
837   -- Check_Bad_Body --
838   --------------------
839
840   procedure Check_Bad_Body (Unit_Node : Node_Id; Unit_Kind : Node_Kind) is
841      Fname : File_Name_Type;
842
843      procedure Bad_Body_Error (Msg : String);
844      --  Issue message for bad body found
845
846      --------------------
847      -- Bad_Body_Error --
848      --------------------
849
850      procedure Bad_Body_Error (Msg : String) is
851      begin
852         Error_Msg_N (Msg, Unit_Node);
853         Error_Msg_File_1 := Fname;
854         Error_Msg_N ("remove incorrect body in file{!", Unit_Node);
855      end Bad_Body_Error;
856
857      --  Local variables
858
859      Sname   : Unit_Name_Type;
860      Src_Ind : Source_File_Index;
861
862   --  Start of processing for Check_Bad_Body
863
864   begin
865      --  Nothing to do if we are only checking syntax, because we don't know
866      --  enough to know if we require or forbid a body in this case.
867
868      if Operating_Mode = Check_Syntax then
869         return;
870      end if;
871
872      --  Check for body not allowed
873
874      if (Unit_Kind = N_Package_Declaration
875           and then not Body_Required (Unit_Node))
876        or else (Unit_Kind = N_Generic_Package_Declaration
877                  and then not Body_Required (Unit_Node))
878        or else Unit_Kind = N_Package_Renaming_Declaration
879        or else Unit_Kind = N_Subprogram_Renaming_Declaration
880        or else Nkind (Original_Node (Unit (Unit_Node)))
881                         in N_Generic_Instantiation
882      then
883         Sname := Unit_Name (Main_Unit);
884
885         --  If we do not already have a body name, then get the body name
886
887         if not Is_Body_Name (Sname) then
888            Sname := Get_Body_Name (Sname);
889         end if;
890
891         Fname := Get_File_Name (Sname, Subunit => False);
892         Src_Ind := Load_Source_File (Fname);
893
894         --  Case where body is present and it is not a subunit. Exclude the
895         --  subunit case, because it has nothing to do with the package we are
896         --  compiling. It is illegal for a child unit and a subunit with the
897         --  same expanded name (RM 10.2(9)) to appear together in a partition,
898         --  but there is nothing to stop a compilation environment from having
899         --  both, and the test here simply allows that. If there is an attempt
900         --  to include both in a partition, this is diagnosed at bind time. In
901         --  Ada 83 mode this is not a warning case.
902
903         --  Note that in general we do not give the message if the file in
904         --  question does not look like a body. This includes weird cases,
905         --  but in particular means that if the file is just a No_Body pragma,
906         --  then we won't give the message (that's the whole point of this
907         --  pragma, to be used this way and to cause the body file to be
908         --  ignored in this context).
909
910         if Src_Ind > No_Source_File
911           and then Source_File_Is_Body (Src_Ind)
912         then
913            Errout.Finalize (Last_Call => False);
914
915            Error_Msg_Unit_1 := Sname;
916
917            --  Ada 83 case of a package body being ignored. This is not an
918            --  error as far as the Ada 83 RM is concerned, but it is almost
919            --  certainly not what is wanted so output a warning. Give this
920            --  message only if there were no errors, since otherwise it may
921            --  be incorrect (we may have misinterpreted a junk spec as not
922            --  needing a body when it really does).
923
924            if Unit_Kind = N_Package_Declaration
925              and then Ada_Version = Ada_83
926              and then Operating_Mode = Generate_Code
927              and then Distribution_Stub_Mode /= Generate_Caller_Stub_Body
928              and then not Compilation_Errors
929            then
930               Error_Msg_N
931                 ("package $$ does not require a body??", Unit_Node);
932               Error_Msg_File_1 := Fname;
933               Error_Msg_N ("body in file{ will be ignored??", Unit_Node);
934
935               --  Ada 95 cases of a body file present when no body is
936               --  permitted. This we consider to be an error.
937
938            else
939               --  For generic instantiations, we never allow a body
940
941               if Nkind (Original_Node (Unit (Unit_Node))) in
942                                                    N_Generic_Instantiation
943               then
944                  Bad_Body_Error
945                    ("generic instantiation for $$ does not allow a body");
946
947               --  A library unit that is a renaming never allows a body
948
949               elsif Unit_Kind in N_Renaming_Declaration then
950                  Bad_Body_Error
951                    ("renaming declaration for $$ does not allow a body!");
952
953                  --  Remaining cases are packages and generic packages. Here
954                  --  we only do the test if there are no previous errors,
955                  --  because if there are errors, they may lead us to
956                  --  incorrectly believe that a package does not allow a
957                  --  body when in fact it does.
958
959               elsif not Compilation_Errors then
960                  if Unit_Kind = N_Package_Declaration then
961                     Bad_Body_Error
962                       ("package $$ does not allow a body!");
963
964                  elsif Unit_Kind = N_Generic_Package_Declaration then
965                     Bad_Body_Error
966                       ("generic package $$ does not allow a body!");
967                  end if;
968               end if;
969
970            end if;
971         end if;
972      end if;
973   end Check_Bad_Body;
974
975   --------------------
976   -- Check_Rep_Info --
977   --------------------
978
979   procedure Check_Rep_Info is
980   begin
981      if List_Representation_Info /= 0
982        or else List_Representation_Info_Mechanisms
983      then
984         Set_Standard_Error;
985         Write_Eol;
986         Write_Str
987           ("cannot generate representation information, no code generated");
988         Write_Eol;
989         Write_Eol;
990         Set_Standard_Output;
991      end if;
992   end Check_Rep_Info;
993
994   ----------------------------------------
995   -- Post_Compilation_Validation_Checks --
996   ----------------------------------------
997
998   procedure Post_Compilation_Validation_Checks is
999   begin
1000      --  Validate alignment check warnings. In some cases we generate warnings
1001      --  about possible alignment errors because we don't know the alignment
1002      --  that will be chosen by the back end. This routine is in charge of
1003      --  getting rid of those warnings if we can tell they are not needed.
1004
1005      Checks.Validate_Alignment_Check_Warnings;
1006
1007      --  Validate compile time warnings and errors (using the values for size
1008      --  and alignment annotated by the backend where possible). We need to
1009      --  unlock temporarily these tables to reanalyze their expression.
1010
1011      Atree.Unlock;
1012      Nlists.Unlock;
1013      Elists.Unlock;
1014      Sem.Unlock;
1015      Sem_Prag.Validate_Compile_Time_Warning_Errors;
1016      Sem.Lock;
1017      Elists.Lock;
1018      Nlists.Lock;
1019      Atree.Lock;
1020
1021      --  Validate unchecked conversions (using the values for size and
1022      --  alignment annotated by the backend where possible).
1023
1024      Sem_Ch13.Validate_Unchecked_Conversions;
1025
1026      --  Validate address clauses (again using alignment values annotated
1027      --  by the backend where possible).
1028
1029      Sem_Ch13.Validate_Address_Clauses;
1030   end Post_Compilation_Validation_Checks;
1031
1032   -----------------------------------
1033   --  Read_JSON_Files_For_Repinfo  --
1034   -----------------------------------
1035
1036   procedure Read_JSON_Files_For_Repinfo is
1037   begin
1038      --  This is the same loop construct as in Repinfo.List_Rep_Info
1039
1040      for U in Main_Unit .. Last_Unit loop
1041         if In_Extended_Main_Source_Unit (Cunit_Entity (U)) then
1042            declare
1043               Nam   : constant String :=
1044                         Get_Name_String
1045                           (File_Name (Source_Index (U))) & ".json";
1046               Namid : constant File_Name_Type    := Name_Enter (Nam);
1047               Index : constant Source_File_Index := Load_Config_File (Namid);
1048
1049            begin
1050               if Index = No_Source_File then
1051                  Write_Str ("cannot locate ");
1052                  Write_Line (Nam);
1053                  raise Unrecoverable_Error;
1054               end if;
1055
1056               Repinfo.Input.Read_JSON_Stream (Source_Text (Index).all, Nam);
1057            exception
1058               when Repinfo.Input.Invalid_JSON_Stream =>
1059                  raise Unrecoverable_Error;
1060            end;
1061         end if;
1062      end loop;
1063   end Read_JSON_Files_For_Repinfo;
1064
1065   --  Local variables
1066
1067   Back_End_Mode : Back_End.Back_End_Mode_Type;
1068   Ecode         : Exit_Code_Type;
1069
1070   Main_Unit_Kind : Node_Kind;
1071   --  Kind of main compilation unit node
1072
1073   Main_Unit_Node : Node_Id;
1074   --  Compilation unit node for main unit
1075
1076--  Start of processing for Gnat1drv
1077
1078begin
1079   --  This inner block is set up to catch assertion errors and constraint
1080   --  errors. Since the code for handling these errors can cause another
1081   --  exception to be raised (namely Unrecoverable_Error), we need two
1082   --  nested blocks, so that the outer one handles unrecoverable error.
1083
1084   begin
1085      --  Initialize all packages. For the most part, these initialization
1086      --  calls can be made in any order. Exceptions are as follows:
1087
1088      --  Lib.Initialize needs to be called before Scan_Compiler_Arguments,
1089      --  because it initializes a table filled by Scan_Compiler_Arguments.
1090
1091      Osint.Initialize;
1092      Fmap.Reset_Tables;
1093      Lib.Initialize;
1094      Lib.Xref.Initialize;
1095      Scan_Compiler_Arguments;
1096      Osint.Add_Default_Search_Dirs;
1097      Atree.Initialize;
1098      Nlists.Initialize;
1099      Sinput.Initialize;
1100      Sem.Initialize;
1101      Exp_CG.Initialize;
1102      Csets.Initialize;
1103      Uintp.Initialize;
1104      Urealp.Initialize;
1105      Errout.Initialize;
1106      SCOs.Initialize;
1107      Snames.Initialize;
1108      Stringt.Initialize;
1109      Ghost.Initialize;
1110      Inline.Initialize;
1111      Par_SCO.Initialize;
1112      Sem_Ch8.Initialize;
1113      Sem_Ch12.Initialize;
1114      Sem_Ch13.Initialize;
1115      Sem_Elim.Initialize;
1116      Sem_Eval.Initialize;
1117      Sem_Type.Init_Interp_Tables;
1118
1119      --  Capture compilation date and time
1120
1121      Opt.Compilation_Time := System.OS_Lib.Current_Time_String;
1122
1123      --  Get the target parameters only when -gnats is not used, to avoid
1124      --  failing when there is no default runtime.
1125
1126      if Operating_Mode /= Check_Syntax then
1127
1128         --  Acquire target parameters from system.ads (package System source)
1129
1130         Targparm_Acquire : declare
1131
1132            S : Source_File_Index;
1133            N : File_Name_Type;
1134
1135         begin
1136            Name_Buffer (1 .. 10) := "system.ads";
1137            Name_Len := 10;
1138            N := Name_Find;
1139            S := Load_Source_File (N);
1140
1141            --  Failed to read system.ads, fatal error
1142
1143            if S = No_Source_File then
1144               Write_Line
1145                 ("fatal error, run-time library not installed correctly");
1146               Write_Line ("cannot locate file system.ads");
1147               raise Unrecoverable_Error;
1148
1149            elsif S = No_Access_To_Source_File then
1150               Write_Line
1151                 ("fatal error, run-time library not installed correctly");
1152               Write_Line ("no read access for file system.ads");
1153               raise Unrecoverable_Error;
1154
1155            --  Read system.ads successfully, remember its source index
1156
1157            else
1158               System_Source_File_Index := S;
1159            end if;
1160
1161            --  Call to get target parameters. Note that the actual interface
1162            --  routines are in Tbuild. They can't be in this procedure because
1163            --  of accessibility issues.
1164
1165            Targparm.Get_Target_Parameters
1166              (System_Text  => Source_Text  (S),
1167               Source_First => Source_First (S),
1168               Source_Last  => Source_Last  (S),
1169               Make_Id      => Tbuild.Make_Id'Access,
1170               Make_SC      => Tbuild.Make_SC'Access,
1171               Set_NOD      => Tbuild.Set_NOD'Access,
1172               Set_NSA      => Tbuild.Set_NSA'Access,
1173               Set_NUA      => Tbuild.Set_NUA'Access,
1174               Set_NUP      => Tbuild.Set_NUP'Access);
1175
1176            --  Acquire configuration pragma information from Targparm
1177
1178            Restrict.Restrictions := Targparm.Restrictions_On_Target;
1179         end Targparm_Acquire;
1180      end if;
1181
1182      --  Perform various adjustments and settings of global switches
1183
1184      Adjust_Global_Switches;
1185
1186      --  Output copyright notice if full list mode unless we have a list
1187      --  file, in which case we defer this so that it is output in the file.
1188
1189      if (Verbose_Mode or else (Full_List and then Full_List_File_Name = null))
1190
1191        --  Debug flag gnatd7 suppresses this copyright notice
1192
1193        and then not Debug_Flag_7
1194      then
1195         Write_Eol;
1196         Write_Str ("GNAT ");
1197         Write_Str (Gnat_Version_String);
1198         Write_Eol;
1199         Write_Str ("Copyright 1992-" & Current_Year
1200                    & ", Free Software Foundation, Inc.");
1201         Write_Eol;
1202      end if;
1203
1204      --  Check we do not have more than one source file, this happens only in
1205      --  the case where the driver is called directly, it cannot happen when
1206      --  gnat1 is invoked from gcc in the normal case.
1207
1208      if Osint.Number_Of_Files /= 1 then
1209
1210         --  In GNATprove mode, gcc is not called, so we may end up with
1211         --  switches wrongly interpreted as source file names when they are
1212         --  written by mistake without a starting hyphen. Issue a specific
1213         --  error message but do not print the internal 'usage' message.
1214
1215         if GNATprove_Mode then
1216            Write_Str
1217              ("one of the following is not a valid switch or source file "
1218               & "name: ");
1219            Osint.Dump_Command_Line_Source_File_Names;
1220         else
1221            Usage;
1222            Write_Eol;
1223         end if;
1224
1225         Osint.Fail ("you must provide one source file");
1226
1227      elsif Usage_Requested then
1228         Usage;
1229      end if;
1230
1231      --  Generate target dependent output file if requested
1232
1233      if Target_Dependent_Info_Write_Name /= null then
1234         Set_Targ.Write_Target_Dependent_Values;
1235      end if;
1236
1237      --  Call the front end
1238
1239      Original_Operating_Mode := Operating_Mode;
1240      Frontend;
1241
1242      --  Exit with errors if the main source could not be parsed
1243
1244      if Sinput.Main_Source_File <= No_Source_File then
1245         Errout.Finalize (Last_Call => True);
1246         Errout.Output_Messages;
1247         Exit_Program (E_Errors);
1248      end if;
1249
1250      Main_Unit_Node := Cunit (Main_Unit);
1251      Main_Unit_Kind := Nkind (Unit (Main_Unit_Node));
1252
1253      Check_Bad_Body (Main_Unit_Node, Main_Unit_Kind);
1254
1255      --  In CodePeer mode we always delete old SCIL files before regenerating
1256      --  new ones, in case of e.g. errors, and also to remove obsolete scilx
1257      --  files generated by CodePeer itself.
1258
1259      if CodePeer_Mode then
1260         Comperr.Delete_SCIL_Files;
1261      end if;
1262
1263      --  Ditto for old C files before regenerating new ones
1264
1265      if Generate_C_Code then
1266         Delete_C_File;
1267         Delete_H_File;
1268      end if;
1269
1270      --  Exit if compilation errors detected
1271
1272      Errout.Finalize (Last_Call => False);
1273
1274      if Compilation_Errors then
1275         Treepr.Tree_Dump;
1276         Post_Compilation_Validation_Checks;
1277         Errout.Finalize (Last_Call => True);
1278         Errout.Output_Messages;
1279         Namet.Finalize;
1280
1281         --  Generate ALI file if specially requested
1282
1283         if Opt.Force_ALI_File then
1284            Write_ALI (Object => False);
1285         end if;
1286
1287         Exit_Program (E_Errors);
1288      end if;
1289
1290      --  Case of no code required to be generated, exit indicating no error
1291
1292      if Original_Operating_Mode = Check_Syntax then
1293         Treepr.Tree_Dump;
1294         Errout.Finalize (Last_Call => True);
1295         Errout.Output_Messages;
1296         Namet.Finalize;
1297         Check_Rep_Info;
1298
1299         --  Use a goto instead of calling Exit_Program so that finalization
1300         --  occurs normally.
1301
1302         goto End_Of_Program;
1303
1304      elsif Original_Operating_Mode = Check_Semantics then
1305         Back_End_Mode := Declarations_Only;
1306
1307      --  All remaining cases are cases in which the user requested that code
1308      --  be generated (i.e. no -gnatc or -gnats switch was used). Check if we
1309      --  can in fact satisfy this request.
1310
1311      --  Cannot generate code if someone has turned off code generation for
1312      --  any reason at all. We will try to figure out a reason below.
1313
1314      elsif Operating_Mode /= Generate_Code then
1315         Back_End_Mode := Skip;
1316
1317      --  We can generate code for a subprogram body unless there were missing
1318      --  subunits. Note that we always generate code for all generic units (a
1319      --  change from some previous versions of GNAT).
1320
1321      elsif Main_Unit_Kind = N_Subprogram_Body
1322        and then not Subunits_Missing
1323      then
1324         Back_End_Mode := Generate_Object;
1325
1326      --  We can generate code for a package body unless there are subunits
1327      --  missing (note that we always generate code for generic units, which
1328      --  is a change from some earlier versions of GNAT).
1329
1330      elsif Main_Unit_Kind = N_Package_Body and then not Subunits_Missing then
1331         Back_End_Mode := Generate_Object;
1332
1333      --  We can generate code for a package declaration or a subprogram
1334      --  declaration only if it does not required a body.
1335
1336      elsif Main_Unit_Kind in N_Package_Declaration | N_Subprogram_Declaration
1337        and then
1338          (not Body_Required (Main_Unit_Node)
1339             or else Distribution_Stub_Mode = Generate_Caller_Stub_Body)
1340      then
1341         Back_End_Mode := Generate_Object;
1342
1343      --  We can generate code for a generic package declaration of a generic
1344      --  subprogram declaration only if does not require a body.
1345
1346      elsif Main_Unit_Kind in
1347              N_Generic_Package_Declaration | N_Generic_Subprogram_Declaration
1348        and then not Body_Required (Main_Unit_Node)
1349      then
1350         Back_End_Mode := Generate_Object;
1351
1352      --  Compilation units that are renamings do not require bodies, so we can
1353      --  generate code for them.
1354
1355      elsif Main_Unit_Kind in N_Package_Renaming_Declaration |
1356                              N_Subprogram_Renaming_Declaration
1357      then
1358         Back_End_Mode := Generate_Object;
1359
1360      --  Compilation units that are generic renamings do not require bodies
1361      --  so we can generate code for them.
1362
1363      elsif Main_Unit_Kind in N_Generic_Renaming_Declaration then
1364         Back_End_Mode := Generate_Object;
1365
1366      --  It is not an error to analyze in CodePeer mode a spec which requires
1367      --  a body, in order to generate SCIL for this spec.
1368
1369      elsif CodePeer_Mode then
1370         Back_End_Mode := Generate_Object;
1371
1372      --  Differentiate use of -gnatceg to generate a C header from an Ada spec
1373      --  to the CCG case (standard.h found) where C code generation should
1374      --  only be performed on full units.
1375
1376      elsif Generate_C_Code then
1377         Name_Len := 10;
1378         Name_Buffer (1 .. Name_Len) := "standard.h";
1379
1380         if Find_File (Name_Find, Osint.Source, Full_Name => True) = No_File
1381         then
1382            Back_End_Mode := Generate_Object;
1383         else
1384            Back_End_Mode := Skip;
1385         end if;
1386
1387      --  It is not an error to analyze in GNATprove mode a spec which requires
1388      --  a body, when the body is not available. During frame condition
1389      --  generation, the corresponding ALI file is generated. During
1390      --  analysis, the spec is analyzed.
1391
1392      elsif GNATprove_Mode then
1393         Back_End_Mode := Declarations_Only;
1394
1395      --  In all other cases (specs which have bodies, generics, and bodies
1396      --  where subunits are missing), we cannot generate code and we generate
1397      --  a warning message. Note that generic instantiations are gone at this
1398      --  stage since they have been replaced by their instances.
1399
1400      else
1401         Back_End_Mode := Skip;
1402      end if;
1403
1404      --  At this stage Back_End_Mode is set to indicate if the backend should
1405      --  be called to generate code. If it is Skip, then code generation has
1406      --  been turned off, even though code was requested by the original
1407      --  command. This is not an error from the user point of view, but it is
1408      --  an error from the point of view of the gcc driver, so we must exit
1409      --  with an error status.
1410
1411      --  We generate an informative message (from the gcc point of view, it
1412      --  is an error message, but from the users point of view this is not an
1413      --  error, just a consequence of compiling something that cannot
1414      --  generate code).
1415
1416      if Back_End_Mode = Skip then
1417
1418         --  An ignored Ghost unit is rewritten into a null statement. Do
1419         --  not emit any errors related to code generation because the
1420         --  unit does not exist.
1421
1422         if Is_Ignored_Ghost_Unit (Main_Unit_Node) then
1423
1424            --  Exit the gnat driver with success, otherwise external builders
1425            --  such as gnatmake and gprbuild will treat the compilation of an
1426            --  ignored Ghost unit as a failure. Be sure we produce an empty
1427            --  object file for the unit.
1428
1429            Ecode := E_Success;
1430            Back_End.Gen_Or_Update_Object_File;
1431
1432         --  Otherwise the unit is missing a crucial piece that prevents code
1433         --  generation.
1434
1435         else
1436            Ecode := E_No_Code;
1437
1438            Set_Standard_Error;
1439            Write_Str ("cannot generate code for file ");
1440            Write_Name (Unit_File_Name (Main_Unit));
1441
1442            if Subunits_Missing then
1443               Write_Str (" (missing subunits)");
1444               Write_Eol;
1445
1446               --  Force generation of ALI file, for backward compatibility
1447
1448               Opt.Force_ALI_File := True;
1449
1450            elsif Main_Unit_Kind = N_Subunit then
1451               Write_Str (" (subunit)");
1452               Write_Eol;
1453
1454               --  Do not generate an ALI file in this case, because it would
1455               --  become obsolete when the parent is compiled, and thus
1456               --  confuse tools such as gnatfind.
1457
1458            elsif Main_Unit_Kind = N_Subprogram_Declaration then
1459               Write_Str (" (subprogram spec)");
1460               Write_Eol;
1461
1462            --  Generic package body in GNAT implementation mode
1463
1464            elsif Main_Unit_Kind = N_Package_Body and then GNAT_Mode then
1465               Write_Str (" (predefined generic)");
1466               Write_Eol;
1467
1468               --  Force generation of ALI file, for backward compatibility
1469
1470               Opt.Force_ALI_File := True;
1471
1472            --  Only other case is a package spec
1473
1474            else
1475               Write_Str (" (package spec)");
1476               Write_Eol;
1477            end if;
1478         end if;
1479
1480         Set_Standard_Output;
1481
1482         Post_Compilation_Validation_Checks;
1483         Errout.Finalize (Last_Call => True);
1484         Errout.Output_Messages;
1485         Treepr.Tree_Dump;
1486
1487         --  Generate ALI file if specially requested, or for missing subunits,
1488         --  subunits or predefined generic. For ignored ghost code, the object
1489         --  file IS generated, so Object should be True, and since the object
1490         --  file is generated, we need to generate the ALI file. We never want
1491         --  an object file without an ALI file.
1492
1493         if Is_Ignored_Ghost_Unit (Main_Unit_Node)
1494           or else Opt.Force_ALI_File
1495         then
1496            Write_ALI (Object => Is_Ignored_Ghost_Unit (Main_Unit_Node));
1497         end if;
1498
1499         Namet.Finalize;
1500         Check_Rep_Info;
1501
1502         --  Exit the driver with an appropriate status indicator. This will
1503         --  generate an empty object file for ignored Ghost units, otherwise
1504         --  no object file will be generated.
1505
1506         Exit_Program (Ecode);
1507      end if;
1508
1509      --  In -gnatc mode we only do annotation if -gnatR is also set, or if
1510      --  -gnatwz is enabled (default setting) and there is an unchecked
1511      --  conversion that involves a type whose size is not statically known,
1512      --  as indicated by Back_Annotate_Rep_Info being set to True.
1513
1514      --  We don't call for annotations on a subunit, because to process those
1515      --  the back end requires that the parent(s) be properly compiled.
1516
1517      --  Annotation is suppressed for targets where front-end layout is
1518      --  enabled, because the front end determines representations.
1519
1520      --  A special back end is always called in CodePeer and GNATprove modes,
1521      --  unless this is a subunit.
1522
1523      if Back_End_Mode = Declarations_Only
1524        and then
1525          (not (Back_Annotate_Rep_Info or Generate_SCIL or GNATprove_Mode)
1526            or else Main_Unit_Kind = N_Subunit)
1527      then
1528         Post_Compilation_Validation_Checks;
1529         Errout.Finalize (Last_Call => True);
1530         Errout.Output_Messages;
1531         Write_ALI (Object => False);
1532         Tree_Dump;
1533         Namet.Finalize;
1534
1535         if not (Generate_SCIL or GNATprove_Mode) then
1536            Check_Rep_Info;
1537         end if;
1538
1539         return;
1540      end if;
1541
1542      --  Ensure that we properly register a dependency on system.ads, since
1543      --  even if we do not semantically depend on this, Targparm has read
1544      --  system parameters from the system.ads file.
1545
1546      Lib.Writ.Ensure_System_Dependency;
1547
1548      --  Add dependencies, if any, on preprocessing data file and on
1549      --  preprocessing definition file(s).
1550
1551      Prepcomp.Add_Dependencies;
1552
1553      if GNATprove_Mode then
1554
1555         --  In GNATprove mode we're writing the ALI much earlier than usual
1556         --  as flow analysis needs the file present in order to append its
1557         --  own globals to it.
1558
1559         --  Note: In GNATprove mode, an "object" file is always generated as
1560         --  the result of calling gnat1 or gnat2why, although this is not the
1561         --  same as the object file produced for compilation.
1562
1563         Write_ALI (Object => True);
1564      end if;
1565
1566      --  Some back ends (for instance Gigi) are known to rely on SCOs for code
1567      --  generation. Make sure they are available.
1568
1569      if Generate_SCO then
1570         Par_SCO.SCO_Record_Filtered;
1571      end if;
1572
1573      --  If -gnatd_j is specified, exercise the JSON parser of Repinfo
1574
1575      if Debug_Flag_Underscore_J then
1576         Read_JSON_Files_For_Repinfo;
1577      end if;
1578
1579      --  Back end needs to explicitly unlock tables it needs to touch
1580
1581      Atree.Lock;
1582      Elists.Lock;
1583      Fname.UF.Lock;
1584      Ghost.Lock;
1585      Inline.Lock;
1586      Lib.Lock;
1587      Namet.Lock;
1588      Nlists.Lock;
1589      Sem.Lock;
1590      Sinput.Lock;
1591      Stringt.Lock;
1592
1593      --  Here we call the back end to generate the output code
1594
1595      Generating_Code := True;
1596      Back_End.Call_Back_End (Back_End_Mode);
1597
1598      --  Once the backend is complete, we unlock the names table. This call
1599      --  allows a few extra entries, needed for example for the file name
1600      --  for the library file output.
1601
1602      Namet.Unlock;
1603
1604      --  Generate the call-graph output of dispatching calls
1605
1606      Exp_CG.Generate_CG_Output;
1607
1608      --  Perform post compilation validation checks
1609
1610      Post_Compilation_Validation_Checks;
1611
1612      --  Now we complete output of errors, rep info and the tree info. These
1613      --  are delayed till now, since it is perfectly possible for gigi to
1614      --  generate errors, modify the tree (in particular by setting flags
1615      --  indicating that elaboration is required, and also to back annotate
1616      --  representation information for List_Rep_Info).
1617
1618      Errout.Finalize (Last_Call => True);
1619      Errout.Output_Messages;
1620
1621      --  Back annotation of representation info is not done in CodePeer and
1622      --  SPARK modes.
1623
1624      if not (Generate_SCIL or GNATprove_Mode) then
1625         Repinfo.List_Rep_Info (Ttypes.Bytes_Big_Endian);
1626      end if;
1627
1628      Inline.List_Inlining_Info;
1629
1630      --  Only write the library if the backend did not generate any error
1631      --  messages. Otherwise signal errors to the driver program so that
1632      --  there will be no attempt to generate an object file.
1633
1634      if Compilation_Errors then
1635         Treepr.Tree_Dump;
1636         Exit_Program (E_Errors);
1637      end if;
1638
1639      if not GNATprove_Mode then
1640         Write_ALI (Object => (Back_End_Mode = Generate_Object));
1641      end if;
1642
1643      if not Compilation_Errors then
1644
1645         --  In case of ada backends, we need to make sure that the generated
1646         --  object file has a timestamp greater than the ALI file. We do this
1647         --  to make gnatmake happy when checking the ALI and obj timestamps,
1648         --  where it expects the object file being written after the ali file.
1649
1650         --  Gnatmake's assumption is true for gcc platforms where the gcc
1651         --  wrapper needs to call the assembler after calling gnat1, but is
1652         --  not true for ada backends, where the object files are created
1653         --  directly by gnat1 (so are created before the ali file).
1654
1655         Back_End.Gen_Or_Update_Object_File;
1656      end if;
1657
1658      --  Generate tree after writing the ALI file, since Write_ALI may in
1659      --  fact result in further tree decoration from the original tree file.
1660      --  Note that we dump the tree just before generating it, so that the
1661      --  dump will exactly reflect what is written out.
1662
1663      Treepr.Tree_Dump;
1664
1665      --  Finalize name table and we are all done
1666
1667      Namet.Finalize;
1668
1669   exception
1670      --  Handle fatal internal compiler errors
1671
1672      when Rtsfind.RE_Not_Available =>
1673         Comperr.Compiler_Abort ("RE_Not_Available");
1674
1675      when System.Assertions.Assert_Failure =>
1676         Comperr.Compiler_Abort ("Assert_Failure");
1677
1678      when Constraint_Error =>
1679         Comperr.Compiler_Abort ("Constraint_Error");
1680
1681      when Program_Error =>
1682         Comperr.Compiler_Abort ("Program_Error");
1683
1684      --  Assume this is a bug. If it is real, the message will in any case
1685      --  say Storage_Error, giving a strong hint.
1686
1687      when Storage_Error =>
1688         Comperr.Compiler_Abort ("Storage_Error");
1689
1690      when Unrecoverable_Error =>
1691         raise;
1692
1693      when others =>
1694         Comperr.Compiler_Abort ("exception");
1695   end;
1696
1697   <<End_Of_Program>>
1698
1699   if Debug_Flag_Dot_AA then
1700      Atree.Print_Statistics;
1701   end if;
1702
1703--  The outer exception handler handles an unrecoverable error
1704
1705exception
1706   when Unrecoverable_Error =>
1707      Errout.Finalize (Last_Call => True);
1708      Errout.Output_Messages;
1709
1710      Set_Standard_Error;
1711      Write_Str ("compilation abandoned");
1712      Write_Eol;
1713
1714      Set_Standard_Output;
1715      Source_Dump;
1716      Tree_Dump;
1717      Exit_Program (E_Errors);
1718
1719end Gnat1drv;
1720