ghc.lprl 108 KB
Newer Older
1
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1997
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
%

This is the driver script for the Glasgow Haskell compilation system.
It is written in \tr{perl}.  The first section includes a long
``usage'' message that describes how the driver is supposed to work.

%************************************************************************
%*									*
\section[Driver-usage]{Usage message}
%*									*
%************************************************************************

\begin{code}
($Pgm = $0) =~ s|.*/||;
$ShortUsage  =  "\nUsage: For basic information, try the `-help' option.\n";
$LongUsage = "\n" . <<EOUSAGE;
Use of the Glorious Haskell Compilation System driver:

    $Pgm [command-line-options-and-input-files]

------------------------------------------------------------------------
This driver ($Pgm) guides each input file through (some of the)
possible phases of a compilation:

    - unlit:	extract code from a "literate program"
    - hscpp:	run code through the C pre-processor (if -cpp flag given)
    - hsc:	run the Haskell compiler proper
    - gcc:	run the C compiler (if compiling via C)
30
31
    - as:	run the assembler
    - ld:	run the linker
32
33
34

For each input file, the phase to START with is determined by the
file's suffix:
35
    - .lhs	literate Haskell: unlit
36
    - .hs	illiterate Haskell: hsc
37
38
39
40
41
42
43
44
45
46
47
    - .hc	C from the Haskell compiler: gcc
    - .c	C not from the Haskell compiler: gcc
    - .s	assembly language: as
    - other	passed directly to the linker: ld

If no files are given on the command line, input is taken from
standard input, and processing is as for an .hs file.  (All output is
to stdout or stderr, however).

The phase at which to STOP processing is determined by a command-line
option:
sof's avatar
sof committed
48
    -E		stop after generating preprocessed, de-litted Haskell (used in conjunction with -cpp)
49
50
51
52
53
54
    -C		stop after generating C (.hc output)
    -S		stop after generating assembler (.s output)
    -c		stop after generating object files (.o output)

Other commonly-used options are:

55
    -O		An `optimising' package of compiler flags, for faster code
56
57
58
59
60
61
62
63

    -prof	Compile for cost-centre profiling
		(add -auto for automagic cost-centres on top-level functions)

    -fglasgow-exts  Allow Glasgow extensions (unboxed types, etc.)

    -H14m	Increase compiler's heap size

64
65
    -M          Output the Makefile rules recording the
                dependencies of a list of Haskell files.
sof's avatar
sof committed
66
67
68
	        (ghc driver script calls upon the help of a
                 compatible mkdependHS script to do the actual
		 processing)
69

70
71
72
73
74
75
The User's Guide has more information about GHC's *many* options.

Given the above, here are some TYPICAL invocations of $Pgm:

    # compile a Haskell module to a .o file, optimising:
    % $Pgm -c -O Foo.hs
76
77
    # link three .o files into an executable called "test":
    % $Pgm -o test Foo.o Bar.o Baz.o
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    # compile a Haskell module to C (a .hc file), using a bigger heap:
    % $Pgm -C -H16m Foo.hs
    # compile Haskell-produced C (.hc) to assembly language:
    % $Pgm -S Foo.hc
------------------------------------------------------------------------
EOUSAGE
\end{code}

%************************************************************************
%*									*
\section[Driver-init]{Initialisation}
%*									*
%************************************************************************

92
93
94
95
96
97
98
99
100
The driver script need to be told where to find these executables, so
in the course of building the driver `executable', make-variables holding
these are prepended to the de-litted version of this file. The variables are:

\begin{verbatim}
INSTALLING

HOSTPLATFORM TARGETPLATFORM

101
ProjectName ProjectVersion ProjectVersionInt ProjectPatchLevel 
102

sof's avatar
sof committed
103
104
HscMajorVersion HscMinorVersion CcMajorVersion CcMinorVersion

105
106
TOP_PWD

sof's avatar
sof committed
107
bindir libdir libexecdir datadir
108
109
110
111
112
113
114
115
116

CURRENT_DIR TMPDIR

GHC_LIB_DIR GHC_RUNTIME_DIR GHC_UTILS_DIR GHC_INCLUDE_DIR

GHC_OPT_HILEV_ASM GhcWithNativeCodeGen

GHC_UNLIT GHC_HSCPP GHC_HSC GHC_SYSMAN

sof's avatar
sof committed
117
CP RM CONTEXT_DIFF
118
119
120
121
122
123
124
125
126
127

WAY_*_NAME WAY_*_HC_OPTS

LeadingUnderscore

\end{verbatim}

Establish what executables to run for the various phases, what the
default options are for those phases, and other similar boring stuff.

128
129
130
\begin{code}
select(STDERR); $| = 1; select(STDOUT); # no STDERR buffering, please.

131
$TargetPlatform = $TARGETPLATFORM;
132

133
134
135
$TopPwd	           = "${TOP_PWD}";
$InstBinDirGhc     = "${bindir}";
$InstLibDirGhc     = "${libdir}";
sof's avatar
sof committed
136
137
138
139
140
#
# Normally the same as InstLibDirGhc, but we accommodate
# for it being separate.
#
$InstLibExecDirGhc = "${libexecdir}";
141
$InstDataDirGhc    = "${datadir}";
142

143
144
145
146
147
148
149
150
151
152
$Status  = 0; # just used for exit() status
$Verbose = '';

# set up signal handler
sub quit_upon_signal { &tidy_up_and_die(1, ''); }
$SIG{'INT'}  = 'quit_upon_signal';
$SIG{'QUIT'} = 'quit_upon_signal';

# where to get "require"d .prl files at runtime (poor man's dynamic loading)
#   (use LIB, not DATA, because we can't be sure of arch-independence)
153
154
@INC = ( ( $INSTALLING ) ? $InstLibDirGhc
			   : "$TopPwd/${CURRENT_DIR}" );
155
156
157
158

if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
    $Tmp_prefix = ($ENV{'TMPDIR'} . "/ghc$$");
} else {
159
160
161
    print STDERR "TMPDIR has not been set to anything useful!\n" if (${TMPDIR} eq '');
    $Tmp_prefix ="${TMPDIR}/ghc$$"; # TMPDIR set via Makefile when booting..
    $ENV{'TMPDIR'} = ${TMPDIR}; # set the env var as well
162
163
}

sof's avatar
sof committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Some shells run into real trouble when command line and environment
# gets big (e.g., cmd lines of >4K to /bin/sh causes havoc on our 
# Solaris-2.5.1 boxes - even though sysconf(_SC_ARG_MAX) reports 1M ...).
# To work around any such */bin/sh* problems, we will scribble such
# awfully long command lines into a temp file and exec that temp file
# with $(REAL_SHELL) (don't use the SHELL variable directly as this
# will normally get you the wrong thing when the driver is invoked
# from within `make'). If the REAL_SHELL variable isn't set, you'll
# get SHELL. This is all a terrible hack. (in case you hadn't reached
# the same conclusion by now :-)
#
# TBC..
#
if ( ! $ENV{'REAL_SHELL'} ) {
    $ENV{'REAL_SHELL'} = $ENV{'SHELL'};
}

181
182
@Files_to_tidy = (); # files we nuke in the case of abnormal termination

sof's avatar
sof committed
183
$Unlit = ( $INSTALLING ) ? "$InstLibExecDirGhc/unlit"
184
			 : "$TopPwd/${CURRENT_DIR}/${GHC_UNLIT}";
185

186
187
188
$Cp   = $CP;
$Rm   = $RM;
$Diff = $CONTEXT_DIFF;
189
190
191
$Cat  = 'cat';
$Cmp  = 'cmp';
$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}";
sof's avatar
sof committed
196

197
@HsCpp_flags	= ();
sof's avatar
sof committed
198
$HsC	 = ( $INSTALLING ) ? "$InstLibExecDirGhc/hsc"
199
			   : "$TopPwd/${CURRENT_DIR}/${GHC_HSC}";
200

sof's avatar
sof committed
201
# For PVM fiends only
sof's avatar
sof committed
202
$SysMan	 = ( $INSTALLING ) ? "$InstLibExecDirGhc/SysMan"
203
			   : "$TopPwd/${CURRENT_DIR}/${GHC_SYSMAN}";
sof's avatar
sof committed
204
205
206

@Unlit_flags	= ();

