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