ghc.lprl 110 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',
sof's avatar
sof committed
290
		     '-fwarn-type-defaults',
291
292
		     '-fwarn-name-shadowing',
		     '-fwarn-missing-signatures');
293
294
\end{code}

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

297
298
299
300
301
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

302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
%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" );
327
328

# these are options that are "fed back" through the option processing loop
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
354
#
%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",
355
	'_mg', "$WAY_mg_HC_OPTS");
356
357
358
359
360

\end{code}

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

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

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

371
372
373
# 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.

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

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

@HsSourceCppOpts = 
	( "-D__HASKELL1__=$Haskell1Version"
	, "-D__GLASGOW_HASKELL__=$ProjectVersionInt"
sof's avatar
sof committed
382
	, "-D__HASKELL98__"
383
	, "-D__CONCURRENT_HASKELL__"
384
385
	);

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

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

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

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

# 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  = ();
430
\end{code}
sof's avatar
sof committed
431

432
433
434
435
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
436
437
438
439
$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      = '';
440
$StgLint       = '';
sof's avatar
sof committed
441
442
443
444
445

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


446
447
448
449
450
451
452
453
454
455
456
\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
457
458
$Cpp_flag_set = 0;	  # (hack)
$Only_preprocess_C = 0;	  # pretty hackish
sof's avatar
sof committed
459
460
$Only_preprocess_hc = 0;  # ditto
$Only_generate_deps = 0;  # "
461
462
$PostprocessCcOutput = 0;

sof's avatar
sof committed
463
464
465
466
467
# Win32 only:
#    static /= 0 => produce code for DLLs (when compiling/linking.)
$Static = 1;
$Static = 0 if ($TargetPlatform =~ /-mingw32$/);

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

$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
487
$PROFdict = '';		# set to relevant hsc flag if -auto-dicts
488
$PROFignore_scc = '';	# set to relevant parser flag if explicit sccs ignored
489
$UNPROFscc_auto = '';	# set to relevant hsc flag if forcing auto sccs without profiling
490
$TICKYing = '';    	# set to t if compiling for ticky-ticky profiling
491
$PARing = '';		# set to p if compiling for PAR
492
493
494
495
$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;
496
$Isuffix    = '';
497
498
$Osuffix    = '';	# default: use the normal suffix for that kind of output
$HiSuffix   = 'hi';
499
$HiSuffix_prelude = '';
500
$Do_recomp_chkr = 0;	# don't use the recompilatio checker unless asked
501
502
$Do_cc	    = -1;   # a MAGIC indeterminate value; will be set to 1 or 0.
$Do_as	    = 1;
sof's avatar
sof committed
503

504
505
$Keep_hc_file_too = 0;
$Keep_s_file_too = 0;
506
$UseGhcInternals = 0; # if 1, may use GHC* modules
507
$SplitObjFiles = 0;
508
$DoAsmMangling = 1; # on by default, off by -fno-asm-mangling
509
510
511
512
$NoOfSplitFiles = 0;
$Dump_parser_output = 0;
$Dump_raw_asm = 0;
$Dump_asm_splitting_info = 0;
513
$NoImplicitPrelude = 0;
514
515
516
# 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
517
518
519
520
521
522

} # end of initDriverGlobals (Sigh)

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

# the list of files
523
524
525
526
@Input_file = ();

# and files to be linked...
@Link_file  = ();
sof's avatar
sof committed
527
528
529
530

# and whatever else
@Cmd_opts  = ();

sof's avatar
sof committed
531
532
533
# cmd line options prefixing the unit we're compiling
@File_options = ();

534
535
536
537
538
539
540
541
542
543
\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}
544
$LinkChk = 0;	# set to 0 if the link check should *not* be done
545
546
547

# major & minor version numbers; major numbers must always agree;
# minor disagreements yield a warning.
sof's avatar
sof committed
548
549
550
551
$HsC_major_version = $HscMajorVersion;
$HsC_minor_version = $HscMinorVersion;
$Cc_major_version  = $CcMajorVersion;
$Cc_minor_version  = $CcMinorVersion;
552
553
554
555
556

# options: these must always agree
$HsC_consist_options = '';    # we record, in this order:
			      #	    Build tag; debugging?
$Cc_consist_options  = '';    # we record, in this order:
557
			      #	    Build tag; debugging?
