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