aboutsummaryrefslogtreecommitdiffstats
path: root/lib/hipe/x86/hipe_x86_x87.erl
blob: 85268ab85a3c2aae702ef47d0f463446446692c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
%% -*- erlang-indent-level: 2 -*-
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% Floating point handling.

-ifdef(HIPE_AMD64).
-define(HIPE_X86_X87,       hipe_amd64_x87).
-define(HIPE_X86_DEFUSE,    hipe_amd64_defuse).
-define(HIPE_X86_LIVENESS,  hipe_amd64_liveness).
-define(HIPE_X86_REGISTERS, hipe_amd64_registers).
-else.
-define(HIPE_X86_X87,       hipe_x86_x87).
-define(HIPE_X86_DEFUSE,    hipe_x86_defuse).
-define(HIPE_X86_LIVENESS,  hipe_x86_liveness).
-define(HIPE_X86_REGISTERS, hipe_x86_registers).
-endif.

-module(?HIPE_X86_X87).

-export([map/1]).

-include("../x86/hipe_x86.hrl").
-include("../main/hipe.hrl").

%%----------------------------------------------------------------------

map(CFG0) ->
  %% hipe_x86_cfg:pp(CFG0),
  Liveness = ?HIPE_X86_LIVENESS:analyse(CFG0),
  StartLabel = hipe_x86_cfg:start_label(CFG0),
  {CFG1,_} = do_blocks([], [StartLabel], CFG0, Liveness, [], gb_trees:empty()),
  CFG1.

do_blocks(Pred, [Lbl|Lbls], CFG, Liveness, Map, BlockMap) ->
  case gb_trees:lookup(Lbl, BlockMap) of
    none ->
      %% This block has not been visited.
      Block = hipe_x86_cfg:bb(CFG, Lbl),
      Succ = hipe_x86_cfg:succ(CFG, Lbl),
      NewBlockMap = gb_trees:insert(Lbl, Map, BlockMap),
      LiveOut = [X || X <- ?HIPE_X86_LIVENESS:liveout(Liveness, Lbl),
			   is_fp(X)],
      Code = hipe_bb:code(Block),
      ReverseCode = lists:reverse(Code),
      {NewCode0, NewMap, NewBlockMap1, Dirty} = 
	do_block(ReverseCode, LiveOut, Map, NewBlockMap),
      NewCFG1 =
	case Dirty of
	  true ->
	    NewBlock = hipe_bb:code_update(Block, NewCode0),
	    hipe_x86_cfg:bb_add(CFG, Lbl, NewBlock);
	  _ ->
	    CFG
	end,
      {NewCFG3, NewBlockMap2} =
	do_blocks(Lbl, Succ, NewCFG1, Liveness, NewMap, NewBlockMap1),
      do_blocks(Pred, Lbls, NewCFG3, Liveness, Map, NewBlockMap2);
    {value, fail} ->
      %% Don't have to follow this trace any longer.
      do_blocks(Pred,Lbls, CFG, Liveness, Map, BlockMap);
    {value, ExistingMap} ->
      %% This block belongs to a trace already handled.
      %% The Map coming in must be identical to the one used
      %% when the block was processed.
      if ExistingMap =:= Map -> 
	  do_blocks(Pred, Lbls, CFG, Liveness, Map, BlockMap);
	 true ->
	  NewCFG = do_shuffle(Pred, Lbl, CFG, Map, ExistingMap),
	  do_blocks(Pred, Lbls, NewCFG, Liveness, Map, BlockMap)
      end
  end;
do_blocks(_Pred, [], CFG, _Liveness, _Map, BlockMap) ->
  {CFG, BlockMap}.

do_block(Ins, LiveOut, Map, BlockMap) ->
  do_block(Ins, LiveOut, Map, BlockMap, false).

do_block([I|Is], LiveOut, Map, BlockMap, Dirty) ->
  case handle_insn(I) of
    false -> 
      {NewCode, NewMap, NewBlockMap, NewDirty} = 
	do_block(Is, LiveOut, Map, BlockMap, Dirty),
      {NewCode++[I], NewMap, NewBlockMap, NewDirty};
    true ->
      Def = ordsets:from_list(?HIPE_X86_DEFUSE:insn_def(I)),
      Use = ordsets:from_list(?HIPE_X86_DEFUSE:insn_use(I)),
      NewLiveOut = 
	ordsets:filter(fun(X) -> is_fp(X) end,
		       ordsets:union(ordsets:subtract(LiveOut, Def), Use)),
      {NewCode, NewMap, NewBlockMap, NewDirty} = 
	do_block(Is, NewLiveOut, Map, BlockMap, Dirty),
      {NewI, NewMap1, NewBlockMap1} = 
	do_insn(I, LiveOut, NewMap, NewBlockMap),
      NewDirty1 =
	if NewDirty =:= true -> true;
	   NewI =:= [I] -> false;
	   true -> true
	end,
      {NewCode++NewI, NewMap1, NewBlockMap1, NewDirty1}
  end;
