1 /*
   2  * Copyright (c) 2015, 2018, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  27 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  28 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  29 #include "gc/shenandoah/shenandoahBrooksPointer.hpp"
  30 #include "gc/shenandoah/shenandoahHeap.hpp"
  31 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  32 #include "gc/shenandoah/shenandoahRuntime.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/block.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/movenode.hpp"
  38 #include "opto/phaseX.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/runtime.hpp"
  41 #include "opto/subnode.hpp"
  42 
  43 Node* ShenandoahBarrierNode::skip_through_barrier(Node* n) {
  44   if (n == NULL) {
  45     return NULL;
  46   }
  47   if (n->Opcode() == Op_ShenandoahEnqueueBarrier) {
  48     n = n->in(1);
  49   }
  50 
  51   if (n->is_ShenandoahBarrier()) {
  52     return n->in(ValueIn);
  53   } else if (n->is_Phi() &&
  54              n->req() == 3 &&
  55              n->in(1) != NULL &&
  56              n->in(1)->is_ShenandoahBarrier() &&
  57              n->in(2) != NULL &&
  58              n->in(2)->bottom_type() == TypePtr::NULL_PTR &&
  59              n->in(0) != NULL &&
  60              n->in(0)->in(1) != NULL &&
  61              n->in(0)->in(1)->is_IfProj() &&
  62              n->in(0)->in(2) != NULL &&
  63              n->in(0)->in(2)->is_IfProj() &&
  64              n->in(0)->in(1)->in(0) != NULL &&
  65              n->in(0)->in(1)->in(0) == n->in(0)->in(2)->in(0) &&
  66              n->in(1)->in(ValueIn)->Opcode() == Op_CastPP) {
  67     Node* iff = n->in(0)->in(1)->in(0);
  68     Node* res = n->in(1)->in(ValueIn)->in(1);
  69     if (iff->is_If() &&
  70         iff->in(1) != NULL &&
  71         iff->in(1)->is_Bool() &&
  72         iff->in(1)->as_Bool()->_test._test == BoolTest::ne &&
  73         iff->in(1)->in(1) != NULL &&
  74         iff->in(1)->in(1)->Opcode() == Op_CmpP &&
  75         iff->in(1)->in(1)->in(1) != NULL &&
  76         iff->in(1)->in(1)->in(1) == res &&
  77         iff->in(1)->in(1)->in(2) != NULL &&
  78         iff->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
  79       return res;
  80     }
  81   }
  82   return n;
  83 }
  84 
  85 bool ShenandoahBarrierNode::needs_barrier(PhaseGVN* phase, ShenandoahBarrierNode* orig, Node* n, Node* rb_mem, bool allow_fromspace) {
  86   Unique_Node_List visited;
  87   return needs_barrier_impl(phase, orig, n, rb_mem, allow_fromspace, visited);
  88 }
  89 
  90 bool ShenandoahBarrierNode::needs_barrier_impl(PhaseGVN* phase, ShenandoahBarrierNode* orig, Node* n, Node* rb_mem, bool allow_fromspace, Unique_Node_List &visited) {
  91   if (visited.member(n)) {
  92     return false; // Been there.
  93   }
  94   visited.push(n);
  95 
  96   if (n->is_Allocate()) {
  97     return false;
  98   }
  99 
 100   if (n->is_CallJava() || n->Opcode() == Op_CallLeafNoFP) {
 101     return true;
 102   }
 103 
 104   const Type* type = phase->type(n);
 105   if (type == Type::TOP) {
 106     return false;
 107   }
 108   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
 109     return false;
 110   }
 111   if (type->make_oopptr() && type->make_oopptr()->const_oop() != NULL) {
 112     return false;
 113   }
 114 
 115   if (ShenandoahOptimizeStableFinals) {
 116     const TypeAryPtr* ary = type->isa_aryptr();
 117     if (ary && ary->is_stable() && allow_fromspace) {
 118       return false;
 119     }
 120   }
 121 
 122   if (n->is_CheckCastPP() || n->is_ConstraintCast() || n->Opcode() == Op_ShenandoahEnqueueBarrier) {
 123     return needs_barrier_impl(phase, orig, n->in(1), rb_mem, allow_fromspace, visited);
 124   }
 125   if (n->is_Parm()) {
 126     return true;
 127   }
 128   if (n->is_Proj()) {
 129     return needs_barrier_impl(phase, orig, n->in(0), rb_mem, allow_fromspace, visited);
 130   }
 131 
 132   if (n->Opcode() == Op_ShenandoahWBMemProj) {
 133     return needs_barrier_impl(phase, orig, n->in(ShenandoahWBMemProjNode::WriteBarrier), rb_mem, allow_fromspace, visited);
 134   }
 135   if (n->is_Phi()) {
 136     bool need_barrier = false;
 137     for (uint i = 1; i < n->req() && ! need_barrier; i++) {
 138       Node* input = n->in(i);
 139       if (input == NULL) {
 140         need_barrier = true; // Phi not complete yet?
 141       } else if (needs_barrier_impl(phase, orig, input, rb_mem, allow_fromspace, visited)) {
 142         need_barrier = true;
 143       }
 144     }
 145     return need_barrier;
 146   }
 147   if (n->is_CMove()) {
 148     return needs_barrier_impl(phase, orig, n->in(CMoveNode::IfFalse), rb_mem, allow_fromspace, visited) ||
 149            needs_barrier_impl(phase, orig, n->in(CMoveNode::IfTrue ), rb_mem, allow_fromspace, visited);
 150   }
 151   if (n->Opcode() == Op_CreateEx) {
 152     return true;
 153   }
 154   if (n->Opcode() == Op_ShenandoahWriteBarrier) {
 155     return false;
 156   }
 157   if (n->Opcode() == Op_ShenandoahReadBarrier) {
 158     if (rb_mem == n->in(Memory)) {
 159       return false;
 160     } else {
 161       return true;
 162     }
 163   }
 164 
 165   if (n->Opcode() == Op_LoadP ||
 166       n->Opcode() == Op_LoadN ||
 167       n->Opcode() == Op_GetAndSetP ||
 168       n->Opcode() == Op_CompareAndExchangeP ||
 169       n->Opcode() == Op_ShenandoahCompareAndExchangeP ||
 170       n->Opcode() == Op_GetAndSetN ||
 171       n->Opcode() == Op_CompareAndExchangeN ||
 172       n->Opcode() == Op_ShenandoahCompareAndExchangeN) {
 173     return true;
 174   }
 175   if (n->Opcode() == Op_DecodeN ||
 176       n->Opcode() == Op_EncodeP) {
 177     return needs_barrier_impl(phase, orig, n->in(1), rb_mem, allow_fromspace, visited);
 178   }
 179 
 180 #ifdef ASSERT
 181   tty->print("need barrier on?: "); n->dump();
 182   ShouldNotReachHere();
 183 #endif
 184   return true;
 185 }
 186 
 187 bool ShenandoahReadBarrierNode::dominates_memory_rb_impl(PhaseGVN* phase,
 188                                                          Node* b1,
 189                                                          Node* b2,
 190                                                          Node* current,
 191                                                          bool linear) {
 192   ResourceMark rm;
 193   VectorSet visited(Thread::current()->resource_area());
 194   Node_Stack phis(0);
 195 
 196   for(int i = 0; i < 10; i++) {
 197     if (current == NULL) {
 198       return false;
 199     } else if (visited.test_set(current->_idx) || current->is_top() || current == b1) {
 200       current = NULL;
 201       while (phis.is_nonempty() && current == NULL) {
 202         uint idx = phis.index();
 203         Node* phi = phis.node();
 204         if (idx >= phi->req()) {
 205           phis.pop();
 206         } else {
 207           current = phi->in(idx);
 208           phis.set_index(idx+1);
 209         }
 210       }
 211       if (current == NULL) {
 212         return true;
 213       }
 214     } else if (current == phase->C->immutable_memory()) {
 215       return false;
 216     } else if (current->isa_Phi()) {
 217       if (!linear) {
 218         return false;
 219       }
 220       phis.push(current, 2);
 221       current = current->in(1);
 222     } else if (current->Opcode() == Op_ShenandoahWriteBarrier) {
 223       const Type* in_type = current->bottom_type();
 224       const Type* this_type = b2->bottom_type();
 225       if (is_independent(in_type, this_type)) {
 226         current = current->in(Memory);
 227       } else {
 228         return false;
 229       }
 230     } else if (current->Opcode() == Op_ShenandoahWBMemProj) {
 231       current = current->in(ShenandoahWBMemProjNode::WriteBarrier);
 232     } else if (current->is_Proj()) {
 233       current = current->in(0);
 234     } else if (current->is_Call()) {
 235       return false; // TODO: Maybe improve by looking at the call's memory effects?
 236     } else if (current->is_MemBar()) {
 237       return false; // TODO: Do we need to stop at *any* membar?
 238     } else if (current->is_MergeMem()) {
 239       const TypePtr* adr_type = brooks_pointer_type(phase->type(b2));
 240       uint alias_idx = phase->C->get_alias_index(adr_type);
 241       current = current->as_MergeMem()->memory_at(alias_idx);
 242     } else {
 243 #ifdef ASSERT
 244       current->dump();
 245 #endif
 246       ShouldNotReachHere();
 247       return false;
 248     }
 249   }
 250   return false;
 251 }
 252 
 253 bool ShenandoahReadBarrierNode::is_independent(Node* mem) {
 254   if (mem->is_Phi() || mem->is_Proj() || mem->is_MergeMem()) {
 255     return true;
 256   } else if (mem->Opcode() == Op_ShenandoahWBMemProj) {
 257     return true;
 258   } else if (mem->Opcode() == Op_ShenandoahWriteBarrier) {
 259     const Type* mem_type = mem->bottom_type();
 260     const Type* this_type = bottom_type();
 261     if (is_independent(mem_type, this_type)) {
 262       return true;
 263     } else {
 264       return false;
 265     }
 266   } else if (mem->is_Call() || mem->is_MemBar()) {
 267     return false;
 268   }
 269 #ifdef ASSERT
 270   mem->dump();
 271 #endif
 272   ShouldNotReachHere();
 273   return true;
 274 }
 275 
 276 bool ShenandoahReadBarrierNode::dominates_memory_rb(PhaseGVN* phase, Node* b1, Node* b2, bool linear) {
 277   return dominates_memory_rb_impl(phase, b1->in(Memory), b2, b2->in(Memory), linear);
 278 }
 279 
 280 bool ShenandoahReadBarrierNode::is_independent(const Type* in_type, const Type* this_type) {
 281   assert(in_type->isa_oopptr(), "expect oop ptr");
 282   assert(this_type->isa_oopptr(), "expect oop ptr");
 283 
 284   ciKlass* in_kls = in_type->is_oopptr()->klass();
 285   ciKlass* this_kls = this_type->is_oopptr()->klass();
 286   if (in_kls != NULL && this_kls != NULL &&
 287       in_kls->is_loaded() && this_kls->is_loaded() &&
 288       (!in_kls->is_subclass_of(this_kls)) &&
 289       (!this_kls->is_subclass_of(in_kls))) {
 290     return true;
 291   }
 292   return false;
 293 }
 294 
 295 Node* ShenandoahReadBarrierNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 296   if (! can_reshape) {
 297     return NULL;
 298   }
 299 
 300   if (in(Memory) == phase->C->immutable_memory()) return NULL;
 301 
 302   // If memory input is a MergeMem, take the appropriate slice out of it.
 303   Node* mem_in = in(Memory);
 304   if (mem_in->isa_MergeMem()) {
 305     const TypePtr* adr_type = brooks_pointer_type(bottom_type());
 306     uint alias_idx = phase->C->get_alias_index(adr_type);
 307     mem_in = mem_in->as_MergeMem()->memory_at(alias_idx);
 308     set_req(Memory, mem_in);
 309     return this;
 310   }
 311 
 312   Node* input = in(Memory);
 313   if (input->Opcode() == Op_ShenandoahWBMemProj) {
 314     ResourceMark rm;
 315     VectorSet seen(Thread::current()->resource_area());
 316     Node* n = in(Memory);
 317     while (n->Opcode() == Op_ShenandoahWBMemProj &&
 318            n->in(ShenandoahWBMemProjNode::WriteBarrier) != NULL &&
 319            n->in(ShenandoahWBMemProjNode::WriteBarrier)->Opcode() == Op_ShenandoahWriteBarrier &&
 320            n->in(ShenandoahWBMemProjNode::WriteBarrier)->in(Memory) != NULL) {
 321       if (seen.test_set(n->_idx)) {
 322         return NULL; // loop
 323       }
 324       n = n->in(ShenandoahWBMemProjNode::WriteBarrier)->in(Memory);
 325     }
 326 
 327     Node* wb = input->in(ShenandoahWBMemProjNode::WriteBarrier);
 328     const Type* in_type = phase->type(wb);
 329     // is_top() test not sufficient here: we can come here after CCP
 330     // in a dead branch of the graph that has not yet been removed.
 331     if (in_type == Type::TOP) return NULL; // Dead path.
 332     assert(wb->Opcode() == Op_ShenandoahWriteBarrier, "expect write barrier");
 333     if (is_independent(in_type, _type)) {
 334       phase->igvn_rehash_node_delayed(wb);
 335       set_req(Memory, wb->in(Memory));
 336       if (can_reshape && input->outcnt() == 0) {
 337         phase->is_IterGVN()->_worklist.push(input);
 338       }
 339       return this;
 340     }
 341   }
 342   return NULL;
 343 }
 344 
 345 ShenandoahWriteBarrierNode::ShenandoahWriteBarrierNode(Compile* C, Node* ctrl, Node* mem, Node* obj)
 346   : ShenandoahBarrierNode(ctrl, mem, obj, false) {
 347   assert(UseShenandoahGC && ShenandoahWriteBarrier, "should be enabled");
 348   ShenandoahBarrierSetC2::bsc2()->state()->add_shenandoah_barrier(this);
 349 }
 350 
 351 Node* ShenandoahWriteBarrierNode::Identity(PhaseGVN* phase) {
 352   assert(in(0) != NULL, "should have control");
 353   PhaseIterGVN* igvn = phase->is_IterGVN();
 354   Node* mem_in = in(Memory);
 355   Node* mem_proj = NULL;
 356 
 357   if (igvn != NULL) {
 358     mem_proj = find_out_with(Op_ShenandoahWBMemProj);
 359     if (mem_in == mem_proj) {
 360       return this;
 361     }
 362   }
 363 
 364   Node* replacement = Identity_impl(phase);
 365   if (igvn != NULL) {
 366     if (replacement != NULL && replacement != this && mem_proj != NULL) {
 367       igvn->replace_node(mem_proj, mem_in);
 368     }
 369   }
 370   return replacement;
 371 }
 372 
 373 Node* ShenandoahWriteBarrierNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 374   assert(in(0) != NULL, "should have control");
 375   if (!can_reshape) {
 376     return NULL;
 377   }
 378 
 379   Node* mem_in = in(Memory);
 380 
 381   if (mem_in->isa_MergeMem()) {
 382     const TypePtr* adr_type = brooks_pointer_type(bottom_type());
 383     uint alias_idx = phase->C->get_alias_index(adr_type);
 384     mem_in = mem_in->as_MergeMem()->memory_at(alias_idx);
 385     set_req(Memory, mem_in);
 386     return this;
 387   }
 388 
 389   Node* val = in(ValueIn);
 390   if (val->is_ShenandoahBarrier()) {
 391     set_req(ValueIn, val->in(ValueIn));
 392     return this;
 393   }
 394 
 395   return NULL;
 396 }
 397 
 398 bool ShenandoahWriteBarrierNode::expand(Compile* C, PhaseIterGVN& igvn, int& loop_opts_cnt) {
 399   if (UseShenandoahGC) {
 400     if (ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count() > 0 || (!ShenandoahWriteBarrier && ShenandoahStoreValEnqueueBarrier)) {
 401       bool attempt_more_loopopts = ShenandoahLoopOptsAfterExpansion;
 402       C->clear_major_progress();
 403       PhaseIdealLoop ideal_loop(igvn, LoopOptsShenandoahExpand);
 404       if (C->failing()) return false;
 405       PhaseIdealLoop::verify(igvn);
 406       DEBUG_ONLY(ShenandoahBarrierNode::verify_raw_mem(C->root());)
 407       if (attempt_more_loopopts) {
 408         C->set_major_progress();
 409         if (!C->optimize_loops(loop_opts_cnt, igvn, LoopOptsShenandoahPostExpand)) {
 410           return false;
 411         }
 412         C->clear_major_progress();
 413       }
 414     }
 415   }
 416   return true;
 417 }
 418 
 419 bool ShenandoahWriteBarrierNode::is_heap_state_test(Node* iff, int mask) {
 420   if (!UseShenandoahGC) {
 421     return false;
 422   }
 423   assert(iff->is_If(), "bad input");
 424   if (iff->Opcode() != Op_If) {
 425     return false;
 426   }
 427   Node* bol = iff->in(1);
 428   if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::ne) {
 429     return false;
 430   }
 431   Node* cmp = bol->in(1);
 432   if (cmp->Opcode() != Op_CmpI) {
 433     return false;
 434   }
 435   Node* in1 = cmp->in(1);
 436   Node* in2 = cmp->in(2);
 437   if (in2->find_int_con(-1) != 0) {
 438     return false;
 439   }
 440   if (in1->Opcode() != Op_AndI) {
 441     return false;
 442   }
 443   in2 = in1->in(2);
 444   if (in2->find_int_con(-1) != mask) {
 445     return false;
 446   }
 447   in1 = in1->in(1);
 448 
 449   return is_gc_state_load(in1);
 450 }
 451 
 452 bool ShenandoahWriteBarrierNode::is_heap_stable_test(Node* iff) {
 453   return is_heap_state_test(iff, ShenandoahHeap::HAS_FORWARDED);
 454 }
 455 
 456 bool ShenandoahWriteBarrierNode::is_gc_state_load(Node *n) {
 457   if (!UseShenandoahGC) {
 458     return false;
 459   }
 460   if (n->Opcode() != Op_LoadB && n->Opcode() != Op_LoadUB) {
 461     return false;
 462   }
 463   Node* addp = n->in(MemNode::Address);
 464   if (!addp->is_AddP()) {
 465     return false;
 466   }
 467   Node* base = addp->in(AddPNode::Address);
 468   Node* off = addp->in(AddPNode::Offset);
 469   if (base->Opcode() != Op_ThreadLocal) {
 470     return false;
 471   }
 472   if (off->find_intptr_t_con(-1) != in_bytes(ShenandoahThreadLocalData::gc_state_offset())) {
 473     return false;
 474   }
 475   return true;
 476 }
 477 
 478 bool ShenandoahWriteBarrierNode::has_safepoint_between(Node* start, Node* stop, PhaseIdealLoop *phase) {
 479   assert(phase->is_dominator(stop, start), "bad inputs");
 480   ResourceMark rm;
 481   Unique_Node_List wq;
 482   wq.push(start);
 483   for (uint next = 0; next < wq.size(); next++) {
 484     Node *m = wq.at(next);
 485     if (m == stop) {
 486       continue;
 487     }
 488     if (m->is_SafePoint() && !m->is_CallLeaf()) {
 489       return true;
 490     }
 491     if (m->is_Region()) {
 492       for (uint i = 1; i < m->req(); i++) {
 493         wq.push(m->in(i));
 494       }
 495     } else {
 496       wq.push(m->in(0));
 497     }
 498   }
 499   return false;
 500 }
 501 
 502 bool ShenandoahWriteBarrierNode::try_common_gc_state_load(Node *n, PhaseIdealLoop *phase) {
 503   assert(is_gc_state_load(n), "inconsistent");
 504   Node* addp = n->in(MemNode::Address);
 505   Node* dominator = NULL;
 506   for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) {
 507     Node* u = addp->fast_out(i);
 508     assert(is_gc_state_load(u), "inconsistent");
 509     if (u != n && phase->is_dominator(u->in(0), n->in(0))) {
 510       if (dominator == NULL) {
 511         dominator = u;
 512       } else {
 513         if (phase->dom_depth(u->in(0)) < phase->dom_depth(dominator->in(0))) {
 514           dominator = u;
 515         }
 516       }
 517     }
 518   }
 519   if (dominator == NULL || has_safepoint_between(n->in(0), dominator->in(0), phase)) {
 520     return false;
 521   }
 522   phase->igvn().replace_node(n, dominator);
 523 
 524   return true;
 525 }
 526 
 527 bool ShenandoahBarrierNode::dominates_memory_impl(PhaseGVN* phase,
 528                                                   Node* b1,
 529                                                   Node* b2,
 530                                                   Node* current,
 531                                                   bool linear) {
 532   ResourceMark rm;
 533   VectorSet visited(Thread::current()->resource_area());
 534   Node_Stack phis(0);
 535 
 536   for(int i = 0; i < 10; i++) {
 537     if (current == NULL) {
 538       return false;
 539     } else if (visited.test_set(current->_idx) || current->is_top() || current == b1) {
 540       current = NULL;
 541       while (phis.is_nonempty() && current == NULL) {
 542         uint idx = phis.index();
 543         Node* phi = phis.node();
 544         if (idx >= phi->req()) {
 545           phis.pop();
 546         } else {
 547           current = phi->in(idx);
 548           phis.set_index(idx+1);
 549         }
 550       }
 551       if (current == NULL) {
 552         return true;
 553       }
 554     } else if (current == b2) {
 555       return false;
 556     } else if (current == phase->C->immutable_memory()) {
 557       return false;
 558     } else if (current->isa_Phi()) {
 559       if (!linear) {
 560         return false;
 561       }
 562       phis.push(current, 2);
 563       current = current->in(1);
 564     } else if (current->Opcode() == Op_ShenandoahWriteBarrier) {
 565       current = current->in(Memory);
 566     } else if (current->Opcode() == Op_ShenandoahWBMemProj) {
 567       current = current->in(ShenandoahWBMemProjNode::WriteBarrier);
 568     } else if (current->is_Proj()) {
 569       current = current->in(0);
 570     } else if (current->is_Call()) {
 571       current = current->in(TypeFunc::Memory);
 572     } else if (current->is_MemBar()) {
 573       current = current->in(TypeFunc::Memory);
 574     } else if (current->is_MergeMem()) {
 575       const TypePtr* adr_type = brooks_pointer_type(phase->type(b2));
 576       uint alias_idx = phase->C->get_alias_index(adr_type);
 577       current = current->as_MergeMem()->memory_at(alias_idx);
 578     } else {
 579 #ifdef ASSERT
 580       current->dump();
 581 #endif
 582       ShouldNotReachHere();
 583       return false;
 584     }
 585   }
 586   return false;
 587 }
 588 
 589 /**
 590  * Determines if b1 dominates b2 through memory inputs. It returns true if:
 591  * - b1 can be reached by following each branch in b2's memory input (through phis, etc)
 592  * - or we get back to b2 (i.e. through a loop) without seeing b1
 593  * In all other cases, (in particular, if we reach immutable_memory without having seen b1)
 594  * we return false.
 595  */
 596 bool ShenandoahBarrierNode::dominates_memory(PhaseGVN* phase, Node* b1, Node* b2, bool linear) {
 597   return dominates_memory_impl(phase, b1, b2, b2->in(Memory), linear);
 598 }
 599 
 600 Node* ShenandoahBarrierNode::Identity_impl(PhaseGVN* phase) {
 601   Node* n = in(ValueIn);
 602 
 603   Node* rb_mem = Opcode() == Op_ShenandoahReadBarrier ? in(Memory) : NULL;
 604   if (! needs_barrier(phase, this, n, rb_mem, _allow_fromspace)) {
 605     return n;
 606   }
 607 
 608   // Try to find a write barrier sibling with identical inputs that we can fold into.
 609   for (DUIterator i = n->outs(); n->has_out(i); i++) {
 610     Node* sibling = n->out(i);
 611     if (sibling == this) {
 612       continue;
 613     }
 614     if (sibling->Opcode() != Op_ShenandoahWriteBarrier) {
 615       continue;
 616     }
 617 
 618     assert(sibling->in(ValueIn) == in(ValueIn), "sanity");
 619     assert(sibling->Opcode() == Op_ShenandoahWriteBarrier, "sanity");
 620 
 621     if (dominates_memory(phase, sibling, this, phase->is_IterGVN() == NULL)) {
 622       return sibling;
 623     }
 624   }
 625   return this;
 626 }
 627 
 628 #ifndef PRODUCT
 629 void ShenandoahBarrierNode::dump_spec(outputStream *st) const {
 630   const TypePtr* adr = adr_type();
 631   if (adr == NULL) {
 632     return;
 633   }
 634   st->print(" @");
 635   adr->dump_on(st);
 636   st->print(" (");
 637   Compile::current()->alias_type(adr)->adr_type()->dump_on(st);
 638   st->print(") ");
 639 }
 640 #endif
 641 
 642 Node* ShenandoahReadBarrierNode::Identity(PhaseGVN* phase) {
 643   Node* id = Identity_impl(phase);
 644 
 645   if (id == this && phase->is_IterGVN()) {
 646     Node* n = in(ValueIn);
 647     // No success in super call. Try to combine identical read barriers.
 648     for (DUIterator i = n->outs(); n->has_out(i); i++) {
 649       Node* sibling = n->out(i);
 650       if (sibling == this || sibling->Opcode() != Op_ShenandoahReadBarrier) {
 651         continue;
 652       }
 653       assert(sibling->in(ValueIn)  == in(ValueIn), "sanity");
 654       if (phase->is_IterGVN()->hash_find(sibling) &&
 655           sibling->bottom_type() == bottom_type() &&
 656           sibling->in(Control) == in(Control) &&
 657           dominates_memory_rb(phase, sibling, this, phase->is_IterGVN() == NULL)) {
 658         return sibling;
 659       }
 660     }
 661   }
 662   return id;
 663 }
 664 
 665 const Type* ShenandoahBarrierNode::Value(PhaseGVN* phase) const {
 666   // Either input is TOP ==> the result is TOP
 667   const Type *t1 = phase->type(in(Memory));
 668   if (t1 == Type::TOP) return Type::TOP;
 669   const Type *t2 = phase->type(in(ValueIn));
 670   if( t2 == Type::TOP ) return Type::TOP;
 671 
 672   if (t2 == TypePtr::NULL_PTR) {
 673     return _type;
 674   }
 675 
 676   const Type* type = t2->is_oopptr()->cast_to_nonconst();
 677   return type;
 678 }
 679 
 680 uint ShenandoahBarrierNode::hash() const {
 681   return TypeNode::hash() + _allow_fromspace;
 682 }
 683 
 684 uint ShenandoahBarrierNode::cmp(const Node& n) const {
 685   return _allow_fromspace == ((ShenandoahBarrierNode&) n)._allow_fromspace
 686     && TypeNode::cmp(n);
 687 }
 688 
 689 uint ShenandoahBarrierNode::size_of() const {
 690   return sizeof(*this);
 691 }
 692 
 693 Node* ShenandoahWBMemProjNode::Identity(PhaseGVN* phase) {
 694   Node* wb = in(WriteBarrier);
 695   if (wb->is_top()) return phase->C->top(); // Dead path.
 696 
 697   assert(wb->Opcode() == Op_ShenandoahWriteBarrier, "expect write barrier");
 698   PhaseIterGVN* igvn = phase->is_IterGVN();
 699   // We can't do the below unless the graph is fully constructed.
 700   if (igvn == NULL) {
 701     return this;
 702   }
 703 
 704   // If the mem projection has no barrier users, it's not needed anymore.
 705   if (wb->outcnt() == 1) {
 706     return wb->in(ShenandoahBarrierNode::Memory);
 707   }
 708 
 709   return this;
 710 }
 711 
 712 #ifdef ASSERT
 713 bool ShenandoahBarrierNode::verify_helper(Node* in, Node_Stack& phis, VectorSet& visited, verify_type t, bool trace, Unique_Node_List& barriers_used) {
 714   assert(phis.size() == 0, "");
 715 
 716   while (true) {
 717     if (in->bottom_type() == TypePtr::NULL_PTR) {
 718       if (trace) {tty->print_cr("NULL");}
 719     } else if (!in->bottom_type()->make_ptr()->make_oopptr()) {
 720       if (trace) {tty->print_cr("Non oop");}
 721     } else if (t == ShenandoahLoad && ShenandoahOptimizeStableFinals &&
 722                in->bottom_type()->make_ptr()->isa_aryptr() &&
 723                in->bottom_type()->make_ptr()->is_aryptr()->is_stable()) {
 724       if (trace) {tty->print_cr("Stable array load");}
 725     } else {
 726       if (in->is_ConstraintCast()) {
 727         in = in->in(1);
 728         continue;
 729       } else if (in->is_AddP()) {
 730         assert(!in->in(AddPNode::Address)->is_top(), "no raw memory access");
 731         in = in->in(AddPNode::Address);
 732         continue;
 733       } else if (in->is_Con()) {
 734         if (trace) {tty->print("Found constant"); in->dump();}
 735       } else if (in->is_ShenandoahBarrier()) {
 736         if (t == ShenandoahOopStore) {
 737           if (in->Opcode() != Op_ShenandoahWriteBarrier) {
 738             return false;
 739           }
 740           uint i = 0;
 741           for (; i < phis.size(); i++) {
 742             Node* n = phis.node_at(i);
 743             if (n->Opcode() == Op_ShenandoahEnqueueBarrier) {
 744               break;
 745             }
 746           }
 747           if (i == phis.size()) {
 748             return false;
 749           }
 750         } else if (t == ShenandoahStore && in->Opcode() != Op_ShenandoahWriteBarrier) {
 751           return false;
 752         }
 753         barriers_used.push(in);
 754         if (trace) {tty->print("Found barrier"); in->dump();}
 755       } else if (in->Opcode() == Op_ShenandoahEnqueueBarrier) {
 756         if (t != ShenandoahOopStore) {
 757           return false;
 758         }
 759         if (trace) {tty->print("Found enqueue barrier"); in->dump();}
 760         phis.push(in, in->req());
 761         in = in->in(1);
 762         continue;
 763       } else if (in->is_Proj() && in->in(0)->is_Allocate()) {
 764         if (trace) {tty->print("Found alloc"); in->in(0)->dump();}
 765       } else if (in->is_Phi()) {
 766         if (!visited.test_set(in->_idx)) {
 767           if (trace) {tty->print("Pushed phi:"); in->dump();}
 768           phis.push(in, 2);
 769           in = in->in(1);
 770           continue;
 771         }
 772         if (trace) {tty->print("Already seen phi:"); in->dump();}
 773       } else if (in->Opcode() == Op_CMoveP || in->Opcode() == Op_CMoveN) {
 774         if (!visited.test_set(in->_idx)) {
 775           if (trace) {tty->print("Pushed cmovep:"); in->dump();}
 776           phis.push(in, CMoveNode::IfTrue);
 777           in = in->in(CMoveNode::IfFalse);
 778           continue;
 779         }
 780         if (trace) {tty->print("Already seen cmovep:"); in->dump();}
 781       } else if (in->Opcode() == Op_EncodeP || in->Opcode() == Op_DecodeN) {
 782         in = in->in(1);
 783         continue;
 784       } else {
 785         return false;
 786       }
 787     }
 788     bool cont = false;
 789     while (phis.is_nonempty()) {
 790       uint idx = phis.index();
 791       Node* phi = phis.node();
 792       if (idx >= phi->req()) {
 793         if (trace) {tty->print("Popped phi:"); phi->dump();}
 794         phis.pop();
 795         continue;
 796       }
 797       if (trace) {tty->print("Next entry(%d) for phi:", idx); phi->dump();}
 798       in = phi->in(idx);
 799       phis.set_index(idx+1);
 800       cont = true;
 801       break;
 802     }
 803     if (!cont) {
 804       break;
 805     }
 806   }
 807   return true;
 808 }
 809 
 810 void ShenandoahBarrierNode::report_verify_failure(const char *msg, Node *n1, Node *n2) {
 811   if (n1 != NULL) {
 812     n1->dump(+10);
 813   }
 814   if (n2 != NULL) {
 815     n2->dump(+10);
 816   }
 817   fatal("%s", msg);
 818 }
 819 
 820 void ShenandoahBarrierNode::verify(RootNode* root) {
 821   ResourceMark rm;
 822   Unique_Node_List wq;
 823   GrowableArray<Node*> barriers;
 824   Unique_Node_List barriers_used;
 825   Node_Stack phis(0);
 826   VectorSet visited(Thread::current()->resource_area());
 827   const bool trace = false;
 828   const bool verify_no_useless_barrier = false;
 829 
 830   wq.push(root);
 831   for (uint next = 0; next < wq.size(); next++) {
 832     Node *n = wq.at(next);
 833     if (n->is_Load()) {
 834       const bool trace = false;
 835       if (trace) {tty->print("Verifying"); n->dump();}
 836       if (n->Opcode() == Op_LoadRange || n->Opcode() == Op_LoadKlass || n->Opcode() == Op_LoadNKlass) {
 837         if (trace) {tty->print_cr("Load range/klass");}
 838       } else {
 839         const TypePtr* adr_type = n->as_Load()->adr_type();
 840 
 841         if (adr_type->isa_oopptr() && adr_type->is_oopptr()->offset() == oopDesc::mark_offset_in_bytes()) {
 842           if (trace) {tty->print_cr("Mark load");}
 843         } else if (adr_type->isa_instptr() &&
 844                    adr_type->is_instptr()->klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
 845                    adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset) {
 846           if (trace) {tty->print_cr("Reference.get()");}
 847         } else {
 848           bool verify = true;
 849           if (adr_type->isa_instptr()) {
 850             const TypeInstPtr* tinst = adr_type->is_instptr();
 851             ciKlass* k = tinst->klass();
 852             assert(k->is_instance_klass(), "");
 853             ciInstanceKlass* ik = (ciInstanceKlass*)k;
 854             int offset = adr_type->offset();
 855 
 856             if ((ik->debug_final_field_at(offset) && ShenandoahOptimizeInstanceFinals) ||
 857                 (ik->debug_stable_field_at(offset) && ShenandoahOptimizeStableFinals)) {
 858               if (trace) {tty->print_cr("Final/stable");}
 859               verify = false;
 860             } else if (k == ciEnv::current()->Class_klass() &&
 861                        tinst->const_oop() != NULL &&
 862                        tinst->offset() >= (ik->size_helper() * wordSize)) {
 863               ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
 864               ciField* field = k->get_field_by_offset(tinst->offset(), true);
 865               if ((ShenandoahOptimizeStaticFinals && field->is_final()) ||
 866                   (ShenandoahOptimizeStableFinals && field->is_stable())) {
 867                 verify = false;
 868               }
 869             }
 870           }
 871 
 872           if (verify && !ShenandoahBarrierNode::verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 873             report_verify_failure("Shenandoah verification: Load should have barriers", n);
 874           }
 875         }
 876       }
 877     } else if (n->is_Store()) {
 878       const bool trace = false;
 879 
 880       if (trace) {tty->print("Verifying"); n->dump();}
 881       if (n->in(MemNode::ValueIn)->bottom_type()->make_oopptr()) {
 882         Node* adr = n->in(MemNode::Address);
 883         bool verify = true;
 884 
 885         if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top()) {
 886           adr = adr->in(AddPNode::Address);
 887           if (adr->is_AddP()) {
 888             assert(adr->in(AddPNode::Base)->is_top(), "");
 889             adr = adr->in(AddPNode::Address);
 890             if (adr->Opcode() == Op_LoadP &&
 891                 adr->in(MemNode::Address)->in(AddPNode::Base)->is_top() &&
 892                 adr->in(MemNode::Address)->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 893                 adr->in(MemNode::Address)->in(AddPNode::Offset)->find_intptr_t_con(-1) == in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset())) {
 894               if (trace) {tty->print_cr("SATB prebarrier");}
 895               verify = false;
 896             }
 897           }
 898         }
 899 
 900         if (verify && !ShenandoahBarrierNode::verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahStoreValEnqueueBarrier ? ShenandoahOopStore : ShenandoahValue, trace, barriers_used)) {
 901           report_verify_failure("Shenandoah verification: Store should have barriers", n);
 902         }
 903       }
 904       if (!ShenandoahBarrierNode::verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 905         report_verify_failure("Shenandoah verification: Store (address) should have barriers", n);
 906       }
 907     } else if (n->Opcode() == Op_CmpP) {
 908       const bool trace = false;
 909 
 910       Node* in1 = n->in(1);
 911       Node* in2 = n->in(2);
 912       if (in1->bottom_type()->isa_oopptr()) {
 913         if (trace) {tty->print("Verifying"); n->dump();}
 914 
 915         bool mark_inputs = false;
 916         if (in1->bottom_type() == TypePtr::NULL_PTR || in2->bottom_type() == TypePtr::NULL_PTR ||
 917             (in1->is_Con() || in2->is_Con())) {
 918           if (trace) {tty->print_cr("Comparison against a constant");}
 919           mark_inputs = true;
 920         } else if ((in1->is_CheckCastPP() && in1->in(1)->is_Proj() && in1->in(1)->in(0)->is_Allocate()) ||
 921                    (in2->is_CheckCastPP() && in2->in(1)->is_Proj() && in2->in(1)->in(0)->is_Allocate())) {
 922           if (trace) {tty->print_cr("Comparison with newly alloc'ed object");}
 923           mark_inputs = true;
 924         } else {
 925           assert(in2->bottom_type()->isa_oopptr(), "");
 926 
 927           if (!ShenandoahBarrierNode::verify_helper(in1, phis, visited, ShenandoahStore, trace, barriers_used) ||
 928               !ShenandoahBarrierNode::verify_helper(in2, phis, visited, ShenandoahStore, trace, barriers_used)) {
 929             report_verify_failure("Shenandoah verification: Cmp should have barriers", n);
 930           }
 931         }
 932         if (verify_no_useless_barrier &&
 933             mark_inputs &&
 934             (!ShenandoahBarrierNode::verify_helper(in1, phis, visited, ShenandoahValue, trace, barriers_used) ||
 935              !ShenandoahBarrierNode::verify_helper(in2, phis, visited, ShenandoahValue, trace, barriers_used))) {
 936           phis.clear();
 937           visited.Reset();
 938         }
 939       }
 940     } else if (n->is_LoadStore()) {
 941       if (n->in(MemNode::ValueIn)->bottom_type()->make_ptr() &&
 942           !ShenandoahBarrierNode::verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahStoreValEnqueueBarrier ? ShenandoahOopStore : ShenandoahValue, trace, barriers_used)) {
 943         report_verify_failure("Shenandoah verification: LoadStore (value) should have barriers", n);
 944       }
 945 
 946       if (n->in(MemNode::Address)->bottom_type()->make_oopptr() && !ShenandoahBarrierNode::verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 947         report_verify_failure("Shenandoah verification: LoadStore (address) should have barriers", n);
 948       }
 949     } else if (n->Opcode() == Op_CallLeafNoFP || n->Opcode() == Op_CallLeaf) {
 950       CallNode* call = n->as_Call();
 951 
 952       static struct {
 953         const char* name;
 954         struct {
 955           int pos;
 956           verify_type t;
 957         } args[6];
 958       } calls[] = {
 959         "aescrypt_encryptBlock",
 960         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 961           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 962         "aescrypt_decryptBlock",
 963         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 964           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 965         "multiplyToLen",
 966         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { TypeFunc::Parms+4, ShenandoahStore },
 967           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 968         "squareToLen",
 969         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { -1,  ShenandoahNone},
 970           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 971         "montgomery_multiply",
 972         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 973           { TypeFunc::Parms+6, ShenandoahStore }, { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 974         "montgomery_square",
 975         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+5, ShenandoahStore },
 976           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 977         "mulAdd",
 978         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 979           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 980         "vectorizedMismatch",
 981         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 982           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 983         "updateBytesCRC32",
 984         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 985           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 986         "updateBytesAdler32",
 987         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 988           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 989         "updateBytesCRC32C",
 990         { { TypeFunc::Parms+1, ShenandoahLoad }, { TypeFunc::Parms+3, ShenandoahLoad},    { -1,  ShenandoahNone},
 991           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 992         "counterMode_AESCrypt",
 993         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 994           { TypeFunc::Parms+3, ShenandoahStore }, { TypeFunc::Parms+5, ShenandoahStore }, { TypeFunc::Parms+6, ShenandoahStore } },
 995         "cipherBlockChaining_encryptAESCrypt",
 996         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 997           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 998         "cipherBlockChaining_decryptAESCrypt",
 999         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
1000           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1001         "shenandoah_clone_barrier",
1002         { { TypeFunc::Parms, ShenandoahLoad },   { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
1003           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1004         "ghash_processBlocks",
1005         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
1006           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1007         "sha1_implCompress",
1008         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1009           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1010         "sha256_implCompress",
1011         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1012           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1013         "sha512_implCompress",
1014         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1015           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1016         "sha1_implCompressMB",
1017         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1018           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1019         "sha256_implCompressMB",
1020         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1021           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1022         "sha512_implCompressMB",
1023         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
1024           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
1025       };
1026 
1027       if (call->is_call_to_arraycopystub()) {
1028         Node* dest = NULL;
1029         const TypeTuple* args = n->as_Call()->_tf->domain();
1030         for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
1031           if (args->field_at(i)->isa_ptr()) {
1032             j++;
1033             if (j == 2) {
1034               dest = n->in(i);
1035               break;
1036             }
1037           }
1038         }
1039         if (!ShenandoahBarrierNode::verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahLoad, trace, barriers_used) ||
1040             !ShenandoahBarrierNode::verify_helper(dest, phis, visited, ShenandoahStore, trace, barriers_used)) {
1041           report_verify_failure("Shenandoah verification: ArrayCopy should have barriers", n);
1042         }
1043       } else if (strlen(call->_name) > 5 &&
1044                  !strcmp(call->_name + strlen(call->_name) - 5, "_fill")) {
1045         if (!ShenandoahBarrierNode::verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahStore, trace, barriers_used)) {
1046           report_verify_failure("Shenandoah verification: _fill should have barriers", n);
1047         }
1048       } else if (!strcmp(call->_name, "shenandoah_wb_pre")) {
1049         // skip
1050       } else {
1051         const int calls_len = sizeof(calls) / sizeof(calls[0]);
1052         int i = 0;
1053         for (; i < calls_len; i++) {
1054           if (!strcmp(calls[i].name, call->_name)) {
1055             break;
1056           }
1057         }
1058         if (i != calls_len) {
1059           const uint args_len = sizeof(calls[0].args) / sizeof(calls[0].args[0]);
1060           for (uint j = 0; j < args_len; j++) {
1061             int pos = calls[i].args[j].pos;
1062             if (pos == -1) {
1063               break;
1064             }
1065             if (!ShenandoahBarrierNode::verify_helper(call->in(pos), phis, visited, calls[i].args[j].t, trace, barriers_used)) {
1066               report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
1067             }
1068           }
1069           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
1070             if (call->in(j)->bottom_type()->make_ptr() &&
1071                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
1072               uint k = 0;
1073               for (; k < args_len && calls[i].args[k].pos != (int)j; k++);
1074               if (k == args_len) {
1075                 fatal("arg %d for call %s not covered", j, call->_name);
1076               }
1077             }
1078           }
1079         } else {
1080           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
1081             if (call->in(j)->bottom_type()->make_ptr() &&
1082                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
1083               fatal("%s not covered", call->_name);
1084             }
1085           }
1086         }
1087       }
1088     } else if (n->is_ShenandoahBarrier()) {
1089       assert(!barriers.contains(n), "");
1090       assert(n->Opcode() != Op_ShenandoahWriteBarrier || n->find_out_with(Op_ShenandoahWBMemProj) != NULL, "bad shenandoah write barrier");
1091       assert(n->Opcode() != Op_ShenandoahWriteBarrier || n->outcnt() > 1, "bad shenandoah write barrier");
1092       barriers.push(n);
1093     } else if (n->Opcode() == Op_ShenandoahEnqueueBarrier) {
1094       // skip
1095     } else if (n->Opcode() == Op_ShenandoahWBMemProj) {
1096       assert(n->in(0) == NULL && n->in(ShenandoahWBMemProjNode::WriteBarrier)->Opcode() == Op_ShenandoahWriteBarrier, "strange ShenandoahWBMemProj");
1097     } else if (n->is_AddP()
1098                || n->is_Phi()
1099                || n->is_ConstraintCast()
1100                || n->Opcode() == Op_Return
1101                || n->Opcode() == Op_CMoveP
1102                || n->Opcode() == Op_CMoveN
1103                || n->Opcode() == Op_Rethrow
1104                || n->is_MemBar()
1105                || n->Opcode() == Op_Conv2B
1106                || n->Opcode() == Op_SafePoint
1107                || n->is_CallJava()
1108                || n->Opcode() == Op_Unlock
1109                || n->Opcode() == Op_EncodeP
1110                || n->Opcode() == Op_DecodeN) {
1111       // nothing to do
1112     } else {
1113       static struct {
1114         int opcode;
1115         struct {
1116           int pos;
1117           verify_type t;
1118         } inputs[2];
1119       } others[] = {
1120         Op_FastLock,
1121         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
1122         Op_Lock,
1123         { { TypeFunc::Parms, ShenandoahLoad },    { -1, ShenandoahNone} },
1124         Op_ArrayCopy,
1125         { { ArrayCopyNode::Src, ShenandoahLoad }, { ArrayCopyNode::Dest, ShenandoahStore } },
1126         Op_StrCompressedCopy,
1127         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
1128         Op_StrInflatedCopy,
1129         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
1130         Op_AryEq,
1131         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
1132         Op_StrIndexOf,
1133         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
1134         Op_StrComp,
1135         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
1136         Op_StrEquals,
1137         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
1138         Op_EncodeISOArray,
1139         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
1140         Op_HasNegatives,
1141         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone} },
1142         Op_CastP2X,
1143         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
1144         Op_StrIndexOfChar,
1145         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
1146       };
1147 
1148       const int others_len = sizeof(others) / sizeof(others[0]);
1149       int i = 0;
1150       for (; i < others_len; i++) {
1151         if (others[i].opcode == n->Opcode()) {
1152           break;
1153         }
1154       }
1155       uint stop = n->is_Call() ? n->as_Call()->tf()->domain()->cnt() : n->req();
1156       if (i != others_len) {
1157         const uint inputs_len = sizeof(others[0].inputs) / sizeof(others[0].inputs[0]);
1158         for (uint j = 0; j < inputs_len; j++) {
1159           int pos = others[i].inputs[j].pos;
1160           if (pos == -1) {
1161             break;
1162           }
1163           if (!ShenandoahBarrierNode::verify_helper(n->in(pos), phis, visited, others[i].inputs[j].t, trace, barriers_used)) {
1164             report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
1165           }
1166         }
1167         for (uint j = 1; j < stop; j++) {
1168           if (n->in(j) != NULL && n->in(j)->bottom_type()->make_ptr() &&
1169               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
1170             uint k = 0;
1171             for (; k < inputs_len && others[i].inputs[k].pos != (int)j; k++);
1172             if (k == inputs_len) {
1173               fatal("arg %d for node %s not covered", j, n->Name());
1174             }
1175           }
1176         }
1177       } else {
1178         for (uint j = 1; j < stop; j++) {
1179           if (n->in(j) != NULL && n->in(j)->bottom_type()->make_ptr() &&
1180               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
1181             fatal("%s not covered", n->Name());
1182           }
1183         }
1184       }
1185     }
1186 
1187     if (n->is_SafePoint()) {
1188       SafePointNode* sfpt = n->as_SafePoint();
1189       if (verify_no_useless_barrier && sfpt->jvms() != NULL) {
1190         for (uint i = sfpt->jvms()->scloff(); i < sfpt->jvms()->endoff(); i++) {
1191           if (!ShenandoahBarrierNode::verify_helper(sfpt->in(i), phis, visited, ShenandoahLoad, trace, barriers_used)) {
1192             phis.clear();
1193             visited.Reset();
1194           }
1195         }
1196       }
1197     }
1198     for( uint i = 0; i < n->len(); ++i ) {
1199       Node *m = n->in(i);
1200       if (m == NULL) continue;
1201 
1202       // In most cases, inputs should be known to be non null. If it's
1203       // not the case, it could be a missing cast_not_null() in an
1204       // intrinsic or support might be needed in AddPNode::Ideal() to
1205       // avoid a NULL+offset input.
1206       if (!(n->is_Phi() ||
1207             (n->is_SafePoint() && (!n->is_CallRuntime() || !strcmp(n->as_Call()->_name, "shenandoah_wb_pre") || !strcmp(n->as_Call()->_name, "unsafe_arraycopy"))) ||
1208             n->Opcode() == Op_CmpP ||
1209             n->Opcode() == Op_CmpN ||
1210             (n->Opcode() == Op_StoreP && i == StoreNode::ValueIn) ||
1211             (n->Opcode() == Op_StoreN && i == StoreNode::ValueIn) ||
1212             n->is_ConstraintCast() ||
1213             n->Opcode() == Op_Return ||
1214             n->Opcode() == Op_Conv2B ||
1215             n->is_AddP() ||
1216             n->Opcode() == Op_CMoveP ||
1217             n->Opcode() == Op_CMoveN ||
1218             n->Opcode() == Op_Rethrow ||
1219             n->is_MemBar() ||
1220             n->is_Mem() ||
1221             n->Opcode() == Op_AryEq ||
1222             n->Opcode() == Op_SCMemProj ||
1223             n->Opcode() == Op_EncodeP ||
1224             n->Opcode() == Op_DecodeN ||
1225             n->Opcode() == Op_ShenandoahWriteBarrier ||
1226             n->Opcode() == Op_ShenandoahWBMemProj ||
1227             n->Opcode() == Op_ShenandoahEnqueueBarrier)) {
1228         if (m->bottom_type()->make_oopptr() && m->bottom_type()->make_oopptr()->meet(TypePtr::NULL_PTR) == m->bottom_type()) {
1229           report_verify_failure("Shenandoah verification: null input", n, m);
1230         }
1231       }
1232 
1233       wq.push(m);
1234     }
1235   }
1236 
1237   if (verify_no_useless_barrier) {
1238     for (int i = 0; i < barriers.length(); i++) {
1239       Node* n = barriers.at(i);
1240       if (!barriers_used.member(n)) {
1241         tty->print("XXX useless barrier"); n->dump(-2);
1242         ShouldNotReachHere();
1243       }
1244     }
1245   }
1246 }
1247 #endif
1248 
1249 bool ShenandoahBarrierNode::is_dominator_same_ctrl(Node*c, Node* d, Node* n, PhaseIdealLoop* phase) {
1250   // That both nodes have the same control is not sufficient to prove
1251   // domination, verify that there's no path from d to n
1252   ResourceMark rm;
1253   Unique_Node_List wq;
1254   wq.push(d);
1255   for (uint next = 0; next < wq.size(); next++) {
1256     Node *m = wq.at(next);
1257     if (m == n) {
1258       return false;
1259     }
1260     if (m->is_Phi() && m->in(0)->is_Loop()) {
1261       assert(phase->ctrl_or_self(m->in(LoopNode::EntryControl)) != c, "following loop entry should lead to new control");
1262     } else {
1263       for (uint i = 0; i < m->req(); i++) {
1264         if (m->in(i) != NULL && phase->ctrl_or_self(m->in(i)) == c) {
1265           wq.push(m->in(i));
1266         }
1267       }
1268     }
1269   }
1270   return true;
1271 }
1272 
1273 bool ShenandoahBarrierNode::is_dominator(Node *d_c, Node *n_c, Node* d, Node* n, PhaseIdealLoop* phase) {
1274   if (d_c != n_c) {
1275     return phase->is_dominator(d_c, n_c);
1276   }
1277   return is_dominator_same_ctrl(d_c, d, n, phase);
1278 }
1279 
1280 Node* next_mem(Node* mem, int alias) {
1281   Node* res = NULL;
1282   if (mem->is_Proj()) {
1283     res = mem->in(0);
1284   } else if (mem->is_SafePoint() || mem->is_MemBar()) {
1285     res = mem->in(TypeFunc::Memory);
1286   } else if (mem->is_Phi()) {
1287     res = mem->in(1);
1288   } else if (mem->is_ShenandoahBarrier()) {
1289     res = mem->in(ShenandoahBarrierNode::Memory);
1290   } else if (mem->is_MergeMem()) {
1291     res = mem->as_MergeMem()->memory_at(alias);
1292   } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
1293     assert(alias = Compile::AliasIdxRaw, "following raw memory can't lead to a barrier");
1294     res = mem->in(MemNode::Memory);
1295   } else if (mem->Opcode() == Op_ShenandoahWBMemProj) {
1296     res = mem->in(ShenandoahWBMemProjNode::WriteBarrier);
1297   } else {
1298 #ifdef ASSERT
1299     mem->dump();
1300 #endif
1301     ShouldNotReachHere();
1302   }
1303   return res;
1304 }
1305 
1306 Node* ShenandoahBarrierNode::no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase) {
1307   Node* iffproj = NULL;
1308   while (c != dom) {
1309     Node* next = phase->idom(c);
1310     assert(next->unique_ctrl_out() == c || c->is_Proj() || c->is_Region(), "multiple control flow out but no proj or region?");
1311     if (c->is_Region()) {
1312       ResourceMark rm;
1313       Unique_Node_List wq;
1314       wq.push(c);
1315       for (uint i = 0; i < wq.size(); i++) {
1316         Node *n = wq.at(i);
1317         if (n == next) {
1318           continue;
1319         }
1320         if (n->is_Region()) {
1321           for (uint j = 1; j < n->req(); j++) {
1322             wq.push(n->in(j));
1323           }
1324         } else {
1325           wq.push(n->in(0));
1326         }
1327       }
1328       for (uint i = 0; i < wq.size(); i++) {
1329         Node *n = wq.at(i);
1330         assert(n->is_CFG(), "");
1331         if (n->is_Multi()) {
1332           for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1333             Node* u = n->fast_out(j);
1334             if (u->is_CFG()) {
1335               if (!wq.member(u) && !u->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
1336                 return NodeSentinel;
1337               }
1338             }
1339           }
1340         }
1341       }
1342     } else  if (c->is_Proj()) {
1343       if (c->is_IfProj()) {
1344         if (c->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) != NULL) {
1345           // continue;
1346         } else {
1347           if (!allow_one_proj) {
1348             return NodeSentinel;
1349           }
1350           if (iffproj == NULL) {
1351             iffproj = c;
1352           } else {
1353             return NodeSentinel;
1354           }
1355         }
1356       } else if (c->Opcode() == Op_JumpProj) {
1357         return NodeSentinel; // unsupported
1358       } else if (c->Opcode() == Op_CatchProj) {
1359         return NodeSentinel; // unsupported
1360       } else if (c->Opcode() == Op_CProj && next->Opcode() == Op_NeverBranch) {
1361         return NodeSentinel; // unsupported
1362       } else {
1363         assert(next->unique_ctrl_out() == c, "unsupported branch pattern");
1364       }
1365     }
1366     c = next;
1367   }
1368   return iffproj;
1369 }
1370 
1371 #ifdef ASSERT
1372 void ShenandoahWriteBarrierNode::memory_dominates_all_paths_helper(Node* c, Node* rep_ctrl, Unique_Node_List& controls, PhaseIdealLoop* phase) {
1373   const bool trace = false;
1374   if (trace) { tty->print("X control is"); c->dump(); }
1375 
1376   uint start = controls.size();
1377   controls.push(c);
1378   for (uint i = start; i < controls.size(); i++) {
1379     Node *n = controls.at(i);
1380 
1381     if (trace) { tty->print("X from"); n->dump(); }
1382 
1383     if (n == rep_ctrl) {
1384       continue;
1385     }
1386 
1387     if (n->is_Proj()) {
1388       Node* n_dom = n->in(0);
1389       IdealLoopTree* n_dom_loop = phase->get_loop(n_dom);
1390       if (n->is_IfProj() && n_dom->outcnt() == 2) {
1391         n_dom_loop = phase->get_loop(n_dom->as_If()->proj_out(n->as_Proj()->_con == 0 ? 1 : 0));
1392       }
1393       if (n_dom_loop != phase->ltree_root()) {
1394         Node* tail = n_dom_loop->tail();
1395         if (tail->is_Region()) {
1396           for (uint j = 1; j < tail->req(); j++) {
1397             if (phase->is_dominator(n_dom, tail->in(j)) && !phase->is_dominator(n, tail->in(j))) {
1398               assert(phase->is_dominator(rep_ctrl, tail->in(j)), "why are we here?");
1399               // entering loop from below, mark backedge
1400               if (trace) { tty->print("X pushing backedge"); tail->in(j)->dump(); }
1401               controls.push(tail->in(j));
1402               //assert(n->in(0) == n_dom, "strange flow control");
1403             }
1404           }
1405         } else if (phase->get_loop(n) != n_dom_loop && phase->is_dominator(n_dom, tail)) {
1406           // entering loop from below, mark backedge
1407           if (trace) { tty->print("X pushing backedge"); tail->dump(); }
1408           controls.push(tail);
1409           //assert(n->in(0) == n_dom, "strange flow control");
1410         }
1411       }
1412     }
1413 
1414     if (n->is_Loop()) {
1415       Node* c = n->in(LoopNode::EntryControl);
1416       if (trace) { tty->print("X pushing"); c->dump(); }
1417       controls.push(c);
1418     } else if (n->is_Region()) {
1419       for (uint i = 1; i < n->req(); i++) {
1420         Node* c = n->in(i);
1421         if (trace) { tty->print("X pushing"); c->dump(); }
1422         controls.push(c);
1423       }
1424     } else {
1425       Node* c = n->in(0);
1426       if (trace) { tty->print("X pushing"); c->dump(); }
1427       controls.push(c);
1428     }
1429   }
1430 }
1431 
1432 bool ShenandoahWriteBarrierNode::memory_dominates_all_paths(Node* mem, Node* rep_ctrl, int alias, PhaseIdealLoop* phase) {
1433   const bool trace = false;
1434   if (trace) {
1435     tty->print("XXX mem is"); mem->dump();
1436     tty->print("XXX rep ctrl is"); rep_ctrl->dump();
1437     tty->print_cr("XXX alias is %d", alias);
1438   }
1439   ResourceMark rm;
1440   Unique_Node_List wq;
1441   Unique_Node_List controls;
1442   wq.push(mem);
1443   for (uint next = 0; next < wq.size(); next++) {
1444     Node *nn = wq.at(next);
1445     if (trace) { tty->print("XX from mem"); nn->dump(); }
1446     assert(nn->bottom_type() == Type::MEMORY, "memory only");
1447 
1448     if (nn->is_Phi()) {
1449       Node* r = nn->in(0);
1450       for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
1451         Node* u = r->fast_out(j);
1452         if (u->is_Phi() && u->bottom_type() == Type::MEMORY && u != nn &&
1453             (u->adr_type() == TypePtr::BOTTOM || phase->C->get_alias_index(u->adr_type()) == alias)) {
1454           if (trace) { tty->print("XX Next mem (other phi)"); u->dump(); }
1455           wq.push(u);
1456         }
1457       }
1458     }
1459 
1460     for (DUIterator_Fast imax, i = nn->fast_outs(imax); i < imax; i++) {
1461       Node* use = nn->fast_out(i);
1462 
1463       if (trace) { tty->print("XX use %p", use->adr_type()); use->dump(); }
1464       if (use->is_CFG() && use->in(TypeFunc::Memory) == nn) {
1465         Node* c = use->in(0);
1466         if (phase->is_dominator(rep_ctrl, c)) {
1467           memory_dominates_all_paths_helper(c, rep_ctrl, controls, phase);
1468         } else if (use->is_CallStaticJava() && use->as_CallStaticJava()->uncommon_trap_request() != 0 && c->is_Region()) {
1469           Node* region = c;
1470           if (trace) { tty->print("XX unc region"); region->dump(); }
1471           for (uint j = 1; j < region->req(); j++) {
1472             if (phase->is_dominator(rep_ctrl, region->in(j))) {
1473               if (trace) { tty->print("XX unc follows"); region->in(j)->dump(); }
1474               memory_dominates_all_paths_helper(region->in(j), rep_ctrl, controls, phase);
1475             }
1476           }
1477         }
1478         //continue;
1479       } else if (use->is_Phi()) {
1480         assert(use->bottom_type() == Type::MEMORY, "bad phi");
1481         if ((use->adr_type() == TypePtr::BOTTOM) ||
1482             phase->C->get_alias_index(use->adr_type()) == alias) {
1483           for (uint j = 1; j < use->req(); j++) {
1484             if (use->in(j) == nn) {
1485               Node* c = use->in(0)->in(j);
1486               if (phase->is_dominator(rep_ctrl, c)) {
1487                 memory_dominates_all_paths_helper(c, rep_ctrl, controls, phase);
1488               }
1489             }
1490           }
1491         }
1492         //        continue;
1493       }
1494 
1495       if (use->is_MergeMem()) {
1496         if (use->as_MergeMem()->memory_at(alias) == nn) {
1497           if (trace) { tty->print("XX Next mem"); use->dump(); }
1498           // follow the memory edges
1499           wq.push(use);
1500         }
1501       } else if (use->is_Phi()) {
1502         assert(use->bottom_type() == Type::MEMORY, "bad phi");
1503         if ((use->adr_type() == TypePtr::BOTTOM) ||
1504             phase->C->get_alias_index(use->adr_type()) == alias) {
1505           if (trace) { tty->print("XX Next mem"); use->dump(); }
1506           // follow the memory edges
1507           wq.push(use);
1508         }
1509       } else if (use->bottom_type() == Type::MEMORY &&
1510                  (use->adr_type() == TypePtr::BOTTOM || phase->C->get_alias_index(use->adr_type()) == alias)) {
1511         if (trace) { tty->print("XX Next mem"); use->dump(); }
1512         // follow the memory edges
1513         wq.push(use);
1514       } else if ((use->is_SafePoint() || use->is_MemBar()) &&
1515                  (use->adr_type() == TypePtr::BOTTOM || phase->C->get_alias_index(use->adr_type()) == alias)) {
1516         for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {
1517           Node* u = use->fast_out(j);
1518           if (u->bottom_type() == Type::MEMORY) {
1519             if (trace) { tty->print("XX Next mem"); u->dump(); }
1520             // follow the memory edges
1521             wq.push(u);
1522           }
1523         }
1524       } else if (use->Opcode() == Op_ShenandoahWriteBarrier && phase->C->get_alias_index(use->adr_type()) == alias) {
1525         Node* m = use->find_out_with(Op_ShenandoahWBMemProj);
1526         if (m != NULL) {
1527           if (trace) { tty->print("XX Next mem"); m->dump(); }
1528           // follow the memory edges
1529           wq.push(m);
1530         }
1531       }
1532     }
1533   }
1534 
1535   if (controls.size() == 0) {
1536     return false;
1537   }
1538 
1539   for (uint i = 0; i < controls.size(); i++) {
1540     Node *n = controls.at(i);
1541 
1542     if (trace) { tty->print("X checking"); n->dump(); }
1543 
1544     if (n->unique_ctrl_out() != NULL) {
1545       continue;
1546     }
1547 
1548     if (n->Opcode() == Op_NeverBranch) {
1549       Node* taken = n->as_Multi()->proj_out(0);
1550       if (!controls.member(taken)) {
1551         if (trace) { tty->print("X not seen"); taken->dump(); }
1552         return false;
1553       }
1554       continue;
1555     }
1556 
1557     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1558       Node* u = n->fast_out(j);
1559 
1560       if (u->is_CFG()) {
1561         if (!controls.member(u)) {
1562           if (u->is_Proj() && u->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
1563             if (trace) { tty->print("X not seen but unc"); u->dump(); }
1564           } else {
1565             Node* c = u;
1566             do {
1567               c = c->unique_ctrl_out();
1568             } while (c != NULL && c->is_Region());
1569             if (c != NULL && c->Opcode() == Op_Halt) {
1570               if (trace) { tty->print("X not seen but halt"); c->dump(); }
1571             } else {
1572               if (trace) { tty->print("X not seen"); u->dump(); }
1573               return false;
1574             }
1575           }
1576         } else {
1577           if (trace) { tty->print("X seen"); u->dump(); }
1578         }
1579       }
1580     }
1581   }
1582   return true;
1583 }
1584 #endif
1585 
1586 Node* ShenandoahBarrierNode::dom_mem(Node* mem, Node*& mem_ctrl, Node* n, Node* rep_ctrl, int alias, PhaseIdealLoop* phase) {
1587   ResourceMark rm;
1588   VectorSet wq(Thread::current()->resource_area());
1589   wq.set(mem->_idx);
1590   mem_ctrl = phase->get_ctrl(mem);
1591   while (!is_dominator(mem_ctrl, rep_ctrl, mem, n, phase)) {
1592     mem = next_mem(mem, alias);
1593     if (wq.test_set(mem->_idx)) {
1594       return NULL; // hit an unexpected loop
1595     }
1596     mem_ctrl = phase->ctrl_or_self(mem);
1597   }
1598   if (mem->is_MergeMem()) {
1599     mem = mem->as_MergeMem()->memory_at(alias);
1600     mem_ctrl = phase->ctrl_or_self(mem);
1601   }
1602   return mem;
1603 }
1604 
1605 Node* ShenandoahBarrierNode::dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase) {
1606   ResourceMark rm;
1607   VectorSet wq(Thread::current()->resource_area());
1608   wq.set(mem->_idx);
1609   mem_ctrl = phase->ctrl_or_self(mem);
1610   while (!phase->is_dominator(mem_ctrl, ctrl) || mem_ctrl == ctrl) {
1611     mem = next_mem(mem, alias);
1612     if (wq.test_set(mem->_idx)) {
1613       return NULL;
1614     }
1615     mem_ctrl = phase->ctrl_or_self(mem);
1616   }
1617   if (mem->is_MergeMem()) {
1618     mem = mem->as_MergeMem()->memory_at(alias);
1619     mem_ctrl = phase->ctrl_or_self(mem);
1620   }
1621   return mem;
1622 }
1623 
1624 static void disconnect_barrier_mem(Node* wb, PhaseIterGVN& igvn) {
1625   Node* mem_in = wb->in(ShenandoahBarrierNode::Memory);
1626   Node* proj = wb->find_out_with(Op_ShenandoahWBMemProj);
1627 
1628   for (DUIterator_Last imin, i = proj->last_outs(imin); i >= imin; ) {
1629     Node* u = proj->last_out(i);
1630     igvn.rehash_node_delayed(u);
1631     int nb = u->replace_edge(proj, mem_in);
1632     assert(nb > 0, "no replacement?");
1633     i -= nb;
1634   }
1635 }
1636 
1637 Node* ShenandoahWriteBarrierNode::move_above_predicates(LoopNode* cl, Node* val_ctrl, PhaseIdealLoop* phase) {
1638   Node* entry = cl->skip_strip_mined(-1)->in(LoopNode::EntryControl);
1639   Node* above_pred = phase->skip_all_loop_predicates(entry);
1640   Node* ctrl = entry;
1641   while (ctrl != above_pred) {
1642     Node* next = ctrl->in(0);
1643     if (!phase->is_dominator(val_ctrl, next)) {
1644       break;
1645     }
1646     ctrl = next;
1647   }
1648   return ctrl;
1649 }
1650 
1651 static MemoryGraphFixer* find_fixer(GrowableArray<MemoryGraphFixer*>& memory_graph_fixers, int alias) {
1652   for (int i = 0; i < memory_graph_fixers.length(); i++) {
1653     if (memory_graph_fixers.at(i)->alias() == alias) {
1654       return memory_graph_fixers.at(i);
1655     }
1656   }
1657   return NULL;
1658 }
1659 
1660 static MemoryGraphFixer* create_fixer(GrowableArray<MemoryGraphFixer*>& memory_graph_fixers, int alias, PhaseIdealLoop* phase, bool include_lsm) {
1661   assert(find_fixer(memory_graph_fixers, alias) == NULL, "none should exist yet");
1662   MemoryGraphFixer* fixer = new MemoryGraphFixer(alias, include_lsm, phase);
1663   memory_graph_fixers.push(fixer);
1664   return fixer;
1665 }
1666 
1667 void ShenandoahWriteBarrierNode::try_move_before_loop_helper(LoopNode* cl, Node* val_ctrl, GrowableArray<MemoryGraphFixer*>& memory_graph_fixers, PhaseIdealLoop* phase, bool include_lsm, Unique_Node_List& uses) {
1668   assert(cl->is_Loop(), "bad control");
1669   Node* ctrl = move_above_predicates(cl, val_ctrl, phase);
1670   Node* mem_ctrl = NULL;
1671   int alias = phase->C->get_alias_index(adr_type());
1672 
1673   MemoryGraphFixer* fixer = find_fixer(memory_graph_fixers, alias);
1674   if (fixer == NULL) {
1675     fixer = create_fixer(memory_graph_fixers, alias, phase, include_lsm);
1676   }
1677 
1678   Node* proj = find_out_with(Op_ShenandoahWBMemProj);
1679 
1680   fixer->remove(proj);
1681   Node* mem = fixer->find_mem(ctrl, NULL);
1682 
1683   assert(!ShenandoahVerifyOptoBarriers || memory_dominates_all_paths(mem, ctrl, alias, phase), "can't fix the memory graph");
1684 
1685   phase->set_ctrl_and_loop(this, ctrl);
1686   phase->igvn().replace_input_of(this, Control, ctrl);
1687 
1688   disconnect_barrier_mem(this, phase->igvn());
1689 
1690   phase->igvn().replace_input_of(this, Memory, mem);
1691   phase->set_ctrl_and_loop(proj, ctrl);
1692 
1693   fixer->fix_mem(ctrl, ctrl, mem, mem, proj, uses);
1694   assert(proj->outcnt() > 0, "disconnected write barrier");
1695 }
1696 
1697 LoopNode* ShenandoahWriteBarrierNode::try_move_before_pre_loop(Node* c, Node* val_ctrl, PhaseIdealLoop* phase) {
1698   // A write barrier between a pre and main loop can get in the way of
1699   // vectorization. Move it above the pre loop if possible
1700   CountedLoopNode* cl = NULL;
1701   if (c->is_IfFalse() &&
1702       c->in(0)->is_CountedLoopEnd()) {
1703     cl = c->in(0)->as_CountedLoopEnd()->loopnode();
1704   } else if (c->is_IfProj() &&
1705              c->in(0)->is_If() &&
1706              c->in(0)->in(0)->is_IfFalse() &&
1707              c->in(0)->in(0)->in(0)->is_CountedLoopEnd()) {
1708     cl = c->in(0)->in(0)->in(0)->as_CountedLoopEnd()->loopnode();
1709   }
1710   if (cl != NULL &&
1711       cl->is_pre_loop() &&
1712       val_ctrl != cl &&
1713       phase->is_dominator(val_ctrl, cl)) {
1714     return cl;
1715   }
1716   return NULL;
1717 }
1718 
1719 void ShenandoahWriteBarrierNode::try_move_before_loop(GrowableArray<MemoryGraphFixer*>& memory_graph_fixers, PhaseIdealLoop* phase, bool include_lsm, Unique_Node_List& uses) {
1720   Node *n_ctrl = phase->get_ctrl(this);
1721   IdealLoopTree *n_loop = phase->get_loop(n_ctrl);
1722   Node* val = in(ValueIn);
1723   Node* val_ctrl = phase->get_ctrl(val);
1724   if (n_loop != phase->ltree_root() && !n_loop->_irreducible) {
1725     IdealLoopTree *val_loop = phase->get_loop(val_ctrl);
1726     Node* mem = in(Memory);
1727     IdealLoopTree *mem_loop = phase->get_loop(phase->get_ctrl(mem));
1728     if (!n_loop->is_member(val_loop) &&
1729         n_loop->is_member(mem_loop)) {
1730       Node* n_loop_head = n_loop->_head;
1731 
1732       if (n_loop_head->is_Loop()) {
1733         LoopNode* loop = n_loop_head->as_Loop();
1734         if (n_loop_head->is_CountedLoop() && n_loop_head->as_CountedLoop()->is_main_loop()) {
1735           LoopNode* res = try_move_before_pre_loop(n_loop_head->in(LoopNode::EntryControl), val_ctrl, phase);
1736           if (res != NULL) {
1737             loop = res;
1738           }
1739         }
1740 
1741         try_move_before_loop_helper(loop, val_ctrl, memory_graph_fixers, phase, include_lsm, uses);
1742       }
1743     }
1744   }
1745   LoopNode* ctrl = try_move_before_pre_loop(in(0), val_ctrl, phase);
1746   if (ctrl != NULL) {
1747     try_move_before_loop_helper(ctrl, val_ctrl, memory_graph_fixers, phase, include_lsm, uses);
1748   }
1749 }
1750 
1751 Node* ShenandoahWriteBarrierNode::would_subsume(ShenandoahBarrierNode* other, PhaseIdealLoop* phase) {
1752   Node* val = in(ValueIn);
1753   Node* val_ctrl = phase->get_ctrl(val);
1754   Node* other_mem = other->in(Memory);
1755   Node* other_ctrl = phase->get_ctrl(other);
1756   Node* this_ctrl = phase->get_ctrl(this);
1757   IdealLoopTree* this_loop = phase->get_loop(this_ctrl);
1758   IdealLoopTree* other_loop = phase->get_loop(other_ctrl);
1759 
1760   Node* ctrl = phase->dom_lca(other_ctrl, this_ctrl);
1761 
1762   if (ctrl->is_Proj() &&
1763       ctrl->in(0)->is_Call() &&
1764       ctrl->unique_ctrl_out() != NULL &&
1765       ctrl->unique_ctrl_out()->Opcode() == Op_Catch &&
1766       !phase->is_dominator(val_ctrl, ctrl->in(0)->in(0))) {
1767     return NULL;
1768   }
1769 
1770   IdealLoopTree* loop = phase->get_loop(ctrl);
1771 
1772   // We don't want to move a write barrier in a loop
1773   // If the LCA is in a inner loop, try a control out of loop if possible
1774   while (!loop->is_member(this_loop) && (other->Opcode() != Op_ShenandoahWriteBarrier || !loop->is_member(other_loop))) {
1775     ctrl = phase->idom(ctrl);
1776     if (ctrl->is_MultiBranch()) {
1777       ctrl = ctrl->in(0);
1778     }
1779     if (ctrl != val_ctrl && phase->is_dominator(ctrl, val_ctrl)) {
1780       return NULL;
1781     }
1782     loop = phase->get_loop(ctrl);
1783   }
1784 
1785   if (ShenandoahDontIncreaseWBFreq) {
1786     Node* this_iffproj = no_branches(this_ctrl, ctrl, true, phase);
1787     if (other->Opcode() == Op_ShenandoahWriteBarrier) {
1788       Node* other_iffproj = no_branches(other_ctrl, ctrl, true, phase);
1789       if (other_iffproj == NULL || this_iffproj == NULL) {
1790         return ctrl;
1791       } else if (other_iffproj != NodeSentinel && this_iffproj != NodeSentinel &&
1792                  other_iffproj->in(0) == this_iffproj->in(0)) {
1793         return ctrl;
1794       }
1795     } else if (this_iffproj == NULL) {
1796       return ctrl;
1797     }
1798     return NULL;
1799   }
1800 
1801   return ctrl;
1802 }
1803 
1804 void ShenandoahWriteBarrierNode::optimize_before_expansion(PhaseIdealLoop* phase, GrowableArray<MemoryGraphFixer*> memory_graph_fixers, bool include_lsm) {
1805   bool progress = false;
1806   Unique_Node_List uses;
1807   do {
1808     progress = false;
1809     for (int i = 0; i < ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count(); i++) {
1810       ShenandoahWriteBarrierNode* wb = ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barrier(i);
1811 
1812       wb->try_move_before_loop(memory_graph_fixers, phase, include_lsm, uses);
1813 
1814       Node* val = wb->in(ValueIn);
1815 
1816       for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
1817         Node* u = val->fast_out(j);
1818         if (u != wb && u->is_ShenandoahBarrier()) {
1819           Node* rep_ctrl = wb->would_subsume(u->as_ShenandoahBarrier(), phase);
1820 
1821           if (rep_ctrl != NULL) {
1822             Node* other = u;
1823             Node* val_ctrl = phase->get_ctrl(val);
1824             if (rep_ctrl->is_Proj() &&
1825                 rep_ctrl->in(0)->is_Call() &&
1826                 rep_ctrl->unique_ctrl_out() != NULL &&
1827                 rep_ctrl->unique_ctrl_out()->Opcode() == Op_Catch) {
1828               rep_ctrl = rep_ctrl->in(0)->in(0);
1829 
1830               assert(phase->is_dominator(val_ctrl, rep_ctrl), "bad control");
1831             } else {
1832               LoopNode* c = ShenandoahWriteBarrierNode::try_move_before_pre_loop(rep_ctrl, val_ctrl, phase);
1833               if (c != NULL) {
1834                 rep_ctrl = ShenandoahWriteBarrierNode::move_above_predicates(c, val_ctrl, phase);
1835               } else {
1836                 while (rep_ctrl->is_IfProj()) {
1837                   CallStaticJavaNode* unc = rep_ctrl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1838                   if (unc != NULL) {
1839                     int req = unc->uncommon_trap_request();
1840                     Deoptimization::DeoptReason trap_reason = Deoptimization::trap_request_reason(req);
1841                     if ((trap_reason == Deoptimization::Reason_loop_limit_check ||
1842                          trap_reason == Deoptimization::Reason_predicate ||
1843                          trap_reason == Deoptimization::Reason_profile_predicate) &&
1844                         phase->is_dominator(val_ctrl, rep_ctrl->in(0)->in(0))) {
1845                       rep_ctrl = rep_ctrl->in(0)->in(0);
1846                       continue;
1847                     }
1848                   }
1849                   break;
1850                 }
1851               }
1852             }
1853 
1854             Node* wb_ctrl = phase->get_ctrl(wb);
1855             Node* other_ctrl = phase->get_ctrl(other);
1856             int alias = phase->C->get_alias_index(wb->adr_type());
1857             MemoryGraphFixer* fixer = find_fixer(memory_graph_fixers, alias);;
1858             if (!is_dominator(wb_ctrl, other_ctrl, wb, other, phase)) {
1859               if (fixer == NULL) {
1860                 fixer = create_fixer(memory_graph_fixers, alias, phase, include_lsm);
1861               }
1862               Node* mem = fixer->find_mem(rep_ctrl, phase->get_ctrl(other) == rep_ctrl ? other : NULL);
1863 
1864               if (mem->has_out_with(Op_Lock) || mem->has_out_with(Op_Unlock)) {
1865                 continue;
1866               }
1867 
1868               Node* wb_proj = wb->find_out_with(Op_ShenandoahWBMemProj);
1869               fixer->remove(wb_proj);
1870               Node* mem_for_ctrl = fixer->find_mem(rep_ctrl, NULL);
1871 
1872               if (wb->in(Memory) != mem) {
1873                 disconnect_barrier_mem(wb, phase->igvn());
1874                 phase->igvn().replace_input_of(wb, Memory, mem);
1875               }
1876               if (rep_ctrl != wb_ctrl) {
1877                 phase->set_ctrl_and_loop(wb, rep_ctrl);
1878                 phase->igvn().replace_input_of(wb, Control, rep_ctrl);
1879                 phase->set_ctrl_and_loop(wb_proj, rep_ctrl);
1880                 progress = true;
1881               }
1882 
1883               fixer->fix_mem(rep_ctrl, rep_ctrl, mem, mem_for_ctrl, wb_proj, uses);
1884 
1885               assert(!ShenandoahVerifyOptoBarriers || ShenandoahWriteBarrierNode::memory_dominates_all_paths(mem, rep_ctrl, alias, phase), "can't fix the memory graph");
1886             }
1887 
1888             if (other->Opcode() == Op_ShenandoahWriteBarrier) {
1889               Node* other_proj = other->find_out_with(Op_ShenandoahWBMemProj);
1890               if (fixer != NULL) {
1891                 fixer->remove(other_proj);
1892               }
1893               phase->igvn().replace_node(other_proj, other->in(Memory));
1894             }
1895             phase->igvn().replace_node(other, wb);
1896             --j; --jmax;
1897           }
1898         }
1899       }
1900     }
1901   } while(progress);
1902 }
1903 
1904 void ShenandoahReadBarrierNode::try_move(Node *n_ctrl, PhaseIdealLoop* phase) {
1905   Node* mem = in(MemNode::Memory);
1906   int alias = phase->C->get_alias_index(adr_type());
1907   const bool trace = false;
1908 
1909 #ifdef ASSERT
1910   if (trace) { tty->print("Trying to move mem of"); dump(); }
1911 #endif
1912 
1913   Node* new_mem = mem;
1914 
1915   ResourceMark rm;
1916   VectorSet seen(Thread::current()->resource_area());
1917   Node_List phis;
1918 
1919   for (;;) {
1920 #ifdef ASSERT
1921     if (trace) { tty->print("Looking for dominator from"); mem->dump(); }
1922 #endif
1923     if (mem->is_Proj() && mem->in(0)->is_Start()) {
1924       if (new_mem != in(MemNode::Memory)) {
1925 #ifdef ASSERT
1926         if (trace) { tty->print("XXX Setting mem to"); new_mem->dump(); tty->print(" for "); dump(); }
1927 #endif
1928         phase->igvn().replace_input_of(this, MemNode::Memory, new_mem);
1929       }
1930       return;
1931     }
1932 
1933     Node* candidate = mem;
1934     do {
1935       if (!is_independent(mem)) {
1936         if (trace) { tty->print_cr("Not independent"); }
1937         if (new_mem != in(MemNode::Memory)) {
1938 #ifdef ASSERT
1939           if (trace) { tty->print("XXX Setting mem to"); new_mem->dump(); tty->print(" for "); dump(); }
1940 #endif
1941           phase->igvn().replace_input_of(this, MemNode::Memory, new_mem);
1942         }
1943         return;
1944       }
1945       if (seen.test_set(mem->_idx)) {
1946         if (trace) { tty->print_cr("Already seen"); }
1947         ShouldNotReachHere();
1948         // Strange graph
1949         if (new_mem != in(MemNode::Memory)) {
1950 #ifdef ASSERT
1951           if (trace) { tty->print("XXX Setting mem to"); new_mem->dump(); tty->print(" for "); dump(); }
1952 #endif
1953           phase->igvn().replace_input_of(this, MemNode::Memory, new_mem);
1954         }
1955         return;
1956       }
1957       if (mem->is_Phi()) {
1958         phis.push(mem);
1959       }
1960       mem = next_mem(mem, alias);
1961       if (mem->bottom_type() == Type::MEMORY) {
1962         candidate = mem;
1963       }
1964       assert(is_dominator(phase->ctrl_or_self(mem), n_ctrl, mem, this, phase) == phase->is_dominator(phase->ctrl_or_self(mem), n_ctrl), "strange dominator");
1965 #ifdef ASSERT
1966       if (trace) { tty->print("Next mem is"); mem->dump(); }
1967 #endif
1968     } while (mem->bottom_type() != Type::MEMORY || !phase->is_dominator(phase->ctrl_or_self(mem), n_ctrl));
1969 
1970     assert(mem->bottom_type() == Type::MEMORY, "bad mem");
1971 
1972     bool not_dom = false;
1973     for (uint i = 0; i < phis.size() && !not_dom; i++) {
1974       Node* nn = phis.at(i);
1975 
1976 #ifdef ASSERT
1977       if (trace) { tty->print("Looking from phi"); nn->dump(); }
1978 #endif
1979       assert(nn->is_Phi(), "phis only");
1980       for (uint j = 2; j < nn->req() && !not_dom; j++) {
1981         Node* m = nn->in(j);
1982 #ifdef ASSERT
1983         if (trace) { tty->print("Input %d is", j); m->dump(); }
1984 #endif
1985         while (m != mem && !seen.test_set(m->_idx)) {
1986           if (is_dominator(phase->ctrl_or_self(m), phase->ctrl_or_self(mem), m, mem, phase)) {
1987             not_dom = true;
1988             // Scheduling anomaly
1989 #ifdef ASSERT
1990             if (trace) { tty->print("Giving up"); m->dump(); }
1991 #endif
1992             break;
1993           }
1994           if (!is_independent(m)) {
1995             if (trace) { tty->print_cr("Not independent"); }
1996             if (new_mem != in(MemNode::Memory)) {
1997 #ifdef ASSERT
1998               if (trace) { tty->print("XXX Setting mem to"); new_mem->dump(); tty->print(" for "); dump(); }
1999 #endif
2000               phase->igvn().replace_input_of(this, MemNode::Memory, new_mem);
2001             }
2002             return;
2003           }
2004           if (m->is_Phi()) {
2005             phis.push(m);
2006           }
2007           m = next_mem(m, alias);
2008 #ifdef ASSERT
2009           if (trace) { tty->print("Next mem is"); m->dump(); }
2010 #endif
2011         }
2012       }
2013     }
2014     if (!not_dom) {
2015       new_mem = mem;
2016       phis.clear();
2017     } else {
2018       seen.Clear();
2019     }
2020   }
2021 }
2022 
2023 CallStaticJavaNode* ShenandoahWriteBarrierNode::pin_and_expand_null_check(PhaseIterGVN& igvn) {
2024   Node* val = in(ValueIn);
2025 
2026   const Type* val_t = igvn.type(val);
2027 
2028   if (val_t->meet(TypePtr::NULL_PTR) != val_t &&
2029       val->Opcode() == Op_CastPP &&
2030       val->in(0) != NULL &&
2031       val->in(0)->Opcode() == Op_IfTrue &&
2032       val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
2033       val->in(0)->in(0)->is_If() &&
2034       val->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
2035       val->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
2036       val->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
2037       val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1) &&
2038       val->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
2039     assert(val->in(0)->in(0)->in(1)->in(1)->in(1) == val->in(1), "");
2040     CallStaticJavaNode* unc = val->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
2041     return unc;
2042   }
2043   return NULL;
2044 }
2045 
2046 void ShenandoahWriteBarrierNode::pin_and_expand_move_barrier(PhaseIdealLoop* phase, GrowableArray<MemoryGraphFixer*>& memory_graph_fixers, Unique_Node_List& uses) {
2047   Node* unc = pin_and_expand_null_check(phase->igvn());
2048   Node* val = in(ValueIn);
2049 
2050   if (unc != NULL) {
2051     Node* ctrl = phase->get_ctrl(this);
2052     Node* unc_ctrl = val->in(0);
2053 
2054     // Don't move write barrier in a loop
2055     IdealLoopTree* loop = phase->get_loop(ctrl);
2056     IdealLoopTree* unc_loop = phase->get_loop(unc_ctrl);
2057 
2058     if (!unc_loop->is_member(loop)) {
2059       return;
2060     }
2061 
2062     Node* branch = no_branches(ctrl, unc_ctrl, false, phase);
2063     assert(branch == NULL || branch == NodeSentinel, "was not looking for a branch");
2064     if (branch == NodeSentinel) {
2065       return;
2066     }
2067 
2068     RegionNode* r = new RegionNode(3);
2069     IfNode* iff = unc_ctrl->in(0)->as_If();
2070 
2071     Node* ctrl_use = unc_ctrl->unique_ctrl_out();
2072     Node* unc_ctrl_clone = unc_ctrl->clone();
2073     phase->register_control(unc_ctrl_clone, loop, iff);
2074     Node* c = unc_ctrl_clone;
2075     Node* new_cast = clone_null_check(c, val, unc_ctrl_clone, phase);
2076     r->init_req(1, new_cast->in(0)->in(0)->as_If()->proj_out(0));
2077 
2078     phase->igvn().replace_input_of(unc_ctrl, 0, c->in(0));
2079     phase->set_idom(unc_ctrl, c->in(0), phase->dom_depth(unc_ctrl));
2080     phase->lazy_replace(c, unc_ctrl);
2081     c = NULL;;
2082     phase->igvn().replace_input_of(val, 0, unc_ctrl_clone);
2083     phase->set_ctrl(val, unc_ctrl_clone);
2084 
2085     IfNode* new_iff = new_cast->in(0)->in(0)->as_If();
2086     fix_null_check(unc, unc_ctrl_clone, r, uses, phase);
2087     Node* iff_proj = iff->proj_out(0);
2088     r->init_req(2, iff_proj);
2089     phase->register_control(r, phase->ltree_root(), iff);
2090 
2091     Node* new_bol = new_iff->in(1)->clone();
2092     Node* new_cmp = new_bol->in(1)->clone();
2093     assert(new_cmp->Opcode() == Op_CmpP, "broken");
2094     assert(new_cmp->in(1) == val->in(1), "broken");
2095     new_bol->set_req(1, new_cmp);
2096     new_cmp->set_req(1, this);
2097     phase->register_new_node(new_bol, new_iff->in(0));
2098     phase->register_new_node(new_cmp, new_iff->in(0));
2099     phase->igvn().replace_input_of(new_iff, 1, new_bol);
2100     phase->igvn().replace_input_of(new_cast, 1, this);
2101 
2102     for (DUIterator_Fast imax, i = this->fast_outs(imax); i < imax; i++) {
2103       Node* u = this->fast_out(i);
2104       if (u == new_cast || u->Opcode() == Op_ShenandoahWBMemProj || u == new_cmp) {
2105         continue;
2106       }
2107       phase->igvn().rehash_node_delayed(u);
2108       int nb = u->replace_edge(this, new_cast);
2109       assert(nb > 0, "no update?");
2110       --i; imax -= nb;
2111     }
2112 
2113     for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
2114       Node* u = val->fast_out(i);
2115       if (u == this) {
2116         continue;
2117       }
2118       phase->igvn().rehash_node_delayed(u);
2119       int nb = u->replace_edge(val, new_cast);
2120       assert(nb > 0, "no update?");
2121       --i; imax -= nb;
2122     }
2123 
2124     Node* new_ctrl = unc_ctrl_clone;
2125 
2126     int alias = phase->C->get_alias_index(adr_type());
2127     MemoryGraphFixer* fixer = find_fixer(memory_graph_fixers, alias);
2128     if (fixer == NULL) {
2129       fixer = create_fixer(memory_graph_fixers, alias, phase, true);
2130     }
2131 
2132     Node* proj = find_out_with(Op_ShenandoahWBMemProj);
2133     fixer->remove(proj);
2134     Node* mem = fixer->find_mem(new_ctrl, NULL);
2135 
2136     if (in(Memory) != mem) {
2137       disconnect_barrier_mem(this, phase->igvn());
2138       phase->igvn().replace_input_of(this, Memory, mem);
2139     }
2140 
2141     phase->set_ctrl_and_loop(this, new_ctrl);
2142     phase->igvn().replace_input_of(this, Control, new_ctrl);
2143     phase->set_ctrl_and_loop(proj, new_ctrl);
2144 
2145     fixer->fix_mem(new_ctrl, new_ctrl, mem, mem, proj, uses);
2146   }
2147 }
2148 
2149 void ShenandoahWriteBarrierNode::pin_and_expand_helper(PhaseIdealLoop* phase) {
2150   Node* val = in(ValueIn);
2151   CallStaticJavaNode* unc = pin_and_expand_null_check(phase->igvn());
2152   Node* rep = this;
2153   Node* ctrl = phase->get_ctrl(this);
2154   if (unc != NULL && val->in(0) == ctrl) {
2155     Node* unc_ctrl = val->in(0);
2156     IfNode* other_iff = unc_ctrl->unique_ctrl_out()->as_If();
2157     ProjNode* other_unc_ctrl = other_iff->proj_out(1);
2158     Node* cast = NULL;
2159     for (DUIterator_Fast imax, i = other_unc_ctrl->fast_outs(imax); i < imax && cast == NULL; i++) {
2160       Node* u = other_unc_ctrl->fast_out(i);
2161       if (u->Opcode() == Op_CastPP && u->in(1) == this) {
2162         cast = u;
2163       }
2164     }
2165     assert(other_unc_ctrl->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) == unc, "broken");
2166     rep = cast;
2167   }
2168 
2169   // Replace all uses of barrier's input that are dominated by ctrl
2170   // with the value returned by the barrier: no need to keep both
2171   // live.
2172   for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
2173     Node* u = val->fast_out(i);
2174     if (u != this) {
2175       if (u->is_Phi()) {
2176         int nb = 0;
2177         for (uint j = 1; j < u->req(); j++) {
2178           if (u->in(j) == val) {
2179             Node* c = u->in(0)->in(j);
2180             if (phase->is_dominator(ctrl, c)) {
2181               phase->igvn().replace_input_of(u, j, rep);
2182               nb++;
2183             }
2184           }
2185         }
2186         if (nb > 0) {
2187           imax -= nb;
2188           --i;
2189         }
2190       } else {
2191         Node* c = phase->ctrl_or_self(u);
2192         if (is_dominator(ctrl, c, this, u, phase)) {
2193           phase->igvn().rehash_node_delayed(u);
2194           int nb = u->replace_edge(val, rep);
2195           assert(nb > 0, "no update?");
2196           --i, imax -= nb;
2197         }
2198       }
2199     }
2200   }
2201 }
2202 
2203 Node* ShenandoahWriteBarrierNode::find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase) {
2204   Node* mem = NULL;
2205   Node* c = ctrl;
2206   do {
2207     if (c->is_Region()) {
2208       Node* phi_bottom = NULL;
2209       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax && mem == NULL; i++) {
2210         Node* u = c->fast_out(i);
2211         if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
2212           if (u->adr_type() == TypePtr::BOTTOM) {
2213             mem = u;
2214           }
2215         }
2216       }
2217     } else {
2218       if (c->is_Call() && c->as_Call()->adr_type() != NULL) {
2219         CallProjections projs;
2220         c->as_Call()->extract_projections(&projs, true, false);
2221         if (projs.fallthrough_memproj != NULL) {
2222           if (projs.fallthrough_memproj->adr_type() == TypePtr::BOTTOM) {
2223             if (projs.catchall_memproj == NULL) {
2224               mem = projs.fallthrough_memproj;
2225             } else {
2226               if (phase->is_dominator(projs.fallthrough_catchproj, ctrl)) {
2227                 mem = projs.fallthrough_memproj;
2228               } else {
2229                 assert(phase->is_dominator(projs.catchall_catchproj, ctrl), "one proj must dominate barrier");
2230                 mem = projs.catchall_memproj;
2231               }
2232             }
2233           }
2234         } else {
2235           Node* proj = c->as_Call()->proj_out(TypeFunc::Memory);
2236           if (proj != NULL &&
2237               proj->adr_type() == TypePtr::BOTTOM) {
2238             mem = proj;
2239           }
2240         }
2241       } else {
2242         for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
2243           Node* u = c->fast_out(i);
2244           if (u->is_Proj() &&
2245               u->bottom_type() == Type::MEMORY &&
2246               u->adr_type() == TypePtr::BOTTOM) {
2247               assert(c->is_SafePoint() || c->is_MemBar() || c->is_Start(), "");
2248               assert(mem == NULL, "only one proj");
2249               mem = u;
2250           }
2251         }
2252         assert(!c->is_Call() || c->as_Call()->adr_type() != NULL || mem == NULL, "no mem projection expected");
2253       }
2254     }
2255     c = phase->idom(c);
2256   } while (mem == NULL);
2257   return mem;
2258 }
2259 
2260 void ShenandoahWriteBarrierNode::follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase) {
2261   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2262     Node* u = n->fast_out(i);
2263     if (!u->is_CFG() && phase->get_ctrl(u) == ctrl && (!u->is_Phi() || !u->in(0)->is_Loop() || u->in(LoopNode::LoopBackControl) != n)) {
2264       uses.push(u);
2265     }
2266   }
2267 }
2268 
2269 void ShenandoahWriteBarrierNode::test_heap_stable(Node*& ctrl, Node* raw_mem, Node*& heap_stable_ctrl,
2270                                                   PhaseIdealLoop* phase) {
2271   IdealLoopTree* loop = phase->get_loop(ctrl);
2272   Node* thread = new ThreadLocalNode();
2273   phase->register_new_node(thread, ctrl);
2274   Node* offset = phase->igvn().MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
2275   phase->set_ctrl(offset, phase->C->root());
2276   Node* gc_state_addr = new AddPNode(phase->C->top(), thread, offset);
2277   phase->register_new_node(gc_state_addr, ctrl);
2278   uint gc_state_idx = Compile::AliasIdxRaw;
2279   const TypePtr* gc_state_adr_type = NULL; // debug-mode-only argument
2280   debug_only(gc_state_adr_type = phase->C->get_adr_type(gc_state_idx));
2281 
2282   Node* gc_state = new LoadBNode(ctrl, raw_mem, gc_state_addr, gc_state_adr_type, TypeInt::BYTE, MemNode::unordered);
2283   phase->register_new_node(gc_state, ctrl);
2284   Node* heap_stable_and = new AndINode(gc_state, phase->igvn().intcon(ShenandoahHeap::HAS_FORWARDED));
2285   phase->register_new_node(heap_stable_and, ctrl);
2286   Node* heap_stable_cmp = new CmpINode(heap_stable_and, phase->igvn().zerocon(T_INT));
2287   phase->register_new_node(heap_stable_cmp, ctrl);
2288   Node* heap_stable_test = new BoolNode(heap_stable_cmp, BoolTest::ne);
2289   phase->register_new_node(heap_stable_test, ctrl);
2290   IfNode* heap_stable_iff = new IfNode(ctrl, heap_stable_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
2291   phase->register_control(heap_stable_iff, loop, ctrl);
2292 
2293   heap_stable_ctrl = new IfFalseNode(heap_stable_iff);
2294   phase->register_control(heap_stable_ctrl, loop, heap_stable_iff);
2295   ctrl = new IfTrueNode(heap_stable_iff);
2296   phase->register_control(ctrl, loop, heap_stable_iff);
2297 
2298   assert(is_heap_stable_test(heap_stable_iff), "Should match the shape");
2299 }
2300 
2301 void ShenandoahWriteBarrierNode::test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase) {
2302   const Type* val_t = phase->igvn().type(val);
2303   if (val_t->meet(TypePtr::NULL_PTR) == val_t) {
2304     IdealLoopTree* loop = phase->get_loop(ctrl);
2305     Node* null_cmp = new CmpPNode(val, phase->igvn().zerocon(T_OBJECT));
2306     phase->register_new_node(null_cmp, ctrl);
2307     Node* null_test = new BoolNode(null_cmp, BoolTest::ne);
2308     phase->register_new_node(null_test, ctrl);
2309     IfNode* null_iff = new IfNode(ctrl, null_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
2310     phase->register_control(null_iff, loop, ctrl);
2311     ctrl = new IfTrueNode(null_iff);
2312     phase->register_control(ctrl, loop, null_iff);
2313     null_ctrl = new IfFalseNode(null_iff);
2314     phase->register_control(null_ctrl, loop, null_iff);
2315   }
2316 }
2317 
2318 Node* ShenandoahWriteBarrierNode::clone_null_check(Node*& c, Node* val, Node* unc_ctrl, PhaseIdealLoop* phase) {
2319   IdealLoopTree *loop = phase->get_loop(c);
2320   Node* iff = unc_ctrl->in(0);
2321   assert(iff->is_If(), "broken");
2322   Node* new_iff = iff->clone();
2323   new_iff->set_req(0, c);
2324   phase->register_control(new_iff, loop, c);
2325   Node* iffalse = new IfFalseNode(new_iff->as_If());
2326   phase->register_control(iffalse, loop, new_iff);
2327   Node* iftrue = new IfTrueNode(new_iff->as_If());
2328   phase->register_control(iftrue, loop, new_iff);
2329   c = iftrue;
2330   const Type *t = phase->igvn().type(val);
2331   assert(val->Opcode() == Op_CastPP, "expect cast to non null here");
2332   Node* uncasted_val = val->in(1);
2333   val = new CastPPNode(uncasted_val, t);
2334   val->init_req(0, c);
2335   phase->register_new_node(val, c);
2336   return val;
2337 }
2338 
2339 void ShenandoahWriteBarrierNode::fix_null_check(Node* unc, Node* unc_ctrl, Node* new_unc_ctrl,
2340                                                 Unique_Node_List& uses, PhaseIdealLoop* phase) {
2341   IfNode* iff = unc_ctrl->in(0)->as_If();
2342   Node* proj = iff->proj_out(0);
2343   assert(proj != unc_ctrl, "bad projection");
2344   Node* use = proj->unique_ctrl_out();
2345 
2346   assert(use == unc || use->is_Region(), "what else?");
2347 
2348   uses.clear();
2349   if (use == unc) {
2350     phase->set_idom(use, new_unc_ctrl, phase->dom_depth(use));
2351     for (uint i = 1; i < unc->req(); i++) {
2352       Node* n = unc->in(i);
2353       if (phase->has_ctrl(n) && phase->get_ctrl(n) == proj) {
2354         uses.push(n);
2355       }
2356     }
2357   } else {
2358     assert(use->is_Region(), "what else?");
2359     uint idx = 1;
2360     for (; use->in(idx) != proj; idx++);
2361     for (DUIterator_Fast imax, i = use->fast_outs(imax); i < imax; i++) {
2362       Node* u = use->fast_out(i);
2363       if (u->is_Phi() && phase->get_ctrl(u->in(idx)) == proj) {
2364         uses.push(u->in(idx));
2365       }
2366     }
2367   }
2368   for(uint next = 0; next < uses.size(); next++ ) {
2369     Node *n = uses.at(next);
2370     assert(phase->get_ctrl(n) == proj, "bad control");
2371     phase->set_ctrl_and_loop(n, new_unc_ctrl);
2372     if (n->in(0) == proj) {
2373       phase->igvn().replace_input_of(n, 0, new_unc_ctrl);
2374     }
2375     for (uint i = 0; i < n->req(); i++) {
2376       Node* m = n->in(i);
2377       if (m != NULL && phase->has_ctrl(m) && phase->get_ctrl(m) == proj) {
2378         uses.push(m);
2379       }
2380     }
2381   }
2382 
2383   phase->igvn().rehash_node_delayed(use);
2384   int nb = use->replace_edge(proj, new_unc_ctrl);
2385   assert(nb == 1, "only use expected");
2386 }
2387 
2388 void ShenandoahWriteBarrierNode::in_cset_fast_test(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase) {
2389   IdealLoopTree *loop = phase->get_loop(ctrl);
2390   Node* raw_rbtrue = new CastP2XNode(ctrl, val);
2391   phase->register_new_node(raw_rbtrue, ctrl);
2392   Node* cset_offset = new URShiftXNode(raw_rbtrue, phase->igvn().intcon(ShenandoahHeapRegion::region_size_bytes_shift_jint()));
2393   phase->register_new_node(cset_offset, ctrl);
2394   Node* in_cset_fast_test_base_addr = phase->igvn().makecon(TypeRawPtr::make(ShenandoahHeap::in_cset_fast_test_addr()));
2395   phase->set_ctrl(in_cset_fast_test_base_addr, phase->C->root());
2396   Node* in_cset_fast_test_adr = new AddPNode(phase->C->top(), in_cset_fast_test_base_addr, cset_offset);
2397   phase->register_new_node(in_cset_fast_test_adr, ctrl);
2398   uint in_cset_fast_test_idx = Compile::AliasIdxRaw;
2399   const TypePtr* in_cset_fast_test_adr_type = NULL; // debug-mode-only argument
2400   debug_only(in_cset_fast_test_adr_type = phase->C->get_adr_type(in_cset_fast_test_idx));
2401   Node* in_cset_fast_test_load = new LoadBNode(ctrl, raw_mem, in_cset_fast_test_adr, in_cset_fast_test_adr_type, TypeInt::BYTE, MemNode::unordered);
2402   phase->register_new_node(in_cset_fast_test_load, ctrl);
2403   Node* in_cset_fast_test_cmp = new CmpINode(in_cset_fast_test_load, phase->igvn().zerocon(T_INT));
2404   phase->register_new_node(in_cset_fast_test_cmp, ctrl);
2405   Node* in_cset_fast_test_test = new BoolNode(in_cset_fast_test_cmp, BoolTest::eq);
2406   phase->register_new_node(in_cset_fast_test_test, ctrl);
2407   IfNode* in_cset_fast_test_iff = new IfNode(ctrl, in_cset_fast_test_test, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
2408   phase->register_control(in_cset_fast_test_iff, loop, ctrl);
2409 
2410   not_cset_ctrl = new IfTrueNode(in_cset_fast_test_iff);
2411   phase->register_control(not_cset_ctrl, loop, in_cset_fast_test_iff);
2412 
2413   ctrl = new IfFalseNode(in_cset_fast_test_iff);
2414   phase->register_control(ctrl, loop, in_cset_fast_test_iff);
2415 }
2416 
2417 void ShenandoahWriteBarrierNode::call_wb_stub(Node*& ctrl, Node*& val, Node*& result_mem,
2418                                               Node* raw_mem, Node* wb_mem,
2419                                               int alias,
2420                                               PhaseIdealLoop* phase) {
2421   IdealLoopTree*loop = phase->get_loop(ctrl);
2422   const TypePtr* obj_type = phase->igvn().type(val)->is_oopptr()->cast_to_nonconst();
2423 
2424   // The slow path stub consumes and produces raw memory in addition
2425   // to the existing memory edges
2426   Node* base = find_bottom_mem(ctrl, phase);
2427 
2428   MergeMemNode* mm = MergeMemNode::make(base);
2429   mm->set_memory_at(alias, wb_mem);
2430   mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
2431   phase->register_new_node(mm, ctrl);
2432 
2433   Node* call = new CallLeafNode(ShenandoahBarrierSetC2::shenandoah_write_barrier_Type(), CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_barrier_JRT), "shenandoah_write_barrier", TypeRawPtr::BOTTOM);
2434   call->init_req(TypeFunc::Control, ctrl);
2435   call->init_req(TypeFunc::I_O, phase->C->top());
2436   call->init_req(TypeFunc::Memory, mm);
2437   call->init_req(TypeFunc::FramePtr, phase->C->top());
2438   call->init_req(TypeFunc::ReturnAdr, phase->C->top());
2439   call->init_req(TypeFunc::Parms, val);
2440   phase->register_control(call, loop, ctrl);
2441   ctrl = new ProjNode(call, TypeFunc::Control);
2442   phase->register_control(ctrl, loop, call);
2443   result_mem = new ProjNode(call, TypeFunc::Memory);
2444   phase->register_new_node(result_mem, call);
2445   val = new ProjNode(call, TypeFunc::Parms);
2446   phase->register_new_node(val, call);
2447   val = new CheckCastPPNode(ctrl, val, obj_type);
2448   phase->register_new_node(val, ctrl);
2449 }
2450 
2451 void ShenandoahWriteBarrierNode::fix_ctrl(Node* barrier, Node* region, const MemoryGraphFixer& fixer, Unique_Node_List& uses, Unique_Node_List& uses_to_ignore, uint last, PhaseIdealLoop* phase) {
2452   Node* ctrl = phase->get_ctrl(barrier);
2453   Node* init_raw_mem = fixer.find_mem(ctrl, barrier);
2454 
2455   // Update the control of all nodes that should be after the
2456   // barrier control flow
2457   uses.clear();
2458   // Every node that is control dependent on the barrier's input
2459   // control will be after the expanded barrier. The raw memory (if
2460   // its memory is control dependent on the barrier's input control)
2461   // must stay above the barrier.
2462   uses_to_ignore.clear();
2463   if (phase->has_ctrl(init_raw_mem) && phase->get_ctrl(init_raw_mem) == ctrl && !init_raw_mem->is_Phi()) {
2464     uses_to_ignore.push(init_raw_mem);
2465   }
2466   for (uint next = 0; next < uses_to_ignore.size(); next++) {
2467     Node *n = uses_to_ignore.at(next);
2468     for (uint i = 0; i < n->req(); i++) {
2469       Node* in = n->in(i);
2470       if (in != NULL && phase->has_ctrl(in) && phase->get_ctrl(in) == ctrl) {
2471         uses_to_ignore.push(in);
2472       }
2473     }
2474   }
2475   for (DUIterator_Fast imax, i = ctrl->fast_outs(imax); i < imax; i++) {
2476     Node* u = ctrl->fast_out(i);
2477     if (u->_idx < last &&
2478         u != barrier &&
2479         !uses_to_ignore.member(u) &&
2480         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
2481         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
2482       Node* old_c = phase->ctrl_or_self(u);
2483       Node* c = old_c;
2484       if (c != ctrl ||
2485           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
2486           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
2487         phase->igvn().rehash_node_delayed(u);
2488         int nb = u->replace_edge(ctrl, region);
2489         if (u->is_CFG()) {
2490           if (phase->idom(u) == ctrl) {
2491             phase->set_idom(u, region, phase->dom_depth(region));
2492           }
2493         } else if (phase->get_ctrl(u) == ctrl) {
2494           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
2495           uses.push(u);
2496         }
2497         assert(nb == 1, "more than 1 ctrl input?");
2498         --i, imax -= nb;
2499       }
2500     }
2501   }
2502 }
2503 
2504 void ShenandoahWriteBarrierNode::pin_and_expand(PhaseIdealLoop* phase) {
2505   Node_List enqueue_barriers;
2506   if (ShenandoahStoreValEnqueueBarrier) {
2507     Unique_Node_List wq;
2508     wq.push(phase->C->root());
2509     for (uint i = 0; i < wq.size(); i++) {
2510       Node* n = wq.at(i);
2511       if (n->Opcode() == Op_ShenandoahEnqueueBarrier) {
2512         enqueue_barriers.push(n);
2513       }
2514       for (uint i = 0; i < n->req(); i++) {
2515         Node* in = n->in(i);
2516         if (in != NULL) {
2517           wq.push(in);
2518         }
2519       }
2520     }
2521   }
2522 
2523   const bool trace = false;
2524 
2525   // Collect raw memory state at CFG points in the entire graph and
2526   // record it in memory_nodes. Optimize the raw memory graph in the
2527   // process. Optimizing the memory graph also makes the memory graph
2528   // simpler.
2529   GrowableArray<MemoryGraphFixer*> memory_graph_fixers;
2530 
2531   // Let's try to common write barriers again
2532   optimize_before_expansion(phase, memory_graph_fixers, true);
2533 
2534   Unique_Node_List uses;
2535   for (int i = 0; i < ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count(); i++) {
2536     ShenandoahWriteBarrierNode* wb = ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barrier(i);
2537     Node* ctrl = phase->get_ctrl(wb);
2538 
2539     Node* val = wb->in(ValueIn);
2540     if (ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) {
2541       assert(is_dominator(phase->get_ctrl(val), ctrl->in(0)->in(0), val, ctrl->in(0), phase), "can't move");
2542       phase->set_ctrl(wb, ctrl->in(0)->in(0));
2543     } else if (ctrl->is_CallRuntime()) {
2544       assert(is_dominator(phase->get_ctrl(val), ctrl->in(0), val, ctrl, phase), "can't move");
2545       phase->set_ctrl(wb, ctrl->in(0));
2546     }
2547 
2548     assert(wb->Opcode() == Op_ShenandoahWriteBarrier, "only for write barriers");
2549     // Look for a null check that dominates this barrier and move the
2550     // barrier right after the null check to enable implicit null
2551     // checks
2552     wb->pin_and_expand_move_barrier(phase, memory_graph_fixers, uses);
2553 
2554     wb->pin_and_expand_helper(phase);
2555   }
2556 
2557   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
2558   Unique_Node_List uses_to_ignore;
2559   for (uint i = 0; i < enqueue_barriers.size(); i++) {
2560     Node* barrier = enqueue_barriers.at(i);
2561     Node* pre_val = barrier->in(1);
2562 
2563     if (phase->igvn().type(pre_val)->higher_equal(TypePtr::NULL_PTR)) {
2564       ShouldNotReachHere();
2565       continue;
2566     }
2567 
2568     Node* ctrl = phase->get_ctrl(barrier);
2569 
2570     if (ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) {
2571       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0)->in(0), pre_val, ctrl->in(0), phase), "can't move");
2572       ctrl = ctrl->in(0)->in(0);
2573       phase->set_ctrl(barrier, ctrl);
2574     } else if (ctrl->is_CallRuntime()) {
2575       assert(is_dominator(phase->get_ctrl(pre_val), ctrl->in(0), pre_val, ctrl, phase), "can't move");
2576       ctrl = ctrl->in(0);
2577       phase->set_ctrl(barrier, ctrl);
2578     }
2579 
2580     Node* init_ctrl = ctrl;
2581     IdealLoopTree* loop = phase->get_loop(ctrl);
2582     Node* raw_mem = fixer.find_mem(ctrl, barrier);
2583     Node* init_raw_mem = raw_mem;
2584     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
2585     Node* heap_stable_ctrl = NULL;
2586     Node* null_ctrl = NULL;
2587     uint last = phase->C->unique();
2588 
2589     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
2590     Node* region = new RegionNode(PATH_LIMIT);
2591     Node* phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
2592 
2593     enum { _fast_path = 1, _slow_path, _null_path, PATH_LIMIT2 };
2594     Node* region2 = new RegionNode(PATH_LIMIT2);
2595     Node* phi2 = PhiNode::make(region2, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
2596 
2597     // Stable path.
2598     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
2599     region->init_req(_heap_stable, heap_stable_ctrl);
2600     phi->init_req(_heap_stable, raw_mem);
2601 
2602     // Null path
2603     Node* reg2_ctrl = NULL;
2604     test_null(ctrl, pre_val, null_ctrl, phase);
2605     if (null_ctrl != NULL) {
2606       reg2_ctrl = null_ctrl->in(0);
2607       region2->init_req(_null_path, null_ctrl);
2608       phi2->init_req(_null_path, raw_mem);
2609     } else {
2610       region2->del_req(_null_path);
2611       phi2->del_req(_null_path);
2612     }
2613 
2614     const int index_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_index_offset());
2615     const int buffer_offset = in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset());
2616     Node* thread = new ThreadLocalNode();
2617     phase->register_new_node(thread, ctrl);
2618     Node* buffer_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(buffer_offset));
2619     phase->register_new_node(buffer_adr, ctrl);
2620     Node* index_adr = new AddPNode(phase->C->top(), thread, phase->igvn().MakeConX(index_offset));
2621     phase->register_new_node(index_adr, ctrl);
2622 
2623     BasicType index_bt = TypeX_X->basic_type();
2624     assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading G1 SATBMarkQueue::_index with wrong size.");
2625     const TypePtr* adr_type = TypeRawPtr::BOTTOM;
2626     Node* index = new LoadXNode(ctrl, raw_mem, index_adr, adr_type, TypeX_X, MemNode::unordered);
2627     phase->register_new_node(index, ctrl);
2628     Node* index_cmp = new CmpXNode(index, phase->igvn().MakeConX(0));
2629     phase->register_new_node(index_cmp, ctrl);
2630     Node* index_test = new BoolNode(index_cmp, BoolTest::ne);
2631     phase->register_new_node(index_test, ctrl);
2632     IfNode* queue_full_iff = new IfNode(ctrl, index_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
2633     if (reg2_ctrl == NULL) reg2_ctrl = queue_full_iff;
2634     phase->register_control(queue_full_iff, loop, ctrl);
2635     Node* not_full = new IfTrueNode(queue_full_iff);
2636     phase->register_control(not_full, loop, queue_full_iff);
2637     Node* full = new IfFalseNode(queue_full_iff);
2638     phase->register_control(full, loop, queue_full_iff);
2639 
2640     ctrl = not_full;
2641 
2642     Node* next_index = new SubXNode(index, phase->igvn().MakeConX(sizeof(intptr_t)));
2643     phase->register_new_node(next_index, ctrl);
2644 
2645     Node* buffer  = new LoadPNode(ctrl, raw_mem, buffer_adr, adr_type, TypeRawPtr::NOTNULL, MemNode::unordered);
2646     phase->register_new_node(buffer, ctrl);
2647     Node *log_addr = new AddPNode(phase->C->top(), buffer, next_index);
2648     phase->register_new_node(log_addr, ctrl);
2649     Node* log_store = new StorePNode(ctrl, raw_mem, log_addr, adr_type, pre_val, MemNode::unordered);
2650     phase->register_new_node(log_store, ctrl);
2651     // update the index
2652     Node* index_update = new StoreXNode(ctrl, log_store, index_adr, adr_type, next_index, MemNode::unordered);
2653     phase->register_new_node(index_update, ctrl);
2654 
2655     // Fast-path case
2656     region2->init_req(_fast_path, ctrl);
2657     phi2->init_req(_fast_path, index_update);
2658 
2659     ctrl = full;
2660 
2661     Node* base = find_bottom_mem(ctrl, phase);
2662 
2663     MergeMemNode* mm = MergeMemNode::make(base);
2664     mm->set_memory_at(Compile::AliasIdxRaw, raw_mem);
2665     phase->register_new_node(mm, ctrl);
2666 
2667     Node* call = new CallLeafNode(ShenandoahBarrierSetC2::write_ref_field_pre_entry_Type(), CAST_FROM_FN_PTR(address, ShenandoahRuntime::write_ref_field_pre_entry), "shenandoah_wb_pre", TypeRawPtr::BOTTOM);
2668     call->init_req(TypeFunc::Control, ctrl);
2669     call->init_req(TypeFunc::I_O, phase->C->top());
2670     call->init_req(TypeFunc::Memory, mm);
2671     call->init_req(TypeFunc::FramePtr, phase->C->top());
2672     call->init_req(TypeFunc::ReturnAdr, phase->C->top());
2673     call->init_req(TypeFunc::Parms, pre_val);
2674     call->init_req(TypeFunc::Parms+1, thread);
2675     phase->register_control(call, loop, ctrl);
2676 
2677     Node* ctrl_proj = new ProjNode(call, TypeFunc::Control);
2678     phase->register_control(ctrl_proj, loop, call);
2679     Node* mem_proj = new ProjNode(call, TypeFunc::Memory);
2680     phase->register_new_node(mem_proj, call);
2681 
2682     // Slow-path case
2683     region2->init_req(_slow_path, ctrl_proj);
2684     phi2->init_req(_slow_path, mem_proj);
2685 
2686     phase->register_control(region2, loop, reg2_ctrl);
2687     phase->register_new_node(phi2, region2);
2688 
2689     region->init_req(_heap_unstable, region2);
2690     phi->init_req(_heap_unstable, phi2);
2691 
2692     phase->register_control(region, loop, heap_stable_ctrl->in(0));
2693     phase->register_new_node(phi, region);
2694 
2695     fix_ctrl(barrier, region, fixer, uses, uses_to_ignore, last, phase);
2696     for(uint next = 0; next < uses.size(); next++ ) {
2697       Node *n = uses.at(next);
2698       assert(phase->get_ctrl(n) == init_ctrl, "bad control");
2699       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
2700       phase->set_ctrl(n, region);
2701       follow_barrier_uses(n, init_ctrl, uses, phase);
2702     }
2703     fixer.fix_mem(init_ctrl, region, init_raw_mem, raw_mem_for_ctrl, phi, uses);
2704 
2705     phase->igvn().replace_node(barrier, pre_val);
2706   }
2707 
2708   for (int i = ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count(); i > 0; i--) {
2709     int cnt = ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count();
2710     ShenandoahWriteBarrierNode* wb = ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barrier(i-1);
2711 
2712     uint last = phase->C->unique();
2713     Node* ctrl = phase->get_ctrl(wb);
2714     Node* orig_ctrl = ctrl;
2715 
2716     Node* raw_mem = fixer.find_mem(ctrl, wb);
2717     Node* init_raw_mem = raw_mem;
2718     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, NULL);
2719     int alias = phase->C->get_alias_index(wb->adr_type());
2720     Node* wb_mem =  wb->in(Memory);
2721     Node* init_wb_mem = wb_mem;
2722 
2723     Node* val = wb->in(ValueIn);
2724     Node* wbproj = wb->find_out_with(Op_ShenandoahWBMemProj);
2725     IdealLoopTree *loop = phase->get_loop(ctrl);
2726 
2727     assert(val->Opcode() != Op_ShenandoahWriteBarrier, "No chain of write barriers");
2728 
2729     CallStaticJavaNode* unc = wb->pin_and_expand_null_check(phase->igvn());
2730     Node* unc_ctrl = NULL;
2731     if (unc != NULL) {
2732       if (val->in(0) != ctrl) {
2733         unc = NULL;
2734       } else {
2735         unc_ctrl = val->in(0);
2736       }
2737     }
2738 
2739     Node* uncasted_val = val;
2740     if (unc != NULL) {
2741       uncasted_val = val->in(1);
2742     }
2743 
2744     Node* heap_stable_ctrl = NULL;
2745     Node* null_ctrl = NULL;
2746 
2747     assert(val->bottom_type()->make_oopptr(), "need oop");
2748     assert(val->bottom_type()->make_oopptr()->const_oop() == NULL, "expect non-constant");
2749 
2750     enum { _heap_stable = 1, _heap_unstable, PATH_LIMIT };
2751     Node* region = new RegionNode(PATH_LIMIT);
2752     Node* val_phi = new PhiNode(region, uncasted_val->bottom_type()->is_oopptr());
2753     Node* mem_phi = PhiNode::make(region, wb_mem, Type::MEMORY, phase->C->alias_type(wb->adr_type())->adr_type());
2754     Node* raw_mem_phi = PhiNode::make(region, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
2755 
2756     enum { _not_cset = 1, _not_equal, _evac_path, _null_path, PATH_LIMIT2 };
2757     Node* region2 = new RegionNode(PATH_LIMIT2);
2758     Node* val_phi2 = new PhiNode(region2, uncasted_val->bottom_type()->is_oopptr());
2759     Node* mem_phi2 = PhiNode::make(region2, wb_mem, Type::MEMORY, phase->C->alias_type(wb->adr_type())->adr_type());
2760     Node* raw_mem_phi2 = PhiNode::make(region2, raw_mem, Type::MEMORY, TypeRawPtr::BOTTOM);
2761 
2762       // Stable path.
2763     test_heap_stable(ctrl, raw_mem, heap_stable_ctrl, phase);
2764     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
2765 
2766     // Heap stable case
2767     region->init_req(_heap_stable, heap_stable_ctrl);
2768     val_phi->init_req(_heap_stable, uncasted_val);
2769     mem_phi->init_req(_heap_stable, wb_mem);
2770     raw_mem_phi->init_req(_heap_stable, raw_mem);
2771 
2772     Node* reg2_ctrl = NULL;
2773     // Null case
2774     test_null(ctrl, val, null_ctrl, phase);
2775     if (null_ctrl != NULL) {
2776       reg2_ctrl = null_ctrl->in(0);
2777       region2->init_req(_null_path, null_ctrl);
2778       val_phi2->init_req(_null_path, uncasted_val);
2779       mem_phi2->init_req(_null_path, wb_mem);
2780       raw_mem_phi2->init_req(_null_path, raw_mem);
2781     } else {
2782       region2->del_req(_null_path);
2783       val_phi2->del_req(_null_path);
2784       mem_phi2->del_req(_null_path);
2785       raw_mem_phi2->del_req(_null_path);
2786     }
2787 
2788     // Test for in-cset.
2789     // Wires !in_cset(obj) to slot 2 of region and phis
2790     Node* not_cset_ctrl = NULL;
2791     in_cset_fast_test(ctrl, not_cset_ctrl, uncasted_val, raw_mem, phase);
2792     if (not_cset_ctrl != NULL) {
2793       if (reg2_ctrl == NULL) reg2_ctrl = not_cset_ctrl->in(0);
2794       region2->init_req(_not_cset, not_cset_ctrl);
2795       val_phi2->init_req(_not_cset, uncasted_val);
2796       mem_phi2->init_req(_not_cset, wb_mem);
2797       raw_mem_phi2->init_req(_not_cset, raw_mem);
2798     }
2799 
2800     // Resolve object when orig-value is in cset.
2801     // Make the unconditional resolve for fwdptr, not the read barrier.
2802     Node* new_val = uncasted_val;
2803     if (unc_ctrl != NULL) {
2804       // Clone the null check in this branch to allow implicit null check
2805       new_val = clone_null_check(ctrl, val, unc_ctrl, phase);
2806       fix_null_check(unc, unc_ctrl, ctrl->in(0)->as_If()->proj_out(0), uses, phase);
2807 
2808       IfNode* iff = unc_ctrl->in(0)->as_If();
2809       phase->igvn().replace_input_of(iff, 1, phase->igvn().intcon(1));
2810     }
2811     Node* addr = new AddPNode(new_val, uncasted_val, phase->igvn().MakeConX(ShenandoahBrooksPointer::byte_offset()));
2812     phase->register_new_node(addr, ctrl);
2813     assert(val->bottom_type()->isa_oopptr(), "what else?");
2814     const TypePtr* obj_type =  val->bottom_type()->is_oopptr();
2815     const TypePtr* adr_type = ShenandoahBarrierNode::brooks_pointer_type(obj_type);
2816     Node* fwd = new LoadPNode(ctrl, wb_mem, addr, adr_type, obj_type, MemNode::unordered);
2817     phase->register_new_node(fwd, ctrl);
2818 
2819     // Only branch to WB stub if object is not forwarded; otherwise reply with fwd ptr
2820     Node* cmp = new CmpPNode(fwd, new_val);
2821     phase->register_new_node(cmp, ctrl);
2822     Node* bol = new BoolNode(cmp, BoolTest::eq);
2823     phase->register_new_node(bol, ctrl);
2824 
2825     IfNode* iff = new IfNode(ctrl, bol, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
2826     if (reg2_ctrl == NULL) reg2_ctrl = iff;
2827     phase->register_control(iff, loop, ctrl);
2828     Node* if_not_eq = new IfFalseNode(iff);
2829     phase->register_control(if_not_eq, loop, iff);
2830     Node* if_eq = new IfTrueNode(iff);
2831     phase->register_control(if_eq, loop, iff);
2832 
2833     // Wire up not-equal-path in slots 3.
2834     region2->init_req(_not_equal, if_not_eq);
2835     val_phi2->init_req(_not_equal, fwd);
2836     mem_phi2->init_req(_not_equal, wb_mem);
2837     raw_mem_phi2->init_req(_not_equal, raw_mem);
2838 
2839     // Call wb-stub and wire up that path in slots 4
2840     Node* result_mem = NULL;
2841     ctrl = if_eq;
2842     call_wb_stub(ctrl, new_val, result_mem,
2843                  raw_mem, wb_mem,
2844                  alias, phase);
2845     region2->init_req(_evac_path, ctrl);
2846     val_phi2->init_req(_evac_path, new_val);
2847     mem_phi2->init_req(_evac_path, result_mem);
2848     raw_mem_phi2->init_req(_evac_path, result_mem);
2849 
2850     phase->register_control(region2, loop, reg2_ctrl);
2851     phase->register_new_node(val_phi2, region2);
2852     phase->register_new_node(mem_phi2, region2);
2853     phase->register_new_node(raw_mem_phi2, region2);
2854 
2855     region->init_req(_heap_unstable, region2);
2856     val_phi->init_req(_heap_unstable, val_phi2);
2857     mem_phi->init_req(_heap_unstable, mem_phi2);
2858     raw_mem_phi->init_req(_heap_unstable, raw_mem_phi2);
2859 
2860     phase->register_control(region, loop, heap_stable_iff);
2861     Node* out_val = val_phi;
2862     phase->register_new_node(val_phi, region);
2863     phase->register_new_node(mem_phi, region);
2864     phase->register_new_node(raw_mem_phi, region);
2865 
2866     fix_ctrl(wb, region, fixer, uses, uses_to_ignore, last, phase);
2867 
2868     ctrl = orig_ctrl;
2869 
2870     phase->igvn().replace_input_of(wbproj, ShenandoahWBMemProjNode::WriteBarrier, phase->C->top());
2871     phase->igvn().replace_node(wbproj, mem_phi);
2872     if (unc != NULL) {
2873       for (DUIterator_Fast imax, i = val->fast_outs(imax); i < imax; i++) {
2874         Node* u = val->fast_out(i);
2875         Node* c = phase->ctrl_or_self(u);
2876         if (u != wb && (c != ctrl || is_dominator_same_ctrl(c, wb, u, phase))) {
2877           phase->igvn().rehash_node_delayed(u);
2878           int nb = u->replace_edge(val, out_val);
2879           --i, imax -= nb;
2880         }
2881       }
2882       if (val->outcnt() == 0) {
2883         phase->igvn()._worklist.push(val);
2884       }
2885     }
2886     phase->igvn().replace_node(wb, out_val);
2887 
2888     follow_barrier_uses(mem_phi, ctrl, uses, phase);
2889     follow_barrier_uses(out_val, ctrl, uses, phase);
2890 
2891     for(uint next = 0; next < uses.size(); next++ ) {
2892       Node *n = uses.at(next);
2893       assert(phase->get_ctrl(n) == ctrl, "bad control");
2894       assert(n != init_raw_mem, "should leave input raw mem above the barrier");
2895       phase->set_ctrl(n, region);
2896       follow_barrier_uses(n, ctrl, uses, phase);
2897     }
2898 
2899     // The slow path call produces memory: hook the raw memory phi
2900     // from the expanded write barrier with the rest of the graph
2901     // which may require adding memory phis at every post dominated
2902     // region and at enclosing loop heads. Use the memory state
2903     // collected in memory_nodes to fix the memory graph. Update that
2904     // memory state as we go.
2905     fixer.fix_mem(ctrl, region, init_raw_mem, raw_mem_for_ctrl, raw_mem_phi, uses);
2906     assert(ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count() == cnt - 1, "not replaced");
2907   }
2908 
2909   assert(ShenandoahBarrierSetC2::bsc2()->state()->shenandoah_barriers_count() == 0, "all write barrier nodes should have been replaced");
2910 }
2911 
2912 void ShenandoahWriteBarrierNode::move_heap_stable_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
2913   IdealLoopTree *loop = phase->get_loop(iff);
2914   Node* loop_head = loop->_head;
2915   Node* entry_c = loop_head->in(LoopNode::EntryControl);
2916 
2917   Node* bol = iff->in(1);
2918   Node* cmp = bol->in(1);
2919   Node* andi = cmp->in(1);
2920   Node* load = andi->in(1);
2921 
2922   assert(is_gc_state_load(load), "broken");
2923   if (!phase->is_dominator(load->in(0), entry_c)) {
2924     Node* mem_ctrl = NULL;
2925     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
2926     load = load->clone();
2927     load->set_req(MemNode::Memory, mem);
2928     load->set_req(0, entry_c);
2929     phase->register_new_node(load, entry_c);
2930     andi = andi->clone();
2931     andi->set_req(1, load);
2932     phase->register_new_node(andi, entry_c);
2933     cmp = cmp->clone();
2934     cmp->set_req(1, andi);
2935     phase->register_new_node(cmp, entry_c);
2936     bol = bol->clone();
2937     bol->set_req(1, cmp);
2938     phase->register_new_node(bol, entry_c);
2939 
2940     Node* old_bol =iff->in(1);
2941     phase->igvn().replace_input_of(iff, 1, bol);
2942   }
2943 }
2944 
2945 bool ShenandoahWriteBarrierNode::identical_backtoback_ifs(Node *n, PhaseIdealLoop* phase) {
2946   if (!n->is_If() || n->is_CountedLoopEnd()) {
2947     return false;
2948   }
2949   Node* region = n->in(0);
2950 
2951   if (!region->is_Region()) {
2952     return false;
2953   }
2954   Node* dom = phase->idom(region);
2955   if (!dom->is_If()) {
2956     return false;
2957   }
2958 
2959   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
2960     return false;
2961   }
2962 
2963   IfNode* dom_if = dom->as_If();
2964   Node* proj_true = dom_if->proj_out(1);
2965   Node* proj_false = dom_if->proj_out(0);
2966 
2967   for (uint i = 1; i < region->req(); i++) {
2968     if (phase->is_dominator(proj_true, region->in(i))) {
2969       continue;
2970     }
2971     if (phase->is_dominator(proj_false, region->in(i))) {
2972       continue;
2973     }
2974     return false;
2975   }
2976 
2977   return true;
2978 }
2979 
2980 void ShenandoahWriteBarrierNode::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
2981   assert(is_heap_stable_test(n), "no other tests");
2982   if (identical_backtoback_ifs(n, phase)) {
2983     Node* n_ctrl = n->in(0);
2984     if (phase->can_split_if(n_ctrl)) {
2985       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
2986       if (is_heap_stable_test(n)) {
2987         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
2988         assert(is_gc_state_load(gc_state_load), "broken");
2989         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
2990         assert(is_gc_state_load(dom_gc_state_load), "broken");
2991         if (gc_state_load != dom_gc_state_load) {
2992           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
2993         }
2994       }
2995       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
2996       Node* proj_true = dom_if->proj_out(1);
2997       Node* proj_false = dom_if->proj_out(0);
2998       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
2999       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
3000 
3001       for (uint i = 1; i < n_ctrl->req(); i++) {
3002         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
3003           bolphi->init_req(i, con_true);
3004         } else {
3005           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
3006           bolphi->init_req(i, con_false);
3007         }
3008       }
3009       phase->register_new_node(bolphi, n_ctrl);
3010       phase->igvn().replace_input_of(n, 1, bolphi);
3011       phase->do_split_if(n);
3012     }
3013   }
3014 }
3015 
3016 IfNode* ShenandoahWriteBarrierNode::find_unswitching_candidate(const IdealLoopTree *loop, PhaseIdealLoop* phase) {
3017   // Find first invariant test that doesn't exit the loop
3018   LoopNode *head = loop->_head->as_Loop();
3019   IfNode* unswitch_iff = NULL;
3020   Node* n = head->in(LoopNode::LoopBackControl);
3021   int loop_has_sfpts = -1;
3022   while (n != head) {
3023     Node* n_dom = phase->idom(n);
3024     if (n->is_Region()) {
3025       if (n_dom->is_If()) {
3026         IfNode* iff = n_dom->as_If();
3027         if (iff->in(1)->is_Bool()) {
3028           BoolNode* bol = iff->in(1)->as_Bool();
3029           if (bol->in(1)->is_Cmp()) {
3030             // If condition is invariant and not a loop exit,
3031             // then found reason to unswitch.
3032             if (is_heap_stable_test(iff) &&
3033                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
3034               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
3035               if (loop_has_sfpts == -1) {
3036                 for(uint i = 0; i < loop->_body.size(); i++) {
3037                   Node *m = loop->_body[i];
3038                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
3039                     loop_has_sfpts = 1;
3040                     break;
3041                   }
3042                 }
3043                 if (loop_has_sfpts == -1) {
3044                   loop_has_sfpts = 0;
3045                 }
3046               }
3047               if (!loop_has_sfpts) {
3048                 unswitch_iff = iff;
3049               }
3050             }
3051           }
3052         }
3053       }
3054     }
3055     n = n_dom;
3056   }
3057   return unswitch_iff;
3058 }
3059 
3060 
3061 void ShenandoahWriteBarrierNode::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
3062   Node_List heap_stable_tests;
3063   Node_List gc_state_loads;
3064 
3065   stack.push(phase->C->start(), 0);
3066   do {
3067     Node* n = stack.node();
3068     uint i = stack.index();
3069 
3070     if (i < n->outcnt()) {
3071       Node* u = n->raw_out(i);
3072       stack.set_index(i+1);
3073       if (!visited.test_set(u->_idx)) {
3074         stack.push(u, 0);
3075       }
3076     } else {
3077       stack.pop();
3078       if (ShenandoahCommonGCStateLoads && is_gc_state_load(n)) {
3079         gc_state_loads.push(n);
3080       }
3081       if (n->is_If() && is_heap_stable_test(n)) {
3082         heap_stable_tests.push(n);
3083       }
3084     }
3085   } while (stack.size() > 0);
3086 
3087   bool progress;
3088   do {
3089     progress = false;
3090     for (uint i = 0; i < gc_state_loads.size(); i++) {
3091       Node* n = gc_state_loads.at(i);
3092       if (n->outcnt() != 0) {
3093         progress |= try_common_gc_state_load(n, phase);
3094       }
3095     }
3096   } while (progress);
3097 
3098   for (uint i = 0; i < heap_stable_tests.size(); i++) {
3099     Node* n = heap_stable_tests.at(i);
3100     assert(is_heap_stable_test(n), "only evacuation test");
3101     merge_back_to_back_tests(n, phase);
3102   }
3103 
3104   if (!phase->C->major_progress()) {
3105     VectorSet seen(Thread::current()->resource_area());
3106     for (uint i = 0; i < heap_stable_tests.size(); i++) {
3107       Node* n = heap_stable_tests.at(i);
3108       IdealLoopTree* loop = phase->get_loop(n);
3109       if (loop != phase->ltree_root() &&
3110           loop->_child == NULL &&
3111           !loop->_irreducible) {
3112         LoopNode* head = loop->_head->as_Loop();
3113         if ((!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
3114             !seen.test_set(head->_idx)) {
3115           IfNode* iff = find_unswitching_candidate(loop, phase);
3116           if (iff != NULL) {
3117             Node* bol = iff->in(1);
3118             if (head->is_strip_mined()) {
3119               head->verify_strip_mined(0);
3120             }
3121             move_heap_stable_test_out_of_loop(iff, phase);
3122             if (loop->policy_unswitching(phase)) {
3123               if (head->is_strip_mined()) {
3124                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
3125                 OuterStripMinedLoopEndNode* le = head->outer_loop_end();
3126                 Node* new_outer = new LoopNode(outer->in(LoopNode::EntryControl), outer->in(LoopNode::LoopBackControl));
3127                 phase->register_control(new_outer, phase->get_loop(outer), outer->in(LoopNode::EntryControl));
3128                 Node* new_le = new IfNode(le->in(0), le->in(1), le->_prob, le->_fcnt);
3129                 phase->register_control(new_le, phase->get_loop(le), le->in(0));
3130                 phase->lazy_replace(outer, new_outer);
3131                 phase->lazy_replace(le, new_le);
3132                 head->clear_strip_mined();
3133               }
3134               phase->do_unswitching(loop, old_new);
3135             } else {
3136               // Not proceeding with unswitching. Move load back in
3137               // the loop.
3138               phase->igvn().replace_input_of(iff, 1, bol);
3139             }
3140           }
3141         }
3142       }
3143     }
3144   }
3145 }
3146 
3147 #ifdef ASSERT
3148 void ShenandoahBarrierNode::verify_raw_mem(RootNode* root) {
3149   const bool trace = false;
3150   ResourceMark rm;
3151   Unique_Node_List nodes;
3152   Unique_Node_List controls;
3153   Unique_Node_List memories;
3154 
3155   nodes.push(root);
3156   for (uint next = 0; next < nodes.size(); next++) {
3157     Node *n  = nodes.at(next);
3158     if (ShenandoahBarrierSetC2::is_shenandoah_wb_call(n)) {
3159       controls.push(n);
3160       if (trace) { tty->print("XXXXXX verifying"); n->dump(); }
3161       for (uint next2 = 0; next2 < controls.size(); next2++) {
3162         Node *m = controls.at(next2);
3163         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3164           Node* u = m->fast_out(i);
3165           if (u->is_CFG() && !u->is_Root() &&
3166               !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1) &&
3167               !(u->is_Region() && u->unique_ctrl_out()->Opcode() == Op_Halt)) {
3168             if (trace) { tty->print("XXXXXX pushing control"); u->dump(); }
3169             controls.push(u);
3170           }
3171         }
3172       }
3173       memories.push(n->as_Call()->proj_out(TypeFunc::Memory));
3174       for (uint next2 = 0; next2 < memories.size(); next2++) {
3175         Node *m = memories.at(next2);
3176         assert(m->bottom_type() == Type::MEMORY, "");
3177         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3178           Node* u = m->fast_out(i);
3179           if (u->bottom_type() == Type::MEMORY && (u->is_Mem() || u->is_ClearArray())) {
3180             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
3181             memories.push(u);
3182           } else if (u->is_LoadStore()) {
3183             if (trace) { tty->print("XXXXXX pushing memory"); u->find_out_with(Op_SCMemProj)->dump(); }
3184             memories.push(u->find_out_with(Op_SCMemProj));
3185           } else if (u->is_MergeMem() && u->as_MergeMem()->memory_at(Compile::AliasIdxRaw) == m) {
3186             if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
3187             memories.push(u);
3188           } else if (u->is_Phi()) {
3189             assert(u->bottom_type() == Type::MEMORY, "");
3190             if (u->adr_type() == TypeRawPtr::BOTTOM || u->adr_type() == TypePtr::BOTTOM) {
3191               assert(controls.member(u->in(0)), "");
3192               if (trace) { tty->print("XXXXXX pushing memory"); u->dump(); }
3193               memories.push(u);
3194             }
3195           } else if (u->is_SafePoint() || u->is_MemBar()) {
3196             for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
3197               Node* uu = u->fast_out(j);
3198               if (uu->bottom_type() == Type::MEMORY) {
3199                 if (trace) { tty->print("XXXXXX pushing memory"); uu->dump(); }
3200                 memories.push(uu);
3201               }
3202             }
3203           }
3204         }
3205       }
3206       for (uint next2 = 0; next2 < controls.size(); next2++) {
3207         Node *m = controls.at(next2);
3208         if (m->is_Region()) {
3209           bool all_in = true;
3210           for (uint i = 1; i < m->req(); i++) {
3211             if (!controls.member(m->in(i))) {
3212               all_in = false;
3213               break;
3214             }
3215           }
3216           if (trace) { tty->print("XXX verifying %s", all_in ? "all in" : ""); m->dump(); }
3217           bool found_phi = false;
3218           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax && !found_phi; j++) {
3219             Node* u = m->fast_out(j);
3220             if (u->is_Phi() && memories.member(u)) {
3221               found_phi = true;
3222               for (uint i = 1; i < u->req() && found_phi; i++) {
3223                 Node* k = u->in(i);
3224                 if (memories.member(k) != controls.member(m->in(i))) {
3225                   found_phi = false;
3226                 }
3227               }
3228             }
3229           }
3230           assert(found_phi || all_in, "");
3231         }
3232       }
3233       controls.clear();
3234       memories.clear();
3235     }
3236     for( uint i = 0; i < n->len(); ++i ) {
3237       Node *m = n->in(i);
3238       if (m != NULL) {
3239         nodes.push(m);
3240       }
3241     }
3242   }
3243 }
3244 #endif
3245 
3246 const Type* ShenandoahEnqueueBarrierNode::bottom_type() const {
3247   if (in(1) == NULL || in(1)->is_top()) {
3248     return Type::TOP;
3249   }
3250   const Type* t = in(1)->bottom_type();
3251   if (t == TypePtr::NULL_PTR) {
3252     return t;
3253   }
3254   return t->is_oopptr()->cast_to_nonconst();
3255 }
3256 
3257 const Type* ShenandoahEnqueueBarrierNode::Value(PhaseGVN* phase) const {
3258   if (in(1) == NULL) {
3259     return Type::TOP;
3260   }
3261   const Type* t = phase->type(in(1));
3262   if (t == Type::TOP) {
3263     return Type::TOP;
3264   }
3265   if (t == TypePtr::NULL_PTR) {
3266     return t;
3267   }
3268   return t->is_oopptr()->cast_to_nonconst();
3269 }
3270 
3271 int ShenandoahEnqueueBarrierNode::needed(Node* n) {
3272   if (n == NULL ||
3273       n->is_Allocate() ||
3274       n->bottom_type() == TypePtr::NULL_PTR ||
3275       (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL)) {
3276     return NotNeeded;
3277   }
3278   if (n->is_Phi() ||
3279       n->is_CMove()) {
3280     return MaybeNeeded;
3281   }
3282   return Needed;
3283 }
3284 
3285 Node* ShenandoahEnqueueBarrierNode::next(Node* n) {
3286   for (;;) {
3287     if (n == NULL) {
3288       return n;
3289     } else if (n->bottom_type() == TypePtr::NULL_PTR) {
3290       return n;
3291     } else if (n->bottom_type()->make_oopptr() != NULL && n->bottom_type()->make_oopptr()->const_oop() != NULL) {
3292       return n;
3293     } else if (n->is_ConstraintCast() ||
3294                n->Opcode() == Op_DecodeN ||
3295                n->Opcode() == Op_EncodeP) {
3296       n = n->in(1);
3297     } else if (n->is_Proj()) {
3298       n = n->in(0);
3299     } else {
3300       return n;
3301     }
3302   }
3303   ShouldNotReachHere();
3304   return NULL;
3305 }
3306 
3307 Node* ShenandoahEnqueueBarrierNode::Identity(PhaseGVN* phase) {
3308   PhaseIterGVN* igvn = phase->is_IterGVN();
3309 
3310   Node* n = next(in(1));
3311 
3312   int cont = needed(n);
3313 
3314   if (cont == NotNeeded) {
3315     return in(1);
3316   } else if (cont == MaybeNeeded) {
3317     if (igvn == NULL) {
3318       phase->record_for_igvn(this);
3319       return this;
3320     } else {
3321       ResourceMark rm;
3322       Unique_Node_List wq;
3323       uint wq_i = 0;
3324 
3325       for (;;) {
3326         if (n->is_Phi()) {
3327           for (uint i = 1; i < n->req(); i++) {
3328             Node* m = n->in(i);
3329             if (m != NULL) {
3330               wq.push(m);
3331             }
3332           }
3333         } else {
3334           assert(n->is_CMove(), "nothing else here");
3335           Node* m = n->in(CMoveNode::IfFalse);
3336           wq.push(m);
3337           m = n->in(CMoveNode::IfTrue);
3338           wq.push(m);
3339         }
3340         Node* orig_n = NULL;
3341         do {
3342           if (wq_i >= wq.size()) {
3343             return in(1);
3344           }
3345           n = wq.at(wq_i);
3346           wq_i++;
3347           orig_n = n;
3348           n = next(n);
3349           cont = needed(n);
3350           if (cont == Needed) {
3351             return this;
3352           }
3353         } while (cont != MaybeNeeded || (orig_n != n && wq.member(n)));
3354       }
3355     }
3356   }
3357 
3358   return this;
3359 }
3360 
3361 #ifdef ASSERT
3362 static bool has_never_branch(Node* root) {
3363   for (uint i = 1; i < root->req(); i++) {
3364     Node* in = root->in(i);
3365     if (in != NULL && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->Opcode() == Op_NeverBranch) {
3366       return true;
3367     }
3368   }
3369   return false;
3370 }
3371 #endif
3372 
3373 void MemoryGraphFixer::collect_memory_nodes() {
3374   Node_Stack stack(0);
3375   VectorSet visited(Thread::current()->resource_area());
3376   Node_List regions;
3377 
3378   // Walk the raw memory graph and create a mapping from CFG node to
3379   // memory node. Exclude phis for now.
3380   stack.push(_phase->C->root(), 1);
3381   do {
3382     Node* n = stack.node();
3383     int opc = n->Opcode();
3384     uint i = stack.index();
3385     if (i < n->req()) {
3386       Node* mem = NULL;
3387       if (opc == Op_Root) {
3388         Node* in = n->in(i);
3389         int in_opc = in->Opcode();
3390         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
3391           mem = in->in(TypeFunc::Memory);
3392         } else if (in_opc == Op_Halt) {
3393           if (!in->in(0)->is_Region()) {
3394             Node* proj = in->in(0);
3395             assert(proj->is_Proj(), "");
3396             Node* in = proj->in(0);
3397             assert(in->is_CallStaticJava() || in->Opcode() == Op_NeverBranch || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
3398             if (in->is_CallStaticJava()) {
3399               mem = in->in(TypeFunc::Memory);
3400             } else if (in->Opcode() == Op_Catch) {
3401               Node* call = in->in(0)->in(0);
3402               assert(call->is_Call(), "");
3403               mem = call->in(TypeFunc::Memory);
3404             }
3405           }
3406         } else {
3407 #ifdef ASSERT
3408           n->dump();
3409           in->dump();
3410 #endif
3411           ShouldNotReachHere();
3412         }
3413       } else {
3414         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
3415         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
3416         mem = n->in(i);
3417       }
3418       i++;
3419       stack.set_index(i);
3420       if (mem == NULL) {
3421         continue;
3422       }
3423       for (;;) {
3424         if (visited.test_set(mem->_idx) || mem->is_Start()) {
3425           break;
3426         }
3427         if (mem->is_Phi()) {
3428           stack.push(mem, 2);
3429           mem = mem->in(1);
3430         } else if (mem->is_Proj()) {
3431           stack.push(mem, mem->req());
3432           mem = mem->in(0);
3433         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
3434           mem = mem->in(TypeFunc::Memory);
3435         } else if (mem->is_MergeMem()) {
3436           MergeMemNode* mm = mem->as_MergeMem();
3437           mem = mm->memory_at(_alias);
3438         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
3439           assert(_alias == Compile::AliasIdxRaw, "");
3440           stack.push(mem, mem->req());
3441           mem = mem->in(MemNode::Memory);
3442         } else if (mem->Opcode() == Op_ShenandoahWriteBarrier) {
3443           assert(_alias != Compile::AliasIdxRaw, "");
3444           mem = mem->in(ShenandoahBarrierNode::Memory);
3445         } else if (mem->Opcode() == Op_ShenandoahWBMemProj) {
3446           stack.push(mem, mem->req());
3447           mem = mem->in(ShenandoahWBMemProjNode::WriteBarrier);
3448         } else {
3449 #ifdef ASSERT
3450           mem->dump();
3451 #endif
3452           ShouldNotReachHere();
3453         }
3454       }
3455     } else {
3456       if (n->is_Phi()) {
3457         // Nothing
3458       } else if (!n->is_Root()) {
3459         Node* c = get_ctrl(n);
3460         _memory_nodes.map(c->_idx, n);
3461       }
3462       stack.pop();
3463     }
3464   } while(stack.is_nonempty());
3465 
3466   // Iterate over CFG nodes in rpo and propagate memory state to
3467   // compute memory state at regions, creating new phis if needed.
3468   Node_List rpo_list;
3469   visited.Clear();
3470   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
3471   Node* root = rpo_list.pop();
3472   assert(root == _phase->C->root(), "");
3473 
3474   const bool trace = false;
3475 #ifdef ASSERT
3476   if (trace) {
3477     for (int i = rpo_list.size() - 1; i >= 0; i--) {
3478       Node* c = rpo_list.at(i);
3479       if (_memory_nodes[c->_idx] != NULL) {
3480         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
3481       }
3482     }
3483   }
3484 #endif
3485   uint last = _phase->C->unique();
3486 
3487 #ifdef ASSERT
3488   uint8_t max_depth = 0;
3489   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
3490     IdealLoopTree* lpt = iter.current();
3491     max_depth = MAX2(max_depth, lpt->_nest);
3492   }
3493 #endif
3494 
3495   bool progress = true;
3496   int iteration = 0;
3497   Node_List dead_phis;
3498   while (progress) {
3499     progress = false;
3500     iteration++;
3501     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop(), "");
3502     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
3503     IdealLoopTree* last_updated_ilt = NULL;
3504     for (int i = rpo_list.size() - 1; i >= 0; i--) {
3505       Node* c = rpo_list.at(i);
3506 
3507       Node* prev_mem = _memory_nodes[c->_idx];
3508       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
3509         Node* prev_region = regions[c->_idx];
3510         Node* unique = NULL;
3511         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
3512           Node* m = _memory_nodes[c->in(j)->_idx];
3513           assert(m != NULL || (c->is_Loop() && j == LoopNode::LoopBackControl && iteration == 1) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "expect memory state");
3514           if (m != NULL) {
3515             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
3516               assert(c->is_Loop() && j == LoopNode::LoopBackControl || _phase->C->has_irreducible_loop(), "");
3517               // continue
3518             } else if (unique == NULL) {
3519               unique = m;
3520             } else if (m == unique) {
3521               // continue
3522             } else {
3523               unique = NodeSentinel;
3524             }
3525           }
3526         }
3527         assert(unique != NULL, "empty phi???");
3528         if (unique != NodeSentinel) {
3529           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c) {
3530             dead_phis.push(prev_region);
3531           }
3532           regions.map(c->_idx, unique);
3533         } else {
3534           Node* phi = NULL;
3535           if (prev_region != NULL && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
3536             phi = prev_region;
3537             for (uint k = 1; k < c->req(); k++) {
3538               Node* m = _memory_nodes[c->in(k)->_idx];
3539               assert(m != NULL, "expect memory state");
3540               phi->set_req(k, m);
3541             }
3542           } else {
3543             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == NULL; j++) {
3544               Node* u = c->fast_out(j);
3545               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
3546                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
3547                 phi = u;
3548                 for (uint k = 1; k < c->req() && phi != NULL; k++) {
3549                   Node* m = _memory_nodes[c->in(k)->_idx];
3550                   assert(m != NULL, "expect memory state");
3551                   if (u->in(k) != m) {
3552                     phi = NULL;
3553                   }
3554                 }
3555               }
3556             }
3557             if (phi == NULL) {
3558               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
3559               for (uint k = 1; k < c->req(); k++) {
3560                 Node* m = _memory_nodes[c->in(k)->_idx];
3561                 assert(m != NULL, "expect memory state");
3562                 phi->init_req(k, m);
3563               }
3564             }
3565           }
3566           assert(phi != NULL, "");
3567           regions.map(c->_idx, phi);
3568         }
3569         Node* current_region = regions[c->_idx];
3570         if (current_region != prev_region) {
3571           progress = true;
3572           if (prev_region == prev_mem) {
3573             _memory_nodes.map(c->_idx, current_region);
3574           }
3575         }
3576       } else if (prev_mem == NULL || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
3577         Node* m = _memory_nodes[_phase->idom(c)->_idx];
3578         assert(m != NULL, "expect memory state");
3579         if (m != prev_mem) {
3580           _memory_nodes.map(c->_idx, m);
3581           progress = true;
3582         }
3583       }
3584 #ifdef ASSERT
3585       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
3586 #endif
3587     }
3588   }
3589 
3590   // Replace existing phi with computed memory state for that region
3591   // if different (could be a new phi or a dominating memory node if
3592   // that phi was found to be useless).
3593   while (dead_phis.size() > 0) {
3594     Node* n = dead_phis.pop();
3595     n->replace_by(_phase->C->top());
3596     n->destruct();
3597   }
3598   for (int i = rpo_list.size() - 1; i >= 0; i--) {
3599     Node* c = rpo_list.at(i);
3600     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
3601       Node* n = regions[c->_idx];
3602       if (n->is_Phi() && n->_idx >= last && n->in(0) == c) {
3603         _phase->register_new_node(n, c);
3604       }
3605     }
3606   }
3607   for (int i = rpo_list.size() - 1; i >= 0; i--) {
3608     Node* c = rpo_list.at(i);
3609     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
3610       Node* n = regions[c->_idx];
3611       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
3612         Node* u = c->fast_out(i);
3613         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
3614             u != n) {
3615           if (u->adr_type() == TypePtr::BOTTOM) {
3616             fix_memory_uses(u, n, n, c);
3617           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
3618             _phase->lazy_replace(u, n);
3619             --i; --imax;
3620           }
3621         }
3622       }
3623     }
3624   }
3625 }
3626 
3627 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
3628   Node* c = _phase->get_ctrl(n);
3629   if (n->is_Proj() && n->in(0) != NULL && n->in(0)->is_Call()) {
3630     assert(c == n->in(0), "");
3631     CallNode* call = c->as_Call();
3632     CallProjections projs;
3633     call->extract_projections(&projs, true, false);
3634     if (projs.catchall_memproj != NULL) {
3635       if (projs.fallthrough_memproj == n) {
3636         c = projs.fallthrough_catchproj;
3637       } else {
3638         assert(projs.catchall_memproj == n, "");
3639         c = projs.catchall_catchproj;
3640       }
3641     }
3642   }
3643   return c;
3644 }
3645 
3646 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
3647   if (_phase->has_ctrl(n))
3648     return get_ctrl(n);
3649   else {
3650     assert (n->is_CFG(), "must be a CFG node");
3651     return n;
3652   }
3653 }
3654 
3655 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
3656   return m != NULL && get_ctrl(m) == c;
3657 }
3658 
3659 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
3660   assert(n == NULL || _phase->ctrl_or_self(n) == ctrl, "");
3661   Node* mem = _memory_nodes[ctrl->_idx];
3662   Node* c = ctrl;
3663   while (!mem_is_valid(mem, c) &&
3664          (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
3665     c = _phase->idom(c);
3666     mem = _memory_nodes[c->_idx];
3667   }
3668   if (n != NULL && mem_is_valid(mem, c)) {
3669     while (!ShenandoahWriteBarrierNode::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
3670       mem = next_mem(mem, _alias);
3671     }
3672     if (mem->is_MergeMem()) {
3673       mem = mem->as_MergeMem()->memory_at(_alias);
3674     }
3675     if (!mem_is_valid(mem, c)) {
3676       do {
3677         c = _phase->idom(c);
3678         mem = _memory_nodes[c->_idx];
3679       } while (!mem_is_valid(mem, c) &&
3680                (!c->is_CatchProj() || mem == NULL || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
3681     }
3682   }
3683   assert(mem->bottom_type() == Type::MEMORY, "");
3684   return mem;
3685 }
3686 
3687 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
3688   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
3689     Node* use = region->fast_out(i);
3690     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
3691         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
3692       return true;
3693     }
3694   }
3695   return false;
3696 }
3697 
3698 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
3699   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
3700   const bool trace = false;
3701   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
3702   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
3703   GrowableArray<Node*> phis;
3704   if (mem_for_ctrl != mem) {
3705     Node* old = mem_for_ctrl;
3706     Node* prev = NULL;
3707     while (old != mem) {
3708       prev = old;
3709       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
3710         assert(_alias == Compile::AliasIdxRaw, "");
3711         old = old->in(MemNode::Memory);
3712       } else if (old->Opcode() == Op_SCMemProj) {
3713         assert(_alias == Compile::AliasIdxRaw, "");
3714         old = old->in(0);
3715       } else if (old->Opcode() == Op_ShenandoahWBMemProj) {
3716         assert(_alias != Compile::AliasIdxRaw, "");
3717         old = old->in(ShenandoahWBMemProjNode::WriteBarrier);
3718       } else if (old->Opcode() == Op_ShenandoahWriteBarrier) {
3719         assert(_alias != Compile::AliasIdxRaw, "");
3720         old = old->in(ShenandoahBarrierNode::Memory);
3721       } else {
3722         ShouldNotReachHere();
3723       }
3724     }
3725     assert(prev != NULL, "");
3726     if (new_ctrl != ctrl) {
3727       _memory_nodes.map(ctrl->_idx, mem);
3728       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
3729     }
3730     uint input = prev->Opcode() == Op_ShenandoahWriteBarrier ? (uint)ShenandoahBarrierNode::Memory : (uint)MemNode::Memory;
3731     _phase->igvn().replace_input_of(prev, input, new_mem);
3732   } else {
3733     uses.clear();
3734     _memory_nodes.map(new_ctrl->_idx, new_mem);
3735     uses.push(new_ctrl);
3736     for(uint next = 0; next < uses.size(); next++ ) {
3737       Node *n = uses.at(next);
3738       assert(n->is_CFG(), "");
3739       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
3740       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3741         Node* u = n->fast_out(i);
3742         if (!u->is_Root() && u->is_CFG() && u != n) {
3743           Node* m = _memory_nodes[u->_idx];
3744           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
3745               !has_mem_phi(u) &&
3746               u->unique_ctrl_out()->Opcode() != Op_Halt) {
3747             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
3748             DEBUG_ONLY(if (trace && m != NULL) { tty->print("ZZZ mem"); m->dump(); });
3749 
3750             if (!mem_is_valid(m, u) || !m->is_Phi()) {
3751               bool push = true;
3752               bool create_phi = true;
3753               if (_phase->is_dominator(new_ctrl, u)) {
3754                 create_phi = false;
3755               } else if (!_phase->C->has_irreducible_loop()) {
3756                 IdealLoopTree* loop = _phase->get_loop(ctrl);
3757                 bool do_check = true;
3758                 IdealLoopTree* l = loop;
3759                 create_phi = false;
3760                 while (l != _phase->ltree_root()) {
3761                   if (_phase->is_dominator(l->_head, u) && _phase->is_dominator(_phase->idom(u), l->_head)) {
3762                     create_phi = true;
3763                     do_check = false;
3764                     break;
3765                   }
3766                   l = l->_parent;
3767                 }
3768 
3769                 if (do_check) {
3770                   assert(!create_phi, "");
3771                   IdealLoopTree* u_loop = _phase->get_loop(u);
3772                   if (u_loop != _phase->ltree_root() && u_loop->is_member(loop)) {
3773                     Node* c = ctrl;
3774                     while (!_phase->is_dominator(c, u_loop->tail())) {
3775                       c = _phase->idom(c);
3776                     }
3777                     if (!_phase->is_dominator(c, u)) {
3778                       do_check = false;
3779                     }
3780                   }
3781                 }
3782 
3783                 if (do_check && _phase->is_dominator(_phase->idom(u), new_ctrl)) {
3784                   create_phi = true;
3785                 }
3786               }
3787               if (create_phi) {
3788                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
3789                 _phase->register_new_node(phi, u);
3790                 phis.push(phi);
3791                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
3792                 if (!mem_is_valid(m, u)) {
3793                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
3794                   _memory_nodes.map(u->_idx, phi);
3795                 } else {
3796                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
3797                   for (;;) {
3798                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj() || m->Opcode() == Op_ShenandoahWriteBarrier || m->Opcode() == Op_ShenandoahWBMemProj, "");
3799                     Node* next = NULL;
3800                     if (m->is_Proj()) {
3801                       next = m->in(0);
3802                     } else if (m->Opcode() == Op_ShenandoahWBMemProj) {
3803                       next = m->in(ShenandoahWBMemProjNode::WriteBarrier);
3804                     } else if (m->is_Mem() || m->is_LoadStore()) {
3805                       assert(_alias == Compile::AliasIdxRaw, "");
3806                       next = m->in(MemNode::Memory);
3807                     } else {
3808                       assert(_alias != Compile::AliasIdxRaw, "");
3809                       assert (m->Opcode() == Op_ShenandoahWriteBarrier, "");
3810                       next = m->in(ShenandoahBarrierNode::Memory);
3811                     }
3812                     if (_phase->get_ctrl(next) != u) {
3813                       break;
3814                     }
3815                     if (next->is_MergeMem()) {
3816                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
3817                       break;
3818                     }
3819                     if (next->is_Phi()) {
3820                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
3821                       break;
3822                     }
3823                     m = next;
3824                   }
3825 
3826                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
3827                   assert(m->is_Mem() || m->is_LoadStore() || m->Opcode() == Op_ShenandoahWriteBarrier, "");
3828                   uint input = (m->is_Mem() || m->is_LoadStore()) ? (uint)MemNode::Memory : (uint)ShenandoahBarrierNode::Memory;
3829                   _phase->igvn().replace_input_of(m, input, phi);
3830                   push = false;
3831                 }
3832               } else {
3833                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
3834               }
3835               if (push) {
3836                 uses.push(u);
3837               }
3838             }
3839           } else if (!mem_is_valid(m, u) &&
3840                      !(u->Opcode() == Op_CProj && u->in(0)->Opcode() == Op_NeverBranch && u->as_Proj()->_con == 1)) {
3841             uses.push(u);
3842           }
3843         }
3844       }
3845     }
3846     for (int i = 0; i < phis.length(); i++) {
3847       Node* n = phis.at(i);
3848       Node* r = n->in(0);
3849       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
3850       for (uint j = 1; j < n->req(); j++) {
3851         Node* m = find_mem(r->in(j), NULL);
3852         _phase->igvn().replace_input_of(n, j, m);
3853         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
3854       }
3855     }
3856   }
3857   uint last = _phase->C->unique();
3858   MergeMemNode* mm = NULL;
3859   int alias = _alias;
3860   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
3861   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
3862     Node* u = mem->out(i);
3863     if (u->_idx < last) {
3864       if (u->is_Mem()) {
3865         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
3866           Node* m = find_mem(_phase->get_ctrl(u), u);
3867           if (m != mem) {
3868             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
3869             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
3870             --i;
3871           }
3872         }
3873       } else if (u->is_MergeMem()) {
3874         MergeMemNode* u_mm = u->as_MergeMem();
3875         if (u_mm->memory_at(alias) == mem) {
3876           MergeMemNode* newmm = NULL;
3877           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
3878             Node* uu = u->fast_out(j);
3879             assert(!uu->is_MergeMem(), "chain of MergeMems?");
3880             if (uu->is_Phi()) {
3881               assert(uu->adr_type() == TypePtr::BOTTOM, "");
3882               Node* region = uu->in(0);
3883               int nb = 0;
3884               for (uint k = 1; k < uu->req(); k++) {
3885                 if (uu->in(k) == u) {
3886                   Node* m = find_mem(region->in(k), NULL);
3887                   if (m != mem) {
3888                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
3889                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
3890                     if (newmm != u) {
3891                       _phase->igvn().replace_input_of(uu, k, newmm);
3892                       nb++;
3893                       --jmax;
3894                     }
3895                   }
3896                 }
3897               }
3898               if (nb > 0) {
3899                 --j;
3900               }
3901             } else {
3902               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
3903               if (m != mem) {
3904                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
3905                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
3906                 if (newmm != u) {
3907                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
3908                   --j, --jmax;
3909                 }
3910               }
3911             }
3912           }
3913         }
3914       } else if (u->is_Phi()) {
3915         assert(u->bottom_type() == Type::MEMORY, "what else?");
3916         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
3917           Node* region = u->in(0);
3918           bool replaced = false;
3919           for (uint j = 1; j < u->req(); j++) {
3920             if (u->in(j) == mem) {
3921               Node* m = find_mem(region->in(j), NULL);
3922               Node* nnew = m;
3923               if (m != mem) {
3924                 if (u->adr_type() == TypePtr::BOTTOM) {
3925                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
3926                   nnew = mm;
3927                 }
3928                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
3929                 _phase->igvn().replace_input_of(u, j, nnew);
3930                 replaced = true;
3931               }
3932             }
3933           }
3934           if (replaced) {
3935             --i;
3936           }
3937         }
3938       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
3939                  u->adr_type() == NULL) {
3940         assert(u->adr_type() != NULL ||
3941                u->Opcode() == Op_Rethrow ||
3942                u->Opcode() == Op_Return ||
3943                u->Opcode() == Op_SafePoint ||
3944                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
3945                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
3946                u->Opcode() == Op_CallLeaf, "");
3947         Node* m = find_mem(_phase->ctrl_or_self(u), u);
3948         if (m != mem) {
3949           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
3950           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
3951           --i;
3952         }
3953       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
3954         Node* m = find_mem(_phase->ctrl_or_self(u), u);
3955         if (m != mem) {
3956           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
3957           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
3958           --i;
3959         }
3960       } else if (u->adr_type() != TypePtr::BOTTOM &&
3961                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
3962         Node* m = find_mem(_phase->ctrl_or_self(u), u);
3963         assert(m != mem, "");
3964         // u is on the wrong slice...
3965         assert(u->is_ClearArray(), "");
3966         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
3967         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
3968         --i;
3969       }
3970     }
3971   }
3972 #ifdef ASSERT
3973   assert(new_mem->outcnt() > 0, "");
3974   for (int i = 0; i < phis.length(); i++) {
3975     Node* n = phis.at(i);
3976     assert(n->outcnt() > 0, "new phi must have uses now");
3977   }
3978 #endif
3979 }
3980 
3981 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
3982   MergeMemNode* mm = MergeMemNode::make(mem);
3983   mm->set_memory_at(_alias, rep_proj);
3984   _phase->register_new_node(mm, rep_ctrl);
3985   return mm;
3986 }
3987 
3988 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
3989   MergeMemNode* newmm = NULL;
3990   MergeMemNode* u_mm = u->as_MergeMem();
3991   Node* c = _phase->get_ctrl(u);
3992   if (_phase->is_dominator(c, rep_ctrl)) {
3993     c = rep_ctrl;
3994   } else {
3995     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
3996   }
3997   if (u->outcnt() == 1) {
3998     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
3999       _phase->igvn().replace_input_of(u, _alias, rep_proj);
4000       --i;
4001     } else {
4002       _phase->igvn().rehash_node_delayed(u);
4003       u_mm->set_memory_at(_alias, rep_proj);
4004     }
4005     newmm = u_mm;
4006     _phase->set_ctrl_and_loop(u, c);
4007   } else {
4008     // can't simply clone u and then change one of its input because
4009     // it adds and then removes an edge which messes with the
4010     // DUIterator
4011     newmm = MergeMemNode::make(u_mm->base_memory());
4012     for (uint j = 0; j < u->req(); j++) {
4013       if (j < newmm->req()) {
4014         if (j == (uint)_alias) {
4015           newmm->set_req(j, rep_proj);
4016         } else if (newmm->in(j) != u->in(j)) {
4017           newmm->set_req(j, u->in(j));
4018         }
4019       } else if (j == (uint)_alias) {
4020         newmm->add_req(rep_proj);
4021       } else {
4022         newmm->add_req(u->in(j));
4023       }
4024     }
4025     if ((uint)_alias >= u->req()) {
4026       newmm->set_memory_at(_alias, rep_proj);
4027     }
4028     _phase->register_new_node(newmm, c);
4029   }
4030   return newmm;
4031 }
4032 
4033 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
4034   if (phi->adr_type() == TypePtr::BOTTOM) {
4035     Node* region = phi->in(0);
4036     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
4037       Node* uu = region->fast_out(j);
4038       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
4039         return false;
4040       }
4041     }
4042     return true;
4043   }
4044   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
4045 }
4046 
4047 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
4048   uint last = _phase-> C->unique();
4049   MergeMemNode* mm = NULL;
4050   assert(mem->bottom_type() == Type::MEMORY, "");
4051   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
4052     Node* u = mem->out(i);
4053     if (u != replacement && u->_idx < last) {
4054       if (u->is_ShenandoahBarrier() && _alias != Compile::AliasIdxRaw) {
4055         if (_phase->C->get_alias_index(u->adr_type()) == _alias && ShenandoahWriteBarrierNode::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
4056           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
4057           assert(u->find_edge(mem) == -1, "only one edge");
4058           --i;
4059         }
4060       } else if (u->is_Mem()) {
4061         if (_phase->C->get_alias_index(u->adr_type()) == _alias && ShenandoahWriteBarrierNode::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
4062           assert(_alias == Compile::AliasIdxRaw , "only raw memory can lead to a memory operation");
4063           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
4064           assert(u->find_edge(mem) == -1, "only one edge");
4065           --i;
4066         }
4067       } else if (u->is_MergeMem()) {
4068         MergeMemNode* u_mm = u->as_MergeMem();
4069         if (u_mm->memory_at(_alias) == mem) {
4070           MergeMemNode* newmm = NULL;
4071           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
4072             Node* uu = u->fast_out(j);
4073             assert(!uu->is_MergeMem(), "chain of MergeMems?");
4074             if (uu->is_Phi()) {
4075               if (should_process_phi(uu)) {
4076                 Node* region = uu->in(0);
4077                 int nb = 0;
4078                 for (uint k = 1; k < uu->req(); k++) {
4079                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
4080                     if (newmm == NULL) {
4081                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
4082                     }
4083                     if (newmm != u) {
4084                       _phase->igvn().replace_input_of(uu, k, newmm);
4085                       nb++;
4086                       --jmax;
4087                     }
4088                   }
4089                 }
4090                 if (nb > 0) {
4091                   --j;
4092                 }
4093               }
4094             } else {
4095               if (rep_ctrl != uu && ShenandoahWriteBarrierNode::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
4096                 if (newmm == NULL) {
4097                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
4098                 }
4099                 if (newmm != u) {
4100                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
4101                   --j, --jmax;
4102                 }
4103               }
4104             }
4105           }
4106         }
4107       } else if (u->is_Phi()) {
4108         assert(u->bottom_type() == Type::MEMORY, "what else?");
4109         Node* region = u->in(0);
4110         if (should_process_phi(u)) {
4111           bool replaced = false;
4112           for (uint j = 1; j < u->req(); j++) {
4113             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
4114               Node* nnew = rep_proj;
4115               if (u->adr_type() == TypePtr::BOTTOM) {
4116                 if (mm == NULL) {
4117                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
4118                 }
4119                 nnew = mm;
4120               }
4121               _phase->igvn().replace_input_of(u, j, nnew);
4122               replaced = true;
4123             }
4124           }
4125           if (replaced) {
4126             --i;
4127           }
4128 
4129         }
4130       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
4131                  u->adr_type() == NULL) {
4132         assert(u->adr_type() != NULL ||
4133                u->Opcode() == Op_Rethrow ||
4134                u->Opcode() == Op_Return ||
4135                u->Opcode() == Op_SafePoint ||
4136                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
4137                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
4138                u->Opcode() == Op_CallLeaf, "");
4139         if (ShenandoahWriteBarrierNode::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
4140           if (mm == NULL) {
4141             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
4142           }
4143           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
4144           --i;
4145         }
4146       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
4147         if (ShenandoahWriteBarrierNode::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
4148           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
4149           --i;
4150         }
4151       }
4152     }
4153   }
4154 }
4155 
4156 void MemoryGraphFixer::remove(Node* n) {
4157   assert(n->Opcode() == Op_ShenandoahWBMemProj, "");
4158   Node* c = _phase->get_ctrl(n);
4159   Node* mem = find_mem(c, NULL);
4160   if (mem == n) {
4161     _memory_nodes.map(c->_idx, mem->in(ShenandoahWBMemProjNode::WriteBarrier)->in(ShenandoahBarrierNode::Memory));
4162   }
4163 }
4164 
4165