blob: 04a618995b4bbb80214901d006868e4d7e8fd3ee [file] [log] [blame]
// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_HEAP_ALLOCATION_RESULT_H_
#define V8_HEAP_ALLOCATION_RESULT_H_
#include "src/common/globals.h"
#include "src/objects/heap-object.h"
#include "src/objects/objects.h"
#include "src/objects/smi.h"
namespace v8 {
namespace internal {
enum class AllocationOrigin {
kGeneratedCode = 0,
kRuntime = 1,
kGC = 2,
kFirstAllocationOrigin = kGeneratedCode,
kLastAllocationOrigin = kGC,
kNumberOfAllocationOrigins = kLastAllocationOrigin + 1
};
// The result of an allocation attempt. Either represents a successful
// allocation that can be turned into an object or a failed attempt.
class AllocationResult final {
public:
static AllocationResult Failure() { return AllocationResult(); }
static AllocationResult FromObject(HeapObject heap_object) {
return AllocationResult(heap_object);
}
// Empty constructor creates a failed result. The callsite determines which
// GC to invoke based on the requested allocation.
AllocationResult() = default;
bool IsFailure() const { return object_.is_null(); }
template <typename T>
bool To(T* obj) const {
if (IsFailure()) return false;
*obj = T::cast(object_);
return true;
}
HeapObject ToObjectChecked() const {
CHECK(!IsFailure());
return HeapObject::cast(object_);
}
HeapObject ToObject() const {
DCHECK(!IsFailure());
return HeapObject::cast(object_);
}
Address ToAddress() const {
DCHECK(!IsFailure());
return HeapObject::cast(object_).address();
}
private:
explicit AllocationResult(HeapObject heap_object) : object_(heap_object) {}
HeapObject object_;
};
STATIC_ASSERT(sizeof(AllocationResult) == kSystemPointerSize);
} // namespace internal
} // namespace v8
#endif // V8_HEAP_ALLOCATION_RESULT_H_