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