1 /*
2 * Copyright (c) 2015, 2022, Red Hat, Inc. All rights reserved.
3 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
4 * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 *
7 * This code is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 only, as
9 * published by the Free Software Foundation.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 *
25 */
26
27 #ifndef SHARE_GC_SHENANDOAH_SHENANDOAHMARK_INLINE_HPP
28 #define SHARE_GC_SHENANDOAH_SHENANDOAHMARK_INLINE_HPP
29
30 #include "gc/shenandoah/shenandoahMark.hpp"
31
32 #include "gc/shared/continuationGCSupport.inline.hpp"
33 #include "gc/shenandoah/shenandoahAgeCensus.hpp"
34 #include "gc/shenandoah/shenandoahAsserts.hpp"
35 #include "gc/shenandoah/shenandoahBarrierSet.inline.hpp"
36 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
37 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
38 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
39 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
40 #include "gc/shenandoah/shenandoahPrefetch.inline.hpp"
41 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
42 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
43 #include "gc/shenandoah/shenandoahUtils.hpp"
44 #include "memory/iterator.inline.hpp"
45 #include "oops/compressedOops.inline.hpp"
46 #include "oops/oop.inline.hpp"
47 #include "utilities/devirtualizer.inline.hpp"
48 #include "utilities/powerOfTwo.hpp"
49
50 template <class T, class OT, ShenandoahGenerationType GENERATION, bool STRING_DEDUP>
51 void ShenandoahMark::do_task(ShenandoahObjToScanQueue* q, T* cl, ShenandoahLiveData* live_data, StringDedup::Requests* const req, ShenandoahMarkTask* task, uint worker_id) {
52 oop obj = task->obj();
53
54 shenandoah_assert_not_forwarded(nullptr, obj);
55 shenandoah_assert_marked(nullptr, obj);
56 shenandoah_assert_not_in_cset_except(nullptr, obj, ShenandoahHeap::heap()->cancelled_gc());
57
58 Klass* klass = obj->klass();
59
60 // Are we in weak subgraph scan?
61 bool weak = task->is_weak();
62 cl->set_weak(weak);
63
64 if (task->is_not_chunked()) {
65 // Dispatch based on object type. The case order does not seem to affect performance,
66 // so it matches the enum order for consistency.
67 switch (klass->kind()) {
68 case Klass::InstanceKlassKind: {
69 // Regular instance.
70 if (STRING_DEDUP && (klass == vmClasses::String_klass())) {
71 dedup_string(obj, req);
72 }
73 InstanceKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
74 break;
75 }
76 case Klass::InlineKlassKind: {
77 // Inline instance.
78 InlineKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
79 break;
80 }
81 case Klass::InstanceRefKlassKind: {
82 // (Weak) reference instance.
83 InstanceRefKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
84 break;
85 }
86 case Klass::InstanceMirrorKlassKind:
87 case Klass::InstanceClassLoaderKlassKind: {
88 // Remaining rare classes, dispatch generically.
89 obj->oop_iterate(cl);
90 break;
91 }
92 case Klass::InstanceStackChunkKlassKind: {
93 // Stack chunk. Loom doesn't support mixing of weak marking and strong marking
94 // of stack chunks, upgrade to strong right away.
95 cl->set_weak(false);
96 InstanceStackChunkKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
97 break;
98 }
99 case Klass::TypeArrayKlassKind: {
100 // Primitive array. Do nothing, no oops there. We use the same
101 // performance tweak TypeArrayKlass::oop_oop_iterate_impl is using:
102 // We skip iterating over the klass pointer since we know that
103 // Universe::TypeArrayKlass never moves.
104 break;
105 }
106 case Klass::ObjArrayKlassKind: {
107 fatal("Unexpected unrefined object array klass");
108 }
109 case Klass::RefArrayKlassKind: {
110 // Reference array and no chunk is set. Must be the first
111 // time we visit it, start the chunked processing.
112 do_chunked_array_start<T, OT>(q, cl, obj, klass, weak);
113 break;
114 }
115 case Klass::FlatArrayKlassKind: {
116 // Flat array, all elements are embedded.
117 FlatArrayKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
118 break;
119 }
120 default: {
121 fatal("Unknown klass kind: %d", klass->kind());
122 }
123 }
124 // Count liveness the last: push the outstanding work to the queues first
125 // Avoid double-counting objects that are visited twice due to upgrade
126 // from final- to strong mark.
127 if (task->count_liveness()) {
128 count_liveness<GENERATION>(live_data, obj, klass, worker_id);
129 }
130 } else {
131 // Reference array chunk. Process it.
132 do_chunked_array<T, OT>(q, cl, obj, klass, task->chunk(), task->pow(), weak);
133 }
134 }
135
136 inline void ShenandoahMark::dedup_string(oop obj, StringDedup::Requests* const req) {
137 assert(req != nullptr, "Should be available if dedup is enabled");
138
139 // Skip if already requested or dedup is forbidden.
140 // The overwhelming majority of Strings would be filtered here.
141 // These bits are also sticky, so older Strings would be filtered here too.
142 if (java_lang_String::deduplication_requested_or_forbidden(obj)) {
143 return;
144 }
145
146 // Accept deduplication request.
147 if (!java_lang_String::test_and_set_deduplication_requested(obj)) {
148 req->add(obj);
149 }
150 }
151
152 template <ShenandoahGenerationType GENERATION>
153 void ShenandoahMark::count_liveness(ShenandoahLiveData* live_data, oop obj, Klass* klass, uint worker_id) {
154 const ShenandoahHeap* const heap = ShenandoahHeap::heap();
155 const size_t region_idx = heap->heap_region_index_containing(obj);
156 ShenandoahHeapRegion* const region = heap->get_region(region_idx);
157 const size_t size = obj->size_given_klass(klass);
158
159 // Age census for objects in the young generation
160 if (GENERATION == YOUNG || (GENERATION == GLOBAL && region->is_young())) {
161 assert(heap->mode()->is_generational(), "Only if generational");
162 assert(region->is_young(), "Only for young objects");
163 const uint age = ShenandoahHeap::get_object_age(obj);
164 ShenandoahAgeCensus* const census = ShenandoahGenerationalHeap::heap()->age_census();
165 CENSUS_NOISE(census->add(age, region->age(), region->youth(), size, worker_id);)
166 NO_CENSUS_NOISE(census->add(age, region->age(), size, worker_id);)
167 }
168
169 if (!region->is_humongous_start()) {
170 assert(!region->is_humongous(), "Cannot have continuations here");
171 assert(region->is_affiliated(), "Do not count live data within Free Regular Region %zu", region_idx);
172 ShenandoahLiveData cur = live_data[region_idx];
173 size_t new_val = size + cur;
174 if (new_val >= SHENANDOAH_LIVEDATA_MAX) {
175 // overflow, flush to region data
176 region->increase_live_data_gc_words(new_val);
177 live_data[region_idx] = 0;
178 } else {
179 // still good, remember in locals
180 live_data[region_idx] = (ShenandoahLiveData) new_val;
181 }
182 } else {
183 shenandoah_assert_in_correct_region(nullptr, obj);
184 size_t num_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
185
186 assert(region->is_affiliated(), "Do not count live data within FREE Humongous Start Region %zu", region_idx);
187 for (size_t i = region_idx; i < region_idx + num_regions; i++) {
188 ShenandoahHeapRegion* chain_reg = heap->get_region(i);
189 assert(chain_reg->is_humongous(), "Expecting a humongous region");
190 assert(chain_reg->is_affiliated(), "Do not count live data within FREE Humongous Continuation Region %zu", i);
191 chain_reg->increase_live_data_gc_words(chain_reg->used() >> LogHeapWordSize);
192 }
193 }
194 }
195
196 template <class T, class OT>
197 void ShenandoahMark::do_chunked_array_start(ShenandoahObjToScanQueue* q, T* cl, oop obj, Klass* klass, bool weak) {
198 assert(obj->is_refArray(), "expect ref array");
199 refArrayOop array = refArrayOop(obj);
200 int len = array->length();
201
202 // Mark reference array klass metadata
203 if (Devirtualizer::do_metadata(cl)) {
204 Devirtualizer::do_klass(cl, klass);
205 }
206
207 if (len <= (int) ObjArrayMarkingStride*2) {
208 // A few slices only, process directly
209 RefArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, 0, len);
210 } else {
211 int bits = log2i_graceful(len);
212 // Compensate for non-power-of-two arrays, cover the array in excess:
213 if (len != (1 << bits)) bits++;
214
215 // Only allow full chunks on the queue. This frees do_chunked_array() from checking from/to
216 // boundaries against array->length(), touching the array header on every chunk.
217 //
218 // To do this, we cut the prefix in full-sized chunks, and submit them on the queue.
219 // If the array is not divided in chunk sizes, then there would be an irregular tail,
220 // which we will process separately.
221
222 int last_idx = 0;
223
224 int chunk = 1;
225 int pow = bits;
226
227 // Handle overflow
228 if (pow >= 31) {
229 assert (pow == 31, "sanity");
230 pow--;
231 chunk = 2;
232 last_idx = (1 << pow);
233 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, 1, pow));
234 assert(pushed, "overflow queue should always succeed pushing");
235 }
236
237 // Split out tasks, as suggested in ShenandoahMarkTask docs. Record the last
238 // successful right boundary to figure out the irregular tail.
239 while ((1 << pow) > (int)ObjArrayMarkingStride &&
240 (chunk*2 < ShenandoahMarkTask::chunk_size())) {
241 pow--;
242 int left_chunk = chunk*2 - 1;
243 int right_chunk = chunk*2;
244 int left_chunk_end = left_chunk * (1 << pow);
245 if (left_chunk_end < len) {
246 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, left_chunk, pow));
247 assert(pushed, "overflow queue should always succeed pushing");
248 chunk = right_chunk;
249 last_idx = left_chunk_end;
250 } else {
251 chunk = left_chunk;
252 }
253 }
254
255 // Process the irregular tail, if present
256 int from = last_idx;
257 if (from < len) {
258 RefArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, from, len);
259 }
260 }
261 }
262
263 template <class T, class OT>
264 void ShenandoahMark::do_chunked_array(ShenandoahObjToScanQueue* q, T* cl, oop obj, Klass* klass, int chunk, int pow, bool weak) {
265 assert(obj->is_refArray(), "expect ref array");
266 refArrayOop array = refArrayOop(obj);
267
268 // Split out tasks, as suggested in ShenandoahMarkTask docs. Avoid pushing tasks that
269 // are known to start beyond the array.
270 while ((1 << pow) > (int)ObjArrayMarkingStride && (chunk*2 < ShenandoahMarkTask::chunk_size())) {
271 pow--;
272 chunk *= 2;
273 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, chunk - 1, pow));
274 assert(pushed, "overflow queue should always succeed pushing");
275 }
276
277 int chunk_size = 1 << pow;
278
279 int from = (chunk - 1) * chunk_size;
280 int to = chunk * chunk_size;
281
282 #ifdef ASSERT
283 int len = array->length();
284 assert (0 <= from && from < len, "from is sane: %d/%d", from, len);
285 assert (0 < to && to <= len, "to is sane: %d/%d", to, len);
286 #endif
287
288 RefArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, from, to);
289 }
290
291 template <ShenandoahGenerationType GENERATION>
292 class ShenandoahSATBBufferClosure : public SATBBufferClosure {
293 private:
294 ShenandoahObjToScanQueue* _queue;
295 ShenandoahObjToScanQueue* _old_queue;
296 ShenandoahHeap* _heap;
297 ShenandoahMarkingContext* const _mark_context;
298 public:
299 ShenandoahSATBBufferClosure(ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q) :
300 _queue(q),
301 _old_queue(old_q),
302 _heap(ShenandoahHeap::heap()),
303 _mark_context(_heap->marking_context())
304 {
305 }
306
307 void do_buffer(void **buffer, size_t size) {
308 assert(size == 0 || !_heap->has_forwarded_objects() || _heap->is_concurrent_old_mark_in_progress(), "Forwarded objects are not expected here");
309 for (size_t i = 0; i < size; ++i) {
310 oop *p = (oop *) &buffer[i];
311 ShenandoahMark::mark_through_ref<oop, GENERATION>(p, _queue, _old_queue, _mark_context, false);
312 }
313 }
314 };
315
316 template<ShenandoahGenerationType GENERATION>
317 bool ShenandoahMark::in_generation(ShenandoahHeap* const heap, oop obj) {
318 // Each in-line expansion of in_generation() resolves GENERATION at compile time.
319 if (GENERATION == YOUNG) {
320 return heap->is_in_young(obj);
321 }
322
323 if (GENERATION == OLD) {
324 return heap->is_in_old(obj);
325 }
326
327 assert((GENERATION == GLOBAL || GENERATION == NON_GEN), "Unexpected generation type");
328 assert(heap->is_in(obj), "Object must be in heap");
329 return true;
330 }
331
332 template<class T, ShenandoahGenerationType GENERATION>
333 void ShenandoahMark::mark_through_ref(T *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
334 // Note: This is a very hot code path, so the code should be conditional on GENERATION template
335 // parameter where possible, in order to generate the most efficient code.
336
337 T o = RawAccess<>::oop_load(p);
338 if (!CompressedOops::is_null(o)) {
339 oop obj = CompressedOops::decode_not_null(o);
340
341 ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap();
342 shenandoah_assert_not_forwarded(p, obj);
343 shenandoah_assert_not_in_cset_except(p, obj, heap->cancelled_gc());
344 if (in_generation<GENERATION>(heap, obj)) {
345 mark_ref(q, mark_context, weak, obj);
346 shenandoah_assert_marked(p, obj);
347 if (GENERATION == YOUNG && heap->is_in_old(p)) {
348 // Mark card as dirty because remembered set scanning still finds interesting pointer.
349 heap->old_generation()->mark_card_as_dirty((HeapWord*)p);
350 } else if (GENERATION == GLOBAL && heap->is_in_old(p) && heap->is_in_young(obj)) {
351 // Mark card as dirty because GLOBAL marking finds interesting pointer.
352 heap->old_generation()->mark_card_as_dirty((HeapWord*)p);
353 }
354 } else if (old_q != nullptr) {
355 // Young mark, bootstrapping old_q or concurrent with old_q marking.
356 mark_ref(old_q, mark_context, weak, obj);
357 shenandoah_assert_marked(p, obj);
358 } else if (GENERATION == OLD) {
359 // Old mark, found a young pointer.
360 if (heap->is_in(p)) {
361 assert(heap->is_in_young(obj), "Expected young object.");
362 heap->old_generation()->mark_card_as_dirty(p);
363 }
364 }
365 }
366 }
367
368 template<>
369 ALWAYSINLINE
370 void ShenandoahMark::mark_through_ref<oop, ShenandoahGenerationType::NON_GEN>(oop *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
371 mark_non_generational_ref(p, q, mark_context, weak);
372 }
373
374 template<>
375 ALWAYSINLINE
376 void ShenandoahMark::mark_through_ref<narrowOop, ShenandoahGenerationType::NON_GEN>(narrowOop *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
377 mark_non_generational_ref(p, q, mark_context, weak);
378 }
379
380 template<class T>
381 void ShenandoahMark::mark_non_generational_ref(T* p, ShenandoahObjToScanQueue* q,
382 ShenandoahMarkingContext* const mark_context, bool weak) {
383 oop o = RawAccess<>::oop_load(p);
384 if (!CompressedOops::is_null(o)) {
385 oop obj = CompressedOops::decode_not_null(o);
386
387 shenandoah_assert_not_forwarded(p, obj);
388 shenandoah_assert_not_in_cset_except(p, obj, ShenandoahHeap::heap()->cancelled_gc());
389
390 mark_ref(q, mark_context, weak, obj);
391
392 shenandoah_assert_marked(p, obj);
393 }
394 }
395
396 inline void ShenandoahMark::mark_ref(ShenandoahObjToScanQueue* q,
397 ShenandoahMarkingContext* const mark_context,
398 bool weak, oop obj) {
399 bool skip_live = false;
400 bool marked;
401 if (weak) {
402 marked = mark_context->mark_weak(obj);
403 } else {
404 marked = mark_context->mark_strong(obj, /* was_upgraded = */ skip_live);
405 }
406 if (marked) {
407 ShenandoahPrefetch::prefetch(obj);
408 bool pushed = q->push(ShenandoahMarkTask(obj, skip_live, weak));
409 assert(pushed, "overflow queue should always succeed pushing");
410 }
411 }
412
413 ShenandoahObjToScanQueueSet* ShenandoahMark::task_queues() const {
414 return _task_queues;
415 }
416
417 ShenandoahObjToScanQueue* ShenandoahMark::get_queue(uint index) const {
418 return _task_queues->queue(index);
419 }
420
421 ShenandoahObjToScanQueue* ShenandoahMark::get_old_queue(uint index) const {
422 if (_old_gen_task_queues != nullptr) {
423 return _old_gen_task_queues->queue(index);
424 }
425 return nullptr;
426 }
427
428 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHMARK_INLINE_HPP