8475e625748cfca87da3881329a331b21f8ea565
[ghc-hetmet.git] / ghc / driver / ghc-asm.lprl
1 %************************************************************************
2 %*                                                                      *
3 \section[Driver-asm-fiddling]{Fiddling with assembler files}
4 %*                                                                      *
5 %************************************************************************
6
7 Tasks:
8 \begin{itemize}
9 \item
10 Utterly stomp out C functions' prologues and epilogues; i.e., the
11 stuff to do with the C stack.
12 \item
13 Any other required tidying up.
14 \end{itemize}
15
16 HPPA specific notes:
17 \begin{itemize}
18 \item
19 The HP linker is very picky about symbols being in the appropriate
20 space (code vs. data).  When we mangle the threaded code to put the
21 info tables just prior to the code, they wind up in code space
22 rather than data space.  This means that references to *_info from
23 un-mangled parts of the RTS (e.g. unthreaded GC code) get
24 unresolved symbols.  Solution:  mini-mangler for .c files on HP.  I
25 think this should really be triggered in the driver by a new -rts
26 option, so that user code doesn't get mangled inappropriately.
27 \item
28 With reversed tables, jumps are to the _info label rather than to
29 the _entry label.  The _info label is just an address in code
30 space, rather than an entry point with the descriptive blob we
31 talked about yesterday.  As a result, you can't use the call-style
32 JMP_ macro.  However, some JMP_ macros take _info labels as targets
33 and some take code entry points within the RTS.  The latter won't
34 work with the goto-style JMP_ macro.  Sigh.  Solution: Use the goto
35 style JMP_ macro, and mangle some more assembly, changing all
36 "RP'literal" and "LP'literal" references to "R'literal" and
37 "L'literal," so that you get the real address of the code, rather
38 than the descriptive blob.  Also change all ".word P%literal"
39 entries in info tables and vector tables to just ".word literal,"
40 for the same reason.  Advantage: No more ridiculous call sequences.
41 \end{itemize}
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection{Constants for various architectures}
46 %*                                                                      *
47 %************************************************************************
48
49 \begin{code}
50 sub init_TARGET_STUFF {
51
52     #--------------------------------------------------------#
53     if ( $TargetPlatform =~ /^alpha-.*-.*/ ) {
54
55     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
56     $T_US           = ''; # _ if symbols have an underscore on the front
57     $T_DO_GC        = 'PerformGC_wrapper';
58     $T_PRE_APP      = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
59     $T_CONST_LBL    = '^\$C(\d+):$'; # regexp for what such a lbl looks like
60     $T_POST_LBL     = ':';
61
62     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.(globl|ent)\s+\S+|\#.*|\.(file|loc)\s+\S+\s+\S+|\.text|\.r?data)\n)';
63     $T_COPY_DIRVS   = '^\s*(\#|\.(file|globl|ent|loc))';
64
65     $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
66     $T_DOT_WORD     = '\.quad';
67     $T_DOT_GLOBAL   = '^\t\.globl';
68     $T_HDR_literal  = "\.rdata\n\t\.align 3\n";
69     $T_HDR_misc     = "\.text\n\t\.align 3\n";
70     $T_HDR_data     = "\.data\n\t\.align 3\n";
71     $T_HDR_consist  = "\.text\n";
72     $T_HDR_closure  = "\.data\n\t\.align 3\n";
73     $T_HDR_info     = "\.text\n\t\.align 3\n";
74     $T_HDR_entry    = "\.text\n\t\.align 3\n";
75     $T_HDR_fast     = "\.text\n\t\.align 3\n";
76     $T_HDR_vector   = "\.text\n\t\.align 3\n";
77     $T_HDR_direct   = "\.text\n\t\.align 3\n";
78
79     #--------------------------------------------------------#
80     } elsif ( $TargetPlatform =~ /^hppa/ ) {
81
82     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
83     $T_US           = ''; # _ if symbols have an underscore on the front
84     $T_DO_GC        = 'PerformGC_wrapper';
85     $T_PRE_APP      = 'DONT THINK THIS APPLIES'; # regexp that says what comes before APP/NO_APP
86     $T_CONST_LBL    = '^L\$C(\d+)$'; # regexp for what such a lbl looks like
87     $T_POST_LBL     = '';
88
89     $T_MOVE_DIRVS   = '^((\s+\.(IMPORT|EXPORT|PARAM).*|\s+\.align\s+\d+|\s+\.(SPACE|SUBSPA)\s+\S+|\s*)\n)';
90     $T_COPY_DIRVS   = '^\s+\.(IMPORT|EXPORT)';
91
92     $T_hsc_cc_PAT   = '\.STRING.*\)(hsc|cc) (.*)\\\\x09(.*)\\\\x00"';
93     $T_DOT_WORD     = '\.word';
94     $T_DOT_GLOBAL   = '^\s+\.EXPORT';
95     $T_HDR_literal  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
96     $T_HDR_misc     = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
97     $T_HDR_data     = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
98     $T_HDR_consist  = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$LIT\$\n";
99     $T_HDR_closure  = "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$DATA\$\n\t\.align 4\n";
100     $T_HDR_info     = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
101     $T_HDR_entry    = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
102     $T_HDR_fast     = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
103     $T_HDR_vector   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
104     $T_HDR_direct   = "\t.SPACE \$TEXT\$\n\t.SUBSPA \$CODE\$\n\t\.align 4\n";
105
106     #--------------------------------------------------------#
107     } elsif ( $TargetPlatform =~ /^i386-.*-(linuxaout|freebsd|nextstep3|cygwin32)/ ) {
108                                 # NeXT added but not tested. CaS
109
110     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
111     $T_US           = '_'; # _ if symbols have an underscore on the front
112     $T_DO_GC        = '_PerformGC_wrapper';
113     $T_PRE_APP      = '^#'; # regexp that says what comes before APP/NO_APP
114     $T_CONST_LBL    = '^LC(\d+):$';
115     $T_POST_LBL     = ':';
116     $T_X86_PRE_LLBL_PAT = 'L';
117     $T_X86_PRE_LLBL         = 'L';
118     $T_X86_BADJMP   = '^\tjmp [^L\*]';
119
120     $T_MOVE_DIRVS   = '^(\s*(\.(p2)?align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.stab[^n].*|\.type\s+.*|\.size\s+.*)\n)';
121     $T_COPY_DIRVS   = '\.(globl|stab)';
122     $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
123     $T_DOT_WORD     = '\.long';
124     $T_DOT_GLOBAL   = '\.globl';
125     $T_HDR_literal  = "\.text\n\t\.align 2\n";
126     $T_HDR_misc     = "\.text\n\t\.align 2,0x90\n";
127     $T_HDR_data     = "\.data\n\t\.align 2\n";
128     $T_HDR_consist  = "\.text\n";
129     $T_HDR_closure  = "\.data\n\t\.align 2\n";
130     $T_HDR_info     = "\.text\n\t\.align 2\n"; # NB: requires padding
131     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
132     $T_HDR_fast     = "\.text\n\t\.align 2,0x90\n";
133     $T_HDR_vector   = "\.text\n\t\.align 2\n"; # NB: requires padding
134     $T_HDR_direct   = "\.text\n\t\.align 2,0x90\n";
135
136     #--------------------------------------------------------#
137     } elsif ( $TargetPlatform =~ /^i386-.*-(solaris2|linux)$/ ) {
138
139     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
140     $T_US           = ''; # _ if symbols have an underscore on the front
141     $T_DO_GC        = 'PerformGC_wrapper';
142     $T_PRE_APP      = # regexp that says what comes before APP/NO_APP
143                       ($TargetPlatform =~ /-linux$/) ? '#' : '/' ;
144     $T_CONST_LBL    = '^\.LC(\d+):$'; # regexp for what such a lbl looks like
145     $T_POST_LBL     = ':';
146     $T_X86_PRE_LLBL_PAT = '\.L';
147     $T_X86_PRE_LLBL         = '.L';
148     $T_X86_BADJMP   = '^\tjmp [^\.\*]';
149
150     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+(,0x90)?|\.globl\s+\S+|\.text|\.data|\.section\s+.*|\.type\s+.*|\.Lfe.*\n\t\.size\s+.*|\.size\s+.*|\.ident.*)\n)';
151     $T_COPY_DIRVS   = '\.(globl)';
152
153     $T_hsc_cc_PAT   = '\.string.*\)(hsc|cc) (.*)\\\\t(.*)"';
154     $T_DOT_WORD     = '\.long';
155     $T_DOT_GLOBAL   = '\.globl';
156     $T_HDR_literal  = "\.section\t\.rodata\n"; # or just use .text??? (WDP 95/11)
157     $T_HDR_misc     = "\.text\n\t\.align 16\n";
158     $T_HDR_data     = "\.data\n\t\.align 4\n"; # ToDo: change align??
159     $T_HDR_consist  = "\.text\n";
160     $T_HDR_closure  = "\.data\n\t\.align 4\n"; # ToDo: change align?
161     $T_HDR_info     = "\.text\n\t\.align 16\n"; # NB: requires padding
162     $T_HDR_entry    = "\.text\n"; # no .align so we're right next to _info (arguably wrong...?)
163     $T_HDR_fast     = "\.text\n\t\.align 16\n";
164     $T_HDR_vector   = "\.text\n\t\.align 16\n"; # NB: requires padding
165     $T_HDR_direct   = "\.text\n\t\.align 16\n";
166
167     #--------------------------------------------------------#
168     } elsif ( $TargetPlatform =~ /^m68k-.*-sunos4/ ) {
169
170     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
171     $T_US           = '_'; # _ if symbols have an underscore on the front
172     $T_DO_GC        = '_PerformGC_wrapper';
173     $T_PRE_APP      = '^# MAY NOT APPLY'; # regexp that says what comes before APP/NO_APP
174     $T_CONST_LBL    = '^LC(\d+):$';
175     $T_POST_LBL     = ':';
176
177     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.proc\s+\d+|\.const|\.cstring|\.globl\s+\S+|\.text|\.data|\.even|\.stab[^n].*)\n)';
178     $T_COPY_DIRVS   = '\.(globl|proc|stab)';
179     $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
180
181     $T_DOT_WORD     = '\.long';
182     $T_DOT_GLOBAL   = '\.globl';
183     $T_HDR_literal  = "\.text\n\t\.even\n";
184     $T_HDR_misc     = "\.text\n\t\.even\n";
185     $T_HDR_data     = "\.data\n\t\.even\n";
186     $T_HDR_consist  = "\.text\n";
187     $T_HDR_closure  = "\.data\n\t\.even\n";
188     $T_HDR_info     = "\.text\n\t\.even\n";
189     $T_HDR_entry    = "\.text\n\t\.even\n";
190     $T_HDR_fast     = "\.text\n\t\.even\n";
191     $T_HDR_vector   = "\.text\n\t\.even\n";
192     $T_HDR_direct   = "\.text\n\t\.even\n";
193
194     #--------------------------------------------------------#
195     } elsif ( $TargetPlatform =~ /^mips-.*/ ) {
196
197     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
198     $T_US           = ''; # _ if symbols have an underscore on the front
199     $T_DO_GC        = 'PerformGC_wrapper';
200     $T_PRE_APP      = '^\s*#'; # regexp that says what comes before APP/NO_APP
201     $T_CONST_LBL    = '^\$LC(\d+):$'; # regexp for what such a lbl looks like
202     $T_POST_LBL     = ':';
203
204     $T_MOVE_DIRVS   = '^(\s*(\.align\s+\d+|\.(globl|ent)\s+\S+|\.text|\.r?data)\n)';
205     $T_COPY_DIRVS   = '\.(globl|ent)';
206
207     $T_hsc_cc_PAT   = 'I WAS TOO LAZY TO DO THIS BIT (WDP 95/05)';
208     $T_DOT_WORD     = '\.word';
209     $T_DOT_GLOBAL   = '^\t\.globl';
210     $T_HDR_literal  = "\t\.rdata\n\t\.align 2\n";
211     $T_HDR_misc     = "\t\.text\n\t\.align 2\n";
212     $T_HDR_data     = "\t\.data\n\t\.align 2\n";
213     $T_HDR_consist  = 'TOO LAZY TO DO THIS TOO';
214     $T_HDR_closure  = "\t\.data\n\t\.align 2\n";
215     $T_HDR_info     = "\t\.text\n\t\.align 2\n";
216     $T_HDR_entry    = "\t\.text\n\t\.align 2\n";
217     $T_HDR_fast     = "\t\.text\n\t\.align 2\n";
218     $T_HDR_vector   = "\t\.text\n\t\.align 2\n";
219     $T_HDR_direct   = "\t\.text\n\t\.align 2\n";
220
221     #--------------------------------------------------------#
222     } elsif ( $TargetPlatform =~ /^powerpc-.*|^rs6000-.*/ ) {
223
224     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
225     $T_US           = ''; # _ if symbols have an underscore on the front
226     $T_DO_GC        = '\.PerformGC_wrapper';
227     $T_PRE_APP      = 'NOT APPLICABLE'; # regexp that says what comes before APP/NO_APP
228     $T_CONST_LBL    = 'NOT APPLICABLE'; # regexp for what such a lbl looks like
229     $T_POST_LBL     = ':';
230
231     $T_MOVE_DIRVS   = '^(\s*(\.toc|\.align \d+|\.csect \S+|\t\.?l?globl \S+)\n)';
232     $T_COPY_DIRVS   = '\.(l?globl)';
233
234     $T_hsc_cc_PAT   = '\.byte.*\)(hsc|cc) (.*)"\n\t\.byte \d+\n\t\.byte "(.*)"\n\t\.byte \d+';
235     $T_DOT_WORD     = '\.long';
236     $T_DOT_GLOBAL   = '\.globl';
237     $T_HDR_toc      = "\.toc\n";
238     $T_HDR_literal  = "\.csect .data[RW]\n\t\.align 2\n";               #not RO!?
239     $T_HDR_misc     = "# misc\n\.csect \.text[PR]\n\t\.align 2\n";
240     $T_HDR_data     = "# data\n\.csect \.data[RW]\n\t\.align 2\n";
241     $T_HDR_consist  = "# consist\n\.csect \.data[RW]\n\t\.align 2\n";
242     $T_HDR_closure  = "# closure\n\.csect \.data[RW]\n\t\.align 2\n";
243     $T_HDR_info     = "# info\n\.csect \.data[RW]\n\t\.align 2\n"; #not RO!?
244     $T_HDR_entry    = "# entry\n\.csect \.text[PR]\n\t\.align 2\n";
245     $T_HDR_fast     = "# fast\n\.csect \.text[PR]\n\t\.align 2\n";
246     $T_HDR_vector   = "# vector\n\.csect \.data[RW]\n\t\.align 2\n"; #not RO!?
247     $T_HDR_direct   = "# direct\n";
248
249     #--------------------------------------------------------#
250     } elsif ( $TargetPlatform =~ /^sparc-.*-solaris2/ ) {
251
252     $T_STABBY       = 0; # 1 iff .stab things (usually if a.out format)
253     $T_US           = ''; # _ if symbols have an underscore on the front
254     $T_DO_GC        = 'PerformGC_wrapper';
255     $T_PRE_APP      = 'DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
256     $T_CONST_LBL    = '^\.LLC(\d+):$'; # regexp for what such a lbl looks like
257     $T_POST_LBL     = ':';
258
259     $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\.text|\.data|\.stab.*|\.section.*|\s+\.type.*|\s+\.size.*)\n)';
260     $T_COPY_DIRVS   = '\.(global|proc|stab)';
261
262     $T_hsc_cc_PAT   = '\.asciz.*\)(hsc|cc) (.*)\\\\t(.*)"';
263     $T_DOT_WORD     = '\.word';
264     $T_DOT_GLOBAL   = '^\t\.global';
265     $T_HDR_literal  = "\.text\n\t\.align 8\n";
266     $T_HDR_misc     = "\.text\n\t\.align 4\n";
267     $T_HDR_data     = "\.data\n\t\.align 8\n";
268     $T_HDR_consist  = "\.text\n";
269     $T_HDR_closure  = "\.data\n\t\.align 4\n";
270     $T_HDR_info     = "\.text\n\t\.align 4\n";
271     $T_HDR_entry    = "\.text\n\t\.align 4\n";
272     $T_HDR_fast     = "\.text\n\t\.align 4\n";
273     $T_HDR_vector   = "\.text\n\t\.align 4\n";
274     $T_HDR_direct   = "\.text\n\t\.align 4\n";
275
276     #--------------------------------------------------------#
277     } elsif ( $TargetPlatform =~ /^sparc-.*-sunos4/ ) {
278
279     $T_STABBY       = 1; # 1 iff .stab things (usually if a.out format)
280     $T_US           = '_'; # _ if symbols have an underscore on the front
281     $T_DO_GC        = '_PerformGC_wrapper';
282     $T_PRE_APP      = '^# DOES NOT SEEM TO APPLY'; # regexp that says what comes before APP/NO_APP
283     $T_CONST_LBL    = '^LC(\d+):$';
284     $T_POST_LBL     = ':';
285
286     $T_MOVE_DIRVS   = '^((\s+\.align\s+\d+|\s+\.proc\s+\d+|\s+\.global\s+\S+|\.text|\.data|\.stab.*)\n)';
287     $T_COPY_DIRVS   = '\.(global|proc|stab)';
288     $T_hsc_cc_PAT   = '\.ascii.*\)(hsc|cc) (.*)\\\\11"\n\t\.ascii\s+"(.*)\\\\0"';
289
290     $T_DOT_WORD     = '\.word';
291     $T_DOT_GLOBAL   = '^\t\.global';
292     $T_HDR_literal  = "\.text\n\t\.align 8\n";
293     $T_HDR_misc     = "\.text\n\t\.align 4\n";
294     $T_HDR_data     = "\.data\n\t\.align 8\n";
295     $T_HDR_consist  = "\.text\n";
296     $T_HDR_closure  = "\.data\n\t\.align 4\n";
297     $T_HDR_info     = "\.text\n\t\.align 4\n";
298     $T_HDR_entry    = "\.text\n\t\.align 4\n";
299     $T_HDR_fast     = "\.text\n\t\.align 4\n";
300     $T_HDR_vector   = "\.text\n\t\.align 4\n";
301     $T_HDR_direct   = "\.text\n\t\.align 4\n";
302
303     #--------------------------------------------------------#
304     } else {
305         print STDERR "$Pgm: don't know how to mangle assembly language for: $TargetPlatform\n";
306         exit 1;
307     }
308
309 if ( 0 ) {
310 print STDERR "T_STABBY: $T_STABBY\n";
311 print STDERR "T_US: $T_US\n";
312 print STDERR "T_DO_GC: $T_DO_GC\n";
313 print STDERR "T_PRE_APP: $T_PRE_APP\n";
314 print STDERR "T_CONST_LBL: $T_CONST_LBL\n";
315 print STDERR "T_POST_LBL: $T_POST_LBL\n";
316 if ( $TargetPlatform =~ /^i386-/ ) {
317     print STDERR "T_X86_PRE_LLBL_PAT: $T_X86_PRE_LLBL_PAT\n";
318     print STDERR "T_X86_PRE_LLBL: $T_X86_PRE_LLBL\n";
319     print STDERR "T_X86_BADJMP: $T_X86_BADJMP\n";
320 }
321 print STDERR "T_MOVE_DIRVS: $T_MOVE_DIRVS\n";
322 print STDERR "T_COPY_DIRVS: $T_COPY_DIRVS\n";
323 print STDERR "T_hsc_cc_PAT: $T_hsc_cc_PAT\n";
324 print STDERR "T_DOT_WORD: $T_DOT_WORD\n";
325 print STDERR "T_HDR_literal: $T_HDR_literal\n";
326 print STDERR "T_HDR_misc: $T_HDR_misc\n";
327 print STDERR "T_HDR_data: $T_HDR_data\n";
328 print STDERR "T_HDR_consist: $T_HDR_consist\n";
329 print STDERR "T_HDR_closure: $T_HDR_closure\n";
330 print STDERR "T_HDR_info: $T_HDR_info\n";
331 print STDERR "T_HDR_entry: $T_HDR_entry\n";
332 print STDERR "T_HDR_fast: $T_HDR_fast\n";
333 print STDERR "T_HDR_vector: $T_HDR_vector\n";
334 print STDERR "T_HDR_direct: $T_HDR_direct\n";
335 }
336
337 }
338 \end{code}
339
340 %************************************************************************
341 %*                                                                      *
342 \subsection{Mangle away}
343 %*                                                                      *
344 %************************************************************************
345
346 \begin{code}
347 sub mangle_asm {
348     local($in_asmf, $out_asmf) = @_;
349
350     # multi-line regexp matching:
351     local($*) = 1;
352     local($i, $c);
353
354
355     &init_TARGET_STUFF();
356     &init_FUNNY_THINGS();
357
358     # perl4 on alphas SEGVs when give ${foo} substitutions in patterns.
359     # To avoid them we declare some locals that allows to avoid using curlies.
360     local($TUS)      = ${T_US};
361     local($TPOSTLBL) = ${T_POST_LBL};
362     local($TMOVEDIRVS) = ${T_MOVE_DIRVS};
363     local($TPREAPP)    = ${T_PRE_APP};
364     local($TCOPYDIRVS) = ${T_COPY_DIRVS};
365     local($TDOTWORD)   = ${T_DOT_WORD};
366
367     open(INASM, "< $in_asmf")
368         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
369     open(OUTASM,"> $out_asmf")
370         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
371
372     # read whole file, divide into "chunks":
373     #   record some info about what we've found...
374
375     @chk = ();          # contents of the chunk
376     $numchks = 0;       # number of them
377     @chkcat = ();       # what category of thing in each chunk
378     @chksymb = ();      # what symbol(base) is defined in this chunk
379     %slowchk = ();      # ditto, its regular "slow" entry code
380     %fastchk = ();      # ditto, fast entry code
381     %closurechk = ();   # ditto, the (static) closure
382     %infochk = ();      # given a symbol base, say what chunk its info tbl is in
383     %vectorchk = ();    # ditto, return vector table
384     %directchk = ();    # ditto, direct return code
385     $EXTERN_DECLS = ''; # .globl <foo> .text (MIPS only)
386
387     $i = 0; $chkcat[0] = 'misc'; $chk[0] = '';
388
389     while (<INASM>) {
390         next if $T_STABBY && /^\.stab.*$TUS[@]?__stg_split_marker/o;
391         next if $T_STABBY && /^\.stab.*ghc.*c_ID/;
392         next if /$TPREAPP(NO_)?APP/o; 
393         next if /^;/ && $TargetPlatform =~ /^hppa/;
394
395         next if /(^$|^\t\.file\t|^ # )/ && $TargetPlatform =~ /^(mips|powerpc|rs6000)-/;
396
397         last if /^_section_\.text:$/ && $TargetPlatform =~ /^powerpc-|^rs6000-/;
398
399         if ( $TargetPlatform =~ /^mips-/ 
400           && /^\t\.(globl \S+ \.text|comm\t)/ ) {
401             $EXTERN_DECLS .= $_ unless /(__DISCARD__|\b(PK_|ASSIGN_)(FLT|DBL)\b)/;
402   
403         # As a temporary solution for compiling "foreign export" declarations,
404         # we use global variables to pass arguments from C to STG land.
405         # These declarations live in the .hc file and not in the generated C
406         # stub file, so we let them pass through here.
407         } elsif ( /^[\t]?\.comm[\t ]+${TUS}__fexp_.*$/ ) {
408             $chk[++$i]   = $_;
409             $chkcat[$i]  = 'data';
410             $chksymb[$i] = '';
411
412         } elsif ( /^\s+/ ) { # most common case first -- a simple line!
413             # duplicated from the bottom
414
415             $chk[$i] .= $_;
416
417         } elsif ( /\.\.ng:$/ && $TargetPlatform =~ /^alpha-/ ) {
418             # Alphas: Local labels not to be confused with new chunks
419             $chk[$i] .= $_;
420   
421         # NB: all the rest start with a non-space
422
423         } elsif ( $TargetPlatform =~ /^mips-/
424                && /^\d+:/ ) { # a funny-looking very-local label
425             $chk[$i] .= $_;
426
427         } elsif ( /$T_CONST_LBL/o ) {
428             $chk[++$i]   = $_;
429             $chkcat[$i]  = 'literal';
430             $chksymb[$i] = $1;
431
432         } elsif ( /^$TUS[@]?__stg_split_marker(\d+)$TPOSTLBL[@]?$/o ) {
433             $chk[++$i]   = $_;
434             $chkcat[$i]  = 'splitmarker';
435             $chksymb[$i] = $1;
436
437         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_info$TPOSTLBL[@]?$/o ) {
438             $symb = $1;
439             $chk[++$i]   = $_;
440             $chkcat[$i]  = 'infotbl';
441             $chksymb[$i] = $symb;
442
443             die "Info table already? $symb; $i\n" if defined($infochk{$symb});
444
445             $infochk{$symb} = $i;
446
447         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_entry$TPOSTLBL[@]?$/o ) {
448             $chk[++$i]   = $_;
449             $chkcat[$i]  = 'slow';
450             $chksymb[$i] = $1;
451
452             $slowchk{$1} = $i;
453
454         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_fast\d+$TPOSTLBL[@]?$/o ) {
455             $chk[++$i]   = $_;
456             $chkcat[$i]  = 'fast';
457             $chksymb[$i] = $1;
458
459             $fastchk{$1} = $i;
460
461         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_closure$TPOSTLBL[@]?$/o ) {
462             $chk[++$i]   = $_;
463             $chkcat[$i]  = 'closure';
464             $chksymb[$i] = $1;
465
466             $closurechk{$1} = $i;
467
468         } elsif ( /^$TUS[@]?ghc.*c_ID$TPOSTLBL/o ) {
469             $chk[++$i]  = $_;
470             $chkcat[$i] = 'consist';
471
472         } elsif ( /^($TUS[@]?__gnu_compiled_c|gcc2_compiled\.)$TPOSTLBL/o ) {
473             ; # toss it
474
475         } elsif ( /^$TUS[@]?ErrorIO_call_count$TPOSTLBL[@]?$/o  # HACK!!!!
476                || /^$TUS[A-Za-z0-9_]+\.\d+$TPOSTLBL[@]?$/o
477                || /^$TUS[@]?.*_CAT$TPOSTLBL[@]?$/o              # PROF: _entryname_CAT
478                || /^$TUS[@]?CC_.*_struct$TPOSTLBL[@]?$/o        # PROF: _CC_ccident_struct
479                || /^$TUS[@]?.*_done$TPOSTLBL[@]?$/o             # PROF: _module_done
480                || /^$TUS[@]?_module_registered$TPOSTLBL[@]?$/o  # PROF: _module_registered
481                ) {
482             $chk[++$i]   = $_;
483             $chkcat[$i]  = 'data';
484             $chksymb[$i] = '';
485
486         } elsif ( /^([A-Za-z0-9_]+)\s+\.comm/ && $TargetPlatform =~ /^hppa/ ) {
487             $chk[++$i]   = $_;
488             $chkcat[$i]  = 'bss';
489             $chksymb[$i] = '';
490
491         } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ && /^LC\.\.([0-9]+)/ ) {
492             $chk[++$i]   = $_;
493             $chkcat[$i]  = 'toc';
494             $chksymb[$i] = $1;
495
496         } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ && /^CC_.*$/ ) {
497             # all CC_ symbols go in the data section...
498             $chk[++$i]   = $_;
499             $chkcat[$i]  = 'data';
500             $chksymb[$i] = '';
501
502         } elsif ( /^($TUS[@]?(ret_|djn_)[A-Za-z0-9_]+)/o ) {
503             $chk[++$i]   = $_;
504             $chkcat[$i]  = 'misc';
505             $chksymb[$i] = '';
506             $symbtmp = $1;
507             $chksymb[$i] = $symbtmp if ($TargetPlatform =~ /^powerpc-|^rs6000-/) ; #rm andre
508
509         } elsif ( /^$TUS[@]?vtbl_([A-Za-z0-9_]+)$TPOSTLBL[@]?$/o ) {
510             $chk[++$i]   = $_;
511             $chkcat[$i]  = 'vector';
512             $chksymb[$i] = $1;
513
514             $vectorchk{$1} = $i;
515
516         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)DirectReturn$TPOSTLBL[@]?$/o ) {
517             $chk[++$i]   = $_;
518             $chkcat[$i]  = 'direct';
519             $chksymb[$i] = $1;
520
521             $directchk{$1} = $i;
522
523         } elsif ( /^$TUS[@]?([A-Za-z0-9_]+)_upd$TPOSTLBL[@]?$/o ) {
524             $chk[++$i]   = $_;
525             $chkcat[$i]  = 'misc';
526             print STDERR "_upd!!!!! I guess this code is dead!!!!\n";
527             # I guess this is never entered, since all _upds are 
528             # either vtbl_'s or ret_'s, caught above. - andre
529             $chksymb[$i] = ''; 
530
531         # As a temporary solution for compiling "foreign export" declarations,
532         # we use global variables to pass arguments from C to STG land.
533         # These declarations live in the .hc file and not in the generated C
534         # stub file, so we let them pass through here.
535         } elsif ( /^[\t ]*\.comm[\t ]+${TUS}__fexp_.*$/ ) {
536             $chk[++$i]   = $_;
537             $chkcat[$i]  = 'data';
538             $chksymb[$i] = '';
539
540         } elsif ( $TargetPlatform =~ /^i386-.*-solaris2/
541              &&   /^(_uname|uname|stat|fstat):/ ) {
542             # for some utterly bizarre reason, this platform
543             # likes to drop little local C routines with these names
544             # into each and every .o file that #includes the
545             # relevant system .h file.  Yuck.  We just don't
546             # tolerate them in .hc files (which we are processing
547             # here).  If you need to call one of these things from
548             # Haskell, make a call to your own C wrapper, then
549             # put that C wrapper (which calls one of these) in a
550             # plain .c file.  WDP 95/12
551             $chk[++$i]   = $_;
552             $chkcat[$i]  = 'toss';
553             $chksymb[$i] = $1;
554
555         } elsif ( /^$TUS[@]?[A-Za-z0-9_]/o
556                 && ( $TargetPlatform !~ /^hppa/ # need to avoid local labels in this case
557                    || ! /^L\$\d+$/ )
558                 && ( $TargetPlatform !~ /^powerpc|^rs6000/ # ditto
559                    || ! /^(L\.\.\d+|LT\.\..*):$/ ) ) {
560             local($thing);
561             chop($thing = $_);
562             print STDERR "Funny global thing?: $_"
563                 unless $KNOWN_FUNNY_THING{$thing}
564                     || /^$TUS[@]?_(PRIn|PRStart).*$TPOSTLBL[@]?$/o # pointer reversal GC routines
565                     || /^$TUS[@]?CC_.*$TPOSTLBL$/o              # PROF: _CC_ccident  ([@]? is a silly hack (see above))
566                     || /^$TUS__fexp_.*$TPOSTLBL$/o              # foreign export droppings (temporary)
567                     || /^$TUS[@]?_reg.*$TPOSTLBL$/o;            # PROF: __reg<module>
568             $chk[++$i]   = $_;
569             $chkcat[$i]  = 'misc';
570             if ($TargetPlatform =~ /^powerpc-|^rs6000-/) 
571                { $chksymb[$i] = $thing; }
572             else { $chksymb[$i] = ''; };
573
574         } else { # simple line (duplicated at the top)
575
576             $chk[$i] .= $_;
577         }
578     }
579     $numchks = $#chk + 1;
580
581     # the division into chunks is imperfect;
582     # we throw some things over the fence into the next
583     # chunk.
584     #
585     # also, there are things we would like to know
586     # about the whole module before we start spitting
587     # output.
588
589     local($FIRST_MANGLABLE) = ($TargetPlatform =~ /^(alpha-|hppa|mips-)/) ? 1 : 0;
590
591 #   print STDERR "first chunk to mangle: $FIRST_MANGLABLE\n";
592
593     # Alphas: NB: we start meddling at chunk 1, not chunk 0
594     # The first ".rdata" is quite magical; as of GCC 2.7.x, it
595     # spits a ".quad 0" in after the v first ".rdata"; we
596     # detect this special case (tossing the ".quad 0")!
597     local($magic_rdata_seen) = 0;
598   
599     # HPPAs, MIPSen: also start medding at chunk 1
600
601     if ($TargetPlatform =~ /^powerpc|^rs6000/) {
602        print OUTASM $T_HDR_toc; # yes, we have to put a .toc 
603                                 # in the beginning of every file!
604     %tocequiv = ();          # maps toc symbol number to toc symbol
605     %revtocequiv = ();       # maps toc symbol to toc symbol number
606     for ($i = 1; $i < $numchks; $i++) {
607         $chk[$i] =~ s/\[RW\]//g;
608         $chk[$i] =~ s/\[DS\]//g;
609         $chk[$i] =~ s/^\.csect .*\[DS\]$//g;
610
611         if ( $chkcat[$i] eq 'toc' && $chk[$i] !~ /\.byte/ )
612 #ToDo: instead of all these changes, just fix mangle_powerpc_tailjump and delete/ignore these tocs?
613            { $chk[$i] =~ s/$T_MOVE_DIRVS//g;
614              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_fast\d+)/\t\.tc \1\[TC\],\.\2/; 
615              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(\S+_entry)\n/\t\.tc \1\[TC\],\.\2\n/;
616              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(ret_\S+)/\t\.tc \1\[TC\],\.\2/;
617              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(djn_\S+)/\t\.tc \1\[TC\],\.\2/;
618              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],(vtbl_\S+)/\t\.tc \1\[TC\],\.\2/;
619              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],ErrorIO_innards/\t\.tc \1\[TC\],\.ErrorIO_innards/;
620              $chk[$i] =~ s/\t\.tc (\S+)\[TC\],startStgWorld/\t\.tc \1\[TC\],\.startStgWorld/;
621              $chk[$i] =~ s/\.tc UpdatePAP\[TC\],UpdatePAP/\.tc UpdatePAP\[TC\],\.UpdatePAP/;
622              $chk[$i] =~ s/\.tc _regMain\[TC\],_regMain/\.tc _regMain\[TC\],\._regMain/; #PROF
623              $chk[$i] =~ s/\.tc resumeThread\[TC\],resumeThread/\.tc resumeThread\[TC\],\.resumeThread/; #CONC
624              $chk[$i] =~ s/\.tc EnterNodeCode\[TC\],EnterNodeCode/\.tc EnterNodeCode\[TC\],\.EnterNodeCode/; #CONC
625              $chk[$i] =~ s/\.tc StackUnderflowEnterNode\[TC\],StackUnderflowEnterNode/\.tc StackUnderflowEnterNode\[TC\],\.StackUnderflowEnterNode/; #CONC
626              $chk[$i] =~ s/\.tc stopThreadDirectReturn\[TC\],stopThreadDirectReturn/\.tc stopThreadDirectReturn\[TC\],\.stopThreadDirectReturn/; #CONC
627              $chk[$i] =~ s/\.tc CommonUnderflow\[TC\],CommonUnderflow/\.tc CommonUnderflow\[TC\],\.CommonUnderflow/; #PAR
628              $chk[$i] =~ s/\.tc IndUpdRetDir\[TC\],IndUpdRetDir/\.tc IndUpdRetDir\[TC\],\.IndUpdRetDir/;
629              $chk[$i] =~ s/\t\.tc (_PRStart_\S+)\[TC\],_PRStart_\S+/\t\.tc \1\[TC\],\.\1/;
630
631              $tocnumber = $chksymb[$i];
632              $tocsymb = $chk[$i];
633              $tocsymb =~ s/^LC\.\.\d+:\n//;
634              $tocsymb =~ s/^\t\.tc \S+,(\S+)\n/\1/;
635              $tocequiv{$tocnumber} = $tocsymb;
636
637            } elsif ( $chkcat[$i] eq 'toc' && $chk[$i] =~ /\.byte/ ) {
638              $chkcat[$i] = 'literal';
639            }
640     }
641     };
642
643     for ($i = $FIRST_MANGLABLE; $i < $numchks; $i++) {
644         $c = $chk[$i]; # convenience copy
645
646 #       print STDERR "\nCHK $i (BEFORE) (",$chkcat[$i],"):\n", $c;
647
648         # toss all prologue stuff; HPPA is pretty weird
649         # (see elsewhere)
650         $c = &mash_hppa_prologue($c) if $TargetPlatform =~ /^hppa/;
651
652         # be slightly paranoid to make sure there's
653         # nothing surprising in there
654         if ( $c =~ /--- BEGIN ---/ ) {
655             if (($p, $r) = split(/--- BEGIN ---/, $c)) {
656
657                 if ($TargetPlatform =~ /^i386-/) {
658                     $p =~ s/^\tpushl \%edi\n//;
659                     $p =~ s/^\tpushl \%esi\n//;
660                     $p =~ s/^\tsubl \$\d+,\%esp\n//;
661                     $p =~ s/^\tmovl \$\d+,\%eax\n\tcall __alloca\n// if ($TargetPlatform =~ /^.*-cygwin32/);
662                 } elsif ($TargetPlatform =~ /^m68k-/) {
663                     $p =~ s/^\tlink a6,#-?\d.*\n//;
664                     $p =~ s/^\tpea a6@\n\tmovel sp,a6\n//;    
665                                 # The above showed up in the asm code,
666                                 # so I added it here.
667                                 # I hope it's correct.
668                                 # CaS
669                     $p =~ s/^\tmovel d2,sp\@-\n//;
670                     $p =~ s/^\tmovel d5,sp\@-\n//; # SMmark.* only?
671                     $p =~ s/^\tmoveml \#0x[0-9a-f]+,sp\@-\n//; # SMmark.* only?
672                 } elsif ($TargetPlatform =~ /^mips-/) {
673                     # the .frame/.mask/.fmask that we use is the same
674                     # as that produced by GCC for miniInterpret; this
675                     # gives GDB some chance of figuring out what happened
676                     $FRAME = "\t.frame\t\$sp,2168,\$31\n\t.mask\t0x90000000,-4\n\t.fmask\t0x00000000,0\n";
677                     $p =~ s/^\t\.(frame).*\n/__FRAME__/g;
678                     $p =~ s/^\t\.(mask|fmask).*\n//g;
679                     $p =~ s/^\t\.cprestore.*\n/\t\.cprestore 416\n/; # 16 + 100 4-byte args
680                     $p =~ s/^\tsubu\t\$sp,\$sp,\d+\n//;
681                     $p =~ s/^\tsw\t\$31,\d+\(\$sp\)\n//;
682                     $p =~ s/^\tsw\t\$fp,\d+\(\$sp\)\n//;
683                     $p =~ s/^\tsw\t\$28,\d+\(\$sp\)\n//;
684                     $p =~ s/__FRAME__/$FRAME/;
685                 } elsif ($TargetPlatform =~ /^powerpc-|^rs6000/) {
686                     $p =~ s/^\tmflr 0\n//;
687                     $p =~ s/^\tstm \d+,-\d+\(1\)\n//;
688                     $p =~ s/^\tstw? 0,\d+\(1\)\n//g;
689                     $p =~ s/^\tstw? 1,\d+\(1\)\n//g; #mc
690                     $p =~ s/^\tlw?z 0,0\(1\)\n//g;   #mc
691                     $p =~ s/^\tstw?u 1,-\d+\(1\)\n//; 
692                     $p =~ s/^\tstw? \d+,-\d+\(1\)\n//g; 
693                     $p =~ s/^\tstfd \d+,-\d+\(1\)\n//g; 
694                 } else {
695                     print STDERR "$Pgm: unknown prologue mangling? $TargetPlatform\n";
696                 }
697
698                 die "Prologue junk?: $p\n" if $p =~ /^\t[^\.]/
699                     && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
700
701                 # glue together what's left
702                 $c = $p . $r;
703                 $c =~ s/\n\t\n/\n/; # junk blank line
704             }
705         }
706
707         if ( $TargetPlatform =~ /^mips-/ ) {
708             # MIPS: first, this basic sequence may occur "--- END ---" or not
709             $c =~ s/^\tlw\t\$31,\d+\(\$sp\)\n\taddu\t\$sp,\$sp,\d+\n\tj\t\$31\n\t\.end/\t\.end/;
710         }
711
712         # toss all epilogue stuff; again, paranoidly
713         if ( $c =~ /--- END ---/ ) {
714             if (($r, $e) = split(/--- END ---/, $c)) {
715                 if ($TargetPlatform =~ /^i386-/) {
716                     $e =~ s/^\tret\n//;
717                     $e =~ s/^\tpopl \%edi\n//;
718                     $e =~ s/^\tpopl \%esi\n//;
719                     $e =~ s/^\taddl \$\d+,\%esp\n//;
720                 } elsif ($TargetPlatform =~ /^m68k-/) {
721                     $e =~ s/^\tunlk a6\n//;
722                     $e =~ s/^\trts\n//;
723                 } elsif ($TargetPlatform =~ /^mips-/) {
724                     $e =~ s/^\tlw\t\$31,\d+\(\$sp\)\n//;
725                     $e =~ s/^\tlw\t\$fp,\d+\(\$sp\)\n//;
726                     $e =~ s/^\taddu\t\$sp,\$sp,\d+\n//;
727                     $e =~ s/^\tj\t\$31\n//;
728                 } elsif ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
729                     $e =~ s/^\taddi 1,1,\d+\n//;
730                     $e =~ s/^\tcal 1,\d+\(1\)\n//;
731                     $e =~ s/^\tlw?z? \d+,\d+\(1\)\n//; 
732                     $e =~ s/^\tmtlr 0\n//;
733                     $e =~ s/^\tbl?r\n//;
734                 } else {
735                     print STDERR "$Pgm: unknown epilogue mangling? $TargetPlatform\n";
736                 }
737                 die "Epilogue junk?: $e\n" if $e =~ /^\t[^\.]/
738                     && $TargetPlatform !~ /^powerpc-/; #ToDo: remove test
739
740                 # glue together what's left
741                 $c = $r . $e;
742                 $c =~ s/\n\t\n/\n/; # junk blank line
743             }
744         }
745
746         # On SPARCs, we don't do --- BEGIN/END ---, we just
747         # toss the register-windowing save/restore/ret* instructions
748         # directly:
749         if ( $TargetPlatform =~ /^sparc-/ ) {
750             $c =~ s/^\t(save .*|restore|ret|retl)\n//g;
751             # throw away PROLOGUE comments
752             $c =~ s/^\t!#PROLOGUE# 0\n\t!#PROLOGUE# 1\n//;
753         }
754
755         # On Alphas, the prologue mangling is done a little later (below)
756
757         # toss all calls to __DISCARD__
758         $c =~ s/^\t(call|jbsr|jal)\s+$TUS[@]?__DISCARD__\n//go;
759
760         # MIPS: that may leave some gratuitous asm macros around
761         # (no harm done; but we get rid of them to be tidier)
762         $c =~ s/^\t\.set\tnoreorder\n\t\.set\tnomacro\n\taddu\t(\S+)\n\t\.set\tmacro\n\t\.set\treorder\n/\taddu\t$1\n/
763             if $TargetPlatform =~ /^mips-/;
764
765         # toss stack adjustment after DoSparks
766         $c =~ s/^(\tjbsr _DoSparks\n)\taddqw #8,sp/$1/g
767                 if $TargetPlatform =~ /^m68k-/; # this looks old...
768
769         if ( $TargetPlatform =~ /^alpha-/ &&
770            ! $magic_rdata_seen &&
771            $c =~ /^\s*\.rdata\n\t\.quad 0\n\t\.align \d\n/ ) {
772             $c =~ s/^\s*\.rdata\n\t\.quad 0\n\t\.align (\d)\n/\.rdata\n\t\.align $1\n/;
773             $magic_rdata_seen = 1;
774         }
775
776         # pick some end-things and move them to the next chunk
777
778         # pin a funny end-thing on (for easier matching):
779         $c .= 'FUNNY#END#THING';
780
781         while ( $c =~ /$TMOVEDIRVS[@]?FUNNY#END#THING/o ) {  # [@]? is a silly hack to avoid having to use curlies for T_PRE_APP
782                                                            # (this SEGVs perl4 on alphas, you see)
783
784             $to_move = $1;
785             if ( $i < ($numchks - 1)
786               && ( $to_move =~ /$TCOPYDIRVS/
787                 || ($TargetPlatform =~ /^hppa/ && $to_move =~ /align/ && $chkcat[$i+1] eq 'literal') )) {
788                 $chk[$i + 1] = $to_move . $chk[$i + 1];
789                 # otherwise they're tossed
790             }
791
792             $c =~ s/$TMOVEDIRVS[@]?FUNNY#END#THING/FUNNY#END#THING/o; # [@]? is a hack (see above)
793         }
794
795         if ( $TargetPlatform =~ /^alpha-/ && $c =~ /^\t\.ent\s+(\S+)/ ) {
796             $ent = $1;
797             # toss all prologue stuff, except for loading gp, and the ..ng address
798             if (($p, $r) = split(/^\t\.prologue/, $c)) {
799                 if (($keep, $junk) = split(/\.\.ng:/, $p)) {
800                     $c = $keep . "..ng:\n";
801                 } else {
802                     print STDERR "malformed code block ($ent)?\n"
803                 }
804             }
805             $c .= "\t.frame \$30,0,\$26,0\n\t.prologue" . $r;
806         }
807   
808         $c =~ s/FUNNY#END#THING//;
809
810 #       print STDERR "\nCHK $i (AFTER) (",$chkcat[$i],"):\n", $c;
811
812         $chk[$i] = $c; # update w/ convenience copy
813     }
814
815     if ( $TargetPlatform =~ /^alpha-/ ) {
816         # print out the header stuff first
817         $chk[0] =~ s/^(\t\.file.*)"(ghc\d+\.c)"/$1"$ifile_root.hc"/;
818         print OUTASM $chk[0];
819
820     } elsif ( $TargetPlatform =~ /^hppa/ ) {
821         print OUTASM $chk[0];
822
823     } elsif ( $TargetPlatform =~ /^mips-/ ) {
824         $chk[0] = "\t\.file\t1 \"$ifile_root.hc\"\n" . $chk[0];
825
826         # get rid of horrible "<dollar>Revision: .*$" strings
827         local(@lines0) = split(/\n/, $chk[0]);
828         local($z) = 0;
829         while ( $z <= $#lines0 ) {
830             if ( $lines0[$z] =~ /^\t\.byte\t0x24,0x52,0x65,0x76,0x69,0x73,0x69,0x6f$/ ) {
831                 undef($lines0[$z]);
832                 $z++;
833                 while ( $z <= $#lines0 ) {
834                     undef($lines0[$z]);
835                     last if $lines0[$z] =~ /[,\t]0x0$/;
836                     $z++;
837                 }
838             }
839             $z++;
840         }
841         $chk[0] = join("\n", @lines0);
842         $chk[0] =~ s/\n\n+/\n/;
843         print OUTASM $chk[0];
844     }
845
846     # print out all the literal strings next
847     for ($i = 0; $i < $numchks; $i++) {
848         if ( $chkcat[$i] eq 'literal' ) {
849             print OUTASM $T_HDR_literal, $chk[$i];
850             print OUTASM "; end literal\n" if $TargetPlatform =~ /^hppa/; # for the splitter
851
852             $chkcat[$i] = 'DONE ALREADY';
853         }
854     }
855
856     # on the HPPA, print out all the bss next
857     if ( $TargetPlatform =~ /^hppa/ ) {
858         for ($i = 1; $i < $numchks; $i++) {
859             if ( $chkcat[$i] eq 'bss' ) {
860                 print OUTASM "\t.SPACE \$PRIVATE\$\n\t.SUBSPA \$BSS\$\n\t.align 4\n";
861                 print OUTASM $chk[$i];
862
863                 $chkcat[$i] = 'DONE ALREADY';
864             }
865         }
866     }
867
868     for ($i = $FIRST_MANGLABLE; $i < $numchks; $i++) {
869 #       print STDERR "$i: cat $chkcat[$i], symb $chksymb[$i]\n";
870
871         next if $chkcat[$i] eq 'DONE ALREADY';
872
873         if ( $chkcat[$i] eq 'misc' ) {
874             if ($chk[$i] ne '') {
875                 print OUTASM $T_HDR_misc;
876                 if ($TargetPlatform =~ /^powerpc-|^rs6000/) { 
877                    $chksymb[$i] =~ s/://;
878 #new                   if ($chksymb[$i] =~ /ret.*upd/ || $KNOWN_FUNNY_THING{$chksymb[$i]}
879 #new                    || $chksymb[$i] =~ /^$.{T_US}_(PRIn|PRStart).*${T_POST_LBL}$/o )
880 #new                      { print OUTASM "\t\.globl $chksymb[$i]\n"; }
881 #                   if ($chksymb[$i] ne '' && $chksymb[$i] !~ /ret_[a-z]/ && $chksymb[$i] !~ /djn_[a-z]/) 
882                    if ($chksymb[$i] ne '')
883                        { print OUTASM "\t\.globl \.$chksymb[$i]\n"; };
884                    if ($chk[$i] =~ /TOC\[tc0\], 0\n/)
885                      { ($p, $r) = split(/TOC\[tc0\], 0\n/, $chk[$i]); $printDS = 1;}
886                    else { $r = $chk[$i]; $printDS = 0; };
887                    $chk[$i] = &mangle_powerpc_tailjump($r);
888                 };
889                 &print_doctored($chk[$i], 0);
890                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/ && $printDS) { 
891 #ok                   if ($chksymb[$i] !~ /\_regMain/) {
892                      print OUTASM "\.csect ${chksymb[$i]}[DS]\n";       
893                      print OUTASM "${p}TOC[tc0], 0\n";
894 #ok                   }
895                 }
896             }
897
898         } elsif ( $chkcat[$i] eq 'toss' ) {
899             print STDERR "*** NB: TOSSING code for $chksymb[$i] !!! ***\n";
900
901         } elsif ( $chkcat[$i] eq 'data' ) {
902             if ($chk[$i] ne '') {
903                 print OUTASM $T_HDR_data;
904                 print OUTASM $chk[$i];
905             }
906
907         } elsif ( $chkcat[$i] eq 'consist' ) {
908             if ( $chk[$i] =~ /$T_hsc_cc_PAT/o ) {
909                 local($consist) = "$1.$2.$3";
910                 $consist =~ s/,/./g;
911                 $consist =~ s/\//./g;
912                 $consist =~ s/-/_/g;
913                 $consist =~ s/[^A-Za-z0-9_.]/ZZ/g; # ToDo: properly?
914                 #
915                 # Using a cygnus-2.7-96q4 gcc build on hppas, the 
916                 # consistency chunk for ghc_cc_ID often (but not always!)
917                 # gets lumped with a bunch of .IMPORT directives containing info on
918                 # the code or data space nature of external symbols. We can't
919                 # toss these, so once the consistency ID has been turned into
920                 # a representable symbol, we substitute it for the symbol
921                 # that the string was attached to in the first place (ghc_cc_ID.)
922                 # (The original string is also substituted away.)
923                 #
924                 # This change may affect the code output on other platforms in
925                 # adverse ways, hence we restrict this hack hppa targets only.
926                 #
927                 #    -- 2/98 SOF
928                 if ( $TargetPlatform =~ /^hppa/ )  {
929                         $chk[$i] =~ s/^$TUS[@]?ghc.*c_ID$TPOSTLBL/$consist/o;
930                         $chk[$i] =~ s/\t$T_hsc_cc_PAT/$T_HDR_misc/o;
931                         $consist = $chk[$i]; #clumsily
932                 }
933                 print OUTASM $T_HDR_consist, "${consist}${T_POST_LBL}\n";
934
935             } elsif ( $TargetPlatform !~ /^(mips)-/ ) { # we just don't try in those case (ToDo)
936                 # on mips: consistency string is just a v
937                 # horrible bunch of .bytes,
938                 # which I am too lazy to sort out (WDP 95/05)
939
940                 print STDERR "Couldn't grok consistency: ", $chk[$i];
941             }
942
943         } elsif ( $chkcat[$i] eq 'splitmarker' ) {
944             # we can just re-constitute this one...
945             # NB: we emit _three_ underscores no matter what,
946             # so ghc-split doesn't have to care.
947             print OUTASM "___stg_split_marker",$chksymb[$i],"${T_POST_LBL}\n";
948
949         } elsif ( $chkcat[$i] eq 'closure'
950                || $chkcat[$i] eq 'infotbl'
951                || $chkcat[$i] eq 'slow'
952                || $chkcat[$i] eq 'fast' ) { # do them in that order
953             $symb = $chksymb[$i];
954
955             # CLOSURE
956             if ( defined($closurechk{$symb}) ) {
957                 print OUTASM $T_HDR_closure;
958                 print OUTASM $chk[$closurechk{$symb}];
959                 $chkcat[$closurechk{$symb}] = 'DONE ALREADY';
960             }
961
962             # INFO TABLE
963             if ( defined($infochk{$symb}) ) {
964
965                 print OUTASM $T_HDR_info;
966                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
967                   if ( !defined($slowchk{$symb}) && defined($fastchk{$symb}) ) {
968                      $fastname = $chk[$fastchk{$symb}];
969                      $fastname =~ s/([_A-Za-z]*_fast\d+):.*(.*\n)*/\1/;
970                      $chk[$infochk{$symb}] =~ s/\.long StdErrorCode/\.long $fastname/;
971                   }
972                   $chk[$infochk{$symb}] =~ s/\.long ([_A-Za-z]\S+_entry)/\.long \.\1/;
973                   $chk[$infochk{$symb}] =~ s/\.long ([A-Za-z]\S+_upd)/\.long \.\1/;
974                   $chk[$infochk{$symb}] =~ s/\.long (IndUpdRet\S+)/\.long \.\1/;
975                   $chk[$infochk{$symb}] =~ s/\.long StdErrorCode/\.long \.StdErrorCode/;
976                   $chk[$infochk{$symb}] =~ s/\.long UpdErr/\.long \.UpdErr/;
977                   print OUTASM $chk[$infochk{$symb}];
978                 } else {
979                 print OUTASM &rev_tbl($symb, $chk[$infochk{$symb}], 1);
980                 }
981                 # entry code will be put here!
982
983                 # paranoia
984                 if ( $chk[$infochk{$symb}] =~ /$TDOTWORD[@]?\s+([A-Za-z0-9_]+_entry)$/o
985                   && $1 ne "${T_US}${symb}_entry" ) {
986                     print STDERR "!!! entry point???\n",$chk[$infochk{$symb}];
987                 }
988
989                 $chkcat[$infochk{$symb}] = 'DONE ALREADY';
990             }
991
992             # STD ENTRY POINT
993             if ( defined($slowchk{$symb}) ) {
994
995                 # teach it to drop through to the fast entry point:
996                 $c = $chk[$slowchk{$symb}];
997
998                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
999                 ($p, $r) = split(/TOC\[tc0\], 0\n/, $c); 
1000                 if ($symb =~ /^[_A-Z]/)
1001                 { 
1002                   print OUTASM "\t\.globl \.${chksymb[$i]}_entry\n"; 
1003                   print OUTASM "\.csect ${symb}_entry[DS]\n";   
1004                   print OUTASM "${p}TOC[tc0], 0\n";
1005                   }; 
1006                   $r =~ s/\.csect \.text\[PR\]\n//; # todo: properly - andre
1007                   $c = &mangle_powerpc_tailjump($r);
1008                 };
1009
1010                 if ( defined($fastchk{$symb}) ) {
1011                     if ( $TargetPlatform =~ /^alpha-/ ) {
1012                         $c =~ s/^\tjmp \$31,\(\$27\),0\n\t\.align 4\n\t\.end/\t.align 4\n\t.end/;
1013                     } elsif ( $TargetPlatform =~ /^hppa/ ) {
1014                         $c =~ s/^\s+ldil.*\n\s+ldo.*\n\s+bv.*\n(.*\n)?\s+\.EXIT/$1\t.EXIT/;
1015                     } elsif ( $TargetPlatform =~ /^i386-/ ) {
1016                         # Reg alloc depending, gcc generated code may jump to the fast entry point via
1017                         # a number of registers.
1018                         $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%edx\n\tjmp \*\%edx\n//;
1019                         $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%ecx\n\tjmp \*\%ecx\n//;
1020                         $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%eax\n\tjmp \*\%eax\n//;
1021                         # The next two only apply if we're not stealing %esi or %edi.
1022                         $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%esi\n\tjmp \*\%esi\n// if ($StolenX86Regs < 3);
1023                         $c =~ s/^\tmovl \$${T_US}${symb}_fast\d+,\%edi\n\tjmp \*\%edi\n// if ($StolenX86Regs < 4);
1024                     } elsif ( $TargetPlatform =~ /^mips-/ ) {
1025                         $c =~ s/^\tjmp \$31,\(\$27\),0\n\t\.align 4\n\t\.end/\t.align 4\n\t.end/;
1026                     } elsif ( $TargetPlatform =~ /^m68k-/ ) {
1027                         $c =~ s/^\tjmp ${T_US}${symb}_fast\d+.*\n\tnop\n//;
1028                         $c =~ s/^\tjmp ${T_US}${symb}_fast\d+.*\n//;
1029                     } elsif ( $TargetPlatform =~ /^powerpc-|^rs6000-/ ) {
1030                         $c =~ s/^\tb \.${T_US}${symb}_fast\d+\n//;
1031                     } elsif ( $TargetPlatform =~ /^sparc-/ ) {
1032                         $c =~ s/^\tcall ${T_US}${symb}_fast\d+,.*\n\tnop\n//;
1033                         $c =~ s/^\tcall ${T_US}${symb}_fast\d+,.*\n(\t[a-z].*\n)/$1/;
1034                     } else {
1035                         print STDERR "$Pgm: mystery slow-fast dropthrough: $TargetPlatform\n";
1036                     }
1037                 }
1038
1039                 if ( $TargetPlatform !~ /^(alpha-|hppa|mips-)/ ) {
1040                     # On alphas, hppa: no very good way to look for "dangling"
1041                     # references to fast-entry point.
1042                     # (questionable re hppa and mips...)
1043                     print STDERR "still has jump to fast entry point:\n$c"
1044                         if $c =~ /$TUS[@]?$symb[@]?_fast/; # NB: paranoia
1045                 }
1046
1047                 print OUTASM $T_HDR_entry;
1048
1049                 &print_doctored($c, 1); # NB: the 1!!!
1050
1051                 $chkcat[$slowchk{$symb}] = 'DONE ALREADY';
1052             }
1053             
1054             # FAST ENTRY POINT
1055             if ( defined($fastchk{$symb}) ) {
1056                 $c = $chk[$fastchk{$symb}];
1057                 if ( ! defined($slowchk{$symb})
1058                    # ToDo: the || clause can go once we're no longer
1059                    # concerned about producing exactly the same output as before
1060 #OLD:              || $TargetPlatform =~ /^(m68k|sparc|i386)-/
1061                    ) {
1062                     print OUTASM $T_HDR_fast;
1063                 }
1064                   if ($TargetPlatform =~ /^powerpc-|^rs6000-/) {
1065                     local(@lbls) = split(/:/, $c);
1066                     $fullname = $lbls[0];
1067                     $fullname =~ s/$T_MOVE_DIRVS//g;
1068                     if ( $fullname =~ /^[A-Z]/)
1069                        { print OUTASM "\t\.globl \.${fullname}\n";
1070                     } else {
1071 #                       print OUTASM "\t\.lglobl \.${fullname}\n"; #todo: rm - andre
1072                     };
1073                     $c =~ s/((.*\n)*)\t.long \S+, TOC\[tc0\], 0\n\.csect \.text\[PR\]\n((.*\n)*)/\1\3/;
1074                     $c = &mangle_powerpc_tailjump($c);
1075                   };
1076                 &print_doctored($c, 0);
1077                 $chkcat[$fastchk{$symb}] = 'DONE ALREADY';
1078             }
1079
1080         } elsif ( $chkcat[$i] eq 'vector'
1081                || $chkcat[$i] eq 'direct' ) { # do them in that order
1082             $symb = $chksymb[$i];
1083
1084             # VECTOR TABLE
1085             if ( defined($vectorchk{$symb}) ) {
1086                 print OUTASM $T_HDR_vector;
1087                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
1088                   if ( $symb =~ /^[A-Z]/) {
1089                      print OUTASM "\t\.globl \.vtbl_${symb}\n";
1090                      print OUTASM "\t\.globl vtbl_${symb}\n";
1091                   };
1092                   $chk[$vectorchk{$symb}] =~ s/\.long (\S+)/\.long \.\1/g;
1093                   print OUTASM ".vtbl_${symb}:\n";
1094                   print OUTASM $chk[$vectorchk{$symb}];
1095                 } else {
1096                   print OUTASM &rev_tbl($symb, $chk[$vectorchk{$symb}], 0);
1097                 }
1098                 # direct return code will be put here!
1099                 $chkcat[$vectorchk{$symb}] = 'DONE ALREADY';
1100             }
1101
1102             # DIRECT RETURN
1103             if ( defined($directchk{$symb}) ) {
1104                 print OUTASM $T_HDR_direct;
1105                 if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
1106                   ($p, $r) = split(/TOC\[tc0\], 0\n/, $chk[$directchk{$symb}]); 
1107                   &print_doctored($r, 0);
1108                   print OUTASM "\.csect ${symb}DirectReturn[DS]\n";     
1109                   print OUTASM "${p}TOC[tc0], 0\n";
1110                 } else {
1111                   &print_doctored($chk[$directchk{$symb}], 0);
1112                 }
1113                 $chkcat[$directchk{$symb}] = 'DONE ALREADY';
1114
1115             } elsif ( $TargetPlatform =~ /^alpha-/ ) {
1116                 # Alphas: the commented nop is for the splitter, to ensure
1117                 # that no module ends with a label as the very last
1118                 # thing.  (The linker will adjust the label to point
1119                 # to the first code word of the next module linked in,
1120                 # even if alignment constraints cause the label to move!)
1121
1122                 print OUTASM "\t# nop\n";
1123             }
1124             
1125         } elsif ( $chkcat[$i] eq 'toc' ) {
1126             # silly optimisation to print tocs, since they come in groups...
1127             print OUTASM $T_HDR_toc;
1128             local($j)   = $i;
1129             while ($chkcat[$j] eq 'toc')
1130               { if (   $chk[$j] !~ /\.tc UpdatePAP\[TC\]/ # not needed: always turned into a jump.
1131                    ) 
1132                 {
1133                   print OUTASM $chk[$j];
1134                 }
1135                 $chkcat[$j] = 'DONE ALREADY';
1136                 $j++;
1137             }
1138             
1139         } else {
1140             &tidy_up_and_die(1,"$Pgm: unknown chkcat (ghc-asm: $TargetPlatform)\n$chkcat[$i]\n$chk[$i]\n");
1141         }
1142     }
1143
1144     print OUTASM $EXTERN_DECLS if $TargetPlatform =~ /^mips-/;
1145
1146     if ($TargetPlatform =~ /^powerpc-|^rs6000-/) { 
1147          print OUTASM ".csect .text[PR]\n_section_.text:\n.csect .data[RW]\n\t.long _section_.text\n"
1148     };
1149
1150     # finished
1151     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
1152     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
1153 }
1154 \end{code}
1155
1156 \begin{code}
1157 sub mash_hppa_prologue { # OK, epilogue, too
1158     local($_) = @_;
1159
1160     # toss all prologue stuff
1161     s/^\s+\.ENTRY[^\0]*--- BEGIN ---/\t.ENTRY/;
1162
1163     # Lie about our .CALLINFO
1164     s/^\s+\.CALLINFO.*$/\t.CALLINFO NO_CALLS,NO_UNWIND/;
1165
1166     # Get rid of P'
1167
1168     s/LP'/L'/g;
1169     s/RP'/R'/g;
1170
1171     # toss all epilogue stuff
1172     s/^\s+--- END ---[^\0]*\.EXIT/\t.EXIT/;
1173
1174     # Sorry; we moved the _info stuff to the code segment.
1175     s/_info,DATA/_info,CODE/g;
1176
1177     return($_);
1178 }
1179 \end{code}
1180
1181 \begin{code}
1182 sub print_doctored {
1183     local($_, $need_fallthru_patch) = @_;
1184
1185     if ( $TargetPlatform !~ /^i386-/ 
1186       || ! /^\t[a-z]/ ) { # no instructions in here, apparently
1187         print OUTASM $_;
1188         return;
1189     }
1190     # OK, must do some x86 **HACKING**
1191
1192     local($entry_patch) = '';
1193     local($exit_patch)  = '';
1194     local($call_entry_patch)= '';
1195     local($call_exit_patch)     = '';
1196     local($gc_call_entry_patch)= '';    # Patches before and after calls to Perform_GC_wrapper
1197     local($gc_call_exit_patch)  = '';
1198
1199 #OLD:   # first, convert calls to *very magic form*: (ToDo: document
1200     # for real!)  from
1201     #
1202     #   pushl $768
1203     #   call _?PerformGC_wrapper
1204     #   addl $4,%esp
1205     # to
1206     #   movl $768, %eax
1207     #   call _?PerformGC_wrapper
1208     #
1209     # The reason we do this now is to remove the apparent use of
1210     # %esp, which would throw off the "what patch code do we need"
1211     # decision.
1212     #
1213     # Special macros in ghc/includes/COptWraps.lh, used in
1214     # ghc/runtime/CallWrap_C.lc, are required for this to work!
1215     #
1216
1217     s/^\tpushl \$(\d+)\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \$$1,\%eax\n\tcall ${T_DO_GC}\n/go;
1218     s/^\tpushl \%eax\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tcall ${T_DO_GC}\n/go;
1219     s/^\tpushl \%edx\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \%edx,\%eax\n\tcall ${T_DO_GC}\n/go;
1220
1221 #=  if ( $StolenX86Regs <= 4 ) { # %ecx is ordinary reg
1222 #=      s/^\tpushl \%ecx\n\tcall ${T_DO_GC}\n\taddl \$4,\%esp\n/\tmovl \%ecx,\%eax\n\tcall ${T_DO_GC}\n/go;
1223 #=  }
1224
1225     # gotta watch out for weird instructions that
1226     # invisibly smash various regs:
1227     #   rep*    %ecx used for counting
1228     #   scas*   %edi used for destination index
1229     #   cmps*   %e[sd]i used for indices
1230     #   loop*   %ecx used for counting
1231     #
1232     # SIGH.
1233
1234     # We cater for:
1235     #  * use of STG reg [ nn(%ebx) ] where no machine reg avail
1236     #
1237     #  * GCC used an "STG reg" for its own purposes
1238     #
1239     #  * some secret uses of machine reg, requiring STG reg
1240     #    to be saved/restored
1241
1242     # The most dangerous "GCC uses" of an "STG reg" are when
1243     # the reg holds the target of a jmp -- it's tricky to
1244     # insert the patch-up code before we get to the target!
1245     # So here we change the jmps:
1246
1247     # --------------------------------------------------------
1248     # it can happen that we have jumps of the form...
1249     #   jmp *<something involving %esp>
1250     # or
1251     #   jmp <something involving another naughty register...>
1252     #
1253     # a reasonably-common case is:
1254     #
1255     #   movl $_blah,<bad-reg>
1256     #   jmp  *<bad-reg>
1257     #
1258     # which is easily fixed as:
1259     #
1260     # sigh! try to hack around it...
1261     #
1262
1263     if ($StolenX86Regs <= 2 ) { # YURGH! spurious uses of esi?
1264         s/^\tmovl (.*),\%esi\n\tjmp \*%esi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
1265         s/^\tjmp \*(-?\d*)\((.*\%esi.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
1266         s/^\tjmp \*\%esi\n/\tmovl \%esi,\%eax\n\tjmp \*\%eax\n/g;
1267         die "$Pgm: (mangler) still have jump involving \%esi!\n$_"
1268             if /(jmp|call) .*\%esi/;
1269     }
1270     if ($StolenX86Regs <= 3 ) { # spurious uses of edi?
1271         s/^\tmovl (.*),\%edi\n\tjmp \*%edi\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
1272         s/^\tjmp \*(-?\d*)\((.*\%edi.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
1273         s/^\tjmp \*\%edi\n/\tmovl \%edi,\%eax\n\tjmp \*\%eax\n/g;
1274         die "$Pgm: (mangler) still have jump involving \%edi!\n$_"
1275             if /(jmp|call) .*\%edi/;
1276     }
1277 #=  if ($StolenX86Regs <= 4 ) { # spurious uses of ecx?
1278 #=      s/^\tmovl (.*),\%ecx\n\tjmp \*%ecx\n/\tmovl $1,\%eax\n\tjmp \*\%eax\n/g;
1279 #=      s/^\tjmp \*(-?\d*)\((.*\%ecx.*)\)\n/\tmovl $2,\%eax\n\tjmp \*$1\(\%eax\)\n/g;
1280 #=      s/^\tjmp \*\%ecx\n/\tmovl \%ecx,\%eax\n\tjmp \*\%eax\n/g;
1281 #=      die "$Pgm: (mangler) still have jump involving \%ecx!\n$_"
1282 #=          if /(jmp|call) .*\%ecx/;
1283 #=  }
1284
1285     # OK, now we can decide what our patch-up code is going to
1286     # be:
1287
1288     # Offsets into register table - you'd better update these magic
1289     # numbers should you change its contents!
1290     local($OFFSET_R1)=48;
1291     local($OFFSET_SpA)=80;
1292
1293         # Note funky ".=" stuff; we're *adding* to these _patch guys
1294     if ( $StolenX86Regs <= 2
1295          && ( /${OFFSET_R1}\(\%ebx\)/ || /\%esi/ || /^\tcmps/ ) ) { # R1 (esi)
1296         $entry_patch .= "\tmovl \%esi,${OFFSET_R1}(\%ebx)\n";
1297         $exit_patch  .= "\tmovl ${OFFSET_R1}(\%ebx),\%esi\n";
1298
1299         $gc_call_entry_patch  .= "\tmovl \%esi,${OFFSET_R1}(\%ebx)\n";
1300         $gc_call_exit_patch .= "\tmovl ${OFFSET_R1}(\%ebx),\%esi\n";
1301
1302         # nothing for call_{entry,exit} because %esi is callee-save
1303     }
1304     if ( $StolenX86Regs <= 3
1305          && ( /${OFFSET_SpA}\(\%ebx\)/ || /\%edi/ || /^\t(scas|cmps)/ ) ) { # SpA (edi)
1306         $entry_patch .= "\tmovl \%edi,${OFFSET_SpA}(\%ebx)\n";
1307         $exit_patch  .= "\tmovl ${OFFSET_SpA}(\%ebx),\%edi\n";
1308
1309         $gc_call_entry_patch  .= "\tmovl \%edi,${OFFSET_SpA}(\%ebx)\n";
1310         $gc_call_exit_patch .= "\tmovl ${OFFSET_SpA}(\%ebx),\%edi\n";
1311
1312         # nothing for call_{entry,exit} because %edi is callee-save
1313     }
1314     local ($OFFSET_Hp) = 96;
1315
1316 #=  local ($OFFSET_rSaveECX) = 124;
1317 #=  if ( $StolenX86Regs <= 4
1318 #=       && ( /${OFFSET_Hp}\(\%ebx\)/ || /\%ecx/ || /^\t(rep|loop)/ ) ) { # Hp (ecx)
1319 #=      $entry_patch .= "\tmovl \%ecx,${OFFSET_Hp}(\%ebx)\n";
1320 #=      $exit_patch  .= "\tmovl ${OFFSET_Hp}(\%ebx),\%ecx\n";
1321 #=
1322 #=      $call_exit_patch  .= "\tmovl \%ecx,${OFFSET_rSaveECX}(\%ebx)\n";
1323 #=      $call_entry_patch .= "\tmovl ${OFFSET_rSaveECX}(\%ebx),\%ecx\n";
1324 #=      # I have a really bad feeling about this if we ever
1325 #=      # have a nested call...
1326 #=      # NB: should just hide it somewhere in the C stack.
1327 #=  }
1328     # --------------------------------------------------------
1329     # next, here we go with non-%esp patching!
1330     #
1331     s/^(\t[a-z])/$entry_patch$1/; # before first instruction
1332
1333 # Actually, call_entry_patch and call_exit_patch never get set,
1334 # so let's nuke this one
1335 #    s/^(\tcall .*\n(\taddl \$\d+,\%esp\n)?)/$call_exit_patch$1$call_entry_patch/g; # _all_ calls
1336
1337 # Before calling GC we must set up the exit condition before the call
1338 # and entry condition when we come back
1339     s/^(\tcall ${T_DO_GC}\n(\taddl \$\d+,\%esp\n)?)/$gc_call_exit_patch$1$gc_call_entry_patch/g; # _all_ calls
1340
1341     # fix _all_ non-local jumps:
1342
1343     s/^\tjmp \*${T_X86_PRE_LLBL_PAT}/\tJMP___SL/go;
1344     s/^\tjmp ${T_X86_PRE_LLBL_PAT}/\tJMP___L/go;
1345
1346     s/^(\tjmp .*\n)/$exit_patch$1/g; # here's the fix...
1347
1348     s/^\tJMP___SL/\tjmp \*${T_X86_PRE_LLBL}/go;
1349     s/^\tJMP___L/\tjmp ${T_X86_PRE_LLBL}/go;
1350
1351     # fix post-PerformGC wrapper (re-)entries ???
1352
1353     if ($StolenX86Regs == 2 ) {
1354         die "ARGH! Jump uses \%esi or \%edi with -monly-2-regs:\n$_" 
1355             if /^\t(jmp|call) .*\%e(si|di)/;
1356 #=      die "ARGH! Jump uses \%esi, \%edi, or \%ecx with -monly-2-regs:\n$_" 
1357 #=          if /^\t(jmp|call) .*\%e(si|di|cx)/;
1358     } elsif ($StolenX86Regs == 3 ) {
1359         die "ARGH! Jump uses \%edi with -monly-3-regs:\n$_" 
1360             if /^\t(jmp|call) .*\%edi/;
1361 #=      die "ARGH! Jump uses \%edi or \%ecx with -monly-3-regs:\n$_" 
1362 #=          if /^\t(jmp|call) .*\%e(di|cx)/;
1363 #=  } elsif ($StolenX86Regs == 4 ) {
1364 #=      die "ARGH! Jump uses \%ecx with -monly-4-regs:\n$_" 
1365 #=          if /^\t(jmp|call) .*\%ecx/;
1366     }
1367
1368     # final peephole fixes
1369
1370     local($OFFSET_R2)=52;
1371     s/^\tmovl \%eax,${OFFSET_R2}\(\%ebx\)\n\tjmp \*${OFFSET_R2}\(\%ebx\)\n/\tmovl \%eax,${OFFSET_R2}\(\%ebx\)\n\tjmp \*\%eax\n/;
1372
1373 # the short form may tickle perl bug:
1374 #    s/^\tmovl \$${T_US}(.*),(\%e[abcd]x)\n\tjmp \*$2/\tjmp $T_US$1/g;
1375     s/^\tmovl \$${T_US}(.*),\%eax\n\tjmp \*\%eax/\tjmp $T_US$1/g;
1376     s/^\tmovl \$${T_US}(.*),\%ebx\n\tjmp \*\%ebx/\tjmp $T_US$1/g;
1377     s/^\tmovl \$${T_US}(.*),\%ecx\n\tjmp \*\%ecx/\tjmp $T_US$1/g;
1378     s/^\tmovl \$${T_US}(.*),\%edx\n\tjmp \*\%edx/\tjmp $T_US$1/g;
1379
1380     # Hacks to eliminate some reloads of Hp.  Worth about 5% code size.
1381     # We could do much better than this, but at least it catches about
1382     # half of the unnecessary reloads.
1383     # Note that these will stop working if either:
1384     #  (i) the offset of Hp from BaseReg changes from 80, or
1385     #  (ii) the register assignment of BaseReg changes from %ebx
1386
1387     s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%e.x\n\tmovl \$(.*),(-?[0-9]*)\(\%e.x\)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%e(.)x/\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$3x\n\tmovl \$$1,$2\(\%e$3x\)/g;
1388
1389     s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%e(.)x\n\tmovl (.*),\%e(.)x\n\tmovl \%e$3x,(-?[0-9]*\(\%e$1x\))\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$1x/\tmovl ${OFFSET_Hp}\(\%ebx\),\%e$1x\n\tmovl $2,\%e$3x\n\tmovl \%e$3x,$4/g;
1390
1391     s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx((\n\t(movl|addl) .*,((-?[0-9]*\(.*)|(\%e[abc]x)))+)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx/\tmovl ${OFFSET_Hp}\(\%ebx\),\%edx$1/g;
1392     s/^\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax((\n\t(movl|addl) .*,((-?[0-9]*\(.*)|(\%e[bcd]x)))+)\n\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax/\tmovl ${OFFSET_Hp}\(\%ebx\),\%eax$1/g;
1393
1394     # --------------------------------------------------------
1395     # that's it -- print it
1396     #
1397     #die "Funny jumps?\n$_" if /${T_X86_BADJMP}/o; # paranoia
1398
1399     print OUTASM $_;
1400
1401     if ( $need_fallthru_patch ) { # exit patch for end of slow entry code
1402         print OUTASM $exit_patch;
1403         # ToDo: make it not print if there is a "jmp" at the end
1404     }
1405 }
1406 \end{code}
1407
1408 \begin{code}
1409 sub init_FUNNY_THINGS {
1410     %KNOWN_FUNNY_THING = (
1411         "${T_US}CheckHeapCode${T_POST_LBL}", 1,
1412         "${T_US}CommonUnderflow${T_POST_LBL}", 1,
1413         "${T_US}Continue${T_POST_LBL}", 1,
1414         "${T_US}EnterNodeCode${T_POST_LBL}", 1,
1415         "${T_US}ErrorIO_call_count${T_POST_LBL}", 1,
1416         "${T_US}ErrorIO_innards${T_POST_LBL}", 1,
1417         "${T_US}IndUpdRetDir${T_POST_LBL}", 1,
1418         "${T_US}IndUpdRetV0${T_POST_LBL}", 1,
1419         "${T_US}IndUpdRetV1${T_POST_LBL}", 1,
1420         "${T_US}IndUpdRetV2${T_POST_LBL}", 1,
1421         "${T_US}IndUpdRetV3${T_POST_LBL}", 1,
1422         "${T_US}IndUpdRetV4${T_POST_LBL}", 1,
1423         "${T_US}IndUpdRetV5${T_POST_LBL}", 1,
1424         "${T_US}IndUpdRetV6${T_POST_LBL}", 1,
1425         "${T_US}IndUpdRetV7${T_POST_LBL}", 1,
1426         "${T_US}PrimUnderflow${T_POST_LBL}", 1,
1427         "${T_US}StackUnderflowEnterNode${T_POST_LBL}", 1,
1428         "${T_US}StdErrorCode${T_POST_LBL}", 1,
1429         "${T_US}UnderflowVect0${T_POST_LBL}", 1,
1430         "${T_US}UnderflowVect1${T_POST_LBL}", 1,
1431         "${T_US}UnderflowVect2${T_POST_LBL}", 1,
1432         "${T_US}UnderflowVect3${T_POST_LBL}", 1,
1433         "${T_US}UnderflowVect4${T_POST_LBL}", 1,
1434         "${T_US}UnderflowVect5${T_POST_LBL}", 1,
1435         "${T_US}UnderflowVect6${T_POST_LBL}", 1,
1436         "${T_US}UnderflowVect7${T_POST_LBL}", 1,
1437         "${T_US}UpdErr${T_POST_LBL}", 1,
1438         "${T_US}UpdatePAP${T_POST_LBL}", 1,
1439         "${T_US}_Enter_Internal${T_POST_LBL}", 1,
1440         "${T_US}_PRMarking_MarkNextAStack${T_POST_LBL}", 1,
1441         "${T_US}_PRMarking_MarkNextBStack${T_POST_LBL}", 1,
1442         "${T_US}_PRMarking_MarkNextCAF${T_POST_LBL}", 1,
1443         "${T_US}_PRMarking_MarkNextGA${T_POST_LBL}", 1,
1444         "${T_US}_PRMarking_MarkNextRoot${T_POST_LBL}", 1,
1445         "${T_US}_PRMarking_MarkNextSpark${T_POST_LBL}", 1,
1446         "${T_US}_PRMarking_MarkNextEvent${T_POST_LBL}", 1,
1447         "${T_US}_PRMarking_MarkNextClosureInFetchBuffer${T_POST_LBL}", 1,
1448         "${T_US}_Scavenge_Forward_Ref${T_POST_LBL}", 1,
1449         "${T_US}__std_entry_error__${T_POST_LBL}", 1,
1450         "${T_US}_startMarkWorld${T_POST_LBL}", 1,
1451         "${T_US}resumeThread${T_POST_LBL}", 1,
1452         "${T_US}startCcRegisteringWorld${T_POST_LBL}", 1,
1453         "${T_US}startEnterFloat${T_POST_LBL}", 1,
1454         "${T_US}startEnterInt${T_POST_LBL}", 1,
1455         "${T_US}startPerformIO${T_POST_LBL}", 1,
1456         "${T_US}startStgWorld${T_POST_LBL}", 1,
1457         "${T_US}stopPerformIO${T_POST_LBL}", 1,
1458         "${T_US}ShouldCompile_Z36d1z5${T_POST_LBL}", 1
1459     );
1460 }
1461 \end{code}
1462
1463 The following table reversal is used for both info tables and return
1464 vectors.  In both cases, we remove the first entry from the table,
1465 reverse the table, put the label at the end, and paste some code
1466 (that which is normally referred to by the first entry in the table)
1467 right after the table itself.  (The code pasting is done elsewhere.)
1468
1469 \begin{code}
1470 sub rev_tbl {
1471     local($symb, $tbl, $discard1) = @_;
1472
1473     local($before) = '';
1474     local($label) = '';
1475     local(@imports) = (); # hppa only
1476     local(@words) = ();
1477     local($after) = '';
1478     local(@lines) = split(/\n/, $tbl);
1479     local($i, $j); #local ($i, $extra, $words_to_pad, $j);
1480    
1481     # see comment in mangleAsm as to why this silliness is needed.
1482     local($TDOTWORD) = ${T_DOT_WORD};
1483     local($TDOTGLOBAL) = ${T_DOT_GLOBAL};
1484     local($TUS) = ${T_US};
1485     local($TPOSTLBL) = ${T_POST_LBL};
1486
1487     for ($i = 0; $i <= $#lines && $lines[$i] !~ /^\t$TDOTWORD\s+/o; $i++) {
1488         $label .= $lines[$i] . "\n",
1489             next if $lines[$i] =~ /^[A-Za-z0-9_]+_info$TPOSTLBL[@]?$/o
1490                  || $lines[$i] =~ /$TDOTGLOBAL/o
1491                  || $lines[$i] =~ /^$TUS[@]?vtbl_\S+$TPOSTLBL[@]?$/o;
1492
1493         $before .= $lines[$i] . "\n"; # otherwise...
1494     }
1495
1496     if ( $TargetPlatform !~ /^hppa/ ) {
1497         for ( ; $i <= $#lines && $lines[$i] =~ /^\t$TDOTWORD\s+/o; $i++) {
1498             push(@words, $lines[$i]);
1499         }
1500     } else { # hppa weirdness
1501         for ( ; $i <= $#lines && $lines[$i] =~ /^\s+\.(word|IMPORT)/; $i++) {
1502             if ($lines[$i] =~ /^\s+\.IMPORT/) {
1503                 push(@imports, $lines[$i]);
1504             } else {
1505                 # We don't use HP's ``function pointers''
1506                 # We just use labels in code space, like normal people
1507                 $lines[$i] =~ s/P%//;
1508                 push(@words, $lines[$i]);
1509             }
1510         }
1511     }
1512
1513     # now throw away the first word (entry code):
1514     shift(@words) if $discard1;
1515
1516 # Padding removed to reduce code size and improve performance on Pentiums.
1517 # Simon M. 13/4/96
1518     # for 486-cache-friendliness, we want our tables aligned
1519     # on 16-byte boundaries (.align 4).  Let's pad:
1520 #    $extra = ($#words + 1) % 4;
1521 #    $words_to_pad = ($extra == 0) ? 0 : 4 - $extra;
1522 #    for ($j = 0; $j < $words_to_pad; $j++) { push(@words, "\t${T_DOT_WORD} 0"); }
1523
1524     for (; $i <= $#lines; $i++) {
1525         $after .= $lines[$i] . "\n";
1526     }
1527
1528     # Alphas:If we have anonymous text (not part of a procedure), the
1529     # linker may complain about missing exception information.  Bleh.
1530     if ( $TargetPlatform =~ /^alpha-/ && $label =~ /^([A-Za-z0-9_]+):$/) {
1531         $before = "\t.ent $1\n" . $before;
1532         $after .= "\t.end $1\n";
1533     }
1534
1535     $tbl = $before
1536          . (($TargetPlatform !~ /^hppa/) ? '' : join("\n", @imports) . "\n")
1537          . join("\n", (reverse @words)) . "\n"
1538          . $label . $after;
1539
1540 #   print STDERR "before=$before\n";
1541 #   print STDERR "label=$label\n";
1542 #   print STDERR "words=",(reverse @words),"\n";
1543 #   print STDERR "after=$after\n";
1544
1545     $tbl;
1546 }
1547 \end{code}
1548
1549 \begin{code}
1550 sub mini_mangle_asm_i386 {
1551     local($in_asmf, $out_asmf) = @_;
1552
1553     &init_TARGET_STUFF();
1554
1555     # see mangleAsm comment
1556     local($TUS) = ${T_US};
1557     local($TPOSTLBL)=${T_POST_LBL};
1558
1559     open(INASM, "< $in_asmf")
1560         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
1561     open(OUTASM,"> $out_asmf")
1562         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
1563
1564     while (<INASM>) {
1565         print OUTASM;
1566
1567         next unless
1568             /^$TUS[@]?(PerformGC|StackOverflow|Yield|PerformReschedule)_wrapper$TPOSTLBL\n/o;
1569         print OUTASM "\tmovl \%esp, ${T_US}__temp_esp\n";
1570         print OUTASM "\tmovl \%eax, ${T_US}__temp_eax\n";
1571     }
1572
1573     # finished:
1574     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
1575     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
1576 }
1577 \end{code}
1578
1579 The HP is a major nuisance.  The threaded code mangler moved info
1580 tables from data space to code space, but unthreaded code in the RTS
1581 still has references to info tables in data space.  Since the HP
1582 linker is very precise about where symbols live, we need to patch the
1583 references in the unthreaded RTS as well.
1584
1585 \begin{code}
1586 sub mini_mangle_asm_hppa {
1587     local($in_asmf, $out_asmf) = @_;
1588
1589     open(INASM, "< $in_asmf")
1590         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
1591     open(OUTASM,"> $out_asmf")
1592         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
1593
1594     while (<INASM>) {
1595         s/_info,DATA/_info,CODE/;   # Move _info references to code space
1596         s/P%_PR/_PR/;
1597         print OUTASM;
1598     }
1599
1600     # finished:
1601     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
1602     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
1603 }
1604
1605 \end{code}
1606  
1607 \begin{code}
1608 sub mini_mangle_asm_powerpc {
1609     local($in_asmf, $out_asmf) = @_;
1610
1611     open(INASM, "< $in_asmf")
1612         || &tidy_up_and_die(1,"$Pgm: failed to open `$in_asmf' (to read)\n");
1613     open(OUTASM,"> $out_asmf")
1614         || &tidy_up_and_die(1,"$Pgm: failed to open `$out_asmf' (to write)\n");
1615
1616     while (<INASM>) {
1617         s/long _PRStart/long ._PRStart/;
1618         s/long _PRIn_/long ._PRIn_/;
1619         s/long _Dummy_(\S+)_entry/long ._Dummy_\1_entry/;
1620         s/long _PRMarking_MarkNextRoot\[DS\]/long ._PRMarking_MarkNextRoot/;
1621         s/long _PRMarking_MarkNextCAF\[DS\]/long ._PRMarking_MarkNextCAF/;
1622         s/long _PRMarking_MarkNextAStack\[DS\]/long ._PRMarking_MarkNextAStack/;
1623         s/long _PRMarking_MarkNextBStack\[DS\]/long ._PRMarking_MarkNextBStack/;
1624         s/\.tc EnterNodeCode\[TC]\,EnterNodeCode\[DS\]/\.tc EnterNodeCode\[TC]\,.EnterNodeCode/; # CONC
1625         s/\.tc CheckHeapCode\[TC]\,CheckHeapCode\[DS\]/\.tc CheckHeapCode\[TC]\,.CheckHeapCode/; # CONC
1626         print OUTASM;
1627     }
1628
1629     # finished:
1630     close(OUTASM) || &tidy_up_and_die(1,"Failed writing to $out_asmf\n");
1631     close(INASM)  || &tidy_up_and_die(1,"Failed reading from $in_asmf\n");
1632 }
1633
1634 sub mangle_powerpc_tailjump {
1635     local($c) = @_;
1636     local($maybe_more) = 1;
1637     while (($c =~ /\tlw?z? \d+,LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n/) && $maybe_more) 
1638       { $maybe_more = 0;
1639         $lcsymb = $c;
1640         $lcsymb =~ s/(.*\n)*\tlw?z? \d+,LC\.\.(\d+)\(2\)\n\tmtctr \d+\n\tbctr\n(.*\n)*/\2/;
1641 # the checks for r1 and r2 are mostly paranoia...
1642         $r1 = $c;
1643         $r1 =~ s/(.*\n)*\tlw?z? (\d+),LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n(.*\n)*/\2/;
1644         $r2 = $c;
1645         $r2 =~ s/(.*\n)*\tlw?z? \d+,LC\.\.(\d+)\(2\)\n\tmtctr (\d+)\n\tbctr\n(.*\n)*/\3/;
1646         if (r1 == r2)
1647           { $maybe_more = 1;
1648             $c =~ s/((.*\n)*)\tlw?z? \d+,LC\.\.\d+\(2\)\n\tmtctr \d+\n\tbctr\n((.*\n)*)/\1\tb $tocequiv{$lcsymb}\n\3/;
1649           }
1650       };
1651     $c;
1652 }
1653
1654 # make "require"r happy...
1655 1;
1656 \end{code}