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",
 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::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         !u->depends_only_on_test() && // preserve dependency on test
1044         !uses_to_ignore.member(u) &&
1045         (u->in(0) != ctrl || (!u->is_Region() && !u->is_Phi())) &&
1046         (ctrl->Opcode() != Op_CatchProj || u->Opcode() != Op_CreateEx)) {
1047       Node* old_c = phase->ctrl_or_self(u);
1048       Node* c = old_c;
1049       if (c != ctrl ||
1050           is_dominator_same_ctrl(old_c, barrier, u, phase) ||
1051           ShenandoahBarrierSetC2::is_shenandoah_state_load(u)) {
1052         phase->igvn().rehash_node_delayed(u);
1053         int nb = u->replace_edge(ctrl, region, &phase->igvn());
1054         if (u->is_CFG()) {
1055           if (phase->idom(u) == ctrl) {
1056             phase->set_idom(u, region, phase->dom_depth(region));
1057           }
1058         } else if (phase->get_ctrl(u) == ctrl) {
1059           assert(u != init_raw_mem, "should leave input raw mem above the barrier");
1060           uses.push(u);
1061         }
1062         assert(nb == 1, "more than 1 ctrl input?");
1063         --i, imax -= nb;
1064       }
1065     }
1066   }
1067 }
1068 
1069 static Node* create_phis_on_call_return(Node* ctrl, Node* c, Node* n, Node* n_clone, const CallProjections* projs, PhaseIdealLoop* phase) {
1070   Node* region = nullptr;
1071   while (c != ctrl) {
1072     if (c->is_Region()) {
1073       region = c;
1074     }
1075     c = phase->idom(c);
1076   }
1077   assert(region != nullptr, "");
1078   Node* phi = new PhiNode(region, n->bottom_type());
1079   for (uint j = 1; j < region->req(); j++) {
1080     Node* in = region->in(j);
1081     if (phase->is_dominator(projs->fallthrough_catchproj, in)) {
1082       phi->init_req(j, n);
1083     } else if (phase->is_dominator(projs->catchall_catchproj, in)) {
1084       phi->init_req(j, n_clone);
1085     } else {
1086       phi->init_req(j, create_phis_on_call_return(ctrl, in, n, n_clone, projs, phase));
1087     }
1088   }
1089   phase->register_new_node(phi, region);
1090   return phi;
1091 }
1092 
1093 void ShenandoahBarrierC2Support::pin_and_expand(PhaseIdealLoop* phase) {
1094   ShenandoahBarrierSetC2State* state = ShenandoahBarrierSetC2::bsc2()->state();
1095 
1096   Unique_Node_List uses;
1097   Node_Stack stack(0);
1098   Node_List clones;
1099   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1100     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1101 
1102     Node* ctrl = phase->get_ctrl(lrb);
1103     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1104 
1105     CallStaticJavaNode* unc = nullptr;
1106     Node* unc_ctrl = nullptr;
1107     Node* uncasted_val = val;
1108 
1109     for (DUIterator_Fast imax, i = lrb->fast_outs(imax); i < imax; i++) {
1110       Node* u = lrb->fast_out(i);
1111       if (u->Opcode() == Op_CastPP &&
1112           u->in(0) != nullptr &&
1113           phase->is_dominator(u->in(0), ctrl)) {
1114         const Type* u_t = phase->igvn().type(u);
1115 
1116         if (u_t->meet(TypePtr::NULL_PTR) != u_t &&
1117             u->in(0)->Opcode() == Op_IfTrue &&
1118             u->in(0)->as_Proj()->is_uncommon_trap_if_pattern() &&
1119             u->in(0)->in(0)->is_If() &&
1120             u->in(0)->in(0)->in(1)->Opcode() == Op_Bool &&
1121             u->in(0)->in(0)->in(1)->as_Bool()->_test._test == BoolTest::ne &&
1122             u->in(0)->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1123             u->in(0)->in(0)->in(1)->in(1)->in(1) == val &&
1124             u->in(0)->in(0)->in(1)->in(1)->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1125           IdealLoopTree* loop = phase->get_loop(ctrl);
1126           IdealLoopTree* unc_loop = phase->get_loop(u->in(0));
1127 
1128           if (!unc_loop->is_member(loop)) {
1129             continue;
1130           }
1131 
1132           Node* branch = no_branches(ctrl, u->in(0), false, phase);
1133           assert(branch == nullptr || branch == NodeSentinel, "was not looking for a branch");
1134           if (branch == NodeSentinel) {
1135             continue;
1136           }
1137 
1138           Node* iff = u->in(0)->in(0);
1139           Node* bol = iff->in(1)->clone();
1140           Node* cmp = bol->in(1)->clone();
1141           cmp->set_req(1, lrb);
1142           bol->set_req(1, cmp);
1143           phase->igvn().replace_input_of(iff, 1, bol);
1144           phase->set_ctrl(lrb, iff->in(0));
1145           phase->register_new_node(cmp, iff->in(0));
1146           phase->register_new_node(bol, iff->in(0));
1147           break;
1148         }
1149       }
1150     }
1151     if ((ctrl->is_Proj() && ctrl->in(0)->is_CallJava()) || ctrl->is_CallJava()) {
1152       CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_CallJava() : ctrl->as_CallJava();
1153       if (call->entry_point() == OptoRuntime::rethrow_stub()) {
1154         // The rethrow call may have too many projections to be
1155         // properly handled here. Given there's no reason for a
1156         // barrier to depend on the call, move it above the call
1157         stack.push(lrb, 0);
1158         do {
1159           Node* n = stack.node();
1160           uint idx = stack.index();
1161           if (idx < n->req()) {
1162             Node* in = n->in(idx);
1163             stack.set_index(idx+1);
1164             if (in != nullptr) {
1165               if (phase->has_ctrl(in)) {
1166                 if (phase->is_dominator(call, phase->get_ctrl(in))) {
1167 #ifdef ASSERT
1168                   for (uint i = 0; i < stack.size(); i++) {
1169                     assert(stack.node_at(i) != in, "node shouldn't have been seen yet");
1170                   }
1171 #endif
1172                   stack.push(in, 0);
1173                 }
1174               } else {
1175                 assert(phase->is_dominator(in, call->in(0)), "no dependency on the call");
1176               }
1177             }
1178           } else {
1179             phase->set_ctrl(n, call->in(0));
1180             stack.pop();
1181           }
1182         } while(stack.size() > 0);
1183         continue;
1184       }
1185       CallProjections* projs = call->extract_projections(false, false);
1186 #ifdef ASSERT
1187       VectorSet cloned;
1188 #endif
1189       Node* lrb_clone = lrb->clone();
1190       phase->register_new_node(lrb_clone, projs->catchall_catchproj);
1191       phase->set_ctrl(lrb, projs->fallthrough_catchproj);
1192 
1193       stack.push(lrb, 0);
1194       clones.push(lrb_clone);
1195 
1196       do {
1197         assert(stack.size() == clones.size(), "");
1198         Node* n = stack.node();
1199 #ifdef ASSERT
1200         if (n->is_Load()) {
1201           Node* mem = n->in(MemNode::Memory);
1202           for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
1203             Node* u = mem->fast_out(j);
1204             assert(!u->is_Store() || !u->is_LoadStore() || phase->get_ctrl(u) != ctrl, "anti dependent store?");
1205           }
1206         }
1207 #endif
1208         uint idx = stack.index();
1209         Node* n_clone = clones.at(clones.size()-1);
1210         if (idx < n->outcnt()) {
1211           Node* u = n->raw_out(idx);
1212           Node* c = phase->ctrl_or_self(u);
1213           if (phase->is_dominator(call, c) && phase->is_dominator(c, projs->fallthrough_proj)) {
1214             stack.set_index(idx+1);
1215             assert(!u->is_CFG(), "");
1216             stack.push(u, 0);
1217             assert(!cloned.test_set(u->_idx), "only one clone");
1218             Node* u_clone = u->clone();
1219             int nb = u_clone->replace_edge(n, n_clone, &phase->igvn());
1220             assert(nb > 0, "should have replaced some uses");
1221             phase->register_new_node(u_clone, projs->catchall_catchproj);
1222             clones.push(u_clone);
1223             phase->set_ctrl(u, projs->fallthrough_catchproj);
1224           } else {
1225             bool replaced = false;
1226             if (u->is_Phi()) {
1227               for (uint k = 1; k < u->req(); k++) {
1228                 if (u->in(k) == n) {
1229                   if (phase->is_dominator(projs->catchall_catchproj, u->in(0)->in(k))) {
1230                     phase->igvn().replace_input_of(u, k, n_clone);
1231                     replaced = true;
1232                   } else if (!phase->is_dominator(projs->fallthrough_catchproj, u->in(0)->in(k))) {
1233                     phase->igvn().replace_input_of(u, k, create_phis_on_call_return(ctrl, u->in(0)->in(k), n, n_clone, projs, phase));
1234                     replaced = true;
1235                   }
1236                 }
1237               }
1238             } else {
1239               if (phase->is_dominator(projs->catchall_catchproj, c)) {
1240                 phase->igvn().rehash_node_delayed(u);
1241                 int nb = u->replace_edge(n, n_clone, &phase->igvn());
1242                 assert(nb > 0, "should have replaced some uses");
1243                 replaced = true;
1244               } else if (!phase->is_dominator(projs->fallthrough_catchproj, c)) {
1245                 if (u->is_If()) {
1246                   // Can't break If/Bool/Cmp chain
1247                   assert(n->is_Bool(), "unexpected If shape");
1248                   assert(stack.node_at(stack.size()-2)->is_Cmp(), "unexpected If shape");
1249                   assert(n_clone->is_Bool(), "unexpected clone");
1250                   assert(clones.at(clones.size()-2)->is_Cmp(), "unexpected clone");
1251                   Node* bol_clone = n->clone();
1252                   Node* cmp_clone = stack.node_at(stack.size()-2)->clone();
1253                   bol_clone->set_req(1, cmp_clone);
1254 
1255                   Node* nn = stack.node_at(stack.size()-3);
1256                   Node* nn_clone = clones.at(clones.size()-3);
1257                   assert(nn->Opcode() == nn_clone->Opcode(), "mismatch");
1258 
1259                   int nb = cmp_clone->replace_edge(nn, create_phis_on_call_return(ctrl, c, nn, nn_clone, projs, phase),
1260                                                    &phase->igvn());
1261                   assert(nb > 0, "should have replaced some uses");
1262 
1263                   phase->register_new_node(bol_clone, u->in(0));
1264                   phase->register_new_node(cmp_clone, u->in(0));
1265 
1266                   phase->igvn().replace_input_of(u, 1, bol_clone);
1267 
1268                 } else {
1269                   phase->igvn().rehash_node_delayed(u);
1270                   int nb = u->replace_edge(n, create_phis_on_call_return(ctrl, c, n, n_clone, projs, phase), &phase->igvn());
1271                   assert(nb > 0, "should have replaced some uses");
1272                 }
1273                 replaced = true;
1274               }
1275             }
1276             if (!replaced) {
1277               stack.set_index(idx+1);
1278             }
1279           }
1280         } else {
1281           stack.pop();
1282           clones.pop();
1283         }
1284       } while (stack.size() > 0);
1285       assert(stack.size() == 0 && clones.size() == 0, "");
1286     }
1287   }
1288 
1289   for (int i = 0; i < state->load_reference_barriers_count(); i++) {
1290     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1291     Node* ctrl = phase->get_ctrl(lrb);
1292     IdealLoopTree* loop = phase->get_loop(ctrl);
1293     Node* head = loop->head();
1294     if (head->is_OuterStripMinedLoop()) {
1295       // Expanding a barrier here will break loop strip mining
1296       // verification. Transform the loop so the loop nest doesn't
1297       // appear as strip mined.
1298       OuterStripMinedLoopNode* outer = head->as_OuterStripMinedLoop();
1299       hide_strip_mined_loop(outer, outer->unique_ctrl_out()->as_CountedLoop(), phase);
1300     }
1301     if (head->is_BaseCountedLoop() && ctrl->is_IfProj() && ctrl->in(0)->is_BaseCountedLoopEnd() &&
1302         head->as_BaseCountedLoop()->loopexit() == ctrl->in(0)) {
1303       Node* entry = head->in(LoopNode::EntryControl);
1304       Node* backedge = head->in(LoopNode::LoopBackControl);
1305       Node* new_head = new LoopNode(entry, backedge);
1306       phase->register_control(new_head, phase->get_loop(entry), entry);
1307       phase->lazy_replace(head, new_head);
1308     }
1309   }
1310 
1311   // Expand load-reference-barriers
1312   MemoryGraphFixer fixer(Compile::AliasIdxRaw, true, phase);
1313   Unique_Node_List uses_to_ignore;
1314   for (int i = state->load_reference_barriers_count() - 1; i >= 0; i--) {
1315     ShenandoahLoadReferenceBarrierNode* lrb = state->load_reference_barrier(i);
1316     uint last = phase->C->unique();
1317     Node* ctrl = phase->get_ctrl(lrb);
1318     Node* val = lrb->in(ShenandoahLoadReferenceBarrierNode::ValueIn);
1319 
1320     Node* orig_ctrl = ctrl;
1321 
1322     Node* raw_mem = fixer.find_mem(ctrl, lrb);
1323     Node* raw_mem_for_ctrl = fixer.find_mem(ctrl, nullptr);
1324 
1325     IdealLoopTree *loop = phase->get_loop(ctrl);
1326 
1327     Node* heap_stable_ctrl = nullptr;
1328     Node* null_ctrl = nullptr;
1329 
1330     assert(val->bottom_type()->make_oopptr(), "need oop");
1331     assert(val->bottom_type()->make_oopptr()->const_oop() == nullptr, "expect non-constant");
1332 
1333     enum { _heap_stable = 1, _evac_path, _not_cset, PATH_LIMIT };
1334     Node* region = new RegionNode(PATH_LIMIT);
1335     Node* val_phi = new PhiNode(region, val->bottom_type()->is_oopptr());
1336 
1337     // Stable path.
1338     int flags = ShenandoahHeap::HAS_FORWARDED;
1339     if (!ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1340       flags |= ShenandoahHeap::WEAK_ROOTS;
1341     }
1342     test_gc_state(ctrl, raw_mem, heap_stable_ctrl, phase, flags);
1343     IfNode* heap_stable_iff = heap_stable_ctrl->in(0)->as_If();
1344 
1345     // Heap stable case
1346     region->init_req(_heap_stable, heap_stable_ctrl);
1347     val_phi->init_req(_heap_stable, val);
1348 
1349     // Test for in-cset, unless it's a native-LRB. Native LRBs need to return null
1350     // even for non-cset objects to prevent resurrection of such objects.
1351     // Wires !in_cset(obj) to slot 2 of region and phis
1352     Node* not_cset_ctrl = nullptr;
1353     if (ShenandoahBarrierSet::is_strong_access(lrb->decorators())) {
1354       test_in_cset(ctrl, not_cset_ctrl, val, raw_mem, phase);
1355     }
1356     if (not_cset_ctrl != nullptr) {
1357       region->init_req(_not_cset, not_cset_ctrl);
1358       val_phi->init_req(_not_cset, val);
1359     } else {
1360       region->del_req(_not_cset);
1361       val_phi->del_req(_not_cset);
1362     }
1363 
1364     // Resolve object when orig-value is in cset.
1365     // Make the unconditional resolve for fwdptr.
1366 
1367     // Call lrb-stub and wire up that path in slots 4
1368     Node* result_mem = nullptr;
1369 
1370     Node* addr;
1371     {
1372       VectorSet visited;
1373       addr = get_load_addr(phase, visited, lrb);
1374     }
1375     if (addr->Opcode() == Op_AddP) {
1376       Node* orig_base = addr->in(AddPNode::Base);
1377       Node* base = new CheckCastPPNode(ctrl, orig_base, orig_base->bottom_type(), ConstraintCastNode::StrongDependency);
1378       phase->register_new_node(base, ctrl);
1379       if (addr->in(AddPNode::Base) == addr->in((AddPNode::Address))) {
1380         // Field access
1381         addr = addr->clone();
1382         addr->set_req(AddPNode::Base, base);
1383         addr->set_req(AddPNode::Address, base);
1384         phase->register_new_node(addr, ctrl);
1385       } else {
1386         Node* addr2 = addr->in(AddPNode::Address);
1387         if (addr2->Opcode() == Op_AddP && addr2->in(AddPNode::Base) == addr2->in(AddPNode::Address) &&
1388               addr2->in(AddPNode::Base) == orig_base) {
1389           addr2 = addr2->clone();
1390           addr2->set_req(AddPNode::Base, base);
1391           addr2->set_req(AddPNode::Address, base);
1392           phase->register_new_node(addr2, ctrl);
1393           addr = addr->clone();
1394           addr->set_req(AddPNode::Base, base);
1395           addr->set_req(AddPNode::Address, addr2);
1396           phase->register_new_node(addr, ctrl);
1397         }
1398       }
1399     }
1400     call_lrb_stub(ctrl, val, addr, lrb->decorators(), phase);
1401     region->init_req(_evac_path, ctrl);
1402     val_phi->init_req(_evac_path, val);
1403 
1404     phase->register_control(region, loop, heap_stable_iff);
1405     Node* out_val = val_phi;
1406     phase->register_new_node(val_phi, region);
1407 
1408     fix_ctrl(lrb, region, fixer, uses, uses_to_ignore, last, phase);
1409 
1410     ctrl = orig_ctrl;
1411 
1412     phase->igvn().replace_node(lrb, out_val);
1413 
1414     follow_barrier_uses(out_val, ctrl, uses, phase);
1415 
1416     for(uint next = 0; next < uses.size(); next++ ) {
1417       Node *n = uses.at(next);
1418       assert(phase->get_ctrl(n) == ctrl, "bad control");
1419       assert(n != raw_mem, "should leave input raw mem above the barrier");
1420       phase->set_ctrl(n, region);
1421       follow_barrier_uses(n, ctrl, uses, phase);
1422     }
1423     fixer.record_new_ctrl(ctrl, region, raw_mem, raw_mem_for_ctrl);
1424   }
1425   // Done expanding load-reference-barriers.
1426   assert(ShenandoahBarrierSetC2::bsc2()->state()->load_reference_barriers_count() == 0, "all load reference barrier nodes should have been replaced");
1427 }
1428 
1429 Node* ShenandoahBarrierC2Support::get_load_addr(PhaseIdealLoop* phase, VectorSet& visited, Node* in) {
1430   if (visited.test_set(in->_idx)) {
1431     return nullptr;
1432   }
1433   switch (in->Opcode()) {
1434     case Op_Proj:
1435       return get_load_addr(phase, visited, in->in(0));
1436     case Op_CastPP:
1437     case Op_CheckCastPP:
1438     case Op_DecodeN:
1439     case Op_EncodeP:
1440       return get_load_addr(phase, visited, in->in(1));
1441     case Op_LoadN:
1442     case Op_LoadP:
1443       return in->in(MemNode::Address);
1444     case Op_CompareAndExchangeN:
1445     case Op_CompareAndExchangeP:
1446     case Op_GetAndSetN:
1447     case Op_GetAndSetP:
1448     case Op_ShenandoahCompareAndExchangeP:
1449     case Op_ShenandoahCompareAndExchangeN:
1450       // Those instructions would just have stored a different
1451       // value into the field. No use to attempt to fix it at this point.
1452       return phase->igvn().zerocon(T_OBJECT);
1453     case Op_CMoveP:
1454     case Op_CMoveN: {
1455       Node* t = get_load_addr(phase, visited, in->in(CMoveNode::IfTrue));
1456       Node* f = get_load_addr(phase, visited, in->in(CMoveNode::IfFalse));
1457       // Handle unambiguous cases: single address reported on both branches.
1458       if (t != nullptr && f == nullptr) return t;
1459       if (t == nullptr && f != nullptr) return f;
1460       if (t != nullptr && t == f)    return t;
1461       // Ambiguity.
1462       return phase->igvn().zerocon(T_OBJECT);
1463     }
1464     case Op_Phi: {
1465       Node* addr = nullptr;
1466       for (uint i = 1; i < in->req(); i++) {
1467         Node* addr1 = get_load_addr(phase, visited, in->in(i));
1468         if (addr == nullptr) {
1469           addr = addr1;
1470         }
1471         if (addr != addr1) {
1472           return phase->igvn().zerocon(T_OBJECT);
1473         }
1474       }
1475       return addr;
1476     }
1477     case Op_ShenandoahLoadReferenceBarrier:
1478       return get_load_addr(phase, visited, in->in(ShenandoahLoadReferenceBarrierNode::ValueIn));
1479     case Op_CallDynamicJava:
1480     case Op_CallLeaf:
1481     case Op_CallStaticJava:
1482     case Op_ConN:
1483     case Op_ConP:
1484     case Op_Parm:
1485     case Op_CreateEx:
1486       return phase->igvn().zerocon(T_OBJECT);
1487     default:
1488 #ifdef ASSERT
1489       fatal("Unknown node in get_load_addr: %s", NodeClassNames[in->Opcode()]);
1490 #endif
1491       return phase->igvn().zerocon(T_OBJECT);
1492   }
1493 
1494 }
1495 
1496 void ShenandoahBarrierC2Support::move_gc_state_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase) {
1497   IdealLoopTree *loop = phase->get_loop(iff);
1498   Node* loop_head = loop->_head;
1499   Node* entry_c = loop_head->in(LoopNode::EntryControl);
1500 
1501   Node* bol = iff->in(1);
1502   Node* cmp = bol->in(1);
1503   Node* andi = cmp->in(1);
1504   Node* load = andi->in(1);
1505 
1506   assert(is_gc_state_load(load), "broken");
1507   if (!phase->is_dominator(load->in(0), entry_c)) {
1508     Node* mem_ctrl = nullptr;
1509     Node* mem = dom_mem(load->in(MemNode::Memory), loop_head, Compile::AliasIdxRaw, mem_ctrl, phase);
1510     load = load->clone();
1511     load->set_req(MemNode::Memory, mem);
1512     load->set_req(0, entry_c);
1513     phase->register_new_node(load, entry_c);
1514     andi = andi->clone();
1515     andi->set_req(1, load);
1516     phase->register_new_node(andi, entry_c);
1517     cmp = cmp->clone();
1518     cmp->set_req(1, andi);
1519     phase->register_new_node(cmp, entry_c);
1520     bol = bol->clone();
1521     bol->set_req(1, cmp);
1522     phase->register_new_node(bol, entry_c);
1523 
1524     phase->igvn().replace_input_of(iff, 1, bol);
1525   }
1526 }
1527 
1528 bool ShenandoahBarrierC2Support::identical_backtoback_ifs(Node* n, PhaseIdealLoop* phase) {
1529   if (!n->is_If() || n->is_CountedLoopEnd()) {
1530     return false;
1531   }
1532   Node* region = n->in(0);
1533 
1534   if (!region->is_Region()) {
1535     return false;
1536   }
1537   Node* dom = phase->idom(region);
1538   if (!dom->is_If()) {
1539     return false;
1540   }
1541 
1542   if (!is_heap_stable_test(n) || !is_heap_stable_test(dom)) {
1543     return false;
1544   }
1545 
1546   IfNode* dom_if = dom->as_If();
1547   Node* proj_true = dom_if->proj_out(1);
1548   Node* proj_false = dom_if->proj_out(0);
1549 
1550   for (uint i = 1; i < region->req(); i++) {
1551     if (phase->is_dominator(proj_true, region->in(i))) {
1552       continue;
1553     }
1554     if (phase->is_dominator(proj_false, region->in(i))) {
1555       continue;
1556     }
1557     return false;
1558   }
1559 
1560   return true;
1561 }
1562 
1563 bool ShenandoahBarrierC2Support::merge_point_safe(Node* region) {
1564   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1565     Node* n = region->fast_out(i);
1566     if (n->is_LoadStore()) {
1567       // Splitting a LoadStore node through phi, causes it to lose its SCMemProj: the split if code doesn't have support
1568       // for a LoadStore at the region the if is split through because that's not expected to happen (LoadStore nodes
1569       // should be between barrier nodes). It does however happen with Shenandoah though because barriers can get
1570       // expanded around a LoadStore node.
1571       return false;
1572     }
1573   }
1574   return true;
1575 }
1576 
1577 
1578 void ShenandoahBarrierC2Support::merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase) {
1579   assert(is_heap_stable_test(n), "no other tests");
1580   if (identical_backtoback_ifs(n, phase)) {
1581     Node* n_ctrl = n->in(0);
1582     if (phase->can_split_if(n_ctrl) && merge_point_safe(n_ctrl)) {
1583       IfNode* dom_if = phase->idom(n_ctrl)->as_If();
1584       if (is_heap_stable_test(n)) {
1585         Node* gc_state_load = n->in(1)->in(1)->in(1)->in(1);
1586         assert(is_gc_state_load(gc_state_load), "broken");
1587         Node* dom_gc_state_load = dom_if->in(1)->in(1)->in(1)->in(1);
1588         assert(is_gc_state_load(dom_gc_state_load), "broken");
1589         if (gc_state_load != dom_gc_state_load) {
1590           phase->igvn().replace_node(gc_state_load, dom_gc_state_load);
1591         }
1592       }
1593       PhiNode* bolphi = PhiNode::make_blank(n_ctrl, n->in(1));
1594       Node* proj_true = dom_if->proj_out(1);
1595       Node* proj_false = dom_if->proj_out(0);
1596       Node* con_true = phase->igvn().makecon(TypeInt::ONE);
1597       Node* con_false = phase->igvn().makecon(TypeInt::ZERO);
1598 
1599       for (uint i = 1; i < n_ctrl->req(); i++) {
1600         if (phase->is_dominator(proj_true, n_ctrl->in(i))) {
1601           bolphi->init_req(i, con_true);
1602         } else {
1603           assert(phase->is_dominator(proj_false, n_ctrl->in(i)), "bad if");
1604           bolphi->init_req(i, con_false);
1605         }
1606       }
1607       phase->register_new_node(bolphi, n_ctrl);
1608       phase->igvn().replace_input_of(n, 1, bolphi);
1609       phase->do_split_if(n);
1610     }
1611   }
1612 }
1613 
1614 IfNode* ShenandoahBarrierC2Support::find_unswitching_candidate(const IdealLoopTree* loop, PhaseIdealLoop* phase) {
1615   // Find first invariant test that doesn't exit the loop
1616   LoopNode *head = loop->_head->as_Loop();
1617   IfNode* unswitch_iff = nullptr;
1618   Node* n = head->in(LoopNode::LoopBackControl);
1619   int loop_has_sfpts = -1;
1620   while (n != head) {
1621     Node* n_dom = phase->idom(n);
1622     if (n->is_Region()) {
1623       if (n_dom->is_If()) {
1624         IfNode* iff = n_dom->as_If();
1625         if (iff->in(1)->is_Bool()) {
1626           BoolNode* bol = iff->in(1)->as_Bool();
1627           if (bol->in(1)->is_Cmp()) {
1628             // If condition is invariant and not a loop exit,
1629             // then found reason to unswitch.
1630             if (is_heap_stable_test(iff) &&
1631                 (loop_has_sfpts == -1 || loop_has_sfpts == 0)) {
1632               assert(!loop->is_loop_exit(iff), "both branches should be in the loop");
1633               if (loop_has_sfpts == -1) {
1634                 for(uint i = 0; i < loop->_body.size(); i++) {
1635                   Node *m = loop->_body[i];
1636                   if (m->is_SafePoint() && !m->is_CallLeaf()) {
1637                     loop_has_sfpts = 1;
1638                     break;
1639                   }
1640                 }
1641                 if (loop_has_sfpts == -1) {
1642                   loop_has_sfpts = 0;
1643                 }
1644               }
1645               if (!loop_has_sfpts) {
1646                 unswitch_iff = iff;
1647               }
1648             }
1649           }
1650         }
1651       }
1652     }
1653     n = n_dom;
1654   }
1655   return unswitch_iff;
1656 }
1657 
1658 
1659 void ShenandoahBarrierC2Support::optimize_after_expansion(VectorSet &visited, Node_Stack &stack, Node_List &old_new, PhaseIdealLoop* phase) {
1660   Node_List heap_stable_tests;
1661   stack.push(phase->C->start(), 0);
1662   do {
1663     Node* n = stack.node();
1664     uint i = stack.index();
1665 
1666     if (i < n->outcnt()) {
1667       Node* u = n->raw_out(i);
1668       stack.set_index(i+1);
1669       if (!visited.test_set(u->_idx)) {
1670         stack.push(u, 0);
1671       }
1672     } else {
1673       stack.pop();
1674       if (n->is_If() && is_heap_stable_test(n)) {
1675         heap_stable_tests.push(n);
1676       }
1677     }
1678   } while (stack.size() > 0);
1679 
1680   for (uint i = 0; i < heap_stable_tests.size(); i++) {
1681     Node* n = heap_stable_tests.at(i);
1682     assert(is_heap_stable_test(n), "only evacuation test");
1683     merge_back_to_back_tests(n, phase);
1684   }
1685 
1686   if (!phase->C->major_progress()) {
1687     VectorSet seen;
1688     for (uint i = 0; i < heap_stable_tests.size(); i++) {
1689       Node* n = heap_stable_tests.at(i);
1690       IdealLoopTree* loop = phase->get_loop(n);
1691       if (loop != phase->ltree_root() &&
1692           loop->_child == nullptr &&
1693           !loop->_irreducible) {
1694         Node* head = loop->_head;
1695         if (head->is_Loop() &&
1696             (!head->is_CountedLoop() || head->as_CountedLoop()->is_main_loop() || head->as_CountedLoop()->is_normal_loop()) &&
1697             !seen.test_set(head->_idx)) {
1698           IfNode* iff = find_unswitching_candidate(loop, phase);
1699           if (iff != nullptr) {
1700             Node* bol = iff->in(1);
1701             if (head->as_Loop()->is_strip_mined()) {
1702               head->as_Loop()->verify_strip_mined(0);
1703             }
1704             move_gc_state_test_out_of_loop(iff, phase);
1705 
1706             AutoNodeBudget node_budget(phase);
1707 
1708             if (loop->policy_unswitching(phase)) {
1709               if (head->as_Loop()->is_strip_mined()) {
1710                 OuterStripMinedLoopNode* outer = head->as_CountedLoop()->outer_loop();
1711                 hide_strip_mined_loop(outer, head->as_CountedLoop(), phase);
1712               }
1713               phase->do_unswitching(loop, old_new);
1714             } else {
1715               // Not proceeding with unswitching. Move load back in
1716               // the loop.
1717               phase->igvn().replace_input_of(iff, 1, bol);
1718             }
1719           }
1720         }
1721       }
1722     }
1723   }
1724 }
1725 
1726 #ifdef ASSERT
1727 static bool has_never_branch(Node* root) {
1728   for (uint i = 1; i < root->req(); i++) {
1729     Node* in = root->in(i);
1730     if (in != nullptr && in->Opcode() == Op_Halt && in->in(0)->is_Proj() && in->in(0)->in(0)->is_NeverBranch()) {
1731       return true;
1732     }
1733   }
1734   return false;
1735 }
1736 #endif
1737 
1738 void MemoryGraphFixer::collect_memory_nodes() {
1739   Node_Stack stack(0);
1740   VectorSet visited;
1741   Node_List regions;
1742 
1743   // Walk the raw memory graph and create a mapping from CFG node to
1744   // memory node. Exclude phis for now.
1745   stack.push(_phase->C->root(), 1);
1746   do {
1747     Node* n = stack.node();
1748     int opc = n->Opcode();
1749     uint i = stack.index();
1750     if (i < n->req()) {
1751       Node* mem = nullptr;
1752       if (opc == Op_Root) {
1753         Node* in = n->in(i);
1754         int in_opc = in->Opcode();
1755         if (in_opc == Op_Return || in_opc == Op_Rethrow) {
1756           mem = in->in(TypeFunc::Memory);
1757         } else if (in_opc == Op_Halt) {
1758           if (in->in(0)->is_Region()) {
1759             Node* r = in->in(0);
1760             for (uint j = 1; j < r->req(); j++) {
1761               assert(!r->in(j)->is_NeverBranch(), "");
1762             }
1763           } else {
1764             Node* proj = in->in(0);
1765             assert(proj->is_Proj(), "");
1766             Node* in = proj->in(0);
1767             assert(in->is_CallStaticJava() || in->is_NeverBranch() || in->Opcode() == Op_Catch || proj->is_IfProj(), "");
1768             if (in->is_CallStaticJava()) {
1769               mem = in->in(TypeFunc::Memory);
1770             } else if (in->Opcode() == Op_Catch) {
1771               Node* call = in->in(0)->in(0);
1772               assert(call->is_Call(), "");
1773               mem = call->in(TypeFunc::Memory);
1774             } else if (in->is_NeverBranch()) {
1775               mem = collect_memory_for_infinite_loop(in);
1776             }
1777           }
1778         } else {
1779 #ifdef ASSERT
1780           n->dump();
1781           in->dump();
1782 #endif
1783           ShouldNotReachHere();
1784         }
1785       } else {
1786         assert(n->is_Phi() && n->bottom_type() == Type::MEMORY, "");
1787         assert(n->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(n->adr_type()) == _alias, "");
1788         mem = n->in(i);
1789       }
1790       i++;
1791       stack.set_index(i);
1792       if (mem == nullptr) {
1793         continue;
1794       }
1795       for (;;) {
1796         if (visited.test_set(mem->_idx) || mem->is_Start()) {
1797           break;
1798         }
1799         if (mem->is_Phi()) {
1800           stack.push(mem, 2);
1801           mem = mem->in(1);
1802         } else if (mem->is_Proj()) {
1803           stack.push(mem, mem->req());
1804           mem = mem->in(0);
1805         } else if (mem->is_SafePoint() || mem->is_MemBar()) {
1806           mem = mem->in(TypeFunc::Memory);
1807         } else if (mem->is_MergeMem()) {
1808           MergeMemNode* mm = mem->as_MergeMem();
1809           mem = mm->memory_at(_alias);
1810         } else if (mem->is_Store() || mem->is_LoadStore() || mem->is_ClearArray()) {
1811           assert(_alias == Compile::AliasIdxRaw, "");
1812           stack.push(mem, mem->req());
1813           mem = mem->in(MemNode::Memory);
1814         } else {
1815 #ifdef ASSERT
1816           mem->dump();
1817 #endif
1818           ShouldNotReachHere();
1819         }
1820       }
1821     } else {
1822       if (n->is_Phi()) {
1823         // Nothing
1824       } else if (!n->is_Root()) {
1825         Node* c = get_ctrl(n);
1826         _memory_nodes.map(c->_idx, n);
1827       }
1828       stack.pop();
1829     }
1830   } while(stack.is_nonempty());
1831 
1832   // Iterate over CFG nodes in rpo and propagate memory state to
1833   // compute memory state at regions, creating new phis if needed.
1834   Node_List rpo_list;
1835   visited.clear();
1836   _phase->rpo(_phase->C->root(), stack, visited, rpo_list);
1837   Node* root = rpo_list.pop();
1838   assert(root == _phase->C->root(), "");
1839 
1840   const bool trace = false;
1841 #ifdef ASSERT
1842   if (trace) {
1843     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1844       Node* c = rpo_list.at(i);
1845       if (_memory_nodes[c->_idx] != nullptr) {
1846         tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump();
1847       }
1848     }
1849   }
1850 #endif
1851   uint last = _phase->C->unique();
1852 
1853 #ifdef ASSERT
1854   uint16_t max_depth = 0;
1855   for (LoopTreeIterator iter(_phase->ltree_root()); !iter.done(); iter.next()) {
1856     IdealLoopTree* lpt = iter.current();
1857     max_depth = MAX2(max_depth, lpt->_nest);
1858   }
1859 #endif
1860 
1861   bool progress = true;
1862   int iteration = 0;
1863   Node_List dead_phis;
1864   while (progress) {
1865     progress = false;
1866     iteration++;
1867     assert(iteration <= 2+max_depth || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1868     if (trace) { tty->print_cr("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); }
1869 
1870     for (int i = rpo_list.size() - 1; i >= 0; i--) {
1871       Node* c = rpo_list.at(i);
1872 
1873       Node* prev_mem = _memory_nodes[c->_idx];
1874       if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1875         Node* prev_region = regions[c->_idx];
1876         Node* unique = nullptr;
1877         for (uint j = 1; j < c->req() && unique != NodeSentinel; j++) {
1878           Node* m = _memory_nodes[c->in(j)->_idx];
1879           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");
1880           if (m != nullptr) {
1881             if (m == prev_region && ((c->is_Loop() && j == LoopNode::LoopBackControl) || (prev_region->is_Phi() && prev_region->in(0) == c))) {
1882               assert((c->is_Loop() && j == LoopNode::LoopBackControl) || _phase->C->has_irreducible_loop() || has_never_branch(_phase->C->root()), "");
1883               // continue
1884             } else if (unique == nullptr) {
1885               unique = m;
1886             } else if (m == unique) {
1887               // continue
1888             } else {
1889               unique = NodeSentinel;
1890             }
1891           }
1892         }
1893         assert(unique != nullptr, "empty phi???");
1894         if (unique != NodeSentinel) {
1895           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c) {
1896             dead_phis.push(prev_region);
1897           }
1898           regions.map(c->_idx, unique);
1899         } else {
1900           Node* phi = nullptr;
1901           if (prev_region != nullptr && prev_region->is_Phi() && prev_region->in(0) == c && prev_region->_idx >= last) {
1902             phi = prev_region;
1903             for (uint k = 1; k < c->req(); k++) {
1904               Node* m = _memory_nodes[c->in(k)->_idx];
1905               assert(m != nullptr, "expect memory state");
1906               phi->set_req(k, m);
1907             }
1908           } else {
1909             for (DUIterator_Fast jmax, j = c->fast_outs(jmax); j < jmax && phi == nullptr; j++) {
1910               Node* u = c->fast_out(j);
1911               if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1912                   (u->adr_type() == TypePtr::BOTTOM || _phase->C->get_alias_index(u->adr_type()) == _alias)) {
1913                 phi = u;
1914                 for (uint k = 1; k < c->req() && phi != nullptr; k++) {
1915                   Node* m = _memory_nodes[c->in(k)->_idx];
1916                   assert(m != nullptr, "expect memory state");
1917                   if (u->in(k) != m) {
1918                     phi = NodeSentinel;
1919                   }
1920                 }
1921               }
1922             }
1923             if (phi == NodeSentinel) {
1924               phi = new PhiNode(c, Type::MEMORY, _phase->C->get_adr_type(_alias));
1925               for (uint k = 1; k < c->req(); k++) {
1926                 Node* m = _memory_nodes[c->in(k)->_idx];
1927                 assert(m != nullptr, "expect memory state");
1928                 phi->init_req(k, m);
1929               }
1930             }
1931           }
1932           if (phi != nullptr) {
1933             regions.map(c->_idx, phi);
1934           } else {
1935             assert(c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1936           }
1937         }
1938         Node* current_region = regions[c->_idx];
1939         if (current_region != prev_region) {
1940           progress = true;
1941           if (prev_region == prev_mem) {
1942             _memory_nodes.map(c->_idx, current_region);
1943           }
1944         }
1945       } else if (prev_mem == nullptr || prev_mem->is_Phi() || ctrl_or_self(prev_mem) != c) {
1946         Node* m = _memory_nodes[_phase->idom(c)->_idx];
1947         assert(m != nullptr || c->Opcode() == Op_Halt, "expect memory state");
1948         if (m != prev_mem) {
1949           _memory_nodes.map(c->_idx, m);
1950           progress = true;
1951         }
1952       }
1953 #ifdef ASSERT
1954       if (trace) { tty->print("X %d", c->_idx);  _memory_nodes[c->_idx]->dump(); }
1955 #endif
1956     }
1957   }
1958 
1959   // Replace existing phi with computed memory state for that region
1960   // if different (could be a new phi or a dominating memory node if
1961   // that phi was found to be useless).
1962   while (dead_phis.size() > 0) {
1963     Node* n = dead_phis.pop();
1964     n->replace_by(_phase->C->top());
1965     n->destruct(&_phase->igvn());
1966   }
1967   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1968     Node* c = rpo_list.at(i);
1969     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1970       Node* n = regions[c->_idx];
1971       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1972       if (n != nullptr && n->is_Phi() && n->_idx >= last && n->in(0) == c) {
1973         _phase->register_new_node(n, c);
1974       }
1975     }
1976   }
1977   for (int i = rpo_list.size() - 1; i >= 0; i--) {
1978     Node* c = rpo_list.at(i);
1979     if (c->is_Region() && (_include_lsm || !c->is_OuterStripMinedLoop())) {
1980       Node* n = regions[c->_idx];
1981       assert(n != nullptr || c->unique_ctrl_out()->Opcode() == Op_Halt, "expected memory state");
1982       for (DUIterator_Fast imax, i = c->fast_outs(imax); i < imax; i++) {
1983         Node* u = c->fast_out(i);
1984         if (u->is_Phi() && u->bottom_type() == Type::MEMORY &&
1985             u != n) {
1986           assert(c->unique_ctrl_out()->Opcode() != Op_Halt, "expected memory state");
1987           if (u->adr_type() == TypePtr::BOTTOM) {
1988             fix_memory_uses(u, n, n, c);
1989           } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
1990             _phase->lazy_replace(u, n);
1991             --i; --imax;
1992           }
1993         }
1994       }
1995     }
1996   }
1997 }
1998 
1999 Node* MemoryGraphFixer::collect_memory_for_infinite_loop(const Node* in) {
2000   Node* mem = nullptr;
2001   Node* head = in->in(0);
2002   assert(head->is_Region(), "unexpected infinite loop graph shape");
2003 
2004   Node* phi_mem = nullptr;
2005   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
2006     Node* u = head->fast_out(j);
2007     if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
2008       if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2009         assert(phi_mem == nullptr || phi_mem->adr_type() == TypePtr::BOTTOM, "");
2010         phi_mem = u;
2011       } else if (u->adr_type() == TypePtr::BOTTOM) {
2012         assert(phi_mem == nullptr || _phase->C->get_alias_index(phi_mem->adr_type()) == _alias, "");
2013         if (phi_mem == nullptr) {
2014           phi_mem = u;
2015         }
2016       }
2017     }
2018   }
2019   if (phi_mem == nullptr) {
2020     ResourceMark rm;
2021     Node_Stack stack(0);
2022     stack.push(head, 1);
2023     do {
2024       Node* n = stack.node();
2025       uint i = stack.index();
2026       if (i >= n->req()) {
2027         stack.pop();
2028       } else {
2029         stack.set_index(i + 1);
2030         Node* c = n->in(i);
2031         assert(c != head, "should have found a safepoint on the way");
2032         if (stack.size() != 1 || _phase->is_dominator(head, c)) {
2033           for (;;) {
2034             if (c->is_Region()) {
2035               stack.push(c, 1);
2036               break;
2037             } else if (c->is_SafePoint() && !c->is_CallLeaf()) {
2038               Node* m = c->in(TypeFunc::Memory);
2039               if (m->is_MergeMem()) {
2040                 m = m->as_MergeMem()->memory_at(_alias);
2041               }
2042               assert(mem == nullptr || mem == m, "several memory states");
2043               mem = m;
2044               break;
2045             } else {
2046               assert(c != c->in(0), "");
2047               c = c->in(0);
2048             }
2049           }
2050         }
2051       }
2052     } while (stack.size() > 0);
2053     assert(mem != nullptr, "should have found safepoint");
2054   } else {
2055     mem = phi_mem;
2056   }
2057   return mem;
2058 }
2059 
2060 Node* MemoryGraphFixer::get_ctrl(Node* n) const {
2061   Node* c = _phase->get_ctrl(n);
2062   if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Call()) {
2063     assert(c == n->in(0), "");
2064     CallNode* call = c->as_Call();
2065     CallProjections* projs = call->extract_projections(true, false);
2066     if (projs->catchall_memproj != nullptr) {
2067       if (projs->fallthrough_memproj == n) {
2068         c = projs->fallthrough_catchproj;
2069       } else {
2070         assert(projs->catchall_memproj == n, "");
2071         c = projs->catchall_catchproj;
2072       }
2073     }
2074   }
2075   return c;
2076 }
2077 
2078 Node* MemoryGraphFixer::ctrl_or_self(Node* n) const {
2079   if (_phase->has_ctrl(n))
2080     return get_ctrl(n);
2081   else {
2082     assert (n->is_CFG(), "must be a CFG node");
2083     return n;
2084   }
2085 }
2086 
2087 bool MemoryGraphFixer::mem_is_valid(Node* m, Node* c) const {
2088   return m != nullptr && get_ctrl(m) == c;
2089 }
2090 
2091 Node* MemoryGraphFixer::find_mem(Node* ctrl, Node* n) const {
2092   assert(n == nullptr || _phase->ctrl_or_self(n) == ctrl, "");
2093   assert(!ctrl->is_Call() || ctrl == n, "projection expected");
2094 #ifdef ASSERT
2095   if ((ctrl->is_Proj() && ctrl->in(0)->is_Call()) ||
2096       (ctrl->is_Catch() && ctrl->in(0)->in(0)->is_Call())) {
2097     CallNode* call = ctrl->is_Proj() ? ctrl->in(0)->as_Call() : ctrl->in(0)->in(0)->as_Call();
2098     int mems = 0;
2099     for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
2100       Node* u = call->fast_out(i);
2101       if (u->bottom_type() == Type::MEMORY) {
2102         mems++;
2103       }
2104     }
2105     assert(mems <= 1, "No node right after call if multiple mem projections");
2106   }
2107 #endif
2108   Node* mem = _memory_nodes[ctrl->_idx];
2109   Node* c = ctrl;
2110   while (!mem_is_valid(mem, c) &&
2111          (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem))) {
2112     c = _phase->idom(c);
2113     mem = _memory_nodes[c->_idx];
2114   }
2115   if (n != nullptr && mem_is_valid(mem, c)) {
2116     while (!ShenandoahBarrierC2Support::is_dominator_same_ctrl(c, mem, n, _phase) && _phase->ctrl_or_self(mem) == ctrl) {
2117       mem = next_mem(mem, _alias);
2118     }
2119     if (mem->is_MergeMem()) {
2120       mem = mem->as_MergeMem()->memory_at(_alias);
2121     }
2122     if (!mem_is_valid(mem, c)) {
2123       do {
2124         c = _phase->idom(c);
2125         mem = _memory_nodes[c->_idx];
2126       } while (!mem_is_valid(mem, c) &&
2127                (!c->is_CatchProj() || mem == nullptr || c->in(0)->in(0)->in(0) != get_ctrl(mem)));
2128     }
2129   }
2130   assert(mem->bottom_type() == Type::MEMORY, "");
2131   return mem;
2132 }
2133 
2134 bool MemoryGraphFixer::has_mem_phi(Node* region) const {
2135   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2136     Node* use = region->fast_out(i);
2137     if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
2138         (_phase->C->get_alias_index(use->adr_type()) == _alias)) {
2139       return true;
2140     }
2141   }
2142   return false;
2143 }
2144 
2145 void MemoryGraphFixer::fix_mem(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl, Node* new_mem, Unique_Node_List& uses) {
2146   assert(_phase->ctrl_or_self(new_mem) == new_ctrl, "");
2147   const bool trace = false;
2148   DEBUG_ONLY(if (trace) { tty->print("ZZZ control is"); ctrl->dump(); });
2149   DEBUG_ONLY(if (trace) { tty->print("ZZZ mem is"); mem->dump(); });
2150   GrowableArray<Node*> phis;
2151   if (mem_for_ctrl != mem) {
2152     Node* old = mem_for_ctrl;
2153     Node* prev = nullptr;
2154     while (old != mem) {
2155       prev = old;
2156       if (old->is_Store() || old->is_ClearArray() || old->is_LoadStore()) {
2157         assert(_alias == Compile::AliasIdxRaw, "");
2158         old = old->in(MemNode::Memory);
2159       } else if (old->Opcode() == Op_SCMemProj) {
2160         assert(_alias == Compile::AliasIdxRaw, "");
2161         old = old->in(0);
2162       } else {
2163         ShouldNotReachHere();
2164       }
2165     }
2166     assert(prev != nullptr, "");
2167     if (new_ctrl != ctrl) {
2168       _memory_nodes.map(ctrl->_idx, mem);
2169       _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2170     }
2171     uint input = (uint)MemNode::Memory;
2172     _phase->igvn().replace_input_of(prev, input, new_mem);
2173   } else {
2174     uses.clear();
2175     _memory_nodes.map(new_ctrl->_idx, new_mem);
2176     uses.push(new_ctrl);
2177     for(uint next = 0; next < uses.size(); next++ ) {
2178       Node *n = uses.at(next);
2179       assert(n->is_CFG(), "");
2180       DEBUG_ONLY(if (trace) { tty->print("ZZZ ctrl"); n->dump(); });
2181       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2182         Node* u = n->fast_out(i);
2183         if (!u->is_Root() && u->is_CFG() && u != n) {
2184           Node* m = _memory_nodes[u->_idx];
2185           if (u->is_Region() && (!u->is_OuterStripMinedLoop() || _include_lsm) &&
2186               !has_mem_phi(u) &&
2187               u->unique_ctrl_out()->Opcode() != Op_Halt) {
2188             DEBUG_ONLY(if (trace) { tty->print("ZZZ region"); u->dump(); });
2189             DEBUG_ONLY(if (trace && m != nullptr) { tty->print("ZZZ mem"); m->dump(); });
2190 
2191             if (!mem_is_valid(m, u) || !m->is_Phi()) {
2192               bool push = true;
2193               bool create_phi = true;
2194               if (_phase->is_dominator(new_ctrl, u)) {
2195                 create_phi = false;
2196               }
2197               if (create_phi) {
2198                 Node* phi = new PhiNode(u, Type::MEMORY, _phase->C->get_adr_type(_alias));
2199                 _phase->register_new_node(phi, u);
2200                 phis.push(phi);
2201                 DEBUG_ONLY(if (trace) { tty->print("ZZZ new phi"); phi->dump(); });
2202                 if (!mem_is_valid(m, u)) {
2203                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting mem"); phi->dump(); });
2204                   _memory_nodes.map(u->_idx, phi);
2205                 } else {
2206                   DEBUG_ONLY(if (trace) { tty->print("ZZZ NOT setting mem"); m->dump(); });
2207                   for (;;) {
2208                     assert(m->is_Mem() || m->is_LoadStore() || m->is_Proj(), "");
2209                     Node* next = nullptr;
2210                     if (m->is_Proj()) {
2211                       next = m->in(0);
2212                     } else {
2213                       assert(m->is_Mem() || m->is_LoadStore(), "");
2214                       assert(_alias == Compile::AliasIdxRaw, "");
2215                       next = m->in(MemNode::Memory);
2216                     }
2217                     if (_phase->get_ctrl(next) != u) {
2218                       break;
2219                     }
2220                     if (next->is_MergeMem()) {
2221                       assert(_phase->get_ctrl(next->as_MergeMem()->memory_at(_alias)) != u, "");
2222                       break;
2223                     }
2224                     if (next->is_Phi()) {
2225                       assert(next->adr_type() == TypePtr::BOTTOM && next->in(0) == u, "");
2226                       break;
2227                     }
2228                     m = next;
2229                   }
2230 
2231                   DEBUG_ONLY(if (trace) { tty->print("ZZZ setting to phi"); m->dump(); });
2232                   assert(m->is_Mem() || m->is_LoadStore(), "");
2233                   uint input = (uint)MemNode::Memory;
2234                   _phase->igvn().replace_input_of(m, input, phi);
2235                   push = false;
2236                 }
2237               } else {
2238                 DEBUG_ONLY(if (trace) { tty->print("ZZZ skipping region"); u->dump(); });
2239               }
2240               if (push) {
2241                 uses.push(u);
2242               }
2243             }
2244           } else if (!mem_is_valid(m, u) &&
2245                      !(u->Opcode() == Op_CProj && u->in(0)->is_NeverBranch() && u->as_Proj()->_con == 1)) {
2246             uses.push(u);
2247           }
2248         }
2249       }
2250     }
2251     for (int i = 0; i < phis.length(); i++) {
2252       Node* n = phis.at(i);
2253       Node* r = n->in(0);
2254       DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi"); n->dump(); });
2255       for (uint j = 1; j < n->req(); j++) {
2256         Node* m = find_mem(r->in(j), nullptr);
2257         _phase->igvn().replace_input_of(n, j, m);
2258         DEBUG_ONLY(if (trace) { tty->print("ZZZ fixing new phi: %d", j); m->dump(); });
2259       }
2260     }
2261   }
2262   uint last = _phase->C->unique();
2263   MergeMemNode* mm = nullptr;
2264   int alias = _alias;
2265   DEBUG_ONLY(if (trace) { tty->print("ZZZ raw mem is"); mem->dump(); });
2266   // Process loads first to not miss an anti-dependency: if the memory
2267   // edge of a store is updated before a load is processed then an
2268   // anti-dependency may be missed.
2269   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2270     Node* u = mem->out(i);
2271     if (u->_idx < last && u->is_Load() && _phase->C->get_alias_index(u->adr_type()) == alias) {
2272       Node* m = find_mem(_phase->get_ctrl(u), u);
2273       if (m != mem) {
2274         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2275         _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2276         --i;
2277       }
2278     }
2279   }
2280   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2281     Node* u = mem->out(i);
2282     if (u->_idx < last) {
2283       if (u->is_Mem()) {
2284         if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2285           Node* m = find_mem(_phase->get_ctrl(u), u);
2286           if (m != mem) {
2287             DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2288             _phase->igvn().replace_input_of(u, MemNode::Memory, m);
2289             --i;
2290           }
2291         }
2292       } else if (u->is_MergeMem()) {
2293         MergeMemNode* u_mm = u->as_MergeMem();
2294         if (u_mm->memory_at(alias) == mem) {
2295           MergeMemNode* newmm = nullptr;
2296           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2297             Node* uu = u->fast_out(j);
2298             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2299             if (uu->is_Phi()) {
2300               assert(uu->adr_type() == TypePtr::BOTTOM, "");
2301               Node* region = uu->in(0);
2302               int nb = 0;
2303               for (uint k = 1; k < uu->req(); k++) {
2304                 if (uu->in(k) == u) {
2305                   Node* m = find_mem(region->in(k), nullptr);
2306                   if (m != mem) {
2307                     DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", k); uu->dump(); });
2308                     newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2309                     if (newmm != u) {
2310                       _phase->igvn().replace_input_of(uu, k, newmm);
2311                       nb++;
2312                       --jmax;
2313                     }
2314                   }
2315                 }
2316               }
2317               if (nb > 0) {
2318                 --j;
2319               }
2320             } else {
2321               Node* m = find_mem(_phase->ctrl_or_self(uu), uu);
2322               if (m != mem) {
2323                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); uu->dump(); });
2324                 newmm = clone_merge_mem(u, mem, m, _phase->ctrl_or_self(m), i);
2325                 if (newmm != u) {
2326                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2327                   --j, --jmax;
2328                 }
2329               }
2330             }
2331           }
2332         }
2333       } else if (u->is_Phi()) {
2334         assert(u->bottom_type() == Type::MEMORY, "what else?");
2335         if (_phase->C->get_alias_index(u->adr_type()) == alias || u->adr_type() == TypePtr::BOTTOM) {
2336           Node* region = u->in(0);
2337           bool replaced = false;
2338           for (uint j = 1; j < u->req(); j++) {
2339             if (u->in(j) == mem) {
2340               Node* m = find_mem(region->in(j), nullptr);
2341               Node* nnew = m;
2342               if (m != mem) {
2343                 if (u->adr_type() == TypePtr::BOTTOM) {
2344                   mm = allocate_merge_mem(mem, m, _phase->ctrl_or_self(m));
2345                   nnew = mm;
2346                 }
2347                 DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of phi %d", j); u->dump(); });
2348                 _phase->igvn().replace_input_of(u, j, nnew);
2349                 replaced = true;
2350               }
2351             }
2352           }
2353           if (replaced) {
2354             --i;
2355           }
2356         }
2357       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2358                  u->adr_type() == nullptr) {
2359         assert(u->adr_type() != nullptr ||
2360                u->Opcode() == Op_Rethrow ||
2361                u->Opcode() == Op_Return ||
2362                u->Opcode() == Op_SafePoint ||
2363                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2364                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2365                u->Opcode() == Op_CallLeaf, "");
2366         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2367         if (m != mem) {
2368           mm = allocate_merge_mem(mem, m, _phase->get_ctrl(m));
2369           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2370           --i;
2371         }
2372       } else if (_phase->C->get_alias_index(u->adr_type()) == alias) {
2373         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2374         if (m != mem) {
2375           DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2376           _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2377           --i;
2378         }
2379       } else if (u->adr_type() != TypePtr::BOTTOM &&
2380                  _memory_nodes[_phase->ctrl_or_self(u)->_idx] == u) {
2381         Node* m = find_mem(_phase->ctrl_or_self(u), u);
2382         assert(m != mem, "");
2383         // u is on the wrong slice...
2384         assert(u->is_ClearArray(), "");
2385         DEBUG_ONLY(if (trace) { tty->print("ZZZ setting memory of use"); u->dump(); });
2386         _phase->igvn().replace_input_of(u, u->find_edge(mem), m);
2387         --i;
2388       }
2389     }
2390   }
2391 #ifdef ASSERT
2392   assert(new_mem->outcnt() > 0, "");
2393   for (int i = 0; i < phis.length(); i++) {
2394     Node* n = phis.at(i);
2395     assert(n->outcnt() > 0, "new phi must have uses now");
2396   }
2397 #endif
2398 }
2399 
2400 void MemoryGraphFixer::record_new_ctrl(Node* ctrl, Node* new_ctrl, Node* mem, Node* mem_for_ctrl) {
2401   if (mem_for_ctrl != mem && new_ctrl != ctrl) {
2402     _memory_nodes.map(ctrl->_idx, mem);
2403     _memory_nodes.map(new_ctrl->_idx, mem_for_ctrl);
2404   }
2405 }
2406 
2407 MergeMemNode* MemoryGraphFixer::allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const {
2408   MergeMemNode* mm = MergeMemNode::make(mem);
2409   mm->set_memory_at(_alias, rep_proj);
2410   _phase->register_new_node(mm, rep_ctrl);
2411   return mm;
2412 }
2413 
2414 MergeMemNode* MemoryGraphFixer::clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const {
2415   MergeMemNode* newmm = nullptr;
2416   MergeMemNode* u_mm = u->as_MergeMem();
2417   Node* c = _phase->get_ctrl(u);
2418   if (_phase->is_dominator(c, rep_ctrl)) {
2419     c = rep_ctrl;
2420   } else {
2421     assert(_phase->is_dominator(rep_ctrl, c), "one must dominate the other");
2422   }
2423   if (u->outcnt() == 1) {
2424     if (u->req() > (uint)_alias && u->in(_alias) == mem) {
2425       _phase->igvn().replace_input_of(u, _alias, rep_proj);
2426       --i;
2427     } else {
2428       _phase->igvn().rehash_node_delayed(u);
2429       u_mm->set_memory_at(_alias, rep_proj);
2430     }
2431     newmm = u_mm;
2432     _phase->set_ctrl_and_loop(u, c);
2433   } else {
2434     // can't simply clone u and then change one of its input because
2435     // it adds and then removes an edge which messes with the
2436     // DUIterator
2437     newmm = MergeMemNode::make(u_mm->base_memory());
2438     for (uint j = 0; j < u->req(); j++) {
2439       if (j < newmm->req()) {
2440         if (j == (uint)_alias) {
2441           newmm->set_req(j, rep_proj);
2442         } else if (newmm->in(j) != u->in(j)) {
2443           newmm->set_req(j, u->in(j));
2444         }
2445       } else if (j == (uint)_alias) {
2446         newmm->add_req(rep_proj);
2447       } else {
2448         newmm->add_req(u->in(j));
2449       }
2450     }
2451     if ((uint)_alias >= u->req()) {
2452       newmm->set_memory_at(_alias, rep_proj);
2453     }
2454     _phase->register_new_node(newmm, c);
2455   }
2456   return newmm;
2457 }
2458 
2459 bool MemoryGraphFixer::should_process_phi(Node* phi) const {
2460   if (phi->adr_type() == TypePtr::BOTTOM) {
2461     Node* region = phi->in(0);
2462     for (DUIterator_Fast jmax, j = region->fast_outs(jmax); j < jmax; j++) {
2463       Node* uu = region->fast_out(j);
2464       if (uu->is_Phi() && uu != phi && uu->bottom_type() == Type::MEMORY && _phase->C->get_alias_index(uu->adr_type()) == _alias) {
2465         return false;
2466       }
2467     }
2468     return true;
2469   }
2470   return _phase->C->get_alias_index(phi->adr_type()) == _alias;
2471 }
2472 
2473 void MemoryGraphFixer::fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const {
2474   uint last = _phase-> C->unique();
2475   MergeMemNode* mm = nullptr;
2476   assert(mem->bottom_type() == Type::MEMORY, "");
2477   for (DUIterator i = mem->outs(); mem->has_out(i); i++) {
2478     Node* u = mem->out(i);
2479     if (u != replacement && u->_idx < last) {
2480       if (u->is_MergeMem()) {
2481         MergeMemNode* u_mm = u->as_MergeMem();
2482         if (u_mm->memory_at(_alias) == mem) {
2483           MergeMemNode* newmm = nullptr;
2484           for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
2485             Node* uu = u->fast_out(j);
2486             assert(!uu->is_MergeMem(), "chain of MergeMems?");
2487             if (uu->is_Phi()) {
2488               if (should_process_phi(uu)) {
2489                 Node* region = uu->in(0);
2490                 int nb = 0;
2491                 for (uint k = 1; k < uu->req(); k++) {
2492                   if (uu->in(k) == u && _phase->is_dominator(rep_ctrl, region->in(k))) {
2493                     if (newmm == nullptr) {
2494                       newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2495                     }
2496                     if (newmm != u) {
2497                       _phase->igvn().replace_input_of(uu, k, newmm);
2498                       nb++;
2499                       --jmax;
2500                     }
2501                   }
2502                 }
2503                 if (nb > 0) {
2504                   --j;
2505                 }
2506               }
2507             } else {
2508               if (rep_ctrl != uu && ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(uu), replacement, uu, _phase)) {
2509                 if (newmm == nullptr) {
2510                   newmm = clone_merge_mem(u, mem, rep_proj, rep_ctrl, i);
2511                 }
2512                 if (newmm != u) {
2513                   _phase->igvn().replace_input_of(uu, uu->find_edge(u), newmm);
2514                   --j, --jmax;
2515                 }
2516               }
2517             }
2518           }
2519         }
2520       } else if (u->is_Phi()) {
2521         assert(u->bottom_type() == Type::MEMORY, "what else?");
2522         Node* region = u->in(0);
2523         if (should_process_phi(u)) {
2524           bool replaced = false;
2525           for (uint j = 1; j < u->req(); j++) {
2526             if (u->in(j) == mem && _phase->is_dominator(rep_ctrl, region->in(j))) {
2527               Node* nnew = rep_proj;
2528               if (u->adr_type() == TypePtr::BOTTOM) {
2529                 if (mm == nullptr) {
2530                   mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2531                 }
2532                 nnew = mm;
2533               }
2534               _phase->igvn().replace_input_of(u, j, nnew);
2535               replaced = true;
2536             }
2537           }
2538           if (replaced) {
2539             --i;
2540           }
2541 
2542         }
2543       } else if ((u->adr_type() == TypePtr::BOTTOM && u->Opcode() != Op_StrInflatedCopy) ||
2544                  u->adr_type() == nullptr) {
2545         assert(u->adr_type() != nullptr ||
2546                u->Opcode() == Op_Rethrow ||
2547                u->Opcode() == Op_Return ||
2548                u->Opcode() == Op_SafePoint ||
2549                (u->is_CallStaticJava() && u->as_CallStaticJava()->uncommon_trap_request() != 0) ||
2550                (u->is_CallStaticJava() && u->as_CallStaticJava()->_entry_point == OptoRuntime::rethrow_stub()) ||
2551                u->Opcode() == Op_CallLeaf, "%s", u->Name());
2552         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2553           if (mm == nullptr) {
2554             mm = allocate_merge_mem(mem, rep_proj, rep_ctrl);
2555           }
2556           _phase->igvn().replace_input_of(u, u->find_edge(mem), mm);
2557           --i;
2558         }
2559       } else if (_phase->C->get_alias_index(u->adr_type()) == _alias) {
2560         if (ShenandoahBarrierC2Support::is_dominator(rep_ctrl, _phase->ctrl_or_self(u), replacement, u, _phase)) {
2561           _phase->igvn().replace_input_of(u, u->find_edge(mem), rep_proj);
2562           --i;
2563         }
2564       }
2565     }
2566   }
2567 }
2568 
2569 ShenandoahLoadReferenceBarrierNode::ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* obj, DecoratorSet decorators)
2570 : Node(ctrl, obj), _decorators(decorators) {
2571   ShenandoahBarrierSetC2::bsc2()->state()->add_load_reference_barrier(this);
2572 }
2573 
2574 DecoratorSet ShenandoahLoadReferenceBarrierNode::decorators() const {
2575   return _decorators;
2576 }
2577 
2578 uint ShenandoahLoadReferenceBarrierNode::size_of() const {
2579   return sizeof(*this);
2580 }
2581 
2582 static DecoratorSet mask_decorators(DecoratorSet decorators) {
2583   return decorators & (ON_STRONG_OOP_REF | ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF | ON_UNKNOWN_OOP_REF | IN_NATIVE);
2584 }
2585 
2586 uint ShenandoahLoadReferenceBarrierNode::hash() const {
2587   uint hash = Node::hash();
2588   hash += mask_decorators(_decorators);
2589   return hash;
2590 }
2591 
2592 bool ShenandoahLoadReferenceBarrierNode::cmp( const Node &n ) const {
2593   return Node::cmp(n) && n.Opcode() == Op_ShenandoahLoadReferenceBarrier &&
2594          mask_decorators(_decorators) == mask_decorators(((const ShenandoahLoadReferenceBarrierNode&)n)._decorators);
2595 }
2596 
2597 const Type* ShenandoahLoadReferenceBarrierNode::bottom_type() const {
2598   if (in(ValueIn) == nullptr || in(ValueIn)->is_top()) {
2599     return Type::TOP;
2600   }
2601   const Type* t = in(ValueIn)->bottom_type();
2602   if (t == TypePtr::NULL_PTR) {
2603     return t;
2604   }
2605 
2606   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2607     return t;
2608   }
2609 
2610   return t->meet(TypePtr::NULL_PTR);
2611 }
2612 
2613 const Type* ShenandoahLoadReferenceBarrierNode::Value(PhaseGVN* phase) const {
2614   // Either input is TOP ==> the result is TOP
2615   const Type *t2 = phase->type(in(ValueIn));
2616   if( t2 == Type::TOP ) return Type::TOP;
2617 
2618   if (t2 == TypePtr::NULL_PTR) {
2619     return t2;
2620   }
2621 
2622   if (ShenandoahBarrierSet::is_strong_access(decorators())) {
2623     return t2;
2624   }
2625 
2626   return t2->meet(TypePtr::NULL_PTR);
2627 }
2628 
2629 Node* ShenandoahLoadReferenceBarrierNode::Identity(PhaseGVN* phase) {
2630   Node* value = in(ValueIn);
2631   if (!needs_barrier(phase, value)) {
2632     return value;
2633   }
2634   return this;
2635 }
2636 
2637 bool ShenandoahLoadReferenceBarrierNode::needs_barrier(PhaseGVN* phase, Node* n) {
2638   Unique_Node_List visited;
2639   return needs_barrier_impl(phase, n, visited);
2640 }
2641 
2642 bool ShenandoahLoadReferenceBarrierNode::needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited) {
2643   if (n == nullptr) return false;
2644   if (visited.member(n)) {
2645     return false; // Been there.
2646   }
2647   visited.push(n);
2648 
2649   if (n->is_Allocate()) {
2650     // tty->print_cr("optimize barrier on alloc");
2651     return false;
2652   }
2653   if (n->is_Call()) {
2654     // tty->print_cr("optimize barrier on call");
2655     return false;
2656   }
2657 
2658   const Type* type = phase->type(n);
2659   if (type == Type::TOP) {
2660     return false;
2661   }
2662   if (type->make_ptr()->higher_equal(TypePtr::NULL_PTR)) {
2663     // tty->print_cr("optimize barrier on null");
2664     return false;
2665   }
2666   if (type->make_oopptr() && type->make_oopptr()->const_oop() != nullptr) {
2667     // tty->print_cr("optimize barrier on constant");
2668     return false;
2669   }
2670 
2671   switch (n->Opcode()) {
2672     case Op_AddP:
2673       return true; // TODO: Can refine?
2674     case Op_LoadP:
2675     case Op_ShenandoahCompareAndExchangeN:
2676     case Op_ShenandoahCompareAndExchangeP:
2677     case Op_CompareAndExchangeN:
2678     case Op_CompareAndExchangeP:
2679     case Op_GetAndSetN:
2680     case Op_GetAndSetP:
2681       return true;
2682     case Op_Phi: {
2683       for (uint i = 1; i < n->req(); i++) {
2684         if (needs_barrier_impl(phase, n->in(i), visited)) return true;
2685       }
2686       return false;
2687     }
2688     case Op_CheckCastPP:
2689     case Op_CastPP:
2690       return needs_barrier_impl(phase, n->in(1), visited);
2691     case Op_Proj:
2692       return needs_barrier_impl(phase, n->in(0), visited);
2693     case Op_ShenandoahLoadReferenceBarrier:
2694       // tty->print_cr("optimize barrier on barrier");
2695       return false;
2696     case Op_Parm:
2697       // tty->print_cr("optimize barrier on input arg");
2698       return false;
2699     case Op_DecodeN:
2700     case Op_EncodeP:
2701       return needs_barrier_impl(phase, n->in(1), visited);
2702     case Op_LoadN:
2703       return true;
2704     case Op_CMoveN:
2705     case Op_CMoveP:
2706       return needs_barrier_impl(phase, n->in(2), visited) ||
2707              needs_barrier_impl(phase, n->in(3), visited);
2708     case Op_CreateEx:
2709       return false;
2710     default:
2711       break;
2712   }
2713 #ifdef ASSERT
2714   tty->print("need barrier on?: ");
2715   tty->print_cr("ins:");
2716   n->dump(2);
2717   tty->print_cr("outs:");
2718   n->dump(-2);
2719   ShouldNotReachHere();
2720 #endif
2721   return true;
2722 }