do_block([], LiveOut, Map, BlockMap, Dirty) ->
  case [X || X <- Map, not lists:member(X, LiveOut)] of
    [] ->
      {[], Map, BlockMap, Dirty}; 
    Pop ->
      {PopIns, NewMap} = pop_dead(Pop, Map),
      {PopIns, NewMap, BlockMap, true}
  end.

do_shuffle(Pred, Lbl, CFG, OldMap, NewMap) ->
  %% First make sure both maps have the same members.
  Push = NewMap -- OldMap,
  Pop = OldMap -- NewMap,
  {PopInsn, OldMap0} = pop_dead(Pop, OldMap),
  {PushInsn, OldMap1} = 
    case Push of
      []-> {[], OldMap0};
      _-> push_list(lists:reverse(Push), OldMap0)
    end,
  Code =
    if OldMap1 =:= NewMap ->
	%% It was enough to push and pop.
	PopInsn ++ PushInsn ++ [hipe_x86:mk_jmp_label(Lbl)];
       true ->
	%% Shuffle the positions so the maps match
	Cycles = find_swap_cycles(OldMap1, NewMap),
	SwitchInsns = do_switching(Cycles),
	PopInsn ++ PushInsn ++ SwitchInsns ++ [hipe_x86:mk_jmp_label(Lbl)]
    end,
  %% Update the CFG.
  NewLabel = hipe_gensym:get_next_label(x86),
  NewCFG1 = hipe_x86_cfg:bb_add(CFG, NewLabel, hipe_bb:mk_bb(Code)),
  OldPred = hipe_x86_cfg:bb(NewCFG1, Pred),
  PredCode = hipe_bb:code(OldPred),
  NewLast = redirect(lists:last(PredCode), Lbl,NewLabel),
  NewPredCode = butlast(PredCode) ++ [NewLast],
  NewPredBB = hipe_bb:code_update(OldPred, NewPredCode),
  hipe_x86_cfg:bb_add(NewCFG1, Pred, NewPredBB).

find_swap_cycles(OldMap, NewMap) ->
  Moves = [get_pos(X, NewMap, 1) || X <- OldMap],
  find_swap_cycles(OldMap, Moves, lists:seq(1, length(OldMap)), []).

find_swap_cycles(OldMap, Moves, NotHandled, Cycles) ->
  if NotHandled =:= [] -> Cycles;
     true -> 
      Cycle = find_cycle(Moves, [hd(NotHandled)]),
      NewNotHandled = NotHandled -- Cycle,
      case lists:member(1, Cycle) of
	true ->
	  %% The cycle that contains the first element on the stack
	  %% must be processed last.
	  NewCycle = format_cycle(Cycle),
	  find_swap_cycles(OldMap, Moves, NewNotHandled, Cycles ++ [NewCycle]);
	_ ->
	  NewCycle = format_cycle(Cycle),
	  find_swap_cycles(OldMap, Moves, NewNotHandled, [NewCycle|Cycles])
      end
  end.

find_cycle(Moves, Cycle) ->
  To = lists:nth(lists:last(Cycle), Moves),
  if To =:= hd(Cycle) -> Cycle;
     true -> find_cycle(Moves, Cycle ++ [To])
  end.

format_cycle(C) ->
  %% The position numbers start with 1 - should start with 0.
  %% If position 0 is in the cycle it will be permuted until
  %% the 0 is first and then remove it.
  %% Otherwise the first element is also added last.
  NewCycle = [X - 1 || X <- C],
  case lists:member(0, NewCycle) of
    true -> format_cycle(NewCycle, []);
    _ -> NewCycle ++ [hd(NewCycle)]
  end.

format_cycle([H|T], NewCycle) ->
  case H of
    0 -> T ++ NewCycle;
    _ -> format_cycle(T, NewCycle ++ [H])
  end.

do_switching(Cycles) ->
  do_switching(Cycles, []).