207
#
208
209
210
# HsC_rts_flags: if we want to talk to the LML runtime system
# NB: we don't use powers-of-2 sizes, because this may do
#   terrible things to cache behavior.
211
#
212
213
$Specific_heap_size = 6 * 1000 * 1000;
$Specific_stk_size  = 1000 * 1000;
214
$Scale_sizes_by     = 1.0;
215
216
217

\end{code}

218
219
The variables set by @setupOptFlags@ represent parts of the
-O/-O2/etc ``templates,'' which are filled in later, using these.
220
These are the default values, which may be changed by user flags.
sof's avatar
sof committed
221

222
\begin{code}
sof's avatar
sof committed
223
224
225
226
227
228
sub setupOptFlags {
   $Oopt_MaxSimplifierIterations  = '-fmax-simplifier-iterations4';
   $Oopt_PedanticBottoms	  = '-fpedantic-bottoms'; # ON by default
   $Oopt_MonadEtaExpansion	  = '';
   $Oopt_FinalStgProfilingMassage = '';
   $Oopt_StgStats		  = '';
229
   $Oopt_DoSpecialise		  = '-fspecialise';
sof's avatar
sof committed
230
231
232
233
   $Oopt_FoldrBuild		  = 0; # *Off* by default!
   $Oopt_FB_Support		  = ''; # was '-fdo-arity-expand';
#  $Oopt_FoldrBuildWW		  = 0; # Off by default
   $Oopt_FoldrBuildInline	  = ''; # was '-fdo-inline-foldr-build';
sof's avatar
sof committed
234
   $Oopt_ShowSimplifierProgress   = '';
sof's avatar
sof committed
235
236
} # end of setupOptFlags

237
# Assign defaults to these right away.
sof's avatar
sof committed
238
&setupOptFlags();
239
240
241
\end{code}

Things to do with C compilers/etc:
242
243
244
245