558
559
560
561
562
563
564
565
566
567
\end{code}

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

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

sof's avatar
sof committed
569
570
571
572
&initDriverGlobals();
&splitCmdLine(@ARGV);
# Run through the cmd-line first time.
&processArgs(@Cmd_opts);
573

sof's avatar
sof committed
574
575
576
# Check to see if driver is only in the business
# to generate dependencies
if (  $Status == 0 && $Only_generate_deps ) {
577

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

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

sof's avatar
sof committed
593
594
595
596
597
598
599
600
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++;
    }
}
601

sof's avatar
sof committed
602
603
604
605
606
607
608
609
610
611
612
# 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
    }
}
613

sof's avatar
sof committed
614
615
616
617
618
619
# crash and burn if there were errors
if ( $Status > 0 ) {
    print STDERR $ShortUsage;
    exit $Status;
}
\end{code}
620

sof's avatar
sof committed
621
622
623
624
625
%************************************************************************
%*									*
\section[Driver-post-argv-mangling]{Setup after reading options}
%*									*
%************************************************************************
626

sof's avatar
sof committed
627
628
629
630
631
%************************************************************************
%*									*
\subsection{Set up for optimisation level (\tr{-O} or whatever)}
%*									*
%************************************************************************
632

sof's avatar
sof committed
633
634
635
636
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).
637

sof's avatar
sof committed
638
639
640
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...).
641

sof's avatar
sof committed
642
643
644
645
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.
646

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

sof's avatar
sof committed
650
651
652
653
654
655
656
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...)
657

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

sof's avatar
sof committed
662
663
664
\item[\tr{-fstatic-args}:]
The static-arguments-transformation pass {\em must} have the
simplifier run right after it.
665

sof's avatar
sof committed
666
667
668
669
\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.)
670

sof's avatar
sof committed
671
672
673
674
\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}
675

sof's avatar
sof committed
676
677
678
679
680
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}
681

sof's avatar
sof committed
682
\begin{code}
683

sof's avatar
sof committed
684
sub setupOptimiseFlags {
685

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

# 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
708
709
710
711
712
713
714
715
716
	  #
	  # 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.
717
718
719
	  #
          # Let's find out..
          #'-fclone-binds',
sof's avatar
sof committed
720

sof's avatar
sof committed
721
	  $Oopt_MaxSimplifierIterations,
sof's avatar
sof committed
722
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
723
	  ']',
sof's avatar
sof committed
724
725
726
727
728
	$Oopt_AddAutoSccs,
#	'-ffull-laziness',	# removed 95/04 WDP following Andr\'e's lead
	
	$Oopt_FinalStgProfilingMassage
      );
729

