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/aotLinkedClassBulkLoader.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::equals
 808 //
 809 // Returns true if the methods are the same, taking redefined methods
 810 // into account.
 811 bool ciMethod::equals(const ciMethod* m) const {
 812   if (this == m) return true;
 813   VM_ENTRY_MARK;
 814   Method* m1 = this->get_Method();
 815   Method* m2 = m->get_Method();
 816   if (m1->is_old()) m1 = m1->get_new_method();
 817   if (m2->is_old()) m2 = m2->get_new_method();
 818   return m1 == m2;
 819 }
 820 
 821 
 822 // ------------------------------------------------------------------
 823 // ciMethod::resolve_invoke
 824 //
 825 // Given a known receiver klass, find the target for the call.
 826 // Return null if the call has no target or the target is abstract.
 827 ciMethod* ciMethod::resolve_invoke(ciKlass* caller, ciKlass* exact_receiver, bool check_access, bool allow_abstract) {
 828   check_is_loaded();
 829   VM_ENTRY_MARK;
 830 
 831   Klass* caller_klass = caller->get_Klass();
 832   Klass* recv         = exact_receiver->get_Klass();
 833   Klass* resolved     = holder()->get_Klass();
 834   Symbol* h_name      = name()->get_symbol();
 835   Symbol* h_signature = signature()->get_symbol();
 836 
 837   LinkInfo link_info(resolved, h_name, h_signature, caller_klass,
 838                      check_access ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
 839                      check_access ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
 840   Method* m = nullptr;
 841   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 842   // the vtable has not been setup, and the LinkResolver will fail.
 843   if (recv->is_array_klass()
 844        ||
 845       (InstanceKlass::cast(recv)->is_linked() && !exact_receiver->is_interface())) {
 846     if (holder()->is_interface()) {
 847       m = LinkResolver::resolve_interface_call_or_null(recv, link_info);
 848     } else {
 849       m = LinkResolver::resolve_virtual_call_or_null(recv, link_info);
 850     }
 851   }
 852 
 853   if (m == nullptr) {
 854     // Return null only if there was a problem with lookup (uninitialized class, etc.)
 855     return nullptr;
 856   }
 857 
 858   ciMethod* result = this;
 859   if (m != get_Method()) {
 860     result = CURRENT_THREAD_ENV->get_method(m);
 861   }
 862 
 863   if (result->is_abstract() && !allow_abstract) {
 864     // Don't return abstract methods because they aren't optimizable or interesting.
 865     return nullptr;
 866   }
 867   return result;
 868 }
 869 
 870 // ------------------------------------------------------------------
 871 // ciMethod::resolve_vtable_index
 872 //
 873 // Given a known receiver klass, find the vtable index for the call.
 874 // Return Method::invalid_vtable_index if the vtable_index is unknown.
 875 int ciMethod::resolve_vtable_index(ciKlass* caller, ciKlass* receiver) {
 876    check_is_loaded();
 877 
 878    int vtable_index = Method::invalid_vtable_index;
 879    // Only do lookup if receiver klass has been linked.  Otherwise,
 880    // the vtable has not been setup, and the LinkResolver will fail.
 881    if (!receiver->is_interface()
 882        && (!receiver->is_instance_klass() ||
 883            receiver->as_instance_klass()->is_linked())) {
 884      VM_ENTRY_MARK;
 885 
 886      Klass* caller_klass = caller->get_Klass();
 887      Klass* recv         = receiver->get_Klass();
 888      Symbol* h_name = name()->get_symbol();
 889      Symbol* h_signature = signature()->get_symbol();
 890 
 891      LinkInfo link_info(recv, h_name, h_signature, caller_klass);
 892      vtable_index = LinkResolver::resolve_virtual_vtable_index(recv, link_info);
 893      if (vtable_index == Method::nonvirtual_vtable_index) {
 894        // A statically bound method.  Return "no such index".
 895        vtable_index = Method::invalid_vtable_index;
 896      }
 897    }
 898 
 899    return vtable_index;
 900 }
 901 
 902 // ------------------------------------------------------------------
 903 // ciMethod::get_field_at_bci
 904 ciField* ciMethod::get_field_at_bci(int bci, bool &will_link) {
 905   ciBytecodeStream iter(this);
 906   iter.reset_to_bci(bci);
 907   iter.next();
 908   return iter.get_field(will_link);
 909 }
 910 
 911 // ------------------------------------------------------------------
 912 // ciMethod::get_method_at_bci
 913 ciMethod* ciMethod::get_method_at_bci(int bci, bool &will_link, ciSignature* *declared_signature) {
 914   ciBytecodeStream iter(this);
 915   iter.reset_to_bci(bci);
 916   iter.next();
 917   return iter.get_method(will_link, declared_signature);
 918 }
 919 
 920 // ------------------------------------------------------------------
 921 ciKlass* ciMethod::get_declared_method_holder_at_bci(int bci) {
 922   ciBytecodeStream iter(this);
 923   iter.reset_to_bci(bci);
 924   iter.next();
 925   return iter.get_declared_method_holder();
 926 }
 927 
 928 // ------------------------------------------------------------------
 929 // Adjust a CounterData count to be commensurate with
 930 // interpreter_invocation_count.  If the MDO exists for
 931 // only 25% of the time the method exists, then the
 932 // counts in the MDO should be scaled by 4X, so that
 933 // they can be usefully and stably compared against the
 934 // invocation counts in methods.
 935 int ciMethod::scale_count(int count, float prof_factor) {
 936   if (count > 0 && method_data() != nullptr) {
 937     int counter_life = method_data()->invocation_count();
 938     int method_life = interpreter_invocation_count();
 939     if (method_life < counter_life) { // may happen because of the snapshot timing
 940       method_life = counter_life;
 941     }
 942     if (counter_life > 0) {
 943       count = (int)((double)count * prof_factor * method_life / counter_life + 0.5);
 944       count = (count > 0) ? count : 1;
 945     } else {
 946       count = 1;
 947     }
 948   }
 949   return count;
 950 }
 951 
 952 
 953 // ------------------------------------------------------------------
 954 // ciMethod::is_special_get_caller_class_method
 955 //
 956 bool ciMethod::is_ignored_by_security_stack_walk() const {
 957   check_is_loaded();
 958   VM_ENTRY_MARK;
 959   return get_Method()->is_ignored_by_security_stack_walk();
 960 }
 961 
 962 // ------------------------------------------------------------------
 963 // ciMethod::needs_clinit_barrier
 964 //
 965 bool ciMethod::needs_clinit_barrier() const {
 966   check_is_loaded();
 967   return is_static() && !holder()->is_initialized();
 968 }
 969 
 970 // ------------------------------------------------------------------
 971 // invokedynamic support
 972 
 973 // ------------------------------------------------------------------
 974 // ciMethod::is_method_handle_intrinsic
 975 //
 976 // Return true if the method is an instance of the JVM-generated
 977 // signature-polymorphic MethodHandle methods, _invokeBasic, _linkToVirtual, etc.
 978 bool ciMethod::is_method_handle_intrinsic() const {
 979   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 980   return (MethodHandles::is_signature_polymorphic(iid) &&
 981           MethodHandles::is_signature_polymorphic_intrinsic(iid));
 982 }
 983 
 984 // ------------------------------------------------------------------
 985 // ciMethod::is_compiled_lambda_form
 986 //
 987 // Return true if the method is a generated MethodHandle adapter.
 988 // These are built by Java code.
 989 bool ciMethod::is_compiled_lambda_form() const {
 990   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
 991   return iid == vmIntrinsics::_compiledLambdaForm;
 992 }
 993 
 994 // ------------------------------------------------------------------
 995 // ciMethod::is_object_initializer
 996 //
 997 bool ciMethod::is_object_initializer() const {
 998    return name() == ciSymbols::object_initializer_name();
 999 }
1000 
1001 // ------------------------------------------------------------------
1002 // ciMethod::is_scoped
1003 //
1004 // Return true for methods annotated with @Scoped
1005 bool ciMethod::is_scoped() const {
1006    return get_Method()->is_scoped();
1007 }
1008 
1009 // ------------------------------------------------------------------
1010 // ciMethod::has_member_arg
1011 //
1012 // Return true if the method is a linker intrinsic like _linkToVirtual.
1013 // These are built by the JVM.
1014 bool ciMethod::has_member_arg() const {
1015   vmIntrinsics::ID iid = _intrinsic_id;  // do not check if loaded
1016   return (MethodHandles::is_signature_polymorphic(iid) &&
1017           MethodHandles::has_member_arg(iid));
1018 }
1019 
1020 // ------------------------------------------------------------------
1021 // ciMethod::ensure_method_data
1022 //
1023 // Generate new MethodData* objects at compile time.
1024 // Return true if allocation was successful or no MDO is required.
1025 bool ciMethod::ensure_method_data(const methodHandle& h_m, bool training_data_only) {
1026   EXCEPTION_CONTEXT;
1027   if (is_native() || is_abstract() || h_m()->is_accessor()) {
1028     return true;
1029   }
1030   if (h_m()->method_data() == nullptr) {
1031     if (training_data_only) {
1032       Method::install_training_method_data(h_m);
1033     } else {
1034       Method::build_profiling_method_data(h_m, THREAD);
1035       if (HAS_PENDING_EXCEPTION) {
1036         CLEAR_PENDING_EXCEPTION;
1037       }
1038     }
1039   }
1040   if (h_m()->method_data() != nullptr) {
1041     _method_data = CURRENT_ENV->get_method_data(h_m()->method_data());
1042     return _method_data->load_data();
1043   } else {
1044     _method_data = CURRENT_ENV->get_empty_methodData();
1045     return false;
1046   }
1047 }
1048 
1049 // public, retroactive version
1050 bool ciMethod::ensure_method_data(bool training_data_only) {
1051   bool result = true;
1052   if (_method_data == nullptr || _method_data->is_empty()) {
1053     GUARDED_VM_ENTRY({
1054       methodHandle mh(Thread::current(), get_Method());
1055       result = ensure_method_data(mh, training_data_only);
1056     });
1057   }
1058   return result;
1059 }
1060 
1061 
1062 // ------------------------------------------------------------------
1063 // ciMethod::method_data
1064 //
1065 ciMethodData* ciMethod::method_data() {
1066   if (CURRENT_ENV->task()->is_precompiled() && CURRENT_ENV->task()->comp_level() == CompLevel_full_optimization) {
1067     if (_method_data_recorded == nullptr) {
1068       VM_ENTRY_MARK;
1069       methodHandle h_m(thread, get_Method());
1070       MethodTrainingData* mtd = TrainingData::lookup_for(h_m());
1071       MethodData* mdo = (mtd != nullptr ? mtd->final_profile() : nullptr);
1072       DirectiveSet* directives = DirectivesStack::getMatchingDirective(h_m, CURRENT_ENV->task()->compiler());
1073       if (mdo == nullptr || directives->IgnoreRecordedProfileOption) {
1074         if (directives->IgnoreRecordedProfileOption) {
1075           ResourceMark rm;
1076           log_debug(precompile)("Ignore recorded profile for %s", h_m->name_and_sig_as_C_string());
1077         } else {
1078           ResourceMark rm;
1079           log_debug(precompile)("No profile for %s", h_m->name_and_sig_as_C_string());
1080         }
1081         _method_data_recorded = CURRENT_ENV->get_empty_methodData();
1082       } else {
1083 #if INCLUDE_CDS
1084         if (mdo->extra_data_lock() == nullptr) {
1085           assert(!HAS_PENDING_EXCEPTION, "");
1086           mdo->restore_unshareable_info(thread);
1087           assert(!HAS_PENDING_EXCEPTION, "");
1088         }
1089 #endif
1090         _method_data_recorded = CURRENT_ENV->get_method_data(mdo);
1091         _method_data_recorded->load_data();
1092         {
1093           ResourceMark rm;
1094           log_debug(precompile)("Recorded profile " PTR_FORMAT " for %s", p2i(mdo), h_m->name_and_sig_as_C_string());
1095         }
1096       }
1097     }
1098     assert(_method_data_recorded != nullptr, "");
1099     return _method_data_recorded;
1100   } else {
1101     if (_method_data != nullptr) {
1102       return _method_data;
1103     }
1104     VM_ENTRY_MARK;
1105     methodHandle h_m(thread, get_Method());
1106     MethodData* mdo = h_m()->method_data();
1107     if (mdo != nullptr) {
1108       _method_data = CURRENT_ENV->get_method_data(mdo);
1109       _method_data->load_data();
1110     } else {
1111       _method_data = CURRENT_ENV->get_empty_methodData();
1112     }
1113     return _method_data;
1114   }
1115 }
1116 
1117 // ------------------------------------------------------------------
1118 // ciMethod::method_data_or_null
1119 // Returns a pointer to ciMethodData if MDO exists on the VM side,
1120 // null otherwise.
1121 ciMethodData* ciMethod::method_data_or_null() {
1122   ciMethodData *md = method_data();
1123   if (md->is_empty()) {
1124     return nullptr;
1125   }
1126   return md;
1127 }
1128 
1129 // ------------------------------------------------------------------
1130 // ciMethod::ensure_method_counters
1131 //
1132 MethodCounters* ciMethod::ensure_method_counters() {
1133   check_is_loaded();
1134   VM_ENTRY_MARK;
1135   methodHandle mh(THREAD, get_Method());
1136   MethodCounters* method_counters = mh->get_method_counters(CHECK_NULL);
1137   return method_counters;
1138 }
1139 
1140 // ------------------------------------------------------------------
1141 // ciMethod::has_option
1142 //
1143 bool ciMethod::has_option(CompileCommandEnum option) {
1144   check_is_loaded();
1145   VM_ENTRY_MARK;
1146   methodHandle mh(THREAD, get_Method());
1147   return CompilerOracle::has_option(mh, option);
1148 }
1149 
1150 // ------------------------------------------------------------------
1151 // ciMethod::has_option_value
1152 //
1153 bool ciMethod::has_option_value(CompileCommandEnum option, double& value) {
1154   check_is_loaded();
1155   VM_ENTRY_MARK;
1156   methodHandle mh(THREAD, get_Method());
1157   return CompilerOracle::has_option_value(mh, option, value);
1158 }
1159 // ------------------------------------------------------------------
1160 // ciMethod::can_be_compiled
1161 //
1162 // Have previous compilations of this method succeeded?
1163 bool ciMethod::can_be_compiled() {
1164   check_is_loaded();
1165   ciEnv* env = CURRENT_ENV;
1166   if (is_c1_compile(env->comp_level())) {
1167     return _is_c1_compilable;
1168   }
1169 
1170 #if INCLUDE_JVMCI
1171   if (EnableJVMCI && UseJVMCICompiler &&
1172       env->comp_level() == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1173     return false;
1174   }
1175 #endif
1176   return _is_c2_compilable;
1177 }
1178 
1179 // ------------------------------------------------------------------
1180 // ciMethod::has_compiled_code
1181 bool ciMethod::has_compiled_code() {
1182   return inline_instructions_size() > 0;
1183 }
1184 
1185 int ciMethod::highest_osr_comp_level() {
1186   check_is_loaded();
1187   VM_ENTRY_MARK;
1188   return get_Method()->highest_osr_comp_level();
1189 }
1190 
1191 // ------------------------------------------------------------------
1192 // ciMethod::code_size_for_inlining
1193 //
1194 // Code size for inlining decisions.  This method returns a code
1195 // size of 1 for methods which has the ForceInline annotation.
1196 int ciMethod::code_size_for_inlining() {
1197   check_is_loaded();
1198   if (get_Method()->force_inline()) {
1199     return 1;
1200   }
1201   return code_size();
1202 }
1203 
1204 // ------------------------------------------------------------------
1205 // ciMethod::inline_instructions_size
1206 //
1207 // This is a rough metric for "fat" methods, compared before inlining
1208 // with InlineSmallCode.  The CodeBlob::code_size accessor includes
1209 // junk like exception handler, stubs, and constant table, which are
1210 // not highly relevant to an inlined method.  So we use the more
1211 // specific accessor nmethod::insts_size.
1212 // Also some instructions inside the code are excluded from inline
1213 // heuristic (e.g. post call nop instructions; see InlineSkippedInstructionsCounter)
1214 int ciMethod::inline_instructions_size() {
1215   if (_inline_instructions_size == -1) {
1216     if (TrainingData::have_data()) {
1217       GUARDED_VM_ENTRY(
1218         CompLevel level = static_cast<CompLevel>(CURRENT_ENV->comp_level());
1219         methodHandle top_level_mh(Thread::current(), CURRENT_ENV->task()->method());
1220         MethodTrainingData* mtd = MethodTrainingData::find(top_level_mh);
1221         if (mtd != nullptr) {
1222           CompileTrainingData* ctd = mtd->last_toplevel_compile(level);
1223           if (ctd != nullptr) {
1224             methodHandle mh(Thread::current(), get_Method());
1225             MethodTrainingData* this_mtd = MethodTrainingData::find(mh);
1226             if (this_mtd != nullptr) {
1227               auto r = ctd->ci_records().ciMethod__inline_instructions_size.find(this_mtd);
1228               if (r.is_valid()) {
1229                 _inline_instructions_size = r.result();
1230               }
1231             }
1232           }
1233         }
1234       );
1235     }
1236   }
1237   if (_inline_instructions_size == -1) {
1238     GUARDED_VM_ENTRY(
1239       nmethod* code = get_Method()->code();
1240       if (code != nullptr && !code->is_scc() && (code->comp_level() == CompLevel_full_optimization)) {
1241         int isize = code->insts_end() - code->verified_entry_point() - code->skipped_instructions_size();
1242         _inline_instructions_size = isize > 0 ? isize : 0;
1243       } else {
1244         _inline_instructions_size = 0;
1245       }
1246       if (TrainingData::need_data()) {
1247         CompileTrainingData* ctd = CURRENT_ENV->task()->training_data();
1248         if (ctd != nullptr) {
1249           methodHandle mh(Thread::current(), get_Method());
1250           MethodTrainingData* this_mtd = MethodTrainingData::make(mh);
1251           ctd->ci_records().ciMethod__inline_instructions_size.append_if_missing(_inline_instructions_size, this_mtd);
1252         }
1253       }
1254     );
1255   }
1256   return _inline_instructions_size;
1257 }
1258 
1259 // ------------------------------------------------------------------
1260 // ciMethod::log_nmethod_identity
1261 void ciMethod::log_nmethod_identity(xmlStream* log) {
1262   GUARDED_VM_ENTRY(
1263     nmethod* code = get_Method()->code();
1264     if (code != nullptr) {
1265       code->log_identity(log);
1266     }
1267   )
1268 }
1269 
1270 // ------------------------------------------------------------------
1271 // ciMethod::is_not_reached
1272 bool ciMethod::is_not_reached(int bci) {
1273   check_is_loaded();
1274   VM_ENTRY_MARK;
1275   return Interpreter::is_not_reached(
1276                methodHandle(THREAD, get_Method()), bci);
1277 }
1278 
1279 // ------------------------------------------------------------------
1280 // ciMethod::was_never_executed
1281 bool ciMethod::was_executed_more_than(int times) {
1282   // Invocation counter is reset when the Method* is compiled.
1283   // If the method has compiled code we therefore assume it has
1284   // be executed more than n times.
1285   if (is_accessor() || is_empty() || has_compiled_code()) {
1286     // interpreter doesn't bump invocation counter of trivial methods
1287     // compiler does not bump invocation counter of compiled methods
1288     return true;
1289   }
1290   if (!method_data()->is_empty()) {
1291     return (method_data()->invocation_count() > times);
1292   }
1293   VM_ENTRY_MARK;
1294   return get_Method()->was_executed_more_than(times);
1295 }
1296 
1297 // ------------------------------------------------------------------
1298 // ciMethod::has_unloaded_classes_in_signature
1299 bool ciMethod::has_unloaded_classes_in_signature() {
1300   // ciSignature is resolved against some accessing class and
1301   // signature classes aren't required to be local. As a benefit,
1302   // it makes signature classes visible through loader constraints.
1303   // So, encountering an unloaded class signals it is absent both in
1304   // the callee (local) and caller contexts.
1305   return signature()->has_unloaded_classes();
1306 }
1307 
1308 // ------------------------------------------------------------------
1309 // ciMethod::is_klass_loaded
1310 bool ciMethod::is_klass_loaded(int refinfo_index, Bytecodes::Code bc, bool must_be_resolved) const {
1311   VM_ENTRY_MARK;
1312   return get_Method()->is_klass_loaded(refinfo_index, bc, must_be_resolved);
1313 }
1314 
1315 // ------------------------------------------------------------------
1316 // ciMethod::check_call
1317 bool ciMethod::check_call(int refinfo_index, bool is_static) const {
1318   // This method is used only in C2 from InlineTree::ok_to_inline,
1319   // and is only used under -Xcomp.
1320   // It appears to fail when applied to an invokeinterface call site.
1321   // FIXME: Remove this method and resolve_method_statically; refactor to use the other LinkResolver entry points.
1322   VM_ENTRY_MARK;
1323   {
1324     ExceptionMark em(THREAD);
1325     HandleMark hm(THREAD);
1326     constantPoolHandle pool (THREAD, get_Method()->constants());
1327     Bytecodes::Code code = (is_static ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual);
1328     Method* spec_method = LinkResolver::resolve_method_statically(code, pool, refinfo_index, THREAD);
1329     if (HAS_PENDING_EXCEPTION) {
1330       CLEAR_PENDING_EXCEPTION;
1331       return false;
1332     } else {
1333       return (spec_method->is_static() == is_static);
1334     }
1335   }
1336   return false;
1337 }
1338 // ------------------------------------------------------------------
1339 // ciMethod::print_codes
1340 //
1341 // Print the bytecodes for this method.
1342 void ciMethod::print_codes_on(outputStream* st) {
1343   check_is_loaded();
1344   GUARDED_VM_ENTRY(get_Method()->print_codes_on(st);)
1345 }
1346 
1347 
1348 #define FETCH_FLAG_FROM_VM(flag_accessor) { \
1349   check_is_loaded(); \
1350   VM_ENTRY_MARK; \
1351   return get_Method()->flag_accessor(); \
1352 }
1353 
1354 bool ciMethod::has_loops      () const {         FETCH_FLAG_FROM_VM(has_loops); }
1355 bool ciMethod::has_jsrs       () const {         FETCH_FLAG_FROM_VM(has_jsrs);  }
1356 bool ciMethod::is_getter      () const {         FETCH_FLAG_FROM_VM(is_getter); }
1357 bool ciMethod::is_setter      () const {         FETCH_FLAG_FROM_VM(is_setter); }
1358 bool ciMethod::is_accessor    () const {         FETCH_FLAG_FROM_VM(is_accessor); }
1359 bool ciMethod::is_initializer () const {         FETCH_FLAG_FROM_VM(is_initializer); }
1360 bool ciMethod::is_empty       () const {         FETCH_FLAG_FROM_VM(is_empty_method); }
1361 
1362 bool ciMethod::is_boxing_method() const {
1363   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1364     switch (intrinsic_id()) {
1365       case vmIntrinsics::_Boolean_valueOf:
1366       case vmIntrinsics::_Byte_valueOf:
1367       case vmIntrinsics::_Character_valueOf:
1368       case vmIntrinsics::_Short_valueOf:
1369       case vmIntrinsics::_Integer_valueOf:
1370       case vmIntrinsics::_Long_valueOf:
1371       case vmIntrinsics::_Float_valueOf:
1372       case vmIntrinsics::_Double_valueOf:
1373         return true;
1374       default:
1375         return false;
1376     }
1377   }
1378   return false;
1379 }
1380 
1381 bool ciMethod::is_unboxing_method() const {
1382   if (intrinsic_id() != vmIntrinsics::_none && holder()->is_box_klass()) {
1383     switch (intrinsic_id()) {
1384       case vmIntrinsics::_booleanValue:
1385       case vmIntrinsics::_byteValue:
1386       case vmIntrinsics::_charValue:
1387       case vmIntrinsics::_shortValue:
1388       case vmIntrinsics::_intValue:
1389       case vmIntrinsics::_longValue:
1390       case vmIntrinsics::_floatValue:
1391       case vmIntrinsics::_doubleValue:
1392         return true;
1393       default:
1394         return false;
1395     }
1396   }
1397   return false;
1398 }
1399 
1400 bool ciMethod::is_vector_method() const {
1401   return (holder() == ciEnv::current()->vector_VectorSupport_klass()) &&
1402          (intrinsic_id() != vmIntrinsics::_none);
1403 }
1404 
1405 BCEscapeAnalyzer  *ciMethod::get_bcea() {
1406 #ifdef COMPILER2
1407   if (_bcea == nullptr) {
1408     _bcea = new (CURRENT_ENV->arena()) BCEscapeAnalyzer(this, nullptr);
1409   }
1410   return _bcea;
1411 #else // COMPILER2
1412   ShouldNotReachHere();
1413   return nullptr;
1414 #endif // COMPILER2
1415 }
1416 
1417 ciMethodBlocks  *ciMethod::get_method_blocks() {
1418   if (_method_blocks == nullptr) {
1419     Arena *arena = CURRENT_ENV->arena();
1420     _method_blocks = new (arena) ciMethodBlocks(arena, this);
1421   }
1422   return _method_blocks;
1423 }
1424 
1425 #undef FETCH_FLAG_FROM_VM
1426 
1427 void ciMethod::dump_name_as_ascii(outputStream* st, Method* method) {
1428   st->print("%s %s %s",
1429             CURRENT_ENV->replay_name(method->method_holder()),
1430             method->name()->as_quoted_ascii(),
1431             method->signature()->as_quoted_ascii());
1432 }
1433 
1434 void ciMethod::dump_name_as_ascii(outputStream* st) {
1435   Method* method = get_Method();
1436   dump_name_as_ascii(st, method);
1437 }
1438 
1439 void ciMethod::dump_replay_data(outputStream* st) {
1440   ResourceMark rm;
1441   Method* method = get_Method();
1442   if (MethodHandles::is_signature_polymorphic_method(method)) {
1443     // ignore for now
1444     return;
1445   }
1446   MethodCounters* mcs = method->method_counters();
1447   st->print("ciMethod ");
1448   dump_name_as_ascii(st);
1449   st->print_cr(" %d %d %d %d %d",
1450                mcs == nullptr ? 0 : mcs->invocation_counter()->raw_counter(),
1451                mcs == nullptr ? 0 : mcs->backedge_counter()->raw_counter(),
1452                interpreter_invocation_count(),
1453                interpreter_throwout_count(),
1454                _inline_instructions_size);
1455 }
1456 
1457 // ------------------------------------------------------------------
1458 // ciMethod::print_codes
1459 //
1460 // Print a range of the bytecodes for this method.
1461 void ciMethod::print_codes_on(int from, int to, outputStream* st) {
1462   check_is_loaded();
1463   GUARDED_VM_ENTRY(get_Method()->print_codes_on(from, to, st);)
1464 }
1465 
1466 // ------------------------------------------------------------------
1467 // ciMethod::print_name
1468 //
1469 // Print the name of this method, including signature and some flags.
1470 void ciMethod::print_name(outputStream* st) {
1471   check_is_loaded();
1472   GUARDED_VM_ENTRY(get_Method()->print_name(st);)
1473 }
1474 
1475 // ------------------------------------------------------------------
1476 // ciMethod::print_short_name
1477 //
1478 // Print the name of this method, without signature.
1479 void ciMethod::print_short_name(outputStream* st) {
1480   if (is_loaded()) {
1481     GUARDED_VM_ENTRY(get_Method()->print_short_name(st););
1482   } else {
1483     // Fall back if method is not loaded.
1484     holder()->print_name_on(st);
1485     st->print("::");
1486     name()->print_symbol_on(st);
1487     if (WizardMode)
1488       signature()->as_symbol()->print_symbol_on(st);
1489   }
1490 }
1491 
1492 // ------------------------------------------------------------------
1493 // ciMethod::print_impl
1494 //
1495 // Implementation of the print method.
1496 void ciMethod::print_impl(outputStream* st) {
1497   ciMetadata::print_impl(st);
1498   st->print(" name=");
1499   name()->print_symbol_on(st);
1500   st->print(" holder=");
1501   holder()->print_name_on(st);
1502   st->print(" signature=");
1503   signature()->as_symbol()->print_symbol_on(st);
1504   if (is_loaded()) {
1505     st->print(" loaded=true");
1506     st->print(" arg_size=%d", arg_size());
1507     st->print(" flags=");
1508     flags().print_member_flags(st);
1509   } else {
1510     st->print(" loaded=false");
1511   }
1512 }
1513 
1514 // ------------------------------------------------------------------
1515 
1516 static BasicType erase_to_word_type(BasicType bt) {
1517   if (is_subword_type(bt))   return T_INT;
1518   if (is_reference_type(bt)) return T_OBJECT;
1519   return bt;
1520 }
1521 
1522 static bool basic_types_match(ciType* t1, ciType* t2) {
1523   if (t1 == t2)  return true;
1524   return erase_to_word_type(t1->basic_type()) == erase_to_word_type(t2->basic_type());
1525 }
1526 
1527 bool ciMethod::is_consistent_info(ciMethod* declared_method, ciMethod* resolved_method) {
1528   bool invoke_through_mh_intrinsic = declared_method->is_method_handle_intrinsic() &&
1529                                   !resolved_method->is_method_handle_intrinsic();
1530 
1531   if (!invoke_through_mh_intrinsic) {
1532     // Method name & descriptor should stay the same.
1533     // Signatures may reference unloaded types and thus they may be not strictly equal.
1534     ciSymbol* declared_signature = declared_method->signature()->as_symbol();
1535     ciSymbol* resolved_signature = resolved_method->signature()->as_symbol();
1536 
1537     return (declared_method->name()->equals(resolved_method->name())) &&
1538            (declared_signature->equals(resolved_signature));
1539   }
1540 
1541   ciMethod* linker = declared_method;
1542   ciMethod* target = resolved_method;
1543   // Linkers have appendix argument which is not passed to callee.
1544   int has_appendix = MethodHandles::has_member_arg(linker->intrinsic_id()) ? 1 : 0;
1545   if (linker->arg_size() != (target->arg_size() + has_appendix)) {
1546     return false; // argument slot count mismatch
1547   }
1548 
1549   ciSignature* linker_sig = linker->signature();
1550   ciSignature* target_sig = target->signature();
1551 
1552   if (linker_sig->count() + (linker->is_static() ? 0 : 1) !=
1553       target_sig->count() + (target->is_static() ? 0 : 1) + has_appendix) {
1554     return false; // argument count mismatch
1555   }
1556 
1557   int sbase = 0, rbase = 0;
1558   switch (linker->intrinsic_id()) {
1559     case vmIntrinsics::_linkToVirtual:
1560     case vmIntrinsics::_linkToInterface:
1561     case vmIntrinsics::_linkToSpecial: {
1562       if (target->is_static()) {
1563         return false;
1564       }
1565       if (linker_sig->type_at(0)->is_primitive_type()) {
1566         return false;  // receiver should be an oop
1567       }
1568       sbase = 1; // skip receiver
1569       break;
1570     }
1571     case vmIntrinsics::_linkToStatic: {
1572       if (!target->is_static()) {
1573         return false;
1574       }
1575       break;
1576     }
1577     case vmIntrinsics::_invokeBasic: {
1578       if (target->is_static()) {
1579         if (target_sig->type_at(0)->is_primitive_type()) {
1580           return false; // receiver should be an oop
1581         }
1582         rbase = 1; // skip receiver
1583       }
1584       break;
1585     }
1586     default:
1587       break;
1588   }
1589   assert(target_sig->count() - rbase == linker_sig->count() - sbase - has_appendix, "argument count mismatch");
1590   int arg_count = target_sig->count() - rbase;
1591   for (int i = 0; i < arg_count; i++) {
1592     if (!basic_types_match(linker_sig->type_at(sbase + i), target_sig->type_at(rbase + i))) {
1593       return false;
1594     }
1595   }
1596   // Only check the return type if the symbolic info has non-void return type.
1597   // I.e. the return value of the resolved method can be dropped.
1598   if (!linker->return_type()->is_void() &&
1599       !basic_types_match(linker->return_type(), target->return_type())) {
1600     return false;
1601   }
1602   return true; // no mismatch found
1603 }
1604 
1605 // ------------------------------------------------------------------