1 /*
   2  * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/classPrelinker.hpp"
  27 #include "ci/ciCallProfile.hpp"
  28 #include "ci/ciExceptionHandler.hpp"
  29 #include "ci/ciInstanceKlass.hpp"
  30 #include "ci/ciMethod.hpp"
  31 #include "ci/ciMethodBlocks.hpp"
  32 #include "ci/ciMethodData.hpp"
  33 #include "ci/ciStreams.hpp"
  34 #include "ci/ciSymbol.hpp"
  35 #include "ci/ciReplay.hpp"
  36 #include "ci/ciSymbols.hpp"
  37 #include "ci/ciUtilities.inline.hpp"
  38 #include "compiler/compileTask.hpp"
  39 #include "compiler/abstractCompiler.hpp"
  40 #include "compiler/compilerDefinitions.inline.hpp"
  41 #include "compiler/methodLiveness.hpp"
  42 #include "interpreter/interpreter.hpp"
  43 #include "interpreter/linkResolver.hpp"
  44 #include "interpreter/oopMapCache.hpp"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "oops/generateOopMap.hpp"
  50 #include "oops/method.inline.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "oops/trainingData.hpp"
  53 #include "prims/methodHandles.hpp"
  54 #include "runtime/deoptimization.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "utilities/bitMap.inline.hpp"
  57 #include "utilities/xmlstream.hpp"
  58 #ifdef COMPILER2
  59 #include "ci/bcEscapeAnalyzer.hpp"
  60 #include "ci/ciTypeFlow.hpp"
  61 #include "oops/method.hpp"
  62 #endif
  63 
  64 // ciMethod
  65 //
  66 // This class represents a Method* in the HotSpot virtual
  67 // machine.
  68 
  69 
  70 // ------------------------------------------------------------------
  71 // ciMethod::ciMethod
  72 //
  73 // Loaded method.
  74 ciMethod::ciMethod(const methodHandle& h_m, ciInstanceKlass* holder) :
  75   ciMetadata(h_m()),
  76   _holder(holder)
  77 {
  78   assert(h_m() != nullptr, "no null method");
  79   assert(_holder->get_instanceKlass() == h_m->method_holder(), "");
  80 
  81   // These fields are always filled in in loaded methods.
  82   _flags = ciFlags(h_m->access_flags());
  83 
  84   // Easy to compute, so fill them in now.
  85   _max_stack          = h_m->max_stack();
  86   _max_locals         = h_m->max_locals();
  87   _code_size          = h_m->code_size();
  88   _handler_count      = h_m->exception_table_length();
  89   _size_of_parameters = h_m->size_of_parameters();
  90   _uses_monitors      = h_m->has_monitor_bytecodes();
  91   _balanced_monitors  = !_uses_monitors || h_m->guaranteed_monitor_matching();
  92   _is_c1_compilable   = !h_m->is_not_c1_compilable();
  93   _is_c2_compilable   = !h_m->is_not_c2_compilable();
  94   _can_be_parsed      = true;
  95   _has_reserved_stack_access = h_m->has_reserved_stack_access();
  96   _is_overpass        = h_m->is_overpass();
  97   // Lazy fields, filled in on demand.  Require allocation.
  98   _code               = nullptr;
  99   _exception_handlers = nullptr;
 100   _liveness           = nullptr;
 101   _method_blocks = nullptr;
 102 #if defined(COMPILER2)
 103   _flow               = nullptr;
 104   _bcea               = nullptr;
 105 #endif // COMPILER2
 106 
 107   // Check for blackhole intrinsic and then populate the intrinsic ID.
 108   CompilerOracle::tag_blackhole_if_possible(h_m);
 109   _intrinsic_id       = h_m->intrinsic_id();
 110 
 111   ciEnv *env = CURRENT_ENV;
 112   if (env->jvmti_can_hotswap_or_post_breakpoint()) {
 113     // 6328518 check hotswap conditions under the right lock.
 114     MutexLocker locker(Compile_lock);
 115     if (Dependencies::check_evol_method(h_m()) != nullptr) {
 116       _is_c1_compilable = false;
 117       _is_c2_compilable = false;
 118       _can_be_parsed = false;
 119     }
 120   } else {
 121     DEBUG_ONLY(CompilerThread::current()->check_possible_safepoint());
 122   }
 123 
 124   if (h_m->method_holder()->is_linked()) {
 125     _can_be_statically_bound = h_m->can_be_statically_bound();
 126     _can_omit_stack_trace = h_m->can_omit_stack_trace();
 127   } else {
 128     // Have to use a conservative value in this case.
 129     _can_be_statically_bound = false;
 130     _can_omit_stack_trace = true;
 131   }
 132 
 133   // Adjust the definition of this condition to be more useful:
 134   // %%% take these conditions into account in vtable generation
 135   if (!_can_be_statically_bound && h_m->is_private())
 136     _can_be_statically_bound = true;
 137   if (_can_be_statically_bound && h_m->is_abstract())
 138     _can_be_statically_bound = false;
 139 
 140   // generating _signature may allow GC and therefore move m.
 141   // These fields are always filled in.
 142   _name = env->get_symbol(h_m->name());
 143   ciSymbol* sig_symbol = env->get_symbol(h_m->signature());
 144   constantPoolHandle cpool(Thread::current(), h_m->constants());
 145   _signature = new (env->arena()) ciSignature(_holder, cpool, sig_symbol);
 146   _method_data = nullptr;
 147   _method_data_recorded = nullptr;
 148   // Take a snapshot of these values, so they will be commensurate with the MDO.
 149   if (ProfileInterpreter || CompilerConfig::is_c1_profiling()) {
 150     int invcnt = h_m->interpreter_invocation_count();
 151     // if the value overflowed report it as max int
 152     _interpreter_invocation_count = invcnt < 0 ? max_jint : invcnt ;
 153     _interpreter_throwout_count   = h_m->interpreter_throwout_count();
 154   } else {
 155     _interpreter_invocation_count = 0;
 156     _interpreter_throwout_count = 0;
 157   }
 158   if (_interpreter_invocation_count == 0)
 159     _interpreter_invocation_count = 1;
 160   _inline_instructions_size = -1;
 161   if (ReplayCompiles) {
 162     ciReplay::initialize(this);
 163   }
 164   DirectiveSet* directives = DirectivesStack::getMatchingDirective(h_m, CURRENT_ENV->task()->compiler());
 165   ccstrlist bci_list = directives->TooManyTrapsAtBCIOption;
 166   int len = (int)strlen(bci_list);
 167   Arena* arena = CURRENT_ENV->arena();
 168   _has_trap_at_bci = new (arena) GrowableArray<int>(arena, 2, 0, 0);
 169   for (int i = 0; i < len; i++) {
 170     int v = -1;
 171     int read;
 172     if (sscanf(bci_list + i, "%i%n", &v, &read) != 1) {
 173       warning("wrong format for TooManyTrapsAtBCI option: \"%s\"", bci_list);
 174       break;
 175     }
 176     assert(v >= 0 && v < (1<<16), "%i", v);
 177     _has_trap_at_bci->append_if_missing(v);
 178     i += read;
 179   }
 180 }
 181 
 182 
 183 // ------------------------------------------------------------------
 184 // ciMethod::ciMethod
 185 //
 186 // Unloaded method.
 187 ciMethod::ciMethod(ciInstanceKlass* holder,
 188                    ciSymbol*        name,
 189                    ciSymbol*        signature,
 190                    ciInstanceKlass* accessor) :
 191   ciMetadata((Metadata*)nullptr),
 192   _name(                   name),
 193   _holder(                 holder),
 194   _method_data(            nullptr),
 195   _method_data_recorded(   nullptr),
 196   _method_blocks(          nullptr),
 197   _intrinsic_id(           vmIntrinsics::_none),
 198   _inline_instructions_size(-1),
 199   _can_be_statically_bound(false),
 200   _can_omit_stack_trace(true),
 201   _has_trap_at_bci(        nullptr),
 202   _liveness(               nullptr)
 203 #if defined(COMPILER2)
 204   ,
 205   _flow(                   nullptr),
 206   _bcea(                   nullptr)
 207 #endif // COMPILER2
 208 {
 209   // Usually holder and accessor are the same type but in some cases
 210   // the holder has the wrong class loader (e.g. invokedynamic call
 211   // sites) so we pass the accessor.
 212   _signature = new (CURRENT_ENV->arena()) ciSignature(accessor, constantPoolHandle(), signature);
 213 }
 214 
 215 
 216 // ------------------------------------------------------------------
 217 // ciMethod::load_code
 218 //
 219 // Load the bytecodes and exception handler table for this method.
 220 void ciMethod::load_code() {
 221   VM_ENTRY_MARK;
 222   assert(is_loaded(), "only loaded methods have code");
 223 
 224   Method* me = get_Method();
 225   Arena* arena = CURRENT_THREAD_ENV->arena();
 226 
 227   // Load the bytecodes.
 228   _code = (address)arena->Amalloc(code_size());
 229   memcpy(_code, me->code_base(), code_size());
 230 
 231 #if INCLUDE_JVMTI
 232   // Revert any breakpoint bytecodes in ci's copy
 233   if (me->number_of_breakpoints() > 0) {
 234     BreakpointInfo* bp = me->method_holder()->breakpoints();
 235     for (; bp != nullptr; bp = bp->next()) {
 236       if (bp->match(me)) {
 237         code_at_put(bp->bci(), bp->orig_bytecode());
 238       }
 239     }
 240   }
 241 #endif
 242 
 243   // And load the exception table.
 244   ExceptionTable exc_table(me);
 245 
 246   // Allocate one extra spot in our list of exceptions.  This
 247   // last entry will be used to represent the possibility that
 248   // an exception escapes the method.  See ciExceptionHandlerStream
 249   // for details.
 250   _exception_handlers =
 251     (ciExceptionHandler**)arena->Amalloc(sizeof(ciExceptionHandler*)
 252                                          * (_handler_count + 1));
 253   if (_handler_count > 0) {
 254     for (int i=0; i<_handler_count; i++) {
 255       _exception_handlers[i] = new (arena) ciExceptionHandler(
 256                                 holder(),
 257             /* start    */      exc_table.start_pc(i),
 258             /* limit    */      exc_table.end_pc(i),
 259             /* goto pc  */      exc_table.handler_pc(i),
 260             /* cp index */      exc_table.catch_type_index(i));
 261     }
 262   }
 263 
 264   // Put an entry at the end of our list to represent the possibility
 265   // of exceptional exit.
 266   _exception_handlers[_handler_count] =
 267     new (arena) ciExceptionHandler(holder(), 0, code_size(), -1, 0);
 268 
 269   if (CIPrintMethodCodes) {
 270     print_codes();
 271   }
 272 }
 273 
 274 
 275 // ------------------------------------------------------------------
 276 // ciMethod::has_linenumber_table
 277 //
 278 // length unknown until decompression
 279 bool    ciMethod::has_linenumber_table() const {
 280   check_is_loaded();
 281   VM_ENTRY_MARK;
 282   return get_Method()->has_linenumber_table();
 283 }
 284 
 285 
 286 // ------------------------------------------------------------------
 287 // ciMethod::line_number_from_bci
 288 int ciMethod::line_number_from_bci(int bci) const {
 289   check_is_loaded();
 290   VM_ENTRY_MARK;
 291   return get_Method()->line_number_from_bci(bci);
 292 }
 293 
 294 
 295 // ------------------------------------------------------------------
 296 // ciMethod::vtable_index
 297 //
 298 // Get the position of this method's entry in the vtable, if any.
 299 int ciMethod::vtable_index() {
 300   check_is_loaded();
 301   assert(holder()->is_linked(), "must be linked");
 302   VM_ENTRY_MARK;
 303   return get_Method()->vtable_index();
 304 }
 305 
 306 // ------------------------------------------------------------------
 307 // ciMethod::uses_balanced_monitors
 308 //
 309 // Does this method use monitors in a strict stack-disciplined manner?
 310 bool ciMethod::has_balanced_monitors() {
 311   check_is_loaded();
 312   if (_balanced_monitors) return true;
 313 
 314   // Analyze the method to see if monitors are used properly.
 315   VM_ENTRY_MARK;
 316   methodHandle method(THREAD, get_Method());
 317   assert(method->has_monitor_bytecodes(), "should have checked this");
 318 
 319   // Check to see if a previous compilation computed the
 320   // monitor-matching analysis.
 321   if (method->guaranteed_monitor_matching()) {
 322     _balanced_monitors = true;
 323     return true;
 324   }
 325 
 326   {
 327     ExceptionMark em(THREAD);
 328     ResourceMark rm(THREAD);
 329     GeneratePairingInfo gpi(method);
 330     if (!gpi.compute_map(THREAD)) {
 331       fatal("Unrecoverable verification or out-of-memory error");
 332     }
 333     if (!gpi.monitor_safe()) {
 334       return false;
 335     }
 336     method->set_guaranteed_monitor_matching();
 337     _balanced_monitors = true;
 338   }
 339   return true;
 340 }
 341 
 342 
 343 // ------------------------------------------------------------------
 344 // ciMethod::get_flow_analysis
 345 ciTypeFlow* ciMethod::get_flow_analysis() {
 346 #if defined(COMPILER2)
 347   if (_flow == nullptr) {
 348     ciEnv* env = CURRENT_ENV;
 349     _flow = new (env->arena()) ciTypeFlow(env, this);
 350     _flow->do_flow();
 351   }
 352   return _flow;
 353 #else // COMPILER2
 354   ShouldNotReachHere();
 355   return nullptr;
 356 #endif // COMPILER2
 357 }
 358 
 359 
 360 // ------------------------------------------------------------------
 361 // ciMethod::get_osr_flow_analysis
 362 ciTypeFlow* ciMethod::get_osr_flow_analysis(int osr_bci) {
 363 #if defined(COMPILER2)
 364   // OSR entry points are always place after a call bytecode of some sort
 365   assert(osr_bci >= 0, "must supply valid OSR entry point");
 366   ciEnv* env = CURRENT_ENV;
 367   ciTypeFlow* flow = new (env->arena()) ciTypeFlow(env, this, osr_bci);
 368   flow->do_flow();
 369   return flow;
 370 #else // COMPILER2
 371   ShouldNotReachHere();
 372   return nullptr;
 373 #endif // COMPILER2
 374 }
 375 
 376 // ------------------------------------------------------------------
 377 // ciMethod::raw_liveness_at_bci
 378 //
 379 // Which local variables are live at a specific bci?
 380 MethodLivenessResult ciMethod::raw_liveness_at_bci(int bci) {
 381   check_is_loaded();
 382   if (_liveness == nullptr) {
 383     // Create the liveness analyzer.
 384     Arena* arena = CURRENT_ENV->arena();
 385     _liveness = new (arena) MethodLiveness(arena, this);
 386     _liveness->compute_liveness();
 387   }
 388   return _liveness->get_liveness_at(bci);
 389 }
 390 
 391 // ------------------------------------------------------------------
 392 // ciMethod::liveness_at_bci
 393 //
 394 // Which local variables are live at a specific bci?  When debugging
 395 // will return true for all locals in some cases to improve debug
 396 // information.
 397 MethodLivenessResult ciMethod::liveness_at_bci(int bci) {
 398   if (CURRENT_ENV->should_retain_local_variables() || DeoptimizeALot) {
 399     // Keep all locals live for the user's edification and amusement.
 400     MethodLivenessResult result(_max_locals);
 401     result.set_range(0, _max_locals);
 402     result.set_is_valid();
 403     return result;
 404   }
 405   return raw_liveness_at_bci(bci);
 406 }
 407 
 408 // ciMethod::live_local_oops_at_bci
 409 //
 410 // find all the live oops in the locals array for a particular bci
 411 // Compute what the interpreter believes by using the interpreter
 412 // oopmap generator. This is used as a double check during osr to
 413 // guard against conservative result from MethodLiveness making us
 414 // think a dead oop is live.  MethodLiveness is conservative in the
 415 // sense that it may consider locals to be live which cannot be live,
 416 // like in the case where a local could contain an oop or  a primitive
 417 // along different paths.  In that case the local must be dead when
 418 // those paths merge. Since the interpreter's viewpoint is used when
 419 // gc'ing an interpreter frame we need to use its viewpoint  during
 420 // OSR when loading the locals.
 421 
 422 ResourceBitMap ciMethod::live_local_oops_at_bci(int bci) {
 423   VM_ENTRY_MARK;
 424   InterpreterOopMap mask;
 425   OopMapCache::compute_one_oop_map(methodHandle(THREAD, get_Method()), bci, &mask);
 426   int mask_size = max_locals();
 427   ResourceBitMap result(mask_size);
 428   int i;
 429   for (i = 0; i < mask_size ; i++ ) {
 430     if (mask.is_oop(i)) result.set_bit(i);
 431   }
 432   return result;
 433 }
 434 
 435 
 436 #ifdef COMPILER1
 437 // ------------------------------------------------------------------
 438 // ciMethod::bci_block_start
 439 //
 440 // Marks all bcis where a new basic block starts
 441 const BitMap& ciMethod::bci_block_start() {
 442   check_is_loaded();
 443   if (_liveness == nullptr) {
 444     // Create the liveness analyzer.
 445     Arena* arena = CURRENT_ENV->arena();
 446     _liveness = new (arena) MethodLiveness(arena, this);
 447     _liveness->compute_liveness();
 448   }
 449 
 450   return _liveness->get_bci_block_start();
 451 }
 452 #endif // COMPILER1
 453 
 454 
 455 // ------------------------------------------------------------------
 456 // ciMethod::check_overflow
 457 //
 458 // Check whether the profile counter is overflowed and adjust if true.
 459 // For invoke* it will turn negative values into max_jint,
 460 // and for checkcast/aastore/instanceof turn positive values into min_jint.
 461 int ciMethod::check_overflow(int c, Bytecodes::Code code) {
 462   switch (code) {
 463     case Bytecodes::_aastore:    // fall-through
 464     case Bytecodes::_checkcast:  // fall-through
 465     case Bytecodes::_instanceof: {
 466       if (VM_Version::profile_all_receivers_at_type_check()) {
 467         return (c < 0 ? max_jint : c); // always non-negative
 468       }
 469       return (c > 0 ? min_jint : c); // always non-positive
 470     }
 471     default: {
 472       assert(Bytecodes::is_invoke(code), "%s", Bytecodes::name(code));
 473       return (c < 0 ? max_jint : c); // always non-negative
 474     }
 475   }
 476 }
 477 
 478 
 479 // ------------------------------------------------------------------
 480 // ciMethod::call_profile_at_bci
 481 //
 482 // Get the ciCallProfile for the invocation of this method.
 483 // Also reports receiver types for non-call type checks (if TypeProfileCasts).
 484 ciCallProfile ciMethod::call_profile_at_bci(int bci) {
 485   ResourceMark rm;
 486   ciCallProfile result;
 487   if (method_data() != nullptr && method_data()->is_mature()) {
 488     ciProfileData* data = method_data()->bci_to_data(bci);
 489     if (data != nullptr && data->is_CounterData()) {
 490       // Every profiled call site has a counter.
 491       int count = check_overflow(data->as_CounterData()->count(), java_code_at_bci(bci));
 492 
 493       if (!data->is_ReceiverTypeData()) {
 494         result._receiver_count[0] = 0;  // that's a definite zero
 495       } else { // ReceiverTypeData is a subclass of CounterData
 496         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
 497         // In addition, virtual call sites have receiver type information
 498         int receivers_count_total = 0;
 499         int morphism = 0;
 500         // Precompute morphism for the possible fixup
 501         for (uint i = 0; i < call->row_limit(); i++) {
 502           ciKlass* receiver = call->receiver(i);
 503           if (receiver == nullptr)  continue;
 504           morphism++;
 505         }
 506         int epsilon = 0;
 507         // For a call, it is assumed that either the type of the receiver(s)
 508         // is recorded or an associated counter is incremented, but not both. With
 509         // tiered compilation, however, both can happen due to the interpreter and
 510         // C1 profiling invocations differently. Address that inconsistency here.
 511         if (morphism == 1 && count > 0) {
 512           epsilon = count;
 513           count = 0;
 514         }
 515         for (uint i = 0; i < call->row_limit(); i++) {
 516           ciKlass* receiver = call->receiver(i);
 517           if (receiver == nullptr)  continue;
 518           int rcount = saturated_add(call->receiver_count(i), epsilon);
 519           if (rcount == 0) rcount = 1; // Should be valid value
 520           receivers_count_total = saturated_add(receivers_count_total, rcount);
 521           // Add the receiver to result data.
 522           result.add_receiver(receiver, rcount);
 523           // If we extend profiling to record methods,
 524           // we will set result._method also.
 525         }
 526         // Determine call site's morphism.
 527         // The call site count is 0 with known morphism (only 1 or 2 receivers)
 528         // or < 0 in the case of a type check failure for checkcast, aastore, instanceof.
 529         // The call site count is > 0 in the case of a polymorphic virtual call.
 530         if (morphism > 0 && morphism == result._limit) {
 531            // The morphism <= MorphismLimit.
 532            if ((morphism <  ciCallProfile::MorphismLimit) ||
 533                (morphism == ciCallProfile::MorphismLimit && count == 0)) {
 534 #ifdef ASSERT
 535              if (count > 0) {
 536                this->print_short_name(tty);
 537                tty->print_cr(" @ bci:%d", bci);
 538                this->print_codes();
 539                assert(false, "this call site should not be polymorphic");
 540              }
 541 #endif
 542              result._morphism = morphism;
 543            }
 544         }
 545         // Make the count consistent if this is a call profile. If count is
 546         // zero or less, presume that this is a typecheck profile and
 547         // do nothing.  Otherwise, increase count to be the sum of all
 548         // receiver's counts.
 549         if (count >= 0) {
 550           count = saturated_add(count, receivers_count_total);
 551         }
 552       }
 553       result._count = count;
 554     }
 555   }
 556   return result;
 557 }
 558 
 559 // ------------------------------------------------------------------
 560 // Add new receiver and sort data by receiver's profile count.
 561 void ciCallProfile::add_receiver(ciKlass* receiver, int receiver_count) {
 562   // Add new receiver and sort data by receiver's counts when we have space
 563   // for it otherwise replace the less called receiver (less called receiver
 564   // is placed to the last array element which is not used).
 565   // First array's element contains most called receiver.
 566   int i = _limit;
 567   for (; i > 0 && receiver_count > _receiver_count[i-1]; i--) {
 568     _receiver[i] = _receiver[i-1];
 569     _receiver_count[i] = _receiver_count[i-1];
 570   }
 571   _receiver[i] = receiver;
 572   _receiver_count[i] = receiver_count;
 573   if (_limit < MorphismLimit) _limit++;
 574 }
 575 
 576 
 577 void ciMethod::assert_virtual_call_type_ok(int bci) {
 578   assert(java_code_at_bci(bci) == Bytecodes::_invokevirtual ||
 579          java_code_at_bci(bci) == Bytecodes::_invokeinterface, "unexpected bytecode %s", Bytecodes::name(java_code_at_bci(bci)));
 580 }
 581 
 582 void ciMethod::assert_call_type_ok(int bci) {
 583   assert(java_code_at_bci(bci) == Bytecodes::_invokestatic ||
 584          java_code_at_bci(bci) == Bytecodes::_invokespecial ||
 585          java_code_at_bci(bci) == Bytecodes::_invokedynamic, "unexpected bytecode %s", Bytecodes::name(java_code_at_bci(bci)));
 586 }
 587 
 588 /**
 589  * Check whether profiling provides a type for the argument i to the
 590  * call at bci bci
 591  *
 592  * @param [in]bci         bci of the call
 593  * @param [in]i           argument number
 594  * @param [out]type       profiled type of argument, null if none
 595  * @param [out]ptr_kind   whether always null, never null or maybe null
 596  * @return                true if profiling exists
 597  *
 598  */
 599 bool ciMethod::argument_profiled_type(int bci, int i, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 600   if (MethodData::profile_parameters() && method_data() != nullptr && method_data()->is_mature()) {
 601     ciProfileData* data = method_data()->bci_to_data(bci);
 602     if (data != nullptr) {
 603       if (data->is_VirtualCallTypeData()) {
 604         assert_virtual_call_type_ok(bci);
 605         ciVirtualCallTypeData* call = (ciVirtualCallTypeData*)data->as_VirtualCallTypeData();
 606         if (i >= call->number_of_arguments()) {
 607           return false;
 608         }
 609         type = call->valid_argument_type(i);
 610         ptr_kind = call->argument_ptr_kind(i);
 611         return true;
 612       } else if (data->is_CallTypeData()) {
 613         assert_call_type_ok(bci);
 614         ciCallTypeData* call = (ciCallTypeData*)data->as_CallTypeData();
 615         if (i >= call->number_of_arguments()) {
 616           return false;
 617         }
 618         type = call->valid_argument_type(i);
 619         ptr_kind = call->argument_ptr_kind(i);
 620         return true;
 621       }
 622     }
 623   }
 624   return false;
 625 }
 626 
 627 /**
 628  * Check whether profiling provides a type for the return value from
 629  * the call at bci bci
 630  *
 631  * @param [in]bci         bci of the call
 632  * @param [out]type       profiled type of argument, null if none
 633  * @param [out]ptr_kind   whether always null, never null or maybe null
 634  * @return                true if profiling exists
 635  *
 636  */
 637 bool ciMethod::return_profiled_type(int bci, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 638   if (MethodData::profile_return() && method_data() != nullptr && method_data()->is_mature()) {
 639     ciProfileData* data = method_data()->bci_to_data(bci);
 640     if (data != nullptr) {
 641       if (data->is_VirtualCallTypeData()) {
 642         assert_virtual_call_type_ok(bci);
 643         ciVirtualCallTypeData* call = (ciVirtualCallTypeData*)data->as_VirtualCallTypeData();
 644         if (call->has_return()) {
 645           type = call->valid_return_type();
 646           ptr_kind = call->return_ptr_kind();
 647           return true;
 648         }
 649       } else if (data->is_CallTypeData()) {
 650         assert_call_type_ok(bci);
 651         ciCallTypeData* call = (ciCallTypeData*)data->as_CallTypeData();
 652         if (call->has_return()) {
 653           type = call->valid_return_type();
 654           ptr_kind = call->return_ptr_kind();
 655         }
 656         return true;
 657       }
 658     }
 659   }
 660   return false;
 661 }
 662 
 663 /**
 664  * Check whether profiling provides a type for the parameter i
 665  *
 666  * @param [in]i           parameter number
 667  * @param [out]type       profiled type of parameter, null if none
 668  * @param [out]ptr_kind   whether always null, never null or maybe null
 669  * @return                true if profiling exists
 670  *
 671  */
 672 bool ciMethod::parameter_profiled_type(int i, ciKlass*& type, ProfilePtrKind& ptr_kind) {
 673   if (MethodData::profile_parameters() && method_data() != nullptr && method_data()->is_mature()) {
 674     ciParametersTypeData* parameters = method_data()->parameters_type_data();
 675     if (parameters != nullptr && i < parameters->number_of_parameters()) {
 676       type = parameters->valid_parameter_type(i);
 677       ptr_kind = parameters->parameter_ptr_kind(i);
 678       return true;
 679     }
 680   }
 681   return false;
 682 }
 683 
 684 
 685 // ------------------------------------------------------------------
 686 // ciMethod::find_monomorphic_target
 687 //
 688 // Given a certain calling environment, find the monomorphic target
 689 // for the call.  Return null if the call is not monomorphic in
 690 // its calling environment, or if there are only abstract methods.
 691 // The returned method is never abstract.
 692 // Note: If caller uses a non-null result, it must inform dependencies
 693 // via assert_unique_concrete_method or assert_leaf_type.
 694 ciMethod* ciMethod::find_monomorphic_target(ciInstanceKlass* caller,
 695                                             ciInstanceKlass* callee_holder,
 696                                             ciInstanceKlass* actual_recv,
 697                                             bool check_access) {
 698   check_is_loaded();
 699 
 700   if (actual_recv->is_interface()) {
 701     // %%% We cannot trust interface types, yet.  See bug 6312651.
 702     return nullptr;
 703   }
 704 
 705   ciMethod* root_m = resolve_invoke(caller, actual_recv, check_access, true /* allow_abstract */);
 706   if (root_m == nullptr) {
 707     // Something went wrong looking up the actual receiver method.
 708     return nullptr;
 709   }
 710 
 711   // Make certain quick checks even if UseCHA is false.
 712 
 713   // Is it private or final?
 714   if (root_m->can_be_statically_bound()) {
 715     assert(!root_m->is_abstract(), "sanity");
 716     return root_m;
 717   }
 718 
 719   if (actual_recv->is_leaf_type() && actual_recv == root_m->holder()) {
 720     // Easy case.  There is no other place to put a method, so don't bother
 721     // to go through the VM_ENTRY_MARK and all the rest.
 722     if (root_m->is_abstract()) {
 723       return nullptr;
 724     }
 725     return root_m;
 726   }
 727 
 728   // Array methods (clone, hashCode, etc.) are always statically bound.
 729   // If we were to see an array type here, we'd return root_m.
 730   // However, this method processes only ciInstanceKlasses.  (See 4962591.)
 731   // The inline_native_clone intrinsic narrows Object to T[] properly,
 732   // so there is no need to do the same job here.
 733 
 734   if (!UseCHA)  return nullptr;
 735 
 736   VM_ENTRY_MARK;
 737 
 738   methodHandle target;
 739   {
 740     MutexLocker locker(Compile_lock);
 741     InstanceKlass* context = actual_recv->get_instanceKlass();
 742     if (UseVtableBasedCHA) {
 743       target = methodHandle(THREAD, Dependencies::find_unique_concrete_method(context,
 744                                                                               root_m->get_Method(),
 745                                                                               callee_holder->get_Klass(),
 746                                                                               this->get_Method()));
 747     } else {
 748       if (root_m->is_abstract()) {
 749         return nullptr; // not supported
 750       }
 751       target = methodHandle(THREAD, Dependencies::find_unique_concrete_method(context, root_m->get_Method()));
 752     }
 753     assert(target() == nullptr || !target()->is_abstract(), "not allowed");
 754     // %%% Should upgrade this ciMethod API to look for 1 or 2 concrete methods.
 755   }
 756 
 757 #ifndef PRODUCT
 758   LogTarget(Debug, dependencies) lt;
 759   if (lt.is_enabled() && target() != nullptr && target() != root_m->get_Method()) {
 760     LogStream ls(&lt);
 761     ls.print("found a non-root unique target method");
 762     ls.print_cr("  context = %s", actual_recv->get_Klass()->external_name());
 763     ls.print("  method  = ");
 764     target->print_short_name(&ls);
 765     ls.cr();
 766   }
 767 #endif //PRODUCT
 768 
 769   if (target() == nullptr) {
 770     return nullptr;
 771   }
 772   if (target() == root_m->get_Method()) {
 773     return root_m;
 774   }
 775   if (!root_m->is_public() &&
 776       !root_m->is_protected()) {
 777     // If we are going to reason about inheritance, it's easiest
 778     // if the method in question is public, protected, or private.
 779     // If the answer is not root_m, it is conservatively correct
 780     // to return null, even if the CHA encountered irrelevant
 781     // methods in other packages.
 782     // %%% TO DO: Work out logic for package-private methods
 783     // with the same name but different vtable indexes.
 784     return nullptr;
 785   }
 786   return CURRENT_THREAD_ENV->get_method(target());
 787 }
 788 
 789 // ------------------------------------------------------------------
 790 // ciMethod::can_be_statically_bound
 791 //
 792 // Tries to determine whether a method can be statically bound in some context.
 793 bool ciMethod::can_be_statically_bound(ciInstanceKlass* context) const {
 794   return (holder() == context) && can_be_statically_bound();
 795 }
 796 
 797 // ------------------------------------------------------------------
 798 // ciMethod::can_omit_stack_trace
 799 //
 800 // Tries to determine whether a method can omit stack trace in throw in compiled code.
 801 bool ciMethod::can_omit_stack_trace() const {
 802   if (!StackTraceInThrowable) {
 803     return true; // stack trace is switched off.
 804   }
 805   if (!OmitStackTraceInFastThrow) {
 806     return false; // Have to provide stack trace.
 807   }
 808   return _can_omit_stack_trace;
 809 }
 810 
 811 // ------------------------------------------------------------------
 812 // ciMethod::resolve_invoke
 813 //
 814 // Given a known receiver klass, find the target for the call.
 815 // Return null if the call has no target or the target is abstract.
 816 ciMethod* ciMethod::resolve_invoke(ciKlass* caller, ciKlass* exact_receiver, bool check_access, bool allow_abstract) {
 817   check_is_loaded();
 818   VM_ENTRY_MARK;
 819 
 820   Klass* caller_klass = caller->get_Klass();
 821   Klass* recv         = exact_receiver->get_Klass();
 822   Klass* resolved     = holder()->get_Klass();
 823   Symbol* h_name      = name()->get_symbol();
 824   Symbol* h_signature = signature()->get_symbol();
 825 
 826   LinkInfo link_info(resolved, h_name, h_signature, caller_klass,
 827                      check_access ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
 828                      check_access ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
 829   Method* m = nullptr;
 830   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 831   // the vtable has not been setup, and the LinkResolver will fail.
 832   if (recv->is_array_klass()
 833        ||
 834       (InstanceKlass::cast(recv)->is_linked() && !exact_receiver->is_interface())) {
 835     if (holder()->is_interface()) {
 836       m = LinkResolver::resolve_interface_call_or_null(recv, link_info);
 837     } else {
 838       m = LinkResolver::resolve_virtual_call_or_null(recv, link_info);
 839     }
 840   }
 841 
 842   if (m == nullptr) {
 843     // Return null only if there was a problem with lookup (uninitialized class, etc.)
 844     return nullptr;
 845   }
 846 
 847   ciMethod* result = this;
 848   if (m != get_Method()) {
 849     result = CURRENT_THREAD_ENV->get_method(m);
 850   }
 851 
 852   if (result->is_abstract() && !allow_abstract) {
 853     // Don't return abstract methods because they aren't optimizable or interesting.
 854     return nullptr;
 855   }
 856   return result;
 857 }
 858 
 859 // ------------------------------------------------------------------
 860 // ciMethod::resolve_vtable_index
 861 //
 862 // Given a known receiver klass, find the vtable index for the call.
 863 // Return Method::invalid_vtable_index if the vtable_index is unknown.
 864 int ciMethod::resolve_vtable_index(ciKlass* caller, ciKlass* receiver) {
 865    check_is_loaded();
 866 
 867    int vtable_index = Method::invalid_vtable_index;
 868    // Only do lookup if receiver klass has been linked.  Otherwise,
 869    // the vtable has not been setup, and the LinkResolver will fail.
 870    if (!receiver->is_interface()
 871        && (!receiver->is_instance_klass() ||
 872            receiver->as_instance_klass()->is_linked())) {
 873      VM_ENTRY_MARK;
 874 
 875      Klass* caller_klass = caller->get_Klass();
 876      Klass* recv         = receiver->get_Klass();
 877      Symbol* h_name = name()->get_symbol();
 878      Symbol* h_signature = signature()->get_symbol();
 879 
 880      LinkInfo link_info(recv, h_name, h_signature, caller_klass);
 881      vtable_index = LinkResolver::resolve_virtual_vtable_index(recv, link_info);
 882      if (vtable_index == Method::nonvirtual_vtable_index) {
 883        // A statically bound method.  Return "no such index".
 884        vtable_index = Method::invalid_vtable_index;
 885      }
 886    }
 887 
 888    return vtable_index;
 889 }
 890 
 891 // ------------------------------------------------------------------
 892 // ciMethod::get_field_at_bci
 893 ciField* ciMethod::get_field_at_bci(int bci, bool &will_link) {
 894   ciBytecodeStream iter(this);
 895   iter.reset_to_bci(bci);
 896   iter.next();
 897   return iter.get_field(will_link);
 898 }
 899 
 900 // ------------------------------------------------------------------
 901 // ciMethod::get_method_at_bci
 902 ciMethod* ciMethod::get_method_at_bci(int bci, bool &will_link, ciSignature* *declared_signature) {
 903   ciBytecodeStream iter(this);
 904   iter.reset_to_bci(bci);
 905   iter.next();
 906   return iter.get_method(will_link, declared_signature);
 907 }
 908 
 909 // ------------------------------------------------------------------
 910 ciKlass* ciMethod::get_declared_method_holder_at_bci(int bci) {
 911   ciBytecodeStream iter(this);
 912   iter.reset_to_bci(bci);
 913   iter.next();
 914   return iter.get_declared_method_holder();
 915 }
 916 
 917 // ------------------------------------------------------------------
 918 // Adjust a CounterData count to be commensurate with
 919 // interpreter_invocation_count.  If the MDO exists for
 920 // only 25% of the time the method exists, then the
 921 // counts in the MDO should be scaled by 4X, so that
 922 // they can be usefully and stably compared against the
 923 // invocation counts in methods.
 924 int ciMethod::scale_count(int count, float prof_factor) {
 925   if (count > 0 && method_data() != nullptr) {
 926     int counter_life = method_data()->invocation_count();
 927     int method_life = interpreter_invocation_count();
 928     if (method_life < counter_life) { // may happen because of the snapshot timing
 929       method_life = counter_life;
 930     }
 931     if (counter_life > 0) {
 932       count = (int)((double)count * prof_factor * method_life / counter_life + 0.5);
 933       count = (count > 0) ? count : 1;
 934     } else {
 935       count = 1;
 936     }
 937   }
 938   return count;
 939 }
 940 
 941 
 942 // ------------------------------------------------------------------
 943 // ciMethod::is_special_get_caller_class_method
 944 //
 945 bool ciMethod::is_ignored_by_security_stack_walk() const {
 946   check_is_loaded();
 947   VM_ENTRY_MARK;
 948   return get_Method()->is_ignored_by_security_stack_walk();
 949 }
 950 
 951 // ------------------------------------------------------------------
 952 // ciMethod::needs_clinit_barrier
 953 //
 954 bool ciMethod::needs_clinit_barrier() const {
 955   check_is_loaded();
 956   return is_static() && !holder()->is_initialized();
 957 }
 958 
 959 // ------------------------------------------------------------------
 960 // invokedynamic support
 961 
 962 // ------------------------------------------------------------------
 963 // ciMethod::is_method_handle_intrinsic
 964 //
 965 // Return true if the method is an instance of the JVM-generated
 966 // signature-polymorphic MethodHandle methods, _invokeBasic, _linkToVirtual, etc.
 967 bool ciMethod::is_method_handle_intrinsic() const {
 968   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 969   return (MethodHandles::is_signature_polymorphic(iid) &&
 970           MethodHandles::is_signature_polymorphic_intrinsic(iid));
 971 }
 972 
 973 // ------------------------------------------------------------------
 974 // ciMethod::is_compiled_lambda_form
 975 //
 976 // Return true if the method is a generated MethodHandle adapter.
 977 // These are built by Java code.
 978 bool ciMethod::is_compiled_lambda_form() const {
 979   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 980   return iid == vmIntrinsics::_compiledLambdaForm;
 981 }
 982 
 983 // ------------------------------------------------------------------
 984 // ciMethod::is_object_initializer
 985 //
 986 bool ciMethod::is_object_initializer() const {
 987    return name() == ciSymbols::object_initializer_name();
 988 }
 989 
 990 // ------------------------------------------------------------------
 991 // ciMethod::has_member_arg
 992 //
 993 // Return true if the method is a linker intrinsic like _linkToVirtual.
 994 // These are built by the JVM.
 995 bool ciMethod::has_member_arg() const {
 996   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 997   return (MethodHandles::is_signature_polymorphic(iid) &&
 998           MethodHandles::has_member_arg(iid));
 999 }
1000 
1001 // ------------------------------------------------------------------
1002 // ciMethod::ensure_method_data
1003 //
1004 // Generate new MethodData* objects at compile time.
1005 // Return true if allocation was successful or no MDO is required.
1006 bool ciMethod::ensure_method_data(const methodHandle& h_m, bool training_data_only) {
1007   EXCEPTION_CONTEXT;
1008   if (is_native() || is_abstract() || h_m()->is_accessor()) {
1009     return true;
1010   }
1011   if (h_m()->method_data() == nullptr) {
1012     if (training_data_only) {
1013       Method::install_training_method_data(h_m);
1014     } else {
1015       Method::build_profiling_method_data(h_m, THREAD);
1016       if (HAS_PENDING_EXCEPTION) {
1017         CLEAR_PENDING_EXCEPTION;
1018       }
1019     }
1020   }
1021   if (h_m()->method_data() != nullptr) {
1022     _method_data = CURRENT_ENV->get_method_data(h_m()->method_data());
1023     return _method_data->load_data();
1024   } else {
1025     _method_data = CURRENT_ENV->get_empty_methodData();
1026     return false;
1027   }
1028 }
1029 
1030 // public, retroactive version
1031 bool ciMethod::ensure_method_data(bool training_data_only) {
1032   bool result = true;
1033   if (_method_data == nullptr || _method_data->is_empty()) {
1034     GUARDED_VM_ENTRY({
1035       methodHandle mh(Thread::current(), get_Method());
1036       result = ensure_method_data(mh, training_data_only);
1037     });
1038   }
1039   return result;
1040 }
1041 
1042 
1043 // ------------------------------------------------------------------
1044 // ciMethod::method_data
1045 //
1046 ciMethodData* ciMethod::method_data() {
1047   if (CURRENT_ENV->task()->is_precompiled() && CURRENT_ENV->task()->comp_level() == CompLevel_full_optimization) {
1048     if (_method_data_recorded == nullptr) {
1049       VM_ENTRY_MARK;
1050       methodHandle h_m(thread, get_Method());
1051       MethodTrainingData* mtd = TrainingData::lookup_for(h_m());
1052       MethodData* mdo = (mtd != nullptr ? mtd->final_profile() : nullptr);
1053       DirectiveSet* directives = DirectivesStack::getMatchingDirective(h_m, CURRENT_ENV->task()->compiler());
1054       if (mdo == nullptr || directives->IgnoreRecordedProfileOption) {
1055         if (directives->IgnoreRecordedProfileOption) {
1056           ResourceMark rm;
1057           log_debug(precompile)("Ignore recorded profile for %s", h_m->name_and_sig_as_C_string());
1058         } else {
1059           ResourceMark rm;
1060           log_debug(precompile)("No profile for %s", h_m->name_and_sig_as_C_string());
1061         }
1062         _method_data_recorded = CURRENT_ENV->get_empty_methodData();
1063       } else {
1064         if (mdo->extra_data_lock() == nullptr) {
1065           assert(!HAS_PENDING_EXCEPTION, "");
1066           mdo->restore_unshareable_info(thread);
1067           assert(!HAS_PENDING_EXCEPTION, "");
1068         }
1069         _method_data_recorded = CURRENT_ENV->get_method_data(mdo);
1070         _method_data_recorded->load_data();
1071         {
1072           ResourceMark rm;
1073           log_debug(precompile)("Recorded profile " PTR_FORMAT " for %s", p2i(mdo), h_m->name_and_sig_as_C_string());
1074         }
1075       }
1076     }
1077     assert(_method_data_recorded != nullptr, "");
1078     return _method_data_recorded;
1079   } else {
1080     if (_method_data != nullptr) {
1081       return _method_data;
1082     }
1083     VM_ENTRY_MARK;
1084     methodHandle h_m(thread, get_Method());
1085     MethodData* mdo = h_m()->method_data();
1086     if (mdo != nullptr) {
1087       _method_data = CURRENT_ENV->get_method_data(mdo);
1088       _method_data->load_data();
1089     } else {
1090       _method_data = CURRENT_ENV->get_empty_methodData();
1091     }
1092     return _method_data;
1093   }
1094 }
1095 
1096 // ------------------------------------------------------------------
1097 // ciMethod::method_data_or_null
1098 // Returns a pointer to ciMethodData if MDO exists on the VM side,
1099 // null otherwise.
1100 ciMethodData* ciMethod::method_data_or_null() {
1101   ciMethodData *md = method_data();
1102   if (md->is_empty()) {
1103     return nullptr;
1104   }
1105   return md;
1106 }
1107 
1108 // ------------------------------------------------------------------
1109 // ciMethod::ensure_method_counters
1110 //
1111 MethodCounters* ciMethod::ensure_method_counters() {
1112   check_is_loaded();
1113   VM_ENTRY_MARK;
1114   methodHandle mh(THREAD, get_Method());
1115   MethodCounters* method_counters = mh->get_method_counters(CHECK_NULL);
1116   return method_counters;
1117 }
1118 
1119 // ------------------------------------------------------------------
1120 // ciMethod::has_option
1121 //
1122 bool ciMethod::has_option(enum CompileCommand option) {
1123   check_is_loaded();
1124   VM_ENTRY_MARK;
1125   methodHandle mh(THREAD, get_Method());
1126   return CompilerOracle::has_option(mh, option);
1127 }
1128 
1129 // ------------------------------------------------------------------
1130 // ciMethod::has_option_value
1131 //
1132 bool ciMethod::has_option_value(enum CompileCommand option, double& value) {
1133   check_is_loaded();
1134   VM_ENTRY_MARK;
1135   methodHandle mh(THREAD, get_Method());
1136   return CompilerOracle::has_option_value(mh, option, value);
1137 }
1138 // ------------------------------------------------------------------
1139 // ciMethod::can_be_compiled
1140 //
1141 // Have previous compilations of this method succeeded?
1142 bool ciMethod::can_be_compiled() {
1143   check_is_loaded();
1144   ciEnv* env = CURRENT_ENV;
1145   if (is_c1_compile(env->comp_level())) {
1146     return _is_c1_compilable;
1147   }
1148 
1149 #if INCLUDE_JVMCI
1150   if (EnableJVMCI && UseJVMCICompiler &&
1151       env->comp_level() == CompLevel_full_optimization && !ClassPrelinker::class_preloading_finished()) {
1152     return false;
1153   }
1154 #endif
1155   return _is_c2_compilable;
1156 }
1157 
1158 // ------------------------------------------------------------------
1159 // ciMethod::has_compiled_code
1160 bool ciMethod::has_compiled_code() {
1161   return inline_instructions_size() > 0;
1162 }
1163 
1164 int ciMethod::highest_osr_comp_level() {
1165   check_is_loaded();
1166   VM_ENTRY_MARK;
1167   return get_Method()->highest_osr_comp_level();
1168 }
1169 
1170 // ------------------------------------------------------------------
1171 // ciMethod::code_size_for_inlining
1172 //
1173 // Code size for inlining decisions.  This method returns a code
1174 // size of 1 for methods which has the ForceInline annotation.
1175 int ciMethod::code_size_for_inlining() {
1176   check_is_loaded();
1177   if (get_Method()->force_inline()) {
1178     return 1;
1179   }
1180   return code_size();
1181 }
1182 
1183 // ------------------------------------------------------------------
1184 // ciMethod::inline_instructions_size
1185 //
1186 // This is a rough metric for "fat" methods, compared before inlining
1187 // with InlineSmallCode.  The CodeBlob::code_size accessor includes
1188 // junk like exception handler, stubs, and constant table, which are
1189 // not highly relevant to an inlined method.  So we use the more
1190 // specific accessor nmethod::insts_size.
1191 // Also some instructions inside the code are excluded from inline
1192 // heuristic (e.g. post call nop instructions; see InlineSkippedInstructionsCounter)
1193 int ciMethod::inline_instructions_size() {
1194   if (_inline_instructions_size == -1) {
1195     if (TrainingData::have_data()) {
1196       GUARDED_VM_ENTRY(
1197         CompLevel level = static_cast<CompLevel>(CURRENT_ENV->comp_level());
1198         methodHandle top_level_mh(Thread::current(), CURRENT_ENV->task()->method());
1199         MethodTrainingData* mtd = MethodTrainingData::find(top_level_mh);
1200         if (mtd != nullptr) {
1201           CompileTrainingData* ctd = mtd->last_toplevel_compile(level);
1202           if (ctd != nullptr) {
1203             methodHandle mh(Thread::current(), get_Method());
1204             MethodTrainingData* this_mtd = MethodTrainingData::find(mh);
1205             if (this_mtd != nullptr) {
1206               auto r = ctd->ci_records().ciMethod__inline_instructions_size.find(this_mtd);
1207               if (r.is_valid()) {
1208                 _inline_instructions_size = r.result();
1209               }
1210             }
1211           }
1212         }
1213       );
1214     }
1215   }
1216   if (_inline_instructions_size == -1) {
1217     GUARDED_VM_ENTRY(
1218       CompiledMethod* code = get_Method()->code();
1219       if (code != nullptr && !code->is_scc() && code->comp_level() == CompLevel_full_optimization) {
1220         int isize = code->insts_end() - code->verified_entry_point() - code->skipped_instructions_size();
1221         _inline_instructions_size = isize > 0 ? isize : 0;
1222       } else {
1223         _inline_instructions_size = 0;
1224       }
1225       if (TrainingData::need_data()) {
1226         CompileTrainingData* ctd = CURRENT_ENV->task()->training_data();
1227         if (ctd != nullptr) {
1228           methodHandle mh(Thread::current(), get_Method());
1229           MethodTrainingData* this_mtd = MethodTrainingData::make(mh);
1230           ctd->ci_records().ciMethod__inline_instructions_size.append_if_missing(_inline_instructions_size, this_mtd);
1231         }
1232       }
1233     );
1234   }
1235   return _inline_instructions_size;
1236 }
1237 
1238 // ------------------------------------------------------------------
1239 // ciMethod::log_nmethod_identity
1240 void ciMethod::log_nmethod_identity(xmlStream* log) {
1241   GUARDED_VM_ENTRY(
1242     CompiledMethod* code = get_Method()->code();
1243     if (code != nullptr) {
1244       code->log_identity(log);
1245     }
1246   )
1247 }
1248 
1249 // ------------------------------------------------------------------
1250 // ciMethod::is_not_reached
1251 bool ciMethod::is_not_reached(int bci) {
1252   check_is_loaded();
1253   VM_ENTRY_MARK;
1254   return Interpreter::is_not_reached(
1255                methodHandle(THREAD, get_Method()), bci);
1256 }
1257 
1258 // ------------------------------------------------------------------
1259 // ciMethod::was_never_executed
1260 bool ciMethod::was_executed_more_than(int times) {
1261   // Invocation counter is reset when the Method* is compiled.
1262   // If the method has compiled code we therefore assume it has
1263   // be executed more than n times.
1264   if (is_accessor() || is_empty() || has_compiled_code()) {
1265     // interpreter doesn't bump invocation counter of trivial methods
1266     // compiler does not bump invocation counter of compiled methods
1267     return true;
1268   }
1269   if (!method_data()->is_empty()) {
1270     return (method_data()->invocation_count() > times);
1271   }
1272   VM_ENTRY_MARK;
1273   return get_Method()->was_executed_more_than(times);
1274 }
1275 
1276 // ------------------------------------------------------------------
1277 // ciMethod::has_unloaded_classes_in_signature
1278 bool ciMethod::has_unloaded_classes_in_signature() {
1279   // ciSignature is resolved against some accessing class and
1280   // signature classes aren't required to be local. As a benefit,
1281   // it makes signature classes visible through loader constraints.
1282   // So, encountering an unloaded class signals it is absent both in
1283   // the callee (local) and caller contexts.
1284   return signature()->has_unloaded_classes();
1285 }
1286 
1287 // ------------------------------------------------------------------
1288 // ciMethod::is_klass_loaded
1289 bool ciMethod::is_klass_loaded(int refinfo_index, Bytecodes::Code bc, bool must_be_resolved) const {
1290   VM_ENTRY_MARK;
1291   return get_Method()->is_klass_loaded(refinfo_index, bc, must_be_resolved);
1292 }
1293 
1294 // ------------------------------------------------------------------
1295 // ciMethod::check_call
1296 bool ciMethod::check_call(int refinfo_index, bool is_static) const {
1297   // This method is used only in C2 from InlineTree::ok_to_inline,
1298   // and is only used under -Xcomp.
1299   // It appears to fail when applied to an invokeinterface call site.
1300   // FIXME: Remove this method and resolve_method_statically; refactor to use the other LinkResolver entry points.
1301   VM_ENTRY_MARK;
1302   {
1303     ExceptionMark em(THREAD);
1304     HandleMark hm(THREAD);
1305     constantPoolHandle pool (THREAD, get_Method()->constants());
1306     Bytecodes::Code code = (is_static ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual);
1307     Method* spec_method = LinkResolver::resolve_method_statically(code, pool, refinfo_index, THREAD);
1308     if (HAS_PENDING_EXCEPTION) {
1309       CLEAR_PENDING_EXCEPTION;
1310       return false;
1311     } else {
1312       return (spec_method->is_static() == is_static);
1313     }
1314   }
1315   return false;
1316 }
1317 // ------------------------------------------------------------------
1318 // ciMethod::print_codes
1319 //
1320 // Print the bytecodes for this method.
1321 void ciMethod::print_codes_on(outputStream* st) {
1322   check_is_loaded();
1323   GUARDED_VM_ENTRY(get_Method()->print_codes_on(st);)
1324 }
1325 
1326 
1327 #define FETCH_FLAG_FROM_VM(flag_accessor) { \
1328   check_is_loaded(); \
1329   VM_ENTRY_MARK; \
1330   return get_Method()->flag_accessor(); \
1331 }
1332 
1333 bool ciMethod::has_loops      () const {         FETCH_FLAG_FROM_VM(has_loops); }
1334 bool ciMethod::has_jsrs       () const {         FETCH_FLAG_FROM_VM(has_jsrs);  }
1335 bool ciMethod::is_getter      () const {         FETCH_FLAG_FROM_VM(is_getter); }
1336 bool ciMethod::is_setter      () const {         FETCH_FLAG_FROM_VM(is_setter); }
1337 bool ciMethod::is_accessor    () const {         FETCH_FLAG_FROM_VM(is_accessor); }
1338 bool ciMethod::is_initializer () const {         FETCH_FLAG_FROM_VM(is_initializer); }
1339 bool ciMethod::is_empty       () const {         FETCH_FLAG_FROM_VM(is_empty_method); }
1340 
1341 bool ciMethod::is_boxing_method() const {
1342   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1343     switch (intrinsic_id()) {
1344       case vmIntrinsics::_Boolean_valueOf:
1345       case vmIntrinsics::_Byte_valueOf:
1346       case vmIntrinsics::_Character_valueOf:
1347       case vmIntrinsics::_Short_valueOf:
1348       case vmIntrinsics::_Integer_valueOf:
1349       case vmIntrinsics::_Long_valueOf:
1350       case vmIntrinsics::_Float_valueOf:
1351       case vmIntrinsics::_Double_valueOf:
1352         return true;
1353       default:
1354         return false;
1355     }
1356   }
1357   return false;
1358 }
1359 
1360 bool ciMethod::is_unboxing_method() const {
1361   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1362     switch (intrinsic_id()) {
1363       case vmIntrinsics::_booleanValue:
1364       case vmIntrinsics::_byteValue:
1365       case vmIntrinsics::_charValue:
1366       case vmIntrinsics::_shortValue:
1367       case vmIntrinsics::_intValue:
1368       case vmIntrinsics::_longValue:
1369       case vmIntrinsics::_floatValue:
1370       case vmIntrinsics::_doubleValue:
1371         return true;
1372       default:
1373         return false;
1374     }
1375   }
1376   return false;
1377 }
1378 
1379 bool ciMethod::is_vector_method() const {
1380   return (holder() == ciEnv::current()->vector_VectorSupport_klass()) &&
1381          (intrinsic_id() != vmIntrinsics::_none);
1382 }
1383 
1384 BCEscapeAnalyzer  *ciMethod::get_bcea() {
1385 #ifdef COMPILER2
1386   if (_bcea == nullptr) {
1387     _bcea = new (CURRENT_ENV->arena()) BCEscapeAnalyzer(this, nullptr);
1388   }
1389   return _bcea;
1390 #else // COMPILER2
1391   ShouldNotReachHere();
1392   return nullptr;
1393 #endif // COMPILER2
1394 }
1395 
1396 ciMethodBlocks  *ciMethod::get_method_blocks() {
1397   if (_method_blocks == nullptr) {
1398     Arena *arena = CURRENT_ENV->arena();
1399     _method_blocks = new (arena) ciMethodBlocks(arena, this);
1400   }
1401   return _method_blocks;
1402 }
1403 
1404 #undef FETCH_FLAG_FROM_VM
1405 
1406 void ciMethod::dump_name_as_ascii(outputStream* st, Method* method) {
1407   st->print("%s %s %s",
1408             CURRENT_ENV->replay_name(method->method_holder()),
1409             method->name()->as_quoted_ascii(),
1410             method->signature()->as_quoted_ascii());
1411 }
1412 
1413 void ciMethod::dump_name_as_ascii(outputStream* st) {
1414   Method* method = get_Method();
1415   dump_name_as_ascii(st, method);
1416 }
1417 
1418 void ciMethod::dump_replay_data(outputStream* st) {
1419   ResourceMark rm;
1420   Method* method = get_Method();
1421   if (MethodHandles::is_signature_polymorphic_method(method)) {
1422     // ignore for now
1423     return;
1424   }
1425   MethodCounters* mcs = method->method_counters();
1426   st->print("ciMethod ");
1427   dump_name_as_ascii(st);
1428   st->print_cr(" %d %d %d %d %d",
1429                mcs == nullptr ? 0 : mcs->invocation_counter()->raw_counter(),
1430                mcs == nullptr ? 0 : mcs->backedge_counter()->raw_counter(),
1431                interpreter_invocation_count(),
1432                interpreter_throwout_count(),
1433                _inline_instructions_size);
1434 }
1435 
1436 // ------------------------------------------------------------------
1437 // ciMethod::print_codes
1438 //
1439 // Print a range of the bytecodes for this method.
1440 void ciMethod::print_codes_on(int from, int to, outputStream* st) {
1441   check_is_loaded();
1442   GUARDED_VM_ENTRY(get_Method()->print_codes_on(from, to, st);)
1443 }
1444 
1445 // ------------------------------------------------------------------
1446 // ciMethod::print_name
1447 //
1448 // Print the name of this method, including signature and some flags.
1449 void ciMethod::print_name(outputStream* st) {
1450   check_is_loaded();
1451   GUARDED_VM_ENTRY(get_Method()->print_name(st);)
1452 }
1453 
1454 // ------------------------------------------------------------------
1455 // ciMethod::print_short_name
1456 //
1457 // Print the name of this method, without signature.
1458 void ciMethod::print_short_name(outputStream* st) {
1459   if (is_loaded()) {
1460     GUARDED_VM_ENTRY(get_Method()->print_short_name(st););
1461   } else {
1462     // Fall back if method is not loaded.
1463     holder()->print_name_on(st);
1464     st->print("::");
1465     name()->print_symbol_on(st);
1466     if (WizardMode)
1467       signature()->as_symbol()->print_symbol_on(st);
1468   }
1469 }
1470 
1471 // ------------------------------------------------------------------
1472 // ciMethod::print_impl
1473 //
1474 // Implementation of the print method.
1475 void ciMethod::print_impl(outputStream* st) {
1476   ciMetadata::print_impl(st);
1477   st->print(" name=");
1478   name()->print_symbol_on(st);
1479   st->print(" holder=");
1480   holder()->print_name_on(st);
1481   st->print(" signature=");
1482   signature()->as_symbol()->print_symbol_on(st);
1483   if (is_loaded()) {
1484     st->print(" loaded=true");
1485     st->print(" arg_size=%d", arg_size());
1486     st->print(" flags=");
1487     flags().print_member_flags(st);
1488   } else {
1489     st->print(" loaded=false");
1490   }
1491 }
1492 
1493 // ------------------------------------------------------------------
1494 
1495 static BasicType erase_to_word_type(BasicType bt) {
1496   if (is_subword_type(bt))   return T_INT;
1497   if (is_reference_type(bt)) return T_OBJECT;
1498   return bt;
1499 }
1500 
1501 static bool basic_types_match(ciType* t1, ciType* t2) {
1502   if (t1 == t2)  return true;
1503   return erase_to_word_type(t1->basic_type()) == erase_to_word_type(t2->basic_type());
1504 }
1505 
1506 bool ciMethod::is_consistent_info(ciMethod* declared_method, ciMethod* resolved_method) {
1507   bool invoke_through_mh_intrinsic = declared_method->is_method_handle_intrinsic() &&
1508                                   !resolved_method->is_method_handle_intrinsic();
1509 
1510   if (!invoke_through_mh_intrinsic) {
1511     // Method name & descriptor should stay the same.
1512     // Signatures may reference unloaded types and thus they may be not strictly equal.
1513     ciSymbol* declared_signature = declared_method->signature()->as_symbol();
1514     ciSymbol* resolved_signature = resolved_method->signature()->as_symbol();
1515 
1516     return (declared_method->name()->equals(resolved_method->name())) &&
1517            (declared_signature->equals(resolved_signature));
1518   }
1519 
1520   ciMethod* linker = declared_method;
1521   ciMethod* target = resolved_method;
1522   // Linkers have appendix argument which is not passed to callee.
1523   int has_appendix = MethodHandles::has_member_arg(linker->intrinsic_id()) ? 1 : 0;
1524   if (linker->arg_size() != (target->arg_size() + has_appendix)) {
1525     return false; // argument slot count mismatch
1526   }
1527 
1528   ciSignature* linker_sig = linker->signature();
1529   ciSignature* target_sig = target->signature();
1530 
1531   if (linker_sig->count() + (linker->is_static() ? 0 : 1) !=
1532       target_sig->count() + (target->is_static() ? 0 : 1) + has_appendix) {
1533     return false; // argument count mismatch
1534   }
1535 
1536   int sbase = 0, rbase = 0;
1537   switch (linker->intrinsic_id()) {
1538     case vmIntrinsics::_linkToVirtual:
1539     case vmIntrinsics::_linkToInterface:
1540     case vmIntrinsics::_linkToSpecial: {
1541       if (target->is_static()) {
1542         return false;
1543       }
1544       if (linker_sig->type_at(0)->is_primitive_type()) {
1545         return false;  // receiver should be an oop
1546       }
1547       sbase = 1; // skip receiver
1548       break;
1549     }
1550     case vmIntrinsics::_linkToStatic: {
1551       if (!target->is_static()) {
1552         return false;
1553       }
1554       break;
1555     }
1556     case vmIntrinsics::_invokeBasic: {
1557       if (target->is_static()) {
1558         if (target_sig->type_at(0)->is_primitive_type()) {
1559           return false; // receiver should be an oop
1560         }
1561         rbase = 1; // skip receiver
1562       }
1563       break;
1564     }
1565     default:
1566       break;
1567   }
1568   assert(target_sig->count() - rbase == linker_sig->count() - sbase - has_appendix, "argument count mismatch");
1569   int arg_count = target_sig->count() - rbase;
1570   for (int i = 0; i < arg_count; i++) {
1571     if (!basic_types_match(linker_sig->type_at(sbase + i), target_sig->type_at(rbase + i))) {
1572       return false;
1573     }
1574   }
1575   // Only check the return type if the symbolic info has non-void return type.
1576   // I.e. the return value of the resolved method can be dropped.
1577   if (!linker->return_type()->is_void() &&
1578       !basic_types_match(linker->return_type(), target->return_type())) {
1579     return false;
1580   }
1581   return true; // no mismatch found
1582 }
1583 
1584 // ------------------------------------------------------------------