heap-inl.h 25.1 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_HEAP_HEAP_INL_H_
#define V8_HEAP_HEAP_INL_H_
7

8 9
#include <cmath>

10
// Clients of this interface shouldn't depend on lots of heap internals.
11 12
// Do not include anything from src/heap other than src/heap/heap.h and its
// write barrier here!
13
#include "src/base/atomic-utils.h"
14
#include "src/base/atomicops.h"
15
#include "src/base/platform/platform.h"
16
#include "src/heap/heap-write-barrier.h"
17
#include "src/heap/heap.h"
18
#include "src/heap/third-party/heap-api.h"
19
#include "src/objects/feedback-vector.h"
20

21
// TODO(gc): There is one more include to remove in order to no longer
22
// leak heap internals to users of this interface!
23 24
#include "src/execution/isolate-data.h"
#include "src/execution/isolate.h"
25
#include "src/heap/code-object-registry.h"
26
#include "src/heap/large-spaces.h"
27
#include "src/heap/memory-allocator.h"
28
#include "src/heap/memory-chunk.h"
29
#include "src/heap/new-spaces-inl.h"
30
#include "src/heap/paged-spaces-inl.h"
31
#include "src/heap/read-only-spaces.h"
32
#include "src/heap/spaces-inl.h"
33
#include "src/objects/allocation-site-inl.h"
34
#include "src/objects/api-callbacks-inl.h"
35
#include "src/objects/cell-inl.h"
36
#include "src/objects/descriptor-array.h"
37
#include "src/objects/feedback-cell-inl.h"
38
#include "src/objects/literal-objects-inl.h"
39
#include "src/objects/objects-inl.h"
40
#include "src/objects/oddball.h"
41
#include "src/objects/property-cell.h"
42
#include "src/objects/scope-info.h"
43
#include "src/objects/script-inl.h"
44
#include "src/objects/slots-inl.h"
45
#include "src/objects/struct-inl.h"
46
#include "src/profiler/heap-profiler.h"
47
#include "src/sanitizer/msan.h"
48
#include "src/strings/string-hasher.h"
49
#include "src/zone/zone-list-inl.h"
50

