[project @ 1999-06-02 14:18:42 by simonmar]
[ghc-hetmet.git] / ghc / driver / ghc.lprl
1 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1997
2 %
3
4 This is the driver script for the Glasgow Haskell compilation system.
5 It is written in \tr{perl}.  The first section includes a long
6 ``usage'' message that describes how the driver is supposed to work.
7
8 %************************************************************************
9 %*                                                                      *
10 \section[Driver-usage]{Usage message}
11 %*                                                                      *
12 %************************************************************************
13
14 \begin{code}
15 ($Pgm = $0) =~ s|.*/||;
16 $ShortUsage  =  "\nUsage: For basic information, try the `-help' option.\n";
17 $LongUsage = "\n" . <<EOUSAGE;
18 Use of the Glorious Haskell Compilation System driver:
19
20     $Pgm [command-line-options-and-input-files]
21
22 ------------------------------------------------------------------------
23 This driver ($Pgm) guides each input file through (some of the)
24 possible phases of a compilation:
25
26     - unlit:    extract code from a "literate program"
27     - hscpp:    run code through the C pre-processor (if -cpp flag given)
28     - hsc:      run the Haskell compiler proper
29     - gcc:      run the C compiler (if compiling via C)
30     - as:       run the assembler
31     - ld:       run the linker
32
33 For each input file, the phase to START with is determined by the
34 file's suffix:
35     - .lhs      literate Haskell: unlit
36     - .hs       illiterate Haskell: hsc
37     - .hc       C from the Haskell compiler: gcc
38     - .c        C not from the Haskell compiler: gcc
39     - .s        assembly language: as
40     - other     passed directly to the linker: ld
41
42 If no files are given on the command line, input is taken from
43 standard input, and processing is as for an .hs file.  (All output is
44 to stdout or stderr, however).
45
46 The phase at which to STOP processing is determined by a command-line
47 option:
48     -E          stop after generating preprocessed, de-litted Haskell (used in conjunction with -cpp)
49     -C          stop after generating C (.hc output)
50     -S          stop after generating assembler (.s output)
51     -c          stop after generating object files (.o output)
52
53 Other commonly-used options are:
54
55     -O          An `optimising' package of compiler flags, for faster code
56
57     -prof       Compile for cost-centre profiling
58                 (add -auto for automagic cost-centres on top-level functions)
59
60     -fglasgow-exts  Allow Glasgow extensions (unboxed types, etc.)
61
62     -H14m       Increase compiler's heap size
63
64     -M          Output the Makefile rules recording the
65                 dependencies of a list of Haskell files.
66                 (ghc driver script calls upon the help of a
67                  compatible mkdependHS script to do the actual
68                  processing)
69
70 The User's Guide has more information about GHC's *many* options.
71
72 Given the above, here are some TYPICAL invocations of $Pgm:
73
74     # compile a Haskell module to a .o file, optimising:
75     % $Pgm -c -O Foo.hs
76     # link three .o files into an executable called "test":
77     % $Pgm -o test Foo.o Bar.o Baz.o
78     # compile a Haskell module to C (a .hc file), using a bigger heap:
79     % $Pgm -C -H16m Foo.hs
80     # compile Haskell-produced C (.hc) to assembly language:
81     % $Pgm -S Foo.hc
82 ------------------------------------------------------------------------
83 EOUSAGE
84 \end{code}
85
86 %************************************************************************
87 %*                                                                      *
88 \section[Driver-init]{Initialisation}
89 %*                                                                      *
90 %************************************************************************
91
92 The driver script need to be told where to find these executables, so
93 in the course of building the driver `executable', make-variables holding
94 these are prepended to the de-litted version of this file. The variables are:
95
96 \begin{verbatim}
97 INSTALLING
98
99 HOSTPLATFORM TARGETPLATFORM
100
101 ProjectName ProjectVersion ProjectVersionInt ProjectPatchLevel 
102
103 HscMajorVersion HscMinorVersion CcMajorVersion CcMinorVersion
104
105 TOP_PWD
106
107 bindir libdir libexecdir datadir
108
109 CURRENT_DIR TMPDIR
110
111 GHC_LIB_DIR GHC_RUNTIME_DIR GHC_UTILS_DIR GHC_INCLUDE_DIR
112
113 GHC_OPT_HILEV_ASM GhcWithNativeCodeGen
114
115 GHC_UNLIT GHC_HSCPP GHC_HSC GHC_SYSMAN
116
117 CP RM CONTEXT_DIFF
118
119 WAY_*_NAME WAY_*_REAL_OPTS
120
121 LeadingUnderscore
122
123 \end{verbatim}
124
125 Establish what executables to run for the various phases, what the
126 default options are for those phases, and other similar boring stuff.
127
128 \begin{code}
129 select(STDERR); $| = 1; select(STDOUT); # no STDERR buffering, please.
130
131 $TargetPlatform = $TARGETPLATFORM;
132
133 $TopPwd            = "${TOP_PWD}";
134 $InstBinDirGhc     = "${bindir}";
135 $InstLibDirGhc     = "${libdir}";
136 #
137 # Normally the same as InstLibDirGhc, but we accommodate
138 # for it being separate.
139 #
140 $InstLibExecDirGhc = "${libexecdir}";
141 $InstDataDirGhc    = "${datadir}";
142
143 $Status  = 0; # just used for exit() status
144 $Verbose = '';
145
146 # set up signal handler
147 sub quit_upon_signal { &tidy_up_and_die(1, ''); }
148 $SIG{'INT'}  = 'quit_upon_signal';
149 $SIG{'QUIT'} = 'quit_upon_signal';
150
151 # where to get "require"d .prl files at runtime (poor man's dynamic loading)
152 #   (use LIB, not DATA, because we can't be sure of arch-independence)
153 @INC = ( ( $INSTALLING ) ? $InstLibDirGhc
154                            : "$TopPwd/${CURRENT_DIR}" );
155
156 if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
157     $Tmp_prefix = ($ENV{'TMPDIR'} . "/ghc$$");
158 } else {
159     print STDERR "TMPDIR has not been set to anything useful!\n" if (${TMPDIR} eq '');
160     $Tmp_prefix ="${TMPDIR}/ghc$$"; # TMPDIR set via Makefile when booting..
161     $ENV{'TMPDIR'} = ${TMPDIR}; # set the env var as well
162 }
163
164 # Some shells run into real trouble when command line and environment
165 # gets big (e.g., cmd lines of >4K to /bin/sh causes havoc on our 
166 # Solaris-2.5.1 boxes - even though sysconf(_SC_ARG_MAX) reports 1M ...).
167 # To work around any such */bin/sh* problems, we will scribble such
168 # awfully long command lines into a temp file and exec that temp file
169 # with $(REAL_SHELL) (don't use the SHELL variable directly as this
170 # will normally get you the wrong thing when the driver is invoked
171 # from within `make'). If the REAL_SHELL variable isn't set, you'll
172 # get SHELL. This is all a terrible hack. (in case you hadn't reached
173 # the same conclusion by now :-)
174 #
175 # TBC..
176 #
177 if ( ! $ENV{'REAL_SHELL'} ) {
178     $ENV{'REAL_SHELL'} = $ENV{'SHELL'};
179 }
180
181 @Files_to_tidy = (); # files we nuke in the case of abnormal termination
182
183 $Unlit = ( $INSTALLING ) ? "$InstLibExecDirGhc/unlit"
184                          : "$TopPwd/${CURRENT_DIR}/${GHC_UNLIT}";
185
186 $Cp   = $CP;
187 $Rm   = $RM;
188 $Diff = $CONTEXT_DIFF;
189 $Cat  = 'cat';
190 $Cmp  = 'cmp';
191 $Time = '';
192
193 $HsCpp   = # but this is re-set to "cat" (after options) if -cpp not seen
194            ( $INSTALLING ) ? "$InstLibExecDirGhc/hscpp"
195                            : "$TopPwd/${CURRENT_DIR}/${GHC_HSCPP}";
196
197 @HsCpp_flags    = ();
198 $HsC     = ( $INSTALLING ) ? "$InstLibExecDirGhc/hsc"
199                            : "$TopPwd/${CURRENT_DIR}/${GHC_HSC}";
200
201 # For PVM fiends only
202 $SysMan  = ( $INSTALLING ) ? "$InstLibExecDirGhc/SysMan"
203                            : "$TopPwd/${CURRENT_DIR}/${GHC_SYSMAN}";
204
205 @Unlit_flags    = ();
206
207 #
208 # HsC_rts_flags: if we want to talk to the LML runtime system
209 # NB: we don't use powers-of-2 sizes, because this may do
210 #   terrible things to cache behavior.
211 #
212 $Specific_heap_size = 6 * 1000 * 1000;
213 $Specific_stk_size  = 1000 * 1000;
214 $Scale_sizes_by     = 1.0;
215
216 \end{code}
217
218 The variables set by @setupOptFlags@ represent parts of the
219 -O/-O2/etc ``templates,'' which are filled in later, using these.
220 These are the default values, which may be changed by user flags.
221
222 \begin{code}
223 sub setupOptFlags {
224    $Oopt_MaxSimplifierIterations  = '-fmax-simplifier-iterations4';
225    $Oopt_PedanticBottoms          = '-fpedantic-bottoms'; # ON by default
226    $Oopt_FinalStgProfilingMassage = '';
227    $Oopt_StgStats                 = '';
228    $Oopt_DoSpecialise             = '-fspecialise';
229    $Oopt_FoldrBuild               = 0; # *Off* by default!
230    $Oopt_UsageSPInf               = ''; # Off by default
231 } # end of setupOptFlags
232
233 # Assign defaults to these right away.
234 &setupOptFlags();
235 \end{code}
236
237 Things to do with C compilers/etc:
238
239 (added -Wimplicit: implicit prototypes cause very hard-to-find
240 problems, so I'm turing on the warnings -- SDM 4/5/98)
241
242 \begin{code}
243 $CcRegd         = $GHC_OPT_HILEV_ASM;
244 @CcBoth_flags   = ('-S','-Wimplicit');   # flags for *any* C compilation
245 @CcInjects      = ();
246
247 # GCC flags: 
248 #    those for all files, 
249 #    those only for .c files;
250 #    those only for .hc files
251
252 @CcRegd_flags    = ();
253 @CcRegd_flags_c  = ();
254 @CcRegd_flags_hc = ();
255
256 $As              = ''; # "assembler" is normally GCC
257 @As_flags        = ();
258
259 $Lnkr            = ''; # "linker" is normally GCC
260 @Ld_flags        = ();
261 @Dll_flags       = ();
262
263 # 'nm' is used for consistency checking (ToDo: mk-world-ify)
264 # ToDo: check the OS or something ("alpha" is surely not the crucial question)
265 $Nm = ($TargetPlatform =~ /^alpha-/) ? 'nm -B' : 'nm';
266 \end{code}
267
268 Warning packages that are controlled by -W and -Wall.  The 'standard'
269 warnings that you get all the time are
270         
271         -fwarn-overlapping-patterns
272         -fwarn-missing-methods
273         -fwarn-duplicate-exports
274
275 these are turned off by -Wnot.
276
277 \begin{code}
278 @StandardWarnings = ('-fwarn-overlapping-patterns', 
279                      '-fwarn-missing-methods',
280                      '-fwarn-duplicate-exports');
281 @MinusWOpts       = (@StandardWarnings, 
282                      '-fwarn-incomplete-patterns', 
283                      '-fwarn-unused-binds',
284                      '-fwarn-unused-imports');
285 @MinusWallOpts    = (@MinusWOpts, 
286                      '-fwarn-unused-matches',
287                      '-fwarn-type-defaults',
288                      '-fwarn-name-shadowing',
289                      '-fwarn-missing-signatures');
290 \end{code}
291
292 What options \tr{-user-setup-a} turn into (user-defined ``packages''
293
294 of options).  Note that a particular user-setup implies a particular
295 Prelude ({\em including} its interface file(s)).
296 \begin{code}
297 $BuildTag       = ''; # default is sequential build w/ Appel-style GC
298
299 %BuildDescr     = (# system ways begin
300                    '',      'Normal Sequential',
301                    '_p',    "Profiling",
302                    '_t',    "Ticky-ticky Profiling",
303                    '_u',    "Unregisterised",
304                    '_mp',   "Parallel",
305                    '_mg',   "Gransim",
306                    # system ways end
307                    '_a',    "$WAY_a_NAME",
308                    '_b',    "$WAY_b_NAME",
309                    '_c',    "$WAY_c_NAME",
310                    '_d',    "$WAY_d_NAME",
311                    '_e',    "$WAY_e_NAME",
312                    '_f',    "$WAY_f_NAME",
313                    '_g',    "$WAY_g_NAME",
314                    '_h',    "$WAY_h_NAME",
315                    '_i',    "$WAY_i_NAME",
316                    '_j',    "$WAY_j_NAME",
317                    '_k',    "$WAY_k_NAME",
318                    '_l',    "$WAY_l_NAME",
319                    '_m',    "$WAY_m_NAME",
320                    '_n',    "$WAY_n_NAME",
321                    '_o',    "$WAY_o_NAME",
322                    '_A',    "$WAY_A_NAME",
323                    '_B',    "$WAY_B_NAME" );
324
325 # these are options that are "fed back" through the option processing loop
326 #
327 %SetupOpts = 
328        (
329         '_a', "$WAY_a_REAL_OPTS",
330         '_b', "$WAY_b_REAL_OPTS",
331         '_c', "$WAY_c_REAL_OPTS",
332         '_d', "$WAY_d_REAL_OPTS",
333         '_e', "$WAY_e_REAL_OPTS",
334         '_f', "$WAY_f_REAL_OPTS",
335         '_g', "$WAY_g_REAL_OPTS",
336         '_h', "$WAY_h_REAL_OPTS",
337         '_i', "$WAY_i_REAL_OPTS",
338         '_j', "$WAY_j_REAL_OPTS",
339         '_k', "$WAY_k_REAL_OPTS",
340         '_l', "$WAY_l_REAL_OPTS",
341         '_m', "$WAY_m_REAL_OPTS",
342         '_n', "$WAY_n_REAL_OPTS",
343         '_o', "$WAY_o_REAL_OPTS",
344         '_A', "$WAY_A_REAL_OPTS",
345         '_B', "$WAY_B_REAL_OPTS",
346
347         # system ways
348         '_p',  "-fscc-profiling -DPROFILING -optc-DPROFILING",
349         '_t',  "-fticky-ticky -DTICKY_TICKY -optc-DTICKY_TICKY",
350         '_u',  "-optc-DNO_REGS -optc-DUSE_MINIINTERPRETER -fno-asm-mangling -funregisterised",
351         '_mp', "-fstack-check -fparallel -D__PARALLEL_HASKELL__ -optc-DPAR",
352         '_mg', "-fstack-check -fconcurrent -fgransim -D__GRANSIM__ -D__CONCURRENT_HASKELL__ -optc-DCONCURRENT -optc-DGRAN");
353
354 \end{code}
355
356 Import/include directories (\tr{-I} options) are sufficiently weird to
357 require special handling.
358
359 \begin{code}
360 @Import_dir     = ('.'); #-i things
361 @Include_dir    = ('.'); #-I things; other default(s) stuck on AFTER option processing
362
363 # where to look for interface files (system hi's, i.e., prelude and syslibs)
364 @SysImport_dir  = ( $INSTALLING )
365                     ? ( "$InstLibDirGhc/imports/std" )
366                     : ( "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std" );
367
368 # We need to look in ghc/ and glaExts/ when searching for implicitly needed .hi files, but 
369 # we should really *not* look there for explicitly imported modules.
370
371 $Haskell1Version = 5; # i.e., Haskell 1.4
372 @Cpp_define      = ();
373
374 # Cpp symbols defined when we're processing Haskell source.
375
376 @HsSourceCppOpts = 
377         ( "-D__HASKELL1__=$Haskell1Version"
378         , "-D__GLASGOW_HASKELL__=$ProjectVersionInt"
379         , "-D__HASKELL98__"
380         , "-D__CONCURRENT_HASKELL__"
381         );
382
383 @UserLibrary_dir= ();   #-L things;...
384 @UserLibrary    = ();   #-l things asked for by the user
385
386 @SysLibrary_dir = ( ( $INSTALLING )     #-syslib things supplied by the system
387                     ? $InstLibDirGhc
388                     : ( "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR"
389                       , "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/gmp"
390                       , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std"
391                       , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std/cbits"
392                       )
393                   );
394 @SysLibrary = (); # will be built up as we go along
395
396 $TopClosureFile # defaults to 1.2 one; will be mangled later
397         = '';
398 #       ( $INSTALLING)  ? "$InstLibDirGhc/TopClosureXXXX.o"
399 #                         : "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/main/TopClosureXXXX.o";
400
401 # make depend for Haskell
402 $MkDependHS
403         = ( $INSTALLING ) ? "$InstLibExecDirGhc/mkdependHS"
404                           : "$TopPwd/$CURRENT_DIR/$GHC_UTILS_DIR/mkdependHS/mkdependHS";
405 # Fill in later
406 @MkDependHS_flags = ();
407
408 # do_link flag should not be reset while rescanning the cmd-line.
409 $Do_lnkr    = 1;
410 $Specific_output_dir = '';      # set by -odir <dir>
411 $Specific_output_file = '';     # set by -o <file>; "-" for stdout
412 \end{code}
413
414 Function to initialise the per-compilation-unit globals that
415 are used to guide and control the invocation of the different phases.
416
417 \begin{code} 
418 sub initDriverGlobals {
419
420 # reset the following options:
421 # RTS flags to use while compiling
422 @HsC_rts_flags      = ();
423 @HsC_flags      = ();
424 @HsC_antiflags  = ();
425 \end{code}
426
427 The optimisations/etc to be done by the compiler are {\em normally}
428 expressed with a \tr{-O} (or \tr{-O2}) flag, or by its absence.
429
430 \begin{code}
431 $OptLevel      = 0; # no -O == 0; -O == 1; -O2 == 2; -Ofile == 3
432 $MinusO2ForC   = 0; # set to 1 if -O2 should be given to C compiler
433 $StolenX86Regs = 4; # **HACK*** of the very worst sort
434 $CoreLint      = '';
435 $USPLint       = '';
436 $StgLint       = '';
437
438 @Import_dir     = ('.'); #-i things
439 @Include_dir    = ('.'); #-I things; other default(s) stuck on AFTER option processing
440
441
442 \end{code}
443
444 We are given a list of files with various presumably-known suffixes
445 (unknown-suffix files go straight to the linker).  For each file, we
446 begin by assuming that we'll run every phase over it.  However: (1)
447 global flags (\tr{-c}, \tr{-S}, etc.) tell us not to run any phase
448 past a certain point; and (2) the file's suffix tells us what phase to
449 start with.  Linking is weird and kept track of separately.
450
451 Here are the initial defaults applied to all files:
452 \begin{code}
453 $Cpp_flag_set = 0;        # (hack)
454 $Only_preprocess_C = 0;   # pretty hackish
455 $Only_preprocess_hc = 0;  # ditto
456 $Only_generate_deps = 0;  # ""
457 $Only_generate_dll  = 0;
458 $PostprocessCcOutput = 0;
459
460 # Win32 only:
461 #    static = 0 => produce code for DLLs (when compiling & linking.)
462 $Static = 1;
463 $Static = 0 if ($EnableWin32DLLs eq 'YES');
464
465 # native code-gen or via C?
466 $HaveNativeCodeGen = $GhcWithNativeCodeGen;
467 $HscOut = '-C='; # '-C=' ==> .hc output; '-S=' ==> .s output; '-N=' ==> neither
468 $HscOut = '-S='
469     if ($HaveNativeCodeGen ne 'YES') && $TargetPlatform =~ /^(alpha)-/;
470 # TEMP: disable x86 & Sparc if $HaveNativeCodeGen && $TargetPlatform =~ /^(i386|alpha|sparc)-/;
471 $ProduceHi    = '-hifile=';
472 $HiOnStdout   = 0;
473 $HiWith       = '';
474 $HiDiff_flag  = '';
475 $Keep_HiDiffs = 0;
476
477 $CollectingGCstats = 0;
478 $CollectGhcTimings = 0;
479 $DEBUGging = '';        # -DDEBUG and all that it entails (um... not really)
480 $PROFing = '';          # set to p or e if profiling
481 $PROFgroup = '';        # set to group if an explicit -Ggroup specified
482 $PROFauto = '';         # set to relevant hsc flag if -auto or -auto-all
483 $PROFcaf  = '';         # set to relevant hsc flag if -caf-all
484 $PROFdict = '';         # set to relevant hsc flag if -auto-dicts
485 $PROFignore_scc = '';   # set to relevant parser flag if explicit sccs ignored
486 $UNPROFscc_auto = '';   # set to relevant hsc flag if forcing auto sccs without profiling
487 $TICKYing = '';         # set to t if compiling for ticky-ticky profiling
488 $PARing = '';           # set to p if compiling for PAR
489 $GRANing = '';          # set to g if compiling for GRAN
490 $UNREGing = '';         # set to u if compiling unregisterised
491 $Specific_hi_file = '';         # set by -ohi <file>; "-" for stdout
492 $Specific_dump_file = '';       # set by -odump <file>; "-" for stdout
493 $Using_dump_file = 0;
494 $Isuffix    = '';
495 $Osuffix    = '';       # default: use the normal suffix for that kind of output
496 $HiSuffix   = 'hi';
497 $HiSuffix_prelude = '';
498 $CompilingPrelude=0;
499 $Do_recomp_chkr = 0;    # don't use the recompilatio checker unless asked
500 $Do_cc      = -1;   # a MAGIC indeterminate value; will be set to 1 or 0.
501 $Do_as      = 1;
502
503 $Keep_hc_file_too = 0;
504 $Keep_s_file_too = 0;
505 $UseGhcInternals = 0; # if 1, may use GHC* modules
506 $SplitObjFiles = 0;
507 $DoAsmMangling = 1; # on by default, off by -fno-asm-mangling
508 $NoOfSplitFiles = 0;
509 $Dump_parser_output = 0;
510 $Dump_raw_asm = 0;
511 $Dump_asm_splitting_info = 0;
512 $NoImplicitPrelude = 0;
513 # 1 => don't tell the linker to hoist in PrelMain.Main, as an 
514 # external main is provided instead.
515 $NoHaskellMain=0;
516
517 } # end of initDriverGlobals (Sigh)
518
519 # we split the argv passed to the driver into three:
520
521 # the list of files
522 @Input_file = ();
523
524 # and files to be linked...
525 @Link_file  = ();
526
527 # and whatever else
528 @Cmd_opts  = ();
529
530 # cmd line options prefixing the unit we're compiling
531 @File_options = ();
532
533 \end{code}
534
535 We inject consistency-checking information into \tr{.hc} files (both
536 when created by the Haskell compiler and when compiled by the C
537 compiler), so that we can check that an executable is made from
538 consistently-built pieces.  (The check is normally done just after
539 linking.)  The checking is done by introducing/munging
540 \tr{what(1)}-style strings.  Anyway, here are the relevant global
541 variables and their defaults:
542 \begin{code}
543 $LinkChk = 0;   # set to 0 if the link check should *not* be done
544
545 # major & minor version numbers; major numbers must always agree;
546 # minor disagreements yield a warning.
547 $HsC_major_version = $HscMajorVersion;
548 $HsC_minor_version = $HscMinorVersion;
549 $Cc_major_version  = $CcMajorVersion;
550 $Cc_minor_version  = $CcMinorVersion;
551
552 # options: these must always agree
553 $HsC_consist_options = '';    # we record, in this order:
554                               #     Build tag; debugging?
555 $Cc_consist_options  = '';    # we record, in this order:
556                               #     Build tag; debugging?
557 \end{code}
558
559 %************************************************************************
560 %*                                                                      *
561 \section[Driver-parse-argv]{Munge the command-line options}
562 %*                                                                      *
563 %************************************************************************
564
565 Now slurp through the arguments.
566 \begin{code}
567
568 &initDriverGlobals();
569 &splitCmdLine(@ARGV);
570 # Run through the cmd-line first time.
571 &processArgs(@Cmd_opts);
572
573 # Check to see if driver is only in the business
574 # to generate dependencies
575 if (  $Status == 0 && $Only_generate_deps ) {
576
577     push (@MkDependHS_flags, "-o$Osuffix") if $Osuffix;
578     push (@MkDependHS_flags, "-s$BuildTag") if $BuildTag;
579     # They're not (currently) needed, but we need to quote any -#include options
580     foreach (@Cmd_opts) {
581         s/-#include.*$/'$&'/g;
582     };
583     local($to_do) = "$MkDependHS @MkDependHS_flags @HsSourceCppOpts -- @Cmd_opts -- @Input_file" ;
584     &run_something($to_do, 'Haskell dependencies');
585     exit $Status;
586 }
587
588 # ..or just to construct a (Haskell) DLL.
589 if (  $Status == 0 && $Only_generate_dll && $EnableWin32DLLs ) {
590
591     &createWin32DLL();
592     exit $Status;
593 }
594
595 # if there are several input files,
596 # we don't allow \tr{-o <file>} or \tr{-ohi <file>} options...
597 # (except if linking, of course)
598
599 if ($#Input_file > 0 && ( ! $Do_lnkr )) {
600     if ( ($Specific_output_file ne '' && $Specific_output_file ne '-')
601       || ($Specific_hi_file ne ''     && $Specific_hi_file ne '-') ) {
602         print STDERR "$Pgm: You can't use -o or -ohi options if you have multiple input files.\n";
603         print STDERR "\tPerhaps the -odir option will do what you want.\n";
604         $Status++;
605     }
606 }
607
608 # check for various pathological -o and -odir combinations...
609 if ($Specific_output_dir ne '' && $Specific_output_file ne '') {
610     if ($Specific_output_file eq '-') {
611         print STDERR "$Pgm: can't set output directory with -ohi AND have output to stdout\n";
612         $Status++;
613     } else { # amalgamate...
614         $Specific_output_file = "$Specific_output_dir/$Specific_output_file";
615         # ToDo: check we haven't got a junk name now...
616         $Specific_output_dir  = ''; # reset
617     }
618 }
619
620 # crash and burn if there were errors
621 if ( $Status > 0 ) {
622     print STDERR $ShortUsage;
623     exit $Status;
624 }
625 \end{code}
626
627 %************************************************************************
628 %*                                                                      *
629 \section[Driver-post-argv-mangling]{Setup after reading options}
630 %*                                                                      *
631 %************************************************************************
632
633 %************************************************************************
634 %*                                                                      *
635 \subsection{Set up for optimisation level (\tr{-O} or whatever)}
636 %*                                                                      *
637 %************************************************************************
638
639 We come now to the default ``wads of options'' that are turned on by
640 \tr{-O0} (do min optimisation), \tr{-O} (ordinary optimisation),
641 \tr{-O2} (aggressive optimisation), or no O-ish flag (compile speed is
642 more important).
643
644 The user can also specify his/her own list of options in a file; in
645 that case, the work is already done (see stuff about @minusO3@,
646 earlier...).
647
648 GHC allows very precise control of what happens during a compilation.
649 Core-to-Core and STG-to-STG passes can be run in any order, as many
650 times as you like.  Individual transformations can be turned on or
651 disabled.
652
653 Sadly, however, there are some interdependencies \& Things You Must
654 Not Do.  Here is the list.
655
656 CORE-TO-CORE PASSES:
657 \begin{description}
658 \item[\tr{-fspecialise}:]
659 The specialiser must have dependency-analysed input; but if you run
660 the simplifier to do this, you must not let it toss away unused
661 bindings!  (The typechecker conveys some specialisation info via
662 ``unused'' bindings...)
663
664 \item[\tr{-ffloat-inwards}:]
665 Floating inwards should be done before strictness analysis, because
666 the latter will give better results.
667
668 \item[\tr{-fstatic-args}:]
669 The static-arguments-transformation pass {\em must} have the
670 simplifier run right after it.
671
672 \item[\tr{-fcalc-inlinings[12]}:]
673 Not required, but there may be slight gains by re-simplifying after
674 this is done.  (You could then \tr{-fcalc-inlinings} again, just for
675 fun.)
676
677 \item[\tr{-ffull-laziness}:]
678 The (outwards-)let-floater should be the {\em last} Core-to-Core pass
679 that's run.  (Um, well, howzabout the simplifier just once more...)
680 \end{description}
681
682 STG-TO-STG PASSES:
683 \begin{description}
684 \item[\tr{-fupdate-analysis}:]
685 It really really wants to be the last STG-to-STG pass that is run.
686 \end{description}
687
688 \begin{code}
689
690 sub setupOptimiseFlags {
691
692         # this pass-ordering sequence was agreed by Simon and Andr\'e
693         # (WDP 94/07, 94/11).
694
695    @HsC_minusNoO_flags 
696     = ( 
697         '-fsimplify',
698           '[', 
699                 '-finline-phase2',
700                 $Oopt_MaxSimplifierIterations,
701           ']',
702
703         $Oopt_AddAutoSccs,
704         $Oopt_FinalStgProfilingMassage
705       );
706
707    @HsC_minusO_flags # NOTE: used for *both* -O and -O2 (some conditional bits)
708     = (
709         '-ffoldr-build-on',
710
711         '-fdo-eta-reduction',
712         '-fdo-case-elim',
713         '-fdo-lambda-eta-expansion',
714         '-fcase-of-case',
715         '-fcase-merge',
716         '-flet-to-case',
717         $Oopt_PedanticBottoms,
718
719         # initial simplify: mk specialiser happy: minimum effort please
720
721         '-fsimplify',
722           '[', 
723           '-finline-phase1',            # Don't inline rule Ids till specialisation has bitten
724
725 #               APR 99: the stuff in this comment is now
726 #               handled by -finline-phase1
727 #
728 # I don't understand why we want -fessential-unfoldings-only here
729 # If we have it, the following nasty thing happens:
730 #       f  = E
731 #       g* = f
732 #       ...g...
733 # where "*" means exported.
734 # In the essential-unfoldings pass we still substitute f for g
735 # but we don't substitute E for f first.  So we get
736 #       f  = E
737 #       g* = f
738 #       ...f...
739 # The g=f will get reverse-substituted later, but it's untidy. --SLPJ
740 #
741 # SDM: Here's why it's necessary.
742 #
743 #   If we unfold in the first pass before the specialiser is run
744 #   we miss opportunities for specialisation because eg. wrappers
745 #   have been inlined for specialisable functions.  
746 #
747 #   This shows up in PrelArr.lhs - the specialised instance for newArray 
748 #   calls the generic rangeSize, because rangeSize is strict and is
749 #   replaced by its wrapper by the simplifier.
750 #         '-fessential-unfoldings-only',
751 #         '-fsimpl-uf-use-threshold0',
752
753           '-fmax-simplifier-iterations2',
754           ']',
755
756         ($Oopt_DoSpecialise) ? ( $Oopt_DoSpecialise, ) : (),
757
758         $Oopt_UsageSPInf, # infer usage information here in case we need it later.
759                           # (add more of these where you need them --KSW 1999-04)
760
761         '-fsimplify',
762           '[', 
763                 $Oopt_MaxSimplifierIterations,  
764
765                 # Still don't inline transformation rule Ids, to give the
766                 # rules a good chance to fire
767                 '-finline-phase1',
768           ']',
769
770         '-ffull-laziness',
771
772         '-ffloat-inwards',
773
774         '-fsimplify',
775           '[', 
776                 '-finline-phase2',
777                 $Oopt_MaxSimplifierIterations,  
778           ']',
779
780         '-fstrictness',
781         # '-fcpr-analyse',
782         '-fworker-wrapper',
783
784         '-fsimplify',
785           '[', 
786                 $Oopt_MaxSimplifierIterations,  
787                 # No -finline-phase: allow all Ids to be inlined now
788           ']',
789
790         '-ffloat-inwards',
791
792 # Case-liberation for -O2.  This should be after
793 # strictness analysis and the simplification which follows it.
794
795 #       ( ($OptLevel != 2)
796 #        ? ''
797 #       : "-fliberate-case -fsimplify [ $Oopt_FB_Support -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fcase-merge -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_PedanticBottoms $Oopt_MaxSimplifierIterations $Oopt_ShowSimplifierProgress ]" ),
798
799 # Final clean-up simplification:
800
801         '-fsimplify',
802           '[', 
803                 $Oopt_MaxSimplifierIterations,  
804           ']',
805
806       # '-fstatic-args',
807
808       # stg2stg passes
809 #       '-flambda-lift',
810         $Oopt_FinalStgProfilingMassage,
811         $Oopt_StgStats,
812
813       # flags for stg2stg
814         '-flet-no-escape',
815
816       # SPECIAL FLAGS for -O2
817         ($OptLevel == 2) ? (
818           '-fupdate-analysis',  # virtually useless; relegated to -O2
819           '-fsemi-tagging',
820         ) : (),
821       );
822
823 \end{code}
824
825 Sort out what we're going to do about optimising.  First, the @hsc@
826 flags and regular @cc@ flags to worry about:
827 \begin{code}
828 if ( $OptLevel <= 0 ) {
829
830     # for this level, we tell the parser -fignore-interface-pragmas
831     push(@HsC_flags, '-fignore-interface-pragmas');
832     # and tell the compiler not to produce them
833     push(@HsC_flags, '-fomit-interface-pragmas');
834
835     &add_Hsc_flags( @HsC_minusNoO_flags );
836     push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O'); # not optional!
837
838 } elsif ( $OptLevel == 1 || $OptLevel == 2 ) {
839
840     &add_Hsc_flags( @HsC_minusO_flags );
841     push(@CcBoth_flags, ($MinusO2ForC || $OptLevel == 2) ? '-O2' : '-O'); # not optional!
842     # -O? to GCC is not optional! -O2 probably isn't worth it generally,
843     # but it *is* useful in compiling the garbage collector.
844
845 } else { # -Ofile, then...
846
847     &add_Hsc_flags( @HsC_minusO3_flags );
848     push(@HsC_flags, $Oopt_FinalStgProfilingMassage) if $Oopt_FinalStgProfilingMassage;
849
850     push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O'); # possibly to be elaborated...
851 }
852
853 } # setupOptimiseFlags
854
855 \end{code}
856
857 %************************************************************************
858 %*                                                                      *
859 \subsection{Check for consistency, etc.}
860 %*                                                                      *
861 %************************************************************************
862
863 Sort out @$BuildTag@, @$PROFing@, @$PARing@,
864 @$GRANing@, @$TICKYing@, @UNREGing@:
865 \begin{code}
866 sub setupBuildFlags {
867
868
869    # PROFILING stuff after argv mangling:
870    if ( ! $PROFing ) {
871      # add -auto sccs even if not profiling !
872      push(@HsC_flags, $UNPROFscc_auto) if $UNPROFscc_auto;
873
874    } else {
875       push(@HsC_flags, $PROFauto) if $PROFauto;
876       push(@HsC_flags, $PROFcaf)  if $PROFcaf;
877       push(@HsC_flags, $PROFdict) if $PROFdict;
878
879       $Oopt_FinalStgProfilingMassage = '-fmassage-stg-for-profiling';
880
881       # Ignore user sccs when auto annotating, but warn when doing so.
882       $PROFignore_scc = '-W' if $PROFauto; 
883   }
884   #if ( $BuildTag ne '' ) {
885   #    local($b) = $BuildDescr{$BuildTag};
886   #    if ($PARing    eq 'p') { print STDERR "$Pgm: Can't mix $b with -parallel.\n"; exit 1; }
887   #    if ($GRANing   eq 'g') { print STDERR "$Pgm: Can't mix $b with -gransim.\n"; exit 1; }
888   #    if ($TICKYing  eq 't') { print STDERR "$Pgm: Can't mix $b with -ticky.\n"; exit 1; }
889
890   #    # ok to have a user-way profiling build
891   #    # eval the profiling opts ... but leave user-way BuildTag 
892   #    if ($PROFing   eq 'p') { &processArgs(split(' ', $SetupOpts{'_p'})); } # eval($EvaldSetupOpts{'_p'}); }
893
894   if ( $PROFing eq 'p' ) {
895       if ($PARing   eq 'p') { print STDERR "$Pgm: Can't do profiling with -parallel.\n"; exit 1; }
896       if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't do profiling with -gransim.\n"; exit 1; }
897       if ($TICKYing eq 't') { print STDERR "$Pgm: Can't do profiling with -ticky.\n"; exit 1; }
898       $BuildTag = '_p' ;
899
900   } elsif ( $PARing eq 'p' ) {
901       if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't mix -parallel with -gransim.\n"; exit 1; }
902       if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -parallel with -ticky.\n"; exit 1; }
903       $BuildTag = '_mp';
904
905       if ( $Do_lnkr && ( ! $ENV{'PVM_ROOT'} || ! $ENV{'PVM_ARCH'} )) {
906           print STDERR "$Pgm: both your PVM_ROOT and PVM_ARCH environment variables must be set for linking under -parallel.\n";
907           exit(1);
908       }
909
910   } elsif ( $GRANing eq 'g' ) {
911       if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -gransim with -ticky.\n"; exit 1; }
912       $BuildTag = '_mg';
913
914   } elsif ( $TICKYing eq 't' ) {
915       $BuildTag = '_t';
916
917   } elsif ( $UNREGing eq 'u' ) {
918       $BuildTag = '_u';
919   }
920
921 \end{code}
922
923 After the sanity checks, add flags to the necessary parts of the driver pipeline:
924
925 \begin{code}
926   if ( $BuildTag ne '' ) { # something other than normal sequential...
927
928       local($Tag) = "${BuildTag}";
929       $Tag =~ s/_//;  # move the underscore to the back
930
931       $HscOut = '-C='; # must go via C
932       &processArgs(split(' ', $SetupOpts{$BuildTag}));
933 #      eval($EvaldSetupOpts{$BuildTag});
934   }
935 \end{code}
936
937 Decide what the consistency-checking options are in force for this run:
938 \begin{code}
939
940   $HsC_consist_options = "${BuildTag},${DEBUGging}";
941   $Cc_consist_options  = "${BuildTag},${DEBUGging}";
942
943   #
944   # Funny place to put it, but why not.
945   #
946   if ( $HiSuffix_prelude eq '' ) {
947
948        if ($CompilingPrelude) {
949          $HiSuffix_prelude = "$HiSuffix" if $CompilingPrelude;
950        } else {
951          local($Tag) = "${BuildTag}";
952   
953          $Tag =~ s/_//;
954          $Tag =  "${Tag}_" if $Tag ne '';
955          $HiSuffix_prelude="${Tag}hi";
956        }
957   }
958 } # setupBuildFlags
959 \end{code}
960
961 %************************************************************************
962 %*                                                                      *
963 \subsection{Add on machine-specific C-compiler flags}
964 %*                                                                      *
965 %************************************************************************
966
967 Shove on magical machine-specific options.  We use \tr{unshift} to
968 stick them on the {\em front} of the arrays, so that ``later''
969 user-specified flags can clobber them (e.g., \tr{-U__STG_REV_TBLS__}).
970
971 Note: a few ``always apply'' flags were set at the very beginning.
972
973 \begin{code}
974 sub setupMachOpts {
975
976   if ($TargetPlatform =~ /^alpha-/) {
977       unshift(@CcBoth_flags,  ('-static'));
978
979   } elsif ($TargetPlatform =~ /^hppa/) {
980       unshift(@CcBoth_flags,  ('-static'));
981       #
982       # We don't put in '-mlong-calls', because it's only
983       # needed for very big modules (sigh), and we don't want
984       # to hobble ourselves further on all the other modules
985       # (most of them).
986       #  
987       # [Dated comment (gcc-2.6.x?), -mlong-calls is no longer
988       #  a supported gcc HPPA flag]
989       unshift(@CcBoth_flags,  ('-D_HPUX_SOURCE'));
990         # ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
991         # (very nice, but too bad the HP /usr/include files don't agree.)
992
993   } elsif ($TargetPlatform =~ /^i386-/) {
994       # -fno-defer-pop : basically the same game as for m68k
995       #
996       # -fomit-frame-pointer : *must* in .hc files; because we're stealing
997       #  the fp (%ebp) for our register maps.
998
999       unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1000       unshift(@CcRegd_flags_hc, '-fomit-frame-pointer');
1001       unshift(@CcRegd_flags,    "-DSTOLEN_X86_REGS=$StolenX86Regs");
1002       
1003       unshift(@CcBoth_flags,  ('-DDONT_WANT_WIN32_DLL_SUPPORT')) if ($Static);
1004
1005   } elsif ($TargetPlatform =~ /^m68k-/) {
1006       # -fno-defer-pop : for the .hc files, we want all the pushing/
1007       #    popping of args to routines to be explicit; if we let things
1008       #    be deferred 'til after an STGJUMP, imminent death is certain!
1009       #
1010       # -fomit-frame-pointer : *don't*
1011       #    It's better to have a6 completely tied up being a frame pointer
1012       #    rather than let GCC pick random things to do with it.
1013       #    (If we want to steal a6, then we would try to do things
1014       #    as on iX86, where we *do* steal the frame pointer [%ebp].)
1015
1016       unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1017       unshift(@CcRegd_flags,    '-fno-omit-frame-pointer');
1018         # maybe gives reg alloc a better time
1019         # also: -fno-defer-pop is not sufficiently well-behaved without it
1020
1021   } elsif ($TargetPlatform =~ /^mips-/) {
1022       unshift(@CcBoth_flags,  ('-static'));
1023
1024   } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
1025       unshift(@CcBoth_flags,  ('-static')); # always easier to start with
1026       unshift(@CcRegd_flags, ('-finhibit-size-directive')); # avoids traceback tables
1027   } elsif ($TargetPlatform =~ /^sparc-/) {
1028   }
1029 } # end of setupMachOpts
1030 \end{code}
1031
1032 %************************************************************************
1033 %*                                                                      *
1034 \subsection{Set up for warnings}
1035 %*                                                                      *
1036 %************************************************************************
1037
1038 Several warnings are turned on by default.  These are supposed to be
1039 the 'I'm pretty sure you've made a mistake here' kind of warnings.
1040 The rest are turned on by the -W and -Wall options, or individually
1041 via their -fwarn and -fno-warn flags.
1042
1043 \begin{code}
1044 sub setupWarningFlags {
1045 &add_Hsc_flags( @StandardWarnings );
1046 }
1047 \end{code}
1048
1049 Same unshifting magic, but for special linker flags.
1050
1051 The configure script determines whether the object file symbol tables
1052 have a leading underscore, and sets @LeadingUnderscore@ accordingly.
1053 (The driver script `sees' the setting of the @LeadingUnderscore@
1054 by having the Makefile prepend it).
1055
1056 \begin{code}
1057 sub setupLinkOpts {
1058   local($uscore) = ( ${LeadingUnderscore} eq 'YES' ) ? '_' : '';
1059
1060   unshift(@Ld_flags,
1061         (($Ld_main) ? ( '-u', "${uscore}Main_" . $Ld_main . '_closure' ) : ()));
1062
1063   # things that are referenced by the RTS - make sure that we pull 'em in
1064   unshift(@Ld_flags,
1065          ( '-u', "${uscore}PrelBase_Izh_static_info"
1066           ,'-u', "${uscore}PrelBase_Czh_static_info"
1067           ,'-u', "${uscore}PrelBase_Fzh_static_info"
1068           ,'-u', "${uscore}PrelBase_Dzh_static_info"
1069           ,'-u', "${uscore}PrelAddr_Azh_static_info"
1070           ,'-u', "${uscore}PrelAddr_Wzh_static_info"
1071           ,'-u', "${uscore}PrelAddr_I64zh_static_info"
1072           ,'-u', "${uscore}PrelAddr_W64zh_static_info"
1073           ,'-u', "${uscore}PrelStable_StablePtr_static_info"
1074           ,'-u', "${uscore}PrelBase_Izh_con_info"
1075           ,'-u', "${uscore}PrelBase_Czh_con_info"
1076           ,'-u', "${uscore}PrelBase_Fzh_con_info"
1077           ,'-u', "${uscore}PrelBase_Dzh_con_info"
1078           ,'-u', "${uscore}PrelAddr_Azh_con_info"
1079           ,'-u', "${uscore}PrelAddr_Wzh_con_info"
1080           ,'-u', "${uscore}PrelAddr_I64zh_con_info"
1081           ,'-u', "${uscore}PrelAddr_W64zh_con_info"
1082           ,'-u', "${uscore}PrelStable_StablePtr_con_info"
1083           ,'-u', "${uscore}PrelBase_False_static_closure"
1084           ,'-u', "${uscore}PrelBase_True_static_closure"
1085           ,'-u', "${uscore}PrelPack_unpackCString_closure"
1086           ,'-u', "${uscore}PrelException_stackOverflow_closure"
1087           ,'-u', "${uscore}PrelException_heapOverflow_closure"
1088         ));
1089   if (!$NoHaskellMain) {
1090    unshift (@Ld_flags,'-u', "${uscore}PrelMain_mainIO_closure");
1091   }
1092   if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
1093     # sometimes we have lots of toc entries...
1094     #  unshift(@Ld_flags, ('-Xlinker -bbigtoc -Xlinker -bnoquiet')); 
1095     unshift(@Ld_flags, ('-Xlinker -bbigtoc')); 
1096   }
1097
1098
1099 } # end of setupLinkOpts
1100
1101 \end{code}
1102
1103 %************************************************************************
1104 %*                                                                      *
1105 \subsection{Set up include paths and system-library enslurpment}
1106 %*                                                                      *
1107 %************************************************************************
1108
1109 Now that we know what garbage-collector, etc., are required, we can
1110 finalise our list of libraries to slurp through, and generally Get
1111 Ready for Business.
1112
1113 \begin{code}
1114 sub setupIncPaths {
1115   # default includes must be added AFTER option processing
1116   if ( ! $INSTALLING ) {
1117       push (@Include_dir, "$TopPwd/${CURRENT_DIR}/${GHC_INCLUDE_DIR}");
1118   } else {
1119       push (@Include_dir, "$InstLibDirGhc/includes");
1120       push (@Include_dir, "$InstLibDirGhc/includes");
1121   }
1122 } # end of setupIncPaths
1123 \end{code}
1124
1125 \begin{code}
1126 sub setupSyslibs {
1127   push(@SysLibrary, ( '-lHS', '-lHS_cbits' )); # basic I/O and prelude stuff
1128
1129   local($f);
1130   foreach $f (@SysLibrary) {
1131       next if $f =~ /_cbits/;
1132       $f .= $BuildTag if $f =~ /^-lHS/;
1133   }
1134
1135   # Push library HSrts, plus boring clib bit
1136   push(@SysLibrary, "-lHSrts${BuildTag}");
1137
1138   #
1139   # RTS compiled with cygwin32, uses the WinMM API
1140   # to implement the itimers, since cygwin.dll does not
1141   # support it. Only reqd. for `ways' that use itimers.
1142   #
1143   push(@SysLibrary, '-lwinmm')   if $TargetPlatform eq 'i386-unknown-cygwin32';
1144    # Note: currently only tested with mingw, may cause conflicts when linking
1145    #       with libcygwin.a
1146   push(@SysLibrary, '-lwsock32') if ($TargetPlatform =~ /-(mingw32|cygwin32)$/);
1147
1148   # Push the pvm libraries
1149   if ($BuildTag eq '_mp') {
1150       $pvmlib = "$ENV{'PVM_ROOT'}/lib/$ENV{'PVM_ARCH'}";
1151       push(@SysLibrary, "-L$pvmlib", '-lgpvm3', '-lpvm3');
1152       if ( $ENV{'PVM_ARCH'} eq 'SUNMP' ) {
1153           push(@SysLibrary, '-lthread', '-lsocket', '-lnsl');
1154       } elsif ( $ENV{'PVM_ARCH'} eq 'SUN4SOL2' ) {
1155           push(@SysLibrary, '-lsocket', '-lnsl');
1156       }
1157   }
1158
1159 # Push the GNU multi-precision arith lib; and the math library
1160
1161 # If this machine has GMP already installed, then we'll get the installed
1162 # lib here, because presumably the one in the tree won't have been built.
1163
1164 if ($LibGmp eq 'not-installed') {
1165   push(@SysLibrary, "-lgmp");
1166 } else {
1167   push(@SysLibrary, "-l$LibGmp");
1168 }
1169
1170 push(@SysLibrary, '-lm') if !( $TargetPlatform =~ /^.*(cygwin32|mingw32)$/ );
1171 \end{code}
1172
1173 %************************************************************************
1174 %*                                                                      *
1175 \subsection{Check that this system was built to do what we are asking}
1176 %*                                                                      *
1177 %************************************************************************
1178
1179 Before continuing we check that the appropriate build is available.
1180
1181 \begin{code}
1182 #die "$Pgm: no BuildAvail?? $BuildTag\n" if $BuildDescr{$BuildTag} eq '' ; # sanity
1183
1184 if ( $BuildDescr{$BuildTag} eq '' ) {
1185     print STDERR "$Pgm: a `", $BuildDescr{$BuildTag},
1186         "' \"build\" is not available with your GHC setup.\n";
1187     print STDERR "(It was not configured for it at your site.)\n";
1188     print STDERR $ShortUsage;
1189     exit 1;
1190 }
1191
1192 } # end of setupSyslibs
1193
1194 \end{code}
1195
1196 %************************************************************************
1197 %*                                                                      *
1198 \subsection{Final miscellaneous setup bits before we start going}
1199 %*                                                                      *
1200 %************************************************************************
1201
1202 Record largest specific heapsize, if any.
1203 \begin{code}
1204 sub setupHeapStackSize {
1205    $Specific_heap_size = $Specific_heap_size * $Scale_sizes_by;
1206    push(@HsC_rts_flags, '-H'.$Specific_heap_size);
1207    $Specific_stk_size = $Specific_stk_size * $Scale_sizes_by;
1208    push(@HsC_rts_flags, "-K$Specific_stk_size");
1209 }
1210 \end{code}
1211
1212 If no input or link files seen, then we let 'em feed in stdin; this is
1213 mainly for debugging.
1214
1215 \begin{code}
1216
1217 if ($#Input_file < 0 && $#Link_file < 0) {
1218     @Input_file = ( '-' );
1219
1220     open(INF, "> $Tmp_prefix.hs") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.hs\n");
1221     print STDERR "Enter your Haskell program, end with ^D (on a line of its own):\n" if -t;
1222     while (<STDIN>) { print INF $_; }
1223     close(INF) || &tidy_up_and_die(1,"Failed writing to $Tmp_prefix.hs\n");
1224 }
1225
1226 \end{code}
1227
1228 Tell the world who we are, if they asked.
1229 \begin{code}
1230 print STDERR "${ProjectName}, version ${ProjectVersion}, patchlevel ${ProjectPatchLevel}\n"
1231     if $Verbose;
1232 \end{code}
1233
1234 %************************************************************************
1235 %*                                                                      *
1236 \section[Driver-main-loop]{Main loop: Process input files, and link if required}
1237 %*                                                                      *
1238 %************************************************************************
1239
1240 Process the input files; don't continue with linking if there are
1241 problems (global variable @$Status@ non-zero).
1242 \begin{code}
1243 foreach $ifile (@Input_file) {
1244     &ProcessInputFile($ifile);
1245 }
1246
1247 # don't link if there were errors...
1248 if ( $Status > 0 ) { 
1249     print STDERR $ShortUsage;
1250     &tidy_up();
1251     exit $Status;
1252 }
1253
1254 # Link if appropriate.
1255 &runLinker() if $Do_lnkr;
1256
1257 # that...  that's all, folks!
1258 &tidy_up();
1259 exit $Status; # will still be 0 if all went well
1260 \end{code}
1261
1262 %************************************************************************
1263 %*                                                                      *
1264 \section[Driver-do-one-file]{How to process a single input file}
1265 %*                                                                      *
1266 %************************************************************************
1267
1268 \begin{code}
1269 sub ProcessInputFile {
1270     local($ifile) = @_;   # input file name
1271     local($ifile_root);   # root of or basename of input file
1272     local($ofile_target); # ultimate output file we hope to produce
1273                           # from input file (need to know for recomp
1274                           # checking purposes)
1275     local($hifile_target);# ditto (but .hi file)
1276     local($ofile_c_stub_target); 
1277     local($ofile_h_stub_target); 
1278 \end{code}
1279
1280 Handle the weirdity of input from stdin.
1281 \begin{code}
1282     if ($ifile ne '-') {
1283         ($ifile_root  = $ifile) =~ s/\.[^\.\/]+$//;
1284         $ofile_target = # may be reset later...
1285                         ($Specific_output_file ne '' && ! $Do_lnkr)
1286                         ? $Specific_output_file
1287                         : &odir_ify($ifile_root, 'o');
1288         $hifile_target= ($Specific_hi_file ne '')
1289                         ? $Specific_hi_file
1290                         : "$ifile_root.$HiSuffix"; # ToDo: odirify?
1291                         # NB: may change if $ifile_root isn't module name (??)
1292         ($ofile_c_stub_target = $ifile) =~s/\.[^\.\/]+$/_stub.c/;
1293         ($ofile_h_stub_target = $ifile) =~s/\.[^\.\/]+$/_stub.h/;
1294     } else {
1295         $ifile = "$Tmp_prefix.hs"; # we know that's where we put the input
1296         $ifile_root   = '_stdin';
1297         $ofile_target = '_stdout'; # gratuitous?
1298         $hifile_target= '_stdout'; # ditto?
1299     }
1300 \end{code}
1301
1302 We need to decide what phases of the compilation system we will run
1303 over this file.  The defaults are the ones established when processing
1304 flags.  (That established what the last phase run for all files is.)
1305
1306 We do the pre-recompilation-checker phases here; the rest later.
1307 \begin{code}
1308 \end{code}
1309
1310 Look at the suffix and decide what initial phases of compilation may
1311 be dropped off for this file.  Also the rather boring business of
1312 which files are coming-in/going-out.
1313
1314 Again, we'll do the post-recompilation-checker parts of this later.
1315 \begin{code}
1316     local($do_lit2pgm)  = ($ifile =~ /\.lhs$/) ? 1 : 0;
1317     local($do_hscpp)    = 1; # but "hscpp" might really be "cat"
1318     local($do_hsc)      = 1;
1319
1320     # names of the files to stuff between phases
1321     # defaults are temporaries
1322     local($in_lit2pgm)    = $ifile;
1323     local($lit2pgm_hscpp) = "$Tmp_prefix.lpp";
1324     local($hscpp_hsc)     = "$Tmp_prefix.cpp";
1325     local($hsc_hi)        = "$Tmp_prefix.hi";
1326     local($cc_as_o)       = "${Tmp_prefix}_o.s"; # temporary for raw .s file if opt C
1327     local($cc_as)         = "$Tmp_prefix.s";     # mangled or hsc-produced .s code
1328     local($as_out)        = $ofile_target;
1329
1330     local($is_hc_file) = 1; #Is the C code .hc or .c? Assume .hc for now
1331
1332     # OK, let's strip off some literate junk..
1333     if ($do_lit2pgm) {
1334         &runLit2pgm($in_lit2pgm, $lit2pgm_hscpp)
1335     } else {
1336         $lit2pgm_hscpp = $ifile;
1337     }
1338
1339     #
1340     @File_options = ();
1341
1342     # Scan the top of the de-litted file for {-# OPTIONS #-} pragmas
1343     &check_for_source_options($lit2pgm_hscpp,$ifile);
1344
1345     # Options found in the source file take a back seat, i.e., we scan
1346     # them first. Only process the command line again if source file
1347     # contained anything of interest *or* there's more than one
1348     # input file (we have to reset the options).
1349     #
1350     if ( $#Input_file >= 0 || $#File_options >= 0) {
1351         #@File_options = (@File_options, @Cmd_opts);
1352
1353         # Now process the command line
1354         &initDriverGlobals();
1355         &processArgs((@File_options,@Cmd_opts));
1356         print STDERR "\nEffective command line: " .
1357                      join(' ',(@File_options,@Cmd_opts)) . "\n" if $Verbose;
1358     }
1359     #
1360     # Having got the effective command line scanned, set up
1361     # the various options in prep for some real work.
1362     #
1363     # check the sanity of the BuildTag we're about to use,
1364     # and if needs be, add some more flags and setup to
1365     # the different phases.
1366     #
1367     &setupBuildFlags();
1368     &setupOptimiseFlags();
1369     &setupMachOpts();
1370     &setupIncPaths();
1371     &setupWarningFlags();
1372     &setupHeapStackSize();
1373
1374     #
1375     # These two variables need to be set after the
1376     # command-line has been processed and the build options
1377     # have be seen set up. This is because command-line options
1378     # can control whether to compile vias C or not.
1379     # 
1380     local($do_cc)       = ( $Do_cc != -1) # i.e., it was set explicitly
1381                           ? $Do_cc
1382                           : ( ($HscOut eq '-C=') ? 1 : 0 );
1383     local($do_as)       = $Do_as;
1384     local($hsc_out)        = ( $HscOut eq '-C=' ) ? "$Tmp_prefix.hc" : "$Tmp_prefix.s" ;
1385     local($hsc_out_c_stub) = ( $HscOut eq '-C=' ) ? "${Tmp_prefix}_stb.c" : "";
1386     local($hsc_out_h_stub) = ( $HscOut eq '-C=' ) ? "${Tmp_prefix}_stb.h" : "";
1387
1388     if ($Only_preprocess_hc) { # stop after having run $Cc -E
1389        $do_as=0;
1390     }
1391     if ($Only_preprocess_C)     { # stop after having run $hscpp
1392        $do_hsc=0; $do_cc = 0; $do_as=0;
1393     } elsif ($ifile =~ /.lhs$/ || $ifile =~ /.hs$/ ) {
1394        ;
1395     } elsif ($ifile =~ /\.hc$/ || $ifile =~ /_hc$/ ) { # || $ifile =~ /\.$Isuffix$/o) # ToDo: better
1396         $do_hscpp = 0; $do_hsc = 0; $do_cc = 1;
1397         $hsc_out = $ifile;
1398         $hsc_out_c_stub = '';
1399         $hsc_out_h_stub = '';
1400     } elsif ($ifile =~ /\.c$/) {
1401         $do_hscpp = 0; $do_hsc = 0; $do_cc = 1;
1402         $hsc_out = $ifile; $is_hc_file = 0;
1403         $hsc_out_c_stub = '';
1404         $hsc_out_h_stub = '';
1405     } elsif ($ifile =~ /\.[sS]$/) {
1406         $do_hscpp = 0; $do_hsc = 0; $do_cc = 0;
1407         $cc_as = $ifile;    
1408     } else { # don't know what it is, but nothing to do herein...
1409         $do_hscpp = 0; $do_hsc = 0; $do_cc = 0; $do_as = 0;
1410     }
1411
1412     # hack to avoid running hscpp
1413     $HsCpp = $Cat if ! $Cpp_flag_set;
1414
1415     &runHscpp($in_lit2pgm, $lit2pgm_hscpp, $hscpp_hsc) if $do_hscpp;
1416
1417 \end{code}
1418
1419 We now think about whether to run hsc/cc or not (when hsc produces .s
1420 stuff, it effectively takes the place of both phases).
1421 To get the output file name right: for each phase that we are {\em
1422 not} going to run, set its input (i.e., the output of its preceding
1423 phase) to @"$ifile_root.<suffix>"@.
1424
1425 \begin{code}
1426     local($going_interactive) = $HscOut eq '-N=' || $ifile_root eq '_stdin';
1427
1428     #
1429     # Warning issued if -keep-hc-file-too is used without
1430     # -fvia-C (or the equivalent)
1431     #
1432     if ( $HscOut ne '-C=' && $Keep_hc_file_too ) {
1433         print STDERR "$Pgm: warning: Native code generator to be used, -keep-hc-file-too will be ignored\n";
1434     }
1435
1436     if (! $do_cc && ! $do_as) { # stopping after hsc
1437         $hsc_out = ($Specific_output_file ne '')
1438                  ? $Specific_output_file
1439                  : &odir_ify($ifile_root, ($HscOut eq '-C=') ? 'hc' : 's');
1440
1441         $ofile_target = $hsc_out; # reset
1442     }
1443
1444     if (! $do_as) { # stopping after gcc (or hsc)
1445         $cc_as = ($Specific_output_file ne '')
1446                  ? $Specific_output_file
1447                  : &odir_ify($ifile_root, ( $Only_preprocess_hc ) ? 'i' : 's');
1448
1449         $ofile_target = $cc_as; # reset
1450     }
1451
1452 \end{code}
1453
1454
1455 Now the Haskell compiler, C compiler, and assembler
1456
1457 \begin{code}
1458    if ($do_hsc) {
1459         &runHscAndProcessInterfaces( $ifile, $hscpp_hsc, $ifile_root, 
1460                                      $ofile_target, $hifile_target,
1461                                      $going_interactive);
1462     }
1463
1464     if (-f $hsc_out_h_stub) {
1465         &run_something("cp $hsc_out_h_stub $ofile_h_stub_target", 'Copy foreign export header file');
1466     }
1467
1468     if (-f $hsc_out_c_stub) {
1469         &run_something("cp $hsc_out_c_stub $ofile_c_stub_target", 'Copy foreign export C stubs');
1470         local ($hsc_out_s_stub);
1471         local ($hsc_out_o_stub);
1472         ($ofile_s_stub_target = $ofile_c_stub_target) =~ s/\.(.*)$/\.s/;
1473         ($ofile_o_stub_target = $ofile_c_stub_target) =~ s/\.(.*)$/\.o/;
1474         &runGcc    (0, $ofile_c_stub_target, $ofile_s_stub_target);
1475         &runAs     ($ofile_o_stub_target, $ofile_s_stub_target);
1476         #
1477         # Bring the C stub protos into scope when compiling the .hc file.
1478         #
1479         push (@CcInjects, "#include \"${hsc_out_h_stub}\"\n");
1480         # Hack - ensure that the stub .h file is included in the OPTIONS section
1481         #        if the .hc file is saved.
1482         push (@File_options, "-#include \"${ofile_h_stub_target}\"\n");
1483         
1484     }
1485
1486     if ($do_cc) {
1487         &runGcc    ($is_hc_file, $hsc_out, $cc_as_o);
1488         &runMangler($is_hc_file, $cc_as_o, $cc_as, $ifile_root) if ! $Only_preprocess_hc;
1489     }
1490
1491     &split_asm_file($cc_as)  if $do_as && $SplitObjFiles;
1492
1493     # save a copy of the .s file..
1494     &saveIntermediate($ifile_root , "s" , $cc_as) if ($do_as && $Keep_s_file_too);
1495     &runAs($as_out, $ifile_root) if $do_as;
1496 \end{code}
1497
1498 Finally, decide what to queue up for linker input.
1499 \begin{code}
1500     # tentatively assume we will eventually produce linker input:
1501     push(@Link_file, &odir_ify($ifile_root, 'o'));
1502
1503 #ToDo:    local($or_isuf) = ($Isuffix eq '') ? '' : "|$Isuffix";
1504
1505     if ( $ifile !~ /\.(lhs|hs|hc|c|s|a|S)$/ && $ifile !~ /_hc$/ ) {
1506         # There's sometimes confusion regarding .hi files; users
1507         # supplying them on the command line.
1508         if ( $ifile =~ /\.hi$/ ) {
1509             print STDERR "$Pgm: warning: found `$ifile' on command line; interface files should not be supplied here - ignoring it.\n";
1510         } else {
1511            print STDERR "$Pgm: don't recognise suffix on `$ifile'; passing it through to linker\n";
1512         }
1513         # oops; we tentatively pushed the wrong thing; fix & do the right thing
1514         pop(@Link_file); push(@Link_file, $ifile);
1515     }
1516
1517
1518 } # end of ProcessInputFile
1519 \end{code}
1520
1521 %************************************************************************
1522 %*                                                                      *
1523 \section[Driver-run-phases]{Routines to run the various phases}
1524 %*                                                                      *
1525 %************************************************************************
1526
1527 \begin{code}
1528 sub runLit2pgm {
1529     local($in_lit2pgm, $lit2pgm_hscpp) = @_;
1530
1531     local($to_do) = "";
1532
1533     # Only add #line pragma if we're going to need it.
1534     $to_do  = "echo '#line 1 \"$in_lit2pgm\"' > $lit2pgm_hscpp && " if ($Cpp_flag_set);
1535     $to_do .= "$Unlit @Unlit_flags $in_lit2pgm -  >> $lit2pgm_hscpp";
1536      
1537     push(@Files_to_tidy, $lit2pgm_hscpp );
1538
1539     &run_something($to_do, 'literate pre-processor');
1540 }
1541 \end{code}
1542
1543 \begin{code}
1544 sub runHscpp {
1545     local($in_lit2pgm, $lit2pgm_hscpp, $hscpp_hsc) = @_;
1546
1547     local($to_do) = "";
1548
1549     # Strictly speaking, echoing of the following line pragma is only required
1550     # on non-delit'ed input, as we've already added it during de-lit. However,
1551     # hscpp will then add a {-# LINE 1 "$lit2pgm_hsc" -} to the top of the file,
1552     # which is not very informative (but harmless). Hence, we uniformly have
1553     # {-# LINE 1 "$in_lit2pgm" #-} as the first line to all cpp'ed hsc input.
1554     #
1555     $to_do = "echo '{-# LINE 1 \"$in_lit2pgm\" -}' > $hscpp_hsc && ";
1556
1557     if ($HsCpp eq $Cat) {
1558         $to_do .= "$HsCpp $lit2pgm_hscpp >> $hscpp_hsc";
1559         push(@Files_to_tidy, $hscpp_hsc );
1560         &run_something($to_do, 'Ineffective C pre-processor');
1561     } else {
1562         local($includes) = '-I' . join(' -I',@Include_dir);
1563         $to_do .= "$HsCpp $Verbose @HsCpp_flags @HsSourceCppOpts $includes $lit2pgm_hscpp >> $hscpp_hsc";
1564         push(@Files_to_tidy, $hscpp_hsc );
1565         &run_something($to_do, 'Haskellised C pre-processor');
1566     }
1567    
1568     if ( $Only_preprocess_C ) {
1569         $to_do = "$Cat $hscpp_hsc";
1570         &run_something($to_do, '');
1571     }
1572
1573 }
1574 \end{code}
1575
1576
1577 \begin{code}
1578 sub runHscAndProcessInterfaces {
1579     local($ifile, $hscpp_hsc, $ifile_root, 
1580           $ofile_target, $hifile_target,
1581           $going_interactive) = @_;
1582
1583         # $ifile                is the original input file
1584         # $hscpp_hsc            post-unlit, post-cpp, etc., input file
1585         # $ifile_root           input filename minus suffix
1586         # $ofile_target         the output file that we ultimately hope to produce
1587         # $hifile_target        the .hi file ... (ditto)
1588         
1589     local($source_unchanged) = 1;
1590
1591     # Check if the source file is up to date relative to the target; in
1592     # that case we say "source is unchanged" and let the compiler bail out
1593     # early if the import usage information allows it.
1594
1595     ($i_dev,$i_ino,$i_mode,$i_nlink,$i_uid,$i_gid,$i_rdev,$i_size,
1596      $i_atime,$i_mtime,$i_ctime,$i_blksize,$i_blocks) = stat($ifile);
1597
1598     # The informational messages below are now conditional on -v being set -- SOF
1599     if ( $ofile_target ne "_stdin.s" && ! -f $ofile_target ) {
1600         print STDERR "$Pgm:compile:Output file $ofile_target doesn't exist\n" if $Verbose;
1601         $source_unchanged = 0;
1602     }
1603
1604     ($o_dev,$o_ino,$o_mode,$o_nlink,$o_uid,$o_gid,$o_rdev,$o_size,
1605      $o_atime,$o_mtime,$o_ctime,$o_blksize,$o_blocks) = stat(_); # stat info from -f test
1606
1607     if ( $hifile_target ne "_stdout" && ! -f $hifile_target ) {
1608         print STDERR "$Pgm:compile:Interface file $hifile_target doesn't exist\n" if $Verbose;
1609         $source_unchanged = 0;
1610     }
1611
1612     ($hi_dev,$hi_ino,$hi_mode,$hi_nlink,$hi_uid,$hi_gid,$hi_rdev,$hi_size,
1613      $hi_atime,$hi_mtime,$hi_ctime,$hi_blksize,$hi_blocks) = stat(_); # stat info from -f test
1614
1615     if ( $ofile_target ne "_stdin.s" && $i_mtime > $o_mtime) {
1616         print STDERR "$Pgm:recompile:Input file $ifile newer than $ofile_target\n" if $Verbose;
1617         $source_unchanged = 0;
1618     }
1619
1620     # Tell the compiler which version we're using
1621     push(@HsC_flags, "-fhi-version=${ProjectVersionInt}");
1622
1623     # So if source_unchanged is still "1", we pass on the good news to the compiler
1624     # The -recomp flag can disable this, forcing recompilation
1625     if ($Do_recomp_chkr && $source_unchanged) {
1626         push(@HsC_flags, '-fsource-unchanged'); 
1627     }   
1628
1629     # Indicate whether we're static or not.
1630     # This will only ever 
1631     push(@HsC_flags, '-static') if $Static;
1632
1633     # Run the compiler
1634
1635     &runHsc($ifile_root, $hsc_out, $hsc_hi, $hsc_out_c_stub, $hsc_out_h_stub, $going_interactive);
1636
1637    # See if it bailed out early, saying nothing needed doing.  
1638    # We work this out by seeing if it created an output .hi file
1639
1640     if ( ! -f $hsc_hi && $ProduceHi !~ /-nohifile=/ ) {
1641         # Doesn't exist, so we bailed out early.
1642         # Tell the C compiler and assembler not to run
1643         $do_cc = 0; $do_as = 0;
1644
1645         # Update dependency info, touch both object file and 
1646         # interface file, so that the following invariant is
1647         # maintained:
1648         #
1649         #   a dependent module's interface file should after recompilation
1650         #   checking be newer than the interface files of its imports. 
1651         #
1652         # That is, if module A's interface file changes, then module B
1653         # (which import from A) needs to be checked.
1654         # If A's change does not affect B, which causes the compiler to bail
1655         # out early, we still need to touch the interface file of B. The reason
1656         # for this is that B may export A's interface.
1657         #
1658         &run_something("touch $ofile_target",
1659                        "Touch $ofile_target,  to propagate dependencies") if $HscOut ne '-N=';
1660         &run_something("touch $hifile_target", 
1661                        "Touch $hifile_target,  to propagate dependencies") if $ProduceHi =~ /-nohifile=/ ;
1662
1663     } else {    
1664
1665      # Didn't bail out early (new .hi file) so we thunder on
1666     
1667         # If non-interactive, heave in the consistency info at the end
1668         # NB: pretty hackish (depends on how $output is set)
1669         if ( ! $going_interactive ) {
1670             if ( $HscOut eq '-C=' ) {
1671             $to_do = "echo 'static char ghc_hsc_ID[] = \"\@(#)hsc $ifile\t$HsC_major_version.$HsC_minor_version,$HsC_consist_options\";' >> $hsc_out";
1672     
1673             } elsif ( $HscOut eq '-S=' ) {
1674                 local($consist) = "hsc.$ifile.$HsC_major_version.$HsC_minor_version.$HsC_consist_options";
1675                 $consist =~ s/,/./g;
1676                 $consist =~ s/\//./g;
1677                 $consist =~ s/-/_/g;
1678                 $consist =~ s/[^A-Za-z0-9_.]/ZZ/g; # ToDo: properly?
1679                 $to_do = "echo '\n\t.text\n$consist:' >> $hsc_out";
1680             }
1681             &run_something($to_do, 'Pin on Haskell consistency info');  
1682         }   
1683
1684
1685         # Interface-handling is important enough to live off by itself
1686         if ( $ProduceHi !~ /-nohifile=/ ) { # If we've produced one, process it.
1687            require('ghc-iface.prl') || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-iface.prl!\n");
1688            &postprocessHiFile($hsc_hi, $hifile_target, $going_interactive);
1689         }
1690         # if we're going to split up object files,
1691         # we inject split markers into the .hc file now
1692         if ( $HscOut eq '-C=' && $SplitObjFiles ) {
1693             &inject_split_markers ( $hsc_out );
1694         }
1695
1696         # save a copy of the .hc file, even if we are carrying on...
1697         if ($HscOut eq '-C=' && $do_cc && $Keep_hc_file_too) {
1698             &saveIntermediate($ifile_root , "hc" , $hsc_out);
1699         }
1700
1701     }
1702 }
1703 \end{code}
1704
1705
1706 \begin{code}
1707 sub runHsc {
1708     local($ifile_root, $hsc_out, $hsc_hi, $hsc_out_c_stub, $hsc_out_h_stub, $going_interactive) = @_;
1709
1710     &makeHiMap() unless $HiMapDone;
1711     push(@HsC_flags, "-himap=$HiIncludeString");
1712
1713     # here, we may produce .hc/.s and/or .hi files
1714     local($output) = '';
1715     #@Files_to_tidy = ();
1716
1717     if ( $going_interactive ) {
1718         # don't need .hi unless we're going to show it on stdout:
1719         $ProduceHi = '-nohifile=' if ! ($HiOnStdout || $Specific_hi_file ne '' );
1720         $do_cc = 0; $do_as = 0; $Do_lnkr = 0; # and we won't go any further...
1721     }
1722
1723     # set up for producing output/.hi; note that flag twiddling
1724     # may mean that nothing will actually be produced:
1725     $output = "$ProduceHi$hsc_hi $HscOut$hsc_out -F=$hsc_out_c_stub -FH=$hsc_out_h_stub";
1726     push(@Files_to_tidy, $hsc_hi, $hsc_out, $hsc_out_c_stub, $hsc_out_h_stub );
1727
1728     # if we're compiling foo.hs, we want the GC stats to end up in foo.stat
1729     if ( $CollectingGCstats ) {
1730         push(@HsC_rts_flags, "-S$ifile_root.stat");
1731         push(@Files_to_tidy, "$ifile_root.stat");
1732     }
1733
1734     if ( $CollectGhcTimings ) { # assume $RTS_style eq 'ghc'
1735         # emit nofibbish time/bytes-alloc stats to stderr;
1736         # see later .stat file post-processing
1737         print STDERR "warning: both -Rgc-stats and -Rghc-timing used, -Rghc-timing wins." if $CollectingGCstats;
1738         push(@HsC_rts_flags, "-s$Tmp_prefix.stat");
1739         push(@Files_to_tidy, "$Tmp_prefix.stat");
1740     }
1741
1742     local($dump) = '';
1743     if ($Specific_dump_file ne '') {
1744         $dump = "2>> $Specific_dump_file";
1745         $Using_dump_file = 1;
1746     }
1747
1748     local($to_do);
1749     # Win32 only: If the command processor used by system()
1750     # exec()s the application as an ordinary Win32 executable,
1751     # we're in trouble here, since the command line is likely
1752     # to be > 255 chars long. To work around this situation,
1753     # $HsC also understands `at-files',  i.e., `@file' on the
1754     # command line will cause $HsC to add the contents of `file'
1755     # to the command line.
1756     #
1757     #  [ Note: support for `at-files' is not compiled in by default ]
1758     $cmd_line_opts_via_at_file=0;
1759     if ($cmd_line_opts_via_at_file) {
1760
1761       local($to_do_opts) = "$Tmp_prefix.opts";
1762       open(OPTS, "> $Tmp_prefix.opts") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.opts\n");
1763       print OPTS "$dump @HsC_flags $CoreLint $USPLint $StgLint $Verbose";
1764       close(OPTS);
1765       $to_do = "$HsC $hscpp_hsc \@$Tmp_prefix.opts $output +RTS @HsC_rts_flags";
1766
1767     } else {
1768
1769     $to_do = "$HsC $hscpp_hsc $dump @HsC_flags $CoreLint $USPLint $StgLint $Verbose $output +RTS @HsC_rts_flags";
1770     }
1771     &run_something($to_do, 'Haskell compiler');
1772
1773     # finish business w/ nofibbish time/bytes-alloc stats
1774     &process_ghc_timings() if $CollectGhcTimings;
1775 }
1776 \end{code}
1777
1778 Use \tr{@Import_dir} and \tr{@SysImport_dir} to make a tmp file
1779 of (module-name, pathname) pairs, one per line, separated by a space.
1780 \begin{code}
1781 $HiMapDone = 0;
1782 $HiIncludeString = ();          # dir1:dir2:dir3, to pass to GHC
1783
1784 sub makeHiMap {
1785
1786     # collect in %HiMap; write later; also used elsewhere in driver
1787
1788     local($mod, $path, $d, $e);
1789
1790     # reset the global variables:
1791     $HiMapDone = 0;
1792     $HiIncludeString = ();              # dir1:dir2:dir3, to pass to GHC
1793     
1794     foreach $d ( @Import_dir ) {
1795         if ($HiIncludeString) { 
1796            $HiIncludeString = "$HiIncludeString:${d}%.${HiSuffix}";
1797         } else { 
1798            $HiIncludeString = "$d%.${HiSuffix}"; 
1799         }
1800
1801     }
1802
1803     foreach $d ( @SysImport_dir ) {
1804         if ($HiIncludeString) { 
1805             $HiIncludeString = "$HiIncludeString:${d}%.${HiSuffix_prelude}";
1806         } else { 
1807             $HiIncludeString = "${d}%.${HiSuffix_prelude}";
1808         }
1809     }
1810
1811     $HiMapDone = 1;
1812 }
1813
1814 \end{code}
1815
1816 Invoke the 'linker' - either the standard linker or the one used to build
1817 a (Win32) DLL.
1818
1819 \begin{code}
1820 sub runLinker()
1821 {
1822     local($libdirs) = '';
1823
1824     # append last minute flags linker and consistency flags
1825     &setupBuildFlags();
1826     &setupSyslibs();
1827     &setupLinkOpts();
1828
1829     # glue them together:
1830     push(@UserLibrary_dir, @SysLibrary_dir);
1831
1832     $libdirs = '-L' . join(' -L',@UserLibrary_dir) if $#UserLibrary_dir >= 0;
1833
1834     # for a linker, use an explicitly given one, or the going C compiler ...
1835     local($lnkr) = ( $Lnkr ) ? $Lnkr : $CcRegd;
1836
1837     if ( ($Specific_output_file eq '') && 
1838          ($TargetPlatform eq 'i386-unknown-cygwin32') ) {
1839          $Specific_output_file = 'main.exe';
1840          print STDERR "Output file not specified, defaulting to \"main.exe\"\n";
1841     }
1842
1843     local($output) = ($Specific_output_file ne '') ? "-o $Specific_output_file" : '';
1844     @Files_to_tidy = ($Specific_output_file ne '') ? $Specific_output_file : 'a.out'; 
1845
1846     &prepareWin32DllLink(1);
1847
1848     local($to_do) = "$lnkr $Verbose @Ld_flags $output @Link_file $TopClosureFile $libdirs @UserLibrary @SysLibrary";
1849     &run_something($to_do, 'Linker');
1850
1851     # finally, check the consistency info in the binary
1852     local($executable) = $Files_to_tidy[0];
1853     @Files_to_tidy = (); # reset; we don't want to nuke it if it's inconsistent
1854
1855     if ( $LinkChk ) {
1856         # dynamically load consistency-chking code; then do it.
1857         require('ghc-consist.prl')
1858             || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-consist.prl!\n");
1859
1860         &chk_consistency_info ( $executable );
1861     }
1862
1863     # if PVM parallel stuff, we do truly weird things.
1864     # Essentially: (1) move the executable over to where PVM expects
1865     # to find it.  (2) create a script in place of the executable
1866     # which will cause the program to be run, via SysMan.
1867     if ( $PARing eq 'p' ) {
1868         local($pvm_executable) = $executable;
1869         local($pvm_executable_base);
1870
1871         if ( $pvm_executable !~ /^\// ) { # a relative path name: make absolute
1872             local($pwd) = `pwd`;
1873             chop($pwd);
1874             $pwd =~ s/^\/tmp_mnt//;
1875             $pvm_executable = "$pwd/$pvm_executable";
1876         }
1877
1878         $pvm_executable =~ s|/|=|g; # make /s into =s
1879         $pvm_executable_base = $pvm_executable;
1880
1881         $pvm_executable = $ENV{'PVM_ROOT'} . '/bin/' . $ENV{'PVM_ARCH'}
1882                         . "/$pvm_executable";
1883
1884         &run_something("$Rm -f $pvm_executable; $Cp -p $executable $pvm_executable && $Rm -f $executable", 'Moving binary to PVM land');
1885
1886         # OK, now create the magic script for "$executable"
1887         open(EXEC, "> $executable") || &tidy_up_and_die(1,"$Pgm: couldn't open $executable to write!\n");
1888         print EXEC <<EOSCRIPT1;
1889 eval 'exec perl -S \$0 \${1+"\$@"}'
1890   if \$running_under_some_shell;
1891 # =!=!=!=!=!=!=!=!=!=!=!
1892 # This script is automatically generated: DO NOT EDIT!!!
1893 # Generated by Glasgow Haskell, version ${ProjectVersion} ${ProjectPatchLevel}
1894 #
1895 \$pvm_executable      = '$pvm_executable';
1896 \$pvm_executable_base = '$pvm_executable_base';
1897 \$SysMan = '$SysMan';
1898 EOSCRIPT1
1899
1900         print EXEC <<\EOSCRIPT2;
1901 # first, some magical shortcuts to run "commands" on the binary
1902 # (which is hidden)
1903 if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {
1904     local($cmd) = $1;
1905     system("$cmd $pvm_executable");
1906     exit(0); # all done
1907 }
1908
1909 # OK, really run it; process the args first
1910 $ENV{'PE'} = $pvm_executable_base;
1911 $debug = '';
1912 $nprocessors = 2; # the default
1913 @nonPVM_args = ();
1914 $in_RTS_args = 0;
1915
1916 # ToDo: handle --RTS
1917 args: while ($a = shift(@ARGV)) {
1918     if ( $a eq '+RTS' ) {
1919         $in_RTS_args = 1;
1920     } elsif ( $a eq '-RTS' ) {
1921         $in_RTS_args = 0;
1922     }
1923     if ( $a eq '-d' && $in_RTS_args ) {
1924         $debug = '-';
1925     } elsif ( $a =~ /^-N(\d+)/ && $in_RTS_args ) {
1926         $nprocessors = $1;
1927     } else {
1928         push(@nonPVM_args, $a);
1929     }
1930 }
1931
1932 local($return_val) = 0;
1933 system("$SysMan $debug $pvm_executable $nprocessors @nonPVM_args");
1934 $return_val = $?;
1935 system("mv $ENV{'HOME'}/$pvm_executable_base.???.gr .") if -f "$ENV{'HOME'}/$pvm_executable_base.001.gr";
1936 exit($return_val);
1937 EOSCRIPT2
1938         close(EXEC) || die "Failed closing $executable\n";
1939         chmod 0755, $executable;
1940     }
1941 }
1942
1943 sub createWin32DLL()
1944 {
1945     local ($libdirs);
1946
1947     # append last minute flags linker and consistency flags
1948     &setupBuildFlags();
1949     &setupSyslibs();
1950     &setupLinkOpts();
1951
1952     # glue them together:
1953     push(@UserLibrary_dir, @SysLibrary_dir);
1954
1955     $libdirs = '-L' . join(' -L',@UserLibrary_dir) if $#UserLibrary_dir >= 0;
1956
1957     &prepareWin32DllLink(0);
1958
1959     local ($bld_dll) = "dllwrap";
1960
1961     local ($output) = ($Specific_output_file ne '') ? "$Specific_output_file" : 'HSdll.dll';
1962     local ($output_dir);
1963     local ($output_file);
1964     local ($output_lib, $output_def);
1965
1966     ($output_dir = $output) =~ s|(.*/)[^/]+$|$1|;
1967     $output_dir = "" if ($output_dir eq $output);
1968     ($output_file = $output) =~ s|.*/([^/]+)$|$1|;
1969
1970     ($output_lib = $output_file) =~ s|(.+)\.[^\.]*$|${output_dir}lib$1_imp.a|;
1971     ($output_def = $output_file) =~ s|(.+)\.[^\.]*$|${output_dir}$1.def|;
1972
1973     push (@Dll_flags, "-mno-cygwin --target=i386-mingw32") if ($TargetPlatform =~ /^.*mingw32$/);
1974     push (@Dll_flags, "--output-lib $output_lib");
1975     # If the "--def " option hasn't been supplied, assume everything 
1976     # is going to be exported via the DLL.."
1977     if (!grep(/--def/, @Dll_flags)) {
1978       push (@Dll_flags, "--export-all --output-def $output_def");
1979     }
1980
1981     local($to_do) = "$bld_dll @Dll_flags -o $output @Link_file $libdirs @UserLibrary @SysLibrary";
1982     # Make sure the user sees this piece of magic.
1983     print STDERR "$to_do\n" if (!$Verbose);
1984     &run_something($to_do, 'DLL creator');
1985 }
1986
1987 sub prepareWin32DllLink ()
1988 {
1989     local($linking_main) = @_;
1990
1991     #
1992     # Win32 DLLs - link with import libraries, not the real archives.
1993     # 
1994     if ( $TargetPlatform =~ /-mingw32$/ ) {
1995        if (!$Static) {
1996          #
1997          # If the libraries have the form libHSfoo.a, we
1998          # transform that into libHSfoo_imp.a - the import
1999          # library of the DLL.
2000          # 
2001          foreach $a ( @SysLibrary ) {
2002            $a = "${a}_imp" if ($a =~ /^-lHS/);
2003          }
2004          foreach $a ( @UserLibrary ) {
2005            $a = "${a}_imp" if ($a =~ /^-lHS/);
2006          }
2007          push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/Main.o"
2008                                           : "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/Main.o") if $linking_main;
2009          push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/PrelMain.o"
2010                                           : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/PrelMain.o") if $linking_main;
2011        }
2012        push(@Ld_flags,  "-mno-cygwin");
2013     }
2014 }
2015 \end{code}
2016
2017
2018 %************************************************************************
2019 %*                                                                      *
2020 \section[Driver-misc-utils]{Miscellaneous utilities}
2021 %*                                                                      *
2022 %************************************************************************
2023
2024 %************************************************************************
2025 %*                                                                      *
2026 \subsection[Driver-odir-ify]{@odir_ify@: Mangle filename if \tr{-odir} set}
2027 %*                                                                      *
2028 %************************************************************************
2029
2030 \begin{code}
2031 sub osuf_ify {
2032     local($ofile,$def_suffix) = @_;
2033
2034     return(($Osuffix eq '') ? "$ofile.$def_suffix" : "$ofile.$Osuffix" );
2035 }
2036
2037 sub odir_ify {
2038     local($orig_file, $def_suffix) = @_;
2039     if ($Specific_output_dir eq '') {   # do nothing
2040         &osuf_ify($orig_file, $def_suffix);
2041     } else {
2042         local ($orig_file_only);
2043         ($orig_file_only = $orig_file) =~ s|.*/||;
2044         &osuf_ify("$Specific_output_dir/$orig_file_only",$def_suffix);
2045     }
2046 }
2047 \end{code}
2048
2049 \begin{code}
2050 sub runGcc {
2051     local($is_hc_file, $hsc_out, $cc_as_o) = @_;
2052
2053     local($includes) = '-I' . join(' -I', @Include_dir);
2054     local($cc);
2055     local($s_output);
2056     local($c_flags) = "@CcBoth_flags";
2057     local($ddebug_flag) = ( $DEBUGging ) ? '-DDEBUG' : '';
2058
2059     $c_flags .= " -mno-cygwin" if ( $TargetPlatform =~ /-mingw32$/ );
2060
2061     # "input" files to use that are not in some weird directory;
2062     # to help C compilers grok .hc files [ToDo: de-hackify]
2063     local($cc_help)   = "ghc$$.c";
2064     local($cc_help_s) = "ghc$$.s";
2065
2066     $cc       = $CcRegd;
2067     $s_output = (($is_hc_file && $DoAsmMangling) || $TargetPlatform =~ /^(powerpc|rs6000|hppa)/) ? $cc_as_o : $cc_as;
2068     $c_flags .= " @CcRegd_flags";
2069     $c_flags .= ($is_hc_file) ? " @CcRegd_flags_hc"  : " @CcRegd_flags_c";
2070
2071     # C compiler won't like the .hc extension.  So we create
2072     # a tmp .c file which #include's the needful.
2073     open(TMP, "> $cc_help") || &tidy_up_and_die(1,"$Pgm: failed to open `$cc_help' (to write)\n");
2074     if ( $is_hc_file ) {
2075         print TMP <<EOINCL;
2076 #include "Stg.h"
2077 EOINCL
2078         # user may have asked for #includes to be injected...
2079         print TMP @CcInjects if $#CcInjects >= 0;
2080     } else {
2081         # Straight .c files may want to know that they're being used
2082         # with a particular version of GHC, so we define __GLASGOW_HASKELL__ for their benefit.
2083         print TMP "#define __GLASGOW_HASKELL__ ${ProjectVersionInt}\n";
2084     }
2085     # heave in the consistency info
2086     print TMP "static char ghc_cc_ID[] = \"\@(#)cc $ifile\t$Cc_major_version.$Cc_minor_version,$Cc_consist_options\";\n";
2087
2088     print TMP "#include \"$hsc_out\"\n";
2089     close(TMP) || &tidy_up_and_die(1,"Failed writing to $cc_help\n");
2090
2091     # Don't redirect stderr into intermediate file if slamming output onto stdout (e.g., with -E)
2092     local($fuse_stderr) = "2>&1" if ! $Only_preprocess_hc;
2093     local($to_do) = "$cc $Verbose $ddebug_flag $c_flags @Cpp_define $includes $cc_help > $Tmp_prefix.ccout $fuse_stderr && ( if [ $cc_help_s != $s_output ] ; then mv $cc_help_s $s_output ; else exit 0 ; fi )";
2094
2095     if ( $Only_preprocess_hc ) { # HACK ALERT!
2096         $to_do =~ s/ -S\b//g;
2097     }
2098     push(@Files_to_tidy, $cc_help, $cc_help_s, $s_output );
2099     $PostprocessCcOutput = 1 if ! $Only_preprocess_hc;  # hack, dear hack...
2100     &run_something($to_do, 'C compiler');
2101     $PostprocessCcOutput = 0;
2102     if ( $Only_preprocess_hc ) {
2103        system("$Cat $Tmp_prefix.ccout");
2104     }
2105     unlink($cc_help, $cc_help_s);
2106 }
2107 \end{code}
2108
2109 \begin{code}
2110 sub runMangler {
2111     local($is_hc_file, $cc_as_o, $cc_as, $ifile_root) = @_;
2112
2113     print STDERR `cat $cc_as_o` if $Dump_raw_asm; # to stderr, before mangling
2114
2115     if ($is_hc_file && $DoAsmMangling) {
2116         # dynamically load assembler-fiddling code, which we are about to use:
2117         require('ghc-asm.prl')
2118              || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm.prl!\n");
2119         # post-process the assembler [.hc files only]
2120         &mangle_asm($cc_as_o, $cc_as);
2121
2122     } elsif ($TargetPlatform =~ /^hppa/) {
2123         # minor mangling of non-threaded files for hp-pa only
2124         require('ghc-asm.prl')
2125         || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm-hppa.prl!\n");
2126         &mini_mangle_asm_hppa($cc_as_o, $cc_as);
2127
2128     } elsif ($TargetPlatform =~ /^powerpc|^rs6000/) {
2129         # minor mangling of non-threaded files for powerpcs and rs6000s 
2130         require('ghc-asm.prl')
2131         || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-asm-powerpc.prl!\n");
2132         &mini_mangle_asm_powerpc($cc_as_o, $cc_as);
2133     }
2134
2135     # save a copy of the .s file, even if we are carrying on...
2136     #if ($do_as && $Keep_s_file_too) {
2137     #    &saveIntermediate($ifile_root , "s" , $cc_as);
2138     #}
2139 }
2140 \end{code}
2141
2142 \begin{code}
2143 sub runAs {
2144     local($as_out, $ifile_root) = @_;
2145
2146     local($asmblr) = ( $As ) ? $As : $CcRegd;
2147
2148     # need to add the -I flags in case the file is going through cpp (.S files)
2149     local($includes) = '-I' . join(' -I', @Include_dir);
2150
2151     if ( ! $SplitObjFiles ) {
2152         local($to_do)  = "$asmblr -o $as_out -c @As_flags $includes $cc_as";
2153         push(@Files_to_tidy, $as_out );
2154         &run_something($to_do, 'Unix assembler');
2155
2156     } else { # more complicated split-ification...
2157
2158         # must assemble files $Tmp_prefix__[1 .. $NoOfSplitFiles].s
2159
2160         # If -odir is used, great, just pin it in front of the
2161         # generated split file names. If it hasn't been set, we
2162         # snatch it from the ifile_root.
2163         #
2164         # 
2165
2166         if ( $Specific_output_dir eq '' ) {
2167             $Specific_output_dir = ${ifile_root};
2168         }
2169
2170         for ($f = 1; $f <= $NoOfSplitFiles; $f++ ) {
2171             local($split_out) = &odir_ify("${ifile_root}__${f}",'o');
2172             local($to_do) = "$asmblr -o $split_out -c @As_flags ${Tmp_prefix}__${f}.s";
2173             push(@Files_to_tidy, $split_out );
2174
2175             &run_something($to_do, 'Unix assembler');
2176         }
2177     }
2178 }
2179 \end{code}
2180
2181 %************************************************************************
2182 %*                                                                      *
2183 \subsection[Driver-run-something]{@run_something@: Run a phase}
2184 %*                                                                      *
2185 %************************************************************************
2186
2187 \begin{code}
2188 sub run_something {
2189     local($str_to_do, $tidy_name) = @_;
2190
2191     print STDERR "\n$tidy_name:\n\t" if $Verbose;
2192     print STDERR "$str_to_do\n" if $Verbose;
2193
2194     if ($Using_dump_file) {
2195         open(DUMP, ">> $Specific_dump_file")
2196             || &tidy_up_and_die(1,"$Pgm: failed to open `$Specific_dump_file'\n");
2197         print DUMP "\nCompilation Dump for: $str_to_do\n\n";
2198         close(DUMP) 
2199             || &tidy_up_and_die(1,"$Pgm: failed closing `$Specific_dump_file'\n");
2200     }
2201
2202     local($return_val) = 0;
2203
2204     if ( length($str_to_do) > 4000) { 
2205       # 4000 - on the random side, just like the *real* ARG_MAX 
2206       # for some shells.
2207
2208       # With some shells, command lines of this length may
2209       # very well cause trouble. To safeguard against this, we squirrel the
2210       # command into a file and exec that.
2211       local ($sh) = $ENV{'REAL_SHELL'};
2212       print STDERR "Backup plan A: saving cmd line in ${Tmp_prefix}.sh and executing that with $sh\n" if $Verbose;
2213       open (TEMP, "> ${Tmp_prefix}.sh") || 
2214                 &tidy_up_and_die(1,"$Pgm: failed to open `$Tmp_prefix.sh'\n");
2215       print TEMP "$Time $str_to_do\n";
2216       close (TEMP) ||
2217                 &tidy_up_and_die(1,"$Pgm: failed closing `$Tmp_prefix.sh'\n");
2218       system("$sh $Tmp_prefix.sh");
2219       $return_val = $?;
2220       
2221       unlink "${Tmp_prefix}.sh";
2222     } else {
2223       system("$Time $str_to_do");
2224       $return_val = $?;
2225     }
2226
2227     if ( $PostprocessCcOutput ) { # hack, continued
2228         open(CCOUT, "< $Tmp_prefix.ccout")
2229             || &tidy_up_and_die(1,"$Pgm: failed to open `$Tmp_prefix.ccout'\n");
2230         while ( <CCOUT> ) {
2231             next if /call-clobbered/;
2232             next if /control reaches end/;
2233             next if /from .*Stg\.h:/;
2234             next if /from ghc\d+.c:\d+:/;
2235             next if /: At top level:$/;
2236             next if /: In function \`.*\':$/;
2237             next if /\`ghc_cc_ID\' defined but not used/;
2238             print STDERR $_;
2239         }
2240         close(CCOUT) || &tidy_up_and_die(1,"$Pgm: failed closing `$Tmp_prefix.ccout'\n");
2241     }
2242
2243     if ($return_val != 0) {
2244         if ($Using_dump_file) {
2245             print STDERR "Compilation Errors dumped in $Specific_dump_file\n";
2246         }
2247         &tidy_up_and_die($return_val, '');
2248     }
2249     $Using_dump_file = 0;
2250 }
2251 \end{code}
2252
2253 %************************************************************************
2254 %*                                                                      *
2255 \subsection[Driver-ghc-timing]{Emit nofibbish GHC timings}
2256 %*                                                                      *
2257 %************************************************************************
2258
2259 NB: nearly the same as in @runstdtest@ script.
2260
2261 \begin{code}
2262 sub process_ghc_timings {
2263     local($StatsFile) = "$Tmp_prefix.stat";
2264     local($SysSpecificTiming) = 'ghc';
2265
2266     open(STATS, $StatsFile) || die "Failed when opening $StatsFile\n";
2267     local($max_live)    = 0; 
2268     local($tot_live)    = 0; # for calculating residency stuff
2269     local($tot_samples) = 0;
2270
2271     while (<STATS>) {
2272         if (! /Gen:\s+0/ && ! /Minor/ && /^\s*\d+\s+\d+\s+(\d+)\s+\d+\.\d+/ ) {
2273                 $max_live = $1 if $max_live < $1;
2274                 $tot_live += $1;
2275                 $tot_samples += 1;
2276         }
2277         $BytesAlloc = $1 if /^\s*([0-9,]+) bytes allocated in the heap/;
2278
2279         if ( /^\s*([0-9,]+) bytes maximum residency .* (\d+) sample/ ) {
2280             $MaxResidency = $1; $ResidencySamples = $2;
2281         }
2282
2283         $GCs = $1 if /^\s*([0-9,]+) (collections? in generation 0|garbage collections? performed)/;
2284
2285         if ( /^\s+([0-9]+)\s+Mb total memory/ ) {
2286             $TotMem = $1;
2287         }
2288
2289         # The presence of -? in the following pattern is only there to
2290         # accommodate 0.29 && <= 2.05 RTS'
2291         if ( /^\s*INIT\s+time\s*(\d+\.\d\d)s\s*\(\s*-?(\d+\.\d\d)s elapsed\)/ ) {
2292             $InitTime = $1; $InitElapsed = $2;
2293         } elsif ( /^\s*MUT\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
2294             $MutTime = $1; $MutElapsed = $2;
2295         } elsif ( /^\s*GC\s+time\s*(\d+\.\d\d)s\s*\(\s*(\d+\.\d\d)s elapsed\)/ ) {
2296             $GcTime = $1; $GcElapsed = $2;
2297         }
2298     }
2299     close(STATS) || die "Failed when closing $StatsFile\n";
2300     if ( $tot_samples > 0 ) {
2301         $ResidencySamples = $tot_samples;
2302         $MaxResidency = $max_live;
2303         $AvgResidency = int ($tot_live / $tot_samples) ;
2304     }
2305
2306     # warn about what we didn't find
2307     print STDERR "Warning: BytesAlloc not found in stats file\n" unless defined($BytesAlloc);
2308     print STDERR "Warning: GCs not found in stats file\n" unless defined($GCs);
2309     print STDERR "Warning: InitTime not found in stats file\n" unless defined($InitTime);
2310     print STDERR "Warning: InitElapsed not found in stats file\n" unless defined($InitElapsed);
2311     print STDERR "Warning: MutTime not found in stats file\n" unless defined($MutTime);
2312     print STDERR "Warning: MutElapsed not found in stats file\n" unless defined($MutElapsed);
2313     print STDERR "Warning: GcTime inot found in stats file\n" unless defined($GcTime);
2314     print STDERR "Warning: GcElapsed not found in stats file\n" unless defined($GcElapsed);
2315
2316     # things we didn't necessarily expect to find
2317     $MaxResidency     = 0 unless defined($MaxResidency);
2318     $AvgResidency     = 0 unless defined($AvgResidency);
2319     $ResidencySamples = 0 unless defined($ResidencySamples);
2320
2321     # a bit of tidying
2322     $BytesAlloc =~ s/,//g;
2323     $MaxResidency =~ s/,//g;
2324     $GCs =~ s/,//g;
2325     $InitTime =~ s/,//g;
2326     $InitElapsed =~ s/,//g;
2327     $MutTime =~ s/,//g;
2328     $MutElapsed =~ s/,//g;
2329     $GcTime =~ s/,//g;
2330     $GcElapsed =~ s/,//g;
2331
2332     # print out what we found
2333     print STDERR "<<$SysSpecificTiming: ",
2334         "$BytesAlloc bytes, $GCs GCs, $AvgResidency/$MaxResidency avg/max bytes residency ($ResidencySamples samples), ${TotMem}M in use, $InitTime INIT ($InitElapsed elapsed), $MutTime MUT ($MutElapsed elapsed), $GcTime GC ($GcElapsed elapsed)",
2335         " :$SysSpecificTiming>>\n";
2336
2337     # OK, party over
2338     unlink $StatsFile;
2339 }
2340 \end{code}
2341
2342 %************************************************************************
2343 %*                                                                      *
2344 \subsection[Driver-dying]{@tidy_up@ and @tidy_up_and_die@: Dying gracefully}
2345 %*                                                                      *
2346 %************************************************************************
2347
2348 \begin{code}
2349 sub tidy_up {
2350     local($to_do) = "\n$Rm $Tmp_prefix*";
2351     if ( $Tmp_prefix !~ /^\s*$/ ) {
2352         print STDERR "$to_do\n" if $Verbose;
2353         system($to_do);
2354     }
2355 }
2356
2357 sub tidy_up_and_die {
2358     local($return_val, $msg) = @_;
2359
2360     # delete any files to tidy
2361     print STDERR "deleting... @Files_to_tidy\n" if $Verbose && $#Files_to_tidy >= 0;
2362     unlink @Files_to_tidy if $#Files_to_tidy >= 0;
2363
2364     &tidy_up();
2365     print STDERR $msg;
2366     exit (($return_val == 0) ? 0 : 1);
2367 }
2368 \end{code}
2369
2370 %************************************************************************
2371 %*                                                                      *
2372 \subsection[Driver-arg-with-arg]{@grab_arg_arg@: Do an argument with an argument}
2373 %*                                                                      *
2374 %************************************************************************
2375
2376 Some command-line arguments take an argument, e.g.,
2377 \tr{-Rmax-heapsize} expects a number to follow.  This can either be
2378 given a part of the same argument (\tr{-Rmax-heapsize8M}) or as the
2379 next argument (\tr{-Rmax-heapsize 8M}).  We allow both cases.
2380
2381 Note: no error-checking; \tr{-Rmax-heapsize -Rgc-stats} will silently
2382 gobble the second argument (and probably set the heapsize to something
2383 nonsensical).
2384 \begin{code}
2385 sub grab_arg_arg {
2386     local(*Args, $option, $rest_of_arg) = @_;
2387     
2388     if ($rest_of_arg ne '') {
2389         return($rest_of_arg);
2390     } elsif ($#Args >= 0) {
2391         local($temp) = $Args[0]; shift(@Args); 
2392         return($temp);
2393     } else {
2394         print STDERR "$Pgm: no argument following $option option\n";
2395         $Status++;
2396     }
2397 }
2398 \end{code}
2399
2400 \begin{code}
2401 sub isntAntiFlag {
2402     local($flag) = @_;
2403     local($f);
2404
2405 #Not in HsC_antiflag ## NO!: and not already in HsC_flags
2406
2407     foreach $f ( @HsC_antiflags ) {
2408         return(0) if $flag eq $f;
2409     }
2410 #    foreach $f ( @HsC_flags ) {
2411 #       return(0) if $flag eq $f;
2412 #    }
2413     return(1);
2414 }
2415
2416 sub squashHscFlag {  # pretty terrible
2417     local($flag) = @_;
2418     local($f);
2419
2420     foreach $f ( @HsC_flags ) {
2421         if ($flag eq $f) { $f = ''; }
2422     }
2423 }
2424
2425 sub add_Hsc_flags {
2426     local(@flags) = @_;
2427     local($f);
2428
2429     foreach $f ( @flags ) {
2430         push( @HsC_flags, $f ) if &isntAntiFlag($f);
2431     }
2432 }
2433 \end{code}
2434
2435 To add another system library, you'll need to augment the
2436 Supported_syslibs variable with name and info on your addition
2437 to the syslib family. The info bit consist of the following:
2438
2439    - interface file directory
2440        see the misc or posix entry for how to distinguish
2441        between using installed and build tree directories.
2442        
2443    - directory location of archives
2444        
2445    - location of (way-independent) C support libs.
2446        not all libraries need this - if you don't, just
2447        give the empty string.
2448    - list of syslibs you depend on.
2449
2450    - additional ghc command line flags that should be used.
2451    - additional C compiler command line flags that should be used.
2452    - link 
2453
2454
2455 \begin{code}
2456
2457 # Hash to keep track of 
2458 %Syslibs_added = ();
2459
2460 sub add_syslib {
2461     local($syslib) = @_;
2462
2463     # Lifting this out of this sub brings it out of scope - why??
2464     %Supported_syslibs =
2465      ( exts,
2466         [  # where to slurp interface files from
2467           ( $INSTALLING 
2468                ? "$InstLibDirGhc/imports/exts"
2469                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/exts"
2470           )
2471         , # where to find the archive to use when linking
2472           ( $INSTALLING 
2473                ? "$InstLibDirGhc"
2474                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/exts"
2475           )
2476         , '' # no cbits
2477         , '' # Syslib dependencies
2478         , '' # extra ghc opts
2479         , '' # extra cc opts
2480         , '' # extra ld opts
2481         ],
2482
2483        misc,
2484         [  # where to slurp interface files from
2485           ( $INSTALLING 
2486                ? "$InstLibDirGhc/imports/misc"
2487                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/misc"
2488           )
2489         , # where to find the archive to use when linking
2490           ( $INSTALLING 
2491                ? "$InstLibDirGhc"
2492                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/misc"
2493           )
2494         , # where to find the cbits archive to use when linking
2495           ( $INSTALLING 
2496                ? "$InstLibDirGhc"
2497                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/misc/cbits"
2498           )
2499         , 'exts' # Syslib dependencies
2500         , ''     # extra ghc opts
2501         , ''     # extra cc opts
2502         , ( $TargetPlatform =~ /-solaris2$/  ? '-lnsl -lsocket' : '')
2503         ],
2504        hbc,
2505         [  # where to slurp interface files from
2506           ( $INSTALLING 
2507                ? "$InstLibDirGhc/imports/hbc"
2508                : "$TopPwd/CONTRIB/libraries/hbc/src"
2509           )
2510         , # where to find the archive to use when linking
2511           ( $INSTALLING 
2512                ? "$InstLibDirGhc"
2513                : "$TopPwd/CONTRIB/libraries/src/hbc"
2514           )
2515         , # where to find the cbits archive to use when linking
2516           ( $INSTALLING 
2517                ? "$InstLibDirGhc"
2518                : "$TopPwd/CONTRIB/libraries/hbc/cbits"
2519           )
2520         , 'exts' # Syslib dependencies
2521         , ''     # extra ghc opts
2522         , ''     # extra cc opts
2523         , ''
2524         ],
2525        posix,
2526         [  # where to slurp interface files from
2527           ( $INSTALLING 
2528                ? "$InstLibDirGhc/imports/posix"
2529                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/posix"
2530           )
2531         , # where to find the archive to use when linking
2532           ( $INSTALLING 
2533                ? "$InstLibDirGhc"
2534                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/posix"
2535           )
2536         , # where to find the cbits archive to use when linking
2537           ( $INSTALLING 
2538                ? "$InstLibDirGhc"
2539                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/posix/cbits"
2540           )
2541         , 'misc' # Syslib dependencies
2542         , ''     # extra ghc opts
2543         , ''     # extra cc opts
2544         , ''     # extra ld opts
2545         ],
2546        concurrent,
2547         [  # where to slurp interface files from
2548           ( $INSTALLING 
2549                ? "$InstLibDirGhc/imports/concurrent"
2550                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/concurrent"
2551           )
2552         , # where to find the archive to use when linking
2553           ( $INSTALLING 
2554                ? "$InstLibDirGhc"
2555                : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/concurrent"
2556           )
2557         , '' # where to find the cbits archive to use when linking
2558         , '' # Syslib dependencies
2559         , '' # extra ghc opts
2560         , '' # extra cc opts
2561         , '' # extra ld opts
2562         ],
2563        win32,
2564         [  # where to slurp interface files from
2565           ( $INSTALLING 
2566                ? "$InstLibDirGhc/imports/win32"
2567                : "$TopPwd/hslibs/win32/src"
2568           )
2569         , # where to find the archive to use when linking
2570           ( $INSTALLING 
2571                ? "$InstLibDirGhc"
2572                : "$TopPwd/hslibs/win32/src"
2573           )
2574         , ''
2575         , 'exts' # Syslib dependencies
2576         , ''     # extra ghc opts
2577         , ''     # extra cc opts
2578         , '-luser32 -lgdi32'     # extra ld opts
2579         ],
2580        com,
2581         [  # where to slurp interface files from
2582           ( $INSTALLING 
2583                ? "$InstLibDirGhc/imports/com"
2584                : "$TopPwd/hdirect/lib"
2585           )
2586         , # where to find the archive to use when linking
2587           ( $INSTALLING 
2588                ? "$InstLibDirGhc"
2589                : "$TopPwd/hdirect/lib"
2590           )
2591         , ''
2592         , 'exts' # Syslib dependencies
2593         , ''     # extra ghc opts
2594         , ''     # extra cc opts
2595         , '-luser32 -lole32 -loleaut32 -ladvapi32'
2596                  # extra ld opts
2597         ]
2598     );
2599
2600     # check if it's supported..
2601     
2602     if ( !exists $Supported_syslibs{$syslib} ) {
2603        print STDERR "$Pgm: no such system library (-syslib): $syslib\n";
2604        $Status++;
2605        return;
2606     }
2607
2608     # This check is here to avoid syslib loops from
2609     # spoiling the party. A side-effect of it is that
2610     # it disallows multiple mentions of a syslib on a command-line,
2611     # explicit *and* implicit ones (i.e., "-syslib exts -syslib misc"
2612     # is not equal to "-syslib exts -syslib misc -syslib exts",
2613     # which it needs to be)
2614     # 
2615     # Since our current collection of syslibs don't have any
2616     # loops, this test is disabled.
2617     #
2618     # ToDo: loop avoidance scheme when the need arises
2619     #
2620     #return if ( exists $Syslibs_added{$syslib} );
2621         
2622     $Syslibs_added{$syslib} = 1;
2623
2624     local ($hi_dir, $lib_dir, $lib_cbits_dir,
2625            $syslib_deps, $syslib_ghc_opts,
2626            $syslib_cc_opts, $syslib_ld_opts) = @{ $Supported_syslibs{$syslib} };
2627
2628
2629     unshift(@SysImport_dir, $hi_dir);
2630     push(@SysLibrary_dir, $lib_dir);
2631     push(@SysLibrary_dir, $lib_cbits_dir) if ( $lib_cbits_dir ne '');
2632
2633     push(@SysLibrary, "-lHS$syslib");
2634     push(@SysLibrary, "-lHS${syslib}_cbits") if ( $lib_cbits_dir ne '');
2635     push(@SysLibrary, $syslib_ld_opts) if ($syslib_ld_opts ne '');   
2636
2637     # Add on any extra dependencies.
2638     foreach $lib (split(' ',$syslib_deps)) {
2639       &add_syslib($lib);
2640     }
2641 }
2642 \end{code}
2643
2644 Source files may have {-# OPTIONS ... #-} pragmas at the top, containing
2645 command line options we want to append to collection of commands specified
2646 directly. @check_for_source_options@ looks at the top of a de-lit'ified Haskell
2647 file for any such pragmas:
2648
2649 \begin{code}
2650 sub check_for_source_options {
2651     local($file,$ifile) = @_;
2652     local($comment_start,$comment_end);
2653
2654     if ($ifile =~ /\.hc$/ || 
2655         $ifile =~ /_hc$/  || 
2656         $ifile =~ /\.s$/  || 
2657         $ifile =~ /_s$/ ) {  # `Real' C intermediate
2658        $comment_start = "/\\*";
2659        $comment_end   = "\\*/";
2660     } else { # Assume it is a file containing Haskell source
2661        $comment_start = "{-#";
2662        $comment_end   = "#-}";
2663     }
2664
2665     open(FILE,$file) || return(1); # No big loss
2666     
2667     while (<FILE>) {
2668         if ( /^${comment_start} OPTIONS (.*)${comment_end}$/ ) {
2669            # add the options found at the back of the command line.
2670            local(@entries) = split(/\s+/,$1);
2671            print STDERR "Found OPTIONS " . join(' ',@entries) . " in $file\n" if $Verbose;
2672            push(@File_options, @entries);
2673         }
2674         elsif ( /^$/ ) { # ignore empty lines
2675            ;
2676         }
2677         elsif ( /^#line.+$/ ) { # ignore comment lines (unused..ToDo: rm )
2678            ;
2679         }
2680         elsif ( /^{-# LINE.+$/ ) { # ignore line pragmas
2681            ;
2682         }
2683         else { # stop looking, something non-empty / not
2684                # ${comment_start} OPTIONS .. ${comment_end} encountered.
2685             close(FILE);return(0);
2686         }
2687     }
2688     close(FILE);
2689     return(0);
2690 }
2691 \end{code}
2692
2693
2694 We split the initial argv up into three arrays:
2695
2696   - @Cmd_opts 
2697   - @Link_file
2698   - @Input_file
2699
2700 the reason for doing so is to be able to deal
2701 with {-# OPTIONS #-} pragma in source files properly.
2702
2703 \begin{code}
2704 sub splitCmdLine {
2705     local(@args) = @_;
2706
2707 arg: while($_ = $args[0]) {
2708     shift(@args);
2709     # sigh, we have to deal with these -option arg specially here.
2710     /^-(tmpdir|odir|ohi|o|isuf|osuf|hisuf|odump|syslib)$/ && 
2711        do { push(@Cmd_opts, $_); push(@Cmd_opts,$args[0]); shift(@args); next arg; };
2712     /^--?./  && do { push(@Cmd_opts, $_); next arg; };
2713
2714     if (/\.([^_]+_)?[oa]$/) {
2715         push(@Link_file, $_);
2716     } else {
2717         push(@Input_file, $_);
2718     }
2719
2720     # input files must exist:
2721     if (! -f $_) {
2722         print STDERR "$Pgm: input file doesn't exist: $_\n";
2723         $Status++;
2724     }
2725   }
2726 }    
2727
2728 \end{code}
2729
2730 When saving an intermediate file (.hc or .s) away, we 
2731 have to prefix any OPTIONS found in the original source file.
2732
2733 \begin{code}
2734 sub saveIntermediate { 
2735   local ($final,$suffix,$tmp)= @_ ;
2736   local ($to_do);
2737
2738   # $final  -- root of where to park ${final}.${suffix}
2739   # $tmp    -- temporary file where hsc put the intermediate file.
2740
2741   # Delete the old file
2742   $to_do = "$Rm ${final}.${suffix}"; &run_something($to_do, "Removing old .${suffix} file");
2743
2744   if ( $#File_options >= 0 ) { # OPTIONS found in Haskell source unit
2745     # Add OPTION comment to the top of the generated .${suffix} file
2746     open(TEMP, "> ${final}.${suffix}") || &tidy_up_and_die(1,"Can't open ${final}.${suffix}\n");
2747     print TEMP "/* OPTIONS " . join(' ',@File_options) . " */\n";
2748     close(TEMP);
2749     print STDERR "Prepending OPTIONS: " . join(' ',@File_options) . " to ${final}.${suffix}\n" if $Verbose;
2750   }
2751   $to_do = "$Cat $tmp  >> ${final}.${suffix}";
2752   &run_something($to_do, "Saving copy of .${suffix} file");
2753
2754 }
2755
2756 \end{code}
2757
2758
2759 Command-line processor
2760
2761 \begin{code}
2762 sub processArgs {
2763     local(@Args) = @_;
2764
2765 # can't use getopt(s); what we want is too complicated
2766
2767 arg: while($_ = $Args[0]) {
2768     shift(@Args);
2769
2770     #---------- help -------------------------------------------------------
2771     if (/^-\?$/ || /^--?help$/) { print $LongUsage; exit $Status; }
2772
2773     #-----------version ----------------------------------------------------
2774     /^--version$/   && do { print STDERR "${ProjectName}, version ${ProjectVersion}, patchlevel ${ProjectPatchLevel}\n"; exit $Status; };
2775
2776     #---------- verbosity and such -----------------------------------------
2777     /^-v$/          && do { $Verbose = '-v'; $Time = 'time'; next arg; };
2778
2779     #---------- what phases are to be run ----------------------------------
2780     /^-(no-)?recomp/        && do { $Do_recomp_chkr = ($1 eq '') ? 1 : 0; next arg; };
2781
2782     /^-cpp$/        && do { $Cpp_flag_set = 1; next arg; };
2783     # change the global default:
2784     # we won't run cat; we'll run the real thing
2785         
2786     /^-C$/          && do { $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0; $HscOut = '-C=';
2787                             next arg; };
2788     # stop after generating C
2789         
2790     /^-noC$/        && do { $HscOut = '-N='; $ProduceHi = '-nohifile=';
2791                             $Do_cc = 0; $Do_as = 0; $Do_lnkr = 0;
2792                             next arg; };
2793     # leave out actual C generation (debugging) [also turns off interface gen]
2794
2795
2796     /^-hi$/              && do { $HiOnStdout = 1; $ProduceHi = '-hifile='; next arg; };
2797     # _do_ generate an interface; usually used as: -noC -hi
2798     /^-hi-with-(.*)$/    && do { $HiOnStdout = 1; $HiWith .= " $1" ; $ProduceHi = '-hifile='; next arg; };
2799     # limit ourselves to outputting a particular section.
2800
2801     /^-nohi$/       && do { $ProduceHi = '-nohifile='; next arg; };
2802     # don't generate an interface (even if generating C)
2803
2804     /^-hi-diffs$/             && do { $HiDiff_flag  = 'normal'; next arg; };
2805     /^-hi-diffs-with-usages$/ && do { $HiDiff_flag  = 'usages'; next arg; };
2806     /^-no-hi-diffs$/          && do { $HiDiff_flag  = '';       next arg; };
2807     /^-keep-hi-diffs$/        && do { $Keep_HiDiffs = 1; next arg; };
2808
2809     # show/disable diffs if the interface file changes
2810
2811     /^-E$/          && do { push(@CcBoth_flags, '-E');
2812                             $Only_preprocess_C = 1;
2813                             $Do_as = 0; $Do_lnkr = 0; next arg; };
2814     # stop after preprocessing C
2815     /^-M$/          && do { $Only_generate_deps = 1; $Do_as = 0; $Do_lnkr = 0; next arg; };
2816     # only generate dependency information.
2817     /^--mk-dll$/    && do { $Only_generate_dll  = 1; $Do_as = 0; $Do_lnkr = 0; next arg; };
2818     # Build a Win32 DLL (where supported).
2819     /^-S$/          && do { $Do_as = 0; $Do_lnkr = 0; next arg; };
2820     # stop after generating assembler
2821         
2822     /^-c$/          && do { $Do_lnkr = 0; next arg; };
2823     # stop after generating .o files
2824
2825     /^-link-chk$/    && do { $LinkChk = 1; next arg; };
2826     # don't do consistency-checking after a link
2827     /^-no-link-chk$/ && do { $LinkChk = 0; next arg; };
2828
2829     /^-tmpdir$/ && do { $Tmp_prefix = &grab_arg_arg(*Args,'-tmpdir', '');
2830                         $Tmp_prefix = "$Tmp_prefix/ghc$$";
2831                         $ENV{'TMPDIR'} = $Tmp_prefix; # for those who use it...
2832                         next arg; };
2833     # use an alternate directory for temp files
2834
2835     #---------- redirect output --------------------------------------------
2836
2837     # -o <file>; applies to the last phase, whatever it is
2838     # "-o -" sends it to stdout
2839     # if <file> has a directory component, that dir must already exist
2840
2841     /^-odir$/       && do { $Specific_output_dir = &grab_arg_arg(*Args,'-odir', '');
2842                             #
2843                             # Hack, of the worst sort: don't do validation of
2844                             # odir argument if you're using -M (dependency generation).
2845                             #
2846                             if ( ! $Only_generate_deps && ! -d $Specific_output_dir) {
2847                                 print STDERR "$Pgm: -odir: no such directory: $Specific_output_dir\n";
2848                                 $Status++;
2849                             }
2850                             next arg; };
2851
2852     /^-o$/          && do { $Specific_output_file = &grab_arg_arg(*Args,'-o', '');
2853                             if ($Specific_output_file ne '-'
2854                              && $Specific_output_file =~ /(.*)\/[^\/]*$/) {
2855                                 local($dir_part) = $1;
2856                                 if (! -d $dir_part) {
2857                                     print STDERR "$Pgm: no such directory: $dir_part\n";
2858                                     $Status++;
2859                                 }
2860                             }
2861                             next arg; };
2862
2863     # NB: -isuf not documented yet (because it doesn't work yet)
2864     /^-isuf$/       && do { $Isuffix  = &grab_arg_arg(*Args,'-isuf', '');
2865                             if ($Isuffix =~ /\./ ) {
2866                                 print STDERR "$Pgm: -isuf suffix shouldn't contain a .\n";
2867                                 $Status++;
2868                             }
2869                             next arg; };
2870
2871     /^-osuf$/       && do { $Osuffix  = &grab_arg_arg(*Args,'-osuf', '');
2872                             if ($Osuffix =~ /\./ ) {
2873                                 print STDERR "$Pgm: -osuf suffix shouldn't contain a .\n";
2874                                 $Status++;
2875                             }
2876                             next arg; };
2877
2878     # -ohi <file>; send the interface to <file>; "-ohi -" to send to stdout
2879     /^-ohi$/        && do { $Specific_hi_file = &grab_arg_arg(*Args,'-ohi', '');
2880                             if ($Specific_hi_file ne '-'
2881                              && $Specific_hi_file =~ /(.*)\/[^\/]*$/) {
2882                                 local($dir_part) = $1;
2883                                 if (! -d $dir_part) {
2884                                     print STDERR "$Pgm: no such directory: $dir_part\n";
2885                                     $Status++;
2886                                 }
2887                             }
2888                             $ProduceHi='-hifile=';
2889                             next arg; };
2890
2891     # The suffix to use when looking for interface files
2892     /^-hisuf$/      && do { $HiSuffix = &grab_arg_arg(*Args,'-hisuf', '');
2893                             if ($HiSuffix =~ /\./ ) {
2894                                 print STDERR "$Pgm: -hisuf suffix shouldn't contain a .\n";
2895                                 $Status++;
2896                             }
2897                             next arg; };
2898     /^-odump$/      && do { $Specific_dump_file = &grab_arg_arg(*Args,'-odump', '');
2899                             if ($Specific_dump_file =~ /(.*)\/[^\/]*$/) {
2900                                 local($dir_part) = $1;
2901                                 if (! -d $dir_part) {
2902                                     print STDERR "$Pgm: no such directory: $dir_part\n";
2903                                     $Status++;
2904                                 }
2905                             }
2906                             next arg; };
2907
2908     #-------------- scc & Profiling Stuff ----------------------------------
2909
2910     /^-prof$/ && do { $PROFing = 'p'; next arg; }; # profiling -- details later!
2911
2912     /^-auto-dicts$/ && do {
2913                 $PROFdicts = '-fauto-sccs-on-dicts';
2914                 next arg; };
2915     /^-auto-all$/ && do {
2916                 $PROFauto = '-fauto-sccs-on-all-toplevs';
2917                 next arg; };
2918     /^-auto$/ && do {
2919                 $PROFauto = '-fauto-sccs-on-exported-toplevs';
2920                 next arg; };
2921
2922     /^-caf-all/ && do { # generate individual CAF SCC annotations
2923                 $PROFcaf = '-fauto-sccs-on-individual-cafs';
2924                 next arg; };
2925
2926     /^-ignore-scc$/ && do {
2927                 # forces ignore of scc annotations even if profiling
2928                 $PROFignore_scc = '-W';
2929                 next arg; };
2930
2931     /^-G(.*)$/  && do { push(@HsC_flags, "-G=$1");   # set group for cost centres
2932                         next arg; };
2933
2934     /^-unprof-scc-auto/ && do {
2935                 # generate auto SCCs on top level bindings when not profiling.
2936                 # Used to measure optimisation effects of presence of sccs.
2937                 $UNPROFscc_auto = ( /-all/ )
2938                             ? '-fauto-sccs-on-all-toplevs'
2939                             : '-fauto-sccs-on-exported-toplevs';
2940                 next arg; };
2941
2942     #--------- ticky/parallel ----------------------------------------------
2943     # we sort out the details a bit later on
2944
2945     /^-gransim$/    && do { $GRANing   = 'g'; &add_syslib('concurrent'); next arg; }; # GranSim
2946     /^-ticky$/      && do { $TICKYing  = 't'; next arg; }; # ticky-ticky
2947     /^-parallel$/   && do { $PARing    = 'p'; &add_syslib('concurrent'); next arg; }; # parallel Haskell
2948
2949     #-------------- "user ways" --------------------------------------------
2950
2951     (/^-user-setup-([a-oA-Z])$/ ) && 
2952            do {
2953                 /^-user-setup-([a-oA-Z])$/  && do { $BuildTag = "_$1"; };
2954
2955                 local($stuff) = $UserSetupOpts{$BuildTag};
2956                 local(@opts)  = split(/\s+/, $stuff);
2957                 
2958                 # feed relevant ops into the arg-processing loop (if any)
2959                 unshift(@Args, @opts) if $#opts >= 0;
2960
2961                 next arg; };
2962
2963     #---------- set search paths for libraries and things ------------------
2964
2965     # we do -i just like HBC (-i clears the list; -i<colon-separated-items>
2966     # prepends the items to the list); -I is for including C .h files.
2967
2968     /^-i$/          && do { @Import_dir = ();  # import path cleared!
2969                             @SysImport_dir = ();
2970                             print STDERR "WARNING: import paths cleared by `-i'\n";
2971                             next arg; };
2972
2973     /^-i(.*)/       && do { local(@new_items)
2974                               = split( /:/, &grab_arg_arg(*Args,'-i', $1));
2975                             unshift(@Import_dir, @new_items);
2976                             next arg; };
2977
2978     /^-I(.*)/       && do { push(@Include_dir,     &grab_arg_arg(*Args,'-I', $1)); next arg; };
2979     /^-L(.*)/       && do { push(@UserLibrary_dir, &grab_arg_arg(*Args,'-L', $1)); next arg; };
2980     /^-l(.*)/       && do { push(@UserLibrary,'-l'.&grab_arg_arg(*Args,'-l', $1)); next arg; };
2981
2982     /^-syslib(.*)/  && do { local($syslib) = &grab_arg_arg(*Args,'-syslib',$1);
2983                             &add_syslib($syslib);
2984                             next arg; };
2985
2986     #=======================================================================
2987     # various flags that we can harmlessly send to one program or another
2988     # (we will later "reclaim" some of the compiler ones now sent to gcc)
2989     #=======================================================================
2990
2991     #---------- this driver itself (ghc) -----------------------------------
2992     # these change what executable is run for each phase:
2993     /^-pgmL(.*)$/   && do { $Unlit      = $1; next arg; };
2994     /^-pgmP(.*)$/   && do { $HsCpp      = $1; next arg; };
2995     /^-pgmC(.*)$/   && do { $HsC        = $1; next arg; };
2996     /^-pgmcO?(.*)$/ && do { $CcRegd     = $1; next arg; }; # the O? for back compat
2997     /^-pgma(.*)$/   && do { $As         = $1; next arg; };
2998     /^-pgml(.*)$/   && do { $Lnkr       = $1; next arg; };
2999     /^-pgmdep(.*)$/ && do { $MkDependHS = $1; next arg; };
3000
3001     #---------- the get-anything-through opts (all pgms) -------------------
3002     # these allow arbitrary option-strings to go to any phase:
3003     /^-optL(.*)$/   && do { push(@Unlit_flags,      $1); next arg; };
3004     /^-optP(.*)$/   && do { push(@HsCpp_flags,      $1); next arg; };
3005     /^-optCrts(.*)$/&& do { push(@HsC_rts_flags,    $1); next arg; };
3006     /^-optC(.*)$/   && do { push(@HsC_flags,        $1); next arg; };
3007     /^-optcpp(.*)$/ && do { push(@Cpp_define,       $1); $Only_preprocess_hc = ($1 eq "-E"); next arg; };
3008     /^-optc(.*)$/   && do { push(@CcBoth_flags,     $1); next arg; };
3009     /^-opta(.*)$/   && do { push(@As_flags,         $1); next arg; };
3010     /^-optl(.*)$/   && do { push(@Ld_flags,         $1); next arg; };
3011     /^-optdll(.*)$/ && do { push(@Dll_flags,        $1); next arg; };
3012     /^-optdep(.*)$/ && do { push(@MkDependHS_flags, $1); next arg; };
3013
3014     #---------- Haskell C pre-processor (hscpp) ----------------------------
3015     /^-D(.*)/       && do { push(@HsCpp_flags, "'-D".&grab_arg_arg(*Args,'-D',$1)."'"); next arg; };
3016     /^-U(.*)/       && do { push(@HsCpp_flags, "'-U".&grab_arg_arg(*Args,'-U',$1)."'"); next arg; };
3017
3018     #---------- post-Haskell "assembler"------------------------------------
3019     /^-ddump-raw-asm$/            && do { $Dump_raw_asm        = 1; next arg; };
3020     /^-ddump-asm-splitting-info$/ && do { $Dump_asm_splitting_info = 1; next arg; };
3021
3022     #---------- Haskell compiler (hsc) -------------------------------------
3023
3024     /^-keep-hc-files?-too$/     && do { $Keep_hc_file_too = 1; next arg; };
3025     /^-keep-s-files?-too$/      && do { $Keep_s_file_too = 1;  next arg; };
3026
3027     /^-fignore-interface-pragmas$/ && do { push(@HsC_flags, $_); next arg; };
3028     /^-fignore-asserts$/           && do { push(@HsC_flags, $_); next arg; };
3029
3030     /^-fno-implicit-prelude$/      && do { $NoImplicitPrelude= 1; push(@HsC_flags, $_); next arg; };
3031
3032      #
3033      # have the compiler proper generate concurrent code,
3034      # really only used when you want to configure your own
3035      # special user compilation way.
3036      #
3037      # (ditto for -fgransim, fscc-profiling, -fparallel and -fticky-ticky)
3038      #
3039     /^-fscc-profiling$/   && do { push(@HsC_flags,$_); next arg; };
3040     /^-fticky-ticky$/     && do { push(@HsC_flags,$_); next arg; };
3041     /^-fgransim$/         && do { push(@HsC_flags,$_); next arg; };
3042     /^-fparallel$/        && do { push(@HsC_flags,$_); next arg; };
3043
3044     /^-split-objs$/     && do {
3045                         if ( $TargetPlatform !~ /^(alpha|hppa1\.1|i386|m68k|mips|powerpc|rs6000|sparc)-/ ) {
3046                             $SplitObjFiles = 0;
3047                             print STDERR "WARNING: don't know how to split objects on this platform: $TargetPlatform\n`-split-objs' option ignored\n";
3048                         } else {
3049                             $SplitObjFiles = 1;
3050                             $HscOut = '-C=';
3051
3052                             push(@HsC_flags, "-fglobalise-toplev-names"); 
3053                             push(@CcBoth_flags, '-DUSE_SPLIT_MARKERS');
3054
3055                             require('ghc-split.prl')
3056                              || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-split.prl!\n");
3057                         }
3058                         next arg; };
3059
3060     /^-unreg$/              && do { $UNREGing = 'u'; next arg; };
3061     /^-funregisterised$/    && do { push(@HsC_flags, $_); next arg; };
3062     /^-fno-asm-mangling$/   && do { $DoAsmMangling = 0; next arg; };
3063
3064     /^-fallow-overlapping-instances$/ && do { push(@HsC_flags, $_); next arg; };
3065     /^-fallow-undecidable-instances$/ && do { push(@HsC_flags, $_); next arg; };
3066     /^-fhistory-size.*$/              && do { push(@HsC_flags, $_); next arg; };
3067     /^-fglasgow-exts$/
3068                 && do { push(@HsC_flags, $_);
3069
3070                         # -fglasgow-exts implies -syslib exts
3071                         &add_syslib('exts');
3072
3073                         next arg; };
3074
3075     /^-fspeciali[sz]e$/
3076                 && do { $Oopt_DoSpecialise = '-fspecialise'; next arg; };
3077     /^-fno-speciali[sz]e$/
3078                 && do { $Oopt_DoSpecialise = ''; next arg; };
3079
3080     /^-fusagesp$/
3081                 && do {  $Oopt_UsageSPInf = '-fusagesp';
3082                          push (@HsC_flags, '-fusagesp-on'); next arg; };
3083
3084     /^-fcompiling-prelude$/ && do { $CompilingPrelude=1; push(@HsC_flags, $_); next arg; };
3085
3086 # Now the foldr/build options, which are *on* by default (for -O).
3087
3088     /^-ffoldr-build$/
3089                     && do { $Oopt_FoldrBuild = 1; 
3090                             #print "Yes F/B\n";
3091                             next arg; };
3092
3093     /^-fno-foldr-build$/
3094                     && do { $Oopt_FoldrBuild = 0; 
3095                             next arg; };
3096
3097     # --------------- Renamer -------------
3098
3099
3100     /^-fno-prune-tydecls$/     && do { push(@HsC_flags, $_); next arg; };
3101     /^-fno-prune-instdecls$/     && do { push(@HsC_flags, $_); next arg; };
3102
3103     # ---------------
3104
3105     /^-fasm-(.*)$/  && do { $HscOut = '-S='; next arg; }; # force using nativeGen
3106     /^-fvia-[cC]$/          && do { $HscOut = '-C='; next arg; }; # force using C compiler
3107
3108     # ---------------
3109
3110     /^-funfolding-.*$/
3111                     && do { push(@HsC_flags, $_); next arg };
3112
3113     /^-funfold-casms-in-hi-file$/
3114                     && do { push(@HsC_flags, $_); next arg };
3115
3116     /^(-fmax-simplifier-iterations)(.*)$/
3117                     && do { $Oopt_MaxSimplifierIterations = $1 . &grab_arg_arg(*Args,$1, $2);
3118                             next arg; };
3119
3120     /^-fno-pedantic-bottoms$/
3121                     && do { $Oopt_PedanticBottoms = ''; next arg; };
3122
3123     /^-fno-pre-inlining$/
3124                     && do { push(@HsC_flags, $_); next arg };
3125
3126     /^-fno-let-from-(case|app|strict-let)$/ # experimental, really (WDP 95/10)
3127                     && do { push(@HsC_flags, $_); next arg; };
3128
3129     /^-funbox-strict-fields$/
3130                    && do { push(@HsC_flags, $_); next arg; };
3131
3132     # --------------- Warnings etc. ------
3133
3134     /^-fwarn-(.*)$/      && do { push(@HsC_flags, $_); next arg; };
3135
3136     /^-fno-(.*)$/   && do { push(@HsC_antiflags, "-f$1");
3137                             &squashHscFlag("-f$1");
3138                             next arg; };
3139
3140     /^-W$/          && do { push(@HsC_flags, @MinusWOpts); next arg; };
3141     /^-Wall$/       && do { push(@HsC_flags, @MinusWallOpts); next arg; };
3142     /^(-Wnot|w)$/   && do { foreach (@Hsc_flags) {
3143                                 /^-fwarn-(.*)$/ && do { $_=''; };
3144                             };
3145                             push(@HsC_antiflags, @StandardWarnings);
3146                             next arg; };
3147
3148     # --------------- fun stuff ----------------
3149
3150     /^-freport-compile$/ && do { push(@HsC_flags, $_); next arg; };
3151
3152     # --------------- platform specific flags (for gcc mostly) ----------------
3153
3154     /^-mlong-calls$/ && do { # for GCC for HP-PA boxes,
3155                              # for 2.6.x..?, does not apply for 2.7.2
3156                              # any longer.
3157                             unshift(@CcBoth_flags, ( $_ ));
3158                             next arg; };
3159
3160     /^-m(v8|sparclite|cypress|supersparc|cpu=(cypress|supersparc))$/
3161                      && do { # for GCC for SPARCs
3162                             unshift(@CcBoth_flags, ( $_ ));
3163                             next arg; };
3164
3165     /^-monly-([432])-regs/ && do { # for iX86 boxes only; no effect otherwise
3166                             $StolenX86Regs = $1;
3167                             next arg; };
3168
3169     #*************** ... and lots of debugging ones (form: -d* )
3170
3171     # -d(no-)core-lint is done this way so it is turn-off-able.
3172     /^-dcore-lint/       && do { $CoreLint = '-dcore-lint'; next arg; };
3173     /^-dno-core-lint/    && do { $CoreLint = '';            next arg; };
3174     # Ditto for USP lint
3175     /^-dusagesp-lint/    && do { $USPLint = '-dusagesp-lint'; next arg; };
3176     /^-dno-usagesp-lint/ && do { $USPLint = '';               next arg; };
3177     # Ditto for STG lint
3178     /^-dstg-lint/       && do { $StgLint = '-dstg-lint'; next arg; };
3179     /^-dno-stg-lint/    && do { $StgLint = '';           next arg; };
3180
3181     /^-d(dump|ppr)-/         && do { push(@HsC_flags, $_); next arg; };
3182     /^-dverbose-(simpl|stg)/ && do { push(@HsC_flags, $_); next arg; };
3183     /^-dshow-passes/         && do { push(@HsC_flags, $_); next arg; };
3184     /^-dshow-rn-stats/       && do { push(@HsC_flags, $_); next arg; };
3185     /^-dshow-rn-trace/       && do { push(@HsC_flags, $_); next arg; };
3186     /^-dsource-stats/        && do { push(@HsC_flags, $_); next arg; };
3187     /^-dsimplifier-stats/    && do { push(@HsC_flags, $_); next arg; };
3188     /^-dstg-stats/           && do { $Oopt_StgStats = $_; next arg; };
3189
3190     #*************** ... and now all these -R* ones for its runtime system...
3191
3192     /^-Rscale-sizes?(.*)/ && do {
3193         $Scale_sizes_by = &grab_arg_arg(*Args,'-Rscale-sizes', $1);
3194         next arg; };
3195
3196     /^(-H|-Rmax-heapsize)(.*)/ && do {
3197         local($heap_size) = &grab_arg_arg(*Args,$1, $2);
3198         if ($heap_size =~ /(\d+)[Kk]$/) {
3199             $heap_size = $1 * 1000;
3200         } elsif ($heap_size =~ /(\d+)[Mm]$/) {
3201             $heap_size = $1 * 1000 * 1000;
3202         } elsif ($heap_size =~ /(\d+)[Gg]$/) {
3203             $heap_size = $1 * 1000 * 1000 * 1000;
3204         }
3205         if ($heap_size <= 0) {
3206             print STDERR "$Pgm: resetting heap-size to zero!!! $heap_size\n";
3207             $Specific_heap_size = 0;
3208         
3209         # if several heap sizes given, take the largest...
3210         } elsif ($heap_size >= $Specific_heap_size) {
3211             $Specific_heap_size = $heap_size;
3212         } else {
3213             print STDERR "$Pgm: ignoring heap-size-setting option ($_)...not the largest seen\n";
3214         }
3215         next arg; };
3216
3217     /^(-K|Rmax-(stk|stack)size)(.*)/ && do {
3218         local($flag) = $1;
3219         local($stk_size) = &grab_arg_arg(*Args,'-Rmax-stksize', $3);
3220         if ($stk_size =~ /(\d+)[Kk]$/) {
3221             $stk_size = $1 * 1000;
3222         } elsif ($stk_size =~ /(\d+)[Mm]$/) {
3223             $stk_size = $1 * 1000 * 1000;
3224         } elsif ($stk_size =~ /(\d+)[Gg]$/) {
3225             $stk_size = $1 * 1000 * 1000 * 1000;
3226         }
3227         if ($stk_size <= 0) {
3228             print STDERR "$Pgm: resetting stack-size to zero!!! $stk_size\n";
3229             $Specific_stk_size = 0;
3230
3231         # if several stack sizes given, take the largest...
3232         } elsif ($stk_size >= $Specific_stk_size) {
3233             $Specific_stk_size = $stk_size;
3234         } else {
3235             print STDERR "$Pgm: ignoring stack-size-setting option ($flag $stk_size)...not the largest seen\n";
3236         }
3237         next arg; };
3238
3239     /^-Rgc-stats$/ && do {  $CollectingGCstats++;
3240                             # the two RTSs do this diff ways; we will try to compensate
3241                             next arg; };
3242
3243     /^-Rghc-timing/ && do { $CollectGhcTimings = 1; next arg; };
3244
3245     #---------- C high-level assembler (gcc) -------------------------------
3246     /^-(Wall|ansi|pedantic)$/ && do { push(@CcBoth_flags, $_); next arg; };
3247
3248     # -dgcc-lint is a useful way of making GCC very fussy.
3249     # From alan@spri.levels.unisa.edu.au (Alan Modra).
3250     /^-dgcc-lint$/ && do { push(@CcBoth_flags, '-Wall -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs'); next arg; };
3251     # An alternate set, from mark@sgcs.com (Mark W. Snitily)
3252     # -Wall -Wstrict-prototypes -Wmissing-prototypes -Wcast-align -Wshadow
3253
3254     # inject "#include <wurble>" into the compiler's C output!
3255
3256     /^-#include(.*)/    && do {
3257         local($to_include) = &grab_arg_arg(*Args,'-#include', $1);
3258         push(@CcInjects, "#include $to_include\n");
3259         next arg; };
3260
3261     #---------- Linker (gcc, really) ---------------------------------------
3262
3263     /^-static$/         && do { $Static=1; push(@Ld_flags, $_); next arg; };
3264     /^-no-hs-main$/     && do { $NoHaskellMain=1; next arg;    };
3265
3266     #---------- mixed cc and linker magic ----------------------------------
3267     # this optimisation stuff is finally sorted out later on...
3268
3269     /^-O2-for-C$/ && do { $MinusO2ForC = 1; next arg; };
3270
3271     /^-O[1-2]?$/ && do {
3272                 local($opt_lev) = ( /^-O2$/ ) ? 2 : 1; # max 'em
3273                 $OptLevel = ( $opt_lev > $OptLevel ) ? $opt_lev : $OptLevel;
3274
3275                 $HscOut = '-C=' if $OptLevel == 2; # force use of C compiler
3276                 next arg; };
3277
3278     /^-Onot$/   && do { $OptLevel = 0; next arg; }; # # set it to <no opt>
3279
3280     /^-Ofile(.*)/ && do {
3281                 $OptLevel = 3;
3282                 local($ofile) = &grab_arg_arg(*Args,'-Ofile', $1);
3283                 @HsC_minusO3_flags = ();
3284
3285                 open(OFILE, "< $ofile") || die "Can't open $ofile!\n";
3286                 while (<OFILE>) {
3287                     chop;
3288                     s/\#.*//;       # death to comments
3289                     s/[ \t]+//g;    # death to whitespace
3290                     next if /^$/;   # ditto, blank lines
3291                     s/([()*{}])/\\$1/g;    # protect shell metacharacters
3292                     if ( /^C:(.*)/ ) {
3293                         push(@CcBoth_flags, $1);
3294                     } else {
3295                         push(@HsC_minusO3_flags, $_);
3296                     }
3297                 }
3298                 close(OFILE);
3299                 next arg; };
3300
3301     /^-debug$/  && do { # all this does is mark a .hc/.o as "debugging"
3302                         # in the consistency info
3303                         $DEBUGging = 'd';
3304                         next arg; };
3305
3306     #---------- linking .a file --------------------------------------------
3307
3308     /^-Main(.*)/ && do {
3309                 # specifies main or mainPrimIO to be linked
3310                 $Ld_main = $1;
3311                 next arg; }; 
3312
3313     #---------- catch unrecognized flags -----------------------------------
3314
3315     /^-./ && do {
3316         print STDERR "$Pgm: unrecognised option: $_\n";
3317         $Status++;
3318         next arg; };
3319
3320 }
3321
3322 } # end of processArgs
3323
3324 \end{code}