sof's avatar
sof committed
730
731
732
   @HsC_minusO_flags # NOTE: used for *both* -O and -O2 (some conditional bits)
    = (
        '-fdo-eta-reduction',
733

sof's avatar
sof committed
734
735
	# initial simplify: mk specialiser happy: minimum effort please
	'-fsimplify',
sof's avatar
sof committed
736
	  '[', 
sof's avatar
sof committed
737
738
	  $Oopt_FB_Support,
	  '-fkeep-spec-pragma-ids',	# required before specialisation
sof's avatar
sof committed
739
740
741
742
743
744
745
746
747
748
749
750

# 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...
751
# The g=f will get reverse-substituted later, but it's untidy. --SLPJ
sof's avatar
sof committed
752
#
753
754
755
756
757
758
759
760
761
762
763
764
# 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
765

sof's avatar
sof committed
766
767
768
	  # See remark re: cloning in defn of minusnotO
	  '-fclone-binds',

769
	  '-fdo-case-elim',
sof's avatar
sof committed
770
771
	  '-fmax-simplifier-iterations1',
	  $Oopt_PedanticBottoms,
sof's avatar
sof committed
772
	  ']',
773

sof's avatar
sof committed
774
775
776
	($Oopt_DoSpecialise) ? (
	  $Oopt_DoSpecialise,
	) : (),
777

778
	'-fsimplify', 		# need dependency anal after specialiser ...
sof's avatar
sof committed
779
	  '[', 			# need tossing before calc-inlinings ...
sof's avatar
sof committed
780
781
782
783
784
785
786
787
788
789
790
791
	  $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
792
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
793
794
795
796
797
798
799
800
801
	  #
	  # 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
802
	  ']',
803

sof's avatar
sof committed
804
805
806
807
#	($Oopt_FoldrBuildWW) ? (
#		'-ffoldr-build-ww-anal',
#		'-ffoldr-build-worker-wrapper',
#		'-fsimplify', 
sof's avatar
sof committed
808
#		  '[', 
sof's avatar
sof committed
809
810
811
812
813
814
815
816
817
818
819
820
#		  $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
821
#		  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
822
#		  ']',
sof's avatar
sof committed
823
#	 ) : (),
824

sof's avatar
sof committed
825
826
827
	# this pass-ordering sequence was agreed by Simon and Andr\'e
	# (WDP 94/07, 94/11).
	'-ffull-laziness',
828

sof's avatar
sof committed
829
830
	($Oopt_FoldrBuild) ? (
	  '-ffoldr-build-on',		# desugar list comprehensions for foldr/build
831

sof's avatar
sof committed
832
	  '-fsimplify', 
sof's avatar
sof committed
833
	    '[', 
sof's avatar
sof committed
834
835
836
837
838
839
840
841
842
843
844
845
846
847
	    '-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
848
	    $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
849
	    ']',
sof's avatar
sof committed
850
	) : (),
851

sof's avatar
sof committed
852
	'-ffloat-inwards',
853

sof's avatar
sof committed
854
	'-fsimplify',
sof's avatar
sof committed
855
	  '[', 
sof's avatar
sof committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
	  $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
872
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
873
	  ']',
874

sof's avatar
sof committed
875
	'-fstrictness',
876

sof's avatar
sof committed
877
	'-fsimplify',
sof's avatar
sof committed
878
	  '[', 
sof's avatar
sof committed
879
880
881
882
883
884
885
886
887
888
889
890
891
	  $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
892
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
893
	  ']',
894

sof's avatar
sof committed
895
	'-ffloat-inwards',
896

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

sof's avatar
sof committed
900
901
#	( ($OptLevel != 2)
#        ? ''
902
#	: "-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 ]" ),
903

sof's avatar
sof committed
904
# Final clean-up simplification:
905

sof's avatar
sof committed
906
	'-fsimplify',
sof's avatar
sof committed
907
	  '[', 
sof's avatar
sof committed
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
	  $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
925
	  $Oopt_ShowSimplifierProgress,
sof's avatar
sof committed
926
	  ']',
927

sof's avatar
sof committed
928
      #	'-fstatic-args',
929

sof's avatar
sof committed
930
#LATER:	'-fcalc-inlinings2', -- pointless for 2.01
931

sof's avatar
sof committed
932
933
934
935
      # stg2stg passes
	'-flambda-lift',
	$Oopt_FinalStgProfilingMassage,
	$Oopt_StgStats,
936

sof's avatar
sof committed
937
938
      # flags for stg2stg
	'-flet-no-escape',
939

sof's avatar
sof committed
940
941
      # SPECIAL FLAGS for -O2
	($OptLevel == 2) ? (
942
	  '-fupdate-analysis',	# virtually useless; relegated to -O2
sof's avatar
sof committed
943
944
945
	  '-fsemi-tagging',
	) : (),
      );
946

sof's avatar
sof committed
947
\end{code}
948

sof's avatar
sof committed
949
950
951
952
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 ) {
953

sof's avatar
sof committed
954
955
956
957
    # 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');
958

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

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

sof's avatar
sof committed
964
965
966
    &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,
967
    # but it *is* useful in compiling the garbage collector.
sof's avatar
sof committed
968
969
970
971

} else { # -Ofile, then...

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

sof's avatar
sof committed
974
975
976
977
978
979
980
981
982
983
984
985
986
    push(@CcBoth_flags, ($MinusO2ForC) ? '-O2' : '-O');	# possibly to be elaborated...
}

} # setupOptimiseFlags

\end{code}

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

987
Sort out @$BuildTag@, @$PROFing@, @$PARing@,
sof's avatar
sof committed
988
989
990
991
992
@$GRANing@, @$TICKYing@:
\begin{code}
sub setupBuildFlags {


993
994
995
996
997
998
999
1000
1001
1002
1003
   # 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;
1004
      push(@HsC_flags, $PROFdict) if $PROFdict;
1005
1006

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

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

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
      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
1024
1025
1026
      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; }
