1 /*
   2  * Copyright (c) 1999, 2012, 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 "ci/ciCallProfile.hpp"
  27 #include "ci/ciExceptionHandler.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciMethod.hpp"
  30 #include "ci/ciMethodBlocks.hpp"
  31 #include "ci/ciMethodData.hpp"
  32 #include "ci/ciMethodKlass.hpp"
  33 #include "ci/ciStreams.hpp"
  34 #include "ci/ciSymbol.hpp"
  35 #include "ci/ciUtilities.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "compiler/abstractCompiler.hpp"
  38 #include "compiler/compilerOracle.hpp"
  39 #include "compiler/methodLiveness.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/linkResolver.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "memory/allocation.inline.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/generateOopMap.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "prims/nativeLookup.hpp"
  48 #include "runtime/deoptimization.hpp"
  49 #include "utilities/bitMap.inline.hpp"
  50 #include "utilities/xmlstream.hpp"
  51 #ifdef COMPILER2
  52 #include "ci/bcEscapeAnalyzer.hpp"
  53 #include "ci/ciTypeFlow.hpp"
  54 #include "oops/methodOop.hpp"
  55 #endif
  56 #ifdef SHARK
  57 #include "ci/ciTypeFlow.hpp"
  58 #include "oops/methodOop.hpp"
  59 #endif
  60 
  61 // ciMethod
  62 //
  63 // This class represents a methodOop in the HotSpot virtual
  64 // machine.
  65 
  66 
  67 // ------------------------------------------------------------------
  68 // ciMethod::ciMethod
  69 //
  70 // Loaded method.
  71 ciMethod::ciMethod(methodHandle h_m) : ciObject(h_m) {
  72   assert(h_m() != NULL, "no null method");
  73 
  74   // These fields are always filled in in loaded methods.
  75   _flags = ciFlags(h_m()->access_flags());
  76 
  77   // Easy to compute, so fill them in now.
  78   _max_stack          = h_m()->max_stack();
  79   _max_locals         = h_m()->max_locals();
  80   _code_size          = h_m()->code_size();
  81   _intrinsic_id       = h_m()->intrinsic_id();
  82   _handler_count      = h_m()->exception_table_length();
  83   _uses_monitors      = h_m()->access_flags().has_monitor_bytecodes();
  84   _balanced_monitors  = !_uses_monitors || h_m()->access_flags().is_monitor_matching();
  85   _is_c1_compilable   = !h_m()->is_not_c1_compilable();
  86   _is_c2_compilable   = !h_m()->is_not_c2_compilable();
  87   // Lazy fields, filled in on demand.  Require allocation.
  88   _code               = NULL;
  89   _exception_handlers = NULL;
  90   _liveness           = NULL;
  91   _method_blocks = NULL;
  92 #if defined(COMPILER2) || defined(SHARK)
  93   _flow               = NULL;
  94   _bcea               = NULL;
  95 #endif // COMPILER2 || SHARK
  96 
  97   ciEnv *env = CURRENT_ENV;
  98   if (env->jvmti_can_hotswap_or_post_breakpoint() && can_be_compiled()) {
  99     // 6328518 check hotswap conditions under the right lock.
 100     MutexLocker locker(Compile_lock);
 101     if (Dependencies::check_evol_method(h_m()) != NULL) {
 102       _is_c1_compilable = false;
 103       _is_c2_compilable = false;
 104     }
 105   } else {
 106     CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
 107   }
 108 
 109   if (instanceKlass::cast(h_m()->method_holder())->is_linked()) {
 110     _can_be_statically_bound = h_m()->can_be_statically_bound();
 111   } else {
 112     // Have to use a conservative value in this case.
 113     _can_be_statically_bound = false;
 114   }
 115 
 116   // Adjust the definition of this condition to be more useful:
 117   // %%% take these conditions into account in vtable generation
 118   if (!_can_be_statically_bound && h_m()->is_private())
 119     _can_be_statically_bound = true;
 120   if (_can_be_statically_bound && h_m()->is_abstract())
 121     _can_be_statically_bound = false;
 122 
 123   // generating _signature may allow GC and therefore move m.
 124   // These fields are always filled in.
 125   _name = env->get_symbol(h_m()->name());
 126   _holder = env->get_object(h_m()->method_holder())->as_instance_klass();
 127   ciSymbol* sig_symbol = env->get_symbol(h_m()->signature());
 128   constantPoolHandle cpool = h_m()->constants();
 129   _signature = new (env->arena()) ciSignature(_holder, cpool, sig_symbol);
 130   _method_data = NULL;
 131   // Take a snapshot of these values, so they will be commensurate with the MDO.
 132   if (ProfileInterpreter || TieredCompilation) {
 133     int invcnt = h_m()->interpreter_invocation_count();
 134     // if the value overflowed report it as max int
 135     _interpreter_invocation_count = invcnt < 0 ? max_jint : invcnt ;
 136     _interpreter_throwout_count   = h_m()->interpreter_throwout_count();
 137   } else {
 138     _interpreter_invocation_count = 0;
 139     _interpreter_throwout_count = 0;
 140   }
 141   if (_interpreter_invocation_count == 0)
 142     _interpreter_invocation_count = 1;
 143 }
 144 
 145 
 146 // ------------------------------------------------------------------
 147 // ciMethod::ciMethod
 148 //
 149 // Unloaded method.
 150 ciMethod::ciMethod(ciInstanceKlass* holder,
 151                    ciSymbol*        name,
 152                    ciSymbol*        signature,
 153                    ciInstanceKlass* accessor) :
 154   ciObject(ciMethodKlass::make()),
 155   _name(                   name),
 156   _holder(                 holder),
 157   _intrinsic_id(           vmIntrinsics::_none),
 158   _liveness(               NULL),
 159   _can_be_statically_bound(false),
 160   _method_blocks(          NULL),
 161   _method_data(            NULL)
 162 #if defined(COMPILER2) || defined(SHARK)
 163   ,
 164   _flow(                   NULL),
 165   _bcea(                   NULL)
 166 #endif // COMPILER2 || SHARK
 167 {
 168   // Usually holder and accessor are the same type but in some cases
 169   // the holder has the wrong class loader (e.g. invokedynamic call
 170   // sites) so we pass the accessor.
 171   _signature = new (CURRENT_ENV->arena()) ciSignature(accessor, constantPoolHandle(), signature);
 172 }
 173 
 174 
 175 // ------------------------------------------------------------------
 176 // ciMethod::load_code
 177 //
 178 // Load the bytecodes and exception handler table for this method.
 179 void ciMethod::load_code() {
 180   VM_ENTRY_MARK;
 181   assert(is_loaded(), "only loaded methods have code");
 182 
 183   methodOop me = get_methodOop();
 184   Arena* arena = CURRENT_THREAD_ENV->arena();
 185 
 186   // Load the bytecodes.
 187   _code = (address)arena->Amalloc(code_size());
 188   memcpy(_code, me->code_base(), code_size());
 189 
 190   // Revert any breakpoint bytecodes in ci's copy
 191   if (me->number_of_breakpoints() > 0) {
 192     BreakpointInfo* bp = instanceKlass::cast(me->method_holder())->breakpoints();
 193     for (; bp != NULL; bp = bp->next()) {
 194       if (bp->match(me)) {
 195         code_at_put(bp->bci(), bp->orig_bytecode());
 196       }
 197     }
 198   }
 199 
 200   // And load the exception table.
 201   ExceptionTable exc_table(me);
 202 
 203   // Allocate one extra spot in our list of exceptions.  This
 204   // last entry will be used to represent the possibility that
 205   // an exception escapes the method.  See ciExceptionHandlerStream
 206   // for details.
 207   _exception_handlers =
 208     (ciExceptionHandler**)arena->Amalloc(sizeof(ciExceptionHandler*)
 209                                          * (_handler_count + 1));
 210   if (_handler_count > 0) {
 211     for (int i=0; i<_handler_count; i++) {
 212       _exception_handlers[i] = new (arena) ciExceptionHandler(
 213                                 holder(),
 214             /* start    */      exc_table.start_pc(i),
 215             /* limit    */      exc_table.end_pc(i),
 216             /* goto pc  */      exc_table.handler_pc(i),
 217             /* cp index */      exc_table.catch_type_index(i));
 218     }
 219   }
 220 
 221   // Put an entry at the end of our list to represent the possibility
 222   // of exceptional exit.
 223   _exception_handlers[_handler_count] =
 224     new (arena) ciExceptionHandler(holder(), 0, code_size(), -1, 0);
 225 
 226   if (CIPrintMethodCodes) {
 227     print_codes();
 228   }
 229 }
 230 
 231 
 232 // ------------------------------------------------------------------
 233 // ciMethod::has_linenumber_table
 234 //
 235 // length unknown until decompression
 236 bool    ciMethod::has_linenumber_table() const {
 237   check_is_loaded();
 238   VM_ENTRY_MARK;
 239   return get_methodOop()->has_linenumber_table();
 240 }
 241 
 242 
 243 // ------------------------------------------------------------------
 244 // ciMethod::compressed_linenumber_table
 245 u_char* ciMethod::compressed_linenumber_table() const {
 246   check_is_loaded();
 247   VM_ENTRY_MARK;
 248   return get_methodOop()->compressed_linenumber_table();
 249 }
 250 
 251 
 252 // ------------------------------------------------------------------
 253 // ciMethod::line_number_from_bci
 254 int ciMethod::line_number_from_bci(int bci) const {
 255   check_is_loaded();
 256   VM_ENTRY_MARK;
 257   return get_methodOop()->line_number_from_bci(bci);
 258 }
 259 
 260 
 261 // ------------------------------------------------------------------
 262 // ciMethod::vtable_index
 263 //
 264 // Get the position of this method's entry in the vtable, if any.
 265 int ciMethod::vtable_index() {
 266   check_is_loaded();
 267   assert(holder()->is_linked(), "must be linked");
 268   VM_ENTRY_MARK;
 269   return get_methodOop()->vtable_index();
 270 }
 271 
 272 
 273 #ifdef SHARK
 274 // ------------------------------------------------------------------
 275 // ciMethod::itable_index
 276 //
 277 // Get the position of this method's entry in the itable, if any.
 278 int ciMethod::itable_index() {
 279   check_is_loaded();
 280   assert(holder()->is_linked(), "must be linked");
 281   VM_ENTRY_MARK;
 282   return klassItable::compute_itable_index(get_methodOop());
 283 }
 284 #endif // SHARK
 285 
 286 
 287 // ------------------------------------------------------------------
 288 // ciMethod::native_entry
 289 //
 290 // Get the address of this method's native code, if any.
 291 address ciMethod::native_entry() {
 292   check_is_loaded();
 293   assert(flags().is_native(), "must be native method");
 294   VM_ENTRY_MARK;
 295   methodOop method = get_methodOop();
 296   address entry = method->native_function();
 297   assert(entry != NULL, "must be valid entry point");
 298   return entry;
 299 }
 300 
 301 
 302 // ------------------------------------------------------------------
 303 // ciMethod::interpreter_entry
 304 //
 305 // Get the entry point for running this method in the interpreter.
 306 address ciMethod::interpreter_entry() {
 307   check_is_loaded();
 308   VM_ENTRY_MARK;
 309   methodHandle mh(THREAD, get_methodOop());
 310   return Interpreter::entry_for_method(mh);
 311 }
 312 
 313 
 314 // ------------------------------------------------------------------
 315 // ciMethod::uses_balanced_monitors
 316 //
 317 // Does this method use monitors in a strict stack-disciplined manner?
 318 bool ciMethod::has_balanced_monitors() {
 319   check_is_loaded();
 320   if (_balanced_monitors) return true;
 321 
 322   // Analyze the method to see if monitors are used properly.
 323   VM_ENTRY_MARK;
 324   methodHandle method(THREAD, get_methodOop());
 325   assert(method->has_monitor_bytecodes(), "should have checked this");
 326 
 327   // Check to see if a previous compilation computed the
 328   // monitor-matching analysis.
 329   if (method->guaranteed_monitor_matching()) {
 330     _balanced_monitors = true;
 331     return true;
 332   }
 333 
 334   {
 335     EXCEPTION_MARK;
 336     ResourceMark rm(THREAD);
 337     GeneratePairingInfo gpi(method);
 338     gpi.compute_map(CATCH);
 339     if (!gpi.monitor_safe()) {
 340       return false;
 341     }
 342     method->set_guaranteed_monitor_matching();
 343     _balanced_monitors = true;
 344   }
 345   return true;
 346 }
 347 
 348 
 349 // ------------------------------------------------------------------
 350 // ciMethod::get_flow_analysis
 351 ciTypeFlow* ciMethod::get_flow_analysis() {
 352 #if defined(COMPILER2) || defined(SHARK)
 353   if (_flow == NULL) {
 354     ciEnv* env = CURRENT_ENV;
 355     _flow = new (env->arena()) ciTypeFlow(env, this);
 356     _flow->do_flow();
 357   }
 358   return _flow;
 359 #else // COMPILER2 || SHARK
 360   ShouldNotReachHere();
 361   return NULL;
 362 #endif // COMPILER2 || SHARK
 363 }
 364 
 365 
 366 // ------------------------------------------------------------------
 367 // ciMethod::get_osr_flow_analysis
 368 ciTypeFlow* ciMethod::get_osr_flow_analysis(int osr_bci) {
 369 #if defined(COMPILER2) || defined(SHARK)
 370   // OSR entry points are always place after a call bytecode of some sort
 371   assert(osr_bci >= 0, "must supply valid OSR entry point");
 372   ciEnv* env = CURRENT_ENV;
 373   ciTypeFlow* flow = new (env->arena()) ciTypeFlow(env, this, osr_bci);
 374   flow->do_flow();
 375   return flow;
 376 #else // COMPILER2 || SHARK
 377   ShouldNotReachHere();
 378   return NULL;
 379 #endif // COMPILER2 || SHARK
 380 }
 381 
 382 // ------------------------------------------------------------------
 383 // ciMethod::raw_liveness_at_bci
 384 //
 385 // Which local variables are live at a specific bci?
 386 MethodLivenessResult ciMethod::raw_liveness_at_bci(int bci) {
 387   check_is_loaded();
 388   if (_liveness == NULL) {
 389     // Create the liveness analyzer.
 390     Arena* arena = CURRENT_ENV->arena();
 391     _liveness = new (arena) MethodLiveness(arena, this);
 392     _liveness->compute_liveness();
 393   }
 394   return _liveness->get_liveness_at(bci);
 395 }
 396 
 397 // ------------------------------------------------------------------
 398 // ciMethod::liveness_at_bci
 399 //
 400 // Which local variables are live at a specific bci?  When debugging
 401 // will return true for all locals in some cases to improve debug
 402 // information.
 403 MethodLivenessResult ciMethod::liveness_at_bci(int bci) {
 404   MethodLivenessResult result = raw_liveness_at_bci(bci);
 405   if (CURRENT_ENV->jvmti_can_access_local_variables() || DeoptimizeALot || CompileTheWorld) {
 406     // Keep all locals live for the user's edification and amusement.
 407     result.at_put_range(0, result.size(), true);
 408   }
 409   return result;
 410 }
 411 
 412 // ciMethod::live_local_oops_at_bci
 413 //
 414 // find all the live oops in the locals array for a particular bci
 415 // Compute what the interpreter believes by using the interpreter
 416 // oopmap generator. This is used as a double check during osr to
 417 // guard against conservative result from MethodLiveness making us
 418 // think a dead oop is live.  MethodLiveness is conservative in the
 419 // sense that it may consider locals to be live which cannot be live,
 420 // like in the case where a local could contain an oop or  a primitive
 421 // along different paths.  In that case the local must be dead when
 422 // those paths merge. Since the interpreter's viewpoint is used when
 423 // gc'ing an interpreter frame we need to use its viewpoint  during
 424 // OSR when loading the locals.
 425 
 426 BitMap ciMethod::live_local_oops_at_bci(int bci) {
 427   VM_ENTRY_MARK;
 428   InterpreterOopMap mask;
 429   OopMapCache::compute_one_oop_map(get_methodOop(), bci, &mask);
 430   int mask_size = max_locals();
 431   BitMap result(mask_size);
 432   result.clear();
 433   int i;
 434   for (i = 0; i < mask_size ; i++ ) {
 435     if (mask.is_oop(i)) result.set_bit(i);
 436   }
 437   return result;
 438 }
 439 
 440 
 441 #ifdef COMPILER1
 442 // ------------------------------------------------------------------
 443 // ciMethod::bci_block_start
 444 //
 445 // Marks all bcis where a new basic block starts
 446 const BitMap ciMethod::bci_block_start() {
 447   check_is_loaded();
 448   if (_liveness == NULL) {
 449     // Create the liveness analyzer.
 450     Arena* arena = CURRENT_ENV->arena();
 451     _liveness = new (arena) MethodLiveness(arena, this);
 452     _liveness->compute_liveness();
 453   }
 454 
 455   return _liveness->get_bci_block_start();
 456 }
 457 #endif // COMPILER1
 458 
 459 
 460 // ------------------------------------------------------------------
 461 // ciMethod::call_profile_at_bci
 462 //
 463 // Get the ciCallProfile for the invocation of this method.
 464 // Also reports receiver types for non-call type checks (if TypeProfileCasts).
 465 ciCallProfile ciMethod::call_profile_at_bci(int bci) {
 466   ResourceMark rm;
 467   ciCallProfile result;
 468   if (method_data() != NULL && method_data()->is_mature()) {
 469     ciProfileData* data = method_data()->bci_to_data(bci);
 470     if (data != NULL && data->is_CounterData()) {
 471       // Every profiled call site has a counter.
 472       int count = data->as_CounterData()->count();
 473 
 474       if (!data->is_ReceiverTypeData()) {
 475         result._receiver_count[0] = 0;  // that's a definite zero
 476       } else { // ReceiverTypeData is a subclass of CounterData
 477         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
 478         // In addition, virtual call sites have receiver type information
 479         int receivers_count_total = 0;
 480         int morphism = 0;
 481         // Precompute morphism for the possible fixup
 482         for (uint i = 0; i < call->row_limit(); i++) {
 483           ciKlass* receiver = call->receiver(i);
 484           if (receiver == NULL)  continue;
 485           morphism++;
 486         }
 487         int epsilon = 0;
 488         if (TieredCompilation && ProfileInterpreter) {
 489           // Interpreter and C1 treat final and special invokes differently.
 490           // C1 will record a type, whereas the interpreter will just
 491           // increment the count. Detect this case.
 492           if (morphism == 1 && count > 0) {
 493             epsilon = count;
 494             count = 0;
 495           }
 496         }
 497         for (uint i = 0; i < call->row_limit(); i++) {
 498           ciKlass* receiver = call->receiver(i);
 499           if (receiver == NULL)  continue;
 500           int rcount = call->receiver_count(i) + epsilon;
 501           if (rcount == 0) rcount = 1; // Should be valid value
 502           receivers_count_total += rcount;
 503           // Add the receiver to result data.
 504           result.add_receiver(receiver, rcount);
 505           // If we extend profiling to record methods,
 506           // we will set result._method also.
 507         }
 508         // Determine call site's morphism.
 509         // The call site count is 0 with known morphism (onlt 1 or 2 receivers)
 510         // or < 0 in the case of a type check failured for checkcast, aastore, instanceof.
 511         // The call site count is > 0 in the case of a polymorphic virtual call.
 512         if (morphism > 0 && morphism == result._limit) {
 513            // The morphism <= MorphismLimit.
 514            if ((morphism <  ciCallProfile::MorphismLimit) ||
 515                (morphism == ciCallProfile::MorphismLimit && count == 0)) {
 516 #ifdef ASSERT
 517              if (count > 0) {
 518                this->print_short_name(tty);
 519                tty->print_cr(" @ bci:%d", bci);
 520                this->print_codes();
 521                assert(false, "this call site should not be polymorphic");
 522              }
 523 #endif
 524              result._morphism = morphism;
 525            }
 526         }
 527         // Make the count consistent if this is a call profile. If count is
 528         // zero or less, presume that this is a typecheck profile and
 529         // do nothing.  Otherwise, increase count to be the sum of all
 530         // receiver's counts.
 531         if (count >= 0) {
 532           count += receivers_count_total;
 533         }
 534       }
 535       result._count = count;
 536     }
 537   }
 538   return result;
 539 }
 540 
 541 // ------------------------------------------------------------------
 542 // Add new receiver and sort data by receiver's profile count.
 543 void ciCallProfile::add_receiver(ciKlass* receiver, int receiver_count) {
 544   // Add new receiver and sort data by receiver's counts when we have space
 545   // for it otherwise replace the less called receiver (less called receiver
 546   // is placed to the last array element which is not used).
 547   // First array's element contains most called receiver.
 548   int i = _limit;
 549   for (; i > 0 && receiver_count > _receiver_count[i-1]; i--) {
 550     _receiver[i] = _receiver[i-1];
 551     _receiver_count[i] = _receiver_count[i-1];
 552   }
 553   _receiver[i] = receiver;
 554   _receiver_count[i] = receiver_count;
 555   if (_limit < MorphismLimit) _limit++;
 556 }
 557 
 558 // ------------------------------------------------------------------
 559 // ciMethod::find_monomorphic_target
 560 //
 561 // Given a certain calling environment, find the monomorphic target
 562 // for the call.  Return NULL if the call is not monomorphic in
 563 // its calling environment, or if there are only abstract methods.
 564 // The returned method is never abstract.
 565 // Note: If caller uses a non-null result, it must inform dependencies
 566 // via assert_unique_concrete_method or assert_leaf_type.
 567 ciMethod* ciMethod::find_monomorphic_target(ciInstanceKlass* caller,
 568                                             ciInstanceKlass* callee_holder,
 569                                             ciInstanceKlass* actual_recv) {
 570   check_is_loaded();
 571 
 572   if (actual_recv->is_interface()) {
 573     // %%% We cannot trust interface types, yet.  See bug 6312651.
 574     return NULL;
 575   }
 576 
 577   ciMethod* root_m = resolve_invoke(caller, actual_recv);
 578   if (root_m == NULL) {
 579     // Something went wrong looking up the actual receiver method.
 580     return NULL;
 581   }
 582   assert(!root_m->is_abstract(), "resolve_invoke promise");
 583 
 584   // Make certain quick checks even if UseCHA is false.
 585 
 586   // Is it private or final?
 587   if (root_m->can_be_statically_bound()) {
 588     return root_m;
 589   }
 590 
 591   if (actual_recv->is_leaf_type() && actual_recv == root_m->holder()) {
 592     // Easy case.  There is no other place to put a method, so don't bother
 593     // to go through the VM_ENTRY_MARK and all the rest.
 594     return root_m;
 595   }
 596 
 597   // Array methods (clone, hashCode, etc.) are always statically bound.
 598   // If we were to see an array type here, we'd return root_m.
 599   // However, this method processes only ciInstanceKlasses.  (See 4962591.)
 600   // The inline_native_clone intrinsic narrows Object to T[] properly,
 601   // so there is no need to do the same job here.
 602 
 603   if (!UseCHA)  return NULL;
 604 
 605   VM_ENTRY_MARK;
 606 
 607   methodHandle target;
 608   {
 609     MutexLocker locker(Compile_lock);
 610     klassOop context = actual_recv->get_klassOop();
 611     target = Dependencies::find_unique_concrete_method(context,
 612                                                        root_m->get_methodOop());
 613     // %%% Should upgrade this ciMethod API to look for 1 or 2 concrete methods.
 614   }
 615 
 616 #ifndef PRODUCT
 617   if (TraceDependencies && target() != NULL && target() != root_m->get_methodOop()) {
 618     tty->print("found a non-root unique target method");
 619     tty->print_cr("  context = %s", instanceKlass::cast(actual_recv->get_klassOop())->external_name());
 620     tty->print("  method  = ");
 621     target->print_short_name(tty);
 622     tty->cr();
 623   }
 624 #endif //PRODUCT
 625 
 626   if (target() == NULL) {
 627     return NULL;
 628   }
 629   if (target() == root_m->get_methodOop()) {
 630     return root_m;
 631   }
 632   if (!root_m->is_public() &&
 633       !root_m->is_protected()) {
 634     // If we are going to reason about inheritance, it's easiest
 635     // if the method in question is public, protected, or private.
 636     // If the answer is not root_m, it is conservatively correct
 637     // to return NULL, even if the CHA encountered irrelevant
 638     // methods in other packages.
 639     // %%% TO DO: Work out logic for package-private methods
 640     // with the same name but different vtable indexes.
 641     return NULL;
 642   }
 643   return CURRENT_THREAD_ENV->get_object(target())->as_method();
 644 }
 645 
 646 // ------------------------------------------------------------------
 647 // ciMethod::resolve_invoke
 648 //
 649 // Given a known receiver klass, find the target for the call.
 650 // Return NULL if the call has no target or the target is abstract.
 651 ciMethod* ciMethod::resolve_invoke(ciKlass* caller, ciKlass* exact_receiver) {
 652    check_is_loaded();
 653    VM_ENTRY_MARK;
 654 
 655    KlassHandle caller_klass (THREAD, caller->get_klassOop());
 656    KlassHandle h_recv       (THREAD, exact_receiver->get_klassOop());
 657    KlassHandle h_resolved   (THREAD, holder()->get_klassOop());
 658    Symbol* h_name      = name()->get_symbol();
 659    Symbol* h_signature = signature()->get_symbol();
 660 
 661    methodHandle m;
 662    // Only do exact lookup if receiver klass has been linked.  Otherwise,
 663    // the vtable has not been setup, and the LinkResolver will fail.
 664    if (h_recv->oop_is_javaArray()
 665         ||
 666        instanceKlass::cast(h_recv())->is_linked() && !exact_receiver->is_interface()) {
 667      if (holder()->is_interface()) {
 668        m = LinkResolver::resolve_interface_call_or_null(h_recv, h_resolved, h_name, h_signature, caller_klass);
 669      } else {
 670        m = LinkResolver::resolve_virtual_call_or_null(h_recv, h_resolved, h_name, h_signature, caller_klass);
 671      }
 672    }
 673 
 674    if (m.is_null()) {
 675      // Return NULL only if there was a problem with lookup (uninitialized class, etc.)
 676      return NULL;
 677    }
 678 
 679    ciMethod* result = this;
 680    if (m() != get_methodOop()) {
 681      result = CURRENT_THREAD_ENV->get_object(m())->as_method();
 682    }
 683 
 684    // Don't return abstract methods because they aren't
 685    // optimizable or interesting.
 686    if (result->is_abstract()) {
 687      return NULL;
 688    } else {
 689      return result;
 690    }
 691 }
 692 
 693 // ------------------------------------------------------------------
 694 // ciMethod::resolve_vtable_index
 695 //
 696 // Given a known receiver klass, find the vtable index for the call.
 697 // Return methodOopDesc::invalid_vtable_index if the vtable_index is unknown.
 698 int ciMethod::resolve_vtable_index(ciKlass* caller, ciKlass* receiver) {
 699    check_is_loaded();
 700 
 701    int vtable_index = methodOopDesc::invalid_vtable_index;
 702    // Only do lookup if receiver klass has been linked.  Otherwise,
 703    // the vtable has not been setup, and the LinkResolver will fail.
 704    if (!receiver->is_interface()
 705        && (!receiver->is_instance_klass() ||
 706            receiver->as_instance_klass()->is_linked())) {
 707      VM_ENTRY_MARK;
 708 
 709      KlassHandle caller_klass (THREAD, caller->get_klassOop());
 710      KlassHandle h_recv       (THREAD, receiver->get_klassOop());
 711      Symbol* h_name = name()->get_symbol();
 712      Symbol* h_signature = signature()->get_symbol();
 713 
 714      vtable_index = LinkResolver::resolve_virtual_vtable_index(h_recv, h_recv, h_name, h_signature, caller_klass);
 715      if (vtable_index == methodOopDesc::nonvirtual_vtable_index) {
 716        // A statically bound method.  Return "no such index".
 717        vtable_index = methodOopDesc::invalid_vtable_index;
 718      }
 719    }
 720 
 721    return vtable_index;
 722 }
 723 
 724 // ------------------------------------------------------------------
 725 // ciMethod::interpreter_call_site_count
 726 int ciMethod::interpreter_call_site_count(int bci) {
 727   if (method_data() != NULL) {
 728     ResourceMark rm;
 729     ciProfileData* data = method_data()->bci_to_data(bci);
 730     if (data != NULL && data->is_CounterData()) {
 731       return scale_count(data->as_CounterData()->count());
 732     }
 733   }
 734   return -1;  // unknown
 735 }
 736 
 737 // ------------------------------------------------------------------
 738 // Adjust a CounterData count to be commensurate with
 739 // interpreter_invocation_count.  If the MDO exists for
 740 // only 25% of the time the method exists, then the
 741 // counts in the MDO should be scaled by 4X, so that
 742 // they can be usefully and stably compared against the
 743 // invocation counts in methods.
 744 int ciMethod::scale_count(int count, float prof_factor) {
 745   if (count > 0 && method_data() != NULL) {
 746     int counter_life;
 747     int method_life = interpreter_invocation_count();
 748     if (TieredCompilation) {
 749       // In tiered the MDO's life is measured directly, so just use the snapshotted counters
 750       counter_life = MAX2(method_data()->invocation_count(), method_data()->backedge_count());
 751     } else {
 752       int current_mileage = method_data()->current_mileage();
 753       int creation_mileage = method_data()->creation_mileage();
 754       counter_life = current_mileage - creation_mileage;
 755     }
 756 
 757     // counter_life due to backedge_counter could be > method_life
 758     if (counter_life > method_life)
 759       counter_life = method_life;
 760     if (0 < counter_life && counter_life <= method_life) {
 761       count = (int)((double)count * prof_factor * method_life / counter_life + 0.5);
 762       count = (count > 0) ? count : 1;
 763     }
 764   }
 765   return count;
 766 }
 767 
 768 // ------------------------------------------------------------------
 769 // invokedynamic support
 770 
 771 // ------------------------------------------------------------------
 772 // ciMethod::is_method_handle_invoke
 773 //
 774 // Return true if the method is an instance of one of the two
 775 // signature-polymorphic MethodHandle methods, invokeExact or invokeGeneric.
 776 bool ciMethod::is_method_handle_invoke() const {
 777   if (!is_loaded()) {
 778     bool flag = (holder()->name() == ciSymbol::java_lang_invoke_MethodHandle() &&
 779                  methodOopDesc::is_method_handle_invoke_name(name()->sid()));
 780     return flag;
 781   }
 782   VM_ENTRY_MARK;
 783   return get_methodOop()->is_method_handle_invoke();
 784 }
 785 
 786 // ------------------------------------------------------------------
 787 // ciMethod::is_method_handle_adapter
 788 //
 789 // Return true if the method is a generated MethodHandle adapter.
 790 // These are built by MethodHandleCompiler.
 791 bool ciMethod::is_method_handle_adapter() const {
 792   if (!is_loaded())  return false;
 793   VM_ENTRY_MARK;
 794   return get_methodOop()->is_method_handle_adapter();
 795 }
 796 
 797 ciInstance* ciMethod::method_handle_type() {
 798   check_is_loaded();
 799   VM_ENTRY_MARK;
 800   oop mtype = get_methodOop()->method_handle_type();
 801   return CURRENT_THREAD_ENV->get_object(mtype)->as_instance();
 802 }
 803 
 804 
 805 // ------------------------------------------------------------------
 806 // ciMethod::ensure_method_data
 807 //
 808 // Generate new methodDataOop objects at compile time.
 809 // Return true if allocation was successful or no MDO is required.
 810 bool ciMethod::ensure_method_data(methodHandle h_m) {
 811   EXCEPTION_CONTEXT;
 812   if (is_native() || is_abstract() || h_m()->is_accessor()) return true;
 813   if (h_m()->method_data() == NULL) {
 814     methodOopDesc::build_interpreter_method_data(h_m, THREAD);
 815     if (HAS_PENDING_EXCEPTION) {
 816       CLEAR_PENDING_EXCEPTION;
 817     }
 818   }
 819   if (h_m()->method_data() != NULL) {
 820     _method_data = CURRENT_ENV->get_object(h_m()->method_data())->as_method_data();
 821     _method_data->load_data();
 822     return true;
 823   } else {
 824     _method_data = CURRENT_ENV->get_empty_methodData();
 825     return false;
 826   }
 827 }
 828 
 829 // public, retroactive version
 830 bool ciMethod::ensure_method_data() {
 831   bool result = true;
 832   if (_method_data == NULL || _method_data->is_empty()) {
 833     GUARDED_VM_ENTRY({
 834       result = ensure_method_data(get_methodOop());
 835     });
 836   }
 837   return result;
 838 }
 839 
 840 
 841 // ------------------------------------------------------------------
 842 // ciMethod::method_data
 843 //
 844 ciMethodData* ciMethod::method_data() {
 845   if (_method_data != NULL) {
 846     return _method_data;
 847   }
 848   VM_ENTRY_MARK;
 849   ciEnv* env = CURRENT_ENV;
 850   Thread* my_thread = JavaThread::current();
 851   methodHandle h_m(my_thread, get_methodOop());
 852 
 853   if (h_m()->method_data() != NULL) {
 854     _method_data = CURRENT_ENV->get_object(h_m()->method_data())->as_method_data();
 855     _method_data->load_data();
 856   } else {
 857     _method_data = CURRENT_ENV->get_empty_methodData();
 858   }
 859   return _method_data;
 860 
 861 }
 862 
 863 // ------------------------------------------------------------------
 864 // ciMethod::method_data_or_null
 865 // Returns a pointer to ciMethodData if MDO exists on the VM side,
 866 // NULL otherwise.
 867 ciMethodData* ciMethod::method_data_or_null() {
 868   ciMethodData *md = method_data();
 869   if (md->is_empty()) return NULL;
 870   return md;
 871 }
 872 
 873 // ------------------------------------------------------------------
 874 // ciMethod::will_link
 875 //
 876 // Will this method link in a specific calling context?
 877 bool ciMethod::will_link(ciKlass* accessing_klass,
 878                          ciKlass* declared_method_holder,
 879                          Bytecodes::Code bc) {
 880   if (!is_loaded()) {
 881     // Method lookup failed.
 882     return false;
 883   }
 884 
 885   // The link checks have been front-loaded into the get_method
 886   // call.  This method (ciMethod::will_link()) will be removed
 887   // in the future.
 888 
 889   return true;
 890 }
 891 
 892 // ------------------------------------------------------------------
 893 // ciMethod::should_exclude
 894 //
 895 // Should this method be excluded from compilation?
 896 bool ciMethod::should_exclude() {
 897   check_is_loaded();
 898   VM_ENTRY_MARK;
 899   methodHandle mh(THREAD, get_methodOop());
 900   bool ignore;
 901   return CompilerOracle::should_exclude(mh, ignore);
 902 }
 903 
 904 // ------------------------------------------------------------------
 905 // ciMethod::should_inline
 906 //
 907 // Should this method be inlined during compilation?
 908 bool ciMethod::should_inline() {
 909   check_is_loaded();
 910   VM_ENTRY_MARK;
 911   methodHandle mh(THREAD, get_methodOop());
 912   return CompilerOracle::should_inline(mh);
 913 }
 914 
 915 // ------------------------------------------------------------------
 916 // ciMethod::should_not_inline
 917 //
 918 // Should this method be disallowed from inlining during compilation?
 919 bool ciMethod::should_not_inline() {
 920   check_is_loaded();
 921   VM_ENTRY_MARK;
 922   methodHandle mh(THREAD, get_methodOop());
 923   return CompilerOracle::should_not_inline(mh);
 924 }
 925 
 926 // ------------------------------------------------------------------
 927 // ciMethod::should_print_assembly
 928 //
 929 // Should the compiler print the generated code for this method?
 930 bool ciMethod::should_print_assembly() {
 931   check_is_loaded();
 932   VM_ENTRY_MARK;
 933   methodHandle mh(THREAD, get_methodOop());
 934   return CompilerOracle::should_print(mh);
 935 }
 936 
 937 // ------------------------------------------------------------------
 938 // ciMethod::break_at_execute
 939 //
 940 // Should the compiler insert a breakpoint into the generated code
 941 // method?
 942 bool ciMethod::break_at_execute() {
 943   check_is_loaded();
 944   VM_ENTRY_MARK;
 945   methodHandle mh(THREAD, get_methodOop());
 946   return CompilerOracle::should_break_at(mh);
 947 }
 948 
 949 // ------------------------------------------------------------------
 950 // ciMethod::has_option
 951 //
 952 bool ciMethod::has_option(const char* option) {
 953   check_is_loaded();
 954   VM_ENTRY_MARK;
 955   methodHandle mh(THREAD, get_methodOop());
 956   return CompilerOracle::has_option_string(mh, option);
 957 }
 958 
 959 // ------------------------------------------------------------------
 960 // ciMethod::can_be_compiled
 961 //
 962 // Have previous compilations of this method succeeded?
 963 bool ciMethod::can_be_compiled() {
 964   check_is_loaded();
 965   ciEnv* env = CURRENT_ENV;
 966   if (is_c1_compile(env->comp_level())) {
 967     return _is_c1_compilable;
 968   }
 969   return _is_c2_compilable;
 970 }
 971 
 972 // ------------------------------------------------------------------
 973 // ciMethod::set_not_compilable
 974 //
 975 // Tell the VM that this method cannot be compiled at all.
 976 void ciMethod::set_not_compilable() {
 977   check_is_loaded();
 978   VM_ENTRY_MARK;
 979   ciEnv* env = CURRENT_ENV;
 980   if (is_c1_compile(env->comp_level())) {
 981     _is_c1_compilable = false;
 982   } else {
 983     _is_c2_compilable = false;
 984   }
 985   get_methodOop()->set_not_compilable(env->comp_level());
 986 }
 987 
 988 // ------------------------------------------------------------------
 989 // ciMethod::can_be_osr_compiled
 990 //
 991 // Have previous compilations of this method succeeded?
 992 //
 993 // Implementation note: the VM does not currently keep track
 994 // of failed OSR compilations per bci.  The entry_bci parameter
 995 // is currently unused.
 996 bool ciMethod::can_be_osr_compiled(int entry_bci) {
 997   check_is_loaded();
 998   VM_ENTRY_MARK;
 999   ciEnv* env = CURRENT_ENV;
1000   return !get_methodOop()->is_not_osr_compilable(env->comp_level());
1001 }
1002 
1003 // ------------------------------------------------------------------
1004 // ciMethod::has_compiled_code
1005 bool ciMethod::has_compiled_code() {
1006   VM_ENTRY_MARK;
1007   return get_methodOop()->code() != NULL;
1008 }
1009 
1010 int ciMethod::comp_level() {
1011   check_is_loaded();
1012   VM_ENTRY_MARK;
1013   nmethod* nm = get_methodOop()->code();
1014   if (nm != NULL) return nm->comp_level();
1015   return 0;
1016 }
1017 
1018 int ciMethod::highest_osr_comp_level() {
1019   check_is_loaded();
1020   VM_ENTRY_MARK;
1021   return get_methodOop()->highest_osr_comp_level();
1022 }
1023 
1024 // ------------------------------------------------------------------
1025 // ciMethod::code_size_for_inlining
1026 //
1027 // Code size for inlining decisions.
1028 //
1029 // Don't fully count method handle adapters against inlining budgets:
1030 // the metric we use here is the number of call sites in the adapter
1031 // as they are probably the instructions which generate some code.
1032 int ciMethod::code_size_for_inlining() {
1033   check_is_loaded();
1034 
1035   // Method handle adapters
1036   if (is_method_handle_adapter()) {
1037     // Count call sites
1038     int call_site_count = 0;
1039     ciBytecodeStream iter(this);
1040     while (iter.next() != ciBytecodeStream::EOBC()) {
1041       if (Bytecodes::is_invoke(iter.cur_bc())) {
1042         call_site_count++;
1043       }
1044     }
1045     return call_site_count;
1046   }
1047 
1048   // Normal method
1049   return code_size();
1050 }
1051 
1052 // ------------------------------------------------------------------
1053 // ciMethod::instructions_size
1054 //
1055 // This is a rough metric for "fat" methods, compared before inlining
1056 // with InlineSmallCode.  The CodeBlob::code_size accessor includes
1057 // junk like exception handler, stubs, and constant table, which are
1058 // not highly relevant to an inlined method.  So we use the more
1059 // specific accessor nmethod::insts_size.
1060 int ciMethod::instructions_size(int comp_level) {
1061   GUARDED_VM_ENTRY(
1062     nmethod* code = get_methodOop()->code();
1063     if (code != NULL && (comp_level == CompLevel_any || comp_level == code->comp_level())) {
1064       return code->insts_end() - code->verified_entry_point();
1065     }
1066     return 0;
1067   )
1068 }
1069 
1070 // ------------------------------------------------------------------
1071 // ciMethod::log_nmethod_identity
1072 void ciMethod::log_nmethod_identity(xmlStream* log) {
1073   GUARDED_VM_ENTRY(
1074     nmethod* code = get_methodOop()->code();
1075     if (code != NULL) {
1076       code->log_identity(log);
1077     }
1078   )
1079 }
1080 
1081 // ------------------------------------------------------------------
1082 // ciMethod::is_not_reached
1083 bool ciMethod::is_not_reached(int bci) {
1084   check_is_loaded();
1085   VM_ENTRY_MARK;
1086   return Interpreter::is_not_reached(
1087                methodHandle(THREAD, get_methodOop()), bci);
1088 }
1089 
1090 // ------------------------------------------------------------------
1091 // ciMethod::was_never_executed
1092 bool ciMethod::was_executed_more_than(int times) {
1093   VM_ENTRY_MARK;
1094   return get_methodOop()->was_executed_more_than(times);
1095 }
1096 
1097 // ------------------------------------------------------------------
1098 // ciMethod::has_unloaded_classes_in_signature
1099 bool ciMethod::has_unloaded_classes_in_signature() {
1100   VM_ENTRY_MARK;
1101   {
1102     EXCEPTION_MARK;
1103     methodHandle m(THREAD, get_methodOop());
1104     bool has_unloaded = methodOopDesc::has_unloaded_classes_in_signature(m, (JavaThread *)THREAD);
1105     if( HAS_PENDING_EXCEPTION ) {
1106       CLEAR_PENDING_EXCEPTION;
1107       return true;     // Declare that we may have unloaded classes
1108     }
1109     return has_unloaded;
1110   }
1111 }
1112 
1113 // ------------------------------------------------------------------
1114 // ciMethod::is_klass_loaded
1115 bool ciMethod::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
1116   VM_ENTRY_MARK;
1117   return get_methodOop()->is_klass_loaded(refinfo_index, must_be_resolved);
1118 }
1119 
1120 // ------------------------------------------------------------------
1121 // ciMethod::check_call
1122 bool ciMethod::check_call(int refinfo_index, bool is_static) const {
1123   VM_ENTRY_MARK;
1124   {
1125     EXCEPTION_MARK;
1126     HandleMark hm(THREAD);
1127     constantPoolHandle pool (THREAD, get_methodOop()->constants());
1128     methodHandle spec_method;
1129     KlassHandle  spec_klass;
1130     LinkResolver::resolve_method(spec_method, spec_klass, pool, refinfo_index, THREAD);
1131     if (HAS_PENDING_EXCEPTION) {
1132       CLEAR_PENDING_EXCEPTION;
1133       return false;
1134     } else {
1135       return (spec_method->is_static() == is_static);
1136     }
1137   }
1138   return false;
1139 }
1140 
1141 // ------------------------------------------------------------------
1142 // ciMethod::print_codes
1143 //
1144 // Print the bytecodes for this method.
1145 void ciMethod::print_codes_on(outputStream* st) {
1146   check_is_loaded();
1147   GUARDED_VM_ENTRY(get_methodOop()->print_codes_on(st);)
1148 }
1149 
1150 
1151 #define FETCH_FLAG_FROM_VM(flag_accessor) { \
1152   check_is_loaded(); \
1153   VM_ENTRY_MARK; \
1154   return get_methodOop()->flag_accessor(); \
1155 }
1156 
1157 bool ciMethod::is_empty_method() const {         FETCH_FLAG_FROM_VM(is_empty_method); }
1158 bool ciMethod::is_vanilla_constructor() const {  FETCH_FLAG_FROM_VM(is_vanilla_constructor); }
1159 bool ciMethod::has_loops      () const {         FETCH_FLAG_FROM_VM(has_loops); }
1160 bool ciMethod::has_jsrs       () const {         FETCH_FLAG_FROM_VM(has_jsrs);  }
1161 bool ciMethod::is_accessor    () const {         FETCH_FLAG_FROM_VM(is_accessor); }
1162 bool ciMethod::is_initializer () const {         FETCH_FLAG_FROM_VM(is_initializer); }
1163 
1164 BCEscapeAnalyzer  *ciMethod::get_bcea() {
1165 #ifdef COMPILER2
1166   if (_bcea == NULL) {
1167     _bcea = new (CURRENT_ENV->arena()) BCEscapeAnalyzer(this, NULL);
1168   }
1169   return _bcea;
1170 #else // COMPILER2
1171   ShouldNotReachHere();
1172   return NULL;
1173 #endif // COMPILER2
1174 }
1175 
1176 ciMethodBlocks  *ciMethod::get_method_blocks() {
1177   Arena *arena = CURRENT_ENV->arena();
1178   if (_method_blocks == NULL) {
1179     _method_blocks = new (arena) ciMethodBlocks(arena, this);
1180   }
1181   return _method_blocks;
1182 }
1183 
1184 #undef FETCH_FLAG_FROM_VM
1185 
1186 
1187 // ------------------------------------------------------------------
1188 // ciMethod::print_codes
1189 //
1190 // Print a range of the bytecodes for this method.
1191 void ciMethod::print_codes_on(int from, int to, outputStream* st) {
1192   check_is_loaded();
1193   GUARDED_VM_ENTRY(get_methodOop()->print_codes_on(from, to, st);)
1194 }
1195 
1196 // ------------------------------------------------------------------
1197 // ciMethod::print_name
1198 //
1199 // Print the name of this method, including signature and some flags.
1200 void ciMethod::print_name(outputStream* st) {
1201   check_is_loaded();
1202   GUARDED_VM_ENTRY(get_methodOop()->print_name(st);)
1203 }
1204 
1205 // ------------------------------------------------------------------
1206 // ciMethod::print_short_name
1207 //
1208 // Print the name of this method, without signature.
1209 void ciMethod::print_short_name(outputStream* st) {
1210   check_is_loaded();
1211   GUARDED_VM_ENTRY(get_methodOop()->print_short_name(st);)
1212 }
1213 
1214 // ------------------------------------------------------------------
1215 // ciMethod::print_impl
1216 //
1217 // Implementation of the print method.
1218 void ciMethod::print_impl(outputStream* st) {
1219   ciObject::print_impl(st);
1220   st->print(" name=");
1221   name()->print_symbol_on(st);
1222   st->print(" holder=");
1223   holder()->print_name_on(st);
1224   st->print(" signature=");
1225   signature()->as_symbol()->print_symbol_on(st);
1226   if (is_loaded()) {
1227     st->print(" loaded=true flags=");
1228     flags().print_member_flags(st);
1229   } else {
1230     st->print(" loaded=false");
1231   }
1232 }