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