Debian Codegraph @

lib/mlrisc-lib/MLRISC/x86/mltree/orig-x86-fp.sml

raw
1 (* x86-fp.sml
2 *
3 * COPYRIGHT (c) 2001 Bell Labs, Lucent Technologies
4 *
5 * This phase takes a cluster with pseudo x86 fp instructions, performs
6 * liveness analysis to determine their live ranges, and rewrite the
7 * program into the correct stack based code.
8 *
9 * The Basics
10 * ----------
11 * o We assume there are 7 pseudo fp registers, %fp(0), ..., %fp(6),
12 * which are mapped onto the %st stack. One stack location is reserved
13 * for holding temporaries.
14 * o Important: for floating point comparisons, we actually need
15 * two extra stack locations in the worst case. We handle this by
16 * specifying that the instruction define an extra temporary fp register
17 * when necessary.
18 * o The mapping between %fp <-> %st may change from program point to
19 * program point. We keep track of this lazy renaming and try to minimize
20 * the number of FXCH that we insert.
21 * o At split and merge points, we may get inconsistent %fp <-> %st mappings.
22 * We handle this by inserting the appropriate renaming code.
23 * o Parallel copies (renaming) are rewritten into a sequence of FXCHs!
24 *
25 * Pseudo fp instructions Semantics
26 * --------------------------------------
27 * FMOVE src, dst dst := src
28 * FILOAD ea, dst dst := cvti2f(mem[ea])
29 * FBINOP lsrc, rsrc, dst dst := lsrc * rsrc
30 * FIBINOP lsrc, rsrc, dst dst := lsrc * cvti2f(rsrc)
31 * FUNOP src, dst dst := unaryOp src
32 * FCMP lsrc, rsrc fp condition code := fcmp(lsrc, rsrc)
33 *
34 * An instruction may use its source operand(s) destructively.
35 * We find this info using a global liveness analysis.
36 *
37 * The Translation
38 * ---------------
39 * o We keep track of the bindings between %fp registers and the
40 * %st(..) staack locations.
41 * o FXCH and FLDL are inserted at the appropriate places to move operands
42 * to %st(0). FLDL is used if the operand is not dead. FXCH is used
43 * if the operand is the last use.
44 * o FCOPY's between pseudo %fp registers are done by software renaming
45 * and generate no code by itself!
46 * o FSTL %st(1) are also generated to pop the stack after the last use
47 * of an operand.
48 *
49 * Note
50 * ----
51 * 1. This module should be run after floating point register allocation.
52 *
53 * -- Allen Leung ([email protected])
54 *)
55
56 local
57 val debug = false (* set this to true to debug this module
58 * set this to false for production use.
59 *)
60 val debugLiveness = true (* debug liveness analysis *)
61 val debugDead = false (* debug dead code removal *)
62 val sanityCheck = true
63 in
64 functor X86FP
65 (structure X86Instr : X86INSTR
66 structure X86Props : INSN_PROPERTIES
67 where I = X86Instr
68 structure Flowgraph : CONTROL_FLOW_GRAPH
69 where I = X86Instr
70 structure Liveness : LIVENESS
71 where CFG = Flowgraph
72 structure Asm : INSTRUCTION_EMITTER
73 where I = X86Instr
74 and S.P = Flowgraph.P
75 ) : CFG_OPTIMIZATION =
76 struct
77 structure CFG = Flowgraph
78 structure G = Graph
79 structure I = X86Instr
80 structure T = I.T
81 structure P = X86Props
82 structure C = I.C
83 structure A = Array
84 structure L = Label
85 structure An = Annotations
86 structure CB = CellsBasis
87 structure SL = CB.SortedCells
88 structure HT = IntHashTable
89 structure IM = IntRedBlackMap
90
91 type flowgraph = CFG.cfg
92 type an = An.annotations
93
94 val name = "X86 floating point rewrite"
95
96 val debugOn = MLRiscControl.mkFlag ("x86-fp-debug", "x86 fp debug mode")
97 val traceOn = MLRiscControl.mkFlag ("x86-fp-trace", "x86 fp trace mode")
98
99 fun error msg = MLRiscErrorMsg.error("X86FP",msg)
100 fun pr msg = TextIO.output(!MLRiscControl.debug_stream,msg)
101
102 val i2s = Int.toString
103
104 (*
105 * No overflow checking is needed for integer arithmetic in this module
106 *)
107
108 fun celllistToCellset l = List.foldr CB.CellSet.add CB.CellSet.empty l
109 fun celllistToString l = CB.CellSet.toString(celllistToCellset l)
110
111 (* Annotation to mark split edges *)
112 exception TargetMovedTo of G.node_id
113
114 (*-----------------------------------------------------------------------
115 * Primitive instruction handling routines
116 *-----------------------------------------------------------------------*)
117
118 (* Annotation an instruction *)
119 fun mark(instr, []) = instr
120 | mark(instr, a::an) = mark(I.ANNOTATION{i=instr,a=a}, an)
121
122 (* Add pop suffix to a binary operator *)
123 fun pop I.FADDL = I.FADDP | pop I.FADDS = I.FADDP
124 | pop I.FSUBL = I.FSUBP | pop I.FSUBS = I.FSUBP
125 | pop I.FSUBRL = I.FSUBRP | pop I.FSUBRS = I.FSUBRP
126 | pop I.FMULL = I.FMULP | pop I.FMULS = I.FMULP
127 | pop I.FDIVL = I.FDIVP | pop I.FDIVS = I.FDIVP
128 | pop I.FDIVRL = I.FDIVRP | pop I.FDIVRS = I.FDIVRP
129 | pop _ = error "fbinop.pop"
130
131 (* Invert the operator *)
132 fun invert I.FADDL = I.FADDL | invert I.FADDS = I.FADDS
133 | invert I.FSUBL = I.FSUBRL | invert I.FSUBS = I.FSUBRS
134 | invert I.FSUBRL = I.FSUBL | invert I.FSUBRS = I.FSUBS
135 | invert I.FMULL = I.FMULL | invert I.FMULS = I.FMULS
136 | invert I.FDIVL = I.FDIVRL | invert I.FDIVS = I.FDIVRS
137 | invert I.FDIVRL = I.FDIVL | invert I.FDIVRS = I.FDIVS
138 | invert I.FADDP = I.FADDP | invert I.FMULP = I.FMULP
139 | invert I.FSUBP = I.FSUBRP | invert I.FSUBRP = I.FSUBP
140 | invert I.FDIVP = I.FDIVRP | invert I.FDIVRP = I.FDIVP
141 | invert _ = error "invert"
142
143 (* Pseudo instructions *)
144 fun FLD(I.FP32, ea) = I.flds ea
145 | FLD(I.FP64, ea) = I.fldl ea
146 | FLD(I.FP80, ea) = I.fldt ea
147
148 fun FILD(I.I8, ea) = error "FILD"
149 | FILD(I.I16, ea) = I.fild ea
150 | FILD(I.I32, ea) = I.fildl ea
151 | FILD(I.I64, ea) = I.fildll ea
152
153 fun FSTP(I.FP32, ea) = I.fstps ea
154 | FSTP(I.FP64, ea) = I.fstpl ea
155 | FSTP(I.FP80, ea) = I.fstpt ea
156
157 fun FST(I.FP32, ea) = I.fsts ea
158 | FST(I.FP64, ea) = I.fstl ea
159 | FST(I.FP80, ea) = error "FSTT"
160
161 (*-----------------------------------------------------------------------
162 * Pretty print routines
163 *-----------------------------------------------------------------------*)
164 fun fregToString f = "%f"^i2s(CB.registerNum f)
165 fun fregsToString s =
166 List.foldr (fn (r,"") => fregToString r |
167 (r,s) => fregToString r^" "^s) "" s
168
169 fun blknumOf(CFG.BLOCK{id, ...}) = id
170
171 (*-----------------------------------------------------------------------
172 * A stack datatype that mimics the x86 floating point stack
173 * and keeps track of bindings between %st(n) and %fp(n).
174 *-----------------------------------------------------------------------*)
175 structure ST :>
176 sig
177 type stack
178 type stnum = int (* 0 -- 7 *)
179 val create : unit -> stack
180 val stack0 : stack
181 val copy : stack -> stack
182 val clear : stack -> unit
183 val fp : stack * CB.register_id -> stnum
184 val st : stack * stnum -> CB.register_id
185 val set : stack * stnum * CB.register_id -> unit
186 val push : stack * CB.register_id -> unit
187 val xch : stack * stnum * stnum -> unit
188 val pop : stack -> unit
189 val depth : stack -> int
190 val nonFull : stack -> unit
191 val kill : stack * CellsBasis.cell -> unit
192 val stackToString : stack -> string
193 val equal : stack * stack -> bool
194 end =
195 struct
196 type stnum = int
197 datatype stack =
198 STACK of
199 { st : CB.register_id A.array, (* mapping %st -> %fp registers *)
200 fp : stnum A.array, (* mapping %fp -> %st registers *)
201 sp : int ref (* stack pointer *)
202 }
203
204 (* Create a new stack *)
205 fun create() = STACK{st=A.array(8,~1), fp=A.array(7,16), sp=ref ~1}
206
207 val stack0 = create()
208
209 (* Copy a stack *)
210 fun copy(STACK{st, fp, sp}) =
211 let val st' = A.array(8, ~1)
212 val fp' = A.array(7, 16)
213 in A.copy{src=st,dst=st',si=0,di=0,len=NONE};
214 A.copy{src=fp,dst=fp',si=0,di=0,len=NONE};
215 STACK{st=st', fp=fp', sp=ref(!sp)}
216 end
217
218 (* Depth of stack *)
219 fun depth(STACK{sp, ...}) = !sp + 1
220
221 fun nonFull(STACK{sp, ...}) =
222 if !sp >= 7 then error "stack overflow" else ()
223
224 (* Given %st(n), lookup the corresponding %fp(n) *)
225 fun st(STACK{st, sp, ...}, n) = A.sub(st, !sp - n)
226
227 (* Given %fp(n), lookup the corresponding %st(n) *)
228 fun fp(STACK{fp, sp, ...}, n) = !sp - A.sub(fp, n)
229
230 fun stackToString stack =
231 let val depth = depth stack
232 fun f i = if i >= depth then " ]"
233 else "%st("^i2s i^")=%f"^i2s(st(stack,i))^" "^f(i+1)
234 in "[ "^f 0 end
235
236 fun clear(STACK{st, fp, sp, ...}) =
237 (sp := ~1; A.modify(fn _ => ~1) st; A.modify(fn _ => 16) fp)
238
239 (* Set %st(n) := %f *)
240 fun set(STACK{st, fp, sp, ...}, n, f) =
241 (A.update(st, !sp - n, f);
242 if f >= 0 then A.update(fp, f, !sp - n) else ()
243 )
244
245 (* Pop one entry *)
246 fun pop(STACK{sp, st, fp, ...}) = sp := !sp - 1
247
248 (* Push %fp(f) onto %st(0) *)
249 fun push(stack as STACK{sp, ...}, f) = (sp := !sp + 1; set(stack, 0, f))
250
251 (* Exchange the contents of %st(m) and %st(n) *)
252 fun xch(stack, m, n) =
253 let val f_m = st(stack, m)
254 val f_n = st(stack, n)
255 in set(stack, m, f_n);
256 set(stack, n, f_m)
257 end
258
259 fun kill(STACK{fp, ...}, f) = A.update(fp, CB.registerNum f, 16)
260
261 fun equal(st1, st2) =
262 let val m = depth st1
263 val n = depth st2
264 fun loop i =
265 i >= m orelse (st(st1, i) = st(st2, i) andalso loop(i+1))
266 in m = n andalso loop(0)
267 end
268
269 end (* struct *)
270
271 (*-----------------------------------------------------------------------
272 * Module to handle forward propagation.
273 * Forward propagation does the following:
274 * Given an instruction
275 * fmove mem, %fp(n)
276 * We delay the generation of the load until the first use of %fp(n),
277 * which we can further optimize by folding the load into the operand
278 * of the instruction, if it is the last use of this operand.
279 * If %fp(n) is dead then no load is necessary.
280 * Of course, we have to be careful whenever we encounter other
281 * instruction with a write.
282 *-----------------------------------------------------------------------*)
283 (*
284 structure ForwardPropagation :>
285 sig
286 type readbuffer
287 val create : ST.stack -> readbuffer
288 val load : readbuffer * C.cell * I.fsize * I.ea -> unit
289 val getreg : readbuffer * bool * C.cell * I.instruction list ->
290 I.operand * I.instruction list
291 val flush : readbuffer * I.instruction list -> I.instruction list
292 end =
293 struct
294
295 datatype readbuffer =
296 READ of { stack : ST.stack,
297 loads : (I.fsize * I.ea) option A.array,
298 pending : int ref
299 }
300
301 fun create stack =
302 READ{stack =stack,
303 loads =A.array(8, NONE),
304 pending =ref 0
305 }
306
307 fun load(READ{pending, loads, ...}, fd, fsize, mem) =
308 (A.update(loads, fd, SOME(fsize, mem));
309 pending := !pending + 1
310 )
311
312 (* Extract the operand for a register
313 * If it has a delayed load associated with it then
314 * we perform the load at this time.
315 *)
316 fun getreg(READ{pending, loads, stack, ...}, isLastUse, fs, code) =
317 case A.sub(loads, fs) of
318 NONE =>
319 let val n = ST.st(stack, fs)
320 in if isLastUse
321 then (ST n, code)
322 else let val code = I.FLDL(ST n)::code
323 in ST.push(stack, fs); (ST0, code)
324 end
325 end
326 | SOME(fsize, mem) =>
327 let val code = FLD(fsize, mem)::code
328 in A.update(loads, fs, NONE); (* delete load *)
329 pending := !pending - 1;
330 ST.push(stack, fs); (* fs is now in place *)
331 (ST0, code)
332 end
333
334 (* Extract a binary operand.
335 * We'll try to fold this into the operand
336 *)
337 fun getopnd(READ{pending, loads, stack,...}, isLastUse, I.FPR fs, code) =
338 (case A.sub(loads, fs) of
339 NONE =>
340 let val n = ST.st(stack, fs)
341 in if isLastUse fs (* regmap XXX *)
342 then (ST n, code)
343 else let val code = I.FLDL(ST n)::code
344 in ST.push(stack, fs); (ST0, code)
345 end
346 end
347 | SOME(fsize, mem) =>
348 (A.update(loads, fs, NONE); (* delete load *)
349 pending := !pending - 1;
350 if isLastUse fs then (mem, code)
351 else let val code = FLD(fsize, mem)::code
352 in ST.push(stack, fs);
353 (ST0, code)
354 end
355 )
356 )
357 | getopnd(_, _, ea, code) = (ea, code)
358
359 fun flush(READ{pending=ref 0,...}, code) = code
360
361 end (* struct *)
362 *)
363
364 (*-----------------------------------------------------------------------
365 * Module to handle delayed stores.
366 * Delayed store does the following:
367 * Given an instruction
368 * fstore %fp(n), %mem
369 * We delay the generation of the store until necessary.
370 * This gives us an opportunity to rearrange the order of the stores
371 * to eliminate unnecessary fxch.
372 *-----------------------------------------------------------------------*)
373 (*
374 structure DelayStore :>
375 sig
376 type writebuffer
377 val create : ST.stack -> writebuffer
378 val flush : writebuffer * I.instruction list -> I.instruction list
379 end =
380 struct
381 datatype writebuffer =
382 WRITE of { front : (I.ea * C.cell) list ref,
383 back : (I.ea * C.cell) list ref,
384 stack : ST.stack,
385 pending : int ref
386 }
387 fun create stack = WRITE{front=ref [], back=ref [],
388 stack=stack, pending=ref 0}
389 fun flush(WRITE{pending=ref 0,...}, code) = code
390 end (* struct *)
391 *)
392
393 (*-----------------------------------------------------------------------
394 * Main routine.
395 *
396 * Algorithm:
397 * 1. Perform liveness analysis.
398 * 2. For each fp register, mark all its last use point(s).
399 * Registers are popped at their last uses.
400 * 3. Rewrite the instructions basic block by basic block.
401 * 4. Insert shuffle code at basic block boundaries.
402 * When necessary, split critical edges.
403 * 5. Sacrifice a goat to make sure things don't go wrong.
404 *-----------------------------------------------------------------------*)
405 fun run(Cfg as G.GRAPH cfg) =
406 let
407 val numberOfBlks = #capacity cfg ()
408 val ENTRY = List.hd (#entries cfg ())
409 val EXIT = List.hd (#exits cfg ())
410
411 val getCell = C.getCellsByKind CB.FP
412 (*extract the fp component of cellset*)
413
414 val stTable = A.tabulate(8, fn n => I.ST(C.ST n))
415
416 fun ST n = (if sanityCheck andalso (n < 0 orelse n >= 8) then
417 pr("WARNING BAD %st("^i2s n^")\n")
418 else ();
419 A.sub(stTable, n)
420 )
421
422 fun FXCH n = I.fxch{opnd=C.ST n}
423
424 val ST0 = ST 0
425 val ST1 = ST 1
426 val POP_ST = I.fstpl ST0 (* Instruction to pop an entry *)
427
428 (* Dump instructions *)
429 fun dump instrs =
430 let val Asm.S.STREAM{emit, ...} =
431 AsmStream.withStream (!MLRiscControl.debug_stream)
432 Asm.makeStream []
433 in app emit (rev instrs)
434 end
435
436 (* Create assembly of instruction *)
437 fun assemble instr =
438 let val buf = StringOutStream.mkStreamBuf()
439 val stream = StringOutStream.openStringOut buf
440 val Asm.S.STREAM{emit, ...} =
441 AsmStream.withStream stream Asm.makeStream []
442 val _ = emit instr
443 val s = StringOutStream.getString buf
444 val n = String.size s
445 in if n = 0 then s else String.substring(s, 0, n - 1)
446 end
447
448 (*------------------------------------------------------------------
449 * Perform liveness analysis on the floating point variables
450 * P.S. I'm glad I didn't throw away the code liveness code.
451 *------------------------------------------------------------------*)
452 val defUse = P.defUse CB.FP (* def/use properties *)
453 val {liveIn=liveInTable, liveOut=liveOutTable} = Liveness.liveness {
454 defUse=defUse,
455 (* updateCell=C.updateCellsByKind CB.FP, *)
456 getCell=getCell
457 } Cfg
458 (*------------------------------------------------------------------
459 * Scan the instructions compute the last uses and dead definitions
460 * at each program point. Ideally we can do this during the code
461 * rewriting phase. But that's probably too error prone for now.
462 *------------------------------------------------------------------*)
463 fun computeLastUse(blknum, insns, liveOut) =
464 let fun scan([], _, lastUse) = lastUse
465 | scan(i::instrs, live, lastUse) =
466 let val (d, u) = defUse i
467 val d = SL.uniq(d)(* definitions *)
468 val u = SL.uniq(u)(* uses *)
469 val dead = SL.return(SL.difference(d, live))
470 val live = SL.difference(live, d)
471 val last = SL.return(SL.difference(u, live))
472 val live = SL.union(live, u)
473 val _ =
474 if debug andalso debugLiveness then
475 (case last of
476 [] => ()
477 | _ => print(assemble i^"\tlast use="^
478 fregsToString last^"\n")
479 )
480 else ()
481 in scan(instrs, live, (last,dead)::lastUse)
482 end
483 val liveOutSet = SL.uniq liveOut
484 val _ =
485 if debug andalso debugLiveness then
486 print("LiveOut("^i2s blknum^") = "^
487 fregsToString(SL.return liveOutSet)^"\n")
488 else ()
489 in scan(!insns, liveOutSet, [])
490 end
491
492 (*------------------------------------------------------------------
493 * Temporary work space
494 *------------------------------------------------------------------*)
495 val {high, low} = C.cellRange CB.FP
496 val n = high+1
497 val lastUseTbl = A.array(n,~1) (* table for marking last uses *)
498 val useTbl = A.array(n,~1) (* table for marking uses *)
499
500 (* %fp register bindings before and after a basic block *)
501 val bindingsIn = A.array(numberOfBlks, NONE)
502 val bindingsOut = A.array(numberOfBlks, NONE)
503 val stampCounter = ref ~4096
504
505 (* Edges that need splitting *)
506 exception NoEdgesToSplit
507 val edgesToSplit = IntHashTable.mkTable(32, NoEdgesToSplit)
508 val addEdgesToSplit = IntHashTable.insert edgesToSplit
509 fun lookupEdgesToSplit b =
510 getOpt(IntHashTable.find edgesToSplit b, [])
511
512 (*------------------------------------------------------------------
513 * Code for handling bindings between basic block
514 *------------------------------------------------------------------*)
515
516 fun splitEdge(title, source, target, e) =
517 (if debug andalso !traceOn then
518 pr(title^" SPLITTING "^i2s source^"->"^ i2s target^"\n")
519 else ();
520 addEdgesToSplit(target,(source,target,e)::lookupEdgesToSplit target)
521 )
522
523 fun computeFreq(_,_,CFG.EDGE{w,...}) = !w
524
525 (* Given a cellset, return a sorted and unique
526 * list of elements with all non-physical registers removed
527 *)
528 fun removeNonPhysical celllist =
529 let fun loop([], S) = SL.return(SL.uniq S)
530 | loop(f::fs, S) =
531 let val fx = CB.registerNum f
532 in loop(fs,if fx <= 7 then f::S else S)
533 end
534 in loop(celllist, [])
535 end
536
537 (* Given a sorted and unique list of registers,
538 * Return a stack with these elements
539 *)
540 fun newStack fregs =
541 let val stack = ST.create()
542 in app (fn f => ST.push(stack, CB.registerNum f)) (rev fregs);
543 stack
544 end
545
546 (*
547 * This function looks at all the entries on the stack,
548 * and generate code to deallocate all the dead values.
549 * The stack is updated.
550 *)
551 fun removeDeadValues(stack, liveSet, code) =
552 let val stamp = !stampCounter
553 val _ = stampCounter := !stampCounter - 1
554 fun markLive [] = ()
555 | markLive(r::rs) =
556 (A.update(useTbl, CB.registerNum r, stamp); markLive rs)
557 fun isLive f = A.sub(useTbl, f) = stamp
558 fun loop(i, depth, code) =
559 if i >= depth then code else
560 let val f = ST.st(stack, i)
561 in if isLive f (* live? *)
562 then loop(i+1, depth, code)
563 else
564 (if debug andalso !traceOn then
565 pr("REMOVING %f"^i2s f^" in %st("^i2s i^")"^
566 " current stack="^ST.stackToString stack^"\n")
567 else ();
568 if i = 0 then
569 (ST.pop stack;
570 loop(0, depth-1, POP_ST::code)
571 )
572 else (ST.xch(stack,0,i);
573 ST.pop stack;
574 loop(0, depth-1, I.fstpl(ST i)::code)
575 )
576 )
577 end
578 in markLive liveSet;
579 loop(0, ST.depth stack, code)
580 end
581
582
583 (*------------------------------------------------------------------
584 * Given two stacks, source and target, where the bindings are
585 * permutation of each other, generate the minimal number of
586 * fxchs to match source with target.
587 *
588 * Important: source and target MUST be permutations of each other.
589 *
590 * Essentially, we first decompose the permutation into cycles,
591 * and process each cycle.
592 *------------------------------------------------------------------*)
593 fun shuffle(source, target, code) =
594 let val stamp = !stampCounter
595 val _ = stampCounter := !stampCounter - 1
596 val permutation = lastUseTbl (* reuse the space *)
597
598 val _ = if debug andalso !traceOn then
599 pr("SHUFFLE "^ST.stackToString source^
600 "->"^ST.stackToString target^"\n")
601 else ()
602
603 (* Compute the initial permutation *)
604 val n = ST.depth source
605 fun computeInitialPermutation(i) =
606 if i >= n
607 then ()
608 else let val f = ST.st(source, i)
609 val j = ST.fp(target, f)
610 in A.update(permutation, j, i);
611 computeInitialPermutation(i+1)
612 end
613 val _ = computeInitialPermutation 0
614
615 (* Decompose the initial permutation into cycles.
616 * The cycle involving 0 is treated specially.
617 *)
618 val visited = useTbl
619 fun isVisited i = A.sub(visited,i) = stamp
620 fun markAsVisited i = A.update(visited,i,stamp)
621 fun decomposeCycles(i, cycle0, cycles) =
622 if i >= n then (cycle0, cycles)
623 else if isVisited i orelse
624 A.sub(permutation, i) = i (* trivial cycle *)
625 then decomposeCycles(i+1, cycle0, cycles)
626 else let fun makeCycle(j, cycle, zero) =
627 let val k = A.sub(permutation, j)
628 val cycle = j::cycle
629 val zero = zero orelse j = 0
630 in markAsVisited j;
631 if k = i then (cycle, zero)
632 else makeCycle(k, cycle, zero)
633 end
634 val (cycle, zero) = makeCycle(i, [], false)
635 in if zero then decomposeCycles(i+1, [cycle], cycles)
636 else decomposeCycles(i+1, cycle0, cycle::cycles)
637 end
638
639 val (cycle0, cycles) = decomposeCycles(0, [], [])
640
641 (*
642 * Generate shuffle for a cycle that does not involve 0.
643 * Given a cycle (c_1, ..., c_k), we generate this code:
644 * fxch %st(c_1),
645 * fxch %st(c_2),
646 * ...
647 * fxch %st(c_k),
648 * fxch %st(c_1)
649 *)
650 fun genxch([], code) = code
651 | genxch(c::cs, code) = genxch(cs, FXCH c::code)
652
653 fun gen([], code) = error "shuffle.gen"
654 | gen(cs as (c::_), code) = FXCH c::genxch(cs, code)
655
656 (*
657 * Generate shuffle for a cycle that involves 0.
658 * Given a cycle (c_1,...,c_k) we first shuffle this to
659 * an equivalent cycle (c_1, ..., c_k) where c'_k = 0,
660 * then we generate this code:
661 * fxch %st(c'_1),
662 * fxch %st(c'_2),
663 * ...
664 * fxch %st(c'_{k-1}),
665 *)
666 fun gen0([], code) = error "shuffle.gen0"
667 | gen0(cs, code) =
668 let fun rearrange(0::cs, cs') = cs@rev cs'
669 | rearrange(c::cs, cs') = rearrange(cs, c::cs')
670 | rearrange([], _) = error "shuffle.rearrange"
671 val cs = rearrange(cs, [])
672 in genxch(cs, code)
673 end
674
675 (*
676 * Generate code. Must process the non-zero cycles first.
677 *)
678 val code = List.foldr gen code cycles
679 val code = List.foldr gen0 code cycle0
680 in code
681 end (* shuffle *)
682
683 (*------------------------------------------------------------------
684 * Insert code at the end of a basic block.
685 * Make sure we put code in front of a transfer instruction
686 *------------------------------------------------------------------*)
687 fun insertAtEnd(insns, code) =
688 (case insns of
689 [] => code
690 | jmp::rest =>
691 if P.instrKind jmp = P.IK_JUMP then
692 jmp::code@rest
693 else
694 code@insns
695 )
696
697 (*------------------------------------------------------------------
698 * Magic for inserting shuffle code at the end of a basic block
699 *------------------------------------------------------------------*)
700 fun shuffleOut(stackOut, insns, b, block, liveOut) =
701 let
702 val liveOut = removeNonPhysical(liveOut)
703
704 (* Generate code that remove unnecessary values *)
705 val code = removeDeadValues(stackOut, liveOut, [])
706
707 fun done(stackOut, insns, code) =
708 (A.update(bindingsOut,b,SOME stackOut);
709 insertAtEnd(insns, code)
710 )
711
712 (* Generate code that shuffle values from source to target *)
713 fun match(source, target) =
714 done(target, insns, shuffle(source, target, []))
715
716 (* Generate code that shuffle values from source to liveOut *)
717 fun matchLiveOut() =
718 case liveOut of
719 [] => done(stackOut, insns, code)
720 | _ => match(stackOut, newStack liveOut)
721
722 (* With multiple successors, find out which one we
723 * should connect to. Choose the one from the block that
724 * follows from this one, if that exists, or else choose
725 * from the edge with the highest frequency.
726 *)
727 fun find([], _, id, best) = (id, best)
728 | find((_, target, _)::edges, highestFreq, id, best) =
729 let val CFG.BLOCK{freq, ...} = #node_info cfg target
730 in if target = b+1 then (target, A.sub(bindingsIn, target))
731 else (case A.sub(bindingsIn, target) of
732 NONE => find(edges, highestFreq, id, best)
733 | this as SOME stack =>
734 if highestFreq < !freq then
735 find(edges, !freq, target, this)
736 else
737 find(edges, highestFreq, id, best)
738 )
739 end
740
741 (*
742 * Split all edges source->target except omitThis.
743 *)
744 fun splitAllEdgesExcept([], omitThis) = ()
745 | splitAllEdgesExcept((source,target,e)::edges, omitThis) =
746 if target = EXIT then error "can't split exit edge!"
747 else
748 (if target <> omitThis andalso
749 target <= b andalso (* XXX *)
750 target <> ENTRY
751 then splitEdge("ShuffleOut",source,target,e) else ();
752 splitAllEdgesExcept(edges, omitThis)
753 )
754
755 (* Just one successor;
756 * try to match the bindings of the successor if it exist.
757 *)
758 fun matchIt succ =
759 let val (succBlock, target) = find(succ, ~1.0, ~1, NONE)
760 in splitAllEdgesExcept(succ, succBlock);
761 case target of
762 SOME stackIn => match(stackOut, stackIn)
763 | NONE => done(stackOut,insns,code)
764 end
765
766 in case #out_edges cfg b of
767 [] => matchLiveOut()
768 | succ as [(_,target,_)] =>
769 if target = EXIT then matchLiveOut()
770 else matchIt succ
771 | succ => matchIt succ
772 end (* shuffleOut *)
773
774 (*------------------------------------------------------------------
775 * Compute the initial fp stack bindings for basic block b.
776 *------------------------------------------------------------------*)
777 fun shuffleIn(b, block, liveIn) =
778 let
779 val liveInSet = removeNonPhysical liveIn
780
781 (* With multiple predecessors, find out which one we
782 * should connect to. Choose the one from the block that
783 * falls into this one, if that exists, or else choose
784 * from the edge with the highest frequency.
785 *)
786 fun find([], _, best) = best
787 | find((source, _, _)::edges, highestFreq, best) =
788 let val CFG.BLOCK{freq, ...} = #node_info cfg source
789 in case A.sub(bindingsOut, source) of
790 NONE => find(edges, highestFreq, best)
791 | this as SOME stack =>
792 if source = b-1
793 then this (* falls into b *)
794 else if highestFreq < !freq then find(edges, !freq, this)
795 else find(edges, highestFreq, best)
796 end
797
798 fun splitAllDoneEdges [] = ()
799 | splitAllDoneEdges ((source, target, e)::edges) =
800 (if source < b andalso
801 source <> ENTRY andalso
802 source <> EXIT
803 then splitEdge("ShuffleIn", source, target, e) else ();
804 splitAllDoneEdges edges
805 )
806
807 (* The initial stack bindings are determined by the live set.
808 * No compensation code is needed.
809 *)
810 fun fromLiveIn() =
811 let val stackIn =
812 case liveInSet of
813 [] => ST.stack0
814 | _ =>
815 (pr("liveIn="^celllistToString liveIn^"\n");
816 newStack liveInSet
817 )
818 val stackOut = ST.copy stackIn
819 in (stackIn, stackOut, [])
820 end
821
822 val pred = #in_edges cfg b
823
824 val (stackIn, stackOut, code) =
825 case find(pred, ~1.0, NONE) of
826 NONE => (splitAllDoneEdges(pred); fromLiveIn())
827 | SOME stackIn' =>
828 (case pred of
829 [_] => (* one predecessor *)
830 (* Use the bindings as from the previous block
831 * We first have to deallocate all unused values.
832 *)
833 let val stackOut = ST.copy stackIn'
834 (* Clean the stack of unused entries *)
835 val code = removeDeadValues(stackOut, liveInSet, [])
836 in (stackIn', stackOut, code) end
837 | pred => (* more than one predecessors *)
838 let val stackIn = ST.copy stackIn'
839 val code = removeDeadValues(stackIn, liveInSet, [])
840 val stackOut = ST.copy stackIn
841 in (* If we have to generate code to deallocate
842 * the stack then we have split the edge.
843 *)
844 case code of
845 [] => ()
846 | _ => splitAllDoneEdges(pred);
847 (stackIn, stackOut, [])
848 end
849 )
850 in A.update(bindingsIn, b, SOME stackIn);
851 A.update(bindingsOut, b, SOME stackOut);
852 (stackIn, stackOut, code)
853 end
854
855 (*------------------------------------------------------------------
856 * Code for patching up critical edges.
857 * The trick is finding a good place to insert the critical edges.
858 * Let's call an edge x->y that requires compensation
859 * code c to be inserted an candidate edge. We write this as x->y(c)
860 *
861 * Here are the heuristics that we use to improve the final code:
862 *
863 * 1. Given two candidate edges a->x(c1) and b->x(c2) where c1=c2
864 * then we can merge the two copies of compensation code.
865 * This is quite common. This generalizes to any number of edges.
866 *
867 * 2. Given two candidate edges a->x(c1) and b->x(c2) and where
868 * c1 and c2 are pops, we can partially share c1 and c2.
869 * Currently, I think I only recognize this case when
870 * x has no fp registers live-in.
871 *
872 * 3. Given two candidate edges a->x(c1) and b->x(c2),
873 * if a->x has a higher frequency then put the compensation
874 * code in front of x (so that it falls through into x)
875 * whenever possible.
876 *
877 * As you can see, the voodoo is strong here.
878 *
879 * The routine has two main phases:
880 * 1. Determine the compensation code by applying the heuristics
881 * above.
882 * 2. Then insert them and rebuild the cfg by renaming all block
883 * ids. This is currently necessary to keep the layout order
884 * consistent with the order of the id.
885 *------------------------------------------------------------------*)
886 fun repairCriticalEdges(Cfg as G.GRAPH cfg) =
887 let
888 val cleanup = [#create MLRiscAnnotations.COMMENT "cleanup edge"]
889 val critical = [#create MLRiscAnnotations.COMMENT "critical edge"]
890
891 fun annotate(gen, an) =
892 app (fn ((_,CFG.BLOCK{annotations, ...}),_) => annotations := an)
893 gen
894
895 (*
896 * Special case: target block has stack depth of 0.
897 * Just generate code that pop entries from the sources.
898 * To make things interesting, we try to share code among
899 * all the critical edges.
900 *)
901 fun genPoppingCode(_, []) = ()
902 | genPoppingCode(targetId, edges) =
903 let (* Edges annotated with the source stack depth
904 * Ordered by increasing stack height
905 *)
906 val edges =
907 IM.listItemsi
908 (foldr (fn (edge as (sourceId, _, _), M) =>
909 let val n = ST.depth(valOf(A.sub(bindingsOut,sourceId)))
910 in IM.insert(M, n, edge :: getOpt(IM.find(M, n), []))
911 end) IM.empty edges)
912
913 (* Generate n pops *)
914 fun pops(0, code) = code
915 | pops(n, code) = pops(n-1, POP_ST::code)
916
917 (* Create the chain of blocks *)
918 fun makeChain(depth, [], chain) = chain
919 | makeChain(depth, (d, es)::es', chain) =
920 let val code = pops(d - depth, [])
921 in makeChain(d, es', (es, code)::chain)
922 end
923
924 val chain = makeChain(0, edges, [])
925
926 in annotate(CFG.splitEdges Cfg {groups=chain, jump=false}, cleanup)
927 end
928
929 (*
930 * Generate repair code.
931 *)
932 fun genRepairCode(targetId, stackIn, edges) =
933 let val liveIn = IntHashTable.lookup liveInTable targetId
934 val liveInSet = removeNonPhysical liveIn
935 val _ = if debug then
936 pr("LiveIn = "^celllistToString liveIn^"\n")
937 else ()
938
939 (* Group all edges whose output stack configurations
940 * are the same. Each group is merged together into
941 * a single compensation block
942 *)
943 fun partition([], S) = S
944 | partition((e as (src,_,_))::es, S) =
945 let val stackOut = ST.copy(valOf(A.sub(bindingsOut,src)))
946 fun find([], S) = partition(es, ([e],stackOut)::S)
947 | find((x as (es',st'))::S', S) =
948 if ST.equal(stackOut,st') then
949 partition(es, (e::es',st')::S' @ S)
950 else
951 find(S', x::S)
952 in find(S, [])
953 end
954
955 (* Partition by the source bindings *)
956 val S = partition(edges, [])
957
958 (* Compute frequencies *)
959 val S = map (fn (es,st) => (CFG.sumEdgeFreqs es,es,st)) S
960
961 (* Ordered by non-increasing frequencies *)
962 val S = ListMergeSort.sort (fn ((x,_,_),(y,_,_)) => x < y) S
963
964 (* Generate code *)
965 fun gen(freq, edges, stackOut) =
966 let (* deallocate unused values *)
967 val code = removeDeadValues(stackOut,liveInSet,[])
968 (* shuffle values *)
969 val code = shuffle(stackOut, stackIn, code)
970 in annotate(
971 CFG.splitEdges Cfg {groups=[(edges,code)], jump=false},
972 critical)
973 end
974
975 in app gen S
976 end
977
978 (* Split all edges entering targetId *)
979 fun split(targetId, edges) =
980 let val stackIn = valOf(A.sub(bindingsIn,targetId))
981 fun log(s, t, e) =
982 case A.sub (bindingsOut, s) of
983 SOME stackOut =>
984 (pr("SPLIT "^i2s s^"->"^i2s t^" "^
985 ST.stackToString stackOut^"->"^
986 ST.stackToString stackIn^"\n"))
987 | NONE => error "split:stackOut"
988 val _ = if debug andalso !traceOn then app log edges else ()
989 in if ST.depth stackIn = 0 then genPoppingCode(targetId, edges)
990 else genRepairCode(targetId, stackIn, edges)
991 end
992
993 in IntHashTable.appi split edgesToSplit;
994 CFG.changed Cfg;
995 Cfg
996 end
997
998 (*------------------------------------------------------------------
999 * Process all blocks which are not the entry or the exit
1000 *------------------------------------------------------------------*)
1001 val stamp = ref 0
1002 fun rewriteAllBlocks (_, CFG.BLOCK{kind=CFG.START, ...}) = ()
1003 | rewriteAllBlocks (_, CFG.BLOCK{kind=CFG.STOP, ...}) = ()
1004 | rewriteAllBlocks
1005 (blknum, block as CFG.BLOCK{insns, labels, annotations, ...}) =
1006 let val _ =
1007 if debug andalso !debugOn then
1008 app (fn l => pr(L.toString l^":\n")) (!labels)
1009 else ();
1010 val liveIn = HT.lookup liveInTable blknum
1011 val liveOut = HT.lookup liveOutTable blknum
1012 val st = rewrite(!stamp, blknum, block,
1013 insns, liveIn, liveOut,
1014 annotations)
1015 in stamp := st (* update stamp *)
1016 end
1017
1018 (*------------------------------------------------------------------
1019 * Translate code within a basic block.
1020 * Each instruction is given a unique stamp for identifying last
1021 * uses.
1022 *------------------------------------------------------------------*)
1023 and rewrite(stamp, blknum, block, insns, liveIn, liveOut,
1024 annotations) =
1025 let val (stackIn, stack, code) = shuffleIn(blknum, block, liveIn)
1026
1027 (* Dump instructions when encountering a bug *)
1028 fun bug msg =
1029 (pr("-------- bug in block "^i2s blknum^" ----\n");
1030 dump(!insns);
1031 error msg
1032 )
1033
1034 fun loop(stamp, [], [], code) = (stamp, code)
1035 | loop(stamp, instr::rest, (lastUse,dead)::lastUses, code) =
1036 let fun mark(tbl, []) = ()
1037 | mark(tbl, r::rs) =
1038 (A.update(tbl, CB.registerNum r, stamp); mark(tbl, rs))
1039 in mark(lastUseTbl,lastUse); (* mark all last uses *)
1040 trans(stamp, instr, [], rest, dead, lastUses, code)
1041 end
1042 | loop _ = error "loop"
1043
1044 (*
1045 * Main routine that does the actual translation.
1046 * A few reminders:
1047 * o The instructions are processed in normal order
1048 * and generated in the reversed order.
1049 * o (Local) liveness is computed at the same time.
1050 * o For each use, we have to find out whether it is
1051 * the last use. If so, we can kill it and reclaim
1052 * the stack entry at the same time.
1053 *)
1054 and trans(stamp, instr, an, rest, dead, lastUses, code) =
1055 let (* Call this continuation when done with code generation *)
1056 fun FINISH code = loop(stamp+1, rest, lastUses, code)
1057
1058 fun KILL_THE_DEAD(dead, code) =
1059 let fun kill([], code) = FINISH code
1060 | kill(f::fs, code) =
1061 let val fx = CB.registerNum f
1062 in if debug andalso debugDead then
1063 pr("DEAD "^fregToString f^" in "^
1064 ST.stackToString stack^"\n")
1065 else ();
1066 (* not a physical register *)
1067 if fx >= 8 then kill(fs, code)
1068 else
1069 let val i = ST.fp(stack, fx)
1070 in if debug andalso debugDead then
1071 pr("KILLING "^fregToString f^
1072 "=%st("^i2s i^")\n")
1073 else ();
1074 if i < 0 then kill(fs, code) (* dead already *)
1075 else if i = 0 then
1076 (ST.pop stack; kill(fs, POP_ST::code))
1077 else
1078 (ST.xch(stack,0,i); ST.pop stack;
1079 kill(fs, I.fstpl(ST i)::code)
1080 )
1081 end
1082 end
1083 in kill(dead, code)
1084 end
1085
1086 (* Call this continuation when done with floating point
1087 * code generation. Remove all dead code first.
1088 *)
1089 fun DONE code = KILL_THE_DEAD(dead, code)
1090
1091 (* Is this the last use of register f? *)
1092 fun isLastUse f = A.sub(lastUseTbl, f) = stamp
1093
1094 (* Is this value dead? *)
1095 fun isDead f =
1096 let fun loop [] = false
1097 | loop(r::rs) = CB.sameColor(f,r) orelse loop rs
1098 in loop dead end
1099
1100 (* Dump the stack before each intruction for debugging *)
1101 fun log() = if debug andalso !traceOn then
1102 pr(ST.stackToString stack^assemble instr^"...\n")
1103 else ()
1104
1105 (* Find the location of a source register *)
1106 fun getfs(f) =
1107 let val fx = CB.registerNum f
1108 val s = ST.fp(stack, fx)
1109 in (isLastUse fx,s) end
1110
1111 (* Generate memory to memory move *)
1112 fun mmmove(fsize,src,dst) =
1113 let val _ = ST.nonFull stack
1114 val code = FLD(fsize,src)::code
1115 val code = mark(FSTP(fsize,dst),an)::code
1116 in DONE code end
1117
1118 (* Allocate a new register in %st(0) *)
1119 fun alloc(f,code) = (ST.push(stack,CB.registerNum f); code)
1120
1121 (* register -> register move *)
1122 fun rrmove(fs,fd) =
1123 if CB.sameColor(fs,fd) then DONE code
1124 else
1125 let val (dead,ss) = getfs fs
1126 in if dead then (* fs is dead *)
1127 (ST.set(stack,ss,CB.registerNum fd); (* rename fd to fs *)
1128 DONE code (* no code is generated *)
1129 )
1130 else (* fs is not dead; push it onto %st(0);
1131 * set fd to %st(0)
1132 *)
1133 let val code = alloc(fd, code)
1134 in DONE(mark(I.fldl(ST ss),an)::code)
1135 end
1136 end
1137
1138 (* memory -> register move.
1139 * Do dead code elimination here.
1140 *)
1141 fun mrmove(fsize,src,fd) =
1142 if isDead fd
1143 then FINISH code (* value has been killed *)
1144 else
1145 let val code = alloc(fd, code)
1146 in DONE(mark(FLD(fsize,src),an)::code)
1147 end
1148
1149 (* exchange %st(n) and %st(0) *)
1150 fun xch(n) = (ST.xch(stack,0,n); FXCH n)
1151
1152 (* push %st(n) onto the stack *)
1153 fun push(n) = (ST.push(stack,~2); I.fldl(ST n))
1154
1155
1156 (* push mem onto the stack *)
1157 fun pushmem(src) = (ST.push(stack,~2); I.fldl(src))
1158
1159 (* register -> memory move.
1160 * Use pop version of the opcode if it is the last use.
1161 *)
1162 fun rmmove(fsize,fs,dst) =
1163 let fun fstp(code) =
1164 (ST.pop stack; DONE(mark(FSTP(fsize,dst),an)::code))
1165 fun fst(code) = DONE(mark(FST(fsize,dst),an)::code)
1166 in case getfs fs of
1167 (true, 0) => fstp code
1168 | (true, n) => fstp(xch n::code)
1169 | (false, 0) => fst(code)
1170 | (false, n) => fst(xch n::code)
1171 end
1172
1173 (* Floating point move *)
1174 fun fmove{fsize,src=I.FPR fs,dst=I.FPR fd} = rrmove(fs,fd)
1175 | fmove{fsize,src,dst=I.FPR fd} = mrmove(fsize,src,fd)
1176 | fmove{fsize,src=I.FPR fs,dst} = rmmove(fsize,fs,dst)
1177 | fmove{fsize,src,dst} = mmmove(fsize,src,dst)
1178
1179 (* Floating point integer load operator *)
1180 fun fiload{isize,ea,dst=I.FPR fd} =
1181 let val code = alloc(fd, code)
1182 val code = mark(FILD(isize,ea),an)::code
1183 in DONE code
1184 end
1185 | fiload{isize,ea,dst} =
1186 let val code = mark(FILD(isize,ea),an)::code
1187 val code = I.fstpl(dst)::code (* XXX *)
1188 in DONE code
1189 end
1190
1191 (* Make a copy of register fs to %st(0). *)
1192 fun moveregtotop(fs, code) =
1193 (case getfs fs of
1194 (true, 0) => code
1195 | (true, n) => xch n::code
1196 | (false, n) => push n::code
1197 )
1198
1199 fun movememtotop(fsize, mem, code) =
1200 (ST.push(stack, ~2); FLD(fsize, mem)::code)
1201
1202 (* Move an operand to top of stack *)
1203 fun movetotop(fsize, I.FPR fs, code) = moveregtotop(fs, code)
1204 | movetotop(fsize, mem, code) = movememtotop(fsize, mem, code)
1205
1206 fun storeResult(fsize, dst, n, code) =
1207 case dst of
1208 I.FPR fd => (ST.set(stack, n, CB.registerNum fd); DONE code)
1209 | mem =>
1210 let val code = if n = 0 then code else xch n::code
1211 in ST.pop stack; DONE(FSTP(fsize, mem)::code) end
1212
1213 (* Floating point unary operator *)
1214 fun funop{fsize,unOp,src,dst} =
1215 let val code = movetotop(fsize, src, code)
1216 val code = mark(I.funary unOp,an)::code
1217
1218 (* Moronic hack to deal with partial tangent! *)
1219 val code =
1220 case unOp of
1221 I.FPTAN =>
1222 (if ST.depth stack >= 7 then error "FPTAN"
1223 else ();
1224 POP_ST::code (* pop the useless 1.0 *)
1225 )
1226 | _ => code
1227 in storeResult(fsize, dst, 0, code)
1228 end
1229
1230 (* Floating point binary operator.
1231 * Note:
1232 * binop src, dst
1233 * means dst := dst binop src
1234 * (lsrc := lsrc binop rsrc)
1235 * on the x86
1236 *)
1237 fun fbinop{fsize,binOp,lsrc,rsrc,dst} =
1238 let (* generate code and set %st(n) = fd *)
1239 (* op2 := op1 - op2 *)
1240 fun oper(binOp,op1,op2,n,code) =
1241 let val code =
1242 mark(I.fbinary{binOp=binOp,src=op1,dst=op2},an)
1243 ::code
1244 in storeResult(I.FP64, dst, n, code)
1245 end
1246
1247 fun operR(binOp,op1,op2,n,code) =
1248 oper(invert binOp,op1,op2,n,code)
1249
1250 fun operP(binOp,op1,op2,n,code) =
1251 (ST.pop stack; oper(pop binOp,op1,op2,n-1,code))
1252
1253 fun operRP(binOp,op1,op2,n,code) =
1254 (ST.pop stack; operR(pop binOp,op1,op2,n-1,code))
1255
1256 (* Many special cases to consider.
1257 * Basically, try to reuse stack space as
1258 * much as possible by taking advantage of last uses.
1259 *
1260 * Stack=[st(0)=3.0 st(1)=2.0]
1261 * fsub %st(1), %st [1,2.0]
1262 * fsubr %st(1), %st [-1,2.0]
1263 * fsub %st, %st(1) [3.0,1.0]
1264 * fsubr %st, %st(1) [3.0,-1.0]
1265 *
1266 * fsubp %st, %st(1) [1]
1267 * fsubrp %st, %st(1) [-1]
1268 * So,
1269 * fsub %st(n), %st (means %st - %st(n) -> %st)
1270 * fsub %st, %st(n) (means %st - %st(n) -> %st(n))
1271 * fsubr %st(n), %st (means %st(n) - %st -> %st)
1272 * fsubr %st, %st(n) (means %st(n) - %st -> %st(n))
1273 *)
1274 fun reg2(fx, fy) =
1275 let val (dx, sx) = getfs fx
1276 val (dy, sy) = getfs fy
1277 fun loop(dx, sx, dy, sy, code) =
1278 (* op1, op2 (dst) *)
1279 case (dx, sx, dy, sy) of
1280 (true, 0, false, n) => oper(binOp,ST n,ST0,0,code)
1281 | (false, n, true, 0) => operR(binOp,ST n,ST0,0,code)
1282 | (true, n, true, 0) => operRP(binOp,ST0,ST n,n,code)
1283 | (true, 0, true, n) => operP(binOp,ST0,ST n,n,code)
1284 | (false, 0, true, n) => oper(binOp,ST0,ST n,n,code)
1285 | (true, n, false, 0) => operR(binOp,ST0,ST n,n,code)
1286 | (true, sx, dy, sy) =>
1287 loop(true, 0, dy, sy, xch sx::code)
1288 | (dx, sx, true, sy) =>
1289 loop(dx, sx, true, 0, xch sy::code)
1290 | (false, sx, false, sy) =>
1291 loop(true, 0, false, sy+1, push sx::code)
1292 in if sx = sy then (* same register *)
1293 let val code =
1294 case (dx, sx) of
1295 (true, 0) => code
1296 | (true, n) => xch n::code
1297 | (false, n) => push n::code
1298 in oper(binOp,ST0,ST0,0,code)
1299 end
1300 else loop(dx, sx, dy, sy, code)
1301 end
1302
1303 (* reg/mem operands *)
1304 fun regmem(binOp, fx, mem) =
1305 case getfs fx of
1306 (true, 0) => oper(binOp,mem,ST0,0,code)
1307 | (true, n) => oper(binOp,mem,ST0,0,xch n::code)
1308 | (false, n) => oper(binOp,mem,ST0,0,push n::code)
1309
1310 (* Two memory operands. Optimize the case when
1311 * the two operands are identical.
1312 *)
1313 fun mem2(lsrc, rsrc) =
1314 let val _ = ST.push(stack,~2)
1315 val code = FLD(fsize,lsrc)::code
1316 val rsrc = if P.eqOpn(lsrc, rsrc) then ST0 else rsrc
1317 in oper(binOp,rsrc,ST0,0,code)
1318 end
1319
1320 fun process(I.FPR fx, I.FPR fy) = reg2(fx, fy)
1321 | process(I.FPR fx, mem) = regmem(binOp, fx, mem)
1322 | process(mem, I.FPR fy) = regmem(invert binOp, fy, mem)
1323 | process(lsrc, rsrc) = mem2(lsrc, rsrc)
1324
1325 in process(lsrc, rsrc)
1326 end
1327
1328 (* Floating point binary operator with integer conversion *)
1329 fun fibinop{isize,binOp,lsrc,rsrc,dst} =
1330 let fun oper(binOp,src,code) =
1331 let val code = mark(I.fibinary{binOp=binOp,src=src},an)
1332 ::code
1333 in storeResult(I.FP64, dst, 0, code)
1334 end
1335
1336 fun regmem(binOp, fx, mem) =
1337 case getfs fx of
1338 (true, 0) => oper(binOp, mem, code)
1339 | (true, n) => oper(binOp, mem, xch n::code)
1340 | (false, n) => oper(binOp, mem, push n::code)
1341
1342 in case (lsrc, rsrc) of
1343 (I.FPR fx, mem) => regmem(binOp, fx, mem)
1344 | (lsrc, rsrc) => oper(binOp, rsrc, pushmem lsrc::code)
1345 end
1346
1347 (* Floating point comparison
1348 * We have to make sure there are enough registers.
1349 * The trick is that tmp is always a physical register.
1350 * So we can always use it as temporary space if we
1351 * have run out.
1352 *)
1353 fun fcmp{i,fsize,lsrc,rsrc} =
1354 let fun fucompp code =
1355 (ST.pop stack; ST.pop stack;
1356 if i then
1357 POP_ST :: mark(I.fucomip(ST 1), an) :: code
1358 else
1359 mark(I.fucompp,an) :: code
1360 )
1361 fun fucomp(n) =
1362 (ST.pop stack;
1363 mark((if i then I.fucomip else I.fucomp)(ST n),an))
1364 fun fucom(n) =
1365 mark((if i then I.fucomi else I.fucom)(ST n),an)
1366
1367 fun genmemcmp() =
1368 let val code = movememtotop(fsize, rsrc, code)
1369 val code = movememtotop(fsize, lsrc, code)
1370 in FINISH(fucompp(code))
1371 end
1372
1373 fun genmemregcmp(lsrc, fy) =
1374 case getfs fy of
1375 (false, n) =>
1376 let val code = movememtotop(fsize, lsrc, code)
1377 in FINISH(fucomp(n+1)::code) end
1378 | (true, n) =>
1379 let val code = if n = 0 then code else xch n::code
1380 val code = movememtotop(fsize, lsrc, code)
1381 in FINISH(fucompp(code))
1382 end
1383
1384 fun genregmemcmp(fx, rsrc) =
1385 let val code =
1386 case getfs fx of
1387 (true, n) =>
1388 let val code = if n = 0 then code
1389 else xch n::code
1390 val code = movememtotop(fsize, rsrc, code)
1391 in xch 1::code end
1392 | (false, n) =>
1393 let val code = movememtotop(fsize, rsrc, code)
1394 in push(n+1)::code
1395 end
1396 in FINISH(fucompp(code))
1397 end
1398
1399 (* Deal with the special case when both sources are
1400 * in the same register
1401 *)
1402 fun regsame(dx, sx) =
1403 let val (code, cmp) =
1404 case (dx, sx) of
1405 (true, 0) => (code, fucomp 0) (* pop once! *)
1406 | (false, 0) => (code, fucom 0) (* don't pop! *)
1407 | (true, n) => (xch n::code, fucomp 0)
1408 | (false, n) => (xch n::code, fucom 0)
1409 in FINISH(cmp::code) end
1410
1411 fun reg2(fx, fy) =
1412 (* special case is when things are already in place.
1413 * Note: should also generate FUCOM and FUCOMP!!!
1414 *)
1415 let val (dx, sx) = getfs fx
1416 val (dy, sy) = getfs fy
1417 fun fstp(n) =
1418 (ST.xch(stack,n,0); ST.pop stack; I.fstpl(ST n))
1419 in if sx = sy then regsame(dx, sx) (* same register!*)
1420 else
1421 (* first, move sx to %st(0) *)
1422 let val (sy, code) =
1423 if sx = 0 then (sy, code) (* there already *)
1424 else (if sy = 0 then sx else sy,
1425 xch sx::code)
1426
1427 (* Generate the appropriate comparison op *)
1428 val (sy, code, popY) =
1429 case (dx, dy, sy) of
1430 (true, true, 0) => (~1,fucompp code, false)
1431 | (true, _, _) => (sy-1,fucomp sy::code,dy)
1432 | (false, _, _) => (sy, fucom sy::code, dy)
1433
1434 (* Pop fy if it is dead and hasn't already
1435 * been popped.
1436 *)
1437 val code = if popY then fstp sy::code else code
1438 in FINISH code
1439 end
1440 end
1441
1442 in case (lsrc, rsrc) of
1443 (I.FPR x, I.FPR y) => reg2(x, y)
1444 | (I.FPR x, mem) => genregmemcmp(x, mem)
1445 | (mem, I.FPR y) => genmemregcmp(mem, y)
1446 | _ => genmemcmp()
1447 end
1448
1449
1450 fun prCopy(dst, src) =
1451 ListPair.app(fn (fd, fs) =>
1452 pr(fregToString(fd)^"<-"^fregToString fs^" "))
1453 (dst, src)
1454
1455 (* Parallel copy magic.
1456 * For each src registers, we find out
1457 * 1. whether it is the last use, and if so,
1458 * 2. whether it is used more than once.
1459 * If a source is a last and unique use, then we
1460 * can simply rename it to appropriate destination register.
1461 *)
1462 fun fcopy(I.COPY{dst,src,tmp,...}) = let
1463 fun loop([], [], copies, renames) = (copies, renames)
1464 | loop(fd::fds, fs::fss, copies, renames) =
1465 let val fsx = CB.registerNum fs
1466 in if isLastUse fsx then
1467 if A.sub(useTbl,fsx) <> stamp
1468 (* unused *)
1469 then (A.update(useTbl,fsx,stamp);
1470 loop(fds, fss, copies,
1471 if CB.sameColor(fd,fs) then renames
1472 else (fd, fs)::renames)
1473 )
1474 else loop(fds, fss, (fd, fs)::copies, renames)
1475 else loop(fds, fss, (fd, fs)::copies, renames)
1476 end
1477 | loop _ = error "fcopy.loop"
1478
1479 (* generate code for the copies *)
1480 fun genCopy([], code) = code
1481 | genCopy((fd, fs)::copies, code) =
1482 let val ss = ST.fp(stack, CB.registerNum fs)
1483 val _ = ST.push(stack, CB.registerNum fd)
1484 val code = I.fldl(ST ss)::code
1485 in genCopy(copies, code) end
1486
1487 (* perform the renaming; it must be done in parallel! *)
1488 fun renaming(renames) =
1489 let val ss = map (fn (_,fs) =>
1490 ST.fp(stack,CB.registerNum fs)) renames
1491 in ListPair.app (fn ((fd,_),ss) =>
1492 ST.set(stack,ss,CB.registerNum fd))
1493 (renames, ss)
1494 end
1495
1496 (* val _ = if debug then
1497 (ListPair.app (fn (fd, fs) =>
1498 pr(fregToString(regmap fd)^"<-"^
1499 fregToString(regmap fs)^" ")
1500 ) (dst, src);
1501 pr "\n")
1502 else () *)
1503
1504 val (copies, renames) = loop(dst, src, [], [])
1505 val code = genCopy(copies, code)
1506 in renaming renames;
1507 case tmp of
1508 SOME(I.FPR f) =>
1509 (if debug andalso debugDead
1510 then pr("KILLING tmp "^fregToString f^"\n")
1511 else ();
1512 ST.kill(stack, f)
1513 )
1514 | _ => ();
1515 DONE code
1516 end
1517 | fcopy _ = error "fcopy"
1518
1519 fun call(instr, return) = let
1520 val code = mark(I.INSTR instr, an)::code
1521 val returnSet = SL.return(SL.uniq(getCell return))
1522 in
1523 case returnSet of
1524 [] => ()
1525 | [r] => ST.push(stack, CB.registerNum r)
1526 | _ =>
1527 error "can't return more than one fp argument (yet)";
1528 KILL_THE_DEAD(List.filter isDead returnSet, code)
1529 end
1530 fun x86trans instr =
1531 (case instr
1532 of I.FMOVE x => (log(); fmove x)
1533 | I.FBINOP x => (log(); fbinop x)
1534 | I.FIBINOP x => (log(); fibinop x)
1535 | I.FUNOP x => (log(); funop x)
1536 | I.FILOAD x => (log(); fiload x)
1537 | I.FCMP x => (log(); fcmp x)
1538
1539 (* handle calling convention *)
1540 | I.CALL{return, ...} => (log(); call(instr,return))
1541
1542 (*
1543 * Catch instructions that absolutely
1544 * should not have been generated at this point.
1545 *)
1546 | (I.FLD1 | I.FLDL2E | I.FLDLG2 | I.FLDLN2 | I.FLDPI |
1547 I.FLDZ | I.FLDL _ | I.FLDS _ | I.FLDT _ |
1548 I.FILD _ | I.FILDL _ | I.FILDLL _ |
1549 I.FENV _ | I.FBINARY _ | I.FIBINARY _ | I.FUNARY _ |
1550 I.FUCOMPP | I.FUCOM _ | I.FUCOMP _ | I.FCOMPP | I.FXCH _ |
1551 I.FCOMI _ | I.FCOMIP _ | I.FUCOMI _ | I.FUCOMIP _ |
1552 I.FSTPL _ | I.FSTPS _ | I.FSTPT _ | I.FSTL _ | I.FSTS _
1553 ) => bug("Illegal FP instructions")
1554
1555 (* Other instructions are untouched *)
1556 | instr => FINISH(mark(I.INSTR instr, an)::code)
1557 (*esac*))
1558 in
1559 case instr
1560 of I.ANNOTATION{a,i} =>
1561 trans(stamp, i, a::an, rest, dead, lastUses, code)
1562 | I.COPY{k=CB.FP, ...} => (log(); fcopy instr)
1563 | I.LIVE _ => DONE(mark(instr, an)::code)
1564 | I.INSTR instr => x86trans(instr)
1565 | _ => FINISH(mark(instr, an)::code)
1566 end (* trans *)
1567
1568 (*
1569 * Check the translation result to see if it matches the original
1570 * code.
1571 *)
1572 fun checkTranslation(stackIn, stackOut, insns) =
1573 let val n = ref(ST.depth stackIn)
1574 fun push() = n := !n + 1
1575 fun pop() = n := !n - 1
1576 fun scan(I.INSTR(I.FBINARY{binOp, ...})) =
1577 (case binOp of
1578 ( I.FADDP | I.FSUBP | I.FSUBRP | I.FMULP
1579 | I.FDIVP | I.FDIVRP) => pop()
1580 | _ => ()
1581 )
1582 | scan(I.INSTR(I.FIBINARY{binOp, ...})) = ()
1583 | scan(I.INSTR(I.FUNARY I.FPTAN)) = push()
1584 | scan(I.INSTR(I.FUNARY _)) = ()
1585 | scan(I.INSTR(I.FLDL(I.ST n))) = push()
1586 | scan(I.INSTR(I.FLDL mem)) = push()
1587 | scan(I.INSTR(I.FLDS mem)) = push()
1588 | scan(I.INSTR(I.FLDT mem)) = push()
1589 | scan(I.INSTR(I.FSTL(I.ST n))) = ()
1590 | scan(I.INSTR(I.FSTPL(I.ST n))) = pop()
1591 | scan(I.INSTR(I.FSTL mem)) = ()
1592 | scan(I.INSTR(I.FSTS mem)) = ()
1593 | scan(I.INSTR(I.FSTPL mem)) = pop()
1594 | scan(I.INSTR(I.FSTPS mem)) = pop()
1595 | scan(I.INSTR(I.FSTPT mem)) = pop()
1596 | scan(I.INSTR(I.FXCH{opnd=i,...})) = ()
1597 | scan(I.INSTR(I.FUCOM _)) = ()
1598 | scan(I.INSTR(I.FUCOMP _)) = pop()
1599 | scan(I.INSTR(I.FUCOMPP)) = (pop(); pop())
1600 | scan(I.INSTR(I.FILD mem)) = push()
1601 | scan(I.INSTR(I.FILDL mem)) = push()
1602 | scan(I.INSTR(I.FILDLL mem)) = push()
1603 | scan(I.INSTR(I.CALL{return, ...})) =
1604 (n := 0; (* clear the stack *)
1605 (* Simulate the pushing of arguments *)
1606 let val returnSet = SL.return(SL.uniq(getCell return))
1607 in app (fn _ => push()) returnSet
1608 end
1609 )
1610 | scan _ = ()
1611 val _ = app scan (rev insns);
1612 val n = !n
1613 val m = ST.depth stackOut
1614 in
1615 if n <> m then
1616 (dump(insns);
1617 bug("Bad translation n="^i2s n^ " expected="^i2s m^"\n")
1618 )
1619 else ()
1620 end
1621
1622
1623 (* Dump the initial code *)
1624 val _ = if debug andalso !debugOn then
1625 (pr("-------- block "^i2s blknum^" ----"^
1626 celllistToString liveIn^" "^
1627 ST.stackToString stackIn^"\n");
1628 dump (!insns);
1629 pr("succ=");
1630 app (fn b => pr(i2s b^" ")) (#succ cfg blknum);
1631 pr("\n")
1632 )
1633 else ()
1634
1635 (* Compute the last uses *)
1636 val lastUse = computeLastUse(blknum, insns, liveOut)
1637
1638 (* Rewrite the code *)
1639 val (stamp, insns') = loop(stamp, rev(!insns), lastUse, code)
1640
1641 (* Insert shuffle code at the end if necessary *)
1642 val insns' = shuffleOut(stack, insns', blknum, block, liveOut)
1643
1644 (* Dump translation *)
1645 val _ = if debug andalso !debugOn then
1646 (pr("-------- translation "^i2s blknum^"----"^
1647 celllistToString liveIn^" "^
1648 ST.stackToString stackIn^"\n");
1649 dump insns';
1650 pr("-------- done "^i2s blknum^"----"^
1651 celllistToString liveOut^" "^
1652 ST.stackToString stack^"\n")
1653 )
1654 else ()
1655
1656 (* Check if things are okay *)
1657 val _ = if debug andalso sanityCheck then
1658 checkTranslation(stackIn, stack, insns')
1659 else ()
1660
1661 in insns := insns'; (* update the instructions *)
1662 stamp
1663 end (* process *)
1664
1665 in (* Translate all blocks *)
1666 stamp := C.firstPseudo;
1667 #forall_nodes cfg rewriteAllBlocks;
1668 (* If we found critical edges, then we have to split them... *)
1669 if IntHashTable.numItems edgesToSplit = 0 then Cfg
1670 else repairCriticalEdges(Cfg)
1671 end
1672 end (* functor *)
1673
1674 end (* local *)