1 /*
  2  * Copyright (c) 2014, 2025, 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 "opto/addnode.hpp"
 26 #include "opto/callnode.hpp"
 27 #include "opto/castnode.hpp"
 28 #include "opto/cfgnode.hpp"
 29 #include "opto/connode.hpp"
 30 #include "opto/loopnode.hpp"
 31 #include "opto/matcher.hpp"
 32 #include "opto/phaseX.hpp"
 33 #include "opto/subnode.hpp"
 34 #include "opto/type.hpp"
 35 #include "utilities/checkedCast.hpp"
 36 
 37 const ConstraintCastNode::DependencyType ConstraintCastNode::DependencyType::FloatingNarrowing(true, true, "floating narrowing dependency"); // not pinned, narrows type
 38 const ConstraintCastNode::DependencyType ConstraintCastNode::DependencyType::FloatingNonNarrowing(true, false, "floating non-narrowing dependency"); // not pinned, doesn't narrow type
 39 const ConstraintCastNode::DependencyType ConstraintCastNode::DependencyType::NonFloatingNarrowing(false, true, "non-floating narrowing dependency"); // pinned, narrows type
 40 const ConstraintCastNode::DependencyType ConstraintCastNode::DependencyType::NonFloatingNonNarrowing(false, false, "non-floating non-narrowing dependency"); // pinned, doesn't narrow type
 41 
 42 //=============================================================================
 43 // If input is already higher or equal to cast type, then this is an identity.
 44 Node* ConstraintCastNode::Identity(PhaseGVN* phase) {
 45   if (!_dependency.narrows_type()) {
 46     // If this cast doesn't carry a type dependency (i.e. not used for type narrowing), we cannot optimize it.
 47     return this;
 48   }
 49 
 50   // This cast node carries a type dependency. We can remove it if:
 51   // - Its input has a narrower type
 52   // - There's a dominating cast with same input but narrower type
 53   Node* dom = dominating_cast(phase, phase);
 54   if (dom != nullptr) {
 55     return dom;
 56   }
 57   return higher_equal_types(phase, in(1)) ? in(1) : this;
 58 }
 59 
 60 //------------------------------Value------------------------------------------
 61 // Take 'join' of input and cast-up type
 62 const Type* ConstraintCastNode::Value(PhaseGVN* phase) const {
 63   if (in(0) && phase->type(in(0)) == Type::TOP) return Type::TOP;
 64 
 65   const Type* in_type = phase->type(in(1));
 66   const Type* ft = in_type->filter_speculative(_type);
 67 
 68   // Check if both _type and in_type had a speculative type, but for the just
 69   // computed ft the speculative type was dropped.
 70   if (ft->speculative() == nullptr &&
 71       _type->speculative() != nullptr &&
 72       in_type->speculative() != nullptr) {
 73     // Speculative type may have disagreed between cast and input, and was
 74     // dropped in filtering. Recompute so that ft can take speculative type
 75     // of in_type. If we did not do it now, a subsequent ::Value call would
 76     // do it, and violate idempotence of ::Value.
 77     ft = in_type->filter_speculative(ft);
 78   }
 79 
 80 #ifdef ASSERT
 81   // Previous versions of this function had some special case logic,
 82   // which is no longer necessary.  Make sure of the required effects.
 83   switch (Opcode()) {
 84     case Op_CastII:
 85     {
 86       if (in_type == Type::TOP) {
 87         assert(ft == Type::TOP, "special case #1");
 88       }
 89       const Type* rt = in_type->join_speculative(_type);
 90       if (rt->empty()) {
 91         assert(ft == Type::TOP, "special case #2");
 92       }
 93       break;
 94     }
 95     case Op_CastPP:
 96     if (in_type == TypePtr::NULL_PTR &&
 97         _type->isa_ptr() && _type->is_ptr()->_ptr == TypePtr::NotNull) {
 98       assert(ft == Type::TOP, "special case #3");
 99       break;
100     }
101   }
102 #endif //ASSERT
103 
104   return ft;
105 }
106 
107 //------------------------------Ideal------------------------------------------
108 // Return a node which is more "ideal" than the current node.  Strip out
109 // control copies
110 Node* ConstraintCastNode::Ideal(PhaseGVN* phase, bool can_reshape) {
111   if (in(0) != nullptr && remove_dead_region(phase, can_reshape)) {
112     return this;
113   }
114   if (in(1) != nullptr && phase->type(in(1)) != Type::TOP) {
115     return TypeNode::Ideal(phase, can_reshape);
116   }
117   return nullptr;
118 }
119 
120 uint ConstraintCastNode::hash() const {
121   return TypeNode::hash() + _dependency.hash() + (_extra_types != nullptr ? _extra_types->hash() : 0);
122 }
123 
124 bool ConstraintCastNode::cmp(const Node &n) const {
125   if (!TypeNode::cmp(n)) {
126     return false;
127   }
128   ConstraintCastNode& cast = (ConstraintCastNode&) n;
129   if (!cast._dependency.cmp(_dependency)) {
130     return false;
131   }
132   if (_extra_types == nullptr || cast._extra_types == nullptr) {
133     return _extra_types == cast._extra_types;
134   }
135   return _extra_types->eq(cast._extra_types);
136 }
137 
138 uint ConstraintCastNode::size_of() const {
139   return sizeof(*this);
140 }
141 
142 Node* ConstraintCastNode::make_cast_for_basic_type(Node* c, Node* n, const Type* t, const DependencyType& dependency, BasicType bt) {
143   switch(bt) {
144   case T_INT:
145     return new CastIINode(c, n, t, dependency);
146   case T_LONG:
147     return new CastLLNode(c, n, t, dependency);
148   default:
149     fatal("Bad basic type %s", type2name(bt));
150   }
151   return nullptr;
152 }
153 
154 TypeNode* ConstraintCastNode::dominating_cast(PhaseGVN* gvn, PhaseTransform* pt) const {
155   // See discussion at definition of ConstraintCastNode::DependencyType: replacing this cast with a dominating one is
156   // not safe if _dependency.narrows_type() is not true.
157   assert(_dependency.narrows_type(), "cast can't be replaced by dominating one");
158   Node* val = in(1);
159   Node* ctl = in(0);
160   int opc = Opcode();
161   if (ctl == nullptr) {
162     return nullptr;
163   }
164   // Range check CastIIs may all end up under a single range check and
165   // in that case only the narrower CastII would be kept by the code
166   // below which would be incorrect.
167   if (is_CastII() && as_CastII()->has_range_check()) {
168     return nullptr;
169   }
170   if (type()->isa_rawptr() && (gvn->type_or_null(val) == nullptr || gvn->type(val)->isa_oopptr())) {
171     return nullptr;
172   }
173   for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
174     Node* u = val->fast_out(i);
175     if (u != this &&
176         u->outcnt() > 0 &&
177         u->Opcode() == opc &&
178         u->in(0) != nullptr &&
179         higher_equal_types(gvn, u)) {
180       if (pt->is_dominator(u->in(0), ctl)) {
181         return u->as_Type();
182       }
183       if (is_CheckCastPP() && u->in(1)->is_Proj() && u->in(1)->in(0)->is_Allocate() &&
184           u->in(0)->is_Proj() && u->in(0)->in(0)->is_Initialize() &&
185           u->in(1)->in(0)->as_Allocate()->initialization() == u->in(0)->in(0)) {
186         // CheckCastPP following an allocation always dominates all
187         // use of the allocation result
188         return u->as_Type();
189       }
190     }
191   }
192   return nullptr;
193 }
194 
195 bool ConstraintCastNode::higher_equal_types(PhaseGVN* phase, const Node* other) const {
196   const Type* t = phase->type(other);
197   if (!t->higher_equal_speculative(type())) {
198     return false;
199   }
200   if (_extra_types != nullptr) {
201     for (uint i = 0; i < _extra_types->cnt(); ++i) {
202       if (!t->higher_equal_speculative(_extra_types->field_at(i))) {
203         return false;
204       }
205     }
206   }
207   return true;
208 }
209 
210 #ifndef PRODUCT
211 void ConstraintCastNode::dump_spec(outputStream *st) const {
212   TypeNode::dump_spec(st);
213   if (_extra_types != nullptr) {
214     st->print(" extra types: ");
215     _extra_types->dump_on(st);
216   }
217   st->print(" ");
218   _dependency.dump_on(st);
219 }
220 #endif
221 
222 CastIINode* CastIINode::make_with(Node* parent, const TypeInteger* type, const DependencyType& dependency) const {
223   return new CastIINode(in(0), parent, type, dependency, _range_check_dependency, _extra_types);
224 }
225 
226 CastLLNode* CastLLNode::make_with(Node* parent, const TypeInteger* type, const DependencyType& dependency) const {
227   return new CastLLNode(in(0), parent, type, dependency, _extra_types);
228 }
229 
230 Node* ConstraintCastNode::find_or_make_integer_cast(PhaseIterGVN* igvn, Node* parent, const TypeInteger* type, const DependencyType& dependency) const {
231   Node* n = make_with(parent, type, dependency);
232   Node* existing = igvn->hash_find_insert(n);
233   if (existing != nullptr) {
234     n->destruct(igvn);
235     return existing;
236   }
237   return igvn->register_new_node_with_optimizer(n);
238 }
239 
240 Node *CastIINode::Ideal(PhaseGVN *phase, bool can_reshape) {
241   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
242   if (progress != nullptr) {
243     return progress;
244   }
245   if (!phase->C->post_loop_opts_phase()) {
246     // makes sure we run widen_type() to potentially common type assertions after loop opts
247     phase->C->record_for_post_loop_opts_igvn(this);
248   }
249   if (!_range_check_dependency || phase->C->post_loop_opts_phase()) {
250     return optimize_integer_cast(phase, T_INT);
251   }
252   return nullptr;
253 }
254 
255 Node* CastIINode::Identity(PhaseGVN* phase) {
256   Node* progress = ConstraintCastNode::Identity(phase);
257   if (progress != this) {
258     return progress;
259   }
260   return this;
261 }
262 
263 bool CastIINode::cmp(const Node &n) const {
264   return ConstraintCastNode::cmp(n) && ((CastIINode&)n)._range_check_dependency == _range_check_dependency;
265 }
266 
267 uint CastIINode::size_of() const {
268   return sizeof(*this);
269 }
270 
271 #ifndef PRODUCT
272 void CastIINode::dump_spec(outputStream* st) const {
273   ConstraintCastNode::dump_spec(st);
274   if (_range_check_dependency) {
275     st->print(" range check dependency");
276   }
277 }
278 #endif
279 
280 CastIINode* CastIINode::pin_array_access_node() const {
281   assert(_dependency.is_floating(), "already pinned");
282   if (has_range_check()) {
283     return new CastIINode(in(0), in(1), bottom_type(), _dependency.with_pinned_dependency(), has_range_check());
284   }
285   return nullptr;
286 }
287 
288 void CastIINode::remove_range_check_cast(Compile* C) {
289   if (has_range_check()) {
290     // Range check CastII nodes feed into an address computation subgraph. Remove them to let that subgraph float freely.
291     // For memory access or integer divisions nodes that depend on the cast, record the dependency on the cast's control
292     // as a precedence edge, so they can't float above the cast in case that cast's narrowed type helped eliminate a
293     // range check or a null divisor check.
294     assert(in(0) != nullptr, "All RangeCheck CastII must have a control dependency");
295     ResourceMark rm;
296     Unique_Node_List wq;
297     wq.push(this);
298     for (uint next = 0; next < wq.size(); ++next) {
299       Node* m = wq.at(next);
300       for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
301         Node* use = m->fast_out(i);
302         if (use->is_Mem() || use->is_div_or_mod(T_INT) || use->is_div_or_mod(T_LONG)) {
303           use->ensure_control_or_add_prec(in(0));
304         } else if (!use->is_CFG() && !use->is_Phi()) {
305           wq.push(use);
306         }
307       }
308     }
309     subsume_by(in(1), C);
310     if (outcnt() == 0) {
311       disconnect_inputs(C);
312     }
313   }
314 }
315 
316 bool CastLLNode::is_inner_loop_backedge(IfProjNode* proj) {
317   if (proj != nullptr) {
318     Node* ctrl_use = proj->unique_ctrl_out_or_null();
319     if (ctrl_use != nullptr && ctrl_use->Opcode() == Op_Loop &&
320         ctrl_use->in(2) == proj &&
321         ctrl_use->as_Loop()->is_loop_nest_inner_loop()) {
322       return true;
323     }
324   }
325   return false;
326 }
327 
328 bool CastLLNode::cmp_used_at_inner_loop_exit_test(CmpNode* cmp) {
329   for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
330     Node* bol = cmp->fast_out(i);
331     if (bol->Opcode() == Op_Bool) {
332       for (DUIterator_Fast jmax, j = bol->fast_outs(jmax); j < jmax; j++) {
333         Node* iff = bol->fast_out(j);
334         if (iff->Opcode() == Op_If) {
335           IfTrueNode* true_proj = iff->as_If()->true_proj_or_null();
336           IfFalseNode* false_proj = iff->as_If()->false_proj_or_null();
337           if (is_inner_loop_backedge(true_proj) || is_inner_loop_backedge(false_proj)) {
338             return true;
339           }
340         }
341       }
342     }
343   }
344   return false;
345 }
346 
347 // Find if this is a cast node added by PhaseIdealLoop::create_loop_nest() to narrow the number of iterations of the
348 // inner loop
349 bool CastLLNode::used_at_inner_loop_exit_test() const {
350   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
351     Node* convl2i = fast_out(i);
352     if (convl2i->Opcode() == Op_ConvL2I) {
353       for (DUIterator_Fast jmax, j = convl2i->fast_outs(jmax); j < jmax; j++) {
354         Node* cmp_or_sub = convl2i->fast_out(j);
355         if (cmp_or_sub->Opcode() == Op_CmpI) {
356           if (cmp_used_at_inner_loop_exit_test(cmp_or_sub->as_Cmp())) {
357             // (Loop .. .. (IfProj (If (Bool (CmpI (ConvL2I (CastLL )))))))
358             return true;
359           }
360         } else if (cmp_or_sub->Opcode() == Op_SubI && cmp_or_sub->in(1)->find_int_con(-1) == 0) {
361           for (DUIterator_Fast kmax, k = cmp_or_sub->fast_outs(kmax); k < kmax; k++) {
362             Node* cmp = cmp_or_sub->fast_out(k);
363             if (cmp->Opcode() == Op_CmpI) {
364               if (cmp_used_at_inner_loop_exit_test(cmp->as_Cmp())) {
365                 // (Loop .. .. (IfProj (If (Bool (CmpI (SubI 0 (ConvL2I (CastLL ))))))))
366                 return true;
367               }
368             }
369           }
370         }
371       }
372     }
373   }
374   return false;
375 }
376 
377 Node* CastLLNode::Ideal(PhaseGVN* phase, bool can_reshape) {
378   Node* progress = ConstraintCastNode::Ideal(phase, can_reshape);
379   if (progress != nullptr) {
380     return progress;
381   }
382   if (!phase->C->post_loop_opts_phase()) {
383     // makes sure we run widen_type() to potentially common type assertions after loop opts
384     phase->C->record_for_post_loop_opts_igvn(this);
385   }
386   // transform (CastLL (ConvI2L ..)) into (ConvI2L (CastII ..)) if the type of the CastLL is narrower than the type of
387   // the ConvI2L.
388   Node* in1 = in(1);
389   if (in1 != nullptr && in1->Opcode() == Op_ConvI2L) {
390     const Type* t = Value(phase);
391     const Type* t_in = phase->type(in1);
392     if (t != Type::TOP && t_in != Type::TOP) {
393       const TypeLong* tl = t->is_long();
394       const TypeLong* t_in_l = t_in->is_long();
395       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");
396       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");
397       if (tl != t_in_l) {
398         const TypeInt* ti = TypeInt::make(checked_cast<jint>(tl->_lo), checked_cast<jint>(tl->_hi), tl->_widen);
399         Node* castii = phase->transform(new CastIINode(in(0), in1->in(1), ti));
400         Node* convi2l = in1->clone();
401         convi2l->set_req(1, castii);
402         return convi2l;
403       }
404     }
405   }
406   // If it's a cast created by PhaseIdealLoop::short_running_loop(), don't transform it until the counted loop is created
407   // in next loop opts pass
408   if (!can_reshape || !used_at_inner_loop_exit_test()) {
409     return optimize_integer_cast(phase, T_LONG);
410   }
411   return nullptr;
412 }
413 
414 //------------------------------Value------------------------------------------
415 // Take 'join' of input and cast-up type, unless working with an Interface
416 const Type* CheckCastPPNode::Value(PhaseGVN* phase) const {
417   if( in(0) && phase->type(in(0)) == Type::TOP ) return Type::TOP;
418 
419   const Type *inn = phase->type(in(1));
420   if( inn == Type::TOP ) return Type::TOP;  // No information yet
421 
422   if (inn->isa_oopptr() && _type->isa_oopptr()) {
423     return ConstraintCastNode::Value(phase);
424   }
425 
426   const TypePtr *in_type = inn->isa_ptr();
427   const TypePtr *my_type = _type->isa_ptr();
428   const Type *result = _type;
429   if (in_type != nullptr && my_type != nullptr) {
430     TypePtr::PTR in_ptr = in_type->ptr();
431     if (in_ptr == TypePtr::Null) {
432       result = in_type;
433     } else if (in_ptr != TypePtr::Constant) {
434       result =  my_type->cast_to_ptr_type(my_type->join_ptr(in_ptr));
435     }
436   }
437 
438   return result;
439 }
440 
441 //=============================================================================
442 //------------------------------Value------------------------------------------
443 const Type* CastX2PNode::Value(PhaseGVN* phase) const {
444   const Type* t = phase->type(in(1));
445   if (t == Type::TOP) return Type::TOP;
446   if (t->base() == Type_X && t->singleton()) {
447     uintptr_t bits = (uintptr_t) t->is_intptr_t()->get_con();
448     if (bits == 0)   return TypePtr::NULL_PTR;
449     return TypeRawPtr::make((address) bits);
450   }
451   return CastX2PNode::bottom_type();
452 }
453 
454 //------------------------------Idealize---------------------------------------
455 static inline bool fits_in_int(const Type* t, bool but_not_min_int = false) {
456   if (t == Type::TOP)  return false;
457   const TypeX* tl = t->is_intptr_t();
458   jint lo = min_jint;
459   jint hi = max_jint;
460   if (but_not_min_int)  ++lo;  // caller wants to negate the value w/o overflow
461   return (tl->_lo >= lo) && (tl->_hi <= hi);
462 }
463 
464 static inline Node* addP_of_X2P(PhaseGVN *phase,
465                                 Node* base,
466                                 Node* dispX,
467                                 bool negate = false) {
468   if (negate) {
469     dispX = phase->transform(new SubXNode(phase->MakeConX(0), dispX));
470   }
471   return new AddPNode(phase->C->top(),
472                       phase->transform(new CastX2PNode(base)),
473                       dispX);
474 }
475 
476 Node *CastX2PNode::Ideal(PhaseGVN *phase, bool can_reshape) {
477   // convert CastX2P(AddX(x, y)) to AddP(CastX2P(x), y) if y fits in an int
478   int op = in(1)->Opcode();
479   Node* x;
480   Node* y;
481   switch (op) {
482     case Op_SubX:
483     x = in(1)->in(1);
484     // Avoid ideal transformations ping-pong between this and AddP for raw pointers.
485     if (phase->find_intptr_t_con(x, -1) == 0)
486     break;
487     y = in(1)->in(2);
488     if (fits_in_int(phase->type(y), true)) {
489       return addP_of_X2P(phase, x, y, true);
490     }
491     break;
492     case Op_AddX:
493     x = in(1)->in(1);
494     y = in(1)->in(2);
495     if (fits_in_int(phase->type(y))) {
496       return addP_of_X2P(phase, x, y);
497     }
498     if (fits_in_int(phase->type(x))) {
499       return addP_of_X2P(phase, y, x);
500     }
501     break;
502   }
503   return nullptr;
504 }
505 
506 //------------------------------Identity---------------------------------------
507 Node* CastX2PNode::Identity(PhaseGVN* phase) {
508   if (in(1)->Opcode() == Op_CastP2X)  return in(1)->in(1);
509   return this;
510 }
511 
512 //=============================================================================
513 //------------------------------Value------------------------------------------
514 const Type* CastP2XNode::Value(PhaseGVN* phase) const {
515   const Type* t = phase->type(in(1));
516   if (t == Type::TOP) return Type::TOP;
517   if (t->base() == Type::RawPtr && t->singleton()) {
518     uintptr_t bits = (uintptr_t) t->is_rawptr()->get_con();
519     return TypeX::make(bits);
520   }
521   return CastP2XNode::bottom_type();
522 }
523 
524 Node *CastP2XNode::Ideal(PhaseGVN *phase, bool can_reshape) {
525   return (in(0) && remove_dead_region(phase, can_reshape)) ? this : nullptr;
526 }
527 
528 //------------------------------Identity---------------------------------------
529 Node* CastP2XNode::Identity(PhaseGVN* phase) {
530   if (in(1)->Opcode() == Op_CastX2P)  return in(1)->in(1);
531   return this;
532 }
533 
534 Node* ConstraintCastNode::make_cast_for_type(Node* c, Node* in, const Type* type, const DependencyType& dependency,
535                                              const TypeTuple* types) {
536   if (type->isa_int()) {
537     return new CastIINode(c, in, type, dependency, false, types);
538   } else if (type->isa_long()) {
539     return new CastLLNode(c, in, type, dependency, types);
540   } else if (type->isa_half_float()) {
541     return new CastHHNode(c, in, type, dependency, types);
542   } else if (type->isa_float()) {
543     return new CastFFNode(c, in, type, dependency, types);
544   } else if (type->isa_double()) {
545     return new CastDDNode(c, in, type, dependency, types);
546   } else if (type->isa_vect()) {
547     return new CastVVNode(c, in, type, dependency, types);
548   } else if (type->isa_ptr()) {
549     return new CastPPNode(c, in, type, dependency, types);
550   }
551   fatal("unreachable. Invalid cast type.");
552   return nullptr;
553 }
554 
555 Node* ConstraintCastNode::optimize_integer_cast_of_add(PhaseGVN* phase, BasicType bt) {
556   PhaseIterGVN *igvn = phase->is_IterGVN();
557   const TypeInteger* this_type = this->type()->isa_integer(bt);
558   if (this_type == nullptr) {
559     return nullptr;
560   }
561 
562   Node* z = in(1);
563   const TypeInteger* rx = nullptr;
564   const TypeInteger* ry = nullptr;
565   // Similar to ConvI2LNode::Ideal() for the same reasons
566   if (Compile::push_thru_add(phase, z, this_type, rx, ry, bt, bt)) {
567     if (igvn == nullptr) {
568       // Postpone this optimization to iterative GVN, where we can handle deep
569       // AddI chains without an exponential number of recursive Ideal() calls.
570       phase->record_for_igvn(this);
571       return nullptr;
572     }
573     int op = z->Opcode();
574     Node* x = z->in(1);
575     Node* y = z->in(2);
576 
577     const TypeInteger* tx = phase->type(x)->is_integer(bt);
578     const TypeInteger* ty = phase->type(y)->is_integer(bt);
579 
580     // (Cast (Add x y) tz) is transformed into (Add (Cast x rx) (Cast y ry))
581     //
582     // tz = [tzlo, tzhi]
583     // rx = [rxlo, rxhi]
584     // ry = [rylo, ryhi]
585     // with type of x, tx = [txlo, txhi]
586     // with type of y, ty = [tylo, tyhi]
587     //
588     // From Compile::push_thru_add():
589     // rxlo = max(tzlo - tyhi, txlo)
590     // rxhi = min(tzhi - tylo, txhi)
591     // rylo = max(tzlo - txhi, tylo)
592     // ryhi = min(tzhi - txlo, tyhi)
593     //
594     // If x is a constant, then txlo = txhi
595     // rxlo = txlo, rxhi = txhi
596     // The bounds of the type of the Add after transformation then is:
597     // rxlo + rylo >= txlo + tzlo - txhi >= tzlo
598     // rxhi + ryhi <= txhi + tzhi - txlo <= tzhi
599     // The resulting type is not wider than the type of the Cast
600     // before transformation
601     //
602     // If neither x nor y are constant then the type of the resulting
603     // Add can be wider than the type of the type of the Cast before
604     // transformation.
605     // For instance, tx = [0, 10], ty = [0, 10], tz = [0, 10]
606     // then rx = [0, 10], ry = [0, 10]
607     // and rx + ry = [0, 20] which is wider than tz
608     //
609     // Same reasoning applies to (Cast (Sub x y) tz)
610     const DependencyType& dependency = (!tx->is_con() && !ty->is_con()) ? _dependency.with_non_narrowing() : _dependency;
611     Node* cx = find_or_make_integer_cast(igvn, x, rx, dependency);
612     Node* cy = find_or_make_integer_cast(igvn, y, ry, dependency);
613     if (op == Op_Add(bt)) {
614       return AddNode::make(cx, cy, bt);
615     } else {
616       assert(op == Op_Sub(bt), "");
617       return SubNode::make(cx, cy, bt);
618     }
619     return nullptr;
620   }
621   return nullptr;
622 }
623 
624 Node* ConstraintCastNode::optimize_integer_cast(PhaseGVN* phase, BasicType bt) {
625   Node* res = optimize_integer_cast_of_add(phase, bt);
626   if (res != nullptr) {
627     return res;
628   }
629   const Type* t = Value(phase);
630   if (t != Type::TOP && phase->C->post_loop_opts_phase()) {
631     const Type* bottom_t = bottom_type();
632     const TypeInteger* wide_t = widen_type(phase, bottom_t, bt);
633     if (wide_t != bottom_t) {
634       // Widening the type of the Cast (to allow some commoning) causes the Cast to change how it can be optimized (if
635       // type of its input is narrower than the Cast's type, we can't remove it to not loose the control dependency).
636       return make_with(in(1), wide_t, _dependency.with_non_narrowing());
637     }
638   }
639   return nullptr;
640 }
641 
642 const TypeInteger* ConstraintCastNode::widen_type(const PhaseGVN* phase, const Type* res, BasicType bt) const {
643   const TypeInteger* this_type = res->is_integer(bt);
644   // At VerifyConstraintCasts == 1, we verify the ConstraintCastNodes that are present during code
645   // emission. This allows us detecting possible mis-scheduling due to these nodes being pinned at
646   // the wrong control nodes.
647   // At VerifyConstraintCasts == 2, we do not perform widening so that we can verify the
648   // correctness of more ConstraintCastNodes. This further helps us detect possible
649   // mis-transformations that may happen due to these nodes being pinned at the wrong control
650   // nodes.
651   if (VerifyConstraintCasts > 1) {
652     return this_type;
653   }
654 
655   const TypeInteger* in_type = phase->type(in(1))->isa_integer(bt);
656   if (in_type != nullptr &&
657       (in_type->lo_as_long() != this_type->lo_as_long() ||
658        in_type->hi_as_long() != this_type->hi_as_long())) {
659     jlong lo1 = this_type->lo_as_long();
660     jlong hi1 = this_type->hi_as_long();
661     int w1 = this_type->_widen;
662     if (lo1 >= 0) {
663       // Keep a range assertion of >=0.
664       lo1 = 0;        hi1 = max_signed_integer(bt);
665     } else if (hi1 < 0) {
666       // Keep a range assertion of <0.
667       lo1 = min_signed_integer(bt); hi1 = -1;
668     } else {
669       lo1 = min_signed_integer(bt); hi1 = max_signed_integer(bt);
670     }
671     return TypeInteger::make(MAX2(in_type->lo_as_long(), lo1),
672                              MIN2(in_type->hi_as_long(), hi1),
673                              MAX2((int)in_type->_widen, w1), bt);
674   }
675   return this_type;
676 }