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