(added -Wimplicit: implicit prototypes cause very hard-to-find
problems, so I'm turing on the warnings -- SDM 4/5/98)

246
\begin{code}
247
$CcRegd	 	= $GHC_OPT_HILEV_ASM;
248
@CcBoth_flags	= ('-S','-Wimplicit');   # flags for *any* C compilation
249
250
@CcInjects	= ();

251
252
253
254
255
# GCC flags: 
#    those for all files, 
#    those only for .c files;
#    those only for .hc files

256
257
@CcRegd_flags    = ();
@CcRegd_flags_c	 = ();
258
259
@CcRegd_flags_hc = ();

260
261
$As	 	 = ''; # "assembler" is normally GCC
@As_flags	 = ();
262

263
264
$Lnkr	 	 = ''; # "linker" is normally GCC
@Ld_flags	 = ();
265
266
267
268
269
270

# 'nm' is used for consistency checking (ToDo: mk-world-ify)
# ToDo: check the OS or something ("alpha" is surely not the crucial question)
$Nm = ($TargetPlatform =~ /^alpha-/) ? 'nm -B' : 'nm';
\end{code}

271
272
273
274
Warning packages that are controlled by -W and -Wall.  The 'standard'
warnings that you get all the time are
	
	-fwarn-overlapping-patterns
275
	-fwarn-missing-methods
sof's avatar
sof committed
276
	-fwarn-duplicate-exports
277
278
279
280
281

these are turned off by -Wnot.

\begin{code}
@StandardWarnings = ('-fwarn-overlapping-patterns', 
sof's avatar
sof committed
282
283
		     '-fwarn-missing-methods',
		     '-fwarn-duplicate-exports');
284
285
@MinusWOpts    	  = (@StandardWarnings, 
		     '-fwarn-incomplete-patterns', 
286
287
		     '-fwarn-unused-binds',
		     '-fwarn-unused-imports');
288
@MinusWallOpts 	  = (@MinusWOpts, 
289
		     '-fwarn-unused-matches',
290
291
		     '-fwarn-name-shadowing',
		     '-fwarn-missing-signatures');
292
293
\end{code}

294
What options \tr{-user-setup-a} turn into (user-defined ``packages''
295

296
297
298
299
300
of options).  Note that a particular user-setup implies a particular
Prelude ({\em including} its interface file(s)).
\begin{code}
$BuildTag	= ''; # default is sequential build w/ Appel-style GC

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
%BuildDescr	= (# system ways begin
                   '',	    'normal sequential',
		   '_p',    "$WAY_p_NAME",
		   '_t',    "$WAY_t_NAME",
		   '_u',    "$WAY_u_NAME",
		   '_mp',   "$WAY_mp_NAME",
		   '_mg',   "$WAY_mg_NAME",
		   # system ways end
		   '_a',    "$WAY_a_NAME",
		   '_b',    "$WAY_b_NAME",
		   '_c',    "$WAY_c_NAME",
		   '_d',    "$WAY_d_NAME",
		   '_e',    "$WAY_e_NAME",
		   '_f',    "$WAY_f_NAME",
		   '_g',    "$WAY_g_NAME",
		   '_h',    "$WAY_h_NAME",
		   '_i',    "$WAY_i_NAME",
		   '_j',    "$WAY_j_NAME",
		   '_k',    "$WAY_k_NAME",
		   '_l',    "$WAY_l_NAME",
		   '_m',    "$WAY_m_NAME",
		   '_n',    "$WAY_n_NAME",
		   '_o',    "$WAY_o_NAME",
		   '_A',    "$WAY_A_NAME",
		   '_B',    "$WAY_B_NAME" );
326
327

# these are options that are "fed back" through the option processing loop
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#
%SetupOpts = 
       (
	'_a', "$WAY_a_HC_OPTS",
	'_b', "$WAY_b_HC_OPTS",
	'_c', "$WAY_c_HC_OPTS",
	'_d', "$WAY_d_HC_OPTS",
	'_e', "$WAY_e_HC_OPTS",
	'_f', "$WAY_f_HC_OPTS",
	'_g', "$WAY_g_HC_OPTS",
	'_h', "$WAY_h_HC_OPTS",
	'_i', "$WAY_i_HC_OPTS",
	'_j', "$WAY_j_HC_OPTS",
	'_k', "$WAY_k_HC_OPTS",
	'_l', "$WAY_l_HC_OPTS",
	'_m', "$WAY_m_HC_OPTS",
	'_n', "$WAY_n_HC_OPTS",
	'_o', "$WAY_o_HC_OPTS",
	'_A', "$WAY_A_HC_OPTS",
	'_B', "$WAY_B_HC_OPTS",

	# system ways
	'_p',  "$WAY_p_HC_OPTS",
	'_t',  "$WAY_t_HC_OPTS",
	'_u',  "$WAY_u_HC_OPTS",
	'_mp', "$WAY_mp_HC_OPTS",
354
	'_mg', "$WAY_mg_HC_OPTS");
355
356
357
358
359

\end{code}

Import/include directories (\tr{-I} options) are sufficiently weird to
require special handling.
360

361
362
363
364
\begin{code}
@Import_dir	= ('.'); #-i things
@Include_dir	= ('.'); #-I things; other default(s) stuck on AFTER option processing

365
# where to look for interface files (system hi's, i.e., prelude and syslibs)
366
@SysImport_dir	= ( $INSTALLING )
367
368
		    ? ( "$InstLibDirGhc/imports/std" )
		    : ( "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std" );
369

370
371
372
# We need to look in ghc/ and glaExts/ when searching for implicitly needed .hi files, but 
# we should really *not* look there for explicitly imported modules.

373
$Haskell1Version = 5; # i.e., Haskell 1.4
374
@Cpp_define	 = ();
375

376
377
378
379
380
381
382
383
384
# Cpp symbols defined when we're processing Haskell source.

@HsSourceCppOpts = 
	( "-D__HASKELL1__=$Haskell1Version"
	, "-D__GLASGOW_HASKELL__=$ProjectVersionInt"
	# not yet -- SDM
	# , "-D__CONCURRENT_HASKELL__"
	);

385
386
387
@UserLibrary_dir= ();	#-L things;...
@UserLibrary   	= ();	#-l things asked for by the user

388
@SysLibrary_dir = ( ( $INSTALLING )	#-syslib things supplied by the system
389
		    ? $InstLibDirGhc
390
391
		    : ( "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR"
		      , "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/gmp"
392
393
		      , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std"
		      , "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/std/cbits"
394
		      )
395
		  );
396
@SysLibrary = (); # will be built up as we go along
397
398

$TopClosureFile # defaults to 1.2 one; will be mangled later
399
400
401
	= '';
#	( $INSTALLING)  ? "$InstLibDirGhc/TopClosureXXXX.o"
#			  : "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/main/TopClosureXXXX.o";
sof's avatar
sof committed
402
403
404

# make depend for Haskell
$MkDependHS
sof's avatar
sof committed
405
	= ( $INSTALLING ) ? "$InstBinDirGhc/mkdependHS"
406
			  : "$TopPwd/$CURRENT_DIR/$GHC_UTILS_DIR/mkdependHS/mkdependHS";
sof's avatar
sof committed
407
# Fill in later
sof's avatar
sof committed
408
@MkDependHS_flags = ();
sof's avatar
sof committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

# do_link flag should not be reset while rescanning the cmd-line.
$Do_lnkr    = 1;
$Specific_output_dir = '';  	# set by -odir <dir>
$Specific_output_file = '';	# set by -o <file>; "-" for stdout
\end{code}

Function to initialise the per-compilation-unit globals that
are used to guide and control the invocation of the different phases.

\begin{code} 
sub initDriverGlobals {

# reset the following options:
# RTS flags to use while compiling
@HsC_rts_flags      = ();
@HsP_flags	= (); # these are the flags destined solely for
		      # the flex/yacc parser
@HsC_flags	= ();
@HsC_antiflags  = ();
429
\end{code}
sof's avatar
sof committed
430

431
432
433
434
The optimisations/etc to be done by the compiler are {\em normally}
expressed with a \tr{-O} (or \tr{-O2}) flag, or by its absence.

\begin{code}
sof's avatar
sof committed
435
436
437
438
$OptLevel      = 0; # no -O == 0; -O == 1; -O2 == 2; -Ofile == 3
$MinusO2ForC   = 0; # set to 1 if -O2 should be given to C compiler
$StolenX86Regs = 4; # **HACK*** of the very worst sort
$CoreLint      = '';
439
$StgLint       = '';
sof's avatar
sof committed
440
441
442
443
444

@Import_dir	= ('.'); #-i things
@Include_dir	= ('.'); #-I things; other default(s) stuck on AFTER option processing


445
446
447
448
449
450
451
452
453
454
455
\end{code}

We are given a list of files with various presumably-known suffixes
(unknown-suffix files go straight to the linker).  For each file, we
begin by assuming that we'll run every phase over it.  However: (1)
global flags (\tr{-c}, \tr{-S}, etc.) tell us not to run any phase
past a certain point; and (2) the file's suffix tells us what phase to
start with.  Linking is weird and kept track of separately.

Here are the initial defaults applied to all files:
\begin{code}
sof's avatar
sof committed
456
457
$Cpp_flag_set = 0;	  # (hack)
$Only_preprocess_C = 0;	  # pretty hackish
sof's avatar
sof committed
458
459
$Only_preprocess_hc = 0;  # ditto
$Only_generate_deps = 0;  # "
460
461
462
$PostprocessCcOutput = 0;

# native code-gen or via C?
463
$HaveNativeCodeGen = $GhcWithNativeCodeGen;
464
465
$HscOut = '-C='; # '-C=' ==> .hc output; '-S=' ==> .s output; '-N=' ==> neither
$HscOut = '-S='
466
467
    if $HaveNativeCodeGen && $TargetPlatform =~ /^(alpha)-/;
# TEMP: disable x86 & Sparc if $HaveNativeCodeGen && $TargetPlatform =~ /^(i386|alpha|sparc)-/;
sof's avatar
sof committed
468
469
$ProduceHi    = '-hifile=';
$HiOnStdout   = 0;
sof's avatar
sof committed
470
$HiWith       = '';
sof's avatar
sof committed
471
472
$HiDiff_flag  = '';
$Keep_HiDiffs = 0;
473
474
475
476
477
478
479
480
481

$CollectingGCstats = 0;
$CollectGhcTimings = 0;
$DEBUGging = '';	# -DDEBUG and all that it entails (um... not really)
$PROFing = '';		# set to p or e if profiling
$PROFgroup = '';	# set to group if an explicit -Ggroup specified
$PROFauto = '';	        # set to relevant hsc flag if -auto or -auto-all
$PROFcaf  = '';	        # set to relevant hsc flag if -caf-all
$PROFignore_scc = '';	# set to relevant parser flag if explicit sccs ignored
482
$UNPROFscc_auto = '';	# set to relevant hsc flag if forcing auto sccs without profiling
483
$TICKYing = '';    	# set to t if compiling for ticky-ticky profiling
484
$PARing = '';		# set to p if compiling for PAR
485
486
487
488
$GRANing = '';		# set to g if compiling for GRAN
$Specific_hi_file = '';		# set by -ohi <file>; "-" for stdout
$Specific_dump_file = '';	# set by -odump <file>; "-" for stdout
$Using_dump_file = 0;
489
$Isuffix    = '';
490
491
$Osuffix    = '';	# default: use the normal suffix for that kind of output
$HiSuffix   = 'hi';
492
$HiSuffix_prelude = '';
493
$Do_recomp_chkr = 0;	# don't use the recompilatio checker unless asked
494
495
$Do_cc	    = -1;   # a MAGIC indeterminate value; will be set to 1 or 0.
$Do_as	    = 1;
sof's avatar
sof committed
496

497
498
$Keep_hc_file_too = 0;
$Keep_s_file_too = 0;
499
$UseGhcInternals = 0; # if 1, may use GHC* modules
500
$SplitObjFiles = 0;
501
$DoAsmMangling = 1; # on by default, off by -fno-asm-mangling
502
503
504
505
$NoOfSplitFiles = 0;
$Dump_parser_output = 0;
$Dump_raw_asm = 0;
$Dump_asm_splitting_info = 0;
506
$NoImplicitPrelude = 0;
507
508
509
# 1 => don't tell the linker to hoist in PrelMain.Main, as an 
# external main is provided instead.
$NoHaskellMain=0;
sof's avatar
sof committed
510
511
512
513
514
515

} # end of initDriverGlobals (Sigh)

# we split the argv passed to the driver into three:

# the list of files
516
517
518
519
@Input_file = ();

# and files to be linked...
@Link_file  = ();
sof's avatar
sof committed
520
521
522
523

# and whatever else
@Cmd_opts  = ();

sof's avatar
sof committed
524
525
526
# cmd line options prefixing the unit we're compiling
@File_options = ();

527
528
529
530
531
532
533
534
535
536
\end{code}

We inject consistency-checking information into \tr{.hc} files (both
when created by the Haskell compiler and when compiled by the C
compiler), so that we can check that an executable is made from
consistently-built pieces.  (The check is normally done just after
linking.)  The checking is done by introducing/munging
\tr{what(1)}-style strings.  Anyway, here are the relevant global
variables and their defaults:
\begin{code}
537
$LinkChk = 0;	# set to 0 if the link check should *not* be done
538
539
540

# major & minor version numbers; major numbers must always agree;
# minor disagreements yield a warning.
sof's avatar
sof committed
541
542
543
544
$HsC_major_version = $HscMajorVersion;
$HsC_minor_version = $HscMinorVersion;
$Cc_major_version  = $CcMajorVersion;
$Cc_minor_version  = $CcMinorVersion;
545
546
547
548
549

# options: these must always agree
$HsC_consist_options = '';    # we record, in this order:
			      #	    Build tag; debugging?
$Cc_consist_options  = '';    # we record, in this order:
550
			      #	    Build tag; debugging?
551
552
553
554
555
556
557
558
559
560
\end{code}

%************************************************************************
%*									*
\section[Driver-parse-argv]{Munge the command-line options}
%*									*
%************************************************************************

Now slurp through the arguments.
\begin{code}
561

sof's avatar
sof committed
562
563
564
565
&initDriverGlobals();
&splitCmdLine(@ARGV);
# Run through the cmd-line first time.
&processArgs(@Cmd_opts);
566

sof's avatar
sof committed
567
568
569
# Check to see if driver is only in the business
# to generate dependencies
if (  $Status == 0 && $Only_generate_deps ) {
570

sof's avatar
sof committed
571
572
    push (@MkDependHS_flags, "-o$Osuffix") if $Osuffix;
    push (@MkDependHS_flags, "-s$BuildTag") if $BuildTag;
sof's avatar
sof committed
573
    # They're not (currently) needed, but we need to quote any -#include options
574
575
576
    foreach (@Cmd_opts) {
    	s/-#include.*$/'$&'/g;
    };
577
    local($to_do) = "$MkDependHS @MkDependHS_flags @HsSourceCppOpts -- @Cmd_opts -- @Input_file" ;
sof's avatar
sof committed
578
579
580
    &run_something($to_do, 'Haskell dependencies');
    exit $Status;
}
581

sof's avatar
sof committed
582
583
584
# if there are several input files,
# we don't allow \tr{-o <file>} or \tr{-ohi <file>} options...
# (except if linking, of course)
585

sof's avatar
sof committed
586
587
588
589
590
591
592
593
if ($#Input_file > 0 && ( ! $Do_lnkr )) {
    if ( ($Specific_output_file ne '' && $Specific_output_file ne '-')
      || ($Specific_hi_file ne ''     && $Specific_hi_file ne '-') ) {
	print STDERR "$Pgm: You can't use -o or -ohi options if you have multiple input files.\n";
	print STDERR "\tPerhaps the -odir option will do what you want.\n";
	$Status++;
    }
}
594

sof's avatar
sof committed
595
596
597
598
599
600
601
602
603
604
605
# check for various pathological -o and -odir combinations...
if ($Specific_output_dir ne '' && $Specific_output_file ne '') {
    if ($Specific_output_file eq '-') {
	print STDERR "$Pgm: can't set output directory with -ohi AND have output to stdout\n";
	$Status++;
    } else { # amalgamate...
    	$Specific_output_file = "$Specific_output_dir/$Specific_output_file";
	# ToDo: check we haven't got a junk name now...
	$Specific_output_dir  = ''; # reset
    }
}
606

sof's avatar
sof committed
607
608
609
610
611
612
# crash and burn if there were errors
if ( $Status > 0 ) {
    print STDERR $ShortUsage;
    exit $Status;
}
\end{code}
613

sof's avatar
sof committed
614
615
616
617
618
%************************************************************************
%*									*
\section[Driver-post-argv-mangling]{Setup after reading options}
%*									*
%************************************************************************
619

sof's avatar
sof committed
620
621
622
623
624
%************************************************************************
%*									*
\subsection{Set up for optimisation level (\tr{-O} or whatever)}
%*									*
%************************************************************************
625

sof's avatar
sof committed
626
627
628
629
We come now to the default ``wads of options'' that are turned on by
\tr{-O0} (do min optimisation), \tr{-O} (ordinary optimisation),
\tr{-O2} (aggressive optimisation), or no O-ish flag (compile speed is
more important).
630

sof's avatar
sof committed
631
632
633
The user can also specify his/her own list of options in a file; in
that case, the work is already done (see stuff about @minusO3@,
earlier...).
634

sof's avatar
sof committed
635
636
637
638
GHC allows very precise control of what happens during a compilation.
Core-to-Core and STG-to-STG passes can be run in any order, as many
times as you like.  Individual transformations can be turned on or
disabled.
639

sof's avatar
sof committed
640
641
Sadly, however, there are some interdependencies \& Things You Must
Not Do.  Here is the list.
642

sof's avatar
sof committed
643
644
645
646
647
648
649
CORE-TO-CORE PASSES:
\begin{description}
\item[\tr{-fspecialise}:]
The specialiser must have dependency-analysed input; but if you run
the simplifier to do this, you must not let it toss away unused
bindings!  (The typechecker conveys some specialisation info via
``unused'' bindings...)
650

sof's avatar
sof committed
651
652
653
\item[\tr{-ffloat-inwards}:]
Floating inwards should be done before strictness analysis, because
the latter will give better results.
654

sof's avatar
sof committed
655
656
657
\item[\tr{-fstatic-args}:]
The static-arguments-transformation pass {\em must} have the
simplifier run right after it.
658

sof's avatar
sof committed
659
660
661
662
\item[\tr{-fcalc-inlinings[12]}:]
Not required, but there may be slight gains by re-simplifying after
this is done.  (You could then \tr{-fcalc-inlinings} again, just for
fun.)
663

sof's avatar
sof committed
664
665
666
667
\item[\tr{-ffull-laziness}:]
The (outwards-)let-floater should be the {\em last} Core-to-Core pass
that's run.  (Um, well, howzabout the simplifier just once more...)
\end{description}
668

sof's avatar
sof committed
669
670
671
672
673
STG-TO-STG PASSES:
\begin{description}
\item[\tr{-fupdate-analysis}:]
It really really wants to be the last STG-to-STG pass that is run.
\end{description}
674

sof's avatar
sof committed
675
\begin{code}
676

sof's avatar
sof committed
677
sub setupOptimiseFlags {
678

sof's avatar
sof committed
679
680
   @HsC_minusNoO_flags 
    = (	'-fsimplify',
sof's avatar
sof committed
681
	  '[',
sof's avatar
sof committed
682
683
684
685
	  $Oopt_FB_Support,
	  '-ffloat-lets-exposing-whnf',
	  '-ffloat-primops-ok',
	  '-fcase-of-case',
686
	  '-fdo-case-elim',
sof's avatar
sof committed
687
688
#	  '-fdo-lambda-eta-expansion',	# too complicated
	  '-freuse-con',
sof's avatar
sof committed
689
#	  '-flet-to-case',		# no strictness analysis, so...
sof's avatar
sof committed
690
691
	  $Oopt_PedanticBottoms,
#	  $Oopt_MonadEtaExpansion,	# no thanks
sof's avatar
sof committed
692
693
694
695
696
697
698
699
700

# These two work fine, if you really want no simplification at all,
# for bizarre test reasons.  But you get really terrible code if you use them,
#	for example: let x = e in x
# with dozens of redundant thunks etc.  So I'm leaving them out.
#
#	  '-fsimpl-uf-use-threshold0',
#	  '-fessential-unfoldings-only',

sof's avatar
sof committed
701
702
703
704
705
706
707
708
709
	  #
	  # The presence of -fclone-binds is *temporary* to work around
          # the fact that the desugarer in 3.0{2.3} does generate
	  # bindings with identical ids, and the type checker doesn't perform
	  # properly cloned type substitutions. Instead, we make sure that all 
	  # binders are cloned first time through the simplifier.
          #
	  # Will be properly fixed in the `new compiler` I hear, at which point
	  # the cloning can be turned off here.
710
711
712
	  #
          # Let's find out..
          #'-fclone-binds',
sof's avatar
sof committed
713

sof's avatar
sof committed
714
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
715
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
716
	  ']',
sof's avatar
sof committed
717
718
719
720
721
	$Oopt_AddAutoSccs,
#	'-ffull-laziness',	# removed 95/04 WDP following Andr\'e's lead
	
	$Oopt_FinalStgProfilingMassage
      );
722

sof's avatar
sof committed
723
724
725
   @HsC_minusO_flags # NOTE: used for *both* -O and -O2 (some conditional bits)
    = (
        '-fdo-eta-reduction',
726

sof's avatar
sof committed
727
728
	# initial simplify: mk specialiser happy: minimum effort please
	'-fsimplify',
sof's avatar
sof committed
729
	  '[', 
sof's avatar
sof committed
730
731
	  $Oopt_FB_Support,
	  '-fkeep-spec-pragma-ids',	# required before specialisation
sof's avatar
sof committed
732
733
734
735
736
737
738
739
740
741
742
743

# I don't understand why we want -fessential-unfoldings-only here
# If we have it, the following nasty thing happens:
#	f  = E
#	g* = f
#	...g...
# where "*" means exported.
# In the essential-unfoldings pass we still substitute f for g
# but we don't substitute E for f first.  So we get
#	f  = E
#	g* = f
#	...f...
744
# The g=f will get reverse-substituted later, but it's untidy. --SLPJ
sof's avatar
sof committed
745
#
746
747
748
749
750
751
752
753
754
755
756
757
# SDM: Here's why it's necessary.
#
#   If we unfold in the first pass before the specialiser is run
#   we miss opportunities for specialisation because eg. wrappers
#   have been inlined for specialisable functions.  
#
#   This shows up in PrelArr.lhs - the specialised instance for newArray 
#   calls the generic rangeSize, because rangeSize is strict and is
#   replaced by its wrapper by the simplifier.

	  '-fessential-unfoldings-only',
	  '-fsimpl-uf-use-threshold0',
sof's avatar
sof committed
758

sof's avatar
sof committed
759
760
761
	  # See remark re: cloning in defn of minusnotO
	  '-fclone-binds',

sof's avatar
sof committed
762
763
	  '-fmax-simplifier-iterations1',
	  $Oopt_PedanticBottoms,
sof's avatar
sof committed
764
	  ']',
765

sof's avatar
sof committed
766
767
768
	($Oopt_DoSpecialise) ? (
	  $Oopt_DoSpecialise,
	) : (),
769

770
	'-fsimplify', 		# need dependency anal after specialiser ...
sof's avatar
sof committed
771
	  '[', 			# need tossing before calc-inlinings ...
sof's avatar
sof committed
772
773
774
775
776
777
778
779
780
781
782
783
	  $Oopt_FB_Support,
	  '-ffloat-lets-exposing-whnf',
	  '-ffloat-primops-ok',
	  '-fcase-of-case',
	  '-fdo-case-elim',
	  '-fcase-merge',
#	  '-fdo-eta-reduction',
	  '-fdo-lambda-eta-expansion',
	  '-freuse-con',
	  $Oopt_PedanticBottoms,
	  $Oopt_MonadEtaExpansion,
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
784
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
785
786
787
788
789
790
791
792
793
	  #
	  # The presence of -fclone-binds is *crucial* here as
	  # -ffull-laziness (which we're about to do next) floats
	  # bindings outwards, so we better make sure that this
	  # doesn't result in the floating out of bindings
	  # with identical uniques, i.e., -ffull-laziness needs
	  # to be preceeded by a simplifier pass with -fclone-binds
	  # set.
          '-fclone-binds',
sof's avatar
sof committed
794
	  ']',
795

sof's avatar
sof committed
796
797
798
799
#	($Oopt_FoldrBuildWW) ? (
#		'-ffoldr-build-ww-anal',
#		'-ffoldr-build-worker-wrapper',
#		'-fsimplify', 
sof's avatar
sof committed
800
#		  '[', 
sof's avatar
sof committed
801
802
803
804
805
806
807
808
809
810
811
812
#		  $Oopt_FB_Support,
#		  '-ffloat-lets-exposing-whnf',
#		  '-ffloat-primops-ok',
#		  '-fcase-of-case',
#		  '-fdo-case-elim',
#		  '-fcase-merge',
#		  '-fdo-eta-reduction',
#		  '-fdo-lambda-eta-expansion',
#		  '-freuse-con',
#		  $Oopt_PedanticBottoms,
#		  $Oopt_MonadEtaExpansion,
#		  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
813
#		  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
814
#		  ']',
sof's avatar
sof committed
815
#	 ) : (),
816

sof's avatar
sof committed
817
818
819
	# this pass-ordering sequence was agreed by Simon and Andr\'e
	# (WDP 94/07, 94/11).
	'-ffull-laziness',
820

sof's avatar
sof committed
821
822
	($Oopt_FoldrBuild) ? (
	  '-ffoldr-build-on',		# desugar list comprehensions for foldr/build
823

sof's avatar
sof committed
824
	  '-fsimplify', 
sof's avatar
sof committed
825
	    '[', 
sof's avatar
sof committed
826
827
828
829
830
831
832
833
834
835
836
837
838
839
	    '-fignore-inline-pragma',	# **** NB!
	    '-fdo-foldr-build',		# NB
	    $Oopt_FB_Support,
	    '-ffloat-lets-exposing-whnf',
	    '-ffloat-primops-ok',
	    '-fcase-of-case',
	    '-fdo-case-elim',
	    '-fcase-merge',
#	    '-fdo-eta-reduction',
	    '-fdo-lambda-eta-expansion',	# After full laziness
	    '-freuse-con',
	    $Oopt_PedanticBottoms,
	    $Oopt_MonadEtaExpansion,
	    $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
840
	    $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
841
	    ']',
sof's avatar
sof committed
842
	) : (),
843

sof's avatar
sof committed
844
	'-ffloat-inwards',
845

sof's avatar
sof committed
846
	'-fsimplify',
sof's avatar
sof committed
847
	  '[', 
sof's avatar
sof committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
	  $Oopt_FB_Support,
	  '-ffloat-lets-exposing-whnf',
	  '-ffloat-primops-ok',
	  '-fcase-of-case',
	  '-fdo-case-elim',
	  '-fcase-merge',
	  '-fdo-eta-reduction',
	  '-fdo-lambda-eta-expansion',
	  '-freuse-con',
  	  ($Oopt_FoldrBuildInline),
			# you need to inline foldr and build
	  ($Oopt_FoldrBuild) ? ('-fdo-foldr-build') : (), 
			# but do reductions if you see them!
	  $Oopt_PedanticBottoms,
	  $Oopt_MonadEtaExpansion,
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
864
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
865
	  ']',
866

sof's avatar
sof committed
867
	'-fstrictness',
868

sof's avatar
sof committed
869
	'-fsimplify',
sof's avatar
sof committed
870
	  '[', 
sof's avatar
sof committed
871
872
873
874
875
876
877
878
879
880
881
882
883
	  $Oopt_FB_Support,
	  '-ffloat-lets-exposing-whnf',
	  '-ffloat-primops-ok',
	  '-fcase-of-case',
	  '-fdo-case-elim',
	  '-fcase-merge',
#	  '-fdo-eta-reduction',
	  '-fdo-lambda-eta-expansion',
	  '-freuse-con',
	  '-flet-to-case',		# Aha! Only done after strictness analysis
	  $Oopt_PedanticBottoms,
	  $Oopt_MonadEtaExpansion,
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
884
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
885
	  ']',
886

sof's avatar
sof committed
887
	'-ffloat-inwards',
888

sof's avatar
sof committed
889
890
# Case-liberation for -O2.  This should be after
# strictness analysis and the simplification which follows it.
891

sof's avatar
sof committed
892
893
#	( ($OptLevel != 2)
#        ? ''
894
#	: "-fliberate-case -fsimplify [ $Oopt_FB_Support -ffloat-lets-exposing-whnf -ffloat-primops-ok -fcase-of-case -fdo-case-elim -fcase-merge -fdo-eta-reduction -fdo-lambda-eta-expansion -freuse-con -flet-to-case $Oopt_PedanticBottoms $Oopt_MonadEtaExpansion $Oopt_MaxSimplifierIterations $Oopt_ShowSimplifierProgress ]" ),
895

sof's avatar
sof committed
896
# Final clean-up simplification:
897

sof's avatar
sof committed
898
	'-fsimplify',
sof's avatar
sof committed
899
	  '[', 
sof's avatar
sof committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
	  $Oopt_FB_Support,
	  '-ffloat-lets-exposing-whnf',
	  '-ffloat-primops-ok',
	  '-fcase-of-case',
	  '-fdo-case-elim',
	  '-fcase-merge',
#	  '-fdo-eta-reduction',
	  '-fdo-lambda-eta-expansion',
	  '-freuse-con',
	  '-flet-to-case',
	  '-fignore-inline-pragma',	# **** NB!
	  $Oopt_FoldrBuildInline,	
	  ($Oopt_FoldrBuild) ? ('-fdo-foldr-build') : (), 
			# but still do reductions if you see them!
	  $Oopt_PedanticBottoms,
	  $Oopt_MonadEtaExpansion,
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
917
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
918
	  ']',
919

sof's avatar
sof committed
920
      #	'-fstatic-args',
921

sof's avatar
sof committed
922
#LATER:	'-fcalc-inlinings2', -- pointless for 2.01
923

sof's avatar
sof committed
924
925
926
927
      # stg2stg passes
	'-flambda-lift',
	$Oopt_FinalStgProfilingMassage,
	$Oopt_StgStats,
928

sof's avatar
sof committed
929
930
      # flags for stg2stg
	'-flet-no-escape',
931

sof's avatar
sof committed
932
933
      # SPECIAL FLAGS for -O2
	($OptLevel == 2) ? (
934
	  '-fupdate-analysis',	# virtually useless; relegated to -O2
sof's avatar
sof committed
935
936
937
	  '-fsemi-tagging',
	) : (),
      );
938

sof's avatar
sof committed
939
\end{code}
940

sof's avatar
sof committed
941
942
943
944
Sort out what we're going to do about optimising.  First, the @hsc@
flags and regular @cc@ flags to worry about:
\begin{code}
if ( $OptLevel <= 0 ) {
945

sof's avatar
sof committed
946
947
948
949
    # for this level, we tell the parser -fignore-interface-pragmas
    push(@HsC_flags, '-fignore-interface-pragmas');
    # and tell the compiler not to produce them
    push(@HsC_flags, '-fomit-interface-pragmas');
950

sof's avatar
sof committed
951
952
    &add_Hsc_flags( @HsC_minusNoO_flags );
    push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O');	# not optional!
953

sof's avatar
sof committed
954
} elsif ( $OptLevel == 1 || $OptLevel == 2 ) {
955

sof's avatar
sof committed
956
957
958
    &add_Hsc_flags( @HsC_minusO_flags );
    push(@CcBoth_flags, ($MinusO2ForC || $OptLevel == 2) ? '-O2' : '-O'); # not optional!
    # -O? to GCC is not optional! -O2 probably isn't worth it generally,
959
    # but it *is* useful in compiling the garbage collector.
sof's avatar
sof committed
960
961
962
963

} else { # -Ofile, then...

    &add_Hsc_flags( @HsC_minusO3_flags );
sof's avatar
sof committed
964
965
    push(@HsC_flags, $Oopt_FinalStgProfilingMassage) if $Oopt_FinalStgProfilingMassage;

sof's avatar
sof committed
966
967
968
969
970
971
972
973
974
975
976
977
978
    push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O');	# possibly to be elaborated...
}

} # setupOptimiseFlags

\end{code}

%************************************************************************
%*									*
\subsection{Check for consistency, etc.}
%*									*
%************************************************************************

979
Sort out @$BuildTag@, @$PROFing@, @$PARing@,
sof's avatar
sof committed
980
981
982
983
984
@$GRANing@, @$TICKYing@:
\begin{code}
sub setupBuildFlags {


985
986
987
988
989
990
991
992
993
994
995
996
997
998
   # PROFILING stuff after argv mangling:
   if ( ! $PROFing ) {
     # warn about any scc exprs found (in case scc used as identifier)
     push(@HsP_flags, '-W');

     # add -auto sccs even if not profiling !
     push(@HsC_flags, $UNPROFscc_auto) if $UNPROFscc_auto;

   } else {
      push(@HsC_flags, $PROFauto) if $PROFauto;
      push(@HsC_flags, $PROFcaf)  if $PROFcaf;
      #push(@HsC_flags, $PROFdict) if $PROFdict;

      $Oopt_FinalStgProfilingMassage = '-fmassage-stg-for-profiling';
sof's avatar
sof committed
999

sof's avatar
sof committed
1000
1001
1002
      # Ignore user sccs when auto annotating, but warn when doing so.
      $PROFignore_scc = '-W' if $PROFauto; 

1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
      push(@HsP_flags, (($PROFignore_scc) ? $PROFignore_scc : '-S'));
  }
  #if ( $BuildTag ne '' ) {
  #    local($b) = $BuildDescr{$BuildTag};
  #    if ($PARing    eq 'p') { print STDERR "$Pgm: Can't mix $b with -parallel.\n"; exit 1; }
  #    if ($GRANing   eq 'g') { print STDERR "$Pgm: Can't mix $b with -gransim.\n"; exit 1; }
  #    if ($TICKYing  eq 't') { print STDERR "$Pgm: Can't mix $b with -ticky.\n"; exit 1; }

  #    # ok to have a user-way profiling build
  #    # eval the profiling opts ... but leave user-way BuildTag 
  #    if ($PROFing   eq 'p') { &processArgs(split(' ', $SetupOpts{'_p'})); } # eval($EvaldSetupOpts{'_p'}); }

  if ( $PROFing eq 'p' ) {
sof's avatar
sof committed
1016
1017
1018
      if ($PARing   eq 'p') { print STDERR "$Pgm: Can't do profiling with -parallel.\n"; exit 1; }
      if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't do profiling with -gransim.\n"; exit 1; }
      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't do profiling with -ticky.\n"; exit 1; }
1019
      $BuildTag = '_p' ;
sof's avatar
sof committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

  } elsif ( $PARing eq 'p' ) {
      if ($GRANing  eq 'g') { print STDERR "$Pgm: Can't mix -parallel with -gransim.\n"; exit 1; }
      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -parallel with -ticky.\n"; exit 1; }
      $BuildTag = '_mp';

      if ( $Do_lnkr && ( ! $ENV{'PVM_ROOT'} || ! $ENV{'PVM_ARCH'} )) {
	  print STDERR "$Pgm: both your PVM_ROOT and PVM_ARCH environment variables must be set for linking under -parallel.\n";
	  exit(1);
      }

  } elsif ( $GRANing eq 'g' ) {
      if ($TICKYing eq 't') { print STDERR "$Pgm: Can't mix -gransim with -ticky.\n"; exit 1; }
      $BuildTag = '_mg';

  } elsif ( $TICKYing eq 't' ) {
      $BuildTag = '_t';
  }

\end{code}

After the sanity checks, add flags to the necessary parts of the driver pipeline:

\begin{code}
  if ( $BuildTag ne '' ) { # something other than normal sequential...

1046
      local($Tag) = "${BuildTag}";
sof's avatar
sof committed
1047
1048
1049
      $Tag =~ s/_//;  # move the underscore to the back

      $HscOut = '-C='; # must go via C
1050
1051
      &processArgs(split(' ', $SetupOpts{$BuildTag}));
#      eval($EvaldSetupOpts{$BuildTag});
sof's avatar
sof committed
1052
1053
1054
1055
1056
  }
\end{code}

Decide what the consistency-checking options are in force for this run:
\begin{code}
1057

sof's avatar
sof committed
1058
1059
1060
  $HsC_consist_options = "${BuildTag},${DEBUGging}";
  $Cc_consist_options  = "${BuildTag},${DEBUGging}";

1061
1062
1063
1064
1065
1066
1067
1068
1069
  #
  # Funny place to put it, but why not.
  #
  if ( $HiSuffix_prelude eq '' ) {
       local($Tag) = "${BuildTag}";
       $Tag =~ s/_//;
       $Tag = "${Tag}_" if $Tag ne '';
       $HiSuffix_prelude="${Tag}hi";
  }
sof's avatar
sof committed
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
} # setupBuildFlags
\end{code}

%************************************************************************
%*									*
\subsection{Add on machine-specific C-compiler flags}
%*									*
%************************************************************************

Shove on magical machine-specific options.  We use \tr{unshift} to
stick them on the {\em front} of the arrays, so that ``later''
user-specified flags can clobber them (e.g., \tr{-U__STG_REV_TBLS__}).

Note: a few ``always apply'' flags were set at the very beginning.

\begin{code}
sub setupMachOpts {

  if ($TargetPlatform =~ /^alpha-/) {
      unshift(@CcBoth_flags,  ('-static'));

  } elsif ($TargetPlatform =~ /^hppa/) {
      unshift(@CcBoth_flags,  ('-static'));
1093
      #
sof's avatar
sof committed
1094
1095
1096
1097
      # We don't put in '-mlong-calls', because it's only
      # needed for very big modules (sigh), and we don't want
      # to hobble ourselves further on all the other modules
      # (most of them).
1098
1099
1100
      #  
      # [Dated comment (gcc-2.6.x?), -mlong-calls is no longer
      #  a supported gcc HPPA flag]
sof's avatar
sof committed
1101
1102
1103
1104
1105
1106
1107
      unshift(@CcBoth_flags,  ('-D_HPUX_SOURCE'));
        # ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
        # (very nice, but too bad the HP /usr/include files don't agree.)

  } elsif ($TargetPlatform =~ /^i386-/) {
      # -fno-defer-pop : basically the same game as for m68k
      #
1108
1109
      # -fomit-frame-pointer : *must* in .hc files; because we're stealing
      #	 the fp (%ebp) for our register maps.
sof's avatar
sof committed
1110
1111

      unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1112
      unshift(@CcRegd_flags_hc, '-fomit-frame-pointer');
sof's avatar
sof committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
      unshift(@CcRegd_flags,    "-DSTOLEN_X86_REGS=$StolenX86Regs");

  } elsif ($TargetPlatform =~ /^m68k-/) {
      # -fno-defer-pop : for the .hc files, we want all the pushing/
      #    popping of args to routines to be explicit; if we let things
      #    be deferred 'til after an STGJUMP, imminent death is certain!
      #
      # -fomit-frame-pointer : *don't*
      #	   It's better to have a6 completely tied up being a frame pointer
      #	   rather than let GCC pick random things to do with it.
      #	   (If we want to steal a6, then we would try to do things
      #	   as on iX86, where we *do* steal the frame pointer [%ebp].)

      unshift(@CcRegd_flags_hc, '-fno-defer-pop');
      unshift(@CcRegd_flags,    '-fno-omit-frame-pointer');
	# maybe gives reg alloc a better time
	# also: -fno-defer-pop is not sufficiently well-behaved without it

  } elsif ($TargetPlatform =~ /^mips-/) {
      unshift(@CcBoth_flags,  ('-static'));

1134
  } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
sof's avatar
sof committed
1135
1136
1137
1138
1139
1140
1141
      unshift(@CcBoth_flags,  ('-static')); # always easier to start with
      unshift(@CcRegd_flags, ('-finhibit-size-directive')); # avoids traceback tables
  } elsif ($TargetPlatform =~ /^sparc-/) {
  }
} # end of setupMachOpts
\end{code}

