1 /*
   2  * Copyright (c) 2015, 2021, Red Hat, Inc. All rights reserved.
   3  * Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 
  28 #include "classfile/javaClasses.hpp"
  29 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  30 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
  31 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  32 #include "gc/shenandoah/shenandoahForwarding.hpp"
  33 #include "gc/shenandoah/shenandoahHeap.hpp"
  34 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  35 #include "gc/shenandoah/shenandoahRuntime.hpp"
  36 #include "gc/shenandoah/shenandoahThreadLocalData.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/block.hpp"
  39 #include "opto/callnode.hpp"
  40 #include "opto/castnode.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "opto/phaseX.hpp"
  43 #include "opto/rootnode.hpp"
  44 #include "opto/runtime.hpp"
  45 #include "opto/subnode.hpp"
  46 
  47 bool ShenandoahBarrierC2Support::expand(Compile* C, PhaseIterGVN& igvn) {
  48   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
  49   if (state->load_reference_barriers_count() > 0) {
  50     assert(C->post_loop_opts_phase(), "no loop opts allowed");
  51     C->reset_post_loop_opts_phase(); // ... but we know what we are doing
  52     C->clear_major_progress();
  53     PhaseIdealLoop::optimize(igvn, LoopOptsShenandoahExpand);
  54     if (C->failing()) return false;
  55 
  56     C->set_major_progress();
  57     if (!C->optimize_loops(igvn, LoopOptsShenandoahPostExpand)) {
  58       return false;
  59     }
  60     C->clear_major_progress();
  61     C->process_for_post_loop_opts_igvn(igvn);
  62     if (C->failing()) return false;
  63 
  64     C->set_post_loop_opts_phase(); // now for real!
  65   }
  66   return true;
  67 }
  68 
  69 bool ShenandoahBarrierC2Support::is_gc_state_test(Node* iff, int mask) {
  70   if (!UseShenandoahGC) {
  71     return false;
  72   }
  73   assert(iff->is_If(), "bad input");
  74   if (iff->Opcode() != Op_If) {
  75     return false;
  76   }
  77   Node* bol = iff->in(1);
  78   if (!bol->is_Bool() || bol->as_Bool()->_test._test != BoolTest::ne) {
  79     return false;
  80   }
  81   Node* cmp = bol->in(1);
  82   if (cmp->Opcode() != Op_CmpI) {
  83     return false;
  84   }
  85   Node* in1 = cmp->in(1);
  86   Node* in2 = cmp->in(2);
  87   if (in2->find_int_con(-1) != 0) {
  88     return false;
  89   }
  90   if (in1->Opcode() != Op_AndI) {
  91     return false;
  92   }
  93   in2 = in1->in(2);
  94   if (in2->find_int_con(-1) != mask) {
  95     return false;
  96   }
  97   in1 = in1->in(1);
  98 
  99   return is_gc_state_load(in1);
 100 }
 101 
 102 bool ShenandoahBarrierC2Support::is_heap_stable_test(Node* iff) {
 103   return is_gc_state_test(iff, ShenandoahHeap::HAS_FORWARDED);
 104 }
 105 
 106 bool ShenandoahBarrierC2Support::is_gc_state_load(Node *n) {
 107   if (!UseShenandoahGC) {
 108     return false;
 109   }
 110   if (n->Opcode() != Op_LoadB && n->Opcode() != Op_LoadUB) {
 111     return false;
 112   }
 113   Node* addp = n->in(MemNode::Address);
 114   if (!addp->is_AddP()) {
 115     return false;
 116   }
 117   Node* base = addp->in(AddPNode::Address);
 118   Node* off = addp->in(AddPNode::Offset);
 119   if (base->Opcode() != Op_ThreadLocal) {
 120     return false;
 121   }
 122   if (off->find_intptr_t_con(-1) != in_bytes(ShenandoahThreadLocalData::gc_state_offset())) {
 123     return false;
 124   }
 125   return true;
 126 }
 127 
 128 bool ShenandoahBarrierC2Support::has_safepoint_between(Node* start, Node* stop, PhaseIdealLoop *phase) {
 129   assert(phase->is_dominator(stop, start), "bad inputs");
 130   ResourceMark rm;
 131   Unique_Node_List wq;
 132   wq.push(start);
 133   for (uint next = 0; next < wq.size(); next++) {
 134     Node *m = wq.at(next);
 135     if (m == stop) {
 136       continue;
 137     }
 138     if (m->is_SafePoint() && !m->is_CallLeaf()) {
 139       return true;
 140     }
 141     if (m->is_Region()) {
 142       for (uint i = 1; i < m->req(); i++) {
 143         wq.push(m->in(i));
 144       }
 145     } else {
 146       wq.push(m->in(0));
 147     }
 148   }
 149   return false;
 150 }
 151 
 152 #ifdef ASSERT
 153 bool ShenandoahBarrierC2Support::verify_helper(Node* in, Node_Stack& phis, VectorSet& visited, verify_type t, bool trace, Unique_Node_List& barriers_used) {
 154   assert(phis.size() == 0, "");
 155 
 156   while (true) {
 157     if (in->bottom_type() == TypePtr::NULL_PTR) {
 158       if (trace) {tty->print_cr("null");}
 159     } else if (!in->bottom_type()->make_ptr()->make_oopptr()) {
 160       if (trace) {tty->print_cr("Non oop");}
 161     } else {
 162       if (in->is_ConstraintCast()) {
 163         in = in->in(1);
 164         continue;
 165       } else if (in->is_AddP()) {
 166         assert(!in->in(AddPNode::Address)->is_top(), "no raw memory access");
 167         in = in->in(AddPNode::Address);
 168         continue;
 169       } else if (in->is_Con()) {
 170         if (trace) {
 171           tty->print("Found constant");
 172           in->dump();
 173         }
 174       } else if (in->Opcode() == Op_Parm) {
 175         if (trace) {
 176           tty->print("Found argument");
 177         }
 178       } else if (in->Opcode() == Op_CreateEx) {
 179         if (trace) {
 180           tty->print("Found create-exception");
 181         }
 182       } else if (in->Opcode() == Op_LoadP && in->adr_type() == TypeRawPtr::BOTTOM) {
 183         if (trace) {
 184           tty->print("Found raw LoadP (OSR argument?)");
 185         }
 186       } else if (in->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 187         if (t == ShenandoahOopStore) {
 188           return false;
 189         }
 190         barriers_used.push(in);
 191         if (trace) {tty->print("Found barrier"); in->dump();}
 192       } else if (in->is_Proj() && in->in(0)->is_Allocate()) {
 193         if (trace) {
 194           tty->print("Found alloc");
 195           in->in(0)->dump();
 196         }
 197       } else if (in->is_Proj() && (in->in(0)->Opcode() == Op_CallStaticJava || in->in(0)->Opcode() == Op_CallDynamicJava)) {
 198         if (trace) {
 199           tty->print("Found Java call");
 200         }
 201       } else if (in->is_Phi()) {
 202         if (!visited.test_set(in->_idx)) {
 203           if (trace) {tty->print("Pushed phi:"); in->dump();}
 204           phis.push(in, 2);
 205           in = in->in(1);
 206           continue;
 207         }
 208         if (trace) {tty->print("Already seen phi:"); in->dump();}
 209       } else if (in->Opcode() == Op_CMoveP || in->Opcode() == Op_CMoveN) {
 210         if (!visited.test_set(in->_idx)) {
 211           if (trace) {tty->print("Pushed cmovep:"); in->dump();}
 212           phis.push(in, CMoveNode::IfTrue);
 213           in = in->in(CMoveNode::IfFalse);
 214           continue;
 215         }
 216         if (trace) {tty->print("Already seen cmovep:"); in->dump();}
 217       } else if (in->Opcode() == Op_EncodeP || in->Opcode() == Op_DecodeN) {
 218         in = in->in(1);
 219         continue;
 220       } else {
 221         return false;
 222       }
 223     }
 224     bool cont = false;
 225     while (phis.is_nonempty()) {
 226       uint idx = phis.index();
 227       Node* phi = phis.node();
 228       if (idx >= phi->req()) {
 229         if (trace) {tty->print("Popped phi:"); phi->dump();}
 230         phis.pop();
 231         continue;
 232       }
 233       if (trace) {tty->print("Next entry(%d) for phi:", idx); phi->dump();}
 234       in = phi->in(idx);
 235       phis.set_index(idx+1);
 236       cont = true;
 237       break;
 238     }
 239     if (!cont) {
 240       break;
 241     }
 242   }
 243   return true;
 244 }
 245 
 246 void ShenandoahBarrierC2Support::report_verify_failure(const char* msg, Node* n1, Node* n2) {
 247   if (n1 != nullptr) {
 248     n1->dump(+10);
 249   }
 250   if (n2 != nullptr) {
 251     n2->dump(+10);
 252   }
 253   fatal("%s", msg);
 254 }
 255 
 256 void ShenandoahBarrierC2Support::verify(RootNode* root) {
 257   ResourceMark rm;
 258   Unique_Node_List wq;
 259   GrowableArray<Node*> barriers;
 260   Unique_Node_List barriers_used;
 261   Node_Stack phis(0);
 262   VectorSet visited;
 263   const bool trace = false;
 264   const bool verify_no_useless_barrier = false;
 265 
 266   wq.push(root);
 267   for (uint next = 0; next < wq.size(); next++) {
 268     Node *n = wq.at(next);
 269     if (n->is_Load()) {
 270       const bool trace = false;
 271       if (trace) {tty->print("Verifying"); n->dump();}
 272       if (n->Opcode() == Op_LoadRange || n->Opcode() == Op_LoadKlass || n->Opcode() == Op_LoadNKlass) {
 273         if (trace) {tty->print_cr("Load range/klass");}
 274       } else {
 275         const TypePtr* adr_type = n->as_Load()->adr_type();
 276 
 277         if (adr_type->isa_oopptr() && adr_type->is_oopptr()->offset() == oopDesc::mark_offset_in_bytes()) {
 278           if (trace) {tty->print_cr("Mark load");}
 279         } else if (adr_type->isa_instptr() &&
 280                    adr_type->is_instptr()->instance_klass()->is_subtype_of(Compile::current()->env()->Reference_klass()) &&
 281                    adr_type->is_instptr()->offset() == java_lang_ref_Reference::referent_offset()) {
 282           if (trace) {tty->print_cr("Reference.get()");}
 283         } else if (!verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 284           report_verify_failure("Shenandoah verification: Load should have barriers", n);
 285         }
 286       }
 287     } else if (n->is_Store()) {
 288       const bool trace = false;
 289 
 290       if (trace) {tty->print("Verifying"); n->dump();}
 291       if (n->in(MemNode::ValueIn)->bottom_type()->make_oopptr()) {
 292         Node* adr = n->in(MemNode::Address);
 293         bool verify = true;
 294 
 295         if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top()) {
 296           adr = adr->in(AddPNode::Address);
 297           if (adr->is_AddP()) {
 298             assert(adr->in(AddPNode::Base)->is_top(), "");
 299             adr = adr->in(AddPNode::Address);
 300             if (adr->Opcode() == Op_LoadP &&
 301                 adr->in(MemNode::Address)->in(AddPNode::Base)->is_top() &&
 302                 adr->in(MemNode::Address)->in(AddPNode::Address)->Opcode() == Op_ThreadLocal &&
 303                 adr->in(MemNode::Address)->in(AddPNode::Offset)->find_intptr_t_con(-1) == in_bytes(ShenandoahThreadLocalData::satb_mark_queue_buffer_offset())) {
 304               if (trace) {tty->print_cr("SATB prebarrier");}
 305               verify = false;
 306             }
 307           }
 308         }
 309 
 310         if (verify && !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahValue, trace, barriers_used)) {
 311           report_verify_failure("Shenandoah verification: Store should have barriers", n);
 312         }
 313       }
 314       if (!verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 315         report_verify_failure("Shenandoah verification: Store (address) should have barriers", n);
 316       }
 317     } else if (n->Opcode() == Op_CmpP) {
 318       const bool trace = false;
 319 
 320       Node* in1 = n->in(1);
 321       Node* in2 = n->in(2);
 322       if (in1->bottom_type()->isa_oopptr()) {
 323         if (trace) {tty->print("Verifying"); n->dump();}
 324 
 325         bool mark_inputs = false;
 326         if (in1->bottom_type() == TypePtr::NULL_PTR || in2->bottom_type() == TypePtr::NULL_PTR ||
 327             (in1->is_Con() || in2->is_Con())) {
 328           if (trace) {tty->print_cr("Comparison against a constant");}
 329           mark_inputs = true;
 330         } else if ((in1->is_CheckCastPP() && in1->in(1)->is_Proj() && in1->in(1)->in(0)->is_Allocate()) ||
 331                    (in2->is_CheckCastPP() && in2->in(1)->is_Proj() && in2->in(1)->in(0)->is_Allocate())) {
 332           if (trace) {tty->print_cr("Comparison with newly alloc'ed object");}
 333           mark_inputs = true;
 334         } else {
 335           assert(in2->bottom_type()->isa_oopptr(), "");
 336 
 337           if (!verify_helper(in1, phis, visited, ShenandoahStore, trace, barriers_used) ||
 338               !verify_helper(in2, phis, visited, ShenandoahStore, trace, barriers_used)) {
 339             report_verify_failure("Shenandoah verification: Cmp should have barriers", n);
 340           }
 341         }
 342         if (verify_no_useless_barrier &&
 343             mark_inputs &&
 344             (!verify_helper(in1, phis, visited, ShenandoahValue, trace, barriers_used) ||
 345              !verify_helper(in2, phis, visited, ShenandoahValue, trace, barriers_used))) {
 346           phis.clear();
 347           visited.reset();
 348         }
 349       }
 350     } else if (n->is_LoadStore()) {
 351       if (n->in(MemNode::ValueIn)->bottom_type()->make_ptr() &&
 352           !verify_helper(n->in(MemNode::ValueIn), phis, visited, ShenandoahValue, trace, barriers_used)) {
 353         report_verify_failure("Shenandoah verification: LoadStore (value) should have barriers", n);
 354       }
 355 
 356       if (n->in(MemNode::Address)->bottom_type()->make_oopptr() && !verify_helper(n->in(MemNode::Address), phis, visited, ShenandoahStore, trace, barriers_used)) {
 357         report_verify_failure("Shenandoah verification: LoadStore (address) should have barriers", n);
 358       }
 359     } else if (n->Opcode() == Op_CallLeafNoFP || n->Opcode() == Op_CallLeaf) {
 360       CallNode* call = n->as_Call();
 361 
 362       static struct {
 363         const char* name;
 364         struct {
 365           int pos;
 366           verify_type t;
 367         } args[6];
 368       } calls[] = {
 369         "array_partition_stub",
 370         { { TypeFunc::Parms, ShenandoahStore }, { TypeFunc::Parms+4, ShenandoahStore },   { -1, ShenandoahNone },
 371           { -1, ShenandoahNone },                { -1, ShenandoahNone },                  { -1, ShenandoahNone } },
 372         "arraysort_stub",
 373         { { TypeFunc::Parms, ShenandoahStore },  { -1, ShenandoahNone },                  { -1, ShenandoahNone },
 374           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 375         "aescrypt_encryptBlock",
 376         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 377           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 378         "aescrypt_decryptBlock",
 379         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 380           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 381         "multiplyToLen",
 382         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { TypeFunc::Parms+4, ShenandoahStore },
 383           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 384         "squareToLen",
 385         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },   { -1,  ShenandoahNone},
 386           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 387         "montgomery_multiply",
 388         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 389           { TypeFunc::Parms+6, ShenandoahStore }, { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 390         "montgomery_square",
 391         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+5, ShenandoahStore },
 392           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 393         "mulAdd",
 394         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 395           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 396         "vectorizedMismatch",
 397         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahLoad },   { -1,  ShenandoahNone},
 398           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 399         "updateBytesCRC32",
 400         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 401           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 402         "updateBytesAdler32",
 403         { { TypeFunc::Parms+1, ShenandoahLoad }, { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 404           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 405         "updateBytesCRC32C",
 406         { { TypeFunc::Parms+1, ShenandoahLoad }, { TypeFunc::Parms+3, ShenandoahLoad},    { -1,  ShenandoahNone},
 407           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 408         "counterMode_AESCrypt",
 409         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 410           { TypeFunc::Parms+3, ShenandoahStore }, { TypeFunc::Parms+5, ShenandoahStore }, { TypeFunc::Parms+6, ShenandoahStore } },
 411         "cipherBlockChaining_encryptAESCrypt",
 412         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 413           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 414         "cipherBlockChaining_decryptAESCrypt",
 415         { { TypeFunc::Parms, ShenandoahLoad },   { TypeFunc::Parms+1, ShenandoahStore },  { TypeFunc::Parms+2, ShenandoahLoad },
 416           { TypeFunc::Parms+3, ShenandoahLoad },  { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 417         "shenandoah_clone_barrier",
 418         { { TypeFunc::Parms, ShenandoahLoad },   { -1,  ShenandoahNone},                  { -1,  ShenandoahNone},
 419           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 420         "ghash_processBlocks",
 421         { { TypeFunc::Parms, ShenandoahStore },  { TypeFunc::Parms+1, ShenandoahLoad },   { TypeFunc::Parms+2, ShenandoahLoad },
 422           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 423         "sha1_implCompress",
 424         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 425           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 426         "sha256_implCompress",
 427         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 428           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 429         "sha512_implCompress",
 430         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 431           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 432         "sha1_implCompressMB",
 433         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 434           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 435         "sha256_implCompressMB",
 436         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 437           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 438         "sha512_implCompressMB",
 439         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahStore },   { -1, ShenandoahNone },
 440           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 441         "encodeBlock",
 442         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+3, ShenandoahStore },   { -1, ShenandoahNone },
 443           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 444         "decodeBlock",
 445         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+3, ShenandoahStore },   { -1, ShenandoahNone },
 446           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 447         "intpoly_montgomeryMult_P256",
 448         { { TypeFunc::Parms, ShenandoahLoad },  { TypeFunc::Parms+1, ShenandoahLoad  },   { TypeFunc::Parms+2, ShenandoahStore },
 449           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 450         "intpoly_assign",
 451         { { TypeFunc::Parms+1, ShenandoahStore }, { TypeFunc::Parms+2, ShenandoahLoad },  { -1, ShenandoahNone },
 452           { -1,  ShenandoahNone},                 { -1,  ShenandoahNone},                 { -1,  ShenandoahNone} },
 453       };
 454 
 455       if (call->is_call_to_arraycopystub()) {
 456         Node* dest = nullptr;
 457         const TypeTuple* args = n->as_Call()->_tf->domain_sig();
 458         for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 459           if (args->field_at(i)->isa_ptr()) {
 460             j++;
 461             if (j == 2) {
 462               dest = n->in(i);
 463               break;
 464             }
 465           }
 466         }
 467         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahLoad, trace, barriers_used) ||
 468             !verify_helper(dest, phis, visited, ShenandoahStore, trace, barriers_used)) {
 469           report_verify_failure("Shenandoah verification: ArrayCopy should have barriers", n);
 470         }
 471       } else if (strlen(call->_name) > 5 &&
 472                  !strcmp(call->_name + strlen(call->_name) - 5, "_fill")) {
 473         if (!verify_helper(n->in(TypeFunc::Parms), phis, visited, ShenandoahStore, trace, barriers_used)) {
 474           report_verify_failure("Shenandoah verification: _fill should have barriers", n);
 475         }
 476       } else if (!strcmp(call->_name, "shenandoah_wb_pre")) {
 477         // skip
 478       } else {
 479         const int calls_len = sizeof(calls) / sizeof(calls[0]);
 480         int i = 0;
 481         for (; i < calls_len; i++) {
 482           if (!strcmp(calls[i].name, call->_name)) {
 483             break;
 484           }
 485         }
 486         if (i != calls_len) {
 487           const uint args_len = sizeof(calls[0].args) / sizeof(calls[0].args[0]);
 488           for (uint j = 0; j < args_len; j++) {
 489             int pos = calls[i].args[j].pos;
 490             if (pos == -1) {
 491               break;
 492             }
 493             if (!verify_helper(call->in(pos), phis, visited, calls[i].args[j].t, trace, barriers_used)) {
 494               report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 495             }
 496           }
 497           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 498             if (call->in(j)->bottom_type()->make_ptr() &&
 499                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 500               uint k = 0;
 501               for (; k < args_len && calls[i].args[k].pos != (int)j; k++);
 502               if (k == args_len) {
 503                 fatal("arg %d for call %s not covered", j, call->_name);
 504               }
 505             }
 506           }
 507         } else {
 508           for (uint j = TypeFunc::Parms; j < call->req(); j++) {
 509             if (call->in(j)->bottom_type()->make_ptr() &&
 510                 call->in(j)->bottom_type()->make_ptr()->isa_oopptr()) {
 511               fatal("%s not covered", call->_name);
 512             }
 513           }
 514         }
 515       }
 516     } else if (n->Opcode() == Op_ShenandoahLoadReferenceBarrier) {
 517       // skip
 518     } else if (n->is_AddP()
 519                || n->is_Phi()
 520                || n->is_ConstraintCast()
 521                || n->Opcode() == Op_Return
 522                || n->Opcode() == Op_CMoveP
 523                || n->Opcode() == Op_CMoveN
 524                || n->Opcode() == Op_Rethrow
 525                || n->is_MemBar()
 526                || n->Opcode() == Op_Conv2B
 527                || n->Opcode() == Op_SafePoint
 528                || n->is_CallJava()
 529                || n->Opcode() == Op_Unlock
 530                || n->Opcode() == Op_EncodeP
 531                || n->Opcode() == Op_DecodeN) {
 532       // nothing to do
 533     } else {
 534       static struct {
 535         int opcode;
 536         struct {
 537           int pos;
 538           verify_type t;
 539         } inputs[2];
 540       } others[] = {
 541         Op_FastLock,
 542         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 543         Op_Lock,
 544         { { TypeFunc::Parms, ShenandoahLoad },    { -1, ShenandoahNone} },
 545         Op_ArrayCopy,
 546         { { ArrayCopyNode::Src, ShenandoahLoad }, { ArrayCopyNode::Dest, ShenandoahStore } },
 547         Op_StrCompressedCopy,
 548         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 549         Op_StrInflatedCopy,
 550         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 551         Op_AryEq,
 552         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 553         Op_StrIndexOf,
 554         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 555         Op_StrComp,
 556         { { 2, ShenandoahLoad },                  { 4, ShenandoahLoad } },
 557         Op_StrEquals,
 558         { { 2, ShenandoahLoad },                  { 3, ShenandoahLoad } },
 559         Op_VectorizedHashCode,
 560         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
 561         Op_EncodeISOArray,
 562         { { 2, ShenandoahLoad },                  { 3, ShenandoahStore } },
 563         Op_CountPositives,
 564         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone} },
 565         Op_CastP2X,
 566         { { 1, ShenandoahLoad },                  { -1, ShenandoahNone} },
 567         Op_StrIndexOfChar,
 568         { { 2, ShenandoahLoad },                  { -1, ShenandoahNone } },
 569       };
 570 
 571       const int others_len = sizeof(others) / sizeof(others[0]);
 572       int i = 0;
 573       for (; i < others_len; i++) {
 574         if (others[i].opcode == n->Opcode()) {
 575           break;
 576         }
 577       }
 578       uint stop = n->is_Call() ? n->as_Call()->tf()->domain_sig()->cnt() : n->req();
 579       if (i != others_len) {
 580         const uint inputs_len = sizeof(others[0].inputs) / sizeof(others[0].inputs[0]);
 581         for (uint j = 0; j < inputs_len; j++) {
 582           int pos = others[i].inputs[j].pos;
 583           if (pos == -1) {
 584             break;
 585           }
 586           if (!verify_helper(n->in(pos), phis, visited, others[i].inputs[j].t, trace, barriers_used)) {
 587             report_verify_failure("Shenandoah verification: intrinsic calls should have barriers", n);
 588           }
 589         }
 590         for (uint j = 1; j < stop; j++) {
 591           if (n->in(j) != nullptr && n->in(j)->bottom_type()->make_ptr() &&
 592               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 593             uint k = 0;
 594             for (; k < inputs_len && others[i].inputs[k].pos != (int)j; k++);
 595             if (k == inputs_len) {
 596               fatal("arg %d for node %s not covered", j, n->Name());
 597             }
 598           }
 599         }
 600       } else {
 601         for (uint j = 1; j < stop; j++) {
 602           if (n->in(j) != nullptr && n->in(j)->bottom_type()->make_ptr() &&
 603               n->in(j)->bottom_type()->make_ptr()->make_oopptr()) {
 604             fatal("%s not covered", n->Name());
 605           }
 606         }
 607       }
 608     }
 609 
 610     if (n->is_SafePoint()) {
 611       SafePointNode* sfpt = n->as_SafePoint();
 612       if (verify_no_useless_barrier && sfpt->jvms() != nullptr) {
 613         for (uint i = sfpt->jvms()->scloff(); i < sfpt->jvms()->endoff(); i++) {
 614           if (!verify_helper(sfpt->in(i), phis, visited, ShenandoahLoad, trace, barriers_used)) {
 615             phis.clear();
 616             visited.reset();
 617           }
 618         }
 619       }
 620     }
 621   }
 622 
 623   if (verify_no_useless_barrier) {
 624     for (int i = 0; i < barriers.length(); i++) {
 625       Node* n = barriers.at(i);
 626       if (!barriers_used.member(n)) {
 627         tty->print("XXX useless barrier"); n->dump(-2);
 628         ShouldNotReachHere();
 629       }
 630     }
 631   }
 632 }
 633 #endif
 634 
 635 bool ShenandoahBarrierC2Support::is_dominator_same_ctrl(Node* c, Node* d, Node* n, PhaseIdealLoop* phase) {
 636   // That both nodes have the same control is not sufficient to prove
 637   // domination, verify that there's no path from d to n
 638   ResourceMark rm;
 639   Unique_Node_List wq;
 640   wq.push(d);
 641   for (uint next = 0; next < wq.size(); next++) {
 642     Node *m = wq.at(next);
 643     if (m == n) {
 644       return false;
 645     }
 646     if (m->is_Phi() && m->in(0)->is_Loop()) {
 647       assert(phase->ctrl_or_self(m->in(LoopNode::EntryControl)) != c, "following loop entry should lead to new control");
 648     } else {
 649       if (m->is_Store() || m->is_LoadStore()) {
 650         // Take anti-dependencies into account
 651         Node* mem = m->in(MemNode::Memory);
 652         for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
 653           Node* u = mem->fast_out(i);
 654           if (u->is_Load() && phase->C->can_alias(m->adr_type(), phase->C->get_alias_index(u->adr_type())) &&
 655               phase->ctrl_or_self(u) == c) {
 656             wq.push(u);
 657           }
 658         }
 659       }
 660       for (uint i = 0; i < m->req(); i++) {
 661         if (m->in(i) != nullptr && phase->ctrl_or_self(m->in(i)) == c) {
 662           wq.push(m->in(i));
 663         }
 664       }
 665     }
 666   }
 667   return true;
 668 }
 669 
 670 bool ShenandoahBarrierC2Support::is_dominator(Node* d_c, Node* n_c, Node* d, Node* n, PhaseIdealLoop* phase) {
 671   if (d_c != n_c) {
 672     return phase->is_dominator(d_c, n_c);
 673   }
 674   return is_dominator_same_ctrl(d_c, d, n, phase);
 675 }
 676 
 677 Node* next_mem(Node* mem, int alias) {
 678   Node* res = nullptr;
 679   if (mem->is_Proj()) {
 680     res = mem->in(0);
 681   } else if (mem->is_SafePoint() || mem->is_MemBar()) {
 682     res = mem->in(TypeFunc::Memory);
 683   } else if (mem->is_Phi()) {
 684     res = mem->in(1);
 685   } else if (mem->is_MergeMem()) {
 686     res = mem->as_MergeMem()->memory_at(alias);
 687   } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
 688     assert(alias == Compile::AliasIdxRaw, "following raw memory can't lead to a barrier");
 689     res = mem->in(MemNode::Memory);
 690   } else {
 691 #ifdef ASSERT
 692     mem->dump();
 693 #endif
 694     ShouldNotReachHere();
 695   }
 696   return res;
 697 }
 698 
 699 Node* ShenandoahBarrierC2Support::no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase) {
 700   Node* iffproj = nullptr;
 701   while (c != dom) {
 702     Node* next = phase->idom(c);
 703     assert(next->unique_ctrl_out_or_null() == c || c->is_Proj() || c->is_Region(), "multiple control flow out but no proj or region?");
 704     if (c->is_Region()) {
 705       ResourceMark rm;
 706       Unique_Node_List wq;
 707       wq.push(c);
 708       for (uint i = 0; i < wq.size(); i++) {
 709         Node *n = wq.at(i);
 710         if (n == next) {
 711           continue;
 712         }
 713         if (n->is_Region()) {
 714           for (uint j = 1; j < n->req(); j++) {
 715             wq.push(n->in(j));
 716           }
 717         } else {
 718           wq.push(n->in(0));
 719         }
 720       }
 721       for (uint i = 0; i < wq.size(); i++) {
 722         Node *n = wq.at(i);
 723         assert(n->is_CFG(), "");
 724         if (n->is_Multi()) {
 725           for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 726             Node* u = n->fast_out(j);
 727             if (u->is_CFG()) {
 728               if (!wq.member(u) && !u->as_Proj()->is_uncommon_trap_proj()) {
 729                 return NodeSentinel;
 730               }
 731             }
 732           }
 733         }
 734       }
 735     } else  if (c->is_Proj()) {
 736       if (c->is_IfProj()) {
 737         if (c->as_Proj()->is_uncommon_trap_if_pattern() != nullptr) {
 738           // continue;
 739         } else {
 740           if (!allow_one_proj) {
 741             return NodeSentinel;
 742           }
 743           if (iffproj == nullptr) {
 744             iffproj = c;
 745           } else {
 746             return NodeSentinel;
 747           }
 748         }
 749       } else if (c->Opcode() == Op_JumpProj) {
 750         return NodeSentinel; // unsupported
 751       } else if (c->Opcode() == Op_CatchProj) {
 752         return NodeSentinel; // unsupported
 753       } else if (c->Opcode() == Op_CProj && next->is_NeverBranch()) {
 754         return NodeSentinel; // unsupported
 755       } else {
 756         assert(next->unique_ctrl_out() == c, "unsupported branch pattern");
 757       }
 758     }
 759     c = next;
 760   }
 761   return iffproj;
 762 }
 763 
 764 Node* ShenandoahBarrierC2Support::dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase) {
 765   ResourceMark rm;
 766   VectorSet wq;
 767   wq.set(mem->_idx);
 768   mem_ctrl = phase->ctrl_or_self(mem);
 769   while (!phase->is_dominator(mem_ctrl, ctrl) || mem_ctrl == ctrl) {
 770     mem = next_mem(mem, alias);
 771     if (wq.test_set(mem->_idx)) {
 772       return nullptr;
 773     }
 774     mem_ctrl = phase->ctrl_or_self(mem);
 775   }
 776   if (mem->is_MergeMem()) {
 777     mem = mem->as_MergeMem()->memory_at(alias);
 778     mem_ctrl = phase->ctrl_or_self(mem);
 779   }
 780   return mem;
 781 }
 782 
 783 Node* ShenandoahBarrierC2Support::find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase) {
 784   Node* mem = nullptr;
 785   Node* c = ctrl;
 786   do {
 787     if (c->is_Region()) {
 788       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax && mem == nullptr; i++) {
 789         Node* u = c->fast_out(i);
 790         if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
 791           if (u->adr_type() == TypePtr::BOTTOM) {
 792             mem = u;
 793           }
 794         }
 795       }
 796     } else {
 797       if (c->is_Call() && c->as_Call()->adr_type() != nullptr) {
 798         CallProjections* projs = c->as_Call()->extract_projections(true, false);
 799         if (projs->fallthrough_memproj != nullptr) {
 800           if (projs->fallthrough_memproj->adr_type() == TypePtr::BOTTOM) {
 801             if (projs->catchall_memproj == nullptr) {
 802               mem = projs->fallthrough_memproj;
 803             } else {
 804               if (phase->is_dominator(projs->fallthrough_catchproj, ctrl)) {
 805                 mem = projs->fallthrough_memproj;
 806               } else {
 807                 assert(phase->is_dominator(projs->catchall_catchproj, ctrl), "one proj must dominate barrier");
 808                 mem = projs->catchall_memproj;
 809               }
 810             }
 811           }
 812         } else {
 813           Node* proj = c->as_Call()->proj_out(TypeFunc::Memory);
 814           if (proj != nullptr &&
 815               proj->adr_type() == TypePtr::BOTTOM) {
 816             mem = proj;
 817           }
 818         }
 819       } else {
 820         for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
 821           Node* u = c->fast_out(i);
 822           if (u->is_Proj() &&
 823               u->bottom_type() == Type::MEMORY &&
 824               u->adr_type() == TypePtr::BOTTOM) {
 825               assert(c->is_SafePoint() || c->is_MemBar() || c->is_Start(), "");
 826               assert(mem == nullptr, "only one proj");
 827               mem = u;
 828           }
 829         }
 830         assert(!c->is_Call() || c->as_Call()->adr_type() != nullptr || mem == nullptr, "no mem projection expected");
 831       }
 832     }
 833     c = phase->idom(c);
 834   } while (mem == nullptr);
 835   return mem;
 836 }
 837 
 838 void ShenandoahBarrierC2Support::follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase) {
 839   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 840     Node* u = n->fast_out(i);
 841     if (!u->is_CFG() && phase->get_ctrl(u) == ctrl && (!u->is_Phi() || !u->in(0)->is_Loop() || u->in(LoopNode::LoopBackControl) != n)) {
 842       uses.push(u);
 843     }
 844   }
 845 }
 846 
 847 static void hide_strip_mined_loop(OuterStripMinedLoopNode* outer, CountedLoopNode* inner, PhaseIdealLoop* phase) {
 848   OuterStripMinedLoopEndNode* le = inner->outer_loop_end();
 849   Node* new_outer = new LoopNode(outer->in(LoopNode::EntryControl), outer->in(LoopNode::LoopBackControl));
 850   phase->register_control(new_outer, phase->get_loop(outer), outer->in(LoopNode::EntryControl));
 851   Node* new_le = new IfNode(le->in(0), le->in(1), le->_prob, le->_fcnt);
 852   phase->register_control(new_le, phase->get_loop(le), le->in(0));
 853   phase->lazy_replace(outer, new_outer);
 854   phase->lazy_replace(le, new_le);
 855   inner->clear_strip_mined();
 856 }
 857 
 858 void ShenandoahBarrierC2Support::test_gc_state(Node*& ctrl, Node* raw_mem, Node*& test_fail_ctrl,
 859                                                PhaseIdealLoop* phase, int flags) {
 860   PhaseIterGVN& igvn = phase->igvn();
 861   Node* old_ctrl = ctrl;
 862 
 863   Node* thread          = new ThreadLocalNode();
 864   Node* gc_state_offset = igvn.MakeConX(in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
 865   Node* gc_state_addr   = new AddPNode(phase->C->top(), thread, gc_state_offset);
 866   Node* gc_state        = new LoadBNode(old_ctrl, raw_mem, gc_state_addr,
 867                                         DEBUG_ONLY(phase->C->get_adr_type(Compile::AliasIdxRaw)) NOT_DEBUG(nullptr),
 868                                         TypeInt::BYTE, MemNode::unordered);
 869   Node* gc_state_and    = new AndINode(gc_state, igvn.intcon(flags));
 870   Node* gc_state_cmp    = new CmpINode(gc_state_and, igvn.zerocon(T_INT));
 871   Node* gc_state_bool   = new BoolNode(gc_state_cmp, BoolTest::ne);
 872 
 873   IfNode* gc_state_iff  = new IfNode(old_ctrl, gc_state_bool, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 874   ctrl                  = new IfTrueNode(gc_state_iff);
 875   test_fail_ctrl        = new IfFalseNode(gc_state_iff);
 876 
 877   IdealLoopTree* loop = phase->get_loop(old_ctrl);
 878   phase->register_control(gc_state_iff,   loop, old_ctrl);
 879   phase->register_control(ctrl,           loop, gc_state_iff);
 880   phase->register_control(test_fail_ctrl, loop, gc_state_iff);
 881 
 882   phase->register_new_node(thread,        old_ctrl);
 883   phase->register_new_node(gc_state_addr, old_ctrl);
 884   phase->register_new_node(gc_state,      old_ctrl);
 885   phase->register_new_node(gc_state_and,  old_ctrl);
 886   phase->register_new_node(gc_state_cmp,  old_ctrl);
 887   phase->register_new_node(gc_state_bool, old_ctrl);
 888 
 889   phase->set_ctrl(gc_state_offset, phase->C->root());
 890 
 891   assert(is_gc_state_test(gc_state_iff, flags), "Should match the shape");
 892 }
 893 
 894 void ShenandoahBarrierC2Support::test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase) {
 895   Node* old_ctrl = ctrl;
 896   PhaseIterGVN& igvn = phase->igvn();
 897 
 898   const Type* val_t = igvn.type(val);
 899   if (val_t->meet(TypePtr::NULL_PTR) == val_t) {
 900     Node* null_cmp   = new CmpPNode(val, igvn.zerocon(T_OBJECT));
 901     Node* null_test  = new BoolNode(null_cmp, BoolTest::ne);
 902 
 903     IfNode* null_iff = new IfNode(old_ctrl, null_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
 904     ctrl             = new IfTrueNode(null_iff);
 905     null_ctrl        = new IfFalseNode(null_iff);
 906 
 907     IdealLoopTree* loop = phase->get_loop(old_ctrl);
 908     phase->register_control(null_iff,  loop, old_ctrl);
 909     phase->register_control(ctrl,      loop, null_iff);
 910     phase->register_control(null_ctrl, loop, null_iff);
 911 
 912     phase->register_new_node(null_cmp,  old_ctrl);
 913     phase->register_new_node(null_test, old_ctrl);
 914   }
 915 }
 916 
 917 void ShenandoahBarrierC2Support::test_in_cset(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase) {
 918   Node* old_ctrl = ctrl;
 919   PhaseIterGVN& igvn = phase->igvn();
 920 
 921   Node* raw_val        = new CastP2XNode(old_ctrl, val);
 922   Node* cset_idx       = new URShiftXNode(raw_val, igvn.intcon(ShenandoahHeapRegion::region_size_bytes_shift_jint()));
 923 
 924   // Figure out the target cset address with raw pointer math.
 925   // This avoids matching AddP+LoadB that would emit inefficient code.
 926   // See JDK-8245465.
 927   Node* cset_addr_ptr  = igvn.makecon(TypeRawPtr::make(ShenandoahHeap::in_cset_fast_test_addr()));
 928   Node* cset_addr      = new CastP2XNode(old_ctrl, cset_addr_ptr);
 929   Node* cset_load_addr = new AddXNode(cset_addr, cset_idx);
 930   Node* cset_load_ptr  = new CastX2PNode(cset_load_addr);
 931 
 932   Node* cset_load      = new LoadBNode(old_ctrl, raw_mem, cset_load_ptr,
 933                                        DEBUG_ONLY(phase->C->get_adr_type(Compile::AliasIdxRaw)) NOT_DEBUG(nullptr),
 934                                        TypeInt::BYTE, MemNode::unordered);
 935   Node* cset_cmp       = new CmpINode(cset_load, igvn.zerocon(T_INT));
 936   Node* cset_bool      = new BoolNode(cset_cmp, BoolTest::ne);
 937 
 938   IfNode* cset_iff     = new IfNode(old_ctrl, cset_bool, PROB_UNLIKELY(0.999), COUNT_UNKNOWN);
 939   ctrl                 = new IfTrueNode(cset_iff);
 940   not_cset_ctrl        = new IfFalseNode(cset_iff);
 941 
 942   IdealLoopTree *loop = phase->get_loop(old_ctrl);
 943   phase->register_control(cset_iff,      loop, old_ctrl);
 944   phase->register_control(ctrl,          loop, cset_iff);
 945   phase->register_control(not_cset_ctrl, loop, cset_iff);
 946 
 947   phase->set_ctrl(cset_addr_ptr, phase->C->root());
 948 
 949   phase->register_new_node(raw_val,        old_ctrl);
 950   phase->register_new_node(cset_idx,       old_ctrl);
 951   phase->register_new_node(cset_addr,      old_ctrl);
 952   phase->register_new_node(cset_load_addr, old_ctrl);
 953   phase->register_new_node(cset_load_ptr,  old_ctrl);
 954   phase->register_new_node(cset_load,      old_ctrl);
 955   phase->register_new_node(cset_cmp,       old_ctrl);
 956   phase->register_new_node(cset_bool,      old_ctrl);
 957 }
 958 
 959 void ShenandoahBarrierC2Support::call_lrb_stub(Node*& ctrl, Node*& val, Node* load_addr,
 960                                                DecoratorSet decorators, PhaseIdealLoop* phase) {
 961   IdealLoopTree*loop = phase->get_loop(ctrl);
 962   const TypePtr* obj_type = phase->igvn().type(val)->is_oopptr();
 963 
 964   address calladdr = nullptr;
 965   const char* name = nullptr;
 966   bool is_strong  = ShenandoahBarrierSet::is_strong_access(decorators);
 967   bool is_weak    = ShenandoahBarrierSet::is_weak_access(decorators);
 968   bool is_phantom = ShenandoahBarrierSet::is_phantom_access(decorators);
 969   bool is_native  = ShenandoahBarrierSet::is_native_access(decorators);
 970   bool is_narrow  = UseCompressedOops && !is_native;
 971   if (is_strong) {
 972     if (is_narrow) {
 973       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong_narrow);
 974       name = "load_reference_barrier_strong_narrow";
 975     } else {
 976       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_strong);
 977       name = "load_reference_barrier_strong";
 978     }
 979   } else if (is_weak) {
 980     if (is_narrow) {
 981       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak_narrow);
 982       name = "load_reference_barrier_weak_narrow";
 983     } else {
 984       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_weak);
 985       name = "load_reference_barrier_weak";
 986     }
 987   } else {
 988     assert(is_phantom, "only remaining strength");
 989     if (is_narrow) {
 990       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom_narrow);
 991       name = "load_reference_barrier_phantom_narrow";
 992     } else {
 993       calladdr = CAST_FROM_FN_PTR(address, ShenandoahRuntime::load_reference_barrier_phantom);
 994       name = "load_reference_barrier_phantom";
 995     }
 996   }
 997   Node* call = new CallLeafNode(ShenandoahBarrierSetC2::shenandoah_load_reference_barrier_Type(), calladdr, name, TypeRawPtr::BOTTOM);
 998 
 999   call->init_req(TypeFunc::Control, ctrl);
1000   call->init_req(TypeFunc::I_O, phase->C->top());
1001   call->init_req(TypeFunc::Memory, phase->C->top());
1002   call->init_req(TypeFunc::FramePtr, phase->C->top());
1003   call->init_req(TypeFunc::ReturnAdr, phase->C->top());
1004   call->init_req(TypeFunc::Parms, val);
1005   call->init_req(TypeFunc::Parms+1, load_addr);
1006   phase->register_control(call, loop, ctrl);
1007   ctrl = new ProjNode(call, TypeFunc::Control);
1008   phase->register_control(ctrl, loop, call);
1009   val = new ProjNode(call, TypeFunc::Parms);
1010   phase->register_new_node(val, call);
1011   val = new CheckCastPPNode(ctrl, val, obj_type);
1012   phase->register_new_node(val, ctrl);
1013 }
1014 
1015 void ShenandoahBarrierC2Support::fix_ctrl(Node* barrier, Node* region, const MemoryGraphFixer& fixer, Unique_Node_List& uses, Unique_Node_List& uses_to_ignore, uint last, PhaseIdealLoop* phase) {
1016   Node* ctrl = phase->get_ctrl(barrier);
1017   Node* init_raw_mem = fixer.find_mem(ctrl, barrier);
1018 
1019   // Update the control of all nodes that should be after the
1020   // barrier control flow
1021   uses.clear();
1022   // Every node that is control dependent on the barrier's input
1023   // control will be after the expanded barrier. The raw memory (if
1024   // its memory is control dependent on the barrier's input control)
1025   // must stay above the barrier.
1026   uses_to_ignore.clear();
1027   if (phase->has_ctrl(init_raw_mem) && phase->get_ctrl(init_raw_mem) == ctrl && !init_raw_mem->is_Phi()) {
1028     uses_to_ignore.push(init_raw_mem);
1029   }
1030   for (uint next = 0; next < uses_to_ignore.size(); next++) {
1031     Node *n = uses_to_ignore.at(next);
1032     for (uint i = 0; i < n->req(); i++) {
1033       Node* in = n->in(i);
1034       if (in != nullptr && phase->has_ctrl(in) && phase->get_ctrl(in) == ctrl) {
1035         uses_to_ignore.push(in);
1036       }
1037     }
1038   }
1039   for (DUIterator_Fast imax, i = ctrl->fast_outs(imax); i < imax; i++) {
1040     Node* u = ctrl->fast_out(i);
1041     if (u->_idx < last &&
1042         u != barrier &&
1043         !uses_to_ignore.member(u) &&
1044         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1045         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1046       Node* old_c = phase->ctrl_or_self(u);
1047       Node* c = old_c;
1048       if (c != ctrl ||
1049           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1050           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1051         phase->igvn().rehash_node_delayed(u);
1052         int nb = u->replace_edge(ctrl, region, &phase->igvn());
1053         if (u->is_CFG()) {
1054           if (phase->idom(u) == ctrl) {
1055             phase->set_idom(u, region, phase->dom_depth(region));
1056           }
1057         } else if (phase->get_ctrl(u) == ctrl) {
1058           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1059           uses.push(u);
1060         }
1061         assert(nb == 1, "more than 1 ctrl input?");
1062         --i, imax -= nb;
1063       }
1064     }
1065   }
1066 }
1067 
1068 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections* projs, PhaseIdealLoop* phase) {
1069   Node* region = nullptr;
1070   while (c != ctrl) {
1071     if (c->is_Region()) {
1072       region = c;
1073     }
1074     c = phase->idom(c);
1075   }
1076   assert(region != nullptr, "");
1077   Node* phi = new PhiNode(region, n->bottom_type());
1078   for (uint j = 1; j < region->req(); j++) {
1079     Node* in = region->in(j);
1080     if (phase->is_dominator(projs->fallthrough_catchproj, in)) {
1081       phi->init_req(j, n);
1082     } else if (phase->is_dominator(projs->catchall_catchproj, in)) {
1083       phi->init_req(j, n_clone);
1084     } else {
1085       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1086     }
1087   }
1088   phase->register_new_node(phi, region);
1089   return phi;
1090 }
1091 
1092 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1093   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1094 
1095   Unique_Node_List uses;
1096   Node_Stack stack(0);
1097   Node_List clones;
1098   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1099     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1100 
1101     Node* ctrl = phase->get_ctrl(lrb);
1102     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1103 
1104     CallStaticJavaNode* unc = nullptr;
1105     Node* unc_ctrl = nullptr;
1106     Node* uncasted_val = val;
1107 
1108     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1109       Node* u = lrb->fast_out(i);
1110       if (u->Opcode() == Op_CastPP &&
1111           u->in(0) != nullptr &&
1112           phase->is_dominator(u->in(0), ctrl)) {
1113         const Type* u_t = phase->igvn().type(u);
1114 
1115         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1116             u->in(0)->Opcode() == Op_IfTrue &&
1117             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern() &&
1118             u->in(0)->in(0)->is_If() &&
1119             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1120             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1121             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1122             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1123             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1124           IdealLoopTree* loop = phase->get_loop(ctrl);
1125           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1126 
1127           if (!unc_loop->is_member(loop)) {
1128             continue;
1129           }
1130 
1131           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1132           assert(branch == nullptr || branch == NodeSentinel, "was not looking for a branch");
1133           if (branch == NodeSentinel) {
1134             continue;
1135           }
1136 
1137           Node* iff = u->in(0)->in(0);
1138           Node* bol = iff->in(1)->clone();
1139           Node* cmp = bol->in(1)->clone();
1140           cmp->set_req(1, lrb);
1141           bol->set_req(1, cmp);
1142           phase->igvn().replace_input_of(iff, 1, bol);
1143           phase->set_ctrl(lrb, iff->in(0));
1144           phase->register_new_node(cmp, iff->in(0));
1145           phase->register_new_node(bol, iff->in(0));
1146           break;
1147         }
1148       }
1149     }
1150     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1151       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1152       if (call->entry_point() == OptoRuntime::rethrow_stub()) {
1153         // The rethrow call may have too many projections to be
1154         // properly handled here. Given there's no reason for a
1155         // barrier to depend on the call, move it above the call
1156         stack.push(lrb, 0);
1157         do {
1158           Node* n = stack.node();
1159           uint idx = stack.index();
1160           if (idx < n->req()) {
1161             Node* in = n->in(idx);
1162             stack.set_index(idx+1);
1163             if (in != nullptr) {
1164               if (phase->has_ctrl(in)) {
1165                 if (phase->is_dominator(call, phase->get_ctrl(in))) {
1166 #ifdef ASSERT
1167                   for (uint i = 0; i < stack.size(); i++) {
1168                     assert(stack.node_at(i) != in, "node shouldn't have been seen yet");
1169                   }
1170 #endif
1171                   stack.push(in, 0);
1172                 }
1173               } else {
1174                 assert(phase->is_dominator(in, call->in(0)), "no dependency on the call");
1175               }
1176             }
1177           } else {
1178             phase->set_ctrl(n, call->in(0));
1179             stack.pop();
1180           }
1181         } while(stack.size() > 0);
1182         continue;
1183       }
1184       CallProjections* projs = call->extract_projections(false, false);
1185 #ifdef ASSERT
1186       VectorSet cloned;
1187 #endif
1188       Node* lrb_clone = lrb->clone();
1189       phase->register_new_node(lrb_clone, projs->catchall_catchproj);
1190       phase->set_ctrl(lrb, projs->fallthrough_catchproj);
1191 
1192       stack.push(lrb, 0);
1193       clones.push(lrb_clone);
1194 
1195       do {
1196         assert(stack.size() == clones.size(), "");
1197         Node* n = stack.node();
1198 #ifdef ASSERT
1199         if (n->is_Load()) {
1200           Node* mem = n->in(MemNode::Memory);
1201           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1202             Node* u = mem->fast_out(j);
1203             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1204           }
1205         }
1206 #endif
1207         uint idx = stack.index();
1208         Node* n_clone = clones.at(clones.size()-1);
1209         if (idx < n->outcnt()) {
1210           Node* u = n->raw_out(idx);
1211           Node* c = phase->ctrl_or_self(u);
1212           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs->fallthrough_proj)) {
1213             stack.set_index(idx+1);
1214             assert(!u->is_CFG(), "");
1215             stack.push(u, 0);
1216             assert(!cloned.test_set(u->_idx), "only one clone");
1217             Node* u_clone = u->clone();
1218             int nb = u_clone->replace_edge(n, n_clone, &phase->igvn());
1219             assert(nb > 0, "should have replaced some uses");
1220             phase->register_new_node(u_clone, projs->catchall_catchproj);
1221             clones.push(u_clone);
1222             phase->set_ctrl(u, projs->fallthrough_catchproj);
1223           } else {
1224             bool replaced = false;
1225             if (u->is_Phi()) {
1226               for (uint k = 1; k < u->req(); k++) {
1227                 if (u->in(k) == n) {
1228                   if (phase->is_dominator(projs->catchall_catchproj, u->in(0)->in(k))) {
1229                     phase->igvn().replace_input_of(u, k, n_clone);
1230                     replaced = true;
1231                   } else if (!phase->is_dominator(projs->fallthrough_catchproj, u->in(0)->in(k))) {
1232                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1233                     replaced = true;
1234                   }
1235                 }
1236               }
1237             } else {
1238               if (phase->is_dominator(projs->catchall_catchproj, c)) {
1239                 phase->igvn().rehash_node_delayed(u);
1240                 int nb = u->replace_edge(n, n_clone, &phase->igvn());
1241                 assert(nb > 0, "should have replaced some uses");
1242                 replaced = true;
1243               } else if (!phase->is_dominator(projs->fallthrough_catchproj, c)) {
1244                 if (u->is_If()) {
1245                   // Can't break If/Bool/Cmp chain
1246                   assert(n->is_Bool(), "unexpected If shape");
1247                   assert(stack.node_at(stack.size()-2)->is_Cmp(), "unexpected If shape");
1248                   assert(n_clone->is_Bool(), "unexpected clone");
1249                   assert(clones.at(clones.size()-2)->is_Cmp(), "unexpected clone");
1250                   Node* bol_clone = n->clone();
1251                   Node* cmp_clone = stack.node_at(stack.size()-2)->clone();
1252                   bol_clone->set_req(1, cmp_clone);
1253 
1254                   Node* nn = stack.node_at(stack.size()-3);
1255                   Node* nn_clone = clones.at(clones.size()-3);
1256                   assert(nn->Opcode() == nn_clone->Opcode(), "mismatch");
1257 
1258                   int nb = cmp_clone->replace_edge(nn, create_phis_on_call_return(ctrl, c, nn, nn_clone, projs, phase),
1259                                                    &phase->igvn());
1260                   assert(nb > 0, "should have replaced some uses");
1261 
1262                   phase->register_new_node(bol_clone, u->in(0));
1263                   phase->register_new_node(cmp_clone, u->in(0));
1264 
1265                   phase->igvn().replace_input_of(u, 1, bol_clone);
1266 
1267                 } else {
1268                   phase->igvn().rehash_node_delayed(u);
1269                   int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase), &phase->igvn());
1270                   assert(nb > 0, "should have replaced some uses");
1271                 }
1272                 replaced = true;
1273               }
1274             }
1275             if (!replaced) {
1276               stack.set_index(idx+1);
1277             }
1278           }
1279         } else {
1280           stack.pop();
1281           clones.pop();
1282         }
1283       } while (stack.size() > 0);
1284       assert(stack.size() == 0 && clones.size() == 0, "");
1285     }
1286   }
1287 
1288   for (int i = 0; i < state->load_reference_barriers_count(); i++) {
1289     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1290     Node* ctrl = phase->get_ctrl(lrb);
1291     IdealLoopTree* loop = phase->get_loop(ctrl);
1292     Node* head = loop->head();
1293     if (head->is_OuterStripMinedLoop()) {
1294       // Expanding a barrier here will break loop strip mining
1295       // verification. Transform the loop so the loop nest doesn't
1296       // appear as strip mined.
1297       OuterStripMinedLoopNode* outer = head->as_OuterStripMinedLoop();
1298       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1299     }
1300     if (head->is_BaseCountedLoop() && ctrl->is_IfProj() && ctrl->in(0)->is_BaseCountedLoopEnd() &&
1301         head->as_BaseCountedLoop()->loopexit() == ctrl->in(0)) {
1302       Node* entry = head->in(LoopNode::EntryControl);
1303       Node* backedge = head->in(LoopNode::LoopBackControl);
1304       Node* new_head = new LoopNode(entry, backedge);
1305       phase->register_control(new_head, phase->get_loop(entry), entry);
1306       phase->lazy_replace(head, new_head);
1307     }
1308   }
1309 
1310   // Expand load-reference-barriers
1311   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1312   Unique_Node_List uses_to_ignore;
1313   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1314     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1315     uint last = phase->C->unique();
1316     Node* ctrl = phase->get_ctrl(lrb);
1317     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1318 
1319     Node* orig_ctrl = ctrl;
1320 
1321     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1322     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, nullptr);
1323 
1324     IdealLoopTree *loop = phase->get_loop(ctrl);
1325 
1326     Node* heap_stable_ctrl = nullptr;
1327     Node* null_ctrl = nullptr;
1328 
1329     assert(val->bottom_type()->make_oopptr(), "need oop");
1330     assert(val->bottom_type()->make_oopptr()->const_oop() == nullptr, "expect non-constant");
1331 
1332     enum { _heap_stable = 1, _evac_path, _not_cset, PATH_LIMIT };
1333     Node* region = new RegionNode(PATH_LIMIT);
1334     Node* val_phi = new PhiNode(region, val->bottom_type()->is_oopptr());
1335 
1336     // Stable path.
1337     int flags = ShenandoahHeap::HAS_FORWARDED;
1338     if (!ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1339       flags |= ShenandoahHeap::WEAK_ROOTS;
1340     }
1341     test_gc_state(ctrl, raw_mem, heap_stable_ctrl, phase, flags);
1342     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1343 
1344     // Heap stable case
1345     region->init_req(_heap_stable, heap_stable_ctrl);
1346     val_phi->init_req(_heap_stable, val);
1347 
1348     // Test for in-cset, unless it's a native-LRB. Native LRBs need to return null
1349     // even for non-cset objects to prevent resurrection of such objects.
1350     // Wires !in_cset(obj) to slot 2 of region and phis
1351     Node* not_cset_ctrl = nullptr;
1352     if (ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1353       test_in_cset(ctrl, not_cset_ctrl, val, raw_mem, phase);
1354     }
1355     if (not_cset_ctrl != nullptr) {
1356       region->init_req(_not_cset, not_cset_ctrl);
1357       val_phi->init_req(_not_cset, val);
1358     } else {
1359       region->del_req(_not_cset);
1360       val_phi->del_req(_not_cset);
1361     }
1362 
1363     // Resolve object when orig-value is in cset.
1364     // Make the unconditional resolve for fwdptr.
1365 
1366     // Call lrb-stub and wire up that path in slots 4
1367     Node* result_mem = nullptr;
1368 
1369     Node* addr;
1370     {
1371       VectorSet visited;
1372       addr = get_load_addr(phase, visited, lrb);
1373     }
1374     if (addr->Opcode() == Op_AddP) {
1375       Node* orig_base = addr->in(AddPNode::Base);
1376       Node* base = new CheckCastPPNode(ctrl, orig_base, orig_base->bottom_type(), ConstraintCastNode::StrongDependency);
1377       phase->register_new_node(base, ctrl);
1378       if (addr->in(AddPNode::Base) == addr->in((AddPNode::Address))) {
1379         // Field access
1380         addr = addr->clone();
1381         addr->set_req(AddPNode::Base, base);
1382         addr->set_req(AddPNode::Address, base);
1383         phase->register_new_node(addr, ctrl);
1384       } else {
1385         Node* addr2 = addr->in(AddPNode::Address);
1386         if (addr2->Opcode() == Op_AddP && addr2->in(AddPNode::Base) == addr2->in(AddPNode::Address) &&
1387               addr2->in(AddPNode::Base) == orig_base) {
1388           addr2 = addr2->clone();
1389           addr2->set_req(AddPNode::Base, base);
1390           addr2->set_req(AddPNode::Address, base);
1391           phase->register_new_node(addr2, ctrl);
1392           addr = addr->clone();
1393           addr->set_req(AddPNode::Base, base);
1394           addr->set_req(AddPNode::Address, addr2);
1395           phase->register_new_node(addr, ctrl);
1396         }
1397       }
1398     }
1399     call_lrb_stub(ctrl, val, addr, lrb->decorators(), phase);
1400     region->init_req(_evac_path, ctrl);
1401     val_phi->init_req(_evac_path, val);
1402 
1403     phase->register_control(region, loop, heap_stable_iff);
1404     Node* out_val = val_phi;
1405     phase->register_new_node(val_phi, region);
1406 
1407     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1408 
1409     ctrl = orig_ctrl;
1410 
1411     phase->igvn().replace_node(lrb, out_val);
1412 
1413     follow_barrier_uses(out_val, ctrl, uses, phase);
1414 
1415     for(uint next = 0; next < uses.size(); next++ ) {
1416       Node *n = uses.at(next);
1417       assert(phase->get_ctrl(n) == ctrl, "bad control");
1418       assert(n != raw_mem, "should leave input raw mem above the barrier");
1419       phase->set_ctrl(n, region);
1420       follow_barrier_uses(n, ctrl, uses, phase);
1421     }
1422     fixer.record_new_ctrl(ctrl, region, raw_mem, raw_mem_for_ctrl);
1423   }
1424   // Done expanding load-reference-barriers.
1425   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1426 }
1427 
1428 Node* ShenandoahBarrierC2Support::get_load_addr(PhaseIdealLoop* phase, VectorSet& visited, Node* in) {
1429   if (visited.test_set(in->_idx)) {
1430     return nullptr;
1431   }
1432   switch (in->Opcode()) {
1433     case Op_Proj:
1434       return get_load_addr(phase, visited, in->in(0));
1435     case Op_CastPP:
1436     case Op_CheckCastPP:
1437     case Op_DecodeN:
1438     case Op_EncodeP:
1439       return get_load_addr(phase, visited, in->in(1));
1440     case Op_LoadN:
1441     case Op_LoadP:
1442       return in->in(MemNode::Address);
1443     case Op_CompareAndExchangeN:
1444     case Op_CompareAndExchangeP:
1445     case Op_GetAndSetN:
1446     case Op_GetAndSetP:
1447     case Op_ShenandoahCompareAndExchangeP:
1448     case Op_ShenandoahCompareAndExchangeN:
1449       // Those instructions would just have stored a different
1450       // value into the field. No use to attempt to fix it at this point.
1451       return phase->igvn().zerocon(T_OBJECT);
1452     case Op_CMoveP:
1453     case Op_CMoveN: {
1454       Node* t = get_load_addr(phase, visited, in->in(CMoveNode::IfTrue));
1455       Node* f = get_load_addr(phase, visited, in->in(CMoveNode::IfFalse));
1456       // Handle unambiguous cases: single address reported on both branches.
1457       if (t != nullptr && f == nullptr) return t;
1458       if (t == nullptr && f != nullptr) return f;
1459       if (t != nullptr && t == f)    return t;
1460       // Ambiguity.
1461       return phase->igvn().zerocon(T_OBJECT);
1462     }
1463     case Op_Phi: {
1464       Node* addr = nullptr;
1465       for (uint i = 1; i < in->req(); i++) {
1466         Node* addr1 = get_load_addr(phase, visited, in->in(i));
1467         if (addr == nullptr) {
1468           addr = addr1;
1469         }
1470         if (addr != addr1) {
1471           return phase->igvn().zerocon(T_OBJECT);
1472         }
1473       }
1474       return addr;
1475     }
1476     case Op_ShenandoahLoadReferenceBarrier:
1477       return get_load_addr(phase, visited, in->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1478     case Op_CallDynamicJava:
1479     case Op_CallLeaf:
1480     case Op_CallStaticJava:
1481     case Op_ConN:
1482     case Op_ConP:
1483     case Op_Parm:
1484     case Op_CreateEx:
1485       return phase->igvn().zerocon(T_OBJECT);
1486     default:
1487 #ifdef ASSERT
1488       fatal("Unknown node in get_load_addr: %s", NodeClassNames[in->Opcode()]);
1489 #endif
1490       return phase->igvn().zerocon(T_OBJECT);
1491   }
1492 
1493 }
1494 
1495 void ShenandoahBarrierC2Support::move_gc_state_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1496   IdealLoopTree *loop = phase->get_loop(iff);
1497   Node* loop_head = loop->_head;
1498   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1499 
1500   Node* bol = iff->in(1);
1501   Node* cmp = bol->in(1);
1502   Node* andi = cmp->in(1);
1503   Node* load = andi->in(1);
1504 
1505   assert(is_gc_state_load(load), "broken");
1506   if (!phase->is_dominator(load->in(0), entry_c)) {
1507     Node* mem_ctrl = nullptr;
1508     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1509     load = load->clone();
1510     load->set_req(MemNode::Memory, mem);
1511     load->set_req(0, entry_c);
1512     phase->register_new_node(load, entry_c);
1513     andi = andi->clone();
1514     andi->set_req(1, load);
1515     phase->register_new_node(andi, entry_c);
1516     cmp = cmp->clone();
1517     cmp->set_req(1, andi);
1518     phase->register_new_node(cmp, entry_c);
1519     bol = bol->clone();
1520     bol->set_req(1, cmp);
1521     phase->register_new_node(bol, entry_c);
1522 
1523     phase->igvn().replace_input_of(iff, 1, bol);
1524   }
1525 }
1526 
1527 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1528   if (!n->is_If() || n->is_CountedLoopEnd()) {
1529     return false;
1530   }
1531   Node* region = n->in(0);
1532 
1533   if (!region->is_Region()) {
1534     return false;
1535   }
1536   Node* dom = phase->idom(region);
1537   if (!dom->is_If()) {
1538     return false;
1539   }
1540 
1541   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1542     return false;
1543   }
1544 
1545   IfNode* dom_if = dom->as_If();
1546   Node* proj_true = dom_if->proj_out(1);
1547   Node* proj_false = dom_if->proj_out(0);
1548 
1549   for (uint i = 1; i < region->req(); i++) {
1550     if (phase->is_dominator(proj_true, region->in(i))) {
1551       continue;
1552     }
1553     if (phase->is_dominator(proj_false, region->in(i))) {
1554       continue;
1555     }
1556     return false;
1557   }
1558 
1559   return true;
1560 }
1561 
1562 bool ShenandoahBarrierC2Support::merge_point_safe(Node* region) {
1563   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1564     Node* n = region->fast_out(i);
1565     if (n->is_LoadStore()) {
1566       // Splitting a LoadStore node through phi, causes it to lose its SCMemProj: the split if code doesn't have support
1567       // for a LoadStore at the region the if is split through because that's not expected to happen (LoadStore nodes
1568       // should be between barrier nodes). It does however happen with Shenandoah though because barriers can get
1569       // expanded around a LoadStore node.
1570       return false;
1571     }
1572   }
1573   return true;
1574 }
1575 
1576 
1577 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1578   assert(is_heap_stable_test(n), "no other tests");
1579   if (identical_backtoback_ifs(n, phase)) {
1580     Node* n_ctrl = n->in(0);
1581     if (phase->can_split_if(n_ctrl) && merge_point_safe(n_ctrl)) {
1582       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1583       if (is_heap_stable_test(n)) {
1584         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1585         assert(is_gc_state_load(gc_state_load), "broken");
1586         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1587         assert(is_gc_state_load(dom_gc_state_load), "broken");
1588         if (gc_state_load != dom_gc_state_load) {
1589           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1590         }
1591       }
1592       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1593       Node* proj_true = dom_if->proj_out(1);
1594       Node* proj_false = dom_if->proj_out(0);
1595       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1596       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1597 
1598       for (uint i = 1; i < n_ctrl->req(); i++) {
1599         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1600           bolphi->init_req(i, con_true);
1601         } else {
1602           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1603           bolphi->init_req(i, con_false);
1604         }
1605       }
1606       phase->register_new_node(bolphi, n_ctrl);
1607       phase->igvn().replace_input_of(n, 1, bolphi);
1608       phase->do_split_if(n);
1609     }
1610   }
1611 }
1612 
1613 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1614   // Find first invariant test that doesn't exit the loop
1615   LoopNode *head = loop->_head->as_Loop();
1616   IfNode* unswitch_iff = nullptr;
1617   Node* n = head->in(LoopNode::LoopBackControl);
1618   int loop_has_sfpts = -1;
1619   while (n != head) {
1620     Node* n_dom = phase->idom(n);
1621     if (n->is_Region()) {
1622       if (n_dom->is_If()) {
1623         IfNode* iff = n_dom->as_If();
1624         if (iff->in(1)->is_Bool()) {
1625           BoolNode* bol = iff->in(1)->as_Bool();
1626           if (bol->in(1)->is_Cmp()) {
1627             // If condition is invariant and not a loop exit,
1628             // then found reason to unswitch.
1629             if (is_heap_stable_test(iff) &&
1630                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1631               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1632               if (loop_has_sfpts == -1) {
1633                 for(uint i = 0; i < loop->_body.size(); i++) {
1634                   Node *m = loop->_body[i];
1635                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1636                     loop_has_sfpts = 1;
1637                     break;
1638                   }
1639                 }
1640                 if (loop_has_sfpts == -1) {
1641                   loop_has_sfpts = 0;
1642                 }
1643               }
1644               if (!loop_has_sfpts) {
1645                 unswitch_iff = iff;
1646               }
1647             }
1648           }
1649         }
1650       }
1651     }
1652     n = n_dom;
1653   }
1654   return unswitch_iff;
1655 }
1656 
1657 
1658 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1659   Node_List heap_stable_tests;
1660   stack.push(phase->C->start(), 0);
1661   do {
1662     Node* n = stack.node();
1663     uint i = stack.index();
1664 
1665     if (i < n->outcnt()) {
1666       Node* u = n->raw_out(i);
1667       stack.set_index(i+1);
1668       if (!visited.test_set(u->_idx)) {
1669         stack.push(u, 0);
1670       }
1671     } else {
1672       stack.pop();
1673       if (n->is_If() && is_heap_stable_test(n)) {
1674         heap_stable_tests.push(n);
1675       }
1676     }
1677   } while (stack.size() > 0);
1678 
1679   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1680     Node* n = heap_stable_tests.at(i);
1681     assert(is_heap_stable_test(n), "only evacuation test");
1682     merge_back_to_back_tests(n, phase);
1683   }
1684 
1685   if (!phase->C->major_progress()) {
1686     VectorSet seen;
1687     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1688       Node* n = heap_stable_tests.at(i);
1689       IdealLoopTree* loop = phase->get_loop(n);
1690       if (loop != phase->ltree_root() &&
1691           loop->_child == nullptr &&
1692           !loop->_irreducible) {
1693         Node* head = loop->_head;
1694         if (head->is_Loop() &&
1695             (!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1696             !seen.test_set(head->_idx)) {
1697           IfNode* iff = find_unswitching_candidate(loop, phase);
1698           if (iff != nullptr) {
1699             Node* bol = iff->in(1);
1700             if (head->as_Loop()->is_strip_mined()) {
1701               head->as_Loop()->verify_strip_mined(0);
1702             }
1703             move_gc_state_test_out_of_loop(iff, phase);
1704 
1705             AutoNodeBudget node_budget(phase);
1706 
1707             if (loop->policy_unswitching(phase)) {
1708               if (head->as_Loop()->is_strip_mined()) {
1709                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1710                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1711               }
1712               phase->do_unswitching(loop, old_new);
1713             } else {
1714               // Not proceeding with unswitching. Move load back in
1715               // the loop.
1716               phase->igvn().replace_input_of(iff, 1, bol);
1717             }
1718           }
1719         }
1720       }
1721     }
1722   }
1723 }
1724 
1725 #ifdef ASSERT
1726 static bool has_never_branch(Node* root) {
1727   for (uint i = 1; i < root->req(); i++) {
1728     Node* in = root->in(i);
1729     if (in != nullptr && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->is_NeverBranch()) {
1730       return true;
1731     }
1732   }
1733   return false;
1734 }
1735 #endif
1736 
1737 void MemoryGraphFixer::collect_memory_nodes() {
1738   Node_Stack stack(0);
1739   VectorSet visited;
1740   Node_List regions;
1741 
1742   // Walk the raw memory graph and create a mapping from CFG node to
1743   // memory node. Exclude phis for now.
1744   stack.push(_phase->C->root(), 1);
1745   do {
1746     Node* n = stack.node();
1747     int opc = n->Opcode();
1748     uint i = stack.index();
1749     if (i < n->req()) {
1750       Node* mem = nullptr;
1751       if (opc == Op_Root) {
1752         Node* in = n->in(i);
1753         int in_opc = in->Opcode();
1754         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
1755           mem = in->in(TypeFunc::Memory);
1756         } else if (in_opc == Op_Halt) {
1757           if (in->in(0)->is_Region()) {
1758             Node* r = in->in(0);
1759             for (uint j = 1; j < r->req(); j++) {
1760               assert(!r->in(j)->is_NeverBranch(), "");
1761             }
1762           } else {
1763             Node* proj = in->in(0);
1764             assert(proj->is_Proj(), "");
1765             Node* in = proj->in(0);
1766             assert(in->is_CallStaticJava() || in->is_NeverBranch() || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
1767             if (in->is_CallStaticJava()) {
1768               mem = in->in(TypeFunc::Memory);
1769             } else if (in->Opcode() == Op_Catch) {
1770               Node* call = in->in(0)->in(0);
1771               assert(call->is_Call(), "");
1772               mem = call->in(TypeFunc::Memory);
1773             } else if (in->is_NeverBranch()) {
1774               mem = collect_memory_for_infinite_loop(in);
1775             }
1776           }
1777         } else {
1778 #ifdef ASSERT
1779           n->dump();
1780           in->dump();
1781 #endif
1782           ShouldNotReachHere();
1783         }
1784       } else {
1785         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
1786         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
1787         mem = n->in(i);
1788       }
1789       i++;
1790       stack.set_index(i);
1791       if (mem == nullptr) {
1792         continue;
1793       }
1794       for (;;) {
1795         if (visited.test_set(mem->_idx) || mem->is_Start()) {
1796           break;
1797         }
1798         if (mem->is_Phi()) {
1799           stack.push(mem, 2);
1800           mem = mem->in(1);
1801         } else if (mem->is_Proj()) {
1802           stack.push(mem, mem->req());
1803           mem = mem->in(0);
1804         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
1805           mem = mem->in(TypeFunc::Memory);
1806         } else if (mem->is_MergeMem()) {
1807           MergeMemNode* mm = mem->as_MergeMem();
1808           mem = mm->memory_at(_alias);
1809         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
1810           assert(_alias == Compile::AliasIdxRaw, "");
1811           stack.push(mem, mem->req());
1812           mem = mem->in(MemNode::Memory);
1813         } else {
1814 #ifdef ASSERT
1815           mem->dump();
1816 #endif
1817           ShouldNotReachHere();
1818         }
1819       }
1820     } else {
1821       if (n->is_Phi()) {
1822         // Nothing
1823       } else if (!n->is_Root()) {
1824         Node* c = get_ctrl(n);
1825         _memory_nodes.map(c->_idx, n);
1826       }
1827       stack.pop();
1828     }
1829   } while(stack.is_nonempty());
1830 
1831   // Iterate over CFG nodes in rpo and propagate memory state to
1832   // compute memory state at regions, creating new phis if needed.
1833   Node_List rpo_list;
1834   visited.clear();
1835   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
1836   Node* root = rpo_list.pop();
1837   assert(root == _phase->C->root(), "");
1838 
1839   const bool trace = false;
1840 #ifdef ASSERT
1841   if (trace) {
1842     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1843       Node* c = rpo_list.at(i);
1844       if (_memory_nodes[c->_idx] != nullptr) {
1845         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
1846       }
1847     }
1848   }
1849 #endif
1850   uint last = _phase->C->unique();
1851 
1852 #ifdef ASSERT
1853   uint16_t max_depth = 0;
1854   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
1855     IdealLoopTree* lpt = iter.current();
1856     max_depth = MAX2(max_depth, lpt->_nest);
1857   }
1858 #endif
1859 
1860   bool progress = true;
1861   int iteration = 0;
1862   Node_List dead_phis;
1863   while (progress) {
1864     progress = false;
1865     iteration++;
1866     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1867     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
1868 
1869     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1870       Node* c = rpo_list.at(i);
1871 
1872       Node* prev_mem = _memory_nodes[c->_idx];
1873       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1874         Node* prev_region = regions[c->_idx];
1875         Node* unique = nullptr;
1876         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
1877           Node* m = _memory_nodes[c->in(j)->_idx];
1878           assert(m != nullptr || (c->is_Loop() && j == LoopNode::LoopBackControl && iteration == 1) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "expect memory state");
1879           if (m != nullptr) {
1880             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
1881               assert((c->is_Loop() && j == LoopNode::LoopBackControl) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1882               // continue
1883             } else if (unique == nullptr) {
1884               unique = m;
1885             } else if (m == unique) {
1886               // continue
1887             } else {
1888               unique = NodeSentinel;
1889             }
1890           }
1891         }
1892         assert(unique != nullptr, "empty phi???");
1893         if (unique != NodeSentinel) {
1894           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c) {
1895             dead_phis.push(prev_region);
1896           }
1897           regions.map(c->_idx, unique);
1898         } else {
1899           Node* phi = nullptr;
1900           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
1901             phi = prev_region;
1902             for (uint k = 1; k < c->req(); k++) {
1903               Node* m = _memory_nodes[c->in(k)->_idx];
1904               assert(m != nullptr, "expect memory state");
1905               phi->set_req(k, m);
1906             }
1907           } else {
1908             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == nullptr; j++) {
1909               Node* u = c->fast_out(j);
1910               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1911                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
1912                 phi = u;
1913                 for (uint k = 1; k < c->req() && phi != nullptr; k++) {
1914                   Node* m = _memory_nodes[c->in(k)->_idx];
1915                   assert(m != nullptr, "expect memory state");
1916                   if (u->in(k) != m) {
1917                     phi = NodeSentinel;
1918                   }
1919                 }
1920               }
1921             }
1922             if (phi == NodeSentinel) {
1923               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
1924               for (uint k = 1; k < c->req(); k++) {
1925                 Node* m = _memory_nodes[c->in(k)->_idx];
1926                 assert(m != nullptr, "expect memory state");
1927                 phi->init_req(k, m);
1928               }
1929             }
1930           }
1931           if (phi != nullptr) {
1932             regions.map(c->_idx, phi);
1933           } else {
1934             assert(c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1935           }
1936         }
1937         Node* current_region = regions[c->_idx];
1938         if (current_region != prev_region) {
1939           progress = true;
1940           if (prev_region == prev_mem) {
1941             _memory_nodes.map(c->_idx, current_region);
1942           }
1943         }
1944       } else if (prev_mem == nullptr || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
1945         Node* m = _memory_nodes[_phase->idom(c)->_idx];
1946         assert(m != nullptr || c->Opcode() == Op_Halt, "expect memory state");
1947         if (m != prev_mem) {
1948           _memory_nodes.map(c->_idx, m);
1949           progress = true;
1950         }
1951       }
1952 #ifdef ASSERT
1953       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
1954 #endif
1955     }
1956   }
1957 
1958   // Replace existing phi with computed memory state for that region
1959   // if different (could be a new phi or a dominating memory node if
1960   // that phi was found to be useless).
1961   while (dead_phis.size() > 0) {
1962     Node* n = dead_phis.pop();
1963     n->replace_by(_phase->C->top());
1964     n->destruct(&_phase->igvn());
1965   }
1966   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1967     Node* c = rpo_list.at(i);
1968     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1969       Node* n = regions[c->_idx];
1970       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1971       if (n != nullptr && n->is_Phi() && n->_idx >= last && n->in(0) == c) {
1972         _phase->register_new_node(n, c);
1973       }
1974     }
1975   }
1976   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1977     Node* c = rpo_list.at(i);
1978     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1979       Node* n = regions[c->_idx];
1980       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1981       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
1982         Node* u = c->fast_out(i);
1983         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1984             u != n) {
1985           assert(c->unique_ctrl_out()->Opcode() != Op_Halt, "expected memory state");
1986           if (u->adr_type() == TypePtr::BOTTOM) {
1987             fix_memory_uses(u, n, n, c);
1988           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
1989             _phase->lazy_replace(u, n);
1990             --i; --imax;
1991           }
1992         }
1993       }
1994     }
1995   }
1996 }
1997 
1998 Node* MemoryGraphFixer::collect_memory_for_infinite_loop(const Node* in) {
1999   Node* mem = nullptr;
2000   Node* head = in->in(0);
2001   assert(head->is_Region(), "unexpected infinite loop graph shape");
2002 
2003   Node* phi_mem = nullptr;
2004   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
2005     Node* u = head->fast_out(j);
2006     if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
2007       if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2008         assert(phi_mem == nullptr || phi_mem->adr_type() == TypePtr::BOTTOM, "");
2009         phi_mem = u;
2010       } else if (u->adr_type() == TypePtr::BOTTOM) {
2011         assert(phi_mem == nullptr || _phase->C->get_alias_index(phi_mem->adr_type()) == _alias, "");
2012         if (phi_mem == nullptr) {
2013           phi_mem = u;
2014         }
2015       }
2016     }
2017   }
2018   if (phi_mem == nullptr) {
2019     ResourceMark rm;
2020     Node_Stack stack(0);
2021     stack.push(head, 1);
2022     do {
2023       Node* n = stack.node();
2024       uint i = stack.index();
2025       if (i >= n->req()) {
2026         stack.pop();
2027       } else {
2028         stack.set_index(i + 1);
2029         Node* c = n->in(i);
2030         assert(c != head, "should have found a safepoint on the way");
2031         if (stack.size() != 1 || _phase->is_dominator(head, c)) {
2032           for (;;) {
2033             if (c->is_Region()) {
2034               stack.push(c, 1);
2035               break;
2036             } else if (c->is_SafePoint() && !c->is_CallLeaf()) {
2037               Node* m = c->in(TypeFunc::Memory);
2038               if (m->is_MergeMem()) {
2039                 m = m->as_MergeMem()->memory_at(_alias);
2040               }
2041               assert(mem == nullptr || mem == m, "several memory states");
2042               mem = m;
2043               break;
2044             } else {
2045               assert(c != c->in(0), "");
2046               c = c->in(0);
2047             }
2048           }
2049         }
2050       }
2051     } while (stack.size() > 0);
2052     assert(mem != nullptr, "should have found safepoint");
2053   } else {
2054     mem = phi_mem;
2055   }
2056   return mem;
2057 }
2058 
2059 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2060   Node* c = _phase->get_ctrl(n);
2061   if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Call()) {
2062     assert(c == n->in(0), "");
2063     CallNode* call = c->as_Call();
2064     CallProjections* projs = call->extract_projections(true, false);
2065     if (projs->catchall_memproj != nullptr) {
2066       if (projs->fallthrough_memproj == n) {
2067         c = projs->fallthrough_catchproj;
2068       } else {
2069         assert(projs->catchall_memproj == n, "");
2070         c = projs->catchall_catchproj;
2071       }
2072     }
2073   }
2074   return c;
2075 }
2076 
2077 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2078   if (_phase->has_ctrl(n))
2079     return get_ctrl(n);
2080   else {
2081     assert (n->is_CFG(), "must be a CFG node");
2082     return n;
2083   }
2084 }
2085 
2086 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2087   return m != nullptr && get_ctrl(m) == c;
2088 }
2089 
2090 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2091   assert(n == nullptr || _phase->ctrl_or_self(n) == ctrl, "");
2092   assert(!ctrl->is_Call() || ctrl == n, "projection expected");
2093 #ifdef ASSERT
2094   if ((ctrl->is_Proj() && ctrl->in(0)->is_Call()) ||
2095       (ctrl->is_Catch() && ctrl->in(0)->in(0)->is_Call())) {
2096     CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_Call() : ctrl->in(0)->in(0)->as_Call();
2097     int mems = 0;
2098     for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
2099       Node* u = call->fast_out(i);
2100       if (u->bottom_type() == Type::MEMORY) {
2101         mems++;
2102       }
2103     }
2104     assert(mems <= 1, "No node right after call if multiple mem projections");
2105   }
2106 #endif
2107   Node* mem = _memory_nodes[ctrl->_idx];
2108   Node* c = ctrl;
2109   while (!mem_is_valid(mem, c) &&
2110          (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2111     c = _phase->idom(c);
2112     mem = _memory_nodes[c->_idx];
2113   }
2114   if (n != nullptr && mem_is_valid(mem, c)) {
2115     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2116       mem = next_mem(mem, _alias);
2117     }
2118     if (mem->is_MergeMem()) {
2119       mem = mem->as_MergeMem()->memory_at(_alias);
2120     }
2121     if (!mem_is_valid(mem, c)) {
2122       do {
2123         c = _phase->idom(c);
2124         mem = _memory_nodes[c->_idx];
2125       } while (!mem_is_valid(mem, c) &&
2126                (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2127     }
2128   }
2129   assert(mem->bottom_type() == Type::MEMORY, "");
2130   return mem;
2131 }
2132 
2133 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2134   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2135     Node* use = region->fast_out(i);
2136     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2137         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2138       return true;
2139     }
2140   }
2141   return false;
2142 }
2143 
2144 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2145   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2146   const bool trace = false;
2147   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2148   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2149   GrowableArray<Node*> phis;
2150   if (mem_for_ctrl != mem) {
2151     Node* old = mem_for_ctrl;
2152     Node* prev = nullptr;
2153     while (old != mem) {
2154       prev = old;
2155       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2156         assert(_alias == Compile::AliasIdxRaw, "");
2157         old = old->in(MemNode::Memory);
2158       } else if (old->Opcode() == Op_SCMemProj) {
2159         assert(_alias == Compile::AliasIdxRaw, "");
2160         old = old->in(0);
2161       } else {
2162         ShouldNotReachHere();
2163       }
2164     }
2165     assert(prev != nullptr, "");
2166     if (new_ctrl != ctrl) {
2167       _memory_nodes.map(ctrl->_idx, mem);
2168       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2169     }
2170     uint input = (uint)MemNode::Memory;
2171     _phase->igvn().replace_input_of(prev, input, new_mem);
2172   } else {
2173     uses.clear();
2174     _memory_nodes.map(new_ctrl->_idx, new_mem);
2175     uses.push(new_ctrl);
2176     for(uint next = 0; next < uses.size(); next++ ) {
2177       Node *n = uses.at(next);
2178       assert(n->is_CFG(), "");
2179       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2180       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2181         Node* u = n->fast_out(i);
2182         if (!u->is_Root() && u->is_CFG() && u != n) {
2183           Node* m = _memory_nodes[u->_idx];
2184           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2185               !has_mem_phi(u) &&
2186               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2187             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2188             DEBUG_ONLY(if (trace && m != nullptr) { tty->print("ZZZ mem"); m->dump(); });
2189 
2190             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2191               bool push = true;
2192               bool create_phi = true;
2193               if (_phase->is_dominator(new_ctrl, u)) {
2194                 create_phi = false;
2195               }
2196               if (create_phi) {
2197                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2198                 _phase->register_new_node(phi, u);
2199                 phis.push(phi);
2200                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2201                 if (!mem_is_valid(m, u)) {
2202                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2203                   _memory_nodes.map(u->_idx, phi);
2204                 } else {
2205                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2206                   for (;;) {
2207                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2208                     Node* next = nullptr;
2209                     if (m->is_Proj()) {
2210                       next = m->in(0);
2211                     } else {
2212                       assert(m->is_Mem() || m->is_LoadStore(), "");
2213                       assert(_alias == Compile::AliasIdxRaw, "");
2214                       next = m->in(MemNode::Memory);
2215                     }
2216                     if (_phase->get_ctrl(next) != u) {
2217                       break;
2218                     }
2219                     if (next->is_MergeMem()) {
2220                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2221                       break;
2222                     }
2223                     if (next->is_Phi()) {
2224                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2225                       break;
2226                     }
2227                     m = next;
2228                   }
2229 
2230                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2231                   assert(m->is_Mem() || m->is_LoadStore(), "");
2232                   uint input = (uint)MemNode::Memory;
2233                   _phase->igvn().replace_input_of(m, input, phi);
2234                   push = false;
2235                 }
2236               } else {
2237                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2238               }
2239               if (push) {
2240                 uses.push(u);
2241               }
2242             }
2243           } else if (!mem_is_valid(m, u) &&
2244                      !(u->Opcode() == Op_CProj && u->in(0)->is_NeverBranch() && u->as_Proj()->_con == 1)) {
2245             uses.push(u);
2246           }
2247         }
2248       }
2249     }
2250     for (int i = 0; i < phis.length(); i++) {
2251       Node* n = phis.at(i);
2252       Node* r = n->in(0);
2253       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2254       for (uint j = 1; j < n->req(); j++) {
2255         Node* m = find_mem(r->in(j), nullptr);
2256         _phase->igvn().replace_input_of(n, j, m);
2257         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2258       }
2259     }
2260   }
2261   uint last = _phase->C->unique();
2262   MergeMemNode* mm = nullptr;
2263   int alias = _alias;
2264   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2265   // Process loads first to not miss an anti-dependency: if the memory
2266   // edge of a store is updated before a load is processed then an
2267   // anti-dependency may be missed.
2268   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2269     Node* u = mem->out(i);
2270     if (u->_idx < last && u->is_Load() && _phase->C->get_alias_index(u->adr_type()) == alias) {
2271       Node* m = find_mem(_phase->get_ctrl(u), u);
2272       if (m != mem) {
2273         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2274         _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2275         --i;
2276       }
2277     }
2278   }
2279   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2280     Node* u = mem->out(i);
2281     if (u->_idx < last) {
2282       if (u->is_Mem()) {
2283         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2284           Node* m = find_mem(_phase->get_ctrl(u), u);
2285           if (m != mem) {
2286             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2287             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2288             --i;
2289           }
2290         }
2291       } else if (u->is_MergeMem()) {
2292         MergeMemNode* u_mm = u->as_MergeMem();
2293         if (u_mm->memory_at(alias) == mem) {
2294           MergeMemNode* newmm = nullptr;
2295           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2296             Node* uu = u->fast_out(j);
2297             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2298             if (uu->is_Phi()) {
2299               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2300               Node* region = uu->in(0);
2301               int nb = 0;
2302               for (uint k = 1; k < uu->req(); k++) {
2303                 if (uu->in(k) == u) {
2304                   Node* m = find_mem(region->in(k), nullptr);
2305                   if (m != mem) {
2306                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2307                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2308                     if (newmm != u) {
2309                       _phase->igvn().replace_input_of(uu, k, newmm);
2310                       nb++;
2311                       --jmax;
2312                     }
2313                   }
2314                 }
2315               }
2316               if (nb > 0) {
2317                 --j;
2318               }
2319             } else {
2320               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2321               if (m != mem) {
2322                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2323                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2324                 if (newmm != u) {
2325                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2326                   --j, --jmax;
2327                 }
2328               }
2329             }
2330           }
2331         }
2332       } else if (u->is_Phi()) {
2333         assert(u->bottom_type() == Type::MEMORY, "what else?");
2334         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2335           Node* region = u->in(0);
2336           bool replaced = false;
2337           for (uint j = 1; j < u->req(); j++) {
2338             if (u->in(j) == mem) {
2339               Node* m = find_mem(region->in(j), nullptr);
2340               Node* nnew = m;
2341               if (m != mem) {
2342                 if (u->adr_type() == TypePtr::BOTTOM) {
2343                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2344                   nnew = mm;
2345                 }
2346                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2347                 _phase->igvn().replace_input_of(u, j, nnew);
2348                 replaced = true;
2349               }
2350             }
2351           }
2352           if (replaced) {
2353             --i;
2354           }
2355         }
2356       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2357                  u->adr_type() == nullptr) {
2358         assert(u->adr_type() != nullptr ||
2359                u->Opcode() == Op_Rethrow ||
2360                u->Opcode() == Op_Return ||
2361                u->Opcode() == Op_SafePoint ||
2362                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2363                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2364                u->Opcode() == Op_CallLeaf, "");
2365         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2366         if (m != mem) {
2367           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2368           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2369           --i;
2370         }
2371       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2372         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2373         if (m != mem) {
2374           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2375           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2376           --i;
2377         }
2378       } else if (u->adr_type() != TypePtr::BOTTOM &&
2379                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2380         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2381         assert(m != mem, "");
2382         // u is on the wrong slice...
2383         assert(u->is_ClearArray(), "");
2384         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2385         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2386         --i;
2387       }
2388     }
2389   }
2390 #ifdef ASSERT
2391   assert(new_mem->outcnt() > 0, "");
2392   for (int i = 0; i < phis.length(); i++) {
2393     Node* n = phis.at(i);
2394     assert(n->outcnt() > 0, "new phi must have uses now");
2395   }
2396 #endif
2397 }
2398 
2399 void MemoryGraphFixer::record_new_ctrl(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl) {
2400   if (mem_for_ctrl != mem && new_ctrl != ctrl) {
2401     _memory_nodes.map(ctrl->_idx, mem);
2402     _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2403   }
2404 }
2405 
2406 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2407   MergeMemNode* mm = MergeMemNode::make(mem);
2408   mm->set_memory_at(_alias, rep_proj);
2409   _phase->register_new_node(mm, rep_ctrl);
2410   return mm;
2411 }
2412 
2413 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2414   MergeMemNode* newmm = nullptr;
2415   MergeMemNode* u_mm = u->as_MergeMem();
2416   Node* c = _phase->get_ctrl(u);
2417   if (_phase->is_dominator(c, rep_ctrl)) {
2418     c = rep_ctrl;
2419   } else {
2420     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2421   }
2422   if (u->outcnt() == 1) {
2423     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2424       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2425       --i;
2426     } else {
2427       _phase->igvn().rehash_node_delayed(u);
2428       u_mm->set_memory_at(_alias, rep_proj);
2429     }
2430     newmm = u_mm;
2431     _phase->set_ctrl_and_loop(u, c);
2432   } else {
2433     // can't simply clone u and then change one of its input because
2434     // it adds and then removes an edge which messes with the
2435     // DUIterator
2436     newmm = MergeMemNode::make(u_mm->base_memory());
2437     for (uint j = 0; j < u->req(); j++) {
2438       if (j < newmm->req()) {
2439         if (j == (uint)_alias) {
2440           newmm->set_req(j, rep_proj);
2441         } else if (newmm->in(j) != u->in(j)) {
2442           newmm->set_req(j, u->in(j));
2443         }
2444       } else if (j == (uint)_alias) {
2445         newmm->add_req(rep_proj);
2446       } else {
2447         newmm->add_req(u->in(j));
2448       }
2449     }
2450     if ((uint)_alias >= u->req()) {
2451       newmm->set_memory_at(_alias, rep_proj);
2452     }
2453     _phase->register_new_node(newmm, c);
2454   }
2455   return newmm;
2456 }
2457 
2458 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2459   if (phi->adr_type() == TypePtr::BOTTOM) {
2460     Node* region = phi->in(0);
2461     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2462       Node* uu = region->fast_out(j);
2463       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2464         return false;
2465       }
2466     }
2467     return true;
2468   }
2469   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2470 }
2471 
2472 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2473   uint last = _phase-> C->unique();
2474   MergeMemNode* mm = nullptr;
2475   assert(mem->bottom_type() == Type::MEMORY, "");
2476   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2477     Node* u = mem->out(i);
2478     if (u != replacement && u->_idx < last) {
2479       if (u->is_MergeMem()) {
2480         MergeMemNode* u_mm = u->as_MergeMem();
2481         if (u_mm->memory_at(_alias) == mem) {
2482           MergeMemNode* newmm = nullptr;
2483           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2484             Node* uu = u->fast_out(j);
2485             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2486             if (uu->is_Phi()) {
2487               if (should_process_phi(uu)) {
2488                 Node* region = uu->in(0);
2489                 int nb = 0;
2490                 for (uint k = 1; k < uu->req(); k++) {
2491                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2492                     if (newmm == nullptr) {
2493                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2494                     }
2495                     if (newmm != u) {
2496                       _phase->igvn().replace_input_of(uu, k, newmm);
2497                       nb++;
2498                       --jmax;
2499                     }
2500                   }
2501                 }
2502                 if (nb > 0) {
2503                   --j;
2504                 }
2505               }
2506             } else {
2507               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2508                 if (newmm == nullptr) {
2509                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2510                 }
2511                 if (newmm != u) {
2512                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2513                   --j, --jmax;
2514                 }
2515               }
2516             }
2517           }
2518         }
2519       } else if (u->is_Phi()) {
2520         assert(u->bottom_type() == Type::MEMORY, "what else?");
2521         Node* region = u->in(0);
2522         if (should_process_phi(u)) {
2523           bool replaced = false;
2524           for (uint j = 1; j < u->req(); j++) {
2525             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2526               Node* nnew = rep_proj;
2527               if (u->adr_type() == TypePtr::BOTTOM) {
2528                 if (mm == nullptr) {
2529                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2530                 }
2531                 nnew = mm;
2532               }
2533               _phase->igvn().replace_input_of(u, j, nnew);
2534               replaced = true;
2535             }
2536           }
2537           if (replaced) {
2538             --i;
2539           }
2540 
2541         }
2542       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2543                  u->adr_type() == nullptr) {
2544         assert(u->adr_type() != nullptr ||
2545                u->Opcode() == Op_Rethrow ||
2546                u->Opcode() == Op_Return ||
2547                u->Opcode() == Op_SafePoint ||
2548                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2549                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2550                u->Opcode() == Op_CallLeaf, "%s", u->Name());
2551         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2552           if (mm == nullptr) {
2553             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2554           }
2555           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2556           --i;
2557         }
2558       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2559         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2560           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2561           --i;
2562         }
2563       }
2564     }
2565   }
2566 }
2567 
2568 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj, DecoratorSet decorators)
2569 : Node(ctrl, obj), _decorators(decorators) {
2570   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2571 }
2572 
2573 DecoratorSet ShenandoahLoadReferenceBarrierNode::decorators() const {
2574   return _decorators;
2575 }
2576 
2577 uint ShenandoahLoadReferenceBarrierNode::size_of() const {
2578   return sizeof(*this);
2579 }
2580 
2581 static DecoratorSet mask_decorators(DecoratorSet decorators) {
2582   return decorators & (ON_STRONG_OOP_REF | ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF | ON_UNKNOWN_OOP_REF | IN_NATIVE);
2583 }
2584 
2585 uint ShenandoahLoadReferenceBarrierNode::hash() const {
2586   uint hash = Node::hash();
2587   hash += mask_decorators(_decorators);
2588   return hash;
2589 }
2590 
2591 bool ShenandoahLoadReferenceBarrierNode::cmp( const Node &n ) const {
2592   return Node::cmp(n) && n.Opcode() == Op_ShenandoahLoadReferenceBarrier &&
2593          mask_decorators(_decorators) == mask_decorators(((const ShenandoahLoadReferenceBarrierNode&)n)._decorators);
2594 }
2595 
2596 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2597   if (in(ValueIn) == nullptr || in(ValueIn)->is_top()) {
2598     return Type::TOP;
2599   }
2600   const Type* t = in(ValueIn)->bottom_type();
2601   if (t == TypePtr::NULL_PTR) {
2602     return t;
2603   }
2604 
2605   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2606     return t;
2607   }
2608 
2609   return t->meet(TypePtr::NULL_PTR);
2610 }
2611 
2612 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
2613   // Either input is TOP ==> the result is TOP
2614   const Type *t2 = phase->type(in(ValueIn));
2615   if( t2 == Type::TOP ) return Type::TOP;
2616 
2617   if (t2 == TypePtr::NULL_PTR) {
2618     return t2;
2619   }
2620 
2621   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2622     return t2;
2623   }
2624 
2625   return t2->meet(TypePtr::NULL_PTR);
2626 }
2627 
2628 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
2629   Node* value = in(ValueIn);
2630   if (!needs_barrier(phase, value)) {
2631     return value;
2632   }
2633   return this;
2634 }
2635 
2636 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
2637   Unique_Node_List visited;
2638   return needs_barrier_impl(phase, n, visited);
2639 }
2640 
2641 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
2642   if (n == nullptr) return false;
2643   if (visited.member(n)) {
2644     return false; // Been there.
2645   }
2646   visited.push(n);
2647 
2648   if (n->is_Allocate()) {
2649     // tty->print_cr("optimize barrier on alloc");
2650     return false;
2651   }
2652   if (n->is_Call()) {
2653     // tty->print_cr("optimize barrier on call");
2654     return false;
2655   }
2656 
2657   const Type* type = phase->type(n);
2658   if (type == Type::TOP) {
2659     return false;
2660   }
2661   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
2662     // tty->print_cr("optimize barrier on null");
2663     return false;
2664   }
2665   if (type->make_oopptr() && type->make_oopptr()->const_oop() != nullptr) {
2666     // tty->print_cr("optimize barrier on constant");
2667     return false;
2668   }
2669 
2670   switch (n->Opcode()) {
2671     case Op_AddP:
2672       return true; // TODO: Can refine?
2673     case Op_LoadP:
2674     case Op_ShenandoahCompareAndExchangeN:
2675     case Op_ShenandoahCompareAndExchangeP:
2676     case Op_CompareAndExchangeN:
2677     case Op_CompareAndExchangeP:
2678     case Op_GetAndSetN:
2679     case Op_GetAndSetP:
2680       return true;
2681     case Op_Phi: {
2682       for (uint i = 1; i < n->req(); i++) {
2683         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
2684       }
2685       return false;
2686     }
2687     case Op_CheckCastPP:
2688     case Op_CastPP:
2689       return needs_barrier_impl(phase, n->in(1), visited);
2690     case Op_Proj:
2691       return needs_barrier_impl(phase, n->in(0), visited);
2692     case Op_ShenandoahLoadReferenceBarrier:
2693       // tty->print_cr("optimize barrier on barrier");
2694       return false;
2695     case Op_Parm:
2696       // tty->print_cr("optimize barrier on input arg");
2697       return false;
2698     case Op_DecodeN:
2699     case Op_EncodeP:
2700       return needs_barrier_impl(phase, n->in(1), visited);
2701     case Op_LoadN:
2702       return true;
2703     case Op_CMoveN:
2704     case Op_CMoveP:
2705       return needs_barrier_impl(phase, n->in(2), visited) ||
2706              needs_barrier_impl(phase, n->in(3), visited);
2707     case Op_CreateEx:
2708       return false;
2709     default:
2710       break;
2711   }
2712 #ifdef ASSERT
2713   tty->print("need barrier on?: ");
2714   tty->print_cr("ins:");
2715   n->dump(2);
2716   tty->print_cr("outs:");
2717   n->dump(-2);
2718   ShouldNotReachHere();
2719 #endif
2720   return true;
2721 }