1027
      $BuildTag = '_p' ;
sof's avatar
sof committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053

  } 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...

1054
      local($Tag) = "${BuildTag}";
sof's avatar
sof committed
1055
1056
1057
      $Tag =~ s/_//;  # move the underscore to the back

      $HscOut = '-C='; # must go via C
1058
1059
      &processArgs(split(' ', $SetupOpts{$BuildTag}));
#      eval($EvaldSetupOpts{$BuildTag});
sof's avatar
sof committed
1060
1061
1062
1063
1064
  }
\end{code}

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

sof's avatar
sof committed
1066
1067
1068
  $HsC_consist_options = "${BuildTag},${DEBUGging}";
  $Cc_consist_options  = "${BuildTag},${DEBUGging}";

1069
1070
1071
1072
1073
1074
1075
1076
1077
  #
  # 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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
} # 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'));
1101
      #
sof's avatar
sof committed
1102
1103
1104
1105
      # 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).
1106
1107
1108
      #  
      # [Dated comment (gcc-2.6.x?), -mlong-calls is no longer
      #  a supported gcc HPPA flag]
sof's avatar
sof committed
1109
1110
1111
1112
1113
1114
1115
      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
      #
1116
1117
      # -fomit-frame-pointer : *must* in .hc files; because we're stealing
      #	 the fp (%ebp) for our register maps.
sof's avatar
sof committed
1118
1119

      unshift(@CcRegd_flags_hc, '-fno-defer-pop');
1120
      unshift(@CcRegd_flags_hc, '-fomit-frame-pointer');
sof's avatar
sof committed
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
      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'));

1142
  } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
sof's avatar
sof committed
1143
1144
1145
1146
1147
1148
1149
      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}

1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
%************************************************************************
%*									*
\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
1167
1168
Same unshifting magic, but for special linker flags.

1169
1170
1171
1172
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
1173
1174
1175

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

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

  # things that are referenced by the RTS - make sure that we pull 'em in
sof's avatar
sof committed
1182
  unshift(@Ld_flags,
1183
1184
1185
1186
1187
1188
1189
1190
         ( '-u', "${uscore}PrelBase_Izh_static_info"
          ,'-u', "${uscore}PrelBase_Czh_static_info"
          ,'-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"
1191
          ,'-u', "${uscore}PrelStable_StablePtr_static_info"
1192
1193
1194
1195
1196
1197
1198
1199
	  ,'-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"
1200
          ,'-u', "${uscore}PrelStable_StablePtr_con_info"
1201
1202
1203
          ,'-u', "${uscore}PrelBase_False_static_closure"
          ,'-u', "${uscore}PrelBase_True_static_closure"
          ,'-u', "${uscore}PrelPack_unpackCString_closure"
1204
1205
          ,'-u', "${uscore}PrelException_stackOverflow_closure"
          ,'-u', "${uscore}PrelException_heapOverflow_closure"
sof's avatar
sof committed
1206
	));
1207
1208
1209
  if (!$NoHaskellMain) {
   unshift (@Ld_flags,'-u', "${uscore}PrelMain_mainIO_closure");
  }
1210
1211
1212
1213
1214
  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
1215

sof's avatar
sof committed
1216

sof's avatar
sof committed
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
} # 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
1234
1235
  if ( ! $INSTALLING ) {
      push (@Include_dir, "$TopPwd/${CURRENT_DIR}/${GHC_INCLUDE_DIR}");
sof's avatar
sof committed
1236
1237
  } else {
      push (@Include_dir, "$InstLibDirGhc/includes");
sof's avatar
sof committed
1238
      push (@Include_dir, "$InstLibDirGhc/includes");
sof's avatar
sof committed
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
  }
} # 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}");
1255

1256
1257
1258
1259
1260
  #
  # 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.
  #
1261
  push(@SysLibrary, '-lwinmm') if $TargetPlatform eq 'i386-unknown-cygwin32';
