1 /*
  2  * Copyright (c) 2014, 2023, 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 "opto/addnode.hpp"
 27 #include "opto/callnode.hpp"
 28 #include "opto/castnode.hpp"
 29 #include "opto/connode.hpp"
 30 #include "opto/graphKit.hpp"
 31 #include "opto/inlinetypenode.hpp"
 32 #include "opto/matcher.hpp"
 33 #include "opto/phaseX.hpp"
 34 #include "opto/rootnode.hpp"
 35 #include "opto/subnode.hpp"
 36 #include "opto/type.hpp"
 37 #include "castnode.hpp"
 38 #include "utilities/checkedCast.hpp"
 39 
 40 //=============================================================================
 41 // If input is already higher or equal to cast type, then this is an identity.
 42 Node* ConstraintCastNode::Identity(PhaseGVN* phase) {
 43   if (_dependency == UnconditionalDependency) {
 44     return this;
 45   }
 46   Node* dom = dominating_cast(phase, phase);
 47   if (dom != nullptr) {
 48     return dom;
 49   }
 50   return higher_equal_types(phase, in(1)) ? in(1) : this;
 51 }
 52 
 53 //------------------------------Value------------------------------------------
 54 // Take 'join' of input and cast-up type
 55 const Type* ConstraintCastNode::Value(PhaseGVN* phase) const {
 56   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
 57 
 58   const Type* in_type = phase->type(in(1));
 59   const Type* ft = in_type->filter_speculative(_type);
 60 
 61   // Check if both _type and in_type had a speculative type, but for the just
 62   // computed ft the speculative type was dropped.
 63   if (ft->speculative() == nullptr &&
 64       _type->speculative() != nullptr &&
 65       in_type->speculative() != nullptr) {
 66     // Speculative type may have disagreed between cast and input, and was
 67     // dropped in filtering. Recompute so that ft can take speculative type
 68     // of in_type. If we did not do it now, a subsequent ::Value call would
 69     // do it, and violate idempotence of ::Value.
 70     ft = in_type->filter_speculative(ft);
 71   }
 72 
 73 #ifdef ASSERT
 74   // Previous versions of this function had some special case logic,
 75   // which is no longer necessary.  Make sure of the required effects.
 76   switch (Opcode()) {
 77     case Op_CastII:
 78     {
 79       if (in_type == Type::TOP) {
 80         assert(ft == Type::TOP, "special case #1");
 81       }
 82       const Type* rt = in_type->join_speculative(_type);
 83       if (rt->empty()) {
 84         assert(ft == Type::TOP, "special case #2");
 85       }
 86       break;
 87     }
 88     case Op_CastPP:
 89     if (in_type == TypePtr::NULL_PTR &&
 90         _type->isa_ptr() && _type->is_ptr()->_ptr == TypePtr::NotNull) {
 91       assert(ft == Type::TOP, "special case #3");
 92       break;
 93     }
 94   }
 95 #endif //ASSERT
 96 
 97   return ft;
 98 }
 99 
100 //------------------------------Ideal------------------------------------------
101 // Return a node which is more "ideal" than the current node.  Strip out
102 // control copies
103 Node *ConstraintCastNode::Ideal(PhaseGVN *phase, bool can_reshape) {
104   if (in(0) && remove_dead_region(phase, can_reshape)) {
105     return this;
106   }
107 
108   // Push cast through InlineTypeNode
109   InlineTypeNode* vt = in(1)->isa_InlineType();
110   if (vt != nullptr && phase->type(vt)->filter_speculative(_type) != Type::TOP) {
111     Node* cast = clone();
112     cast->set_req(1, vt->get_oop());
113     vt = vt->clone()->as_InlineType();
114     if (!_type->maybe_null()) {
115       vt->as_InlineType()->set_is_init(*phase);
116     }
117     vt->set_oop(*phase, phase->transform(cast));
118     return vt;
119   }
120 
121   return nullptr;
122 }
123 
124 uint ConstraintCastNode::hash() const {
125   return TypeNode::hash() + (int)_dependency + (_extra_types != nullptr ? _extra_types->hash() : 0);
126 }
127 
128 bool ConstraintCastNode::cmp(const Node &n) const {
129   if (!TypeNode::cmp(n)) {
130     return false;
131   }
132   ConstraintCastNode& cast = (ConstraintCastNode&) n;
133   if (cast._dependency != _dependency) {
134     return false;
135   }
136   if (_extra_types == nullptr || cast._extra_types == nullptr) {
137     return _extra_types == cast._extra_types;
138   }
139   return _extra_types->eq(cast._extra_types);
140 }
141 
142 uint ConstraintCastNode::size_of() const {
143   return sizeof(*this);
144 }
145 
146 Node* ConstraintCastNode::make_cast_for_basic_type(Node* c, Node* n, const Type* t, DependencyType dependency, BasicType bt) {
147   switch(bt) {
148   case T_INT:
149     return new CastIINode(c, n, t, dependency);
150   case T_LONG:
151     return new CastLLNode(c, n, t, dependency);
152   default:
153     fatal("Bad basic type %s", type2name(bt));
154   }
155   return nullptr;
156 }
157 
158 TypeNode* ConstraintCastNode::dominating_cast(PhaseGVN* gvn, PhaseTransform* pt) const {
159   if (_dependency == UnconditionalDependency) {
160     return nullptr;
161   }
162   Node* val = in(1);
163   Node* ctl = in(0);
164   int opc = Opcode();
165   if (ctl == nullptr) {
166     return nullptr;
167   }
168   // Range check CastIIs may all end up under a single range check and
169   // in that case only the narrower CastII would be kept by the code
170   // below which would be incorrect.
171   if (is_CastII() && as_CastII()->has_range_check()) {
172     return nullptr;
173   }
174   if (type()->isa_rawptr() && (gvn->type_or_null(val) == nullptr || gvn->type(val)->isa_oopptr())) {
175     return nullptr;
176   }
177   for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
178     Node* u = val->fast_out(i);
179     if (u != this &&
180         u->outcnt() > 0 &&
181         u->Opcode() == opc &&
182         u->in(0) != nullptr &&
183         higher_equal_types(gvn, u)) {
184       if (pt->is_dominator(u->in(0), ctl)) {
185         return u->as_Type();
186       }
187       if (is_CheckCastPP() && u->in(1)->is_Proj() && u->in(1)->in(0)->is_Allocate() &&
188           u->in(0)->is_Proj() && u->in(0)->in(0)->is_Initialize() &&
189           u->in(1)->in(0)->as_Allocate()->initialization() == u->in(0)->in(0)) {
190         // CheckCastPP following an allocation always dominates all
191         // use of the allocation result
192         return u->as_Type();
193       }
194     }
195   }
196   return nullptr;
197 }
198 
199 bool ConstraintCastNode::higher_equal_types(PhaseGVN* phase, const Node* other) const {
200   const Type* t = phase->type(other);
201   if (!t->higher_equal_speculative(type())) {
202     return false;
203   }
204   if (_extra_types != nullptr) {
205     for (uint i = 0; i < _extra_types->cnt(); ++i) {
206       if (!t->higher_equal_speculative(_extra_types->field_at(i))) {
207         return false;
208       }
209     }
210   }
211   return true;
212 }
213 
214 #ifndef PRODUCT
215 void ConstraintCastNode::dump_spec(outputStream *st) const {
216   TypeNode::dump_spec(st);
217   if (_extra_types != nullptr) {
218     st->print(" extra types: ");
219     _extra_types->dump_on(st);
220   }
221   if (_dependency != RegularDependency) {
222     st->print(" %s dependency", _dependency == StrongDependency ? "strong" : "unconditional");
223   }
224 }
225 #endif
226 
227 const Type* CastIINode::Value(PhaseGVN* phase) const {
228   const Type *res = ConstraintCastNode::Value(phase);
229   if (res == Type::TOP) {
230     return Type::TOP;
231   }
232   assert(res->isa_int(), "res must be int");
233 
234   // Similar to ConvI2LNode::Value() for the same reasons
235   // see if we can remove type assertion after loop opts
236   // But here we have to pay extra attention:
237   // Do not narrow the type of range check dependent CastIINodes to
238   // avoid corruption of the graph if a CastII is replaced by TOP but
239   // the corresponding range check is not removed.
240   if (!_range_check_dependency) {
241     res = widen_type(phase, res, T_INT);
242   }
243 
244   return res;
245 }
246 
247 static Node* find_or_make_integer_cast(PhaseIterGVN* igvn, Node* parent, Node* control, const TypeInteger* type, ConstraintCastNode::DependencyType dependency, BasicType bt) {
248   Node* n = ConstraintCastNode::make_cast_for_basic_type(control, parent, type, dependency, bt);
249   Node* existing = igvn->hash_find_insert(n);
250   if (existing != nullptr) {
251     n->destruct(igvn);
252     return existing;
253   }
254   return igvn->register_new_node_with_optimizer(n);
255 }
256 
257 Node *CastIINode::Ideal(PhaseGVN *phase, bool can_reshape) {
258   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
259   if (progress != nullptr) {
260     return progress;
261   }
262   if (can_reshape && !_range_check_dependency && !phase->C->post_loop_opts_phase()) {
263     // makes sure we run ::Value to potentially remove type assertion after loop opts
264     phase->C->record_for_post_loop_opts_igvn(this);
265   }
266   if (!_range_check_dependency) {
267     return optimize_integer_cast(phase, T_INT);
268   }
269   return nullptr;
270 }
271 
272 Node* CastIINode::Identity(PhaseGVN* phase) {
273   Node* progress = ConstraintCastNode::Identity(phase);
274   if (progress != this) {
275     return progress;
276   }
277   if (_range_check_dependency) {
278     if (phase->C->post_loop_opts_phase()) {
279       return this->in(1);
280     } else {
281       phase->C->record_for_post_loop_opts_igvn(this);
282     }
283   }
284   return this;
285 }
286 
287 bool CastIINode::cmp(const Node &n) const {
288   return ConstraintCastNode::cmp(n) && ((CastIINode&)n)._range_check_dependency == _range_check_dependency;
289 }
290 
291 uint CastIINode::size_of() const {
292   return sizeof(*this);
293 }
294 
295 #ifndef PRODUCT
296 void CastIINode::dump_spec(outputStream* st) const {
297   ConstraintCastNode::dump_spec(st);
298   if (_range_check_dependency) {
299     st->print(" range check dependency");
300   }
301 }
302 #endif
303 
304 CastIINode* CastIINode::pin_array_access_node() const {
305   assert(_dependency == RegularDependency, "already pinned");
306   if (has_range_check()) {
307     return new CastIINode(in(0), in(1), bottom_type(), StrongDependency, has_range_check());
308   }
309   return nullptr;
310 }
311 
312 
313 const Type* CastLLNode::Value(PhaseGVN* phase) const {
314   const Type* res = ConstraintCastNode::Value(phase);
315   if (res == Type::TOP) {
316     return Type::TOP;
317   }
318   assert(res->isa_long(), "res must be long");
319 
320   return widen_type(phase, res, T_LONG);
321 }
322 
323 Node* CastLLNode::Ideal(PhaseGVN* phase, bool can_reshape) {
324   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
325   if (progress != nullptr) {
326     return progress;
327   }
328   if (!phase->C->post_loop_opts_phase()) {
329     // makes sure we run ::Value to potentially remove type assertion after loop opts
330     phase->C->record_for_post_loop_opts_igvn(this);
331   }
332   // transform (CastLL (ConvI2L ..)) into (ConvI2L (CastII ..)) if the type of the CastLL is narrower than the type of
333   // the ConvI2L.
334   Node* in1 = in(1);
335   if (in1 != nullptr && in1->Opcode() == Op_ConvI2L) {
336     const Type* t = Value(phase);
337     const Type* t_in = phase->type(in1);
338     if (t != Type::TOP && t_in != Type::TOP) {
339       const TypeLong* tl = t->is_long();
340       const TypeLong* t_in_l = t_in->is_long();
341       assert(tl->_lo >= t_in_l->_lo && tl->_hi <= t_in_l->_hi, "CastLL type should be narrower than or equal to the type of its input");
342       assert((tl != t_in_l) == (tl->_lo > t_in_l->_lo || tl->_hi < t_in_l->_hi), "if type differs then this nodes's type must be narrower");
343       if (tl != t_in_l) {
344         const TypeInt* ti = TypeInt::make(checked_cast<jint>(tl->_lo), checked_cast<jint>(tl->_hi), tl->_widen);
345         Node* castii = phase->transform(new CastIINode(in(0), in1->in(1), ti));
346         Node* convi2l = in1->clone();
347         convi2l->set_req(1, castii);
348         return convi2l;
349       }
350     }
351   }
352   return optimize_integer_cast(phase, T_LONG);
353 }
354 
355 //=============================================================================
356 //------------------------------Identity---------------------------------------
357 // If input is already higher or equal to cast type, then this is an identity.
358 Node* CheckCastPPNode::Identity(PhaseGVN* phase) {
359   if (in(1)->is_InlineType() && _type->isa_instptr() && phase->type(in(1))->inline_klass()->is_subtype_of(_type->is_instptr()->instance_klass())) {
360     return in(1);
361   }
362   return ConstraintCastNode::Identity(phase);
363 }
364 
365 //------------------------------Value------------------------------------------
366 // Take 'join' of input and cast-up type, unless working with an Interface
367 const Type* CheckCastPPNode::Value(PhaseGVN* phase) const {
368   if( in(0) && phase->type(in(0)) == Type::TOP ) return Type::TOP;
369 
370   const Type *inn = phase->type(in(1));
371   if( inn == Type::TOP ) return Type::TOP;  // No information yet
372 
373   if (inn->isa_oopptr() && _type->isa_oopptr()) {
374     return ConstraintCastNode::Value(phase);
375   }
376 
377   const TypePtr *in_type = inn->isa_ptr();
378   const TypePtr *my_type = _type->isa_ptr();
379   const Type *result = _type;
380   if (in_type != nullptr && my_type != nullptr) {
381     // TODO 8302672
382     if (!StressReflectiveCode && my_type->isa_aryptr() && in_type->isa_aryptr()) {
383       // Propagate array properties (not flat/null-free)
384       // Don't do this when StressReflectiveCode is enabled because it might lead to
385       // a dying data path while the corresponding flat/null-free check is not folded.
386       my_type = my_type->is_aryptr()->update_properties(in_type->is_aryptr());
387       if (my_type == nullptr) {
388         return Type::TOP; // Inconsistent properties
389       }
390     }
391     TypePtr::PTR in_ptr = in_type->ptr();
392     if (in_ptr == TypePtr::Null) {
393       result = in_type;
394     } else if (in_ptr != TypePtr::Constant) {
395       result = my_type->cast_to_ptr_type(my_type->join_ptr(in_ptr));
396     }
397   }
398 
399   return result;
400 }
401 
402 //=============================================================================
403 //------------------------------Value------------------------------------------
404 const Type* CastX2PNode::Value(PhaseGVN* phase) const {
405   const Type* t = phase->type(in(1));
406   if (t == Type::TOP) return Type::TOP;
407   if (t->base() == Type_X && t->singleton()) {
408     uintptr_t bits = (uintptr_t) t->is_intptr_t()->get_con();
409     if (bits == 0)   return TypePtr::NULL_PTR;
410     return TypeRawPtr::make((address) bits);
411   }
412   return CastX2PNode::bottom_type();
413 }
414 
415 //------------------------------Idealize---------------------------------------
416 static inline bool fits_in_int(const Type* t, bool but_not_min_int = false) {
417   if (t == Type::TOP)  return false;
418   const TypeX* tl = t->is_intptr_t();
419   jint lo = min_jint;
420   jint hi = max_jint;
421   if (but_not_min_int)  ++lo;  // caller wants to negate the value w/o overflow
422   return (tl->_lo >= lo) && (tl->_hi <= hi);
423 }
424 
425 static inline Node* addP_of_X2P(PhaseGVN *phase,
426                                 Node* base,
427                                 Node* dispX,
428                                 bool negate = false) {
429   if (negate) {
430     dispX = phase->transform(new SubXNode(phase->MakeConX(0), dispX));
431   }
432   return new AddPNode(phase->C->top(),
433                       phase->transform(new CastX2PNode(base)),
434                       dispX);
435 }
436 
437 Node *CastX2PNode::Ideal(PhaseGVN *phase, bool can_reshape) {
438   // convert CastX2P(AddX(x, y)) to AddP(CastX2P(x), y) if y fits in an int
439   int op = in(1)->Opcode();
440   Node* x;
441   Node* y;
442   switch (op) {
443     case Op_SubX:
444     x = in(1)->in(1);
445     // Avoid ideal transformations ping-pong between this and AddP for raw pointers.
446     if (phase->find_intptr_t_con(x, -1) == 0)
447     break;
448     y = in(1)->in(2);
449     if (fits_in_int(phase->type(y), true)) {
450       return addP_of_X2P(phase, x, y, true);
451     }
452     break;
453     case Op_AddX:
454     x = in(1)->in(1);
455     y = in(1)->in(2);
456     if (fits_in_int(phase->type(y))) {
457       return addP_of_X2P(phase, x, y);
458     }
459     if (fits_in_int(phase->type(x))) {
460       return addP_of_X2P(phase, y, x);
461     }
462     break;
463   }
464   return nullptr;
465 }
466 
467 //------------------------------Identity---------------------------------------
468 Node* CastX2PNode::Identity(PhaseGVN* phase) {
469   if (in(1)->Opcode() == Op_CastP2X)  return in(1)->in(1);
470   return this;
471 }
472 
473 //=============================================================================
474 //------------------------------Value------------------------------------------
475 const Type* CastP2XNode::Value(PhaseGVN* phase) const {
476   const Type* t = phase->type(in(1));
477   if (t == Type::TOP) return Type::TOP;
478   if (t->base() == Type::RawPtr && t->singleton()) {
479     uintptr_t bits = (uintptr_t) t->is_rawptr()->get_con();
480     return TypeX::make(bits);
481   }
482 
483   if (t->is_zero_type() || !t->maybe_null()) {
484     for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
485       Node* u = fast_out(i);
486       if (u->Opcode() == Op_OrL) {
487         for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
488           Node* cmp = u->fast_out(j);
489           if (cmp->Opcode() == Op_CmpL) {
490             // Give CmpL a chance to get optimized
491             phase->record_for_igvn(cmp);
492           }
493         }
494       }
495     }
496   }
497 
498   return CastP2XNode::bottom_type();
499 }
500 
501 Node *CastP2XNode::Ideal(PhaseGVN *phase, bool can_reshape) {
502   return (in(0) && remove_dead_region(phase, can_reshape)) ? this : nullptr;
503 }
504 
505 //------------------------------Identity---------------------------------------
506 Node* CastP2XNode::Identity(PhaseGVN* phase) {
507   if (in(1)->Opcode() == Op_CastX2P)  return in(1)->in(1);
508   return this;
509 }
510 
511 Node* ConstraintCastNode::make_cast_for_type(Node* c, Node* in, const Type* type, DependencyType dependency,
512                                              const TypeTuple* types) {
513   if (type->isa_int()) {
514     return new CastIINode(c, in, type, dependency, false, types);
515   } else if (type->isa_long()) {
516     return new CastLLNode(c, in, type, dependency, types);
517   } else if (type->isa_float()) {
518     return new CastFFNode(c, in, type, dependency, types);
519   } else if (type->isa_double()) {
520     return new CastDDNode(c, in, type, dependency, types);
521   } else if (type->isa_vect()) {
522     return new CastVVNode(c, in, type, dependency, types);
523   } else if (type->isa_ptr()) {
524     return new CastPPNode(c, in, type, dependency, types);
525   }
526   fatal("unreachable. Invalid cast type.");
527   return nullptr;
528 }
529 
530 Node* ConstraintCastNode::optimize_integer_cast(PhaseGVN* phase, BasicType bt) {
531   PhaseIterGVN *igvn = phase->is_IterGVN();
532   const TypeInteger* this_type = this->type()->is_integer(bt);
533   Node* z = in(1);
534   const TypeInteger* rx = nullptr;
535   const TypeInteger* ry = nullptr;
536   // Similar to ConvI2LNode::Ideal() for the same reasons
537   if (Compile::push_thru_add(phase, z, this_type, rx, ry, bt, bt)) {
538     if (igvn == nullptr) {
539       // Postpone this optimization to iterative GVN, where we can handle deep
540       // AddI chains without an exponential number of recursive Ideal() calls.
541       phase->record_for_igvn(this);
542       return nullptr;
543     }
544     int op = z->Opcode();
545     Node* x = z->in(1);
546     Node* y = z->in(2);
547 
548     Node* cx = find_or_make_integer_cast(igvn, x, in(0), rx, _dependency, bt);
549     Node* cy = find_or_make_integer_cast(igvn, y, in(0), ry, _dependency, bt);
550     if (op == Op_Add(bt)) {
551       return AddNode::make(cx, cy, bt);
552     } else {
553       assert(op == Op_Sub(bt), "");
554       return SubNode::make(cx, cy, bt);
555     }
556     return nullptr;
557   }
558   return nullptr;
559 }
560 
561 const Type* ConstraintCastNode::widen_type(const PhaseGVN* phase, const Type* res, BasicType bt) const {
562   if (!phase->C->post_loop_opts_phase()) {
563     return res;
564   }
565   const TypeInteger* this_type = res->is_integer(bt);
566   const TypeInteger* in_type = phase->type(in(1))->isa_integer(bt);
567   if (in_type != nullptr &&
568       (in_type->lo_as_long() != this_type->lo_as_long() ||
569        in_type->hi_as_long() != this_type->hi_as_long())) {
570     jlong lo1 = this_type->lo_as_long();
571     jlong hi1 = this_type->hi_as_long();
572     int w1 = this_type->_widen;
573     if (lo1 >= 0) {
574       // Keep a range assertion of >=0.
575       lo1 = 0;        hi1 = max_signed_integer(bt);
576     } else if (hi1 < 0) {
577       // Keep a range assertion of <0.
578       lo1 = min_signed_integer(bt); hi1 = -1;
579     } else {
580       lo1 = min_signed_integer(bt); hi1 = max_signed_integer(bt);
581     }
582     return TypeInteger::make(MAX2(in_type->lo_as_long(), lo1),
583                              MIN2(in_type->hi_as_long(), hi1),
584                              MAX2((int)in_type->_widen, w1), bt);
585   }
586   return res;
587 }