Debian Codegraph @

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

raw
1 (* x86.sml
2 *
3 * COPYRIGHT (c) 1998 Bell Laboratories.
4 *
5 * This is a revised version that takes into account of
6 * the extended x86 instruction set, and has better handling of
7 * non-standard types. I've factored out the integer/floating point
8 * comparison code, added optimizations for conditional moves.
9 * The latter generates SETcc and CMOVcc (Pentium Pro only) instructions.
10 * To avoid problems, I have tried to incorporate as much of
11 * Lal's original magic incantations as possible.
12 *
13 * Some changes:
14 *
15 * 1. REMU/REMS are now supported
16 * 2. COND is supported by generating SETcc and/or CMOVcc; this
17 * may require at least a Pentium II to work.
18 * 3. Division by a constant has been optimized. Division by
19 * a power of 2 generates SHRL or SARL.
20 * 4. Better addressing mode selection has been implemented. This should
21 * improve array indexing on SML/NJ.
22 * 5. Generate testl/testb instead of andl whenever appropriate. This
23 * is recommended by the Intel Optimization Guide and seems to improve
24 * boxity tests on SML/NJ.
25 *
26 * More changes for floating point:
27 * A new mode is implemented which generates pseudo 3-address instructions
28 * for floating point. These instructions are register allocated the
29 * normal way, with the virtual registers mapped onto a set of pseudo
30 * %fp registers. These registers are then mapped onto the %st registers
31 * with a new postprocessing phase.
32 *
33 * -- Allen
34 *)
35
36 functor X86
37 (structure X86Instr : X86INSTR
38 structure MLTreeUtils : MLTREE_UTILS (* where T = X86Instr.T *)
39 where type T.Basis.cond = X86Instr.T.Basis.cond
40 and type T.Basis.div_rounding_mode = X86Instr.T.Basis.div_rounding_mode
41 and type T.Basis.ext = X86Instr.T.Basis.ext
42 and type T.Basis.fcond = X86Instr.T.Basis.fcond
43 and type T.Basis.rounding_mode = X86Instr.T.Basis.rounding_mode
44 and type T.Constant.const = X86Instr.T.Constant.const
45 and type ('s,'r,'f,'c) T.Extension.ccx = ('s,'r,'f,'c) X86Instr.T.Extension.ccx
46 and type ('s,'r,'f,'c) T.Extension.fx = ('s,'r,'f,'c) X86Instr.T.Extension.fx
47 and type ('s,'r,'f,'c) T.Extension.rx = ('s,'r,'f,'c) X86Instr.T.Extension.rx
48 and type ('s,'r,'f,'c) T.Extension.sx = ('s,'r,'f,'c) X86Instr.T.Extension.sx
49 and type T.I.div_rounding_mode = X86Instr.T.I.div_rounding_mode
50 and type T.Region.region = X86Instr.T.Region.region
51 and type T.ccexp = X86Instr.T.ccexp
52 and type T.fexp = X86Instr.T.fexp
53 (* and type T.labexp = X86Instr.T.labexp *)
54 and type T.mlrisc = X86Instr.T.mlrisc
55 and type T.oper = X86Instr.T.oper
56 and type T.rep = X86Instr.T.rep
57 and type T.rexp = X86Instr.T.rexp
58 and type T.stm = X86Instr.T.stm
59 structure ExtensionComp : MLTREE_EXTENSION_COMP (* where I = X86Instr and T = X86Instr.T *)
60 where type I.addressing_mode = X86Instr.addressing_mode
61 and type I.ea = X86Instr.ea
62 and type I.instr = X86Instr.instr
63 and type I.instruction = X86Instr.instruction
64 and type I.operand = X86Instr.operand
65 where type T.Basis.cond = X86Instr.T.Basis.cond
66 and type T.Basis.div_rounding_mode = X86Instr.T.Basis.div_rounding_mode
67 and type T.Basis.ext = X86Instr.T.Basis.ext
68 and type T.Basis.fcond = X86Instr.T.Basis.fcond
69 and type T.Basis.rounding_mode = X86Instr.T.Basis.rounding_mode
70 and type T.Constant.const = X86Instr.T.Constant.const
71 and type ('s,'r,'f,'c) T.Extension.ccx = ('s,'r,'f,'c) X86Instr.T.Extension.ccx
72 and type ('s,'r,'f,'c) T.Extension.fx = ('s,'r,'f,'c) X86Instr.T.Extension.fx
73 and type ('s,'r,'f,'c) T.Extension.rx = ('s,'r,'f,'c) X86Instr.T.Extension.rx
74 and type ('s,'r,'f,'c) T.Extension.sx = ('s,'r,'f,'c) X86Instr.T.Extension.sx
75 and type T.I.div_rounding_mode = X86Instr.T.I.div_rounding_mode
76 and type T.Region.region = X86Instr.T.Region.region
77 and type T.ccexp = X86Instr.T.ccexp
78 and type T.fexp = X86Instr.T.fexp
79 (* and type T.labexp = X86Instr.T.labexp *)
80 and type T.mlrisc = X86Instr.T.mlrisc
81 and type T.oper = X86Instr.T.oper
82 and type T.rep = X86Instr.T.rep
83 and type T.rexp = X86Instr.T.rexp
84 and type T.stm = X86Instr.T.stm
85 structure MLTreeStream : MLTREE_STREAM (* where T = ExtensionComp.T *)
86 where type T.Basis.cond = ExtensionComp.T.Basis.cond
87 and type T.Basis.div_rounding_mode = ExtensionComp.T.Basis.div_rounding_mode
88 and type T.Basis.ext = ExtensionComp.T.Basis.ext
89 and type T.Basis.fcond = ExtensionComp.T.Basis.fcond
90 and type T.Basis.rounding_mode = ExtensionComp.T.Basis.rounding_mode
91 and type T.Constant.const = ExtensionComp.T.Constant.const
92 and type ('s,'r,'f,'c) T.Extension.ccx = ('s,'r,'f,'c) ExtensionComp.T.Extension.ccx
93 and type ('s,'r,'f,'c) T.Extension.fx = ('s,'r,'f,'c) ExtensionComp.T.Extension.fx
94 and type ('s,'r,'f,'c) T.Extension.rx = ('s,'r,'f,'c) ExtensionComp.T.Extension.rx
95 and type ('s,'r,'f,'c) T.Extension.sx = ('s,'r,'f,'c) ExtensionComp.T.Extension.sx
96 and type T.I.div_rounding_mode = ExtensionComp.T.I.div_rounding_mode
97 and type T.Region.region = ExtensionComp.T.Region.region
98 and type T.ccexp = ExtensionComp.T.ccexp
99 and type T.fexp = ExtensionComp.T.fexp
100 (* and type T.labexp = ExtensionComp.T.labexp *)
101 and type T.mlrisc = ExtensionComp.T.mlrisc
102 and type T.oper = ExtensionComp.T.oper
103 and type T.rep = ExtensionComp.T.rep
104 and type T.rexp = ExtensionComp.T.rexp
105 and type T.stm = ExtensionComp.T.stm
106 datatype arch = Pentium | PentiumPro | PentiumII | PentiumIII
107 val arch : arch ref
108 val cvti2f :
109 {ty: X86Instr.T.ty,
110 src: X86Instr.operand,
111 (* source operand, guaranteed to be non-memory! *)
112 an: Annotations.annotations ref (* cluster annotations *)
113 } ->
114 {instrs : X86Instr.instruction list,(* the instructions *)
115 tempMem: X86Instr.operand, (* temporary for CVTI2F *)
116 cleanup: X86Instr.instruction list (* cleanup code *)
117 }
118 (* When the following flag is set, we allocate floating point registers
119 * directly on the floating point stack
120 *)
121 val fast_floating_point : bool ref
122 ) : sig include MLTREECOMP
123 val rewriteMemReg : bool
124 end =
125 struct
126 val rewriteMemReg = true (* should we rewrite memRegs *)
127 val enableFastFPMode = true (* set this to false to disable the mode *)
128
129 structure I = X86Instr
130 structure T = I.T
131 structure TS = ExtensionComp.TS
132 structure C = I.C
133 structure Shuffle = Shuffle(I)
134 structure W32 = Word32
135 structure A = MLRiscAnnotations
136 structure CFG = ExtensionComp.CFG
137 structure CB = CellsBasis
138
139 type instrStream = (I.instruction,C.cellset,CFG.cfg) TS.stream
140 type mltreeStream = (T.stm,T.mlrisc list,CFG.cfg) TS.stream
141
142 datatype kind = REAL | INTEGER
143
144 structure Gen = MLTreeGen
145 (structure T = T
146 structure Cells = C
147 val intTy = 32
148 val naturalWidths = [32]
149 datatype rep = SE | ZE | NEITHER
150 val rep = NEITHER
151 )
152
153 fun error msg = MLRiscErrorMsg.error("X86",msg)
154
155 (* Should we perform automatic MemReg translation?
156 * If this is on, we can avoid doing RewritePseudo phase entirely.
157 *)
158 val rewriteMemReg = rewriteMemReg
159
160 (* The following hardcoded *)
161 fun isMemReg r = rewriteMemReg andalso
162 let val r = CB.registerNum r
163 in r >= 8 andalso r < 32
164 end
165 fun isFMemReg r = if enableFastFPMode andalso !fast_floating_point
166 then let val r = CB.registerNum r
167 in r >= 8 andalso r < 32 end
168 else true
169 val isAnyFMemReg = List.exists (fn r =>
170 let val r = CB.registerNum r
171 in r >= 8 andalso r < 32 end
172 )
173
174 val ST0 = C.ST 0
175 val ST7 = C.ST 7
176
177 val opcodes8 = {INC=I.INCB,DEC=I.DECB,ADD=I.ADDB,SUB=I.SUBB,
178 NOT=I.NOTB,NEG=I.NEGB,
179 SHL=I.SHLB,SHR=I.SHRB,SAR=I.SARB,
180 OR=I.ORB,AND=I.ANDB,XOR=I.XORB}
181 val opcodes16 = {INC=I.INCW,DEC=I.DECW,ADD=I.ADDW,SUB=I.SUBW,
182 NOT=I.NOTW,NEG=I.NEGW,
183 SHL=I.SHLW,SHR=I.SHRW,SAR=I.SARW,
184 OR=I.ORW,AND=I.ANDW,XOR=I.XORW}
185 val opcodes32 = {INC=I.INCL,DEC=I.DECL,ADD=I.ADDL,SUB=I.SUBL,
186 NOT=I.NOTL,NEG=I.NEGL,
187 SHL=I.SHLL,SHR=I.SHRL,SAR=I.SARL,
188 OR=I.ORL,AND=I.ANDL,XOR=I.XORL}
189
190 (*
191 * The code generator
192 *)
193 fun selectInstructions
194 (instrStream as
195 TS.S.STREAM{emit=emitInstruction,defineLabel,entryLabel,pseudoOp,
196 annotation,getAnnotations,beginCluster,endCluster,exitBlock,comment,...}) =
197 let
198 val emit = emitInstruction o I.INSTR
199 exception EA
200
201 (* label where a trap is generated -- one per cluster *)
202 val trapLabel = ref (NONE: (I.instruction * Label.label) option)
203
204 (* flag floating point generation *)
205 val floatingPointUsed = ref false
206
207 (* effective address of an integer register *)
208 fun IntReg r = if isMemReg r then I.MemReg r else I.Direct r
209 and RealReg r = if isFMemReg r then I.FDirect r else I.FPR r
210
211 (* Add an overflow trap *)
212 fun trap() =
213 let
214 val jmp =
215 case !trapLabel of
216 NONE => let val label = Label.label "trap" ()
217 val jmp =
218 I.ANNOTATION{i=I.jcc{cond=I.O,
219 opnd=I.ImmedLabel(T.LABEL label)},
220 a=MLRiscAnnotations.BRANCHPROB (Probability.unlikely)}
221 in trapLabel := SOME(jmp, label); jmp end
222 | SOME(jmp, _) => jmp
223 in emitInstruction jmp end
224
225 val newReg = C.newReg
226 val newFreg = C.newFreg
227
228 fun fsize 32 = I.FP32
229 | fsize 64 = I.FP64
230 | fsize 80 = I.FP80
231 | fsize _ = error "fsize"
232
233 (* mark an expression with a list of annotations *)
234 fun mark'(i,[]) = emitInstruction(i)
235 | mark'(i,a::an) = mark'(I.ANNOTATION{i=i,a=a},an)
236
237 (* annotate an expression and emit it *)
238 fun mark(i,an) = mark'(I.INSTR i,an)
239
240 val emits = app emitInstruction
241
242 (* emit parallel copies for integers
243 * Translates parallel copies that involve memregs into
244 * individual copies.
245 *)
246 fun copy([], [], an) = ()
247 | copy(dst, src, an) =
248 let fun mvInstr{dst as I.MemReg rd, src as I.MemReg rs} =
249 if CB.sameColor(rd,rs) then [] else
250 let val tmpR = I.Direct(newReg())
251 in [I.move{mvOp=I.MOVL, src=src, dst=tmpR},
252 I.move{mvOp=I.MOVL, src=tmpR, dst=dst}]
253 end
254 | mvInstr{dst=I.Direct rd, src=I.Direct rs} =
255 if CB.sameColor(rd,rs) then []
256 else [I.COPY{k=CB.GP, sz=32, dst=[rd], src=[rs], tmp=NONE}]
257 | mvInstr{dst, src} = [I.move{mvOp=I.MOVL, src=src, dst=dst}]
258 in
259 emits (Shuffle.shuffle{mvInstr=mvInstr, ea=IntReg}
260 {tmp=SOME(I.Direct(newReg())),
261 dst=dst, src=src})
262 end
263
264 (* conversions *)
265 val itow = Word.fromInt
266 val wtoi = Word.toInt
267 fun toInt32 i = T.I.toInt32(32, i)
268 val w32toi32 = Word32.toLargeIntX
269 val i32tow32 = Word32.fromLargeInt
270
271 (* One day, this is going to bite us when precision(LargeInt)>32 *)
272 fun wToInt32 w = Int32.fromLarge(Word32.toLargeIntX w)
273
274 (* some useful registers *)
275 val eax = I.Direct(C.eax)
276 val ecx = I.Direct(C.ecx)
277 val edx = I.Direct(C.edx)
278
279 fun immedLabel lab = I.ImmedLabel(T.LABEL lab)
280
281 (* Is the expression zero? *)
282 fun isZero(T.LI z) = z = 0
283 | isZero(T.MARK(e,a)) = isZero e
284 | isZero _ = false
285 (* Does the expression set the zero bit?
286 * WARNING: we assume these things are not optimized out!
287 *)
288 fun setZeroBit(T.ANDB _) = true
289 | setZeroBit(T.ORB _) = true
290 | setZeroBit(T.XORB _) = true
291 | setZeroBit(T.SRA _) = true
292 | setZeroBit(T.SRL _) = true
293 | setZeroBit(T.SLL _) = true
294 | setZeroBit(T.SUB _) = true
295 | setZeroBit(T.ADDT _) = true
296 | setZeroBit(T.SUBT _) = true
297 | setZeroBit(T.MARK(e, _)) = setZeroBit e
298 | setZeroBit _ = false
299
300 fun setZeroBit2(T.ANDB _) = true
301 | setZeroBit2(T.ORB _) = true
302 | setZeroBit2(T.XORB _) = true
303 | setZeroBit2(T.SRA _) = true
304 | setZeroBit2(T.SRL _) = true
305 | setZeroBit2(T.SLL _) = true
306 | setZeroBit2(T.ADD(32, _, _)) = true (* can't use leal! *)
307 | setZeroBit2(T.SUB _) = true
308 | setZeroBit2(T.ADDT _) = true
309 | setZeroBit2(T.SUBT _) = true
310 | setZeroBit2(T.MARK(e, _)) = setZeroBit2 e
311 | setZeroBit2 _ = false
312
313 (* emit parallel copies for floating point
314 * Normal version.
315 *)
316 fun fcopy'(fty, [], [], _) = ()
317 | fcopy'(fty, dst as [_], src as [_], an) =
318 mark'(I.COPY{k=CB.FP, sz=fty, dst=dst,src=src,tmp=NONE}, an)
319 | fcopy'(fty, dst, src, an) =
320 mark'(I.COPY{k=CB.FP, sz=fty, dst=dst,src=src,tmp=SOME(I.FDirect(newFreg()))}, an)
321
322 (* emit parallel copies for floating point.
323 * Fast version.
324 * Translates parallel copies that involve memregs into
325 * individual copies.
326 *)
327
328 fun fcopy''(fty, [], [], _) = ()
329 | fcopy''(fty, dst, src, an) =
330 if true orelse isAnyFMemReg dst orelse isAnyFMemReg src then
331 let val fsize = fsize fty
332 fun mvInstr{dst, src} = [I.fmove{fsize=fsize, src=src, dst=dst}]
333 in
334 emits (Shuffle.shuffle{mvInstr=mvInstr, ea=RealReg}
335 {tmp=case dst of
336 [_] => NONE
337 | _ => SOME(I.FPR(newReg())),
338 dst=dst, src=src})
339 end
340 else
341 mark'(I.COPY{k=CB.FP, sz=fty, dst=dst,
342 src=src,tmp=
343 case dst of
344 [_] => NONE
345 | _ => SOME(I.FPR(newFreg()))}, an)
346
347 fun fcopy x = if enableFastFPMode andalso !fast_floating_point
348 then fcopy'' x else fcopy' x
349
350 (* Translates MLTREE condition code to x86 condition code *)
351 fun cond T.LT = I.LT | cond T.LTU = I.B
352 | cond T.LE = I.LE | cond T.LEU = I.BE
353 | cond T.EQ = I.EQ | cond T.NE = I.NE
354 | cond T.GE = I.GE | cond T.GEU = I.AE
355 | cond T.GT = I.GT | cond T.GTU = I.A
356 | cond cc = error(concat["cond(", T.Basis.condToString cc, ")"])
357
358 fun zero dst = emit(I.BINARY{binOp=I.XORL, src=dst, dst=dst})
359
360 (* Move and annotate *)
361 fun move'(src as I.Direct s, dst as I.Direct d, an) =
362 if CB.sameColor(s,d) then ()
363 else mark'(I.COPY{k=CB.GP, sz=32, dst=[d], src=[s], tmp=NONE}, an)
364 | move'(I.Immed 0, dst as I.Direct d, an) =
365 mark(I.BINARY{binOp=I.XORL, src=dst, dst=dst}, an)
366 | move'(src, dst, an) = mark(I.MOVE{mvOp=I.MOVL, src=src, dst=dst}, an)
367
368 (* Move only! *)
369 fun move(src, dst) = move'(src, dst, [])
370
371 val readonly = I.Region.readonly
372
373 (*
374 * Compute an effective address.
375 *)
376 fun address(ea, mem) = let
377 (* Keep building a bigger and bigger effective address expressions
378 * The input is a list of trees
379 * b -- base
380 * i -- index
381 * s -- scale
382 * d -- immed displacement
383 *)
384 fun doEA([], b, i, s, d) = makeAddressingMode(b, i, s, d)
385 | doEA(t::trees, b, i, s, d) =
386 (case t of
387 T.LI n => doEAImmed(trees, toInt32 n, b, i, s, d)
388 | T.CONST _ => doEALabel(trees, t, b, i, s, d)
389 | T.LABEL _ => doEALabel(trees, t, b, i, s, d)
390 | T.LABEXP le => doEALabel(trees, le, b, i, s, d)
391 | T.ADD(32, t1, t2 as T.REG(_,r)) =>
392 if isMemReg r then doEA(t2::t1::trees, b, i, s, d)
393 else doEA(t1::t2::trees, b, i, s, d)
394 | T.ADD(32, t1, t2) => doEA(t1::t2::trees, b, i, s, d)
395 | T.SUB(32, t1, T.LI n) =>
396 doEA(t1::T.LI(T.I.NEG(32,n))::trees, b, i, s, d)
397 | T.SLL(32, t1, T.LI n) => let
398 val n = T.I.toInt(32, n)
399 in
400 case n
401 of 0 => displace(trees, t1, b, i, s, d)
402 | 1 => indexed(trees, t1, t, 1, b, i, s, d)
403 | 2 => indexed(trees, t1, t, 2, b, i, s, d)
404 | 3 => indexed(trees, t1, t, 3, b, i, s, d)
405 | _ => displace(trees, t, b, i, s, d)
406 end
407 | t => displace(trees, t, b, i, s, d)
408 )
409
410 (* Add an immed constant *)
411 and doEAImmed(trees, 0, b, i, s, d) = doEA(trees, b, i, s, d)
412 | doEAImmed(trees, n, b, i, s, I.Immed m) =
413 doEA(trees, b, i, s, I.Immed(n+m))
414 | doEAImmed(trees, n, b, i, s, I.ImmedLabel le) =
415 doEA(trees, b, i, s,
416 I.ImmedLabel(T.ADD(32,le,T.LI(T.I.fromInt32(32, n)))))
417 | doEAImmed(trees, n, b, i, s, _) = error "doEAImmed"
418
419 (* Add a label expression *)
420 and doEALabel(trees, le, b, i, s, I.Immed 0) =
421 doEA(trees, b, i, s, I.ImmedLabel le)
422 | doEALabel(trees, le, b, i, s, I.Immed m) =
423 doEA(trees, b, i, s,
424 I.ImmedLabel(T.ADD(32,le,T.LI(T.I.fromInt32(32, m))))
425 handle Overflow => error "doEALabel: constant too large")
426 | doEALabel(trees, le, b, i, s, I.ImmedLabel le') =
427 doEA(trees, b, i, s, I.ImmedLabel(T.ADD(32,le,le')))
428 | doEALabel(trees, le, b, i, s, _) = error "doEALabel"
429
430 and makeAddressingMode (NONE, NONE, _, disp) = disp
431 | makeAddressingMode (SOME base, NONE, _, disp) =
432 I.Displace{base=base, disp=disp, mem=mem}
433 | makeAddressingMode (base, SOME index, scale, disp) =
434 I.Indexed{base=base, index=index, scale=scale,
435 disp=disp, mem=mem}
436
437 (* generate code for tree and ensure that it is not in %esp *)
438 and exprNotEsp tree =
439 let val r = expr tree
440 in if CB.sameColor(r, C.esp) then
441 let val tmp = newReg()
442 in move(I.Direct r, I.Direct tmp); tmp end
443 else r
444 end
445
446 (* Add a base register *)
447 and displace(trees, t, NONE, i, s, d) = (* no base yet *)
448 doEA(trees, SOME(expr t), i, s, d)
449 | displace(trees, t, b as SOME base, NONE, _, d) = (* no index *)
450 (* make t the index, but make sure that it is not %esp! *)
451 let val i = expr t
452 in if CB.sameColor(i, C.esp) then
453 (* swap base and index *)
454 if CB.sameColor(base, C.esp) then
455 doEA(trees, SOME i, b, 0, d)
456 else (* base and index = %esp! *)
457 let val index = newReg()
458 in move(I.Direct i, I.Direct index);
459 doEA(trees, b, SOME index, 0, d)
460 end
461 else
462 doEA(trees, b, SOME i, 0, d)
463 end
464 | displace(trees, t, SOME base, i, s, d) = (* base and index *)
465 let val b = expr(T.ADD(32,T.REG(32,base),t))
466 in doEA(trees, SOME b, i, s, d) end
467
468 (* Add an indexed register *)
469 and indexed(trees, t, t0, scale, b, NONE, _, d) = (* no index yet *)
470 doEA(trees, b, SOME(exprNotEsp t), scale, d)
471 | indexed(trees, _, t0, _, NONE, i, s, d) = (* no base *)
472 doEA(trees, SOME(expr t0), i, s, d)
473 | indexed(trees, _, t0, _, SOME base, i, s, d) = (*base and index*)
474 let val b = expr(T.ADD(32, t0, T.REG(32, base)))
475 in doEA(trees, SOME b, i, s, d) end
476
477 in case doEA([ea], NONE, NONE, 0, I.Immed 0) of
478 I.Immed _ => raise EA
479 | I.ImmedLabel le => I.LabelEA le
480 | ea => ea
481 end (* address *)
482
483 (* reduce an expression into an operand *)
484 and operand(T.LI i) = I.Immed(toInt32(i))
485 | operand(x as (T.CONST _ | T.LABEL _)) = I.ImmedLabel x
486 | operand(T.LABEXP le) = I.ImmedLabel le
487 | operand(T.REG(_,r)) = IntReg r
488 | operand(T.LOAD(32,ea,mem)) = address(ea, mem)
489 | operand(t) = I.Direct(expr t)
490
491 and moveToReg(opnd) =
492 let val dst = I.Direct(newReg())
493 in move(opnd, dst); dst
494 end
495
496 and reduceOpnd(I.Direct r) = r
497 | reduceOpnd opnd =
498 let val dst = newReg()
499 in move(opnd, I.Direct dst); dst
500 end
501
502 (* ensure that the operand is either an immed or register *)
503 and immedOrReg(opnd as I.Displace _) = moveToReg opnd
504 | immedOrReg(opnd as I.Indexed _) = moveToReg opnd
505 | immedOrReg(opnd as I.MemReg _) = moveToReg opnd
506 | immedOrReg(opnd as I.LabelEA _) = moveToReg opnd
507 | immedOrReg opnd = opnd
508
509 and isImmediate(I.Immed _) = true
510 | isImmediate(I.ImmedLabel _) = true
511 | isImmediate _ = false
512
513 and regOrMem opnd = if isImmediate opnd then moveToReg opnd else opnd
514
515 and isMemOpnd opnd =
516 (case opnd of
517 I.Displace _ => true
518 | I.Indexed _ => true
519 | I.MemReg _ => true
520 | I.LabelEA _ => true
521 | I.FDirect f => true
522 | _ => false
523 )
524
525 (*
526 * Compute an integer expression and put the result in
527 * the destination register rd.
528 *)
529 and doExpr(exp, rd : CB.cell, an) =
530 let val rdOpnd = IntReg rd
531
532 fun equalRd(I.Direct r) = CB.sameColor(r, rd)
533 | equalRd(I.MemReg r) = CB.sameColor(r, rd)
534 | equalRd _ = false
535
536 (* Emit a binary operator. If the destination is
537 * a memReg, do something smarter.
538 *)
539 fun genBinary(binOp, opnd1, opnd2) =
540 if isMemReg rd andalso
541 (isMemOpnd opnd1 orelse isMemOpnd opnd2) orelse
542 equalRd(opnd2)
543 then
544 let val tmpR = newReg()
545 val tmp = I.Direct tmpR
546 in move(opnd1, tmp);
547 mark(I.BINARY{binOp=binOp, src=opnd2, dst=tmp}, an);
548 move(tmp, rdOpnd)
549 end
550 else
551 (move(opnd1, rdOpnd);
552 mark(I.BINARY{binOp=binOp, src=opnd2, dst=rdOpnd}, an)
553 )
554
555 (* Generate a binary operator; it may commute *)
556 fun binaryComm(binOp, e1, e2) =
557 let val (opnd1, opnd2) =
558 case (operand e1, operand e2) of
559 (x as I.Immed _, y) => (y, x)
560 | (x as I.ImmedLabel _, y) => (y, x)
561 | (x, y as I.Direct _) => (y, x)
562 | (x, y) => (x, y)
563 in genBinary(binOp, opnd1, opnd2)
564 end
565
566 (* Generate a binary operator; non-commutative *)
567 fun binary(binOp, e1, e2) =
568 genBinary(binOp, operand e1, operand e2)
569
570 (* Generate a unary operator *)
571 fun unary(unOp, e) =
572 let val opnd = operand e
573 in if isMemReg rd andalso isMemOpnd opnd then
574 let val tmp = I.Direct(newReg())
575 in move(opnd, tmp); move(tmp, rdOpnd)
576 end
577 else move(opnd, rdOpnd);
578 mark(I.UNARY{unOp=unOp, opnd=rdOpnd}, an)
579 end
580
581 (* Generate shifts; the shift
582 * amount must be a constant or in %ecx *)
583 fun shift(opcode, e1, e2) =
584 let val (opnd1, opnd2) = (operand e1, operand e2)
585 in case opnd2 of
586 I.Immed _ => genBinary(opcode, opnd1, opnd2)
587 | _ =>
588 if equalRd(opnd2) then
589 let val tmpR = newReg()
590 val tmp = I.Direct tmpR
591 in move(opnd1, tmp);
592 move(opnd2, ecx);
593 mark(I.BINARY{binOp=opcode, src=ecx, dst=tmp},an);
594 move(tmp, rdOpnd)
595 end
596 else
597 (move(opnd1, rdOpnd);
598 move(opnd2, ecx);
599 mark(I.BINARY{binOp=opcode, src=ecx, dst=rdOpnd},an)
600 )
601 end
602
603 (* Division or remainder: divisor must be in %edx:%eax pair *)
604 fun divrem (signed, e1, e2, resultReg) =
605 let val (opnd1, opnd2) = (operand e1, operand e2)
606 val _ = move(opnd1, eax)
607 val oper = if signed then (emit(I.CDQ); I.IDIVL1)
608 else (zero edx; I.DIVL1)
609 in mark(I.MULTDIV{multDivOp=oper, src=regOrMem opnd2},an);
610 move(resultReg, rdOpnd)
611 (* NOTE: on the x86, the IDIV instruction traps on overflow
612 if overflow then trap() else ()
613 *)
614 end
615
616 (* division with rounding towards negative infinity *)
617 fun divinf0 (e1, e2) = let
618 val o1 = operand e1
619 val o2 = operand e2
620 val l = Label.anon ()
621 in
622 move (o1, eax);
623 emit I.CDQ;
624 mark (I.MULTDIV { multDivOp = I.IDIVL1, src = regOrMem o2 },
625 an);
626 (* NOTE: on the x86, the IDIV instruction traps on overflow
627 if overflow then trap() else ();
628 *)
629 app emit [I.CMPL { lsrc = edx, rsrc = I.Immed 0 },
630 I.JCC { cond = I.EQ, opnd = immedLabel l },
631 I.BINARY { binOp = I.XORL,
632 src = regOrMem o2,
633 dst = edx },
634 I.JCC { cond = I.GE, opnd = immedLabel l },
635 I.UNARY { unOp = I.DECL, opnd = eax }];
636 defineLabel l;
637 move (eax, rdOpnd)
638 end
639
640 (* analyze for power-of-two-ness *)
641 fun analyze i' = let
642 val i = toInt32 i'
643 in
644 let val (isneg, a, w) =
645 if i >= 0 then (false, i, T.I.toWord32 (32, i'))
646 else (true, ~i, T.I.toWord32 (32, T.I.NEG (32, i')))
647 fun log2 (0w1, p) = p
648 | log2 (w, p) = log2 (W32.>> (w, 0w1), p + 1)
649 in
650 if w > 0w1 andalso W32.andb (w - 0w1, w) = 0w0 then
651 (i, SOME (isneg, a,
652 T.LI (T.I.fromInt32 (32, log2 (w, 0)))))
653 else (i, NONE)
654 end handle _ => (i, NONE)
655 end
656
657 (* Division by a power of two when rounding to neginf is the
658 * same as an arithmetic right shift. *)
659 fun divinf (e1, e2 as T.LI n') =
660 (case analyze n' of
661 (_, NONE) => divinf0 (e1, e2)
662 | (_, SOME (false, _, p)) =>
663 shift (I.SARL, T.REG (32, expr e1), p)
664 | (_, SOME (true, _, p)) => let
665 val reg = expr e1
666 in
667 emit(I.UNARY { unOp = I.NEGL, opnd = I.Direct reg });
668 shift (I.SARL, T.REG (32, reg), p)
669 end)
670 | divinf (e1, e2) = divinf0 (e1, e2)
671
672 fun reminf0 (e1, e2) = let
673 val o1 = operand e1
674 val o2 = operand e2
675 val l = Label.anon ()
676 in
677 move (o1, eax);
678 emit I.CDQ;
679 mark (I.MULTDIV { multDivOp = I.IDIVL1, src = regOrMem o2 },
680 an);
681 app emit [I.CMPL { lsrc = edx, rsrc = I.Immed 0 },
682 I.JCC { cond = I.EQ, opnd = immedLabel l }];
683 move (edx, eax);
684 app emit [I.BINARY { binOp = I.XORL,
685 src = regOrMem o2, dst = eax },
686 I.JCC { cond = I.GE, opnd = immedLabel l },
687 I.BINARY { binOp = I.ADDL,
688 src = regOrMem o2, dst = edx }];
689 defineLabel l;
690 move (edx, rdOpnd)
691 end
692
693 (* n mod (power-of-2) corresponds to a bitmask (AND).
694 * If the power is negative, then we must first negate
695 * the argument and then again negate the result. *)
696 fun reminf (e1, e2 as T.LI n') =
697 (case analyze n' of
698 (_, NONE) => reminf0 (e1, e2)
699 | (_, SOME (false, a, _)) =>
700 binaryComm (I.ANDL, e1,
701 T.LI (T.I.fromInt32 (32, a - 1)))
702 | (_, SOME (true, a, _)) => let
703 val r1 = expr e1
704 val o1 = I.Direct r1
705 in
706 emit (I.UNARY { unOp = I.NEGL, opnd = o1 });
707 emit (I.BINARY { binOp = I.ANDL,
708 src = I.Immed (a - 1),
709 dst = o1 });
710 unary (I.NEGL, T.REG (32, r1))
711 end)
712 | reminf (e1, e2) = reminf0 (e1, e2)
713
714 (* Optimize the special case for division *)
715 fun divide (signed, e1, e2 as T.LI n') =
716 (case analyze n' of
717 (n, SOME (isneg, a, p)) =>
718 if signed then
719 let val label = Label.anon ()
720 val reg1 = expr e1
721 val opnd1 = I.Direct reg1
722 in
723 if isneg then
724 emit (I.UNARY { unOp = I.NEGL,
725 opnd = opnd1 })
726 else if setZeroBit e1 then ()
727 else emit (I.CMPL { lsrc = opnd1,
728 rsrc = I.Immed 0 });
729 emit (I.JCC { cond = I.GE,
730 opnd = immedLabel label });
731 emit (if a = 2 then
732 I.UNARY { unOp = I.INCL,
733 opnd = opnd1 }
734 else
735 I.BINARY { binOp = I.ADDL,
736 src = I.Immed (a - 1),
737 dst = opnd1 });
738 defineLabel label;
739 shift (I.SARL, T.REG (32, reg1), p)
740 end
741 else shift (I.SHRL, e1, p)
742 | (n, NONE) => divrem(signed, e1, e2, eax))
743 | divide (signed, e1, e2) = divrem (signed, e1, e2, eax)
744
745 (* rem never causes overflow *)
746 fun rem (signed, e1, e2 as T.LI n') =
747 (case analyze n' of
748 (n, SOME (isneg, a, _)) =>
749 if signed then
750 (* The following logic should work uniformely
751 * for both isneg and not isneg. It only uses
752 * the absolute value (a) of the divisor.
753 * Here is the formula:
754 * let p be a power of two and a = abs(p):
755 *
756 * x % p = x - ((x < 0 ? x + a - 1 : x) & (-a))
757 *
758 * (That's what GCC seems to do.)
759 *)
760 let val r1 = expr e1
761 val o1 = I.Direct r1
762 val rt = newReg ()
763 val tmp = I.Direct rt
764 val l = Label.anon ()
765 in
766 move (o1, tmp);
767 if setZeroBit e1 then ()
768 else emit (I.CMPL { lsrc = o1,
769 rsrc = I.Immed 0 });
770 emit (I.JCC { cond = I.GE,
771 opnd = immedLabel l });
772 emit (I.BINARY { binOp = I.ADDL,
773 src = I.Immed (a - 1),
774 dst = tmp });
775 defineLabel l;
776 emit (I.BINARY { binOp = I.ANDL,
777 src = I.Immed (~a),
778 dst = tmp });
779 binary (I.SUBL, T.REG (32, r1), T.REG (32, rt))
780 end
781 else
782 if isneg then
783 (* this is really strange... *)
784 divrem (false, e1, e2, edx)
785 else
786 binaryComm (I.ANDL, e1,
787 T.LI (T.I.fromInt32 (32, n - 1)))
788 | (_, NONE) => divrem (signed, e1, e2, edx))
789 | rem(signed, e1, e2) = divrem(signed, e1, e2, edx)
790
791 (* Makes sure the destination must be a register *)
792 fun dstMustBeReg f =
793 if isMemReg rd then
794 let val tmpR = newReg()
795 val tmp = I.Direct(tmpR)
796 in f(tmpR, tmp); move(tmp, rdOpnd) end
797 else f(rd, rdOpnd)
798
799 (* unsigned integer multiplication *)
800 fun uMultiply0 (e1, e2) =
801 (* note e2 can never be (I.Direct edx) *)
802 (move(operand e1, eax);
803 mark(I.MULTDIV{multDivOp=I.MULL1,
804 src=regOrMem(operand e2)},an);
805 move(eax, rdOpnd)
806 )
807
808 fun uMultiply (e1, e2 as T.LI n') =
809 (case analyze n' of
810 (_, SOME (false, _, p)) => shift (I.SHLL, e1, p)
811 | _ => uMultiply0 (e1, e2))
812 | uMultiply (e1 as T.LI _, e2) = uMultiply (e2, e1)
813 | uMultiply (e1, e2) = uMultiply0 (e1, e2)
814
815 (* signed integer multiplication:
816 * The only forms that are allowed that also sets the
817 * OF and CF flags are:
818 *
819 * (dst) (src1) (src2)
820 * imul r32, r32/m32, imm8
821 * (dst) (src)
822 * imul r32, imm8
823 * imul r32, imm32
824 * imul r32, r32/m32
825 * Note: destination must be a register!
826 *)
827 fun multiply (e1, e2) =
828 dstMustBeReg(fn (rd, rdOpnd) =>
829 let fun doit(i1 as I.Immed _, i2 as I.Immed _) =
830 (move(i1, rdOpnd);
831 mark(I.BINARY{binOp=I.IMULL, dst=rdOpnd, src=i2},an))
832 | doit(rm, i2 as I.Immed _) = doit(i2, rm)
833 | doit(imm as I.Immed(i), rm) =
834 mark(I.MUL3{dst=rd, src1=rm, src2=i},an)
835 | doit(r1 as I.Direct _, r2 as I.Direct _) =
836 (move(r1, rdOpnd);
837 mark(I.BINARY{binOp=I.IMULL, dst=rdOpnd, src=r2},an))
838 | doit(r1 as I.Direct _, rm) =
839 (move(r1, rdOpnd);
840 mark(I.BINARY{binOp=I.IMULL, dst=rdOpnd, src=rm},an))
841 | doit(rm, r as I.Direct _) = doit(r, rm)
842 | doit(rm1, rm2) =
843 if equalRd rm2 then
844 let val tmpR = newReg()
845 val tmp = I.Direct tmpR
846 in move(rm1, tmp);
847 mark(I.BINARY{binOp=I.IMULL, dst=tmp, src=rm2},an);
848 move(tmp, rdOpnd)
849 end
850 else
851 (move(rm1, rdOpnd);
852 mark(I.BINARY{binOp=I.IMULL, dst=rdOpnd, src=rm2},an)
853 )
854 val (opnd1, opnd2) = (operand e1, operand e2)
855 in doit(opnd1, opnd2)
856 end
857 )
858
859 fun multiply_notrap (e1, e2 as T.LI n') =
860 (case analyze n' of
861 (_, SOME (isneg, _, p)) => let
862 val r1 = expr e1
863 val o1 = I.Direct r1
864 in
865 if isneg then
866 emit (I.UNARY { unOp = I.NEGL, opnd = o1 })
867 else ();
868 shift (I.SHLL, T.REG (32, r1), p)
869 end
870 | _ => multiply (e1, e2))
871 | multiply_notrap (e1 as T.LI _, e2) = multiply_notrap (e2, e1)
872 | multiply_notrap (e1, e2) = multiply (e1, e2)
873
874 (* Emit a load instruction; makes sure that the destination
875 * is a register
876 *)
877 fun genLoad(mvOp, ea, mem) =
878 dstMustBeReg(fn (_, dst) =>
879 mark(I.MOVE{mvOp=mvOp, src=address(ea, mem), dst=dst},an))
880
881 (* Generate a zero extended loads *)
882 fun load8(ea, mem) = genLoad(I.MOVZBL, ea, mem)
883 fun load16(ea, mem) = genLoad(I.MOVZWL, ea, mem)
884 fun load8s(ea, mem) = genLoad(I.MOVSBL, ea, mem)
885 fun load16s(ea, mem) = genLoad(I.MOVSWL, ea, mem)
886 fun load32(ea, mem) = genLoad(I.MOVL, ea, mem)
887 fun load64(ea, mem) = genLoad(I.MOVL, ea, mem) (* XXX64 *)
888
889 (* Generate a sign extended loads *)
890
891 (* Generate setcc instruction:
892 * semantics: MV(rd, COND(_, T.CMP(ty, cc, t1, t2), yes, no))
893 * Bug, if eax is either t1 or t2 then problem will occur!!!
894 * Note that we have to use eax as the destination of the
895 * setcc because it only works on the registers
896 * %al, %bl, %cl, %dl and %[abcd]h. The last four registers
897 * are inaccessible in 32 bit mode.
898 *)
899 fun setcc(ty, cc, t1, t2, yes, no) =
900 let val (cc, yes, no) =
901 if yes > no then (cc, yes, no)
902 else (T.Basis.negateCond cc, no, yes)
903 in (* Clear the destination first.
904 * This this because stupid SETcc
905 * only writes to the low order
906 * byte. That's Intel architecture, folks.
907 *)
908 case (yes, no, cc) of
909 (1, 0, T.LT) =>
910 let val tmp = I.Direct(expr(T.SUB(32,t1,t2)))
911 in move(tmp, rdOpnd);
912 emit(I.BINARY{binOp=I.SHRL,src=I.Immed 31,dst=rdOpnd})
913 end
914 | (1, 0, T.GT) =>
915 let val tmp = I.Direct(expr(T.SUB(32,t1,t2)))
916 in emit(I.UNARY{unOp=I.NOTL,opnd=tmp});
917 move(tmp, rdOpnd);
918 emit(I.BINARY{binOp=I.SHRL,src=I.Immed 31,dst=rdOpnd})
919 end
920 | (1, 0, _) => (* normal case *)
921 let val cc = cmp(true, ty, cc, t1, t2, [])
922 in mark(I.SET{cond=cond cc, opnd=eax}, an);
923 emit(I.BINARY{binOp=I.ANDL,src=I.Immed 255, dst=eax});
924 move(eax, rdOpnd)
925 end
926 | (C1, C2, _) =>
927 (* general case;
928 * from the Intel optimization guide p3-5
929 *)
930 let val _ = zero eax;
931 val cc = cmp(true, ty, cc, t1, t2, [])
932 fun c19 (base, scale) = let
933 val addr = I.Indexed{base=base,
934 index=C.eax,
935 scale=scale,
936 disp=I.Immed C2,
937 mem=readonly}
938 val tmpR = newReg()
939 val tmp = I.Direct tmpR
940 in emit(I.SET{cond=cond cc, opnd=eax});
941 mark(I.LEA{r32=tmpR, addr=addr}, an);
942 move(tmp, rdOpnd)
943 end
944 in
945 case C1-C2 of
946 1 => c19 (NONE, 0)
947 | 2 => c19 (NONE, 1)
948 | 3 => c19 (SOME C.eax, 1)
949 | 4 => c19 (NONE, 2)
950 | 5 => c19 (SOME C.eax, 2)
951 | 8 => c19 (NONE, 3)
952 | 9 => c19 (SOME C.eax, 3)
953 | D =>
954 (emit(I.SET{cond=cond(T.Basis.negateCond cc),
955 opnd=eax});
956 emit(I.UNARY{unOp=I.DECL, opnd=eax});
957 emit(I.BINARY{binOp=I.ANDL,
958 src=I.Immed D, dst=eax});
959 if C2 = 0 then
960 move(eax, rdOpnd)
961 else
962 let val tmpR = newReg()
963 val tmp = I.Direct tmpR
964 in mark(I.LEA{addr=
965 I.Displace{
966 base=C.eax,
967 disp=I.Immed C2,
968 mem=readonly},
969 r32=tmpR}, an);
970 move(tmp, rdOpnd)
971 end)
972 end
973 end (* setcc *)
974
975 (* Generate cmovcc instruction.
976 * on Pentium Pro and Pentium II only
977 *)
978 fun cmovcc(ty, cc, t1, t2, yes, no) =
979 let fun genCmov(dstR, _) =
980 let val _ = doExpr(no, dstR, []) (* false branch *)
981 val cc = cmp(true, ty, cc, t1, t2, []) (* compare *)
982 in mark(I.CMOV{cond=cond cc, src=regOrMem(operand yes),
983 dst=dstR}, an)
984 end
985 in dstMustBeReg genCmov
986 end
987
988 fun unknownExp exp = doExpr(Gen.compileRexp exp, rd, an)
989
990 (* Add n to rd *)
991 fun addN n =
992 let val n = operand n
993 val src = if isMemReg rd then immedOrReg n else n
994 in mark(I.BINARY{binOp=I.ADDL, src=src, dst=rdOpnd}, an) end
995
996 (* Generate addition *)
997 fun addition(e1, e2) =
998 case e1 of
999 T.REG(_,rs) => if CB.sameColor(rs,rd) then addN e2
1000 else addition1(e1,e2)
1001 | _ => addition1(e1,e2)
1002 and addition1(e1, e2) =
1003 case e2 of
1004 T.REG(_,rs) => if CB.sameColor(rs,rd) then addN e1
1005 else addition2(e1,e2)
1006 | _ => addition2(e1,e2)
1007 and addition2(e1,e2) =
1008 (dstMustBeReg(fn (dstR, _) =>
1009 mark(I.LEA{r32=dstR, addr=address(exp, readonly)}, an))
1010 handle EA => binaryComm(I.ADDL, e1, e2))
1011
1012
1013 in case exp of
1014 T.REG(_,rs) =>
1015 if isMemReg rs andalso isMemReg rd then
1016 let val tmp = I.Direct(newReg())
1017 in move'(I.MemReg rs, tmp, an);
1018 move'(tmp, rdOpnd, [])
1019 end
1020 else move'(IntReg rs, rdOpnd, an)
1021 | T.LI z => let
1022 val n = toInt32 z
1023 in
1024 if n=0 then
1025 (* As per Fermin's request, special optimization for rd := 0.
1026 * Currently we don't bother with the size.
1027 *)
1028 if isMemReg rd then move'(I.Immed 0, rdOpnd, an)
1029 else mark(I.BINARY{binOp=I.XORL, src=rdOpnd, dst=rdOpnd}, an)
1030 else
1031 move'(I.Immed(n), rdOpnd, an)
1032 end
1033 | (T.CONST _ | T.LABEL _) =>
1034 move'(I.ImmedLabel exp, rdOpnd, an)
1035 | T.LABEXP le => move'(I.ImmedLabel le, rdOpnd, an)
1036
1037 (* 32-bit addition *)
1038 | T.ADD(32, e1, e2 as T.LI n) => let
1039 val n = toInt32 n
1040 in
1041 case n
1042 of 1 => unary(I.INCL, e1)
1043 | ~1 => unary(I.DECL, e1)
1044 | _ => addition(e1, e2)
1045 end
1046 | T.ADD(32, e1 as T.LI n, e2) => let
1047 val n = toInt32 n
1048 in
1049 case n
1050 of 1 => unary(I.INCL, e2)
1051 | ~1 => unary(I.DECL, e2)
1052 | _ => addition(e1, e2)
1053 end
1054 | T.ADD(32, e1, e2) => addition(e1, e2)
1055
1056 (* 32-bit addition but set the flag!
1057 * This is a stupid hack for now.
1058 *)
1059 | T.ADD(0, e, e1 as T.LI n) => let
1060 val n = T.I.toInt(32, n)
1061 in
1062 if n=1 then unary(I.INCL, e)
1063 else if n = ~1 then unary(I.DECL, e)
1064 else binaryComm(I.ADDL, e, e1)
1065 end
1066 | T.ADD(0, e1 as T.LI n, e) => let
1067 val n = T.I.toInt(32, n)
1068 in
1069 if n=1 then unary(I.INCL, e)
1070 else if n = ~1 then unary(I.DECL, e)
1071 else binaryComm(I.ADDL, e1, e)
1072 end
1073 | T.ADD(0, e1, e2) => binaryComm(I.ADDL, e1, e2)
1074
1075 (* 32-bit subtraction *)
1076 | T.SUB(32, e1, e2 as T.LI n) => let
1077 val n = toInt32 n
1078 in
1079 case n
1080 of 0 => doExpr(e1, rd, an)
1081 | 1 => unary(I.DECL, e1)
1082 | ~1 => unary(I.INCL, e1)
1083 | _ => binary(I.SUBL, e1, e2)
1084 end
1085 | T.SUB(32, e1 as T.LI n, e2) =>
1086 if n = 0 then unary(I.NEGL, e2)
1087 else binary(I.SUBL, e1, e2)
1088 | T.SUB(32, e1, e2) => binary(I.SUBL, e1, e2)
1089
1090 | T.MULU(32, x, y) => uMultiply(x, y)
1091 | T.DIVU(32, x, y) => divide(false, x, y)
1092 | T.REMU(32, x, y) => rem(false, x, y)
1093
1094 | T.MULS(32, x, y) => multiply_notrap (x, y)
1095 | T.DIVS(T.DIV_TO_ZERO, 32, x, y) => divide(true, x, y)
1096 | T.DIVS(T.DIV_TO_NEGINF, 32, x, y) => divinf (x, y)
1097 | T.REMS(T.DIV_TO_ZERO, 32, x, y) => rem(true, x, y)
1098 | T.REMS(T.DIV_TO_NEGINF, 32, x, y) => reminf (x, y)
1099
1100 | T.ADDT(32, x, y) => (binaryComm(I.ADDL, x, y); trap())
1101 | T.SUBT(32, T.LI 0, y) => (unary(I.NEGL, y); trap())
1102 | T.SUBT(32, x, y) => (binary(I.SUBL, x, y); trap())
1103 | T.MULT(32, x, y) => (multiply (x, y); trap ())
1104 | T.DIVT(T.DIV_TO_ZERO, 32, x, y) => divide(true, x, y)
1105 | T.DIVT(T.DIV_TO_NEGINF, 32, x, y) => divinf (x, y)
1106
1107 | T.ANDB(32, x, y) => binaryComm(I.ANDL, x, y)
1108 | T.ORB(32, x, y) => binaryComm(I.ORL, x, y)
1109 | T.XORB(32, x, y) => binaryComm(I.XORL, x, y)
1110 | T.NOTB(32, x) => unary(I.NOTL, x)
1111
1112 | T.SRA(32, x, y) => shift(I.SARL, x, y)
1113 | T.SRL(32, x, y) => shift(I.SHRL, x, y)
1114 | T.SLL(32, x, y) => shift(I.SHLL, x, y)
1115
1116 | T.LOAD(8, ea, mem) => load8(ea, mem)
1117 | T.LOAD(16, ea, mem) => load16(ea, mem)
1118 | T.LOAD(32, ea, mem) => load32(ea, mem)
1119 | T.LOAD(64, ea, mem) => load64(ea, mem)
1120
1121 | T.SX(32,8,T.LOAD(8,ea,mem)) => load8s(ea, mem)
1122 | T.SX(32,16,T.LOAD(16,ea,mem)) => load16s(ea, mem)
1123 | T.ZX(32,8,T.LOAD(8,ea,mem)) => load8(ea, mem)
1124 | T.ZX(32,16,T.LOAD(16,ea,mem)) => load16(ea, mem)
1125
1126 | T.COND(32, T.CMP(ty, cc, t1, t2), y as T.LI yes, n as T.LI no) =>
1127 (case !arch of (* PentiumPro and higher has CMOVcc *)
1128 Pentium => setcc(ty, cc, t1, t2, toInt32 yes, toInt32 no)
1129 | _ => cmovcc(ty, cc, t1, t2, y, n)
1130 )
1131 | T.COND(32, T.CMP(ty, cc, t1, t2), yes, no) =>
1132 (case !arch of (* PentiumPro and higher has CMOVcc *)
1133 Pentium => unknownExp exp
1134 | _ => cmovcc(ty, cc, t1, t2, yes, no)
1135 )
1136 | T.LET(s,e) => (doStmt s; doExpr(e, rd, an))
1137 | T.MARK(e, A.MARKREG f) => (f rd; doExpr(e, rd, an))
1138 | T.MARK(e, a) => doExpr(e, rd, a::an)
1139 | T.PRED(e,c) => doExpr(e, rd, A.CTRLUSE c::an)
1140 | T.REXT e =>
1141 ExtensionComp.compileRext (reducer()) {e=e, rd=rd, an=an}
1142 (* simplify and try again *)
1143 | exp => unknownExp exp
1144 end (* doExpr *)
1145
1146 (* generate an expression and return its result register
1147 * If rewritePseudo is on, the result is guaranteed to be in a
1148 * non memReg register
1149 *)
1150 and expr(exp as T.REG(_, rd)) =
1151 if isMemReg rd then genExpr exp else rd
1152 | expr exp = genExpr exp
1153
1154 and genExpr exp =
1155 let val rd = newReg() in doExpr(exp, rd, []); rd end
1156
1157 (* Compare an expression with zero.
1158 * On the x86, TEST is superior to AND for doing the same thing,
1159 * since it doesn't need to write out the result in a register.
1160 *)
1161 and cmpWithZero(cc as (T.EQ | T.NE), e as T.ANDB(ty, a, b), an) =
1162 (case ty of
1163 8 => test(I.TESTB, a, b, an)
1164 | 16 => test(I.TESTW, a, b, an)
1165 | 32 => test(I.TESTL, a, b, an)
1166 | _ => doExpr(e, newReg(), an);
1167 cc)
1168 | cmpWithZero(cc, e, an) =
1169 let val e =
1170 case e of (* hack to disable the lea optimization XXX *)
1171 T.ADD(_, a, b) => T.ADD(0, a, b)
1172 | e => e
1173 in doExpr(e, newReg(), an); cc end
1174
1175 (* Emit a test.
1176 * The available modes are
1177 * r/m, r
1178 * r/m, imm
1179 * On selecting the right instruction: TESTL/TESTW/TESTB.
1180 * When anding an operand with a constant
1181 * that fits within 8 (or 16) bits, it is possible to use TESTB,
1182 * (or TESTW) instead of TESTL. Because x86 is little endian,
1183 * this works for memory operands too. However, with TESTB, it is
1184 * not possible to use registers other than
1185 * AL, CL, BL, DL, and AH, CH, BH, DH. So, the best way is to
1186 * perform register allocation first, and if the operand registers
1187 * are one of EAX, ECX, EBX, or EDX, replace the TESTL instruction
1188 * by TESTB.
1189 *)
1190 and test(testopcode, a, b, an) =
1191 let val (_, opnd1, opnd2) = commuteComparison(T.EQ, true, a, b)
1192 (* translate r, r/m => r/m, r *)
1193 val (opnd1, opnd2) =
1194 if isMemOpnd opnd2 then (opnd2, opnd1) else (opnd1, opnd2)
1195 in mark(testopcode{lsrc=opnd1, rsrc=opnd2}, an)
1196 end
1197
1198 (* %eflags <- src *)
1199 and moveToEflags src =
1200 if CB.sameColor(src, C.eflags) then ()
1201 else (move(I.Direct src, eax); emit(I.LAHF))
1202
1203 (* dst <- %eflags *)
1204 and moveFromEflags dst =
1205 if CB.sameColor(dst, C.eflags) then ()
1206 else (emit(I.SAHF); move(eax, I.Direct dst))
1207
1208 (* generate a condition code expression
1209 * The zero is for setting the condition code!
1210 * I have no idea why this is used.
1211 *)
1212 and doCCexpr(T.CMP(ty, cc, t1, t2), rd, an) =
1213 (cmp(false, ty, cc, t1, t2, an);
1214 moveFromEflags rd
1215 )
1216 | doCCexpr(T.CC(cond,rs), rd, an) =
1217 if CB.sameColor(rs,C.eflags) orelse CB.sameColor(rd,C.eflags) then
1218 (moveToEflags rs; moveFromEflags rd)
1219 else
1220 move'(I.Direct rs, I.Direct rd, an)
1221 | doCCexpr(T.CCMARK(e,A.MARKREG f),rd,an) = (f rd; doCCexpr(e,rd,an))
1222 | doCCexpr(T.CCMARK(e,a), rd, an) = doCCexpr(e,rd,a::an)
1223 | doCCexpr(T.CCEXT e, cd, an) =
1224 ExtensionComp.compileCCext (reducer()) {e=e, ccd=cd, an=an}
1225 | doCCexpr _ = error "doCCexpr"
1226
1227 and ccExpr e = error "ccExpr"
1228
1229 (* generate a comparison and sets the condition code;
1230 * return the actual cc used. If the flag swapable is true,
1231 * we can also reorder the operands.
1232 *)
1233 and cmp(swapable, ty, cc, t1, t2, an) =
1234 (* == and <> can be always be reordered *)
1235 let val swapable = swapable orelse cc = T.EQ orelse cc = T.NE
1236 in (* Sometimes the comparison is not necessary because
1237 * the bits are already set!
1238 *)
1239 if isZero t1 andalso setZeroBit2 t2 then
1240 if swapable then
1241 cmpWithZero(T.Basis.swapCond cc, t2, an)
1242 else (* can't reorder the comparison! *)
1243 genCmp(ty, false, cc, t1, t2, an)
1244 else if isZero t2 andalso setZeroBit2 t1 then
1245 cmpWithZero(cc, t1, an)
1246 else genCmp(ty, swapable, cc, t1, t2, an)
1247 end
1248
1249 (* Give a and b which are the operands to a comparison (or test)
1250 * Return the appropriate condition code and operands.
1251 * The available modes are:
1252 * r/m, imm
1253 * r/m, r
1254 * r, r/m
1255 *)
1256 and commuteComparison(cc, swapable, a, b) =
1257 let val (opnd1, opnd2) = (operand a, operand b)
1258 in (* Try to fold in the operands whenever possible *)
1259 case (isImmediate opnd1, isImmediate opnd2) of
1260 (true, true) => (cc, moveToReg opnd1, opnd2)
1261 | (true, false) =>
1262 if swapable then (T.Basis.swapCond cc, opnd2, opnd1)
1263 else (cc, moveToReg opnd1, opnd2)
1264 | (false, true) => (cc, opnd1, opnd2)
1265 | (false, false) =>
1266 (case (opnd1, opnd2) of
1267 (_, I.Direct _) => (cc, opnd1, opnd2)
1268 | (I.Direct _, _) => (cc, opnd1, opnd2)
1269 | (_, _) => (cc, moveToReg opnd1, opnd2)
1270 )
1271 end
1272
1273 (* generate a real comparison; return the real cc used *)
1274 and genCmp(ty, swapable, cc, a, b, an) =
1275 let val (cc, opnd1, opnd2) = commuteComparison(cc, swapable, a, b)
1276 in mark(I.CMPL{lsrc=opnd1, rsrc=opnd2}, an); cc
1277 end
1278
1279 (* generate code for jumps *)
1280 and jmp(lexp as T.LABEL lab, labs, an) =
1281 mark(I.JMP(I.ImmedLabel lexp, [lab]), an)
1282 | jmp(T.LABEXP le, labs, an) = mark(I.JMP(I.ImmedLabel le, labs), an)
1283 | jmp(ea, labs, an) = mark(I.JMP(operand ea, labs), an)
1284
1285 (* convert mlrisc to cellset:
1286 *)
1287 and cellset mlrisc =
1288 let val addCCReg = CB.CellSet.add
1289 fun g([],acc) = acc
1290 | g(T.GPR(T.REG(_,r))::regs,acc) = g(regs,C.addReg(r,acc))
1291 | g(T.FPR(T.FREG(_,f))::regs,acc) = g(regs,C.addFreg(f,acc))
1292 | g(T.CCR(T.CC(_,cc))::regs,acc) = g(regs,addCCReg(cc,acc))
1293 | g(T.CCR(T.FCC(_,cc))::regs,acc) = g(regs,addCCReg(cc,acc))
1294 | g(_::regs, acc) = g(regs, acc)
1295 in g(mlrisc, C.empty) end
1296
1297 (* generate code for calls *)
1298 and call(ea, flow, def, use, mem, cutsTo, an, pops) =
1299 let fun return(set, []) = set
1300 | return(set, a::an) =
1301 case #peek A.RETURN_ARG a of
1302 SOME r => return(CB.CellSet.add(r, set), an)
1303 | NONE => return(set, an)
1304 in
1305 mark(I.CALL{opnd=operand ea,defs=cellset(def),uses=cellset(use),
1306 return=return(C.empty,an),cutsTo=cutsTo,mem=mem,
1307 pops=pops},an)
1308 end
1309
1310 (* generate code for integer stores; first move data to %eax
1311 * This is mainly because we can't allocate to registers like
1312 * ah, dl, dx etc.
1313 *)
1314 and genStore(mvOp, ea, d, mem, an) =
1315 let val src =
1316 case immedOrReg(operand d) of
1317 src as I.Direct r =>
1318 if CB.sameColor(r,C.eax)
1319 then src else (move(src, eax); eax)
1320 | src => src
1321 in mark(I.MOVE{mvOp=mvOp, src=src, dst=address(ea,mem)},an)
1322 end
1323
1324 (* generate code for 8-bit integer stores *)
1325 (* movb has to use %eax as source. Stupid x86! *)
1326 and store8(ea, d, mem, an) = genStore(I.MOVB, ea, d, mem, an)
1327 and store16(ea, d, mem, an) =
1328 mark(I.MOVE{mvOp=I.MOVW, src=immedOrReg(operand d), dst=address(ea, mem)}, an)
1329 and store32(ea, d, mem, an) =
1330 move'(immedOrReg(operand d), address(ea, mem), an)
1331
1332 (* generate code for branching *)
1333 and branch(T.CMP(ty, cc, t1, t2), lab, an) =
1334 (* allow reordering of operands *)
1335 let val cc = cmp(true, ty, cc, t1, t2, [])
1336 in mark(I.JCC{cond=cond cc, opnd=immedLabel lab}, an) end
1337 | branch(T.FCMP(fty, fcc, t1, t2), lab, an) =
1338 fbranch(fty, fcc, t1, t2, lab, an)
1339 | branch(ccexp, lab, an) =
1340 (doCCexpr(ccexp, C.eflags, []);
1341 mark(I.JCC{cond=cond(Gen.condOf ccexp), opnd=immedLabel lab}, an)
1342 )
1343
1344 (* generate code for floating point compare and branch *)
1345 and fbranch(fty, fcc, t1, t2, lab, an) =
1346 let fun j cc = mark(I.JCC{cond=cc, opnd=immedLabel lab},an)
1347 in fbranching(fty, fcc, t1, t2, j)
1348 end
1349
1350 and fbranching(fty, fcc, t1, t2, j) =
1351 let fun ignoreOrder (T.FREG _) = true
1352 | ignoreOrder (T.FLOAD _) = true
1353 | ignoreOrder (T.FMARK(e,_)) = ignoreOrder e
1354 | ignoreOrder _ = false
1355
1356 fun compare'() = (* Sethi-Ullman style *)
1357 (if ignoreOrder t1 orelse ignoreOrder t2 then
1358 (reduceFexp(fty, t2, []); reduceFexp(fty, t1, []))
1359 else (reduceFexp(fty, t1, []); reduceFexp(fty, t2, []);
1360 emit(I.FXCH{opnd=C.ST(1)}));
1361 emit(I.FUCOMPP);
1362 fcc
1363 )
1364
1365 fun compare''() =
1366 (* direct style *)
1367 (* Try to make lsrc the memory operand *)
1368 let val lsrc = foperand(fty, t1)
1369 val rsrc = foperand(fty, t2)
1370 val fsize = fsize fty
1371 fun cmp(lsrc, rsrc, fcc) =
1372 let val i = !arch <> Pentium
1373 in emit(I.FCMP{i=i,fsize=fsize,lsrc=lsrc,rsrc=rsrc});
1374 fcc
1375 end
1376 in case (lsrc, rsrc) of
1377 (I.FPR _, I.FPR _) => cmp(lsrc, rsrc, fcc)
1378 | (I.FPR _, mem) => cmp(mem,lsrc,T.Basis.swapFcond fcc)
1379 | (mem, I.FPR _) => cmp(lsrc, rsrc, fcc)
1380 | (lsrc, rsrc) => (* can't be both memory! *)
1381 let val ftmpR = newFreg()
1382 val ftmp = I.FPR ftmpR
1383 in emit(I.FMOVE{fsize=fsize,src=rsrc,dst=ftmp});
1384 cmp(lsrc, ftmp, fcc)
1385 end
1386 end
1387
1388 fun compare() =
1389 if enableFastFPMode andalso !fast_floating_point
1390 then compare''() else compare'()
1391
1392 fun andil i = emit(I.BINARY{binOp=I.ANDL,src=I.Immed(i),dst=eax})
1393 fun testil i = emit(I.TESTL{lsrc=eax,rsrc=I.Immed(i)})
1394 fun xoril i = emit(I.BINARY{binOp=I.XORL,src=I.Immed(i),dst=eax})
1395 fun cmpil i = emit(I.CMPL{rsrc=I.Immed(i), lsrc=eax})
1396 fun sahf() = emit(I.SAHF)
1397 fun branch(fcc) =
1398 case fcc
1399 of T.== => (andil 0x4400; xoril 0x4000; j(I.EQ))
1400 | T.?<> => (andil 0x4400; xoril 0x4000; j(I.NE))
1401 | T.? => (sahf(); j(I.P))
1402 | T.<=> => (sahf(); j(I.NP))
1403 | T.> => (testil 0x4500; j(I.EQ))
1404 | T.?<= => (testil 0x4500; j(I.NE))
1405 | T.>= => (testil 0x500; j(I.EQ))
1406 | T.?< => (testil 0x500; j(I.NE))
1407 | T.< => (andil 0x4500; cmpil 0x100; j(I.EQ))
1408 | T.?>= => (andil 0x4500; cmpil 0x100; j(I.NE))
1409 | T.<= => (andil 0x4100; cmpil 0x100; j(I.EQ);
1410 cmpil 0x4000; j(I.EQ))
1411 | T.?> => (sahf(); j(I.P); testil 0x4100; j(I.EQ))
1412 | T.<> => (testil 0x4400; j(I.EQ))
1413 | T.?= => (testil 0x4400; j(I.NE))
1414 | _ => error(concat[
1415 "fbranch(", T.Basis.fcondToString fcc, ")"
1416 ])
1417 (*esac*)
1418
1419 (*
1420 * P Z C
1421 * x < y 0 0 1
1422 * x > y 0 0 0
1423 * x = y 0 1 0
1424 * unordered 1 1 1
1425 * When it's unordered, all three flags, P, Z, C are set.
1426 *)
1427
1428 fun fast_branch(fcc) =
1429 case fcc
1430 of T.== => orderedOnly(I.EQ)
1431 | T.?<> => (j(I.P); j(I.NE))
1432 | T.? => j(I.P)
1433 | T.<=> => j(I.NP)
1434 | T.> => j(I.A) (* "JA" tests that _both_ Z and C are zero, so
1435 * we do not need a separate test of P.
1436 *)
1437 | T.?<= => j(I.BE)
1438 | T.>= => orderedOnly(I.AE)
1439 | T.?< => j(I.B)
1440 | T.< => orderedOnly(I.B)
1441 | T.?>= => (j(I.P); j(I.AE))
1442 | T.<= => orderedOnly(I.BE)
1443 | T.?> => (j(I.P); j(I.A))
1444 | T.<> => orderedOnly(I.NE)
1445 | T.?= => j(I.EQ)
1446 | _ => error(concat[
1447 "fbranch(", T.Basis.fcondToString fcc, ")"
1448 ])
1449 (*esac*)
1450 and orderedOnly fcc =
1451 let val label = Label.anon()
1452 in emit(I.JCC{cond=I.P, opnd=immedLabel label});
1453 j fcc;
1454 defineLabel label
1455 end
1456
1457 val fcc = compare()
1458 in if !arch <> Pentium andalso
1459 (enableFastFPMode andalso !fast_floating_point) then
1460 fast_branch(fcc)
1461 else
1462 (emit I.FNSTSW;
1463 branch(fcc)
1464 )
1465 end
1466
1467 (*========================================================
1468 * Floating point code generation starts here.
1469 * Some generic fp routines first.
1470 *========================================================*)
1471
1472 (* Can this tree be folded into the src operand of a floating point
1473 * operations?
1474 *)
1475 and foldableFexp(T.FREG _) = true
1476 | foldableFexp(T.FLOAD _) = true
1477 | foldableFexp(T.CVTI2F(_, (16 | 32), _)) = true
1478 | foldableFexp(T.CVTF2F(_, _, t)) = foldableFexp t
1479 | foldableFexp(T.FMARK(t, _)) = foldableFexp t
1480 | foldableFexp _ = false
1481
1482 (* Move integer e of size ty into a memory location.
1483 * Returns a quadruple:
1484 * (INTEGER,return ty,effect address of memory location,cleanup code)
1485 *)
1486 and convertIntToFloat(ty, e) =
1487 let val opnd = operand e
1488 in if isMemOpnd opnd andalso (ty = 16 orelse ty = 32)
1489 then (INTEGER, ty, opnd, [])
1490 else
1491 let val {instrs, tempMem, cleanup} =
1492 cvti2f{ty=ty, src=opnd, an=getAnnotations()}
1493 in emits instrs;
1494 (INTEGER, 32, tempMem, cleanup)
1495 end
1496 end
1497
1498 (*========================================================
1499 * Sethi-Ullman based floating point code generation as
1500 * implemented by Lal
1501 *========================================================*)
1502
1503 and fld(32, opnd) = I.FLDS opnd
1504 | fld(64, opnd) = I.FLDL opnd
1505 | fld(80, opnd) = I.FLDT opnd
1506 | fld _ = error "fld"
1507
1508 and fild(16, opnd) = I.FILD opnd
1509 | fild(32, opnd) = I.FILDL opnd
1510 | fild(64, opnd) = I.FILDLL opnd
1511 | fild _ = error "fild"
1512
1513 and fxld(INTEGER, ty, opnd) = fild(ty, opnd)
1514 | fxld(REAL, fty, opnd) = fld(fty, opnd)
1515
1516 and fstp(32, opnd) = I.FSTPS opnd
1517 | fstp(64, opnd) = I.FSTPL opnd
1518 | fstp(80, opnd) = I.FSTPT opnd
1519 | fstp _ = error "fstp"
1520
1521 (* generate code for floating point stores *)
1522 and fstore'(fty, ea, d, mem, an) =
1523 (case d of
1524 T.FREG(fty, fs) => emit(fld(fty, I.FDirect fs))
1525 | _ => reduceFexp(fty, d, []);
1526 mark(fstp(fty, address(ea, mem)), an)
1527 )
1528
1529 (* generate code for floating point loads *)
1530 and fload'(fty, ea, mem, fd, an) =
1531 let val ea = address(ea, mem)
1532 in mark(fld(fty, ea), an);
1533 if CB.sameColor(fd,ST0) then ()
1534 else emit(fstp(fty, I.FDirect fd))
1535 end
1536
1537 and fexpr' e = (reduceFexp(64, e, []); C.ST(0))
1538
1539 (* generate floating point expression and put the result in fd *)
1540 and doFexpr'(fty, T.FREG(_, fs), fd, an) =
1541 (if CB.sameColor(fs,fd) then ()
1542 else mark'(I.COPY{k=CB.FP, sz=64, dst=[fd], src=[fs], tmp=NONE}, an)
1543 )
1544 | doFexpr'(_, T.FLOAD(fty, ea, mem), fd, an) =
1545 fload'(fty, ea, mem, fd, an)
1546 | doFexpr'(fty, T.FEXT fexp, fd, an) =
1547 (ExtensionComp.compileFext (reducer()) {e=fexp, fd=fd, an=an};
1548 if CB.sameColor(fd,ST0) then () else emit(fstp(fty, I.FDirect fd))
1549 )
1550 | doFexpr'(fty, e, fd, an) =
1551 (reduceFexp(fty, e, []);
1552 if CB.sameColor(fd,ST0) then ()
1553 else mark(fstp(fty, I.FDirect fd), an)
1554 )
1555
1556 (*
1557 * Generate floating point expression using Sethi-Ullman's scheme:
1558 * This function evaluates a floating point expression,
1559 * and put result in %ST(0).
1560 *)
1561 and reduceFexp(fty, fexp, an) =
1562 let val ST = I.ST(C.ST 0)
1563 val ST1 = I.ST(C.ST 1)
1564 val cleanupCode = ref [] : I.instruction list ref
1565
1566 datatype su_tree =
1567 LEAF of int * T.fexp * ans
1568 | BINARY of int * T.fty * fbinop * su_tree * su_tree * ans
1569 | UNARY of int * T.fty * I.funOp * su_tree * ans
1570 and fbinop = FADD | FSUB | FMUL | FDIV
1571 | FIADD | FISUB | FIMUL | FIDIV
1572 withtype ans = Annotations.annotations
1573
1574 fun label(LEAF(n, _, _)) = n
1575 | label(BINARY(n, _, _, _, _, _)) = n
1576 | label(UNARY(n, _, _, _, _)) = n
1577
1578 fun annotate(LEAF(n, x, an), a) = LEAF(n,x,a::an)
1579 | annotate(BINARY(n,t,b,x,y,an), a) = BINARY(n,t,b,x,y,a::an)
1580 | annotate(UNARY(n,t,u,x,an), a) = UNARY(n,t,u,x,a::an)
1581
1582 (* Generate expression tree with sethi-ullman numbers *)
1583 fun su(e as T.FREG _) = LEAF(1, e, [])
1584 | su(e as T.FLOAD _) = LEAF(1, e, [])
1585 | su(e as T.CVTI2F _) = LEAF(1, e, [])
1586 | su(T.CVTF2F(_, _, t)) = su t
1587 | su(T.FMARK(t, a)) = annotate(su t, a)
1588 | su(T.FABS(fty, t)) = suUnary(fty, I.FABS, t)
1589 | su(T.FNEG(fty, t)) = suUnary(fty, I.FCHS, t)
1590 | su(T.FSQRT(fty, t)) = suUnary(fty, I.FSQRT, t)
1591 | su(T.FADD(fty, t1, t2)) = suComBinary(fty,FADD,FIADD,t1,t2)
1592 | su(T.FMUL(fty, t1, t2)) = suComBinary(fty,FMUL,FIMUL,t1,t2)
1593 | su(T.FSUB(fty, t1, t2)) = suBinary(fty,FSUB,FISUB,t1,t2)
1594 | su(T.FDIV(fty, t1, t2)) = suBinary(fty,FDIV,FIDIV,t1,t2)
1595 | su _ = error "su"
1596
1597 (* Try to fold the the memory operand or integer conversion *)
1598 and suFold(e as T.FREG _) = (LEAF(0, e, []), false)
1599 | suFold(e as T.FLOAD _) = (LEAF(0, e, []), false)
1600 | suFold(e as T.CVTI2F(_,(16 | 32),_)) = (LEAF(0, e, []), true)
1601 | suFold(T.CVTF2F(_, _, t)) = suFold t
1602 | suFold(T.FMARK(t, a)) =
1603 let val (t, integer) = suFold t
1604 in (annotate(t, a), integer) end
1605 | suFold e = (su e, false)
1606
1607 (* Form unary tree *)
1608 and suUnary(fty, funary, t) =
1609 let val t = su t
1610 in UNARY(label t, fty, funary, t, [])
1611 end
1612
1613 (* Form binary tree *)
1614 and suBinary(fty, binop, ibinop, t1, t2) =
1615 let val t1 = su t1
1616 val (t2, integer) = suFold t2
1617 val n1 = label t1
1618 val n2 = label t2
1619 val n = if n1=n2 then n1+1 else Int.max(n1,n2)
1620 val myOp = if integer then ibinop else binop
1621 in BINARY(n, fty, myOp, t1, t2, [])
1622 end
1623
1624 (* Try to fold in the operand if possible.
1625 * This only applies to commutative operations.
1626 *)
1627 and suComBinary(fty, binop, ibinop, t1, t2) =
1628 let val (t1, t2) = if foldableFexp t2
1629 then (t1, t2) else (t2, t1)
1630 in suBinary(fty, binop, ibinop, t1, t2) end
1631
1632 and sameTree(LEAF(_, T.FREG(t1,f1), []),
1633 LEAF(_, T.FREG(t2,f2), [])) =
1634 t1 = t2 andalso CB.sameColor(f1,f2)
1635 | sameTree _ = false
1636
1637 (* Traverse tree and generate code *)
1638 fun gencode(LEAF(_, t, an)) = mark(fxld(leafEA t), an)
1639 | gencode(BINARY(_, _, binop, x, t2 as LEAF(0, y, a1), a2)) =
1640 let val _ = gencode x
1641 val (_, fty, src) = leafEA y
1642 fun gen(code) = mark(code, a1 @ a2)
1643 fun binary(oper32, oper64) =
1644 if sameTree(x, t2) then
1645 gen(I.FBINARY{binOp=oper64, src=ST, dst=ST})
1646 else
1647 let val oper =
1648 if isMemOpnd src then
1649 case fty of
1650 32 => oper32
1651 | 64 => oper64
1652 | _ => error "gencode: BINARY"
1653 else oper64
1654 in gen(I.FBINARY{binOp=oper, src=src, dst=ST}) end
1655 fun ibinary(oper16, oper32) =
1656 let val oper = case fty of
1657 16 => oper16
1658 | 32 => oper32
1659 | _ => error "gencode: IBINARY"
1660 in gen(I.FIBINARY{binOp=oper, src=src}) end
1661 in case binop of
1662 FADD => binary(I.FADDS, I.FADDL)
1663 | FSUB => binary(I.FDIVS, I.FSUBL)
1664 | FMUL => binary(I.FMULS, I.FMULL)
1665 | FDIV => binary(I.FDIVS, I.FDIVL)
1666 | FIADD => ibinary(I.FIADDS, I.FIADDL)
1667 | FISUB => ibinary(I.FIDIVS, I.FISUBL)
1668 | FIMUL => ibinary(I.FIMULS, I.FIMULL)
1669 | FIDIV => ibinary(I.FIDIVS, I.FIDIVL)
1670 end
1671 | gencode(BINARY(_, fty, binop, t1, t2, an)) =
1672 let fun doit(t1, t2, oper, operP, operRP) =
1673 let (* oper[P] => ST(1) := ST oper ST(1); [pop]
1674 * operR[P] => ST(1) := ST(1) oper ST; [pop]
1675 *)
1676 val n1 = label t1
1677 val n2 = label t2
1678 in if n1 < n2 andalso n1 <= 7 then
1679 (gencode t2;
1680 gencode t1;
1681 mark(I.FBINARY{binOp=operP, src=ST, dst=ST1}, an))
1682 else if n2 <= n1 andalso n2 <= 7 then
1683 (gencode t1;
1684 gencode t2;
1685 mark(I.FBINARY{binOp=operRP, src=ST, dst=ST1}, an))
1686 else
1687 let (* both labels > 7 *)
1688 val fs = I.FDirect(newFreg())
1689 in gencode t2;
1690 emit(fstp(fty, fs));
1691 gencode t1;
1692 mark(I.FBINARY{binOp=oper, src=fs, dst=ST}, an)
1693 end
1694 end
1695 in case binop of
1696 FADD => doit(t1,t2,I.FADDL,I.FADDP,I.FADDP)
1697 | FMUL => doit(t1,t2,I.FMULL,I.FMULP,I.FMULP)
1698 | FSUB => doit(t1,t2,I.FSUBL,I.FSUBP,I.FSUBRP)
1699 | FDIV => doit(t1,t2,I.FDIVL,I.FDIVP,I.FDIVRP)
1700 | _ => error "gencode.BINARY"
1701 end
1702 | gencode(UNARY(_, _, unaryOp, su, an)) =
1703 (gencode(su); mark(I.FUNARY(unaryOp),an))
1704
1705 (* Generate code for a leaf.
1706 * Returns the type and an effective address
1707 *)
1708 and leafEA(T.FREG(fty, f)) = (REAL, fty, I.FDirect f)
1709 | leafEA(T.FLOAD(fty, ea, mem)) = (REAL, fty, address(ea, mem))
1710 | leafEA(T.CVTI2F(_, 32, t)) = int2real(32, t)
1711 | leafEA(T.CVTI2F(_, 16, t)) = int2real(16, t)
1712 | leafEA(T.CVTI2F(_, 8, t)) = int2real(8, t)
1713 | leafEA _ = error "leafEA"
1714
1715 and int2real(ty, e) =
1716 let val (_, ty, ea, cleanup) = convertIntToFloat(ty, e)
1717 in cleanupCode := !cleanupCode @ cleanup;
1718 (INTEGER, ty, ea)
1719 end
1720
1721 in gencode(su fexp);
1722 emits(!cleanupCode)
1723 end (*reduceFexp*)
1724
1725 (*========================================================
1726 * This section generates 3-address style floating
1727 * point code.
1728 *========================================================*)
1729
1730 and isize 16 = I.I16
1731 | isize 32 = I.I32
1732 | isize _ = error "isize"
1733
1734 and fstore''(fty, ea, d, mem, an) =
1735 (floatingPointUsed := true;
1736 mark(I.FMOVE{fsize=fsize fty, dst=address(ea,mem),
1737 src=foperand(fty, d)},
1738 an)
1739 )
1740
1741 and fload''(fty, ea, mem, d, an) =
1742 (floatingPointUsed := true;
1743 mark(I.FMOVE{fsize=fsize fty, src=address(ea,mem),
1744 dst=RealReg d}, an)
1745 )
1746
1747 and fiload''(ity, ea, d, an) =
1748 (floatingPointUsed := true;
1749 mark(I.FILOAD{isize=isize ity, ea=ea, dst=RealReg d}, an)
1750 )
1751
1752 and fexpr''(e as T.FREG(_,f)) =
1753 if isFMemReg f then transFexpr e else f
1754 | fexpr'' e = transFexpr e
1755
1756 and transFexpr e =
1757 let val fd = newFreg() in doFexpr''(64, e, fd, []); fd end
1758
1759 (*
1760 * Process a floating point operand. Put operand in register
1761 * when possible. The operand should match the given fty.
1762 *)
1763 and foperand(fty, e as T.FREG(fty', f)) =
1764 if fty = fty' then RealReg f else I.FPR(fexpr'' e)
1765 | foperand(fty, T.CVTF2F(_, _, e)) =
1766 foperand(fty, e) (* nop on the x86 *)
1767 | foperand(fty, e as T.FLOAD(fty', ea, mem)) =
1768 (* fold operand when the precison matches *)
1769 if fty = fty' then address(ea, mem) else I.FPR(fexpr'' e)
1770 | foperand(fty, e) = I.FPR(fexpr'' e)
1771
1772 (*
1773 * Process a floating point operand.
1774 * Try to fold in a memory operand or conversion from an integer.
1775 *)
1776 and fioperand(T.FREG(fty,f)) = (REAL, fty, RealReg f, [])
1777 | fioperand(T.FLOAD(fty, ea, mem)) =
1778 (REAL, fty, address(ea, mem), [])
1779 | fioperand(T.CVTF2F(_, _, e)) = fioperand(e) (* nop on the x86 *)
1780 | fioperand(T.CVTI2F(_, ty, e)) = convertIntToFloat(ty, e)
1781 | fioperand(T.FMARK(e,an)) = fioperand(e) (* XXX *)
1782 | fioperand(e) = (REAL, 64, I.FPR(fexpr'' e), [])
1783
1784 (* Generate binary operator. Since the real binary operators
1785 * does not take memory as destination, we also ensure this
1786 * does not happen.
1787 *)
1788 and fbinop(targetFty,
1789 binOp, binOpR, ibinOp, ibinOpR, lsrc, rsrc, fd, an) =
1790 (* Put the mem operand in rsrc *)
1791 let
1792 fun isMemOpnd(T.FREG(_, f)) = isFMemReg f
1793 | isMemOpnd(T.FLOAD _) = true
1794 | isMemOpnd(T.CVTI2F(_, (16 | 32), _)) = true
1795 | isMemOpnd(T.CVTF2F(_, _, t)) = isMemOpnd t
1796 | isMemOpnd(T.FMARK(t, _)) = isMemOpnd t
1797 | isMemOpnd _ = false
1798 val (binOp, ibinOp, lsrc, rsrc) =
1799 if isMemOpnd lsrc then (binOpR, ibinOpR, rsrc, lsrc)
1800 else (binOp, ibinOp, lsrc, rsrc)
1801 val lsrc = foperand(targetFty, lsrc)
1802 val (kind, fty, rsrc, code) = fioperand(rsrc)
1803 fun dstMustBeFreg f =
1804 if targetFty <> 64 then
1805 let val tmpR = newFreg()
1806 val tmp = I.FPR tmpR
1807 in mark(f tmp, an);
1808 emit(I.FMOVE{fsize=fsize targetFty,
1809 src=tmp, dst=RealReg fd})
1810 end
1811 else mark(f(RealReg fd), an)
1812 in case kind of
1813 REAL =>
1814 dstMustBeFreg(fn dst =>
1815 I.FBINOP{fsize=fsize fty, binOp=binOp,
1816 lsrc=lsrc, rsrc=rsrc, dst=dst})
1817 | INTEGER =>
1818 (dstMustBeFreg(fn dst =>
1819 I.FIBINOP{isize=isize fty, binOp=ibinOp,
1820 lsrc=lsrc, rsrc=rsrc, dst=dst});
1821 emits code
1822 )
1823 end
1824
1825 and funop(fty, unOp, src, fd, an) =
1826 let val src = foperand(fty, src)
1827 in mark(I.FUNOP{fsize=fsize fty,
1828 unOp=unOp, src=src, dst=RealReg fd},an)
1829 end
1830
1831 and doFexpr''(fty, e, fd, an) =
1832 (floatingPointUsed := true;
1833 case e of
1834 T.FREG(_,fs) => if CB.sameColor(fs,fd) then ()
1835 else fcopy''(fty, [fd], [fs], an)
1836 (* Stupid x86 does everything as 80-bits internally. *)
1837
1838 (* Binary operators *)
1839 | T.FADD(_, a, b) => fbinop(fty,
1840 I.FADDL, I.FADDL, I.FIADDL, I.FIADDL,
1841 a, b, fd, an)
1842 | T.FSUB(_, a, b) => fbinop(fty,
1843 I.FSUBL, I.FSUBRL, I.FISUBL, I.FISUBRL,
1844 a, b, fd, an)
1845 | T.FMUL(_, a, b) => fbinop(fty,
1846 I.FMULL, I.FMULL, I.FIMULL, I.FIMULL,
1847 a, b, fd, an)
1848 | T.FDIV(_, a, b) => fbinop(fty,
1849 I.FDIVL, I.FDIVRL, I.FIDIVL, I.FIDIVRL,
1850 a, b, fd, an)
1851
1852 (* Unary operators *)
1853 | T.FNEG(_, a) => funop(fty, I.FCHS, a, fd, an)
1854 | T.FABS(_, a) => funop(fty, I.FABS, a, fd, an)
1855 | T.FSQRT(_, a) => funop(fty, I.FSQRT, a, fd, an)
1856
1857 (* Load *)
1858 | T.FLOAD(fty,ea,mem) => fload''(fty, ea, mem, fd, an)
1859
1860 (* Type conversions *)
1861 | T.CVTF2F(_, _, e) => doFexpr''(fty, e, fd, an)
1862 | T.CVTI2F(_, ty, e) =>
1863 let val (_, ty, ea, cleanup) = convertIntToFloat(ty, e)
1864 in fiload''(ty, ea, fd, an);
1865 emits cleanup
1866 end
1867
1868 | T.FMARK(e,A.MARKREG f) => (f fd; doFexpr''(fty, e, fd, an))
1869 | T.FMARK(e, a) => doFexpr''(fty, e, fd, a::an)
1870 | T.FPRED(e, c) => doFexpr''(fty, e, fd, A.CTRLUSE c::an)
1871 | T.FEXT fexp =>
1872 ExtensionComp.compileFext (reducer()) {e=fexp, fd=fd, an=an}
1873 | _ => error("doFexpr''")
1874 )
1875
1876 (*========================================================
1877 * Tie the two styles of fp code generation together
1878 *========================================================*)
1879 and fstore(fty, ea, d, mem, an) =
1880 if enableFastFPMode andalso !fast_floating_point
1881 then fstore''(fty, ea, d, mem, an)
1882 else fstore'(fty, ea, d, mem, an)
1883 and fload(fty, ea, d, mem, an) =
1884 if enableFastFPMode andalso !fast_floating_point
1885 then fload''(fty, ea, d, mem, an)
1886 else fload'(fty, ea, d, mem, an)
1887 and fexpr e =
1888 if enableFastFPMode andalso !fast_floating_point
1889 then fexpr'' e else fexpr' e
1890 and doFexpr(fty, e, fd, an) =
1891 if enableFastFPMode andalso !fast_floating_point
1892 then doFexpr''(fty, e, fd, an)
1893 else doFexpr'(fty, e, fd, an)
1894
1895 (*================================================================
1896 * Optimizations for x := x op y
1897 * Special optimizations:
1898 * Generate a binary operator, result must in memory.
1899 * The source must not be in memory
1900 *================================================================*)
1901 and binaryMem(binOp, src, dst, mem, an) =
1902 mark(I.BINARY{binOp=binOp, src=immedOrReg(operand src),
1903 dst=address(dst,mem)}, an)
1904 and unaryMem(unOp, opnd, mem, an) =
1905 mark(I.UNARY{unOp=unOp, opnd=address(opnd,mem)}, an)
1906
1907 and isOne(T.LI n) = n = 1
1908 | isOne _ = false
1909
1910 (*
1911 * Perform optimizations based on recognizing
1912 * x := x op y or
1913 * x := y op x
1914 * first.
1915 *)
1916 and store(ty, ea, d, mem, an,
1917 {INC,DEC,ADD,SUB,NOT,NEG,SHL,SHR,SAR,OR,AND,XOR},
1918 doStore
1919 ) =
1920 let fun default() = doStore(ea, d, mem, an)
1921 fun binary1(t, t', unary, binary, ea', x) =
1922 if t = ty andalso t' = ty then
1923 if MLTreeUtils.eqRexp(ea, ea') then
1924 if isOne x then unaryMem(unary, ea, mem, an)
1925 else binaryMem(binary, x, ea, mem, an)
1926 else default()
1927 else default()
1928 fun unary(t,unOp, ea') =
1929 if t = ty andalso MLTreeUtils.eqRexp(ea, ea') then
1930 unaryMem(unOp, ea, mem, an)
1931 else default()
1932 fun binary(t,t',binOp,ea',x) =
1933 if t = ty andalso t' = ty andalso
1934 MLTreeUtils.eqRexp(ea, ea') then
1935 binaryMem(binOp, x, ea, mem, an)
1936 else default()
1937
1938 fun binaryCom1(t,unOp,binOp,x,y) =
1939 if t = ty then
1940 let fun again() =
1941 case y of
1942 T.LOAD(ty',ea',_) =>
1943 if ty' = ty andalso MLTreeUtils.eqRexp(ea, ea') then
1944 if isOne x then unaryMem(unOp, ea, mem, an)
1945 else binaryMem(binOp,x,ea,mem,an)
1946 else default()
1947 | _ => default()
1948 in case x of
1949 T.LOAD(ty',ea',_) =>
1950 if ty' = ty andalso MLTreeUtils.eqRexp(ea, ea') then
1951 if isOne y then unaryMem(unOp, ea, mem, an)
1952 else binaryMem(binOp,y,ea,mem,an)
1953 else again()
1954 | _ => again()
1955 end
1956 else default()
1957
1958 fun binaryCom(t,binOp,x,y) =
1959 if t = ty then
1960 let fun again() =
1961 case y of
1962 T.LOAD(ty',ea',_) =>
1963 if ty' = ty andalso MLTreeUtils.eqRexp(ea, ea') then
1964 binaryMem(binOp,x,ea,mem,an)
1965 else default()
1966 | _ => default()
1967 in case x of
1968 T.LOAD(ty',ea',_) =>
1969 if ty' = ty andalso MLTreeUtils.eqRexp(ea, ea') then
1970 binaryMem(binOp,y,ea,mem,an)
1971 else again()
1972 | _ => again()
1973 end
1974 else default()
1975
1976 in case d of
1977 T.ADD(t,x,y) => binaryCom1(t,INC,ADD,x,y)
1978 | T.SUB(t,T.LOAD(t',ea',_),x) => binary1(t,t',DEC,SUB,ea',x)
1979 | T.ORB(t,x,y) => binaryCom(t,OR,x,y)
1980 | T.ANDB(t,x,y) => binaryCom(t,AND,x,y)
1981 | T.XORB(t,x,y) => binaryCom(t,XOR,x,y)
1982 | T.SLL(t,T.LOAD(t',ea',_),x) => binary(t,t',SHL,ea',x)
1983 | T.SRL(t,T.LOAD(t',ea',_),x) => binary(t,t',SHR,ea',x)
1984 | T.SRA(t,T.LOAD(t',ea',_),x) => binary(t,t',SAR,ea',x)
1985 | T.NEG(t,T.LOAD(t',ea',_)) => unary(t,NEG,ea')
1986 | T.NOTB(t,T.LOAD(t',ea',_)) => unary(t,NOT,ea')
1987 | _ => default()
1988 end (* store *)
1989
1990 (* generate code for a statement *)
1991 and stmt(T.MV(_, rd, e), an) = doExpr(e, rd, an)
1992 | stmt(T.FMV(fty, fd, e), an) = doFexpr(fty, e, fd, an)
1993 | stmt(T.CCMV(ccd, e), an) = doCCexpr(e, ccd, an)
1994 | stmt(T.COPY(_, dst, src), an) = copy(dst, src, an)
1995 | stmt(T.FCOPY(fty, dst, src), an) = fcopy(fty, dst, src, an)
1996 | stmt(T.JMP(e, labs), an) = jmp(e, labs, an)
1997 | stmt(T.CALL{funct, targets, defs, uses, region, pops, ...}, an) =
1998 call(funct,targets,defs,uses,region,[],an, pops)
1999 | stmt(T.FLOW_TO(T.CALL{funct, targets, defs, uses, region, pops, ...},
2000 cutTo), an) =
2001 call(funct,targets,defs,uses,region,cutTo,an, pops)
2002 | stmt(T.RET _, an) = mark(I.RET NONE, an)
2003 | stmt(T.STORE(8, ea, d, mem), an) =
2004 store(8, ea, d, mem, an, opcodes8, store8)
2005 | stmt(T.STORE(16, ea, d, mem), an) =
2006 store(16, ea, d, mem, an, opcodes16, store16)
2007 | stmt(T.STORE(32, ea, d, mem), an) =
2008 store(32, ea, d, mem, an, opcodes32, store32)
2009 | stmt(T.STORE(64, ea, d, mem), an) =
2010 store(32, ea, d, mem, an, opcodes32, store32) (* XXX64 *)
2011
2012 | stmt(T.FSTORE(fty, ea, d, mem), an) = fstore(fty, ea, d, mem, an)
2013 | stmt(T.BCC(cc, lab), an) = branch(cc, lab, an)
2014 | stmt(T.DEFINE l, _) = defineLabel l
2015 | stmt(T.LIVE S, an) = mark'(I.LIVE{regs=cellset S,spilled=C.empty},an)
2016 | stmt(T.KILL S, an) = mark'(I.KILL{regs=cellset S,spilled=C.empty},an)
2017 | stmt(T.ANNOTATION(s, a), an) = stmt(s, a::an)
2018 | stmt(T.EXT s, an) =
2019 ExtensionComp.compileSext (reducer()) {stm=s, an=an}
2020 | stmt(s, _) = doStmts(Gen.compileStm s)
2021
2022 and doStmt s = stmt(s, [])
2023
2024 and doStmts ss = app doStmt ss
2025
2026 and beginCluster' _ =
2027 ((* Must be cleared by the client.
2028 * if rewriteMemReg then memRegsUsed := 0w0 else ();
2029 *)
2030 floatingPointUsed := false;
2031 trapLabel := NONE;
2032 beginCluster 0
2033 )
2034 and endCluster' a =
2035 (case !trapLabel
2036 of NONE => ()
2037 | SOME(_, lab) => (defineLabel lab; emit(I.INTO))
2038 (*esac*);
2039 (* If floating point has been used allocate an extra
2040 * register just in case we didn't use any explicit register
2041 *)
2042 if !floatingPointUsed then (newFreg(); ())
2043 else ();
2044 endCluster(a)
2045 )
2046
2047 and reducer() =
2048 TS.REDUCER{reduceRexp = expr,
2049 reduceFexp = fexpr,
2050 reduceCCexp = ccExpr,
2051 reduceStm = stmt,
2052 operand = operand,
2053 reduceOperand = reduceOpnd,
2054 addressOf = fn e => address(e, I.Region.memory), (*XXX*)
2055 emit = mark',
2056 instrStream = instrStream,
2057 mltreeStream = self()
2058 }
2059
2060 and self() =
2061 TS.S.STREAM
2062 { beginCluster = beginCluster',
2063 endCluster = endCluster',
2064 emit = doStmt,
2065 pseudoOp = pseudoOp,
2066 defineLabel = defineLabel,
2067 entryLabel = entryLabel,
2068 comment = comment,
2069 annotation = annotation,
2070 getAnnotations = getAnnotations,
2071 exitBlock = fn mlrisc => exitBlock(cellset mlrisc)
2072 }
2073
2074 in self()
2075 end
2076
2077 end (* functor *)