summaryrefslogtreecommitdiffstats
path: root/js/src/jit/x86/CodeGenerator-x86.cpp
blob: c0bda64e04127de64bf9e1c4ff9429d64fe25d6f (plain)
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "jit/x86/CodeGenerator-x86.h"

#include "mozilla/Casting.h"
#include "mozilla/DebugOnly.h"

#include <iterator>

#include "jsnum.h"

#include "jit/CodeGenerator.h"
#include "jit/MIR.h"
#include "jit/MIRGraph.h"
#include "js/Conversions.h"
#include "vm/Shape.h"
#include "wasm/WasmTypes.h"

#include "jit/MacroAssembler-inl.h"
#include "jit/shared/CodeGenerator-shared-inl.h"
#include "vm/JSScript-inl.h"

using namespace js;
using namespace js::jit;

using JS::GenericNaN;
using mozilla::BitwiseCast;
using mozilla::DebugOnly;
using mozilla::FloatingPoint;

CodeGeneratorX86::CodeGeneratorX86(MIRGenerator* gen, LIRGraph* graph,
                                   MacroAssembler* masm)
    : CodeGeneratorX86Shared(gen, graph, masm) {}

static const uint32_t FrameSizes[] = {128, 256, 512, 1024};

FrameSizeClass FrameSizeClass::FromDepth(uint32_t frameDepth) {
  for (uint32_t i = 0; i < std::size(FrameSizes); i++) {
    if (frameDepth < FrameSizes[i]) {
      return FrameSizeClass(i);
    }
  }

  return FrameSizeClass::None();
}

FrameSizeClass FrameSizeClass::ClassLimit() {
  return FrameSizeClass(std::size(FrameSizes));
}

uint32_t FrameSizeClass::frameSize() const {
  MOZ_ASSERT(class_ != NO_FRAME_SIZE_CLASS_ID);
  MOZ_ASSERT(class_ < std::size(FrameSizes));

  return FrameSizes[class_];
}

ValueOperand CodeGeneratorX86::ToValue(LInstruction* ins, size_t pos) {
  Register typeReg = ToRegister(ins->getOperand(pos + TYPE_INDEX));
  Register payloadReg = ToRegister(ins->getOperand(pos + PAYLOAD_INDEX));
  return ValueOperand(typeReg, payloadReg);
}

ValueOperand CodeGeneratorX86::ToTempValue(LInstruction* ins, size_t pos) {
  Register typeReg = ToRegister(ins->getTemp(pos + TYPE_INDEX));
  Register payloadReg = ToRegister(ins->getTemp(pos + PAYLOAD_INDEX));
  return ValueOperand(typeReg, payloadReg);
}

void CodeGenerator::visitValue(LValue* value) {
  const ValueOperand out = ToOutValue(value);
  masm.moveValue(value->value(), out);
}

void CodeGenerator::visitBox(LBox* box) {
  const LDefinition* type = box->getDef(TYPE_INDEX);

  DebugOnly<const LAllocation*> a = box->getOperand(0);
  MOZ_ASSERT(!a->isConstant());

  // On x86, the input operand and the output payload have the same
  // virtual register. All that needs to be written is the type tag for
  // the type definition.
  masm.mov(ImmWord(MIRTypeToTag(box->type())), ToRegister(type));
}

void CodeGenerator::visitBoxFloatingPoint(LBoxFloatingPoint* box) {
  const AnyRegister in = ToAnyRegister(box->getOperand(0));
  const ValueOperand out = ToOutValue(box);

  masm.moveValue(TypedOrValueRegister(box->type(), in), out);
}

void CodeGenerator::visitUnbox(LUnbox* unbox) {
  // Note that for unbox, the type and payload indexes are switched on the
  // inputs.
  Operand type = ToOperand(unbox->type());
  Operand payload = ToOperand(unbox->payload());
  Register output = ToRegister(unbox->output());
  MUnbox* mir = unbox->mir();

  JSValueTag tag = MIRTypeToTag(mir->type());
  if (mir->fallible()) {
    masm.cmp32(type, Imm32(tag));
    bailoutIf(Assembler::NotEqual, unbox->snapshot());
  } else {
#ifdef DEBUG
    Label ok;
    masm.branch32(Assembler::Equal, type, Imm32(tag), &ok);
    masm.assumeUnreachable("Infallible unbox type mismatch");
    masm.bind(&ok);
#endif
  }

  // Note: If spectreValueMasking is disabled, then this instruction will
  // default to a no-op as long as the lowering allocate the same register for
  // the output and the payload.
  masm.unboxNonDouble(type, payload, output, ValueTypeFromMIRType(mir->type()));
}

// See ../CodeGenerator.cpp for more information.
void CodeGenerator::visitWasmRegisterResult(LWasmRegisterResult* lir) {}

void CodeGenerator::visitWasmUint32ToDouble(LWasmUint32ToDouble* lir) {
  Register input = ToRegister(lir->input());
  Register temp = ToRegister(lir->temp());

  if (input != temp) {
    masm.mov(input, temp);
  }

  // Beware: convertUInt32ToDouble clobbers input.
  masm.convertUInt32ToDouble(temp, ToFloatRegister(lir->output()));
}

void CodeGenerator::visitWasmUint32ToFloat32(LWasmUint32ToFloat32* lir) {
  Register input = ToRegister(lir->input());
  Register temp = ToRegister(lir->temp());
  FloatRegister output = ToFloatRegister(lir->output());

  if (input != temp) {
    masm.mov(input, temp);
  }

  // Beware: convertUInt32ToFloat32 clobbers input.
  masm.convertUInt32ToFloat32(temp, output);
}

