-
Notifications
You must be signed in to change notification settings - Fork 54
/
UnboxedObject.cpp
1573 lines (1312 loc) · 50.2 KB
/
UnboxedObject.cpp
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
/* -*- 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 "vm/UnboxedObject-inl.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryChecking.h"
#include "jit/BaselineIC.h"
#include "jit/ExecutableAllocator.h"
#include "jit/JitCommon.h"
#include "jit/Linker.h"
#include "gc/Nursery-inl.h"
#include "jit/MacroAssembler-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/Shape-inl.h"
#include "vm/TypeInference-inl.h"
using mozilla::ArrayLength;
using mozilla::PodCopy;
using namespace js;
/////////////////////////////////////////////////////////////////////
// UnboxedLayout
/////////////////////////////////////////////////////////////////////
void UnboxedLayout::trace(JSTracer* trc) {
for (size_t i = 0; i < properties_.length(); i++) {
TraceManuallyBarrieredEdge(trc, &properties_[i].name,
"unboxed_layout_name");
}
if (newScript()) {
newScript()->trace(trc);
}
TraceNullableEdge(trc, &nativeGroup_, "unboxed_layout_nativeGroup");
TraceNullableEdge(trc, &nativeShape_, "unboxed_layout_nativeShape");
TraceNullableEdge(trc, &allocationScript_, "unboxed_layout_allocationScript");
TraceNullableEdge(trc, &replacementGroup_, "unboxed_layout_replacementGroup");
TraceNullableEdge(trc, &constructorCode_, "unboxed_layout_constructorCode");
}
size_t UnboxedLayout::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) {
return mallocSizeOf(this) + properties_.sizeOfExcludingThis(mallocSizeOf) +
(newScript() ? newScript()->sizeOfIncludingThis(mallocSizeOf) : 0) +
mallocSizeOf(traceList());
}
void UnboxedLayout::setNewScript(TypeNewScript* newScript,
bool writeBarrier /* = true */) {
if (newScript_ && writeBarrier) {
TypeNewScript::writeBarrierPre(newScript_);
}
newScript_ = newScript;
}
// Constructor code returns a 0x1 value to indicate the constructor code should
// be cleared.
static const uintptr_t CLEAR_CONSTRUCTOR_CODE_TOKEN = 0x1;
/* static */
bool UnboxedLayout::makeConstructorCode(JSContext* cx,
HandleObjectGroup group) {
gc::AutoSuppressGC suppress(cx);
using namespace jit;
if (!cx->realm()->ensureJitRealmExists(cx)) {
return false;
}
AutoSweepObjectGroup sweep(group);
UnboxedLayout& layout = group->unboxedLayout(sweep);
MOZ_ASSERT(!layout.constructorCode());
UnboxedPlainObject* templateObject =
UnboxedPlainObject::create(cx, group, TenuredObject);
if (!templateObject) {
return false;
}
JitContext jitContext(cx, nullptr);
StackMacroAssembler masm;
Register propertiesReg, newKindReg;
#ifdef JS_CODEGEN_X86
propertiesReg = eax;
newKindReg = ecx;
masm.loadPtr(Address(masm.getStackPointer(), sizeof(void*)), propertiesReg);
masm.loadPtr(Address(masm.getStackPointer(), 2 * sizeof(void*)), newKindReg);
#else
propertiesReg = IntArgReg0;
newKindReg = IntArgReg1;
#endif
#ifdef JS_CODEGEN_ARM64
// ARM64 communicates stack address via sp, but uses a pseudo-sp (PSP) for
// addressing. The register we use for PSP may however also be used by
// calling code, and it is nonvolatile, so save it. Do this as a special
// case first because the generic save/restore code needs the PSP to be
// initialized already.
MOZ_ASSERT(PseudoStackPointer64.Is(masm.GetStackPointer64()));
masm.Str(PseudoStackPointer64, vixl::MemOperand(sp, -16, vixl::PreIndex));
// Initialize the PSP from the SP.
masm.initPseudoStackPtr();
#endif
MOZ_ASSERT(propertiesReg.volatile_());
MOZ_ASSERT(newKindReg.volatile_());
AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
regs.take(propertiesReg);
regs.take(newKindReg);
Register object = regs.takeAny(), scratch1 = regs.takeAny(),
scratch2 = regs.takeAny();
LiveGeneralRegisterSet savedNonVolatileRegisters =
SavedNonVolatileRegisters(regs);
masm.PushRegsInMask(savedNonVolatileRegisters);
// The scratch double register might be used by MacroAssembler methods.
if (ScratchDoubleReg.volatile_()) {
masm.push(ScratchDoubleReg);
}
Label failure, tenuredObject, allocated, unknownProperties;
masm.branch32(Assembler::NotEqual, newKindReg, Imm32(GenericObject),
&tenuredObject);
masm.load32(AbsoluteAddress(group->addressOfFlags()), scratch1);
masm.branchTest32(Assembler::NonZero, scratch1,
Imm32(OBJECT_FLAG_UNKNOWN_PROPERTIES), &unknownProperties);
masm.branchTest32(Assembler::NonZero, scratch1, Imm32(OBJECT_FLAG_PRE_TENURE),
&tenuredObject);
masm.bind(&unknownProperties);
// Allocate an object in the nursery
TemplateObject templateObj(templateObject);
masm.createGCObject(object, scratch1, templateObj, gc::DefaultHeap, &failure,
/* initFixedSlots = */ false);
masm.jump(&allocated);
masm.bind(&tenuredObject);
// Allocate an object in the tenured heap.
masm.createGCObject(object, scratch1, templateObj, gc::TenuredHeap, &failure,
/* initFixedSlots = */ false);
// If any of the properties being stored are in the nursery, add a store
// buffer entry for the new object.
Label postBarrier;
for (size_t i = 0; i < layout.properties().length(); i++) {
const UnboxedLayout::Property& property = layout.properties()[i];
if (!UnboxedTypeNeedsPostBarrier(property.type)) {
continue;
}
Address valueAddress(
propertiesReg, i * sizeof(IdValuePair) + offsetof(IdValuePair, value));
if (property.type == JSVAL_TYPE_OBJECT) {
Label notObject;
masm.branchTestObject(Assembler::NotEqual, valueAddress, ¬Object);
Register valueObject = masm.extractObject(valueAddress, scratch1);
masm.branchPtrInNurseryChunk(Assembler::Equal, valueObject, scratch2,
&postBarrier);
masm.bind(¬Object);
} else {
MOZ_ASSERT(property.type == JSVAL_TYPE_STRING);
Label notString;
masm.branchTestString(Assembler::NotEqual, valueAddress, ¬String);
masm.unboxString(valueAddress, scratch1);
masm.branchPtrInNurseryChunk(Assembler::Equal, scratch1, scratch2,
&postBarrier);
masm.bind(¬String);
}
}
masm.jump(&allocated);
masm.bind(&postBarrier);
LiveGeneralRegisterSet liveVolatileRegisters;
liveVolatileRegisters.add(propertiesReg);
if (object.volatile_()) {
liveVolatileRegisters.add(object);
}
masm.PushRegsInMask(liveVolatileRegisters);
masm.mov(ImmPtr(cx->runtime()), scratch1);
masm.setupUnalignedABICall(scratch2);
masm.passABIArg(scratch1);
masm.passABIArg(object);
masm.callWithABI(JS_FUNC_TO_DATA_PTR(void*, PostWriteBarrier));
masm.PopRegsInMask(liveVolatileRegisters);
masm.bind(&allocated);
ValueOperand valueOperand;
#ifdef JS_NUNBOX32
valueOperand = ValueOperand(scratch1, scratch2);
#else
valueOperand = ValueOperand(scratch1);
#endif
Label failureStoreOther, failureStoreObject;
for (size_t i = 0; i < layout.properties().length(); i++) {
const UnboxedLayout::Property& property = layout.properties()[i];
Address valueAddress(
propertiesReg, i * sizeof(IdValuePair) + offsetof(IdValuePair, value));
Address targetAddress(object,
UnboxedPlainObject::offsetOfData() + property.offset);
masm.loadValue(valueAddress, valueOperand);
if (property.type == JSVAL_TYPE_OBJECT) {
HeapTypeSet* types =
group->maybeGetProperty(sweep, IdToTypeId(NameToId(property.name)));
Label notObject;
masm.branchTestObject(Assembler::NotEqual, valueOperand,
types->mightBeMIRType(MIRType::Null)
? ¬Object
: &failureStoreObject);
Register payloadReg = masm.extractObject(valueOperand, scratch1);
if (!types->hasType(TypeSet::AnyObjectType())) {
Register scratch = (payloadReg == scratch1) ? scratch2 : scratch1;
masm.guardObjectType(payloadReg, types, scratch, payloadReg,
&failureStoreObject);
}
masm.storeUnboxedProperty(
targetAddress, JSVAL_TYPE_OBJECT,
TypedOrValueRegister(MIRType::Object, AnyRegister(payloadReg)),
nullptr);
if (notObject.used()) {
Label done;
masm.jump(&done);
masm.bind(¬Object);
masm.branchTestNull(Assembler::NotEqual, valueOperand,
&failureStoreOther);
masm.storeUnboxedProperty(targetAddress, JSVAL_TYPE_OBJECT, NullValue(),
nullptr);
masm.bind(&done);
}
} else {
masm.storeUnboxedProperty(targetAddress, property.type,
ConstantOrRegister(valueOperand),
&failureStoreOther);
}
}
Label done;
masm.bind(&done);
if (object != ReturnReg) {
masm.movePtr(object, ReturnReg);
}
// Restore non-volatile registers which were saved on entry.
if (ScratchDoubleReg.volatile_()) {
masm.pop(ScratchDoubleReg);
}
masm.PopRegsInMask(savedNonVolatileRegisters);
#ifdef JS_CODEGEN_ARM64
// Now restore the value that was in the PSP register on entry, and return.
// Obtain the correct SP from the PSP.
masm.Mov(sp, PseudoStackPointer64);
// Restore the saved value of the PSP register, this value is whatever the
// caller had saved in it, not any actual SP value, and it must not be
// overwritten subsequently.
masm.Ldr(PseudoStackPointer64, vixl::MemOperand(sp, 16, vixl::PostIndex));
// Perform a plain Ret(), as abiret() will move SP <- PSP and that is wrong.
masm.Ret(vixl::lr);
#else
masm.abiret();
#endif
masm.bind(&failureStoreOther);
// There was a failure while storing a value which cannot be stored at all
// in the unboxed object. Initialize the object so it is safe for GC and
// return null.
masm.initUnboxedObjectContents(object,
templateObject->layoutDontCheckGeneration());
masm.bind(&failure);
masm.movePtr(ImmWord(0), object);
masm.jump(&done);
masm.bind(&failureStoreObject);
// There was a failure while storing a value to an object slot of the
// unboxed object. If the value is storable, the failure occurred due to
// incomplete type information in the object, so return a token to trigger
// regeneration of the jitcode after a new object is created in the VM.
{
Label isObject;
masm.branchTestObject(Assembler::Equal, valueOperand, &isObject);
masm.branchTestNull(Assembler::NotEqual, valueOperand, &failureStoreOther);
masm.bind(&isObject);
}
// Initialize the object so it is safe for GC.
masm.initUnboxedObjectContents(object,
templateObject->layoutDontCheckGeneration());
masm.movePtr(ImmWord(CLEAR_CONSTRUCTOR_CODE_TOKEN), object);
masm.jump(&done);
Linker linker(masm, "UnboxedObject");
JitCode* code = linker.newCode(cx, CodeKind::Other);
if (!code) {
return false;
}
layout.setConstructorCode(code);
return true;
}
void UnboxedLayout::detachFromRealm() {
if (isInList()) {
remove();
}
}
static Value GetUnboxedValue(uint8_t* p, JSValueType type,
bool maybeUninitialized) {
switch (type) {
case JSVAL_TYPE_BOOLEAN:
if (maybeUninitialized) {
// Squelch Valgrind/MSan errors.
MOZ_MAKE_MEM_DEFINED(p, 1);
}
return BooleanValue(*p != 0);
case JSVAL_TYPE_INT32:
if (maybeUninitialized) {
MOZ_MAKE_MEM_DEFINED(p, sizeof(int32_t));
}
return Int32Value(*reinterpret_cast<int32_t*>(p));
case JSVAL_TYPE_DOUBLE: {
// During unboxed plain object creation, non-GC thing properties are
// left uninitialized. This is normally fine, since the properties will
// be filled in shortly, but if they are read before that happens we
// need to make sure that doubles are canonical.
if (maybeUninitialized) {
MOZ_MAKE_MEM_DEFINED(p, sizeof(double));
}
double d = *reinterpret_cast<double*>(p);
if (maybeUninitialized) {
return DoubleValue(JS::CanonicalizeNaN(d));
}
return DoubleValue(d);
}
case JSVAL_TYPE_STRING:
return StringValue(*reinterpret_cast<JSString**>(p));
case JSVAL_TYPE_OBJECT:
return ObjectOrNullValue(*reinterpret_cast<JSObject**>(p));
default:
MOZ_CRASH("Invalid type for unboxed value");
}
}
static bool SetUnboxedValue(JSContext* cx, JSObject* unboxedObject, jsid id,
uint8_t* p, JSValueType type, const Value& v,
bool preBarrier) {
switch (type) {
case JSVAL_TYPE_BOOLEAN:
if (v.isBoolean()) {
*p = v.toBoolean();
return true;
}
return false;
case JSVAL_TYPE_INT32:
if (v.isInt32()) {
*reinterpret_cast<int32_t*>(p) = v.toInt32();
return true;
}
return false;
case JSVAL_TYPE_DOUBLE:
if (v.isNumber()) {
*reinterpret_cast<double*>(p) = v.toNumber();
return true;
}
return false;
case JSVAL_TYPE_STRING:
if (v.isString()) {
JSString** np = reinterpret_cast<JSString**>(p);
if (IsInsideNursery(v.toString()) && !IsInsideNursery(unboxedObject)) {
v.toString()->storeBuffer()->putWholeCell(unboxedObject);
}
if (preBarrier) {
JSString::writeBarrierPre(*np);
}
*np = v.toString();
return true;
}
return false;
case JSVAL_TYPE_OBJECT:
if (v.isObjectOrNull()) {
JSObject** np = reinterpret_cast<JSObject**>(p);
// Update property types when writing object properties. Types for
// other properties were captured when the unboxed layout was
// created.
AddTypePropertyId(cx, unboxedObject, id, v);
// As above, trigger post barriers on the whole object.
JSObject* obj = v.toObjectOrNull();
if (IsInsideNursery(obj) && !IsInsideNursery(unboxedObject)) {
obj->storeBuffer()->putWholeCell(unboxedObject);
}
if (preBarrier) {
JSObject::writeBarrierPre(*np);
}
*np = obj;
return true;
}
return false;
default:
MOZ_CRASH("Invalid type for unboxed value");
}
}
/////////////////////////////////////////////////////////////////////
// UnboxedPlainObject
/////////////////////////////////////////////////////////////////////
bool UnboxedPlainObject::setValue(JSContext* cx,
const UnboxedLayout::Property& property,
const Value& v) {
uint8_t* p = &data_[property.offset];
return SetUnboxedValue(cx, this, NameToId(property.name), p, property.type, v,
/* preBarrier = */ true);
}
Value UnboxedPlainObject::getValue(const UnboxedLayout::Property& property,
bool maybeUninitialized /* = false */) {
uint8_t* p = &data_[property.offset];
return GetUnboxedValue(p, property.type, maybeUninitialized);
}
void UnboxedPlainObject::trace(JSTracer* trc, JSObject* obj) {
UnboxedPlainObject* uobj = &obj->as<UnboxedPlainObject>();
if (uobj->maybeExpando()) {
TraceManuallyBarrieredEdge(trc, uobj->addressOfExpando(),
"unboxed_expando");
}
const UnboxedLayout& layout = uobj->layoutDontCheckGeneration();
const int32_t* list = layout.traceList();
if (!list) {
return;
}
uint8_t* data = uobj->data();
while (*list != -1) {
GCPtrString* heap = reinterpret_cast<GCPtrString*>(data + *list);
TraceEdge(trc, heap, "unboxed_string");
list++;
}
list++;
while (*list != -1) {
GCPtrObject* heap = reinterpret_cast<GCPtrObject*>(data + *list);
TraceNullableEdge(trc, heap, "unboxed_object");
list++;
}
// Unboxed objects don't have Values to trace.
MOZ_ASSERT(*(list + 1) == -1);
}
/* static */
UnboxedExpandoObject* UnboxedPlainObject::ensureExpando(
JSContext* cx, Handle<UnboxedPlainObject*> obj) {
if (obj->maybeExpando()) {
return obj->maybeExpando();
}
UnboxedExpandoObject* expando = NewObjectWithGivenProto<UnboxedExpandoObject>(
cx, nullptr, gc::AllocKind::OBJECT4);
if (!expando) {
return nullptr;
}
// Don't track property types for expando objects. This allows Baseline
// and Ion AddSlot ICs to guard on the unboxed group without guarding on
// the expando group.
MarkObjectGroupUnknownProperties(cx, expando->group());
// If the expando is tenured then the original object must also be tenured.
// Otherwise barriers triggered on the original object for writes to the
// expando (as can happen in the JIT) won't see the tenured->nursery edge.
// See WholeCellEdges::mark.
MOZ_ASSERT_IF(!IsInsideNursery(expando), !IsInsideNursery(obj));
// As with setValue(), we need to manually trigger post barriers on the
// whole object. If we treat the field as a GCPtrObject and later
// convert the object to its native representation, we will end up with a
// corrupted store buffer entry.
if (IsInsideNursery(expando) && !IsInsideNursery(obj)) {
expando->storeBuffer()->putWholeCell(obj);
}
obj->setExpandoUnsafe(expando);
return expando;
}
bool UnboxedPlainObject::containsUnboxedOrExpandoProperty(JSContext* cx,
jsid id) const {
if (layoutDontCheckGeneration().lookup(id)) {
return true;
}
if (maybeExpando() && maybeExpando()->containsShapeOrElement(cx, id)) {
return true;
}
return false;
}
static bool PropagatePropertyTypes(JSContext* cx, jsid id,
ObjectGroup* oldGroup,
ObjectGroup* newGroup) {
AutoSweepObjectGroup sweepOld(oldGroup);
HeapTypeSet* typeProperty = oldGroup->maybeGetProperty(sweepOld, id);
TypeSet::TypeList types;
if (!typeProperty->enumerateTypes(&types)) {
ReportOutOfMemory(cx);
return false;
}
for (size_t j = 0; j < types.length(); j++) {
AddTypePropertyId(cx, newGroup, nullptr, id, types[j]);
}
return true;
}
static PlainObject* MakeReplacementTemplateObject(JSContext* cx,
HandleObjectGroup group,
const UnboxedLayout& layout) {
Rooted<PlainObject*> obj(
cx, NewObjectWithGroup<PlainObject>(cx, group, layout.getAllocKind(),
TenuredObject));
if (!obj) {
return nullptr;
}
RootedId id(cx);
for (size_t i = 0; i < layout.properties().length(); i++) {
const UnboxedLayout::Property& property = layout.properties()[i];
id = NameToId(property.name);
Shape* shape = NativeObject::addDataProperty(
cx, obj, id, SHAPE_INVALID_SLOT, JSPROP_ENUMERATE);
if (!shape) {
return nullptr;
}
MOZ_ASSERT(shape->slot() == i);
MOZ_ASSERT(obj->slotSpan() == i + 1);
MOZ_ASSERT(!obj->inDictionaryMode());
}
return obj;
}
/* static */
bool UnboxedLayout::makeNativeGroup(JSContext* cx, ObjectGroup* group) {
MOZ_ASSERT(cx->realm() == group->realm());
AutoEnterAnalysis enter(cx);
AutoSweepObjectGroup sweep(group);
UnboxedLayout& layout = group->unboxedLayout(sweep);
Rooted<TaggedProto> proto(cx, group->proto());
MOZ_ASSERT(!layout.nativeGroup());
RootedObjectGroup replacementGroup(cx);
// Immediately clear any new script on the group. This is done by replacing
// the existing new script with one for a replacement default new group.
// This is done so that the size of the replacment group's objects is the
// same as that for the unboxed group, so that we do not see polymorphic
// slot accesses later on for sites that see converted objects from this
// group and objects that were allocated using the replacement new group.
if (layout.newScript()) {
replacementGroup = ObjectGroupRealm::makeGroup(cx, group->realm(),
&PlainObject::class_, proto);
if (!replacementGroup) {
return false;
}
PlainObject* templateObject =
MakeReplacementTemplateObject(cx, replacementGroup, layout);
if (!templateObject) {
return false;
}
TypeNewScript* replacementNewScript = TypeNewScript::makeNativeVersion(
cx, layout.newScript(), templateObject);
if (!replacementNewScript) {
return false;
}
replacementGroup->setNewScript(replacementNewScript);
gc::gcTracer.traceTypeNewScript(replacementGroup);
group->clearNewScript(cx, replacementGroup);
}
// Similarly, if this group is keyed to an allocation site, replace its
// entry with a new group that has no unboxed layout.
if (layout.allocationScript()) {
RootedScript script(cx, layout.allocationScript());
jsbytecode* pc = layout.allocationPc();
replacementGroup = ObjectGroupRealm::makeGroup(cx, group->realm(),
&PlainObject::class_, proto);
if (!replacementGroup) {
return false;
}
PlainObject* templateObject = &script->getObject(pc)->as<PlainObject>();
replacementGroup->addDefiniteProperties(cx, templateObject->lastProperty());
ObjectGroupRealm& realm = ObjectGroupRealm::get(group);
realm.replaceAllocationSiteGroup(script, pc, JSProto_Object,
replacementGroup);
// Clear any baseline information at this opcode which might use the old
// group.
if (script->hasICScript()) {
jit::ICEntry& entry =
script->icScript()->icEntryFromPCOffset(script->pcToOffset(pc));
jit::ICFallbackStub* fallback = entry.fallbackStub();
for (jit::ICStubIterator iter = fallback->beginChain(); !iter.atEnd();
iter++) {
iter.unlink(cx);
}
if (fallback->isNewObject_Fallback()) {
fallback->toNewObject_Fallback()->setTemplateObject(nullptr);
} else if (fallback->isNewArray_Fallback()) {
fallback->toNewArray_Fallback()->setTemplateGroup(replacementGroup);
}
}
}
size_t nfixed = gc::GetGCKindSlots(layout.getAllocKind());
RootedShape shape(cx, EmptyShape::getInitialShape(cx, &PlainObject::class_,
proto, nfixed, 0));
if (!shape) {
return false;
}
// Add shapes for each property, if this is for a plain object.
for (size_t i = 0; i < layout.properties().length(); i++) {
const UnboxedLayout::Property& property = layout.properties()[i];
Rooted<StackShape> child(
cx, StackShape(shape->base()->unowned(), NameToId(property.name), i,
JSPROP_ENUMERATE));
shape = cx->zone()->propertyTree().getChild(cx, shape, child);
if (!shape) {
return false;
}
}
ObjectGroup* nativeGroup = ObjectGroupRealm::makeGroup(
cx, group->realm(), &PlainObject::class_, proto,
group->flags(sweep) & OBJECT_FLAG_DYNAMIC_MASK);
if (!nativeGroup) {
return false;
}
// No sense propagating if we don't know what we started with.
AutoSweepObjectGroup sweepNative(nativeGroup);
if (!group->unknownProperties(sweep)) {
for (size_t i = 0; i < layout.properties().length(); i++) {
const UnboxedLayout::Property& property = layout.properties()[i];
jsid id = NameToId(property.name);
if (!PropagatePropertyTypes(cx, id, group, nativeGroup)) {
return false;
}
// If we are OOM we may not be able to propagate properties.
if (nativeGroup->unknownProperties(sweepNative)) {
break;
}
}
} else {
// If we skip, though, the new group had better agree.
MOZ_ASSERT(nativeGroup->unknownProperties(sweepNative));
}
layout.nativeGroup_ = nativeGroup;
layout.nativeShape_ = shape;
layout.replacementGroup_ = replacementGroup;
nativeGroup->setOriginalUnboxedGroup(group);
group->markStateChange(sweep, cx);
return true;
}
/* static */
NativeObject* UnboxedPlainObject::convertToNative(JSContext* cx,
JSObject* obj) {
// This function returns the original object (instead of bool) to make sure
// Ion's LConvertUnboxedObjectToNative works correctly. If we return bool
// and use defineReuseInput, the object register is not preserved across the
// call.
const UnboxedLayout& layout = obj->as<UnboxedPlainObject>().layout();
UnboxedExpandoObject* expando = obj->as<UnboxedPlainObject>().maybeExpando();
// Ensure we're working in the object's realm, so we don't have to worry about
// creating groups or templates in the wrong realm.
AutoRealm ar(cx, obj);
if (!layout.nativeGroup()) {
if (!UnboxedLayout::makeNativeGroup(cx, obj->group())) {
return nullptr;
}
// makeNativeGroup can reentrantly invoke this method.
if (obj->is<PlainObject>()) {
return &obj->as<PlainObject>();
}
}
AutoValueVector values(cx);
for (size_t i = 0; i < layout.properties().length(); i++) {
// We might be reading properties off the object which have not been
// initialized yet. Make sure any double values we read here are
// canonicalized.
if (!values.append(obj->as<UnboxedPlainObject>().getValue(
layout.properties()[i], true))) {
return nullptr;
}
}
// We are eliminating the expando edge with the conversion, so trigger a
// pre barrier.
JSObject::writeBarrierPre(expando);
// Additionally trigger a post barrier on the expando itself. Whole cell
// store buffer entries can be added on the original unboxed object for
// writes to the expando (see WholeCellEdges::trace), so after conversion
// we need to make sure the expando itself will still be traced.
if (expando && !IsInsideNursery(expando)) {
cx->runtime()->gc.storeBuffer().putWholeCell(expando);
}
obj->setGroup(layout.nativeGroup());
obj->as<PlainObject>().setLastPropertyMakeNative(cx, layout.nativeShape());
for (size_t i = 0; i < values.length(); i++) {
obj->as<PlainObject>().initSlotUnchecked(i, values[i]);
}
if (!expando) {
return &obj->as<PlainObject>();
}
// Add properties from the expando object to the object, in order.
// Suppress GC here, so that callers don't need to worry about this
// method collecting. The stuff below can only fail due to OOM, in
// which case the object will not have been completely filled back in.
gc::AutoSuppressGC suppress(cx);
Vector<jsid> ids(cx);
for (Shape::Range<NoGC> r(expando->lastProperty()); !r.empty();
r.popFront()) {
if (!ids.append(r.front().propid())) {
return nullptr;
}
}
for (size_t i = 0; i < expando->getDenseInitializedLength(); i++) {
if (!expando->getDenseElement(i).isMagic(JS_ELEMENTS_HOLE)) {
if (!ids.append(INT_TO_JSID(i))) {
return nullptr;
}
}
}
::Reverse(ids.begin(), ids.end());
RootedPlainObject nobj(cx, &obj->as<PlainObject>());
Rooted<UnboxedExpandoObject*> nexpando(cx, expando);
RootedId id(cx);
Rooted<PropertyDescriptor> desc(cx);
for (size_t i = 0; i < ids.length(); i++) {
id = ids[i];
if (!GetOwnPropertyDescriptor(cx, nexpando, id, &desc)) {
return nullptr;
}
ObjectOpResult result;
if (!DefineProperty(cx, nobj, id, desc, result)) {
return nullptr;
}
MOZ_ASSERT(result.ok());
}
return nobj;
}
/* static */ JS::Result<UnboxedObject*, JS::OOM&> UnboxedObject::createInternal(
JSContext* cx, js::gc::AllocKind kind, js::gc::InitialHeap heap,
js::HandleObjectGroup group) {
const js::Class* clasp = group->clasp();
MOZ_ASSERT(clasp == &UnboxedPlainObject::class_);
MOZ_ASSERT(CanBeFinalizedInBackground(kind, clasp));
kind = GetBackgroundAllocKind(kind);
debugCheckNewObject(group, /* shape = */ nullptr, kind, heap);
JSObject* obj =
js::AllocateObject(cx, kind, /* nDynamicSlots = */ 0, heap, clasp);
if (!obj) {
return cx->alreadyReportedOOM();
}
UnboxedObject* uobj = static_cast<UnboxedObject*>(obj);
uobj->initGroup(group);
MOZ_ASSERT(clasp->shouldDelayMetadataBuilder());
cx->realm()->setObjectPendingMetadata(cx, uobj);
js::gc::gcTracer.traceCreateObject(uobj);
return uobj;
}
/* static */
UnboxedPlainObject* UnboxedPlainObject::create(JSContext* cx,
HandleObjectGroup group,
NewObjectKind newKind) {
AutoSetNewObjectMetadata metadata(cx);
MOZ_ASSERT(group->clasp() == &class_);
gc::AllocKind allocKind;
{
AutoSweepObjectGroup sweep(group);
allocKind = group->unboxedLayout(sweep).getAllocKind();
}
gc::InitialHeap heap = GetInitialHeap(newKind, &class_);
MOZ_ASSERT(newKind != SingletonObject);
JSObject* obj;
JS_TRY_VAR_OR_RETURN_NULL(cx, obj,
createInternal(cx, allocKind, heap, group));
UnboxedPlainObject* uobj = static_cast<UnboxedPlainObject*>(obj);
uobj->initExpando();
// Initialize reference fields of the object. All fields in the object will
// be overwritten shortly, but references need to be safe for the GC.
const int32_t* list = uobj->layout().traceList();
if (list) {
uint8_t* data = uobj->data();
while (*list != -1) {
GCPtrString* heap = reinterpret_cast<GCPtrString*>(data + *list);
heap->init(cx->names().empty);
list++;
}
list++;
while (*list != -1) {
GCPtrObject* heap = reinterpret_cast<GCPtrObject*>(data + *list);
heap->init(nullptr);
list++;
}
// Unboxed objects don't have Values to initialize.
MOZ_ASSERT(*(list + 1) == -1);
}
return uobj;
}
/* static */
JSObject* UnboxedPlainObject::createWithProperties(JSContext* cx,
HandleObjectGroup group,
NewObjectKind newKind,
IdValuePair* properties) {
MOZ_ASSERT(newKind == GenericObject || newKind == TenuredObject);
{
AutoSweepObjectGroup sweep(group);
UnboxedLayout& layout = group->unboxedLayout(sweep);
if (layout.constructorCode()) {
MOZ_ASSERT(!cx->helperThread());
typedef JSObject* (*ConstructorCodeSignature)(IdValuePair*,
NewObjectKind);
ConstructorCodeSignature function =
reinterpret_cast<ConstructorCodeSignature>(
layout.constructorCode()->raw());
JSObject* obj;
{
JS::AutoSuppressGCAnalysis nogc;
obj = reinterpret_cast<JSObject*>(
CALL_GENERATED_2(function, properties, newKind));
}
if (obj > reinterpret_cast<JSObject*>(CLEAR_CONSTRUCTOR_CODE_TOKEN)) {
return obj;
}
if (obj == reinterpret_cast<JSObject*>(CLEAR_CONSTRUCTOR_CODE_TOKEN)) {
layout.setConstructorCode(nullptr);
}
}
}
UnboxedPlainObject* obj = UnboxedPlainObject::create(cx, group, newKind);
if (!obj) {
return nullptr;
}
// AutoSweepObjectGroup can't be live across a GC call, so we reset() it
// before calling NewPlainObjectWithProperties.
mozilla::Maybe<AutoSweepObjectGroup> sweep;
sweep.emplace(group);
UnboxedLayout& layout = group->unboxedLayout(*sweep);
for (size_t i = 0; i < layout.properties().length(); i++) {
if (!obj->setValue(cx, layout.properties()[i], properties[i].value)) {
sweep.reset();
return NewPlainObjectWithProperties(
cx, properties, layout.properties().length(), newKind);
}
}
#ifndef JS_CODEGEN_NONE
if (!cx->helperThread() && !group->unknownProperties(*sweep) &&
!layout.constructorCode() && cx->runtime()->jitSupportsFloatingPoint &&
jit::CanLikelyAllocateMoreExecutableMemory()) {
if (!UnboxedLayout::makeConstructorCode(cx, group)) {
return nullptr;
}
}
#endif
return obj;
}
/* static */
bool UnboxedPlainObject::obj_lookupProperty(
JSContext* cx, HandleObject obj, HandleId id, MutableHandleObject objp,
MutableHandle<PropertyResult> propp) {
if (obj->as<UnboxedPlainObject>().containsUnboxedOrExpandoProperty(cx, id)) {
propp.setNonNativeProperty();
objp.set(obj);
return true;
}
RootedObject proto(cx, obj->staticPrototype());
if (!proto) {
objp.set(nullptr);
propp.setNotFound();
return true;
}
return LookupProperty(cx, proto, id, objp, propp);
}
/* static */