1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
%************************************************************************
%*									*
\subsection{Set up for warnings}
%*									*
%************************************************************************

Several warnings are turned on by default.  These are supposed to be
the 'I'm pretty sure you've made a mistake here' kind of warnings.
The rest are turned on by the -W and -Wall options, or individually
via their -fwarn and -fno-warn flags.

\begin{code}
sub setupWarningFlags {
&add_Hsc_flags( @StandardWarnings );
}
\end{code}

sof's avatar
sof committed
1159
1160
Same unshifting magic, but for special linker flags.

1161
1162
1163
1164
The configure script determines whether the object file symbol tables
have a leading underscore, and sets @LeadingUnderscore@ accordingly.
(The driver script `sees' the setting of the @LeadingUnderscore@
by having the Makefile prepend it).
sof's avatar
sof committed
1165
1166
1167

\begin{code}
sub setupLinkOpts {
1168
  local($uscore) = ( ${LeadingUnderscore} eq 'YES' ) ? '_' : '';
sof's avatar
sof committed
1169
1170

  unshift(@Ld_flags,
sof's avatar
sof committed
1171
        (($Ld_main) ? ( '-u', "${uscore}Main_" . $Ld_main . '_closure' ) : ()));
1172
1173

  # things that are referenced by the RTS - make sure that we pull 'em in
sof's avatar
sof committed
1174
  unshift(@Ld_flags,
1175
         ( '-u', "${uscore}PrelBase_IZh_static_info"
sof's avatar
sof committed
1176
          ,'-u', "${uscore}PrelBase_CZh_static_info"
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
          ,'-u', "${uscore}PrelBase_FZh_static_info"
          ,'-u', "${uscore}PrelBase_DZh_static_info"
          ,'-u', "${uscore}PrelAddr_AZh_static_info"
          ,'-u', "${uscore}PrelAddr_WZh_static_info"
          ,'-u', "${uscore}PrelAddr_I64Zh_static_info"
          ,'-u', "${uscore}PrelAddr_W64Zh_static_info"
          ,'-u', "${uscore}PrelForeign_StablePtr_static_info"
	  ,'-u', "${uscore}PrelBase_IZh_con_info"
          ,'-u', "${uscore}PrelBase_CZh_con_info"
          ,'-u', "${uscore}PrelBase_FZh_con_info"
          ,'-u', "${uscore}PrelBase_DZh_con_info"
          ,'-u', "${uscore}PrelAddr_AZh_con_info"
          ,'-u', "${uscore}PrelAddr_WZh_con_info"
          ,'-u', "${uscore}PrelAddr_I64Zh_con_info"
          ,'-u', "${uscore}PrelAddr_W64Zh_con_info"
          ,'-u', "${uscore}PrelForeign_StablePtr_con_info"
          ,'-u', "${uscore}PrelBase_False_static_closure"
          ,'-u', "${uscore}PrelBase_True_static_closure"
          ,'-u', "${uscore}PrelPack_unpackCString_closure"
sof's avatar
sof committed
1196
	));
1197
1198
1199
  if (!$NoHaskellMain) {
   unshift (@Ld_flags,'-u', "${uscore}PrelMain_mainIO_closure");
  }
1200
1201
1202
1203
1204
  if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
    # sometimes we have lots of toc entries...
    #  unshift(@Ld_flags, ('-Xlinker -bbigtoc -Xlinker -bnoquiet')); 
    unshift(@Ld_flags, ('-Xlinker -bbigtoc')); 
  }
sof's avatar
sof committed
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222

} # end of setupLinkOpts

\end{code}

%************************************************************************
%*									*
\subsection{Set up include paths and system-library enslurpment}
%*									*
%************************************************************************

Now that we know what garbage-collector, etc., are required, we can
finalise our list of libraries to slurp through, and generally Get
Ready for Business.

\begin{code}
sub setupIncPaths {
  # default includes must be added AFTER option processing
1223
1224
  if ( ! $INSTALLING ) {
      push (@Include_dir, "$TopPwd/${CURRENT_DIR}/${GHC_INCLUDE_DIR}");
sof's avatar
sof committed
1225
1226
  } else {
      push (@Include_dir, "$InstLibDirGhc/includes");
sof's avatar
sof committed
1227
      push (@Include_dir, "$InstLibDirGhc/includes");
sof's avatar
sof committed
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
  }
} # end of setupIncPaths
\end{code}

\begin{code}
sub setupSyslibs {
  push(@SysLibrary, ( '-lHS', '-lHS_cbits' )); # basic I/O and prelude stuff

  local($f);
  foreach $f (@SysLibrary) {
      next if $f =~ /_cbits/;
      $f .= $BuildTag if $f =~ /^-lHS/;
  }

  # Push library HSrts, plus boring clib bit
  push(@SysLibrary, "-lHSrts${BuildTag}");
1244

1245
1246
1247
1248
1249
  #
  # RTS compiled with cygwin32, uses the WinMM API
  # to implement the itimers, since cygwin.dll does not
  # support it. Only reqd. for `ways' that use itimers.
  #
1250
  push(@SysLibrary, '-lwinmm') if $TargetPlatform eq 'i386-unknown-cygwin32';
sof's avatar
sof committed
1251
1252
1253
1254

  # Push the pvm libraries
  if ($BuildTag eq '_mp') {
      $pvmlib = "$ENV{'PVM_ROOT'}/lib/$ENV{'PVM_ARCH'}";
1255
      push(@SysLibrary, "-L$pvmlib", '-lgpvm3', '-lpvm3');
sof's avatar
sof committed
1256
1257
1258
1259
1260
1261
1262
1263
      if ( $ENV{'PVM_ARCH'} eq 'SUNMP' ) {
          push(@SysLibrary, '-lthread', '-lsocket', '-lnsl');
      } elsif ( $ENV{'PVM_ARCH'} eq 'SUN4SOL2' ) {
          push(@SysLibrary, '-lsocket', '-lnsl');
      }
  }

# Push the GNU multi-precision arith lib; and the math library
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273

# If this machine has GMP already installed, then we'll get the installed
# lib here, because presumably the one in the tree won't have been built.

if ($LibGmp eq 'not-installed') {
  push(@SysLibrary, "-lgmp");
} else {
  push(@SysLibrary, "-l$LibGmp");
}

sof's avatar
sof committed
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
push(@SysLibrary, '-lm');
\end{code}

%************************************************************************
%*									*
\subsection{Check that this system was built to do what we are asking}
%*									*
%************************************************************************

Before continuing we check that the appropriate build is available.

\begin{code}
1286
#die "$Pgm: no BuildAvail?? $BuildTag\n" if $BuildDescr{$BuildTag} eq '' ; # sanity
sof's avatar
sof committed
1287

1288
if ( $BuildDescr{$BuildTag} eq '' ) {
sof's avatar
sof committed
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
    print STDERR "$Pgm: a `", $BuildDescr{$BuildTag},
	"' \"build\" is not available with your GHC setup.\n";
    print STDERR "(It was not configured for it at your site.)\n";
    print STDERR $ShortUsage;
    exit 1;
}

} # end of setupSyslibs

