1// Copyright 2012 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_HEAP_INL_H_
29#define V8_HEAP_INL_H_
30
31#include "heap.h"
32#include "isolate.h"
33#include "list-inl.h"
34#include "objects.h"
35#include "platform.h"
36#include "v8-counters.h"
37#include "store-buffer.h"
38#include "store-buffer-inl.h"
39
40namespace v8 {
41namespace internal {
42
43void PromotionQueue::insert(HeapObject* target, int size) {
44  if (emergency_stack_ != NULL) {
45    emergency_stack_->Add(Entry(target, size));
46    return;
47  }
48
49  if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(rear_))) {
50    NewSpacePage* rear_page =
51        NewSpacePage::FromAddress(reinterpret_cast<Address>(rear_));
52    ASSERT(!rear_page->prev_page()->is_anchor());
53    rear_ = reinterpret_cast<intptr_t*>(rear_page->prev_page()->area_end());
54    ActivateGuardIfOnTheSamePage();
55  }
56
57  if (guard_) {
58    ASSERT(GetHeadPage() ==
59           Page::FromAllocationTop(reinterpret_cast<Address>(limit_)));
60
61    if ((rear_ - 2) < limit_) {
62      RelocateQueueHead();
63      emergency_stack_->Add(Entry(target, size));
64      return;
65    }
66  }
67
68  *(--rear_) = reinterpret_cast<intptr_t>(target);
69  *(--rear_) = size;
70  // Assert no overflow into live objects.
71#ifdef DEBUG
72  SemiSpace::AssertValidRange(HEAP->new_space()->top(),
73                              reinterpret_cast<Address>(rear_));
74#endif
75}
76
77
78void PromotionQueue::ActivateGuardIfOnTheSamePage() {
79  guard_ = guard_ ||
80      heap_->new_space()->active_space()->current_page()->address() ==
81      GetHeadPage()->address();
82}
83
84
85MaybeObject* Heap::AllocateStringFromUtf8(Vector<const char> str,
86                                          PretenureFlag pretenure) {
87  // Check for ASCII first since this is the common case.
88  const char* start = str.start();
89  int length = str.length();
90  int non_ascii_start = String::NonAsciiStart(start, length);
91  if (non_ascii_start >= length) {
92    // If the string is ASCII, we do not need to convert the characters
93    // since UTF8 is backwards compatible with ASCII.
94    return AllocateStringFromOneByte(str, pretenure);
95  }
96  // Non-ASCII and we need to decode.
97  return AllocateStringFromUtf8Slow(str, non_ascii_start, pretenure);
98}
99
100
101template<>
102bool inline Heap::IsOneByte(Vector<const char> str, int chars) {
103  // TODO(dcarney): incorporate Latin-1 check when Latin-1 is supported?
104  // ASCII only check.
105  return chars == str.length();
106}
107
108
109template<>
110bool inline Heap::IsOneByte(String* str, int chars) {
111  return str->IsOneByteRepresentation();
112}
113
114
115MaybeObject* Heap::AllocateInternalizedStringFromUtf8(
116    Vector<const char> str, int chars, uint32_t hash_field) {
117  if (IsOneByte(str, chars)) {
118    return AllocateOneByteInternalizedString(
119        Vector<const uint8_t>::cast(str), hash_field);
120  }
121  return AllocateInternalizedStringImpl<false>(str, chars, hash_field);
122}
123
124
125template<typename T>
126MaybeObject* Heap::AllocateInternalizedStringImpl(
127    T t, int chars, uint32_t hash_field) {
128  if (IsOneByte(t, chars)) {
129    return AllocateInternalizedStringImpl<true>(t, chars, hash_field);
130  }
131  return AllocateInternalizedStringImpl<false>(t, chars, hash_field);
132}
133
134
135MaybeObject* Heap::AllocateOneByteInternalizedString(Vector<const uint8_t> str,
136                                                     uint32_t hash_field) {
137  if (str.length() > SeqOneByteString::kMaxLength) {
138    return Failure::OutOfMemoryException(0x2);
139  }
140  // Compute map and object size.
141  Map* map = ascii_internalized_string_map();
142  int size = SeqOneByteString::SizeFor(str.length());
143
144  // Allocate string.
145  Object* result;
146  { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
147                   ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
148                   : old_data_space_->AllocateRaw(size);
149    if (!maybe_result->ToObject(&result)) return maybe_result;
150  }
151
152  // String maps are all immortal immovable objects.
153  reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
154  // Set length and hash fields of the allocated string.
155  String* answer = String::cast(result);
156  answer->set_length(str.length());
157  answer->set_hash_field(hash_field);
158
159  ASSERT_EQ(size, answer->Size());
160
161  // Fill in the characters.
162  OS::MemCopy(answer->address() + SeqOneByteString::kHeaderSize,
163              str.start(), str.length());
164
165  return answer;
166}
167
168
169MaybeObject* Heap::AllocateTwoByteInternalizedString(Vector<const uc16> str,
170                                                     uint32_t hash_field) {
171  if (str.length() > SeqTwoByteString::kMaxLength) {
172    return Failure::OutOfMemoryException(0x3);
173  }
174  // Compute map and object size.
175  Map* map = internalized_string_map();
176  int size = SeqTwoByteString::SizeFor(str.length());
177
178  // Allocate string.
179  Object* result;
180  { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
181                   ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
182                   : old_data_space_->AllocateRaw(size);
183    if (!maybe_result->ToObject(&result)) return maybe_result;
184  }
185
186  reinterpret_cast<HeapObject*>(result)->set_map(map);
187  // Set length and hash fields of the allocated string.
188  String* answer = String::cast(result);
189  answer->set_length(str.length());
190  answer->set_hash_field(hash_field);
191
192  ASSERT_EQ(size, answer->Size());
193
194  // Fill in the characters.
195  OS::MemCopy(answer->address() + SeqTwoByteString::kHeaderSize,
196              str.start(), str.length() * kUC16Size);
197
198  return answer;
199}
200
201MaybeObject* Heap::CopyFixedArray(FixedArray* src) {
202  return CopyFixedArrayWithMap(src, src->map());
203}
204
205
206MaybeObject* Heap::CopyFixedDoubleArray(FixedDoubleArray* src) {
207  return CopyFixedDoubleArrayWithMap(src, src->map());
208}
209
210
211MaybeObject* Heap::AllocateRaw(int size_in_bytes,
212                               AllocationSpace space,
213                               AllocationSpace retry_space) {
214  ASSERT(AllowHandleAllocation::IsAllowed() && gc_state_ == NOT_IN_GC);
215  ASSERT(space != NEW_SPACE ||
216         retry_space == OLD_POINTER_SPACE ||
217         retry_space == OLD_DATA_SPACE ||
218         retry_space == LO_SPACE);
219#ifdef DEBUG
220  if (FLAG_gc_interval >= 0 &&
221      !disallow_allocation_failure_ &&
222      Heap::allocation_timeout_-- <= 0) {
223    return Failure::RetryAfterGC(space);
224  }
225  isolate_->counters()->objs_since_last_full()->Increment();
226  isolate_->counters()->objs_since_last_young()->Increment();
227#endif
228  MaybeObject* result;
229  if (NEW_SPACE == space) {
230    result = new_space_.AllocateRaw(size_in_bytes);
231    if (always_allocate() && result->IsFailure()) {
232      space = retry_space;
233    } else {
234      return result;
235    }
236  }
237
238  if (OLD_POINTER_SPACE == space) {
239    result = old_pointer_space_->AllocateRaw(size_in_bytes);
240  } else if (OLD_DATA_SPACE == space) {
241    result = old_data_space_->AllocateRaw(size_in_bytes);
242  } else if (CODE_SPACE == space) {
243    result = code_space_->AllocateRaw(size_in_bytes);
244  } else if (LO_SPACE == space) {
245    result = lo_space_->AllocateRaw(size_in_bytes, NOT_EXECUTABLE);
246  } else if (CELL_SPACE == space) {
247    result = cell_space_->AllocateRaw(size_in_bytes);
248  } else if (PROPERTY_CELL_SPACE == space) {
249    result = property_cell_space_->AllocateRaw(size_in_bytes);
250  } else {
251    ASSERT(MAP_SPACE == space);
252    result = map_space_->AllocateRaw(size_in_bytes);
253  }
254  if (result->IsFailure()) old_gen_exhausted_ = true;
255  return result;
256}
257
258
259MaybeObject* Heap::NumberFromInt32(
260    int32_t value, PretenureFlag pretenure) {
261  if (Smi::IsValid(value)) return Smi::FromInt(value);
262  // Bypass NumberFromDouble to avoid various redundant checks.
263  return AllocateHeapNumber(FastI2D(value), pretenure);
264}
265
266
267MaybeObject* Heap::NumberFromUint32(
268    uint32_t value, PretenureFlag pretenure) {
269  if (static_cast<int32_t>(value) >= 0 &&
270      Smi::IsValid(static_cast<int32_t>(value))) {
271    return Smi::FromInt(static_cast<int32_t>(value));
272  }
273  // Bypass NumberFromDouble to avoid various redundant checks.
274  return AllocateHeapNumber(FastUI2D(value), pretenure);
275}
276
277
278void Heap::FinalizeExternalString(String* string) {
279  ASSERT(string->IsExternalString());
280  v8::String::ExternalStringResourceBase** resource_addr =
281      reinterpret_cast<v8::String::ExternalStringResourceBase**>(
282          reinterpret_cast<byte*>(string) +
283          ExternalString::kResourceOffset -
284          kHeapObjectTag);
285
286  // Dispose of the C++ object if it has not already been disposed.
287  if (*resource_addr != NULL) {
288    (*resource_addr)->Dispose();
289    *resource_addr = NULL;
290  }
291}
292
293
294MaybeObject* Heap::AllocateRawMap() {
295#ifdef DEBUG
296  isolate_->counters()->objs_since_last_full()->Increment();
297  isolate_->counters()->objs_since_last_young()->Increment();
298#endif
299  MaybeObject* result = map_space_->AllocateRaw(Map::kSize);
300  if (result->IsFailure()) old_gen_exhausted_ = true;
301  return result;
302}
303
304
305MaybeObject* Heap::AllocateRawCell() {
306#ifdef DEBUG
307  isolate_->counters()->objs_since_last_full()->Increment();
308  isolate_->counters()->objs_since_last_young()->Increment();
309#endif
310  MaybeObject* result = cell_space_->AllocateRaw(Cell::kSize);
311  if (result->IsFailure()) old_gen_exhausted_ = true;
312  return result;
313}
314
315
316MaybeObject* Heap::AllocateRawPropertyCell() {
317#ifdef DEBUG
318  isolate_->counters()->objs_since_last_full()->Increment();
319  isolate_->counters()->objs_since_last_young()->Increment();
320#endif
321  MaybeObject* result =
322      property_cell_space_->AllocateRaw(PropertyCell::kSize);
323  if (result->IsFailure()) old_gen_exhausted_ = true;
324  return result;
325}
326
327
328bool Heap::InNewSpace(Object* object) {
329  bool result = new_space_.Contains(object);
330  ASSERT(!result ||                  // Either not in new space
331         gc_state_ != NOT_IN_GC ||   // ... or in the middle of GC
332         InToSpace(object));         // ... or in to-space (where we allocate).
333  return result;
334}
335
336
337bool Heap::InNewSpace(Address address) {
338  return new_space_.Contains(address);
339}
340
341
342bool Heap::InFromSpace(Object* object) {
343  return new_space_.FromSpaceContains(object);
344}
345
346
347bool Heap::InToSpace(Object* object) {
348  return new_space_.ToSpaceContains(object);
349}
350
351
352bool Heap::InOldPointerSpace(Address address) {
353  return old_pointer_space_->Contains(address);
354}
355
356
357bool Heap::InOldPointerSpace(Object* object) {
358  return InOldPointerSpace(reinterpret_cast<Address>(object));
359}
360
361
362bool Heap::InOldDataSpace(Address address) {
363  return old_data_space_->Contains(address);
364}
365
366
367bool Heap::InOldDataSpace(Object* object) {
368  return InOldDataSpace(reinterpret_cast<Address>(object));
369}
370
371
372bool Heap::OldGenerationAllocationLimitReached() {
373  if (!incremental_marking()->IsStopped()) return false;
374  return OldGenerationSpaceAvailable() < 0;
375}
376
377
378bool Heap::ShouldBePromoted(Address old_address, int object_size) {
379  // An object should be promoted if:
380  // - the object has survived a scavenge operation or
381  // - to space is already 25% full.
382  NewSpacePage* page = NewSpacePage::FromAddress(old_address);
383  Address age_mark = new_space_.age_mark();
384  bool below_mark = page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK) &&
385      (!page->ContainsLimit(age_mark) || old_address < age_mark);
386  return below_mark || (new_space_.Size() + object_size) >=
387                        (new_space_.EffectiveCapacity() >> 2);
388}
389
390
391void Heap::RecordWrite(Address address, int offset) {
392  if (!InNewSpace(address)) store_buffer_.Mark(address + offset);
393}
394
395
396void Heap::RecordWrites(Address address, int start, int len) {
397  if (!InNewSpace(address)) {
398    for (int i = 0; i < len; i++) {
399      store_buffer_.Mark(address + start + i * kPointerSize);
400    }
401  }
402}
403
404
405OldSpace* Heap::TargetSpace(HeapObject* object) {
406  InstanceType type = object->map()->instance_type();
407  AllocationSpace space = TargetSpaceId(type);
408  return (space == OLD_POINTER_SPACE)
409      ? old_pointer_space_
410      : old_data_space_;
411}
412
413
414AllocationSpace Heap::TargetSpaceId(InstanceType type) {
415  // Heap numbers and sequential strings are promoted to old data space, all
416  // other object types are promoted to old pointer space.  We do not use
417  // object->IsHeapNumber() and object->IsSeqString() because we already
418  // know that object has the heap object tag.
419
420  // These objects are never allocated in new space.
421  ASSERT(type != MAP_TYPE);
422  ASSERT(type != CODE_TYPE);
423  ASSERT(type != ODDBALL_TYPE);
424  ASSERT(type != CELL_TYPE);
425  ASSERT(type != PROPERTY_CELL_TYPE);
426
427  if (type <= LAST_NAME_TYPE) {
428    if (type == SYMBOL_TYPE) return OLD_POINTER_SPACE;
429    ASSERT(type < FIRST_NONSTRING_TYPE);
430    // There are four string representations: sequential strings, external
431    // strings, cons strings, and sliced strings.
432    // Only the latter two contain non-map-word pointers to heap objects.
433    return ((type & kIsIndirectStringMask) == kIsIndirectStringTag)
434        ? OLD_POINTER_SPACE
435        : OLD_DATA_SPACE;
436  } else {
437    return (type <= LAST_DATA_TYPE) ? OLD_DATA_SPACE : OLD_POINTER_SPACE;
438  }
439}
440
441
442bool Heap::AllowedToBeMigrated(HeapObject* object, AllocationSpace dst) {
443  // Object migration is governed by the following rules:
444  //
445  // 1) Objects in new-space can be migrated to one of the old spaces
446  //    that matches their target space or they stay in new-space.
447  // 2) Objects in old-space stay in the same space when migrating.
448  // 3) Fillers (two or more words) can migrate due to left-trimming of
449  //    fixed arrays in new-space, old-data-space and old-pointer-space.
450  // 4) Fillers (one word) can never migrate, they are skipped by
451  //    incremental marking explicitly to prevent invalid pattern.
452  //
453  // Since this function is used for debugging only, we do not place
454  // asserts here, but check everything explicitly.
455  if (object->map() == one_pointer_filler_map()) return false;
456  InstanceType type = object->map()->instance_type();
457  MemoryChunk* chunk = MemoryChunk::FromAddress(object->address());
458  AllocationSpace src = chunk->owner()->identity();
459  switch (src) {
460    case NEW_SPACE:
461      return dst == src || dst == TargetSpaceId(type);
462    case OLD_POINTER_SPACE:
463      return dst == src && (dst == TargetSpaceId(type) || object->IsFiller());
464    case OLD_DATA_SPACE:
465      return dst == src && dst == TargetSpaceId(type);
466    case CODE_SPACE:
467      return dst == src && type == CODE_TYPE;
468    case MAP_SPACE:
469    case CELL_SPACE:
470    case PROPERTY_CELL_SPACE:
471    case LO_SPACE:
472      return false;
473  }
474  UNREACHABLE();
475  return false;
476}
477
478
479void Heap::CopyBlock(Address dst, Address src, int byte_size) {
480  CopyWords(reinterpret_cast<Object**>(dst),
481            reinterpret_cast<Object**>(src),
482            static_cast<size_t>(byte_size / kPointerSize));
483}
484
485
486void Heap::MoveBlock(Address dst, Address src, int byte_size) {
487  ASSERT(IsAligned(byte_size, kPointerSize));
488
489  int size_in_words = byte_size / kPointerSize;
490
491  if ((dst < src) || (dst >= (src + byte_size))) {
492    Object** src_slot = reinterpret_cast<Object**>(src);
493    Object** dst_slot = reinterpret_cast<Object**>(dst);
494    Object** end_slot = src_slot + size_in_words;
495
496    while (src_slot != end_slot) {
497      *dst_slot++ = *src_slot++;
498    }
499  } else {
500    OS::MemMove(dst, src, static_cast<size_t>(byte_size));
501  }
502}
503
504
505void Heap::ScavengePointer(HeapObject** p) {
506  ScavengeObject(p, *p);
507}
508
509
510void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
511  ASSERT(HEAP->InFromSpace(object));
512
513  // We use the first word (where the map pointer usually is) of a heap
514  // object to record the forwarding pointer.  A forwarding pointer can
515  // point to an old space, the code space, or the to space of the new
516  // generation.
517  MapWord first_word = object->map_word();
518
519  // If the first word is a forwarding address, the object has already been
520  // copied.
521  if (first_word.IsForwardingAddress()) {
522    HeapObject* dest = first_word.ToForwardingAddress();
523    ASSERT(HEAP->InFromSpace(*p));
524    *p = dest;
525    return;
526  }
527
528  // Call the slow part of scavenge object.
529  return ScavengeObjectSlow(p, object);
530}
531
532
533MaybeObject* Heap::AllocateEmptyJSArrayWithAllocationSite(
534      ElementsKind elements_kind,
535      Handle<AllocationSite> allocation_site) {
536  return AllocateJSArrayAndStorageWithAllocationSite(elements_kind, 0, 0,
537      allocation_site, DONT_INITIALIZE_ARRAY_ELEMENTS);
538}
539
540
541bool Heap::CollectGarbage(AllocationSpace space, const char* gc_reason) {
542  const char* collector_reason = NULL;
543  GarbageCollector collector = SelectGarbageCollector(space, &collector_reason);
544  return CollectGarbage(space, collector, gc_reason, collector_reason);
545}
546
547
548MaybeObject* Heap::PrepareForCompare(String* str) {
549  // Always flatten small strings and force flattening of long strings
550  // after we have accumulated a certain amount we failed to flatten.
551  static const int kMaxAlwaysFlattenLength = 32;
552  static const int kFlattenLongThreshold = 16*KB;
553
554  const int length = str->length();
555  MaybeObject* obj = str->TryFlatten();
556  if (length <= kMaxAlwaysFlattenLength ||
557      unflattened_strings_length_ >= kFlattenLongThreshold) {
558    return obj;
559  }
560  if (obj->IsFailure()) {
561    unflattened_strings_length_ += length;
562  }
563  return str;
564}
565
566
567intptr_t Heap::AdjustAmountOfExternalAllocatedMemory(
568    intptr_t change_in_bytes) {
569  ASSERT(HasBeenSetUp());
570  intptr_t amount = amount_of_external_allocated_memory_ + change_in_bytes;
571  if (change_in_bytes > 0) {
572    // Avoid overflow.
573    if (amount > amount_of_external_allocated_memory_) {
574      amount_of_external_allocated_memory_ = amount;
575    } else {
576      // Give up and reset the counters in case of an overflow.
577      amount_of_external_allocated_memory_ = 0;
578      amount_of_external_allocated_memory_at_last_global_gc_ = 0;
579    }
580    intptr_t amount_since_last_global_gc = PromotedExternalMemorySize();
581    if (amount_since_last_global_gc > external_allocation_limit_) {
582      CollectAllGarbage(kNoGCFlags, "external memory allocation limit reached");
583    }
584  } else {
585    // Avoid underflow.
586    if (amount >= 0) {
587      amount_of_external_allocated_memory_ = amount;
588    } else {
589      // Give up and reset the counters in case of an underflow.
590      amount_of_external_allocated_memory_ = 0;
591      amount_of_external_allocated_memory_at_last_global_gc_ = 0;
592    }
593  }
594  if (FLAG_trace_external_memory) {
595    PrintPID("%8.0f ms: ", isolate()->time_millis_since_init());
596    PrintF("Adjust amount of external memory: delta=%6" V8_PTR_PREFIX "d KB, "
597           "amount=%6" V8_PTR_PREFIX "d KB, since_gc=%6" V8_PTR_PREFIX "d KB, "
598           "isolate=0x%08" V8PRIxPTR ".\n",
599           change_in_bytes / KB,
600           amount_of_external_allocated_memory_ / KB,
601           PromotedExternalMemorySize() / KB,
602           reinterpret_cast<intptr_t>(isolate()));
603  }
604  ASSERT(amount_of_external_allocated_memory_ >= 0);
605  return amount_of_external_allocated_memory_;
606}
607
608
609Isolate* Heap::isolate() {
610  return reinterpret_cast<Isolate*>(reinterpret_cast<intptr_t>(this) -
611      reinterpret_cast<size_t>(reinterpret_cast<Isolate*>(4)->heap()) + 4);
612}
613
614
615#ifdef DEBUG
616#define GC_GREEDY_CHECK() \
617  if (FLAG_gc_greedy) HEAP->GarbageCollectionGreedyCheck()
618#else
619#define GC_GREEDY_CHECK() { }
620#endif
621
622// Calls the FUNCTION_CALL function and retries it up to three times
623// to guarantee that any allocations performed during the call will
624// succeed if there's enough memory.
625
626// Warning: Do not use the identifiers __object__, __maybe_object__ or
627// __scope__ in a call to this macro.
628
629#define CALL_AND_RETRY(ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY, OOM)\
630  do {                                                                         \
631    GC_GREEDY_CHECK();                                                         \
632    MaybeObject* __maybe_object__ = FUNCTION_CALL;                             \
633    Object* __object__ = NULL;                                                 \
634    if (__maybe_object__->ToObject(&__object__)) RETURN_VALUE;                 \
635    if (__maybe_object__->IsOutOfMemory()) {                                   \
636      OOM;                                                                     \
637    }                                                                          \
638    if (!__maybe_object__->IsRetryAfterGC()) RETURN_EMPTY;                     \
639    ISOLATE->heap()->CollectGarbage(Failure::cast(__maybe_object__)->          \
640                                    allocation_space(),                        \
641                                    "allocation failure");                     \
642    __maybe_object__ = FUNCTION_CALL;                                          \
643    if (__maybe_object__->ToObject(&__object__)) RETURN_VALUE;                 \
644    if (__maybe_object__->IsOutOfMemory()) {                                   \
645      OOM;                                                                     \
646    }                                                                          \
647    if (!__maybe_object__->IsRetryAfterGC()) RETURN_EMPTY;                     \
648    ISOLATE->counters()->gc_last_resort_from_handles()->Increment();           \
649    ISOLATE->heap()->CollectAllAvailableGarbage("last resort gc");             \
650    {                                                                          \
651      AlwaysAllocateScope __scope__;                                           \
652      __maybe_object__ = FUNCTION_CALL;                                        \
653    }                                                                          \
654    if (__maybe_object__->ToObject(&__object__)) RETURN_VALUE;                 \
655    if (__maybe_object__->IsOutOfMemory()) {                                   \
656      OOM;                                                                     \
657    }                                                                          \
658    if (__maybe_object__->IsRetryAfterGC()) {                                  \
659      /* TODO(1181417): Fix this. */                                           \
660      v8::internal::V8::FatalProcessOutOfMemory("CALL_AND_RETRY_LAST", true);  \
661    }                                                                          \
662    RETURN_EMPTY;                                                              \
663  } while (false)
664
665#define CALL_AND_RETRY_OR_DIE(                                             \
666     ISOLATE, FUNCTION_CALL, RETURN_VALUE, RETURN_EMPTY)                   \
667  CALL_AND_RETRY(                                                          \
668      ISOLATE,                                                             \
669      FUNCTION_CALL,                                                       \
670      RETURN_VALUE,                                                        \
671      RETURN_EMPTY,                                                        \
672      v8::internal::V8::FatalProcessOutOfMemory("CALL_AND_RETRY", true))
673
674#define CALL_HEAP_FUNCTION(ISOLATE, FUNCTION_CALL, TYPE)                      \
675  CALL_AND_RETRY_OR_DIE(ISOLATE,                                              \
676                        FUNCTION_CALL,                                        \
677                        return Handle<TYPE>(TYPE::cast(__object__), ISOLATE), \
678                        return Handle<TYPE>())                                \
679
680
681#define CALL_HEAP_FUNCTION_VOID(ISOLATE, FUNCTION_CALL)  \
682  CALL_AND_RETRY_OR_DIE(ISOLATE, FUNCTION_CALL, return, return)
683
684
685#define CALL_HEAP_FUNCTION_PASS_EXCEPTION(ISOLATE, FUNCTION_CALL) \
686  CALL_AND_RETRY(ISOLATE,                                         \
687                 FUNCTION_CALL,                                   \
688                 return __object__,                               \
689                 return __maybe_object__,                         \
690                 return __maybe_object__)
691
692
693void ExternalStringTable::AddString(String* string) {
694  ASSERT(string->IsExternalString());
695  if (heap_->InNewSpace(string)) {
696    new_space_strings_.Add(string);
697  } else {
698    old_space_strings_.Add(string);
699  }
700}
701
702
703void ExternalStringTable::Iterate(ObjectVisitor* v) {
704  if (!new_space_strings_.is_empty()) {
705    Object** start = &new_space_strings_[0];
706    v->VisitPointers(start, start + new_space_strings_.length());
707  }
708  if (!old_space_strings_.is_empty()) {
709    Object** start = &old_space_strings_[0];
710    v->VisitPointers(start, start + old_space_strings_.length());
711  }
712}
713
714
715// Verify() is inline to avoid ifdef-s around its calls in release
716// mode.
717void ExternalStringTable::Verify() {
718#ifdef DEBUG
719  for (int i = 0; i < new_space_strings_.length(); ++i) {
720    Object* obj = Object::cast(new_space_strings_[i]);
721    // TODO(yangguo): check that the object is indeed an external string.
722    ASSERT(heap_->InNewSpace(obj));
723    ASSERT(obj != HEAP->the_hole_value());
724  }
725  for (int i = 0; i < old_space_strings_.length(); ++i) {
726    Object* obj = Object::cast(old_space_strings_[i]);
727    // TODO(yangguo): check that the object is indeed an external string.
728    ASSERT(!heap_->InNewSpace(obj));
729    ASSERT(obj != HEAP->the_hole_value());
730  }
731#endif
732}
733
734
735void ExternalStringTable::AddOldString(String* string) {
736  ASSERT(string->IsExternalString());
737  ASSERT(!heap_->InNewSpace(string));
738  old_space_strings_.Add(string);
739}
740
741
742void ExternalStringTable::ShrinkNewStrings(int position) {
743  new_space_strings_.Rewind(position);
744#ifdef VERIFY_HEAP
745  if (FLAG_verify_heap) {
746    Verify();
747  }
748#endif
749}
750
751
752void Heap::ClearInstanceofCache() {
753  set_instanceof_cache_function(the_hole_value());
754}
755
756
757Object* Heap::ToBoolean(bool condition) {
758  return condition ? true_value() : false_value();
759}
760
761
762void Heap::CompletelyClearInstanceofCache() {
763  set_instanceof_cache_map(the_hole_value());
764  set_instanceof_cache_function(the_hole_value());
765}
766
767
768MaybeObject* TranscendentalCache::Get(Type type, double input) {
769  SubCache* cache = caches_[type];
770  if (cache == NULL) {
771    caches_[type] = cache = new SubCache(type);
772  }
773  return cache->Get(input);
774}
775
776
777Address TranscendentalCache::cache_array_address() {
778  return reinterpret_cast<Address>(caches_);
779}
780
781
782double TranscendentalCache::SubCache::Calculate(double input) {
783  switch (type_) {
784    case ACOS:
785      return acos(input);
786    case ASIN:
787      return asin(input);
788    case ATAN:
789      return atan(input);
790    case COS:
791      return fast_cos(input);
792    case EXP:
793      return exp(input);
794    case LOG:
795      return fast_log(input);
796    case SIN:
797      return fast_sin(input);
798    case TAN:
799      return fast_tan(input);
800    default:
801      return 0.0;  // Never happens.
802  }
803}
804
805
806MaybeObject* TranscendentalCache::SubCache::Get(double input) {
807  Converter c;
808  c.dbl = input;
809  int hash = Hash(c);
810  Element e = elements_[hash];
811  if (e.in[0] == c.integers[0] &&
812      e.in[1] == c.integers[1]) {
813    ASSERT(e.output != NULL);
814    isolate_->counters()->transcendental_cache_hit()->Increment();
815    return e.output;
816  }
817  double answer = Calculate(input);
818  isolate_->counters()->transcendental_cache_miss()->Increment();
819  Object* heap_number;
820  { MaybeObject* maybe_heap_number =
821        isolate_->heap()->AllocateHeapNumber(answer);
822    if (!maybe_heap_number->ToObject(&heap_number)) return maybe_heap_number;
823  }
824  elements_[hash].in[0] = c.integers[0];
825  elements_[hash].in[1] = c.integers[1];
826  elements_[hash].output = heap_number;
827  return heap_number;
828}
829
830
831AlwaysAllocateScope::AlwaysAllocateScope() {
832  // We shouldn't hit any nested scopes, because that requires
833  // non-handle code to call handle code. The code still works but
834  // performance will degrade, so we want to catch this situation
835  // in debug mode.
836  ASSERT(HEAP->always_allocate_scope_depth_ == 0);
837  HEAP->always_allocate_scope_depth_++;
838}
839
840
841AlwaysAllocateScope::~AlwaysAllocateScope() {
842  HEAP->always_allocate_scope_depth_--;
843  ASSERT(HEAP->always_allocate_scope_depth_ == 0);
844}
845
846
847#ifdef VERIFY_HEAP
848NoWeakEmbeddedMapsVerificationScope::NoWeakEmbeddedMapsVerificationScope() {
849  HEAP->no_weak_embedded_maps_verification_scope_depth_++;
850}
851
852
853NoWeakEmbeddedMapsVerificationScope::~NoWeakEmbeddedMapsVerificationScope() {
854  HEAP->no_weak_embedded_maps_verification_scope_depth_--;
855}
856#endif
857
858
859void VerifyPointersVisitor::VisitPointers(Object** start, Object** end) {
860  for (Object** current = start; current < end; current++) {
861    if ((*current)->IsHeapObject()) {
862      HeapObject* object = HeapObject::cast(*current);
863      CHECK(HEAP->Contains(object));
864      CHECK(object->map()->IsMap());
865    }
866  }
867}
868
869
870double GCTracer::SizeOfHeapObjects() {
871  return (static_cast<double>(HEAP->SizeOfObjects())) / MB;
872}
873
874
875DisallowAllocationFailure::DisallowAllocationFailure() {
876#ifdef DEBUG
877  old_state_ = HEAP->disallow_allocation_failure_;
878  HEAP->disallow_allocation_failure_ = true;
879#endif
880}
881
882
883DisallowAllocationFailure::~DisallowAllocationFailure() {
884#ifdef DEBUG
885  HEAP->disallow_allocation_failure_ = old_state_;
886#endif
887}
888
889
890} }  // namespace v8::internal
891
892#endif  // V8_HEAP_INL_H_
893