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