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