[project @ 1996-01-18 16:33:17 by partain]
[ghc-hetmet.git] / ghc / driver / ghc.lprl
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 % *** MSUB does some substitutions here ***
5 % *** grep for $( ***
6 %
7
8 This is the driver script for the Glasgow Haskell compilation system.
9 It is written in \tr{perl}.  The first section includes a long
10 ``usage'' message that describes how the driver is supposed to work.
11
12 %************************************************************************
13 %*                                                                      *
14 \section[Driver-usage]{Usage message}
15 %*                                                                      *
16 %************************************************************************
17
18 \begin{code}
19 ($Pgm = $0) =~ s|.*/||;
20 $ShortUsage  =  "\nUsage: For basic information, try the `-help' option.\n";
21 $LongUsage = "\n" . <<EOUSAGE;
22 Use of the Glorious Haskell Compilation System driver:
23
24     $Pgm [command-line-options-and-input-files]
25
26 ------------------------------------------------------------------------
27 This driver ($Pgm) guides each input file through (some of the)
28 possible phases of a compilation:
29
30     - unlit:    extract code from a "literate program"
31     - hscpp:    run code through the C pre-processor (if -cpp flag given)
32     - hsc:      run the Haskell compiler proper
33     - gcc:      run the C compiler (if compiling via C)
34     - as:       run the Unix assembler
35     - ld:       run the Unix linker
36
37 For each input file, the phase to START with is determined by the
38 file's suffix:
39     - .lhs      literate Haskell: lit2pgm
40     - .hs       illiterate Haskell: hsp
41     - .hc       C from the Haskell compiler: gcc
42     - .c        C not from the Haskell compiler: gcc
43     - .s        assembly language: as
44     - other     passed directly to the linker: ld
45
46 If no files are given on the command line, input is taken from
47 standard input, and processing is as for an .hs file.  (All output is
48 to stdout or stderr, however).
49
50 The phase at which to STOP processing is determined by a command-line
51 option:
52     -C          stop after generating C (.hc output)
53     -E          stop after generating preprocessed C (.i output)
54     -S          stop after generating assembler (.s output)
55     -c          stop after generating object files (.o output)
56
57 Other commonly-used options are:
58
59     -O          An `optimising' package of options, to produce faster code
60
61     -prof       Compile for cost-centre profiling
62                 (add -auto for automagic cost-centres on top-level functions)
63
64     -fglasgow-exts  Allow Glasgow extensions (unboxed types, etc.)
65
66     -H14m       Increase compiler's heap size
67
68 The User's Guide has more information about GHC's *many* options.
69
70 Given the above, here are some TYPICAL invocations of $Pgm:
71
72     # compile a Haskell module to a .o file, optimising:
73     % $Pgm -c -O Foo.hs
74     # compile a Haskell module to C (a .hc file), using a bigger heap:
75     % $Pgm -C -H16m Foo.hs
76     # compile Haskell-produced C (.hc) to assembly language:
77     % $Pgm -S Foo.hc
78     # link three .o files into an executable called "test":
79     % $Pgm -o test Foo.o Bar.o Baz.o
80 ------------------------------------------------------------------------
81 EOUSAGE
82 \end{code}
83
84 %************************************************************************
85 %*                                                                      *
86 \section[Driver-init]{Initialisation}
87 %*                                                                      *
88 %************************************************************************
89
90 Establish what executables to run for the various phases (all the
91 \tr{$(FOO)} make-variables are \tr{msub}bed for from the
92 \tr{Makefile}), what the default options are for those phases, and
93 other similar boring stuff.
94 \begin{code}
95 select(STDERR); $| = 1; select(STDOUT); # no STDERR buffering, please.
96
97 $HostPlatform   = '$(HOSTPLATFORM)';
98 $TargetPlatform = '$(TARGETPLATFORM)';
99
100 #------------------------------------------------------------------------
101 # If you are adjusting paths by hand for a binary GHC distribution,
102 # de-commenting the line to set GLASGOW_HASKELL_ROOT should do.
103 # Or you can leave it as is, and set the environment variable externally.
104 #------------------------------------------------------------------------
105 # $ENV{'GLASGOW_HASKELL_ROOT'} = '/some/absolute/path/name';
106
107 if (! $ENV{'GLASGOW_HASKELL_ROOT'}) { # good -- death to environment variables
108     $TopPwd         = '$(TOP_PWD)';
109     $InstLibDirGhc  = '$(INSTLIBDIR_GHC)';
110     $InstDataDirGhc = '$(INSTDATADIR_GHC)';
111 } else {
112     $TopPwd = $ENV{'GLASGOW_HASKELL_ROOT'};
113
114     if ( '$(INSTLIBDIR_GHC)' =~ /^\/(local\/fp|usr\/local)(\/.*)/ ) {
115         $InstLibDirGhc  = $ENV{'GLASGOW_HASKELL_ROOT'} . $2;
116     } else {
117         print STDERR "GLASGOW_HASKELL_ROOT environment variable is set;\nBut can't untangle $(INSTLIBDIR_GHC).\n(Installation error)\n";
118         exit(1);
119     }
120
121     if ( '$(INSTDATADIR_GHC)' =~ /\/(local\/fp|usr\/local)(\/.*)/ ) {
122         $InstDataDirGhc = $ENV{'GLASGOW_HASKELL_ROOT'} . $2;
123     } else {
124         print STDERR "GLASGOW_HASKELL_ROOT environment variable is set;\nBut can't untangle $(INSTDATADIR_GHC).\n(Installation error)\n";
125         exit(1);
126     }
127 }
128
129 $Status  = 0; # just used for exit() status
130 $Verbose = '';
131 $CoreLint = '';
132 $Time = '';     # ToDo: mkworld-ize the timing command
133
134 # set up signal handler
135 sub quit_upon_signal { &tidy_up_and_die(1, ''); }
136 $SIG{'INT'}  = 'quit_upon_signal';
137 $SIG{'QUIT'} = 'quit_upon_signal';
138
139 # where to get "require"d .prl files at runtime (poor man's dynamic loading)
140 #   (use LIB, not DATA, because we can't be sure of arch-independence)
141 @INC = ( ( $(INSTALLING) ) ? "$InstLibDirGhc"
142                            : "$TopPwd/$(CURRENT_DIR)" );
143
144 if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
145     $Tmp_prefix = ($ENV{'TMPDIR'} . "/ghc$$");
146 } else {
147     $Tmp_prefix ="$(TMPDIR)/ghc$$";
148     $ENV{'TMPDIR'} = '$(TMPDIR)'; # set the env var as well
149 }
150
151 @Files_to_tidy = (); # files we nuke in the case of abnormal termination
152
153 $Unlit = ( $(INSTALLING) ) ? "$InstLibDirGhc/unlit"
154                              : "$TopPwd/$(CURRENT_DIR)/$(GHC_UNLIT)";
155 @Unlit_flags    = ();
156
157 $Cat     = "cat";
158
159 $HsCpp   = # but this is re-set to "cat" (after options) if -cpp not seen
160            ( $(INSTALLING) ) ? "$InstLibDirGhc/hscpp"
161                              : "$TopPwd/$(CURRENT_DIR)/$(GHC_HSCPP)";
162 @HsCpp_flags    = ();
163 $genSPECS_flag  = '';           # See ../utils/hscpp/hscpp.prl
164
165 $HsP     = ( $(INSTALLING) ) ? "$InstLibDirGhc/hsp"
166                              : "$TopPwd/$(CURRENT_DIR)/$(GHC_HSP)";
167 @HsP_flags = ();
168
169 $HsC     = ( $(INSTALLING) ) ? "$InstLibDirGhc/hsc"
170                              : "$TopPwd/$(CURRENT_DIR)/$(GHC_HSC)";
171
172 $SysMan  = ( $(INSTALLING) ) ? "$InstLibDirGhc/SysMan"
173                              : "$TopPwd/$(CURRENT_DIR)/$(GHC_SYSMAN)";
174
175 # HsC_rts_flags: if we want to talk to the LML runtime system
176 # NB: we don't use powers-of-2 sizes, because this may do
177 #   terrible things to cache behavior.
178 $Specific_heap_size = 6 * 1000 * 1000;
179 $Specific_stk_size  = 1000 * 1000;
180 $Scale_sizes_by = 1.0;
181 $RTS_style = $(GHC_RTS_STYLE);
182 @HsC_rts_flags = ();
183
184 @HsC_flags      = ();
185 @HsC_antiflags  = ();
186 \end{code}
187
188 The optimisations/etc to be done by the compiler are {\em normally}
189 expressed with a \tr{-O} (or \tr{-O2}) flag, or by its absence.
190
191 \begin{code}
192 $OptLevel = 0;      # no -O == 0; -O == 1; -O2 == 2; -Ofile == 3
193 $MinusO2ForC = 0;   # set to 1 if -O2 should be given to C compiler
194 $StolenX86Regs = 4; # **HACK*** of the very worst sort
195 \end{code}
196
197 These variables represent parts of the -O/-O2/etc ``templates,''
198 which are filled in later, using these.
199 These are the default values, which may be changed by user flags.
200 \begin{code}
201 $Oopt_UnfoldingUseThreshold     = '-fsimpl-uf-use-threshold3';
202 $Oopt_MaxSimplifierIterations   = '-fmax-simplifier-iterations4';
203 $Oopt_PedanticBottoms           = '-fpedantic-bottoms'; # ON by default
204 $Oopt_MonadEtaExpansion         = '';
205 #OLD:$Oopt_LambdaLift           = '';
206 $Oopt_AddAutoSccs               = '';
207 $Oopt_FinalStgProfilingMassage  = '';
208 $Oopt_StgStats                  = '';
209 $Oopt_SpecialiseUnboxed         = '';
210 $Oopt_DoSpecialise              = '-fspecialise';
211 $Oopt_FoldrBuild                = 1; # On by default!
212 $Oopt_FB_Support                = '-fdo-new-occur-anal -fdo-arity-expand';
213 #$Oopt_FoldrBuildWW             = 0; # Off by default
214 \end{code}
215
216 Things to do with C compilers/etc:
217 \begin{code}
218 $CcUnregd       = '$(GHC_DEBUG_HILEV_ASM)'; # our high-level assembler (non-optimising)
219 $CcRegd         = '$(GHC_OPT_HILEV_ASM)';   # our high-level assembler (optimising)
220 $GccAvailable   = $(GHC_GCC_IS_AVAILABLE);  # whether GCC avail or not for optimising
221
222 @CcBoth_flags   = ('-S');   # flags for *any* C compilation
223 @CcInjects      = ();
224
225 # non-registerizing flags: those for all files, those only for .c files; those only for .hc files
226 @CcUnregd_flags   = ( $GccAvailable ) ? ('-ansi', '-pedantic') : ();
227 @CcUnregd_flags_c = ();
228 @CcUnregd_flags_hc= ();
229
230 # ditto; but for registerizing (we must have GCC for this)
231 @CcRegd_flags    = ('-ansi', '-D__STG_GCC_REGS__', '-D__STG_TAILJUMPS__');
232 @CcRegd_flags_c = ();
233 @CcRegd_flags_hc = ();
234
235 $As             = ''; # assembler is normally the same pgm as used for C compilation
236 @As_flags       = ();
237
238 $Lnkr           = ''; # linker is normally the same pgm as used for C compilation
239 @Ld_flags       = ();
240
241 # 'nm' is used for consistency checking (ToDo: mk-world-ify)
242 # ToDo: check the OS or something ("alpha" is surely not the crucial question)
243 $Nm = ($TargetPlatform =~ /^alpha-/) ? 'nm -B' : 'nm';
244 \end{code}
245
246 What options \tr{-user-setup-a} turn into (user-defined ``packages''
247 of options).  Note that a particular user-setup implies a particular
248 Prelude ({\em including} its interface file(s)).
249 \begin{code}
250 $BuildTag       = ''; # default is sequential build w/ Appel-style GC
251
252 %BuildAvail     = ('',      '$(GHC_BUILD_FLAG_normal)',
253                    '_p',    '$(GHC_BUILD_FLAG_p)',
254                    '_t',    '$(GHC_BUILD_FLAG_t)',
255                    '_u',    '$(GHC_BUILD_FLAG_u)',
256                    '_mc',   '$(GHC_BUILD_FLAG_mc)',
257                    '_mr',   '$(GHC_BUILD_FLAG_mr)',
258                    '_mt',   '$(GHC_BUILD_FLAG_mt)',
259                    '_mp',   '$(GHC_BUILD_FLAG_mp)',
260                    '_mg',   '$(GHC_BUILD_FLAG_mg)',
261                    '_2s',   '$(GHC_BUILD_FLAG_2s)',
262                    '_1s',   '$(GHC_BUILD_FLAG_1s)',
263                    '_du',   '$(GHC_BUILD_FLAG_du)',
264                    '_a',    '$(GHC_BUILD_FLAG_a)',
265                    '_b',    '$(GHC_BUILD_FLAG_b)',
266                    '_c',    '$(GHC_BUILD_FLAG_c)',
267                    '_d',    '$(GHC_BUILD_FLAG_d)',
268                    '_e',    '$(GHC_BUILD_FLAG_e)',
269                    '_f',    '$(GHC_BUILD_FLAG_f)',
270                    '_g',    '$(GHC_BUILD_FLAG_g)',
271                    '_h',    '$(GHC_BUILD_FLAG_h)',
272                    '_i',    '$(GHC_BUILD_FLAG_i)',
273                    '_j',    '$(GHC_BUILD_FLAG_j)',
274                    '_k',    '$(GHC_BUILD_FLAG_k)',
275                    '_l',    '$(GHC_BUILD_FLAG_l)',
276                    '_m',    '$(GHC_BUILD_FLAG_m)',
277                    '_n',    '$(GHC_BUILD_FLAG_n)',
278                    '_o',    '$(GHC_BUILD_FLAG_o)',
279                    '_A',    '$(GHC_BUILD_FLAG_A)',
280                    '_B',    '$(GHC_BUILD_FLAG_B)' );
281
282 %BuildDescr     = ('',      'normal sequential',
283                    '_p',    'profiling',
284                    '_t',    'ticky-ticky profiling',
285                    '_t',    'unregisterized (using portable C only)',
286                    '_mc',   'concurrent',
287                    '_mr',   'profiled concurrent',
288                    '_mt',   'ticky concurrent',
289                    '_mp',   'parallel',
290                    '_mg',   'GranSim',
291                    '_2s',   '2-space GC',
292                    '_1s',   '1-space GC',
293                    '_du',   'dual-mode GC',
294                    '_a',    'user way a',
295                    '_b',    'user way b',
296                    '_c',    'user way c',
297                    '_d',    'user way d',
298                    '_e',    'user way e',
299                    '_f',    'user way f',
300                    '_g',    'user way g',
301                    '_h',    'user way h',
302                    '_i',    'user way i',
303                    '_j',    'user way j',
304                    '_k',    'user way k',
305                    '_l',    'user way l',
306                    '_m',    'user way m',
307                    '_n',    'user way n',
308                    '_o',    'user way o',
309                    '_A',    'user way A',
310                    '_B',    'user way B' );
311
312 # these are options that are "fed back" through the option processing loop
313 %UserSetupOpts  = ('_a', '$(GHC_BUILD_OPTS_a)',
314                    '_b', '$(GHC_BUILD_OPTS_b)',
315                    '_c', '$(GHC_BUILD_OPTS_c)',
316                    '_d', '$(GHC_BUILD_OPTS_d)',
317                    '_e', '$(GHC_BUILD_OPTS_e)',
318                    '_f', '$(GHC_BUILD_OPTS_f)',
319                    '_g', '$(GHC_BUILD_OPTS_g)',
320                    '_h', '$(GHC_BUILD_OPTS_h)',
321                    '_i', '$(GHC_BUILD_OPTS_i)',
322                    '_j', '$(GHC_BUILD_OPTS_j)',
323                    '_k', '$(GHC_BUILD_OPTS_k)',
324                    '_l', '$(GHC_BUILD_OPTS_l)',
325                    '_m', '$(GHC_BUILD_OPTS_m)',
326                    '_n', '$(GHC_BUILD_OPTS_n)',
327                    '_o', '$(GHC_BUILD_OPTS_o)',
328                    '_A', '$(GHC_BUILD_OPTS_A)',
329                    '_B', '$(GHC_BUILD_OPTS_B)',
330
331                    # the GC ones don't have any "fed back" options
332                    '_2s', '',
333                    '_1s', '',
334                    '_du', '' );
335
336 # per-build code fragments which are eval'd
337 %EvaldSetupOpts = ('',      '', # this one must *not* be set!
338
339                             # profiled sequential
340                    '_p',    'push(@HsC_flags,  \'-fscc-profiling\');
341                              push(@CcBoth_flags, \'-DPROFILING\');',
342
343                             # ticky-ticky sequential
344                    '_t',    'push(@HsC_flags, \'-fticky-ticky\');
345                              push(@CcBoth_flags, \'-DTICKY_TICKY\');',
346
347                             # unregisterized (ToDo????)
348                    '_u',    '',
349
350                             # concurrent
351                    '_mc',   '$StkChkByPageFaultOK = 0;
352                              push(@HsC_flags,  \'-fconcurrent\');
353                              push(@HsCpp_flags,\'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\');
354                              push(@Cpp_define, \'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\');',
355
356                             # profiled concurrent
357                    '_mr',   '$StkChkByPageFaultOK = 0;
358                              push(@HsC_flags,  \'-fconcurrent\', \'-fscc-profiling\');
359                              push(@HsCpp_flags,\'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\');
360                              push(@Cpp_define, \'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\', \'-DPROFILING\');',
361
362                             # ticky-ticky concurrent
363                    '_mt',   '$StkChkByPageFaultOK = 0;
364                              push(@HsC_flags,  \'-fconcurrent\', \'-fticky-ticky\');
365                              push(@HsCpp_flags,\'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\');
366                              push(@Cpp_define, \'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\', \'-DTICKY_TICKY\');',
367
368                             # parallel
369                    '_mp',   '$StkChkByPageFaultOK = 0;
370                              push(@HsC_flags,  \'-fconcurrent\');
371                              push(@HsCpp_flags,\'-D__PARALLEL_HASKELL__\',   \'-DPAR\');
372                              push(@Cpp_define, \'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\', \'-DPAR\');',
373
374                             # GranSim
375                    '_mg',   '$StkChkByPageFaultOK = 0;
376                              push(@HsC_flags,  \'-fconcurrent\');
377                              push(@Cpp_define, \'-D__CONCURRENT_HASKELL__\', \'-DCONCURRENT\', \'-DGRAN\');',
378
379                    '_2s',   'push (@CcBoth_flags, \'-DGC2s\');',
380                    '_1s',   'push (@CcBoth_flags, \'-DGC1s\');',
381                    '_du',   'push (@CcBoth_flags, \'-DGCdu\');',
382
383                    '_a',    '', # these user-way guys should not be set!
384                    '_b',    '',
385                    '_c',    '',
386                    '_d',    '',
387                    '_e',    '',
388                    '_f',    '',
389                    '_g',    '',
390                    '_h',    '',
391                    '_i',    '',
392                    '_j',    '',
393                    '_k',    '',
394                    '_l',    '',
395                    '_m',    '',
396                    '_n',    '',
397                    '_o',    '',
398                    '_A',    '',
399                    '_B',    '' );
400 \end{code}
401
402 Import/include directories (\tr{-I} options) are sufficiently weird to
403 require special handling.
404 \begin{code}
405 @Import_dir     = ('.'); #-i things
406 @Include_dir    = ('.'); #-I things; other default(s) stuck on AFTER option processing
407
408 @SysImport_dir  = ( $(INSTALLING) )
409                     ? ( "$InstDataDirGhc/imports" )
410                     : ( "$TopPwd/$(CURRENT_DIR)/$(GHC_LIBSRC)/prelude"
411                       );
412
413 $ghc_version_info = $(PROJECTVERSION) * 100;
414 $haskell1_version = 2; # i.e., Haskell 1.2
415 @Cpp_define     = ();
416
417 @UserLibrary_dir= ();   #-L things;...
418 @UserLibrary    = ();   #-l things asked for by the user
419
420 @SysLibrary_dir = ( ( $(INSTALLING) )   #-syslib things supplied by the system
421                     ? "$InstLibDirGhc"
422                     : ("$TopPwd/$(CURRENT_DIR)/$(GHC_RUNTIMESRC)",
423                        "$TopPwd/$(CURRENT_DIR)/$(GHC_RUNTIMESRC)/gmp",
424                        "$TopPwd/$(CURRENT_DIR)/$(GHC_LIBSRC)")
425                   );
426 @SysLibrary = ( '-lHS' );       # basic I/O and prelude stuff
427
428 $TopClosureFile # defaults to 1.2 one; will be mangled later
429         = ( $(INSTALLING) ) ? "$InstLibDirGhc/TopClosureXXXX.o"
430                             : "$TopPwd/$(CURRENT_DIR)/$(GHC_RUNTIMESRC)/main/TopClosureXXXX.o";
431 \end{code}
432
433 We are given a list of files with various presumably-known suffixes
434 (unknown-suffix files go straight to the linker).  For each file, we
435 begin by assuming that we'll run every phase over it.  However: (1)
436 global flags (\tr{-c}, \tr{-S}, etc.) tell us not to run any phase
437 past a certain point; and (2) the file's suffix tells us what phase to
438 start with.  Linking is weird and kept track of separately.
439
440 Here are the initial defaults applied to all files:
441 \begin{code}
442 $Do_lit2pgm = 1;
443 $Do_hscpp   = 1;        # but we run 'cat' by default (see after arg check)
444 $Cpp_flag_set = 0;      # (hack)
445 $Only_preprocess_C = 0; # pretty hackish
446 $ProduceHi  = 1;        # but beware magical value "2"! (hack)
447 $PostprocessCcOutput = 0;
448 $HiDiff_flag= 0;
449
450 # native code-gen or via C?
451 $HaveNativeCodeGen = $(GHC_WITH_NATIVE_CODEGEN);
452 $ProduceS = '';
453 if ($HaveNativeCodeGen) {
454     if ($TargetPlatform =~ /^(alpha|sparc)-/) {
455         $ProduceS = $TargetPlatform;
456     }
457 }
458 $ProduceC = ($ProduceS) ? 0 : 1;
459
460 $CollectingGCstats = 0;
461 $CollectGhcTimings = 0;
462 $RegisteriseC  = '';    # set to 'o', if using optimised C code (only if avail)
463                         #   or if generating equiv asm code
464 $DEBUGging = '';        # -DDEBUG and all that it entails (um... not really)
465 $PROFing = '';          # set to p or e if profiling
466 $PROFgroup = '';        # set to group if an explicit -Ggroup specified
467 $PROFauto = '';         # set to relevant hsc flag if -auto or -auto-all
468 $PROFcaf  = '';         # set to relevant hsc flag if -caf-all
469 #UNUSED:$PROFdict  = '';        # set to relevant hsc flag if -dict-all
470 $PROFignore_scc = '';   # set to relevant parser flag if explicit sccs ignored
471 $TICKYing = '';         # set to t if compiling for ticky-ticky profiling
472 $PARing = '';           # set to p if compiling for PAR
473 $CONCURing = '';        # set to c if compiling for CONCURRENT
474 $GRANing = '';          # set to g if compiling for GRAN
475 $StkChkByPageFaultOK = 1; # may be set to 0 (false) for some builds
476 $Specific_output_dir = '';      # set by -odir <dir>
477 $Specific_output_file = '';     # set by -o <file>; "-" for stdout
478 $Specific_hi_file = '';         # set by -ohi <file>; "-" for stdout
479 $Specific_dump_file = '';       # set by -odump <file>; "-" for stdout
480 $Using_dump_file = 0;
481 $Osuffix    = '.o';
482 $HiSuffix   = '.hi';
483 $Do_hsp     = 2;    # 1 for "old" parser; 2 for "new" parser (in hsc)
484 $Do_hsc     = 1;
485 $Do_cc      = -1;   # a MAGIC indeterminate value; will be set to 1 or 0.
486 $Do_as      = 1;
487 $Do_lnkr    = 1;
488 $Keep_hc_file_too = 0;
489 $Keep_s_file_too = 0;
490 $CompilingPrelude = 0;
491 $SplitObjFiles = 0;
492 $NoOfSplitFiles = 0;
493 $Dump_parser_output = 0;
494 $Dump_raw_asm = 0;
495 $Dump_asm_insn_counts = 0;
496 $Dump_asm_globals_info = 0;
497 $Dump_asm_splitting_info = 0;
498
499 # and the list of files
500 @Input_file = ();
501
502 # and files to be linked...
503 @Link_file  = ();
504 \end{code}
505
506 We inject consistency-checking information into \tr{.hc} files (both
507 when created by the Haskell compiler and when compiled by the C
508 compiler), so that we can check that an executable is made from
509 consistently-built pieces.  (The check is normally done just after
510 linking.)  The checking is done by introducing/munging
511 \tr{what(1)}-style strings.  Anyway, here are the relevant global
512 variables and their defaults:
513 \begin{code}
514 $LinkChk = 1;   # set to 0 if the link check should *not* be done
515
516 # major & minor version numbers; major numbers must always agree;
517 # minor disagreements yield a warning.
518 $HsC_major_version = 29;
519 $HsC_minor_version = 0;
520 $Cc_major_version  = 33;
521 $Cc_minor_version  = 0;
522
523 # options: these must always agree
524 $HsC_consist_options = '';    # we record, in this order:
525                               #     Build tag; debugging?
526 $Cc_consist_options  = '';    # we record, in this order:
527                               #     Build tag; debugging? registerised?
528 \end{code}
529
530 %************************************************************************
531 %*                                                                      *
532 \section[Driver-parse-argv]{Munge the command-line options}
533 %*                                                                      *
534 %************************************************************************
535
536 Now slurp through the arguments.
537 \begin{code}
538
539 #---------- user defined prelude ---------------------------------------
540
541 if (grep(/^-user-prelude$/, @ARGV)) {
542
543     # If ARGV contains -user-prelude we are compiling a piece of 
544     # prelude for the user, probably with additional specialise pragmas
545
546     # We strip out the -O -f and -user-prelude flags provided on
547     # the command line and add the ones used to compile the prelude
548     # ToDo: get these options from a common definition in mkworld
549
550     # We also enable any options forced through with -user-prelude-force
551
552     # Hey, Check out this grep statement ;-)  (PS)
553
554     @ARGV = grep((!/^-O/ && !/^-f/ && !/^-user-prelude$/) || s/^-user-prelude-force//,
555                  @ARGV);
556
557     unshift(@ARGV,
558         '-prelude',
559         '-O',
560         '-fshow-pragma-name-errs',
561         '-fshow-import-specs',
562         '-fomit-reexported-instances',
563         '-fglasgow-exts',
564         '-genSPECS',
565         '-DUSE_FOLDR_BUILD',
566         '-dcore-lint');
567
568     print STDERR "ghc: -user-prelude options:\n", "@ARGV", "\n";
569 }
570
571 # can't use getopt(s); what we want is too complicated
572 arg: while($_ = $ARGV[0]) {
573     shift(@ARGV);
574
575     #---------- help -------------------------------------------------------
576     if (/^-\?$/ || /^-help$/) { print $LongUsage; exit $Status; }
577
578     #---------- verbosity and such -----------------------------------------
579     /^-v$/          && do { $Verbose = '-v'; $Time = 'time'; next arg; };
580
581     #---------- what phases are to be run ----------------------------------
582     /^-cpp$/        && do { $Cpp_flag_set = 1; next arg; };
583     # change the global default:
584     # we won't run cat; we'll run the real thing
585         
586     /^-C$/          && do { $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0;
587                             $ProduceC = 1; $ProduceS = '';
588                             next arg; };
589     # stop after generating C
590         
591     /^-noC$/        && do { $ProduceC = 0; $ProduceS = ''; $ProduceHi = 0;
592                             $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0;
593                             next arg; };
594     # leave out actual C generation (debugging) [also turns off interface gen]
595
596     /^-hi$/         && do { $ProduceHi = 2; next arg; };
597     # _do_ generate an interface; usually used as: -noC -hi
598     # NB: magic value "2" for $ProduceHi (hack)
599
600     /^-nohi$/       && do { $ProduceHi = 0; next arg; };
601     # don't generate an interface (even if generating C)
602
603     /^-hi-diffs$/   && do { $HiDiff_flag = 1; next arg; };
604     # show diffs if the interface file changes
605
606     /^-E$/          && do { push(@CcBoth_flags, '-E');
607                             $Only_preprocess_C = 1;
608                             $Do_as = 0; $Do_lnkr = 0; next arg; };
609     # stop after preprocessing C
610
611     /^-S$/          && do { $Do_as = 0; $Do_lnkr = 0; next arg; };
612     # stop after generating assembler
613         
614     /^-c$/          && do { $Do_lnkr = 0; next arg; };
615     # stop after generating .o files
616         
617     /^-link-chk$/    && do { $LinkChk = 1; next arg; };
618     /^-no-link-chk$/ && do { $LinkChk = 0; next arg; };
619     # don't do consistency-checking after a link
620
621     # generate code for a different target architecture; e.g., m68k
622     # ToDo: de-Glasgow-ize & probably more...
623 # OLD:
624 #    /^-target$/ && do { $TargetPlatform = &grab_arg_arg('-target', ''); 
625 #                        if ($TargetPlatform ne $HostPlatform) {
626 #                           if ( $TargetPlatform =~ /^m68k-/ ) {
627 #                               $CcUnregd = $CcRegd = 'gcc-m68k';
628 #                           } else {
629 #                               print STDERR "$Pgm: Can't handle -target $TargetPlatform\n";
630 #                               $Status++;
631 #                           }
632 #                       }
633 #                       next arg; };
634
635     /^-unregisteri[sz]ed$/ && do { $RegisteriseC = 'no';
636                                    $ProduceC = 1; $ProduceS = ''; # via C, definitely
637                                    next arg; };
638
639     /^-tmpdir$/ && do { $Tmp_prefix = &grab_arg_arg('-tmpdir', '');
640                         $Tmp_prefix = "$Tmp_prefix/ghc$$";
641                         $ENV{'TMPDIR'} = $Tmp_prefix; # for those who use it...
642                         next arg; };
643     # use an alternate directory for temp files
644
645     #---------- redirect output --------------------------------------------
646
647     # -o <file>; applies to the last phase, whatever it is
648     # "-o -" sends it to stdout
649     # if <file> has a directory component, that dir must already exist
650
651     /^-o$/          && do { $Specific_output_file = &grab_arg_arg('-o', '');
652                             if ($Specific_output_file ne '-'
653                              && $Specific_output_file =~ /(.*)\/[^\/]*$/) {
654                                 local($dir_part) = $1;
655                                 if (! -d $dir_part) {
656                                     print STDERR "$Pgm: no such directory: $dir_part\n";
657                                     $Status++;
658                                 }
659                             }
660                             next arg; };
661
662     # -ohi <file>; send the interface to <file>; "-ohi -" to send to stdout
663     /^-ohi$/        && do { $Specific_hi_file = &grab_arg_arg('-ohi', '');
664                             if ($Specific_hi_file ne '-'
665                              && $Specific_hi_file =~ /(.*)\/[^\/]*$/) {
666                                 local($dir_part) = $1;
667                                 if (! -d $dir_part) {
668                                     print STDERR "$Pgm: no such directory: $dir_part\n";
669                                     $Status++;
670                                 }
671                             }
672                             next arg; };
673
674     /^-odump$/      && do { $Specific_dump_file = &grab_arg_arg('-odump', '');
675                             if ($Specific_dump_file =~ /(.*)\/[^\/]*$/) {
676                                 local($dir_part) = $1;
677                                 if (! -d $dir_part) {
678                                     print STDERR "$Pgm: no such directory: $dir_part\n";
679                                     $Status++;
680                                 }
681                             }
682                             next arg; };
683
684     /^-odir$/       && do { $Specific_output_dir = &grab_arg_arg('-odir', '');
685                             if (! -d $Specific_output_dir) {
686                                 print STDERR "$Pgm: -odir: no such directory: $Specific_output_dir\n";
687                                 $Status++;
688                             }
689                             next arg; };
690
691     /^-osuf$/       && do { $Osuffix  = &grab_arg_arg('-osuf', ''); next arg; };
692     /^-hisuf$/      && do { $HiSuffix = &grab_arg_arg('-hisuf', '');
693                             push(@HsP_flags, "-h$HiSuffix");
694                             next arg; };
695
696     /^-hisuf-prelude$/ && do { # as esoteric as they come...
697                             local($suffix) = &grab_arg_arg('-hisuf-prelude', '');
698                             push(@HsP_flags, "-g$suffix");
699                             next arg; };
700
701     #-------------- scc & Profiling Stuff ----------------------------------
702
703     /^-prof$/ && do { $PROFing = 'p'; next arg; }; # profiling -- details later!
704
705     /^-auto/ && do {
706                 # generate auto SCCs on top level bindings
707                 # -auto-all = all top level bindings
708                 # -auto     = only top level exported bindings
709                 $PROFauto = ( /-all/ )
710                             ? '-fauto-sccs-on-all-toplevs'
711                             : '-fauto-sccs-on-exported-toplevs';
712                 next arg; };
713
714     /^-caf-all/ && do { # generate individual CAF SCC annotations
715                 $PROFcaf = '-fauto-sccs-on-individual-cafs';
716                 next arg; };
717
718 # UNUSED:
719 #    /^-dict-all/ && do { # generate individual SCC annotations on dictionaries
720 #               $PROFdict = '-fauto-sccs-on-individual-dicts';
721 #               next arg; };
722
723     /^-ignore-scc$/ && do {
724                 # forces ignore of scc annotations even if profiling
725                 $PROFignore_scc = '-W';
726                 next arg; };
727
728     /^-G(.*)$/  && do { push(@HsC_flags, $_);   # set group for cost centres
729                         next arg; };
730
731     #--------- ticky/concurrent/parallel -----------------------------------
732     # we sort out the details a bit later on
733
734     /^-concurrent$/ && do { $CONCURing = 'c'; next arg; }; # concurrent Haskell
735     /^-gransim$/    && do { $GRANing   = 'g'; next arg; }; # GranSim
736     /^-ticky$/      && do { $TICKYing  = 't'; next arg; }; # ticky-ticky
737     /^-parallel$/   && do { $PARing    = 'p'; next arg; } ; # parallel Haskell
738
739     #-------------- "user ways" --------------------------------------------
740
741     (/^-user-setup-([a-oA-Z])$/
742     || /^$(GHC_BUILD_FLAG_a)$/
743     || /^$(GHC_BUILD_FLAG_b)$/
744     || /^$(GHC_BUILD_FLAG_c)$/
745     || /^$(GHC_BUILD_FLAG_d)$/
746     || /^$(GHC_BUILD_FLAG_e)$/
747     || /^$(GHC_BUILD_FLAG_f)$/
748     || /^$(GHC_BUILD_FLAG_g)$/
749     || /^$(GHC_BUILD_FLAG_h)$/
750     || /^$(GHC_BUILD_FLAG_i)$/
751     || /^$(GHC_BUILD_FLAG_j)$/
752     || /^$(GHC_BUILD_FLAG_k)$/
753     || /^$(GHC_BUILD_FLAG_l)$/
754     || /^$(GHC_BUILD_FLAG_m)$/
755     || /^$(GHC_BUILD_FLAG_n)$/
756     || /^$(GHC_BUILD_FLAG_o)$/
757     || /^$(GHC_BUILD_FLAG_A)$/
758     || /^$(GHC_BUILD_FLAG_B)$/
759
760     || /^$(GHC_BUILD_FLAG_2s)$/ # GC ones...
761     || /^$(GHC_BUILD_FLAG_1s)$/
762     || /^$(GHC_BUILD_FLAG_du)$/
763     ) && do {
764                 /^-user-setup-([a-oA-Z])$/  && do { $BuildTag = "_$1"; };
765
766                 /^$(GHC_BUILD_FLAG_a)$/  && do { $BuildTag = '_a';  };
767                 /^$(GHC_BUILD_FLAG_b)$/  && do { $BuildTag = '_b';  };
768                 /^$(GHC_BUILD_FLAG_c)$/  && do { $BuildTag = '_c';  };
769                 /^$(GHC_BUILD_FLAG_d)$/  && do { $BuildTag = '_d';  };
770                 /^$(GHC_BUILD_FLAG_e)$/  && do { $BuildTag = '_e';  };
771                 /^$(GHC_BUILD_FLAG_f)$/  && do { $BuildTag = '_f';  };
772                 /^$(GHC_BUILD_FLAG_g)$/  && do { $BuildTag = '_g';  };
773                 /^$(GHC_BUILD_FLAG_h)$/  && do { $BuildTag = '_h';  };
774                 /^$(GHC_BUILD_FLAG_i)$/  && do { $BuildTag = '_i';  };
775                 /^$(GHC_BUILD_FLAG_j)$/  && do { $BuildTag = '_j';  };
776                 /^$(GHC_BUILD_FLAG_k)$/  && do { $BuildTag = '_k';  };
777                 /^$(GHC_BUILD_FLAG_l)$/  && do { $BuildTag = '_l';  };
778                 /^$(GHC_BUILD_FLAG_m)$/  && do { $BuildTag = '_m';  };
779                 /^$(GHC_BUILD_FLAG_n)$/  && do { $BuildTag = '_n';  };
780                 /^$(GHC_BUILD_FLAG_o)$/  && do { $BuildTag = '_o';  };
781                 /^$(GHC_BUILD_FLAG_A)$/  && do { $BuildTag = '_A';  };
782                 /^$(GHC_BUILD_FLAG_B)$/  && do { $BuildTag = '_B';  };
783
784                 /^$(GHC_BUILD_FLAG_2s)$/ && do { $BuildTag = '_2s'; };
785                 /^$(GHC_BUILD_FLAG_1s)$/ && do { $BuildTag = '_1s'; };
786                 /^$(GHC_BUILD_FLAG_du)$/ && do { $BuildTag = '_du'; };
787
788                 local($stuff) = $UserSetupOpts{$BuildTag};
789                 local(@opts)  = split(/\s+/, $stuff);
790                 
791                 # feed relevant ops into the arg-processing loop (if any)
792                 unshift(@ARGV, @opts) if $#opts >= 0;
793
794                 next arg; };
795
796     #---------- set search paths for libraries and things ------------------
797
798     # we do -i just like HBC (-i clears the list; -i<colon-separated-items>
799     # prepends the items to the list); -I is for including C .h files.
800
801     /^-i$/          && do { @Import_dir = ();  # import path cleared!
802                             @SysImport_dir = ();
803                             print STDERR "WARNING: import paths cleared by `-i'\n";
804                             next arg; };
805
806     /^-i(.*)/       && do { local(@new_items)
807                               = split( /:/, &grab_arg_arg('-i', $1));
808                             unshift(@Import_dir, @new_items);
809                             next arg; };
810
811     /^-I(.*)/       && do { push(@Include_dir,     &grab_arg_arg('-I', $1)); next arg; };
812     /^-L(.*)/       && do { push(@UserLibrary_dir, &grab_arg_arg('-L', $1)); next arg; };
813     /^-l(.*)/       && do { push(@UserLibrary,'-l'.&grab_arg_arg('-l', $1)); next arg; };
814
815     /^-syslib(.*)/  && do { local($syslib) = &grab_arg_arg('-syslib',$1);
816                             print STDERR "$Pgm: no such system library (-syslib): $syslib\n",
817                               $Status++ unless $syslib =~ /^(hbc|ghc|contrib)$/;
818
819                             unshift(@SysImport_dir,
820                                 $(INSTALLING)
821                                 ? "$InstDataDirGhc/imports/$syslib"
822                                 : "$TopPwd/$(CURRENT_DIR)/$(GHC_LIBSRC)/$syslib");
823
824                             unshift(@SysLibrary, ('-lHS' . $syslib ));
825
826                             next arg; };
827
828     #=======================================================================
829     # various flags that we can harmlessly send to one program or another
830     # (we will later "reclaim" some of the compiler ones now sent to gcc)
831     #=======================================================================
832
833     #---------- this driver itself (ghc) -----------------------------------
834     # these change what executable is run for each phase:
835     /^-pgmL(.*)$/   && do { $Unlit   = $1; next arg; };
836     /^-pgmP(.*)$/   && do { $HsCpp   = $1; next arg; };
837     /^-pgmp(.*)$/   && do { $HsP     = $1; next arg; };
838     /^-pgmC(.*)$/   && do { $HsC     = $1; next arg; };
839     /^-pgmcO(.*)$/  && do { $CcRegd   = $1; next arg; };
840     /^-pgmc(.*)$/   && do { $CcUnregd  = $1; next arg; };
841     /^-pgma(.*)$/   && do { $As      = $1; next arg; };
842     /^-pgml(.*)$/   && do { $Lnkr    = $1; next arg; };
843
844     #---------- the get-anything-through opts (all pgms) -------------------
845     # these allow arbitrary option-strings to go to any phase:
846     /^-optL(.*)$/   && do { push(@Unlit_flags,   $1); next arg; };
847     /^-optP(.*)$/   && do { push(@HsCpp_flags,   $1); next arg; };
848     /^-optp(.*)$/   && do { push(@HsP_flags,     $1); next arg; };
849     /^-optCrts(.*)$/&& do { push(@HsC_rts_flags, $1); next arg; };
850     /^-optC(.*)$/   && do { push(@HsC_flags,     $1); next arg; };
851     /^-optcNhc(.*)$/ && do { push(@CcUnregd_flags_hc,$1); next arg; };
852     /^-optcNc(.*)$/  && do { push(@CcUnregd_flags_c,$1); next arg; };
853     /^-optcN(.*)$/  && do { push(@CcUnregd_flags,   $1); next arg; };
854     /^-optcOhc(.*)$/&& do { push(@CcRegd_flags_hc,$1); next arg; };
855     /^-optcOc(.*)$/ && do { push(@CcRegd_flags_c, $1); next arg; };
856     /^-optcO(.*)$/  && do { push(@CcRegd_flags,   $1); next arg; };
857     /^-optc(.*)$/   && do { push(@CcBoth_flags,  $1); next arg; };
858     /^-opta(.*)$/   && do { push(@As_flags,      $1); next arg; };
859     /^-optl(.*)$/   && do { push(@Ld_flags,      $1); next arg; };
860
861     #---------- Haskell C pre-processor (hscpp) ----------------------------
862     /^-D(.*)/       && do { push(@HsCpp_flags, "'-D".&grab_arg_arg('-D',$1)."'"); next arg; };
863     /^-U(.*)/       && do { push(@HsCpp_flags, "'-U".&grab_arg_arg('-U',$1)."'"); next arg; };
864
865     /^-genSPECS/   && do { $Cpp_flag_set = 1;
866                            $genSPECS_flag = $_;
867                             next arg; };
868
869     #---------- Haskell parser (hsp) ---------------------------------------
870     /^-ddump-parser$/ && do { $Dump_parser_output = 1; next arg; };
871
872     #---------- post-Haskell "assembler"------------------------------------
873     /^-ddump-raw-asm$/          && do { $Dump_raw_asm          = 1; next arg; };
874     /^-ddump-asm-insn-counts$/  && do { $Dump_asm_insn_counts  = 1; next arg; };
875     /^-ddump-asm-globals-info$/ && do { $Dump_asm_globals_info = 1; next arg; };
876
877     /^-ddump-asm-splitting-info$/ && do { $Dump_asm_splitting_info = 1; next arg; };
878
879     #---------- Haskell compiler (hsc) -------------------------------------
880
881 # possibly resurrect LATER
882 #   /^-fspat-profiling$/  && do { push(@HsC_flags, '-fticky-ticky');
883 #                           $ProduceS = ''; $ProduceC = 1; # must use C compiler
884 #                           push(@CcBoth_flags, '-DDO_SPAT_PROFILING');
885 #                           push(@CcBoth_flags, '-fno-schedule-insns'); # not essential
886 #                           next arg; };
887
888     /^-keep-hc-files?-too$/     && do { $Keep_hc_file_too = 1; next arg; };
889     /^-keep-s-files?-too$/      && do { $Keep_s_file_too = 1;  next arg; };
890
891     /^-fhaskell-1\.3$/          && do { $haskell1_version = 3;
892                                         push(@HsP_flags, '-3');
893                                         push(@HsC_flags, $_);
894                                         $TopClosureFile =~ s/TopClosureXXXX/TopClosure13XXXX/;
895                                         unshift(@SysImport_dir,
896                                             $(INSTALLING)
897                                             ? "$InstDataDirGhc/imports/haskell-1.3"
898                                             : "$TopPwd/$(CURRENT_DIR)/$(GHC_LIBSRC)/haskell-1.3");
899
900                                         unshift(@SysLibrary, '-lHS13');
901
902                                         next arg; };
903
904     /^-fno-implicit-prelude$/      && do { push(@HsP_flags, '-P'); next arg; };
905     /^-fignore-interface-pragmas$/ && do { push(@HsP_flags, '-p'); next arg; };
906
907     /^-prelude$/                && do { $CompilingPrelude = 1;
908                                         push(@HsC_flags, $_); next arg; };
909
910     /^-user-prelude-force/      && do { # ignore if not -user-prelude
911                                         next arg; };
912
913     /^-split-objs(.*)/  && do {
914                         local($sname) = &grab_arg_arg('-split-objs', $1);
915                         $sname =~ s/ //g; # no spaces
916
917                         if ( $TargetPlatform =~ /^(alpha|hppa1\.1|i386|m68k|mips|powerpc|sparc)-/ ) {
918                             $SplitObjFiles = 1;
919                             $ProduceS = '';
920                             $ProduceC = 1;
921
922                             push(@HsC_flags, "-fglobalise-toplev-names$sname"); 
923                             push(@CcBoth_flags, '-DUSE_SPLIT_MARKERS');
924
925                             require('ghc-split.prl')
926                              || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-split.prl!\n");
927                         } else {
928                             $SplitObjFiles = 0;
929                             print STDERR "WARNING: don't know how to split objects on this platform: $TargetPlatform\n`-split-objs' option ignored\n";
930                         }
931                         next arg; };
932
933     /^-f(hide-builtin-names|min-builtin-names)$/
934                 && do { push(@HsC_flags, $_);
935                         push(@HsP_flags, '-P'); # don't read Prelude.hi
936                         push(@HsP_flags, '-N'); # allow foo# names
937                         next arg; };
938     /^-f(glasgow-exts|hide-builtin-instances)$/
939                 && do { push(@HsC_flags, $_);
940                         push(@HsP_flags, '-N');
941
942 #                       push(@HsC_flags, '-fshow-import-specs');
943
944                         if ( ! $(INSTALLING) ) {
945                             unshift(@SysImport_dir,
946                                 "$TopPwd/$(CURRENT_DIR)/$(GHC_LIBSRC)/glaExts");
947                         }
948                         next arg; };
949
950     /^-fspeciali[sz]e-unboxed$/
951                 && do { $Oopt_DoSpecialise      = '-fspecialise';
952                         $Oopt_SpecialiseUnboxed = '-fspecialise-unboxed';
953                         next arg; };
954     /^-fspeciali[sz]e$/
955                 && do { $Oopt_DoSpecialise      = '-fspecialise';
956                         next arg; };
957     /^-fno-speciali[sz]e$/
958                 && do { $Oopt_DoSpecialise      = '';
959                         next arg; };
960
961
962 # Now the foldr/build options, which are *on* by default (for -O).
963
964     /^-fno-foldr-build$/
965                     && do { $Oopt_FoldrBuild = 0; 
966                             $Oopt_FB_Support = ''; 
967                             next arg; };
968
969     /^-fno-foldr-build-rule$/
970                     && do { $Oopt_FoldrBuild = 0; 
971                             next arg; };
972
973     /^-fno-enable-tech$/
974                     && do { $Oopt_FB_Support = ''; 
975                             next arg; };
976
977 #    /^-ffoldr-build-ww$/
978 #                   && do { $Oopt_FoldrBuildWW = 1; next arg; };
979
980
981     /^-fasm-(.*)$/  && do { $ProduceS = $1; $ProduceC = 0; # force using nativeGen
982                             push(@HsC_flags, $_); # if from the command line
983                             next arg; };
984
985     /^-fvia-C$/     && do { $ProduceS = ''; $ProduceC = 1; # force using C compiler
986                             next arg; };
987
988     /^-f(no-)?omit-frame-pointer$/ && do {
989                             unshift(@CcBoth_flags, ( $_ ));
990                             next arg; };
991
992     # ---------------
993
994     /^(-fsimpl-uf-use-threshold)(.*)$/
995                     && do { $Oopt_UnfoldingUseThreshold = $1 . &grab_arg_arg($1, $2);
996                             next arg; };
997
998     /^(-fmax-simplifier-iterations)(.*)$/
999                     && do { $Oopt_MaxSimplifierIterations = $1 . &grab_arg_arg($1, $2);
1000                             next arg; };
1001
1002     /^-fno-pedantic-bottoms$/
1003                     && do { $Oopt_PedanticBottoms = ''; next arg; };
1004
1005     /^-fdo-monad-eta-expansion$/
1006                     && do { $Oopt_MonadEtaExpansion = $_; next arg; };
1007
1008     /^-fno-let-from-(case|app|strict-let)$/ # experimental, really (WDP 95/10)
1009                     && do { push(@HsC_flags, $_); next arg; };
1010
1011     /^(-freturn-in-regs-threshold)(.*)$/
1012                     && do { local($what) = $1;
1013                             local($num)  = &grab_arg_arg($what, $2);
1014                             if ($num < 2 || $num > 8) {
1015                                 die "Bad experimental flag: $_\n";
1016                             } else {
1017                                 $ProduceS = ''; $ProduceC = 1; # force using C compiler
1018                                 push(@HsC_flags, "$what$num");
1019                                 push(@CcRegd_flags, "-D__STG_REGS_AVAIL__=$num");
1020                             }
1021                             next arg; };
1022
1023 #    /^-flambda-lift$/ # so Simon can do some testing; ToDo:rm
1024 #                   && do { $Oopt_LambdaLift = $_; next arg; };
1025
1026     # ---------------
1027
1028     /^-fno-(.*)$/   && do { push(@HsC_antiflags, "-f$1");
1029                             &squashHscFlag("-f$1");
1030                             next arg; };
1031
1032     /^-f/           && do { push(@HsC_flags, $_); next arg; };
1033
1034     # ---------------
1035
1036     /^-mlong-calls$/ && do { # for GCC for HP-PA boxes
1037                             unshift(@CcBoth_flags, ( $_ ));
1038                             next arg; };
1039
1040     /^-m(v8|sparclite|cypress|supersparc|cpu=(cypress|supersparc))$/
1041                      && do { # for GCC for SPARCs
1042                             unshift(@CcBoth_flags, ( $_ ));
1043                             next arg; };
1044
1045     /^-monly-([432])-regs/ && do { # for iX86 boxes only; no effect otherwise
1046                             $StolenX86Regs = $1;
1047                             next arg; };
1048
1049     /^-mtoggle-sp-mangling/ && do { # for iX86 boxes only; for RTS only
1050                             print STDERR "$Pgm: warning: -mtoggle-sp-mangling is no longer supported\n";
1051 #                           $SpX86Mangling = 1 - $SpX86Mangling;
1052                             next arg; };
1053
1054     #*************** ... and lots of debugging ones (form: -d* )
1055
1056     /^-darity-checks$/  && do {
1057                             push(@HsC_flags, $_);
1058                             push(@CcBoth_flags, '-D__DO_ARITY_CHKS__'); 
1059                             next arg; };
1060     /^-darity-checks-C-only$/ && do {
1061                             # so we'll have arity-checkable .hc files
1062                             # should we decide we need them later...
1063                             push(@HsC_flags, '-darity-checks');
1064                             next arg; };
1065     /^-dno-stk-checks$/ && do {
1066                             push(@HsC_flags, '-dno-stk-chks');
1067                             push(@CcBoth_flags, '-D__OMIT_STK_CHKS__'); 
1068                             next arg; };
1069
1070     # -d(no-)core-lint is done this way so it is turn-off-able.
1071     /^-dcore-lint/       && do { $CoreLint = '-dcore-lint'; next arg; };
1072     /^-dno-core-lint/    && do { $CoreLint = '';            next arg; };
1073
1074     /^-d(dump|ppr)-/         && do { push(@HsC_flags, $_); next arg; };
1075     /^-dverbose-(simpl|stg)/ && do { push(@HsC_flags, $_); next arg; };
1076     /^-dshow-passes/         && do { push(@HsC_flags, $_); next arg; };
1077     /^-dsource-stats/        && do { push(@HsC_flags, $_); next arg; };
1078     /^-dsimplifier-stats/    && do { push(@HsC_flags, $_); next arg; };
1079     /^-dstg-stats/           && do { $Oopt_StgStats = $_; next arg; };
1080
1081     #*************** ... and now all these -R* ones for its runtime system...
1082
1083     /^-Rhbc$/       && do { $RTS_style = 'hbc'; next arg; };
1084     /^-Rghc$/       && do { $RTS_style = 'ghc'; next arg; };
1085
1086     /^-Rscale-sizes?(.*)/ && do {
1087         $Scale_sizes_by = &grab_arg_arg('-Rscale-sizes', $1);
1088         next arg; };
1089
1090     /^(-H|-Rmax-heapsize)(.*)/ && do {
1091         local($heap_size) = &grab_arg_arg($1, $2);
1092         if ($heap_size =~ /(\d+)[Kk]$/) {
1093             $heap_size = $1 * 1000;
1094         } elsif ($heap_size =~ /(\d+)[Mm]$/) {
1095             $heap_size = $1 * 1000 * 1000;
1096         } elsif ($heap_size =~ /(\d+)[Gg]$/) {
1097             $heap_size = $1 * 1000 * 1000 * 1000;
1098         }
1099         if ($heap_size <= 0) {
1100             print STDERR "$Pgm: resetting heap-size to zero!!!\n";
1101             $Specific_heap_size = 0;
1102         }
1103         # if several heap sizes given, take the largest...
1104         if ($heap_size >= $Specific_heap_size) {
1105             $Specific_heap_size = $heap_size;
1106         } else {
1107             print STDERR "$Pgm: ignoring heap-size-setting option ($_)...not the largest seen\n";
1108         }
1109         next arg; };
1110
1111     /^-(K|Rmax-(stk|stack)size)(.*)/ && do {
1112         local($stk_size) = &grab_arg_arg('-Rmax-stksize', $3);
1113         if ($stk_size =~ /(\d+)[Kk]$/) {
1114             $stk_size = $1 * 1000;
1115         } elsif ($stk_size =~ /(\d+)[Mm]$/) {
1116             $stk_size = $1 * 1000 * 1000;
1117         } elsif ($stk_size =~ /(\d+)[Gg]$/) {
1118             $stk_size = $1 * 1000 * 1000 * 1000;
1119         }
1120         if ($stk_size <= 0) {
1121             print STDERR "$Pgm: resetting stack-size to zero!!!\n";
1122             $Specific_stk_size = 0;
1123         }
1124         # if several stack sizes given, take the largest...
1125         if ($stk_size >= $Specific_stk_size) {
1126             $Specific_stk_size = $stk_size;
1127         } else {
1128             print STDERR "$Pgm: ignoring stack-size-setting option (-Rmax-stksize $stk_size)...not the largest seen\n";
1129         }
1130         next arg; };
1131
1132     /^-Rgc-stats$/ && do {  $CollectingGCstats++;
1133                             # the two RTSs do this diff ways; we will try to compensate
1134                             next arg; };
1135
1136     /^-Rghc-timing/ && do { $CollectGhcTimings = 1; next arg; };
1137
1138     #---------- C high-level assembler (gcc) -------------------------------
1139 # OLD: and dangerous
1140 #    /^-g$/             && do { push(@CcBoth_flags, $_); next arg; };
1141 #    /^-(p|pg)$/                && do { push(@CcBoth_flags, $_); push(@Ld_flags, $_); next arg; };
1142 #    /^-(fpic|fPIC)$/   && do { push(@CcBoth_flags, $_); push(@As_flags, $_); next arg; };
1143
1144     /^-(Wall|ansi|pedantic)$/ && do { push(@CcBoth_flags, $_); next arg; };
1145
1146     # -dgcc-lint is a useful way of making GCC very fussy.
1147     # From alan@spri.levels.unisa.edu.au (Alan Modra).
1148     /^-dgcc-lint$/ && do { push(@CcBoth_flags, '-Wall -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs'); next arg; };
1149     # An alternate set, from mark@sgcs.com (Mark W. Snitily)
1150     # -Wall -Wstrict-prototypes -Wmissing-prototypes -Wcast-align -Wshadow
1151
1152     # inject "#include <wurble>" into the compiler's C output!
1153
1154     /^-#include(.*)/    && do {
1155         local($to_include) = &grab_arg_arg('-#include', $1);
1156         push(@CcInjects, "#include $to_include\n");
1157         next arg; };
1158
1159     #---------- Linker (gcc, really) ---------------------------------------
1160
1161     /^-static$/         && do { push(@Ld_flags, $_); next arg; };
1162
1163     #---------- mixed cc and linker magic ----------------------------------
1164     # this optimisation stuff is finally sorted out later on...
1165
1166 #    /^-O0$/    && do { # turn all optimisation *OFF*
1167 #               $OptLevel = -1;
1168 #               $ProduceS = ''; $ProduceC = 1; # force use of C compiler
1169 #               next arg; };
1170
1171     /^-O2-for-C$/ && do { $MinusO2ForC = 1; next arg; };
1172
1173     /^-O[1-2]?$/ && do {
1174                 local($opt_lev) = ( /^-O2$/ ) ? 2 : 1; # max 'em
1175                 $OptLevel = ( $opt_lev > $OptLevel ) ? $opt_lev : $OptLevel;
1176
1177                 if ( $OptLevel == 2 ) { # force use of C compiler
1178                     $ProduceS = ''; $ProduceC = 1;
1179                 }
1180                 next arg; };
1181
1182     /^-Onot$/   && do { $OptLevel = 0; next arg; }; # # set it to <no opt>
1183
1184     /^-Ofile(.*)/ && do {
1185                 $OptLevel = 3;
1186                 local($ofile) = &grab_arg_arg('-Ofile', $1);
1187                 @HsC_minusO3_flags = ();
1188
1189                 open(OFILE, "< $ofile") || die "Can't open $ofile!\n";
1190                 while (<OFILE>) {
1191                     chop;
1192                     s/\#.*//;       # death to comments
1193                     s/[ \t]+//g;    # death to whitespace
1194                     next if /^$/;   # ditto, blank lines
1195                     s/([()*{}])/\\$1/g;    # protect shell metacharacters
1196                     if ( /^C:(.*)/ ) {
1197                         push(@CcBoth_flags, $1);
1198                     } else {
1199                         push(@HsC_minusO3_flags, $_);
1200                     }
1201                 }
1202                 close(OFILE);
1203                 next arg; };
1204
1205     /^-debug$/  && do { # all this does is mark a .hc/.o as "debugging"
1206                         # in the consistency info
1207                         $DEBUGging = 'd';
1208                         next arg; };
1209
1210     #---------- linking .a file --------------------------------------------
1211
1212     /^-Main(.*)/ && do {
1213                 # specifies main or mainPrimIO to be linked
1214                 $Ld_main = $1;
1215                 next arg; }; 
1216
1217     #---------- catch unrecognized flags -----------------------------------
1218
1219     /^-./ && do {
1220         print STDERR "$Pgm: unrecognised option: $_\n";
1221         $Status++;
1222         next arg; };
1223
1224     #---------- anything else is considered an input file ------------------
1225     # (well, .o and .a files are immediately queued up as linker fodder..)
1226     if (/\.[oa]$/) {
1227         push(@Link_file, $_);
1228     } else {
1229         push(@Input_file, $_);
1230     }
1231
1232     # input files must exist:
1233     if (! -f $_) {
1234         print STDERR "$Pgm: input file doesn't exist: $_\n";
1235         $Status++;
1236     }
1237 }
1238
1239 # if there are several input files,
1240 # we don't allow \tr{-o <file>} or \tr{-ohi <file>} options...
1241 # (except if linking, of course)
1242
1243 if ($#Input_file > 0 && ( ! $Do_lnkr )) {
1244     if ( ($Specific_output_file ne '' && $Specific_output_file ne '-')
1245       || ($Specific_hi_file ne ''     && $Specific_hi_file ne '-') ) {
1246         print STDERR "$Pgm: You can't use -o or -ohi options if you have multiple input files.\n";
1247         print STDERR "\tPerhaps the -odir option will do what you want.\n";
1248         $Status++;
1249     }
1250 }
1251
1252 # check for various pathological -o and -odir combinations...
1253 if ($Specific_output_dir ne '' && $Specific_output_file ne '') {
1254     if ($Specific_output_file eq '-') {
1255         print STDERR "$Pgm: can't set output directory with -ohi AND have output to stdout\n";
1256         $Status++;
1257     } else { # amalgamate...
1258         $Specific_output_file = "$Specific_output_dir/$Specific_output_file";
1259         # ToDo: check we haven't got a junk name now...
1260         $Specific_output_dir  = ''; # reset
1261     }
1262 }
1263
1264 # PROFILING stuff after argv mangling:
1265 if ( ! $PROFing ) {
1266     # warn about any scc exprs found (in case scc used as identifier)
1267     push(@HsP_flags, '-W');
1268 } else {
1269     $Oopt_AddAutoSccs = '-fadd-auto-sccs' if $PROFauto;
1270     $Oopt_FinalStgProfilingMassage = '-fmassage-stg-for-profiling';
1271
1272     push(@HsC_flags, $PROFauto) if $PROFauto;
1273     push(@HsC_flags, $PROFcaf)  if $PROFcaf;
1274 #UNUSED:    push(@HsC_flags, $PROFdict) if $PROFdict;
1275
1276     push(@HsP_flags, (($PROFignore_scc) ? $PROFignore_scc : '-S'));
1277
1278     if ($SplitObjFiles && ! $CompilingPrelude) {
1279         # can't split with cost centres -- would need global and externs
1280         print STDERR "$Pgm: WARNING: splitting objects when profiling will *BREAK* if any _scc_s are present!\n";
1281         # (but it's fine if there aren't any _scc_s around...)
1282 #       $SplitObjFiles = 0; # unset
1283         #not an error: for now: $Status++;
1284     }
1285 }
1286
1287 # crash and burn if there were errors
1288 if ( $Status > 0 ) {
1289     print STDERR $ShortUsage;
1290     exit $Status;
1291 }
1292 \end{code}
1293
1294 %************************************************************************
1295 %*                                                                      *
1296 \section[Driver-post-argv-mangling]{Setup after reading options}
1297 %*                                                                      *
1298 %************************************************************************
1299
1300 %************************************************************************
1301 %*                                                                      *
1302 \subsection{Set up for optimisation level (\tr{-O} or whatever)}
1303 %*                                                                      *
1304 %************************************************************************
1305
1306 We come now to the default ``wads of options'' that are turned on by
1307 \tr{-O0} (do min optimisation), \tr{-O} (ordinary optimisation),
1308 \tr{-O2} (aggressive optimisation), or no O-ish flag (compile speed is
1309 more important).
1310
1311 The user can also specify his/her own list of options in a file; in
1312 that case, the work is already done (see stuff about @minusO3@,
1313 earlier...).
1314
1315 GHC allows very precise control of what happens during a compilation.
1316 Core-to-Core and STG-to-STG passes can be run in any order, as many
1317 times as you like.  Individual transformations can be turned on or
1318 disabled.
1319
1320 Sadly, however, there are some interdependencies \& Things You Must
1321 Not Do.  Here is the list.
1322
1323 CORE-TO-CORE PASSES:
1324 \begin{description}
1325 \item[\tr{-fspecialise}:]
1326 The specialiser must have dependency-analysed input; but if you run
1327 the simplifier to do this, you must not let it toss away unused
1328 bindings!  (The typechecker conveys some specialisation info via
1329 ``unused'' bindings...)
1330
1331 \item[\tr{-ffloat-inwards}:]
1332 Floating inwards should be done before strictness analysis, because
1333 the latter will give better results.
1334
1335 \item[\tr{-fstatic-args}:]
1336 The static-arguments-transformation pass {\em must} have the
1337 simplifier run right after it.
1338
1339 \item[\tr{-fcalc-inlinings[12]}:]
1340 Not required, but there may be slight gains by re-simplifying after
1341 this is done.  (You could then \tr{-fcalc-inlinings} again, just for
1342 fun.)
1343
1344 \item[\tr{-ffull-laziness}:]
1345 The (outwards-)let-floater should be the {\em last} Core-to-Core pass
1346 that's run.  (Um, well, howzabout the simplifier just once more...)
1347 \end{description}
1348
1349 STG-TO-STG PASSES:
1350 \begin{description}
1351 \item[\tr{-fupdate-analysis}:]
1352 It really really wants to be the last STG-to-STG pass that is run.
1353 \end{description}
1354
1355 \begin{code}
1356 # OLD:
1357 #@HsC_minusO0_flags
1358 #  = (  $Oopt_AddAutoSccs,
1359 #       '-fsimplify', # would rather *not* run the simplifier (ToDo)
1360 #         '\(', '\)', # nothing special at all ????
1361 #
1362 #       $Oopt_FinalStgProfilingMassage
1363 #   );
1364
1365 @HsC_minusNoO_flags
1366   = (   '-fsimplify',
1367           '\(',
1368           "$Oopt_FB_Support",
1369 #         '-falways-float-lets-from-lets',      # no idea why this was here (WDP 95/09)
1370           '-ffloat-lets-exposing-whnf',
1371           '-ffloat-primops-ok',
1372           '-fcase-of-case',
1373 #         '-fdo-lambda-eta-expansion',  # too complicated
1374           '-freuse-con',
1375 #         '-flet-to-case',      # no strictness analysis, so...
1376           "$Oopt_PedanticBottoms",
1377 #         "$Oopt_MonadEtaExpansion",    # no thanks
1378           '-fsimpl-uf-use-threshold0',
1379           '-fessential-unfoldings-only',
1380 #         "$Oopt_UnfoldingUseThreshold",        # no thanks
1381           "$Oopt_MaxSimplifierIterations",
1382           '\)',
1383         $Oopt_AddAutoSccs,
1384 #       '-ffull-laziness',      # removed 95/04 WDP following Andr\'e's lead
1385         '-fuse-get-mentioned-vars', # for the renamer
1386         
1387         $Oopt_FinalStgProfilingMassage
1388     );
1389
1390 @HsC_minusO_flags # NOTE: used for *both* -O and -O2 (some conditional bits)
1391   = (
1392         # initial simplify: mk specialiser and autoscc happy: minimum effort please
1393         '-fsimplify',
1394           '\(', 
1395           "$Oopt_FB_Support",
1396           '-fkeep-spec-pragma-ids',     # required before specialisation
1397           '-fsimpl-uf-use-threshold0',
1398           '-fessential-unfoldings-only',
1399           '-fmax-simplifier-iterations1',
1400           "$Oopt_PedanticBottoms",
1401           '\)',
1402
1403         $Oopt_AddAutoSccs,              # need some basic simplification first
1404
1405         ($Oopt_DoSpecialise) ? (
1406           '-fspecialise-overloaded',
1407           $Oopt_SpecialiseUnboxed,
1408           $Oopt_DoSpecialise,
1409         ) : (),
1410
1411         '-fsimplify',                   # need dependency anal after specialiser ...
1412           '\(',                         # need tossing before calc-inlinings ...
1413           "$Oopt_FB_Support",
1414           '-ffloat-lets-exposing-whnf',
1415           '-ffloat-primops-ok',
1416           '-fcase-of-case',
1417           '-fdo-case-elim',
1418           '-fdo-eta-reduction',
1419           '-fdo-lambda-eta-expansion',
1420           '-freuse-con',
1421           "$Oopt_PedanticBottoms",
1422           "$Oopt_MonadEtaExpansion",
1423           "$Oopt_UnfoldingUseThreshold",
1424           "$Oopt_MaxSimplifierIterations",
1425           '\)',
1426
1427         '-fcalc-inlinings1',
1428
1429 #       ($Oopt_FoldrBuildWW) ? (
1430 #               '-ffoldr-build-ww-anal',
1431 #               '-ffoldr-build-worker-wrapper',
1432 #               '-fsimplify', 
1433 #                 '\(', 
1434 #                 "$Oopt_FB_Support",
1435 #                 '-ffloat-lets-exposing-whnf',
1436 #                 '-ffloat-primops-ok',
1437 #                 '-fcase-of-case',
1438 #                 '-fdo-case-elim',
1439 #                 '-fdo-eta-reduction',
1440 #                 '-fdo-lambda-eta-expansion',
1441 #                 '-freuse-con',
1442 #                 "$Oopt_PedanticBottoms",
1443 #                 "$Oopt_MonadEtaExpansion",
1444 #                 "$Oopt_UnfoldingUseThreshold",
1445 #                 "$Oopt_MaxSimplifierIterations",
1446 #                 '\)',
1447 #        ) : (),
1448
1449         # this pass-ordering sequence was agreed by Simon and Andr\'e
1450         # (WDP 94/07, 94/11).
1451         '-ffull-laziness',
1452
1453         ($Oopt_FoldrBuild) ? (
1454           '-ffoldr-build-on',           # desugar list comprehensions for foldr/build
1455
1456           '-fsimplify', 
1457             '\(', 
1458             '-fignore-inline-pragma',   # **** NB!
1459             '-fdo-foldr-build',         # NB
1460             "$Oopt_FB_Support",
1461             '-ffloat-lets-exposing-whnf',
1462             '-ffloat-primops-ok',
1463             '-fcase-of-case',
1464             '-fdo-case-elim',
1465             '-fdo-eta-reduction',
1466             '-fdo-lambda-eta-expansion',
1467             '-freuse-con',
1468             "$Oopt_PedanticBottoms",
1469             "$Oopt_MonadEtaExpansion",
1470             "$Oopt_UnfoldingUseThreshold",
1471             "$Oopt_MaxSimplifierIterations",
1472             '\)',
1473         ) : (),
1474
1475         '-ffloat-inwards',
1476
1477         '-fsimplify',
1478           '\(', 
1479           "$Oopt_FB_Support",
1480           '-ffloat-lets-exposing-whnf',
1481           '-ffloat-primops-ok',
1482           '-fcase-of-case',
1483           '-fdo-case-elim',
1484           '-fdo-eta-reduction',
1485           '-fdo-lambda-eta-expansion',
1486           '-freuse-con',
1487           '-fdo-inline-foldr-build',    # foldr/build done so inline
1488           "$Oopt_PedanticBottoms",
1489           "$Oopt_MonadEtaExpansion",
1490           "$Oopt_UnfoldingUseThreshold",
1491           "$Oopt_MaxSimplifierIterations",
1492           '\)',
1493
1494         '-fstrictness',
1495
1496         '-fsimplify',
1497           '\(', 
1498           "$Oopt_FB_Support",
1499           '-ffloat-lets-exposing-whnf',
1500           '-ffloat-primops-ok',
1501           '-fcase-of-case',
1502           '-fdo-case-elim',
1503           '-fdo-eta-reduction',
1504           '-fdo-lambda-eta-expansion',
1505           '-freuse-con',
1506           '-flet-to-case',              # Aha! Only done after strictness analysis
1507           "$Oopt_PedanticBottoms",
1508           "$Oopt_MonadEtaExpansion",
1509           "$Oopt_UnfoldingUseThreshold",
1510           "$Oopt_MaxSimplifierIterations",
1511           '\)',
1512
1513         '-ffloat-inwards',
1514
1515 # Case-liberation for -O2.  This should be after
1516 # strictness analysis and the simplification which follows it.
1517
1518 #       ( ($OptLevel != 2)
1519 #        ? ''
1520 #       : "-fliberate-case -fsimplify \\( "$Oopt_FB_Support" -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fdo-eta-reduction -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_PedanticBottoms $Oopt_MonadEtaExpansion $Oopt_UnfoldingUseThreshold $Oopt_MaxSimplifierIterations \\)" ),
1521
1522 # Final clean-up simplification:
1523
1524         '-fsimplify',
1525           '\(', 
1526           "$Oopt_FB_Support",
1527           '-ffloat-lets-exposing-whnf',
1528           '-ffloat-primops-ok',
1529           '-fcase-of-case',
1530           '-fdo-case-elim',
1531           '-fdo-eta-reduction',
1532           '-fdo-lambda-eta-expansion',
1533           '-freuse-con',
1534           '-flet-to-case',
1535           '-fignore-inline-pragma',     # **** NB!
1536           '-fdo-inline-foldr-build',    # NB
1537           "$Oopt_PedanticBottoms",
1538           "$Oopt_MonadEtaExpansion",
1539           "$Oopt_UnfoldingUseThreshold",
1540           "$Oopt_MaxSimplifierIterations",
1541           '\)',
1542
1543       # '-fstatic-args',
1544
1545         '-fcalc-inlinings2',
1546
1547       # stg2stg passes
1548         '-fupdate-analysis',
1549         '-flambda-lift',
1550         $Oopt_FinalStgProfilingMassage,
1551         $Oopt_StgStats,
1552
1553       # flags for stg2stg
1554         '-flet-no-escape',
1555
1556       # SPECIAL FLAGS for -O2
1557         ($OptLevel == 2) ? (
1558           '-fsemi-tagging',
1559         ) : (),
1560     );
1561 \end{code}
1562
1563 Sort out what we're going to do about optimising.  First, the @hsc@
1564 flags and regular @cc@ flags to worry about:
1565 \begin{code}
1566 #if     ( $OptLevel < 0 ) {
1567
1568 #   &add_Hsc_flags( @HsC_minusO0_flags );
1569
1570 if ( $OptLevel <= 0 ) {
1571
1572     # for this level, we tell the parser -fignore-interface-pragmas
1573     push(@HsP_flags, '-p');
1574     # and tell the compiler not to produce them
1575     push(@HsC_flags, '-fomit-interface-pragmas');
1576
1577     &add_Hsc_flags( @HsC_minusNoO_flags );
1578     push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O'); # not optional!
1579
1580 } elsif ( $OptLevel == 1 || $OptLevel == 2 ) {
1581
1582     &add_Hsc_flags( @HsC_minusO_flags );
1583     push(@CcBoth_flags, ($MinusO2ForC || $OptLevel == 2) ? '-O2' : '-O'); # not optional!
1584     # -O? to GCC is not optional! -O2 probably isn't worth it generally,
1585     # but it *is* useful in compiling the garbage collectors (so said
1586     # Patrick many moons ago...).
1587
1588 } else { # -Ofile, then...
1589
1590     &add_Hsc_flags( @HsC_minusO3_flags );
1591     push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O'); # possibly to be elaborated...
1592 }
1593 \end{code}
1594
1595 %************************************************************************
1596 %*                                                                      *
1597 \subsection{Check for registerising, consistency, etc.}
1598 %*                                                                      *
1599 %************************************************************************
1600
1601 Are we capable of generating ``registerisable'' C (either using
1602 C or via equivalent native code)?
1603
1604 \begin{code}
1605 $RegisteriseC = ( $GccAvailable
1606                 && $RegisteriseC ne 'no'    # not explicitly *un*set...
1607                 && ($TargetPlatform =~ /^(alpha|hppa1\.1|i386|m68k|mips|powerpc|sparc)-/)
1608                 ) ? 'o' : '';
1609 \end{code}
1610
1611 Sort out @$BuildTag@, @$PROFing@, @$CONCURing@, @$PARing@,
1612 @$GRANing@, @$TICKYing@:
1613 \begin{code}
1614 if ( $BuildTag ne '' ) {
1615     local($b) = $BuildDescr{$BuildTag};
1616     if ($PROFing   eq 'p') { print STDERR "$Pgm: Can't mix $b with profiling.\n"; exit 1; }
1617     if ($CONCURing eq 'c') { print STDERR "$Pgm: Can't mix $b with -concurrent.\n"; exit 1; }
1618     if ($PARing    eq 'p') { print STDERR "$Pgm: Can't mix $b with -parallel.\n"; exit 1; }
1619     if ($GRANing   eq 'g') { print STDERR "$Pgm: Can't mix $b with -gransim.\n"; exit 1; }
1620     if ($TICKYing  eq 't') { print STDERR "$Pgm: Can't mix $b with -ticky.\n"; exit 1; }
1621
1622 } elsif ( $PROFing eq 'p' ) {
1623     if ($PARing   eq 'p') { print STDERR "$Pgm: Can't do profiling with -parallel.\n"; exit 1; }
1624     if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't do profiling with -gransim.\n"; exit 1; }
1625     if ($TICKYing eq 't') { print STDERR "$Pgm: Can't do profiling with -ticky.\n"; exit 1; }
1626     $BuildTag = ($CONCURing eq 'c') ? '_mr' : '_p' ; # possibly "profiled concurrent"...
1627
1628 } elsif ( $CONCURing eq 'c' ) {
1629     if ($PARing  eq 'p') { print STDERR "$Pgm: Can't mix -concurrent with -parallel.\n"; exit 1; }
1630     if ($GRANing eq 'g') { print STDERR "$Pgm: Can't mix -concurrent with -gransim.\n"; exit 1; }
1631     $BuildTag = ($TICKYing eq 't')  ? '_mt' : '_mc' ; # possibly "ticky concurrent"...
1632     # "profiled concurrent" already acct'd for...
1633
1634 } elsif ( $PARing eq 'p' ) {
1635     if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't mix -parallel with -gransim.\n"; exit 1; }
1636     if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -parallel with -ticky.\n"; exit 1; }
1637     $BuildTag = '_mp';
1638
1639     if ( $Do_lnkr && ( ! $ENV{'PVM_ROOT'} || ! $ENV{'PVM_ARCH'} )) {
1640         print STDERR "$Pgm: both your PVM_ROOT and PVM_ARCH environment variables must be set for linking under -parallel.\n";
1641         exit(1);
1642     }
1643
1644 } elsif ( $GRANing eq 'g' ) {
1645     if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -gransim with -ticky.\n"; exit 1; }
1646     $BuildTag = '_mg';
1647
1648 } elsif ( $TICKYing eq 't' ) {
1649     $BuildTag = '_t';
1650 }
1651 \end{code}
1652
1653 \begin{code}
1654 if ( $BuildTag ne '' ) { # something other than normal sequential...
1655
1656     push(@HsP_flags, "-g$BuildTag.hi"); # use appropriate Prelude .hi files
1657
1658     $ProduceC = 1; $ProduceS = ''; # must go via C
1659
1660 #    print STDERR "eval...",$EvaldSetupOpts{$BuildTag},"\n";
1661
1662     eval($EvaldSetupOpts{$BuildTag});
1663 }
1664 \end{code}
1665
1666 Decide what the consistency-checking options are in force for this run:
1667 \begin{code}
1668 $HsC_consist_options = "${BuildTag},${DEBUGging}";
1669 $Cc_consist_options  = "${BuildTag},${DEBUGging},${RegisteriseC}";
1670 \end{code}
1671
1672 %************************************************************************
1673 %*                                                                      *
1674 \subsection{Add on machine-specific C-compiler flags}
1675 %*                                                                      *
1676 %************************************************************************
1677
1678 Shove on magical machine-specific options.  We use \tr{unshift} to
1679 stick them on the {\em front} of the arrays, so that ``later''
1680 user-specified flags can clobber them (e.g., \tr{-U__STG_REV_TBLS__}).
1681
1682 Note: a few ``always apply'' flags were set at the very beginning.
1683
1684 \begin{code}
1685 if ($TargetPlatform =~ /^alpha-/) {
1686     # we know how to *mangle* asm for alpha
1687     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1688     unshift(@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1')) if $StkChkByPageFaultOK;
1689     unshift(@CcBoth_flags,  ('-static')) if $GccAvailable;
1690
1691 } elsif ($TargetPlatform =~ /^hppa/) {
1692     # we know how to *mangle* asm for hppa
1693     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1694     unshift(@CcBoth_flags,  ('-static')) if $GccAvailable;
1695     # We don't put in '-mlong-calls', because it's only
1696     # needed for very big modules (sigh), and we don't want
1697     # to hobble ourselves further on all the other modules
1698     # (most of them).
1699     unshift(@CcBoth_flags,  ('-D_HPUX_SOURCE')) if $GccAvailable;
1700         # ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1701         # (very nice, but too bad the HP /usr/include files don't agree.)
1702
1703 } elsif ($TargetPlatform =~ /^i386-/) {
1704     # we know how to *mangle* asm for X86
1705     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1706     unshift(@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1'))
1707         if $StkChkByPageFaultOK && $TargetPlatform !~ /linux/;
1708         # NB: cannot do required signal magic on Linux for such stk chks */
1709
1710     unshift(@CcRegd_flags, ('-m486')); # not worth not doing
1711
1712     # -fno-defer-pop : basically the same game as for m68k
1713     #
1714     # -fomit-frame-pointer : *must* ; because we're stealing
1715     #   the fp (%ebp) for our register maps.  *All* register
1716     #   maps (in MachRegs.lh) must steal it.
1717
1718     unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1719     unshift(@CcRegd_flags,    '-fomit-frame-pointer');
1720     unshift(@CcRegd_flags,    "-DSTOLEN_X86_REGS=$StolenX86Regs");
1721
1722     unshift(@CcBoth_flags,  ('-static')) if $GccAvailable; # maybe unnecessary???
1723
1724 } elsif ($TargetPlatform =~ /^m68k-/) {
1725     # we know how to *mangle* asm for m68k
1726     unshift (@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1727     unshift (@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1')) if $StkChkByPageFaultOK;
1728
1729     # -fno-defer-pop : for the .hc files, we want all the pushing/
1730     #     popping of args to routines to be explicit; if we let things
1731     #     be deferred 'til after an STGJUMP, imminent death is certain!
1732     #
1733     # -fomit-frame-pointer : *don't*
1734     #     It's better to have a6 completely tied up being a frame pointer
1735     #     rather than let GCC pick random things to do with it.
1736     #     (If we want to steal a6, then we would try to do things
1737     #     as on iX86, where we *do* steal the frame pointer [%ebp].)
1738
1739     unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1740     unshift(@CcRegd_flags,    '-fno-omit-frame-pointer');
1741         # maybe gives reg alloc a better time
1742         # also: -fno-defer-pop is not sufficiently well-behaved without it
1743
1744 } elsif ($TargetPlatform =~ /^powerpc-/) {
1745     # we know how to *mangle* asm for PowerPC
1746     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1747     unshift(@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1')) if $StkChkByPageFaultOK;
1748
1749 } elsif ($TargetPlatform =~ /^sparc-/) {
1750     # we know how to *mangle* asm for SPARC
1751     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1752     unshift(@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1')) if $StkChkByPageFaultOK;
1753
1754 } elsif ($TargetPlatform =~ /^mips-/) {
1755     # we (hope to) know how to *mangle* asm for MIPSen
1756     unshift(@CcRegd_flags, ('-D__STG_REV_TBLS__'));
1757     unshift(@CcRegd_flags, ('-DSTACK_CHECK_BY_PAGE_FAULT=1')) if $StkChkByPageFaultOK;
1758     unshift(@CcBoth_flags,  ('-static')) if $GccAvailable;
1759 }
1760 \end{code}
1761
1762 Same unshifting magic, but for special linker flags.
1763
1764 Should really be whether or not we prepend underscores to global symbols,
1765 not an architecture test.  (JSM)
1766
1767 \begin{code}
1768 unshift(@Ld_flags,
1769     (   $TargetPlatform =~ /^alpha-/
1770      || $TargetPlatform =~ /^hppa/
1771      || $TargetPlatform =~ /^mips-sgi-irix/
1772      || $TargetPlatform =~ /^powerpc-/
1773      || $TargetPlatform =~ /-solaris/
1774     )
1775     ? (($Ld_main) ? (
1776         '-u', 'Main_' . $Ld_main . '_closure',
1777        ) : (),
1778        '-u', 'unsafePerformPrimIO_fast1',
1779        '-u', 'Nil_closure',
1780        '-u', 'IZh_static_info',
1781        '-u', 'False_inregs_info',
1782        '-u', 'True_inregs_info',
1783        '-u', 'CZh_static_info',
1784        '-u', 'DEBUG_REGS') # just for fun, now...
1785
1786     # nice friendly a.out machines...
1787     : (($Ld_main) ? (
1788         '-u', '_Main_' . $Ld_main . '_closure',
1789        ) : (),
1790        '-u', '_unsafePerformPrimIO_fast1',
1791        '-u', '_Nil_closure',
1792        '-u', '_IZh_static_info',
1793        '-u', '_False_inregs_info',
1794        '-u', '_True_inregs_info',
1795        '-u', '_CZh_static_info',
1796        '-u', '_DEBUG_REGS')
1797     );
1798 \end{code}
1799
1800 %************************************************************************
1801 %*                                                                      *
1802 \subsection{Set up include paths and system-library enslurpment}
1803 %*                                                                      *
1804 %************************************************************************
1805
1806 Now that we know what garbage-collector, etc., are required, we can
1807 finalise our list of libraries to slurp through, and generally Get
1808 Ready for Business.
1809
1810 \begin{code}
1811 # default includes must be added AFTER option processing
1812 if ( $(INSTALLING) ) {
1813     push (@Include_dir, "$InstLibDirGhc/includes");
1814     push (@Include_dir, "$InstDataDirGhc/includes");
1815     
1816 } else {
1817     push (@Include_dir, "$TopPwd/$(CURRENT_DIR)/$(GHC_INCLUDESRC)");
1818 }
1819 \end{code}
1820
1821 \begin{code}
1822 local($f);
1823 foreach $f (@SysLibrary) {
1824     $f .= "${BuildTag}" if $f =~ /^-lHS/;
1825 }
1826
1827 # fiddle the TopClosure file name...
1828 $TopClosureFile =~ s/XXXX//;
1829
1830 # Push library HSrts, plus boring clib bit
1831 push(@SysLibrary, "-lHSrts${BuildTag}");
1832 push(@SysLibrary, '-lHSclib');
1833
1834 # Push the pvm libraries
1835 if ($BuildTag eq '_mp') {
1836     $pvmlib = "$ENV{'PVM_ROOT'}/lib/$ENV{'PVM_ARCH'}";
1837     push(@SysLibrary, "-L$pvmlib", '-lpvm3', '-lgpvm3');
1838     if ( $ENV{'PVM_ARCH'} eq 'SUNMP' ) {
1839         push(@SysLibrary, '-lthread', '-lsocket', '-lnsl');
1840     } elsif ( $ENV{'PVM_ARCH'} eq 'SUN4SOL2' ) {
1841         push(@SysLibrary, '-lsocket', '-lnsl');
1842     }
1843 }
1844
1845 # Push the GNU multi-precision arith lib; and the math library
1846 push(@SysLibrary, '-lgmp');
1847 push(@SysLibrary, '-lm');
1848 \end{code}
1849
1850 %************************************************************************
1851 %*                                                                      *
1852 \subsection{Check that this system was built to do what we are asking}
1853 %*                                                                      *
1854 %************************************************************************
1855
1856 Before continuing we check that the appropriate build is available.
1857
1858 \begin{code}
1859 die "$Pgm: no BuildAvail?? $BuildTag\n" if ! $BuildAvail{$BuildTag}; # sanity
1860
1861 if ( $BuildAvail{$BuildTag} =~ /^-build-.*-not-defined$/ ) {
1862     print STDERR "$Pgm: a `", $BuildDescr{$BuildTag},
1863         "' \"build\" is not available with your GHC setup.\n";
1864     print STDERR "(It was not configured for it at your site.)\n";
1865     print STDERR $ShortUsage;
1866     exit 1;
1867 }
1868 \end{code}
1869
1870 %************************************************************************
1871 %*                                                                      *
1872 \subsection{Final miscellaneous setup bits before we start going}
1873 %*                                                                      *
1874 %************************************************************************
1875
1876 Record largest specific heapsize, if any.
1877 \begin{code}
1878 $Specific_heap_size = $Specific_heap_size * $Scale_sizes_by;
1879 push(@HsC_rts_flags, '-H'.$Specific_heap_size);
1880 $Specific_stk_size = $Specific_stk_size * $Scale_sizes_by;
1881 push(@HsC_rts_flags, (($RTS_style eq 'ghc') ? '-K' : '-A').$Specific_stk_size);
1882
1883 # hack to avoid running hscpp
1884 $HsCpp = $Cat if ! $Cpp_flag_set;
1885 \end{code}
1886
1887 If no input or link files seen, then we let 'em feed in stdin; this is
1888 mainly for debugging.
1889 \begin{code}
1890 if ($#Input_file < 0 && $#Link_file < 0) {
1891     push(@Input_file, '-');
1892 }
1893 \end{code}
1894
1895 Tell the world who we are, if they asked.
1896 \begin{code}
1897 if ($Verbose) {
1898     print STDERR "$(PROJECTNAME), version $(PROJECTVERSION) $(PROJECTPATCHLEVEL)\n";
1899 }
1900 \end{code}
1901
1902 %************************************************************************
1903 %*                                                                      *
1904 \section[Driver-main-loop]{Main loop: Process input files, and link if required}
1905 %*                                                                      *
1906 %************************************************************************
1907
1908 Process the input files; don't continue with linking if there are
1909 problems (global variable @$Status@ non-zero).
1910 \begin{code}
1911 foreach $ifile (@Input_file) {
1912     &ProcessInputFile($ifile);
1913 }
1914
1915 if ( $Status > 0 ) { # don't link if there were errors...
1916     print STDERR $ShortUsage;
1917     &tidy_up();
1918     exit $Status;
1919 }
1920 \end{code}
1921
1922 Link if appropriate.
1923 \begin{code}
1924 if ($Do_lnkr) {
1925     local($libdirs);
1926     # glue them together:
1927     push(@UserLibrary_dir, @SysLibrary_dir);
1928     if ($#UserLibrary_dir < 0) {
1929         $libdirs = '';
1930     } else {
1931         $libdirs = '-L' . join(' -L',@UserLibrary_dir);
1932     }
1933     # for a linker, use an explicitly given one, or the going C compiler ...
1934     local($lnkr) = ( $Lnkr ) ? $Lnkr : ($RegisteriseC ? $CcRegd : $CcUnregd );
1935
1936     local($output)= ($Specific_output_file ne '') ? "-o $Specific_output_file" : '';
1937     @Files_to_tidy = ($Specific_output_file ne '') ? "$Specific_output_file" : 'a.out';
1938
1939     local($to_do) = "$lnkr $Verbose @Ld_flags $output @Link_file $TopClosureFile $libdirs @UserLibrary @SysLibrary";
1940     &run_something($to_do, 'Linker');
1941
1942     # finally, check the consistency info in the binary
1943     local($executable) = $Files_to_tidy[0];
1944     @Files_to_tidy = (); # reset; we don't want to nuke it if it's inconsistent
1945
1946     if ( $LinkChk ) {
1947         # dynamically load consistency-chking code; then do it.
1948         require('ghc-consist.prl')
1949             || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-consist.prl!\n");
1950
1951         &chk_consistency_info ( $executable );
1952     }
1953
1954     # if PVM parallel stuff, we do truly weird things.
1955     # Essentially: (1) move the executable over to where PVM expects
1956     # to find it.  (2) create a script in place of the executable
1957     # which will cause the program to be run, via SysMan.
1958     if ( $PARing eq 'p' ) {
1959         local($pvm_executable) = $executable;
1960         local($pvm_executable_base);
1961
1962         if ( $pvm_executable !~ /^\// ) { # a relative path name: make absolute
1963             local($pwd) = `pwd`;
1964             chop($pwd);
1965             $pwd =~ s/^\/tmp_mnt//;
1966             $pvm_executable = "$pwd/$pvm_executable";
1967         }
1968
1969         $pvm_executable =~ s|/|=|g; # make /s into =s
1970         $pvm_executable_base = $pvm_executable;
1971
1972         $pvm_executable = $ENV{'PVM_ROOT'} . '/bin/' . $ENV{'PVM_ARCH'}
1973                         . "/$pvm_executable";
1974
1975         &run_something("rm -f $pvm_executable; cp -p $executable $pvm_executable && rm -f $executable", 'Moving binary to PVM land');
1976
1977         # OK, now create the magic script for "$executable"
1978         open(EXEC, "> $executable") || &tidy_up_and_die(1,"$Pgm: couldn't open $executable to write!\n");
1979         print EXEC <<EOSCRIPT1;
1980 #!$(PERL)
1981 # =!=!=!=!=!=!=!=!=!=!=!
1982 # This script is automatically generated: DO NOT EDIT!!!
1983 # Generated by Glasgow Haskell, version $(PROJECTVERSION) $(PROJECTPATCHLEVEL)
1984 #
1985 \$pvm_executable      = '$pvm_executable';
1986 \$pvm_executable_base = '$pvm_executable_base';
1987 \$SysMan = '$SysMan';
1988 EOSCRIPT1
1989
1990         print EXEC <<\EOSCRIPT2;
1991 # first, some magical shortcuts to run "commands" on the binary
1992 # (which is hidden)
1993 if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {
1994     local($cmd) = $1;
1995     system("$cmd $pvm_executable");
1996     exit(0); # all done
1997 }
1998
1999 # OK, really run it; process the args first
2000 $ENV{'PE'} = $pvm_executable_base;
2001 $debug = '';
2002 $nprocessors = 2; # the default
2003 @nonPVM_args = ();
2004 $in_RTS_args = 0;
2005
2006 # ToDo: handle --RTS
2007 args: while ($a = shift(@ARGV)) {
2008     if ( $a eq '+RTS' ) {
2009         $in_RTS_args = 1;
2010     } elsif ( $a eq '-RTS' ) {
2011         $in_RTS_args = 0;
2012     }
2013     if ( $a eq '-d' && $in_RTS_args ) {
2014         $debug = '-';
2015     } elsif ( $a =~ /^-N(\d+)/ && $in_RTS_args ) {
2016         $nprocessors = $1;
2017     } else {
2018         push(@nonPVM_args, $a);
2019     }
2020 }
2021
2022 exec "$SysMan $debug $nprocessors @nonPVM_args";
2023 print STDERR "Exec failed!!!: $SysMan $debug $nprocessors @nonPVM_args\n";
2024 exit(1); 
2025 EOSCRIPT2
2026         close(EXEC) || die "Failed closing $executable\n";
2027         chmod 0755, "$executable";
2028     }
2029 }
2030
2031 # that...  that's all, folks!
2032 &tidy_up();
2033 exit $Status; # will still be 0 if all went well
2034 \end{code}
2035
2036 %************************************************************************
2037 %*                                                                      *
2038 \section[Driver-do-one-file]{How to process a single input file}
2039 %*                                                                      *
2040 %************************************************************************
2041
2042 \begin{code}
2043 sub ProcessInputFile {
2044     local($ifile) = @_; # input file name
2045     local($ifile_root); # root of or basename of input file
2046     local($ifile_root_file); # non-directory part of $ifile_root
2047 \end{code}
2048
2049 Handle the weirdity of input from stdin.
2050 \begin{code}
2051     if ($ifile eq '-') {
2052         open(INF, "> $Tmp_prefix.hs") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.hs\n");
2053         print STDERR "Enter your Haskell program, end with ^D (on a line of its own):\n";
2054         while (<>) { print INF $_; }
2055         close(INF) || &tidy_up_and_die(1,"Failed writing to $Tmp_prefix.hs\n");
2056         $ifile = "$Tmp_prefix.hs";
2057         $ifile_root = '_stdin';
2058         $ifile_root_file = $ifile_root;
2059     } else {
2060         ($ifile_root = $ifile) =~ s/\.[^\.\/]+$//;
2061         ($ifile_root_file = $ifile_root) =~ s|.*/||;
2062     }
2063 \end{code}
2064
2065 We now decide what phases of the compilation system we will run over
2066 this file.  The defaults are the ones established when processing flags.
2067 (That established what the last phase run for all files is.)
2068
2069 The lower-case names are the local ones (as is usual), just for this
2070 one file.
2071 \begin{code}
2072     local($do_lit2pgm)  = $Do_lit2pgm;
2073     local($do_hscpp)    = $Do_hscpp;
2074     local($do_hsp)      = $Do_hsp;
2075     local($do_hsc)      = $Do_hsc;
2076     local($do_as)       = $Do_as;
2077     local($do_cc)       = ( $Do_cc != -1) # i.e., it was set explicitly
2078                           ? $Do_cc
2079                           : ( ($ProduceC) ? 1 : 0 );
2080 \end{code}
2081
2082 Look at the suffix and decide what initial phases of compilation may
2083 be dropped off for this file.  Also the rather boring business of
2084 which files are coming-in/going-out.
2085 \begin{code}
2086     # names of the files to stuff between phases
2087     # defaults are temporaries
2088     local($in_lit2pgm)    = $ifile;
2089     local($lit2pgm_hscpp) = "$Tmp_prefix.lpp";
2090     local($hscpp_hsp)     = "$Tmp_prefix.cpp";
2091     local($hsp_hsc)       = "$Tmp_prefix.hsp";
2092     local($hsc_cc)        = "$Tmp_prefix.hc";
2093
2094     # to help C compilers grok .hc files [ToDo: de-hackify]
2095     local($cc_help)       = "ghc$$.c";
2096     local($cc_help_s)     = "ghc$$.s";
2097
2098     local($hsc_hi)        = "$Tmp_prefix$HiSuffix";
2099     local($cc_as_o)       = "${Tmp_prefix}_o.s"; # temporary for raw .s file if opt C
2100     local($cc_as)         = "$Tmp_prefix.s";
2101     local($as_out)        = ($Specific_output_file ne '' && ! $Do_lnkr)
2102                                 ? $Specific_output_file
2103                                 : &odir_ify("${ifile_root}${Osuffix}");
2104
2105     local($is_hc_file)    = 1; #Is the C code .hc or .c
2106
2107     if ($ifile =~ /\.lhs$/) {
2108         push(@Link_file, &odir_ify("${ifile_root}${Osuffix}"));
2109     } elsif ($ifile =~ /\.hs$/) {
2110         $do_lit2pgm = 0;
2111         $lit2pgm_hscpp = $ifile;
2112         push(@Link_file, &odir_ify("${ifile_root}${Osuffix}"));
2113     } elsif ($ifile =~ /\.hc$/) {
2114         $do_lit2pgm = 0; $do_hscpp = 0; $do_hsp = 0; $do_hsc = 0; $do_cc = 1;
2115         $hsc_cc = $ifile;    
2116         push(@Link_file, &odir_ify("${ifile_root}${Osuffix}"));
2117     } elsif ($ifile =~ /\.c$/) {
2118         $do_lit2pgm = 0; $do_hscpp = 0; $do_hsp = 0; $do_hsc = 0; $do_cc = 1;
2119         $hsc_cc = $ifile; $is_hc_file = 0;
2120         push(@Link_file, &odir_ify("${ifile_root}${Osuffix}"));
2121     } elsif ($ifile =~ /\.s$/) {
2122         $do_lit2pgm = 0; $do_hscpp = 0; $do_hsp = 0; $do_hsc = 0; $do_cc = 0;
2123         $cc_as = $ifile;    
2124         push(@Link_file, &odir_ify("${ifile_root}${Osuffix}"));
2125     } else {
2126         if ($ifile !~ /\.a$/) {
2127             print STDERR "$Pgm: don't recognise suffix on `$ifile'; passing it through to linker\n";
2128         }
2129         $do_lit2pgm = 0; $do_hscpp = 0; $do_hsp = 0; $do_hsc = 0; $do_cc = 0; $do_as = 0;
2130         push(@Link_file, $ifile);
2131     }
2132 \end{code}
2133
2134 To get the output file name right: for each phase that we are {\em
2135 not} going to run, set its input (i.e., the output of its preceding phase) to
2136 @"$ifile_root.<suffix>"@.
2137 \begin{code}
2138     # lit2pgm -- no preceding phase
2139     if (! $do_hscpp) {
2140         $lit2pgm_hscpp = "$ifile_root.lpp????"; # not done
2141     }
2142     if (! $do_hsp) {
2143         $hscpp_hsp = "$ifile_root.cpp????"; # not done
2144     }
2145     if (! $do_hsc) {
2146         $hsp_hsc = "$ifile_root.hsp????"; # not done
2147     }
2148     if (! $do_cc) {
2149         $hsc_cc = &odir_ify("$ifile_root.hc");
2150     }
2151     if (! $do_as) {
2152         if ($Specific_output_file ne '') {
2153             $cc_as  = $Specific_output_file;
2154         } else {
2155             $cc_as  = &odir_ify(( $Only_preprocess_C ) ? "$ifile_root.i" : "$ifile_root.s");
2156         }
2157     }
2158 \end{code}
2159
2160 OK, now do it!  Note that we don't come back from a @run_something@ if
2161 it fails.
2162 \begin{code}
2163     if ($do_lit2pgm) {
2164         local($to_do) = "echo '#line 1 \"$in_lit2pgm\"' > $lit2pgm_hscpp; ".
2165                         "$Unlit @Unlit_flags $in_lit2pgm -  >> $lit2pgm_hscpp";
2166         @Files_to_tidy = ( $lit2pgm_hscpp );
2167         &run_something($to_do, 'literate pre-processor');
2168     }
2169     if ($do_hscpp) {
2170         # ToDo: specific output?
2171         if ($HsCpp eq $Cat) {
2172             local($to_do) = "echo '#line 1 \"$in_lit2pgm\"' > $hscpp_hsp; ".
2173                             "$HsCpp $lit2pgm_hscpp >> $hscpp_hsp";
2174             @Files_to_tidy = ( $hscpp_hsp );
2175             &run_something($to_do, 'Ineffective C pre-processor');
2176         } else {
2177             local($includes) = '-I' . join(' -I',@Include_dir);
2178             local($to_do) = "echo '#line 1 \"$in_lit2pgm\"' > $hscpp_hsp; ".
2179                             "$HsCpp $Verbose $genSPECS_flag @HsCpp_flags -D__HASKELL1__=$haskell1_version -D__GLASGOW_HASKELL__=$ghc_version_info $includes $lit2pgm_hscpp >> $hscpp_hsp";
2180             @Files_to_tidy = ( $hscpp_hsp );
2181             &run_something($to_do, 'Haskellised C pre-processor');
2182         }
2183     }
2184     if ($do_hsp) {
2185         # glue imports onto HsP_flags
2186         # if new parser, then put a comma on the front of all of them.
2187         local($hsprefix) = ($do_hsp == 2) ? ',' : '';
2188
2189         foreach $a   ( @HsP_flags  )    { $a = "$hsprefix$a" unless $a =~ /^,/; }
2190         foreach $dir ( @Import_dir )    { push(@HsP_flags, "$hsprefix-I$dir"); }
2191         foreach $dir ( @SysImport_dir ) { push(@HsP_flags, "$hsprefix-J$dir"); }
2192     }
2193
2194     if ($do_hsp == 1) { # "old" parser
2195         local($to_do) = "$HsP $Verbose @HsP_flags $hscpp_hsp > $hsp_hsc";
2196         @Files_to_tidy = ( $hsp_hsc );
2197         &run_something($to_do, 'Haskell parser');
2198         if ($Dump_parser_output) {
2199             print STDERR `$Cat $hsp_hsc`;
2200         }
2201         @HsP_flags = (); # reset!
2202     }
2203     if ($do_hsc) {
2204         # here, we may produce .hc and/or .hi files
2205         local($output)    = '';
2206         local($c_source)  = "$ifile_root.hc";
2207         local($c_output)  = $hsc_cc;         # defaults
2208         local($s_output)  = $cc_as;
2209         local($hi_output) = "$ifile_root$HiSuffix";
2210         local($going_interactive) = 0;
2211
2212         if ($Specific_output_file ne '' && ! $do_cc) {
2213             $c_source = $c_output = $Specific_output_file;
2214             @Files_to_tidy = ( $Specific_output_file ) if $Specific_output_file ne '-';
2215         }
2216         if ($Specific_hi_file ne '') {
2217             # we change the suffix (-hisuf) even if a specific -ohi file:
2218             $Specific_hi_file =~ s/\.hi$/$HiSuffix/;
2219             $hi_output = $Specific_hi_file;
2220             @Files_to_tidy = ( $Specific_hi_file ) if $Specific_hi_file ne '-';
2221         }
2222
2223         if ( ! ($ProduceC || $ProduceS)
2224             || $ifile_root eq '_stdin'  # going interactive...
2225             || ($c_output eq '-' && $hi_output eq '-')) {
2226             $going_interactive = 1;
2227 #OLD:       $output = '1>&2';   # interactive/debugging, to stderr
2228             @Files_to_tidy = ();
2229             # don't need .hi (unless magic value "2" says we wanted it anyway):
2230             if ( $ProduceHi == 2 ) {
2231                 $output .= " -hi$hsc_hi";
2232                 unlink($hsc_hi); # needs to be cleared; will be appended to
2233             } else {
2234                 $ProduceHi = 0;
2235             }
2236             $do_cc = 0; $do_as = 0; $Do_lnkr = 0; # and we won't go any further...
2237         }
2238
2239         if ( ! $going_interactive ) {
2240             if ( $ProduceHi ) {
2241                 # we always go to a temp file for these (for later diff'ing)
2242                 $output = "-hi$hsc_hi";
2243                 unlink($hsc_hi); # needs to be cleared; will be appended to
2244                 @Files_to_tidy = ( $hsc_hi );
2245             }
2246             if ( $ProduceC ) {
2247                 $output .= " -C$c_output";
2248                 push(@Files_to_tidy, $c_output);
2249
2250                 open(CFILE, "> $c_output") || &tidy_up_and_die(1,"$Pgm: failed to open `$c_output' (to write)\n");
2251                 print CFILE "#line 2 \"$c_source\"\n";
2252                 close(CFILE) || &tidy_up_and_die(1,"Failed writing to $c_output\n");
2253                 # the "real" C output will then be appended
2254             }
2255             if ( $ProduceS ) {
2256                 $output .= " -fasm-$ProduceS -S$s_output";
2257                 push(@Files_to_tidy, $s_output);
2258
2259                 # ToDo: ummm,... this isn't doing anything (WDP 94/11)
2260                 open(SFILE, "> $s_output") || &tidy_up_and_die(1,"$Pgm: failed to open `$s_output' (to write)\n");
2261                 close(SFILE) || &tidy_up_and_die(1,"Failed writing to $s_output\n");
2262                 # the "real" assembler output will then be appended
2263             }
2264         }
2265
2266         # if we're compiling foo.hs, we want the GC stats to end up in foo.stat
2267         if ( $CollectingGCstats ) {
2268             if ($RTS_style eq 'hbc') {
2269                 push(@HsC_rts_flags, '-S'); # puts it in "STAT"
2270             } else {
2271                 push(@HsC_rts_flags, "-S$ifile_root.stat");
2272                 push(@Files_to_tidy, "$ifile_root.stat");
2273             }
2274         }
2275
2276         if ( $CollectGhcTimings ) { # assume $RTS_style eq 'ghc'
2277             # emit nofibbish time/bytes-alloc stats to stderr;
2278             # see later .stat file post-processing
2279             push(@HsC_rts_flags, "-s$Tmp_prefix.stat");
2280             push(@Files_to_tidy, "$Tmp_prefix.stat");
2281         }
2282
2283         local($dump);
2284         if ($Specific_dump_file ne '') {
2285             $dump = "2>> $Specific_dump_file";
2286             $Using_dump_file = 1;
2287         } else {
2288             $dump = '';
2289         }
2290
2291         local($to_do);
2292         if ($RTS_style eq 'hbc') {
2293             # NB: no parser flags
2294             $to_do = "$HsC < $hsp_hsc $dump @HsC_rts_flags - @HsC_flags $CoreLint $Verbose $output";
2295         } elsif ($do_hsp == 1) { # old style parser -- no HsP_flags
2296             $to_do = "$HsC < $hsp_hsc $dump @HsC_flags $CoreLint $Verbose $output +RTS @HsC_rts_flags";
2297         } else { # new style
2298             $to_do = "$HsC ,-H @HsP_flags ,$hscpp_hsp $dump @HsC_flags $CoreLint $Verbose $output +RTS @HsC_rts_flags";
2299         }
2300         &run_something($to_do, 'Haskell compiler');
2301
2302         # compensate further for HBC's -S rts opt:
2303         if ($CollectingGCstats && $RTS_style eq 'hbc') {
2304             unlink("$ifile_root.stat");
2305             rename('STAT', "$ifile_root.stat");
2306         }
2307
2308         # finish business w/ nofibbish time/bytes-alloc stats
2309         &process_ghc_timings() if $CollectGhcTimings;
2310
2311         # if non-interactive, heave in the consistency info at the end
2312         # NB: pretty hackish (depends on how $output is set)
2313         if ( ! $going_interactive ) {
2314             if ( $ProduceC ) {
2315             $to_do = "echo 'static char ghc_hsc_ID[] = \"\@(#)hsc $ifile\t$HsC_major_version.$HsC_minor_version,$HsC_consist_options\";' >> $c_output";
2316             }
2317             if ( $ProduceS ) {
2318                 local($consist) = "hsc.$ifile.$HsC_major_version.$HsC_minor_version.$HsC_consist_options";
2319                 $consist =~ s/,/./g;
2320                 $consist =~ s/\//./g;
2321                 $consist =~ s/-/_/g;
2322                 $consist =~ s/[^A-Za-z0-9_.]/ZZ/g; # ToDo: properly?
2323                 $to_do = "echo '\n\t.text\n$consist:' >> $s_output";
2324             }
2325             &run_something($to_do, 'Pin on Haskell consistency info');  
2326         }
2327
2328         # call the special mangler to produce the .hi/.h(h?) files...
2329         &diff_hi_file($hsc_hi, $hi_output)
2330                 if $ProduceHi == 1 && ! $going_interactive;
2331 #OLD:   &extract_c_and_hi_files("$Tmp_prefix.hsc", $c_output, $hi_output, $c_source)
2332
2333         # if we produced an interface file "no matter what",
2334         # print what we got on stderr (ToDo: honor -ohi flag)
2335         if ( $ProduceHi == 2 ) {
2336             print STDERR `$Cat $hsc_hi`;
2337         }
2338
2339         # save a copy of the .hc file, even if we are carrying on...
2340         if ($ProduceC && $do_cc && $Keep_hc_file_too) {
2341             local($to_do) = "$(RM) $ifile_root.hc; cp $c_output $ifile_root.hc";
2342             &run_something($to_do, 'Saving copy of .hc file');
2343         }
2344
2345         # save a copy of the .s file, even if we are carrying on...
2346         if ($ProduceS && $do_as && $Keep_s_file_too) {
2347             local($to_do) = "$(RM) $ifile_root.s; cp $cc_as $ifile_root.s";
2348             &run_something($to_do, 'Saving copy of .s file');
2349         }
2350
2351         # if we're going to split up object files,
2352         # we inject split markers into the .hc file now
2353         if ( $ProduceC && $SplitObjFiles ) {
2354             &inject_split_markers ( $c_output );
2355         }
2356     }
2357     if ($do_cc) {
2358         local($includes) = '-I' . join(' -I',@Include_dir);
2359         local($cc);
2360         local($s_output);
2361         local($c_flags) = "@CcBoth_flags";
2362         local($ddebug_flag) = ( $DEBUGging ) ? '-DDEBUG' : '';
2363         if ($RegisteriseC) {
2364             $cc       = $CcRegd;
2365             $s_output = ($is_hc_file || $TargetPlatform =~ /^(hppa|i386)/) ? $cc_as_o : $cc_as;
2366             $c_flags .= " @CcRegd_flags";
2367             $c_flags .= ($is_hc_file) ? " @CcRegd_flags_hc"  : " @CcRegd_flags_c";
2368         } else {
2369             $cc       = $CcUnregd;
2370             $s_output = $cc_as;
2371             $c_flags .= " @CcUnregd_flags";
2372             $c_flags .= ($is_hc_file) ? " @CcUnregd_flags_hc" : " @CcUnregd_flags_c";
2373         }
2374
2375         # C compiler won't like the .hc extension.  So we create
2376         # a tmp .c file which #include's the needful.
2377         open(TMP, "> $cc_help") || &tidy_up_and_die(1,"$Pgm: failed to open `$cc_help' (to write)\n");
2378         if ( $is_hc_file ) {
2379             print TMP <<EOINCL;
2380 #ifdef __STG_GCC_REGS__
2381 # if ! (defined(MAIN_REG_MAP) || defined(MARK_REG_MAP) || defined(SCAN_REG_MAP) || defined(SCAV_REG_MAP) || defined(FLUSH_REG_MAP))
2382 #  define MAIN_REG_MAP
2383 # endif
2384 #endif
2385 #include "stgdefs.h"
2386 EOINCL
2387             # user may have asked for #includes to be injected...
2388             print TMP @CcInjects if $#CcInjects >= 0;
2389         }
2390         # heave in the consistency info
2391         print TMP "static char ghc_cc_ID[] = \"\@(#)cc $ifile\t$Cc_major_version.$Cc_minor_version,$Cc_consist_options\";\n";
2392
2393         # and #include the real source
2394         print TMP "#include \"$hsc_cc\"\n";
2395         close(TMP) || &tidy_up_and_die(1,"Failed writing to $cc_help\n");
2396
2397         local($to_do) = "$cc $Verbose $ddebug_flag $c_flags @Cpp_define -D__HASKELL1__=$haskell1_version $includes $cc_help > $Tmp_prefix.ccout 2>&1 && ( if [ $cc_help_s != $s_output ] ; then mv $cc_help_s $s_output ; else exit 0 ; fi )";
2398         # note: __GLASGOW_HASKELL__ is pointedly *not* #defined at the C level.
2399         if ( $Only_preprocess_C ) { # HACK ALERT!
2400             $to_do =~ s/ -S\b//g;
2401         }
2402         @Files_to_tidy = ( $cc_help, $cc_help_s, $s_output );
2403         $PostprocessCcOutput = 1;       # hack, dear hack...
2404         &run_something($to_do, 'C compiler');
2405         $PostprocessCcOutput = 0;
2406         unlink($cc_help, $cc_help_s);
2407
2408         if ( ($RegisteriseC && $is_hc_file)
2409           || $Dump_asm_insn_counts
2410           || $Dump_asm_globals_info ) {
2411             # dynamically load assembler-fiddling code, which we are about to use
2412             local($target) = 'oops';
2413             $target = '-alpha'   if $TargetPlatform =~ /^alpha-/;
2414             $target = '-hppa'    if $TargetPlatform =~ /^hppa/;
2415             $target = ''         if $TargetPlatform =~ /^i386-/;
2416             $target = '-m68k'    if $TargetPlatform =~ /^m68k-/;
2417             $target = '-mips'    if $TargetPlatform =~ /^mips-/;
2418             $target = ''         if $TargetPlatform =~ /^powerpc-/;
2419             $target = '-solaris' if $TargetPlatform =~ /^sparc-sun-solaris2/;
2420             $target = '-sparc'   if $TargetPlatform =~ /^sparc-sun-sunos4/;
2421
2422             $target ne 'oops'
2423             || &tidy_up_and_die(1,"$Pgm: panic: can't decipher $TargetPlatform!\n");
2424             require("ghc-asm$target.prl")
2425             || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm$target.prl!\n");
2426         }
2427
2428         if ( $Dump_raw_asm ) { # to stderr, before mangling
2429             local($to_pr) = ($RegisteriseC) ? $cc_as_o : $cc_as ;
2430             print STDERR `cat $to_pr`;
2431         }
2432
2433         if ($RegisteriseC) {
2434             if ($is_hc_file) {
2435                 # post-process the assembler [.hc files only]
2436                 &mangle_asm($cc_as_o, $cc_as);
2437
2438             } elsif ($TargetPlatform =~ /^hppa/) {
2439                 # minor mangling of non-threaded files for hp-pa only
2440                 require('ghc-asm-hppa.prl')
2441                 || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm-hppa.prl!\n");
2442                 &mini_mangle_asm($cc_as_o, $cc_as);
2443
2444             } elsif ($TargetPlatform =~ /^i386/) {
2445                 # extremely-minor OFFENSIVE mangling of non-threaded just one file
2446                 require('ghc-asm.prl')
2447                 || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm.prl!\n");
2448                 &mini_mangle_asm($cc_as_o, $cc_as);
2449             }
2450         }
2451
2452         # collect interesting (static-use) info
2453         &dump_asm_insn_counts($cc_as)  if $Dump_asm_insn_counts;
2454         &dump_asm_globals_info($cc_as) if $Dump_asm_globals_info;
2455
2456         # save a copy of the .s file, even if we are carrying on...
2457         if ($do_as && $Keep_s_file_too) {
2458             local($to_do) = "$(RM) $ifile_root.s; cp $cc_as $ifile_root.s";
2459             &run_something($to_do, 'Saving copy of .s file');
2460         }
2461     }
2462
2463     if ($do_as) {
2464         # if we're splitting .o files...
2465         if ( $SplitObjFiles ) {
2466             &split_asm_file ( $cc_as );
2467         }
2468
2469         local($asmblr) = ( $As ) ? $As : ($RegisteriseC ? $CcRegd : $CcUnregd );
2470
2471         if ( ! $SplitObjFiles ) {
2472             local($to_do)  = "$asmblr -o $as_out -c @As_flags $cc_as";
2473             @Files_to_tidy = ( $as_out );
2474             &run_something($to_do, 'Unix assembler');
2475
2476         } else { # more complicated split-ification...
2477
2478             # must assemble files $Tmp_prefix__[1 .. $NoOfSplitFiles].s
2479
2480             for ($f = 1; $f <= $NoOfSplitFiles; $f++ ) {
2481                 local($split_out) = &odir_ify("${ifile_root}__${f}${Osuffix}");
2482                 local($to_do) = "$asmblr -o $split_out -c @As_flags ${Tmp_prefix}__${f}.s";
2483                 @Files_to_tidy = ( $split_out );
2484
2485                 &run_something($to_do, 'Unix assembler');
2486             }
2487         }
2488     }
2489 } # end of ProcessInputFile
2490 \end{code}
2491
2492 %************************************************************************
2493 %*                                                                      *
2494 \section[Driver-misc-utils]{Miscellaneous utilities}
2495 %*                                                                      *
2496 %************************************************************************
2497
2498 %************************************************************************
2499 %*                                                                      *
2500 \subsection[Driver-odir-ify]{@odir_ify@: Mangle filename if \tr{-odir} set}
2501 %*                                                                      *
2502 %************************************************************************
2503
2504 \begin{code}
2505 sub odir_ify {
2506     local($orig_file) = @_;
2507     if ($Specific_output_dir eq '') {   # do nothing
2508         return($orig_file);
2509     } else {
2510         local ($orig_file_only);
2511         ($orig_file_only = $orig_file) =~ s|.*/||;
2512         return("$Specific_output_dir/$orig_file_only");
2513     }
2514 }
2515 \end{code}
2516
2517 %************************************************************************
2518 %*                                                                      *
2519 \subsection[Driver-run-something]{@run_something@: Run a phase}
2520 %*                                                                      *
2521 %************************************************************************
2522
2523 \begin{code}
2524 sub run_something {
2525     local($str_to_do, $tidy_name) = @_;
2526
2527     print STDERR "\n$tidy_name:\n\t" if $Verbose;
2528     print STDERR "$str_to_do\n" if $Verbose;
2529
2530     if ($Using_dump_file) {
2531         open(DUMP, ">> $Specific_dump_file")
2532             || &tidy_up_and_die(1,"$Pgm: failed to open `$Specific_dump_file'\n");
2533         print DUMP "\nCompilation Dump for: $str_to_do\n\n";
2534         close(DUMP) 
2535             || &tidy_up_and_die(1,"$Pgm: failed closing `$Specific_dump_file'\n");
2536     }
2537
2538     local($return_val) = 0;
2539     system("$Time $str_to_do");
2540     $return_val = $?;
2541
2542     if ( $PostprocessCcOutput ) { # hack, continued
2543         open(CCOUT, "< $Tmp_prefix.ccout")
2544             || &tidy_up_and_die(1,"$Pgm: failed to open `$Tmp_prefix.ccout'\n");
2545         while ( <CCOUT> ) {
2546             next if /attribute directive ignored/;
2547             next if /call-clobbered/;
2548             next if /from .*COptRegs\.lh/;
2549             next if /from .*(stg|rts)defs\.h:/;
2550             next if /from ghc\d+.c:\d+:/;
2551             next if /from .*\.lc/;
2552             next if /from .*SMinternal\.lh/;
2553             next if /ANSI C does not support \`long long\'/;
2554             next if /warning:.*was declared \`extern\' and later \`static\'/;
2555             next if /warning: assignment discards \`const\' from pointer target type/;
2556             next if /: At top level:$/;
2557             next if /: In function \`.*\':$/;
2558             next if /\`ghc_cc_ID\' defined but not used/;
2559             print STDERR $_;
2560         }
2561         close(CCOUT) || &tidy_up_and_die(1,"$Pgm: failed closing `$Tmp_prefix.ccout'\n");
2562     }
2563
2564     if ($return_val != 0) {
2565         if ($Using_dump_file) {
2566             print STDERR "Compilation Errors dumped in $Specific_dump_file\n";
2567         }
2568
2569         &tidy_up_and_die($return_val, '');
2570     }
2571     $Using_dump_file = 0;
2572 }
2573 \end{code}
2574
2575 %************************************************************************
2576 %*                                                                      *
2577 \subsection[Driver-demangle-C-and-hi]{@extract_c_and_hi_files@: Unscramble Haskell-compiler output}
2578 %*                                                                      *
2579 %************************************************************************
2580
2581 Update interface if the tmp one is newer...
2582 We first have to fish the module name out of the interface.
2583 \begin{code}
2584 sub diff_hi_file {
2585     local($tmp_hi_file, $hi_file) = @_;
2586     local($if_modulename) = '';
2587
2588     # extract the module name
2589
2590     open(TMP,   "< $tmp_hi_file")|| &tidy_up_and_die(1,"$Pgm: failed to open `$tmp_hi_file' (to read)\n");
2591     while (<TMP>) {
2592         if ( /^interface ([A-Za-z0-9'_]+) / ) {
2593             $if_modulename = $1;
2594         }
2595     }
2596     close(TMP) || &tidy_up_and_die(1,"Failed reading from $tmp_hi_file\n");
2597     &tidy_up_and_die(1,"No module name in $tmp_hi_file\n")
2598         if ! $if_modulename;
2599
2600     #compare/diff with old one
2601
2602     if ($hi_file eq '-') {
2603         &run_something("cat $tmp_hi_file", "copy interface to stdout");
2604
2605     } else {
2606         if ($Specific_hi_file eq '' && $if_modulename ne '') {
2607             if ( $hi_file =~ /\// ) {
2608                  $hi_file =~ s/\/[^\/]+$//;
2609                  $hi_file .= "/$if_modulename$HiSuffix";
2610             } else {
2611                 $hi_file = "$if_modulename$HiSuffix";
2612             }
2613             print STDERR "interface really going into: $hi_file\n" if $Verbose;
2614         }
2615
2616         if ($HiDiff_flag && -f $hi_file) {
2617             local($diffcmd) = '$(CONTEXT_DIFF)';
2618
2619             &run_something("cmp -s $tmp_hi_file $hi_file || $(CONTEXT_DIFF) $hi_file $tmp_hi_file 1>&2 || exit 0",
2620                 "Diff'ing old and new $HiSuffix files"); # NB: to stderr
2621         }
2622
2623         &run_something("cmp -s $tmp_hi_file $hi_file || ( $(RM) $hi_file && $(CP) $tmp_hi_file $hi_file )",
2624                        "Comparing old and new $HiSuffix files");
2625     }
2626 }
2627 \end{code}
2628
2629 %************************************************************************
2630 %*                                                                      *
2631 \subsection[Driver-ghctiming]{Emit nofibbish GHC timings}
2632 %*                                                                      *
2633 %************************************************************************
2634
2635 NB: nearly the same as in @runstdtest@ script.
2636
2637 \begin{code}
2638 sub process_ghc_timings {
2639     local($StatsFile) = "$Tmp_prefix.stat";
2640     local($SysSpecificTiming) = 'ghc';
2641
2642     open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
2643     local($tot_live) = 0; # for calculating avg residency
2644
2645     while (<STATS>) {
2646         $tot_live += $1 if /^\s*\d+\s+\d+\s+\d+\.\d+\%\s+(\d+)\s+\d+\.\d+\%/;
2647
2648         $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
2649
2650         if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
2651             $MaxResidency = $1; $ResidencySamples = $2;
2652         }
2653
2654         $GCs = $1 if /^\s*([0-9,]+) garbage collections? performed/;
2655
2656         if ( /^\s*INIT\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
2657             $InitTime = $1; $InitElapsed = $2;
2658         } elsif ( /^\s*MUT\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
2659             $MutTime = $1; $MutElapsed = $2;
2660         } elsif ( /^\s*GC\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
2661             $GcTime = $1; $GcElapsed = $2;
2662         }
2663     }
2664     close(STATS) || die "Failed when closing $StatsFile\n";
2665     if ( defined($ResidencySamples) && $ResidencySamples > 0 ) {
2666         $AvgResidency = int ($tot_live / $ResidencySamples) ;
2667     }
2668
2669     # warn about what we didn't find
2670     print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
2671     print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
2672     print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
2673     print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
2674     print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
2675     print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
2676     print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
2677     print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
2678
2679     # things we didn't necessarily expect to find
2680     $MaxResidency     = 0 unless defined($MaxResidency);
2681     $AvgResidency     = 0 unless defined($AvgResidency);
2682     $ResidencySamples = 0 unless defined($ResidencySamples);
2683
2684     # a bit of tidying
2685     $BytesAlloc =~ s/,//g;
2686     $MaxResidency =~ s/,//g;
2687     $GCs =~ s/,//g;
2688     $InitTime =~ s/,//g;
2689     $InitElapsed =~ s/,//g;
2690     $MutTime =~ s/,//g;
2691     $MutElapsed =~ s/,//g;
2692     $GcTime =~ s/,//g;
2693     $GcElapsed =~ s/,//g;
2694
2695     # print out what we found
2696     print STDERR "<<$SysSpecificTiming: ",
2697         "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed)",
2698         " :$SysSpecificTiming>>\n";
2699
2700     # OK, party over
2701     unlink $StatsFile;
2702 }
2703 \end{code}
2704
2705 %************************************************************************
2706 %*                                                                      *
2707 \subsection[Driver-dying]{@tidy_up@ and @tidy_up_and_die@: Dying gracefully}
2708 %*                                                                      *
2709 %************************************************************************
2710
2711 \begin{code}
2712 sub tidy_up {
2713     local($to_do) = "\n$(RM) $Tmp_prefix*";
2714     if ( $Tmp_prefix !~ /^\s*$/ ) {
2715         print STDERR "$to_do\n" if $Verbose;
2716         system($to_do);
2717     }
2718 }
2719
2720 sub tidy_up_and_die {
2721     local($return_val, $msg) = @_;
2722
2723     # delete any files to tidy
2724     print STDERR "deleting... @Files_to_tidy\n" if $Verbose && $#Files_to_tidy >= 0;
2725     unlink @Files_to_tidy if $#Files_to_tidy >= 0;
2726
2727     &tidy_up();
2728     print STDERR $msg;
2729     exit (($return_val == 0) ? 0 : 1);
2730 }
2731 \end{code}
2732
2733 %************************************************************************
2734 %*                                                                      *
2735 \subsection[Driver-arg-with-arg]{@grab_arg_arg@: Do an argument with an argument}
2736 %*                                                                      *
2737 %************************************************************************
2738
2739 Some command-line arguments take an argument, e.g.,
2740 \tr{-Rmax-heapsize} expects a number to follow.  This can either be
2741 given a part of the same argument (\tr{-Rmax-heapsize8M}) or as the
2742 next argument (\tr{-Rmax-heapsize 8M}).  We allow both cases.
2743
2744 Note: no error-checking; \tr{-Rmax-heapsize -Rgc-stats} will silently
2745 gobble the second argument (and probably set the heapsize to something
2746 nonsensical). (ToDo?)
2747 \begin{code}
2748 sub grab_arg_arg {
2749     local($option, $rest_of_arg) = @_;
2750     
2751     if ($rest_of_arg) {
2752         return($rest_of_arg);
2753     } elsif ($#ARGV >= 0) {
2754         local($temp) = $ARGV[0]; shift(@ARGV); 
2755         return($temp);
2756     } else {
2757         print STDERR "$Pgm: no argument following $option option\n";
2758         $Status++;
2759     }
2760 }
2761 \end{code}
2762
2763 \begin{code}
2764 sub isntAntiFlag {
2765     local($flag) = @_;
2766     local($f);
2767
2768 #Not in HsC_antiflag ## NO!: and not already in HsC_flags
2769
2770     foreach $f ( @HsC_antiflags ) {
2771         return(0) if $flag eq $f;
2772     }
2773 #    foreach $f ( @HsC_flags ) {
2774 #       return(0) if $flag eq $f;
2775 #    }
2776     return(1);
2777 }
2778
2779 sub squashHscFlag {  # pretty terrible
2780     local($flag) = @_;
2781     local($f);
2782
2783     foreach $f ( @HsC_flags ) {
2784         if ($flag eq $f) { $f = ''; }
2785     }
2786 }
2787
2788 sub add_Hsc_flags {
2789     local(@flags) = @_;
2790     local($f);
2791
2792     foreach $f ( @flags ) {
2793         push( @HsC_flags, $f ) if &isntAntiFlag($f);
2794     }
2795 }
2796 \end{code}