1 /*
   2  * Copyright 2008-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 /*
  26  * JSR 292 reference implementation: method handle structure analysis
  27  */
  28 
  29 #include "incls/_precompiled.incl"
  30 #include "incls/_methodHandleWalk.cpp.incl"
  31 
  32 
  33 // -----------------------------------------------------------------------------
  34 // MethodHandleChain
  35 
  36 void MethodHandleChain::set_method_handle(Handle mh, TRAPS) {
  37   if (!java_dyn_MethodHandle::is_instance(mh()))  lose("bad method handle", CHECK);
  38 
  39   // set current method handle and unpack partially
  40   _method_handle = mh;
  41   _is_last       = false;
  42   _is_bound      = false;
  43   _arg_slot      = -1;
  44   _arg_type      = T_VOID;
  45   _conversion    = -1;
  46   _last_invoke   = Bytecodes::_nop;  //arbitrary non-garbage
  47 
  48   if (sun_dyn_DirectMethodHandle::is_instance(mh())) {
  49     set_last_method(mh(), THREAD);
  50     return;
  51   }
  52   if (sun_dyn_AdapterMethodHandle::is_instance(mh())) {
  53     _conversion = AdapterMethodHandle_conversion();
  54     assert(_conversion != -1, "bad conv value");
  55     assert(sun_dyn_BoundMethodHandle::is_instance(mh()), "also BMH");
  56   }
  57   if (sun_dyn_BoundMethodHandle::is_instance(mh())) {
  58     if (!is_adapter())          // keep AMH and BMH separate in this model
  59       _is_bound = true;
  60     _arg_slot = BoundMethodHandle_vmargslot();
  61     oop target = MethodHandle_vmtarget_oop();
  62     if (!is_bound() || java_dyn_MethodHandle::is_instance(target)) {
  63       _arg_type = compute_bound_arg_type(target, NULL, _arg_slot, CHECK);
  64     } else if (target != NULL && target->is_method()) {
  65       methodOop m = (methodOop) target;
  66       _arg_type = compute_bound_arg_type(NULL, m, _arg_slot, CHECK);
  67       set_last_method(mh(), CHECK);
  68     } else {
  69       _is_bound = false;  // lose!
  70     }
  71   }
  72   if (is_bound() && _arg_type == T_VOID) {
  73     lose("bad vmargslot", CHECK);
  74   }
  75   if (!is_bound() && !is_adapter()) {
  76     lose("unrecognized MH type", CHECK);
  77   }
  78 }
  79 
  80 
  81 void MethodHandleChain::set_last_method(oop target, TRAPS) {
  82   _is_last = true;
  83   klassOop receiver_limit_oop = NULL;
  84   int flags = 0;
  85   methodOop m = MethodHandles::decode_method(target, receiver_limit_oop, flags);
  86   _last_method = methodHandle(THREAD, m);
  87   if ((flags & MethodHandles::_dmf_has_receiver) == 0)
  88     _last_invoke = Bytecodes::_invokestatic;
  89   else if ((flags & MethodHandles::_dmf_does_dispatch) == 0)
  90     _last_invoke = Bytecodes::_invokespecial;
  91   else if ((flags & MethodHandles::_dmf_from_interface) != 0)
  92     _last_invoke = Bytecodes::_invokeinterface;
  93   else
  94     _last_invoke = Bytecodes::_invokevirtual;
  95 }
  96 
  97 
  98 BasicType MethodHandleChain::compute_bound_arg_type(oop target, methodOop m, int arg_slot, TRAPS) {
  99   // There is no direct indication of whether the argument is primitive or not.
 100   // It is implied by the _vmentry code, and by the MethodType of the target.
 101   // FIXME: Make it explicit MethodHandleImpl refactors out from MethodHandle
 102   BasicType arg_type = T_VOID;
 103   if (target != NULL) {
 104     oop mtype = java_dyn_MethodHandle::type(target);
 105     int arg_num = MethodHandles::argument_slot_to_argnum(mtype, arg_slot);
 106     if (arg_num >= 0) {
 107       oop ptype = java_dyn_MethodType::ptype(mtype, arg_num);
 108       arg_type = java_lang_Class::as_BasicType(ptype);
 109     }
 110   } else if (m != NULL) {
 111     // figure out the argument type from the slot
 112     // FIXME: make this explicit in the MH
 113     int cur_slot = m->size_of_parameters();
 114     if (!m->is_static()) {
 115       cur_slot -= type2size[T_OBJECT];
 116       if (cur_slot == arg_slot)
 117         arg_type = T_OBJECT;
 118     }
 119     for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
 120       BasicType bt = ss.type();
 121       cur_slot -= type2size[bt];
 122       if (cur_slot <= arg_slot) {
 123         if (cur_slot == arg_slot)
 124           arg_type = bt;
 125         break;
 126       }
 127     }
 128   }
 129   if (arg_type == T_ARRAY)
 130     arg_type = T_OBJECT;
 131   return arg_type;
 132 }
 133 
 134 
 135 void MethodHandleChain::lose(const char* msg, TRAPS) {
 136   assert(false, "lose");
 137   _lose_message = msg;
 138   if (!THREAD->is_Java_thread() || ((JavaThread*)THREAD)->thread_state() != _thread_in_vm) {
 139     // throw a preallocated exception
 140     THROW_OOP(Universe::virtual_machine_error_instance());
 141   }
 142   THROW_MSG(vmSymbols::java_lang_InternalError(), msg);
 143 }
 144 
 145 
 146 // -----------------------------------------------------------------------------
 147 // MethodHandleWalker
 148 
 149 Bytecodes::Code MethodHandleWalker::conversion_code(BasicType src, BasicType dest) {
 150   if (is_subword_type(src)) {
 151     src = T_INT;          // all subword src types act like int
 152   }
 153   if (src == dest) {
 154     return Bytecodes::_nop;
 155   }
 156 
 157 #define SRC_DEST(s,d) (((int)(s) << 4) + (int)(d))
 158   switch (SRC_DEST(src, dest)) {
 159   case SRC_DEST(T_INT, T_LONG):           return Bytecodes::_i2l;
 160   case SRC_DEST(T_INT, T_FLOAT):          return Bytecodes::_i2f;
 161   case SRC_DEST(T_INT, T_DOUBLE):         return Bytecodes::_i2d;
 162   case SRC_DEST(T_INT, T_BYTE):           return Bytecodes::_i2b;
 163   case SRC_DEST(T_INT, T_CHAR):           return Bytecodes::_i2c;
 164   case SRC_DEST(T_INT, T_SHORT):          return Bytecodes::_i2s;
 165 
 166   case SRC_DEST(T_LONG, T_INT):           return Bytecodes::_l2i;
 167   case SRC_DEST(T_LONG, T_FLOAT):         return Bytecodes::_l2f;
 168   case SRC_DEST(T_LONG, T_DOUBLE):        return Bytecodes::_l2d;
 169 
 170   case SRC_DEST(T_FLOAT, T_INT):          return Bytecodes::_f2i;
 171   case SRC_DEST(T_FLOAT, T_LONG):         return Bytecodes::_f2l;
 172   case SRC_DEST(T_FLOAT, T_DOUBLE):       return Bytecodes::_f2d;
 173 
 174   case SRC_DEST(T_DOUBLE, T_INT):         return Bytecodes::_d2i;
 175   case SRC_DEST(T_DOUBLE, T_LONG):        return Bytecodes::_d2l;
 176   case SRC_DEST(T_DOUBLE, T_FLOAT):       return Bytecodes::_d2f;
 177   }
 178 #undef SRC_DEST
 179 
 180   // cannot do it in one step, or at all
 181   return Bytecodes::_illegal;
 182 }
 183 
 184 
 185 // -----------------------------------------------------------------------------
 186 // MethodHandleWalker::walk
 187 //
 188 MethodHandleWalker::ArgToken
 189 MethodHandleWalker::walk(TRAPS) {
 190   ArgToken empty = ArgToken();  // Empty return value.
 191 
 192   walk_incoming_state(CHECK_(empty));
 193 
 194   for (;;) {
 195     set_method_handle(chain().method_handle_oop());
 196 
 197     assert(_outgoing_argc == argument_count_slow(), "empty slots under control");
 198 
 199     if (chain().is_adapter()) {
 200       int conv_op = chain().adapter_conversion_op();
 201       int arg_slot = chain().adapter_arg_slot();
 202       SlotState* arg_state = slot_state(arg_slot);
 203       if (arg_state == NULL
 204           && conv_op > sun_dyn_AdapterMethodHandle::OP_RETYPE_RAW) {
 205         lose("bad argument index", CHECK_(empty));
 206       }
 207 
 208       // perform the adapter action
 209       switch (chain().adapter_conversion_op()) {
 210       case sun_dyn_AdapterMethodHandle::OP_RETYPE_ONLY:
 211         // No changes to arguments; pass the bits through.
 212         break;
 213 
 214       case sun_dyn_AdapterMethodHandle::OP_RETYPE_RAW: {
 215         // To keep the verifier happy, emit bitwise ("raw") conversions as needed.
 216         // See MethodHandles::same_basic_type_for_arguments for allowed conversions.
 217         Handle incoming_mtype(THREAD, chain().method_type_oop());
 218         oop outgoing_mh_oop = chain().vmtarget_oop();
 219         if (!java_dyn_MethodHandle::is_instance(outgoing_mh_oop))
 220           lose("outgoing target not a MethodHandle", CHECK_(empty));
 221         Handle outgoing_mtype(THREAD, java_dyn_MethodHandle::type(outgoing_mh_oop));
 222         outgoing_mh_oop = NULL;  // GC safety
 223 
 224         int nptypes = java_dyn_MethodType::ptype_count(outgoing_mtype());
 225         if (nptypes != java_dyn_MethodType::ptype_count(incoming_mtype()))
 226           lose("incoming and outgoing parameter count do not agree", CHECK_(empty));
 227 
 228         for (int i = 0, slot = _outgoing.length() - 1; slot >= 0; slot--) {
 229           SlotState* arg_state = slot_state(slot);
 230           if (arg_state->_type == T_VOID)  continue;
 231           ArgToken arg = _outgoing.at(slot)._arg;
 232 
 233           klassOop  in_klass  = NULL;
 234           klassOop  out_klass = NULL;
 235           BasicType inpbt  = java_lang_Class::as_BasicType(java_dyn_MethodType::ptype(incoming_mtype(), i), &in_klass);
 236           BasicType outpbt = java_lang_Class::as_BasicType(java_dyn_MethodType::ptype(outgoing_mtype(), i), &out_klass);
 237           assert(inpbt == arg.basic_type(), "sanity");
 238 
 239           if (inpbt != outpbt) {
 240             vmIntrinsics::ID iid = vmIntrinsics::for_raw_conversion(inpbt, outpbt);
 241             if (iid == vmIntrinsics::_none) {
 242               lose("no raw conversion method", CHECK_(empty));
 243             }
 244             ArgToken arglist[2];
 245             arglist[0] = arg;         // outgoing 'this'
 246             arglist[1] = ArgToken();  // sentinel
 247             arg = make_invoke(NULL, iid, Bytecodes::_invokestatic, false, 1, &arglist[0], CHECK_(empty));
 248             change_argument(inpbt, slot, outpbt, arg);
 249           }
 250 
 251           i++;  // We need to skip void slots at the top of the loop.
 252         }
 253 
 254         BasicType inrbt  = java_lang_Class::as_BasicType(java_dyn_MethodType::rtype(incoming_mtype()));
 255         BasicType outrbt = java_lang_Class::as_BasicType(java_dyn_MethodType::rtype(outgoing_mtype()));
 256         if (inrbt != outrbt) {
 257           assert(false, "IMPLEMENT ME");
 258         }
 259         break;
 260       }
 261 
 262       case sun_dyn_AdapterMethodHandle::OP_CHECK_CAST: {
 263         // checkcast the Nth outgoing argument in place
 264         klassOop dest_klass = NULL;
 265         BasicType dest = java_lang_Class::as_BasicType(chain().adapter_arg_oop(), &dest_klass);
 266         assert(dest == T_OBJECT, "");
 267         assert(dest == arg_state->_type, "");
 268         ArgToken arg = arg_state->_arg;
 269         ArgToken new_arg = make_conversion(T_OBJECT, dest_klass, Bytecodes::_checkcast, arg, CHECK_(empty));
 270         assert(arg.index() == new_arg.index(), "should be the same index");
 271         debug_only(dest_klass = (klassOop)badOop);
 272         break;
 273       }
 274 
 275       case sun_dyn_AdapterMethodHandle::OP_PRIM_TO_PRIM: {
 276         // i2l, etc., on the Nth outgoing argument in place
 277         BasicType src = chain().adapter_conversion_src_type(),
 278                   dest = chain().adapter_conversion_dest_type();
 279         Bytecodes::Code bc = conversion_code(src, dest);
 280         ArgToken arg = arg_state->_arg;
 281         if (bc == Bytecodes::_nop) {
 282           break;
 283         } else if (bc != Bytecodes::_illegal) {
 284           arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 285         } else if (is_subword_type(dest)) {
 286           bc = conversion_code(src, T_INT);
 287           if (bc != Bytecodes::_illegal) {
 288             arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 289             bc = conversion_code(T_INT, dest);
 290             arg = make_conversion(dest, NULL, bc, arg, CHECK_(empty));
 291           }
 292         }
 293         if (bc == Bytecodes::_illegal) {
 294           lose("bad primitive conversion", CHECK_(empty));
 295         }
 296         change_argument(src, arg_slot, dest, arg);
 297         break;
 298       }
 299         
 300       case sun_dyn_AdapterMethodHandle::OP_REF_TO_PRIM: {
 301         // checkcast to wrapper type & call intValue, etc.
 302         BasicType dest = chain().adapter_conversion_dest_type();
 303         ArgToken arg = arg_state->_arg;
 304         arg = make_conversion(T_OBJECT, SystemDictionary::box_klass(dest),
 305                               Bytecodes::_checkcast, arg, CHECK_(empty));
 306         vmIntrinsics::ID unboxer = vmIntrinsics::for_unboxing(dest);
 307         if (unboxer == vmIntrinsics::_none) {
 308           lose("no unboxing method", CHECK_(empty));
 309         }
 310         ArgToken arglist[2];
 311         arglist[0] = arg;         // outgoing 'this'
 312         arglist[1] = ArgToken();  // sentinel
 313         arg = make_invoke(NULL, unboxer, Bytecodes::_invokevirtual, false, 1, &arglist[0], CHECK_(empty));
 314         change_argument(T_OBJECT, arg_slot, dest, arg);
 315         break;
 316       }
 317 
 318       case sun_dyn_AdapterMethodHandle::OP_PRIM_TO_REF: {
 319         // call wrapper type.valueOf
 320         BasicType src = chain().adapter_conversion_src_type();
 321         ArgToken arg = arg_state->_arg;
 322         vmIntrinsics::ID boxer = vmIntrinsics::for_boxing(src);
 323         if (boxer == vmIntrinsics::_none) {
 324           lose("no boxing method", CHECK_(empty));
 325         }
 326         ArgToken arglist[2];
 327         arglist[0] = arg;         // outgoing value
 328         arglist[1] = ArgToken();  // sentinel
 329         assert(false, "I think the argument count must be 1 instead of 0");
 330         arg = make_invoke(NULL, boxer, Bytecodes::_invokevirtual, false, 0, &arglist[0], CHECK_(empty));
 331         change_argument(src, arg_slot, T_OBJECT, arg);
 332         break;
 333       }
 334 
 335       case sun_dyn_AdapterMethodHandle::OP_SWAP_ARGS: {
 336         int dest_arg_slot = chain().adapter_conversion_vminfo();
 337         if (!slot_has_argument(dest_arg_slot)) {
 338           lose("bad swap index", CHECK_(empty));
 339         }
 340         // a simple swap between two arguments
 341         SlotState* dest_arg_state = slot_state(dest_arg_slot);
 342         SlotState temp = (*dest_arg_state);
 343         (*dest_arg_state) = (*arg_state);
 344         (*arg_state) = temp;
 345         break;
 346       }
 347 
 348       case sun_dyn_AdapterMethodHandle::OP_ROT_ARGS: {
 349         int dest_arg_slot = chain().adapter_conversion_vminfo();
 350         if (!slot_has_argument(dest_arg_slot) || arg_slot == dest_arg_slot) {
 351           lose("bad rotate index", CHECK_(empty));
 352         }
 353         SlotState* dest_arg_state = slot_state(dest_arg_slot);
 354         // Rotate the source argument (plus following N slots) into the
 355         // position occupied by the dest argument (plus following N slots).
 356         int rotate_count = type2size[dest_arg_state->_type];
 357         // (no other rotate counts are currently supported)
 358         if (arg_slot < dest_arg_slot) {
 359           for (int i = 0; i < rotate_count; i++) {
 360             SlotState temp = _outgoing.at(arg_slot);
 361             _outgoing.remove_at(arg_slot);
 362             _outgoing.at_insert(dest_arg_slot + rotate_count - 1, temp);
 363           }
 364         } else { // arg_slot > dest_arg_slot
 365           for (int i = 0; i < rotate_count; i++) {
 366             SlotState temp = _outgoing.at(arg_slot + rotate_count - 1);
 367             _outgoing.remove_at(arg_slot + rotate_count - 1);
 368             _outgoing.at_insert(dest_arg_slot, temp);
 369           }
 370         }
 371         break;
 372       }
 373 
 374       case sun_dyn_AdapterMethodHandle::OP_DUP_ARGS: {
 375         int dup_slots = chain().adapter_conversion_stack_pushes();
 376         if (dup_slots <= 0) {
 377           lose("bad dup count", CHECK_(empty));
 378         }
 379         for (int i = 0; i < dup_slots; i++) {
 380           SlotState* dup = slot_state(arg_slot + 2*i);
 381           if (dup == NULL)              break;  // safety net
 382           if (dup->_type != T_VOID)     _outgoing_argc += 1;
 383           _outgoing.at_insert(i, (*dup));
 384         }
 385         break;
 386       }
 387 
 388       case sun_dyn_AdapterMethodHandle::OP_DROP_ARGS: {
 389         int drop_slots = -chain().adapter_conversion_stack_pushes();
 390         if (drop_slots <= 0) {
 391           lose("bad drop count", CHECK_(empty));
 392         }
 393         for (int i = 0; i < drop_slots; i++) {
 394           SlotState* drop = slot_state(arg_slot);
 395           if (drop == NULL)             break;  // safety net
 396           if (drop->_type != T_VOID)    _outgoing_argc -= 1;
 397           _outgoing.remove_at(arg_slot);
 398         }
 399         break;
 400       }
 401 
 402       case sun_dyn_AdapterMethodHandle::OP_COLLECT_ARGS: { //NYI, may GC
 403         lose("unimplemented", CHECK_(empty));
 404         break;
 405       }
 406 
 407       case sun_dyn_AdapterMethodHandle::OP_SPREAD_ARGS: {
 408         klassOop array_klass_oop = NULL;
 409         BasicType array_type = java_lang_Class::as_BasicType(chain().adapter_arg_oop(),
 410                                                              &array_klass_oop);
 411         assert(array_type == T_OBJECT, "");
 412         assert(Klass::cast(array_klass_oop)->oop_is_array(), "");
 413         arrayKlassHandle array_klass(THREAD, array_klass_oop);
 414         debug_only(array_klass_oop = (klassOop)badOop);
 415 
 416         klassOop element_klass_oop = NULL;
 417         BasicType element_type = java_lang_Class::as_BasicType(array_klass->component_mirror(),
 418                                                                &element_klass_oop);
 419         KlassHandle element_klass(THREAD, element_klass_oop);
 420         debug_only(element_klass_oop = (klassOop)badOop);
 421 
 422         // Fetch the argument, which we will cast to the required array type.
 423         assert(arg_state->_type == T_OBJECT, "");
 424         ArgToken array_arg = arg_state->_arg;
 425         array_arg = make_conversion(T_OBJECT, array_klass(), Bytecodes::_checkcast, array_arg, CHECK_(empty));
 426         change_argument(T_OBJECT, arg_slot, T_VOID, ArgToken(tt_void));
 427 
 428         // Check the required length.
 429         int spread_slots = 1 + chain().adapter_conversion_stack_pushes();
 430         int spread_length = spread_slots;
 431         if (type2size[element_type] == 2) {
 432           if (spread_slots % 2 != 0)  spread_slots = -1;  // force error
 433           spread_length = spread_slots / 2;
 434         }
 435         if (spread_slots < 0) {
 436           lose("bad spread length", CHECK_(empty));
 437         }
 438 
 439         jvalue   length_jvalue;  length_jvalue.i = spread_length;
 440         ArgToken length_arg = make_prim_constant(T_INT, &length_jvalue, CHECK_(empty));
 441         // Call a built-in method known to the JVM to validate the length.
 442         ArgToken arglist[3];
 443         arglist[0] = array_arg;   // value to check
 444         arglist[1] = length_arg;  // length to check
 445         arglist[2] = ArgToken();  // sentinel
 446         make_invoke(NULL, vmIntrinsics::_checkSpreadArgument,
 447                     Bytecodes::_invokestatic, false, 3, &arglist[0], CHECK_(empty));
 448 
 449         // Spread out the array elements.
 450         Bytecodes::Code aload_op = Bytecodes::_aaload;
 451         if (element_type != T_OBJECT) {
 452           lose("primitive array NYI", CHECK_(empty));
 453         }
 454         int ap = arg_slot;
 455         for (int i = 0; i < spread_length; i++) {
 456           jvalue   offset_jvalue;  offset_jvalue.i = i;
 457           ArgToken offset_arg = make_prim_constant(T_INT, &offset_jvalue, CHECK_(empty));
 458           ArgToken element_arg = make_fetch(element_type, element_klass(), aload_op, array_arg, offset_arg, CHECK_(empty));
 459           change_argument(T_VOID, ap, element_type, element_arg);
 460           ap += type2size[element_type];
 461         }
 462         break;
 463       }
 464 
 465       case sun_dyn_AdapterMethodHandle::OP_FLYBY: //NYI, runs Java code
 466       case sun_dyn_AdapterMethodHandle::OP_RICOCHET: //NYI, runs Java code
 467         lose("unimplemented", CHECK_(empty));
 468         break;
 469 
 470       default:
 471         lose("bad adapter conversion", CHECK_(empty));
 472         break;
 473       }
 474     }
 475 
 476     if (chain().is_bound()) {
 477       // push a new argument
 478       BasicType arg_type  = chain().bound_arg_type();
 479       jint      arg_slot  = chain().bound_arg_slot();
 480       oop       arg_oop   = chain().bound_arg_oop();
 481       ArgToken  arg;
 482       if (arg_type == T_OBJECT) {
 483         arg = make_oop_constant(arg_oop, CHECK_(empty));
 484       } else {
 485         jvalue arg_value;
 486         BasicType bt = java_lang_boxing_object::get_value(arg_oop, &arg_value);
 487         if (bt == arg_type) {
 488           arg = make_prim_constant(arg_type, &arg_value, CHECK_(empty));
 489         } else {
 490           lose("bad bound value", CHECK_(empty));
 491         }
 492       }
 493       debug_only(arg_oop = badOop);
 494       change_argument(T_VOID, arg_slot, arg_type, arg);
 495     }
 496 
 497     // this test must come after the body of the loop
 498     if (!chain().is_last()) {
 499       chain().next(CHECK_(empty));
 500     } else {
 501       break;
 502     }
 503   }
 504 
 505   // finish the sequence with a tail-call to the ultimate target
 506   // parameters are passed in logical order (recv 1st), not slot order
 507   ArgToken* arglist = NEW_RESOURCE_ARRAY(ArgToken, _outgoing.length() + 1);
 508   int ap = 0;
 509   for (int i = _outgoing.length() - 1; i >= 0; i--) {
 510     SlotState* arg_state = slot_state(i);
 511     if (arg_state->_type == T_VOID)  continue;
 512     arglist[ap++] = _outgoing.at(i)._arg;
 513   }
 514   assert(ap == _outgoing_argc, "");
 515   arglist[ap] = ArgToken();  // add a sentinel, for the sake of asserts
 516   return make_invoke(chain().last_method_oop(),
 517                      vmIntrinsics::_none,
 518                      chain().last_invoke_code(), true,
 519                      ap, arglist, THREAD);
 520 }
 521 
 522 
 523 // -----------------------------------------------------------------------------
 524 // MethodHandleWalker::walk_incoming_state
 525 //
 526 void MethodHandleWalker::walk_incoming_state(TRAPS) {
 527   Handle mtype(THREAD, chain().method_type_oop());
 528   int nptypes = java_dyn_MethodType::ptype_count(mtype());
 529   _outgoing_argc = nptypes;
 530   int argp = nptypes - 1;
 531   if (argp >= 0) {
 532     _outgoing.at_grow(argp, make_state(T_VOID, ArgToken(tt_void))); // presize
 533   }
 534   for (int i = 0; i < nptypes; i++) {
 535     klassOop  arg_type_klass = NULL;
 536     BasicType arg_type = java_lang_Class::as_BasicType(
 537                 java_dyn_MethodType::ptype(mtype(), i), &arg_type_klass);
 538     int index = new_local_index(arg_type);
 539     ArgToken arg = make_parameter(arg_type, arg_type_klass, index, CHECK);
 540     debug_only(arg_type_klass = (klassOop) NULL);
 541     _outgoing.at_put(argp, make_state(arg_type, arg));
 542     if (type2size[arg_type] == 2) {
 543       // add the extra slot, so we can model the JVM stack
 544       _outgoing.at_insert(argp+1, make_state(T_VOID, ArgToken(tt_void)));
 545     }
 546     --argp;
 547   }
 548   // call make_parameter at the end of the list for the return type
 549   klassOop  ret_type_klass = NULL;
 550   BasicType ret_type = java_lang_Class::as_BasicType(
 551               java_dyn_MethodType::rtype(mtype()), &ret_type_klass);
 552   ArgToken  ret = make_parameter(ret_type, ret_type_klass, -1, CHECK);
 553   // ignore ret; client can catch it if needed
 554 }
 555 
 556 
 557 // -----------------------------------------------------------------------------
 558 // MethodHandleWalker::change_argument
 559 //
 560 // This is messy because some kinds of arguments are paired with
 561 // companion slots containing an empty value.
 562 void MethodHandleWalker::change_argument(BasicType old_type, int slot, BasicType new_type,
 563                                          const ArgToken& new_arg) {
 564   int old_size = type2size[old_type];
 565   int new_size = type2size[new_type];
 566   if (old_size == new_size) {
 567     // simple case first
 568     _outgoing.at_put(slot, make_state(new_type, new_arg));
 569   } else if (old_size > new_size) {
 570     for (int i = old_size - 1; i >= new_size; i--) {
 571       assert((i != 0) == (_outgoing.at(slot + i)._type == T_VOID), "");
 572       _outgoing.remove_at(slot + i);
 573     }
 574     if (new_size > 0)
 575       _outgoing.at_put(slot, make_state(new_type, new_arg));
 576     else
 577       _outgoing_argc -= 1;      // deleted a real argument
 578   } else {
 579     for (int i = old_size; i < new_size; i++) {
 580       _outgoing.at_insert(slot + i, make_state(T_VOID, ArgToken(tt_void)));
 581     }
 582     _outgoing.at_put(slot, make_state(new_type, new_arg));
 583     if (old_size == 0)
 584       _outgoing_argc += 1;      // inserted a real argument
 585   }
 586 }
 587 
 588 
 589 int MethodHandleWalker::argument_count_slow() {
 590   int args_seen = 0;
 591   for (int i = _outgoing.length() - 1; i >= 0; i--) {
 592     if (_outgoing.at(i)._type != T_VOID) {
 593       ++args_seen;
 594     }
 595   }
 596   return args_seen;
 597 }
 598 
 599 
 600 // -----------------------------------------------------------------------------
 601 // MethodHandleCompiler
 602 
 603 MethodHandleCompiler::MethodHandleCompiler(Handle root, methodHandle callee, bool is_invokedynamic, TRAPS)
 604   : MethodHandleWalker(root, is_invokedynamic, THREAD),
 605     _callee(callee),
 606     _thread(THREAD),
 607     _bytecode(THREAD, 50),
 608     _constants(THREAD, 10),
 609     _cur_stack(0),
 610     _max_stack(0) {
 611 
 612   // Element zero is always the null constant.
 613   (void) _constants.append(NULL);
 614 
 615   // Set name and signature index.
 616   _name_index      = cpool_symbol_put(_callee->name());
 617   _signature_index = cpool_symbol_put(_callee->signature());
 618 
 619   // Get return type klass.
 620   oop outgoing_mh_oop = chain().vmtarget_oop();
 621   if (java_dyn_MethodHandle::is_instance(outgoing_mh_oop)) {
 622     Handle outgoing_mtype(THREAD, java_dyn_MethodHandle::type(outgoing_mh_oop));
 623     // _rtype is NULL for primitives.
 624     _rtype = java_lang_Class::as_klassOop(java_dyn_MethodType::rtype(outgoing_mtype()));
 625   }
 626   outgoing_mh_oop = NULL;  // GC safety
 627 
 628   int params = _callee->size_of_parameters();  // Incoming arguments plus receiver.
 629   _num_params = for_invokedynamic() ? params - 1 : params;  // XXX Check if callee is static?
 630 }
 631 
 632 
 633 // -----------------------------------------------------------------------------
 634 // MethodHandleCompiler::compile
 635 //
 636 // Compile this MethodHandle into a bytecode adapter and return a
 637 // methodOop.
 638 methodHandle MethodHandleCompiler::compile(TRAPS) {
 639   assert(_thread == THREAD, "must be same thread");
 640   methodHandle nullHandle;
 641   (void) walk(CHECK_(nullHandle));
 642   return get_method_oop(CHECK_(nullHandle));
 643 }
 644 
 645 
 646 void MethodHandleCompiler::emit_bc(Bytecodes::Code op, int index) {
 647   Bytecodes::check(op);  // Are we legal?
 648 
 649   switch (op) {
 650   // b
 651   case Bytecodes::_iconst_m1:
 652   case Bytecodes::_iconst_0:
 653   case Bytecodes::_iconst_1:
 654   case Bytecodes::_iconst_2:
 655   case Bytecodes::_iconst_3:
 656   case Bytecodes::_iconst_4:
 657   case Bytecodes::_iconst_5:
 658   case Bytecodes::_lconst_0:
 659   case Bytecodes::_lconst_1:
 660   case Bytecodes::_fconst_0:
 661   case Bytecodes::_fconst_1:
 662   case Bytecodes::_fconst_2:
 663   case Bytecodes::_dconst_0:
 664   case Bytecodes::_dconst_1:
 665   case Bytecodes::_iload_0:
 666   case Bytecodes::_iload_1:
 667   case Bytecodes::_iload_2:
 668   case Bytecodes::_iload_3:
 669   case Bytecodes::_lload_0:
 670   case Bytecodes::_lload_1:
 671   case Bytecodes::_lload_2:
 672   case Bytecodes::_lload_3:
 673   case Bytecodes::_fload_0:
 674   case Bytecodes::_fload_1:
 675   case Bytecodes::_fload_2:
 676   case Bytecodes::_fload_3:
 677   case Bytecodes::_dload_0:
 678   case Bytecodes::_dload_1:
 679   case Bytecodes::_dload_2:
 680   case Bytecodes::_dload_3:
 681   case Bytecodes::_aload_0:
 682   case Bytecodes::_aload_1:
 683   case Bytecodes::_aload_2:
 684   case Bytecodes::_aload_3:
 685   case Bytecodes::_istore_0:
 686   case Bytecodes::_istore_1:
 687   case Bytecodes::_istore_2:
 688   case Bytecodes::_istore_3:
 689   case Bytecodes::_lstore_0:
 690   case Bytecodes::_lstore_1:
 691   case Bytecodes::_lstore_2:
 692   case Bytecodes::_lstore_3:
 693   case Bytecodes::_fstore_0:
 694   case Bytecodes::_fstore_1:
 695   case Bytecodes::_fstore_2:
 696   case Bytecodes::_fstore_3:
 697   case Bytecodes::_dstore_0:
 698   case Bytecodes::_dstore_1:
 699   case Bytecodes::_dstore_2:
 700   case Bytecodes::_dstore_3:
 701   case Bytecodes::_astore_0:
 702   case Bytecodes::_astore_1:
 703   case Bytecodes::_astore_2:
 704   case Bytecodes::_astore_3:
 705   case Bytecodes::_i2l:
 706   case Bytecodes::_i2f:
 707   case Bytecodes::_i2d:
 708   case Bytecodes::_i2b:
 709   case Bytecodes::_i2c:
 710   case Bytecodes::_i2s:
 711   case Bytecodes::_l2i:
 712   case Bytecodes::_l2f:
 713   case Bytecodes::_l2d:
 714   case Bytecodes::_f2i:
 715   case Bytecodes::_f2l:
 716   case Bytecodes::_f2d:
 717   case Bytecodes::_d2i:
 718   case Bytecodes::_d2l:
 719   case Bytecodes::_d2f:
 720   case Bytecodes::_ireturn:
 721   case Bytecodes::_lreturn:
 722   case Bytecodes::_freturn:
 723   case Bytecodes::_dreturn:
 724   case Bytecodes::_areturn:
 725   case Bytecodes::_return:
 726     assert(strcmp(Bytecodes::format(op), "b") == 0, "wrong bytecode format");
 727     _bytecode.push(op);
 728     break;
 729 
 730   // bi
 731   case Bytecodes::_ldc:
 732   case Bytecodes::_iload:
 733   case Bytecodes::_lload:
 734   case Bytecodes::_fload:
 735   case Bytecodes::_dload:
 736   case Bytecodes::_aload:
 737   case Bytecodes::_istore:
 738   case Bytecodes::_lstore:
 739   case Bytecodes::_fstore:
 740   case Bytecodes::_dstore:
 741   case Bytecodes::_astore:
 742     assert(strcmp(Bytecodes::format(op), "bi") == 0, "wrong bytecode format");
 743     assert((char) index == index, "index does not fit in 8-bit");
 744     _bytecode.push(op);
 745     _bytecode.push(index);
 746     break;
 747 
 748   // bii
 749   case Bytecodes::_ldc2_w:
 750   case Bytecodes::_checkcast:
 751     assert(strcmp(Bytecodes::format(op), "bii") == 0, "wrong bytecode format");
 752     assert((short) index == index, "index does not fit in 16-bit");
 753     _bytecode.push(op);
 754     _bytecode.push(index >> 8);
 755     _bytecode.push(index);
 756     break;
 757 
 758   // bjj
 759   case Bytecodes::_invokestatic:
 760   case Bytecodes::_invokespecial:
 761   case Bytecodes::_invokevirtual:
 762     assert(strcmp(Bytecodes::format(op), "bjj") == 0, "wrong bytecode format");
 763     assert((short) index == index, "index does not fit in 16-bit");
 764     _bytecode.push(op);
 765     _bytecode.push(index >> 8);
 766     _bytecode.push(index);
 767     break;
 768 
 769   default:
 770     ShouldNotReachHere();
 771   }
 772 }
 773 
 774 
 775 void MethodHandleCompiler::emit_load(BasicType bt, int index) {
 776   if (index <= 3) {
 777     switch (bt) {
 778     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 779     case T_INT:    emit_bc(Bytecodes::cast(Bytecodes::_iload_0 + index)); break;
 780     case T_LONG:   emit_bc(Bytecodes::cast(Bytecodes::_lload_0 + index)); break;
 781     case T_FLOAT:  emit_bc(Bytecodes::cast(Bytecodes::_fload_0 + index)); break;
 782     case T_DOUBLE: emit_bc(Bytecodes::cast(Bytecodes::_dload_0 + index)); break;
 783     case T_OBJECT: emit_bc(Bytecodes::cast(Bytecodes::_aload_0 + index)); break;
 784     default:
 785       ShouldNotReachHere();
 786     }
 787   }
 788   else {
 789     switch (bt) {
 790     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 791     case T_INT:    emit_bc(Bytecodes::_iload, index); break;
 792     case T_LONG:   emit_bc(Bytecodes::_lload, index); break;
 793     case T_FLOAT:  emit_bc(Bytecodes::_fload, index); break;
 794     case T_DOUBLE: emit_bc(Bytecodes::_dload, index); break;
 795     case T_OBJECT: emit_bc(Bytecodes::_aload, index); break;
 796     default:
 797       ShouldNotReachHere();
 798     }
 799   }
 800   stack_push(bt);
 801 }
 802 
 803 void MethodHandleCompiler::emit_store(BasicType bt, int index) {
 804   if (index <= 3) {
 805     switch (bt) {
 806     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 807     case T_INT:    emit_bc(Bytecodes::cast(Bytecodes::_istore_0 + index)); break;
 808     case T_LONG:   emit_bc(Bytecodes::cast(Bytecodes::_lstore_0 + index)); break;
 809     case T_FLOAT:  emit_bc(Bytecodes::cast(Bytecodes::_fstore_0 + index)); break;
 810     case T_DOUBLE: emit_bc(Bytecodes::cast(Bytecodes::_dstore_0 + index)); break;
 811     case T_OBJECT: emit_bc(Bytecodes::cast(Bytecodes::_astore_0 + index)); break;
 812     default:
 813       ShouldNotReachHere();
 814     }
 815   }
 816   else {
 817     switch (bt) {
 818     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
 819     case T_INT:    emit_bc(Bytecodes::_istore, index); break;
 820     case T_LONG:   emit_bc(Bytecodes::_lstore, index); break;
 821     case T_FLOAT:  emit_bc(Bytecodes::_fstore, index); break;
 822     case T_DOUBLE: emit_bc(Bytecodes::_dstore, index); break;
 823     case T_OBJECT: emit_bc(Bytecodes::_astore, index); break;
 824     default:
 825       ShouldNotReachHere();
 826     }
 827   }
 828   stack_pop(bt);
 829 }
 830 
 831 
 832 void MethodHandleCompiler::emit_load_constant(ArgToken arg) {
 833   BasicType bt = arg.basic_type();
 834   switch (bt) {
 835   case T_INT: {
 836     jint value = arg.get_jint();
 837     if (-1 <= value && value <= 5)
 838       emit_bc(Bytecodes::cast(Bytecodes::_iconst_0 + value));
 839     else
 840       emit_bc(Bytecodes::_ldc, cpool_int_put(value));
 841     break;
 842   }
 843   case T_LONG: {
 844     jlong value = arg.get_jlong();
 845     if (0 <= value && value <= 1)
 846       emit_bc(Bytecodes::cast(Bytecodes::_lconst_0 + (int) value));
 847     else
 848       emit_bc(Bytecodes::_ldc2_w, cpool_long_put(value));
 849     break;
 850   }
 851   case T_FLOAT: {
 852     jfloat value  = arg.get_jfloat();
 853     if (value == 0.0 || value == 1.0 || value == 2.0)
 854       emit_bc(Bytecodes::cast(Bytecodes::_fconst_0 + (int) value));
 855     else
 856       emit_bc(Bytecodes::_ldc, cpool_float_put(value));
 857     break;
 858   }
 859   case T_DOUBLE: {
 860     jdouble value = arg.get_jdouble();
 861     if (value == 0.0 || value == 1.0)
 862       emit_bc(Bytecodes::cast(Bytecodes::_dconst_0 + (int) value));
 863     else
 864       emit_bc(Bytecodes::_ldc2_w, cpool_double_put(value));
 865     break;
 866   }
 867   case T_OBJECT:
 868     emit_bc(Bytecodes::_ldc, cpool_object_put(arg.object()));
 869     break;
 870   default:
 871     ShouldNotReachHere();
 872   }
 873   stack_push(bt);
 874 }
 875 
 876 
 877 MethodHandleWalker::ArgToken
 878 MethodHandleCompiler::make_conversion(BasicType type, klassOop tk, Bytecodes::Code op,
 879                                       const ArgToken& src, TRAPS) {
 880 
 881   BasicType srctype = src.basic_type();
 882   int index = src.index();
 883 
 884   switch (op) {
 885   case Bytecodes::_i2l:
 886   case Bytecodes::_i2f:
 887   case Bytecodes::_i2d:
 888   case Bytecodes::_i2b:
 889   case Bytecodes::_i2c:
 890   case Bytecodes::_i2s:
 891 
 892   case Bytecodes::_l2i:
 893   case Bytecodes::_l2f:
 894   case Bytecodes::_l2d:
 895 
 896   case Bytecodes::_f2i:
 897   case Bytecodes::_f2l:
 898   case Bytecodes::_f2d:
 899 
 900   case Bytecodes::_d2i:
 901   case Bytecodes::_d2l:
 902   case Bytecodes::_d2f:
 903     emit_load(srctype, index);
 904     stack_pop(srctype);  // pop the src type
 905     emit_bc(op);
 906     stack_push(type);    // push the dest value
 907     if (srctype != type)
 908       index = new_local_index(type);
 909     emit_store(type, index);
 910     break;
 911 
 912   case Bytecodes::_checkcast:
 913     emit_load(srctype, index);
 914     emit_bc(op, cpool_klass_put(tk));
 915     emit_store(srctype, index);
 916     break;
 917 
 918   default:
 919     ShouldNotReachHere();
 920   }
 921 
 922   return make_parameter(type, tk, index, THREAD);
 923 }
 924 
 925 
 926 // -----------------------------------------------------------------------------
 927 // MethodHandleCompiler
 928 //
 929 // Emit bytecodes for the given invoke instruction.
 930 MethodHandleWalker::ArgToken
 931 MethodHandleCompiler::make_invoke(methodOop m, vmIntrinsics::ID iid,
 932                                   Bytecodes::Code op, bool tailcall,
 933                                   int argc, MethodHandleWalker::ArgToken* argv,
 934                                   TRAPS) {
 935   if (m == NULL) {
 936     // Get the intrinsic methodOop.
 937     m = vmIntrinsics::method_for(iid);
 938   }
 939 
 940   klassOop  klass     = m->method_holder();
 941   symbolOop name      = m->name();
 942   symbolOop signature = m->signature();
 943 
 944   // This generated adapter method should be in the same class as the
 945   // DMH target method (for accessability reasons).
 946   if (tailcall) {
 947     _target_klass = klass;
 948   }
 949 
 950   // instanceKlass* ik = instanceKlass::cast(klass);
 951   // tty->print_cr("MethodHandleCompiler::make_invoke: %s %s.%s%s", Bytecodes::name(op), ik->external_name(), name->as_C_string(), signature->as_C_string());
 952 
 953   // Inline the method.
 954   InvocationCounter* ic = m->invocation_counter();
 955   ic->set_carry();
 956 
 957   for (int i = 0; i < argc; i++) {
 958     ArgToken arg = argv[i];
 959     TokenType tt = arg.token_type();
 960     BasicType bt = arg.basic_type();
 961 
 962     switch (tt) {
 963     case tt_parameter:
 964     case tt_temporary:
 965       emit_load(bt, arg.index());
 966       break;
 967     case tt_constant:
 968       emit_load_constant(arg);
 969       break;
 970     case tt_illegal:
 971       // Sentinel.
 972       assert(i == (argc - 1), "sentinel must be last entry");
 973       break;
 974     case tt_void:
 975     default:
 976       ShouldNotReachHere();
 977     }
 978   }
 979 
 980   // Populate constant pool.
 981   int name_index          = cpool_symbol_put(name);
 982   int signature_index     = cpool_symbol_put(signature);
 983   int name_and_type_index = cpool_name_and_type_put(name_index, signature_index);
 984   int klass_index         = cpool_klass_put(klass);
 985   int methodref_index     = cpool_methodref_put(klass_index, name_and_type_index);
 986 
 987   // Generate invoke.
 988   switch (op) {
 989   case Bytecodes::_invokestatic:
 990   case Bytecodes::_invokespecial:
 991   case Bytecodes::_invokevirtual:
 992     emit_bc(op, methodref_index);
 993     break;
 994   case Bytecodes::_invokeinterface:
 995     Unimplemented();
 996     break;
 997   default:
 998     ShouldNotReachHere();
 999   }
1000 
1001   // If tailcall, we have walked all the way to a direct method handle.
1002   // Otherwise, make a recursive call to some helper routine.
1003   BasicType rbt = m->result_type();
1004   ArgToken ret;
1005   if (tailcall) {
1006     switch (rbt) {
1007     case T_BOOLEAN: case T_BYTE: case T_CHAR: case T_SHORT:
1008     case T_INT:    emit_bc(Bytecodes::_ireturn); break;
1009     case T_LONG:   emit_bc(Bytecodes::_lreturn); break;
1010     case T_FLOAT:  emit_bc(Bytecodes::_freturn); break;
1011     case T_DOUBLE: emit_bc(Bytecodes::_dreturn); break;
1012     case T_VOID:   emit_bc(Bytecodes::_return);  break;
1013     case T_OBJECT:
1014       if (_rtype.not_null())
1015         emit_bc(Bytecodes::_checkcast, cpool_klass_put(_rtype()));
1016       emit_bc(Bytecodes::_areturn);
1017       break;
1018     default: ShouldNotReachHere();
1019     }
1020     ret = ArgToken();  // Dummy return value.
1021   }
1022   else {
1023     stack_push(rbt);  // The return value is already pushed onto the stack.
1024     int index = new_local_index(rbt);
1025     switch (rbt) {
1026     case T_BOOLEAN: case T_BYTE: case T_CHAR:  case T_SHORT:
1027     case T_INT:     case T_LONG: case T_FLOAT: case T_DOUBLE:
1028     case T_OBJECT:
1029       emit_store(rbt, index);
1030       ret = ArgToken(tt_temporary, rbt, index);
1031       break;
1032     case T_VOID:
1033       ret = ArgToken(tt_void);
1034       break;
1035     default:
1036       ShouldNotReachHere();
1037     }
1038   }
1039 
1040   return ret;
1041 }
1042 
1043 MethodHandleWalker::ArgToken
1044 MethodHandleCompiler::make_fetch(BasicType type, klassOop tk, Bytecodes::Code op,
1045                                  const MethodHandleWalker::ArgToken& base,
1046                                  const MethodHandleWalker::ArgToken& offset,
1047                                  TRAPS) {
1048   Unimplemented();
1049   return ArgToken();
1050 }
1051 
1052 
1053 int MethodHandleCompiler::cpool_primitive_put(BasicType bt, jvalue* con) {
1054   jvalue con_copy;
1055   assert(bt < T_OBJECT, "");
1056   if (type2aelembytes(bt) < jintSize) {
1057     // widen to int
1058     con_copy = (*con);
1059     con = &con_copy;
1060     switch (bt) {
1061     case T_BOOLEAN: con->i = (con->z ? 1 : 0); break;
1062     case T_BYTE:    con->i = con->b;           break;
1063     case T_CHAR:    con->i = con->c;           break;
1064     case T_SHORT:   con->i = con->s;           break;
1065     default: ShouldNotReachHere();
1066     }
1067     bt = T_INT;
1068   }
1069 
1070 //   for (int i = 1, imax = _constants.length(); i < imax; i++) {
1071 //     ConstantValue* con = _constants.at(i);
1072 //     if (con != NULL && con->is_primitive() && con->_type == bt) {
1073 //       bool match = false;
1074 //       switch (type2size[bt]) {
1075 //       case 1:  if (pcon->_value.i == con->i)  match = true;  break;
1076 //       case 2:  if (pcon->_value.j == con->j)  match = true;  break;
1077 //       }
1078 //       if (match)
1079 //         return i;
1080 //     }
1081 //   }
1082   ConstantValue* cv = new ConstantValue(bt, *con);
1083   int index = _constants.append(cv);
1084 
1085   // long and double entries take 2 slots, we add another empty entry.
1086   if (type2size[bt] == 2)
1087     (void) _constants.append(NULL);
1088 
1089   return index;
1090 }
1091 
1092 
1093 constantPoolHandle MethodHandleCompiler::get_constant_pool(TRAPS) const {
1094   constantPoolHandle nullHandle;
1095   bool is_conc_safe = true;
1096   constantPoolOop cpool_oop = oopFactory::new_constantPool(_constants.length(), is_conc_safe, CHECK_(nullHandle));
1097   constantPoolHandle cpool(THREAD, cpool_oop);
1098 
1099   // Fill the real constant pool skipping the zero element.
1100   for (int i = 1; i < _constants.length(); i++) {
1101     ConstantValue* cv = _constants.at(i);
1102     switch (cv->tag()) {
1103     case JVM_CONSTANT_Utf8:        cpool->symbol_at_put(       i, cv->symbol_oop()                     ); break;
1104     case JVM_CONSTANT_Integer:     cpool->int_at_put(          i, cv->get_jint()                       ); break;
1105     case JVM_CONSTANT_Float:       cpool->float_at_put(        i, cv->get_jfloat()                     ); break;
1106     case JVM_CONSTANT_Long:        cpool->long_at_put(         i, cv->get_jlong()                      ); break;
1107     case JVM_CONSTANT_Double:      cpool->double_at_put(       i, cv->get_jdouble()                    ); break;
1108     case JVM_CONSTANT_Class:       cpool->klass_at_put(        i, cv->klass_oop()                      ); break;
1109     case JVM_CONSTANT_Methodref:   cpool->method_at_put(       i, cv->first_index(), cv->second_index()); break;
1110     case JVM_CONSTANT_NameAndType: cpool->name_and_type_at_put(i, cv->first_index(), cv->second_index()); break;
1111     case JVM_CONSTANT_Object:      cpool->object_at_put(       i, cv->object_oop()                     ); break;
1112     default: ShouldNotReachHere();
1113     }
1114 
1115     switch (cv->tag()) {
1116     case JVM_CONSTANT_Long:
1117     case JVM_CONSTANT_Double:
1118       i++;  // Skip empty entry.
1119       assert(_constants.at(i) == NULL, "empty entry");
1120       break;
1121     }
1122   }
1123 
1124   // Set the constant pool holder to the target method's class.
1125   cpool->set_pool_holder(_target_klass());
1126 
1127   return cpool;
1128 }
1129 
1130 
1131 methodHandle MethodHandleCompiler::get_method_oop(TRAPS) const {
1132   methodHandle nullHandle;
1133   // Create a method that holds the generated bytecode.  invokedynamic
1134   // has no receiver, normal MH calls do.
1135   int flags_bits;
1136   if (for_invokedynamic())
1137     flags_bits = (/*JVM_MH_INVOKE_BITS |*/ JVM_ACC_PUBLIC | JVM_ACC_FINAL | JVM_ACC_STATIC);
1138   else
1139     flags_bits = (/*JVM_MH_INVOKE_BITS |*/ JVM_ACC_PUBLIC | JVM_ACC_FINAL);
1140 
1141   bool is_conc_safe = true;
1142   methodOop m_oop = oopFactory::new_method(bytecode_length(),
1143                                            accessFlags_from(flags_bits),
1144                                            0, 0, 0, is_conc_safe, CHECK_(nullHandle));
1145   methodHandle m(THREAD, m_oop);
1146   m_oop = NULL;  // oop not GC safe
1147 
1148   constantPoolHandle cpool = get_constant_pool(CHECK_(nullHandle));
1149   m->set_constants(cpool());
1150 
1151   m->set_name_index(_name_index);
1152   m->set_signature_index(_signature_index);
1153 
1154   m->set_code((address) bytecode());
1155 
1156   m->set_max_stack(_max_stack);
1157   m->set_max_locals(max_locals());
1158   m->set_size_of_parameters(_num_params);
1159 
1160   typeArrayHandle exception_handlers(THREAD, Universe::the_empty_int_array());
1161   m->set_exception_table(exception_handlers());
1162 
1163   // Set the carry bit of the invocation counter to force inlining of
1164   // the adapter.
1165   InvocationCounter* ic = m->invocation_counter();
1166   ic->set_carry();
1167 
1168   // Rewrite the method and set up the constant pool cache.
1169   objArrayOop m_array = oopFactory::new_system_objArray(1, CHECK_(nullHandle));
1170   objArrayHandle methods(THREAD, m_array);
1171   methods->obj_at_put(0, m());
1172   Rewriter::rewrite(_target_klass(), cpool, methods, CHECK_(nullHandle));  // Use fake class.
1173 
1174   return m;
1175 }
1176 
1177 
1178 #ifndef PRODUCT
1179 
1180 #if 0
1181 // MH printer for debugging.
1182 
1183 class MethodHandlePrinter : public MethodHandleWalker {
1184 private:
1185   outputStream* _out;
1186   bool          _verbose;
1187   int           _temp_num;
1188   stringStream  _strbuf;
1189   const char* strbuf() {
1190     const char* s = _strbuf.as_string();
1191     _strbuf.reset();
1192     return s;
1193   }
1194   ArgToken token(const char* str) {
1195     return (ArgToken) str;
1196   }
1197   void start_params() {
1198     _out->print("(");
1199   }
1200   void end_params() {
1201     if (_verbose)  _out->print("\n");
1202     _out->print(") => {");
1203   }
1204   void put_type_name(BasicType type, klassOop tk, outputStream* s) {
1205     const char* kname = NULL;
1206     if (tk != NULL)
1207       kname = Klass::cast(tk)->external_name();
1208     s->print("%s", (kname != NULL) ? kname : type2name(type));
1209   }
1210   ArgToken maybe_make_temp(const char* statement_op, BasicType type, const char* temp_name) {
1211     const char* value = strbuf();
1212     if (!_verbose)  return token(value);
1213     // make an explicit binding for each separate value
1214     _strbuf.print("%s%d", temp_name, ++_temp_num);
1215     const char* temp = strbuf();
1216     _out->print("\n  %s %s %s = %s;", statement_op, type2name(type), temp, value);
1217     return token(temp);
1218   }
1219 
1220 public:
1221   MethodHandlePrinter(Handle root, bool verbose, outputStream* out, TRAPS)
1222     : MethodHandleWalker(root, THREAD),
1223       _out(out),
1224       _verbose(verbose),
1225       _temp_num(0)
1226   {
1227     start_params();
1228   }
1229   virtual ArgToken make_parameter(BasicType type, klassOop tk, int argnum, TRAPS) {
1230     if (argnum < 0) {
1231       end_params();
1232       return NULL;
1233     }
1234     if (argnum == 0) {
1235       _out->print(_verbose ? "\n  " : "");
1236     } else {
1237       _out->print(_verbose ? ",\n  " : ", ");
1238     }
1239     if (argnum >= _temp_num)
1240       _temp_num = argnum;
1241     // generate an argument name
1242     _strbuf.print("a%d", argnum);
1243     const char* arg = strbuf();
1244     put_type_name(type, tk, _out);
1245     _out->print(" %s", arg);
1246     return token(arg);
1247   }
1248   virtual ArgToken make_oop_constant(oop con, TRAPS) {
1249     if (con == NULL)
1250       _strbuf.print("null");
1251     else
1252       con->print_value_on(&_strbuf);
1253     if (_strbuf.size() == 0) {  // yuck
1254       _strbuf.print("(a ");
1255       put_type_name(T_OBJECT, con->klass(), &_strbuf);
1256       _strbuf.print(")");
1257     }
1258     return maybe_make_temp("constant", T_OBJECT, "k");
1259   }
1260   virtual ArgToken make_prim_constant(BasicType type, jvalue* con, TRAPS) {
1261     java_lang_boxing_object::print(type, con, &_strbuf);
1262     return maybe_make_temp("constant", type, "k");
1263   }
1264   virtual ArgToken make_conversion(BasicType type, klassOop tk, Bytecodes::Code op, ArgToken src, TRAPS) {
1265     _strbuf.print("%s(%s", Bytecodes::name(op), (const char*)src);
1266     if (tk != NULL) {
1267       _strbuf.print(", ");
1268       put_type_name(type, tk, &_strbuf);
1269     }
1270     _strbuf.print(")");
1271     return maybe_make_temp("convert", type, "v");
1272   }
1273   virtual ArgToken make_fetch(BasicType type, klassOop tk, Bytecodes::Code op, ArgToken base, ArgToken offset, TRAPS) {
1274     _strbuf.print("%s(%s, %s", Bytecodes::name(op), (const char*)base, (const char*)offset);
1275     if (tk != NULL) {
1276       _strbuf.print(", ");
1277       put_type_name(type, tk, &_strbuf);
1278     }
1279     _strbuf.print(")");
1280     return maybe_make_temp("fetch", type, "x");
1281   }
1282   virtual ArgToken make_invoke(methodOop m, vmIntrinsics::ID iid,
1283                                Bytecodes::Code op, bool tailcall,
1284                                int argc, ArgToken* argv, TRAPS) {
1285     symbolOop name, sig;
1286     if (m != NULL) {
1287       name = m->name();
1288       sig  = m->signature();
1289     } else {
1290       name = vmSymbols::symbol_at(vmIntrinsics::name_for(iid));
1291       sig  = vmSymbols::symbol_at(vmIntrinsics::signature_for(iid));
1292     }
1293     _strbuf.print("%s %s%s(", Bytecodes::name(op), name->as_C_string(), sig->as_C_string());
1294     for (int i = 0; i < argc; i++) {
1295       _strbuf.print("%s%s", (i > 0 ? ", " : ""), (const char*)argv[i]);
1296     }
1297     _strbuf.print(")");
1298     if (!tailcall) {
1299       BasicType rt = char2type(sig->byte_at(sig->utf8_length()-1));
1300       if (rt == T_ILLEGAL)  rt = T_OBJECT;  // ';' at the end of '(...)L...;'
1301       return maybe_make_temp("invoke", rt, "x");
1302     } else {
1303       const char* ret = strbuf();
1304       _out->print(_verbose ? "\n  return " : " ");
1305       _out->print("%s", ret);
1306       _out->print(_verbose ? "\n}\n" : " }");
1307     }
1308   }
1309 
1310   virtual void set_method_handle(oop mh) {
1311     if (WizardMode && Verbose) {
1312       tty->print("\n--- next target: ");
1313       mh->print();
1314     }
1315   }
1316 
1317   static void print(Handle root, bool verbose, outputStream* out, TRAPS) {
1318     ResourceMark rm;
1319     MethodHandlePrinter printer(root, verbose, out, CHECK);
1320     printer.walk(CHECK);
1321     out->print("\n");
1322   }
1323   static void print(Handle root, bool verbose = Verbose, outputStream* out = tty) {
1324     EXCEPTION_MARK;
1325     ResourceMark rm;
1326     MethodHandlePrinter printer(root, verbose, out, THREAD);
1327     if (!HAS_PENDING_EXCEPTION)
1328       printer.walk(THREAD);
1329     if (HAS_PENDING_EXCEPTION) {
1330       oop ex = PENDING_EXCEPTION;
1331       CLEAR_PENDING_EXCEPTION;
1332       out->print("\n*** ");
1333       if (ex != Universe::virtual_machine_error_instance())
1334         ex->print_on(out);
1335       else
1336         out->print("lose: %s", printer.lose_message());
1337       out->print("\n}\n");
1338     }
1339     out->print("\n");
1340   }
1341 };
1342 #endif
1343 
1344 extern "C"
1345 void print_method_handle(oop mh) {
1346   if (java_dyn_MethodHandle::is_instance(mh)) {
1347 //     MethodHandlePrinter::print(mh);
1348   } else {
1349     tty->print("*** not a method handle: ");
1350     mh->print();
1351   }
1352 }
1353 
1354 #endif // PRODUCT