do_switching([C|Cycles], Insns) ->
  NewInsns = Insns ++ [hipe_x86:mk_fp_unop(fxch, mk_st(X)) || X <- C],
  do_switching(Cycles, NewInsns);
do_switching([], Insns) ->
  Insns.

redirect(Insn, OldLbl, NewLbl) ->
  case Insn of
    #pseudo_call{contlab = ContLab, sdesc = SDesc} ->
      #x86_sdesc{exnlab = ExnLab} = SDesc,
      if ContLab =:= OldLbl -> 
	  Insn#pseudo_call{contlab = NewLbl};
	 ExnLab =:= OldLbl ->
	  Insn#pseudo_call{sdesc = SDesc#x86_sdesc{exnlab = NewLbl}}
      end;
    _ -> 
      hipe_x86_cfg:redirect_jmp(Insn, OldLbl, NewLbl)
  end.

do_insn(I, LiveOut, Map, BlockMap) ->
  case I of
    #pseudo_call{'fun' = Fun, contlab = ContLab} ->
      case Fun of
	%% We don't want to spill anything if an exception has been thrown.
	{_, 'handle_fp_exception'} ->
	  NewBlockMap = 
	    case gb_trees:lookup(ContLab, BlockMap) of
	      {value, fail} ->
		BlockMap;
	      {value, _} ->
		gb_trees:update(ContLab, fail, BlockMap);
	      none ->
		gb_trees:insert(ContLab, fail, BlockMap)
	    end,
	  {[I], [], NewBlockMap};
	_ ->
	  {pop_all(Map)++[I],[],BlockMap}
      end;
    #fp_unop{op = 'fwait'} ->
      Store = pseudo_pop(Map),
      {Store ++ [I], Map, BlockMap};
    #fp_unop{} ->
      {NewI, NewMap} = do_fp_unop(I, LiveOut, Map),
      {NewI, NewMap, BlockMap};
    #fp_binop{} ->
      {NewI, NewMap} = do_fp_binop(I, LiveOut, Map),
      {NewI, NewMap, BlockMap};
    #fmove{src = Src, dst = Dst} ->
      if Src =:= Dst ->
	  %% Don't need to keep this instruction!
	  %% However, we may need to pop from the stack.
	  case is_liveOut(Src, LiveOut) of
	    true->
	      {[], Map, BlockMap};
	    false ->
	      {SwitchInsn, NewMap0} = switch_first(Dst, Map),
	      NewMap = pop(NewMap0),
	      {SwitchInsn++pop_insn(), NewMap, BlockMap}
	  end;
	 true -> 
	  {NewI, NewMap} = do_fmove(Src, Dst, LiveOut, Map),
	  {NewI, NewMap, BlockMap}
      end;
    _ ->
      {[I], Map, BlockMap}
  end.