void CodeGenerator::visitWasmHeapBase(LWasmHeapBase* ins) {
  masm.loadPtr(
      Address(ToRegister(ins->tlsPtr()), offsetof(wasm::TlsData, memoryBase)),
      ToRegister(ins->output()));
}

template <typename T>
void CodeGeneratorX86::emitWasmLoad(T* ins) {
  const MWasmLoad* mir = ins->mir();

  uint32_t offset = mir->access().offset();
  MOZ_ASSERT(offset < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* ptr = ins->ptr();
  const LAllocation* memoryBase = ins->memoryBase();

  // Lowering has set things up so that we can use a BaseIndex form if the
  // pointer is constant and the offset is zero, or if the pointer is zero.

  Operand srcAddr =
      ptr->isBogus()
          ? Operand(ToRegister(memoryBase),
                    offset ? offset : mir->base()->toConstant()->toInt32())
          : Operand(ToRegister(memoryBase), ToRegister(ptr), TimesOne, offset);

  if (mir->type() == MIRType::Int64) {
    MOZ_ASSERT_IF(mir->access().isAtomic(),
                  mir->access().type() != Scalar::Int64);
    masm.wasmLoadI64(mir->access(), srcAddr, ToOutRegister64(ins));
  } else {
    masm.wasmLoad(mir->access(), srcAddr, ToAnyRegister(ins->output()));
  }
}

void CodeGenerator::visitWasmLoad(LWasmLoad* ins) { emitWasmLoad(ins); }

void CodeGenerator::visitWasmLoadI64(LWasmLoadI64* ins) { emitWasmLoad(ins); }

template <typename T>
void CodeGeneratorX86::emitWasmStore(T* ins) {
  const MWasmStore* mir = ins->mir();

  uint32_t offset = mir->access().offset();
  MOZ_ASSERT(offset < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* ptr = ins->ptr();
  const LAllocation* memoryBase = ins->memoryBase();

  // Lowering has set things up so that we can use a BaseIndex form if the
  // pointer is constant and the offset is zero, or if the pointer is zero.

  Operand dstAddr =
      ptr->isBogus()
          ? Operand(ToRegister(memoryBase),
                    offset ? offset : mir->base()->toConstant()->toInt32())
          : Operand(ToRegister(memoryBase), ToRegister(ptr), TimesOne, offset);

  if (mir->access().type() == Scalar::Int64) {
    Register64 value =
        ToRegister64(ins->getInt64Operand(LWasmStoreI64::ValueIndex));
    masm.wasmStoreI64(mir->access(), value, dstAddr);
  } else {
    AnyRegister value = ToAnyRegister(ins->getOperand(LWasmStore::ValueIndex));
    masm.wasmStore(mir->access(), value, dstAddr);
  }
}

void CodeGenerator::visitWasmStore(LWasmStore* ins) { emitWasmStore(ins); }

void CodeGenerator::visitWasmStoreI64(LWasmStoreI64* ins) {
  emitWasmStore(ins);
}

void CodeGenerator::visitWasmCompareExchangeHeap(
    LWasmCompareExchangeHeap* ins) {
  MWasmCompareExchangeHeap* mir = ins->mir();

  Register ptrReg = ToRegister(ins->ptr());
  Register oldval = ToRegister(ins->oldValue());
  Register newval = ToRegister(ins->newValue());
  Register addrTemp = ToRegister(ins->addrTemp());
  Register memoryBase = ToRegister(ins->memoryBase());
  Register output = ToRegister(ins->output());

  masm.leal(Operand(memoryBase, ptrReg, TimesOne, mir->access().offset()),
            addrTemp);

  Address memAddr(addrTemp, 0);
  masm.wasmCompareExchange(mir->access(), memAddr, oldval, newval, output);
}

void CodeGenerator::visitWasmAtomicExchangeHeap(LWasmAtomicExchangeHeap* ins) {
  MWasmAtomicExchangeHeap* mir = ins->mir();

  Register ptrReg = ToRegister(ins->ptr());
  Register value = ToRegister(ins->value());
  Register addrTemp = ToRegister(ins->addrTemp());
  Register memoryBase = ToRegister(ins->memoryBase());
  Register output = ToRegister(ins->output());

  masm.leal(Operand(memoryBase, ptrReg, TimesOne, mir->access().offset()),
            addrTemp);

  Address memAddr(addrTemp, 0);
  masm.wasmAtomicExchange(mir->access(), memAddr, value, output);
}

void CodeGenerator::visitWasmAtomicBinopHeap(LWasmAtomicBinopHeap* ins) {
  MWasmAtomicBinopHeap* mir = ins->mir();

  Register ptrReg = ToRegister(ins->ptr());
  Register temp =
      ins->temp()->isBogusTemp() ? InvalidReg : ToRegister(ins->temp());
  Register addrTemp = ToRegister(ins->addrTemp());
  Register out = ToRegister(ins->output());
  const LAllocation* value = ins->value();
  AtomicOp op = mir->operation();
  Register memoryBase = ToRegister(ins->memoryBase());

  masm.leal(Operand(memoryBase, ptrReg, TimesOne, mir->access().offset()),
            addrTemp);

  Address memAddr(addrTemp, 0);
  if (value->isConstant()) {
    masm.wasmAtomicFetchOp(mir->access(), op, Imm32(ToInt32(value)), memAddr,
                           temp, out);
  } else {
    masm.wasmAtomicFetchOp(mir->access(), op, ToRegister(value), memAddr, temp,
                           out);
  }
}

void CodeGenerator::visitWasmAtomicBinopHeapForEffect(
    LWasmAtomicBinopHeapForEffect* ins) {
  MWasmAtomicBinopHeap* mir = ins->mir();
  MOZ_ASSERT(!mir->hasUses());

  Register ptrReg = ToRegister(ins->ptr());
  Register addrTemp = ToRegister(ins->addrTemp());
  const LAllocation* value = ins->value();
  AtomicOp op = mir->operation();
  Register memoryBase = ToRegister(ins->memoryBase());

  masm.leal(Operand(memoryBase, ptrReg, TimesOne, mir->access().offset()),
            addrTemp);

  Address memAddr(addrTemp, 0);
  if (value->isConstant()) {
    masm.wasmAtomicEffectOp(mir->access(), op, Imm32(ToInt32(value)), memAddr,
                            InvalidReg);
  } else {
    masm.wasmAtomicEffectOp(mir->access(), op, ToRegister(value), memAddr,
                            InvalidReg);
  }
}

void CodeGenerator::visitWasmAtomicLoadI64(LWasmAtomicLoadI64* ins) {
  uint32_t offset = ins->mir()->access().offset();
  MOZ_ASSERT(offset < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* memoryBase = ins->memoryBase();
  const LAllocation* ptr = ins->ptr();
  BaseIndex srcAddr(ToRegister(memoryBase), ToRegister(ptr), TimesOne, offset);

  MOZ_ASSERT(ToRegister(ins->t1()) == ecx);
  MOZ_ASSERT(ToRegister(ins->t2()) == ebx);
  MOZ_ASSERT(ToOutRegister64(ins).high == edx);
  MOZ_ASSERT(ToOutRegister64(ins).low == eax);

  masm.wasmAtomicLoad64(ins->mir()->access(), srcAddr, Register64(ecx, ebx),
                        Register64(edx, eax));
}

void CodeGenerator::visitWasmCompareExchangeI64(LWasmCompareExchangeI64* ins) {
  uint32_t offset = ins->mir()->access().offset();
  MOZ_ASSERT(offset < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* memoryBase = ins->memoryBase();
  const LAllocation* ptr = ins->ptr();
  Operand srcAddr(ToRegister(memoryBase), ToRegister(ptr), TimesOne, offset);

  MOZ_ASSERT(ToRegister64(ins->expected()).low == eax);
  MOZ_ASSERT(ToRegister64(ins->expected()).high == edx);
  MOZ_ASSERT(ToRegister64(ins->replacement()).low == ebx);
  MOZ_ASSERT(ToRegister64(ins->replacement()).high == ecx);
  MOZ_ASSERT(ToOutRegister64(ins).low == eax);
  MOZ_ASSERT(ToOutRegister64(ins).high == edx);

  masm.append(ins->mir()->access(), masm.size());
  masm.lock_cmpxchg8b(edx, eax, ecx, ebx, srcAddr);
}

template <typename T>
void CodeGeneratorX86::emitWasmStoreOrExchangeAtomicI64(
    T* ins, const wasm::MemoryAccessDesc& access) {
  MOZ_ASSERT(access.offset() < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* memoryBase = ins->memoryBase();
  const LAllocation* ptr = ins->ptr();
  Operand srcAddr(ToRegister(memoryBase), ToRegister(ptr), TimesOne,
                  access.offset());

  DebugOnly<const LInt64Allocation> value = ins->value();
  MOZ_ASSERT(ToRegister64(value).low == ebx);
  MOZ_ASSERT(ToRegister64(value).high == ecx);

  // eax and ebx will be overwritten every time through the loop but
  // memoryBase and ptr must remain live for a possible second iteration.

  MOZ_ASSERT(ToRegister(memoryBase) != edx && ToRegister(memoryBase) != eax);
  MOZ_ASSERT(ToRegister(ptr) != edx && ToRegister(ptr) != eax);

  Label again;
  masm.bind(&again);
  masm.append(access, masm.size());
  masm.lock_cmpxchg8b(edx, eax, ecx, ebx, srcAddr);
  masm.j(Assembler::Condition::NonZero, &again);
}

void CodeGenerator::visitWasmAtomicStoreI64(LWasmAtomicStoreI64* ins) {
  MOZ_ASSERT(ToRegister(ins->t1()) == edx);
  MOZ_ASSERT(ToRegister(ins->t2()) == eax);

  emitWasmStoreOrExchangeAtomicI64(ins, ins->mir()->access());
}

void CodeGenerator::visitWasmAtomicExchangeI64(LWasmAtomicExchangeI64* ins) {
  MOZ_ASSERT(ToOutRegister64(ins).high == edx);
  MOZ_ASSERT(ToOutRegister64(ins).low == eax);

  emitWasmStoreOrExchangeAtomicI64(ins, ins->access());
}

void CodeGenerator::visitWasmAtomicBinopI64(LWasmAtomicBinopI64* ins) {
  uint32_t offset = ins->access().offset();
  MOZ_ASSERT(offset < masm.wasmMaxOffsetGuardLimit());

  const LAllocation* memoryBase = ins->memoryBase();
  const LAllocation* ptr = ins->ptr();

  BaseIndex srcAddr(ToRegister(memoryBase), ToRegister(ptr), TimesOne, offset);

  MOZ_ASSERT(ToRegister(memoryBase) == esi || ToRegister(memoryBase) == edi);
  MOZ_ASSERT(ToRegister(ptr) == esi || ToRegister(ptr) == edi);

  Register64 value = ToRegister64(ins->value());

  MOZ_ASSERT(value.low == ebx);
  MOZ_ASSERT(value.high == ecx);

  Register64 output = ToOutRegister64(ins);

  MOZ_ASSERT(output.low == eax);
  MOZ_ASSERT(output.high == edx);

  masm.Push(ecx);
  masm.Push(ebx);

  Address valueAddr(esp, 0);

  // Here the `value` register acts as a temp, we'll restore it below.
  masm.wasmAtomicFetchOp64(ins->access(), ins->operation(), valueAddr, srcAddr,
                           value, output);

  masm.Pop(ebx);
  masm.Pop(ecx);
}

namespace js {
namespace jit {

class OutOfLineTruncate : public OutOfLineCodeBase<CodeGeneratorX86> {
  LInstruction* ins_;

 public:
  explicit OutOfLineTruncate(LInstruction* ins) : ins_(ins) {
    MOZ_ASSERT(ins_->isTruncateDToInt32() ||
               ins_->isWasmBuiltinTruncateDToInt32());
  }

  void accept(CodeGeneratorX86* codegen) override {
    codegen->visitOutOfLineTruncate(this);
  }

  LAllocation* input() { return ins_->getOperand(0); }
  LDefinition* output() { return ins_->getDef(0); }
  LDefinition* tempFloat() { return ins_->getTemp(0); }

  wasm::BytecodeOffset bytecodeOffset() const {
    if (ins_->isTruncateDToInt32()) {
      return ins_->toTruncateDToInt32()->mir()->bytecodeOffset();
    }

    return ins_->toWasmBuiltinTruncateDToInt32()->mir()->bytecodeOffset();
  }
};

class OutOfLineTruncateFloat32 : public OutOfLineCodeBase<CodeGeneratorX86> {
  LInstruction* ins_;

 public:
  explicit OutOfLineTruncateFloat32(LInstruction* ins) : ins_(ins) {
    MOZ_ASSERT(ins_->isTruncateFToInt32() ||
               ins_->isWasmBuiltinTruncateFToInt32());
  }

  void accept(CodeGeneratorX86* codegen) override {
    codegen->visitOutOfLineTruncateFloat32(this);
  }

  LAllocation* input() { return ins_->getOperand(0); }
  LDefinition* output() { return ins_->getDef(0); }
  LDefinition* tempFloat() { return ins_->getTemp(0); }

  wasm::BytecodeOffset bytecodeOffset() const {
    if (ins_->isTruncateFToInt32()) {
      return ins_->toTruncateDToInt32()->mir()->bytecodeOffset();
    }

    return ins_->toWasmBuiltinTruncateFToInt32()->mir()->bytecodeOffset();
  }
};

}  // namespace jit
}  // namespace js

void CodeGenerator::visitTruncateDToInt32(LTruncateDToInt32* ins) {
  FloatRegister input = ToFloatRegister(ins->input());
  Register output = ToRegister(ins->output());

  OutOfLineTruncate* ool = new (alloc()) OutOfLineTruncate(ins);
  addOutOfLineCode(ool, ins->mir());

  masm.branchTruncateDoubleMaybeModUint32(input, output, ool->entry());
  masm.bind(ool->rejoin());
}

void CodeGenerator::visitWasmBuiltinTruncateDToInt32(
    LWasmBuiltinTruncateDToInt32* lir) {
  FloatRegister input = ToFloatRegister(lir->getOperand(0));
  Register output = ToRegister(lir->getDef(0));

  OutOfLineTruncate* ool = new (alloc()) OutOfLineTruncate(lir);
  addOutOfLineCode(ool, lir->mir());

  masm.branchTruncateDoubleMaybeModUint32(input, output, ool->entry());
  masm.bind(ool->rejoin());
}

void CodeGenerator::visitTruncateFToInt32(LTruncateFToInt32* ins) {
  FloatRegister input = ToFloatRegister(ins->input());
  Register output = ToRegister(ins->output());

  OutOfLineTruncateFloat32* ool = new (alloc()) OutOfLineTruncateFloat32(ins);
  addOutOfLineCode(ool, ins->mir());

  masm.branchTruncateFloat32MaybeModUint32(input, output, ool->entry());
  masm.bind(ool->rejoin());
}

void CodeGenerator::visitWasmBuiltinTruncateFToInt32(
    LWasmBuiltinTruncateFToInt32* lir) {
  FloatRegister input = ToFloatRegister(lir->getOperand(0));
  Register output = ToRegister(lir->getDef(0));

  OutOfLineTruncateFloat32* ool = new (alloc()) OutOfLineTruncateFloat32(lir);
  addOutOfLineCode(ool, lir->mir());

  masm.branchTruncateFloat32MaybeModUint32(input, output, ool->entry());
  masm.bind(ool->rejoin());
}

void CodeGeneratorX86::visitOutOfLineTruncate(OutOfLineTruncate* ool) {
  FloatRegister input = ToFloatRegister(ool->input());
  Register output = ToRegister(ool->output());

  Label fail;

  if (Assembler::HasSSE3()) {
    Label failPopDouble;
    // Push double.
    masm.subl(Imm32(sizeof(double)), esp);
    masm.storeDouble(input, Operand(esp, 0));

    // Check exponent to avoid fp exceptions.
    masm.branchDoubleNotInInt64Range(Address(esp, 0), output, &failPopDouble);

    // Load double, perform 64-bit truncation.
    masm.truncateDoubleToInt64(Address(esp, 0), Address(esp, 0), output);

    // Load low word, pop double and jump back.
    masm.load32(Address(esp, 0), output);
    masm.addl(Imm32(sizeof(double)), esp);
    masm.jump(ool->rejoin());

    masm.bind(&failPopDouble);
    masm.addl(Imm32(sizeof(double)), esp);
    masm.jump(&fail);
  } else {
    FloatRegister temp = ToFloatRegister(ool->tempFloat());

    // Try to convert doubles representing integers within 2^32 of a signed
    // integer, by adding/subtracting 2^32 and then trying to convert to int32.
    // This has to be an exact conversion, as otherwise the truncation works
    // incorrectly on the modified value.
    {
      ScratchDoubleScope fpscratch(masm);
      masm.zeroDouble(fpscratch);
      masm.vucomisd(fpscratch, input);
      masm.j(Assembler::Parity, &fail);
    }

    {
      Label positive;
      masm.j(Assembler::Above, &positive);

      masm.loadConstantDouble(4294967296.0, temp);
      Label skip;
      masm.jmp(&skip);

      masm.bind(&positive);
      masm.loadConstantDouble(-4294967296.0, temp);
      masm.bind(&skip);
    }

    masm.addDouble(input, temp);
    masm.vcvttsd2si(temp, output);
    ScratchDoubleScope fpscratch(masm);
    masm.vcvtsi2sd(output, fpscratch, fpscratch);

    masm.vucomisd(fpscratch, temp);
    masm.j(Assembler::Parity, &fail);
    masm.j(Assembler::Equal, ool->rejoin());
  }

  masm.bind(&fail);
  {
    if (gen->compilingWasm()) {
      masm.Push(WasmTlsReg);
    }
    int32_t framePushedAfterTls = masm.framePushed();

    saveVolatile(output);

    if (gen->compilingWasm()) {
      masm.setupWasmABICall();
      masm.passABIArg(input, MoveOp::DOUBLE);

      int32_t tlsOffset = masm.framePushed() - framePushedAfterTls;
      masm.callWithABI(ool->bytecodeOffset(), wasm::SymbolicAddress::ToInt32,
                       mozilla::Some(tlsOffset));
    } else {
      using Fn = int32_t (*)(double);
      masm.setupUnalignedABICall(output);
      masm.passABIArg(input, MoveOp::DOUBLE);
      masm.callWithABI<Fn, JS::ToInt32>(MoveOp::GENERAL,
                                        CheckUnsafeCallWithABI::DontCheckOther);
    }
    masm.storeCallInt32Result(output);

    restoreVolatile(output);

    if (gen->compilingWasm()) {
      masm.Pop(WasmTlsReg);
    }
  }

  masm.jump(ool->rejoin());
}

void CodeGeneratorX86::visitOutOfLineTruncateFloat32(
    OutOfLineTruncateFloat32* ool) {
  FloatRegister input = ToFloatRegister(ool->input());
  Register output = ToRegister(ool->output());

  Label fail;

  if (Assembler::HasSSE3()) {
    Label failPopFloat;

    // Push float32, but subtracts 64 bits so that the value popped by fisttp
    // fits
    masm.subl(Imm32(sizeof(uint64_t)), esp);
    masm.storeFloat32(input, Operand(esp, 0));

    // Check exponent to avoid fp exceptions.
    masm.branchDoubleNotInInt64Range(Address(esp, 0), output, &failPopFloat);

    // Load float, perform 32-bit truncation.
    masm.truncateFloat32ToInt64(Address(esp, 0), Address(esp, 0), output);

    // Load low word, pop 64bits and jump back.
    masm.load32(Address(esp, 0), output);
    masm.addl(Imm32(sizeof(uint64_t)), esp);
    masm.jump(ool->rejoin());

    masm.bind(&failPopFloat);
    masm.addl(Imm32(sizeof(uint64_t)), esp);
    masm.jump(&fail);
  } else {
    FloatRegister temp = ToFloatRegister(ool->tempFloat());

    // Try to convert float32 representing integers within 2^32 of a signed
    // integer, by adding/subtracting 2^32 and then trying to convert to int32.
    // This has to be an exact conversion, as otherwise the truncation works
    // incorrectly on the modified value.
    {
      ScratchFloat32Scope fpscratch(masm);
      masm.zeroFloat32(fpscratch);
      masm.vucomiss(fpscratch, input);
      masm.j(Assembler::Parity, &fail);
    }

    {
      Label positive;
      masm.j(Assembler::Above, &positive);

      masm.loadConstantFloat32(4294967296.f, temp);
      Label skip;
      masm.jmp(&skip);

      masm.bind(&positive);
      masm.loadConstantFloat32(-4294967296.f, temp);
      masm.bind(&skip);
    }

    masm.addFloat32(input, temp);
    masm.vcvttss2si(temp, output);
    ScratchFloat32Scope fpscratch(masm);
    masm.vcvtsi2ss(output, fpscratch, fpscratch);

    masm.vucomiss(fpscratch, temp);
    masm.j(Assembler::Parity, &fail);
    masm.j(Assembler::Equal, ool->rejoin());
  }

  masm.bind(&fail);
  {
    if (gen->compilingWasm()) {
      masm.Push(WasmTlsReg);
    }
    int32_t framePushedAfterTls = masm.framePushed();

    saveVolatile(output);

    masm.Push(input);

    if (gen->compilingWasm()) {
      masm.setupWasmABICall();
    } else {
      masm.setupUnalignedABICall(output);
    }

    masm.vcvtss2sd(input, input, input);
    masm.passABIArg(input.asDouble(), MoveOp::DOUBLE);

    if (gen->compilingWasm()) {
      int32_t tlsOffset = masm.framePushed() - framePushedAfterTls;
      masm.callWithABI(ool->bytecodeOffset(), wasm::SymbolicAddress::ToInt32,
                       mozilla::Some(tlsOffset));
    } else {
      using Fn = int32_t (*)(double);
      masm.callWithABI<Fn, JS::ToInt32>(MoveOp::GENERAL,
                                        CheckUnsafeCallWithABI::DontCheckOther);
    }

    masm.storeCallInt32Result(output);
    masm.Pop(input);

    restoreVolatile(output);

    if (gen->compilingWasm()) {
      masm.Pop(WasmTlsReg);
    }
  }

  masm.jump(ool->rejoin());
}

void CodeGenerator::visitCompareI64(LCompareI64* lir) {
  MCompare* mir = lir->mir();
  MOZ_ASSERT(mir->compareType() == MCompare::Compare_Int64 ||
             mir->compareType() == MCompare::Compare_UInt64);

  const LInt64Allocation lhs = lir->getInt64Operand(LCompareI64::Lhs);
  const LInt64Allocation rhs = lir->getInt64Operand(LCompareI64::Rhs);
  Register64 lhsRegs = ToRegister64(lhs);
  Register output = ToRegister(lir->output());

  bool isSigned = mir->compareType() == MCompare::Compare_Int64;
  Assembler::Condition condition = JSOpToCondition(lir->jsop(), isSigned);
  Label done;

  masm.move32(Imm32(1), output);

  if (IsConstant(rhs)) {
    Imm64 imm = Imm64(ToInt64(rhs));
    masm.branch64(condition, lhsRegs, imm, &done);
  } else {
    Register64 rhsRegs = ToRegister64(rhs);
    masm.branch64(condition, lhsRegs, rhsRegs, &done);
  }

  masm.xorl(output, output);
  masm.bind(&done);
}

void CodeGenerator::visitCompareI64AndBranch(LCompareI64AndBranch* lir) {
  MCompare* mir = lir->cmpMir();
  MOZ_ASSERT(mir->compareType() == MCompare::Compare_Int64 ||
             mir->compareType() == MCompare::Compare_UInt64);

  const LInt64Allocation lhs = lir->getInt64Operand(LCompareI64::Lhs);
  const LInt64Allocation rhs = lir->getInt64Operand(LCompareI64::Rhs);
  Register64 lhsRegs = ToRegister64(lhs);

  bool isSigned = mir->compareType() == MCompare::Compare_Int64;
  Assembler::Condition condition = JSOpToCondition(lir->jsop(), isSigned);

  Label* trueLabel = getJumpLabelForBranch(lir->ifTrue());
  Label* falseLabel = getJumpLabelForBranch(lir->ifFalse());

  if (isNextBlock(lir->ifFalse()->lir())) {
    falseLabel = nullptr;
  } else if (isNextBlock(lir->ifTrue()->lir())) {
    condition = Assembler::InvertCondition(condition);
    trueLabel = falseLabel;
    falseLabel = nullptr;
  }

  if (IsConstant(rhs)) {
    Imm64 imm = Imm64(ToInt64(rhs));
    masm.branch64(condition, lhsRegs, imm, trueLabel, falseLabel);
  } else {
    Register64 rhsRegs = ToRegister64(rhs);
    masm.branch64(condition, lhsRegs, rhsRegs, trueLabel, falseLabel);
  }
}

void CodeGenerator::visitDivOrModI64(LDivOrModI64* lir) {
  MOZ_ASSERT(gen->compilingWasm());
  MOZ_ASSERT(ToRegister(lir->getOperand(LDivOrModI64::Tls)) == WasmTlsReg);

  masm.Push(WasmTlsReg);
  int32_t framePushedAfterTls = masm.framePushed();

  Register64 lhs = ToRegister64(lir->getInt64Operand(LDivOrModI64::Lhs));
  Register64 rhs = ToRegister64(lir->getInt64Operand(LDivOrModI64::Rhs));
  Register64 output = ToOutRegister64(lir);

  MOZ_ASSERT(output == ReturnReg64);

  Label done;

  // Handle divide by zero.
  if (lir->canBeDivideByZero()) {
    Label nonZero;
    // We can use WasmTlsReg as temp register because we preserved it before.
    masm.branchTest64(Assembler::NonZero, rhs, rhs, WasmTlsReg, &nonZero);
    masm.wasmTrap(wasm::Trap::IntegerDivideByZero, lir->bytecodeOffset());
    masm.bind(&nonZero);
  }

  MDefinition* mir = lir->mir();

  // Handle an integer overflow exception from INT64_MIN / -1.
  if (lir->canBeNegativeOverflow()) {
    Label notOverflow;
    masm.branch64(Assembler::NotEqual, lhs, Imm64(INT64_MIN), &notOverflow);
    masm.branch64(Assembler::NotEqual, rhs, Imm64(-1), &notOverflow);
    if (mir->isWasmBuiltinModI64()) {
      masm.xor64(output, output);
    } else {
      masm.wasmTrap(wasm::Trap::IntegerOverflow, lir->bytecodeOffset());
    }
    masm.jump(&done);
    masm.bind(&notOverflow);
  }

  masm.setupWasmABICall();
  masm.passABIArg(lhs.high);
  masm.passABIArg(lhs.low);
  masm.passABIArg(rhs.high);
  masm.passABIArg(rhs.low);

  int32_t tlsOffset = masm.framePushed() - framePushedAfterTls;
  if (mir->isWasmBuiltinModI64()) {
    masm.callWithABI(lir->bytecodeOffset(), wasm::SymbolicAddress::ModI64,
                     mozilla::Some(tlsOffset));
  } else {
    masm.callWithABI(lir->bytecodeOffset(), wasm::SymbolicAddress::DivI64,
                     mozilla::Some(tlsOffset));
  }

  // output in edx:eax, move to output register.
  masm.movl(edx, output.high);
  MOZ_ASSERT(eax == output.low);

  masm.bind(&done);
  masm.Pop(WasmTlsReg);
}

void CodeGenerator::visitUDivOrModI64(LUDivOrModI64* lir) {
  MOZ_ASSERT(gen->compilingWasm());
  MOZ_ASSERT(ToRegister(lir->getOperand(LDivOrModI64::Tls)) == WasmTlsReg);

  masm.Push(WasmTlsReg);
  int32_t framePushedAfterTls = masm.framePushed();

  Register64 lhs = ToRegister64(lir->getInt64Operand(LDivOrModI64::Lhs));
  Register64 rhs = ToRegister64(lir->getInt64Operand(LDivOrModI64::Rhs));
  Register64 output = ToOutRegister64(lir);

  MOZ_ASSERT(output == ReturnReg64);

  // Prevent divide by zero.
  if (lir->canBeDivideByZero()) {
    Label nonZero;
    // We can use WasmTlsReg as temp register because we preserved it before.
    masm.branchTest64(Assembler::NonZero, rhs, rhs, WasmTlsReg, &nonZero);
    masm.wasmTrap(wasm::Trap::IntegerDivideByZero, lir->bytecodeOffset());
    masm.bind(&nonZero);
  }

  masm.setupWasmABICall();
  masm.passABIArg(lhs.high);
  masm.passABIArg(lhs.low);
  masm.passABIArg(rhs.high);
  masm.passABIArg(rhs.low);

  MDefinition* mir = lir->mir();
  int32_t tlsOffset = masm.framePushed() - framePushedAfterTls;
  if (mir->isWasmBuiltinModI64()) {
    masm.callWithABI(lir->bytecodeOffset(), wasm::SymbolicAddress::UModI64,
                     mozilla::Some(tlsOffset));
  } else {
    masm.callWithABI(lir->bytecodeOffset(), wasm::SymbolicAddress::UDivI64,
                     mozilla::Some(tlsOffset));
  }

  // output in edx:eax, move to output register.
  masm.movl(edx, output.high);
  MOZ_ASSERT(eax == output.low);

  masm.Pop(WasmTlsReg);
}

void CodeGeneratorX86::emitBigIntDiv(LBigIntDiv* ins, Register dividend,
                                     Register divisor, Register output,
                                     Label* fail) {
  // Callers handle division by zero and integer overflow.

  MOZ_ASSERT(dividend == eax);
  MOZ_ASSERT(output == edx);

  // Sign extend the lhs into rdx to make rdx:rax.
  masm.cdq();

  masm.idiv(divisor);

  // Create and return the result.
  masm.newGCBigInt(output, divisor, fail, bigIntsCanBeInNursery());
  masm.initializeBigInt(output, dividend);
}

void CodeGeneratorX86::emitBigIntMod(LBigIntMod* ins, Register dividend,
                                     Register divisor, Register output,
                                     Label* fail) {
  // Callers handle division by zero and integer overflow.

  MOZ_ASSERT(dividend == eax);
  MOZ_ASSERT(output == edx);

  // Sign extend the lhs into rdx to make edx:eax.
  masm.cdq();

  masm.idiv(divisor);

  // Move the remainder from edx.
  masm.movl(output, dividend);

  // Create and return the result.
  masm.newGCBigInt(output, divisor, fail, bigIntsCanBeInNursery());
  masm.initializeBigInt(output, dividend);
}

void CodeGenerator::visitWasmSelectI64(LWasmSelectI64* lir) {
  MOZ_ASSERT(lir->mir()->type() == MIRType::Int64);

  Register cond = ToRegister(lir->condExpr());
  Register64 falseExpr = ToRegister64(lir->falseExpr());
  Register64 out = ToOutRegister64(lir);

  MOZ_ASSERT(ToRegister64(lir->trueExpr()) == out,
             "true expr is reused for input");

  Label done;
  masm.branchTest32(Assembler::NonZero, cond, cond, &done);
  masm.movl(falseExpr.low, out.low);
  masm.movl(falseExpr.high, out.high);
  masm.bind(&done);
}

void CodeGenerator::visitWasmReinterpretFromI64(LWasmReinterpretFromI64* lir) {
  MOZ_ASSERT(lir->mir()->type() == MIRType::Double);
  MOZ_ASSERT(lir->mir()->input()->type() == MIRType::Int64);
  Register64 input = ToRegister64(lir->getInt64Operand(0));

  masm.Push(input.high);
  masm.Push(input.low);
  masm.vmovq(Operand(esp, 0), ToFloatRegister(lir->output()));
  masm.freeStack(sizeof(uint64_t));
}

void CodeGenerator::visitWasmReinterpretToI64(LWasmReinterpretToI64* lir) {
  MOZ_ASSERT(lir->mir()->type() == MIRType::Int64);
  MOZ_ASSERT(lir->mir()->input()->type() == MIRType::Double);
  Register64 output = ToOutRegister64(lir);

  masm.reserveStack(sizeof(uint64_t));
  masm.vmovq(ToFloatRegister(lir->input()), Operand(esp, 0));
  masm.Pop(output.low);
  masm.Pop(output.high);
}

void CodeGenerator::visitExtendInt32ToInt64(LExtendInt32ToInt64* lir) {
  Register64 output = ToOutRegister64(lir);
  Register input = ToRegister(lir->input());

  if (lir->mir()->isUnsigned()) {
    if (output.low != input) {
      masm.movl(input, output.low);
    }
    masm.xorl(output.high, output.high);
  } else {
    MOZ_ASSERT(output.low == input);
    MOZ_ASSERT(output.low == eax);
    MOZ_ASSERT(output.high == edx);
    masm.cdq();
  }
}

void CodeGenerator::visitSignExtendInt64(LSignExtendInt64* lir) {
#ifdef DEBUG
  Register64 input = ToRegister64(lir->getInt64Operand(0));
  Register64 output = ToOutRegister64(lir);
  MOZ_ASSERT(input.low == eax);
  MOZ_ASSERT(output.low == eax);
  MOZ_ASSERT(input.high == edx);
  MOZ_ASSERT(output.high == edx);
#endif
  switch (lir->mode()) {
    case MSignExtendInt64::Byte:
      masm.move8SignExtend(eax, eax);
      break;
    case MSignExtendInt64::Half:
      masm.move16SignExtend(eax, eax);
      break;
    case MSignExtendInt64::Word:
      break;
  }
  masm.cdq();
}

void CodeGenerator::visitWrapInt64ToInt32(LWrapInt64ToInt32* lir) {
  const LInt64Allocation& input = lir->getInt64Operand(0);
  Register output = ToRegister(lir->output());

  if (lir->mir()->bottomHalf()) {
    masm.movl(ToRegister(input.low()), output);
  } else {
    masm.movl(ToRegister(input.high()), output);
  }
}

void CodeGenerator::visitClzI64(LClzI64* lir) {
  Register64 input = ToRegister64(lir->getInt64Operand(0));
  Register64 output = ToOutRegister64(lir);

  masm.clz64(input, output.low);
  masm.xorl(output.high, output.high);
}

void CodeGenerator::visitCtzI64(LCtzI64* lir) {
  Register64 input = ToRegister64(lir->getInt64Operand(0));
  Register64 output = ToOutRegister64(lir);

  masm.ctz64(input, output.low);
  masm.xorl(output.high, output.high);
}

void CodeGenerator::visitNotI64(LNotI64* lir) {
  Register64 input = ToRegister64(lir->getInt64Operand(0));
  Register output = ToRegister(lir->output());

  if (input.high == output) {
    masm.orl(input.low, output);
  } else if (input.low == output) {
    masm.orl(input.high, output);
  } else {
    masm.movl(input.high, output);
    masm.orl(input.low, output);
  }

  masm.cmpl(Imm32(0), output);
  masm.emitSet(Assembler::Equal, output);
}

void CodeGenerator::visitWasmTruncateToInt64(LWasmTruncateToInt64* lir) {
  FloatRegister input = ToFloatRegister(lir->input());
  Register64 output = ToOutRegister64(lir);

  MWasmTruncateToInt64* mir = lir->mir();
  FloatRegister floatTemp = ToFloatRegister(lir->temp());

  Label fail, convert;

  MOZ_ASSERT(mir->input()->type() == MIRType::Double ||
             mir->input()->type() == MIRType::Float32);

  auto* ool = new (alloc()) OutOfLineWasmTruncateCheck(mir, input, output);
  addOutOfLineCode(ool, mir);

  bool isSaturating = mir->isSaturating();
  if (mir->input()->type() == MIRType::Float32) {
    if (mir->isUnsigned()) {
      masm.wasmTruncateFloat32ToUInt64(input, output, isSaturating,
                                       ool->entry(), ool->rejoin(), floatTemp);
    } else {
      masm.wasmTruncateFloat32ToInt64(input, output, isSaturating, ool->entry(),
                                      ool->rejoin(), floatTemp);
    }
  } else {
    if (mir->isUnsigned()) {
      masm.wasmTruncateDoubleToUInt64(input, output, isSaturating, ool->entry(),
                                      ool->rejoin(), floatTemp);
    } else {
      masm.wasmTruncateDoubleToInt64(input, output, isSaturating, ool->entry(),
                                     ool->rejoin(), floatTemp);
    }
  }
}

void CodeGenerator::visitInt64ToFloatingPoint(LInt64ToFloatingPoint* lir) {
  Register64 input = ToRegister64(lir->getInt64Operand(0));
  FloatRegister output = ToFloatRegister(lir->output());
  Register temp =
      lir->temp()->isBogusTemp() ? InvalidReg : ToRegister(lir->temp());

  MIRType outputType = lir->mir()->type();
  MOZ_ASSERT(outputType == MIRType::Double || outputType == MIRType::Float32);

  if (outputType == MIRType::Double) {
    if (lir->mir()->isUnsigned()) {
      masm.convertUInt64ToDouble(input, output, temp);
    } else {
      masm.convertInt64ToDouble(input, output);
    }
  } else {
    if (lir->mir()->isUnsigned()) {
      masm.convertUInt64ToFloat32(input, output, temp);
    } else {
      masm.convertInt64ToFloat32(input, output);
    }
  }
}

void CodeGenerator::visitTestI64AndBranch(LTestI64AndBranch* lir) {
  Register64 input = ToRegister64(lir->getInt64Operand(0));

  masm.testl(input.high, input.high);
  jumpToBlock(lir->ifTrue(), Assembler::NonZero);
  masm.testl(input.low, input.low);
  emitBranch(Assembler::NonZero, lir->ifTrue(), lir->ifFalse());
}