sof's avatar
sof committed
1262
1263
1264
1265

  # Push the pvm libraries
  if ($BuildTag eq '_mp') {
      $pvmlib = "$ENV{'PVM_ROOT'}/lib/$ENV{'PVM_ARCH'}";
1266
      push(@SysLibrary, "-L$pvmlib", '-lgpvm3', '-lpvm3');
sof's avatar
sof committed
1267
1268
1269
1270
1271
1272
1273
1274
      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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284

# 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
1285
push(@SysLibrary, '-lm') if !( $TargetPlatform =~ /^.*(cygwin32|mingw32)$/ );
sof's avatar
sof committed
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
\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}
1297
#die "$Pgm: no BuildAvail?? $BuildTag\n" if $BuildDescr{$BuildTag} eq '' ; # sanity
sof's avatar
sof committed
1298

1299
if ( $BuildDescr{$BuildTag} eq '' ) {
sof's avatar
sof committed
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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
    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
1336
1337
    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
1338
1339
1340
1341
1342
1343
1344
    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}
1345
print STDERR "${ProjectName}, version ${ProjectVersion}, patchlevel ${ProjectPatchLevel}\n"
sof's avatar
sof committed
1346
1347
1348
1349
1350
1351
1352
1353
    if $Verbose;
\end{code}

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

sof's avatar
sof committed
1355
1356
1357
1358
1359
1360
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);
}
1361

sof's avatar
sof committed
1362
1363
1364
1365
1366
if ( $Status > 0 ) { # don't link if there were errors...
    print STDERR $ShortUsage;
    &tidy_up();
    exit $Status;
}
1367

1368
1369
# append last minute flags linker and consistency flags
&setupBuildFlags();
sof's avatar
sof committed
1370
1371
&setupSyslibs();
&setupLinkOpts();
1372

sof's avatar
sof committed
1373
\end{code}
1374

sof's avatar
sof committed
1375
1376
1377
1378
Link if appropriate.
\begin{code}
if ($Do_lnkr) {
    local($libdirs) = '';
1379

sof's avatar
sof committed
1380
1381
    # glue them together:
    push(@UserLibrary_dir, @SysLibrary_dir);
1382

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

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

sof's avatar
sof committed
1388
1389
1390
1391
1392
1393
    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
1394
    local($output) = ($Specific_output_file ne '') ? "-o $Specific_output_file" : '';
sof's avatar
sof committed
1395
    @Files_to_tidy = ($Specific_output_file ne '') ? $Specific_output_file : 'a.out'; 
1396

sof's avatar
sof committed
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
    #
    # Win32 DLLs - link with import libraries, not the real archives.
    # 
    if ( $TargetPlatform =~ /-mingw32$/ && !$Static ) {
       foreach $a ( @SysLibrary ) {
	  next if ($a eq '-lm');
          $a = "${a}_imp" if ($a =~ /^-l/);
       }
       push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/Main.o"
			                 : "$TopPwd/$CURRENT_DIR/$GHC_RUNTIME_DIR/Main.o");
       push(@Link_file, ( $INSTALLING ) ? "$InstLibDirGhc/PrelMain.o"
			                 : "$TopPwd/$CURRENT_DIR/$GHC_LIB_DIR/PrelMain.o");
       push(@Ld_flags,  "-mno-cygwin");
    }
sof's avatar
sof committed
1411
1412
    local($to_do) = "$lnkr $Verbose @Ld_flags $output @Link_file $TopClosureFile $libdirs @UserLibrary @SysLibrary";
    &run_something($to_do, 'Linker');
1413

sof's avatar
sof committed
1414
1415
1416
    # 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
1417

sof's avatar
sof committed
1418
1419
1420
1421
    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");
1422

sof's avatar
sof committed
1423
1424
    	&chk_consistency_info ( $executable );
    }
1425

sof's avatar
sof committed
1426
1427
1428
1429
1430
1431
1432
    # 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);
1433

sof's avatar
sof committed
1434
1435
1436
1437
1438
1439
	if ( $pvm_executable !~ /^\// ) { # a relative path name: make absolute
	    local($pwd) = `pwd`;
	    chop($pwd);
	    $pwd =~ s/^\/tmp_mnt//;
	    $pvm_executable = "$pwd/$pvm_executable";
	}
1440

sof's avatar
sof committed
1441
1442
	$pvm_executable =~ s|/|=|g; # make /s into =s
	$pvm_executable_base = $pvm_executable;
1443

sof's avatar
sof committed
1444
1445
	$pvm_executable = $ENV{'PVM_ROOT'} . '/bin/' . $ENV{'PVM_ARCH'}
			. "/$pvm_executable";
1446

sof's avatar
sof committed