1 /*
   2  * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/codeCache.inline.hpp"
  29 #include "code/compiledMethod.inline.hpp"
  30 #include "code/vmreg.inline.hpp"
  31 #include "compiler/oopMap.inline.hpp"
  32 #include "gc/shared/continuationGCSupport.inline.hpp"
  33 #include "gc/shared/gc_globals.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/memAllocator.hpp"
  36 #include "gc/shared/threadLocalAllocBuffer.inline.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "jfr/jfrEvents.hpp"
  39 #include "logging/log.hpp"
  40 #include "logging/logStream.hpp"
  41 #include "oops/access.inline.hpp"
  42 #include "oops/method.inline.hpp"
  43 #include "oops/oopsHierarchy.hpp"
  44 #include "oops/objArrayOop.inline.hpp"
  45 #include "oops/stackChunkOop.inline.hpp"
  46 #include "prims/jvmtiThreadState.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/continuation.hpp"
  49 #include "runtime/continuationEntry.inline.hpp"
  50 #include "runtime/continuationHelper.inline.hpp"
  51 #include "runtime/continuationJavaClasses.inline.hpp"
  52 #include "runtime/continuationWrapper.inline.hpp"
  53 #include "runtime/frame.inline.hpp"
  54 #include "runtime/interfaceSupport.inline.hpp"
  55 #include "runtime/javaThread.inline.hpp"
  56 #include "runtime/jniHandles.inline.hpp"
  57 #include "runtime/keepStackGCProcessed.hpp"
  58 #include "runtime/orderAccess.hpp"
  59 #include "runtime/prefetch.inline.hpp"
  60 #include "runtime/smallRegisterMap.inline.hpp"
  61 #include "runtime/sharedRuntime.hpp"
  62 #include "runtime/stackChunkFrameStream.inline.hpp"
  63 #include "runtime/stackFrameStream.inline.hpp"
  64 #include "runtime/stackOverflow.hpp"
  65 #include "runtime/stackWatermarkSet.inline.hpp"
  66 #include "utilities/debug.hpp"
  67 #include "utilities/exceptions.hpp"
  68 #include "utilities/macros.hpp"
  69 #if INCLUDE_ZGC
  70 #include "gc/z/zStackChunkGCData.inline.hpp"
  71 #endif
  72 
  73 #include <type_traits>
  74 
  75 /*
  76  * This file contains the implementation of continuation freezing (yield) and thawing (run).
  77  *
  78  * This code is very latency-critical and very hot. An ordinary and well-behaved server application
  79  * would likely call these operations many thousands of times per second second, on every core.
  80  *
  81  * Freeze might be called every time the application performs any I/O operation, every time it
  82  * acquires a j.u.c. lock, every time it takes a message from a queue, and thaw can be called
  83  * multiple times in each of those cases, as it is called by the return barrier, which may be
  84  * invoked on method return.
  85  *
  86  * The amortized budget for each of those two operations is ~100-150ns. That is why, for
  87  * example, every effort is made to avoid Java-VM transitions as much as possible.
  88  *
  89  * On the fast path, all frames are known to be compiled, and the chunk requires no barriers
  90  * and so frames simply copied, and the bottom-most one is patched.
  91  * On the slow path, internal pointers in interpreted frames are de/relativized to/from offsets
  92  * and absolute pointers, and barriers invoked.
  93  */
  94 
  95 /************************************************
  96 
  97 Thread-stack layout on freeze/thaw.
  98 See corresponding stack-chunk layout in instanceStackChunkKlass.hpp
  99 
 100             +----------------------------+
 101             |      .                     |
 102             |      .                     |
 103             |      .                     |
 104             |   carrier frames           |
 105             |                            |
 106             |----------------------------|
 107             |                            |
 108             |    Continuation.run        |
 109             |                            |
 110             |============================|
 111             |    enterSpecial frame      |
 112             |  pc                        |
 113             |  rbp                       |
 114             |  -----                     |
 115         ^   |  int argsize               | = ContinuationEntry
 116         |   |  oopDesc* cont             |
 117         |   |  oopDesc* chunk            |
 118         |   |  ContinuationEntry* parent |
 119         |   |  ...                       |
 120         |   |============================| <------ JavaThread::_cont_entry = entry->sp()
 121         |   |  ? alignment word ?        |
 122         |   |----------------------------| <--\
 123         |   |                            |    |
 124         |   |  ? caller stack args ?     |    |   argsize (might not be 2-word aligned) words
 125 Address |   |                            |    |   Caller is still in the chunk.
 126         |   |----------------------------|    |
 127         |   |  pc (? return barrier ?)   |    |  This pc contains the return barrier when the bottom-most frame
 128         |   |  rbp                       |    |  isn't the last one in the continuation.
 129         |   |                            |    |
 130         |   |    frame                   |    |
 131         |   |                            |    |
 132             +----------------------------|     \__ Continuation frames to be frozen/thawed
 133             |                            |     /
 134             |    frame                   |    |
 135             |                            |    |
 136             |----------------------------|    |
 137             |                            |    |
 138             |    frame                   |    |
 139             |                            |    |
 140             |----------------------------| <--/
 141             |                            |
 142             |    doYield/safepoint stub  | When preempting forcefully, we could have a safepoint stub
 143             |                            | instead of a doYield stub
 144             |============================| <- the sp passed to freeze
 145             |                            |
 146             |  Native freeze/thaw frames |
 147             |      .                     |
 148             |      .                     |
 149             |      .                     |
 150             +----------------------------+
 151 
 152 ************************************************/
 153 
 154 static const bool TEST_THAW_ONE_CHUNK_FRAME = false; // force thawing frames one-at-a-time for testing
 155 
 156 #define CONT_JFR false // emit low-level JFR events that count slow/fast path for continuation performance debugging only
 157 #if CONT_JFR
 158   #define CONT_JFR_ONLY(code) code
 159 #else
 160   #define CONT_JFR_ONLY(code)
 161 #endif
 162 
 163 // TODO: See AbstractAssembler::generate_stack_overflow_check,
 164 // Compile::bang_size_in_bytes(), m->as_SafePoint()->jvms()->interpreter_frame_size()
 165 // when we stack-bang, we need to update a thread field with the lowest (farthest) bang point.
 166 
 167 // Data invariants are defined by Continuation::debug_verify_continuation and Continuation::debug_verify_stack_chunk
 168 
 169 // Used to just annotatate cold/hot branches
 170 #define LIKELY(condition)   (condition)
 171 #define UNLIKELY(condition) (condition)
 172 
 173 // debugging functions
 174 #ifdef ASSERT
 175 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue); // address p is readable and *(intptr_t*)p != errvalue
 176 
 177 static void verify_continuation(oop continuation) { Continuation::debug_verify_continuation(continuation); }
 178 
 179 static void do_deopt_after_thaw(JavaThread* thread);
 180 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st);
 181 static void log_frames(JavaThread* thread);
 182 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st = tty);
 183 
 184 #define assert_pfl(p, ...) \
 185 do {                                           \
 186   if (!(p)) {                                  \
 187     JavaThread* t = JavaThread::active();      \
 188     if (t->has_last_Java_frame()) {            \
 189       tty->print_cr("assert(" #p ") failed:"); \
 190       t->print_frame_layout();                 \
 191     }                                          \
 192   }                                            \
 193   vmassert(p, __VA_ARGS__);                    \
 194 } while(0)
 195 
 196 #else
 197 static void verify_continuation(oop continuation) { }
 198 #define assert_pfl(p, ...)
 199 #endif
 200 
 201 // should match Continuation.preemptStatus() in Continuation.java
 202 enum freeze_result {
 203   freeze_ok = 0,
 204   freeze_ok_bottom = 1,
 205   freeze_pinned_cs = 2,
 206   freeze_pinned_native = 3,
 207   freeze_pinned_monitor = 4,
 208   freeze_exception = 5
 209 };
 210 
 211 const char* freeze_result_names[6] = {
 212   "freeze_ok",
 213   "freeze_ok_bottom",
 214   "freeze_pinned_cs",
 215   "freeze_pinned_native",
 216   "freeze_pinned_monitor",
 217   "freeze_exception"
 218 };
 219 
 220 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint);
 221 template<typename ConfigT> static inline int freeze_internal(JavaThread* current, intptr_t* const sp);
 222 
 223 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier);
 224 template<typename ConfigT> static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind);
 225 
 226 
 227 // Entry point to freeze. Transitions are handled manually
 228 // Called from gen_continuation_yield() in sharedRuntime_<cpu>.cpp through Continuation::freeze_entry();
 229 template<typename ConfigT>
 230 static JRT_BLOCK_ENTRY(int, freeze(JavaThread* current, intptr_t* sp))
 231   assert(sp == current->frame_anchor()->last_Java_sp(), "");
 232 
 233   if (current->raw_cont_fastpath() > current->last_continuation()->entry_sp() || current->raw_cont_fastpath() < sp) {
 234     current->set_cont_fastpath(nullptr);
 235   }
 236 
 237   return ConfigT::freeze(current, sp);
 238 JRT_END
 239 
 240 JRT_LEAF(int, Continuation::prepare_thaw(JavaThread* thread, bool return_barrier))
 241   return prepare_thaw_internal(thread, return_barrier);
 242 JRT_END
 243 
 244 template<typename ConfigT>
 245 static JRT_LEAF(intptr_t*, thaw(JavaThread* thread, int kind))
 246   // TODO: JRT_LEAF and NoHandleMark is problematic for JFR events.
 247   // vFrameStreamCommon allocates Handles in RegisterMap for continuations.
 248   // JRT_ENTRY instead?
 249   ResetNoHandleMark rnhm;
 250 
 251   // we might modify the code cache via BarrierSetNMethod::nmethod_entry_barrier
 252   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
 253   return ConfigT::thaw(thread, (Continuation::thaw_kind)kind);
 254 JRT_END
 255 
 256 JVM_ENTRY(jint, CONT_isPinned0(JNIEnv* env, jobject cont_scope)) {
 257   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
 258   return is_pinned0(thread, JNIHandles::resolve(cont_scope), false);
 259 }
 260 JVM_END
 261 
 262 ///////////
 263 
 264 enum class oop_kind { NARROW, WIDE };
 265 template <oop_kind oops, typename BarrierSetT>
 266 class Config {
 267 public:
 268   typedef Config<oops, BarrierSetT> SelfT;
 269   using OopT = std::conditional_t<oops == oop_kind::NARROW, narrowOop, oop>;
 270 
 271   static int freeze(JavaThread* thread, intptr_t* const sp) {
 272     return freeze_internal<SelfT>(thread, sp);
 273   }
 274 
 275   static intptr_t* thaw(JavaThread* thread, Continuation::thaw_kind kind) {
 276     return thaw_internal<SelfT>(thread, kind);
 277   }
 278 };
 279 
 280 static bool stack_overflow_check(JavaThread* thread, size_t size, address sp) {
 281   const size_t page_size = os::vm_page_size();
 282   if (size > page_size) {
 283     if (sp - size < thread->stack_overflow_state()->shadow_zone_safe_limit()) {
 284       return false;
 285     }
 286   }
 287   return true;
 288 }
 289 
 290 #ifdef ASSERT
 291 static oop get_continuation(JavaThread* thread) {
 292   assert(thread != nullptr, "");
 293   assert(thread->threadObj() != nullptr, "");
 294   return java_lang_Thread::continuation(thread->threadObj());
 295 }
 296 
 297 inline void clear_anchor(JavaThread* thread) {
 298   thread->frame_anchor()->clear();
 299 }
 300 
 301 static void set_anchor(JavaThread* thread, intptr_t* sp) {
 302   address pc = *(address*)(sp - frame::sender_sp_ret_address_offset());
 303   assert(pc != nullptr, "");
 304 
 305   JavaFrameAnchor* anchor = thread->frame_anchor();
 306   anchor->set_last_Java_sp(sp);
 307   anchor->set_last_Java_pc(pc);
 308   ContinuationHelper::set_anchor_pd(anchor, sp);
 309 
 310   assert(thread->has_last_Java_frame(), "");
 311   assert(thread->last_frame().cb() != nullptr, "");
 312 }
 313 #endif // ASSERT
 314 
 315 static void set_anchor_to_entry(JavaThread* thread, ContinuationEntry* entry) {
 316   JavaFrameAnchor* anchor = thread->frame_anchor();
 317   anchor->set_last_Java_sp(entry->entry_sp());
 318   anchor->set_last_Java_pc(entry->entry_pc());
 319   ContinuationHelper::set_anchor_to_entry_pd(anchor, entry);
 320 
 321   assert(thread->has_last_Java_frame(), "");
 322   assert(thread->last_frame().cb() != nullptr, "");
 323 }
 324 
 325 #if CONT_JFR
 326 class FreezeThawJfrInfo : public StackObj {
 327   short _e_size;
 328   short _e_num_interpreted_frames;
 329  public:
 330 
 331   FreezeThawJfrInfo() : _e_size(0), _e_num_interpreted_frames(0) {}
 332   inline void record_interpreted_frame() { _e_num_interpreted_frames++; }
 333   inline void record_size_copied(int size) { _e_size += size << LogBytesPerWord; }
 334   template<typename Event> void post_jfr_event(Event *e, oop continuation, JavaThread* jt);
 335 };
 336 
 337 template<typename Event> void FreezeThawJfrInfo::post_jfr_event(Event* e, oop continuation, JavaThread* jt) {
 338   if (e->should_commit()) {
 339     log_develop_trace(continuations)("JFR event: iframes: %d size: %d", _e_num_interpreted_frames, _e_size);
 340     e->set_carrierThread(JFR_JVM_THREAD_ID(jt));
 341     e->set_continuationClass(continuation->klass());
 342     e->set_interpretedFrames(_e_num_interpreted_frames);
 343     e->set_size(_e_size);
 344     e->commit();
 345   }
 346 }
 347 #endif // CONT_JFR
 348 
 349 /////////////// FREEZE ////
 350 
 351 class FreezeBase : public StackObj {
 352 protected:
 353   JavaThread* const _thread;
 354   ContinuationWrapper& _cont;
 355   bool _barriers; // only set when we allocate a chunk
 356   const bool _preempt; // used only on the slow path
 357   const intptr_t * const _frame_sp; // Top frame sp for this freeze
 358 
 359   intptr_t* _bottom_address;
 360 
 361   int _freeze_size; // total size of all frames plus metadata in words.
 362   int _total_align_size;
 363 
 364   intptr_t* _cont_stack_top;
 365   intptr_t* _cont_stack_bottom;
 366 
 367   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
 368 
 369 #ifdef ASSERT
 370   intptr_t* _orig_chunk_sp;
 371   int _fast_freeze_size;
 372   bool _empty;
 373 #endif
 374 
 375   JvmtiSampledObjectAllocEventCollector* _jvmti_event_collector;
 376 
 377   NOT_PRODUCT(int _frames;)
 378   DEBUG_ONLY(intptr_t* _last_write;)
 379 
 380   inline FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp);
 381 
 382 public:
 383   NOINLINE freeze_result freeze_slow();
 384   void freeze_fast_existing_chunk();
 385 
 386   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
 387   void set_jvmti_event_collector(JvmtiSampledObjectAllocEventCollector* jsoaec) { _jvmti_event_collector = jsoaec; }
 388 
 389   inline int size_if_fast_freeze_available();
 390 
 391 #ifdef ASSERT
 392   bool interpreted_native_or_deoptimized_on_stack();
 393 #endif
 394 
 395 protected:
 396   inline void init_rest();
 397   void throw_stack_overflow_on_humongous_chunk();
 398 
 399   // fast path
 400   inline void copy_to_chunk(intptr_t* from, intptr_t* to, int size);
 401   inline void unwind_frames();
 402   inline void patch_stack_pd(intptr_t* frame_sp, intptr_t* heap_sp);
 403 
 404   // slow path
 405   virtual stackChunkOop allocate_chunk_slow(size_t stack_size) = 0;
 406 
 407   int cont_size() { return _cont_stack_bottom - _cont_stack_top; }
 408 
 409 private:
 410   // slow path
 411   frame freeze_start_frame();
 412   frame freeze_start_frame_safepoint_stub(frame f);
 413   NOINLINE freeze_result recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top);
 414   inline frame freeze_start_frame_yield_stub(frame f);
 415   template<typename FKind>
 416   inline freeze_result recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize);
 417   inline void before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame);
 418   inline void after_freeze_java_frame(const frame& hf, bool is_bottom_frame);
 419   freeze_result finalize_freeze(const frame& callee, frame& caller, int argsize);
 420   void patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame);
 421   NOINLINE freeze_result recurse_freeze_interpreted_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 422   freeze_result recurse_freeze_compiled_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 423   NOINLINE freeze_result recurse_freeze_stub_frame(frame& f, frame& caller);
 424   NOINLINE void finish_freeze(const frame& f, const frame& top);
 425 
 426   inline bool stack_overflow();
 427 
 428   static frame sender(const frame& f) { return f.is_interpreted_frame() ? sender<ContinuationHelper::InterpretedFrame>(f)
 429                                                                         : sender<ContinuationHelper::NonInterpretedUnknownFrame>(f); }
 430   template<typename FKind> static inline frame sender(const frame& f);
 431   template<typename FKind> frame new_heap_frame(frame& f, frame& caller);
 432   inline void set_top_frame_metadata_pd(const frame& hf);
 433   inline void patch_pd(frame& callee, const frame& caller);
 434   void adjust_interpreted_frame_unextended_sp(frame& f);
 435   static inline void relativize_interpreted_frame_metadata(const frame& f, const frame& hf);
 436 
 437 protected:
 438   void freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated));
 439   bool freeze_fast_new_chunk(stackChunkOop chunk);
 440 
 441 #ifdef ASSERT
 442   bool is_empty(stackChunkOop chunk) {
 443     // during freeze, the chunk is in an intermediate state (after setting the chunk's argsize but before setting its
 444     // ultimate sp) so we use this instead of stackChunkOopDesc::is_empty
 445     return chunk->sp() >= chunk->stack_size() - chunk->argsize() - frame::metadata_words_at_top;
 446   }
 447 #endif
 448 };
 449 
 450 template <typename ConfigT>
 451 class Freeze : public FreezeBase {
 452 private:
 453   stackChunkOop allocate_chunk(size_t stack_size);
 454 
 455 public:
 456   inline Freeze(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp)
 457     : FreezeBase(thread, cont, frame_sp) {}
 458 
 459   freeze_result try_freeze_fast();
 460 
 461 protected:
 462   virtual stackChunkOop allocate_chunk_slow(size_t stack_size) override { return allocate_chunk(stack_size); }
 463 };
 464 
 465 FreezeBase::FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp) :
 466     _thread(thread), _cont(cont), _barriers(false), _preempt(false), _frame_sp(frame_sp) {
 467   DEBUG_ONLY(_jvmti_event_collector = nullptr;)
 468 
 469   assert(_thread != nullptr, "");
 470   assert(_thread->last_continuation()->entry_sp() == _cont.entrySP(), "");
 471 
 472   DEBUG_ONLY(_cont.entry()->verify_cookie();)
 473 
 474   assert(!Interpreter::contains(_cont.entryPC()), "");
 475 
 476   _bottom_address = _cont.entrySP() - _cont.entry_frame_extension();
 477 #ifdef _LP64
 478   if (((intptr_t)_bottom_address & 0xf) != 0) {
 479     _bottom_address--;
 480   }
 481   assert(is_aligned(_bottom_address, frame::frame_alignment), "");
 482 #endif
 483 
 484   log_develop_trace(continuations)("bottom_address: " INTPTR_FORMAT " entrySP: " INTPTR_FORMAT " argsize: " PTR_FORMAT,
 485                 p2i(_bottom_address), p2i(_cont.entrySP()), (_cont.entrySP() - _bottom_address) << LogBytesPerWord);
 486   assert(_bottom_address != nullptr, "");
 487   assert(_bottom_address <= _cont.entrySP(), "");
 488   DEBUG_ONLY(_last_write = nullptr;)
 489 
 490   assert(_cont.chunk_invariant(), "");
 491   assert(!Interpreter::contains(_cont.entryPC()), "");
 492 #if !defined(PPC64) || defined(ZERO)
 493   static const int doYield_stub_frame_size = frame::metadata_words;
 494 #else
 495   static const int doYield_stub_frame_size = frame::native_abi_reg_args_size >> LogBytesPerWord;
 496 #endif
 497   assert(SharedRuntime::cont_doYield_stub()->frame_size() == doYield_stub_frame_size, "");
 498 
 499   // properties of the continuation on the stack; all sizes are in words
 500   _cont_stack_top    = frame_sp + doYield_stub_frame_size; // we don't freeze the doYield stub frame
 501   _cont_stack_bottom = _cont.entrySP() + (_cont.argsize() == 0 ? frame::metadata_words_at_top : 0)
 502       - ContinuationHelper::frame_align_words(_cont.argsize()); // see alignment in thaw
 503 
 504   log_develop_trace(continuations)("freeze size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 505     cont_size(), _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 506   assert(cont_size() > 0, "");
 507 }
 508 
 509 void FreezeBase::init_rest() { // we want to postpone some initialization after chunk handling
 510   _freeze_size = 0;
 511   _total_align_size = 0;
 512   NOT_PRODUCT(_frames = 0;)
 513 }
 514 
 515 void FreezeBase::copy_to_chunk(intptr_t* from, intptr_t* to, int size) {
 516   stackChunkOop chunk = _cont.tail();
 517   chunk->copy_from_stack_to_chunk(from, to, size);
 518   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
 519 
 520 #ifdef ASSERT
 521   if (_last_write != nullptr) {
 522     assert(_last_write == to + size, "Missed a spot: _last_write: " INTPTR_FORMAT " to+size: " INTPTR_FORMAT
 523         " stack_size: %d _last_write offset: " PTR_FORMAT " to+size: " PTR_FORMAT, p2i(_last_write), p2i(to+size),
 524         chunk->stack_size(), _last_write-chunk->start_address(), to+size-chunk->start_address());
 525     _last_write = to;
 526   }
 527 #endif
 528 }
 529 
 530 // Called _after_ the last possible safepoint during the freeze operation (chunk allocation)
 531 void FreezeBase::unwind_frames() {
 532   ContinuationEntry* entry = _cont.entry();
 533   entry->flush_stack_processing(_thread);
 534   set_anchor_to_entry(_thread, entry);
 535 }
 536 
 537 template <typename ConfigT>
 538 freeze_result Freeze<ConfigT>::try_freeze_fast() {
 539   assert(_thread->thread_state() == _thread_in_vm, "");
 540   assert(_thread->cont_fastpath(), "");
 541 
 542   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 543   assert(_fast_freeze_size == 0, "");
 544 
 545   stackChunkOop chunk = allocate_chunk(cont_size() + frame::metadata_words);
 546   if (freeze_fast_new_chunk(chunk)) {
 547     return freeze_ok;
 548   }
 549   if (_thread->has_pending_exception()) {
 550     return freeze_exception;
 551   }
 552 
 553   // TODO R REMOVE when deopt change is fixed
 554   assert(!_thread->cont_fastpath() || _barriers, "");
 555   log_develop_trace(continuations)("-- RETRYING SLOW --");
 556   return freeze_slow();
 557 }
 558 
 559 // Returns size needed if the continuation fits, otherwise 0.
 560 int FreezeBase::size_if_fast_freeze_available() {
 561   stackChunkOop chunk = _cont.tail();
 562   if (chunk == nullptr || chunk->is_gc_mode() || chunk->requires_barriers() || chunk->has_mixed_frames()) {
 563     log_develop_trace(continuations)("chunk available %s", chunk == nullptr ? "no chunk" : "chunk requires barriers");
 564     return 0;
 565   }
 566 
 567   int total_size_needed = cont_size();
 568   const int chunk_sp = chunk->sp();
 569 
 570   // argsize can be nonzero if we have a caller, but the caller could be in a non-empty parent chunk,
 571   // so we subtract it only if we overlap with the caller, i.e. the current chunk isn't empty.
 572   // Consider leaving the chunk's argsize set when emptying it and removing the following branch,
 573   // although that would require changing stackChunkOopDesc::is_empty
 574   if (chunk_sp < chunk->stack_size()) {
 575     total_size_needed -= _cont.argsize() + frame::metadata_words_at_top;
 576   }
 577 
 578   int chunk_free_room = chunk_sp - frame::metadata_words_at_bottom;
 579   bool available = chunk_free_room >= total_size_needed;
 580   log_develop_trace(continuations)("chunk available: %s size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 581     available ? "yes" : "no" , total_size_needed, _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 582   return available ? total_size_needed : 0;
 583 }
 584 
 585 void FreezeBase::freeze_fast_existing_chunk() {
 586   stackChunkOop chunk = _cont.tail();
 587   DEBUG_ONLY(_orig_chunk_sp = chunk->sp_address();)
 588 
 589   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 590   assert(_fast_freeze_size > 0, "");
 591 
 592   if (chunk->sp() < chunk->stack_size()) { // we are copying into a non-empty chunk
 593     DEBUG_ONLY(_empty = false;)
 594     assert(chunk->sp() < (chunk->stack_size() - chunk->argsize()), "");
 595     assert(*(address*)(chunk->sp_address() - frame::sender_sp_ret_address_offset()) == chunk->pc(), "");
 596 
 597     // the chunk's sp before the freeze, adjusted to point beyond the stack-passed arguments in the topmost frame
 598     // we overlap; we'll overwrite the chunk's top frame's callee arguments
 599     const int chunk_start_sp = chunk->sp() + _cont.argsize() + frame::metadata_words_at_top;
 600     assert(chunk_start_sp <= chunk->stack_size(), "sp not pointing into stack");
 601 
 602     // increase max_size by what we're freezing minus the overlap
 603     chunk->set_max_thawing_size(chunk->max_thawing_size() + cont_size() - _cont.argsize() - frame::metadata_words_at_top);
 604 
 605     intptr_t* const bottom_sp = _cont_stack_bottom - _cont.argsize() - frame::metadata_words_at_top;
 606     assert(bottom_sp == _bottom_address, "");
 607     // Because the chunk isn't empty, we know there's a caller in the chunk, therefore the bottom-most frame
 608     // should have a return barrier (installed back when we thawed it).
 609     assert(*(address*)(bottom_sp-frame::sender_sp_ret_address_offset()) == StubRoutines::cont_returnBarrier(),
 610            "should be the continuation return barrier");
 611     // We copy the fp from the chunk back to the stack because it contains some caller data,
 612     // including, possibly, an oop that might have gone stale since we thawed.
 613     patch_stack_pd(bottom_sp, chunk->sp_address());
 614     // we don't patch the return pc at this time, so as not to make the stack unwalkable for async walks
 615 
 616     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 617   } else { // the chunk is empty
 618     DEBUG_ONLY(_empty = true;)
 619     const int chunk_start_sp = chunk->sp();
 620 
 621     assert(chunk_start_sp == chunk->stack_size(), "");
 622 
 623     chunk->set_max_thawing_size(cont_size());
 624     chunk->set_argsize(_cont.argsize());
 625 
 626     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 627   }
 628 }
 629 
 630 bool FreezeBase::freeze_fast_new_chunk(stackChunkOop chunk) {
 631   DEBUG_ONLY(_empty = true;)
 632 
 633   // Install new chunk
 634   _cont.set_tail(chunk);
 635 
 636   if (UNLIKELY(chunk == nullptr || !_thread->cont_fastpath() || _barriers)) { // OOME/probably humongous
 637     log_develop_trace(continuations)("Retrying slow. Barriers: %d", _barriers);
 638     return false;
 639   }
 640 
 641   chunk->set_max_thawing_size(cont_size());
 642   chunk->set_argsize(_cont.argsize());
 643 
 644   // in a fresh chunk, we freeze *with* the bottom-most frame's stack arguments.
 645   // They'll then be stored twice: in the chunk and in the parent chunk's top frame
 646   const int chunk_start_sp = cont_size() + frame::metadata_words;
 647   assert(chunk_start_sp == chunk->stack_size(), "");
 648 
 649   DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
 650 
 651   freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA true));
 652 
 653   return true;
 654 }
 655 
 656 void FreezeBase::freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated)) {
 657   assert(chunk != nullptr, "");
 658   assert(!chunk->has_mixed_frames(), "");
 659   assert(!chunk->is_gc_mode(), "");
 660   assert(!chunk->has_bitmap(), "");
 661   assert(!chunk->requires_barriers(), "");
 662   assert(chunk == _cont.tail(), "");
 663 
 664   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
 665   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
 666   // will either see no continuation on the stack, or a consistent chunk.
 667   unwind_frames();
 668 
 669   log_develop_trace(continuations)("freeze_fast start: chunk " INTPTR_FORMAT " size: %d orig sp: %d argsize: %d",
 670     p2i((oopDesc*)chunk), chunk->stack_size(), chunk_start_sp, _cont.argsize());
 671   assert(chunk_start_sp <= chunk->stack_size(), "");
 672   assert(chunk_start_sp >= cont_size(), "no room in the chunk");
 673 
 674   const int chunk_new_sp = chunk_start_sp - cont_size(); // the chunk's new sp, after freeze
 675   assert(!(_fast_freeze_size > 0) || _orig_chunk_sp - (chunk->start_address() + chunk_new_sp) == _fast_freeze_size, "");
 676 
 677   intptr_t* chunk_top = chunk->start_address() + chunk_new_sp;
 678   assert(_empty || *(address*)(_orig_chunk_sp - frame::sender_sp_ret_address_offset()) == chunk->pc(), "");
 679 
 680   log_develop_trace(continuations)("freeze_fast start: " INTPTR_FORMAT " sp: %d chunk_top: " INTPTR_FORMAT,
 681                               p2i(chunk->start_address()), chunk_new_sp, p2i(chunk_top));
 682   intptr_t* from = _cont_stack_top - frame::metadata_words_at_bottom;
 683   intptr_t* to   = chunk_top - frame::metadata_words_at_bottom;
 684   copy_to_chunk(from, to, cont_size() + frame::metadata_words_at_bottom);
 685   // Because we're not patched yet, the chunk is now in a bad state
 686 
 687   // patch return pc of the bottom-most frozen frame (now in the chunk) with the actual caller's return address
 688   intptr_t* chunk_bottom_sp = chunk_top + cont_size() - _cont.argsize() - frame::metadata_words_at_top;
 689   assert(_empty || *(address*)(chunk_bottom_sp-frame::sender_sp_ret_address_offset()) == StubRoutines::cont_returnBarrier(), "");
 690   *(address*)(chunk_bottom_sp - frame::sender_sp_ret_address_offset()) = chunk->pc();
 691 
 692   // We're always writing to a young chunk, so the GC can't see it until the next safepoint.
 693   chunk->set_sp(chunk_new_sp);
 694   // set chunk->pc to the return address of the topmost frame in the chunk
 695   chunk->set_pc(*(address*)(_cont_stack_top - frame::sender_sp_ret_address_offset()));
 696 
 697   _cont.write();
 698 
 699   log_develop_trace(continuations)("FREEZE CHUNK #" INTPTR_FORMAT " (young)", _cont.hash());
 700   LogTarget(Trace, continuations) lt;
 701   if (lt.develop_is_enabled()) {
 702     LogStream ls(lt);
 703     chunk->print_on(true, &ls);
 704   }
 705 
 706   // Verification
 707   assert(_cont.chunk_invariant(), "");
 708   chunk->verify();
 709 
 710 #if CONT_JFR
 711   EventContinuationFreezeFast e;
 712   if (e.should_commit()) {
 713     e.set_id(cast_from_oop<u8>(chunk));
 714     DEBUG_ONLY(e.set_allocate(chunk_is_allocated);)
 715     e.set_size(cont_size() << LogBytesPerWord);
 716     e.commit();
 717   }
 718 #endif
 719 }
 720 
 721 NOINLINE freeze_result FreezeBase::freeze_slow() {
 722 #ifdef ASSERT
 723   ResourceMark rm;
 724 #endif
 725 
 726   log_develop_trace(continuations)("freeze_slow  #" INTPTR_FORMAT, _cont.hash());
 727   assert(_thread->thread_state() == _thread_in_vm || _thread->thread_state() == _thread_blocked, "");
 728 
 729 #if CONT_JFR
 730   EventContinuationFreezeSlow e;
 731   if (e.should_commit()) {
 732     e.set_id(cast_from_oop<u8>(_cont.continuation()));
 733     e.commit();
 734   }
 735 #endif
 736 
 737   init_rest();
 738 
 739   HandleMark hm(Thread::current());
 740 
 741   frame f = freeze_start_frame();
 742 
 743   LogTarget(Debug, continuations) lt;
 744   if (lt.develop_is_enabled()) {
 745     LogStream ls(lt);
 746     f.print_on(&ls);
 747   }
 748 
 749   frame caller; // the frozen caller in the chunk
 750   freeze_result res = recurse_freeze(f, caller, 0, false, true);
 751 
 752   if (res == freeze_ok) {
 753     finish_freeze(f, caller);
 754     _cont.write();
 755   }
 756 
 757   return res;
 758 }
 759 
 760 frame FreezeBase::freeze_start_frame() {
 761   frame f = _thread->last_frame();
 762   if (LIKELY(!_preempt)) {
 763     return freeze_start_frame_yield_stub(f);
 764   } else {
 765     return freeze_start_frame_safepoint_stub(f);
 766   }
 767 }
 768 
 769 frame FreezeBase::freeze_start_frame_yield_stub(frame f) {
 770   assert(SharedRuntime::cont_doYield_stub()->contains(f.pc()), "must be");
 771   f = sender<ContinuationHelper::NonInterpretedUnknownFrame>(f);
 772   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), f), "");
 773   return f;
 774 }
 775 
 776 frame FreezeBase::freeze_start_frame_safepoint_stub(frame f) {
 777 #if (defined(X86) || defined(AARCH64) || defined(RISCV64)) && !defined(ZERO)
 778   f.set_fp(f.real_fp()); // f.set_fp(*Frame::callee_link_address(f)); // ????
 779 #else
 780   Unimplemented();
 781 #endif
 782   if (!Interpreter::contains(f.pc())) {
 783     assert(ContinuationHelper::Frame::is_stub(f.cb()), "must be");
 784     assert(f.oop_map() != nullptr, "must be");
 785 
 786     if (Interpreter::contains(ContinuationHelper::StubFrame::return_pc(f))) {
 787       f = sender<ContinuationHelper::StubFrame>(f); // Safepoint stub in interpreter
 788     }
 789   }
 790   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), f), "");
 791   return f;
 792 }
 793 
 794 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
 795 NOINLINE freeze_result FreezeBase::recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top) {
 796   assert(f.unextended_sp() < _bottom_address, ""); // see recurse_freeze_java_frame
 797   assert(f.is_interpreted_frame() || ((top && _preempt) == ContinuationHelper::Frame::is_stub(f.cb())), "");
 798 
 799   if (stack_overflow()) {
 800     return freeze_exception;
 801   }
 802 
 803   if (f.is_compiled_frame()) {
 804     if (UNLIKELY(f.oop_map() == nullptr)) {
 805       // special native frame
 806       return freeze_pinned_native;
 807     }
 808     return recurse_freeze_compiled_frame(f, caller, callee_argsize, callee_interpreted);
 809   } else if (f.is_interpreted_frame()) {
 810     assert((_preempt && top) || !f.interpreter_frame_method()->is_native(), "");
 811     if (_preempt && top && f.interpreter_frame_method()->is_native()) {
 812       // int native entry
 813       return freeze_pinned_native;
 814     }
 815 
 816     return recurse_freeze_interpreted_frame(f, caller, callee_argsize, callee_interpreted);
 817   } else if (_preempt && top && ContinuationHelper::Frame::is_stub(f.cb())) {
 818     return recurse_freeze_stub_frame(f, caller);
 819   } else {
 820     return freeze_pinned_native;
 821   }
 822 }
 823 
 824 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
 825 // See also StackChunkFrameStream<frame_kind>::frame_size()
 826 template<typename FKind>
 827 inline freeze_result FreezeBase::recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize) {
 828   assert(FKind::is_instance(f), "");
 829 
 830   assert(fsize > 0, "");
 831   assert(argsize >= 0, "");
 832   _freeze_size += fsize;
 833   NOT_PRODUCT(_frames++;)
 834 
 835   assert(FKind::frame_bottom(f) <= _bottom_address, "");
 836 
 837   // We don't use FKind::frame_bottom(f) == _bottom_address because on x64 there's sometimes an extra word between
 838   // enterSpecial and an interpreted frame
 839   if (FKind::frame_bottom(f) >= _bottom_address - 1) {
 840     return finalize_freeze(f, caller, argsize); // recursion end
 841   } else {
 842     frame senderf = sender<FKind>(f);
 843     assert(FKind::interpreted || senderf.sp() == senderf.unextended_sp(), "");
 844     freeze_result result = recurse_freeze(senderf, caller, argsize, FKind::interpreted, false); // recursive call
 845     return result;
 846   }
 847 }
 848 
 849 inline void FreezeBase::before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame) {
 850   LogTarget(Trace, continuations) lt;
 851   if (lt.develop_is_enabled()) {
 852     LogStream ls(lt);
 853     ls.print_cr("======== FREEZING FRAME interpreted: %d bottom: %d", f.is_interpreted_frame(), is_bottom_frame);
 854     ls.print_cr("fsize: %d argsize: %d", fsize, argsize);
 855     f.print_value_on(&ls, nullptr);
 856   }
 857   assert(caller.is_interpreted_frame() == Interpreter::contains(caller.pc()), "");
 858 }
 859 
 860 inline void FreezeBase::after_freeze_java_frame(const frame& hf, bool is_bottom_frame) {
 861   LogTarget(Trace, continuations) lt;
 862   if (lt.develop_is_enabled()) {
 863     LogStream ls(lt);
 864     DEBUG_ONLY(hf.print_value_on(&ls, nullptr);)
 865     assert(hf.is_heap_frame(), "should be");
 866     DEBUG_ONLY(print_frame_layout(hf, false, &ls);)
 867     if (is_bottom_frame) {
 868       ls.print_cr("bottom h-frame:");
 869       hf.print_on(&ls);
 870     }
 871   }
 872 }
 873 
 874 // The parameter argsize_md includes metadata that has to be part of caller/callee overlap.
 875 // See also StackChunkFrameStream<frame_kind>::frame_size()
 876 freeze_result FreezeBase::finalize_freeze(const frame& callee, frame& caller, int argsize_md) {
 877   int argsize = argsize_md - frame::metadata_words_at_top;
 878   assert(callee.is_interpreted_frame()
 879     || callee.cb()->as_nmethod()->is_osr_method()
 880     || argsize == _cont.argsize(), "argsize: %d cont.argsize: %d", argsize, _cont.argsize());
 881   log_develop_trace(continuations)("bottom: " INTPTR_FORMAT " count %d size: %d argsize: %d",
 882     p2i(_bottom_address), _frames, _freeze_size << LogBytesPerWord, argsize);
 883 
 884   LogTarget(Trace, continuations) lt;
 885 
 886 #ifdef ASSERT
 887   bool empty = _cont.is_empty();
 888   log_develop_trace(continuations)("empty: %d", empty);
 889 #endif
 890 
 891   stackChunkOop chunk = _cont.tail();
 892 
 893   assert(chunk == nullptr || (chunk->max_thawing_size() == 0) == chunk->is_empty(), "");
 894 
 895   _freeze_size += frame::metadata_words; // for top frame's metadata
 896 
 897   int overlap = 0; // the args overlap the caller -- if there is one in this chunk and is of the same kind
 898   int unextended_sp = -1;
 899   if (chunk != nullptr) {
 900     unextended_sp = chunk->sp();
 901     if (!chunk->is_empty()) {
 902       StackChunkFrameStream<ChunkFrames::Mixed> last(chunk);
 903       unextended_sp = chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp());
 904       bool top_interpreted = Interpreter::contains(chunk->pc());
 905       if (callee.is_interpreted_frame() == top_interpreted) {
 906         overlap = argsize_md;
 907       }
 908     }
 909   }
 910 
 911   log_develop_trace(continuations)("finalize _size: %d overlap: %d unextended_sp: %d", _freeze_size, overlap, unextended_sp);
 912 
 913   _freeze_size -= overlap;
 914   assert(_freeze_size >= 0, "");
 915 
 916   assert(chunk == nullptr || chunk->is_empty()
 917           || unextended_sp == chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp()), "");
 918   assert(chunk != nullptr || unextended_sp < _freeze_size, "");
 919 
 920   // _barriers can be set to true by an allocation in freeze_fast, in which case the chunk is available
 921   bool allocated_old_in_freeze_fast = _barriers;
 922   assert(!allocated_old_in_freeze_fast || (unextended_sp >= _freeze_size && chunk->is_empty()),
 923     "Chunk allocated in freeze_fast is of insufficient size "
 924     "unextended_sp: %d size: %d is_empty: %d", unextended_sp, _freeze_size, chunk->is_empty());
 925   assert(!allocated_old_in_freeze_fast || (!UseZGC && !UseG1GC), "Unexpected allocation");
 926 
 927   DEBUG_ONLY(bool empty_chunk = true);
 928   if (unextended_sp < _freeze_size || chunk->is_gc_mode() || (!allocated_old_in_freeze_fast && chunk->requires_barriers())) {
 929     // ALLOCATE NEW CHUNK
 930 
 931     if (lt.develop_is_enabled()) {
 932       LogStream ls(lt);
 933       if (chunk == nullptr) {
 934         ls.print_cr("no chunk");
 935       } else {
 936         ls.print_cr("chunk barriers: %d _size: %d free size: %d",
 937           chunk->requires_barriers(), _freeze_size, chunk->sp() - frame::metadata_words);
 938         chunk->print_on(&ls);
 939       }
 940     }
 941 
 942     _freeze_size += overlap; // we're allocating a new chunk, so no overlap
 943     // overlap = 0;
 944 
 945     chunk = allocate_chunk_slow(_freeze_size);
 946     if (chunk == nullptr) {
 947       return freeze_exception;
 948     }
 949 
 950     // Install new chunk
 951     _cont.set_tail(chunk);
 952 
 953     int sp = chunk->stack_size() - argsize_md;
 954     chunk->set_sp(sp);
 955     chunk->set_argsize(argsize);
 956     assert(is_empty(chunk), "");
 957   } else {
 958     // REUSE EXISTING CHUNK
 959     log_develop_trace(continuations)("Reusing chunk mixed: %d empty: %d", chunk->has_mixed_frames(), chunk->is_empty());
 960     if (chunk->is_empty()) {
 961       int sp = chunk->stack_size() - argsize_md;
 962       chunk->set_sp(sp);
 963       chunk->set_argsize(argsize);
 964       _freeze_size += overlap;
 965       assert(chunk->max_thawing_size() == 0, "");
 966     } DEBUG_ONLY(else empty_chunk = false;)
 967   }
 968   assert(!chunk->is_gc_mode(), "");
 969   assert(!chunk->has_bitmap(), "");
 970   chunk->set_has_mixed_frames(true);
 971 
 972   assert(chunk->requires_barriers() == _barriers, "");
 973   assert(!_barriers || is_empty(chunk), "");
 974 
 975   assert(!is_empty(chunk) || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).is_done(), "");
 976   assert(!is_empty(chunk) || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame().is_empty(), "");
 977 
 978   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
 979   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
 980   // will either see no continuation or a consistent chunk.
 981   unwind_frames();
 982 
 983   chunk->set_max_thawing_size(chunk->max_thawing_size() + _freeze_size - frame::metadata_words);
 984 
 985   if (lt.develop_is_enabled()) {
 986     LogStream ls(lt);
 987     ls.print_cr("top chunk:");
 988     chunk->print_on(&ls);
 989   }
 990 
 991   // The topmost existing frame in the chunk; or an empty frame if the chunk is empty
 992   caller = StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame();
 993 
 994   DEBUG_ONLY(_last_write = caller.unextended_sp() + (empty_chunk ? argsize_md : overlap);)
 995 
 996   assert(chunk->is_in_chunk(_last_write - _freeze_size),
 997     "last_write-size: " INTPTR_FORMAT " start: " INTPTR_FORMAT, p2i(_last_write-_freeze_size), p2i(chunk->start_address()));
 998 #ifdef ASSERT
 999   if (lt.develop_is_enabled()) {
1000     LogStream ls(lt);
1001     ls.print_cr("top hframe before (freeze):");
1002     assert(caller.is_heap_frame(), "should be");
1003     caller.print_on(&ls);
1004   }
1005 
1006   assert(!empty || Continuation::is_continuation_entry_frame(callee, nullptr), "");
1007 
1008   frame entry = sender(callee);
1009 
1010   assert(Continuation::is_return_barrier_entry(entry.pc()) || Continuation::is_continuation_enterSpecial(entry), "");
1011   assert(callee.is_interpreted_frame() || entry.sp() == entry.unextended_sp(), "");
1012 #endif
1013 
1014   return freeze_ok_bottom;
1015 }
1016 
1017 void FreezeBase::patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame) {
1018   if (is_bottom_frame) {
1019     // If we're the bottom frame, we need to replace the return barrier with the real
1020     // caller's pc.
1021     address last_pc = caller.pc();
1022     assert((last_pc == nullptr) == is_empty(_cont.tail()), "");
1023     ContinuationHelper::Frame::patch_pc(caller, last_pc);
1024   } else {
1025     assert(!caller.is_empty(), "");
1026   }
1027 
1028   patch_pd(hf, caller);
1029 
1030   if (f.is_interpreted_frame()) {
1031     assert(hf.is_heap_frame(), "should be");
1032     ContinuationHelper::InterpretedFrame::patch_sender_sp(hf, caller);
1033   }
1034 
1035 #ifdef ASSERT
1036   if (hf.is_compiled_frame()) {
1037     if (f.is_deoptimized_frame()) { // TODO DEOPT: long term solution: unroll on freeze and patch pc
1038       log_develop_trace(continuations)("Freezing deoptimized frame");
1039       assert(f.cb()->as_compiled_method()->is_deopt_pc(f.raw_pc()), "");
1040       assert(f.cb()->as_compiled_method()->is_deopt_pc(ContinuationHelper::Frame::real_pc(f)), "");
1041     }
1042   }
1043 #endif
1044 }
1045 
1046 #ifdef ASSERT
1047 static void verify_frame_top(const frame& f, intptr_t* top) {
1048   ResourceMark rm;
1049   InterpreterOopMap mask;
1050   f.interpreted_frame_oop_map(&mask);
1051   assert(top <= ContinuationHelper::InterpretedFrame::frame_top(f, &mask),
1052          "frame_top: " INTPTR_FORMAT " Interpreted::frame_top: " INTPTR_FORMAT,
1053            p2i(top), p2i(ContinuationHelper::InterpretedFrame::frame_top(f, &mask)));
1054 }
1055 #endif // ASSERT
1056 
1057 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1058 // See also StackChunkFrameStream<frame_kind>::frame_size()
1059 NOINLINE freeze_result FreezeBase::recurse_freeze_interpreted_frame(frame& f, frame& caller,
1060                                                                     int callee_argsize /* incl. metadata */,
1061                                                                     bool callee_interpreted) {
1062   adjust_interpreted_frame_unextended_sp(f);
1063 
1064   // The frame's top never includes the stack arguments to the callee
1065   intptr_t* const stack_frame_top = ContinuationHelper::InterpretedFrame::frame_top(f, callee_argsize, callee_interpreted);
1066   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
1067   const int fsize = stack_frame_bottom - stack_frame_top;
1068 
1069   DEBUG_ONLY(verify_frame_top(f, stack_frame_top));
1070 
1071   Method* frame_method = ContinuationHelper::Frame::frame_method(f);
1072   // including metadata between f and its args
1073   const int argsize = ContinuationHelper::InterpretedFrame::stack_argsize(f) + frame::metadata_words_at_top;
1074 
1075   log_develop_trace(continuations)("recurse_freeze_interpreted_frame %s _size: %d fsize: %d argsize: %d",
1076     frame_method->name_and_sig_as_C_string(), _freeze_size, fsize, argsize);
1077   // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1078   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1079 
1080   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::InterpretedFrame>(f, caller, fsize, argsize);
1081   if (UNLIKELY(result > freeze_ok_bottom)) {
1082     return result;
1083   }
1084 
1085   bool is_bottom_frame = result == freeze_ok_bottom;
1086   assert(!caller.is_empty() || is_bottom_frame, "");
1087 
1088   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, is_bottom_frame);)
1089 
1090   frame hf = new_heap_frame<ContinuationHelper::InterpretedFrame>(f, caller);
1091   _total_align_size += frame::align_wiggle; // add alignment room for internal interpreted frame alignment on AArch64/PPC64
1092 
1093   intptr_t* heap_frame_top = ContinuationHelper::InterpretedFrame::frame_top(hf, callee_argsize, callee_interpreted);
1094   intptr_t* heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
1095   assert(heap_frame_bottom == heap_frame_top + fsize, "");
1096 
1097   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
1098   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
1099   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1100   assert(!is_bottom_frame || !caller.is_interpreted_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1101 
1102   relativize_interpreted_frame_metadata(f, hf);
1103 
1104   patch(f, hf, caller, is_bottom_frame);
1105 
1106   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
1107   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1108   caller = hf;
1109 
1110   // Mark frame_method's GC epoch for class redefinition on_stack calculation.
1111   frame_method->record_gc_epoch();
1112 
1113   return freeze_ok;
1114 }
1115 
1116 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1117 // See also StackChunkFrameStream<frame_kind>::frame_size()
1118 freeze_result FreezeBase::recurse_freeze_compiled_frame(frame& f, frame& caller,
1119                                                         int callee_argsize /* incl. metadata */,
1120                                                         bool callee_interpreted) {
1121   // The frame's top never includes the stack arguments to the callee
1122   intptr_t* const stack_frame_top = ContinuationHelper::CompiledFrame::frame_top(f, callee_argsize, callee_interpreted);
1123   intptr_t* const stack_frame_bottom = ContinuationHelper::CompiledFrame::frame_bottom(f);
1124   // including metadata between f and its stackargs
1125   const int argsize = ContinuationHelper::CompiledFrame::stack_argsize(f) + frame::metadata_words_at_top;
1126   const int fsize = stack_frame_bottom + argsize - stack_frame_top;
1127 
1128   log_develop_trace(continuations)("recurse_freeze_compiled_frame %s _size: %d fsize: %d argsize: %d",
1129                              ContinuationHelper::Frame::frame_method(f) != nullptr ?
1130                              ContinuationHelper::Frame::frame_method(f)->name_and_sig_as_C_string() : "",
1131                              _freeze_size, fsize, argsize);
1132   // we'd rather not yield inside methods annotated with @JvmtiMountTransition
1133   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition(), "");
1134 
1135   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::CompiledFrame>(f, caller, fsize, argsize);
1136   if (UNLIKELY(result > freeze_ok_bottom)) {
1137     return result;
1138   }
1139 
1140   bool is_bottom_frame = result == freeze_ok_bottom;
1141   assert(!caller.is_empty() || is_bottom_frame, "");
1142 
1143   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, is_bottom_frame);)
1144 
1145   frame hf = new_heap_frame<ContinuationHelper::CompiledFrame>(f, caller);
1146 
1147   intptr_t* heap_frame_top = ContinuationHelper::CompiledFrame::frame_top(hf, callee_argsize, callee_interpreted);
1148 
1149   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1150   assert(!is_bottom_frame || !caller.is_compiled_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1151 
1152   if (caller.is_interpreted_frame()) {
1153     _total_align_size += frame::align_wiggle; // See Thaw::align
1154   }
1155 
1156   patch(f, hf, caller, is_bottom_frame);
1157 
1158   assert(is_bottom_frame || Interpreter::contains(ContinuationHelper::CompiledFrame::real_pc(caller)) == caller.is_interpreted_frame(), "");
1159 
1160   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1161   caller = hf;
1162   return freeze_ok;
1163 }
1164 
1165 NOINLINE freeze_result FreezeBase::recurse_freeze_stub_frame(frame& f, frame& caller) {
1166   intptr_t* const stack_frame_top = ContinuationHelper::StubFrame::frame_top(f, 0, 0);
1167   const int fsize = f.cb()->frame_size();
1168 
1169   log_develop_trace(continuations)("recurse_freeze_stub_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1170     f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1171 
1172   // recurse_freeze_java_frame and freeze inlined here because we need to use a full RegisterMap for lock ownership
1173   NOT_PRODUCT(_frames++;)
1174   _freeze_size += fsize;
1175 
1176   RegisterMap map(_cont.thread(),
1177                   RegisterMap::UpdateMap::include,
1178                   RegisterMap::ProcessFrames::skip,
1179                   RegisterMap::WalkContinuation::skip);
1180   map.set_include_argument_oops(false);
1181   ContinuationHelper::update_register_map<ContinuationHelper::StubFrame>(f, &map);
1182   f.oop_map()->update_register_map(&f, &map); // we have callee-save registers in this case
1183   frame senderf = sender<ContinuationHelper::StubFrame>(f);
1184   assert(senderf.unextended_sp() < _bottom_address - 1, "");
1185   assert(senderf.is_compiled_frame(), "");
1186 
1187   if (UNLIKELY(senderf.oop_map() == nullptr)) {
1188     // native frame
1189     return freeze_pinned_native;
1190   }
1191 
1192   freeze_result result = recurse_freeze_compiled_frame(senderf, caller, 0, 0); // This might be deoptimized
1193   if (UNLIKELY(result > freeze_ok_bottom)) {
1194     return result;
1195   }
1196   assert(result != freeze_ok_bottom, "");
1197   assert(!caller.is_interpreted_frame(), "");
1198 
1199   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, false);)
1200   frame hf = new_heap_frame<ContinuationHelper::StubFrame>(f, caller);
1201   intptr_t* heap_frame_top = ContinuationHelper::StubFrame::frame_top(hf, 0, 0);
1202   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1203   DEBUG_ONLY(after_freeze_java_frame(hf, false);)
1204 
1205   caller = hf;
1206   return freeze_ok;
1207 }
1208 
1209 NOINLINE void FreezeBase::finish_freeze(const frame& f, const frame& top) {
1210   stackChunkOop chunk = _cont.tail();
1211   assert(chunk->to_offset(top.sp()) <= chunk->sp(), "");
1212 
1213   LogTarget(Trace, continuations) lt;
1214   if (lt.develop_is_enabled()) {
1215     LogStream ls(lt);
1216     assert(top.is_heap_frame(), "should be");
1217     top.print_on(&ls);
1218   }
1219 
1220   set_top_frame_metadata_pd(top);
1221 
1222   chunk->set_sp(chunk->to_offset(top.sp()));
1223   chunk->set_pc(top.pc());
1224 
1225   chunk->set_max_thawing_size(chunk->max_thawing_size() + _total_align_size);
1226 
1227   // At this point the chunk is consistent
1228 
1229   if (UNLIKELY(_barriers)) {
1230     log_develop_trace(continuations)("do barriers on old chunk");
1231     // Serial and Parallel GC can allocate objects directly into the old generation.
1232     // Then we want to relativize the derived pointers eagerly so that
1233     // old chunks are all in GC mode.
1234     assert(!UseG1GC, "G1 can not deal with allocating outside of eden");
1235     assert(!UseZGC, "ZGC can not deal with allocating chunks visible to marking");
1236     if (UseShenandoahGC) {
1237       _cont.tail()->relativize_derived_pointers_concurrently();
1238     } else {
1239       ContinuationGCSupport::transform_stack_chunk(_cont.tail());
1240     }
1241     // For objects in the old generation we must maintain the remembered set
1242     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>();
1243   }
1244 
1245   log_develop_trace(continuations)("finish_freeze: has_mixed_frames: %d", chunk->has_mixed_frames());
1246   if (lt.develop_is_enabled()) {
1247     LogStream ls(lt);
1248     chunk->print_on(true, &ls);
1249   }
1250 
1251   if (lt.develop_is_enabled()) {
1252     LogStream ls(lt);
1253     ls.print_cr("top hframe after (freeze):");
1254     assert(_cont.last_frame().is_heap_frame(), "should be");
1255     _cont.last_frame().print_on(&ls);
1256   }
1257 
1258   assert(_cont.chunk_invariant(), "");
1259 }
1260 
1261 inline bool FreezeBase::stack_overflow() { // detect stack overflow in recursive native code
1262   JavaThread* t = !_preempt ? _thread : JavaThread::current();
1263   assert(t == JavaThread::current(), "");
1264   if (os::current_stack_pointer() < t->stack_overflow_state()->shadow_zone_safe_limit()) {
1265     if (!_preempt) {
1266       ContinuationWrapper::SafepointOp so(t, _cont); // could also call _cont.done() instead
1267       Exceptions::_throw_msg(t, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Stack overflow while freezing");
1268     }
1269     return true;
1270   }
1271   return false;
1272 }
1273 
1274 class StackChunkAllocator : public MemAllocator {
1275   const size_t                                 _stack_size;
1276   ContinuationWrapper&                         _continuation_wrapper;
1277   JvmtiSampledObjectAllocEventCollector* const _jvmti_event_collector;
1278   mutable bool                                 _took_slow_path;
1279 
1280   // Does the minimal amount of initialization needed for a TLAB allocation.
1281   // We don't need to do a full initialization, as such an allocation need not be immediately walkable.
1282   virtual oop initialize(HeapWord* mem) const override {
1283     assert(_stack_size > 0, "");
1284     assert(_stack_size <= max_jint, "");
1285     assert(_word_size > _stack_size, "");
1286 
1287     // zero out fields (but not the stack)
1288     const size_t hs = oopDesc::header_size();
1289     Copy::fill_to_aligned_words(mem + hs, vmClasses::StackChunk_klass()->size_helper() - hs);
1290 
1291     jdk_internal_vm_StackChunk::set_size(mem, (int)_stack_size);
1292     jdk_internal_vm_StackChunk::set_sp(mem, (int)_stack_size);
1293 
1294     return finish(mem);
1295   }
1296 
1297   stackChunkOop allocate_fast() const {
1298     if (!UseTLAB) {
1299       return nullptr;
1300     }
1301 
1302     HeapWord* const mem = MemAllocator::mem_allocate_inside_tlab_fast();
1303     if (mem == nullptr) {
1304       return nullptr;
1305     }
1306 
1307     oop obj = initialize(mem);
1308     return stackChunkOopDesc::cast(obj);
1309   }
1310 
1311 public:
1312   StackChunkAllocator(Klass* klass,
1313                       size_t word_size,
1314                       Thread* thread,
1315                       size_t stack_size,
1316                       ContinuationWrapper& continuation_wrapper,
1317                       JvmtiSampledObjectAllocEventCollector* jvmti_event_collector)
1318     : MemAllocator(klass, word_size, thread),
1319       _stack_size(stack_size),
1320       _continuation_wrapper(continuation_wrapper),
1321       _jvmti_event_collector(jvmti_event_collector),
1322       _took_slow_path(false) {}
1323 
1324   // Provides it's own, specialized allocation which skips instrumentation
1325   // if the memory can be allocated without going to a slow-path.
1326   stackChunkOop allocate() const {
1327     // First try to allocate without any slow-paths or instrumentation.
1328     stackChunkOop obj = allocate_fast();
1329     if (obj != nullptr) {
1330       return obj;
1331     }
1332 
1333     // Now try full-blown allocation with all expensive operations,
1334     // including potentially safepoint operations.
1335     _took_slow_path = true;
1336 
1337     // Protect unhandled Loom oops
1338     ContinuationWrapper::SafepointOp so(_thread, _continuation_wrapper);
1339 
1340     // Can safepoint
1341     _jvmti_event_collector->start();
1342 
1343     // Can safepoint
1344     return stackChunkOopDesc::cast(MemAllocator::allocate());
1345   }
1346 
1347   bool took_slow_path() const {
1348     return _took_slow_path;
1349   }
1350 };
1351 
1352 template <typename ConfigT>
1353 stackChunkOop Freeze<ConfigT>::allocate_chunk(size_t stack_size) {
1354   log_develop_trace(continuations)("allocate_chunk allocating new chunk");
1355 
1356   InstanceStackChunkKlass* klass = InstanceStackChunkKlass::cast(vmClasses::StackChunk_klass());
1357   size_t size_in_words = klass->instance_size(stack_size);
1358 
1359   if (CollectedHeap::stack_chunk_max_size() > 0 && size_in_words >= CollectedHeap::stack_chunk_max_size()) {
1360     if (!_preempt) {
1361       throw_stack_overflow_on_humongous_chunk();
1362     }
1363     return nullptr;
1364   }
1365 
1366   JavaThread* current = _preempt ? JavaThread::current() : _thread;
1367   assert(current == JavaThread::current(), "should be current");
1368 
1369   // Allocate the chunk.
1370   //
1371   // This might safepoint while allocating, but all safepointing due to
1372   // instrumentation have been deferred. This property is important for
1373   // some GCs, as this ensures that the allocated object is in the young
1374   // generation / newly allocated memory.
1375   StackChunkAllocator allocator(klass, size_in_words, current, stack_size, _cont, _jvmti_event_collector);
1376   stackChunkOop chunk = allocator.allocate();
1377 
1378   if (chunk == nullptr) {
1379     return nullptr; // OOME
1380   }
1381 
1382   // assert that chunk is properly initialized
1383   assert(chunk->stack_size() == (int)stack_size, "");
1384   assert(chunk->size() >= stack_size, "chunk->size(): %zu size: %zu", chunk->size(), stack_size);
1385   assert(chunk->sp() == chunk->stack_size(), "");
1386   assert((intptr_t)chunk->start_address() % 8 == 0, "");
1387   assert(chunk->max_thawing_size() == 0, "");
1388   assert(chunk->pc() == nullptr, "");
1389   assert(chunk->argsize() == 0, "");
1390   assert(chunk->flags() == 0, "");
1391   assert(chunk->is_gc_mode() == false, "");
1392 
1393   // fields are uninitialized
1394   chunk->set_parent_access<IS_DEST_UNINITIALIZED>(_cont.last_nonempty_chunk());
1395   chunk->set_cont_access<IS_DEST_UNINITIALIZED>(_cont.continuation());
1396 
1397 #if INCLUDE_ZGC
1398   if (UseZGC) {
1399     if (ZGenerational) {
1400       ZStackChunkGCData::initialize(chunk);
1401     }
1402     assert(!chunk->requires_barriers(), "ZGC always allocates in the young generation");
1403     _barriers = false;
1404   } else
1405 #endif
1406 #if INCLUDE_SHENANDOAHGC
1407   if (UseShenandoahGC) {
1408     _barriers = chunk->requires_barriers();
1409   } else
1410 #endif
1411   {
1412     if (!allocator.took_slow_path()) {
1413       // Guaranteed to be in young gen / newly allocated memory
1414       assert(!chunk->requires_barriers(), "Unfamiliar GC requires barriers on TLAB allocation");
1415       _barriers = false;
1416     } else {
1417       // Some GCs could put direct allocations in old gen for slow-path
1418       // allocations; need to explicitly check if that was the case.
1419       _barriers = chunk->requires_barriers();
1420     }
1421   }
1422 
1423   if (_barriers) {
1424     log_develop_trace(continuations)("allocation requires barriers");
1425   }
1426 
1427   assert(chunk->parent() == nullptr || chunk->parent()->is_stackChunk(), "");
1428 
1429   return chunk;
1430 }
1431 
1432 void FreezeBase::throw_stack_overflow_on_humongous_chunk() {
1433   ContinuationWrapper::SafepointOp so(_thread, _cont); // could also call _cont.done() instead
1434   Exceptions::_throw_msg(_thread, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Humongous stack chunk");
1435 }
1436 
1437 #if INCLUDE_JVMTI
1438 static int num_java_frames(ContinuationWrapper& cont) {
1439   ResourceMark rm; // used for scope traversal in num_java_frames(CompiledMethod*, address)
1440   int count = 0;
1441   for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
1442     count += chunk->num_java_frames();
1443   }
1444   return count;
1445 }
1446 
1447 static void invalidate_jvmti_stack(JavaThread* thread) {
1448   if (thread->is_interp_only_mode()) {
1449     JvmtiThreadState *state = thread->jvmti_thread_state();
1450     if (state != nullptr)
1451       state->invalidate_cur_stack_depth();
1452   }
1453 }
1454 
1455 static void jvmti_yield_cleanup(JavaThread* thread, ContinuationWrapper& cont) {
1456   if (JvmtiExport::can_post_frame_pop()) {
1457     int num_frames = num_java_frames(cont);
1458 
1459     ContinuationWrapper::SafepointOp so(Thread::current(), cont);
1460     JvmtiExport::continuation_yield_cleanup(JavaThread::current(), num_frames);
1461   }
1462   invalidate_jvmti_stack(thread);
1463 }
1464 #endif // INCLUDE_JVMTI
1465 
1466 #ifdef ASSERT
1467 static bool monitors_on_stack(JavaThread* thread) {
1468   ContinuationEntry* ce = thread->last_continuation();
1469   RegisterMap map(thread,
1470                   RegisterMap::UpdateMap::include,
1471                   RegisterMap::ProcessFrames::include,
1472                   RegisterMap::WalkContinuation::skip);
1473   map.set_include_argument_oops(false);
1474   for (frame f = thread->last_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map)) {
1475     if ((f.is_interpreted_frame() && ContinuationHelper::InterpretedFrame::is_owning_locks(f)) ||
1476         (f.is_compiled_frame() && ContinuationHelper::CompiledFrame::is_owning_locks(map.thread(), &map, f))) {
1477       return true;
1478     }
1479   }
1480   return false;
1481 }
1482 
1483 bool FreezeBase::interpreted_native_or_deoptimized_on_stack() {
1484   ContinuationEntry* ce = _thread->last_continuation();
1485   RegisterMap map(_thread,
1486                   RegisterMap::UpdateMap::skip,
1487                   RegisterMap::ProcessFrames::skip,
1488                   RegisterMap::WalkContinuation::skip);
1489   map.set_include_argument_oops(false);
1490   for (frame f = freeze_start_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map)) {
1491     if (f.is_interpreted_frame() || f.is_native_frame() || f.is_deoptimized_frame()) {
1492       return true;
1493     }
1494   }
1495   return false;
1496 }
1497 #endif // ASSERT
1498 
1499 static inline int freeze_epilog(JavaThread* thread, ContinuationWrapper& cont) {
1500   verify_continuation(cont.continuation());
1501   assert(!cont.is_empty(), "");
1502   // This is done for the sake of the enterSpecial frame
1503   StackWatermarkSet::after_unwind(thread);
1504 
1505   log_develop_debug(continuations)("=== End of freeze cont ### #" INTPTR_FORMAT, cont.hash());
1506 
1507   return 0;
1508 }
1509 
1510 static int freeze_epilog(JavaThread* thread, ContinuationWrapper& cont, freeze_result res) {
1511   if (UNLIKELY(res != freeze_ok)) {
1512     verify_continuation(cont.continuation());
1513     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1514     return res;
1515   }
1516 
1517   JVMTI_ONLY(jvmti_yield_cleanup(thread, cont)); // can safepoint
1518   return freeze_epilog(thread, cont);
1519 }
1520 
1521 template<typename ConfigT>
1522 static inline int freeze_internal(JavaThread* current, intptr_t* const sp) {
1523   assert(!current->has_pending_exception(), "");
1524 
1525 #ifdef ASSERT
1526   log_trace(continuations)("~~~~ freeze sp: " INTPTR_FORMAT, p2i(current->last_continuation()->entry_sp()));
1527   log_frames(current);
1528 #endif
1529 
1530   CONT_JFR_ONLY(EventContinuationFreeze event;)
1531 
1532   ContinuationEntry* entry = current->last_continuation();
1533 
1534   oop oopCont = entry->cont_oop(current);
1535   assert(oopCont == current->last_continuation()->cont_oop(current), "");
1536   assert(ContinuationEntry::assert_entry_frame_laid_out(current), "");
1537 
1538   verify_continuation(oopCont);
1539   ContinuationWrapper cont(current, oopCont);
1540   log_develop_debug(continuations)("FREEZE #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
1541 
1542   assert(entry->is_virtual_thread() == (entry->scope(current) == java_lang_VirtualThread::vthread_scope()), "");
1543 
1544   assert(monitors_on_stack(current) == ((current->held_monitor_count() - current->jni_monitor_count()) > 0),
1545          "Held monitor count and locks on stack invariant: " INT64_FORMAT " JNI: " INT64_FORMAT, (int64_t)current->held_monitor_count(), (int64_t)current->jni_monitor_count());
1546 
1547   if (entry->is_pinned() || current->held_monitor_count() > 0) {
1548     log_develop_debug(continuations)("PINNED due to critical section/hold monitor");
1549     verify_continuation(cont.continuation());
1550     freeze_result res = entry->is_pinned() ? freeze_pinned_cs : freeze_pinned_monitor;
1551     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1552     return res;
1553   }
1554 
1555   Freeze<ConfigT> freeze(current, cont, sp);
1556 
1557   // There are no interpreted frames if we're not called from the interpreter and we haven't ancountered an i2c
1558   // adapter or called Deoptimization::unpack_frames. Calls from native frames also go through the interpreter
1559   // (see JavaCalls::call_helper).
1560   assert(!current->cont_fastpath()
1561          || (current->cont_fastpath_thread_state() && !freeze.interpreted_native_or_deoptimized_on_stack()), "");
1562   bool fast = UseContinuationFastPath && current->cont_fastpath();
1563   if (fast && freeze.size_if_fast_freeze_available() > 0) {
1564     freeze.freeze_fast_existing_chunk();
1565     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1566     freeze_epilog(current, cont);
1567     return 0;
1568   }
1569 
1570   log_develop_trace(continuations)("chunk unavailable; transitioning to VM");
1571   assert(current == JavaThread::current(), "must be current thread except for preempt");
1572   JRT_BLOCK
1573     // delays a possible JvmtiSampledObjectAllocEventCollector in alloc_chunk
1574     JvmtiSampledObjectAllocEventCollector jsoaec(false);
1575     freeze.set_jvmti_event_collector(&jsoaec);
1576 
1577     freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1578 
1579     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1580     freeze_epilog(current, cont, res);
1581     cont.done(); // allow safepoint in the transition back to Java
1582     return res;
1583   JRT_BLOCK_END
1584 }
1585 
1586 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint) {
1587   ContinuationEntry* entry = thread->last_continuation();
1588   if (entry == nullptr) {
1589     return freeze_ok;
1590   }
1591   if (entry->is_pinned()) {
1592     return freeze_pinned_cs;
1593   } else if (thread->held_monitor_count() > 0) {
1594     return freeze_pinned_monitor;
1595   }
1596 
1597   RegisterMap map(thread,
1598                   RegisterMap::UpdateMap::include,
1599                   RegisterMap::ProcessFrames::skip,
1600                   RegisterMap::WalkContinuation::skip);
1601   map.set_include_argument_oops(false);
1602   frame f = thread->last_frame();
1603 
1604   if (!safepoint) {
1605     f = f.sender(&map); // this is the yield frame
1606   } else { // safepoint yield
1607 #if (defined(X86) || defined(AARCH64) || defined(RISCV64)) && !defined(ZERO)
1608     f.set_fp(f.real_fp()); // Instead of this, maybe in ContinuationWrapper::set_last_frame always use the real_fp?
1609 #else
1610     Unimplemented();
1611 #endif
1612     if (!Interpreter::contains(f.pc())) {
1613       assert(ContinuationHelper::Frame::is_stub(f.cb()), "must be");
1614       assert(f.oop_map() != nullptr, "must be");
1615       f.oop_map()->update_register_map(&f, &map); // we have callee-save registers in this case
1616     }
1617   }
1618 
1619   while (true) {
1620     if ((f.is_interpreted_frame() && f.interpreter_frame_method()->is_native()) || f.is_native_frame()) {
1621       return freeze_pinned_native;
1622     }
1623 
1624     f = f.sender(&map);
1625     if (!Continuation::is_frame_in_continuation(entry, f)) {
1626       oop scope = jdk_internal_vm_Continuation::scope(entry->cont_oop(thread));
1627       if (scope == cont_scope) {
1628         break;
1629       }
1630       int monitor_count = entry->parent_held_monitor_count();
1631       entry = entry->parent();
1632       if (entry == nullptr) {
1633         break;
1634       }
1635       if (entry->is_pinned()) {
1636         return freeze_pinned_cs;
1637       } else if (monitor_count > 0) {
1638         return freeze_pinned_monitor;
1639       }
1640     }
1641   }
1642   return freeze_ok;
1643 }
1644 
1645 /////////////// THAW ////
1646 
1647 static int thaw_size(stackChunkOop chunk) {
1648   int size = chunk->max_thawing_size();
1649   size += frame::metadata_words; // For the top pc+fp in push_return_frame or top = stack_sp - frame::metadata_words in thaw_fast
1650   size += 2*frame::align_wiggle; // in case of alignments at the top and bottom
1651   return size;
1652 }
1653 
1654 // make room on the stack for thaw
1655 // returns the size in bytes, or 0 on failure
1656 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier) {
1657   log_develop_trace(continuations)("~~~~ prepare_thaw return_barrier: %d", return_barrier);
1658 
1659   assert(thread == JavaThread::current(), "");
1660 
1661   ContinuationEntry* ce = thread->last_continuation();
1662   assert(ce != nullptr, "");
1663   oop continuation = ce->cont_oop(thread);
1664   assert(continuation == get_continuation(thread), "");
1665   verify_continuation(continuation);
1666 
1667   stackChunkOop chunk = jdk_internal_vm_Continuation::tail(continuation);
1668   assert(chunk != nullptr, "");
1669 
1670   // The tail can be empty because it might still be available for another freeze.
1671   // However, here we want to thaw, so we get rid of it (it will be GCed).
1672   if (UNLIKELY(chunk->is_empty())) {
1673     chunk = chunk->parent();
1674     assert(chunk != nullptr, "");
1675     assert(!chunk->is_empty(), "");
1676     jdk_internal_vm_Continuation::set_tail(continuation, chunk);
1677   }
1678 
1679   // Verification
1680   chunk->verify();
1681   assert(chunk->max_thawing_size() > 0, "chunk invariant violated; expected to not be empty");
1682 
1683   // Only make space for the last chunk because we only thaw from the last chunk
1684   int size = thaw_size(chunk) << LogBytesPerWord;
1685 
1686   const address bottom = (address)thread->last_continuation()->entry_sp();
1687   // 300 is an estimate for stack size taken for this native code, in addition to StackShadowPages
1688   // for the Java frames in the check below.
1689   if (!stack_overflow_check(thread, size + 300, bottom)) {
1690     return 0;
1691   }
1692 
1693   log_develop_trace(continuations)("prepare_thaw bottom: " INTPTR_FORMAT " top: " INTPTR_FORMAT " size: %d",
1694                               p2i(bottom), p2i(bottom - size), size);
1695   return size;
1696 }
1697 
1698 class ThawBase : public StackObj {
1699 protected:
1700   JavaThread* _thread;
1701   ContinuationWrapper& _cont;
1702   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
1703 
1704   intptr_t* _fastpath;
1705   bool _barriers;
1706   intptr_t* _top_unextended_sp_before_thaw;
1707   int _align_size;
1708   DEBUG_ONLY(intptr_t* _top_stack_address);
1709 
1710   StackChunkFrameStream<ChunkFrames::Mixed> _stream;
1711 
1712   NOT_PRODUCT(int _frames;)
1713 
1714 protected:
1715   ThawBase(JavaThread* thread, ContinuationWrapper& cont) :
1716       _thread(thread), _cont(cont),
1717       _fastpath(nullptr) {
1718     DEBUG_ONLY(_top_unextended_sp_before_thaw = nullptr;)
1719     assert (cont.tail() != nullptr, "no last chunk");
1720     DEBUG_ONLY(_top_stack_address = _cont.entrySP() - thaw_size(cont.tail());)
1721   }
1722 
1723   void clear_chunk(stackChunkOop chunk);
1724   int remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize);
1725   void copy_from_chunk(intptr_t* from, intptr_t* to, int size);
1726 
1727   // fast path
1728   inline void prefetch_chunk_pd(void* start, int size_words);
1729   void patch_return(intptr_t* sp, bool is_last);
1730 
1731   // slow path
1732   NOINLINE intptr_t* thaw_slow(stackChunkOop chunk, bool return_barrier);
1733 
1734 private:
1735   void recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top);
1736   template<typename FKind> bool recurse_thaw_java_frame(frame& caller, int num_frames);
1737   void finalize_thaw(frame& entry, int argsize);
1738 
1739   inline bool seen_by_gc();
1740 
1741   inline void before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame);
1742   inline void after_thaw_java_frame(const frame& f, bool bottom);
1743   inline void patch(frame& f, const frame& caller, bool bottom);
1744   void clear_bitmap_bits(intptr_t* start, int range);
1745 
1746   NOINLINE void recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames);
1747   void recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller);
1748   void recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames);
1749   void finish_thaw(frame& f);
1750 
1751   void push_return_frame(frame& f);
1752   inline frame new_entry_frame();
1753   template<typename FKind> frame new_stack_frame(const frame& hf, frame& caller, bool bottom);
1754   inline void patch_pd(frame& f, const frame& sender);
1755   inline intptr_t* align(const frame& hf, intptr_t* frame_sp, frame& caller, bool bottom);
1756 
1757   void maybe_set_fastpath(intptr_t* sp) { if (sp > _fastpath) _fastpath = sp; }
1758 
1759   static inline void derelativize_interpreted_frame_metadata(const frame& hf, const frame& f);
1760 
1761  public:
1762   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
1763 };
1764 
1765 template <typename ConfigT>
1766 class Thaw : public ThawBase {
1767 public:
1768   Thaw(JavaThread* thread, ContinuationWrapper& cont) : ThawBase(thread, cont) {}
1769 
1770   inline bool can_thaw_fast(stackChunkOop chunk) {
1771     return    !_barriers
1772            &&  _thread->cont_fastpath_thread_state()
1773            && !chunk->has_thaw_slowpath_condition()
1774            && !PreserveFramePointer;
1775   }
1776 
1777   inline intptr_t* thaw(Continuation::thaw_kind kind);
1778   NOINLINE intptr_t* thaw_fast(stackChunkOop chunk);
1779   inline void patch_caller_links(intptr_t* sp, intptr_t* bottom);
1780 };
1781 
1782 template <typename ConfigT>
1783 inline intptr_t* Thaw<ConfigT>::thaw(Continuation::thaw_kind kind) {
1784   verify_continuation(_cont.continuation());
1785   assert(!jdk_internal_vm_Continuation::done(_cont.continuation()), "");
1786   assert(!_cont.is_empty(), "");
1787 
1788   stackChunkOop chunk = _cont.tail();
1789   assert(chunk != nullptr, "guaranteed by prepare_thaw");
1790   assert(!chunk->is_empty(), "guaranteed by prepare_thaw");
1791 
1792   _barriers = chunk->requires_barriers();
1793   return (LIKELY(can_thaw_fast(chunk))) ? thaw_fast(chunk)
1794                                         : thaw_slow(chunk, kind != Continuation::thaw_top);
1795 }
1796 
1797 class ReconstructedStack : public StackObj {
1798   intptr_t* _base;  // _cont.entrySP(); // top of the entry frame
1799   int _thaw_size;
1800   int _argsize;
1801 public:
1802   ReconstructedStack(intptr_t* base, int thaw_size, int argsize)
1803   : _base(base), _thaw_size(thaw_size - (argsize == 0 ? frame::metadata_words_at_top : 0)), _argsize(argsize) {
1804     // The only possible source of misalignment is stack-passed arguments b/c compiled frames are 16-byte aligned.
1805     assert(argsize != 0 || (_base - _thaw_size) == ContinuationHelper::frame_align_pointer(_base - _thaw_size), "");
1806     // We're at most one alignment word away from entrySP
1807     assert(_base - 1 <= top() + total_size() + frame::metadata_words_at_bottom, "missed entry frame");
1808   }
1809 
1810   int entry_frame_extension() const { return _argsize + (_argsize > 0 ? frame::metadata_words_at_top : 0); }
1811 
1812   // top and bottom stack pointers
1813   intptr_t* sp() const { return ContinuationHelper::frame_align_pointer(_base - _thaw_size); }
1814   intptr_t* bottom_sp() const { return ContinuationHelper::frame_align_pointer(_base - entry_frame_extension()); }
1815 
1816   // several operations operate on the totality of the stack being reconstructed,
1817   // including the metadata words
1818   intptr_t* top() const { return sp() - frame::metadata_words_at_bottom;  }
1819   int total_size() const { return _thaw_size + frame::metadata_words_at_bottom; }
1820 };
1821 
1822 inline void ThawBase::clear_chunk(stackChunkOop chunk) {
1823   chunk->set_sp(chunk->stack_size());
1824   chunk->set_argsize(0);
1825   chunk->set_max_thawing_size(0);
1826 }
1827 
1828  int ThawBase::remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize) {
1829   bool empty = false;
1830   StackChunkFrameStream<ChunkFrames::CompiledOnly> f(chunk);
1831   DEBUG_ONLY(intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();)
1832   assert(chunk_sp == f.sp(), "");
1833   assert(chunk_sp == f.unextended_sp(), "");
1834 
1835   const int frame_size = f.cb()->frame_size();
1836   argsize = f.stack_argsize();
1837 
1838   f.next(SmallRegisterMap::instance, true /* stop */);
1839   empty = f.is_done();
1840   assert(!empty || argsize == chunk->argsize(), "");
1841 
1842   if (empty) {
1843     clear_chunk(chunk);
1844   } else {
1845     chunk->set_sp(chunk->sp() + frame_size);
1846     chunk->set_max_thawing_size(chunk->max_thawing_size() - frame_size);
1847     // We set chunk->pc to the return pc into the next frame
1848     chunk->set_pc(f.pc());
1849     assert(f.pc() == *(address*)(chunk_sp + frame_size - frame::sender_sp_ret_address_offset()), "unexpected pc");
1850   }
1851   assert(empty == chunk->is_empty(), "");
1852   // returns the size required to store the frame on stack, and because it is a
1853   // compiled frame, it must include a copy of the arguments passed by the caller
1854   return frame_size + argsize + frame::metadata_words_at_top;
1855 }
1856 
1857 void ThawBase::copy_from_chunk(intptr_t* from, intptr_t* to, int size) {
1858   assert(to >= _top_stack_address, "overwrote past thawing space"
1859     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(to), p2i(_top_stack_address));
1860   assert(to + size <= _cont.entrySP(), "overwrote past thawing space");
1861   _cont.tail()->copy_from_chunk_to_stack(from, to, size);
1862   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
1863 }
1864 
1865 void ThawBase::patch_return(intptr_t* sp, bool is_last) {
1866   log_develop_trace(continuations)("thaw_fast patching -- sp: " INTPTR_FORMAT, p2i(sp));
1867 
1868   address pc = !is_last ? StubRoutines::cont_returnBarrier() : _cont.entryPC();
1869   *(address*)(sp - frame::sender_sp_ret_address_offset()) = pc;
1870 }
1871 
1872 template <typename ConfigT>
1873 NOINLINE intptr_t* Thaw<ConfigT>::thaw_fast(stackChunkOop chunk) {
1874   assert(chunk == _cont.tail(), "");
1875   assert(!chunk->has_mixed_frames(), "");
1876   assert(!chunk->requires_barriers(), "");
1877   assert(!chunk->has_bitmap(), "");
1878   assert(!_thread->is_interp_only_mode(), "");
1879 
1880   LogTarget(Trace, continuations) lt;
1881   if (lt.develop_is_enabled()) {
1882     LogStream ls(lt);
1883     ls.print_cr("thaw_fast");
1884     chunk->print_on(true, &ls);
1885   }
1886 
1887   // Below this heuristic, we thaw the whole chunk, above it we thaw just one frame.
1888   static const int threshold = 500; // words
1889 
1890   const int full_chunk_size = chunk->stack_size() - chunk->sp(); // this initial size could be reduced if it's a partial thaw
1891   int argsize, thaw_size;
1892 
1893   intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();
1894 
1895   bool partial, empty;
1896   if (LIKELY(!TEST_THAW_ONE_CHUNK_FRAME && (full_chunk_size < threshold))) {
1897     prefetch_chunk_pd(chunk->start_address(), full_chunk_size); // prefetch anticipating memcpy starting at highest address
1898 
1899     partial = false;
1900     argsize = chunk->argsize(); // must be called *before* clearing the chunk
1901     clear_chunk(chunk);
1902     thaw_size = full_chunk_size;
1903     empty = true;
1904   } else { // thaw a single frame
1905     partial = true;
1906     thaw_size = remove_top_compiled_frame_from_chunk(chunk, argsize);
1907     empty = chunk->is_empty();
1908   }
1909 
1910   // Are we thawing the last frame(s) in the continuation
1911   const bool is_last = empty && chunk->parent() == nullptr;
1912   assert(!is_last || argsize == 0, "");
1913 
1914   log_develop_trace(continuations)("thaw_fast partial: %d is_last: %d empty: %d size: %d argsize: %d entrySP: " PTR_FORMAT,
1915                               partial, is_last, empty, thaw_size, argsize, p2i(_cont.entrySP()));
1916 
1917   ReconstructedStack rs(_cont.entrySP(), thaw_size, argsize);
1918 
1919   // also copy metadata words at frame bottom
1920   copy_from_chunk(chunk_sp - frame::metadata_words_at_bottom, rs.top(), rs.total_size());
1921 
1922   // update the ContinuationEntry
1923   _cont.set_argsize(argsize);
1924   log_develop_trace(continuations)("setting entry argsize: %d", _cont.argsize());
1925   assert(rs.bottom_sp() == _cont.entry()->bottom_sender_sp(), "");
1926 
1927   // install the return barrier if not last frame, or the entry's pc if last
1928   patch_return(rs.bottom_sp(), is_last);
1929 
1930   // insert the back links from callee to caller frames
1931   patch_caller_links(rs.top(), rs.top() + rs.total_size());
1932 
1933   assert(is_last == _cont.is_empty(), "");
1934   assert(_cont.chunk_invariant(), "");
1935 
1936 #if CONT_JFR
1937   EventContinuationThawFast e;
1938   if (e.should_commit()) {
1939     e.set_id(cast_from_oop<u8>(chunk));
1940     e.set_size(thaw_size << LogBytesPerWord);
1941     e.set_full(!partial);
1942     e.commit();
1943   }
1944 #endif
1945 
1946 #ifdef ASSERT
1947   set_anchor(_thread, rs.sp());
1948   log_frames(_thread);
1949   if (LoomDeoptAfterThaw) {
1950     do_deopt_after_thaw(_thread);
1951   }
1952   clear_anchor(_thread);
1953 #endif
1954 
1955   return rs.sp();
1956 }
1957 
1958 inline bool ThawBase::seen_by_gc() {
1959   return _barriers || _cont.tail()->is_gc_mode();
1960 }
1961 
1962 NOINLINE intptr_t* ThawBase::thaw_slow(stackChunkOop chunk, bool return_barrier) {
1963   LogTarget(Trace, continuations) lt;
1964   if (lt.develop_is_enabled()) {
1965     LogStream ls(lt);
1966     ls.print_cr("thaw slow return_barrier: %d " INTPTR_FORMAT, return_barrier, p2i(chunk));
1967     chunk->print_on(true, &ls);
1968   }
1969 
1970 #if CONT_JFR
1971   EventContinuationThawSlow e;
1972   if (e.should_commit()) {
1973     e.set_id(cast_from_oop<u8>(_cont.continuation()));
1974     e.commit();
1975   }
1976 #endif
1977 
1978   DEBUG_ONLY(_frames = 0;)
1979   _align_size = 0;
1980   int num_frames = (return_barrier ? 1 : 2);
1981 
1982   _stream = StackChunkFrameStream<ChunkFrames::Mixed>(chunk);
1983   _top_unextended_sp_before_thaw = _stream.unextended_sp();
1984 
1985   frame heap_frame = _stream.to_frame();
1986   if (lt.develop_is_enabled()) {
1987     LogStream ls(lt);
1988     ls.print_cr("top hframe before (thaw):");
1989     assert(heap_frame.is_heap_frame(), "should have created a relative frame");
1990     heap_frame.print_value_on(&ls, nullptr);
1991   }
1992 
1993 #if INCLUDE_ZGC || INCLUDE_SHENANDOAHGC
1994   if (UseZGC || UseShenandoahGC) {
1995     _cont.tail()->relativize_derived_pointers_concurrently();
1996   }
1997 #endif
1998 
1999   frame caller; // the thawed caller on the stack
2000   recurse_thaw(heap_frame, caller, num_frames, true);
2001   finish_thaw(caller); // caller is now the topmost thawed frame
2002   _cont.write();
2003 
2004   assert(_cont.chunk_invariant(), "");
2005 
2006   JVMTI_ONLY(if (!return_barrier) invalidate_jvmti_stack(_thread));
2007 
2008   _thread->set_cont_fastpath(_fastpath);
2009 
2010   intptr_t* sp = caller.sp();
2011   return sp;
2012 }
2013 
2014 void ThawBase::recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top) {
2015   log_develop_debug(continuations)("thaw num_frames: %d", num_frames);
2016   assert(!_cont.is_empty(), "no more frames");
2017   assert(num_frames > 0, "");
2018   assert(!heap_frame.is_empty(), "");
2019 
2020   if (top && heap_frame.is_safepoint_blob_frame()) {
2021     assert(ContinuationHelper::Frame::is_stub(heap_frame.cb()), "cb: %s", heap_frame.cb()->name());
2022     recurse_thaw_stub_frame(heap_frame, caller, num_frames);
2023   } else if (!heap_frame.is_interpreted_frame()) {
2024     recurse_thaw_compiled_frame(heap_frame, caller, num_frames, false);
2025   } else {
2026     recurse_thaw_interpreted_frame(heap_frame, caller, num_frames);
2027   }
2028 }
2029 
2030 template<typename FKind>
2031 bool ThawBase::recurse_thaw_java_frame(frame& caller, int num_frames) {
2032   assert(num_frames > 0, "");
2033 
2034   DEBUG_ONLY(_frames++;)
2035 
2036   int argsize = _stream.stack_argsize();
2037 
2038   _stream.next(SmallRegisterMap::instance);
2039   assert(_stream.to_frame().is_empty() == _stream.is_done(), "");
2040 
2041   // we never leave a compiled caller of an interpreted frame as the top frame in the chunk
2042   // as it makes detecting that situation and adjusting unextended_sp tricky
2043   if (num_frames == 1 && !_stream.is_done() && FKind::interpreted && _stream.is_compiled()) {
2044     log_develop_trace(continuations)("thawing extra compiled frame to not leave a compiled interpreted-caller at top");
2045     num_frames++;
2046   }
2047 
2048   if (num_frames == 1 || _stream.is_done()) { // end recursion
2049     finalize_thaw(caller, FKind::interpreted ? 0 : argsize);
2050     return true; // bottom
2051   } else { // recurse
2052     recurse_thaw(_stream.to_frame(), caller, num_frames - 1, false);
2053     return false;
2054   }
2055 }
2056 
2057 void ThawBase::finalize_thaw(frame& entry, int argsize) {
2058   stackChunkOop chunk = _cont.tail();
2059 
2060   if (!_stream.is_done()) {
2061     assert(_stream.sp() >= chunk->sp_address(), "");
2062     chunk->set_sp(chunk->to_offset(_stream.sp()));
2063     chunk->set_pc(_stream.pc());
2064   } else {
2065     chunk->set_argsize(0);
2066     chunk->set_sp(chunk->stack_size());
2067     chunk->set_pc(nullptr);
2068   }
2069   assert(_stream.is_done() == chunk->is_empty(), "");
2070 
2071   int total_thawed = _stream.unextended_sp() - _top_unextended_sp_before_thaw;
2072   chunk->set_max_thawing_size(chunk->max_thawing_size() - total_thawed);
2073 
2074   _cont.set_argsize(argsize);
2075   entry = new_entry_frame();
2076 
2077   assert(entry.sp() == _cont.entrySP(), "");
2078   assert(Continuation::is_continuation_enterSpecial(entry), "");
2079   assert(_cont.is_entry_frame(entry), "");
2080 }
2081 
2082 inline void ThawBase::before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame) {
2083   LogTarget(Trace, continuations) lt;
2084   if (lt.develop_is_enabled()) {
2085     LogStream ls(lt);
2086     ls.print_cr("======== THAWING FRAME: %d", num_frame);
2087     assert(hf.is_heap_frame(), "should be");
2088     hf.print_value_on(&ls, nullptr);
2089   }
2090   assert(bottom == _cont.is_entry_frame(caller), "bottom: %d is_entry_frame: %d", bottom, _cont.is_entry_frame(hf));
2091 }
2092 
2093 inline void ThawBase::after_thaw_java_frame(const frame& f, bool bottom) {
2094 #ifdef ASSERT
2095   LogTarget(Trace, continuations) lt;
2096   if (lt.develop_is_enabled()) {
2097     LogStream ls(lt);
2098     ls.print_cr("thawed frame:");
2099     print_frame_layout(f, false, &ls); // f.print_on(&ls);
2100   }
2101 #endif
2102 }
2103 
2104 inline void ThawBase::patch(frame& f, const frame& caller, bool bottom) {
2105   assert(!bottom || caller.fp() == _cont.entryFP(), "");
2106   if (bottom) {
2107     ContinuationHelper::Frame::patch_pc(caller, _cont.is_empty() ? caller.pc()
2108                                                                  : StubRoutines::cont_returnBarrier());
2109   } else {
2110     // caller might have been deoptimized during thaw but we've overwritten the return address when copying f from the heap.
2111     // If the caller is not deoptimized, pc is unchanged.
2112     ContinuationHelper::Frame::patch_pc(caller, caller.raw_pc());
2113   }
2114 
2115   patch_pd(f, caller);
2116 
2117   if (f.is_interpreted_frame()) {
2118     ContinuationHelper::InterpretedFrame::patch_sender_sp(f, caller);
2119   }
2120 
2121   assert(!bottom || !_cont.is_empty() || Continuation::is_continuation_entry_frame(f, nullptr), "");
2122   assert(!bottom || (_cont.is_empty() != Continuation::is_cont_barrier_frame(f)), "");
2123 }
2124 
2125 void ThawBase::clear_bitmap_bits(intptr_t* start, int range) {
2126   // we need to clear the bits that correspond to arguments as they reside in the caller frame
2127   // or they will keep objects that are otherwise unreachable alive
2128   log_develop_trace(continuations)("clearing bitmap for " INTPTR_FORMAT " - " INTPTR_FORMAT, p2i(start), p2i(start+range));
2129   stackChunkOop chunk = _cont.tail();
2130   chunk->bitmap().clear_range(chunk->bit_index_for(start),
2131                               chunk->bit_index_for(start+range));
2132 }
2133 
2134 NOINLINE void ThawBase::recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames) {
2135   assert(hf.is_interpreted_frame(), "");
2136 
2137   if (UNLIKELY(seen_by_gc())) {
2138     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance);
2139   }
2140 
2141   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::InterpretedFrame>(caller, num_frames);
2142 
2143   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2144 
2145   _align_size += frame::align_wiggle; // possible added alignment for internal interpreted frame alignment om AArch64
2146 
2147   frame f = new_stack_frame<ContinuationHelper::InterpretedFrame>(hf, caller, is_bottom_frame);
2148 
2149   intptr_t* const stack_frame_top = f.sp() + frame::metadata_words_at_top;
2150   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
2151   intptr_t* const heap_frame_top = hf.unextended_sp() + frame::metadata_words_at_top;
2152   intptr_t* const heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
2153 
2154   assert(hf.is_heap_frame(), "should be");
2155   assert(!f.is_heap_frame(), "should not be");
2156 
2157   const int fsize = heap_frame_bottom - heap_frame_top;
2158   assert((stack_frame_bottom == stack_frame_top + fsize), "");
2159 
2160   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
2161   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
2162   copy_from_chunk(heap_frame_top, stack_frame_top, fsize);
2163 
2164   // Make sure the relativized locals is already set.
2165   assert(f.interpreter_frame_local_at(0) == stack_frame_bottom - 1, "invalid frame bottom");
2166 
2167   derelativize_interpreted_frame_metadata(hf, f);
2168   patch(f, caller, is_bottom_frame);
2169 
2170   assert(f.is_interpreted_frame_valid(_cont.thread()), "invalid thawed frame");
2171   assert(stack_frame_bottom <= ContinuationHelper::Frame::frame_top(caller), "");
2172 
2173   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
2174 
2175   maybe_set_fastpath(f.sp());
2176 
2177   const int locals = hf.interpreter_frame_method()->max_locals();
2178 
2179   if (!is_bottom_frame) {
2180     // can only fix caller once this frame is thawed (due to callee saved regs)
2181     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance);
2182   } else if (_cont.tail()->has_bitmap() && locals > 0) {
2183     assert(hf.is_heap_frame(), "should be");
2184     clear_bitmap_bits(heap_frame_bottom - locals, locals);
2185   }
2186 
2187   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2188   caller = f;
2189 }
2190 
2191 void ThawBase::recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller) {
2192   assert(!hf.is_interpreted_frame(), "");
2193   assert(_cont.is_preempted() || !stub_caller, "stub caller not at preemption");
2194 
2195   if (!stub_caller && UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2196     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance);
2197   }
2198 
2199   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::CompiledFrame>(caller, num_frames);
2200 
2201   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2202 
2203   assert(caller.sp() == caller.unextended_sp(), "");
2204 
2205   if ((!is_bottom_frame && caller.is_interpreted_frame()) || (is_bottom_frame && Interpreter::contains(_cont.tail()->pc()))) {
2206     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in freeze_interpreted_frame
2207   }
2208 
2209   // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2210   // yet laid out in the stack, and so the original_pc is not stored in it.
2211   // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2212   frame f = new_stack_frame<ContinuationHelper::CompiledFrame>(hf, caller, is_bottom_frame);
2213   intptr_t* const stack_frame_top = f.sp();
2214   intptr_t* const heap_frame_top = hf.unextended_sp();
2215 
2216   const int added_argsize = (is_bottom_frame || caller.is_interpreted_frame()) ? hf.compiled_frame_stack_argsize() : 0;
2217   int fsize = ContinuationHelper::CompiledFrame::size(hf) + added_argsize;
2218   assert(fsize <= (int)(caller.unextended_sp() - f.unextended_sp()), "");
2219 
2220   intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2221   intptr_t* to   = stack_frame_top - frame::metadata_words_at_bottom;
2222   // copy metadata, except the metadata at the top of the (unextended) entry frame
2223   int sz = fsize + frame::metadata_words_at_bottom + (is_bottom_frame && added_argsize == 0 ? 0 : frame::metadata_words_at_top);
2224 
2225   // If we're the bottom-most thawed frame, we're writing to within one word from entrySP
2226   // (we might have one padding word for alignment)
2227   assert(!is_bottom_frame || (_cont.entrySP() - 1 <= to + sz && to + sz <= _cont.entrySP()), "");
2228   assert(!is_bottom_frame || hf.compiled_frame_stack_argsize() != 0 || (to + sz && to + sz == _cont.entrySP()), "");
2229 
2230   copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2231 
2232   patch(f, caller, is_bottom_frame);
2233 
2234   // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2235   assert(!f.is_deoptimized_frame(), "");
2236   if (hf.is_deoptimized_frame()) {
2237     maybe_set_fastpath(f.sp());
2238   } else if (_thread->is_interp_only_mode()
2239               || (_cont.is_preempted() && f.cb()->as_compiled_method()->is_marked_for_deoptimization())) {
2240     // The caller of the safepoint stub when the continuation is preempted is not at a call instruction, and so
2241     // cannot rely on nmethod patching for deopt.
2242     assert(_thread->is_interp_only_mode() || stub_caller, "expected a stub-caller");
2243 
2244     log_develop_trace(continuations)("Deoptimizing thawed frame");
2245     DEBUG_ONLY(ContinuationHelper::Frame::patch_pc(f, nullptr));
2246 
2247     f.deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2248     assert(f.is_deoptimized_frame(), "");
2249     assert(ContinuationHelper::Frame::is_deopt_return(f.raw_pc(), f), "");
2250     maybe_set_fastpath(f.sp());
2251   }
2252 
2253   if (!is_bottom_frame) {
2254     // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2255     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance);
2256   } else if (_cont.tail()->has_bitmap() && added_argsize > 0) {
2257     clear_bitmap_bits(heap_frame_top + ContinuationHelper::CompiledFrame::size(hf) + frame::metadata_words_at_top, added_argsize);
2258   }
2259 
2260   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2261   caller = f;
2262 }
2263 
2264 void ThawBase::recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames) {
2265   DEBUG_ONLY(_frames++;)
2266 
2267   {
2268     RegisterMap map(nullptr,
2269                     RegisterMap::UpdateMap::include,
2270                     RegisterMap::ProcessFrames::skip,
2271                     RegisterMap::WalkContinuation::skip);
2272     map.set_include_argument_oops(false);
2273     _stream.next(&map);
2274     assert(!_stream.is_done(), "");
2275     if (UNLIKELY(seen_by_gc())) { // we're now doing this on the stub's caller
2276       _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, &map);
2277     }
2278     assert(!_stream.is_done(), "");
2279   }
2280 
2281   recurse_thaw_compiled_frame(_stream.to_frame(), caller, num_frames, true); // this could be deoptimized
2282 
2283   DEBUG_ONLY(before_thaw_java_frame(hf, caller, false, num_frames);)
2284 
2285   assert(ContinuationHelper::Frame::is_stub(hf.cb()), "");
2286   assert(caller.sp() == caller.unextended_sp(), "");
2287   assert(!caller.is_interpreted_frame(), "");
2288 
2289   int fsize = ContinuationHelper::StubFrame::size(hf);
2290 
2291   frame f = new_stack_frame<ContinuationHelper::StubFrame>(hf, caller, false);
2292   intptr_t* stack_frame_top = f.sp();
2293   intptr_t* heap_frame_top = hf.sp();
2294 
2295   copy_from_chunk(heap_frame_top - frame::metadata_words, stack_frame_top - frame::metadata_words,
2296                   fsize + frame::metadata_words);
2297 
2298   { // can only fix caller once this frame is thawed (due to callee saved regs)
2299     RegisterMap map(nullptr,
2300                     RegisterMap::UpdateMap::include,
2301                     RegisterMap::ProcessFrames::skip,
2302                     RegisterMap::WalkContinuation::skip); // map.clear();
2303     map.set_include_argument_oops(false);
2304     f.oop_map()->update_register_map(&f, &map);
2305     ContinuationHelper::update_register_map_with_callee(caller, &map);
2306     _cont.tail()->fix_thawed_frame(caller, &map);
2307   }
2308 
2309   DEBUG_ONLY(after_thaw_java_frame(f, false);)
2310   caller = f;
2311 }
2312 
2313 void ThawBase::finish_thaw(frame& f) {
2314   stackChunkOop chunk = _cont.tail();
2315 
2316   if (chunk->is_empty()) {
2317     // Only remove chunk from list if it can't be reused for another freeze
2318     if (seen_by_gc()) {
2319       _cont.set_tail(chunk->parent());
2320     } else {
2321       chunk->set_has_mixed_frames(false);
2322     }
2323     chunk->set_max_thawing_size(0);
2324     assert(chunk->argsize() == 0, "");
2325   } else {
2326     chunk->set_max_thawing_size(chunk->max_thawing_size() - _align_size);
2327   }
2328   assert(chunk->is_empty() == (chunk->max_thawing_size() == 0), "");
2329 
2330   if (!is_aligned(f.sp(), frame::frame_alignment)) {
2331     assert(f.is_interpreted_frame(), "");
2332     f.set_sp(align_down(f.sp(), frame::frame_alignment));
2333   }
2334   push_return_frame(f);
2335   chunk->fix_thawed_frame(f, SmallRegisterMap::instance); // can only fix caller after push_return_frame (due to callee saved regs)
2336 
2337   assert(_cont.is_empty() == _cont.last_frame().is_empty(), "");
2338 
2339   log_develop_trace(continuations)("thawed %d frames", _frames);
2340 
2341   LogTarget(Trace, continuations) lt;
2342   if (lt.develop_is_enabled()) {
2343     LogStream ls(lt);
2344     ls.print_cr("top hframe after (thaw):");
2345     _cont.last_frame().print_value_on(&ls, nullptr);
2346   }
2347 }
2348 
2349 void ThawBase::push_return_frame(frame& f) { // see generate_cont_thaw
2350   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == f.cb()->as_compiled_method()->is_deopt_pc(f.raw_pc()), "");
2351   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == (f.pc() != f.raw_pc()), "");
2352 
2353   LogTarget(Trace, continuations) lt;
2354   if (lt.develop_is_enabled()) {
2355     LogStream ls(lt);
2356     ls.print_cr("push_return_frame");
2357     f.print_value_on(&ls, nullptr);
2358   }
2359 
2360   assert(f.sp() - frame::metadata_words_at_bottom >= _top_stack_address, "overwrote past thawing space"
2361     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(f.sp() - frame::metadata_words), p2i(_top_stack_address));
2362   ContinuationHelper::Frame::patch_pc(f, f.raw_pc()); // in case we want to deopt the frame in a full transition, this is checked.
2363   ContinuationHelper::push_pd(f);
2364 
2365   assert(ContinuationHelper::Frame::assert_frame_laid_out(f), "");
2366 }
2367 
2368 // returns new top sp
2369 // called after preparations (stack overflow check and making room)
2370 template<typename ConfigT>
2371 static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind) {
2372   assert(thread == JavaThread::current(), "Must be current thread");
2373 
2374   CONT_JFR_ONLY(EventContinuationThaw event;)
2375 
2376   log_develop_trace(continuations)("~~~~ thaw kind: %d sp: " INTPTR_FORMAT, kind, p2i(thread->last_continuation()->entry_sp()));
2377 
2378   ContinuationEntry* entry = thread->last_continuation();
2379   assert(entry != nullptr, "");
2380   oop oopCont = entry->cont_oop(thread);
2381 
2382   assert(!jdk_internal_vm_Continuation::done(oopCont), "");
2383   assert(oopCont == get_continuation(thread), "");
2384   verify_continuation(oopCont);
2385 
2386   assert(entry->is_virtual_thread() == (entry->scope(thread) == java_lang_VirtualThread::vthread_scope()), "");
2387 
2388   ContinuationWrapper cont(thread, oopCont);
2389   log_develop_debug(continuations)("THAW #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
2390 
2391 #ifdef ASSERT
2392   set_anchor_to_entry(thread, cont.entry());
2393   log_frames(thread);
2394   clear_anchor(thread);
2395 #endif
2396 
2397   Thaw<ConfigT> thw(thread, cont);
2398   intptr_t* const sp = thw.thaw(kind);
2399   assert(is_aligned(sp, frame::frame_alignment), "");
2400 
2401   // All the frames have been thawed so we know they don't hold any monitors
2402   assert(thread->held_monitor_count() == 0, "Must be");
2403 
2404 #ifdef ASSERT
2405   intptr_t* sp0 = sp;
2406   address pc0 = *(address*)(sp - frame::sender_sp_ret_address_offset());
2407   set_anchor(thread, sp0);
2408   log_frames(thread);
2409   if (LoomVerifyAfterThaw) {
2410     assert(do_verify_after_thaw(thread, cont.tail(), tty), "");
2411   }
2412   assert(ContinuationEntry::assert_entry_frame_laid_out(thread), "");
2413   clear_anchor(thread);
2414 
2415   LogTarget(Trace, continuations) lt;
2416   if (lt.develop_is_enabled()) {
2417     LogStream ls(lt);
2418     ls.print_cr("Jumping to frame (thaw):");
2419     frame(sp).print_value_on(&ls, nullptr);
2420   }
2421 #endif
2422 
2423   CONT_JFR_ONLY(thw.jfr_info().post_jfr_event(&event, cont.continuation(), thread);)
2424 
2425   verify_continuation(cont.continuation());
2426   log_develop_debug(continuations)("=== End of thaw #" INTPTR_FORMAT, cont.hash());
2427 
2428   return sp;
2429 }
2430 
2431 #ifdef ASSERT
2432 static void do_deopt_after_thaw(JavaThread* thread) {
2433   int i = 0;
2434   StackFrameStream fst(thread, true, false);
2435   fst.register_map()->set_include_argument_oops(false);
2436   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
2437   for (; !fst.is_done(); fst.next()) {
2438     if (fst.current()->cb()->is_compiled()) {
2439       CompiledMethod* cm = fst.current()->cb()->as_compiled_method();
2440       if (!cm->method()->is_continuation_native_intrinsic()) {
2441         cm->make_deoptimized();
2442       }
2443     }
2444   }
2445 }
2446 
2447 class ThawVerifyOopsClosure: public OopClosure {
2448   intptr_t* _p;
2449   outputStream* _st;
2450   bool is_good_oop(oop o) {
2451     return dbg_is_safe(o, -1) && dbg_is_safe(o->klass(), -1) && oopDesc::is_oop(o) && o->klass()->is_klass();
2452   }
2453 public:
2454   ThawVerifyOopsClosure(outputStream* st) : _p(nullptr), _st(st) {}
2455   intptr_t* p() { return _p; }
2456   void reset() { _p = nullptr; }
2457 
2458   virtual void do_oop(oop* p) {
2459     oop o = *p;
2460     if (o == nullptr || is_good_oop(o)) {
2461       return;
2462     }
2463     _p = (intptr_t*)p;
2464     _st->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT, p2i(*p), p2i(p));
2465   }
2466   virtual void do_oop(narrowOop* p) {
2467     oop o = RawAccess<>::oop_load(p);
2468     if (o == nullptr || is_good_oop(o)) {
2469       return;
2470     }
2471     _p = (intptr_t*)p;
2472     _st->print_cr("*** (narrow) non-oop %x found at " PTR_FORMAT, (int)(*p), p2i(p));
2473   }
2474 };
2475 
2476 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st) {
2477   assert(thread->has_last_Java_frame(), "");
2478 
2479   ResourceMark rm;
2480   ThawVerifyOopsClosure cl(st);
2481   CodeBlobToOopClosure cf(&cl, false);
2482 
2483   StackFrameStream fst(thread, true, false);
2484   fst.register_map()->set_include_argument_oops(false);
2485   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
2486   for (; !fst.is_done() && !Continuation::is_continuation_enterSpecial(*fst.current()); fst.next()) {
2487     if (fst.current()->cb()->is_compiled() && fst.current()->cb()->as_compiled_method()->is_marked_for_deoptimization()) {
2488       st->print_cr(">>> do_verify_after_thaw deopt");
2489       fst.current()->deoptimize(nullptr);
2490       fst.current()->print_on(st);
2491     }
2492 
2493     fst.current()->oops_do(&cl, &cf, fst.register_map());
2494     if (cl.p() != nullptr) {
2495       frame fr = *fst.current();
2496       st->print_cr("Failed for frame barriers: %d",chunk->requires_barriers());
2497       fr.print_on(st);
2498       if (!fr.is_interpreted_frame()) {
2499         st->print_cr("size: %d argsize: %d",
2500                      ContinuationHelper::NonInterpretedUnknownFrame::size(fr),
2501                      ContinuationHelper::NonInterpretedUnknownFrame::stack_argsize(fr));
2502       }
2503       VMReg reg = fst.register_map()->find_register_spilled_here(cl.p(), fst.current()->sp());
2504       if (reg != nullptr) {
2505         st->print_cr("Reg %s %d", reg->name(), reg->is_stack() ? (int)reg->reg2stack() : -99);
2506       }
2507       cl.reset();
2508       DEBUG_ONLY(thread->print_frame_layout();)
2509       if (chunk != nullptr) {
2510         chunk->print_on(true, st);
2511       }
2512       return false;
2513     }
2514   }
2515   return true;
2516 }
2517 
2518 static void log_frames(JavaThread* thread) {
2519   const static int show_entry_callers = 3;
2520   LogTarget(Trace, continuations) lt;
2521   if (!lt.develop_is_enabled()) {
2522     return;
2523   }
2524   LogStream ls(lt);
2525 
2526   ls.print_cr("------- frames ---------");
2527   if (!thread->has_last_Java_frame()) {
2528     ls.print_cr("NO ANCHOR!");
2529   }
2530 
2531   RegisterMap map(thread,
2532                   RegisterMap::UpdateMap::include,
2533                   RegisterMap::ProcessFrames::include,
2534                   RegisterMap::WalkContinuation::skip);
2535   map.set_include_argument_oops(false);
2536 
2537   if (false) {
2538     for (frame f = thread->last_frame(); !f.is_entry_frame(); f = f.sender(&map)) {
2539       f.print_on(&ls);
2540     }
2541   } else {
2542     map.set_skip_missing(true);
2543     ResetNoHandleMark rnhm;
2544     ResourceMark rm;
2545     HandleMark hm(Thread::current());
2546     FrameValues values;
2547 
2548     int i = 0;
2549     int post_entry = -1;
2550     for (frame f = thread->last_frame(); !f.is_entry_frame(); f = f.sender(&map)) {
2551       f.describe(values, i++, &map);
2552       if (post_entry >= 0 || Continuation::is_continuation_enterSpecial(f))
2553         post_entry++;
2554       if (post_entry >= show_entry_callers)
2555         break;
2556     }
2557     values.print_on(thread, &ls);
2558   }
2559 
2560   ls.print_cr("======= end frames =========");
2561 }
2562 #endif // ASSERT
2563 
2564 #include CPU_HEADER_INLINE(continuationFreezeThaw)
2565 
2566 #ifdef ASSERT
2567 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st) {
2568   ResourceMark rm;
2569   FrameValues values;
2570   assert(f.get_cb() != nullptr, "");
2571   RegisterMap map(f.is_heap_frame() ?
2572                     nullptr :
2573                     JavaThread::current(),
2574                   RegisterMap::UpdateMap::include,
2575                   RegisterMap::ProcessFrames::skip,
2576                   RegisterMap::WalkContinuation::skip);
2577   map.set_include_argument_oops(false);
2578   map.set_skip_missing(true);
2579   if (callee_complete) {
2580     frame::update_map_with_saved_link(&map, ContinuationHelper::Frame::callee_link_address(f));
2581   }
2582   const_cast<frame&>(f).describe(values, 0, &map);
2583   values.print_on(static_cast<JavaThread*>(nullptr), st);
2584 }
2585 #endif
2586 
2587 static address thaw_entry   = nullptr;
2588 static address freeze_entry = nullptr;
2589 
2590 address Continuation::thaw_entry() {
2591   return ::thaw_entry;
2592 }
2593 
2594 address Continuation::freeze_entry() {
2595   return ::freeze_entry;
2596 }
2597 
2598 class ConfigResolve {
2599 public:
2600   static void resolve() { resolve_compressed(); }
2601 
2602   static void resolve_compressed() {
2603     UseCompressedOops ? resolve_gc<true>()
2604                       : resolve_gc<false>();
2605   }
2606 
2607 private:
2608   template <bool use_compressed>
2609   static void resolve_gc() {
2610     BarrierSet* bs = BarrierSet::barrier_set();
2611     assert(bs != nullptr, "freeze/thaw invoked before BarrierSet is set");
2612     switch (bs->kind()) {
2613 #define BARRIER_SET_RESOLVE_BARRIER_CLOSURE(bs_name)                    \
2614       case BarrierSet::bs_name: {                                       \
2615         resolve<use_compressed, typename BarrierSet::GetType<BarrierSet::bs_name>::type>(); \
2616       }                                                                 \
2617         break;
2618       FOR_EACH_CONCRETE_BARRIER_SET_DO(BARRIER_SET_RESOLVE_BARRIER_CLOSURE)
2619 #undef BARRIER_SET_RESOLVE_BARRIER_CLOSURE
2620 
2621     default:
2622       fatal("BarrierSet resolving not implemented");
2623     };
2624   }
2625 
2626   template <bool use_compressed, typename BarrierSetT>
2627   static void resolve() {
2628     typedef Config<use_compressed ? oop_kind::NARROW : oop_kind::WIDE, BarrierSetT> SelectedConfigT;
2629 
2630     freeze_entry = (address)freeze<SelectedConfigT>;
2631 
2632     // If we wanted, we could templatize by kind and have three different thaw entries
2633     thaw_entry   = (address)thaw<SelectedConfigT>;
2634   }
2635 };
2636 
2637 void Continuation::init() {
2638   ConfigResolve::resolve();
2639 }