\end{code}

%************************************************************************
%*									*
\subsection{Final miscellaneous setup bits before we start going}
%*									*
%************************************************************************

Record largest specific heapsize, if any.
\begin{code}
sub setupHeapStackSize {
   $Specific_heap_size = $Specific_heap_size * $Scale_sizes_by;
   push(@HsC_rts_flags, '-H'.$Specific_heap_size);
   $Specific_stk_size = $Specific_stk_size * $Scale_sizes_by;
   push(@HsC_rts_flags, "-K$Specific_stk_size");
}
\end{code}

If no input or link files seen, then we let 'em feed in stdin; this is
mainly for debugging.

\begin{code}

if ($#Input_file < 0 && $#Link_file < 0) {
    @Input_file = ( '-' );

    open(INF, "> $Tmp_prefix.hs") || &tidy_up_and_die(1,"Can't open $Tmp_prefix.hs\n");
sof's avatar
sof committed
1325
1326
    print STDERR "Enter your Haskell program, end with ^D (on a line of its own):\n" if -t;
    while (<STDIN>) { print INF $_; }
sof's avatar
sof committed
1327
1328
1329
1330
1331
1332
1333
    close(INF) || &tidy_up_and_die(1,"Failed writing to $Tmp_prefix.hs\n");
}

\end{code}

