1 /*
   2  * Copyright (c) 1998, 2018, 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 "compiler/compileLog.hpp"
  27 #include "interpreter/linkResolver.hpp"
  28 #include "memory/universe.hpp"
  29 #include "oops/objArrayKlass.hpp"
  30 #include "oops/valueArrayKlass.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/castnode.hpp"
  33 #include "opto/memnode.hpp"
  34 #include "opto/parse.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/runtime.hpp"
  37 #include "opto/subnode.hpp"
  38 #include "opto/valuetypenode.hpp"
  39 #include "runtime/deoptimization.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 
  42 //=============================================================================
  43 // Helper methods for _get* and _put* bytecodes
  44 //=============================================================================
  45 
  46 void Parse::do_field_access(bool is_get, bool is_field) {
  47   bool will_link;
  48   ciField* field = iter().get_field(will_link);
  49   assert(will_link, "getfield: typeflow responsibility");
  50 
  51   ciInstanceKlass* field_holder = field->holder();
  52 
  53   if (is_field && field_holder->is_valuetype() && peek()->is_ValueType()) {
  54     assert(is_get, "value type field store not supported");
  55     ValueTypeNode* vt = pop()->as_ValueType();
  56     Node* value = vt->field_value_by_offset(field->offset());
  57     push_node(field->layout_type(), value);
  58     return;
  59   }
  60 
  61   if (is_field == field->is_static()) {
  62     // Interpreter will throw java_lang_IncompatibleClassChangeError
  63     // Check this before allowing <clinit> methods to access static fields
  64     uncommon_trap(Deoptimization::Reason_unhandled,
  65                   Deoptimization::Action_none);
  66     return;
  67   }
  68 
  69   // Deoptimize on putfield writes to call site target field.
  70   if (!is_get && field->is_call_site_target()) {
  71     uncommon_trap(Deoptimization::Reason_unhandled,
  72                   Deoptimization::Action_reinterpret,
  73                   NULL, "put to call site target field");
  74     return;
  75   }
  76 
  77   if (C->needs_clinit_barrier(field, method())) {
  78     clinit_barrier(field_holder, method());
  79     if (stopped())  return;
  80   }
  81 
  82   assert(field->will_link(method(), bc()), "getfield: typeflow responsibility");
  83 
  84   // Note:  We do not check for an unloaded field type here any more.
  85 
  86   // Generate code for the object pointer.
  87   Node* obj;
  88   if (is_field) {
  89     int obj_depth = is_get ? 0 : field->type()->size();
  90     obj = null_check(peek(obj_depth));
  91     // Compile-time detect of null-exception?
  92     if (stopped())  return;
  93 
  94 #ifdef ASSERT
  95     const TypeInstPtr *tjp = TypeInstPtr::make(TypePtr::NotNull, iter().get_declared_field_holder());
  96     assert(_gvn.type(obj)->higher_equal(tjp), "cast_up is no longer needed");
  97 #endif
  98 
  99     if (is_get) {
 100       (void) pop();  // pop receiver before getting
 101       do_get_xxx(obj, field);
 102     } else {
 103       do_put_xxx(obj, field, is_field);
 104       if (stopped()) {
 105         return;
 106       }
 107       (void) pop();  // pop receiver after putting
 108     }
 109   } else {
 110     const TypeInstPtr* tip = TypeInstPtr::make(field_holder->java_mirror());
 111     obj = _gvn.makecon(tip);
 112     if (is_get) {
 113       do_get_xxx(obj, field);
 114     } else {
 115       do_put_xxx(obj, field, is_field);
 116     }
 117   }
 118 }
 119 
 120 void Parse::do_get_xxx(Node* obj, ciField* field) {
 121   BasicType bt = field->layout_type();
 122 
 123   // Does this field have a constant value?  If so, just push the value.
 124   if (field->is_constant() &&
 125       // Keep consistent with types found by ciTypeFlow: for an
 126       // unloaded field type, ciTypeFlow::StateVector::do_getstatic()
 127       // speculates the field is null. The code in the rest of this
 128       // method does the same. We must not bypass it and use a non
 129       // null constant here.
 130       (bt != T_OBJECT || field->type()->is_loaded())) {
 131     // final or stable field
 132     Node* con = make_constant_from_field(field, obj);
 133     if (con != NULL) {
 134       push_node(field->layout_type(), con);
 135       return;
 136     }
 137   }
 138 
 139   ciType* field_klass = field->type();
 140   bool is_vol = field->is_volatile();
 141   bool flattened = field->is_flattened();
 142   bool flattenable = field->is_flattenable();
 143 
 144   // Compute address and memory type.
 145   int offset = field->offset_in_bytes();
 146   const TypePtr* adr_type = C->alias_type(field)->adr_type();
 147   Node *adr = basic_plus_adr(obj, obj, offset);
 148 
 149   // Build the resultant type of the load
 150   const Type *type;
 151 
 152   bool must_assert_null = false;
 153 
 154   if (bt == T_OBJECT || bt == T_ARRAY || bt == T_VALUETYPE) {
 155     if (!field->type()->is_loaded()) {
 156       type = TypeInstPtr::BOTTOM;
 157       must_assert_null = true;
 158     } else if (field->is_static_constant()) {
 159       // This can happen if the constant oop is non-perm.
 160       ciObject* con = field->constant_value().as_object();
 161       // Do not "join" in the previous type; it doesn't add value,
 162       // and may yield a vacuous result if the field is of interface type.
 163       if (con->is_null_object()) {
 164         type = TypePtr::NULL_PTR;
 165       } else {
 166         type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
 167       }
 168       assert(type != NULL, "field singleton type must be consistent");
 169     } else {
 170       type = TypeOopPtr::make_from_klass(field_klass->as_klass());
 171       if (bt == T_VALUETYPE && field->is_static() && flattenable) {
 172         // Check if static value type field is already initialized
 173         assert(!flattened, "static fields should not be flattened");
 174         ciInstance* mirror = field->holder()->java_mirror();
 175         ciObject* val = mirror->field_value(field).as_object();
 176         if (!val->is_null_object()) {
 177           type = type->join_speculative(TypePtr::NOTNULL);
 178         }
 179       }
 180     }
 181   } else {
 182     type = Type::get_const_basic_type(bt);
 183   }
 184 
 185   Node* ld = NULL;
 186   if (flattened) {
 187     // Load flattened value type
 188     ld = ValueTypeNode::make_from_flattened(this, field_klass->as_value_klass(), obj, obj, field->holder(), offset);
 189   } else {
 190     DecoratorSet decorators = IN_HEAP;
 191     decorators |= is_vol ? MO_SEQ_CST : MO_UNORDERED;
 192     ld = access_load_at(obj, adr, adr_type, type, bt, decorators);
 193     if (flattenable) {
 194       // Load a non-flattened but flattenable value type from memory
 195       if (field_klass->as_value_klass()->is_scalarizable()) {
 196         ld = ValueTypeNode::make_from_oop(this, ld, field_klass->as_value_klass());
 197       } else {
 198         ld = null2default(ld, field_klass->as_value_klass());
 199       }
 200     }
 201   }
 202 
 203   // Adjust Java stack
 204   if (type2size[bt] == 1)
 205     push(ld);
 206   else
 207     push_pair(ld);
 208 
 209   if (must_assert_null) {
 210     // Do not take a trap here.  It's possible that the program
 211     // will never load the field's class, and will happily see
 212     // null values in this field forever.  Don't stumble into a
 213     // trap for such a program, or we might get a long series
 214     // of useless recompilations.  (Or, we might load a class
 215     // which should not be loaded.)  If we ever see a non-null
 216     // value, we will then trap and recompile.  (The trap will
 217     // not need to mention the class index, since the class will
 218     // already have been loaded if we ever see a non-null value.)
 219     // uncommon_trap(iter().get_field_signature_index());
 220     if (PrintOpto && (Verbose || WizardMode)) {
 221       method()->print_name(); tty->print_cr(" asserting nullness of field at bci: %d", bci());
 222     }
 223     if (C->log() != NULL) {
 224       C->log()->elem("assert_null reason='field' klass='%d'",
 225                      C->log()->identify(field->type()));
 226     }
 227     // If there is going to be a trap, put it at the next bytecode:
 228     set_bci(iter().next_bci());
 229     null_assert(peek());
 230     set_bci(iter().cur_bci()); // put it back
 231   }
 232 }
 233 
 234 void Parse::do_put_xxx(Node* obj, ciField* field, bool is_field) {
 235   bool is_vol = field->is_volatile();
 236 
 237   // Compute address and memory type.
 238   int offset = field->offset_in_bytes();
 239   const TypePtr* adr_type = C->alias_type(field)->adr_type();
 240   Node* adr = basic_plus_adr(obj, obj, offset);
 241   BasicType bt = field->layout_type();
 242   // Value to be stored
 243   Node* val = type2size[bt] == 1 ? pop() : pop_pair();
 244 
 245   DecoratorSet decorators = IN_HEAP;
 246   decorators |= is_vol ? MO_SEQ_CST : MO_UNORDERED;
 247 
 248   // Store the value.
 249   const Type* field_type;
 250   if (!field->type()->is_loaded()) {
 251     field_type = TypeInstPtr::BOTTOM;
 252   } else {
 253     if (bt == T_OBJECT || bt == T_ARRAY || bt == T_VALUETYPE) {
 254       field_type = TypeOopPtr::make_from_klass(field->type()->as_klass());
 255     } else {
 256       field_type = Type::BOTTOM;
 257     }
 258   }
 259 
 260   if (field->is_flattenable() && !val->is_ValueType()) {
 261     inc_sp(1);
 262     val = null_check(val);
 263     dec_sp(1);
 264     if (stopped()) return;
 265   }
 266 
 267   if (field->is_flattened()) {
 268     // Store flattened value type to a non-static field
 269     if (!val->is_ValueType()) {
 270       assert(!gvn().type(val)->maybe_null(), "should never be null");
 271       val = ValueTypeNode::make_from_oop(this, val, field->type()->as_value_klass());
 272     }
 273     val->as_ValueType()->store_flattened(this, obj, obj, field->holder(), offset);
 274   } else {
 275     access_store_at(obj, adr, adr_type, val, field_type, bt, decorators);
 276   }
 277 
 278   if (is_field) {
 279     // Remember we wrote a volatile field.
 280     // For not multiple copy atomic cpu (ppc64) a barrier should be issued
 281     // in constructors which have such stores. See do_exits() in parse1.cpp.
 282     if (is_vol) {
 283       set_wrote_volatile(true);
 284     }
 285     set_wrote_fields(true);
 286 
 287     // If the field is final, the rules of Java say we are in <init> or <clinit>.
 288     // Note the presence of writes to final non-static fields, so that we
 289     // can insert a memory barrier later on to keep the writes from floating
 290     // out of the constructor.
 291     // Any method can write a @Stable field; insert memory barriers after those also.
 292     if (field->is_final()) {
 293       set_wrote_final(true);
 294       if (AllocateNode::Ideal_allocation(obj, &_gvn) != NULL) {
 295         // Preserve allocation ptr to create precedent edge to it in membar
 296         // generated on exit from constructor.
 297         // Can't bind stable with its allocation, only record allocation for final field.
 298         set_alloc_with_final(obj);
 299       }
 300     }
 301     if (field->is_stable()) {
 302       set_wrote_stable(true);
 303     }
 304   }
 305 }
 306 
 307 //=============================================================================
 308 
 309 void Parse::do_newarray() {
 310   bool will_link;
 311   ciKlass* klass = iter().get_klass(will_link);
 312   bool never_null = iter().is_klass_never_null();
 313 
 314   // Uncommon Trap when class that array contains is not loaded
 315   // we need the loaded class for the rest of graph; do not
 316   // initialize the container class (see Java spec)!!!
 317   assert(will_link, "newarray: typeflow responsibility");
 318 
 319   ciArrayKlass* array_klass = ciArrayKlass::make(klass, never_null);
 320 
 321   // Check that array_klass object is loaded
 322   if (!array_klass->is_loaded()) {
 323     // Generate uncommon_trap for unloaded array_class
 324     uncommon_trap(Deoptimization::Reason_unloaded,
 325                   Deoptimization::Action_reinterpret,
 326                   array_klass);
 327     return;
 328   } else if (array_klass->element_klass() != NULL &&
 329              array_klass->element_klass()->is_valuetype() &&
 330              !array_klass->element_klass()->as_value_klass()->is_initialized()) {
 331     uncommon_trap(Deoptimization::Reason_uninitialized,
 332                   Deoptimization::Action_reinterpret,
 333                   NULL);
 334     return;
 335   }
 336 
 337   kill_dead_locals();
 338 
 339   const TypeKlassPtr* array_klass_type = TypeKlassPtr::make(array_klass);
 340   Node* count_val = pop();
 341   Node* obj = new_array(makecon(array_klass_type), count_val, 1);
 342   push(obj);
 343 }
 344 
 345 
 346 void Parse::do_newarray(BasicType elem_type) {
 347   kill_dead_locals();
 348 
 349   Node*   count_val = pop();
 350   const TypeKlassPtr* array_klass = TypeKlassPtr::make(ciTypeArrayKlass::make(elem_type));
 351   Node*   obj = new_array(makecon(array_klass), count_val, 1);
 352   // Push resultant oop onto stack
 353   push(obj);
 354 }
 355 
 356 // Expand simple expressions like new int[3][5] and new Object[2][nonConLen].
 357 // Also handle the degenerate 1-dimensional case of anewarray.
 358 Node* Parse::expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, int ndimensions, int nargs) {
 359   Node* length = lengths[0];
 360   assert(length != NULL, "");
 361   Node* array = new_array(makecon(TypeKlassPtr::make(array_klass)), length, nargs);
 362   if (ndimensions > 1) {
 363     jint length_con = find_int_con(length, -1);
 364     guarantee(length_con >= 0, "non-constant multianewarray");
 365     ciArrayKlass* array_klass_1 = array_klass->as_obj_array_klass()->element_klass()->as_array_klass();
 366     const TypePtr* adr_type = TypeAryPtr::OOPS;
 367     const TypeOopPtr*    elemtype = _gvn.type(array)->is_aryptr()->elem()->make_oopptr();
 368     const intptr_t header   = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 369     for (jint i = 0; i < length_con; i++) {
 370       Node*    elem   = expand_multianewarray(array_klass_1, &lengths[1], ndimensions-1, nargs);
 371       intptr_t offset = header + ((intptr_t)i << LogBytesPerHeapOop);
 372       Node*    eaddr  = basic_plus_adr(array, offset);
 373       access_store_at(array, eaddr, adr_type, elem, elemtype, T_OBJECT, IN_HEAP | IS_ARRAY);
 374     }
 375   }
 376   return array;
 377 }
 378 
 379 void Parse::do_multianewarray() {
 380   int ndimensions = iter().get_dimensions();
 381 
 382   // the m-dimensional array
 383   bool will_link;
 384   ciArrayKlass* array_klass = iter().get_klass(will_link)->as_array_klass();
 385   assert(will_link, "multianewarray: typeflow responsibility");
 386 
 387   // Note:  Array classes are always initialized; no is_initialized check.
 388 
 389   kill_dead_locals();
 390 
 391   // get the lengths from the stack (first dimension is on top)
 392   Node** length = NEW_RESOURCE_ARRAY(Node*, ndimensions + 1);
 393   length[ndimensions] = NULL;  // terminating null for make_runtime_call
 394   int j;
 395   for (j = ndimensions-1; j >= 0 ; j--) length[j] = pop();
 396 
 397   // The original expression was of this form: new T[length0][length1]...
 398   // It is often the case that the lengths are small (except the last).
 399   // If that happens, use the fast 1-d creator a constant number of times.
 400   const int expand_limit = MIN2((int)MultiArrayExpandLimit, 100);
 401   int expand_count = 1;        // count of allocations in the expansion
 402   int expand_fanout = 1;       // running total fanout
 403   for (j = 0; j < ndimensions-1; j++) {
 404     int dim_con = find_int_con(length[j], -1);
 405     expand_fanout *= dim_con;
 406     expand_count  += expand_fanout; // count the level-J sub-arrays
 407     if (dim_con <= 0
 408         || dim_con > expand_limit
 409         || expand_count > expand_limit) {
 410       expand_count = 0;
 411       break;
 412     }
 413   }
 414 
 415   // Can use multianewarray instead of [a]newarray if only one dimension,
 416   // or if all non-final dimensions are small constants.
 417   if (ndimensions == 1 || (1 <= expand_count && expand_count <= expand_limit)) {
 418     Node* obj = NULL;
 419     // Set the original stack and the reexecute bit for the interpreter
 420     // to reexecute the multianewarray bytecode if deoptimization happens.
 421     // Do it unconditionally even for one dimension multianewarray.
 422     // Note: the reexecute bit will be set in GraphKit::add_safepoint_edges()
 423     // when AllocateArray node for newarray is created.
 424     { PreserveReexecuteState preexecs(this);
 425       inc_sp(ndimensions);
 426       // Pass 0 as nargs since uncommon trap code does not need to restore stack.
 427       obj = expand_multianewarray(array_klass, &length[0], ndimensions, 0);
 428     } //original reexecute and sp are set back here
 429     push(obj);
 430     return;
 431   }
 432 
 433   address fun = NULL;
 434   switch (ndimensions) {
 435   case 1: ShouldNotReachHere(); break;
 436   case 2: fun = OptoRuntime::multianewarray2_Java(); break;
 437   case 3: fun = OptoRuntime::multianewarray3_Java(); break;
 438   case 4: fun = OptoRuntime::multianewarray4_Java(); break;
 439   case 5: fun = OptoRuntime::multianewarray5_Java(); break;
 440   };
 441   Node* c = NULL;
 442 
 443   if (fun != NULL) {
 444     c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
 445                           OptoRuntime::multianewarray_Type(ndimensions),
 446                           fun, NULL, TypeRawPtr::BOTTOM,
 447                           makecon(TypeKlassPtr::make(array_klass)),
 448                           length[0], length[1], length[2],
 449                           (ndimensions > 2) ? length[3] : NULL,
 450                           (ndimensions > 3) ? length[4] : NULL);
 451   } else {
 452     // Create a java array for dimension sizes
 453     Node* dims = NULL;
 454     { PreserveReexecuteState preexecs(this);
 455       inc_sp(ndimensions);
 456       Node* dims_array_klass = makecon(TypeKlassPtr::make(ciArrayKlass::make(ciType::make(T_INT))));
 457       dims = new_array(dims_array_klass, intcon(ndimensions), 0);
 458 
 459       // Fill-in it with values
 460       for (j = 0; j < ndimensions; j++) {
 461         Node *dims_elem = array_element_address(dims, intcon(j), T_INT);
 462         store_to_memory(control(), dims_elem, length[j], T_INT, TypeAryPtr::INTS, MemNode::unordered);
 463       }
 464     }
 465 
 466     c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
 467                           OptoRuntime::multianewarrayN_Type(),
 468                           OptoRuntime::multianewarrayN_Java(), NULL, TypeRawPtr::BOTTOM,
 469                           makecon(TypeKlassPtr::make(array_klass)),
 470                           dims);
 471   }
 472   make_slow_call_ex(c, env()->Throwable_klass(), false);
 473 
 474   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms));
 475 
 476   const Type* type = TypeOopPtr::make_from_klass_raw(array_klass);
 477 
 478   // Improve the type:  We know it's not null, exact, and of a given length.
 479   type = type->is_ptr()->cast_to_ptr_type(TypePtr::NotNull);
 480   type = type->is_aryptr()->cast_to_exactness(true);
 481 
 482   const TypeInt* ltype = _gvn.find_int_type(length[0]);
 483   if (ltype != NULL)
 484     type = type->is_aryptr()->cast_to_size(ltype);
 485 
 486     // We cannot sharpen the nested sub-arrays, since the top level is mutable.
 487 
 488   Node* cast = _gvn.transform( new CheckCastPPNode(control(), res, type) );
 489   push(cast);
 490 
 491   // Possible improvements:
 492   // - Make a fast path for small multi-arrays.  (W/ implicit init. loops.)
 493   // - Issue CastII against length[*] values, to TypeInt::POS.
 494 }