blob: 35936dc0b172c8d0f815d8c78b4d4c5b0fb9121c [file] [log] [blame]
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include <utility>
#include "src/api/api-inl.h"
#include "src/codegen/assembler-inl.h"
#include "src/codegen/compilation-cache.h"
#include "src/codegen/macro-assembler-inl.h"
#include "src/common/globals.h"
#include "src/debug/debug.h"
#include "src/deoptimizer/deoptimizer.h"
#include "src/execution/execution.h"
#include "src/handles/global-handles.h"
#include "src/heap/combined-heap.h"
#include "src/heap/factory.h"
#include "src/heap/gc-tracer.h"
#include "src/heap/heap-inl.h"
#include "src/heap/incremental-marking.h"
#include "src/heap/large-spaces.h"
#include "src/heap/mark-compact.h"
#include "src/heap/memory-chunk.h"
#include "src/heap/memory-reducer.h"
#include "src/heap/remembered-set-inl.h"
#include "src/heap/safepoint.h"
#include "src/ic/ic.h"
#include "src/numbers/hash-seed-inl.h"
#include "src/objects/elements.h"
#include "src/objects/field-type.h"
#include "src/objects/frame-array-inl.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/js-collection-inl.h"
#include "src/objects/managed.h"
#include "src/objects/objects-inl.h"
#include "src/objects/slots.h"
#include "src/objects/transitions.h"
#include "src/regexp/regexp.h"
#include "src/snapshot/snapshot.h"
#include "src/utils/ostreams.h"
#include "test/cctest/cctest.h"
#include "test/cctest/heap/heap-tester.h"
#include "test/cctest/heap/heap-utils.h"
#include "test/cctest/test-feedback-vector.h"
#include "test/cctest/test-transitions.h"
namespace v8 {
namespace internal {
namespace heap {
// We only start allocation-site tracking with the second instantiation.
static const int kPretenureCreationCount =
AllocationSite::kPretenureMinimumCreated + 1;
static void CheckMap(Map map, int type, int instance_size) {
CHECK(map.IsHeapObject());
DCHECK(IsValidHeapObject(CcTest::heap(), map));
CHECK_EQ(ReadOnlyRoots(CcTest::heap()).meta_map(), map.map());
CHECK_EQ(type, map.instance_type());
CHECK_EQ(instance_size, map.instance_size());
}
TEST(HeapMaps) {
CcTest::InitializeVM();
ReadOnlyRoots roots(CcTest::heap());
CheckMap(roots.meta_map(), MAP_TYPE, Map::kSize);
CheckMap(roots.heap_number_map(), HEAP_NUMBER_TYPE, HeapNumber::kSize);
CheckMap(roots.fixed_array_map(), FIXED_ARRAY_TYPE, kVariableSizeSentinel);
CheckMap(roots.hash_table_map(), HASH_TABLE_TYPE, kVariableSizeSentinel);
CheckMap(roots.string_map(), STRING_TYPE, kVariableSizeSentinel);
}
static void VerifyStoredPrototypeMap(Isolate* isolate,
int stored_map_context_index,
int stored_ctor_context_index) {
Handle<Context> context = isolate->native_context();
Handle<Map> this_map(Map::cast(context->get(stored_map_context_index)),
isolate);
Handle<JSFunction> fun(
JSFunction::cast(context->get(stored_ctor_context_index)), isolate);
Handle<JSObject> proto(JSObject::cast(fun->initial_map().prototype()),
isolate);
Handle<Map> that_map(proto->map(), isolate);
CHECK(proto->HasFastProperties());
CHECK_EQ(*this_map, *that_map);
}
// Checks that critical maps stored on the context (mostly used for fast-path
// checks) are unchanged after initialization.
TEST(ContextMaps) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope handle_scope(isolate);
VerifyStoredPrototypeMap(isolate,
Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX,
Context::STRING_FUNCTION_INDEX);
VerifyStoredPrototypeMap(isolate, Context::REGEXP_PROTOTYPE_MAP_INDEX,
Context::REGEXP_FUNCTION_INDEX);
}
TEST(InitialObjects) {
LocalContext env;
HandleScope scope(CcTest::i_isolate());
Handle<Context> context = v8::Utils::OpenHandle(*env);
// Initial ArrayIterator prototype.
CHECK_EQ(
context->initial_array_iterator_prototype(),
*v8::Utils::OpenHandle(*CompileRun("[][Symbol.iterator]().__proto__")));
// Initial Array prototype.
CHECK_EQ(context->initial_array_prototype(),
*v8::Utils::OpenHandle(*CompileRun("Array.prototype")));
// Initial Generator prototype.
CHECK_EQ(context->initial_generator_prototype(),
*v8::Utils::OpenHandle(
*CompileRun("(function*(){}).__proto__.prototype")));
// Initial Iterator prototype.
CHECK_EQ(context->initial_iterator_prototype(),
*v8::Utils::OpenHandle(
*CompileRun("[][Symbol.iterator]().__proto__.__proto__")));
// Initial Object prototype.
CHECK_EQ(context->initial_object_prototype(),
*v8::Utils::OpenHandle(*CompileRun("Object.prototype")));
}
static void CheckOddball(Isolate* isolate, Object obj, const char* string) {
CHECK(obj.IsOddball());
Handle<Object> handle(obj, isolate);
Object print_string = *Object::ToString(isolate, handle).ToHandleChecked();
CHECK(String::cast(print_string).IsOneByteEqualTo(CStrVector(string)));
}
static void CheckSmi(Isolate* isolate, int value, const char* string) {
Handle<Object> handle(Smi::FromInt(value), isolate);
Object print_string = *Object::ToString(isolate, handle).ToHandleChecked();
CHECK(String::cast(print_string).IsOneByteEqualTo(CStrVector(string)));
}
static void CheckNumber(Isolate* isolate, double value, const char* string) {
Handle<Object> number = isolate->factory()->NewNumber(value);
CHECK(number->IsNumber());
Handle<Object> print_string =
Object::ToString(isolate, number).ToHandleChecked();
CHECK(String::cast(*print_string).IsOneByteEqualTo(CStrVector(string)));
}
void CheckEmbeddedObjectsAreEqual(Handle<Code> lhs, Handle<Code> rhs) {
int mode_mask = RelocInfo::ModeMask(RelocInfo::FULL_EMBEDDED_OBJECT);
RelocIterator lhs_it(*lhs, mode_mask);
RelocIterator rhs_it(*rhs, mode_mask);
while (!lhs_it.done() && !rhs_it.done()) {
CHECK(lhs_it.rinfo()->target_object() == rhs_it.rinfo()->target_object());
lhs_it.next();
rhs_it.next();
}
CHECK(lhs_it.done() == rhs_it.done());
}
HEAP_TEST(TestNewSpaceRefsInCopiedCode) {
if (FLAG_single_generation) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope sc(isolate);
Handle<HeapNumber> value = factory->NewHeapNumber(1.000123);
CHECK(Heap::InYoungGeneration(*value));
i::byte buffer[i::Assembler::kDefaultBufferSize];
MacroAssembler masm(isolate, v8::internal::CodeObjectRequired::kYes,
ExternalAssemblerBuffer(buffer, sizeof(buffer)));
// Add a new-space reference to the code.
masm.Push(value);
CodeDesc desc;
masm.GetCode(isolate, &desc);
Handle<Code> code =
Factory::CodeBuilder(isolate, desc, CodeKind::FOR_TESTING).Build();
Handle<Code> copy;
{
CodeSpaceMemoryModificationScope modification_scope(isolate->heap());
copy = factory->CopyCode(code);
}
CheckEmbeddedObjectsAreEqual(code, copy);
CcTest::CollectAllAvailableGarbage();
CheckEmbeddedObjectsAreEqual(code, copy);
}
static void CheckFindCodeObject(Isolate* isolate) {
// Test FindCodeObject
#define __ assm.
Assembler assm(AssemblerOptions{});
__ nop(); // supported on all architectures
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
Factory::CodeBuilder(isolate, desc, CodeKind::FOR_TESTING).Build();
CHECK(code->IsCode());
HeapObject obj = HeapObject::cast(*code);
Address obj_addr = obj.address();
for (int i = 0; i < obj.Size(); i += kTaggedSize) {
Object found = isolate->FindCodeObject(obj_addr + i);
CHECK_EQ(*code, found);
}
Handle<Code> copy =
Factory::CodeBuilder(isolate, desc, CodeKind::FOR_TESTING).Build();
HeapObject obj_copy = HeapObject::cast(*copy);
Object not_right =
isolate->FindCodeObject(obj_copy.address() + obj_copy.Size() / 2);
CHECK(not_right != *code);
}
TEST(HandleNull) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope outer_scope(isolate);
LocalContext context;
Handle<Object> n(Object(0), isolate);
CHECK(!n.is_null());
}
TEST(HeapObjects) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope sc(isolate);
Handle<Object> value = factory->NewNumber(1.000123);
CHECK(value->IsHeapNumber());
CHECK(value->IsNumber());
CHECK_EQ(1.000123, value->Number());
value = factory->NewNumber(1.0);
CHECK(value->IsSmi());
CHECK(value->IsNumber());
CHECK_EQ(1.0, value->Number());
value = factory->NewNumberFromInt(1024);
CHECK(value->IsSmi());
CHECK(value->IsNumber());
CHECK_EQ(1024.0, value->Number());
value = factory->NewNumberFromInt(Smi::kMinValue);
CHECK(value->IsSmi());
CHECK(value->IsNumber());
CHECK_EQ(Smi::kMinValue, Handle<Smi>::cast(value)->value());
value = factory->NewNumberFromInt(Smi::kMaxValue);
CHECK(value->IsSmi());
CHECK(value->IsNumber());
CHECK_EQ(Smi::kMaxValue, Handle<Smi>::cast(value)->value());
#if !defined(V8_TARGET_ARCH_64_BIT)
// TODO(lrn): We need a NumberFromIntptr function in order to test this.
value = factory->NewNumberFromInt(Smi::kMinValue - 1);
CHECK(value->IsHeapNumber());
CHECK(value->IsNumber());
CHECK_EQ(static_cast<double>(Smi::kMinValue - 1), value->Number());
#endif
value = factory->NewNumberFromUint(static_cast<uint32_t>(Smi::kMaxValue) + 1);
CHECK(value->IsHeapNumber());
CHECK(value->IsNumber());
CHECK_EQ(static_cast<double>(static_cast<uint32_t>(Smi::kMaxValue) + 1),
value->Number());
value = factory->NewNumberFromUint(static_cast<uint32_t>(1) << 31);
CHECK(value->IsHeapNumber());
CHECK(value->IsNumber());
CHECK_EQ(static_cast<double>(static_cast<uint32_t>(1) << 31),
value->Number());
// nan oddball checks
CHECK(factory->nan_value()->IsNumber());
CHECK(std::isnan(factory->nan_value()->Number()));
Handle<String> s = factory->NewStringFromStaticChars("fisk hest ");
CHECK(s->IsString());
CHECK_EQ(10, s->length());
Handle<String> object_string = Handle<String>::cast(factory->Object_string());
Handle<JSGlobalObject> global(CcTest::i_isolate()->context().global_object(),
isolate);
CHECK(Just(true) == JSReceiver::HasOwnProperty(global, object_string));
// Check ToString for oddballs
ReadOnlyRoots roots(heap);
CheckOddball(isolate, roots.true_value(), "true");
CheckOddball(isolate, roots.false_value(), "false");
CheckOddball(isolate, roots.null_value(), "null");
CheckOddball(isolate, roots.undefined_value(), "undefined");
// Check ToString for Smis
CheckSmi(isolate, 0, "0");
CheckSmi(isolate, 42, "42");
CheckSmi(isolate, -42, "-42");
// Check ToString for Numbers
CheckNumber(isolate, 1.1, "1.1");
CheckFindCodeObject(isolate);
}
TEST(Tagging) {
CcTest::InitializeVM();
int request = 24;
CHECK_EQ(request, static_cast<int>(OBJECT_POINTER_ALIGN(request)));
CHECK(Smi::FromInt(42).IsSmi());
CHECK(Smi::FromInt(Smi::kMinValue).IsSmi());
CHECK(Smi::FromInt(Smi::kMaxValue).IsSmi());
}
TEST(GarbageCollection) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope sc(isolate);
// Check GC.
CcTest::CollectGarbage(NEW_SPACE);
Handle<JSGlobalObject> global(CcTest::i_isolate()->context().global_object(),
isolate);
Handle<String> name = factory->InternalizeUtf8String("theFunction");
Handle<String> prop_name = factory->InternalizeUtf8String("theSlot");
Handle<String> prop_namex = factory->InternalizeUtf8String("theSlotx");
Handle<String> obj_name = factory->InternalizeUtf8String("theObject");
Handle<Smi> twenty_three(Smi::FromInt(23), isolate);
Handle<Smi> twenty_four(Smi::FromInt(24), isolate);
{
HandleScope inner_scope(isolate);
// Allocate a function and keep it in global object's property.
Handle<JSFunction> function = factory->NewFunctionForTest(name);
Object::SetProperty(isolate, global, name, function).Check();
// Allocate an object. Unrooted after leaving the scope.
Handle<JSObject> obj = factory->NewJSObject(function);
Object::SetProperty(isolate, obj, prop_name, twenty_three).Check();
Object::SetProperty(isolate, obj, prop_namex, twenty_four).Check();
CHECK_EQ(Smi::FromInt(23),
*Object::GetProperty(isolate, obj, prop_name).ToHandleChecked());
CHECK_EQ(Smi::FromInt(24),
*Object::GetProperty(isolate, obj, prop_namex).ToHandleChecked());
}
CcTest::CollectGarbage(NEW_SPACE);
// Function should be alive.
CHECK(Just(true) == JSReceiver::HasOwnProperty(global, name));
// Check function is retained.
Handle<Object> func_value =
Object::GetProperty(isolate, global, name).ToHandleChecked();
CHECK(func_value->IsJSFunction());
Handle<JSFunction> function = Handle<JSFunction>::cast(func_value);
{
HandleScope inner_scope(isolate);
// Allocate another object, make it reachable from global.
Handle<JSObject> obj = factory->NewJSObject(function);
Object::SetProperty(isolate, global, obj_name, obj).Check();
Object::SetProperty(isolate, obj, prop_name, twenty_three).Check();
}
// After gc, it should survive.
CcTest::CollectGarbage(NEW_SPACE);
CHECK(Just(true) == JSReceiver::HasOwnProperty(global, obj_name));
Handle<Object> obj =
Object::GetProperty(isolate, global, obj_name).ToHandleChecked();
CHECK(obj->IsJSObject());
CHECK_EQ(Smi::FromInt(23),
*Object::GetProperty(isolate, obj, prop_name).ToHandleChecked());
}
static void VerifyStringAllocation(Isolate* isolate, const char* string) {
HandleScope scope(isolate);
Handle<String> s = isolate->factory()
->NewStringFromUtf8(CStrVector(string))
.ToHandleChecked();
CHECK_EQ(strlen(string), s->length());
for (int index = 0; index < s->length(); index++) {
CHECK_EQ(static_cast<uint16_t>(string[index]), s->Get(index));
}
}
TEST(String) {
CcTest::InitializeVM();
Isolate* isolate = reinterpret_cast<Isolate*>(CcTest::isolate());
VerifyStringAllocation(isolate, "a");
VerifyStringAllocation(isolate, "ab");
VerifyStringAllocation(isolate, "abc");
VerifyStringAllocation(isolate, "abcd");
VerifyStringAllocation(isolate, "fiskerdrengen er paa havet");
}
TEST(LocalHandles) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope scope(CcTest::isolate());
const char* name = "Kasper the spunky";
Handle<String> string = factory->NewStringFromAsciiChecked(name);
CHECK_EQ(strlen(name), string->length());
}
TEST(GlobalHandles) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
GlobalHandles* global_handles = isolate->global_handles();
Handle<Object> h1;
Handle<Object> h2;
Handle<Object> h3;
Handle<Object> h4;
{
HandleScope scope(isolate);
Handle<Object> i = factory->NewStringFromStaticChars("fisk");
Handle<Object> u = factory->NewNumber(1.12344);
h1 = global_handles->Create(*i);
h2 = global_handles->Create(*u);
h3 = global_handles->Create(*i);
h4 = global_handles->Create(*u);
}
// after gc, it should survive
CcTest::CollectGarbage(NEW_SPACE);
CHECK((*h1).IsString());
CHECK((*h2).IsHeapNumber());
CHECK((*h3).IsString());
CHECK((*h4).IsHeapNumber());
CHECK_EQ(*h3, *h1);
GlobalHandles::Destroy(h1.location());
GlobalHandles::Destroy(h3.location());
CHECK_EQ(*h4, *h2);
GlobalHandles::Destroy(h2.location());
GlobalHandles::Destroy(h4.location());
}
static bool WeakPointerCleared = false;
static void TestWeakGlobalHandleCallback(
const v8::WeakCallbackInfo<void>& data) {
std::pair<v8::Persistent<v8::Value>*, int>* p =
reinterpret_cast<std::pair<v8::Persistent<v8::Value>*, int>*>(
data.GetParameter());
if (p->second == 1234) WeakPointerCleared = true;
p->first->Reset();
}
TEST(WeakGlobalUnmodifiedApiHandlesScavenge) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
LocalContext context;
Factory* factory = isolate->factory();
GlobalHandles* global_handles = isolate->global_handles();
WeakPointerCleared = false;
Handle<Object> h1;
Handle<Object> h2;
{
HandleScope scope(isolate);
// Create an Api object that is unmodified.
Local<v8::Function> function = FunctionTemplate::New(context->GetIsolate())
->GetFunction(context.local())
.ToLocalChecked();
Local<v8::Object> i =
function->NewInstance(context.local()).ToLocalChecked();
Handle<Object> u = factory->NewNumber(1.12344);
h1 = global_handles->Create(*u);
h2 = global_handles->Create(*(reinterpret_cast<internal::Address*>(*i)));
}
std::pair<Handle<Object>*, int> handle_and_id(&h2, 1234);
GlobalHandles::MakeWeak(
h2.location(), reinterpret_cast<void*>(&handle_and_id),
&TestWeakGlobalHandleCallback, v8::WeakCallbackType::kParameter);
FLAG_single_generation ? CcTest::CollectGarbage(OLD_SPACE)
: CcTest::CollectGarbage(NEW_SPACE);
CHECK((*h1).IsHeapNumber());
CHECK(WeakPointerCleared);
GlobalHandles::Destroy(h1.location());
}
TEST(WeakGlobalHandlesMark) {
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
GlobalHandles* global_handles = isolate->global_handles();
WeakPointerCleared = false;
Handle<Object> h1;
Handle<Object> h2;
{
HandleScope scope(isolate);
Handle<Object> i = factory->NewStringFromStaticChars("fisk");
Handle<Object> u = factory->NewNumber(1.12344);
h1 = global_handles->Create(*i);
h2 = global_handles->Create(*u);
}
// Make sure the objects are promoted.
CcTest::CollectGarbage(OLD_SPACE);
CcTest::CollectGarbage(NEW_SPACE);
CHECK(!Heap::InYoungGeneration(*h1) && !Heap::InYoungGeneration(*h2));
std::pair<Handle<Object>*, int> handle_and_id(&h2, 1234);
GlobalHandles::MakeWeak(
h2.location(), reinterpret_cast<void*>(&handle_and_id),
&TestWeakGlobalHandleCallback, v8::WeakCallbackType::kParameter);
// Incremental marking potentially marked handles before they turned weak.
CcTest::CollectAllGarbage();
CHECK((*h1).IsString());
CHECK(WeakPointerCleared);
GlobalHandles::Destroy(h1.location());
}
TEST(DeleteWeakGlobalHandle) {
FLAG_stress_compaction = false;
FLAG_stress_incremental_marking = false;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
GlobalHandles* global_handles = isolate->global_handles();
WeakPointerCleared = false;
Handle<Object> h;
{
HandleScope scope(isolate);
Handle<Object> i = factory->NewStringFromStaticChars("fisk");
h = global_handles->Create(*i);
}
std::pair<Handle<Object>*, int> handle_and_id(&h, 1234);
GlobalHandles::MakeWeak(h.location(), reinterpret_cast<void*>(&handle_and_id),
&TestWeakGlobalHandleCallback,
v8::WeakCallbackType::kParameter);
CHECK(!WeakPointerCleared);
CcTest::CollectGarbage(OLD_SPACE);
CHECK(WeakPointerCleared);
}
TEST(BytecodeArray) {
if (FLAG_never_compact) return;
static const uint8_t kRawBytes[] = {0xC3, 0x7E, 0xA5, 0x5A};
static const int kRawBytesSize = sizeof(kRawBytes);
static const int32_t kFrameSize = 32;
static const int32_t kParameterCount = 2;
ManualGCScope manual_gc_scope;
FLAG_manual_evacuation_candidates_selection = true;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Heap* heap = isolate->heap();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
heap::SimulateFullSpace(heap->old_space());
Handle<FixedArray> constant_pool =
factory->NewFixedArray(5, AllocationType::kOld);
for (int i = 0; i < 5; i++) {
Handle<Object> number = factory->NewHeapNumber(i);
constant_pool->set(i, *number);
}
// Allocate and initialize BytecodeArray
Handle<BytecodeArray> array = factory->NewBytecodeArray(
kRawBytesSize, kRawBytes, kFrameSize, kParameterCount, constant_pool);
CHECK(array->IsBytecodeArray());
CHECK_EQ(array->length(), (int)sizeof(kRawBytes));
CHECK_EQ(array->frame_size(), kFrameSize);
CHECK_EQ(array->parameter_count(), kParameterCount);
CHECK_EQ(array->constant_pool(), *constant_pool);
CHECK_LE(array->address(), array->GetFirstBytecodeAddress());
CHECK_GE(array->address() + array->BytecodeArraySize(),
array->GetFirstBytecodeAddress() + array->length());
for (int i = 0; i < kRawBytesSize; i++) {
CHECK_EQ(Memory<uint8_t>(array->GetFirstBytecodeAddress() + i),
kRawBytes[i]);
CHECK_EQ(array->get(i), kRawBytes[i]);
}
FixedArray old_constant_pool_address = *constant_pool;
// Perform a full garbage collection and force the constant pool to be on an
// evacuation candidate.
Page* evac_page = Page::FromHeapObject(*constant_pool);
heap::ForceEvacuationCandidate(evac_page);
CcTest::CollectAllGarbage();
// BytecodeArray should survive.
CHECK_EQ(array->length(), kRawBytesSize);
CHECK_EQ(array->frame_size(), kFrameSize);
for (int i = 0; i < kRawBytesSize; i++) {
CHECK_EQ(array->get(i), kRawBytes[i]);
CHECK_EQ(Memory<uint8_t>(array->GetFirstBytecodeAddress() + i),
kRawBytes[i]);
}
// Constant pool should have been migrated.
CHECK_EQ(array->constant_pool(), *constant_pool);
CHECK_NE(array->constant_pool(), old_constant_pool_address);
}
TEST(BytecodeArrayAging) {
static const uint8_t kRawBytes[] = {0xC3, 0x7E, 0xA5, 0x5A};
static const int kRawBytesSize = sizeof(kRawBytes);
static const int32_t kFrameSize = 32;
static const int32_t kParameterCount = 2;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
Handle<BytecodeArray> array =
factory->NewBytecodeArray(kRawBytesSize, kRawBytes, kFrameSize,
kParameterCount, factory->empty_fixed_array());
CHECK_EQ(BytecodeArray::kFirstBytecodeAge, array->bytecode_age());
array->MakeOlder();
CHECK_EQ(BytecodeArray::kQuadragenarianBytecodeAge, array->bytecode_age());
array->set_bytecode_age(BytecodeArray::kLastBytecodeAge);
array->MakeOlder();
CHECK_EQ(BytecodeArray::kLastBytecodeAge, array->bytecode_age());
}
static const char* not_so_random_string_table[] = {
"abstract", "boolean", "break", "byte", "case",
"catch", "char", "class", "const", "continue",
"debugger", "default", "delete", "do", "double",
"else", "enum", "export", "extends", "false",
"final", "finally", "float", "for", "function",
"goto", "if", "implements", "import", "in",
"instanceof", "int", "interface", "long", "native",
"new", "null", "package", "private", "protected",
"public", "return", "short", "static", "super",
"switch", "synchronized", "this", "throw", "throws",
"transient", "true", "try", "typeof", "var",
"void", "volatile", "while", "with", nullptr};
static void CheckInternalizedStrings(const char** strings) {
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
for (const char* string = *strings; *strings != nullptr;
string = *strings++) {
HandleScope scope(isolate);
Handle<String> a =
isolate->factory()->InternalizeUtf8String(CStrVector(string));
// InternalizeUtf8String may return a failure if a GC is needed.
CHECK(a->IsInternalizedString());
Handle<String> b = factory->InternalizeUtf8String(string);
CHECK_EQ(*b, *a);
CHECK(b->IsOneByteEqualTo(CStrVector(string)));
b = isolate->factory()->InternalizeUtf8String(CStrVector(string));
CHECK_EQ(*b, *a);
CHECK(b->IsOneByteEqualTo(CStrVector(string)));
}
}
TEST(StringTable) {
CcTest::InitializeVM();
v8::HandleScope sc(CcTest::isolate());
CheckInternalizedStrings(not_so_random_string_table);
CheckInternalizedStrings(not_so_random_string_table);
}
TEST(FunctionAllocation) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope sc(CcTest::isolate());
Handle<String> name = factory->InternalizeUtf8String("theFunction");
Handle<JSFunction> function = factory->NewFunctionForTest(name);
Handle<Smi> twenty_three(Smi::FromInt(23), isolate);
Handle<Smi> twenty_four(Smi::FromInt(24), isolate);
Handle<String> prop_name = factory->InternalizeUtf8String("theSlot");
Handle<JSObject> obj = factory->NewJSObject(function);
Object::SetProperty(isolate, obj, prop_name, twenty_three).Check();
CHECK_EQ(Smi::FromInt(23),
*Object::GetProperty(isolate, obj, prop_name).ToHandleChecked());
// Check that we can add properties to function objects.
Object::SetProperty(isolate, function, prop_name, twenty_four).Check();
CHECK_EQ(
Smi::FromInt(24),
*Object::GetProperty(isolate, function, prop_name).ToHandleChecked());
}
TEST(ObjectProperties) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope sc(CcTest::isolate());
Handle<String> object_string(
String::cast(ReadOnlyRoots(CcTest::heap()).Object_string()), isolate);
Handle<Object> object =
Object::GetProperty(isolate, CcTest::i_isolate()->global_object(),
object_string)
.ToHandleChecked();
Handle<JSFunction> constructor = Handle<JSFunction>::cast(object);
Handle<JSObject> obj = factory->NewJSObject(constructor);
Handle<String> first = factory->InternalizeUtf8String("first");
Handle<String> second = factory->InternalizeUtf8String("second");
Handle<Smi> one(Smi::FromInt(1), isolate);
Handle<Smi> two(Smi::FromInt(2), isolate);
// check for empty
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, first));
// add first
Object::SetProperty(isolate, obj, first, one).Check();
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, first));
// delete first
CHECK(Just(true) ==
JSReceiver::DeleteProperty(obj, first, LanguageMode::kSloppy));
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, first));
// add first and then second
Object::SetProperty(isolate, obj, first, one).Check();
Object::SetProperty(isolate, obj, second, two).Check();
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, first));
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, second));
// delete first and then second
CHECK(Just(true) ==
JSReceiver::DeleteProperty(obj, first, LanguageMode::kSloppy));
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, second));
CHECK(Just(true) ==
JSReceiver::DeleteProperty(obj, second, LanguageMode::kSloppy));
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, first));
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, second));
// add first and then second
Object::SetProperty(isolate, obj, first, one).Check();
Object::SetProperty(isolate, obj, second, two).Check();
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, first));
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, second));
// delete second and then first
CHECK(Just(true) ==
JSReceiver::DeleteProperty(obj, second, LanguageMode::kSloppy));
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, first));
CHECK(Just(true) ==
JSReceiver::DeleteProperty(obj, first, LanguageMode::kSloppy));
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, first));
CHECK(Just(false) == JSReceiver::HasOwnProperty(obj, second));
// check string and internalized string match
const char* string1 = "fisk";
Handle<String> s1 = factory->NewStringFromAsciiChecked(string1);
Object::SetProperty(isolate, obj, s1, one).Check();
Handle<String> s1_string = factory->InternalizeUtf8String(string1);
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, s1_string));
// check internalized string and string match
const char* string2 = "fugl";
Handle<String> s2_string = factory->InternalizeUtf8String(string2);
Object::SetProperty(isolate, obj, s2_string, one).Check();
Handle<String> s2 = factory->NewStringFromAsciiChecked(string2);
CHECK(Just(true) == JSReceiver::HasOwnProperty(obj, s2));
}
TEST(JSObjectMaps) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope sc(CcTest::isolate());
Handle<String> name = factory->InternalizeUtf8String("theFunction");
Handle<JSFunction> function = factory->NewFunctionForTest(name);
Handle<String> prop_name = factory->InternalizeUtf8String("theSlot");
Handle<JSObject> obj = factory->NewJSObject(function);
Handle<Map> initial_map(function->initial_map(), isolate);
// Set a propery
Handle<Smi> twenty_three(Smi::FromInt(23), isolate);
Object::SetProperty(isolate, obj, prop_name, twenty_three).Check();
CHECK_EQ(Smi::FromInt(23),
*Object::GetProperty(isolate, obj, prop_name).ToHandleChecked());
// Check the map has changed
CHECK(*initial_map != obj->map());
}
TEST(JSArray) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope sc(CcTest::isolate());
Handle<String> name = factory->InternalizeUtf8String("Array");
Handle<Object> fun_obj =
Object::GetProperty(isolate, CcTest::i_isolate()->global_object(), name)
.ToHandleChecked();
Handle<JSFunction> function = Handle<JSFunction>::cast(fun_obj);
// Allocate the object.
Handle<Object> element;
Handle<JSObject> object = factory->NewJSObject(function);
Handle<JSArray> array = Handle<JSArray>::cast(object);
// We just initialized the VM, no heap allocation failure yet.
JSArray::Initialize(array, 0);
// Set array length to 0.
JSArray::SetLength(array, 0);
CHECK_EQ(Smi::zero(), array->length());
// Must be in fast mode.
CHECK(array->HasSmiOrObjectElements());
// array[length] = name.
Object::SetElement(isolate, array, 0, name, ShouldThrow::kDontThrow).Check();
CHECK_EQ(Smi::FromInt(1), array->length());
element = i::Object::GetElement(isolate, array, 0).ToHandleChecked();
CHECK_EQ(*element, *name);
// Set array length with larger than smi value.
JSArray::SetLength(array, static_cast<uint32_t>(Smi::kMaxValue) + 1);
uint32_t int_length = 0;
CHECK(array->length().ToArrayIndex(&int_length));
CHECK_EQ(static_cast<uint32_t>(Smi::kMaxValue) + 1, int_length);
CHECK(array->HasDictionaryElements()); // Must be in slow mode.
// array[length] = name.
Object::SetElement(isolate, array, int_length, name, ShouldThrow::kDontThrow)
.Check();
uint32_t new_int_length = 0;
CHECK(array->length().ToArrayIndex(&new_int_length));
CHECK_EQ(static_cast<double>(int_length), new_int_length - 1);
element = Object::GetElement(isolate, array, int_length).ToHandleChecked();
CHECK_EQ(*element, *name);
element = Object::GetElement(isolate, array, 0).ToHandleChecked();
CHECK_EQ(*element, *name);
}
TEST(JSObjectCopy) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope sc(CcTest::isolate());
Handle<String> object_string(
String::cast(ReadOnlyRoots(CcTest::heap()).Object_string()), isolate);
Handle<Object> object =
Object::GetProperty(isolate, CcTest::i_isolate()->global_object(),
object_string)
.ToHandleChecked();
Handle<JSFunction> constructor = Handle<JSFunction>::cast(object);
Handle<JSObject> obj = factory->NewJSObject(constructor);
Handle<String> first = factory->InternalizeUtf8String("first");
Handle<String> second = factory->InternalizeUtf8String("second");
Handle<Smi> one(Smi::FromInt(1), isolate);
Handle<Smi> two(Smi::FromInt(2), isolate);
Object::SetProperty(isolate, obj, first, one).Check();
Object::SetProperty(isolate, obj, second, two).Check();
Object::SetElement(isolate, obj, 0, first, ShouldThrow::kDontThrow).Check();
Object::SetElement(isolate, obj, 1, second, ShouldThrow::kDontThrow).Check();
// Make the clone.
Handle<Object> value1, value2;
Handle<JSObject> clone = factory->CopyJSObject(obj);
CHECK(!clone.is_identical_to(obj));
value1 = Object::GetElement(isolate, obj, 0).ToHandleChecked();
value2 = Object::GetElement(isolate, clone, 0).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetElement(isolate, obj, 1).ToHandleChecked();
value2 = Object::GetElement(isolate, clone, 1).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetProperty(isolate, obj, first).ToHandleChecked();
value2 = Object::GetProperty(isolate, clone, first).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetProperty(isolate, obj, second).ToHandleChecked();
value2 = Object::GetProperty(isolate, clone, second).ToHandleChecked();
CHECK_EQ(*value1, *value2);
// Flip the values.
Object::SetProperty(isolate, clone, first, two).Check();
Object::SetProperty(isolate, clone, second, one).Check();
Object::SetElement(isolate, clone, 0, second, ShouldThrow::kDontThrow)
.Check();
Object::SetElement(isolate, clone, 1, first, ShouldThrow::kDontThrow).Check();
value1 = Object::GetElement(isolate, obj, 1).ToHandleChecked();
value2 = Object::GetElement(isolate, clone, 0).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetElement(isolate, obj, 0).ToHandleChecked();
value2 = Object::GetElement(isolate, clone, 1).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetProperty(isolate, obj, second).ToHandleChecked();
value2 = Object::GetProperty(isolate, clone, first).ToHandleChecked();
CHECK_EQ(*value1, *value2);
value1 = Object::GetProperty(isolate, obj, first).ToHandleChecked();
value2 = Object::GetProperty(isolate, clone, second).ToHandleChecked();
CHECK_EQ(*value1, *value2);
}
TEST(StringAllocation) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
const unsigned char chars[] = {0xE5, 0xA4, 0xA7};
for (int length = 0; length < 100; length++) {
v8::HandleScope scope(CcTest::isolate());
char* non_one_byte = NewArray<char>(3 * length + 1);
char* one_byte = NewArray<char>(length + 1);
non_one_byte[3 * length] = 0;
one_byte[length] = 0;
for (int i = 0; i < length; i++) {
one_byte[i] = 'a';
non_one_byte[3 * i] = chars[0];
non_one_byte[3 * i + 1] = chars[1];
non_one_byte[3 * i + 2] = chars[2];
}
Handle<String> non_one_byte_sym = factory->InternalizeUtf8String(
Vector<const char>(non_one_byte, 3 * length));
CHECK_EQ(length, non_one_byte_sym->length());
Handle<String> one_byte_sym =
factory->InternalizeString(OneByteVector(one_byte, length));
CHECK_EQ(length, one_byte_sym->length());
Handle<String> non_one_byte_str =
factory->NewStringFromUtf8(Vector<const char>(non_one_byte, 3 * length))
.ToHandleChecked();
non_one_byte_str->Hash();
CHECK_EQ(length, non_one_byte_str->length());
Handle<String> one_byte_str =
factory->NewStringFromUtf8(Vector<const char>(one_byte, length))
.ToHandleChecked();
one_byte_str->Hash();
CHECK_EQ(length, one_byte_str->length());
DeleteArray(non_one_byte);
DeleteArray(one_byte);
}
}
static int ObjectsFoundInHeap(Heap* heap, Handle<Object> objs[], int size) {
// Count the number of objects found in the heap.
int found_count = 0;
HeapObjectIterator iterator(heap);
for (HeapObject obj = iterator.Next(); !obj.is_null();
obj = iterator.Next()) {
for (int i = 0; i < size; i++) {
if (*objs[i] == obj) {
found_count++;
}
}
}
return found_count;
}
TEST(Iteration) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope scope(CcTest::isolate());
// Array of objects to scan haep for.
const int objs_count = 6;
Handle<Object> objs[objs_count];
int next_objs_index = 0;
// Allocate a JS array to OLD_SPACE and NEW_SPACE
objs[next_objs_index++] = factory->NewJSArray(10);
objs[next_objs_index++] =
factory->NewJSArray(10, HOLEY_ELEMENTS, AllocationType::kOld);
// Allocate a small string to OLD_DATA_SPACE and NEW_SPACE
objs[next_objs_index++] = factory->NewStringFromStaticChars("abcdefghij");
objs[next_objs_index++] =
factory->NewStringFromStaticChars("abcdefghij", AllocationType::kOld);
// Allocate a large string (for large object space).
int large_size = kMaxRegularHeapObjectSize + 1;
char* str = new char[large_size];
for (int i = 0; i < large_size - 1; ++i) str[i] = 'a';
str[large_size - 1] = '\0';
objs[next_objs_index++] =
factory->NewStringFromAsciiChecked(str, AllocationType::kOld);
delete[] str;
// Add a Map object to look for.
objs[next_objs_index++] =
Handle<Map>(HeapObject::cast(*objs[0]).map(), isolate);
CHECK_EQ(objs_count, next_objs_index);
CHECK_EQ(objs_count, ObjectsFoundInHeap(CcTest::heap(), objs, objs_count));
}
TEST(TestBytecodeFlushing) {
#ifndef V8_LITE_MODE
FLAG_opt = false;
FLAG_always_opt = false;
i::FLAG_optimize_for_size = false;
#endif // V8_LITE_MODE
i::FLAG_flush_bytecode = true;
i::FLAG_allow_natives_syntax = true;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
Isolate* i_isolate = CcTest::i_isolate();
Factory* factory = i_isolate->factory();
{
v8::HandleScope scope(isolate);
v8::Context::New(isolate)->Enter();
const char* source =
"function foo() {"
" var x = 42;"
" var y = 42;"
" var z = x + y;"
"};"
"foo()";
Handle<String> foo_name = factory->InternalizeUtf8String("foo");
// This compile will add the code to the compilation cache.
{
v8::HandleScope scope(isolate);
CompileRun(source);
}
// Check function is compiled.
Handle<Object> func_value =
Object::GetProperty(i_isolate, i_isolate->global_object(), foo_name)
.ToHandleChecked();
CHECK(func_value->IsJSFunction());
Handle<JSFunction> function = Handle<JSFunction>::cast(func_value);
CHECK(function->shared().is_compiled());
// The code will survive at least two GCs.
CcTest::CollectAllGarbage();
CcTest::CollectAllGarbage();
CHECK(function->shared().is_compiled());
// Simulate several GCs that use full marking.
const int kAgingThreshold = 6;
for (int i = 0; i < kAgingThreshold; i++) {
CcTest::CollectAllGarbage();
}
// foo should no longer be in the compilation cache
CHECK(!function->shared().is_compiled());
CHECK(!function->is_compiled());
// Call foo to get it recompiled.
CompileRun("foo()");
CHECK(function->shared().is_compiled());
CHECK(function->is_compiled());
}
}
HEAP_TEST(Regress10560) {
i::FLAG_flush_bytecode = true;
i::FLAG_allow_natives_syntax = true;
// Disable flags that allocate a feedback vector eagerly.
i::FLAG_opt = false;
i::FLAG_always_opt = false;
i::FLAG_lazy_feedback_allocation = true;
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
Isolate* i_isolate = CcTest::i_isolate();
Factory* factory = i_isolate->factory();
Heap* heap = i_isolate->heap();
{
v8::HandleScope scope(isolate);
const char* source =
"function foo() {"
" var x = 42;"
" var y = 42;"
" var z = x + y;"
"};"
"foo()";
Handle<String> foo_name = factory->InternalizeUtf8String("foo");
CompileRun(source);
// Check function is compiled.
Handle<Object> func_value =
Object::GetProperty(i_isolate, i_isolate->global_object(), foo_name)
.ToHandleChecked();
CHECK(func_value->IsJSFunction());
Handle<JSFunction> function = Handle<JSFunction>::cast(func_value);
CHECK(function->shared().is_compiled());
CHECK(!function->has_feedback_vector());
// Pre-age bytecode so it will be flushed on next run.
CHECK(function->shared().HasBytecodeArray());
const int kAgingThreshold = 6;
for (int i = 0; i < kAgingThreshold; i++) {
function->shared().GetBytecodeArray().MakeOlder();
if (function->shared().GetBytecodeArray().IsOld()) break;
}
CHECK(function->shared().GetBytecodeArray().IsOld());
heap::SimulateFullSpace(heap->old_space());
// Just check bytecode isn't flushed still
CHECK(function->shared().GetBytecodeArray().IsOld());
CHECK(function->shared().is_compiled());
heap->set_force_gc_on_next_allocation();
// Allocate feedback vector.
IsCompiledScope is_compiled_scope(
function->shared().is_compiled_scope(i_isolate));
JSFunction::EnsureFeedbackVector(function, &is_compiled_scope);
CHECK(function->has_feedback_vector());
CHECK(function->shared().is_compiled());
CHECK(function->is_compiled());
}
}
UNINITIALIZED_TEST(Regress10843) {
FLAG_max_semi_space_size = 2;
FLAG_min_semi_space_size = 2;
FLAG_max_old_space_size = 8;
FLAG_always_compact = true;
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
Factory* factory = i_isolate->factory();
Heap* heap = i_isolate->heap();
bool callback_was_invoked = false;
heap->AddNearHeapLimitCallback(
[](void* data, size_t current_heap_limit,
size_t initial_heap_limit) -> size_t {
*reinterpret_cast<bool*>(data) = true;
return current_heap_limit * 2;
},
&callback_was_invoked);
{
HandleScope scope(i_isolate);
std::vector<Handle<FixedArray>> arrays;
for (int i = 0; i < 140; i++) {
arrays.push_back(factory->NewFixedArray(10000));
}
CcTest::CollectAllGarbage(i_isolate);
CcTest::CollectAllGarbage(i_isolate);
for (int i = 0; i < 40; i++) {
arrays.push_back(factory->NewFixedArray(10000));
}
CcTest::CollectAllGarbage(i_isolate);
for (int i = 0; i < 100; i++) {
arrays.push_back(factory->NewFixedArray(10000));
}
CHECK(callback_was_invoked);
}
isolate->Dispose();
}
// Tests that spill slots from optimized code don't have weak pointers.
TEST(Regress10774) {
i::FLAG_allow_natives_syntax = true;
i::FLAG_turboprop = true;
i::FLAG_turboprop_dynamic_map_checks = true;
#ifdef VERIFY_HEAP
i::FLAG_verify_heap = true;
#endif
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
Isolate* i_isolate = CcTest::i_isolate();
Factory* factory = i_isolate->factory();
Heap* heap = i_isolate->heap();
{
v8::HandleScope scope(isolate);
// We want to generate optimized code with dynamic map check operator that
// migrates deprecated maps. To force this, we want the IC state to be
// monomorphic and the map in the feedback should be a migration target.
const char* source =
"function f(o) {"
" return o.b;"
"}"
"var o = {a:10, b:20};"
"var o1 = {a:10, b:20};"
"var o2 = {a:10, b:20};"
"%PrepareFunctionForOptimization(f);"
"f(o);"
"o1.b = 10.23;" // Deprecate O's map.
"f(o1);" // Install new map in IC
"f(o);" // Mark o's map as migration target
"%OptimizeFunctionOnNextCall(f);"
"f(o);";
CompileRun(source);
Handle<String> foo_name = factory->InternalizeUtf8String("f");
Handle<Object> func_value =
Object::GetProperty(i_isolate, i_isolate->global_object(), foo_name)
.ToHandleChecked();
CHECK(func_value->IsJSFunction());
Handle<JSFunction> fun = Handle<JSFunction>::cast(func_value);
Handle<String> obj_name = factory->InternalizeUtf8String("o2");
Handle<Object> obj_value =
Object::GetProperty(i_isolate, i_isolate->global_object(), obj_name)
.ToHandleChecked();
heap::SimulateFullSpace(heap->new_space());
Handle<JSObject> global(i_isolate->context().global_object(), i_isolate);
// O2 still has the deprecated map and the optimized code should migrate O2
// successfully. This shouldn't crash.
Execution::Call(i_isolate, fun, global, 1, &obj_value).ToHandleChecked();
}
}
#ifndef V8_LITE_MODE
TEST(TestOptimizeAfterBytecodeFlushingCandidate) {
FLAG_opt = true;
FLAG_always_opt = false;
i::FLAG_optimize_for_size = false;
i::FLAG_incremental_marking = true;
i::FLAG_flush_bytecode = true;
i::FLAG_allow_natives_syntax = true;
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope scope(CcTest::isolate());
const char* source =
"function foo() {"
" var x = 42;"
" var y = 42;"
" var z = x + y;"
"};"
"foo()";
Handle<String> foo_name = factory->InternalizeUtf8String("foo");
// This compile will add the code to the compilation cache.
{
v8::HandleScope scope(CcTest::isolate());
CompileRun(source);
}
// Check function is compiled.
Handle<Object> func_value =
Object::GetProperty(isolate, isolate->global_object(), foo_name)
.ToHandleChecked();
CHECK(func_value->IsJSFunction());
Handle<JSFunction> function = Handle<JSFunction>::cast(func_value);
CHECK(function->shared().is_compiled());
// The code will survive at least two GCs.
CcTest::CollectAllGarbage();
CcTest::CollectAllGarbage();
CHECK(function->shared().is_compiled());
// Simulate several GCs that use incremental marking.
const int kAgingThreshold = 6;
for (int i = 0; i < kAgingThreshold; i++) {
heap::SimulateIncrementalMarking(CcTest::heap());
CcTest::CollectAllGarbage();
}
CHECK(!function->shared().is_compiled());
CHECK(!function->is_compiled());
// This compile will compile the function again.
{
v8::HandleScope scope(CcTest::isolate());
CompileRun("foo();");
}
// Simulate several GCs that use incremental marking but make sure
// the loop breaks once the function is enqueued as a candidate.
for (int i = 0; i < kAgingThreshold; i++) {
heap::SimulateIncrementalMarking(CcTest::heap());
if (function->shared().GetBytecodeArray().IsOld()) break;
CcTest::CollectAllGarbage();
}
// Force optimization while incremental marking is active and while
// the function is enqueued as a candidate.
{
v8::HandleScope scope(CcTest::isolate());
CompileRun(
"%PrepareFunctionForOptimization(foo);"
"%OptimizeFunctionOnNextCall(foo); foo();");
}
// Simulate one final GC and make sure the candidate wasn't flushed.
CcTest::CollectAllGarbage();
CHECK(function->shared().is_compiled());
CHECK(function->is_compiled());
}
#endif // V8_LITE_MODE
TEST(TestUseOfIncrementalBarrierOnCompileLazy) {
if (!FLAG_incremental_marking) return;
// Turn off always_opt because it interferes with running the built-in for
// the last call to g().
FLAG_always_opt = false;
FLAG_allow_natives_syntax = true;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
v8::HandleScope scope(CcTest::isolate());
CompileRun(
"function make_closure(x) {"
" return function() { return x + 3 };"
"}"
"var f = make_closure(5);"
"%PrepareFunctionForOptimization(f); f();"
"var g = make_closure(5);");
// Check f is compiled.
Handle<String> f_name = factory->InternalizeUtf8String("f");
Handle<Object> f_value =
Object::GetProperty(isolate, isolate->global_object(), f_name)
.ToHandleChecked();
Handle<JSFunction> f_function = Handle<JSFunction>::cast(f_value);
CHECK(f_function->is_compiled());
// Check g is not compiled.
Handle<String> g_name = factory->InternalizeUtf8String("g");
Handle<Object> g_value =
Object::GetProperty(isolate, isolate->global_object(), g_name)
.ToHandleChecked();
Handle<JSFunction> g_function = Handle<JSFunction>::cast(g_value);
CHECK(!g_function->is_compiled());
heap::SimulateIncrementalMarking(heap);
CompileRun("%OptimizeFunctionOnNextCall(f); f();");
// g should now have available an optimized function, unmarked by gc. The
// CompileLazy built-in will discover it and install it in the closure, and
// the incremental write barrier should be used.
CompileRun("g();");
CHECK(g_function->is_compiled());
}
TEST(CompilationCacheCachingBehavior) {
// If we do not have the compilation cache turned off, this test is invalid.
if (!FLAG_compilation_cache) {
return;
}
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
CompilationCache* compilation_cache = isolate->compilation_cache();
LanguageMode language_mode = construct_language_mode(FLAG_use_strict);
v8::HandleScope scope(CcTest::isolate());
const char* raw_source =
"function foo() {"
" var x = 42;"
" var y = 42;"
" var z = x + y;"
"};"
"foo();";
Handle<String> source = factory->InternalizeUtf8String(raw_source);
Handle<Context> native_context = isolate->native_context();
{
v8::HandleScope scope(CcTest::isolate());
CompileRun(raw_source);
}
// The script should be in the cache now.
{
v8::HandleScope scope(CcTest::isolate());
MaybeHandle<SharedFunctionInfo> cached_script =
compilation_cache->LookupScript(source, Handle<Object>(), 0, 0,
v8::ScriptOriginOptions(true, false),
native_context, language_mode);
CHECK(!cached_script.is_null());
}
// Check that the code cache entry survives at least one GC.
{
CcTest::CollectAllGarbage();
v8::HandleScope scope(CcTest::isolate());
MaybeHandle<SharedFunctionInfo> cached_script =
compilation_cache->LookupScript(source, Handle<Object>(), 0, 0,
v8::ScriptOriginOptions(true, false),
native_context, language_mode);
CHECK(!cached_script.is_null());
// Progress code age until it's old and ready for GC.
Handle<SharedFunctionInfo> shared = cached_script.ToHandleChecked();
CHECK(shared->HasBytecodeArray());
const int kAgingThreshold = 6;
for (int i = 0; i < kAgingThreshold; i++) {
shared->GetBytecodeArray().MakeOlder();
}
}
CcTest::CollectAllGarbage();
{
v8::HandleScope scope(CcTest::isolate());
// Ensure code aging cleared the entry from the cache.
MaybeHandle<SharedFunctionInfo> cached_script =
compilation_cache->LookupScript(source, Handle<Object>(), 0, 0,
v8::ScriptOriginOptions(true, false),
native_context, language_mode);
CHECK(cached_script.is_null());
}
}
static void OptimizeEmptyFunction(const char* name) {
HandleScope scope(CcTest::i_isolate());
EmbeddedVector<char, 256> source;
SNPrintF(source,
"function %s() { return 0; }"
"%%PrepareFunctionForOptimization(%s);"
"%s(); %s();"
"%%OptimizeFunctionOnNextCall(%s);"
"%s();",
name, name, name, name, name, name);
CompileRun(source.begin());
}
// Count the number of native contexts in the weak list of native contexts.
int CountNativeContexts() {
int count = 0;
Object object = CcTest::heap()->native_contexts_list();
while (!object.IsUndefined(CcTest::i_isolate())) {
count++;
object = Context::cast(object).next_context_link();
}
return count;
}
TEST(TestInternalWeakLists) {
FLAG_always_opt = false;
FLAG_allow_natives_syntax = true;
v8::V8::Initialize();
// Some flags turn Scavenge collections into Mark-sweep collections
// and hence are incompatible with this test case.
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
FLAG_retain_maps_for_n_gc = 0;
static const int kNumTestContexts = 10;
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
v8::Local<v8::Context> ctx[kNumTestContexts];
if (!isolate->use_optimizer()) return;
CHECK_EQ(0, CountNativeContexts());
// Create a number of global contests which gets linked together.
for (int i = 0; i < kNumTestContexts; i++) {
ctx[i] = v8::Context::New(CcTest::isolate());
// Collect garbage that might have been created by one of the
// installed extensions.
isolate->compilation_cache()->Clear();
CcTest::CollectAllGarbage();
CHECK_EQ(i + 1, CountNativeContexts());
ctx[i]->Enter();
// Create a handle scope so no function objects get stuck in the outer
// handle scope.
HandleScope scope(isolate);
OptimizeEmptyFunction("f1");
OptimizeEmptyFunction("f2");
OptimizeEmptyFunction("f3");
OptimizeEmptyFunction("f4");
OptimizeEmptyFunction("f5");
// Remove function f1, and
CompileRun("f1=null");
// Scavenge treats these references as strong.
for (int j = 0; j < 10; j++) {
CcTest::CollectGarbage(NEW_SPACE);
}
// Mark compact handles the weak references.
isolate->compilation_cache()->Clear();
CcTest::CollectAllGarbage();
// Get rid of f3 and f5 in the same way.
CompileRun("f3=null");
for (int j = 0; j < 10; j++) {
CcTest::CollectGarbage(NEW_SPACE);
}
CcTest::CollectAllGarbage();
CompileRun("f5=null");
for (int j = 0; j < 10; j++) {
CcTest::CollectGarbage(NEW_SPACE);
}
CcTest::CollectAllGarbage();
ctx[i]->Exit();
}
// Force compilation cache cleanup.
CcTest::heap()->NotifyContextDisposed(true);
CcTest::CollectAllGarbage();
// Dispose the native contexts one by one.
for (int i = 0; i < kNumTestContexts; i++) {
// TODO(dcarney): is there a better way to do this?
i::Address* unsafe = reinterpret_cast<i::Address*>(*ctx[i]);
*unsafe = ReadOnlyRoots(CcTest::heap()).undefined_value().ptr();
ctx[i].Clear();
// Scavenge treats these references as strong.
for (int j = 0; j < 10; j++) {
CcTest::CollectGarbage(i::NEW_SPACE);
CHECK_EQ(kNumTestContexts - i, CountNativeContexts());
}
// Mark compact handles the weak references.
CcTest::CollectAllGarbage();
CHECK_EQ(kNumTestContexts - i - 1, CountNativeContexts());
}
CHECK_EQ(0, CountNativeContexts());
}
TEST(TestSizeOfRegExpCode) {
if (!FLAG_regexp_optimization) return;
FLAG_stress_concurrent_allocation = false;
v8::V8::Initialize();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
LocalContext context;
// Adjust source below and this check to match
// RegExp::kRegExpTooLargeToOptimize.
CHECK_EQ(i::RegExp::kRegExpTooLargeToOptimize, 20 * KB);
// Compile a regexp that is much larger if we are using regexp optimizations.
CompileRun(
"var reg_exp_source = '(?:a|bc|def|ghij|klmno|pqrstu)';"
"var half_size_reg_exp;"
"while (reg_exp_source.length < 20 * 1024) {"
" half_size_reg_exp = reg_exp_source;"
" reg_exp_source = reg_exp_source + reg_exp_source;"
"}"
// Flatten string.
"reg_exp_source.match(/f/);");
// Get initial heap size after several full GCs, which will stabilize
// the heap size and return with sweeping finished completely.
CcTest::CollectAllAvailableGarbage();
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
int initial_size = static_cast<int>(CcTest::heap()->SizeOfObjects());
CompileRun("'foo'.match(reg_exp_source);");
CcTest::CollectAllAvailableGarbage();
int size_with_regexp = static_cast<int>(CcTest::heap()->SizeOfObjects());
CompileRun("'foo'.match(half_size_reg_exp);");
CcTest::CollectAllAvailableGarbage();
int size_with_optimized_regexp =
static_cast<int>(CcTest::heap()->SizeOfObjects());
int size_of_regexp_code = size_with_regexp - initial_size;
// On some platforms the debug-code flag causes huge amounts of regexp code
// to be emitted, breaking this test.
if (!FLAG_debug_code) {
CHECK_LE(size_of_regexp_code, 1 * MB);
}
// Small regexp is half the size, but compiles to more than twice the code
// due to the optimization steps.
CHECK_GE(size_with_optimized_regexp,
size_with_regexp + size_of_regexp_code * 2);
}
HEAP_TEST(TestSizeOfObjects) {
FLAG_stress_concurrent_allocation = false;
v8::V8::Initialize();
Isolate* isolate = CcTest::i_isolate();
Heap* heap = CcTest::heap();
// Disable LAB, such that calculations with SizeOfObjects() and object size
// are correct.
heap->DisableInlineAllocation();
MarkCompactCollector* collector = heap->mark_compact_collector();
// Get initial heap size after several full GCs, which will stabilize
// the heap size and return with sweeping finished completely.
CcTest::CollectAllAvailableGarbage();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
int initial_size = static_cast<int>(heap->SizeOfObjects());
{
HandleScope scope(isolate);
// Allocate objects on several different old-space pages so that
// concurrent sweeper threads will be busy sweeping the old space on
// subsequent GC runs.
AlwaysAllocateScopeForTesting always_allocate(heap);
int filler_size = static_cast<int>(FixedArray::SizeFor(8192));
for (int i = 1; i <= 100; i++) {
isolate->factory()->NewFixedArray(8192, AllocationType::kOld);
CHECK_EQ(initial_size + i * filler_size,
static_cast<int>(heap->SizeOfObjects()));
}
}
// The heap size should go back to initial size after a full GC, even
// though sweeping didn't finish yet.
CcTest::CollectAllGarbage();
// Normally sweeping would not be complete here, but no guarantees.
CHECK_EQ(initial_size, static_cast<int>(heap->SizeOfObjects()));
// Waiting for sweeper threads should not change heap size.
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
CHECK_EQ(initial_size, static_cast<int>(heap->SizeOfObjects()));
}
TEST(TestAlignmentCalculations) {
// Maximum fill amounts are consistent.
int maximum_double_misalignment = kDoubleSize - kTaggedSize;
int max_word_fill = Heap::GetMaximumFillToAlign(kWordAligned);
CHECK_EQ(0, max_word_fill);
int max_double_fill = Heap::GetMaximumFillToAlign(kDoubleAligned);
CHECK_EQ(maximum_double_misalignment, max_double_fill);
int max_double_unaligned_fill = Heap::GetMaximumFillToAlign(kDoubleUnaligned);
CHECK_EQ(maximum_double_misalignment, max_double_unaligned_fill);
Address base = kNullAddress;
int fill = 0;
// Word alignment never requires fill.
fill = Heap::GetFillToAlign(base, kWordAligned);
CHECK_EQ(0, fill);
fill = Heap::GetFillToAlign(base + kTaggedSize, kWordAligned);
CHECK_EQ(0, fill);
// No fill is required when address is double aligned.
fill = Heap::GetFillToAlign(base, kDoubleAligned);
CHECK_EQ(0, fill);
// Fill is required if address is not double aligned.
fill = Heap::GetFillToAlign(base + kTaggedSize, kDoubleAligned);
CHECK_EQ(maximum_double_misalignment, fill);
// kDoubleUnaligned has the opposite fill amounts.
fill = Heap::GetFillToAlign(base, kDoubleUnaligned);
CHECK_EQ(maximum_double_misalignment, fill);
fill = Heap::GetFillToAlign(base + kTaggedSize, kDoubleUnaligned);
CHECK_EQ(0, fill);
}
static HeapObject NewSpaceAllocateAligned(int size,
AllocationAlignment alignment) {
Heap* heap = CcTest::heap();
AllocationResult allocation = heap->new_space()->AllocateRaw(size, alignment);
HeapObject obj;
allocation.To(&obj);
heap->CreateFillerObjectAt(obj.address(), size, ClearRecordedSlots::kNo);
return obj;
}
// Get new space allocation into the desired alignment.
static Address AlignNewSpace(AllocationAlignment alignment, int offset) {
Address* top_addr = CcTest::heap()->new_space()->allocation_top_address();
int fill = Heap::GetFillToAlign(*top_addr, alignment);
int allocation = fill + offset;
if (allocation) {
NewSpaceAllocateAligned(allocation, kWordAligned);
}
return *top_addr;
}
TEST(TestAlignedAllocation) {
// Double misalignment is 4 on 32-bit platforms or when pointer compression
// is enabled, 0 on 64-bit ones when pointer compression is disabled.
const intptr_t double_misalignment = kDoubleSize - kTaggedSize;
Address* top_addr = CcTest::heap()->new_space()->allocation_top_address();
Address start;
HeapObject obj;
HeapObject filler;
if (double_misalignment) {
// Allocate a pointer sized object that must be double aligned at an
// aligned address.
start = AlignNewSpace(kDoubleAligned, 0);
obj = NewSpaceAllocateAligned(kTaggedSize, kDoubleAligned);
CHECK(IsAligned(obj.address(), kDoubleAlignment));
// There is no filler.
CHECK_EQ(kTaggedSize, *top_addr - start);
// Allocate a second pointer sized object that must be double aligned at an
// unaligned address.
start = AlignNewSpace(kDoubleAligned, kTaggedSize);
obj = NewSpaceAllocateAligned(kTaggedSize, kDoubleAligned);
CHECK(IsAligned(obj.address(), kDoubleAlignment));
// There is a filler object before the object.
filler = HeapObject::FromAddress(start);
CHECK(obj != filler && filler.IsFreeSpaceOrFiller() &&
filler.Size() == kTaggedSize);
CHECK_EQ(kTaggedSize + double_misalignment, *top_addr - start);
// Similarly for kDoubleUnaligned.
start = AlignNewSpace(kDoubleUnaligned, 0);
obj = NewSpaceAllocateAligned(kTaggedSize, kDoubleUnaligned);
CHECK(IsAligned(obj.address() + kTaggedSize, kDoubleAlignment));
CHECK_EQ(kTaggedSize, *top_addr - start);
start = AlignNewSpace(kDoubleUnaligned, kTaggedSize);
obj = NewSpaceAllocateAligned(kTaggedSize, kDoubleUnaligned);
CHECK(IsAligned(obj.address() + kTaggedSize, kDoubleAlignment));
// There is a filler object before the object.
filler = HeapObject::FromAddress(start);
CHECK(obj != filler && filler.IsFreeSpaceOrFiller() &&
filler.Size() == kTaggedSize);
CHECK_EQ(kTaggedSize + double_misalignment, *top_addr - start);
}
}
static HeapObject OldSpaceAllocateAligned(int size,
AllocationAlignment alignment) {
Heap* heap = CcTest::heap();
AllocationResult allocation =
heap->old_space()->AllocateRawAligned(size, alignment);
HeapObject obj;
allocation.To(&obj);
heap->CreateFillerObjectAt(obj.address(), size, ClearRecordedSlots::kNo);
return obj;
}
// Get old space allocation into the desired alignment.
static Address AlignOldSpace(AllocationAlignment alignment, int offset) {
Address* top_addr = CcTest::heap()->old_space()->allocation_top_address();
int fill = Heap::GetFillToAlign(*top_addr, alignment);
int allocation = fill + offset;
if (allocation) {
OldSpaceAllocateAligned(allocation, kWordAligned);
}
Address top = *top_addr;
// Now force the remaining allocation onto the free list.
CcTest::heap()->old_space()->FreeLinearAllocationArea();
return top;
}
// Test the case where allocation must be done from the free list, so filler
// may precede or follow the object.
TEST(TestAlignedOverAllocation) {
if (FLAG_stress_concurrent_allocation) return;
ManualGCScope manual_gc_scope;
Heap* heap = CcTest::heap();
// Test checks for fillers before and behind objects and requires a fresh
// page and empty free list.
heap::AbandonCurrentlyFreeMemory(heap->old_space());
// Allocate a dummy object to properly set up the linear allocation info.
AllocationResult dummy = heap->old_space()->AllocateRawUnaligned(kTaggedSize);
CHECK(!dummy.IsRetry());
heap->CreateFillerObjectAt(dummy.ToObjectChecked().address(), kTaggedSize,
ClearRecordedSlots::kNo);
// Double misalignment is 4 on 32-bit platforms or when pointer compression
// is enabled, 0 on 64-bit ones when pointer compression is disabled.
const intptr_t double_misalignment = kDoubleSize - kTaggedSize;
Address start;
HeapObject obj;
HeapObject filler;
if (double_misalignment) {
start = AlignOldSpace(kDoubleAligned, 0);
obj = OldSpaceAllocateAligned(kTaggedSize, kDoubleAligned);
// The object is aligned.
CHECK(IsAligned(obj.address(), kDoubleAlignment));
// Try the opposite alignment case.
start = AlignOldSpace(kDoubleAligned, kTaggedSize);
obj = OldSpaceAllocateAligned(kTaggedSize, kDoubleAligned);
CHECK(IsAligned(obj.address(), kDoubleAlignment));
filler = HeapObject::FromAddress(start);
CHECK(obj != filler);
CHECK(filler.IsFreeSpaceOrFiller());
CHECK_EQ(kTaggedSize, filler.Size());
CHECK(obj != filler && filler.IsFreeSpaceOrFiller() &&
filler.Size() == kTaggedSize);
// Similarly for kDoubleUnaligned.
start = AlignOldSpace(kDoubleUnaligned, 0);
obj = OldSpaceAllocateAligned(kTaggedSize, kDoubleUnaligned);
// The object is aligned.
CHECK(IsAligned(obj.address() + kTaggedSize, kDoubleAlignment));
// Try the opposite alignment case.
start = AlignOldSpace(kDoubleUnaligned, kTaggedSize);
obj = OldSpaceAllocateAligned(kTaggedSize, kDoubleUnaligned);
CHECK(IsAligned(obj.address() + kTaggedSize, kDoubleAlignment));
filler = HeapObject::FromAddress(start);
CHECK(obj != filler && filler.IsFreeSpaceOrFiller() &&
filler.Size() == kTaggedSize);
}
}
TEST(HeapNumberAlignment) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope sc(isolate);
const auto required_alignment =
HeapObject::RequiredAlignment(*factory->heap_number_map());
const int maximum_misalignment =
Heap::GetMaximumFillToAlign(required_alignment);
for (int offset = 0; offset <= maximum_misalignment; offset += kTaggedSize) {
if (!FLAG_single_generation) {
AlignNewSpace(required_alignment, offset);
Handle<Object> number_new = factory->NewNumber(1.000123);
CHECK(number_new->IsHeapNumber());
CHECK(Heap::InYoungGeneration(*number_new));
CHECK_EQ(0, Heap::GetFillToAlign(HeapObject::cast(*number_new).address(),
required_alignment));
}
AlignOldSpace(required_alignment, offset);
Handle<Object> number_old =
factory->NewNumber<AllocationType::kOld>(1.000321);
CHECK(number_old->IsHeapNumber());
CHECK(heap->InOldSpace(*number_old));
CHECK_EQ(0, Heap::GetFillToAlign(HeapObject::cast(*number_old).address(),
required_alignment));
}
}
TEST(TestSizeOfObjectsVsHeapObjectIteratorPrecision) {
CcTest::InitializeVM();
// Disable LAB, such that calculations with SizeOfObjects() and object size
// are correct.
CcTest::heap()->DisableInlineAllocation();
HeapObjectIterator iterator(CcTest::heap());
intptr_t size_of_objects_1 = CcTest::heap()->SizeOfObjects();
intptr_t size_of_objects_2 = 0;
for (HeapObject obj = iterator.Next(); !obj.is_null();
obj = iterator.Next()) {
if (!obj.IsFreeSpace()) {
size_of_objects_2 += obj.Size();
}
}
// Delta must be within 5% of the larger result.
// TODO(gc): Tighten this up by distinguishing between byte
// arrays that are real and those that merely mark free space
// on the heap.
if (size_of_objects_1 > size_of_objects_2) {
intptr_t delta = size_of_objects_1 - size_of_objects_2;
PrintF("Heap::SizeOfObjects: %" V8PRIdPTR
", "
"Iterator: %" V8PRIdPTR
", "
"delta: %" V8PRIdPTR "\n",
size_of_objects_1, size_of_objects_2, delta);
CHECK_GT(size_of_objects_1 / 20, delta);
} else {
intptr_t delta = size_of_objects_2 - size_of_objects_1;
PrintF("Heap::SizeOfObjects: %" V8PRIdPTR
", "
"Iterator: %" V8PRIdPTR
", "
"delta: %" V8PRIdPTR "\n",
size_of_objects_1, size_of_objects_2, delta);
CHECK_GT(size_of_objects_2 / 20, delta);
}
}
TEST(GrowAndShrinkNewSpace) {
if (FLAG_single_generation) return;
// Avoid shrinking new space in GC epilogue. This can happen if allocation
// throughput samples have been taken while executing the benchmark.
FLAG_predictable = true;
FLAG_stress_concurrent_allocation = false; // For SimulateFullSpace.
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
NewSpace* new_space = heap->new_space();
if (heap->MaxSemiSpaceSize() == heap->InitialSemiSpaceSize()) {
return;
}
// Make sure we're in a consistent state to start out.
CcTest::CollectAllGarbage();
CcTest::CollectAllGarbage();
new_space->Shrink();
// Explicitly growing should double the space capacity.
size_t old_capacity, new_capacity;
old_capacity = new_space->TotalCapacity();
GrowNewSpace(heap);
new_capacity = new_space->TotalCapacity();
CHECK_EQ(2 * old_capacity, new_capacity);
old_capacity = new_space->TotalCapacity();
{
v8::HandleScope temporary_scope(CcTest::isolate());
heap::SimulateFullSpace(new_space);
}
new_capacity = new_space->TotalCapacity();
CHECK_EQ(old_capacity, new_capacity);
// Explicitly shrinking should not affect space capacity.
old_capacity = new_space->TotalCapacity();
new_space->Shrink();
new_capacity = new_space->TotalCapacity();
CHECK_EQ(old_capacity, new_capacity);
// Let the scavenger empty the new space.
CcTest::CollectGarbage(NEW_SPACE);
CHECK_LE(new_space->Size(), old_capacity);
// Explicitly shrinking should halve the space capacity.
old_capacity = new_space->TotalCapacity();
new_space->Shrink();
new_capacity = new_space->TotalCapacity();
CHECK_EQ(old_capacity, 2 * new_capacity);
// Consecutive shrinking should not affect space capacity.
old_capacity = new_space->TotalCapacity();
new_space->Shrink();
new_space->Shrink();
new_space->Shrink();
new_capacity = new_space->TotalCapacity();
CHECK_EQ(old_capacity, new_capacity);
}
TEST(CollectingAllAvailableGarbageShrinksNewSpace) {
if (FLAG_single_generation) return;
FLAG_stress_concurrent_allocation = false; // For SimulateFullSpace.
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
if (heap->MaxSemiSpaceSize() == heap->InitialSemiSpaceSize()) {
return;
}
v8::HandleScope scope(CcTest::isolate());
NewSpace* new_space = heap->new_space();
size_t old_capacity, new_capacity;
old_capacity = new_space->TotalCapacity();
GrowNewSpace(heap);
new_capacity = new_space->TotalCapacity();
CHECK_EQ(2 * old_capacity, new_capacity);
{
v8::HandleScope temporary_scope(CcTest::isolate());
heap::SimulateFullSpace(new_space);
}
CcTest::CollectAllAvailableGarbage();
new_capacity = new_space->TotalCapacity();
CHECK_EQ(old_capacity, new_capacity);
}
static int NumberOfGlobalObjects() {
int count = 0;
HeapObjectIterator iterator(CcTest::heap());
for (HeapObject obj = iterator.Next(); !obj.is_null();
obj = iterator.Next()) {
if (obj.IsJSGlobalObject()) count++;
}
return count;
}
// Test that we don't embed maps from foreign contexts into
// optimized code.
TEST(LeakNativeContextViaMap) {
FLAG_allow_natives_syntax = true;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope outer_scope(isolate);
v8::Persistent<v8::Context> ctx1p;
v8::Persistent<v8::Context> ctx2p;
{
v8::HandleScope scope(isolate);
ctx1p.Reset(isolate, v8::Context::New(isolate));
ctx2p.Reset(isolate, v8::Context::New(isolate));
v8::Local<v8::Context>::New(isolate, ctx1p)->Enter();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(2, NumberOfGlobalObjects());
{
v8::HandleScope inner_scope(isolate);
CompileRun("var v = {x: 42}");
v8::Local<v8::Context> ctx1 = v8::Local<v8::Context>::New(isolate, ctx1p);
v8::Local<v8::Context> ctx2 = v8::Local<v8::Context>::New(isolate, ctx2p);
v8::Local<v8::Value> v =
ctx1->Global()->Get(ctx1, v8_str("v")).ToLocalChecked();
ctx2->Enter();
CHECK(ctx2->Global()->Set(ctx2, v8_str("o"), v).FromJust());
v8::Local<v8::Value> res = CompileRun(
"function f() { return o.x; }"
"%PrepareFunctionForOptimization(f);"
"for (var i = 0; i < 10; ++i) f();"
"%OptimizeFunctionOnNextCall(f);"
"f();");
CHECK_EQ(42, res->Int32Value(ctx2).FromJust());
CHECK(ctx2->Global()
->Set(ctx2, v8_str("o"), v8::Int32::New(isolate, 0))
.FromJust());
ctx2->Exit();
v8::Local<v8::Context>::New(isolate, ctx1)->Exit();
ctx1p.Reset();
isolate->ContextDisposedNotification();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, NumberOfGlobalObjects());
ctx2p.Reset();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(0, NumberOfGlobalObjects());
}
// Test that we don't embed functions from foreign contexts into
// optimized code.
TEST(LeakNativeContextViaFunction) {
FLAG_allow_natives_syntax = true;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope outer_scope(isolate);
v8::Persistent<v8::Context> ctx1p;
v8::Persistent<v8::Context> ctx2p;
{
v8::HandleScope scope(isolate);
ctx1p.Reset(isolate, v8::Context::New(isolate));
ctx2p.Reset(isolate, v8::Context::New(isolate));
v8::Local<v8::Context>::New(isolate, ctx1p)->Enter();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(2, NumberOfGlobalObjects());
{
v8::HandleScope inner_scope(isolate);
CompileRun("var v = function() { return 42; }");
v8::Local<v8::Context> ctx1 = v8::Local<v8::Context>::New(isolate, ctx1p);
v8::Local<v8::Context> ctx2 = v8::Local<v8::Context>::New(isolate, ctx2p);
v8::Local<v8::Value> v =
ctx1->Global()->Get(ctx1, v8_str("v")).ToLocalChecked();
ctx2->Enter();
CHECK(ctx2->Global()->Set(ctx2, v8_str("o"), v).FromJust());
v8::Local<v8::Value> res = CompileRun(
"function f(x) { return x(); }"
"%PrepareFunctionForOptimization(f);"
"for (var i = 0; i < 10; ++i) f(o);"
"%OptimizeFunctionOnNextCall(f);"
"f(o);");
CHECK_EQ(42, res->Int32Value(ctx2).FromJust());
CHECK(ctx2->Global()
->Set(ctx2, v8_str("o"), v8::Int32::New(isolate, 0))
.FromJust());
ctx2->Exit();
ctx1->Exit();
ctx1p.Reset();
isolate->ContextDisposedNotification();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, NumberOfGlobalObjects());
ctx2p.Reset();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(0, NumberOfGlobalObjects());
}
TEST(LeakNativeContextViaMapKeyed) {
FLAG_allow_natives_syntax = true;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope outer_scope(isolate);
v8::Persistent<v8::Context> ctx1p;
v8::Persistent<v8::Context> ctx2p;
{
v8::HandleScope scope(isolate);
ctx1p.Reset(isolate, v8::Context::New(isolate));
ctx2p.Reset(isolate, v8::Context::New(isolate));
v8::Local<v8::Context>::New(isolate, ctx1p)->Enter();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(2, NumberOfGlobalObjects());
{
v8::HandleScope inner_scope(isolate);
CompileRun("var v = [42, 43]");
v8::Local<v8::Context> ctx1 = v8::Local<v8::Context>::New(isolate, ctx1p);
v8::Local<v8::Context> ctx2 = v8::Local<v8::Context>::New(isolate, ctx2p);
v8::Local<v8::Value> v =
ctx1->Global()->Get(ctx1, v8_str("v")).ToLocalChecked();
ctx2->Enter();
CHECK(ctx2->Global()->Set(ctx2, v8_str("o"), v).FromJust());
v8::Local<v8::Value> res = CompileRun(
"function f() { return o[0]; }"
"%PrepareFunctionForOptimization(f);"
"for (var i = 0; i < 10; ++i) f();"
"%OptimizeFunctionOnNextCall(f);"
"f();");
CHECK_EQ(42, res->Int32Value(ctx2).FromJust());
CHECK(ctx2->Global()
->Set(ctx2, v8_str("o"), v8::Int32::New(isolate, 0))
.FromJust());
ctx2->Exit();
ctx1->Exit();
ctx1p.Reset();
isolate->ContextDisposedNotification();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, NumberOfGlobalObjects());
ctx2p.Reset();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(0, NumberOfGlobalObjects());
}
TEST(LeakNativeContextViaMapProto) {
FLAG_allow_natives_syntax = true;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope outer_scope(isolate);
v8::Persistent<v8::Context> ctx1p;
v8::Persistent<v8::Context> ctx2p;
{
v8::HandleScope scope(isolate);
ctx1p.Reset(isolate, v8::Context::New(isolate));
ctx2p.Reset(isolate, v8::Context::New(isolate));
v8::Local<v8::Context>::New(isolate, ctx1p)->Enter();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(2, NumberOfGlobalObjects());
{
v8::HandleScope inner_scope(isolate);
CompileRun("var v = { y: 42}");
v8::Local<v8::Context> ctx1 = v8::Local<v8::Context>::New(isolate, ctx1p);
v8::Local<v8::Context> ctx2 = v8::Local<v8::Context>::New(isolate, ctx2p);
v8::Local<v8::Value> v =
ctx1->Global()->Get(ctx1, v8_str("v")).ToLocalChecked();
ctx2->Enter();
CHECK(ctx2->Global()->Set(ctx2, v8_str("o"), v).FromJust());
v8::Local<v8::Value> res = CompileRun(
"function f() {"
" var p = {x: 42};"
" p.__proto__ = o;"
" return p.x;"
"}"
"%PrepareFunctionForOptimization(f);"
"for (var i = 0; i < 10; ++i) f();"
"%OptimizeFunctionOnNextCall(f);"
"f();");
CHECK_EQ(42, res->Int32Value(ctx2).FromJust());
CHECK(ctx2->Global()
->Set(ctx2, v8_str("o"), v8::Int32::New(isolate, 0))
.FromJust());
ctx2->Exit();
ctx1->Exit();
ctx1p.Reset();
isolate->ContextDisposedNotification();
}
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(1, NumberOfGlobalObjects());
ctx2p.Reset();
CcTest::CollectAllAvailableGarbage();
CHECK_EQ(0, NumberOfGlobalObjects());
}
TEST(InstanceOfStubWriteBarrier) {
if (!FLAG_incremental_marking) return;
ManualGCScope manual_gc_scope;
FLAG_allow_natives_syntax = true;
#ifdef VERIFY_HEAP
FLAG_verify_heap = true;
#endif
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer()) return;
if (FLAG_force_marking_deque_overflows) return;
v8::HandleScope outer_scope(CcTest::isolate());
v8::Local<v8::Context> ctx = CcTest::isolate()->GetCurrentContext();
{
v8::HandleScope scope(CcTest::isolate());
CompileRun(
"function foo () { }"
"function mkbar () { return new (new Function(\"\")) (); }"
"function f (x) { return (x instanceof foo); }"
"function g () { f(mkbar()); }"
"%PrepareFunctionForOptimization(f);"
"f(new foo()); f(new foo());"
"%OptimizeFunctionOnNextCall(f);"
"f(new foo()); g();");
}
IncrementalMarking* marking = CcTest::heap()->incremental_marking();
marking->Stop();
CcTest::heap()->StartIncrementalMarking(i::Heap::kNoGCFlags,
i::GarbageCollectionReason::kTesting);
i::Handle<JSFunction> f = i::Handle<JSFunction>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
CcTest::global()->Get(ctx, v8_str("f")).ToLocalChecked())));
CHECK(f->HasAttachedOptimizedCode());
IncrementalMarking::MarkingState* marking_state = marking->marking_state();
const double kStepSizeInMs = 100;
while (!marking_state->IsBlack(f->code()) && !marking->IsStopped()) {
// Discard any pending GC requests otherwise we will get GC when we enter
// code below.
marking->Step(kStepSizeInMs, IncrementalMarking::NO_GC_VIA_STACK_GUARD,
StepOrigin::kV8);
}
CHECK(marking->IsMarking());
{
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Object> global = CcTest::global();
v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
global->Get(ctx, v8_str("g")).ToLocalChecked());
g->Call(ctx, global, 0, nullptr).ToLocalChecked();
}
CcTest::CollectGarbage(OLD_SPACE);
}
HEAP_TEST(GCFlags) {
if (!FLAG_incremental_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
heap->set_current_gc_flags(Heap::kNoGCFlags);
CHECK_EQ(Heap::kNoGCFlags, heap->current_gc_flags_);
// Check whether we appropriately reset flags after GC.
CcTest::heap()->CollectAllGarbage(Heap::kReduceMemoryFootprintMask,
GarbageCollectionReason::kTesting);
CHECK_EQ(Heap::kNoGCFlags, heap->current_gc_flags_);
MarkCompactCollector* collector = heap->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
IncrementalMarking* marking = heap->incremental_marking();
marking->Stop();
heap->StartIncrementalMarking(Heap::kReduceMemoryFootprintMask,
i::GarbageCollectionReason::kTesting);
CHECK_NE(0, heap->current_gc_flags_ & Heap::kReduceMemoryFootprintMask);
CcTest::CollectGarbage(NEW_SPACE);
// NewSpace scavenges should not overwrite the flags.
CHECK_NE(0, heap->current_gc_flags_ & Heap::kReduceMemoryFootprintMask);
CcTest::CollectAllGarbage();
CHECK_EQ(Heap::kNoGCFlags, heap->current_gc_flags_);
}
HEAP_TEST(Regress845060) {
if (FLAG_single_generation) return;
// Regression test for crbug.com/845060, where a raw pointer to a string's
// data was kept across an allocation. If the allocation causes GC and
// moves the string, such raw pointers become invalid.
FLAG_allow_natives_syntax = true;
FLAG_stress_incremental_marking = false;
FLAG_stress_compaction = false;
CcTest::InitializeVM();
LocalContext context;
v8::HandleScope scope(CcTest::isolate());
Heap* heap = CcTest::heap();
// Preparation: create a string in new space.
Local<Value> str = CompileRun("var str = (new Array(10000)).join('x'); str");
CHECK(Heap::InYoungGeneration(*v8::Utils::OpenHandle(*str)));
// Idle incremental marking sets the "kReduceMemoryFootprint" flag, which
// causes from_space to be unmapped after scavenging.
heap->StartIdleIncrementalMarking(GarbageCollectionReason::kTesting);
CHECK(heap->ShouldReduceMemory());
// Run the test (which allocates results) until the original string was
// promoted to old space. Unmapping of from_space causes accesses to any
// stale raw pointers to crash.
CompileRun("while (%InYoungGeneration(str)) { str.split(''); }");
CHECK(!Heap::InYoungGeneration(*v8::Utils::OpenHandle(*str)));
}
TEST(IdleNotificationFinishMarking) {
if (!FLAG_incremental_marking) return;
ManualGCScope manual_gc_scope;
FLAG_allow_natives_syntax = true;
CcTest::InitializeVM();
const int initial_gc_count = CcTest::heap()->gc_count();
heap::SimulateFullSpace(CcTest::heap()->old_space());
IncrementalMarking* marking = CcTest::heap()->incremental_marking();
marking->Stop();
CcTest::heap()->StartIncrementalMarking(i::Heap::kNoGCFlags,
i::GarbageCollectionReason::kTesting);
CHECK_EQ(CcTest::heap()->gc_count(), initial_gc_count);
const double kStepSizeInMs = 100;
do {
marking->Step(kStepSizeInMs, IncrementalMarking::NO_GC_VIA_STACK_GUARD,
StepOrigin::kV8);
} while (!CcTest::heap()
->mark_compact_collector()
->local_marking_worklists()
->IsEmpty());
marking->SetWeakClosureWasOverApproximatedForTesting(true);
// The next idle notification has to finish incremental marking.
const double kLongIdleTime = 1000.0;
CcTest::isolate()->IdleNotificationDeadline(
(v8::base::TimeTicks::HighResolutionNow().ToInternalValue() /
static_cast<double>(v8::base::Time::kMicrosecondsPerSecond)) +
kLongIdleTime);
CHECK_EQ(CcTest::heap()->gc_count(), initial_gc_count + 1);
}
// Test that HAllocateObject will always return an object in new-space.
TEST(OptimizedAllocationAlwaysInNewSpace) {
if (FLAG_single_generation) return;
FLAG_allow_natives_syntax = true;
FLAG_stress_concurrent_allocation = false; // For SimulateFullSpace.
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> ctx = CcTest::isolate()->GetCurrentContext();
heap::SimulateFullSpace(CcTest::heap()->new_space());
AlwaysAllocateScopeForTesting always_allocate(CcTest::heap());
v8::Local<v8::Value> res = CompileRun(
"function c(x) {"
" this.x = x;"
" for (var i = 0; i < 32; i++) {"
" this['x' + i] = x;"
" }"
"}"
"function f(x) { return new c(x); };"
"%PrepareFunctionForOptimization(f);"
"f(1); f(2); f(3);"
"%OptimizeFunctionOnNextCall(f);"
"f(4);");
CHECK_EQ(4, res.As<v8::Object>()
->GetRealNamedProperty(ctx, v8_str("x"))
.ToLocalChecked()
->Int32Value(ctx)
.FromJust());
i::Handle<JSReceiver> o =
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res));
CHECK(Heap::InYoungGeneration(*o));
}
TEST(OptimizedPretenuringAllocationFolding) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> ctx = CcTest::isolate()->GetCurrentContext();
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array();"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = [[{}], [1.1]];"
" }"
" return elements[number_elements-1]"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
v8::Local<v8::Value> int_array =
v8::Object::Cast(*res)->Get(ctx, v8_str("0")).ToLocalChecked();
i::Handle<JSObject> int_array_handle = i::Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(int_array)));
v8::Local<v8::Value> double_array =
v8::Object::Cast(*res)->Get(ctx, v8_str("1")).ToLocalChecked();
i::Handle<JSObject> double_array_handle = i::Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(double_array)));
i::Handle<JSReceiver> o =
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res));
CHECK(CcTest::heap()->InOldSpace(*o));
CHECK(CcTest::heap()->InOldSpace(*int_array_handle));
CHECK(CcTest::heap()->InOldSpace(int_array_handle->elements()));
CHECK(CcTest::heap()->InOldSpace(*double_array_handle));
CHECK(CcTest::heap()->InOldSpace(double_array_handle->elements()));
}
TEST(OptimizedPretenuringObjectArrayLiterals) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking) {
return;
}
v8::HandleScope scope(CcTest::isolate());
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array(number_elements);"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = [{}, {}, {}];"
" }"
" return elements[number_elements - 1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
i::Handle<JSObject> o = Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
CHECK(CcTest::heap()->InOldSpace(o->elements()));
CHECK(CcTest::heap()->InOldSpace(*o));
}
TEST(OptimizedPretenuringNestedInObjectProperties) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking || FLAG_single_generation) {
return;
}
v8::HandleScope scope(CcTest::isolate());
GrowNewSpaceToMaximumCapacity(CcTest::heap());
// Keep the nested literal alive while its root is freed
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"let number_elements = %d;"
"let elements = new Array(number_elements);"
"function f() {"
" for (let i = 0; i < number_elements; i++) {"
" let l = {a: {c: 2.2, d: {e: 3.3}}, b: 1.1}; "
" elements[i] = l.a;"
" }"
" return elements[number_elements-1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
i::Handle<JSObject> o = Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
// Nested literal sites are only pretenured if the top level
// literal is pretenured
CHECK(Heap::InYoungGeneration(*o));
}
TEST(OptimizedPretenuringMixedInObjectProperties) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array(number_elements);"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = {a: {c: 2.2, d: {}}, b: 1.1};"
" }"
" return elements[number_elements - 1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
i::Handle<JSObject> o = Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
CHECK(CcTest::heap()->InOldSpace(*o));
FieldIndex idx1 = FieldIndex::ForPropertyIndex(o->map(), 0);
FieldIndex idx2 = FieldIndex::ForPropertyIndex(o->map(), 1);
CHECK(CcTest::heap()->InOldSpace(o->RawFastPropertyAt(idx1)));
if (!o->IsUnboxedDoubleField(idx2)) {
CHECK(CcTest::heap()->InOldSpace(o->RawFastPropertyAt(idx2)));
} else {
CHECK_EQ(1.1, o->RawFastDoublePropertyAt(idx2));
}
JSObject inner_object = JSObject::cast(o->RawFastPropertyAt(idx1));
CHECK(CcTest::heap()->InOldSpace(inner_object));
if (!inner_object.IsUnboxedDoubleField(idx1)) {
CHECK(CcTest::heap()->InOldSpace(inner_object.RawFastPropertyAt(idx1)));
} else {
CHECK_EQ(2.2, inner_object.RawFastDoublePropertyAt(idx1));
}
CHECK(CcTest::heap()->InOldSpace(inner_object.RawFastPropertyAt(idx2)));
}
TEST(OptimizedPretenuringDoubleArrayProperties) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array(number_elements);"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = {a: 1.1, b: 2.2};"
" }"
" return elements[i - 1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
i::Handle<JSObject> o = Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
CHECK(CcTest::heap()->InOldSpace(*o));
CHECK_EQ(o->property_array(),
ReadOnlyRoots(CcTest::heap()).empty_property_array());
}
TEST(OptimizedPretenuringDoubleArrayLiterals) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array(number_elements);"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = [1.1, 2.2, 3.3];"
" }"
" return elements[number_elements - 1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"
"%%OptimizeFunctionOnNextCall(f);"
"f();",
kPretenureCreationCount);
v8::Local<v8::Value> res = CompileRun(source.begin());
i::Handle<JSObject> o = Handle<JSObject>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
CHECK(CcTest::heap()->InOldSpace(o->elements()));
CHECK(CcTest::heap()->InOldSpace(*o));
}
TEST(OptimizedPretenuringNestedMixedArrayLiterals) {
FLAG_allow_natives_syntax = true;
FLAG_expose_gc = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer() || FLAG_always_opt) return;
if (FLAG_gc_global || FLAG_stress_compaction ||
FLAG_stress_incremental_marking)
return;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> ctx = CcTest::isolate()->GetCurrentContext();
GrowNewSpaceToMaximumCapacity(CcTest::heap());
i::ScopedVector<char> source(1024);
i::SNPrintF(source,
"var number_elements = %d;"
"var elements = new Array(number_elements);"
"function f() {"
" for (var i = 0; i < number_elements; i++) {"
" elements[i] = [[{}, {}, {}], [1.1, 2.2, 3.3]];"
" }"
" return elements[number_elements - 1];"
"};"
"%%PrepareFunctionForOptimization(f);"
"f(); gc();"
"f(); f();"