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::InstanceRefKlassKind: {
77 // (Weak) reference instance.
78 InstanceRefKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
79 break;
80 }
81 case Klass::InstanceMirrorKlassKind:
82 case Klass::InstanceClassLoaderKlassKind: {
83 // Remaining rare classes, dispatch generically.
84 obj->oop_iterate(cl);
85 break;
86 }
87 case Klass::InstanceStackChunkKlassKind: {
88 // Stack chunk. Loom doesn't support mixing of weak marking and strong marking
89 // of stack chunks, upgrade to strong right away.
90 cl->set_weak(false);
91 InstanceStackChunkKlass::cast(klass)->oop_oop_iterate<OT>(obj, cl);
92 break;
93 }
94 case Klass::TypeArrayKlassKind: {
95 // Primitive array. Do nothing, no oops there. We use the same
96 // performance tweak TypeArrayKlass::oop_oop_iterate_impl is using:
97 // We skip iterating over the klass pointer since we know that
98 // Universe::TypeArrayKlass never moves.
99 break;
100 }
101 case Klass::ObjArrayKlassKind: {
102 // Object array and no chunk is set. Must be the first
103 // time we visit it, start the chunked processing.
104 do_chunked_array_start<T, OT>(q, cl, obj, klass, weak);
105 break;
106 }
107 default: {
108 fatal("Unknown klass kind: %d", klass->kind());
109 }
110 }
111 // Count liveness the last: push the outstanding work to the queues first
112 // Avoid double-counting objects that are visited twice due to upgrade
113 // from final- to strong mark.
114 if (task->count_liveness()) {
115 count_liveness<GENERATION>(live_data, obj, klass, worker_id);
116 }
117 } else {
118 // Object array chunk. Process it.
119 do_chunked_array<T, OT>(q, cl, obj, klass, task->chunk(), task->pow(), weak);
120 }
121 }
122
123 inline void ShenandoahMark::dedup_string(oop obj, StringDedup::Requests* const req) {
124 assert(req != nullptr, "Should be available if dedup is enabled");
125
126 // Skip if already requested or dedup is forbidden.
127 // The overwhelming majority of Strings would be filtered here.
128 // These bits are also sticky, so older Strings would be filtered here too.
129 if (java_lang_String::deduplication_requested_or_forbidden(obj)) {
130 return;
131 }
132
133 // Accept deduplication request.
134 if (!java_lang_String::test_and_set_deduplication_requested(obj)) {
135 req->add(obj);
136 }
137 }
138
139 template <ShenandoahGenerationType GENERATION>
140 void ShenandoahMark::count_liveness(ShenandoahLiveData* live_data, oop obj, Klass* klass, uint worker_id) {
141 const ShenandoahHeap* const heap = ShenandoahHeap::heap();
142 const size_t region_idx = heap->heap_region_index_containing(obj);
143 ShenandoahHeapRegion* const region = heap->get_region(region_idx);
144 const size_t size = obj->size_given_klass(klass);
145
146 // Age census for objects in the young generation
147 if (GENERATION == YOUNG || (GENERATION == GLOBAL && region->is_young())) {
148 assert(heap->mode()->is_generational(), "Only if generational");
149 assert(region->is_young(), "Only for young objects");
150 const uint age = ShenandoahHeap::get_object_age(obj);
151 ShenandoahAgeCensus* const census = ShenandoahGenerationalHeap::heap()->age_census();
152 CENSUS_NOISE(census->add(age, region->age(), region->youth(), size, worker_id);)
153 NO_CENSUS_NOISE(census->add(age, region->age(), size, worker_id);)
154 }
155
156 if (!region->is_humongous_start()) {
157 assert(!region->is_humongous(), "Cannot have continuations here");
158 assert(region->is_affiliated(), "Do not count live data within Free Regular Region %zu", region_idx);
159 ShenandoahLiveData cur = live_data[region_idx];
160 size_t new_val = size + cur;
161 if (new_val >= SHENANDOAH_LIVEDATA_MAX) {
162 // overflow, flush to region data
163 region->increase_live_data_gc_words(new_val);
164 live_data[region_idx] = 0;
165 } else {
166 // still good, remember in locals
167 live_data[region_idx] = (ShenandoahLiveData) new_val;
168 }
169 } else {
170 shenandoah_assert_in_correct_region(nullptr, obj);
171 size_t num_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
172
173 assert(region->is_affiliated(), "Do not count live data within FREE Humongous Start Region %zu", region_idx);
174 for (size_t i = region_idx; i < region_idx + num_regions; i++) {
175 ShenandoahHeapRegion* chain_reg = heap->get_region(i);
176 assert(chain_reg->is_humongous(), "Expecting a humongous region");
177 assert(chain_reg->is_affiliated(), "Do not count live data within FREE Humongous Continuation Region %zu", i);
178 chain_reg->increase_live_data_gc_words(chain_reg->used() >> LogHeapWordSize);
179 }
180 }
181 }
182
183 template <class T, class OT>
184 void ShenandoahMark::do_chunked_array_start(ShenandoahObjToScanQueue* q, T* cl, oop obj, Klass* klass, bool weak) {
185 assert(obj->is_objArray(), "expect object array");
186 objArrayOop array = objArrayOop(obj);
187 int len = array->length();
188
189 // Mark objArray klass metadata
190 if (Devirtualizer::do_metadata(cl)) {
191 Devirtualizer::do_klass(cl, klass);
192 }
193
194 if (len <= (int) ObjArrayMarkingStride*2) {
195 // A few slices only, process directly
196 ObjArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, 0, len);
197 } else {
198 int bits = log2i_graceful(len);
199 // Compensate for non-power-of-two arrays, cover the array in excess:
200 if (len != (1 << bits)) bits++;
201
202 // Only allow full chunks on the queue. This frees do_chunked_array() from checking from/to
203 // boundaries against array->length(), touching the array header on every chunk.
204 //
205 // To do this, we cut the prefix in full-sized chunks, and submit them on the queue.
206 // If the array is not divided in chunk sizes, then there would be an irregular tail,
207 // which we will process separately.
208
209 int last_idx = 0;
210
211 int chunk = 1;
212 int pow = bits;
213
214 // Handle overflow
215 if (pow >= 31) {
216 assert (pow == 31, "sanity");
217 pow--;
218 chunk = 2;
219 last_idx = (1 << pow);
220 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, 1, pow));
221 assert(pushed, "overflow queue should always succeed pushing");
222 }
223
224 // Split out tasks, as suggested in ShenandoahMarkTask docs. Record the last
225 // successful right boundary to figure out the irregular tail.
226 while ((1 << pow) > (int)ObjArrayMarkingStride &&
227 (chunk*2 < ShenandoahMarkTask::chunk_size())) {
228 pow--;
229 int left_chunk = chunk*2 - 1;
230 int right_chunk = chunk*2;
231 int left_chunk_end = left_chunk * (1 << pow);
232 if (left_chunk_end < len) {
233 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, left_chunk, pow));
234 assert(pushed, "overflow queue should always succeed pushing");
235 chunk = right_chunk;
236 last_idx = left_chunk_end;
237 } else {
238 chunk = left_chunk;
239 }
240 }
241
242 // Process the irregular tail, if present
243 int from = last_idx;
244 if (from < len) {
245 ObjArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, from, len);
246 }
247 }
248 }
249
250 template <class T, class OT>
251 void ShenandoahMark::do_chunked_array(ShenandoahObjToScanQueue* q, T* cl, oop obj, Klass* klass, int chunk, int pow, bool weak) {
252 assert(obj->is_objArray(), "expect object array");
253 objArrayOop array = objArrayOop(obj);
254
255 // Split out tasks, as suggested in ShenandoahMarkTask docs. Avoid pushing tasks that
256 // are known to start beyond the array.
257 while ((1 << pow) > (int)ObjArrayMarkingStride && (chunk*2 < ShenandoahMarkTask::chunk_size())) {
258 pow--;
259 chunk *= 2;
260 bool pushed = q->push(ShenandoahMarkTask(array, true, weak, chunk - 1, pow));
261 assert(pushed, "overflow queue should always succeed pushing");
262 }
263
264 int chunk_size = 1 << pow;
265
266 int from = (chunk - 1) * chunk_size;
267 int to = chunk * chunk_size;
268
269 #ifdef ASSERT
270 int len = array->length();
271 assert (0 <= from && from < len, "from is sane: %d/%d", from, len);
272 assert (0 < to && to <= len, "to is sane: %d/%d", to, len);
273 #endif
274
275 ObjArrayKlass::cast(klass)->oop_oop_iterate_elements_range<OT>(array, cl, from, to);
276 }
277
278 template <ShenandoahGenerationType GENERATION>
279 class ShenandoahSATBBufferClosure : public SATBBufferClosure {
280 private:
281 ShenandoahObjToScanQueue* _queue;
282 ShenandoahObjToScanQueue* _old_queue;
283 ShenandoahHeap* _heap;
284 ShenandoahMarkingContext* const _mark_context;
285 public:
286 ShenandoahSATBBufferClosure(ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q) :
287 _queue(q),
288 _old_queue(old_q),
289 _heap(ShenandoahHeap::heap()),
290 _mark_context(_heap->marking_context())
291 {
292 }
293
294 void do_buffer(void **buffer, size_t size) {
295 assert(size == 0 || !_heap->has_forwarded_objects() || _heap->is_concurrent_old_mark_in_progress(), "Forwarded objects are not expected here");
296 for (size_t i = 0; i < size; ++i) {
297 oop *p = (oop *) &buffer[i];
298 ShenandoahMark::mark_through_ref<oop, GENERATION>(p, _queue, _old_queue, _mark_context, false);
299 }
300 }
301 };
302
303 template<ShenandoahGenerationType GENERATION>
304 bool ShenandoahMark::in_generation(ShenandoahHeap* const heap, oop obj) {
305 // Each in-line expansion of in_generation() resolves GENERATION at compile time.
306 if (GENERATION == YOUNG) {
307 return heap->is_in_young(obj);
308 }
309
310 if (GENERATION == OLD) {
311 return heap->is_in_old(obj);
312 }
313
314 assert((GENERATION == GLOBAL || GENERATION == NON_GEN), "Unexpected generation type");
315 assert(heap->is_in(obj), "Object must be in heap");
316 return true;
317 }
318
319 template<class T, ShenandoahGenerationType GENERATION>
320 void ShenandoahMark::mark_through_ref(T *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
321 // Note: This is a very hot code path, so the code should be conditional on GENERATION template
322 // parameter where possible, in order to generate the most efficient code.
323
324 T o = RawAccess<>::oop_load(p);
325 if (!CompressedOops::is_null(o)) {
326 oop obj = CompressedOops::decode_not_null(o);
327
328 ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap();
329 shenandoah_assert_not_forwarded(p, obj);
330 shenandoah_assert_not_in_cset_except(p, obj, heap->cancelled_gc());
331 if (in_generation<GENERATION>(heap, obj)) {
332 mark_ref(q, mark_context, weak, obj);
333 shenandoah_assert_marked(p, obj);
334 if (GENERATION == YOUNG && heap->is_in_old(p)) {
335 // Mark card as dirty because remembered set scanning still finds interesting pointer.
336 heap->old_generation()->mark_card_as_dirty((HeapWord*)p);
337 } else if (GENERATION == GLOBAL && heap->is_in_old(p) && heap->is_in_young(obj)) {
338 // Mark card as dirty because GLOBAL marking finds interesting pointer.
339 heap->old_generation()->mark_card_as_dirty((HeapWord*)p);
340 }
341 } else if (old_q != nullptr) {
342 // Young mark, bootstrapping old_q or concurrent with old_q marking.
343 mark_ref(old_q, mark_context, weak, obj);
344 shenandoah_assert_marked(p, obj);
345 } else if (GENERATION == OLD) {
346 // Old mark, found a young pointer.
347 if (heap->is_in(p)) {
348 assert(heap->is_in_young(obj), "Expected young object.");
349 heap->old_generation()->mark_card_as_dirty(p);
350 }
351 }
352 }
353 }
354
355 template<>
356 ALWAYSINLINE
357 void ShenandoahMark::mark_through_ref<oop, ShenandoahGenerationType::NON_GEN>(oop *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
358 mark_non_generational_ref(p, q, mark_context, weak);
359 }
360
361 template<>
362 ALWAYSINLINE
363 void ShenandoahMark::mark_through_ref<narrowOop, ShenandoahGenerationType::NON_GEN>(narrowOop *p, ShenandoahObjToScanQueue* q, ShenandoahObjToScanQueue* old_q, ShenandoahMarkingContext* const mark_context, bool weak) {
364 mark_non_generational_ref(p, q, mark_context, weak);
365 }
366
367 template<class T>
368 void ShenandoahMark::mark_non_generational_ref(T* p, ShenandoahObjToScanQueue* q,
369 ShenandoahMarkingContext* const mark_context, bool weak) {
370 oop o = RawAccess<>::oop_load(p);
371 if (!CompressedOops::is_null(o)) {
372 oop obj = CompressedOops::decode_not_null(o);
373
374 shenandoah_assert_not_forwarded(p, obj);
375 shenandoah_assert_not_in_cset_except(p, obj, ShenandoahHeap::heap()->cancelled_gc());
376
377 mark_ref(q, mark_context, weak, obj);
378
379 shenandoah_assert_marked(p, obj);
380 }
381 }
382
383 inline void ShenandoahMark::mark_ref(ShenandoahObjToScanQueue* q,
384 ShenandoahMarkingContext* const mark_context,
385 bool weak, oop obj) {
386 bool skip_live = false;
387 bool marked;
388 if (weak) {
389 marked = mark_context->mark_weak(obj);
390 } else {
391 marked = mark_context->mark_strong(obj, /* was_upgraded = */ skip_live);
392 }
393 if (marked) {
394 ShenandoahPrefetch::prefetch(obj);
395 bool pushed = q->push(ShenandoahMarkTask(obj, skip_live, weak));
396 assert(pushed, "overflow queue should always succeed pushing");
397 }
398 }
399
400 ShenandoahObjToScanQueueSet* ShenandoahMark::task_queues() const {
401 return _task_queues;
402 }
403
404 ShenandoahObjToScanQueue* ShenandoahMark::get_queue(uint index) const {
405 return _task_queues->queue(index);
406 }
407
408 ShenandoahObjToScanQueue* ShenandoahMark::get_old_queue(uint index) const {
409 if (_old_gen_task_queues != nullptr) {
410 return _old_gen_task_queues->queue(index);
411 }
412 return nullptr;
413 }
414
415 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHMARK_INLINE_HPP