51 52
namespace v8 {
namespace internal {
53

54 55
AllocationSpace AllocationResult::RetrySpace() {
  DCHECK(IsRetry());
jgruber's avatar
jgruber committed
56
  return static_cast<AllocationSpace>(Smi::ToInt(object_));
57 58
}

59
HeapObject AllocationResult::ToObjectChecked() {
60 61 62 63
  CHECK(!IsRetry());
  return HeapObject::cast(object_);
}

64 65 66 67 68
HeapObject AllocationResult::ToObject() {
  DCHECK(!IsRetry());
  return HeapObject::cast(object_);
}

69 70 71 72 73
Address AllocationResult::ToAddress() {
  DCHECK(!IsRetry());
  return HeapObject::cast(object_).address();
}

74 75 76 77 78 79
Isolate* Heap::isolate() {
  return reinterpret_cast<Isolate*>(
      reinterpret_cast<intptr_t>(this) -
      reinterpret_cast<size_t>(reinterpret_cast<Isolate*>(16)->heap()) + 16);
}

80
int64_t Heap::external_memory() { return external_memory_.total(); }
81

82 83
int64_t Heap::update_external_memory(int64_t delta) {
  return external_memory_.Update(delta);
84 85 86 87
}

RootsTable& Heap::roots_table() { return isolate()->roots_table(); }

88 89 90
#define ROOT_ACCESSOR(Type, name, CamelName)                           \
  Type Heap::name() {                                                  \
    return Type::cast(Object(roots_table()[RootIndex::k##CamelName])); \
91
  }
92
MUTABLE_ROOT_LIST(ROOT_ACCESSOR)
93
#undef ROOT_ACCESSOR
94

95
#define ROOT_ACCESSOR(type, name, CamelName)                                   \
96
  void Heap::set_##name(type value) {                                          \
97 98 99 100 101 102
    /* The deserializer makes use of the fact that these common roots are */   \
    /* never in new space and never on a page that is being compacted.    */   \
    DCHECK_IMPLIES(deserialization_complete(),                                 \
                   !RootsTable::IsImmortalImmovable(RootIndex::k##CamelName)); \
    DCHECK_IMPLIES(RootsTable::IsImmortalImmovable(RootIndex::k##CamelName),   \
                   IsImmovable(HeapObject::cast(value)));                      \
103
    roots_table()[RootIndex::k##CamelName] = value.ptr();                      \
104 105 106 107
  }
ROOT_LIST(ROOT_ACCESSOR)
#undef ROOT_ACCESSOR

108
void Heap::SetRootMaterializedObjects(FixedArray objects) {
109
  roots_table()[RootIndex::kMaterializedObjects] = objects.ptr();
110 111
}

112
void Heap::SetRootScriptList(Object value) {
113
  roots_table()[RootIndex::kScriptList] = value.ptr();
114 115
}

116
void Heap::SetMessageListeners(TemplateList value) {
117
  roots_table()[RootIndex::kMessageListeners] = value.ptr();
118 119
}

120
void Heap::SetPendingOptimizeForTestBytecode(Object hash_table) {
121 122
  DCHECK(hash_table.IsObjectHashTable() || hash_table.IsUndefined(isolate()));
  roots_table()[RootIndex::kPendingOptimizeForTestBytecode] = hash_table.ptr();
123 124
}

mlippautz's avatar
mlippautz committed
125
PagedSpace* Heap::paged_space(int idx) {
126 127
  DCHECK_NE(idx, LO_SPACE);
  DCHECK_NE(idx, NEW_SPACE);
128 129
  DCHECK_NE(idx, CODE_LO_SPACE);
  DCHECK_NE(idx, NEW_LO_SPACE);
130
  return static_cast<PagedSpace*>(space_[idx]);
mlippautz's avatar
mlippautz committed
131 132
}

133
Space* Heap::space(int idx) { return space_[idx]; }
mlippautz's avatar
mlippautz committed
134 135

Address* Heap::NewSpaceAllocationTopAddress() {
136
  return new_space_->allocation_top_address();
mlippautz's avatar
mlippautz committed
137 138 139
}

Address* Heap::NewSpaceAllocationLimitAddress() {
140
  return new_space_->allocation_limit_address();
mlippautz's avatar
mlippautz committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
}

Address* Heap::OldSpaceAllocationTopAddress() {
  return old_space_->allocation_top_address();
}

Address* Heap::OldSpaceAllocationLimitAddress() {
  return old_space_->allocation_limit_address();
}

void Heap::UpdateNewSpaceAllocationCounter() {
  new_space_allocation_counter_ = NewSpaceAllocationCounter();
}

size_t Heap::NewSpaceAllocationCounter() {
  return new_space_allocation_counter_ + new_space()->AllocatedSinceLastGC();
}
158

159 160 161 162 163 164 165 166
inline const base::AddressRegion& Heap::code_range() {
#ifdef V8_ENABLE_THIRD_PARTY_HEAP
  return tp_heap_->GetCodeRange();
#else
  return memory_allocator_->code_range();
#endif
}

167
AllocationResult Heap::AllocateRaw(int size_in_bytes, AllocationType type,
168
                                   AllocationOrigin origin,
169
                                   AllocationAlignment alignment) {
170 171
  DCHECK(AllowHandleAllocation::IsAllowed());
  DCHECK(AllowHeapAllocation::IsAllowed());
172 173
  DCHECK_IMPLIES(type == AllocationType::kCode,
                 alignment == AllocationAlignment::kCodeAligned);
174
  DCHECK_EQ(gc_state(), NOT_IN_GC);
175
#ifdef V8_ENABLE_ALLOCATION_TIMEOUT
176 177
  if (FLAG_random_gc_interval > 0 || FLAG_gc_interval >= 0) {
    if (!always_allocate() && Heap::allocation_timeout_-- <= 0) {
178
      return AllocationResult::Retry();
179
    }
180
  }
181 182
#endif
#ifdef DEBUG
183
  IncrementObjectCounters();
184
#endif
185

186 187
  bool large_object = size_in_bytes > kMaxRegularHeapObjectSize;

188
  HeapObject object;
189
  AllocationResult allocation;
190

191
  if (FLAG_single_generation && type == AllocationType::kYoung) {
192
    type = AllocationType::kOld;
193
  }
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208
  if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) {
    allocation = tp_heap_->Allocate(size_in_bytes, type, alignment);
  } else {
    if (AllocationType::kYoung == type) {
      if (large_object) {
        if (FLAG_young_generation_large_objects) {
          allocation = new_lo_space_->AllocateRaw(size_in_bytes);
        } else {
          // If young generation large objects are disalbed we have to tenure
          // the allocation and violate the given allocation type. This could be
          // dangerous. We may want to remove
          // FLAG_young_generation_large_objects and avoid patching.
          allocation = lo_space_->AllocateRaw(size_in_bytes);
        }
209
      } else {
210 211 212 213
        allocation = new_space_->AllocateRaw(size_in_bytes, alignment, origin);
      }
    } else if (AllocationType::kOld == type) {
      if (large_object) {
214
        allocation = lo_space_->AllocateRaw(size_in_bytes);
215 216
      } else {
        allocation = old_space_->AllocateRaw(size_in_bytes, alignment, origin);
217
      }
218 219 220 221 222 223 224 225 226 227 228 229 230
    } else if (AllocationType::kCode == type) {
      if (size_in_bytes <= code_space()->AreaSize() && !large_object) {
        allocation = code_space_->AllocateRawUnaligned(size_in_bytes);
      } else {
        allocation = code_lo_space_->AllocateRaw(size_in_bytes);
      }
    } else if (AllocationType::kMap == type) {
      allocation = map_space_->AllocateRawUnaligned(size_in_bytes);
    } else if (AllocationType::kReadOnly == type) {
      DCHECK(isolate_->serializer_enabled());
      DCHECK(!large_object);
      DCHECK(CanAllocateInReadOnlySpace());
      DCHECK_EQ(AllocationOrigin::kRuntime, origin);
231
      allocation = read_only_space_->AllocateRaw(size_in_bytes, alignment);
232
    } else {
233
      UNREACHABLE();
234
    }
235
  }
236

237
  if (allocation.To(&object)) {
238
    if (AllocationType::kCode == type && !V8_ENABLE_THIRD_PARTY_HEAP_BOOL) {
239 240 241
      // Unprotect the memory chunk of the object if it was not unprotected
      // already.
      UnprotectAndRegisterMemoryChunk(object);
242
      ZapCodeObject(object.address(), size_in_bytes);
243
      if (!large_object) {
244 245
        MemoryChunk::FromHeapObject(object)
            ->GetCodeObjectRegistry()
246
            ->RegisterNewlyAllocatedCodeObject(object.address());
247
      }
248
    }
249
    OnAllocationEvent(object, size_in_bytes);
250
  }
251

252
  return allocation;
253 254
}

255 256 257 258
template <Heap::AllocationRetryMode mode>
HeapObject Heap::AllocateRawWith(int size, AllocationType allocation,
                                 AllocationOrigin origin,
                                 AllocationAlignment alignment) {
259 260
  DCHECK(AllowHandleAllocation::IsAllowed());
  DCHECK(AllowHeapAllocation::IsAllowed());
261 262 263 264 265
  if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) {
    AllocationResult result = AllocateRaw(size, allocation, origin, alignment);
    DCHECK(!result.IsRetry());
    return result.ToObjectChecked();
  }
266
  DCHECK_EQ(gc_state(), NOT_IN_GC);
267 268 269 270 271
  Heap* heap = isolate()->heap();
  Address* top = heap->NewSpaceAllocationTopAddress();
  Address* limit = heap->NewSpaceAllocationLimitAddress();
  if (allocation == AllocationType::kYoung &&
      alignment == AllocationAlignment::kWordAligned &&
272
      size <= kMaxRegularHeapObjectSize &&
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
      (*limit - *top >= static_cast<unsigned>(size)) &&
      V8_LIKELY(!FLAG_single_generation && FLAG_inline_new &&
                FLAG_gc_interval == 0)) {
    DCHECK(IsAligned(size, kTaggedSize));
    HeapObject obj = HeapObject::FromAddress(*top);
    *top += size;
    heap->CreateFillerObjectAt(obj.address(), size, ClearRecordedSlots::kNo);
    MSAN_ALLOCATED_UNINITIALIZED_MEMORY(obj.address(), size);
    return obj;
  }
  switch (mode) {
    case kLightRetry:
      return AllocateRawWithLightRetrySlowPath(size, allocation, origin,
                                               alignment);
    case kRetryOrFail:
      return AllocateRawWithRetryOrFailSlowPath(size, allocation, origin,
                                                alignment);
  }
  UNREACHABLE();
}

294 295 296
Address Heap::DeserializerAllocate(AllocationType type, int size_in_bytes) {
  if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) {
    AllocationResult allocation = tp_heap_->Allocate(
297 298
        size_in_bytes, type, AllocationAlignment::kDoubleAligned);
    return allocation.ToObjectChecked().ptr();
299 300 301 302 303
  } else {
    UNIMPLEMENTED();  // unimplemented
  }
}

304
void Heap::OnAllocationEvent(HeapObject object, int size_in_bytes) {
305
  for (auto& tracker : allocation_trackers_) {
306
    tracker->AllocationEvent(object.address(), size_in_bytes);
307 308
  }

309
  if (FLAG_verify_predictable) {
310 311 312 313
    ++allocations_count_;
    // Advance synthetic time by making a time request.
    MonotonicallyIncreasingTimeInMs();

314 315 316
    UpdateAllocationsHash(object);
    UpdateAllocationsHash(size_in_bytes);

317
    if (allocations_count_ % FLAG_dump_allocations_digest_at_alloc == 0) {
Clemens Hammacher's avatar
Clemens Hammacher committed
318
      PrintAllocationsHash();
319
    }
320 321 322 323
  } else if (FLAG_fuzzer_gc_analysis) {
    ++allocations_count_;
  } else if (FLAG_trace_allocation_stack_interval > 0) {
    ++allocations_count_;
324 325 326 327
    if (allocations_count_ % FLAG_trace_allocation_stack_interval == 0) {
      isolate()->PrintStack(stdout, Isolate::kPrintStackConcise);
    }
  }
328 329
}

330
bool Heap::CanAllocateInReadOnlySpace() {
331
  return read_only_space()->writable();
332 333
}

334
void Heap::UpdateAllocationsHash(HeapObject object) {
335
  Address object_address = object.address();
336
  MemoryChunk* memory_chunk = MemoryChunk::FromAddress(object_address);
337
  AllocationSpace allocation_space = memory_chunk->owner_identity();
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

  STATIC_ASSERT(kSpaceTagSize + kPageSizeBits <= 32);
  uint32_t value =
      static_cast<uint32_t>(object_address - memory_chunk->address()) |
      (static_cast<uint32_t>(allocation_space) << kPageSizeBits);

  UpdateAllocationsHash(value);
}

void Heap::UpdateAllocationsHash(uint32_t value) {
  uint16_t c1 = static_cast<uint16_t>(value);
  uint16_t c2 = static_cast<uint16_t>(value >> 16);
  raw_allocations_hash_ =
      StringHasher::AddCharacterCore(raw_allocations_hash_, c1);
  raw_allocations_hash_ =
      StringHasher::AddCharacterCore(raw_allocations_hash_, c2);
}

356
void Heap::RegisterExternalString(String string) {
357 358
  DCHECK(string.IsExternalString());
  DCHECK(!string.IsThinString());
359 360 361
  external_string_table_.AddString(string);
}

362
void Heap::FinalizeExternalString(String string) {
363
  DCHECK(string.IsExternalString());
364
  Page* page = Page::FromHeapObject(string);
365
  ExternalString ext_string = ExternalString::cast(string);
366 367 368

  page->DecrementExternalBackingStoreBytes(
      ExternalBackingStoreType::kExternalString,
369
      ext_string.ExternalPayloadSize());
370

371
  ext_string.DisposeResource(isolate());
372 373
}

374 375
Address Heap::NewSpaceTop() { return new_space_->top(); }

376 377
bool Heap::InYoungGeneration(Object object) {
  DCHECK(!HasWeakHeapObjectTag(object));
378
  return object.IsHeapObject() && InYoungGeneration(HeapObject::cast(object));
379 380 381 382 383 384 385 386 387 388
}

// static
bool Heap::InYoungGeneration(MaybeObject object) {
  HeapObject heap_object;
  return object->GetHeapObject(&heap_object) && InYoungGeneration(heap_object);
}

// static
bool Heap::InYoungGeneration(HeapObject heap_object) {
389
  if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) return false;
390 391
  bool result =
      BasicMemoryChunk::FromHeapObject(heap_object)->InYoungGeneration();
392 393 394 395 396 397 398
#ifdef DEBUG
  // If in the young generation, then check we're either not in the middle of
  // GC or the object is in to-space.
  if (result) {
    // If the object is in the young generation, then it's not in RO_SPACE so
    // this is safe.
    Heap* heap = Heap::FromWritableHeapObject(heap_object);
399
    DCHECK_IMPLIES(heap->gc_state() == NOT_IN_GC, InToPage(heap_object));
400 401 402 403 404
  }
#endif
  return result;
}

405
// static
406
bool Heap::InFromPage(Object object) {
407
  DCHECK(!HasWeakHeapObjectTag(object));
408
  return object.IsHeapObject() && InFromPage(HeapObject::cast(object));
409 410
}

411
// static
412
bool Heap::InFromPage(MaybeObject object) {
413
  HeapObject heap_object;
414
  return object->GetHeapObject(&heap_object) && InFromPage(heap_object);
415 416
}

417
// static
418
bool Heap::InFromPage(HeapObject heap_object) {
419
  return BasicMemoryChunk::FromHeapObject(heap_object)->IsFromPage();
420 421
}

422
// static
423
bool Heap::InToPage(Object object) {
424
  DCHECK(!HasWeakHeapObjectTag(object));
425
  return object.IsHeapObject() && InToPage(HeapObject::cast(object));
426 427
}

428
// static
429
bool Heap::InToPage(MaybeObject object) {
430
  HeapObject heap_object;
431
  return object->GetHeapObject(&heap_object) && InToPage(heap_object);
432 433
}

434
// static
435
bool Heap::InToPage(HeapObject heap_object) {
436
  return BasicMemoryChunk::FromHeapObject(heap_object)->IsToPage();
437 438
}

439
bool Heap::InOldSpace(Object object) { return old_space_->Contains(object); }
440

441
// static
442
Heap* Heap::FromWritableHeapObject(HeapObject obj) {
443 444 445
  if (V8_ENABLE_THIRD_PARTY_HEAP_BOOL) {
    return Heap::GetIsolateFromWritableObject(obj)->heap();
  }
446
  BasicMemoryChunk* chunk = BasicMemoryChunk::FromHeapObject(obj);
447 448 449
  // RO_SPACE can be shared between heaps, so we can't use RO_SPACE objects to
  // find a heap. The exception is when the ReadOnlySpace is writeable, during
  // bootstrapping, so explicitly allow this case.
450
  SLOW_DCHECK(chunk->IsWritable());
451 452 453 454 455
  Heap* heap = chunk->heap();
  SLOW_DCHECK(heap != nullptr);
  return heap;
}

456
bool Heap::ShouldBePromoted(Address old_address) {
457 458 459 460
  Page* page = Page::FromAddress(old_address);
  Address age_mark = new_space_->age_mark();
  return page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK) &&
         (!page->ContainsLimit(age_mark) || old_address < age_mark);
461 462
}

463
void Heap::CopyBlock(Address dst, Address src, int byte_size) {
464
  DCHECK(IsAligned(byte_size, kTaggedSize));
465
  CopyTagged(dst, src, static_cast<size_t>(byte_size / kTaggedSize));
466 467
}

468
template <Heap::FindMementoMode mode>
469
AllocationMemento Heap::FindAllocationMemento(Map map, HeapObject object) {
470 471
  Address object_address = object.address();
  Address memento_address = object_address + object.SizeFromMap(map);
472
  Address last_memento_word_address = memento_address + kTaggedSize;
473
  // If the memento would be on another page, bail out immediately.
474
  if (!Page::OnSamePage(object_address, last_memento_word_address)) {
475
    return AllocationMemento();
476
  }
477
  HeapObject candidate = HeapObject::FromAddress(memento_address);
478
  ObjectSlot candidate_map_slot = candidate.map_slot();
479 480 481
  // This fast check may peek at an uninitialized word. However, the slow check
  // below (memento_address == top) ensures that this is safe. Mark the word as
  // initialized to silence MemorySanitizer warnings.
482 483 484
  MSAN_MEMORY_IS_INITIALIZED(candidate_map_slot.address(), kTaggedSize);
  if (!candidate_map_slot.contains_value(
          ReadOnlyRoots(this).allocation_memento_map().ptr())) {
485
    return AllocationMemento();
486
  }
487 488 489 490

  // Bail out if the memento is below the age mark, which can happen when
  // mementos survived because a page got moved within new space.
  Page* object_page = Page::FromAddress(object_address);
491 492 493 494
  if (object_page->IsFlagSet(Page::NEW_SPACE_BELOW_AGE_MARK)) {
    Address age_mark =
        reinterpret_cast<SemiSpace*>(object_page->owner())->age_mark();
    if (!object_page->Contains(age_mark)) {
495
      return AllocationMemento();
496 497 498
    }
    // Do an exact check in the case where the age mark is on the same page.
    if (object_address < age_mark) {
499
      return AllocationMemento();
500
    }
501 502
  }

503
  AllocationMemento memento_candidate = AllocationMemento::cast(candidate);
504 505 506 507 508 509 510 511

  // Depending on what the memento is used for, we might need to perform
  // additional checks.
  Address top;
  switch (mode) {
    case Heap::kForGC:
      return memento_candidate;
    case Heap::kForRuntime:
512
      if (memento_candidate.is_null()) return AllocationMemento();
513 514 515 516 517 518
      // Either the object is the last object in the new space, or there is
      // another object of at least word size (the header map word) following
      // it, so suffices to compare ptr and top here.
      top = NewSpaceTop();
      DCHECK(memento_address == top ||
             memento_address + HeapObject::kHeaderSize <= top ||
519
             !Page::OnSamePage(memento_address, top - 1));
520
      if ((memento_address != top) && memento_candidate.IsValid()) {
521 522
        return memento_candidate;
      }
523
      return AllocationMemento();
524 525 526 527
    default:
      UNREACHABLE();
  }
  UNREACHABLE();
528 529
}

530
void Heap::UpdateAllocationSite(Map map, HeapObject object,
531 532
                                PretenuringFeedbackMap* pretenuring_feedback) {
  DCHECK_NE(pretenuring_feedback, &global_pretenuring_feedback_);
533
#ifdef DEBUG
534
  BasicMemoryChunk* chunk = BasicMemoryChunk::FromHeapObject(object);
535 536 537 538 539
  DCHECK_IMPLIES(chunk->IsToPage(),
                 chunk->IsFlagSet(MemoryChunk::PAGE_NEW_NEW_PROMOTION));
  DCHECK_IMPLIES(!chunk->InYoungGeneration(),
                 chunk->IsFlagSet(MemoryChunk::PAGE_NEW_OLD_PROMOTION));
#endif
540
  if (!FLAG_allocation_site_pretenuring ||
541
      !AllocationSite::CanTrack(map.instance_type())) {
542
    return;
543 544
  }
  AllocationMemento memento_candidate =
545
      FindAllocationMemento<kForGC>(map, object);
546
  if (memento_candidate.is_null()) return;
547

548 549 550
  // Entering cached feedback is used in the parallel case. We are not allowed
  // to dereference the allocation site and rather have to postpone all checks
  // till actually merging the data.
551
  Address key = memento_candidate.GetAllocationSiteUnchecked();
552
  (*pretenuring_feedback)[AllocationSite::unchecked_cast(Object(key))]++;
553
}
554

555
void Heap::ExternalStringTable::AddString(String string) {
556
  DCHECK(string.IsExternalString());
557 558
  DCHECK(!Contains(string));

559
  if (InYoungGeneration(string)) {
560
    young_strings_.push_back(string);
561
  } else {
562
    old_strings_.push_back(string);
563 564 565
  }
}

566
Oddball Heap::ToBoolean(bool condition) {
567 568
  ReadOnlyRoots roots(this);
  return condition ? roots.true_value() : roots.false_value();
569 570
}

571
int Heap::NextScriptId() {
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  FullObjectSlot last_script_id_slot(&roots_table()[RootIndex::kLastScriptId]);
  Smi last_id = Smi::cast(last_script_id_slot.Relaxed_Load());
  Smi new_id, last_id_before_cas;
  do {
    if (last_id.value() == Smi::kMaxValue) {
      STATIC_ASSERT(v8::UnboundScript::kNoScriptId == 0);
      new_id = Smi::FromInt(1);
    } else {
      new_id = Smi::FromInt(last_id.value() + 1);
    }

    // CAS returns the old value on success, and the current value in the slot
    // on failure. Therefore, we want to break if the returned value matches the
    // old value (last_id), and keep looping (with the new last_id value) if it
    // doesn't.
    last_id_before_cas = last_id;
    last_id =
        Smi::cast(last_script_id_slot.Relaxed_CompareAndSwap(last_id, new_id));
  } while (last_id != last_id_before_cas);

  return new_id.value();
593 594
}

595
int Heap::NextDebuggingId() {
596
  int last_id = last_debugging_id().value();
597 598
  if (last_id == DebugInfo::DebuggingIdBits::kMax) {
    last_id = DebugInfo::kNoDebuggingId;
599 600 601 602 603 604
  }
  last_id++;
  set_last_debugging_id(Smi::FromInt(last_id));
  return last_id;
}

605
int Heap::GetNextTemplateSerialNumber() {
606
  int next_serial_number = next_template_serial_number().value() + 1;
607 608 609 610
  set_next_template_serial_number(Smi::FromInt(next_serial_number));
  return next_serial_number;
}

611 612 613 614 615 616 617 618 619 620 621 622
int Heap::MaxNumberToStringCacheSize() const {
  // Compute the size of the number string cache based on the max newspace size.
  // The number string cache has a minimum size based on twice the initial cache
  // size to ensure that it is bigger after being made 'full size'.
  size_t number_string_cache_size = max_semi_space_size_ / 512;
  number_string_cache_size =
      Max(static_cast<size_t>(kInitialNumberStringCacheSize * 2),
          Min<size_t>(0x4000u, number_string_cache_size));
  // There is a string and a number per entry so the length is twice the number
  // of entries.
  return static_cast<int>(number_string_cache_size * 2);
}
623 624 625 626 627 628 629 630 631 632 633 634 635

void Heap::IncrementExternalBackingStoreBytes(ExternalBackingStoreType type,
                                              size_t amount) {
  base::CheckedIncrement(&backing_store_bytes_, amount);
  // TODO(mlippautz): Implement interrupt for global memory allocations that can
  // trigger garbage collections.
}

void Heap::DecrementExternalBackingStoreBytes(ExternalBackingStoreType type,
                                              size_t amount) {
  base::CheckedDecrement(&backing_store_bytes_, amount);
}

636 637
bool Heap::HasDirtyJSFinalizationRegistries() {
  return !dirty_js_finalization_registries_list().IsUndefined(isolate());
638 639
}

640
AlwaysAllocateScope::AlwaysAllocateScope(Heap* heap) : heap_(heap) {
641
  heap_->always_allocate_scope_count_++;
642 643
}

644
AlwaysAllocateScope::~AlwaysAllocateScope() {
645
  heap_->always_allocate_scope_count_--;
646 647
}

648 649 650
AlwaysAllocateScopeForTesting::AlwaysAllocateScopeForTesting(Heap* heap)
    : scope_(heap) {}

651 652
CodeSpaceMemoryModificationScope::CodeSpaceMemoryModificationScope(Heap* heap)
    : heap_(heap) {
653 654 655
  if (heap_->write_protect_code_memory()) {
    heap_->increment_code_space_memory_modification_scope_depth();
    heap_->code_space()->SetReadAndWritable();
656
    LargePage* page = heap_->code_lo_space()->first_page();
657
    while (page != nullptr) {
658 659 660
      DCHECK(page->IsFlagSet(MemoryChunk::IS_EXECUTABLE));
      CHECK(heap_->memory_allocator()->IsMemoryChunkExecutable(page));
      page->SetReadAndWritable();
661
      page = page->next_page();
662
    }
663 664 665 666
  }
}

CodeSpaceMemoryModificationScope::~CodeSpaceMemoryModificationScope() {
667 668
  if (heap_->write_protect_code_memory()) {
    heap_->decrement_code_space_memory_modification_scope_depth();
669
    heap_->code_space()->SetDefaultCodePermissions();
670
    LargePage* page = heap_->code_lo_space()->first_page();
671
    while (page != nullptr) {
672 673
      DCHECK(page->IsFlagSet(MemoryChunk::IS_EXECUTABLE));
      CHECK(heap_->memory_allocator()->IsMemoryChunkExecutable(page));
674
      page->SetDefaultCodePermissions();
675
      page = page->next_page();
676
    }
677 678 679
  }
}

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
CodePageCollectionMemoryModificationScope::
    CodePageCollectionMemoryModificationScope(Heap* heap)
    : heap_(heap) {
  if (heap_->write_protect_code_memory() &&
      !heap_->code_space_memory_modification_scope_depth()) {
    heap_->EnableUnprotectedMemoryChunksRegistry();
  }
}

CodePageCollectionMemoryModificationScope::
    ~CodePageCollectionMemoryModificationScope() {
  if (heap_->write_protect_code_memory() &&
      !heap_->code_space_memory_modification_scope_depth()) {
    heap_->ProtectUnprotectedMemoryChunks();
    heap_->DisableUnprotectedMemoryChunksRegistry();
  }
}

698 699 700 701 702
#ifdef V8_ENABLE_THIRD_PARTY_HEAP
CodePageMemoryModificationScope::CodePageMemoryModificationScope(Code code)
    : chunk_(nullptr), scope_active_(false) {}
#else
CodePageMemoryModificationScope::CodePageMemoryModificationScope(Code code)
703
    : CodePageMemoryModificationScope(BasicMemoryChunk::FromHeapObject(code)) {}
704 705
#endif

706
CodePageMemoryModificationScope::CodePageMemoryModificationScope(
707
    BasicMemoryChunk* chunk)
708
    : chunk_(chunk),
709 710
      scope_active_(chunk_->heap()->write_protect_code_memory() &&
                    chunk_->IsFlagSet(MemoryChunk::IS_EXECUTABLE)) {
711
  if (scope_active_) {
712 713 714
    DCHECK(chunk_->owner()->identity() == CODE_SPACE ||
           (chunk_->owner()->identity() == CODE_LO_SPACE));
    MemoryChunk::cast(chunk_)->SetReadAndWritable();
715 716 717 718
  }
}

CodePageMemoryModificationScope::~CodePageMemoryModificationScope() {
719
  if (scope_active_) {
720
    MemoryChunk::cast(chunk_)->SetDefaultCodePermissions();
721 722 723
  }
}

724 725
}  // namespace internal
}  // namespace v8
726

727
#endif  // V8_HEAP_HEAP_INL_H_