do_fmove(Src, Dst = #x86_mem{}, LiveOut, Map) ->
  %% Storing a float from the stack into memory.
  {SwitchInsn, NewMap0} = switch_first(Src, Map),
  case is_liveOut(Src, LiveOut) of
    true ->
      {SwitchInsn ++ [hipe_x86:mk_fp_unop(fst, Dst)], NewMap0};
    _ ->
      NewMap1 = pop(NewMap0),
      {SwitchInsn ++ [hipe_x86:mk_fp_unop(fstp, Dst)], NewMap1}
  end;
do_fmove(Src = #x86_mem{}, Dst, _LiveOut, Map) ->
  %% Pushing a float into the stack.
  case in_map(Dst, Map) of
    true -> ?EXIT({loadingExistingFpVariable,{Src,Dst}});
    _ -> ok
  end,
  {PushOp, [_|NewMap0]} = push(Src, Map),
  %% We want Dst in the map rather than Src.
  NewMap = [Dst|NewMap0],
  {PushOp, NewMap};
do_fmove(Src, Dst, LiveOut, Map) ->
  %% Copying a float that either is spilled or is on the fp stack,
  %% or converting a fixnum in a temp to a float on the fp stack.
  case in_map(Dst, Map) of
    true -> ?EXIT({copyingToExistingFpVariable,{Src,Dst}});
    _ -> ok
  end,
  IsConv =
    case Src of
      #x86_temp{type = Type} -> Type =/= 'double';
      _ -> false
    end,
  case IsConv of
    true ->
      do_conv(Src, Dst, Map);
    _ ->
      %% Copying.
      case {is_liveOut(Src, LiveOut), in_map(Src, Map)} of
	{false, true} ->
	  %% Just remap Dst to Src
	  {Head, [_|T]} = lists:splitwith(fun(X) -> X =/= Src end, Map),
	  {[], Head ++ [Dst|T]};
	_ ->
	  {PushOp, [_|NewMap0]} = push(Src, Map),
	  %% We want Dst in the map rather than Src.
	  NewMap = [Dst|NewMap0],
	  {PushOp, NewMap}
      end
  end.

do_conv(Src = #x86_temp{reg = Reg}, Dst, Map) ->
  %% Converting. Src must not be a register, so we 
  %% might have to put it into memory in between.
  {Move, NewSrc} = 
    case ?HIPE_X86_REGISTERS:is_precoloured(Reg) of
      true ->
	Temp = hipe_x86:mk_new_temp('untagged'),
	{[hipe_x86:mk_move(Src,Temp)], Temp};
      _ ->
	{[], Src}
    end,
  {PushOp, [_|NewMap0]} = push(NewSrc, Map),
  %% We want Dst in the map rather than NewSrc.
  NewMap = [Dst|NewMap0],
  case length(PushOp) of
    1 -> %% No popping of memory object on fpstack
      {Move ++ [hipe_x86:mk_fp_unop(fild, NewSrc)], NewMap};
    _ -> %% H contains pop instructions. Must be kept!
      Head = butlast(PushOp),
      {Move ++ Head ++ [hipe_x86:mk_fp_unop(fild, NewSrc)], NewMap}
  end.

do_fp_unop(I = #fp_unop{arg = Arg, op = fchs}, Liveout, Map) ->
  %% This is fchs, the only operation without a
  %% popping version. Needs special handling.
  case is_liveOut(Arg, Liveout) of
    true ->
      {SwitchIns, NewMap} = switch_first(Arg, Map),
      {SwitchIns ++ [I#fp_unop{arg = []}], NewMap};
    false ->
      %% Don't need to keep this instruction!
      %% However, we may need to pop Src from the stack.
      case in_map(Arg, Map) of
	true ->
	  {SwitchInsn, NewMap0} = switch_first(Arg, Map),
	  NewMap = pop(NewMap0),
	  {SwitchInsn ++ pop_insn(), NewMap};
	_ ->
	  {[],Map}
      end
  end.

do_fp_binop(#fp_binop{src = Src, dst = Dst, op = Op}, LiveOut, Map) ->
  case {is_liveOut(Src, LiveOut), is_liveOut(Dst, LiveOut)} of
    {true, true} ->
      keep_both(Op, Src, Dst, Map);
    {true, false} ->
      keep_src(Op, Src, Dst, Map);
    {false, true} ->
      keep_dst(Op, Src, Dst, Map);
    {false, false} ->
      %% Both Dst and Src are popped.
      keep_none(Op, Src, Dst, Map)
  end.

keep_both(Op, Src, Dst, Map) ->
  %% Keep both Dst and Src if it is there.
  {SwitchInsn, NewMap} = switch_first(Dst, Map),
  NewSrc = get_new_opnd(Src, NewMap),
  Insn = format_fp_binop(Op, NewSrc, mk_st(0)),
  {SwitchInsn++Insn, NewMap}.

keep_src(Op, Src, Dst, Map) ->
  %% Pop Dst but keep Src in stack if it is there.
  {SwitchInsn, NewMap0} = switch_first(Dst, Map),
  NewSrc = get_new_opnd(Src, NewMap0),
  NewMap = pop(NewMap0),
  Insn = format_fp_binop(Op, NewSrc, mk_st(0)),
  {SwitchInsn ++ Insn ++ pop_insn(), NewMap}.

keep_dst(Op, Src, Dst, Map) ->
  %% Keep Dst but pop Src.
  %% Dst must be in stack.
  DstInMap = in_map(Dst, Map),
  SrcInMap = in_map(Src, Map),
  case SrcInMap of
    true ->
      case DstInMap of
	true ->
	  %% Src must be popped. If Dst is on top of the stack we can
	  %% alter the operation rather than shuffle the stack.
	  {SwitchInsn, Insn, NewMap} =
	    if hd(Map) =:= Dst ->
		NewOp = mk_op_pop(reverse_op(Op)),
		NewDst = get_new_opnd(Src, Map),
		TmpMap = lists:map(fun(X) ->
				     if X =:= Src -> Dst; true -> X end
				   end, Map),
		{[], format_fp_binop(NewOp, mk_st(0), NewDst), pop(TmpMap)};
	       true ->
		{SwitchInsn1, NewMap0} = switch_first(Src, Map),
		NewDst = get_new_opnd(Dst,NewMap0),
		NewOp = mk_op_pop(Op),
		{SwitchInsn1,format_fp_binop(NewOp, mk_st(0), NewDst), pop(NewMap0)}
	    end,
	  {SwitchInsn ++ Insn, NewMap};
	_ ->
	  %% Src is on the stack, but Dst isn't. Use memory command to avoid
	  %% unnecessary loading instructions.
	  {SwitchInsn, NewMap0} = switch_first(Src, Map),
	  NewOp = reverse_op(Op),
	  NewMap = [Dst] ++ tl(NewMap0),
	  Insn = format_fp_binop(NewOp, Dst, mk_st(0)),
	  {SwitchInsn ++ Insn, NewMap}
      end;
    _ ->
      %% Src isn't in the map so it doesn't have to be popped.
      {SwitchInsn, NewMap} = switch_first(Dst, Map),
      {SwitchInsn ++ [#fp_unop{arg = Src, op = Op}], NewMap}
  end.

keep_none(Op, Src, Dst, Map) ->
  %% Dst must be on stack.
  {PushInsn, NewMap0} = 
    case in_map(Dst, Map) of
      true -> {[], Map};
      _ -> push(Dst, Map)
    end,
  case in_map(Src, NewMap0) of
    true ->
      %% Src must be popped.
      {SwitchInsn1, NewMap1} = switch_first(Src, NewMap0),
      NewOp = mk_op_pop(Op),
      NewDst = get_new_opnd(Dst,NewMap1),
      NewMap2 = pop(NewMap1),
      %% Then Dst has to be popped.
      {PopInsn, NewMap} = pop_member(Dst, NewMap2),
      Insn = format_fp_binop(NewOp, mk_st(0), NewDst),
      {PushInsn ++ SwitchInsn1 ++ Insn ++ PopInsn, NewMap};
    _ ->
      %% Src isn't in the map so it doesn't have to be popped.
      {SwitchInsn, NewMap1} = switch_first(Dst, NewMap0),
      NewMap = pop(NewMap1),
      {SwitchInsn ++ [#fp_unop{arg = Src, op = Op}] ++ pop_insn(), NewMap}
  end.

format_fp_binop(Op, Src = #x86_temp{}, Dst = #x86_fpreg{reg = Reg}) ->
  %% Handle that st(0) is sometimes implicit.
  if Reg =:= 0 -> [hipe_x86:mk_fp_unop(Op, Src)];
     true -> [hipe_x86:mk_fp_binop(Op, Src, Dst)]
  end;
format_fp_binop(Op, Src, Dst) ->
  [hipe_x86:mk_fp_binop(Op, Src, Dst)].

in_map(X, Map) ->
  lists:member(X, Map).

push_list(L, Map) ->
  push_list(L, Map, []).
push_list([H|T], Map, Acc) ->
  {Insn, NewMap} = push(H,Map),
  push_list(T, NewMap, Acc++Insn);
push_list([], Map, Acc) ->
  {Acc, Map}.

push(X, Map0) ->
  {PopInsn, Map} = 
    if length(Map0) > 7 -> pop_a_temp(Map0);
       true -> {[], Map0}
    end,
  NewX = get_new_opnd(X,Map),
  NewMap = [X | Map],
  PushOp = [hipe_x86:mk_fp_unop(fld, NewX)],
  {PopInsn ++ PushOp, NewMap}.

pop([_|Map]) ->
  Map.

pop_insn() ->
  [hipe_x86:mk_fp_unop('fstp',mk_st(0))].

pop_dead(Dead, Map) ->
  Dead0 = [X || X <- Map, lists:member(X,Dead)],
  pop_dead(Dead0, Map, []).

pop_dead([D|Dead], Map, Code) ->
  {I, NewMap0} = switch_first(D, Map),
  NewMap = pop(NewMap0),
  Store = case D of
	    #x86_temp{} -> [hipe_x86:mk_fp_unop('fstp', D)];
	    _ -> pop_insn()
	  end,
  pop_dead(Dead, NewMap, Code++I++Store);
pop_dead([], Map, Code) ->
  {Code,Map}.

pop_all(Map) ->
  {Code, _} = pop_dead(Map, Map),
  Code.

pop_member(Member, Map) ->
  {Head,[_|T]} = lists:splitwith(fun(X)-> X =/= Member end, Map),
  {[hipe_x86:mk_fp_unop('fstp', mk_st(get_pos(Member, Map, 0)))],
   Head++T}.

pop_a_temp(Map) ->
  Temp = find_a_temp(Map),
  {SwitchInsn, NewMap0} = switch_first(Temp, Map),
  NewMap = pop(NewMap0),
  {SwitchInsn ++ [hipe_x86:mk_fp_unop('fstp', Temp)], NewMap}.

find_a_temp([H = #x86_temp{}|_]) ->
  H;
find_a_temp([_|T]) ->
  find_a_temp(T);
find_a_temp([]) ->
  ?EXIT({noTempOnFPStack,{}}).

switch_first(X, Map = [H|_]) ->
  Pos = get_pos(X, Map, 0),
  case Pos of
    0 -> 
      {[], Map};
    notFound ->
      push(X, Map);
    _ ->	    
      {[_|Head], [_|Tail]} = lists:splitwith(fun(Y)-> Y =/= X end, Map),
      NewMap = [X|Head] ++ [H|Tail],
      Ins = hipe_x86:mk_fp_unop(fxch, mk_st(Pos)),
      {[Ins], NewMap}
  end;
switch_first(X, Map) ->
  push(X, Map).

get_pos(X, [H|T], Pos) ->
  if X =:= H -> Pos;
     true -> get_pos(X, T, Pos+1)
  end;
get_pos(_, [], _) ->
  notFound.

get_new_opnd(X, Map) ->
  I = get_pos(X, Map, 0),
  case I of
    notFound ->
      %% The operand is probably a spilled float.
      X;
    _ ->
      mk_st(I)
  end.

is_fp(#x86_fpreg{}) ->
  true;
is_fp(#x86_mem{type = Type}) ->
  Type =:= 'double';
is_fp(#x86_temp{type = Type}) ->
  Type =:= 'double'.

handle_insn(I) ->
  case I of
    #fmove{} -> true;
    #fp_unop{} -> true;
    #fp_binop{} -> true;
    #pseudo_call{} ->true;
    %% #ret{} -> true;
    _ -> false
  end.

is_liveOut(X, LiveOut) ->
  ordsets:is_element(X, LiveOut).

mk_st(X) ->
  hipe_x86:mk_fpreg(X, false).

reverse_op(Op) ->
  case Op of
    'fsub' -> 'fsubr';
    'fdiv' -> 'fdivr';
    'fsubr'-> 'fsub';
    'fdivr' -> 'fdiv';
    _ -> Op
  end.

mk_op_pop(Op) ->
  case Op of
    'fadd'-> 'faddp';
    'fdiv' -> 'fdivp';
    'fdivr' -> 'fdivrp';
    'fmul' -> 'fmulp';
    'fsub' -> 'fsubp';
    'fsubr' -> 'fsubrp';
    _ -> ?EXIT({operandHasNoPopVariant,{Op}})
  end.

butlast([X|Xs]) -> butlast(Xs,X).

butlast([],_) -> [];
butlast([X|Xs],Y) -> [Y|butlast(Xs,X)].

%%pp_insn(Op, Src, Dst) ->
%%  pp([hipe_x86:mk_fp_binop(Op, Src, Dst)]).

%%pp([I|Ins]) ->
%%  hipe_x86_pp:pp_insn(I),
%%  pp(Ins);
%%pp([]) ->
%%  [].

pseudo_pop(Map) when length(Map) > 0 ->
  Dst = hipe_x86:mk_new_temp('double'),
  pseudo_pop(Dst, length(Map), []);
pseudo_pop(_) ->
  [].

pseudo_pop(Dst, St, Acc) when St > 1 ->
  %% Store all members of the stack to a single temporary to force 
  %% any floating point overflow exceptions to occur even though we
  %% don't have overflow for the extended double precision in the x87.
  pseudo_pop(Dst, St-1, 
	     [hipe_x86:mk_fp_unop('fxch', mk_st(St-1)),
	      hipe_x86:mk_fp_unop('fst', Dst),
	      hipe_x86:mk_fp_unop('fxch', mk_st(St-1))
	      |Acc]);
pseudo_pop(Dst, _St, Acc) ->
  [hipe_x86:mk_fp_unop('fst', Dst)|Acc].