Tell the world who we are, if they asked.
\begin{code}
1334
print STDERR "${ProjectName}, version ${ProjectVersion}, patchlevel ${ProjectPatchLevel}\n"
sof's avatar
sof committed
1335
1336
1337
1338
1339
1340
1341
1342
    if $Verbose;
\end{code}

%************************************************************************
%*									*
\section[Driver-main-loop]{Main loop: Process input files, and link if required}
%*									*
%************************************************************************
1343

sof's avatar
sof committed
1344
1345
1346
1347
1348
1349
Process the input files; don't continue with linking if there are
problems (global variable @$Status@ non-zero).
\begin{code}
foreach $ifile (@Input_file) {
    &ProcessInputFile($ifile);
}
1350

sof's avatar
sof committed
1351
1352
1353
1354
1355
if ( $Status > 0 ) { # don't link if there were errors...
    print STDERR $ShortUsage;
    &tidy_up();
    exit $Status;
}
1356

1357
1358
# append last minute flags linker and consistency flags
&setupBuildFlags();
sof's avatar
sof committed
1359
1360
&setupSyslibs();
&setupLinkOpts();
1361

sof's avatar
sof committed
1362
\end{code}
1363

sof's avatar
sof committed
1364
1365
1366
1367
Link if appropriate.
\begin{code}
if ($Do_lnkr) {
    local($libdirs) = '';
1368

sof's avatar
sof committed
1369
1370
    # glue them together:
    push(@UserLibrary_dir, @SysLibrary_dir);
1371

sof's avatar
sof committed
1372
    $libdirs = '-L' . join(' -L',@UserLibrary_dir) if $#UserLibrary_dir >= 0;
1373

sof's avatar
sof committed
1374
1375
    # for a linker, use an explicitly given one, or the going C compiler ...
    local($lnkr) = ( $Lnkr ) ? $Lnkr : $CcRegd;
1376

sof's avatar
sof committed
1377
1378
1379
1380
1381
1382
    if ( ($Specific_output_file eq '') && 
         ($TargetPlatform eq 'i386-unknown-cygwin32') ) {
         $Specific_output_file = 'main.exe';
         print STDERR "Output file not specified, defaulting to \"main.exe\"\n";
    }

sof's avatar
sof committed
1383
    local($output) = ($Specific_output_file ne '') ? "-o $Specific_output_file" : '';
sof's avatar
sof committed
1384
    @Files_to_tidy = ($Specific_output_file ne '') ? $Specific_output_file : 'a.out'; 
1385

sof's avatar
sof committed
1386
1387
    local($to_do) = "$lnkr $Verbose @Ld_flags $output @Link_file $TopClosureFile $libdirs @UserLibrary @SysLibrary";
    &run_something($to_do, 'Linker');
1388

sof's avatar
sof committed
1389
1390
1391
    # finally, check the consistency info in the binary
    local($executable) = $Files_to_tidy[0];
    @Files_to_tidy = (); # reset; we don't want to nuke it if it's inconsistent
1392

sof's avatar
sof committed
1393
1394
1395
1396
    if ( $LinkChk ) {
    	# dynamically load consistency-chking code; then do it.
	require('ghc-consist.prl')
	    || &tidy_up_and_die(1,"$Pgm: panic: can't load ghc-consist.prl!\n");
1397

sof's avatar
sof committed
1398
1399
    	&chk_consistency_info ( $executable );
    }
1400

sof's avatar
sof committed
1401
1402
1403
1404
1405
1406
1407
    # if PVM parallel stuff, we do truly weird things.
    # Essentially: (1) move the executable over to where PVM expects
    # to find it.  (2) create a script in place of the executable
    # which will cause the program to be run, via SysMan.
    if ( $PARing eq 'p' ) {
	local($pvm_executable) = $executable;
	local($pvm_executable_base);
1408

sof's avatar
sof committed
1409
1410
1411
1412
1413
1414
	if ( $pvm_executable !~ /^\// ) { # a relative path name: make absolute
	    local($pwd) = `pwd`;
	    chop($pwd);
	    $pwd =~ s/^\/tmp_mnt//;
	    $pvm_executable = "$pwd/$pvm_executable";
	}
1415

sof's avatar
sof committed
1416
1417
	$pvm_executable =~ s|/|=|g; # make /s into =s
	$pvm_executable_base = $pvm_executable;
1418

sof's avatar
sof committed
1419
1420
	$pvm_executable = $ENV{'PVM_ROOT'} . '/bin/' . $ENV{'PVM_ARCH'}
			. "/$pvm_executable";
1421

sof's avatar
sof committed
1422
	&run_something("$Rm -f $pvm_executable; $Cp -p $executable $pvm_executable && $Rm -f $executable", 'Moving binary to PVM land');
1423

sof's avatar
sof committed
1424
1425
1426
	# OK, now create the magic script for "$executable"
	open(EXEC, "> $executable") || &tidy_up_and_die(1,"$Pgm: couldn't open $executable to write!\n");
	print EXEC <<EOSCRIPT1;
sof's avatar
sof committed
1427
1428
eval 'exec perl -S \$0 \${1+"\$@"}'
  if \$running_under_some_shell;
sof's avatar
sof committed
1429
1430
# =!=!=!=!=!=!=!=!=!=!=!
# This script is automatically generated: DO NOT EDIT!!!
1431
# Generated by Glasgow Haskell, version ${ProjectVersion} ${ProjectPatchLevel}
sof's avatar
sof committed
1432
1433
1434
1435
1436
#
\$pvm_executable      = '$pvm_executable';
\$pvm_executable_base = '$pvm_executable_base';
\$SysMan = '$SysMan';
EOSCRIPT1
1437

sof's avatar
sof committed
1438
1439
1440
1441
1442
1443
1444
1445
	print EXEC <<\EOSCRIPT2;
# first, some magical shortcuts to run "commands" on the binary
# (which is hidden)
if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {
    local($cmd) = $1;
    system("$cmd $pvm_executable");
    exit(0); # all done
}
1446

sof's avatar
sof committed
1447
1448
1449
1450
1451
1452
# OK, really run it; process the args first
$ENV{'PE'} = $pvm_executable_base;
$debug = '';
$nprocessors = 2; # the default
@nonPVM_args = ();
$in_RTS_args = 0;
1453

sof's avatar
sof committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
# ToDo: handle --RTS
args: while ($a = shift(@ARGV)) {
    if ( $a eq '+RTS' ) {
	$in_RTS_args = 1;
    } elsif ( $a eq '-RTS' ) {
	$in_RTS_args = 0;
    }
    if ( $a eq '-d' && $in_RTS_args ) {
	$debug = '-';
    } elsif ( $a =~ /^-N(\d+)/ && $in_RTS_args ) {
	$nprocessors = $1;
    } else {
	push(@nonPVM_args, $a);
    }
}
1469

sof's avatar
sof committed
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
<