1 /*
   2  * Copyright (c) 2018, 2024, 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/nmethod.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/objectMonitor.inline.hpp"
  59 #include "runtime/orderAccess.hpp"
  60 #include "runtime/prefetch.inline.hpp"
  61 #include "runtime/smallRegisterMap.inline.hpp"
  62 #include "runtime/sharedRuntime.hpp"
  63 #include "runtime/stackChunkFrameStream.inline.hpp"
  64 #include "runtime/stackFrameStream.inline.hpp"
  65 #include "runtime/stackOverflow.hpp"
  66 #include "runtime/stackWatermarkSet.inline.hpp"
  67 #include "utilities/debug.hpp"
  68 #include "utilities/exceptions.hpp"
  69 #include "utilities/macros.hpp"
  70 #include "utilities/vmError.hpp"
  71 #if INCLUDE_ZGC
  72 #include "gc/z/zStackChunkGCData.inline.hpp"
  73 #endif
  74 
  75 #include <type_traits>
  76 
  77 /*
  78  * This file contains the implementation of continuation freezing (yield) and thawing (run).
  79  *
  80  * This code is very latency-critical and very hot. An ordinary and well-behaved server application
  81  * would likely call these operations many thousands of times per second second, on every core.
  82  *
  83  * Freeze might be called every time the application performs any I/O operation, every time it
  84  * acquires a j.u.c. lock, every time it takes a message from a queue, and thaw can be called
  85  * multiple times in each of those cases, as it is called by the return barrier, which may be
  86  * invoked on method return.
  87  *
  88  * The amortized budget for each of those two operations is ~100-150ns. That is why, for
  89  * example, every effort is made to avoid Java-VM transitions as much as possible.
  90  *
  91  * On the fast path, all frames are known to be compiled, and the chunk requires no barriers
  92  * and so frames simply copied, and the bottom-most one is patched.
  93  * On the slow path, internal pointers in interpreted frames are de/relativized to/from offsets
  94  * and absolute pointers, and barriers invoked.
  95  */
  96 
  97 /************************************************
  98 
  99 Thread-stack layout on freeze/thaw.
 100 See corresponding stack-chunk layout in instanceStackChunkKlass.hpp
 101 
 102             +----------------------------+
 103             |      .                     |
 104             |      .                     |
 105             |      .                     |
 106             |   carrier frames           |
 107             |                            |
 108             |----------------------------|
 109             |                            |
 110             |    Continuation.run        |
 111             |                            |
 112             |============================|
 113             |    enterSpecial frame      |
 114             |  pc                        |
 115             |  rbp                       |
 116             |  -----                     |
 117         ^   |  int argsize               | = ContinuationEntry
 118         |   |  oopDesc* cont             |
 119         |   |  oopDesc* chunk            |
 120         |   |  ContinuationEntry* parent |
 121         |   |  ...                       |
 122         |   |============================| <------ JavaThread::_cont_entry = entry->sp()
 123         |   |  ? alignment word ?        |
 124         |   |----------------------------| <--\
 125         |   |                            |    |
 126         |   |  ? caller stack args ?     |    |   argsize (might not be 2-word aligned) words
 127 Address |   |                            |    |   Caller is still in the chunk.
 128         |   |----------------------------|    |
 129         |   |  pc (? return barrier ?)   |    |  This pc contains the return barrier when the bottom-most frame
 130         |   |  rbp                       |    |  isn't the last one in the continuation.
 131         |   |                            |    |
 132         |   |    frame                   |    |
 133         |   |                            |    |
 134             +----------------------------|     \__ Continuation frames to be frozen/thawed
 135             |                            |     /
 136             |    frame                   |    |
 137             |                            |    |
 138             |----------------------------|    |
 139             |                            |    |
 140             |    frame                   |    |
 141             |                            |    |
 142             |----------------------------| <--/
 143             |                            |
 144             |    doYield/safepoint stub  | When preempting forcefully, we could have a safepoint stub
 145             |                            | instead of a doYield stub
 146             |============================| <- the sp passed to freeze
 147             |                            |
 148             |  Native freeze/thaw frames |
 149             |      .                     |
 150             |      .                     |
 151             |      .                     |
 152             +----------------------------+
 153 
 154 ************************************************/
 155 
 156 static const bool TEST_THAW_ONE_CHUNK_FRAME = false; // force thawing frames one-at-a-time for testing
 157 
 158 #define CONT_JFR false // emit low-level JFR events that count slow/fast path for continuation performance debugging only
 159 #if CONT_JFR
 160   #define CONT_JFR_ONLY(code) code
 161 #else
 162   #define CONT_JFR_ONLY(code)
 163 #endif
 164 
 165 // TODO: See AbstractAssembler::generate_stack_overflow_check,
 166 // Compile::bang_size_in_bytes(), m->as_SafePoint()->jvms()->interpreter_frame_size()
 167 // when we stack-bang, we need to update a thread field with the lowest (farthest) bang point.
 168 
 169 // Data invariants are defined by Continuation::debug_verify_continuation and Continuation::debug_verify_stack_chunk
 170 
 171 // Used to just annotatate cold/hot branches
 172 #define LIKELY(condition)   (condition)
 173 #define UNLIKELY(condition) (condition)
 174 
 175 // debugging functions
 176 #ifdef ASSERT
 177 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue); // address p is readable and *(intptr_t*)p != errvalue
 178 
 179 static void verify_continuation(oop continuation) { Continuation::debug_verify_continuation(continuation); }
 180 
 181 static void do_deopt_after_thaw(JavaThread* thread);
 182 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st);
 183 static void log_frames(JavaThread* thread);
 184 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp);
 185 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st = tty);
 186 
 187 #define assert_pfl(p, ...) \
 188 do {                                           \
 189   if (!(p)) {                                  \
 190     JavaThread* t = JavaThread::active();      \
 191     if (t->has_last_Java_frame()) {            \
 192       tty->print_cr("assert(" #p ") failed:"); \
 193       t->print_frame_layout();                 \
 194     }                                          \
 195   }                                            \
 196   vmassert(p, __VA_ARGS__);                    \
 197 } while(0)
 198 
 199 #else
 200 static void verify_continuation(oop continuation) { }
 201 #define assert_pfl(p, ...)
 202 #endif
 203 
 204 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint);
 205 template<typename ConfigT, bool preempt> static inline int freeze_internal(JavaThread* thread, intptr_t* const sp, int freeze_kind = freeze_self_from_java);
 206 
 207 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier);
 208 template<typename ConfigT> static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind);
 209 
 210 
 211 // Entry point to freeze. Transitions are handled manually
 212 // Called from gen_continuation_yield() in sharedRuntime_<cpu>.cpp through Continuation::freeze_entry();
 213 template<typename ConfigT>
 214 static JRT_BLOCK_ENTRY(int, freeze(JavaThread* current, intptr_t* sp))
 215   assert(sp == current->frame_anchor()->last_Java_sp(), "");
 216 
 217   if (current->raw_cont_fastpath() > current->last_continuation()->entry_sp() || current->raw_cont_fastpath() < sp) {
 218     current->set_cont_fastpath(nullptr);
 219   }
 220 
 221   return ConfigT::freeze(current, sp);
 222 JRT_END
 223 
 224 JRT_LEAF(int, Continuation::prepare_thaw(JavaThread* thread, bool return_barrier))
 225   return prepare_thaw_internal(thread, return_barrier);
 226 JRT_END
 227 
 228 template<typename ConfigT>
 229 static JRT_LEAF(intptr_t*, thaw(JavaThread* thread, int kind))
 230   // TODO: JRT_LEAF and NoHandleMark is problematic for JFR events.
 231   // vFrameStreamCommon allocates Handles in RegisterMap for continuations.
 232   // Also the preemption case with JVMTI events enabled might safepoint so
 233   // undo the NoSafepointVerifier here and rely on handling by ContinuationWrapper.
 234   // JRT_ENTRY instead?
 235   ResetNoHandleMark rnhm;
 236   debug_only(PauseNoSafepointVerifier pnsv(&__nsv);)
 237 
 238   // we might modify the code cache via BarrierSetNMethod::nmethod_entry_barrier
 239   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));
 240   return ConfigT::thaw(thread, (Continuation::thaw_kind)kind);
 241 JRT_END
 242 
 243 JVM_ENTRY(jint, CONT_isPinned0(JNIEnv* env, jobject cont_scope)) {
 244   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
 245   return is_pinned0(thread, JNIHandles::resolve(cont_scope), false);
 246 }
 247 JVM_END
 248 
 249 ///////////
 250 
 251 enum class oop_kind { NARROW, WIDE };
 252 template <oop_kind oops, typename BarrierSetT>
 253 class Config {
 254 public:
 255   typedef Config<oops, BarrierSetT> SelfT;
 256   using OopT = std::conditional_t<oops == oop_kind::NARROW, narrowOop, oop>;
 257 
 258   static int freeze(JavaThread* thread, intptr_t* const sp) {
 259     return freeze_internal<SelfT, false>(thread, sp);
 260   }
 261 
 262   static int freeze_preempt(JavaThread* thread, intptr_t* const sp, int preempt_kind) {
 263     return freeze_internal<SelfT, true>(thread, sp, preempt_kind);
 264   }
 265 
 266   static intptr_t* thaw(JavaThread* thread, Continuation::thaw_kind kind) {
 267     return thaw_internal<SelfT>(thread, kind);
 268   }
 269 };
 270 
 271 static bool stack_overflow_check(JavaThread* thread, size_t size, address sp) {
 272   const size_t page_size = os::vm_page_size();
 273   if (size > page_size) {
 274     if (sp - size < thread->stack_overflow_state()->shadow_zone_safe_limit()) {
 275       return false;
 276     }
 277   }
 278   return true;
 279 }
 280 
 281 #ifdef ASSERT
 282 static oop get_continuation(JavaThread* thread) {
 283   assert(thread != nullptr, "");
 284   assert(thread->threadObj() != nullptr, "");
 285   return java_lang_Thread::continuation(thread->threadObj());
 286 }
 287 #endif // ASSERT
 288 
 289 inline void clear_anchor(JavaThread* thread) {
 290   thread->frame_anchor()->clear();
 291 }
 292 
 293 static void set_anchor(JavaThread* thread, intptr_t* sp, address pc = nullptr) {
 294   if (pc == nullptr) {
 295     pc = ContinuationHelper::return_address_at(
 296            sp - frame::sender_sp_ret_address_offset());
 297   }
 298   assert(pc != nullptr, "");
 299 
 300   JavaFrameAnchor* anchor = thread->frame_anchor();
 301   anchor->set_last_Java_sp(sp);
 302   anchor->set_last_Java_pc(pc);
 303   ContinuationHelper::set_anchor_pd(anchor, sp);
 304 
 305   assert(thread->has_last_Java_frame(), "");
 306   assert(thread->last_frame().cb() != nullptr, "");
 307 }
 308 
 309 static void set_anchor_to_entry(JavaThread* thread, ContinuationEntry* entry) {
 310   JavaFrameAnchor* anchor = thread->frame_anchor();
 311   anchor->set_last_Java_sp(entry->entry_sp());
 312   anchor->set_last_Java_pc(entry->entry_pc());
 313   ContinuationHelper::set_anchor_to_entry_pd(anchor, entry);
 314 
 315   assert(thread->has_last_Java_frame(), "");
 316   assert(thread->last_frame().cb() != nullptr, "");
 317 }
 318 
 319 #ifdef ASSERT
 320 static int monitors_to_fix_on_stack(JavaThread* thread) {
 321   ResourceMark rm(JavaThread::current());
 322   ContinuationEntry* ce = thread->last_continuation();
 323   RegisterMap map(thread,
 324                   RegisterMap::UpdateMap::include,
 325                   RegisterMap::ProcessFrames::include,
 326                   RegisterMap::WalkContinuation::include);
 327   map.set_include_argument_oops(false);
 328   ResourceHashtable<oopDesc*, bool> rhtable;
 329   int monitor_count = 0;
 330   for (frame f = thread->last_frame(); Continuation::is_frame_in_continuation(thread, f); f = f.sender(&map)) {
 331     if (f.is_interpreted_frame()) {
 332       frame abs = !f.is_heap_frame() ? f : map.stack_chunk()->derelativize(f);
 333       monitor_count += ContinuationHelper::InterpretedFrame::monitors_to_fix(thread, abs, rhtable, map.stack_chunk()());
 334     } else if (f.is_compiled_frame()) {
 335       monitor_count += ContinuationHelper::CompiledFrame::monitors_to_fix(thread, &map, f, rhtable);
 336     } else if (f.is_native_frame()) {
 337       monitor_count += ContinuationHelper::NativeFrame::monitors_to_fix(thread, f, rhtable);
 338     }
 339   }
 340   return monitor_count;
 341 }
 342 #endif
 343 
 344 #if CONT_JFR
 345 class FreezeThawJfrInfo : public StackObj {
 346   short _e_size;
 347   short _e_num_interpreted_frames;
 348  public:
 349 
 350   FreezeThawJfrInfo() : _e_size(0), _e_num_interpreted_frames(0) {}
 351   inline void record_interpreted_frame() { _e_num_interpreted_frames++; }
 352   inline void record_size_copied(int size) { _e_size += size << LogBytesPerWord; }
 353   template<typename Event> void post_jfr_event(Event *e, oop continuation, JavaThread* jt);
 354 };
 355 
 356 template<typename Event> void FreezeThawJfrInfo::post_jfr_event(Event* e, oop continuation, JavaThread* jt) {
 357   if (e->should_commit()) {
 358     log_develop_trace(continuations)("JFR event: iframes: %d size: %d", _e_num_interpreted_frames, _e_size);
 359     e->set_carrierThread(JFR_JVM_THREAD_ID(jt));
 360     e->set_continuationClass(continuation->klass());
 361     e->set_interpretedFrames(_e_num_interpreted_frames);
 362     e->set_size(_e_size);
 363     e->commit();
 364   }
 365 }
 366 #endif // CONT_JFR
 367 
 368 /////////////// FREEZE ////
 369 
 370 class FreezeBase : public StackObj {
 371 protected:
 372   JavaThread* const _thread;
 373   ContinuationWrapper& _cont;
 374   bool _barriers; // only set when we allocate a chunk
 375 
 376   intptr_t* _bottom_address;
 377 
 378   const bool _preempt;
 379   // Used on preemption only
 380   frame _last_frame;
 381   oop _monitorenter_obj;
 382 
 383   // Used to support freezing with held monitors
 384   int _monitors_to_fix;
 385   int _monitors_in_lockstack;
 386 
 387   int _freeze_size; // total size of all frames plus metadata in words.
 388   int _total_align_size;
 389 
 390   intptr_t* _cont_stack_top;
 391   intptr_t* _cont_stack_bottom;
 392 
 393   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
 394 
 395 #ifdef ASSERT
 396   intptr_t* _orig_chunk_sp;
 397   int _fast_freeze_size;
 398   bool _empty;
 399 #endif
 400 
 401   JvmtiSampledObjectAllocEventCollector* _jvmti_event_collector;
 402 
 403   NOT_PRODUCT(int _frames;)
 404   DEBUG_ONLY(intptr_t* _last_write;)
 405 
 406   inline FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp, bool preempt);
 407 
 408 public:
 409   NOINLINE freeze_result freeze_slow();
 410   void freeze_fast_existing_chunk();
 411 
 412   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
 413   void set_jvmti_event_collector(JvmtiSampledObjectAllocEventCollector* jsoaec) { _jvmti_event_collector = jsoaec; }
 414 
 415   inline int size_if_fast_freeze_available();
 416 
 417   inline frame& last_frame() { return _last_frame; }
 418   inline void set_last_frame() { _last_frame = _thread->last_frame(); }
 419 
 420 #ifdef ASSERT
 421   bool check_valid_fast_path();
 422 #endif
 423 
 424 protected:
 425   inline void init_rest();
 426   void throw_stack_overflow_on_humongous_chunk();
 427 
 428   // fast path
 429   inline void copy_to_chunk(intptr_t* from, intptr_t* to, int size);
 430   inline void unwind_frames();
 431   inline void patch_stack_pd(intptr_t* frame_sp, intptr_t* heap_sp);
 432 
 433   // slow path
 434   virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) = 0;
 435 
 436   int cont_size() { return pointer_delta_as_int(_cont_stack_bottom, _cont_stack_top); }
 437 
 438 private:
 439   // slow path
 440   frame freeze_start_frame();
 441   frame freeze_start_frame_on_preempt();
 442   NOINLINE freeze_result recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top);
 443   inline frame freeze_start_frame_yield_stub();
 444   template<typename FKind>
 445   inline freeze_result recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize);
 446   inline void before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame);
 447   inline void after_freeze_java_frame(const frame& hf, bool is_bottom_frame);
 448   freeze_result finalize_freeze(const frame& callee, frame& caller, int argsize);
 449   void patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame);
 450   NOINLINE freeze_result recurse_freeze_interpreted_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 451   freeze_result recurse_freeze_compiled_frame(frame& f, frame& caller, int callee_argsize, bool callee_interpreted);
 452   NOINLINE freeze_result recurse_freeze_stub_frame(frame& f, frame& caller);
 453   NOINLINE freeze_result recurse_freeze_native_frame(frame& f, frame& caller);
 454   NOINLINE void finish_freeze(const frame& f, const frame& top);
 455 
 456   void fix_monitors_in_interpreted_frame(frame& f);
 457   template <typename RegisterMapT>
 458   void fix_monitors_in_compiled_frame(frame& f, RegisterMapT* map);
 459   void fix_monitors_in_fast_path();
 460 
 461   inline bool stack_overflow();
 462 
 463   static frame sender(const frame& f) { return f.is_interpreted_frame() ? sender<ContinuationHelper::InterpretedFrame>(f)
 464                                                                         : sender<ContinuationHelper::NonInterpretedUnknownFrame>(f); }
 465   template<typename FKind> static inline frame sender(const frame& f);
 466   template<typename FKind> frame new_heap_frame(frame& f, frame& caller);
 467   inline void set_top_frame_metadata_pd(const frame& hf);
 468   inline void patch_pd(frame& callee, const frame& caller);
 469   void adjust_interpreted_frame_unextended_sp(frame& f);
 470   static inline void prepare_freeze_interpreted_top_frame(const frame& f);
 471   static inline void relativize_interpreted_frame_metadata(const frame& f, const frame& hf);
 472 
 473 protected:
 474   void freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated));
 475   bool freeze_fast_new_chunk(stackChunkOop chunk);
 476 };
 477 
 478 template <typename ConfigT>
 479 class Freeze : public FreezeBase {
 480 private:
 481   stackChunkOop allocate_chunk(size_t stack_size, int argsize_md);
 482 
 483 public:
 484   inline Freeze(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt)
 485     : FreezeBase(thread, cont, frame_sp, preempt) {}
 486 
 487   freeze_result try_freeze_fast();
 488 
 489 protected:
 490   virtual stackChunkOop allocate_chunk_slow(size_t stack_size, int argsize_md) override { return allocate_chunk(stack_size, argsize_md); }
 491 };
 492 
 493 FreezeBase::FreezeBase(JavaThread* thread, ContinuationWrapper& cont, intptr_t* frame_sp, bool preempt) :
 494     _thread(thread), _cont(cont), _barriers(false), _preempt(preempt), _last_frame(false /* no initialization */) {
 495   DEBUG_ONLY(_jvmti_event_collector = nullptr;)
 496 
 497   assert(_thread != nullptr, "");
 498   assert(_thread->last_continuation()->entry_sp() == _cont.entrySP(), "");
 499 
 500   DEBUG_ONLY(_cont.entry()->verify_cookie();)
 501 
 502   assert(!Interpreter::contains(_cont.entryPC()), "");
 503 
 504   _bottom_address = _cont.entrySP() - _cont.entry_frame_extension();
 505 #ifdef _LP64
 506   if (((intptr_t)_bottom_address & 0xf) != 0) {
 507     _bottom_address--;
 508   }
 509   assert(is_aligned(_bottom_address, frame::frame_alignment), "");
 510 #endif
 511 
 512   log_develop_trace(continuations)("bottom_address: " INTPTR_FORMAT " entrySP: " INTPTR_FORMAT " argsize: " PTR_FORMAT,
 513                 p2i(_bottom_address), p2i(_cont.entrySP()), (_cont.entrySP() - _bottom_address) << LogBytesPerWord);
 514   assert(_bottom_address != nullptr, "");
 515   assert(_bottom_address <= _cont.entrySP(), "");
 516   DEBUG_ONLY(_last_write = nullptr;)
 517 
 518   assert(_cont.chunk_invariant(), "");
 519   assert(!Interpreter::contains(_cont.entryPC()), "");
 520 #if !defined(PPC64) || defined(ZERO)
 521   static const int doYield_stub_frame_size = frame::metadata_words;
 522 #else
 523   static const int doYield_stub_frame_size = frame::native_abi_reg_args_size >> LogBytesPerWord;
 524 #endif
 525   // With preemption doYield() might not have been resolved yet
 526   assert(_preempt || SharedRuntime::cont_doYield_stub()->frame_size() == doYield_stub_frame_size, "");
 527 
 528   // properties of the continuation on the stack; all sizes are in words
 529   _cont_stack_top    = frame_sp + (!preempt ? doYield_stub_frame_size : 0); // we don't freeze the doYield stub frame
 530   _cont_stack_bottom = _cont.entrySP() + (_cont.argsize() == 0 ? frame::metadata_words_at_top : 0)
 531       - ContinuationHelper::frame_align_words(_cont.argsize()); // see alignment in thaw
 532 
 533   log_develop_trace(continuations)("freeze size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 534     cont_size(), _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 535   assert(cont_size() > 0, "");
 536 
 537   if (LockingMode == LM_LEGACY) {
 538     _monitors_to_fix = thread->held_monitor_count();
 539     assert(_monitors_to_fix >= 0, "invariant");
 540     _monitors_in_lockstack = 0;
 541     assert(_thread->lock_stack().monitor_count() == 0, "should be set only for LM_LIGHTWEIGHT");
 542   } else {
 543     _monitors_in_lockstack = _thread->lock_stack().monitor_count();
 544     assert(_monitors_in_lockstack >= 0 && _monitors_in_lockstack <= 8, "_monitors_in_lockstack=%d", _monitors_in_lockstack);
 545     _monitors_to_fix = _monitors_in_lockstack;
 546     assert(thread->held_monitor_count() == 0, "should be set only for LM_LEGACY");
 547   }
 548   DEBUG_ONLY(int verified_cnt = monitors_to_fix_on_stack(_thread);)
 549   assert(verified_cnt == _monitors_to_fix || thread->obj_locker_count() > 0 ||
 550          (LockingMode == LM_LIGHTWEIGHT && verified_cnt == _thread->lock_stack().unique_count()),
 551          "wrong monitor count. Found %d in the stack but counter is %d", verified_cnt, _monitors_to_fix);
 552 }
 553 
 554 void FreezeBase::init_rest() { // we want to postpone some initialization after chunk handling
 555   _freeze_size = 0;
 556   _total_align_size = 0;
 557   NOT_PRODUCT(_frames = 0;)
 558 }
 559 
 560 void FreezeBase::fix_monitors_in_interpreted_frame(frame& f) {
 561   assert(LockingMode == LM_LEGACY, "invariant");
 562   BasicObjectLock* first_mon = f.interpreter_frame_monitor_begin();
 563   BasicObjectLock* last_mon = f.interpreter_frame_monitor_end();
 564   assert(last_mon <= first_mon, "must be");
 565 
 566   if (first_mon == last_mon) {
 567     // No monitors in this frame
 568     return;
 569   }
 570 
 571   for (BasicObjectLock* current = f.previous_monitor_in_interpreter_frame(first_mon);
 572        current >= last_mon; current = f.previous_monitor_in_interpreter_frame(current)) {
 573     oop obj = current->obj();
 574     if (obj == nullptr) {
 575       continue;
 576     }
 577     if (obj == _monitorenter_obj) {
 578       assert(_preempt, "should be preemption on monitorenter case");
 579       assert(obj->mark().monitor() != nullptr, "failed to acquire the lock but its not inflated");
 580       continue;
 581     }
 582     markWord mark = obj->mark();
 583     if (mark.has_monitor() && !mark.monitor()->is_owner_anonymous()) {
 584       // Good for freezing, nothing to do.
 585       assert(mark.monitor()->is_owner(_thread), "invariant");
 586       continue;
 587     }
 588     // Found locked monitor that needs fixing. Inflate will fix the owner for stack-locked case or inflated but anonymously owned.
 589     ObjectMonitor* om = ObjectSynchronizer::inflate(_thread, obj, ObjectSynchronizer::InflateCause::inflate_cause_cont_freeze);
 590     assert(om != nullptr, "invariant");
 591     assert(om->is_owner(_thread), "invariant");
 592     if (--_monitors_to_fix == 0) break;
 593   }
 594   assert(_monitors_to_fix >= 0, "invariant");
 595 }
 596 
 597 template <typename RegisterMapT>
 598 void FreezeBase::fix_monitors_in_compiled_frame(frame& f, RegisterMapT* map) {
 599   assert(LockingMode == LM_LEGACY, "invariant");
 600   assert(!f.is_interpreted_frame(), "");
 601   assert(ContinuationHelper::CompiledFrame::is_instance(f), "");
 602 
 603   nmethod* nm = f.cb()->as_nmethod();
 604 
 605   if (!nm->has_monitors()) {
 606     // No monitors in this frame
 607     return;
 608   }
 609 
 610   for (ScopeDesc* scope = nm->scope_desc_at(f.pc()); scope != nullptr; scope = scope->sender()) {
 611     GrowableArray<MonitorValue*>* mons = scope->monitors();
 612     if (mons == nullptr || mons->is_empty()) {
 613       continue;
 614     }
 615 
 616     for (int index = (mons->length()-1); index >= 0; index--) { // see compiledVFrame::monitors()
 617       MonitorValue* mon = mons->at(index);
 618       if (mon->eliminated()) {
 619         continue; // we ignore eliminated monitors
 620       }
 621       ScopeValue* ov = mon->owner();
 622       StackValue* owner_sv = StackValue::create_stack_value(&f, map, ov); // it is an oop
 623       oop obj = owner_sv->get_obj()();
 624       if (obj == nullptr) {
 625         continue;
 626       }
 627       if (obj == _monitorenter_obj) {
 628         assert(_preempt, "should be preemption on monitorenter case");
 629         assert(obj->mark().monitor() != nullptr, "failed to acquire the lock but its not inflated");
 630         continue;
 631       }
 632       markWord mark = obj->mark();
 633       if (mark.has_monitor() && !mark.monitor()->is_owner_anonymous()) {
 634         // Good for freezing, nothing to do.
 635         assert(mark.monitor()->is_owner(_thread), "invariant");
 636         continue;
 637       }
 638       // Found locked monitor that needs fixing. Inflate will fix the owner for stack-locked case or inflated but anonymously owned.
 639       ObjectMonitor* om = ObjectSynchronizer::inflate(_thread, obj, ObjectSynchronizer::InflateCause::inflate_cause_cont_freeze);
 640       assert(om != nullptr, "invariant");
 641       assert(om->is_owner(_thread), "invariant");
 642       if (--_monitors_to_fix == 0) break;
 643     }
 644   }
 645   assert(_monitors_to_fix >= 0, "invariant");
 646 }
 647 
 648 void FreezeBase::fix_monitors_in_fast_path() {
 649   if (LockingMode == LM_LIGHTWEIGHT) {
 650     stackChunkOop chunk = _cont.tail();
 651     assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "no room for lockstack");
 652     _thread->lock_stack().move_to_address((oop*)chunk->start_address());
 653 
 654     chunk->set_lockstack_size((uint8_t)_monitors_in_lockstack);
 655     chunk->set_has_lockstack(true);
 656 
 657     DEBUG_ONLY(_monitors_to_fix -= _monitors_in_lockstack;)
 658   } else {
 659     assert(LockingMode == LM_LEGACY, "invariant");
 660     _monitorenter_obj = _thread->is_on_monitorenter() ? _thread->current_pending_monitor()->object() : nullptr;
 661 
 662     ResourceMark rm(_thread);
 663     RegisterMap map(JavaThread::current(),
 664                   RegisterMap::UpdateMap::include,
 665                   RegisterMap::ProcessFrames::skip, // already processed in unwind_frames()
 666                   RegisterMap::WalkContinuation::skip);
 667     map.set_include_argument_oops(false);
 668     frame freezed_top(_cont_stack_top);
 669     frame first = !_preempt ? freezed_top : freezed_top.sender(&map);
 670     for (frame f = first; _monitors_to_fix > 0 && Continuation::is_frame_in_continuation(_cont.entry(), f); f = f.sender(&map)) {
 671       fix_monitors_in_compiled_frame(f, &map);
 672     }
 673   }
 674   assert(_monitors_to_fix == 0, "missing monitors in stack");
 675   assert(_thread->held_monitor_count() == 0, "should be 0 now");
 676 }
 677 
 678 void FreezeBase::copy_to_chunk(intptr_t* from, intptr_t* to, int size) {
 679   stackChunkOop chunk = _cont.tail();
 680   chunk->copy_from_stack_to_chunk(from, to, size);
 681   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
 682 
 683 #ifdef ASSERT
 684   if (_last_write != nullptr) {
 685     assert(_last_write == to + size, "Missed a spot: _last_write: " INTPTR_FORMAT " to+size: " INTPTR_FORMAT
 686         " stack_size: %d _last_write offset: " PTR_FORMAT " to+size: " PTR_FORMAT, p2i(_last_write), p2i(to+size),
 687         chunk->stack_size(), _last_write-chunk->start_address(), to+size-chunk->start_address());
 688     _last_write = to;
 689   }
 690 #endif
 691 }
 692 
 693 // Called _after_ the last possible safepoint during the freeze operation (chunk allocation)
 694 void FreezeBase::unwind_frames() {
 695   ContinuationEntry* entry = _cont.entry();
 696   entry->flush_stack_processing(_thread);
 697   set_anchor_to_entry(_thread, entry);
 698 }
 699 
 700 template <typename ConfigT>
 701 freeze_result Freeze<ConfigT>::try_freeze_fast() {
 702   assert(_thread->thread_state() == _thread_in_vm, "");
 703   assert(_thread->cont_fastpath(), "");
 704 
 705   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 706   assert(_fast_freeze_size == 0, "");
 707 
 708   stackChunkOop chunk = allocate_chunk(cont_size() + frame::metadata_words + _monitors_in_lockstack, _cont.argsize() + frame::metadata_words_at_top);
 709   if (freeze_fast_new_chunk(chunk)) {
 710     return freeze_ok;
 711   }
 712   if (_thread->has_pending_exception()) {
 713     return freeze_exception;
 714   }
 715 
 716   // TODO R REMOVE when deopt change is fixed
 717   assert(!_thread->cont_fastpath() || _barriers, "");
 718   log_develop_trace(continuations)("-- RETRYING SLOW --");
 719   return freeze_slow();
 720 }
 721 
 722 // Returns size needed if the continuation fits, otherwise 0.
 723 int FreezeBase::size_if_fast_freeze_available() {
 724   stackChunkOop chunk = _cont.tail();
 725   if (chunk == nullptr || chunk->is_gc_mode() || chunk->requires_barriers() || chunk->has_mixed_frames()) {
 726     log_develop_trace(continuations)("chunk available %s", chunk == nullptr ? "no chunk" : "chunk requires barriers");
 727     return 0;
 728   }
 729 
 730   int total_size_needed = cont_size();
 731   const int chunk_sp = chunk->sp();
 732 
 733   // argsize can be nonzero if we have a caller, but the caller could be in a non-empty parent chunk,
 734   // so we subtract it only if we overlap with the caller, i.e. the current chunk isn't empty.
 735   // Consider leaving the chunk's argsize set when emptying it and removing the following branch,
 736   // although that would require changing stackChunkOopDesc::is_empty
 737   if (!chunk->is_empty()) {
 738     total_size_needed -= _cont.argsize() + frame::metadata_words_at_top;
 739   }
 740 
 741   total_size_needed += _monitors_in_lockstack;
 742 
 743   int chunk_free_room = chunk_sp - frame::metadata_words_at_bottom;
 744   bool available = chunk_free_room >= total_size_needed;
 745   log_develop_trace(continuations)("chunk available: %s size: %d argsize: %d top: " INTPTR_FORMAT " bottom: " INTPTR_FORMAT,
 746     available ? "yes" : "no" , total_size_needed, _cont.argsize(), p2i(_cont_stack_top), p2i(_cont_stack_bottom));
 747   return available ? total_size_needed : 0;
 748 }
 749 
 750 void FreezeBase::freeze_fast_existing_chunk() {
 751   stackChunkOop chunk = _cont.tail();
 752 
 753   DEBUG_ONLY(_fast_freeze_size = size_if_fast_freeze_available();)
 754   assert(_fast_freeze_size > 0, "");
 755 
 756   if (!chunk->is_empty()) { // we are copying into a non-empty chunk
 757     DEBUG_ONLY(_empty = false;)
 758     DEBUG_ONLY(_orig_chunk_sp = chunk->sp_address();)
 759 #ifdef ASSERT
 760     {
 761       intptr_t* retaddr_slot = (chunk->sp_address()
 762                                 - frame::sender_sp_ret_address_offset());
 763       assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
 764              "unexpected saved return address");
 765     }
 766 #endif
 767 
 768     // the chunk's sp before the freeze, adjusted to point beyond the stack-passed arguments in the topmost frame
 769     // we overlap; we'll overwrite the chunk's top frame's callee arguments
 770     const int chunk_start_sp = chunk->sp() + _cont.argsize() + frame::metadata_words_at_top;
 771     assert(chunk_start_sp <= chunk->stack_size(), "sp not pointing into stack");
 772 
 773     // increase max_size by what we're freezing minus the overlap
 774     chunk->set_max_thawing_size(chunk->max_thawing_size() + cont_size() - _cont.argsize() - frame::metadata_words_at_top);
 775 
 776     intptr_t* const bottom_sp = _cont_stack_bottom - _cont.argsize() - frame::metadata_words_at_top;
 777     assert(bottom_sp == _bottom_address, "");
 778     // Because the chunk isn't empty, we know there's a caller in the chunk, therefore the bottom-most frame
 779     // should have a return barrier (installed back when we thawed it).
 780 #ifdef ASSERT
 781     {
 782       intptr_t* retaddr_slot = (bottom_sp
 783                                 - frame::sender_sp_ret_address_offset());
 784       assert(ContinuationHelper::return_address_at(retaddr_slot)
 785              == StubRoutines::cont_returnBarrier(),
 786              "should be the continuation return barrier");
 787     }
 788 #endif
 789     // We copy the fp from the chunk back to the stack because it contains some caller data,
 790     // including, possibly, an oop that might have gone stale since we thawed.
 791     patch_stack_pd(bottom_sp, chunk->sp_address());
 792     // we don't patch the return pc at this time, so as not to make the stack unwalkable for async walks
 793 
 794     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 795   } else { // the chunk is empty
 796     const int chunk_start_sp = chunk->stack_size();
 797 
 798     DEBUG_ONLY(_empty = true;)
 799     DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
 800 
 801     chunk->set_max_thawing_size(cont_size());
 802     chunk->set_bottom(chunk_start_sp - _cont.argsize() - frame::metadata_words_at_top);
 803     chunk->set_sp(chunk->bottom());
 804 
 805     freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA false));
 806   }
 807 }
 808 
 809 bool FreezeBase::freeze_fast_new_chunk(stackChunkOop chunk) {
 810   DEBUG_ONLY(_empty = true;)
 811 
 812   // Install new chunk
 813   _cont.set_tail(chunk);
 814 
 815   if (UNLIKELY(chunk == nullptr || !_thread->cont_fastpath() || _barriers)) { // OOME/probably humongous
 816     log_develop_trace(continuations)("Retrying slow. Barriers: %d", _barriers);
 817     return false;
 818   }
 819 
 820   chunk->set_max_thawing_size(cont_size());
 821 
 822   // in a fresh chunk, we freeze *with* the bottom-most frame's stack arguments.
 823   // They'll then be stored twice: in the chunk and in the parent chunk's top frame
 824   const int chunk_start_sp = cont_size() + frame::metadata_words + _monitors_in_lockstack;
 825   assert(chunk_start_sp == chunk->stack_size(), "");
 826 
 827   DEBUG_ONLY(_orig_chunk_sp = chunk->start_address() + chunk_start_sp;)
 828 
 829   freeze_fast_copy(chunk, chunk_start_sp CONT_JFR_ONLY(COMMA true));
 830 
 831   return true;
 832 }
 833 
 834 void FreezeBase::freeze_fast_copy(stackChunkOop chunk, int chunk_start_sp CONT_JFR_ONLY(COMMA bool chunk_is_allocated)) {
 835   assert(chunk != nullptr, "");
 836   assert(!chunk->has_mixed_frames(), "");
 837   assert(!chunk->is_gc_mode(), "");
 838   assert(!chunk->has_bitmap(), "");
 839   assert(!chunk->requires_barriers(), "");
 840   assert(chunk == _cont.tail(), "");
 841 
 842   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
 843   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
 844   // will either see no continuation on the stack, or a consistent chunk.
 845   unwind_frames();
 846 
 847   log_develop_trace(continuations)("freeze_fast start: chunk " INTPTR_FORMAT " size: %d orig sp: %d argsize: %d",
 848     p2i((oopDesc*)chunk), chunk->stack_size(), chunk_start_sp, _cont.argsize());
 849   assert(chunk_start_sp <= chunk->stack_size(), "");
 850   assert(chunk_start_sp >= cont_size(), "no room in the chunk");
 851 
 852   const int chunk_new_sp = chunk_start_sp - cont_size(); // the chunk's new sp, after freeze
 853   assert(!(_fast_freeze_size > 0) || (_orig_chunk_sp - (chunk->start_address() + chunk_new_sp)) == (_fast_freeze_size - _monitors_in_lockstack), "");
 854 
 855   intptr_t* chunk_top = chunk->start_address() + chunk_new_sp;
 856 #ifdef ASSERT
 857   if (!_empty) {
 858     intptr_t* retaddr_slot = (_orig_chunk_sp
 859                               - frame::sender_sp_ret_address_offset());
 860     assert(ContinuationHelper::return_address_at(retaddr_slot) == chunk->pc(),
 861            "unexpected saved return address");
 862   }
 863 #endif
 864 
 865   log_develop_trace(continuations)("freeze_fast start: " INTPTR_FORMAT " sp: %d chunk_top: " INTPTR_FORMAT,
 866                               p2i(chunk->start_address()), chunk_new_sp, p2i(chunk_top));
 867   intptr_t* from = _cont_stack_top - frame::metadata_words_at_bottom;
 868   intptr_t* to   = chunk_top - frame::metadata_words_at_bottom;
 869   copy_to_chunk(from, to, cont_size() + frame::metadata_words_at_bottom);
 870   // Because we're not patched yet, the chunk is now in a bad state
 871 
 872   // patch return pc of the bottom-most frozen frame (now in the chunk)
 873   // with the actual caller's return address
 874   intptr_t* chunk_bottom_retaddr_slot = (chunk_top + cont_size()
 875                                          - _cont.argsize()
 876                                          - frame::metadata_words_at_top
 877                                          - frame::sender_sp_ret_address_offset());
 878 #ifdef ASSERT
 879   if (!_empty) {
 880     assert(ContinuationHelper::return_address_at(chunk_bottom_retaddr_slot)
 881            == StubRoutines::cont_returnBarrier(),
 882            "should be the continuation return barrier");
 883   }
 884 #endif
 885   ContinuationHelper::patch_return_address_at(chunk_bottom_retaddr_slot,
 886                                               chunk->pc());
 887 
 888   // We're always writing to a young chunk, so the GC can't see it until the next safepoint.
 889   chunk->set_sp(chunk_new_sp);
 890   // set chunk->pc to the return address of the topmost frame in the chunk
 891   chunk->set_pc(ContinuationHelper::return_address_at(
 892                   _cont_stack_top - frame::sender_sp_ret_address_offset()));
 893 
 894   // Fix monitors after unwinding frames to make sure oops are valid.
 895   if (_monitors_to_fix > 0) {
 896     fix_monitors_in_fast_path();
 897   }
 898 
 899   _cont.write();
 900 
 901   log_develop_trace(continuations)("FREEZE CHUNK #" INTPTR_FORMAT " (young)", _cont.hash());
 902   LogTarget(Trace, continuations) lt;
 903   if (lt.develop_is_enabled()) {
 904     LogStream ls(lt);
 905     chunk->print_on(true, &ls);
 906   }
 907 
 908   // Verification
 909   assert(_cont.chunk_invariant(), "");
 910   chunk->verify();
 911 
 912 #if CONT_JFR
 913   EventContinuationFreezeFast e;
 914   if (e.should_commit()) {
 915     e.set_id(cast_from_oop<u8>(chunk));
 916     DEBUG_ONLY(e.set_allocate(chunk_is_allocated);)
 917     e.set_size(cont_size() << LogBytesPerWord);
 918     e.commit();
 919   }
 920 #endif
 921 }
 922 
 923 NOINLINE freeze_result FreezeBase::freeze_slow() {
 924 #ifdef ASSERT
 925   ResourceMark rm;
 926 #endif
 927 
 928   log_develop_trace(continuations)("freeze_slow  #" INTPTR_FORMAT, _cont.hash());
 929   assert(_thread->thread_state() == _thread_in_vm || _thread->thread_state() == _thread_blocked, "");
 930 
 931 #if CONT_JFR
 932   EventContinuationFreezeSlow e;
 933   if (e.should_commit()) {
 934     e.set_id(cast_from_oop<u8>(_cont.continuation()));
 935     e.commit();
 936   }
 937 #endif
 938 
 939   init_rest();
 940 
 941   HandleMark hm(Thread::current());
 942 
 943   frame f = freeze_start_frame();
 944 
 945   LogTarget(Debug, continuations) lt;
 946   if (lt.develop_is_enabled()) {
 947     LogStream ls(lt);
 948     f.print_on(&ls);
 949   }
 950 
 951   frame caller; // the frozen caller in the chunk
 952   freeze_result res = recurse_freeze(f, caller, 0, false, true);
 953 
 954   if (res == freeze_ok) {
 955     finish_freeze(f, caller);
 956     _cont.write();
 957     assert(_monitors_to_fix == 0, "missing monitors in stack");
 958     assert(_thread->held_monitor_count() == 0, "should be 0 now");
 959   }
 960 
 961   return res;
 962 }
 963 
 964 frame FreezeBase::freeze_start_frame() {
 965   if (LIKELY(!_preempt)) {
 966     return freeze_start_frame_yield_stub();
 967   } else {
 968     return freeze_start_frame_on_preempt();
 969   }
 970 }
 971 
 972 frame FreezeBase::freeze_start_frame_yield_stub() {
 973   frame f = _thread->last_frame();
 974   assert(SharedRuntime::cont_doYield_stub()->contains(f.pc()), "must be");
 975   f = sender<ContinuationHelper::NonInterpretedUnknownFrame>(f);
 976   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), f), "");
 977   return f;
 978 }
 979 
 980 frame FreezeBase::freeze_start_frame_on_preempt() {
 981   assert(_last_frame.sp() == _thread->last_frame().sp(), "_last_frame should be already initialized");
 982   assert(Continuation::is_frame_in_continuation(_thread->last_continuation(), _last_frame), "");
 983   return _last_frame;
 984 }
 985 
 986 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
 987 NOINLINE freeze_result FreezeBase::recurse_freeze(frame& f, frame& caller, int callee_argsize, bool callee_interpreted, bool top) {
 988   assert(f.unextended_sp() < _bottom_address, ""); // see recurse_freeze_java_frame
 989   assert(f.is_interpreted_frame() || ((top && _preempt) == ContinuationHelper::Frame::is_stub(f.cb()))
 990          || ((top && _preempt) == f.is_native_frame()), "");
 991 
 992   if (stack_overflow()) {
 993     return freeze_exception;
 994   }
 995 
 996   if (f.is_compiled_frame()) {
 997     if (UNLIKELY(f.oop_map() == nullptr)) {
 998       // special native frame
 999       return freeze_pinned_native;
1000     }
1001     return recurse_freeze_compiled_frame(f, caller, callee_argsize, callee_interpreted);
1002   } else if (f.is_interpreted_frame()) {
1003     assert(!f.interpreter_frame_method()->is_native() || (top && _preempt), "");
1004     return recurse_freeze_interpreted_frame(f, caller, callee_argsize, callee_interpreted);
1005   } else if (top && _preempt) {
1006     assert(f.is_native_frame() || f.is_runtime_frame(), "");
1007     return f.is_native_frame() ? recurse_freeze_native_frame(f, caller) : recurse_freeze_stub_frame(f, caller);
1008   } else {
1009     return freeze_pinned_native;
1010   }
1011 }
1012 
1013 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1014 // See also StackChunkFrameStream<frame_kind>::frame_size()
1015 template<typename FKind>
1016 inline freeze_result FreezeBase::recurse_freeze_java_frame(const frame& f, frame& caller, int fsize, int argsize) {
1017   assert(FKind::is_instance(f), "");
1018 
1019   assert(fsize > 0, "");
1020   assert(argsize >= 0, "");
1021   _freeze_size += fsize;
1022   NOT_PRODUCT(_frames++;)
1023 
1024   assert(FKind::frame_bottom(f) <= _bottom_address, "");
1025 
1026   // We don't use FKind::frame_bottom(f) == _bottom_address because on x64 there's sometimes an extra word between
1027   // enterSpecial and an interpreted frame
1028   if (FKind::frame_bottom(f) >= _bottom_address - 1) {
1029     return finalize_freeze(f, caller, argsize); // recursion end
1030   } else {
1031     frame senderf = sender<FKind>(f);
1032     assert(FKind::interpreted || senderf.sp() == senderf.unextended_sp(), "");
1033     freeze_result result = recurse_freeze(senderf, caller, argsize, FKind::interpreted, false); // recursive call
1034     return result;
1035   }
1036 }
1037 
1038 inline void FreezeBase::before_freeze_java_frame(const frame& f, const frame& caller, int fsize, int argsize, bool is_bottom_frame) {
1039   LogTarget(Trace, continuations) lt;
1040   if (lt.develop_is_enabled()) {
1041     LogStream ls(lt);
1042     ls.print_cr("======== FREEZING FRAME interpreted: %d bottom: %d", f.is_interpreted_frame(), is_bottom_frame);
1043     ls.print_cr("fsize: %d argsize: %d", fsize, argsize);
1044     f.print_value_on(&ls, nullptr);
1045   }
1046   assert(caller.is_interpreted_frame() == Interpreter::contains(caller.pc()), "");
1047 }
1048 
1049 inline void FreezeBase::after_freeze_java_frame(const frame& hf, bool is_bottom_frame) {
1050   LogTarget(Trace, continuations) lt;
1051   if (lt.develop_is_enabled()) {
1052     LogStream ls(lt);
1053     DEBUG_ONLY(hf.print_value_on(&ls, nullptr);)
1054     assert(hf.is_heap_frame(), "should be");
1055     DEBUG_ONLY(print_frame_layout(hf, false, &ls);)
1056     if (is_bottom_frame) {
1057       ls.print_cr("bottom h-frame:");
1058       hf.print_on(&ls);
1059     }
1060   }
1061 }
1062 
1063 // The parameter argsize_md includes metadata that has to be part of caller/callee overlap.
1064 // See also StackChunkFrameStream<frame_kind>::frame_size()
1065 freeze_result FreezeBase::finalize_freeze(const frame& callee, frame& caller, int argsize_md) {
1066   int argsize = argsize_md - frame::metadata_words_at_top;
1067   assert(callee.is_interpreted_frame()
1068     || ContinuationHelper::Frame::is_stub(callee.cb())
1069     || callee.cb()->as_nmethod()->is_osr_method()
1070     || argsize == _cont.argsize(), "argsize: %d cont.argsize: %d", argsize, _cont.argsize());
1071   log_develop_trace(continuations)("bottom: " INTPTR_FORMAT " count %d size: %d argsize: %d",
1072     p2i(_bottom_address), _frames, _freeze_size << LogBytesPerWord, argsize);
1073 
1074   LogTarget(Trace, continuations) lt;
1075 
1076 #ifdef ASSERT
1077   bool empty = _cont.is_empty();
1078   log_develop_trace(continuations)("empty: %d", empty);
1079 #endif
1080 
1081   stackChunkOop chunk = _cont.tail();
1082 
1083   assert(chunk == nullptr || (chunk->max_thawing_size() == 0) == chunk->is_empty(), "");
1084 
1085   _freeze_size += frame::metadata_words; // for top frame's metadata
1086 
1087   int overlap = 0; // the args overlap the caller -- if there is one in this chunk and is of the same kind
1088   int unextended_sp = -1;
1089   if (chunk != nullptr) {
1090     if (!chunk->is_empty()) {
1091       StackChunkFrameStream<ChunkFrames::Mixed> last(chunk);
1092       unextended_sp = chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp());
1093       bool top_interpreted = Interpreter::contains(chunk->pc());
1094       if (callee.is_interpreted_frame() == top_interpreted) {
1095         overlap = argsize_md;
1096       }
1097     } else {
1098       unextended_sp = chunk->stack_size() - frame::metadata_words_at_top;
1099     }
1100   }
1101 
1102   log_develop_trace(continuations)("finalize _size: %d overlap: %d unextended_sp: %d", _freeze_size, overlap, unextended_sp);
1103 
1104   _freeze_size -= overlap;
1105   assert(_freeze_size >= 0, "");
1106 
1107   assert(chunk == nullptr || chunk->is_empty()
1108           || unextended_sp == chunk->to_offset(StackChunkFrameStream<ChunkFrames::Mixed>(chunk).unextended_sp()), "");
1109   assert(chunk != nullptr || unextended_sp < _freeze_size, "");
1110 
1111   _freeze_size += _monitors_in_lockstack;
1112 
1113   // _barriers can be set to true by an allocation in freeze_fast, in which case the chunk is available
1114   bool allocated_old_in_freeze_fast = _barriers;
1115   assert(!allocated_old_in_freeze_fast || (unextended_sp >= _freeze_size && chunk->is_empty()),
1116     "Chunk allocated in freeze_fast is of insufficient size "
1117     "unextended_sp: %d size: %d is_empty: %d", unextended_sp, _freeze_size, chunk->is_empty());
1118   assert(!allocated_old_in_freeze_fast || (!UseZGC && !UseG1GC), "Unexpected allocation");
1119 
1120   DEBUG_ONLY(bool empty_chunk = true);
1121   if (unextended_sp < _freeze_size || chunk->is_gc_mode() || (!allocated_old_in_freeze_fast && chunk->requires_barriers())) {
1122     // ALLOCATE NEW CHUNK
1123 
1124     if (lt.develop_is_enabled()) {
1125       LogStream ls(lt);
1126       if (chunk == nullptr) {
1127         ls.print_cr("no chunk");
1128       } else {
1129         ls.print_cr("chunk barriers: %d _size: %d free size: %d",
1130           chunk->requires_barriers(), _freeze_size, chunk->sp() - frame::metadata_words);
1131         chunk->print_on(&ls);
1132       }
1133     }
1134 
1135     _freeze_size += overlap; // we're allocating a new chunk, so no overlap
1136     // overlap = 0;
1137 
1138     chunk = allocate_chunk_slow(_freeze_size, argsize_md);
1139     if (chunk == nullptr) {
1140       return freeze_exception;
1141     }
1142 
1143     // Install new chunk
1144     _cont.set_tail(chunk);
1145     assert(chunk->is_empty(), "");
1146   } else {
1147     // REUSE EXISTING CHUNK
1148     log_develop_trace(continuations)("Reusing chunk mixed: %d empty: %d", chunk->has_mixed_frames(), chunk->is_empty());
1149     if (chunk->is_empty()) {
1150       int sp = chunk->stack_size() - argsize_md;
1151       chunk->set_sp(sp);
1152       chunk->set_bottom(sp);
1153       _freeze_size += overlap;
1154       assert(chunk->max_thawing_size() == 0, "");
1155     } DEBUG_ONLY(else empty_chunk = false;)
1156   }
1157   assert(!chunk->is_gc_mode(), "");
1158   assert(!chunk->has_bitmap(), "");
1159   chunk->set_has_mixed_frames(true);
1160 
1161   assert(chunk->requires_barriers() == _barriers, "");
1162   assert(!_barriers || chunk->is_empty(), "");
1163 
1164   assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).is_done(), "");
1165   assert(!chunk->is_empty() || StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame().is_empty(), "");
1166 
1167   if (_preempt) {
1168     frame f = _thread->last_frame();
1169     if (f.is_interpreted_frame()) {
1170       // Do it now that we know freezing will be successful.
1171       prepare_freeze_interpreted_top_frame(f);
1172     }
1173   }
1174 
1175   // We unwind frames after the last safepoint so that the GC will have found the oops in the frames, but before
1176   // writing into the chunk. This is so that an asynchronous stack walk (not at a safepoint) that suspends us here
1177   // will either see no continuation or a consistent chunk.
1178   unwind_frames();
1179 
1180   chunk->set_max_thawing_size(chunk->max_thawing_size() + _freeze_size - _monitors_in_lockstack - frame::metadata_words);
1181 
1182   if (lt.develop_is_enabled()) {
1183     LogStream ls(lt);
1184     ls.print_cr("top chunk:");
1185     chunk->print_on(&ls);
1186   }
1187 
1188   // Fix monitors after unwinding frames to make sure oops are valid. Also do it now to avoid unnecessary
1189   // calls to fix_monitors_in_interpreted_frame/fix_monitors_in_compiled_frame() later.
1190   if (_monitors_to_fix > 0) {
1191     if (_monitors_in_lockstack > 0) {
1192       assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "no room for lockstack");
1193       _thread->lock_stack().move_to_address((oop*)chunk->start_address());
1194 
1195       chunk->set_lockstack_size((uint8_t)_monitors_in_lockstack);
1196       chunk->set_has_lockstack(true);
1197 
1198       _monitors_to_fix -= _monitors_in_lockstack;
1199       assert(_monitors_to_fix == 0, "invariant");
1200     }
1201     _monitorenter_obj = _thread->is_on_monitorenter() ? _thread->current_pending_monitor()->object() : nullptr;
1202   }
1203 
1204   // The topmost existing frame in the chunk; or an empty frame if the chunk is empty
1205   caller = StackChunkFrameStream<ChunkFrames::Mixed>(chunk).to_frame();
1206 
1207   DEBUG_ONLY(_last_write = caller.unextended_sp() + (empty_chunk ? argsize_md : overlap);)
1208 
1209   assert(chunk->is_in_chunk(_last_write - _freeze_size),
1210     "last_write-size: " INTPTR_FORMAT " start: " INTPTR_FORMAT, p2i(_last_write-_freeze_size), p2i(chunk->start_address()));
1211 #ifdef ASSERT
1212   if (lt.develop_is_enabled()) {
1213     LogStream ls(lt);
1214     ls.print_cr("top hframe before (freeze):");
1215     assert(caller.is_heap_frame(), "should be");
1216     caller.print_on(&ls);
1217   }
1218 
1219   assert(!empty || Continuation::is_continuation_entry_frame(callee, nullptr), "");
1220 
1221   frame entry = sender(callee);
1222 
1223   assert((!empty && Continuation::is_return_barrier_entry(entry.pc())) || (empty && Continuation::is_continuation_enterSpecial(entry)), "");
1224   assert(callee.is_interpreted_frame() || entry.sp() == entry.unextended_sp(), "");
1225 #endif
1226 
1227   return freeze_ok_bottom;
1228 }
1229 
1230 void FreezeBase::patch(const frame& f, frame& hf, const frame& caller, bool is_bottom_frame) {
1231   if (is_bottom_frame) {
1232     // If we're the bottom frame, we need to replace the return barrier with the real
1233     // caller's pc.
1234     address last_pc = caller.pc();
1235     assert((last_pc == nullptr) == _cont.tail()->is_empty(), "");
1236     ContinuationHelper::Frame::patch_pc(caller, last_pc);
1237   } else {
1238     assert(!caller.is_empty(), "");
1239   }
1240 
1241   patch_pd(hf, caller);
1242 
1243   if (f.is_interpreted_frame()) {
1244     assert(hf.is_heap_frame(), "should be");
1245     ContinuationHelper::InterpretedFrame::patch_sender_sp(hf, caller);
1246   }
1247 
1248 #ifdef ASSERT
1249   if (hf.is_compiled_frame()) {
1250     if (f.is_deoptimized_frame()) { // TODO DEOPT: long term solution: unroll on freeze and patch pc
1251       log_develop_trace(continuations)("Freezing deoptimized frame");
1252       assert(f.cb()->as_nmethod()->is_deopt_pc(f.raw_pc()), "");
1253       assert(f.cb()->as_nmethod()->is_deopt_pc(ContinuationHelper::Frame::real_pc(f)), "");
1254     }
1255   }
1256 #endif
1257 }
1258 
1259 #ifdef ASSERT
1260 static void verify_frame_top(const frame& f, intptr_t* top) {
1261   ResourceMark rm;
1262   InterpreterOopMap mask;
1263   f.interpreted_frame_oop_map(&mask);
1264   assert(top <= ContinuationHelper::InterpretedFrame::frame_top(f, &mask),
1265          "frame_top: " INTPTR_FORMAT " Interpreted::frame_top: " INTPTR_FORMAT,
1266            p2i(top), p2i(ContinuationHelper::InterpretedFrame::frame_top(f, &mask)));
1267 }
1268 #endif // ASSERT
1269 
1270 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1271 // See also StackChunkFrameStream<frame_kind>::frame_size()
1272 NOINLINE freeze_result FreezeBase::recurse_freeze_interpreted_frame(frame& f, frame& caller,
1273                                                                     int callee_argsize /* incl. metadata */,
1274                                                                     bool callee_interpreted) {
1275   adjust_interpreted_frame_unextended_sp(f);
1276 
1277   // The frame's top never includes the stack arguments to the callee
1278   intptr_t* const stack_frame_top = ContinuationHelper::InterpretedFrame::frame_top(f, callee_argsize, callee_interpreted);
1279   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
1280   const int fsize = pointer_delta_as_int(stack_frame_bottom, stack_frame_top);
1281 
1282   DEBUG_ONLY(verify_frame_top(f, stack_frame_top));
1283 
1284   Method* frame_method = ContinuationHelper::Frame::frame_method(f);
1285   // including metadata between f and its args
1286   const int argsize = ContinuationHelper::InterpretedFrame::stack_argsize(f) + frame::metadata_words_at_top;
1287 
1288   log_develop_trace(continuations)("recurse_freeze_interpreted_frame %s _size: %d fsize: %d argsize: %d",
1289     frame_method->name_and_sig_as_C_string(), _freeze_size, fsize, argsize);
1290   // we'd rather not yield inside methods annotated with @JvmtiMountTransition. In the preempt case
1291   // we already checked it is safe to do so in Continuation::is_safe_vthread_to_preempt().
1292   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition() || _preempt, "");
1293 
1294   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::InterpretedFrame>(f, caller, fsize, argsize);
1295   if (UNLIKELY(result > freeze_ok_bottom)) {
1296     return result;
1297   }
1298 
1299   bool is_bottom_frame = result == freeze_ok_bottom;
1300   assert(!caller.is_empty() || is_bottom_frame, "");
1301 
1302   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, is_bottom_frame);)
1303 
1304   frame hf = new_heap_frame<ContinuationHelper::InterpretedFrame>(f, caller);
1305   _total_align_size += frame::align_wiggle; // add alignment room for internal interpreted frame alignment on AArch64/PPC64
1306 
1307   intptr_t* heap_frame_top = ContinuationHelper::InterpretedFrame::frame_top(hf, callee_argsize, callee_interpreted);
1308   intptr_t* heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
1309   assert(heap_frame_bottom == heap_frame_top + fsize, "");
1310 
1311   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
1312   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
1313   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1314   assert(!is_bottom_frame || !caller.is_interpreted_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1315 
1316   relativize_interpreted_frame_metadata(f, hf);
1317 
1318   patch(f, hf, caller, is_bottom_frame);
1319 
1320   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
1321   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1322   caller = hf;
1323 
1324   // Mark frame_method's GC epoch for class redefinition on_stack calculation.
1325   frame_method->record_gc_epoch();
1326 
1327   if (_monitors_to_fix > 0) {
1328     // Check if we have monitors in this frame
1329     fix_monitors_in_interpreted_frame(f);
1330   }
1331 
1332   return freeze_ok;
1333 }
1334 
1335 // The parameter callee_argsize includes metadata that has to be part of caller/callee overlap.
1336 // See also StackChunkFrameStream<frame_kind>::frame_size()
1337 freeze_result FreezeBase::recurse_freeze_compiled_frame(frame& f, frame& caller,
1338                                                         int callee_argsize /* incl. metadata */,
1339                                                         bool callee_interpreted) {
1340   // The frame's top never includes the stack arguments to the callee
1341   intptr_t* const stack_frame_top = ContinuationHelper::CompiledFrame::frame_top(f, callee_argsize, callee_interpreted);
1342   intptr_t* const stack_frame_bottom = ContinuationHelper::CompiledFrame::frame_bottom(f);
1343   // including metadata between f and its stackargs
1344   const int argsize = ContinuationHelper::CompiledFrame::stack_argsize(f) + frame::metadata_words_at_top;
1345   const int fsize = pointer_delta_as_int(stack_frame_bottom + argsize, stack_frame_top);
1346 
1347   log_develop_trace(continuations)("recurse_freeze_compiled_frame %s _size: %d fsize: %d argsize: %d",
1348                              ContinuationHelper::Frame::frame_method(f) != nullptr ?
1349                              ContinuationHelper::Frame::frame_method(f)->name_and_sig_as_C_string() : "",
1350                              _freeze_size, fsize, argsize);
1351   // we'd rather not yield inside methods annotated with @JvmtiMountTransition. In the preempt case
1352   // we already checked it is safe to do so in Continuation::is_safe_vthread_to_preempt().
1353   assert(!ContinuationHelper::Frame::frame_method(f)->jvmti_mount_transition() || _preempt, "");
1354 
1355   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::CompiledFrame>(f, caller, fsize, argsize);
1356   if (UNLIKELY(result > freeze_ok_bottom)) {
1357     return result;
1358   }
1359 
1360   bool is_bottom_frame = result == freeze_ok_bottom;
1361   assert(!caller.is_empty() || is_bottom_frame, "");
1362 
1363   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, argsize, is_bottom_frame);)
1364 
1365   frame hf = new_heap_frame<ContinuationHelper::CompiledFrame>(f, caller);
1366 
1367   intptr_t* heap_frame_top = ContinuationHelper::CompiledFrame::frame_top(hf, callee_argsize, callee_interpreted);
1368 
1369   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1370   assert(!is_bottom_frame || !caller.is_compiled_frame() || (heap_frame_top + fsize) == (caller.unextended_sp() + argsize), "");
1371 
1372   if (caller.is_interpreted_frame()) {
1373     _total_align_size += frame::align_wiggle; // See Thaw::align
1374   }
1375 
1376   patch(f, hf, caller, is_bottom_frame);
1377 
1378   assert(is_bottom_frame || Interpreter::contains(ContinuationHelper::CompiledFrame::real_pc(caller)) == caller.is_interpreted_frame(), "");
1379 
1380   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1381   caller = hf;
1382 
1383   if (_monitors_to_fix > 0) {
1384     // Check if we have monitors in this frame
1385     fix_monitors_in_compiled_frame(f, SmallRegisterMap::instance);
1386   }
1387 
1388   return freeze_ok;
1389 }
1390 
1391 NOINLINE freeze_result FreezeBase::recurse_freeze_stub_frame(frame& f, frame& caller) {
1392   DEBUG_ONLY(frame fsender = sender(f);)
1393   assert(fsender.is_compiled_frame(), "sender should be compiled frame");
1394   assert(_thread->is_on_monitorenter(), "");
1395 
1396   intptr_t* const stack_frame_top = ContinuationHelper::StubFrame::frame_top(f);
1397   const int fsize = f.cb()->frame_size();
1398 
1399   log_develop_trace(continuations)("recurse_freeze_stub_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1400     f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1401 
1402   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::StubFrame>(f, caller, fsize, 0);
1403   if (UNLIKELY(result > freeze_ok_bottom)) {
1404     return result;
1405   }
1406 
1407   bool is_bottom_frame = result == freeze_ok_bottom;
1408   assert(!caller.is_empty() || (is_bottom_frame && !_cont.is_empty()), "");
1409 
1410   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0, is_bottom_frame);)
1411 
1412   frame hf = new_heap_frame<ContinuationHelper::StubFrame>(f, caller);
1413   intptr_t* heap_frame_top = ContinuationHelper::StubFrame::frame_top(hf);
1414 
1415   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1416 
1417   if (caller.is_interpreted_frame()) {
1418     _total_align_size += frame::align_wiggle;
1419   }
1420 
1421   patch(f, hf, caller, is_bottom_frame);
1422 
1423   DEBUG_ONLY(after_freeze_java_frame(hf, is_bottom_frame);)
1424 
1425   caller = hf;
1426   return freeze_ok;
1427 }
1428 
1429 NOINLINE freeze_result FreezeBase::recurse_freeze_native_frame(frame& f, frame& caller) {
1430   if (!f.cb()->as_nmethod()->method()->is_object_wait0()) {
1431     assert(_thread->is_on_monitorenter(), "");
1432     // Synchronized native method case. Unlike the interpreter native wrapper, the compiled
1433     // native wrapper tries to acquire the monitor after marshalling the arguments from the
1434     // caller into the native convention. This is so that we have a valid oopMap in case of
1435     // having to block in the slow path. But that would require freezing those registers too
1436     // and then fixing them back on thaw in case of oops. To avoid complicating things and
1437     // given that this would be a rare case anyways just pin the vthread to the carrier.
1438     return freeze_pinned_native;
1439   }
1440 
1441   intptr_t* const stack_frame_top = ContinuationHelper::NativeFrame::frame_top(f);
1442   const int fsize = f.cb()->frame_size();
1443 
1444   log_develop_trace(continuations)("recurse_freeze_native_frame %s _size: %d fsize: %d :: " INTPTR_FORMAT " - " INTPTR_FORMAT,
1445     f.cb()->name(), _freeze_size, fsize, p2i(stack_frame_top), p2i(stack_frame_top+fsize));
1446 
1447   freeze_result result = recurse_freeze_java_frame<ContinuationHelper::NativeFrame>(f, caller, fsize, 0);
1448   if (UNLIKELY(result > freeze_ok_bottom)) {
1449     return result;
1450   }
1451 
1452   assert(result == freeze_ok, "should have caller frame");
1453   DEBUG_ONLY(before_freeze_java_frame(f, caller, fsize, 0 /* argsize */, false /* is_bottom_frame */);)
1454 
1455   frame hf = new_heap_frame<ContinuationHelper::NativeFrame>(f, caller);
1456   intptr_t* heap_frame_top = ContinuationHelper::NativeFrame::frame_top(hf);
1457 
1458   copy_to_chunk(stack_frame_top, heap_frame_top, fsize);
1459 
1460   if (caller.is_interpreted_frame()) {
1461     _total_align_size += frame::align_wiggle;
1462   }
1463 
1464   patch(f, hf, caller, false /* is_bottom_frame */);
1465 
1466   DEBUG_ONLY(after_freeze_java_frame(hf, false /* is_bottom_frame */);)
1467 
1468   caller = hf;
1469   return freeze_ok;
1470 }
1471 
1472 NOINLINE void FreezeBase::finish_freeze(const frame& f, const frame& top) {
1473   stackChunkOop chunk = _cont.tail();
1474 
1475   LogTarget(Trace, continuations) lt;
1476   if (lt.develop_is_enabled()) {
1477     LogStream ls(lt);
1478     assert(top.is_heap_frame(), "should be");
1479     top.print_on(&ls);
1480   }
1481 
1482   set_top_frame_metadata_pd(top);
1483 
1484   chunk->set_sp(chunk->to_offset(top.sp()));
1485   chunk->set_pc(top.pc());
1486 
1487   chunk->set_max_thawing_size(chunk->max_thawing_size() + _total_align_size);
1488 
1489   assert(chunk->sp_address() - chunk->start_address() >= _monitors_in_lockstack, "clash with lockstack");
1490 
1491   // At this point the chunk is consistent
1492 
1493   if (UNLIKELY(_barriers)) {
1494     log_develop_trace(continuations)("do barriers on old chunk");
1495     // Serial and Parallel GC can allocate objects directly into the old generation.
1496     // Then we want to relativize the derived pointers eagerly so that
1497     // old chunks are all in GC mode.
1498     assert(!UseG1GC, "G1 can not deal with allocating outside of eden");
1499     assert(!UseZGC, "ZGC can not deal with allocating chunks visible to marking");
1500     if (UseShenandoahGC) {
1501       _cont.tail()->relativize_derived_pointers_concurrently();
1502     } else {
1503       ContinuationGCSupport::transform_stack_chunk(_cont.tail());
1504     }
1505     // For objects in the old generation we must maintain the remembered set
1506     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>();
1507   }
1508 
1509   log_develop_trace(continuations)("finish_freeze: has_mixed_frames: %d", chunk->has_mixed_frames());
1510   if (lt.develop_is_enabled()) {
1511     LogStream ls(lt);
1512     chunk->print_on(true, &ls);
1513   }
1514 
1515   if (lt.develop_is_enabled()) {
1516     LogStream ls(lt);
1517     ls.print_cr("top hframe after (freeze):");
1518     assert(_cont.last_frame().is_heap_frame(), "should be");
1519     _cont.last_frame().print_on(&ls);
1520     DEBUG_ONLY(print_frame_layout(top, false, &ls);)
1521   }
1522 
1523   assert(_cont.chunk_invariant(), "");
1524 }
1525 
1526 inline bool FreezeBase::stack_overflow() { // detect stack overflow in recursive native code
1527   JavaThread* t = !_preempt ? _thread : JavaThread::current();
1528   assert(t == JavaThread::current(), "");
1529   if (os::current_stack_pointer() < t->stack_overflow_state()->shadow_zone_safe_limit()) {
1530     if (!_preempt) {
1531       ContinuationWrapper::SafepointOp so(t, _cont); // could also call _cont.done() instead
1532       Exceptions::_throw_msg(t, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Stack overflow while freezing");
1533     }
1534     return true;
1535   }
1536   return false;
1537 }
1538 
1539 class StackChunkAllocator : public MemAllocator {
1540   const size_t                                 _stack_size;
1541   int                                          _argsize_md;
1542   ContinuationWrapper&                         _continuation_wrapper;
1543   JvmtiSampledObjectAllocEventCollector* const _jvmti_event_collector;
1544   JavaThread* const                            _target;
1545   mutable bool                                 _took_slow_path;
1546 
1547   // Does the minimal amount of initialization needed for a TLAB allocation.
1548   // We don't need to do a full initialization, as such an allocation need not be immediately walkable.
1549   virtual oop initialize(HeapWord* mem) const override {
1550     assert(_stack_size > 0, "");
1551     assert(_stack_size <= max_jint, "");
1552     assert(_word_size > _stack_size, "");
1553 
1554     // zero out fields (but not the stack)
1555     const size_t hs = oopDesc::header_size();
1556     oopDesc::set_klass_gap(mem, 0);
1557     Copy::fill_to_aligned_words(mem + hs, vmClasses::StackChunk_klass()->size_helper() - hs);
1558 
1559     int bottom = (int)_stack_size - _argsize_md;
1560 
1561     jdk_internal_vm_StackChunk::set_size(mem, (int)_stack_size);
1562     jdk_internal_vm_StackChunk::set_bottom(mem, bottom);
1563     jdk_internal_vm_StackChunk::set_sp(mem, bottom);
1564 
1565     return finish(mem);
1566   }
1567 
1568   stackChunkOop allocate_fast() const {
1569     if (!UseTLAB) {
1570       return nullptr;
1571     }
1572 
1573     HeapWord* const mem = MemAllocator::mem_allocate_inside_tlab_fast();
1574     if (mem == nullptr) {
1575       return nullptr;
1576     }
1577 
1578     oop obj = initialize(mem);
1579     return stackChunkOopDesc::cast(obj);
1580   }
1581 
1582   bool is_preempt() const { return _thread != _target; }
1583 
1584 public:
1585   StackChunkAllocator(Klass* klass,
1586                       size_t word_size,
1587                       Thread* thread,
1588                       size_t stack_size,
1589                       int argsize_md,
1590                       ContinuationWrapper& continuation_wrapper,
1591                       JvmtiSampledObjectAllocEventCollector* jvmti_event_collector,
1592                       JavaThread* target)
1593     : MemAllocator(klass, word_size, thread),
1594       _stack_size(stack_size),
1595       _argsize_md(argsize_md),
1596       _continuation_wrapper(continuation_wrapper),
1597       _jvmti_event_collector(jvmti_event_collector),
1598       _target(target),
1599       _took_slow_path(false) {}
1600 
1601   // Provides it's own, specialized allocation which skips instrumentation
1602   // if the memory can be allocated without going to a slow-path.
1603   stackChunkOop allocate() const {
1604     // First try to allocate without any slow-paths or instrumentation.
1605     stackChunkOop obj = allocate_fast();
1606     if (obj != nullptr) {
1607       return obj;
1608     }
1609 
1610     // Now try full-blown allocation with all expensive operations,
1611     // including potentially safepoint operations.
1612     _took_slow_path = true;
1613 
1614     // Protect unhandled Loom oops
1615     ContinuationWrapper::SafepointOp so(_thread, _continuation_wrapper);
1616 
1617     // Can safepoint
1618     _jvmti_event_collector->start();
1619 
1620     // Can safepoint
1621     return stackChunkOopDesc::cast(MemAllocator::allocate());
1622   }
1623 
1624   bool took_slow_path() const {
1625     return _took_slow_path;
1626   }
1627 };
1628 
1629 template <typename ConfigT>
1630 stackChunkOop Freeze<ConfigT>::allocate_chunk(size_t stack_size, int argsize_md) {
1631   log_develop_trace(continuations)("allocate_chunk allocating new chunk");
1632 
1633   InstanceStackChunkKlass* klass = InstanceStackChunkKlass::cast(vmClasses::StackChunk_klass());
1634   size_t size_in_words = klass->instance_size(stack_size);
1635 
1636   if (CollectedHeap::stack_chunk_max_size() > 0 && size_in_words >= CollectedHeap::stack_chunk_max_size()) {
1637     if (!_preempt) {
1638       throw_stack_overflow_on_humongous_chunk();
1639     }
1640     return nullptr;
1641   }
1642 
1643   JavaThread* current = _preempt ? JavaThread::current() : _thread;
1644   assert(current == JavaThread::current(), "should be current");
1645 
1646   // Allocate the chunk.
1647   //
1648   // This might safepoint while allocating, but all safepointing due to
1649   // instrumentation have been deferred. This property is important for
1650   // some GCs, as this ensures that the allocated object is in the young
1651   // generation / newly allocated memory.
1652   StackChunkAllocator allocator(klass, size_in_words, current, stack_size, argsize_md, _cont, _jvmti_event_collector, _thread);
1653   stackChunkOop chunk = allocator.allocate();
1654 
1655   if (chunk == nullptr) {
1656     return nullptr; // OOME
1657   }
1658 
1659   // assert that chunk is properly initialized
1660   assert(chunk->stack_size() == (int)stack_size, "");
1661   assert(chunk->size() >= stack_size, "chunk->size(): %zu size: %zu", chunk->size(), stack_size);
1662   assert(chunk->sp() == chunk->bottom(), "");
1663   assert((intptr_t)chunk->start_address() % 8 == 0, "");
1664   assert(chunk->max_thawing_size() == 0, "");
1665   assert(chunk->pc() == nullptr, "");
1666   assert(chunk->is_empty(), "");
1667   assert(chunk->flags() == 0, "");
1668   assert(chunk->is_gc_mode() == false, "");
1669   assert(chunk->lockstack_size() == 0, "");
1670   assert(chunk->object_waiter() == nullptr, "");
1671 
1672   // fields are uninitialized
1673   chunk->set_parent_access<IS_DEST_UNINITIALIZED>(_cont.last_nonempty_chunk());
1674   chunk->set_cont_access<IS_DEST_UNINITIALIZED>(_cont.continuation());
1675 
1676 #if INCLUDE_ZGC
1677   if (UseZGC) {
1678     if (ZGenerational) {
1679       ZStackChunkGCData::initialize(chunk);
1680     }
1681     assert(!chunk->requires_barriers(), "ZGC always allocates in the young generation");
1682     _barriers = false;
1683   } else
1684 #endif
1685 #if INCLUDE_SHENANDOAHGC
1686   if (UseShenandoahGC) {
1687     _barriers = chunk->requires_barriers();
1688   } else
1689 #endif
1690   {
1691     if (!allocator.took_slow_path()) {
1692       // Guaranteed to be in young gen / newly allocated memory
1693       assert(!chunk->requires_barriers(), "Unfamiliar GC requires barriers on TLAB allocation");
1694       _barriers = false;
1695     } else {
1696       // Some GCs could put direct allocations in old gen for slow-path
1697       // allocations; need to explicitly check if that was the case.
1698       _barriers = chunk->requires_barriers();
1699     }
1700   }
1701 
1702   if (_barriers) {
1703     log_develop_trace(continuations)("allocation requires barriers");
1704   }
1705 
1706   assert(chunk->parent() == nullptr || chunk->parent()->is_stackChunk(), "");
1707 
1708   return chunk;
1709 }
1710 
1711 void FreezeBase::throw_stack_overflow_on_humongous_chunk() {
1712   ContinuationWrapper::SafepointOp so(_thread, _cont); // could also call _cont.done() instead
1713   Exceptions::_throw_msg(_thread, __FILE__, __LINE__, vmSymbols::java_lang_StackOverflowError(), "Humongous stack chunk");
1714 }
1715 
1716 #if INCLUDE_JVMTI
1717 static int num_java_frames(ContinuationWrapper& cont) {
1718   ResourceMark rm; // used for scope traversal in num_java_frames(nmethod*, address)
1719   int count = 0;
1720   for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
1721     count += chunk->num_java_frames();
1722   }
1723   return count;
1724 }
1725 
1726 static void invalidate_jvmti_stack(JavaThread* thread) {
1727   if (thread->is_interp_only_mode()) {
1728     JvmtiThreadState *state = thread->jvmti_thread_state();
1729     if (state != nullptr)
1730       state->invalidate_cur_stack_depth();
1731   }
1732 }
1733 
1734 static void jvmti_yield_cleanup(JavaThread* thread, ContinuationWrapper& cont) {
1735   if (JvmtiExport::can_post_frame_pop()) {
1736     int num_frames = num_java_frames(cont);
1737 
1738     ContinuationWrapper::SafepointOp so(Thread::current(), cont);
1739     JvmtiExport::continuation_yield_cleanup(JavaThread::current(), num_frames);
1740   }
1741   invalidate_jvmti_stack(thread);
1742 }
1743 
1744 static void jvmti_mount_end(JavaThread* current, ContinuationWrapper& cont, frame top) {
1745   assert(current->vthread() != nullptr, "must be");
1746 
1747   HandleMarkCleaner hm(current);
1748   Handle vth(current, current->vthread());
1749 
1750   ContinuationWrapper::SafepointOp so(current, cont);
1751 
1752   // Since we might safepoint set the anchor so that the stack can we walked.
1753   set_anchor(current, top.sp());
1754 
1755   JRT_BLOCK
1756     current->rebind_to_jvmti_thread_state_of(vth());
1757     {
1758       MutexLocker mu(JvmtiThreadState_lock);
1759       JvmtiThreadState* state = current->jvmti_thread_state();
1760       if (state != NULL && state->is_pending_interp_only_mode()) {
1761         JvmtiEventController::enter_interp_only_mode(state);
1762       }
1763     }
1764     assert(current->is_in_VTMS_transition(), "sanity check");
1765     assert(!current->is_in_tmp_VTMS_transition(), "sanity check");
1766     JvmtiVTMSTransitionDisabler::finish_VTMS_transition((jthread)vth.raw_value(), /* is_mount */ true);
1767 
1768     // If pending_jvmti_unmount_event() is true here we are in the preemption
1769     // cancelled case. Since we never unmounted we don't post the mount event
1770     // and just clear the pending unmount flag.
1771     if (current->pending_jvmti_unmount_event()) {
1772       current->set_pending_jvmti_unmount_event(false);
1773     } else if (JvmtiExport::should_post_vthread_mount()) {
1774       JvmtiExport::post_vthread_mount((jthread)vth.raw_value());
1775     }
1776 
1777     if (current->pending_contended_entered_event()) {
1778       JvmtiExport::post_monitor_contended_entered(current, current->contended_entered_monitor());
1779       current->set_contended_entered_monitor(nullptr);
1780     }
1781   JRT_BLOCK_END
1782 
1783   clear_anchor(current);
1784 }
1785 #endif // INCLUDE_JVMTI
1786 
1787 #ifdef ASSERT
1788 
1789 // There are no interpreted frames if we're not called from the interpreter and we haven't ancountered an i2c
1790 // adapter or called Deoptimization::unpack_frames. As for native frames, upcalls from JNI also go through the
1791 // interpreter (see JavaCalls::call_helper), while the UpcallLinker explicitly sets cont_fastpath.
1792 bool FreezeBase::check_valid_fast_path() {
1793   ContinuationEntry* ce = _thread->last_continuation();
1794   RegisterMap map(_thread,
1795                   RegisterMap::UpdateMap::skip,
1796                   RegisterMap::ProcessFrames::skip,
1797                   RegisterMap::WalkContinuation::skip);
1798   map.set_include_argument_oops(false);
1799   int i = 0;
1800   for (frame f = freeze_start_frame(); Continuation::is_frame_in_continuation(ce, f); f = f.sender(&map), i++) {
1801     if (!((f.is_compiled_frame() && !f.is_deoptimized_frame()) || (i == 0 && f.is_runtime_frame()))) {
1802       return false;
1803     }
1804   }
1805   return true;
1806 }
1807 #endif // ASSERT
1808 
1809 static inline int freeze_epilog(ContinuationWrapper& cont) {
1810   verify_continuation(cont.continuation());
1811   assert(!cont.is_empty(), "");
1812 
1813   log_develop_debug(continuations)("=== End of freeze cont ### #" INTPTR_FORMAT, cont.hash());
1814   return 0;
1815 }
1816 
1817 static int freeze_epilog(JavaThread* thread, ContinuationWrapper& cont, freeze_result res) {
1818   if (UNLIKELY(res != freeze_ok)) {
1819     verify_continuation(cont.continuation());
1820     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1821     return res;
1822   }
1823 
1824   JVMTI_ONLY(jvmti_yield_cleanup(thread, cont)); // can safepoint
1825   return freeze_epilog(cont);
1826 }
1827 
1828 static int preempt_epilog(ContinuationWrapper& cont, freeze_result res, frame& old_last_frame, int freeze_kind) {
1829   if (UNLIKELY(res != freeze_ok)) {
1830     verify_continuation(cont.continuation());
1831     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1832     return res;
1833   }
1834 
1835   patch_return_pc_with_preempt_stub(old_last_frame);
1836   cont.set_preempted(true);
1837   cont.tail()->set_preempt_kind(freeze_kind);
1838 
1839   return freeze_epilog(cont);
1840 }
1841 
1842 template<typename ConfigT, bool preempt>
1843 static inline int freeze_internal(JavaThread* current, intptr_t* const sp, int freeze_kind) {
1844   assert(!current->has_pending_exception(), "");
1845 
1846 #ifdef ASSERT
1847   log_trace(continuations)("~~~~ freeze sp: " INTPTR_FORMAT "JavaThread: " INTPTR_FORMAT, p2i(current->last_continuation()->entry_sp()), p2i(current));
1848   log_frames(current);
1849 #endif
1850 
1851   CONT_JFR_ONLY(EventContinuationFreeze event;)
1852 
1853   ContinuationEntry* entry = current->last_continuation();
1854 
1855   oop oopCont = entry->cont_oop(current);
1856   assert(oopCont == current->last_continuation()->cont_oop(current), "");
1857   assert(ContinuationEntry::assert_entry_frame_laid_out(current), "");
1858 
1859   verify_continuation(oopCont);
1860   ContinuationWrapper cont(current, oopCont);
1861   log_develop_debug(continuations)("FREEZE #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
1862 
1863   assert(entry->is_virtual_thread() == (entry->scope(current) == java_lang_VirtualThread::vthread_scope()), "");
1864 
1865   const bool pinned_monitor = NOT_LOOM_MONITOR_SUPPORT(current->held_monitor_count() > 0) LOOM_MONITOR_SUPPORT_ONLY(current->jni_monitor_count() > 0);
1866   if (entry->is_pinned() || pinned_monitor) {
1867     log_develop_debug(continuations)("PINNED due to critical section/hold monitor");
1868     verify_continuation(cont.continuation());
1869     freeze_result res = entry->is_pinned() ? freeze_pinned_cs : freeze_pinned_monitor;
1870     log_develop_trace(continuations)("=== end of freeze (fail %d)", res);
1871     return res;
1872   }
1873 
1874   Freeze<ConfigT> freeze(current, cont, sp, preempt);
1875 
1876   if (preempt) {
1877     freeze.set_last_frame();  // remember last frame
1878     if (freeze_kind == freeze_on_wait AARCH64_ONLY(|| true)) {
1879       // Force freeze slow path on wait to avoid dealing with native wrapper frames on the fast
1880       // path. For aarch64 force slow path always for now. It needs extra instructions to correctly
1881       // set the last pc we copy into the stackChunk, since it will not necessarily be at sp[-1]).
1882       current->push_cont_fastpath(current->last_Java_sp());
1883     }
1884   }
1885 
1886   assert(!current->cont_fastpath() || freeze.check_valid_fast_path(), "");
1887   bool fast = UseContinuationFastPath && current->cont_fastpath();
1888   if (fast && freeze.size_if_fast_freeze_available() > 0) {
1889     freeze.freeze_fast_existing_chunk();
1890     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1891     return !preempt ? freeze_epilog(cont) : preempt_epilog(cont, freeze_ok, freeze.last_frame(), freeze_kind);
1892   }
1893 
1894   if (preempt) {
1895     JvmtiSampledObjectAllocEventCollector jsoaec(false);
1896     freeze.set_jvmti_event_collector(&jsoaec);
1897 
1898     freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1899 
1900     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1901     preempt_epilog(cont, res, freeze.last_frame(), freeze_kind);
1902     return res;
1903   }
1904 
1905   log_develop_trace(continuations)("chunk unavailable; transitioning to VM");
1906   assert(current == JavaThread::current(), "must be current thread");
1907   JRT_BLOCK
1908     // delays a possible JvmtiSampledObjectAllocEventCollector in alloc_chunk
1909     JvmtiSampledObjectAllocEventCollector jsoaec(false);
1910     freeze.set_jvmti_event_collector(&jsoaec);
1911 
1912     freeze_result res = fast ? freeze.try_freeze_fast() : freeze.freeze_slow();
1913 
1914     CONT_JFR_ONLY(freeze.jfr_info().post_jfr_event(&event, oopCont, current);)
1915     freeze_epilog(current, cont, res);
1916     cont.done(); // allow safepoint in the transition back to Java
1917     return res;
1918   JRT_BLOCK_END
1919 }
1920 
1921 static freeze_result is_pinned0(JavaThread* thread, oop cont_scope, bool safepoint) {
1922   ContinuationEntry* entry = thread->last_continuation();
1923   if (entry == nullptr) {
1924     return freeze_ok;
1925   }
1926   if (entry->is_pinned()) {
1927     return freeze_pinned_cs;
1928   } else if (thread->held_monitor_count() > 0) {
1929     return freeze_pinned_monitor;
1930   }
1931 
1932   RegisterMap map(thread,
1933                   RegisterMap::UpdateMap::include,
1934                   RegisterMap::ProcessFrames::skip,
1935                   RegisterMap::WalkContinuation::skip);
1936   map.set_include_argument_oops(false);
1937   frame f = thread->last_frame();
1938 
1939   if (!safepoint) {
1940     f = f.sender(&map); // this is the yield frame
1941   } else { // safepoint yield
1942 #if (defined(X86) || defined(AARCH64) || defined(RISCV64)) && !defined(ZERO)
1943     f.set_fp(f.real_fp()); // Instead of this, maybe in ContinuationWrapper::set_last_frame always use the real_fp?
1944 #else
1945     Unimplemented();
1946 #endif
1947     if (!Interpreter::contains(f.pc())) {
1948       assert(ContinuationHelper::Frame::is_stub(f.cb()), "must be");
1949       assert(f.oop_map() != nullptr, "must be");
1950       f.oop_map()->update_register_map(&f, &map); // we have callee-save registers in this case
1951     }
1952   }
1953 
1954   while (true) {
1955     if ((f.is_interpreted_frame() && f.interpreter_frame_method()->is_native()) || f.is_native_frame()) {
1956       return freeze_pinned_native;
1957     }
1958 
1959     f = f.sender(&map);
1960     if (!Continuation::is_frame_in_continuation(entry, f)) {
1961       oop scope = jdk_internal_vm_Continuation::scope(entry->cont_oop(thread));
1962       if (scope == cont_scope) {
1963         break;
1964       }
1965       intx monitor_count = entry->parent_held_monitor_count();
1966       entry = entry->parent();
1967       if (entry == nullptr) {
1968         break;
1969       }
1970       if (entry->is_pinned()) {
1971         return freeze_pinned_cs;
1972       } else if (monitor_count > 0) {
1973         return freeze_pinned_monitor;
1974       }
1975     }
1976   }
1977   return freeze_ok;
1978 }
1979 
1980 /////////////// THAW ////
1981 
1982 static int thaw_size(stackChunkOop chunk) {
1983   int size = chunk->max_thawing_size();
1984   size += frame::metadata_words; // For the top pc+fp in push_return_frame or top = stack_sp - frame::metadata_words in thaw_fast
1985   size += 2*frame::align_wiggle; // in case of alignments at the top and bottom
1986   size += frame::metadata_words; // for preemption case (see push_preempt_rerun_adapter)
1987   return size;
1988 }
1989 
1990 // make room on the stack for thaw
1991 // returns the size in bytes, or 0 on failure
1992 static inline int prepare_thaw_internal(JavaThread* thread, bool return_barrier) {
1993   log_develop_trace(continuations)("~~~~ prepare_thaw return_barrier: %d", return_barrier);
1994 
1995   assert(thread == JavaThread::current(), "");
1996 
1997   ContinuationEntry* ce = thread->last_continuation();
1998   assert(ce != nullptr, "");
1999   oop continuation = ce->cont_oop(thread);
2000   assert(continuation == get_continuation(thread), "");
2001   verify_continuation(continuation);
2002 
2003   stackChunkOop chunk = jdk_internal_vm_Continuation::tail(continuation);
2004   assert(chunk != nullptr, "");
2005 
2006   // The tail can be empty because it might still be available for another freeze.
2007   // However, here we want to thaw, so we get rid of it (it will be GCed).
2008   if (UNLIKELY(chunk->is_empty())) {
2009     chunk = chunk->parent();
2010     assert(chunk != nullptr, "");
2011     assert(!chunk->is_empty(), "");
2012     jdk_internal_vm_Continuation::set_tail(continuation, chunk);
2013   }
2014 
2015   // Verification
2016   chunk->verify();
2017   assert(chunk->max_thawing_size() > 0, "chunk invariant violated; expected to not be empty");
2018 
2019   // Only make space for the last chunk because we only thaw from the last chunk
2020   int size = thaw_size(chunk) << LogBytesPerWord;
2021 
2022   const address bottom = (address)thread->last_continuation()->entry_sp();
2023   // 300 is an estimate for stack size taken for this native code, in addition to StackShadowPages
2024   // for the Java frames in the check below.
2025   if (!stack_overflow_check(thread, size + 300, bottom)) {
2026     return 0;
2027   }
2028 
2029   log_develop_trace(continuations)("prepare_thaw bottom: " INTPTR_FORMAT " top: " INTPTR_FORMAT " size: %d",
2030                               p2i(bottom), p2i(bottom - size), size);
2031   return size;
2032 }
2033 
2034 class ThawBase : public StackObj {
2035 protected:
2036   JavaThread* _thread;
2037   ContinuationWrapper& _cont;
2038   CONT_JFR_ONLY(FreezeThawJfrInfo _jfr_info;)
2039 
2040   intptr_t* _fastpath;
2041   bool _barriers;
2042   intptr_t* _top_unextended_sp_before_thaw;
2043   int _align_size;
2044   DEBUG_ONLY(intptr_t* _top_stack_address);
2045 
2046   StackChunkFrameStream<ChunkFrames::Mixed> _stream;
2047 
2048   NOT_PRODUCT(int _frames;)
2049 
2050 protected:
2051   ThawBase(JavaThread* thread, ContinuationWrapper& cont) :
2052       _thread(thread), _cont(cont),
2053       _fastpath(nullptr) {
2054     DEBUG_ONLY(_top_unextended_sp_before_thaw = nullptr;)
2055     assert (cont.tail() != nullptr, "no last chunk");
2056     DEBUG_ONLY(_top_stack_address = _cont.entrySP() - thaw_size(cont.tail());)
2057   }
2058 
2059   void clear_chunk(stackChunkOop chunk);
2060   int remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize);
2061   void copy_from_chunk(intptr_t* from, intptr_t* to, int size);
2062 
2063   // fast path
2064   inline void prefetch_chunk_pd(void* start, int size_words);
2065   void patch_return(intptr_t* sp, bool is_last);
2066 
2067   intptr_t* handle_preempted_continuation(intptr_t* sp, int preempt_kind, bool fast_case);
2068   inline intptr_t* push_resume_adapter(frame& top);
2069   inline intptr_t* push_resume_monitor_operation(stackChunkOop chunk);
2070   inline void fix_native_return_pc_pd(frame& top);
2071   void throw_interrupted_exception(JavaThread* current, frame& top);
2072 
2073   void recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case);
2074   void finish_thaw(frame& f);
2075 
2076 private:
2077   template<typename FKind> bool recurse_thaw_java_frame(frame& caller, int num_frames);
2078   void finalize_thaw(frame& entry, int argsize);
2079 
2080   inline bool seen_by_gc();
2081 
2082   inline void before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame);
2083   inline void after_thaw_java_frame(const frame& f, bool bottom);
2084   inline void patch(frame& f, const frame& caller, bool bottom);
2085   void clear_bitmap_bits(address start, address end);
2086 
2087   NOINLINE void recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames);
2088   void recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller);
2089   void recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames);
2090   void recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames);
2091 
2092   void push_return_frame(frame& f);
2093   inline frame new_entry_frame();
2094   template<typename FKind> frame new_stack_frame(const frame& hf, frame& caller, bool bottom);
2095   inline void patch_pd(frame& f, const frame& sender);
2096   inline void patch_pd(frame& f, intptr_t* caller_sp);
2097   inline intptr_t* align(const frame& hf, intptr_t* frame_sp, frame& caller, bool bottom);
2098 
2099   void maybe_set_fastpath(intptr_t* sp) { if (sp > _fastpath) _fastpath = sp; }
2100 
2101   static inline void derelativize_interpreted_frame_metadata(const frame& hf, const frame& f);
2102 
2103  public:
2104   CONT_JFR_ONLY(FreezeThawJfrInfo& jfr_info() { return _jfr_info; })
2105 };
2106 
2107 template <typename ConfigT>
2108 class Thaw : public ThawBase {
2109 public:
2110   Thaw(JavaThread* thread, ContinuationWrapper& cont) : ThawBase(thread, cont) {}
2111 
2112   inline bool can_thaw_fast(stackChunkOop chunk) {
2113     return    !_barriers
2114            &&  _thread->cont_fastpath_thread_state()
2115            && !chunk->has_thaw_slowpath_condition()
2116            && !PreserveFramePointer;
2117   }
2118 
2119   inline intptr_t* thaw(Continuation::thaw_kind kind);
2120   NOINLINE intptr_t* thaw_fast(stackChunkOop chunk);
2121   NOINLINE intptr_t* thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind);
2122   inline void patch_caller_links(intptr_t* sp, intptr_t* bottom);
2123 };
2124 
2125 template <typename ConfigT>
2126 inline intptr_t* Thaw<ConfigT>::thaw(Continuation::thaw_kind kind) {
2127   verify_continuation(_cont.continuation());
2128   assert(!jdk_internal_vm_Continuation::done(_cont.continuation()), "");
2129   assert(!_cont.is_empty(), "");
2130 
2131   stackChunkOop chunk = _cont.tail();
2132   assert(chunk != nullptr, "guaranteed by prepare_thaw");
2133   assert(!chunk->is_empty(), "guaranteed by prepare_thaw");
2134 
2135   _barriers = chunk->requires_barriers();
2136   return (LIKELY(can_thaw_fast(chunk))) ? thaw_fast(chunk)
2137                                         : thaw_slow(chunk, kind);
2138 }
2139 
2140 class ReconstructedStack : public StackObj {
2141   intptr_t* _base;  // _cont.entrySP(); // top of the entry frame
2142   int _thaw_size;
2143   int _argsize;
2144 public:
2145   ReconstructedStack(intptr_t* base, int thaw_size, int argsize)
2146   : _base(base), _thaw_size(thaw_size - (argsize == 0 ? frame::metadata_words_at_top : 0)), _argsize(argsize) {
2147     // The only possible source of misalignment is stack-passed arguments b/c compiled frames are 16-byte aligned.
2148     assert(argsize != 0 || (_base - _thaw_size) == ContinuationHelper::frame_align_pointer(_base - _thaw_size), "");
2149     // We're at most one alignment word away from entrySP
2150     assert(_base - 1 <= top() + total_size() + frame::metadata_words_at_bottom, "missed entry frame");
2151   }
2152 
2153   int entry_frame_extension() const { return _argsize + (_argsize > 0 ? frame::metadata_words_at_top : 0); }
2154 
2155   // top and bottom stack pointers
2156   intptr_t* sp() const { return ContinuationHelper::frame_align_pointer(_base - _thaw_size); }
2157   intptr_t* bottom_sp() const { return ContinuationHelper::frame_align_pointer(_base - entry_frame_extension()); }
2158 
2159   // several operations operate on the totality of the stack being reconstructed,
2160   // including the metadata words
2161   intptr_t* top() const { return sp() - frame::metadata_words_at_bottom;  }
2162   int total_size() const { return _thaw_size + frame::metadata_words_at_bottom; }
2163 };
2164 
2165 inline void ThawBase::clear_chunk(stackChunkOop chunk) {
2166   chunk->set_sp(chunk->bottom());
2167   chunk->set_max_thawing_size(0);
2168 }
2169 
2170 int ThawBase::remove_top_compiled_frame_from_chunk(stackChunkOop chunk, int &argsize) {
2171   bool empty = false;
2172   StackChunkFrameStream<ChunkFrames::CompiledOnly> f(chunk);
2173   DEBUG_ONLY(intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();)
2174   assert(chunk_sp == f.sp(), "");
2175   assert(chunk_sp == f.unextended_sp(), "");
2176 
2177   int frame_size = f.cb()->frame_size();
2178   argsize = f.stack_argsize();
2179   bool is_stub = f.is_stub();
2180 
2181   f.next(SmallRegisterMap::instance, true /* stop */);
2182   empty = f.is_done();
2183   assert(!empty || argsize == chunk->argsize(), "");
2184 
2185   assert(!is_stub || !empty, "runtime stub should have caller frame");
2186   if (is_stub) {
2187     // If we don't thaw the top compiled frame too, after restoring the saved
2188     // registers back in Java, we would hit the return barrier to thaw one more
2189     // frame effectively overwritting the restored registers during that call.
2190     f.get_cb();
2191     frame_size += f.cb()->frame_size();
2192     argsize = f.stack_argsize();
2193     f.next(SmallRegisterMap::instance, true /* stop */);
2194     empty = f.is_done();
2195     assert(!empty || argsize == chunk->argsize(), "");
2196   }
2197 
2198   if (empty) {
2199     clear_chunk(chunk);
2200   } else {
2201     chunk->set_sp(chunk->sp() + frame_size);
2202     chunk->set_max_thawing_size(chunk->max_thawing_size() - frame_size);
2203     // We set chunk->pc to the return pc into the next frame
2204     chunk->set_pc(f.pc());
2205 #ifdef ASSERT
2206     {
2207       intptr_t* retaddr_slot = (chunk_sp
2208                                 + frame_size
2209                                 - frame::sender_sp_ret_address_offset());
2210       assert(f.pc() == ContinuationHelper::return_address_at(retaddr_slot),
2211              "unexpected pc");
2212     }
2213 #endif
2214   }
2215   assert(empty == chunk->is_empty(), "");
2216   // returns the size required to store the frame on stack, and because it is a
2217   // compiled frame, it must include a copy of the arguments passed by the caller
2218   return frame_size + argsize + frame::metadata_words_at_top;
2219 }
2220 
2221 void ThawBase::copy_from_chunk(intptr_t* from, intptr_t* to, int size) {
2222   assert(to >= _top_stack_address, "overwrote past thawing space"
2223     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(to), p2i(_top_stack_address));
2224   assert(to + size <= _cont.entrySP(), "overwrote past thawing space");
2225   _cont.tail()->copy_from_chunk_to_stack(from, to, size);
2226   CONT_JFR_ONLY(_jfr_info.record_size_copied(size);)
2227 }
2228 
2229 void ThawBase::patch_return(intptr_t* sp, bool is_last) {
2230   log_develop_trace(continuations)("thaw_fast patching -- sp: " INTPTR_FORMAT, p2i(sp));
2231 
2232   address pc = !is_last ? StubRoutines::cont_returnBarrier() : _cont.entryPC();
2233   ContinuationHelper::patch_return_address_at(
2234     sp - frame::sender_sp_ret_address_offset(),
2235     pc);
2236 }
2237 
2238 template <typename ConfigT>
2239 NOINLINE intptr_t* Thaw<ConfigT>::thaw_fast(stackChunkOop chunk) {
2240   assert(chunk == _cont.tail(), "");
2241   assert(!chunk->has_mixed_frames(), "");
2242   assert(!chunk->requires_barriers(), "");
2243   assert(!chunk->has_bitmap(), "");
2244   assert(!_thread->is_interp_only_mode(), "");
2245 
2246   LogTarget(Trace, continuations) lt;
2247   if (lt.develop_is_enabled()) {
2248     LogStream ls(lt);
2249     ls.print_cr("thaw_fast");
2250     chunk->print_on(true, &ls);
2251   }
2252 
2253   // Below this heuristic, we thaw the whole chunk, above it we thaw just one frame.
2254   static const int threshold = 500; // words
2255 
2256   const int full_chunk_size = chunk->stack_size() - chunk->sp(); // this initial size could be reduced if it's a partial thaw
2257   int argsize, thaw_size;
2258 
2259   intptr_t* const chunk_sp = chunk->start_address() + chunk->sp();
2260 
2261   bool partial, empty;
2262   if (LIKELY(!TEST_THAW_ONE_CHUNK_FRAME && (full_chunk_size < threshold))) {
2263     prefetch_chunk_pd(chunk->start_address(), full_chunk_size); // prefetch anticipating memcpy starting at highest address
2264 
2265     partial = false;
2266     argsize = chunk->argsize(); // must be called *before* clearing the chunk
2267     clear_chunk(chunk);
2268     thaw_size = full_chunk_size;
2269     empty = true;
2270   } else { // thaw a single frame
2271     partial = true;
2272     thaw_size = remove_top_compiled_frame_from_chunk(chunk, argsize);
2273     empty = chunk->is_empty();
2274   }
2275 
2276   // Are we thawing the last frame(s) in the continuation
2277   const bool is_last = empty && chunk->parent() == nullptr;
2278   assert(!is_last || argsize == 0, "");
2279 
2280   log_develop_trace(continuations)("thaw_fast partial: %d is_last: %d empty: %d size: %d argsize: %d entrySP: " PTR_FORMAT,
2281                               partial, is_last, empty, thaw_size, argsize, p2i(_cont.entrySP()));
2282 
2283   ReconstructedStack rs(_cont.entrySP(), thaw_size, argsize);
2284 
2285   // also copy metadata words at frame bottom
2286   copy_from_chunk(chunk_sp - frame::metadata_words_at_bottom, rs.top(), rs.total_size());
2287 
2288   // update the ContinuationEntry
2289   _cont.set_argsize(argsize);
2290   log_develop_trace(continuations)("setting entry argsize: %d", _cont.argsize());
2291   assert(rs.bottom_sp() == _cont.entry()->bottom_sender_sp(), "");
2292 
2293   // install the return barrier if not last frame, or the entry's pc if last
2294   patch_return(rs.bottom_sp(), is_last);
2295 
2296   // insert the back links from callee to caller frames
2297   patch_caller_links(rs.top(), rs.top() + rs.total_size());
2298 
2299   assert(is_last == _cont.is_empty(), "");
2300   assert(_cont.chunk_invariant(), "");
2301 
2302 #if CONT_JFR
2303   EventContinuationThawFast e;
2304   if (e.should_commit()) {
2305     e.set_id(cast_from_oop<u8>(chunk));
2306     e.set_size(thaw_size << LogBytesPerWord);
2307     e.set_full(!partial);
2308     e.commit();
2309   }
2310 #endif
2311 
2312 #ifdef ASSERT
2313   set_anchor(_thread, rs.sp());
2314   log_frames(_thread);
2315   if (LoomDeoptAfterThaw) {
2316     do_deopt_after_thaw(_thread);
2317   }
2318   clear_anchor(_thread);
2319 #endif
2320 
2321   return rs.sp();
2322 }
2323 
2324 inline bool ThawBase::seen_by_gc() {
2325   return _barriers || _cont.tail()->is_gc_mode();
2326 }
2327 
2328 template <typename ConfigT>
2329 NOINLINE intptr_t* Thaw<ConfigT>::thaw_slow(stackChunkOop chunk, Continuation::thaw_kind kind) {
2330   bool retry_fast_path = false;
2331 
2332   bool preempted_case = _cont.is_preempted();
2333   if (preempted_case) {
2334     if (chunk->object_waiter() != nullptr) {
2335       assert(chunk->current_pending_monitor() != nullptr || chunk->current_waiting_monitor() != nullptr, "");
2336       return push_resume_monitor_operation(chunk);
2337     }
2338     retry_fast_path = true;
2339   }
2340 
2341 #if INCLUDE_ZGC || INCLUDE_SHENANDOAHGC
2342   if (UseZGC || UseShenandoahGC) {
2343     _cont.tail()->relativize_derived_pointers_concurrently();
2344   }
2345 #endif
2346 
2347   // First thaw after freeze. If there were oops in the stacklock
2348   // during freeze, restore them now.
2349   if (chunk->lockstack_size() > 0) {
2350     assert(kind == Continuation::thaw_top || preempted_case, "");
2351     int lockStackSize = chunk->lockstack_size();
2352     assert(lockStackSize > 0, "should be");
2353 
2354     oop tmp_lockstack[8];
2355     chunk->copy_lockstack(tmp_lockstack);
2356     _thread->lock_stack().move_from_address(tmp_lockstack, lockStackSize);
2357 
2358     chunk->set_lockstack_size(0);
2359     chunk->set_has_lockstack(false);
2360     retry_fast_path = true;
2361   }
2362 
2363   // Retry the fast path now that we possibly cleared the FLAG_HAS_LOCKSTACK
2364   // and FLAGS_PREEMPTED flags from the stackChunk.
2365   if (retry_fast_path && can_thaw_fast(chunk)) {
2366     intptr_t* sp = thaw_fast(chunk);
2367     if (preempted_case) {
2368       int preempt_kind = chunk->get_and_clear_preempt_kind();
2369       return handle_preempted_continuation(sp, preempt_kind, true /* fast_case */);
2370     }
2371     return sp;
2372   }
2373 
2374   LogTarget(Trace, continuations) lt;
2375   if (lt.develop_is_enabled()) {
2376     LogStream ls(lt);
2377     ls.print_cr("thaw slow return_barrier: %d " INTPTR_FORMAT, kind, p2i(chunk));
2378     chunk->print_on(true, &ls);
2379   }
2380 
2381 #if CONT_JFR
2382   EventContinuationThawSlow e;
2383   if (e.should_commit()) {
2384     e.set_id(cast_from_oop<u8>(_cont.continuation()));
2385     e.commit();
2386   }
2387 #endif
2388 
2389   DEBUG_ONLY(_frames = 0;)
2390   _align_size = 0;
2391   bool is_return_barrier = kind != Continuation::thaw_top;
2392   int num_frames = (is_return_barrier ? 1 : 2);
2393 
2394   _stream = StackChunkFrameStream<ChunkFrames::Mixed>(chunk);
2395   _top_unextended_sp_before_thaw = _stream.unextended_sp();
2396 
2397   frame heap_frame = _stream.to_frame();
2398   if (lt.develop_is_enabled()) {
2399     LogStream ls(lt);
2400     ls.print_cr("top hframe before (thaw):");
2401     assert(heap_frame.is_heap_frame(), "should have created a relative frame");
2402     heap_frame.print_value_on(&ls, nullptr);
2403   }
2404 
2405   frame caller; // the thawed caller on the stack
2406   recurse_thaw(heap_frame, caller, num_frames, preempted_case);
2407   finish_thaw(caller); // caller is now the topmost thawed frame
2408   _cont.write();
2409 
2410   assert(_cont.chunk_invariant(), "");
2411 
2412   JVMTI_ONLY(if (!is_return_barrier) invalidate_jvmti_stack(_thread));
2413 
2414   _thread->set_cont_fastpath(_fastpath);
2415 
2416   intptr_t* sp = caller.sp();
2417 
2418   if (preempted_case) {
2419     int preempt_kind = chunk->get_and_clear_preempt_kind();
2420     return handle_preempted_continuation(sp, preempt_kind, false /* fast_case */);
2421   }
2422   return sp;
2423 }
2424 
2425 void ThawBase::recurse_thaw(const frame& heap_frame, frame& caller, int num_frames, bool top_on_preempt_case) {
2426   log_develop_debug(continuations)("thaw num_frames: %d", num_frames);
2427   assert(!_cont.is_empty(), "no more frames");
2428   assert(num_frames > 0, "");
2429   assert(!heap_frame.is_empty(), "");
2430 
2431   if (top_on_preempt_case && (heap_frame.is_native_frame() || heap_frame.is_runtime_frame())) {
2432     heap_frame.is_native_frame() ? recurse_thaw_native_frame(heap_frame, caller, 2) : recurse_thaw_stub_frame(heap_frame, caller, 2);
2433   } else if (!heap_frame.is_interpreted_frame()) {
2434     recurse_thaw_compiled_frame(heap_frame, caller, num_frames, false);
2435   } else {
2436     recurse_thaw_interpreted_frame(heap_frame, caller, num_frames);
2437   }
2438 }
2439 
2440 template<typename FKind>
2441 bool ThawBase::recurse_thaw_java_frame(frame& caller, int num_frames) {
2442   assert(num_frames > 0, "");
2443 
2444   DEBUG_ONLY(_frames++;)
2445 
2446   int argsize = _stream.stack_argsize();
2447 
2448   _stream.next(SmallRegisterMap::instance);
2449   assert(_stream.to_frame().is_empty() == _stream.is_done(), "");
2450 
2451   // we never leave a compiled caller of an interpreted frame as the top frame in the chunk
2452   // as it makes detecting that situation and adjusting unextended_sp tricky
2453   if (num_frames == 1 && !_stream.is_done() && FKind::interpreted && _stream.is_compiled()) {
2454     log_develop_trace(continuations)("thawing extra compiled frame to not leave a compiled interpreted-caller at top");
2455     num_frames++;
2456   }
2457 
2458   if (num_frames == 1 || _stream.is_done()) { // end recursion
2459     finalize_thaw(caller, FKind::interpreted ? 0 : argsize);
2460     return true; // bottom
2461   } else { // recurse
2462     recurse_thaw(_stream.to_frame(), caller, num_frames - 1, false /* top_on_preempt_case */);
2463     return false;
2464   }
2465 }
2466 
2467 void ThawBase::finalize_thaw(frame& entry, int argsize) {
2468   stackChunkOop chunk = _cont.tail();
2469 
2470   if (!_stream.is_done()) {
2471     assert(_stream.sp() >= chunk->sp_address(), "");
2472     chunk->set_sp(chunk->to_offset(_stream.sp()));
2473     chunk->set_pc(_stream.pc());
2474   } else {
2475     chunk->set_sp(chunk->bottom());
2476     chunk->set_pc(nullptr);
2477   }
2478   assert(_stream.is_done() == chunk->is_empty(), "");
2479 
2480   int total_thawed = pointer_delta_as_int(_stream.unextended_sp(), _top_unextended_sp_before_thaw);
2481   chunk->set_max_thawing_size(chunk->max_thawing_size() - total_thawed);
2482 
2483   _cont.set_argsize(argsize);
2484   entry = new_entry_frame();
2485 
2486   assert(entry.sp() == _cont.entrySP(), "");
2487   assert(Continuation::is_continuation_enterSpecial(entry), "");
2488   assert(_cont.is_entry_frame(entry), "");
2489 }
2490 
2491 inline void ThawBase::before_thaw_java_frame(const frame& hf, const frame& caller, bool bottom, int num_frame) {
2492   LogTarget(Trace, continuations) lt;
2493   if (lt.develop_is_enabled()) {
2494     LogStream ls(lt);
2495     ls.print_cr("======== THAWING FRAME: %d", num_frame);
2496     assert(hf.is_heap_frame(), "should be");
2497     hf.print_value_on(&ls, nullptr);
2498   }
2499   assert(bottom == _cont.is_entry_frame(caller), "bottom: %d is_entry_frame: %d", bottom, _cont.is_entry_frame(hf));
2500 }
2501 
2502 inline void ThawBase::after_thaw_java_frame(const frame& f, bool bottom) {
2503 #ifdef ASSERT
2504   LogTarget(Trace, continuations) lt;
2505   if (lt.develop_is_enabled()) {
2506     LogStream ls(lt);
2507     ls.print_cr("thawed frame:");
2508     print_frame_layout(f, false, &ls); // f.print_on(&ls);
2509   }
2510 #endif
2511 }
2512 
2513 inline void ThawBase::patch(frame& f, const frame& caller, bool bottom) {
2514   assert(!bottom || caller.fp() == _cont.entryFP(), "");
2515   if (bottom) {
2516     ContinuationHelper::Frame::patch_pc(caller, _cont.is_empty() ? caller.pc()
2517                                                                  : StubRoutines::cont_returnBarrier());
2518   } else {
2519     // caller might have been deoptimized during thaw but we've overwritten the return address when copying f from the heap.
2520     // If the caller is not deoptimized, pc is unchanged.
2521     ContinuationHelper::Frame::patch_pc(caller, caller.raw_pc());
2522   }
2523 
2524   patch_pd(f, caller);
2525 
2526   if (f.is_interpreted_frame()) {
2527     ContinuationHelper::InterpretedFrame::patch_sender_sp(f, caller);
2528   }
2529 
2530   assert(!bottom || !_cont.is_empty() || Continuation::is_continuation_entry_frame(f, nullptr), "");
2531   assert(!bottom || (_cont.is_empty() != Continuation::is_cont_barrier_frame(f)), "");
2532 }
2533 
2534 void ThawBase::clear_bitmap_bits(address start, address end) {
2535   assert(is_aligned(start, wordSize), "should be aligned: " PTR_FORMAT, p2i(start));
2536   assert(is_aligned(end, VMRegImpl::stack_slot_size), "should be aligned: " PTR_FORMAT, p2i(end));
2537 
2538   // we need to clear the bits that correspond to arguments as they reside in the caller frame
2539   // or they will keep objects that are otherwise unreachable alive.
2540 
2541   // Align `end` if UseCompressedOops is not set to avoid UB when calculating the bit index, since
2542   // `end` could be at an odd number of stack slots from `start`, i.e might not be oop aligned.
2543   // If that's the case the bit range corresponding to the last stack slot should not have bits set
2544   // anyways and we assert that before returning.
2545   address effective_end = UseCompressedOops ? end : align_down(end, wordSize);
2546   log_develop_trace(continuations)("clearing bitmap for " INTPTR_FORMAT " - " INTPTR_FORMAT, p2i(start), p2i(effective_end));
2547   stackChunkOop chunk = _cont.tail();
2548   chunk->bitmap().clear_range(chunk->bit_index_for(start), chunk->bit_index_for(effective_end));
2549   assert(effective_end == end || !chunk->bitmap().at(chunk->bit_index_for(effective_end)), "bit should not be set");
2550 }
2551 
2552 intptr_t* ThawBase::handle_preempted_continuation(intptr_t* sp, int preempt_kind, bool fast_case) {
2553   frame top(sp);
2554   assert(top.pc() == *(address*)(sp - frame::sender_sp_ret_address_offset()), "");
2555 
2556   assert(_cont.is_preempted(), "must be");
2557   _cont.set_preempted(false);
2558 
2559 #if INCLUDE_JVMTI
2560   bool is_vthread = Continuation::continuation_scope(_cont.continuation()) == java_lang_VirtualThread::vthread_scope();
2561   if (is_vthread) {
2562     if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
2563       jvmti_mount_end(_thread, _cont, top);
2564     } else {
2565       _thread->set_is_in_VTMS_transition(false);
2566       java_lang_Thread::set_is_in_VTMS_transition(_thread->vthread(), false);
2567     }
2568   }
2569 #endif
2570 
2571   if (preempt_kind == freeze_on_wait) {
2572     if (_thread->pending_interrupted_exception()) {
2573       throw_interrupted_exception(_thread, top);
2574       _thread->set_pending_interrupted_exception(false);
2575     }
2576     // Possibly update return pc on the top native wrapper frame so
2577     // that we resume execution at the right instruction.
2578     fix_native_return_pc_pd(top);
2579   } else {
2580     assert(preempt_kind == freeze_on_monitorenter, "");
2581     if (top.is_runtime_frame()) {
2582       if (fast_case) {
2583         // If we thawed in the slow path the runtime stub frame already has the correct fp
2584         // (see ThawBase::new_stack_frame). On the fast path though, we copied the original
2585         // fp at the time of freeze which now will have to be fixed.
2586         int fsize = ContinuationHelper::StubFrame::size(top);
2587         patch_pd(top, sp + fsize);
2588       }
2589 
2590       // The continuation might now run on a different platform thread than the previous time so
2591       // we need to adjust the current thread saved in the stub frame before restoring registers.
2592       JavaThread** thread_addr = frame::saved_thread_address(top);
2593       if (thread_addr != nullptr) *thread_addr = _thread;
2594     }
2595   }
2596   sp = push_resume_adapter(top);
2597   return sp;
2598 }
2599 
2600 void ThawBase::throw_interrupted_exception(JavaThread* current, frame& top) {
2601   ContinuationWrapper::SafepointOp so(current, _cont);
2602   // Since we might safepoint set the anchor so that the stack can we walked.
2603   set_anchor(current, top.sp());
2604   JRT_BLOCK
2605     THROW(vmSymbols::java_lang_InterruptedException());
2606   JRT_BLOCK_END
2607   clear_anchor(current);
2608 }
2609 
2610 NOINLINE void ThawBase::recurse_thaw_interpreted_frame(const frame& hf, frame& caller, int num_frames) {
2611   assert(hf.is_interpreted_frame(), "");
2612 
2613   if (UNLIKELY(seen_by_gc())) {
2614     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance);
2615   }
2616 
2617   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::InterpretedFrame>(caller, num_frames);
2618 
2619   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2620 
2621   _align_size += frame::align_wiggle; // possible added alignment for internal interpreted frame alignment om AArch64
2622 
2623   frame f = new_stack_frame<ContinuationHelper::InterpretedFrame>(hf, caller, is_bottom_frame);
2624 
2625   intptr_t* const stack_frame_top = f.sp() + frame::metadata_words_at_top;
2626   intptr_t* const stack_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(f);
2627   intptr_t* const heap_frame_top = hf.unextended_sp() + frame::metadata_words_at_top;
2628   intptr_t* const heap_frame_bottom = ContinuationHelper::InterpretedFrame::frame_bottom(hf);
2629 
2630   assert(hf.is_heap_frame(), "should be");
2631   assert(!f.is_heap_frame(), "should not be");
2632 
2633   const int fsize = pointer_delta_as_int(heap_frame_bottom, heap_frame_top);
2634   assert((stack_frame_bottom == stack_frame_top + fsize), "");
2635 
2636   // Some architectures (like AArch64/PPC64/RISC-V) add padding between the locals and the fixed_frame to keep the fp 16-byte-aligned.
2637   // On those architectures we freeze the padding in order to keep the same fp-relative offsets in the fixed_frame.
2638   copy_from_chunk(heap_frame_top, stack_frame_top, fsize);
2639 
2640   // Make sure the relativized locals is already set.
2641   assert(f.interpreter_frame_local_at(0) == stack_frame_bottom - 1, "invalid frame bottom");
2642 
2643   derelativize_interpreted_frame_metadata(hf, f);
2644   patch(f, caller, is_bottom_frame);
2645 
2646   assert(f.is_interpreted_frame_valid(_cont.thread()), "invalid thawed frame");
2647   assert(stack_frame_bottom <= ContinuationHelper::Frame::frame_top(caller), "");
2648 
2649   CONT_JFR_ONLY(_jfr_info.record_interpreted_frame();)
2650 
2651   maybe_set_fastpath(f.sp());
2652 
2653   Method* m = hf.interpreter_frame_method();
2654   // For native frames we need to count parameters, possible alignment, plus the 2 extra words (temp oop/result handler).
2655   const int locals = !m->is_native() ? m->max_locals() : m->size_of_parameters() + frame::align_wiggle + 2;
2656 
2657   if (!is_bottom_frame) {
2658     // can only fix caller once this frame is thawed (due to callee saved regs)
2659     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance);
2660   } else if (_cont.tail()->has_bitmap() && locals > 0) {
2661     assert(hf.is_heap_frame(), "should be");
2662     address start = (address)(heap_frame_bottom - locals);
2663     address end = (address)heap_frame_bottom;
2664     clear_bitmap_bits(start, end);
2665   }
2666 
2667   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2668   caller = f;
2669 }
2670 
2671 void ThawBase::recurse_thaw_compiled_frame(const frame& hf, frame& caller, int num_frames, bool stub_caller) {
2672   assert(hf.is_compiled_frame(), "");
2673   assert(_cont.is_preempted() || !stub_caller, "stub caller not at preemption");
2674 
2675   if (!stub_caller && UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2676     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance);
2677   }
2678 
2679   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::CompiledFrame>(caller, num_frames);
2680 
2681   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2682 
2683   assert(caller.sp() == caller.unextended_sp(), "");
2684 
2685   if ((!is_bottom_frame && caller.is_interpreted_frame()) || (is_bottom_frame && Interpreter::contains(_cont.tail()->pc()))) {
2686     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_compiled_frame
2687   }
2688 
2689   // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2690   // yet laid out in the stack, and so the original_pc is not stored in it.
2691   // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2692   frame f = new_stack_frame<ContinuationHelper::CompiledFrame>(hf, caller, is_bottom_frame);
2693   intptr_t* const stack_frame_top = f.sp();
2694   intptr_t* const heap_frame_top = hf.unextended_sp();
2695 
2696   const int added_argsize = (is_bottom_frame || caller.is_interpreted_frame()) ? hf.compiled_frame_stack_argsize() : 0;
2697   int fsize = ContinuationHelper::CompiledFrame::size(hf) + added_argsize;
2698   assert(fsize <= (int)(caller.unextended_sp() - f.unextended_sp()), "");
2699 
2700   intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2701   intptr_t* to   = stack_frame_top - frame::metadata_words_at_bottom;
2702   // copy metadata, except the metadata at the top of the (unextended) entry frame
2703   int sz = fsize + frame::metadata_words_at_bottom + (is_bottom_frame && added_argsize == 0 ? 0 : frame::metadata_words_at_top);
2704 
2705   // If we're the bottom-most thawed frame, we're writing to within one word from entrySP
2706   // (we might have one padding word for alignment)
2707   assert(!is_bottom_frame || (_cont.entrySP() - 1 <= to + sz && to + sz <= _cont.entrySP()), "");
2708   assert(!is_bottom_frame || hf.compiled_frame_stack_argsize() != 0 || (to + sz && to + sz == _cont.entrySP()), "");
2709 
2710   copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2711 
2712   patch(f, caller, is_bottom_frame);
2713 
2714   // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2715   assert(!f.is_deoptimized_frame(), "");
2716   if (hf.is_deoptimized_frame()) {
2717     maybe_set_fastpath(f.sp());
2718   } else if (_thread->is_interp_only_mode()
2719               || (_cont.is_preempted() && f.cb()->as_nmethod()->is_marked_for_deoptimization())) {
2720     // The caller of the safepoint stub when the continuation is preempted is not at a call instruction, and so
2721     // cannot rely on nmethod patching for deopt.
2722 
2723     log_develop_trace(continuations)("Deoptimizing thawed frame");
2724     DEBUG_ONLY(ContinuationHelper::Frame::patch_pc(f, nullptr));
2725 
2726     f.deoptimize(nullptr); // the null thread simply avoids the assertion in deoptimize which we're not set up for
2727     assert(f.is_deoptimized_frame(), "");
2728     assert(ContinuationHelper::Frame::is_deopt_return(f.raw_pc(), f), "");
2729     maybe_set_fastpath(f.sp());
2730   }
2731 
2732   if (!is_bottom_frame) {
2733     // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2734     _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance);
2735   } else if (_cont.tail()->has_bitmap() && added_argsize > 0) {
2736     address start = (address)(heap_frame_top + ContinuationHelper::CompiledFrame::size(hf) + frame::metadata_words_at_top);
2737     int stack_args_slots = f.cb()->as_nmethod()->num_stack_arg_slots(false /* rounded */);
2738     int argsize_in_bytes = stack_args_slots * VMRegImpl::stack_slot_size;
2739     clear_bitmap_bits(start, start + argsize_in_bytes);
2740   }
2741 
2742   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2743   caller = f;
2744 }
2745 
2746 void ThawBase::recurse_thaw_stub_frame(const frame& hf, frame& caller, int num_frames) {
2747   DEBUG_ONLY(_frames++;)
2748   bool is_bottom_frame = false;
2749 
2750   if (UNLIKELY(seen_by_gc())) {
2751     // Process the stub's caller here since we might need the full map (if the stub was
2752     // generated on a poll on return we shouldn't need a full map).
2753     RegisterMap map(nullptr,
2754                     RegisterMap::UpdateMap::include,
2755                     RegisterMap::ProcessFrames::skip,
2756                     RegisterMap::WalkContinuation::skip);
2757     map.set_include_argument_oops(false);
2758     _stream.next(&map);
2759     if (!_stream.is_done()) {
2760       _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, &map);
2761     }
2762   } else {
2763     _stream.next(SmallRegisterMap::instance);
2764   }
2765 
2766   if (_stream.is_done()) {
2767     finalize_thaw(caller, 0);
2768     is_bottom_frame = true;
2769   } else {
2770     frame f = _stream.to_frame();
2771     if (f.is_interpreted_frame()) {
2772       recurse_thaw_interpreted_frame(f, caller, num_frames);
2773     } else {
2774       recurse_thaw_compiled_frame(f, caller, num_frames, true);
2775     }
2776   }
2777 
2778   assert(!is_bottom_frame || !_cont.is_empty(), "");
2779   assert(caller.sp() == caller.unextended_sp(), "");
2780   assert(!caller.is_native_frame() || (is_bottom_frame && Continuation::is_continuation_enterSpecial(caller)), "caller should't be native except for enterSpecial case");
2781 
2782   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2783 
2784   if ((!is_bottom_frame && caller.is_interpreted_frame()) || (is_bottom_frame && Interpreter::contains(_cont.tail()->pc()))) {
2785     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_stub_frame
2786   }
2787 
2788   frame f = new_stack_frame<ContinuationHelper::StubFrame>(hf, caller, false);
2789   intptr_t* stack_frame_top = f.sp();
2790   intptr_t* heap_frame_top = hf.sp();
2791   int fsize = ContinuationHelper::StubFrame::size(hf);
2792 
2793   copy_from_chunk(heap_frame_top - frame::metadata_words, stack_frame_top - frame::metadata_words,
2794                   fsize + frame::metadata_words);
2795 
2796   patch(f, caller, is_bottom_frame);
2797 
2798   if (!is_bottom_frame) {
2799     // can only fix caller once this frame is thawed (due to callee saved regs)
2800     RegisterMap map(nullptr,
2801                     RegisterMap::UpdateMap::include,
2802                     RegisterMap::ProcessFrames::skip,
2803                     RegisterMap::WalkContinuation::skip);
2804     map.set_include_argument_oops(false);
2805     f.oop_map()->update_register_map(&f, &map);
2806     ContinuationHelper::update_register_map_with_callee(caller, &map);
2807     _cont.tail()->fix_thawed_frame(caller, &map);
2808   }
2809 
2810   DEBUG_ONLY(after_thaw_java_frame(f, is_bottom_frame);)
2811   caller = f;
2812 }
2813 
2814 void ThawBase::recurse_thaw_native_frame(const frame& hf, frame& caller, int num_frames) {
2815   assert(hf.is_native_frame(), "");
2816   assert(_cont.is_preempted() && hf.cb()->as_nmethod()->method()->is_object_wait0(), "");
2817 
2818   if (UNLIKELY(seen_by_gc())) { // recurse_thaw_stub_frame already invoked our barriers with a full regmap
2819     _cont.tail()->do_barriers<stackChunkOopDesc::BarrierType::Store>(_stream, SmallRegisterMap::instance);
2820   }
2821 
2822   const bool is_bottom_frame = recurse_thaw_java_frame<ContinuationHelper::NativeFrame>(caller, num_frames);
2823   assert(!is_bottom_frame, "");
2824 
2825   DEBUG_ONLY(before_thaw_java_frame(hf, caller, is_bottom_frame, num_frames);)
2826 
2827   assert(caller.sp() == caller.unextended_sp(), "");
2828 
2829   if (caller.is_interpreted_frame()) {
2830     _align_size += frame::align_wiggle; // we add one whether or not we've aligned because we add it in recurse_freeze_compiled_frame
2831   }
2832 
2833   // new_stack_frame must construct the resulting frame using hf.pc() rather than hf.raw_pc() because the frame is not
2834   // yet laid out in the stack, and so the original_pc is not stored in it.
2835   // As a result, f.is_deoptimized_frame() is always false and we must test hf to know if the frame is deoptimized.
2836   frame f = new_stack_frame<ContinuationHelper::NativeFrame>(hf, caller, false /* bottom */);
2837   intptr_t* const stack_frame_top = f.sp();
2838   intptr_t* const heap_frame_top = hf.unextended_sp();
2839 
2840   int fsize = ContinuationHelper::NativeFrame::size(hf);
2841   assert(fsize <= (int)(caller.unextended_sp() - f.unextended_sp()), "");
2842 
2843   intptr_t* from = heap_frame_top - frame::metadata_words_at_bottom;
2844   intptr_t* to   = stack_frame_top - frame::metadata_words_at_bottom;
2845   int sz = fsize + frame::metadata_words_at_bottom;
2846 
2847   copy_from_chunk(from, to, sz); // copying good oops because we invoked barriers above
2848 
2849   patch(f, caller, false /* bottom */);
2850 
2851   // f.is_deoptimized_frame() is always false and we must test hf.is_deoptimized_frame() (see comment above)
2852   assert(!f.is_deoptimized_frame(), "");
2853   assert(!hf.is_deoptimized_frame(), "");
2854   assert(!f.cb()->as_nmethod()->is_marked_for_deoptimization(), "");
2855 
2856   // can only fix caller once this frame is thawed (due to callee saved regs); this happens on the stack
2857   _cont.tail()->fix_thawed_frame(caller, SmallRegisterMap::instance);
2858 
2859   DEBUG_ONLY(after_thaw_java_frame(f, false /* bottom */);)
2860   caller = f;
2861 }
2862 
2863 void ThawBase::finish_thaw(frame& f) {
2864   stackChunkOop chunk = _cont.tail();
2865 
2866   if (chunk->is_empty()) {
2867     // Only remove chunk from list if it can't be reused for another freeze
2868     if (seen_by_gc()) {
2869       _cont.set_tail(chunk->parent());
2870     } else {
2871       chunk->set_has_mixed_frames(false);
2872     }
2873     chunk->set_max_thawing_size(0);
2874   } else {
2875     chunk->set_max_thawing_size(chunk->max_thawing_size() - _align_size);
2876   }
2877   assert(chunk->is_empty() == (chunk->max_thawing_size() == 0), "");
2878 
2879   if (!is_aligned(f.sp(), frame::frame_alignment)) {
2880     assert(f.is_interpreted_frame(), "");
2881     f.set_sp(align_down(f.sp(), frame::frame_alignment));
2882   }
2883   push_return_frame(f);
2884   chunk->fix_thawed_frame(f, SmallRegisterMap::instance); // can only fix caller after push_return_frame (due to callee saved regs)
2885 
2886   assert(_cont.is_empty() == _cont.last_frame().is_empty(), "");
2887 
2888   log_develop_trace(continuations)("thawed %d frames", _frames);
2889 
2890   LogTarget(Trace, continuations) lt;
2891   if (lt.develop_is_enabled()) {
2892     LogStream ls(lt);
2893     ls.print_cr("top hframe after (thaw):");
2894     _cont.last_frame().print_value_on(&ls, nullptr);
2895   }
2896 }
2897 
2898 void ThawBase::push_return_frame(frame& f) { // see generate_cont_thaw
2899   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == f.cb()->as_nmethod()->is_deopt_pc(f.raw_pc()), "");
2900   assert(!f.is_compiled_frame() || f.is_deoptimized_frame() == (f.pc() != f.raw_pc()), "");
2901 
2902   LogTarget(Trace, continuations) lt;
2903   if (lt.develop_is_enabled()) {
2904     LogStream ls(lt);
2905     ls.print_cr("push_return_frame");
2906     f.print_value_on(&ls, nullptr);
2907   }
2908 
2909   assert(f.sp() - frame::metadata_words_at_bottom >= _top_stack_address, "overwrote past thawing space"
2910     " to: " INTPTR_FORMAT " top_address: " INTPTR_FORMAT, p2i(f.sp() - frame::metadata_words), p2i(_top_stack_address));
2911   ContinuationHelper::Frame::patch_pc(f, f.raw_pc()); // in case we want to deopt the frame in a full transition, this is checked.
2912   ContinuationHelper::push_pd(f);
2913 
2914   assert(ContinuationHelper::Frame::assert_frame_laid_out(f), "");
2915 }
2916 
2917 // returns new top sp
2918 // called after preparations (stack overflow check and making room)
2919 template<typename ConfigT>
2920 static inline intptr_t* thaw_internal(JavaThread* thread, const Continuation::thaw_kind kind) {
2921   assert(thread == JavaThread::current(), "Must be current thread");
2922 
2923   CONT_JFR_ONLY(EventContinuationThaw event;)
2924 
2925   log_develop_trace(continuations)("~~~~ thaw kind: %d sp: " INTPTR_FORMAT, kind, p2i(thread->last_continuation()->entry_sp()));
2926 
2927   ContinuationEntry* entry = thread->last_continuation();
2928   assert(entry != nullptr, "");
2929   oop oopCont = entry->cont_oop(thread);
2930 
2931   assert(!jdk_internal_vm_Continuation::done(oopCont), "");
2932   assert(oopCont == get_continuation(thread), "");
2933   verify_continuation(oopCont);
2934 
2935   assert(entry->is_virtual_thread() == (entry->scope(thread) == java_lang_VirtualThread::vthread_scope()), "");
2936 
2937   ContinuationWrapper cont(thread, oopCont);
2938   log_develop_debug(continuations)("THAW #" INTPTR_FORMAT " " INTPTR_FORMAT, cont.hash(), p2i((oopDesc*)oopCont));
2939 
2940 #ifdef ASSERT
2941   set_anchor_to_entry(thread, cont.entry());
2942   log_frames(thread);
2943   clear_anchor(thread);
2944 #endif
2945 
2946   Thaw<ConfigT> thw(thread, cont);
2947   intptr_t* const sp = thw.thaw(kind);
2948   assert(is_aligned(sp, frame::frame_alignment), "");
2949 
2950   DEBUG_ONLY(log_frames_after_thaw(thread, cont, sp);)
2951 
2952   CONT_JFR_ONLY(thw.jfr_info().post_jfr_event(&event, cont.continuation(), thread);)
2953 
2954   verify_continuation(cont.continuation());
2955   log_develop_debug(continuations)("=== End of thaw #" INTPTR_FORMAT, cont.hash());
2956 
2957   return sp;
2958 }
2959 
2960 #ifdef ASSERT
2961 static void do_deopt_after_thaw(JavaThread* thread) {
2962   int i = 0;
2963   StackFrameStream fst(thread, true, false);
2964   fst.register_map()->set_include_argument_oops(false);
2965   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
2966   for (; !fst.is_done(); fst.next()) {
2967     if (fst.current()->cb()->is_nmethod()) {
2968       nmethod* nm = fst.current()->cb()->as_nmethod();
2969       if (!nm->method()->is_continuation_native_intrinsic()) {
2970         nm->make_deoptimized();
2971       }
2972     }
2973   }
2974 }
2975 
2976 class ThawVerifyOopsClosure: public OopClosure {
2977   intptr_t* _p;
2978   outputStream* _st;
2979   bool is_good_oop(oop o) {
2980     return dbg_is_safe(o, -1) && dbg_is_safe(o->klass(), -1) && oopDesc::is_oop(o) && o->klass()->is_klass();
2981   }
2982 public:
2983   ThawVerifyOopsClosure(outputStream* st) : _p(nullptr), _st(st) {}
2984   intptr_t* p() { return _p; }
2985   void reset() { _p = nullptr; }
2986 
2987   virtual void do_oop(oop* p) {
2988     oop o = *p;
2989     if (o == nullptr || is_good_oop(o)) {
2990       return;
2991     }
2992     _p = (intptr_t*)p;
2993     _st->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT, p2i(*p), p2i(p));
2994   }
2995   virtual void do_oop(narrowOop* p) {
2996     oop o = RawAccess<>::oop_load(p);
2997     if (o == nullptr || is_good_oop(o)) {
2998       return;
2999     }
3000     _p = (intptr_t*)p;
3001     _st->print_cr("*** (narrow) non-oop %x found at " PTR_FORMAT, (int)(*p), p2i(p));
3002   }
3003 };
3004 
3005 static bool do_verify_after_thaw(JavaThread* thread, stackChunkOop chunk, outputStream* st) {
3006   assert(thread->has_last_Java_frame(), "");
3007 
3008   ResourceMark rm;
3009   ThawVerifyOopsClosure cl(st);
3010   NMethodToOopClosure cf(&cl, false);
3011 
3012   StackFrameStream fst(thread, true, false);
3013   fst.register_map()->set_include_argument_oops(false);
3014   ContinuationHelper::update_register_map_with_callee(*fst.current(), fst.register_map());
3015   for (; !fst.is_done() && !Continuation::is_continuation_enterSpecial(*fst.current()); fst.next()) {
3016     if (fst.current()->cb()->is_nmethod() && fst.current()->cb()->as_nmethod()->is_marked_for_deoptimization()) {
3017       st->print_cr(">>> do_verify_after_thaw deopt");
3018       fst.current()->deoptimize(nullptr);
3019       fst.current()->print_on(st);
3020     }
3021 
3022     fst.current()->oops_do(&cl, &cf, fst.register_map());
3023     if (cl.p() != nullptr) {
3024       frame fr = *fst.current();
3025       st->print_cr("Failed for frame barriers: %d",chunk->requires_barriers());
3026       fr.print_on(st);
3027       if (!fr.is_interpreted_frame()) {
3028         st->print_cr("size: %d argsize: %d",
3029                      ContinuationHelper::NonInterpretedUnknownFrame::size(fr),
3030                      ContinuationHelper::NonInterpretedUnknownFrame::stack_argsize(fr));
3031       }
3032       VMReg reg = fst.register_map()->find_register_spilled_here(cl.p(), fst.current()->sp());
3033       if (reg != nullptr) {
3034         st->print_cr("Reg %s %d", reg->name(), reg->is_stack() ? (int)reg->reg2stack() : -99);
3035       }
3036       cl.reset();
3037       DEBUG_ONLY(thread->print_frame_layout();)
3038       if (chunk != nullptr) {
3039         chunk->print_on(true, st);
3040       }
3041       return false;
3042     }
3043   }
3044   return true;
3045 }
3046 
3047 static void log_frames(JavaThread* thread) {
3048   const static int show_entry_callers = 100;
3049   LogTarget(Trace, continuations) lt;
3050   if (!lt.develop_is_enabled()) {
3051     return;
3052   }
3053   LogStream ls(lt);
3054 
3055   ls.print_cr("------- frames --------- for thread " INTPTR_FORMAT, p2i(thread));
3056   if (!thread->has_last_Java_frame()) {
3057     ls.print_cr("NO ANCHOR!");
3058   }
3059 
3060   RegisterMap map(thread,
3061                   RegisterMap::UpdateMap::include,
3062                   RegisterMap::ProcessFrames::include,
3063                   RegisterMap::WalkContinuation::skip);
3064   map.set_include_argument_oops(false);
3065 
3066   if (false) {
3067     for (frame f = thread->last_frame(); !f.is_entry_frame(); f = f.sender(&map)) {
3068       f.print_on(&ls);
3069     }
3070   } else {
3071     map.set_skip_missing(true);
3072     ResetNoHandleMark rnhm;
3073     ResourceMark rm;
3074     HandleMark hm(Thread::current());
3075     FrameValues values;
3076 
3077     int i = 0;
3078     int post_entry = -1;
3079     for (frame f = thread->last_frame(); !f.is_first_frame(); f = f.sender(&map), i++) {
3080       f.describe(values, i, &map, i == 0);
3081       if (post_entry >= 0 || Continuation::is_continuation_enterSpecial(f))
3082         post_entry++;
3083       if (post_entry >= show_entry_callers)
3084         break;
3085     }
3086     values.print_on(thread, &ls);
3087   }
3088 
3089   ls.print_cr("======= end frames =========");
3090 }
3091 
3092 static void log_frames_after_thaw(JavaThread* thread, ContinuationWrapper& cont, intptr_t* sp) {
3093   intptr_t* sp0 = sp;
3094   address pc0 = *(address*)(sp - frame::sender_sp_ret_address_offset());
3095   bool use_cont_entry = false;
3096 
3097   // Preemption cases need to use and adjusted version of sp.
3098   if (pc0 == Interpreter::cont_resume_interpreter_adapter() ||
3099       pc0 == StubRoutines::cont_resume_compiler_adapter()) {
3100     // Resuming after being preempted case. We skip the adapter pushed
3101     // into the stack (see push_preempt_rerun_adapter()).
3102     sp0 += frame::metadata_words;
3103 
3104     if (pc0 == StubRoutines::cont_resume_compiler_adapter()) {
3105       address pc1 = *(address*)(sp0 - frame::sender_sp_ret_address_offset());
3106       if (pc1 == SharedRuntime::native_frame_resume_entry()) {
3107         // When top is the compiled native wrapper (Object.wait()) the pc
3108         // would have been modified from its original value to return to
3109         // the correct place. But that means we won't find the oopMap for
3110         // that fixed pc when getting the sender which will trigger asserts.
3111         // So just start walking the frames from the sender instead.
3112         CodeBlob* cb = CodeCache::find_blob(pc1);
3113         assert(cb->as_nmethod()->method()->is_object_wait0(), "");
3114         sp0 += cb->frame_size();
3115       }
3116 #ifdef AARCH64
3117       else {
3118         // Monitorenter case returning to c2 runtime stub requires extra
3119         // adjustment on aarch64 (see push_preempt_rerun_adapter()).
3120         address pc1 = *(address*)(sp0 - frame::sender_sp_ret_address_offset());
3121         CodeBlob* cb = CodeCache::find_blob(pc1);
3122         assert(cb != nullptr, "should be either c1 or c2 runtime stub");
3123         if (cb->frame_size() == 2) {
3124           sp0 += frame::metadata_words;
3125         }
3126       }
3127 #endif
3128     }
3129   } else if (pc0 == StubRoutines::cont_resume_monitor_operation()) {
3130     // Redoing monitor operation after being preempted case. We skip
3131     // the adapter + data pushed into the stack (see push_resume_monitor_operation()).
3132     use_cont_entry = true;
3133   }
3134 
3135   set_anchor(thread, use_cont_entry ? cont.entrySP() : sp0, use_cont_entry ? cont.entryPC() : nullptr);
3136   log_frames(thread);
3137   if (LoomVerifyAfterThaw) {
3138     assert(do_verify_after_thaw(thread, cont.tail(), tty), "");
3139   }
3140   assert(ContinuationEntry::assert_entry_frame_laid_out(thread), "");
3141   clear_anchor(thread);
3142 
3143   LogTarget(Trace, continuations) lt;
3144   if (lt.develop_is_enabled()) {
3145     LogStream ls(lt);
3146     ls.print_cr("Jumping to frame (thaw):");
3147     frame(sp).print_value_on(&ls, nullptr);
3148   }
3149 }
3150 #endif // ASSERT
3151 
3152 #include CPU_HEADER_INLINE(continuationFreezeThaw)
3153 
3154 #ifdef ASSERT
3155 static void print_frame_layout(const frame& f, bool callee_complete, outputStream* st) {
3156   ResourceMark rm;
3157   FrameValues values;
3158   assert(f.get_cb() != nullptr, "");
3159   RegisterMap map(f.is_heap_frame() ?
3160                     nullptr :
3161                     JavaThread::current(),
3162                   RegisterMap::UpdateMap::include,
3163                   RegisterMap::ProcessFrames::skip,
3164                   RegisterMap::WalkContinuation::skip);
3165   map.set_include_argument_oops(false);
3166   map.set_skip_missing(true);
3167   if (callee_complete) {
3168     frame::update_map_with_saved_link(&map, ContinuationHelper::Frame::callee_link_address(f));
3169   }
3170   const_cast<frame&>(f).describe(values, 0, &map, true);
3171   values.print_on(static_cast<JavaThread*>(nullptr), st);
3172 }
3173 #endif
3174 
3175 static address thaw_entry   = nullptr;
3176 static address freeze_entry = nullptr;
3177 static address freeze_preempt_entry = nullptr;
3178 
3179 address Continuation::thaw_entry() {
3180   return ::thaw_entry;
3181 }
3182 
3183 address Continuation::freeze_entry() {
3184   return ::freeze_entry;
3185 }
3186 
3187 address Continuation::freeze_preempt_entry() {
3188   return ::freeze_preempt_entry;
3189 }
3190 
3191 class ConfigResolve {
3192 public:
3193   static void resolve() { resolve_compressed(); }
3194 
3195   static void resolve_compressed() {
3196     UseCompressedOops ? resolve_gc<true>()
3197                       : resolve_gc<false>();
3198   }
3199 
3200 private:
3201   template <bool use_compressed>
3202   static void resolve_gc() {
3203     BarrierSet* bs = BarrierSet::barrier_set();
3204     assert(bs != nullptr, "freeze/thaw invoked before BarrierSet is set");
3205     switch (bs->kind()) {
3206 #define BARRIER_SET_RESOLVE_BARRIER_CLOSURE(bs_name)                    \
3207       case BarrierSet::bs_name: {                                       \
3208         resolve<use_compressed, typename BarrierSet::GetType<BarrierSet::bs_name>::type>(); \
3209       }                                                                 \
3210         break;
3211       FOR_EACH_CONCRETE_BARRIER_SET_DO(BARRIER_SET_RESOLVE_BARRIER_CLOSURE)
3212 #undef BARRIER_SET_RESOLVE_BARRIER_CLOSURE
3213 
3214     default:
3215       fatal("BarrierSet resolving not implemented");
3216     };
3217   }
3218 
3219   template <bool use_compressed, typename BarrierSetT>
3220   static void resolve() {
3221     typedef Config<use_compressed ? oop_kind::NARROW : oop_kind::WIDE, BarrierSetT> SelectedConfigT;
3222 
3223     freeze_entry = (address)freeze<SelectedConfigT>;
3224     freeze_preempt_entry = (address)SelectedConfigT::freeze_preempt;
3225 
3226     // If we wanted, we could templatize by kind and have three different thaw entries
3227     thaw_entry   = (address)thaw<SelectedConfigT>;
3228   }
3229 };
3230 
3231 void Continuation::init() {
3232   ConfigResolve::resolve();
3233 }