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