deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / heap / heap-inl.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_HEAP_HEAP_INL_H_
6 #define V8_HEAP_HEAP_INL_H_
7
8 #include <cmath>
9
10 #include "src/base/platform/platform.h"
11 #include "src/heap/heap.h"
12 #include "src/heap/store-buffer.h"
13 #include "src/heap/store-buffer-inl.h"
14 #include "src/heap-profiler.h"
15 #include "src/isolate.h"
16 #include "src/list-inl.h"
17 #include "src/msan.h"
18 #include "src/objects.h"
19
20 namespace v8 {
21 namespace internal {
22
23 void PromotionQueue::insert(HeapObject* target, int size) {
24   if (emergency_stack_ != NULL) {
25     emergency_stack_->Add(Entry(target, size));
26     return;
27   }
28
29   if ((rear_ - 2) < limit_) {
30     RelocateQueueHead();
31     emergency_stack_->Add(Entry(target, size));
32     return;
33   }
34
35   *(--rear_) = reinterpret_cast<intptr_t>(target);
36   *(--rear_) = size;
37 // Assert no overflow into live objects.
38 #ifdef DEBUG
39   SemiSpace::AssertValidRange(target->GetIsolate()->heap()->new_space()->top(),
40                               reinterpret_cast<Address>(rear_));
41 #endif
42 }
43
44
45 template <>
46 bool inline Heap::IsOneByte(Vector<const char> str, int chars) {
47   // TODO(dcarney): incorporate Latin-1 check when Latin-1 is supported?
48   return chars == str.length();
49 }
50
51
52 template <>
53 bool inline Heap::IsOneByte(String* str, int chars) {
54   return str->IsOneByteRepresentation();
55 }
56
57
58 AllocationResult Heap::AllocateInternalizedStringFromUtf8(
59     Vector<const char> str, int chars, uint32_t hash_field) {
60   if (IsOneByte(str, chars)) {
61     return AllocateOneByteInternalizedString(Vector<const uint8_t>::cast(str),
62                                              hash_field);
63   }
64   return AllocateInternalizedStringImpl<false>(str, chars, hash_field);
65 }
66
67
68 template <typename T>
69 AllocationResult Heap::AllocateInternalizedStringImpl(T t, int chars,
70                                                       uint32_t hash_field) {
71   if (IsOneByte(t, chars)) {
72     return AllocateInternalizedStringImpl<true>(t, chars, hash_field);
73   }
74   return AllocateInternalizedStringImpl<false>(t, chars, hash_field);
75 }
76
77
78 AllocationResult Heap::AllocateOneByteInternalizedString(
79     Vector<const uint8_t> str, uint32_t hash_field) {
80   CHECK_GE(String::kMaxLength, str.length());
81   // Compute map and object size.
82   Map* map = one_byte_internalized_string_map();
83   int size = SeqOneByteString::SizeFor(str.length());
84   AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, TENURED);
85
86   // Allocate string.
87   HeapObject* result;
88   {
89     AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE);
90     if (!allocation.To(&result)) return allocation;
91   }
92
93   // String maps are all immortal immovable objects.
94   result->set_map_no_write_barrier(map);
95   // Set length and hash fields of the allocated string.
96   String* answer = String::cast(result);
97   answer->set_length(str.length());
98   answer->set_hash_field(hash_field);
99
100   DCHECK_EQ(size, answer->Size());
101
102   // Fill in the characters.
103   MemCopy(answer->address() + SeqOneByteString::kHeaderSize, str.start(),
104           str.length());
105
106   return answer;
107 }
108
109
110 AllocationResult Heap::AllocateTwoByteInternalizedString(Vector<const uc16> str,
111                                                          uint32_t hash_field) {
112   CHECK_GE(String::kMaxLength, str.length());
113   // Compute map and object size.
114   Map* map = internalized_string_map();
115   int size = SeqTwoByteString::SizeFor(str.length());
116   AllocationSpace space = SelectSpace(size, OLD_DATA_SPACE, TENURED);
117
118   // Allocate string.
119   HeapObject* result;
120   {
121     AllocationResult allocation = AllocateRaw(size, space, OLD_DATA_SPACE);
122     if (!allocation.To(&result)) return allocation;
123   }
124
125   result->set_map(map);
126   // Set length and hash fields of the allocated string.
127   String* answer = String::cast(result);
128   answer->set_length(str.length());
129   answer->set_hash_field(hash_field);
130
131   DCHECK_EQ(size, answer->Size());
132
133   // Fill in the characters.
134   MemCopy(answer->address() + SeqTwoByteString::kHeaderSize, str.start(),
135           str.length() * kUC16Size);
136
137   return answer;
138 }
139
140 AllocationResult Heap::CopyFixedArray(FixedArray* src) {
141   if (src->length() == 0) return src;
142   return CopyFixedArrayWithMap(src, src->map());
143 }
144
145
146 AllocationResult Heap::CopyFixedDoubleArray(FixedDoubleArray* src) {
147   if (src->length() == 0) return src;
148   return CopyFixedDoubleArrayWithMap(src, src->map());
149 }
150
151
152 AllocationResult Heap::CopyConstantPoolArray(ConstantPoolArray* src) {
153   if (src->length() == 0) return src;
154   return CopyConstantPoolArrayWithMap(src, src->map());
155 }
156
157
158 AllocationResult Heap::AllocateRaw(int size_in_bytes, AllocationSpace space,
159                                    AllocationSpace retry_space) {
160   DCHECK(AllowHandleAllocation::IsAllowed());
161   DCHECK(AllowHeapAllocation::IsAllowed());
162   DCHECK(gc_state_ == NOT_IN_GC);
163 #ifdef DEBUG
164   if (FLAG_gc_interval >= 0 && AllowAllocationFailure::IsAllowed(isolate_) &&
165       Heap::allocation_timeout_-- <= 0) {
166     return AllocationResult::Retry(space);
167   }
168   isolate_->counters()->objs_since_last_full()->Increment();
169   isolate_->counters()->objs_since_last_young()->Increment();
170 #endif
171
172   HeapObject* object;
173   AllocationResult allocation;
174   if (NEW_SPACE == space) {
175     allocation = new_space_.AllocateRaw(size_in_bytes);
176     if (always_allocate() && allocation.IsRetry() && retry_space != NEW_SPACE) {
177       space = retry_space;
178     } else {
179       if (allocation.To(&object)) {
180         OnAllocationEvent(object, size_in_bytes);
181       }
182       return allocation;
183     }
184   }
185
186   if (OLD_POINTER_SPACE == space) {
187     allocation = old_pointer_space_->AllocateRaw(size_in_bytes);
188   } else if (OLD_DATA_SPACE == space) {
189     allocation = old_data_space_->AllocateRaw(size_in_bytes);
190   } else if (CODE_SPACE == space) {
191     if (size_in_bytes <= code_space()->AreaSize()) {
192       allocation = code_space_->AllocateRaw(size_in_bytes);
193     } else {
194       // Large code objects are allocated in large object space.
195       allocation = lo_space_->AllocateRaw(size_in_bytes, EXECUTABLE);
196     }
197   } else if (LO_SPACE == space) {
198     allocation = lo_space_->AllocateRaw(size_in_bytes, NOT_EXECUTABLE);
199   } else if (CELL_SPACE == space) {
200     allocation = cell_space_->AllocateRaw(size_in_bytes);
201   } else {
202     DCHECK(MAP_SPACE == space);
203     allocation = map_space_->AllocateRaw(size_in_bytes);
204   }
205   if (allocation.To(&object)) {
206     OnAllocationEvent(object, size_in_bytes);
207   } else {
208     old_gen_exhausted_ = true;
209   }
210   return allocation;
211 }
212
213
214 void Heap::OnAllocationEvent(HeapObject* object, int size_in_bytes) {
215   HeapProfiler* profiler = isolate_->heap_profiler();
216   if (profiler->is_tracking_allocations()) {
217     profiler->AllocationEvent(object->address(), size_in_bytes);
218   }
219
220   if (FLAG_verify_predictable) {
221     ++allocations_count_;
222
223     UpdateAllocationsHash(object);
224     UpdateAllocationsHash(size_in_bytes);
225
226     if ((FLAG_dump_allocations_digest_at_alloc > 0) &&
227         (--dump_allocations_hash_countdown_ == 0)) {
228       dump_allocations_hash_countdown_ = FLAG_dump_allocations_digest_at_alloc;
229       PrintAlloctionsHash();
230     }
231   }
232 }
233
234
235 void Heap::OnMoveEvent(HeapObject* target, HeapObject* source,
236                        int size_in_bytes) {
237   HeapProfiler* heap_profiler = isolate_->heap_profiler();
238   if (heap_profiler->is_tracking_object_moves()) {
239     heap_profiler->ObjectMoveEvent(source->address(), target->address(),
240                                    size_in_bytes);
241   }
242   if (target->IsSharedFunctionInfo()) {
243     LOG_CODE_EVENT(isolate_, SharedFunctionInfoMoveEvent(source->address(),
244                                                          target->address()));
245   }
246
247   if (FLAG_verify_predictable) {
248     ++allocations_count_;
249
250     UpdateAllocationsHash(source);
251     UpdateAllocationsHash(target);
252     UpdateAllocationsHash(size_in_bytes);
253
254     if ((FLAG_dump_allocations_digest_at_alloc > 0) &&
255         (--dump_allocations_hash_countdown_ == 0)) {
256       dump_allocations_hash_countdown_ = FLAG_dump_allocations_digest_at_alloc;
257       PrintAlloctionsHash();
258     }
259   }
260 }
261
262
263 void Heap::UpdateAllocationsHash(HeapObject* object) {
264   Address object_address = object->address();
265   MemoryChunk* memory_chunk = MemoryChunk::FromAddress(object_address);
266   AllocationSpace allocation_space = memory_chunk->owner()->identity();
267
268   STATIC_ASSERT(kSpaceTagSize + kPageSizeBits <= 32);
269   uint32_t value =
270       static_cast<uint32_t>(object_address - memory_chunk->address()) |
271       (static_cast<uint32_t>(allocation_space) << kPageSizeBits);
272
273   UpdateAllocationsHash(value);
274 }
275
276
277 void Heap::UpdateAllocationsHash(uint32_t value) {
278   uint16_t c1 = static_cast<uint16_t>(value);
279   uint16_t c2 = static_cast<uint16_t>(value >> 16);
280   raw_allocations_hash_ =
281       StringHasher::AddCharacterCore(raw_allocations_hash_, c1);
282   raw_allocations_hash_ =
283       StringHasher::AddCharacterCore(raw_allocations_hash_, c2);
284 }
285
286
287 void Heap::PrintAlloctionsHash() {
288   uint32_t hash = StringHasher::GetHashCore(raw_allocations_hash_);
289   PrintF("\n### Allocations = %u, hash = 0x%08x\n", allocations_count_, hash);
290 }
291
292
293 void Heap::FinalizeExternalString(String* string) {
294   DCHECK(string->IsExternalString());
295   v8::String::ExternalStringResourceBase** resource_addr =
296       reinterpret_cast<v8::String::ExternalStringResourceBase**>(
297           reinterpret_cast<byte*>(string) + ExternalString::kResourceOffset -
298           kHeapObjectTag);
299
300   // Dispose of the C++ object if it has not already been disposed.
301   if (*resource_addr != NULL) {
302     (*resource_addr)->Dispose();
303     *resource_addr = NULL;
304   }
305 }
306
307
308 bool Heap::InNewSpace(Object* object) {
309   bool result = new_space_.Contains(object);
310   DCHECK(!result ||                 // Either not in new space
311          gc_state_ != NOT_IN_GC ||  // ... or in the middle of GC
312          InToSpace(object));        // ... or in to-space (where we allocate).
313   return result;
314 }
315
316
317 bool Heap::InNewSpace(Address address) { return new_space_.Contains(address); }
318
319
320 bool Heap::InFromSpace(Object* object) {
321   return new_space_.FromSpaceContains(object);
322 }
323
324
325 bool Heap::InToSpace(Object* object) {
326   return new_space_.ToSpaceContains(object);
327 }
328
329
330 bool Heap::InOldPointerSpace(Address address) {
331   return old_pointer_space_->Contains(address);
332 }
333
334
335 bool Heap::InOldPointerSpace(Object* object) {
336   return InOldPointerSpace(reinterpret_cast<Address>(object));
337 }
338
339
340 bool Heap::InOldDataSpace(Address address) {
341   return old_data_space_->Contains(address);
342 }
343
344
345 bool Heap::InOldDataSpace(Object* object) {
346   return InOldDataSpace(reinterpret_cast<Address>(object));
347 }
348
349
350 bool Heap::OldGenerationAllocationLimitReached() {
351   if (!incremental_marking()->IsStopped()) return false;
352   return OldGenerationSpaceAvailable() < 0;
353 }
354
355
356 bool Heap::ShouldBePromoted(Address old_address, int object_size) {
357   NewSpacePage* page = NewSpacePage::FromAddress(old_address);
358   Address age_mark = new_space_.age_mark();
359   return page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK) &&
360          (!page->ContainsLimit(age_mark) || old_address < age_mark);
361 }
362
363
364 void Heap::RecordWrite(Address address, int offset) {
365   if (!InNewSpace(address)) store_buffer_.Mark(address + offset);
366 }
367
368
369 void Heap::RecordWrites(Address address, int start, int len) {
370   if (!InNewSpace(address)) {
371     for (int i = 0; i < len; i++) {
372       store_buffer_.Mark(address + start + i * kPointerSize);
373     }
374   }
375 }
376
377
378 OldSpace* Heap::TargetSpace(HeapObject* object) {
379   InstanceType type = object->map()->instance_type();
380   AllocationSpace space = TargetSpaceId(type);
381   return (space == OLD_POINTER_SPACE) ? old_pointer_space_ : old_data_space_;
382 }
383
384
385 AllocationSpace Heap::TargetSpaceId(InstanceType type) {
386   // Heap numbers and sequential strings are promoted to old data space, all
387   // other object types are promoted to old pointer space.  We do not use
388   // object->IsHeapNumber() and object->IsSeqString() because we already
389   // know that object has the heap object tag.
390
391   // These objects are never allocated in new space.
392   DCHECK(type != MAP_TYPE);
393   DCHECK(type != CODE_TYPE);
394   DCHECK(type != ODDBALL_TYPE);
395   DCHECK(type != CELL_TYPE);
396
397   if (type <= LAST_NAME_TYPE) {
398     if (type == SYMBOL_TYPE) return OLD_POINTER_SPACE;
399     DCHECK(type < FIRST_NONSTRING_TYPE);
400     // There are four string representations: sequential strings, external
401     // strings, cons strings, and sliced strings.
402     // Only the latter two contain non-map-word pointers to heap objects.
403     return ((type & kIsIndirectStringMask) == kIsIndirectStringTag)
404                ? OLD_POINTER_SPACE
405                : OLD_DATA_SPACE;
406   } else {
407     return (type <= LAST_DATA_TYPE) ? OLD_DATA_SPACE : OLD_POINTER_SPACE;
408   }
409 }
410
411
412 bool Heap::AllowedToBeMigrated(HeapObject* obj, AllocationSpace dst) {
413   // Object migration is governed by the following rules:
414   //
415   // 1) Objects in new-space can be migrated to one of the old spaces
416   //    that matches their target space or they stay in new-space.
417   // 2) Objects in old-space stay in the same space when migrating.
418   // 3) Fillers (two or more words) can migrate due to left-trimming of
419   //    fixed arrays in new-space, old-data-space and old-pointer-space.
420   // 4) Fillers (one word) can never migrate, they are skipped by
421   //    incremental marking explicitly to prevent invalid pattern.
422   // 5) Short external strings can end up in old pointer space when a cons
423   //    string in old pointer space is made external (String::MakeExternal).
424   //
425   // Since this function is used for debugging only, we do not place
426   // asserts here, but check everything explicitly.
427   if (obj->map() == one_pointer_filler_map()) return false;
428   InstanceType type = obj->map()->instance_type();
429   MemoryChunk* chunk = MemoryChunk::FromAddress(obj->address());
430   AllocationSpace src = chunk->owner()->identity();
431   switch (src) {
432     case NEW_SPACE:
433       return dst == src || dst == TargetSpaceId(type);
434     case OLD_POINTER_SPACE:
435       return dst == src && (dst == TargetSpaceId(type) || obj->IsFiller() ||
436                             obj->IsExternalString());
437     case OLD_DATA_SPACE:
438       return dst == src && dst == TargetSpaceId(type);
439     case CODE_SPACE:
440       return dst == src && type == CODE_TYPE;
441     case MAP_SPACE:
442     case CELL_SPACE:
443     case LO_SPACE:
444       return false;
445   }
446   UNREACHABLE();
447   return false;
448 }
449
450
451 void Heap::CopyBlock(Address dst, Address src, int byte_size) {
452   CopyWords(reinterpret_cast<Object**>(dst), reinterpret_cast<Object**>(src),
453             static_cast<size_t>(byte_size / kPointerSize));
454 }
455
456
457 void Heap::MoveBlock(Address dst, Address src, int byte_size) {
458   DCHECK(IsAligned(byte_size, kPointerSize));
459
460   int size_in_words = byte_size / kPointerSize;
461
462   if ((dst < src) || (dst >= (src + byte_size))) {
463     Object** src_slot = reinterpret_cast<Object**>(src);
464     Object** dst_slot = reinterpret_cast<Object**>(dst);
465     Object** end_slot = src_slot + size_in_words;
466
467     while (src_slot != end_slot) {
468       *dst_slot++ = *src_slot++;
469     }
470   } else {
471     MemMove(dst, src, static_cast<size_t>(byte_size));
472   }
473 }
474
475
476 void Heap::ScavengePointer(HeapObject** p) { ScavengeObject(p, *p); }
477
478
479 AllocationMemento* Heap::FindAllocationMemento(HeapObject* object) {
480   // Check if there is potentially a memento behind the object. If
481   // the last word of the memento is on another page we return
482   // immediately.
483   Address object_address = object->address();
484   Address memento_address = object_address + object->Size();
485   Address last_memento_word_address = memento_address + kPointerSize;
486   if (!NewSpacePage::OnSamePage(object_address, last_memento_word_address)) {
487     return NULL;
488   }
489
490   HeapObject* candidate = HeapObject::FromAddress(memento_address);
491   Map* candidate_map = candidate->map();
492   // This fast check may peek at an uninitialized word. However, the slow check
493   // below (memento_address == top) ensures that this is safe. Mark the word as
494   // initialized to silence MemorySanitizer warnings.
495   MSAN_MEMORY_IS_INITIALIZED(&candidate_map, sizeof(candidate_map));
496   if (candidate_map != allocation_memento_map()) return NULL;
497
498   // Either the object is the last object in the new space, or there is another
499   // object of at least word size (the header map word) following it, so
500   // suffices to compare ptr and top here. Note that technically we do not have
501   // to compare with the current top pointer of the from space page during GC,
502   // since we always install filler objects above the top pointer of a from
503   // space page when performing a garbage collection. However, always performing
504   // the test makes it possible to have a single, unified version of
505   // FindAllocationMemento that is used both by the GC and the mutator.
506   Address top = NewSpaceTop();
507   DCHECK(memento_address == top ||
508          memento_address + HeapObject::kHeaderSize <= top ||
509          !NewSpacePage::OnSamePage(memento_address, top));
510   if (memento_address == top) return NULL;
511
512   AllocationMemento* memento = AllocationMemento::cast(candidate);
513   if (!memento->IsValid()) return NULL;
514   return memento;
515 }
516
517
518 void Heap::UpdateAllocationSiteFeedback(HeapObject* object,
519                                         ScratchpadSlotMode mode) {
520   Heap* heap = object->GetHeap();
521   DCHECK(heap->InFromSpace(object));
522
523   if (!FLAG_allocation_site_pretenuring ||
524       !AllocationSite::CanTrack(object->map()->instance_type()))
525     return;
526
527   AllocationMemento* memento = heap->FindAllocationMemento(object);
528   if (memento == NULL) return;
529
530   if (memento->GetAllocationSite()->IncrementMementoFoundCount()) {
531     heap->AddAllocationSiteToScratchpad(memento->GetAllocationSite(), mode);
532   }
533 }
534
535
536 void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
537   DCHECK(object->GetIsolate()->heap()->InFromSpace(object));
538
539   // We use the first word (where the map pointer usually is) of a heap
540   // object to record the forwarding pointer.  A forwarding pointer can
541   // point to an old space, the code space, or the to space of the new
542   // generation.
543   MapWord first_word = object->map_word();
544
545   // If the first word is a forwarding address, the object has already been
546   // copied.
547   if (first_word.IsForwardingAddress()) {
548     HeapObject* dest = first_word.ToForwardingAddress();
549     DCHECK(object->GetIsolate()->heap()->InFromSpace(*p));
550     // TODO(jochen): Remove again after fixing http://crbug.com/452095
551     CHECK((*p)->IsHeapObject() && dest->IsHeapObject());
552     *p = dest;
553     return;
554   }
555
556   UpdateAllocationSiteFeedback(object, IGNORE_SCRATCHPAD_SLOT);
557
558   // AllocationMementos are unrooted and shouldn't survive a scavenge
559   DCHECK(object->map() != object->GetHeap()->allocation_memento_map());
560   // Call the slow part of scavenge object.
561   return ScavengeObjectSlow(p, object);
562 }
563
564
565 bool Heap::CollectGarbage(AllocationSpace space, const char* gc_reason,
566                           const v8::GCCallbackFlags callbackFlags) {
567   const char* collector_reason = NULL;
568   GarbageCollector collector = SelectGarbageCollector(space, &collector_reason);
569   return CollectGarbage(collector, gc_reason, collector_reason, callbackFlags);
570 }
571
572
573 Isolate* Heap::isolate() {
574   return reinterpret_cast<Isolate*>(
575       reinterpret_cast<intptr_t>(this) -
576       reinterpret_cast<size_t>(reinterpret_cast<Isolate*>(16)->heap()) + 16);
577 }
578
579
580 // Calls the FUNCTION_CALL function and retries it up to three times
581 // to guarantee that any allocations performed during the call will
582 // succeed if there's enough memory.
583
584 // Warning: Do not use the identifiers __object__, __maybe_object__ or
585 // __scope__ in a call to this macro.
586
587 #define RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE) \
588   if (__allocation__.To(&__object__)) {                   \
589     DCHECK(__object__ != (ISOLATE)->heap()->exception()); \
590     RETURN_VALUE;                                         \
591   }
592
593 #define CALL_AND_RETRY(ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY)    \
594   do {                                                                        \
595     AllocationResult __allocation__ = FUNCTION_CALL;                          \
596     Object* __object__ = NULL;                                                \
597     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
598     (ISOLATE)->heap()->CollectGarbage(__allocation__.RetrySpace(),            \
599                                       "allocation failure");                  \
600     __allocation__ = FUNCTION_CALL;                                           \
601     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
602     (ISOLATE)->counters()->gc_last_resort_from_handles()->Increment();        \
603     (ISOLATE)->heap()->CollectAllAvailableGarbage("last resort gc");          \
604     {                                                                         \
605       AlwaysAllocateScope __scope__(ISOLATE);                                 \
606       __allocation__ = FUNCTION_CALL;                                         \
607     }                                                                         \
608     RETURN_OBJECT_UNLESS_RETRY(ISOLATE, RETURN_VALUE)                         \
609     /* TODO(1181417): Fix this. */                                            \
610     v8::internal::Heap::FatalProcessOutOfMemory("CALL_AND_RETRY_LAST", true); \
611     RETURN_EMPTY;                                                             \
612   } while (false)
613
614 #define CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL, RETURN_VALUE, \
615                               RETURN_EMPTY)                         \
616   CALL_AND_RETRY(ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY)
617
618 #define CALL_HEAP_FUNCTION(ISOLATE, FUNCTION_CALL, TYPE)                      \
619   CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL,                               \
620                         return Handle<TYPE>(TYPE::cast(__object__), ISOLATE), \
621                         return Handle<TYPE>())
622
623
624 #define CALL_HEAP_FUNCTION_VOID(ISOLATE, FUNCTION_CALL) \
625   CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL, return, return)
626
627
628 void ExternalStringTable::AddString(String* string) {
629   DCHECK(string->IsExternalString());
630   if (heap_->InNewSpace(string)) {
631     new_space_strings_.Add(string);
632   } else {
633     old_space_strings_.Add(string);
634   }
635 }
636
637
638 void ExternalStringTable::Iterate(ObjectVisitor* v) {
639   if (!new_space_strings_.is_empty()) {
640     Object** start = &new_space_strings_[0];
641     v->VisitPointers(start, start + new_space_strings_.length());
642   }
643   if (!old_space_strings_.is_empty()) {
644     Object** start = &old_space_strings_[0];
645     v->VisitPointers(start, start + old_space_strings_.length());
646   }
647 }
648
649
650 // Verify() is inline to avoid ifdef-s around its calls in release
651 // mode.
652 void ExternalStringTable::Verify() {
653 #ifdef DEBUG
654   for (int i = 0; i < new_space_strings_.length(); ++i) {
655     Object* obj = Object::cast(new_space_strings_[i]);
656     DCHECK(heap_->InNewSpace(obj));
657     DCHECK(obj != heap_->the_hole_value());
658   }
659   for (int i = 0; i < old_space_strings_.length(); ++i) {
660     Object* obj = Object::cast(old_space_strings_[i]);
661     DCHECK(!heap_->InNewSpace(obj));
662     DCHECK(obj != heap_->the_hole_value());
663   }
664 #endif
665 }
666
667
668 void ExternalStringTable::AddOldString(String* string) {
669   DCHECK(string->IsExternalString());
670   DCHECK(!heap_->InNewSpace(string));
671   old_space_strings_.Add(string);
672 }
673
674
675 void ExternalStringTable::ShrinkNewStrings(int position) {
676   new_space_strings_.Rewind(position);
677 #ifdef VERIFY_HEAP
678   if (FLAG_verify_heap) {
679     Verify();
680   }
681 #endif
682 }
683
684
685 void Heap::ClearInstanceofCache() {
686   set_instanceof_cache_function(Smi::FromInt(0));
687 }
688
689
690 Object* Heap::ToBoolean(bool condition) {
691   return condition ? true_value() : false_value();
692 }
693
694
695 void Heap::CompletelyClearInstanceofCache() {
696   set_instanceof_cache_map(Smi::FromInt(0));
697   set_instanceof_cache_function(Smi::FromInt(0));
698 }
699
700
701 AlwaysAllocateScope::AlwaysAllocateScope(Isolate* isolate)
702     : heap_(isolate->heap()), daf_(isolate) {
703   heap_->always_allocate_scope_depth_++;
704 }
705
706
707 AlwaysAllocateScope::~AlwaysAllocateScope() {
708   heap_->always_allocate_scope_depth_--;
709 }
710
711
712 GCCallbacksScope::GCCallbacksScope(Heap* heap) : heap_(heap) {
713   heap_->gc_callbacks_depth_++;
714 }
715
716
717 GCCallbacksScope::~GCCallbacksScope() { heap_->gc_callbacks_depth_--; }
718
719
720 bool GCCallbacksScope::CheckReenter() {
721   return heap_->gc_callbacks_depth_ == 1;
722 }
723
724
725 void VerifyPointersVisitor::VisitPointers(Object** start, Object** end) {
726   for (Object** current = start; current < end; current++) {
727     if ((*current)->IsHeapObject()) {
728       HeapObject* object = HeapObject::cast(*current);
729       CHECK(object->GetIsolate()->heap()->Contains(object));
730       CHECK(object->map()->IsMap());
731     }
732   }
733 }
734
735
736 void VerifySmisVisitor::VisitPointers(Object** start, Object** end) {
737   for (Object** current = start; current < end; current++) {
738     CHECK((*current)->IsSmi());
739   }
740 }
741 }
742 }  // namespace v8::internal
743
744 #endif  // V8_HEAP_HEAP_INL_H_