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