< prev index next >

src/hotspot/share/opto/compile.cpp

Print this page

   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "asm/macroAssembler.inline.hpp"


  27 #include "ci/ciReplay.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "code/aotCodeCache.hpp"
  30 #include "code/exceptionHandlerTable.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "compiler/compilationFailureInfo.hpp"
  33 #include "compiler/compilationMemoryStatistic.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compileLog.hpp"
  36 #include "compiler/compiler_globals.hpp"
  37 #include "compiler/compilerDefinitions.hpp"
  38 #include "compiler/compilerOracle.hpp"
  39 #include "compiler/disassembler.hpp"
  40 #include "compiler/oopMap.hpp"
  41 #include "gc/shared/barrierSet.hpp"
  42 #include "gc/shared/c2/barrierSetC2.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "jvm_io.h"
  45 #include "memory/allocation.hpp"
  46 #include "memory/arena.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "opto/addnode.hpp"
  49 #include "opto/block.hpp"
  50 #include "opto/c2compiler.hpp"
  51 #include "opto/callGenerator.hpp"
  52 #include "opto/callnode.hpp"
  53 #include "opto/castnode.hpp"
  54 #include "opto/cfgnode.hpp"
  55 #include "opto/chaitin.hpp"
  56 #include "opto/compile.hpp"
  57 #include "opto/connode.hpp"
  58 #include "opto/convertnode.hpp"
  59 #include "opto/divnode.hpp"
  60 #include "opto/escape.hpp"
  61 #include "opto/idealGraphPrinter.hpp"

  62 #include "opto/locknode.hpp"
  63 #include "opto/loopnode.hpp"
  64 #include "opto/machnode.hpp"
  65 #include "opto/macro.hpp"
  66 #include "opto/matcher.hpp"
  67 #include "opto/mathexactnode.hpp"
  68 #include "opto/memnode.hpp"

  69 #include "opto/mulnode.hpp"

  70 #include "opto/narrowptrnode.hpp"
  71 #include "opto/node.hpp"
  72 #include "opto/opaquenode.hpp"
  73 #include "opto/opcodes.hpp"
  74 #include "opto/output.hpp"
  75 #include "opto/parse.hpp"
  76 #include "opto/phaseX.hpp"
  77 #include "opto/reachability.hpp"
  78 #include "opto/rootnode.hpp"
  79 #include "opto/runtime.hpp"
  80 #include "opto/stringopts.hpp"
  81 #include "opto/type.hpp"
  82 #include "opto/vector.hpp"
  83 #include "opto/vectornode.hpp"

  84 #include "runtime/globals_extension.hpp"
  85 #include "runtime/sharedRuntime.hpp"
  86 #include "runtime/signature.hpp"
  87 #include "runtime/stubRoutines.hpp"
  88 #include "runtime/timer.hpp"
  89 #include "utilities/align.hpp"
  90 #include "utilities/copy.hpp"
  91 #include "utilities/hashTable.hpp"
  92 #include "utilities/macros.hpp"
  93 
  94 // -------------------- Compile::mach_constant_base_node -----------------------
  95 // Constant table base node singleton.
  96 MachConstantBaseNode* Compile::mach_constant_base_node() {
  97   if (_mach_constant_base_node == nullptr) {
  98     _mach_constant_base_node = new MachConstantBaseNode();
  99     _mach_constant_base_node->add_req(C->root());
 100   }
 101   return _mach_constant_base_node;
 102 }
 103 

 392     record_dead_node(dead->_idx);
 393   }
 394   if (dead->is_macro()) {
 395     remove_macro_node(dead);
 396   }
 397   if (dead->is_expensive()) {
 398     remove_expensive_node(dead);
 399   }
 400   if (dead->is_ReachabilityFence()) {
 401     remove_reachability_fence(dead->as_ReachabilityFence());
 402   }
 403   if (dead->is_OpaqueTemplateAssertionPredicate()) {
 404     remove_template_assertion_predicate_opaque(dead->as_OpaqueTemplateAssertionPredicate());
 405   }
 406   if (dead->is_ParsePredicate()) {
 407     remove_parse_predicate(dead->as_ParsePredicate());
 408   }
 409   if (dead->for_post_loop_opts_igvn()) {
 410     remove_from_post_loop_opts_igvn(dead);
 411   }






 412   if (dead->for_merge_stores_igvn()) {
 413     remove_from_merge_stores_igvn(dead);
 414   }
 415   if (dead->is_Call()) {
 416     remove_useless_late_inlines(                &_late_inlines, dead);
 417     remove_useless_late_inlines(         &_string_late_inlines, dead);
 418     remove_useless_late_inlines(         &_boxing_late_inlines, dead);
 419     remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
 420 
 421     if (dead->is_CallStaticJava()) {
 422       remove_unstable_if_trap(dead->as_CallStaticJava(), false);
 423     }
 424   }
 425   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 426   bs->unregister_potential_barrier_node(dead);
 427 }
 428 
 429 // Disconnect all useless nodes by disconnecting those at the boundary.
 430 void Compile::disconnect_useless_nodes(Unique_Node_List& useful, Unique_Node_List& worklist, const Unique_Node_List* root_and_safepoints) {
 431   uint next = 0;

 439     // Use raw traversal of out edges since this code removes out edges
 440     int max = n->outcnt();
 441     for (int j = 0; j < max; ++j) {
 442       Node* child = n->raw_out(j);
 443       if (!useful.member(child)) {
 444         assert(!child->is_top() || child != top(),
 445                "If top is cached in Compile object it is in useful list");
 446         // Only need to remove this out-edge to the useless node
 447         n->raw_del_out(j);
 448         --j;
 449         --max;
 450         if (child->is_data_proj_of_pure_function(n)) {
 451           worklist.push(n);
 452         }
 453       }
 454     }
 455     if (n->outcnt() == 1 && n->has_special_unique_user()) {
 456       assert(useful.member(n->unique_out()), "do not push a useless node");
 457       worklist.push(n->unique_out());
 458     }



 459   }
 460 
 461   remove_useless_nodes(_macro_nodes,        useful); // remove useless macro nodes
 462   remove_useless_nodes(_parse_predicates,   useful); // remove useless Parse Predicate nodes
 463   // Remove useless Template Assertion Predicate opaque nodes
 464   remove_useless_nodes(_template_assertion_predicate_opaques, useful);
 465   remove_useless_nodes(_expensive_nodes,    useful); // remove useless expensive nodes
 466   remove_useless_nodes(_reachability_fences, useful); // remove useless node recorded for post loop opts IGVN pass
 467   remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass







 468   remove_useless_nodes(_for_merge_stores_igvn, useful); // remove useless node recorded for merge stores IGVN pass
 469   remove_useless_unstable_if_traps(useful);          // remove useless unstable_if traps
 470   remove_useless_coarsened_locks(useful);            // remove useless coarsened locks nodes
 471 #ifdef ASSERT
 472   if (_modified_nodes != nullptr) {
 473     _modified_nodes->remove_useless_nodes(useful.member_set());
 474   }
 475 #endif
 476 
 477   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 478   bs->eliminate_useless_gc_barriers(useful, this);
 479   // clean up the late inline lists
 480   remove_useless_late_inlines(                &_late_inlines, useful);
 481   remove_useless_late_inlines(         &_string_late_inlines, useful);
 482   remove_useless_late_inlines(         &_boxing_late_inlines, useful);
 483   remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
 484   DEBUG_ONLY(verify_graph_edges(true /*check for no_dead_code*/, root_and_safepoints);)
 485 }
 486 
 487 // ============================================================================

 635 
 636 Compile::Compile(ciEnv* ci_env, ciMethod* target, int osr_bci,
 637                  Options options, DirectiveSet* directive)
 638     : Phase(Compiler),
 639       _compile_id(ci_env->compile_id()),
 640       _options(options),
 641       _method(target),
 642       _entry_bci(osr_bci),
 643       _ilt(nullptr),
 644       _stub_function(nullptr),
 645       _stub_name(nullptr),
 646       _stub_id(StubId::NO_STUBID),
 647       _stub_entry_point(nullptr),
 648       _max_node_limit(MaxNodeLimit),
 649       _node_count_inlining_cutoff(NodeCountInliningCutoff),
 650       _post_loop_opts_phase(false),
 651       _merge_stores_phase(false),
 652       _allow_macro_nodes(true),
 653       _inlining_progress(false),
 654       _inlining_incrementally(false),

 655       _do_cleanup(false),
 656       _has_reserved_stack_access(target->has_reserved_stack_access()),

 657 #ifndef PRODUCT
 658       _igv_idx(0),
 659       _trace_opto_output(directive->TraceOptoOutputOption),
 660 #endif
 661       _clinit_barrier_on_entry(false),
 662       _stress_seed(0),
 663       _comp_arena(mtCompiler, Arena::Tag::tag_comp),
 664       _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 665       _env(ci_env),
 666       _directive(directive),
 667       _log(ci_env->log()),
 668       _first_failure_details(nullptr),
 669       _intrinsics(comp_arena(), 0, 0, nullptr),
 670       _macro_nodes(comp_arena(), 8, 0, nullptr),
 671       _parse_predicates(comp_arena(), 8, 0, nullptr),
 672       _template_assertion_predicate_opaques(comp_arena(), 8, 0, nullptr),
 673       _expensive_nodes(comp_arena(), 8, 0, nullptr),
 674       _reachability_fences(comp_arena(), 8, 0, nullptr),
 675       _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),


 676       _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
 677       _unstable_if_traps(comp_arena(), 8, 0, nullptr),
 678       _coarsened_locks(comp_arena(), 8, 0, nullptr),
 679       _congraph(nullptr),
 680       NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 681       _unique(0),
 682       _dead_node_count(0),
 683       _dead_node_list(comp_arena()),
 684       _node_arena_one(mtCompiler, Arena::Tag::tag_node),
 685       _node_arena_two(mtCompiler, Arena::Tag::tag_node),
 686       _node_arena(&_node_arena_one),
 687       _mach_constant_base_node(nullptr),
 688       _Compile_types(mtCompiler, Arena::Tag::tag_type),
 689       _initial_gvn(nullptr),
 690       _igvn_worklist(nullptr),
 691       _types(nullptr),
 692       _node_hash(nullptr),
 693       _late_inlines(comp_arena(), 2, 0, nullptr),
 694       _string_late_inlines(comp_arena(), 2, 0, nullptr),
 695       _boxing_late_inlines(comp_arena(), 2, 0, nullptr),

 764 #define MINIMUM_NODE_HASH  1023
 765 
 766   // GVN that will be run immediately on new nodes
 767   uint estimated_size = method()->code_size()*4+64;
 768   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 769   _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
 770   _types = new (comp_arena()) Type_Array(comp_arena());
 771   _node_hash = new (comp_arena()) NodeHash(comp_arena(), estimated_size);
 772   PhaseGVN gvn;
 773   set_initial_gvn(&gvn);
 774 
 775   { // Scope for timing the parser
 776     TracePhase tp(_t_parser);
 777 
 778     // Put top into the hash table ASAP.
 779     initial_gvn()->transform(top());
 780 
 781     // Set up tf(), start(), and find a CallGenerator.
 782     CallGenerator* cg = nullptr;
 783     if (is_osr_compilation()) {
 784       const TypeTuple *domain = StartOSRNode::osr_domain();
 785       const TypeTuple *range = TypeTuple::make_range(method()->signature());
 786       init_tf(TypeFunc::make(domain, range));
 787       StartNode* s = new StartOSRNode(root(), domain);
 788       initial_gvn()->set_type_bottom(s);
 789       verify_start(s);
 790       cg = CallGenerator::for_osr(method(), entry_bci());
 791     } else {
 792       // Normal case.
 793       init_tf(TypeFunc::make(method()));
 794       StartNode* s = new StartNode(root(), tf()->domain());
 795       initial_gvn()->set_type_bottom(s);
 796       verify_start(s);
 797       float past_uses = method()->interpreter_invocation_count();
 798       float expected_uses = past_uses;
 799       cg = CallGenerator::for_inline(method(), expected_uses);
 800     }
 801     if (failing())  return;
 802     if (cg == nullptr) {
 803       const char* reason = InlineTree::check_can_parse(method());
 804       assert(reason != nullptr, "expect reason for parse failure");
 805       stringStream ss;
 806       ss.print("cannot parse method: %s", reason);
 807       record_method_not_compilable(ss.as_string());
 808       return;
 809     }
 810 
 811     gvn.set_type(root(), root()->bottom_type());
 812 
 813     JVMState* jvms = build_start_state(start(), tf());
 814     if ((jvms = cg->generate(jvms)) == nullptr) {

 872 
 873 #ifndef PRODUCT
 874   if (should_print_ideal()) {
 875     print_ideal_ir("PrintIdeal");
 876   }
 877 #endif
 878 
 879 #ifdef ASSERT
 880   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 881   bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
 882 #endif
 883 
 884   // Dump compilation data to replay it.
 885   if (directive->DumpReplayOption) {
 886     env()->dump_replay_data(_compile_id);
 887   }
 888   if (directive->DumpInlineOption && (ilt() != nullptr)) {
 889     env()->dump_inline_data(_compile_id);
 890   }
 891 
 892   // Now that we know the size of all the monitors we can add a fixed slot
 893   // for the original deopt pc.
 894   int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
























 895   set_fixed_slots(next_slot);
 896 
 897   // Compute when to use implicit null checks. Used by matching trap based
 898   // nodes and NullCheck optimization.
 899   set_allowed_deopt_reasons();
 900 
 901   // Now generate code
 902   Code_Gen();
 903 }
 904 
 905 //------------------------------Compile----------------------------------------
 906 // Compile a runtime stub
 907 Compile::Compile(ciEnv* ci_env,
 908                  TypeFunc_generator generator,
 909                  address stub_function,
 910                  const char* stub_name,
 911                  StubId stub_id,
 912                  int is_fancy_jump,
 913                  bool pass_tls,
 914                  bool return_pc,
 915                  DirectiveSet* directive)
 916     : Phase(Compiler),
 917       _compile_id(0),
 918       _options(Options::for_runtime_stub()),
 919       _method(nullptr),
 920       _entry_bci(InvocationEntryBci),
 921       _stub_function(stub_function),
 922       _stub_name(stub_name),
 923       _stub_id(stub_id),
 924       _stub_entry_point(nullptr),
 925       _max_node_limit(MaxNodeLimit),
 926       _node_count_inlining_cutoff(NodeCountInliningCutoff),
 927       _post_loop_opts_phase(false),
 928       _merge_stores_phase(false),
 929       _allow_macro_nodes(true),
 930       _inlining_progress(false),
 931       _inlining_incrementally(false),
 932       _has_reserved_stack_access(false),

 933 #ifndef PRODUCT
 934       _igv_idx(0),
 935       _trace_opto_output(directive->TraceOptoOutputOption),
 936 #endif
 937       _clinit_barrier_on_entry(false),
 938       _stress_seed(0),
 939       _comp_arena(mtCompiler, Arena::Tag::tag_comp),
 940       _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 941       _env(ci_env),
 942       _directive(directive),
 943       _log(ci_env->log()),
 944       _first_failure_details(nullptr),
 945       _reachability_fences(comp_arena(), 8, 0, nullptr),
 946       _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
 947       _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
 948       _congraph(nullptr),
 949       NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 950       _unique(0),
 951       _dead_node_count(0),
 952       _dead_node_list(comp_arena()),

1068   _fixed_slots = 0;
1069   set_has_split_ifs(false);
1070   set_has_loops(false); // first approximation
1071   set_has_stringbuilder(false);
1072   set_has_boxed_value(false);
1073   _trap_can_recompile = false;  // no traps emitted yet
1074   _major_progress = true; // start out assuming good things will happen
1075   set_has_unsafe_access(false);
1076   set_max_vector_size(0);
1077   set_clear_upper_avx(false);  //false as default for clear upper bits of ymm registers
1078   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1079   set_decompile_count(0);
1080 
1081 #ifndef PRODUCT
1082   _phase_counter = 0;
1083   Copy::zero_to_bytes(_igv_phase_iter, sizeof(_igv_phase_iter));
1084 #endif
1085 
1086   set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
1087   _loop_opts_cnt = LoopOptsCount;





1088   set_do_inlining(Inline);
1089   set_max_inline_size(MaxInlineSize);
1090   set_freq_inline_size(FreqInlineSize);
1091   set_do_scheduling(OptoScheduling);
1092 
1093   set_do_vector_loop(false);
1094   set_has_monitors(false);
1095   set_has_scoped_access(false);
1096 
1097   if (AllowVectorizeOnDemand) {
1098     if (has_method() && _directive->VectorizeOption) {
1099       set_do_vector_loop(true);
1100       NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n",  method()->name()->as_quoted_ascii());})
1101     } else if (has_method() && method()->name() != nullptr &&
1102                method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
1103       set_do_vector_loop(true);
1104     }
1105   }
1106   set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
1107   NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n",  method()->name()->as_quoted_ascii());})

1339   // If this method has already thrown a range-check,
1340   // assume it was because we already tried range smearing
1341   // and it failed.
1342   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1343   return !already_trapped;
1344 }
1345 
1346 
1347 //------------------------------flatten_alias_type-----------------------------
1348 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1349   assert(do_aliasing(), "Aliasing should be enabled");
1350   int offset = tj->offset();
1351   TypePtr::PTR ptr = tj->ptr();
1352 
1353   // Known instance (scalarizable allocation) alias only with itself.
1354   bool is_known_inst = tj->isa_oopptr() != nullptr &&
1355                        tj->is_oopptr()->is_known_instance();
1356 
1357   // Process weird unsafe references.
1358   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1359     assert(InlineUnsafeOps || StressReflectiveCode, "indeterminate pointers come only from unsafe ops");
1360     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1361     tj = TypeOopPtr::BOTTOM;
1362     ptr = tj->ptr();
1363     offset = tj->offset();
1364   }
1365 
1366   // Array pointers need some flattening
1367   const TypeAryPtr* ta = tj->isa_aryptr();
1368   if (ta && ta->is_stable()) {
1369     // Erase stability property for alias analysis.
1370     tj = ta = ta->cast_to_stable(false);
1371   }
1372   if( ta && is_known_inst ) {
1373     if ( offset != Type::OffsetBot &&
1374          offset > arrayOopDesc::length_offset_in_bytes() ) {
1375       offset = Type::OffsetBot; // Flatten constant access into array body only
1376       tj = ta = ta->
1377               remove_speculative()->
1378               cast_to_ptr_type(ptr)->
1379               with_offset(offset);
1380     }
1381   } else if (ta != nullptr) {
1382     // Common slices
1383     if (offset == arrayOopDesc::length_offset_in_bytes()) {
1384       return TypeAryPtr::RANGE;
1385     } else if (offset == oopDesc::klass_offset_in_bytes()) {
1386       return TypeInstPtr::KLASS;
1387     } else if (offset == oopDesc::mark_offset_in_bytes()) {
1388       return TypeInstPtr::MARK;
1389     }
1390 
1391     // Remove size and stability
1392     const TypeAry* normalized_ary = TypeAry::make(ta->elem(), TypeInt::POS, false);
1393     // Remove ptr, const_oop, and offset
1394     if (ta->elem() == Type::BOTTOM) {
1395       // Bottom array (meet of int[] and byte[] for example), accesses to it will be done with
1396       // Unsafe. This should alias with all arrays. For now just leave it as it is (this is
1397       // incorrect, see JDK-8331133).
1398       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, false, Type::OffsetBot);
1399     } else if (ta->elem()->make_oopptr() != nullptr) {
1400       // Object arrays, all of them share the same slice
1401       const TypeAry* tary = TypeAry::make(TypeInstPtr::BOTTOM, TypeInt::POS, false);
1402       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, tary, nullptr, false, Type::OffsetBot);
1403     } else {
1404       // Primitive arrays
1405       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, ta->exact_klass(), true, Type::OffsetBot);
1406     }
1407 
1408     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1409     // cannot be distinguished by bytecode alone.
1410     if (ta->elem() == TypeInt::BOOL) {
1411       tj = ta = TypeAryPtr::BYTES;
1412     }
















1413   }
1414 
1415   // Oop pointers need some flattening
1416   const TypeInstPtr *to = tj->isa_instptr();
1417   if (to && to != TypeOopPtr::BOTTOM) {
1418     ciInstanceKlass* ik = to->instance_klass();

1419     if( ptr == TypePtr::Constant ) {
1420       if (ik != ciEnv::current()->Class_klass() ||
1421           offset < ik->layout_helper_size_in_bytes()) {
1422         // No constant oop pointers (such as Strings); they alias with
1423         // unknown strings.
1424         assert(!is_known_inst, "not scalarizable allocation");
1425         tj = to = to->
1426                 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1427                 remove_speculative()->
1428                 cast_to_ptr_type(TypePtr::BotPTR)->
1429                 cast_to_exactness(false);
1430       }
1431     } else if( is_known_inst ) {
1432       tj = to; // Keep NotNull and klass_is_exact for instance type
1433     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1434       // During the 2nd round of IterGVN, NotNull castings are removed.
1435       // Make sure the Bottom and NotNull variants alias the same.
1436       // Also, make sure exact and non-exact variants alias the same.
1437       tj = to = to->
1438               remove_speculative()->
1439               cast_to_instance_id(TypeOopPtr::InstanceBot)->
1440               cast_to_ptr_type(TypePtr::BotPTR)->
1441               cast_to_exactness(false);
1442     }
1443     if (to->speculative() != nullptr) {
1444       tj = to = to->remove_speculative();
1445     }
1446     // Canonicalize the holder of this field
1447     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1448       // First handle header references such as a LoadKlassNode, even if the
1449       // object's klass is unloaded at compile time (4965979).
1450       if (!is_known_inst) { // Do it only for non-instance types
1451         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, nullptr, offset);
1452       }
1453     } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) {
1454       // Static fields are in the space above the normal instance
1455       // fields in the java.lang.Class instance.
1456       if (ik != ciEnv::current()->Class_klass()) {
1457         to = nullptr;
1458         tj = TypeOopPtr::BOTTOM;
1459         offset = tj->offset();
1460       }
1461     } else {
1462       ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset);
1463       assert(offset < canonical_holder->layout_helper_size_in_bytes(), "");
1464       assert(tj->offset() == offset, "no change to offset expected");
1465       bool xk = to->klass_is_exact();
1466       int instance_id = to->instance_id();
1467 
1468       // If the input type's class is the holder: if exact, the type only includes interfaces implemented by the holder
1469       // but if not exact, it may include extra interfaces: build new type from the holder class to make sure only
1470       // its interfaces are included.
1471       if (xk && ik->equals(canonical_holder)) {
1472         assert(tj == TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, offset, instance_id), "exact type should be canonical type");

1473       } else {
1474         assert(xk || !is_known_inst, "Known instance should be exact type");
1475         tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, offset, instance_id);

1476       }
1477     }
1478   }
1479 
1480   // Klass pointers to object array klasses need some flattening
1481   const TypeKlassPtr *tk = tj->isa_klassptr();
1482   if( tk ) {
1483     // If we are referencing a field within a Klass, we need
1484     // to assume the worst case of an Object.  Both exact and
1485     // inexact types must flatten to the same alias class so
1486     // use NotNull as the PTR.
1487     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1488       tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull,
1489                                        env()->Object_klass(),
1490                                        offset);

1491     }
1492 
1493     if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) {
1494       ciKlass* k = ciObjArrayKlass::make(env()->Object_klass());
1495       if (!k || !k->is_loaded()) {                  // Only fails for some -Xcomp runs
1496         tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), offset);
1497       } else {
1498         tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, offset);
1499       }
1500     }
1501 
1502     // Check for precise loads from the primary supertype array and force them
1503     // to the supertype cache alias index.  Check for generic array loads from
1504     // the primary supertype array and also force them to the supertype cache
1505     // alias index.  Since the same load can reach both, we need to merge
1506     // these 2 disparate memories into the same alias class.  Since the
1507     // primary supertype array is read-only, there's no chance of confusion
1508     // where we bypass an array load and an array store.
1509     int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1510     if (offset == Type::OffsetBot ||
1511         (offset >= primary_supers_offset &&
1512          offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1513         offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1514       offset = in_bytes(Klass::secondary_super_cache_offset());
1515       tj = tk = tk->with_offset(offset);
1516     }
1517   }
1518 
1519   // Flatten all Raw pointers together.
1520   if (tj->base() == Type::RawPtr)
1521     tj = TypeRawPtr::BOTTOM;

1611   intptr_t key = (intptr_t) adr_type;
1612   key ^= key >> logAliasCacheSize;
1613   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1614 }
1615 
1616 
1617 //-----------------------------grow_alias_types--------------------------------
1618 void Compile::grow_alias_types() {
1619   const int old_ats  = _max_alias_types; // how many before?
1620   const int new_ats  = old_ats;          // how many more?
1621   const int grow_ats = old_ats+new_ats;  // how many now?
1622   _max_alias_types = grow_ats;
1623   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), _alias_types, old_ats, grow_ats);
1624   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1625   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1626   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1627 }
1628 
1629 
1630 //--------------------------------find_alias_type------------------------------
1631 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1632   if (!do_aliasing()) {
1633     return alias_type(AliasIdxBot);
1634   }
1635 
1636   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1637   if (ace->_adr_type == adr_type) {
1638     return alias_type(ace->_index);



1639   }
1640 
1641   // Handle special cases.
1642   if (adr_type == nullptr)          return alias_type(AliasIdxTop);
1643   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1644 
1645   // Do it the slow way.
1646   const TypePtr* flat = flatten_alias_type(adr_type);
1647 
1648 #ifdef ASSERT
1649   {
1650     ResourceMark rm;
1651     assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1652            Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1653     assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1654            Type::str(adr_type));
1655     if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1656       const TypeOopPtr* foop = flat->is_oopptr();
1657       // Scalarizable allocations have exact klass always.
1658       bool exact = !foop->klass_is_exact() || foop->is_known_instance();

1668     if (alias_type(i)->adr_type() == flat) {
1669       idx = i;
1670       break;
1671     }
1672   }
1673 
1674   if (idx == AliasIdxTop) {
1675     if (no_create)  return nullptr;
1676     // Grow the array if necessary.
1677     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1678     // Add a new alias type.
1679     idx = _num_alias_types++;
1680     _alias_types[idx]->Init(idx, flat);
1681     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1682     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1683     if (flat->isa_instptr()) {
1684       if (flat->offset() == java_lang_Class::klass_offset()
1685           && flat->is_instptr()->instance_klass() == env()->Class_klass())
1686         alias_type(idx)->set_rewritable(false);
1687     }

1688     if (flat->isa_aryptr()) {
1689 #ifdef ASSERT
1690       const int header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1691       // (T_BYTE has the weakest alignment and size restrictions...)
1692       assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1693 #endif

1694       if (flat->offset() == TypePtr::OffsetBot) {
1695         alias_type(idx)->set_element(flat->is_aryptr()->elem());







1696       }
1697     }
1698     if (flat->isa_klassptr()) {
1699       if (UseCompactObjectHeaders) {
1700         if (flat->offset() == in_bytes(Klass::prototype_header_offset()))
1701           alias_type(idx)->set_rewritable(false);
1702       }
1703       if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1704         alias_type(idx)->set_rewritable(false);
1705       if (flat->offset() == in_bytes(Klass::misc_flags_offset()))
1706         alias_type(idx)->set_rewritable(false);
1707       if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1708         alias_type(idx)->set_rewritable(false);


1709       if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1710         alias_type(idx)->set_rewritable(false);
1711     }
1712 
1713     if (flat->isa_instklassptr()) {
1714       if (flat->offset() == in_bytes(InstanceKlass::access_flags_offset())) {
1715         alias_type(idx)->set_rewritable(false);
1716       }
1717     }
1718     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1719     // but the base pointer type is not distinctive enough to identify
1720     // references into JavaThread.)
1721 
1722     // Check for final fields.
1723     const TypeInstPtr* tinst = flat->isa_instptr();
1724     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1725       ciField* field;
1726       if (tinst->const_oop() != nullptr &&
1727           tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1728           tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1729         // static field
1730         ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1731         field = k->get_field_by_offset(tinst->offset(), true);




1732       } else {
1733         ciInstanceKlass *k = tinst->instance_klass();
1734         field = k->get_field_by_offset(tinst->offset(), false);
1735       }
1736       assert(field == nullptr ||
1737              original_field == nullptr ||
1738              (field->holder() == original_field->holder() &&
1739               field->offset_in_bytes() == original_field->offset_in_bytes() &&
1740               field->is_static() == original_field->is_static()), "wrong field?");
1741       // Set field() and is_rewritable() attributes.
1742       if (field != nullptr)  alias_type(idx)->set_field(field);







1743     }
1744   }
1745 
1746   // Fill the cache for next time.
1747   ace->_adr_type = adr_type;
1748   ace->_index    = idx;
1749   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");

1750 
1751   // Might as well try to fill the cache for the flattened version, too.
1752   AliasCacheEntry* face = probe_alias_cache(flat);
1753   if (face->_adr_type == nullptr) {
1754     face->_adr_type = flat;
1755     face->_index    = idx;
1756     assert(alias_type(flat) == alias_type(idx), "flat type must work too");

1757   }
1758 
1759   return alias_type(idx);
1760 }
1761 
1762 
1763 Compile::AliasType* Compile::alias_type(ciField* field) {
1764   const TypeOopPtr* t;
1765   if (field->is_static())
1766     t = TypeInstPtr::make(field->holder()->java_mirror());
1767   else
1768     t = TypeOopPtr::make_from_klass_raw(field->holder());
1769   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1770   assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1771   return atp;
1772 }
1773 
1774 
1775 //------------------------------have_alias_type--------------------------------
1776 bool Compile::have_alias_type(const TypePtr* adr_type) {

1858   assert(!C->major_progress(), "not cleared");
1859 
1860   if (_for_post_loop_igvn.length() > 0) {
1861     while (_for_post_loop_igvn.length() > 0) {
1862       Node* n = _for_post_loop_igvn.pop();
1863       n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1864       igvn._worklist.push(n);
1865     }
1866     igvn.optimize();
1867     if (failing()) return;
1868     assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1869     assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1870 
1871     // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1872     if (C->major_progress()) {
1873       C->clear_major_progress(); // ensure that major progress is now clear
1874     }
1875   }
1876 }
1877 















































































































































































































































































































































































































































































































































































































1878 void Compile::record_for_merge_stores_igvn(Node* n) {
1879   if (!n->for_merge_stores_igvn()) {
1880     assert(!_for_merge_stores_igvn.contains(n), "duplicate");
1881     n->add_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
1882     _for_merge_stores_igvn.append(n);
1883   }
1884 }
1885 
1886 void Compile::remove_from_merge_stores_igvn(Node* n) {
1887   n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
1888   _for_merge_stores_igvn.remove(n);
1889 }
1890 
1891 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
1892 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
1893 // the stores, and we merge the wrong sequence of stores.
1894 // Example:
1895 //   StoreI RangeCheck StoreI StoreI RangeCheck StoreI
1896 // Apply MergeStores:
1897 //   StoreI RangeCheck [   StoreL  ] RangeCheck StoreI

1976       assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
1977       Bytecodes::Code c = iter.cur_bc();
1978       Node* lhs = nullptr;
1979       Node* rhs = nullptr;
1980       if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
1981         lhs = unc->peek_operand(0);
1982         rhs = unc->peek_operand(1);
1983       } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
1984         lhs = unc->peek_operand(0);
1985       }
1986 
1987       ResourceMark rm;
1988       const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
1989       assert(live_locals.is_valid(), "broken liveness info");
1990       int len = (int)live_locals.size();
1991 
1992       for (int i = 0; i < len; i++) {
1993         Node* local = unc->local(jvms, i);
1994         // kill local using the liveness of next_bci.
1995         // give up when the local looks like an operand to secure reexecution.
1996         if (!live_locals.at(i) && !local->is_top() && local != lhs && local!= rhs) {
1997           uint idx = jvms->locoff() + i;
1998 #ifdef ASSERT
1999           if (PrintOpto && Verbose) {
2000             tty->print("[unstable_if] kill local#%d: ", idx);
2001             local->dump();
2002             tty->cr();
2003           }
2004 #endif
2005           igvn.replace_input_of(unc, idx, top());
2006           modified = true;
2007         }
2008       }
2009     }
2010 
2011     // keep the mondified trap for late query
2012     if (modified) {
2013       trap->set_modified();
2014     } else {
2015       _unstable_if_traps.delete_at(i);
2016     }
2017   }
2018   igvn.optimize();
2019 }
2020 
2021 // StringOpts and late inlining of string methods
2022 void Compile::inline_string_calls(bool parse_time) {
2023   {
2024     // remove useless nodes to make the usage analysis simpler
2025     ResourceMark rm;
2026     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2027   }
2028 
2029   {
2030     ResourceMark rm;
2031     print_method(PHASE_BEFORE_STRINGOPTS, 3);

2223 
2224   if (_string_late_inlines.length() > 0) {
2225     assert(has_stringbuilder(), "inconsistent");
2226 
2227     inline_string_calls(false);
2228 
2229     if (failing())  return;
2230 
2231     inline_incrementally_cleanup(igvn);
2232   }
2233 
2234   set_inlining_incrementally(false);
2235 }
2236 
2237 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2238   // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2239   // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2240   // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2241   // as if "inlining_incrementally() == true" were set.
2242   assert(inlining_incrementally() == false, "not allowed");
2243   assert(_modified_nodes == nullptr, "not allowed");




2244   assert(_late_inlines.length() > 0, "sanity");
2245 
2246   if (StressIncrementalInlining) {
2247     shuffle_late_inlines();
2248   }
2249 
2250   while (_late_inlines.length() > 0) {
2251     igvn_worklist()->ensure_empty(); // should be done with igvn
2252 
2253     while (inline_incrementally_one()) {
2254       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2255     }
2256     if (failing())  return;
2257 
2258     inline_incrementally_cleanup(igvn);
2259   }


2260 }
2261 
2262 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2263   if (_loop_opts_cnt > 0) {
2264     while (major_progress() && (_loop_opts_cnt > 0)) {
2265       TracePhase tp(_t_idealLoop);
2266       PhaseIdealLoop::optimize(igvn, mode);
2267       _loop_opts_cnt--;
2268       if (failing())  return false;
2269       if (major_progress()) {
2270         print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2271       }
2272     }
2273   }
2274   return true;
2275 }
2276 
2277 // Remove edges from "root" to each SafePoint at a backward branch.
2278 // They were inserted during parsing (see add_safepoint()) to make
2279 // infinite loops without calls or exceptions visible to root, i.e.,

2385     print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2386   }
2387   assert(!has_vbox_nodes(), "sanity");
2388 
2389   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2390     Compile::TracePhase tp(_t_renumberLive);
2391     igvn_worklist()->ensure_empty(); // should be done with igvn
2392     {
2393       ResourceMark rm;
2394       PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
2395     }
2396     igvn.reset();
2397     igvn.optimize(true);
2398     if (failing()) return;
2399   }
2400 
2401   // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
2402   // safepoints
2403   remove_root_to_sfpts_edges(igvn);
2404 





2405   if (failing())  return;
2406 











2407   _print_phase_loop_opts = has_loops();
2408   if (_print_phase_loop_opts) {
2409     print_method(PHASE_BEFORE_LOOP_OPTS, 2);
2410   }
2411 
2412   // Perform escape analysis
2413   if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
2414     if (has_loops()) {
2415       // Cleanup graph (remove dead nodes).
2416       TracePhase tp(_t_idealLoop);
2417       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2418       if (failing())  return;













2419     }

2420     bool progress;
2421     print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2422     do {
2423       ConnectionGraph::do_analysis(this, &igvn);
2424 
2425       if (failing())  return;
2426 
2427       int mcount = macro_count(); // Record number of allocations and locks before IGVN
2428 
2429       // Optimize out fields loads from scalar replaceable allocations.
2430       igvn.optimize(true);
2431       print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2432 
2433       if (failing()) return;
2434 
2435       if (congraph() != nullptr && macro_count() > 0) {
2436         TracePhase tp(_t_macroEliminate);
2437         PhaseMacroExpand mexp(igvn);
2438         mexp.eliminate_macro_nodes();
2439         if (failing()) return;


2440         print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
2441 
2442         igvn.set_delay_transform(false);
2443         igvn.optimize();
2444         if (failing()) return;
2445 
2446         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2447       }
2448 
2449       ConnectionGraph::verify_ram_nodes(this, root());
2450       if (failing())  return;
2451 
2452       progress = do_iterative_escape_analysis() &&
2453                  (macro_count() < mcount) &&
2454                  ConnectionGraph::has_candidates(this);
2455       // Try again if candidates exist and made progress
2456       // by removing some allocations and/or locks.
2457     } while (progress);
2458   }
2459 





2460   // Loop transforms on the ideal graph.  Range Check Elimination,
2461   // peeling, unrolling, etc.
2462 
2463   // Set loop opts counter
2464   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2465     {
2466       TracePhase tp(_t_idealLoop);
2467       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2468       _loop_opts_cnt--;
2469       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2470       if (failing())  return;
2471     }
2472     // Loop opts pass if partial peeling occurred in previous pass
2473     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2474       TracePhase tp(_t_idealLoop);
2475       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2476       _loop_opts_cnt--;
2477       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2478       if (failing())  return;
2479     }

2527 
2528   // Once loop optimizations are over, it is safe to get rid of all reachability fence nodes and
2529   // migrate reachability edges to safepoints.
2530   if (OptimizeReachabilityFences && _reachability_fences.length() > 0) {
2531     TracePhase tp1(_t_idealLoop);
2532     TracePhase tp2(_t_reachability);
2533     PhaseIdealLoop::optimize(igvn, PostLoopOptsExpandReachabilityFences);
2534     print_method(PHASE_EXPAND_REACHABILITY_FENCES, 2);
2535     if (failing())  return;
2536     assert(_reachability_fences.length() == 0 || PreserveReachabilityFencesOnConstants, "no RF nodes allowed");
2537   }
2538 
2539   process_for_merge_stores_igvn(igvn);
2540 
2541   if (failing())  return;
2542 
2543 #ifdef ASSERT
2544   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2545 #endif
2546 











2547   {
2548     TracePhase tp(_t_macroExpand);







2549     print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
2550     PhaseMacroExpand  mex(igvn);
2551     // Do not allow new macro nodes once we start to eliminate and expand
2552     C->reset_allow_macro_nodes();
2553     // Last attempt to eliminate macro nodes before expand
2554     mex.eliminate_macro_nodes();
2555     if (failing()) {
2556       return;
2557     }
2558     mex.eliminate_opaque_looplimit_macro_nodes();
2559     if (failing()) {
2560       return;
2561     }
2562     print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
2563     if (mex.expand_macro_nodes()) {
2564       assert(failing(), "must bail out w/ explicit message");
2565       return;
2566     }
2567     print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
2568   }
2569 




2570   {
2571     TracePhase tp(_t_barrierExpand);
2572     if (bs->expand_barriers(this, igvn)) {
2573       assert(failing(), "must bail out w/ explicit message");
2574       return;
2575     }
2576     print_method(PHASE_BARRIER_EXPANSION, 2);
2577   }
2578 
2579   if (C->max_vector_size() > 0) {
2580     C->optimize_logic_cones(igvn);
2581     igvn.optimize();
2582     if (failing()) return;
2583   }
2584 
2585   DEBUG_ONLY( _modified_nodes = nullptr; )

2586 
2587   assert(igvn._worklist.size() == 0, "not empty");
2588 
2589   if (_late_inlines.length() > 0) {
2590     // More opportunities to optimize virtual and MH calls.
2591     // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
2592     process_late_inline_calls_no_inline(igvn);
2593     if (failing())  return;
2594   }
2595   assert(_late_inlines.length() == 0, "late inline queue must be drained");
2596  } // (End scope of igvn; run destructor if necessary for asserts.)
2597 
2598  check_no_dead_use();
2599 
2600  // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
2601  // to remove hashes to unlock nodes for modifications.
2602  C->node_hash()->clear();
2603 
2604  // A method with only infinite loops has no edges entering loops from root
2605  {
2606    TracePhase tp(_t_graphReshaping);
2607    if (final_graph_reshaping()) {
2608      assert(failing(), "must bail out w/ explicit message");
2609      return;
2610    }
2611  }
2612 
2613  print_method(PHASE_OPTIMIZE_FINISHED, 2);
2614  DEBUG_ONLY(set_phase_optimize_finished();)
2615 }

3274     n->subsume_by(sub, this);
3275   }
3276 }
3277 
3278 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3279   switch( nop ) {
3280   case Op_Opaque1:              // Remove Opaque Nodes before matching
3281     n->subsume_by(n->in(1), this);
3282     break;
3283   case Op_CallLeafPure: {
3284     // If the pure call is not supported, then lower to a CallLeaf.
3285     if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
3286       CallNode* call = n->as_Call();
3287       CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
3288                                             call->_name, TypeRawPtr::BOTTOM);
3289       new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
3290       new_call->init_req(TypeFunc::I_O, C->top());
3291       new_call->init_req(TypeFunc::Memory, C->top());
3292       new_call->init_req(TypeFunc::ReturnAdr, C->top());
3293       new_call->init_req(TypeFunc::FramePtr, C->top());
3294       for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain()->cnt(); i++) {
3295         new_call->init_req(i, call->in(i));
3296       }
3297       n->subsume_by(new_call, this);
3298     }
3299     break;
3300   }
3301   case Op_CallStaticJava:
3302   case Op_CallJava:
3303   case Op_CallDynamicJava:
3304     frc.inc_java_call_count(); // Count java call site;
3305   case Op_CallRuntime:
3306   case Op_CallLeaf:
3307   case Op_CallLeafVector:
3308   case Op_CallLeafNoFP: {
3309     assert (n->is_Call(), "");
3310     CallNode *call = n->as_Call();
3311     // See if uncommon argument is shared
3312     if (call->is_CallStaticJava() && call->as_CallStaticJava()->_name) {
3313       Node *n = call->in(TypeFunc::Parms);
3314       int nop = n->Opcode();

3321           nop != Op_DecodeNKlass &&
3322           !n->is_Mem() &&
3323           !n->is_Phi()) {
3324         Node *x = n->clone();
3325         call->set_req(TypeFunc::Parms, x);
3326       }
3327     }
3328     break;
3329   }
3330 
3331   // Mem nodes need explicit cases to satisfy assert(!n->is_Mem()) in default.
3332   case Op_StoreF:
3333   case Op_LoadF:
3334   case Op_StoreD:
3335   case Op_LoadD:
3336   case Op_LoadD_unaligned:
3337   case Op_StoreB:
3338   case Op_StoreC:
3339   case Op_StoreI:
3340   case Op_StoreL:

3341   case Op_CompareAndSwapB:
3342   case Op_CompareAndSwapS:
3343   case Op_CompareAndSwapI:
3344   case Op_CompareAndSwapL:
3345   case Op_CompareAndSwapP:
3346   case Op_CompareAndSwapN:
3347   case Op_WeakCompareAndSwapB:
3348   case Op_WeakCompareAndSwapS:
3349   case Op_WeakCompareAndSwapI:
3350   case Op_WeakCompareAndSwapL:
3351   case Op_WeakCompareAndSwapP:
3352   case Op_WeakCompareAndSwapN:
3353   case Op_CompareAndExchangeB:
3354   case Op_CompareAndExchangeS:
3355   case Op_CompareAndExchangeI:
3356   case Op_CompareAndExchangeL:
3357   case Op_CompareAndExchangeP:
3358   case Op_CompareAndExchangeN:
3359   case Op_GetAndAddS:
3360   case Op_GetAndAddB:

3852           k->subsume_by(m, this);
3853         }
3854       }
3855     }
3856     break;
3857   }
3858   case Op_CmpUL: {
3859     if (!Matcher::has_match_rule(Op_CmpUL)) {
3860       // No support for unsigned long comparisons
3861       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3862       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3863       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3864       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3865       Node* andl = new AndLNode(orl, remove_sign_mask);
3866       Node* cmp = new CmpLNode(andl, n->in(2));
3867       n->subsume_by(cmp, this);
3868     }
3869     break;
3870   }
3871 #ifdef ASSERT





3872   case Op_ConNKlass: {
3873     const TypePtr* tp = n->as_Type()->type()->make_ptr();
3874     ciKlass* klass = tp->is_klassptr()->exact_klass();
3875     assert(klass->is_in_encoding_range(), "klass cannot be compressed");
3876     break;
3877   }
3878 #endif
3879   default:
3880     assert(!n->is_Call(), "");
3881     assert(!n->is_Mem(), "");
3882     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3883     break;
3884   }
3885 }
3886 
3887 //------------------------------final_graph_reshaping_walk---------------------
3888 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3889 // requires that the walk visits a node's inputs before visiting the node.
3890 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3891   Unique_Node_List sfpt;

4224   }
4225 }
4226 
4227 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4228   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4229 }
4230 
4231 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4232   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4233 }
4234 
4235 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4236   if (holder->is_initialized()) {
4237     return false;
4238   }
4239   if (holder->is_being_initialized()) {
4240     if (accessing_method->holder() == holder) {
4241       // Access inside a class. The barrier can be elided when access happens in <clinit>,
4242       // <init>, or a static method. In all those cases, there was an initialization
4243       // barrier on the holder klass passed.
4244       if (accessing_method->is_static_initializer() ||
4245           accessing_method->is_object_initializer() ||
4246           accessing_method->is_static()) {
4247         return false;
4248       }
4249     } else if (accessing_method->holder()->is_subclass_of(holder)) {
4250       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4251       // In case of <init> or a static method, the barrier is on the subclass is not enough:
4252       // child class can become fully initialized while its parent class is still being initialized.
4253       if (accessing_method->is_static_initializer()) {
4254         return false;
4255       }
4256     }
4257     ciMethod* root = method(); // the root method of compilation
4258     if (root != accessing_method) {
4259       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4260     }
4261   }
4262   return true;
4263 }
4264 
4265 #ifndef PRODUCT
4266 //------------------------------verify_bidirectional_edges---------------------
4267 // For each input edge to a node (ie - for each Use-Def edge), verify that
4268 // there is a corresponding Def-Use edge.
4269 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
4270   // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4271   uint stack_size = live_nodes() >> 4;
4272   Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
4273   if (root_and_safepoints != nullptr) {

4303       if (in != nullptr && !in->is_top()) {
4304         // Count instances of `next`
4305         int cnt = 0;
4306         for (uint idx = 0; idx < in->_outcnt; idx++) {
4307           if (in->_out[idx] == n) {
4308             cnt++;
4309           }
4310         }
4311         assert(cnt > 0, "Failed to find Def-Use edge.");
4312         // Check for duplicate edges
4313         // walk the input array downcounting the input edges to n
4314         for (uint j = 0; j < length; j++) {
4315           if (n->in(j) == in) {
4316             cnt--;
4317           }
4318         }
4319         assert(cnt == 0, "Mismatched edge count.");
4320       } else if (in == nullptr) {
4321         assert(i == 0 || i >= n->req() ||
4322                n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||

4323                (n->is_Unlock() && i == (n->req() - 1)) ||
4324                (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4325               "only region, phi, arraycopy, unlock or membar nodes have null data edges");
4326       } else {
4327         assert(in->is_top(), "sanity");
4328         // Nothing to check.
4329       }
4330     }
4331   }
4332 }
4333 
4334 //------------------------------verify_graph_edges---------------------------
4335 // Walk the Graph and verify that there is a one-to-one correspondence
4336 // between Use-Def edges and Def-Use edges in the graph.
4337 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
4338   if (VerifyGraphEdges) {
4339     Unique_Node_List visited;
4340 
4341     // Call graph walk to check edges
4342     verify_bidirectional_edges(visited, root_and_safepoints);
4343     if (no_dead_code) {
4344       // Now make sure that no visited node is used by an unvisited node.
4345       bool dead_nodes = false;

4456 // (1) subklass is already limited to a subtype of superklass => always ok
4457 // (2) subklass does not overlap with superklass => always fail
4458 // (3) superklass has NO subtypes and we can check with a simple compare.
4459 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
4460   if (skip) {
4461     return SSC_full_test;       // Let caller generate the general case.
4462   }
4463 
4464   if (subk->is_java_subtype_of(superk)) {
4465     return SSC_always_true; // (0) and (1)  this test cannot fail
4466   }
4467 
4468   if (!subk->maybe_java_subtype_of(superk)) {
4469     return SSC_always_false; // (2) true path dead; no dynamic test needed
4470   }
4471 
4472   const Type* superelem = superk;
4473   if (superk->isa_aryklassptr()) {
4474     int ignored;
4475     superelem = superk->is_aryklassptr()->base_element_type(ignored);







4476   }
4477 
4478   if (superelem->isa_instklassptr()) {
4479     ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
4480     if (!ik->has_subklass()) {
4481       if (!ik->is_final()) {
4482         // Add a dependency if there is a chance of a later subclass.
4483         dependencies()->assert_leaf_type(ik);
4484       }
4485       if (!superk->maybe_java_subtype_of(subk)) {
4486         return SSC_always_false;
4487       }
4488       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
4489     }
4490   } else {
4491     // A primitive array type has no subtypes.
4492     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
4493   }
4494 
4495   return SSC_full_test;

5288   } else {
5289     _debug_network_printer->update_compiled_method(C->method());
5290   }
5291   tty->print_cr("Method printed over network stream to IGV");
5292   _debug_network_printer->print(name, C->root(), visible_nodes, fr);
5293 }
5294 #endif // !PRODUCT
5295 
5296 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5297   if (type != nullptr && phase->type(value)->higher_equal(type)) {
5298     return value;
5299   }
5300   Node* result = nullptr;
5301   if (bt == T_BYTE) {
5302     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5303     result = new RShiftINode(result, phase->intcon(24));
5304   } else if (bt == T_BOOLEAN) {
5305     result = new AndINode(value, phase->intcon(0xFF));
5306   } else if (bt == T_CHAR) {
5307     result = new AndINode(value,phase->intcon(0xFFFF));


5308   } else {
5309     assert(bt == T_SHORT, "unexpected narrow type");
5310     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5311     result = new RShiftINode(result, phase->intcon(16));
5312   }
5313   if (transform_res) {
5314     result = phase->transform(result);
5315   }
5316   return result;
5317 }
5318 
5319 void Compile::record_method_not_compilable_oom() {
5320   record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
5321 }
5322 
5323 #ifndef PRODUCT
5324 // Collects all the control inputs from nodes on the worklist and from their data dependencies
5325 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
5326   // Follow non-control edges until we reach CFG nodes
5327   for (uint i = 0; i < worklist.size(); i++) {

   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "asm/macroAssembler.inline.hpp"
  27 #include "ci/ciFlatArray.hpp"
  28 #include "ci/ciInlineKlass.hpp"
  29 #include "ci/ciReplay.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "code/aotCodeCache.hpp"
  32 #include "code/exceptionHandlerTable.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "compiler/compilationFailureInfo.hpp"
  35 #include "compiler/compilationMemoryStatistic.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compileLog.hpp"
  38 #include "compiler/compiler_globals.hpp"
  39 #include "compiler/compilerDefinitions.hpp"
  40 #include "compiler/compilerOracle.hpp"
  41 #include "compiler/disassembler.hpp"
  42 #include "compiler/oopMap.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/c2/barrierSetC2.hpp"
  45 #include "jfr/jfrEvents.hpp"
  46 #include "jvm_io.h"
  47 #include "memory/allocation.hpp"
  48 #include "memory/arena.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "opto/addnode.hpp"
  51 #include "opto/block.hpp"
  52 #include "opto/c2compiler.hpp"
  53 #include "opto/callGenerator.hpp"
  54 #include "opto/callnode.hpp"
  55 #include "opto/castnode.hpp"
  56 #include "opto/cfgnode.hpp"
  57 #include "opto/chaitin.hpp"
  58 #include "opto/compile.hpp"
  59 #include "opto/connode.hpp"
  60 #include "opto/convertnode.hpp"
  61 #include "opto/divnode.hpp"
  62 #include "opto/escape.hpp"
  63 #include "opto/idealGraphPrinter.hpp"
  64 #include "opto/inlinetypenode.hpp"
  65 #include "opto/locknode.hpp"
  66 #include "opto/loopnode.hpp"
  67 #include "opto/machnode.hpp"
  68 #include "opto/macro.hpp"
  69 #include "opto/matcher.hpp"
  70 #include "opto/mathexactnode.hpp"
  71 #include "opto/memnode.hpp"
  72 #include "opto/movenode.hpp"
  73 #include "opto/mulnode.hpp"
  74 #include "opto/multnode.hpp"
  75 #include "opto/narrowptrnode.hpp"
  76 #include "opto/node.hpp"
  77 #include "opto/opaquenode.hpp"
  78 #include "opto/opcodes.hpp"
  79 #include "opto/output.hpp"
  80 #include "opto/parse.hpp"
  81 #include "opto/phaseX.hpp"
  82 #include "opto/reachability.hpp"
  83 #include "opto/rootnode.hpp"
  84 #include "opto/runtime.hpp"
  85 #include "opto/stringopts.hpp"
  86 #include "opto/type.hpp"
  87 #include "opto/vector.hpp"
  88 #include "opto/vectornode.hpp"
  89 #include "runtime/arguments.hpp"
  90 #include "runtime/globals_extension.hpp"
  91 #include "runtime/sharedRuntime.hpp"
  92 #include "runtime/signature.hpp"
  93 #include "runtime/stubRoutines.hpp"
  94 #include "runtime/timer.hpp"
  95 #include "utilities/align.hpp"
  96 #include "utilities/copy.hpp"
  97 #include "utilities/hashTable.hpp"
  98 #include "utilities/macros.hpp"
  99 
 100 // -------------------- Compile::mach_constant_base_node -----------------------
 101 // Constant table base node singleton.
 102 MachConstantBaseNode* Compile::mach_constant_base_node() {
 103   if (_mach_constant_base_node == nullptr) {
 104     _mach_constant_base_node = new MachConstantBaseNode();
 105     _mach_constant_base_node->add_req(C->root());
 106   }
 107   return _mach_constant_base_node;
 108 }
 109 

 398     record_dead_node(dead->_idx);
 399   }
 400   if (dead->is_macro()) {
 401     remove_macro_node(dead);
 402   }
 403   if (dead->is_expensive()) {
 404     remove_expensive_node(dead);
 405   }
 406   if (dead->is_ReachabilityFence()) {
 407     remove_reachability_fence(dead->as_ReachabilityFence());
 408   }
 409   if (dead->is_OpaqueTemplateAssertionPredicate()) {
 410     remove_template_assertion_predicate_opaque(dead->as_OpaqueTemplateAssertionPredicate());
 411   }
 412   if (dead->is_ParsePredicate()) {
 413     remove_parse_predicate(dead->as_ParsePredicate());
 414   }
 415   if (dead->for_post_loop_opts_igvn()) {
 416     remove_from_post_loop_opts_igvn(dead);
 417   }
 418   if (dead->is_InlineType()) {
 419     remove_inline_type(dead);
 420   }
 421   if (dead->is_LoadFlat() || dead->is_StoreFlat()) {
 422     remove_flat_access(dead);
 423   }
 424   if (dead->for_merge_stores_igvn()) {
 425     remove_from_merge_stores_igvn(dead);
 426   }
 427   if (dead->is_Call()) {
 428     remove_useless_late_inlines(                &_late_inlines, dead);
 429     remove_useless_late_inlines(         &_string_late_inlines, dead);
 430     remove_useless_late_inlines(         &_boxing_late_inlines, dead);
 431     remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
 432 
 433     if (dead->is_CallStaticJava()) {
 434       remove_unstable_if_trap(dead->as_CallStaticJava(), false);
 435     }
 436   }
 437   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 438   bs->unregister_potential_barrier_node(dead);
 439 }
 440 
 441 // Disconnect all useless nodes by disconnecting those at the boundary.
 442 void Compile::disconnect_useless_nodes(Unique_Node_List& useful, Unique_Node_List& worklist, const Unique_Node_List* root_and_safepoints) {
 443   uint next = 0;

 451     // Use raw traversal of out edges since this code removes out edges
 452     int max = n->outcnt();
 453     for (int j = 0; j < max; ++j) {
 454       Node* child = n->raw_out(j);
 455       if (!useful.member(child)) {
 456         assert(!child->is_top() || child != top(),
 457                "If top is cached in Compile object it is in useful list");
 458         // Only need to remove this out-edge to the useless node
 459         n->raw_del_out(j);
 460         --j;
 461         --max;
 462         if (child->is_data_proj_of_pure_function(n)) {
 463           worklist.push(n);
 464         }
 465       }
 466     }
 467     if (n->outcnt() == 1 && n->has_special_unique_user()) {
 468       assert(useful.member(n->unique_out()), "do not push a useless node");
 469       worklist.push(n->unique_out());
 470     }
 471     if (n->outcnt() == 0) {
 472       worklist.push(n);
 473     }
 474   }
 475 
 476   remove_useless_nodes(_macro_nodes,        useful); // remove useless macro nodes
 477   remove_useless_nodes(_parse_predicates,   useful); // remove useless Parse Predicate nodes
 478   // Remove useless Template Assertion Predicate opaque nodes
 479   remove_useless_nodes(_template_assertion_predicate_opaques, useful);
 480   remove_useless_nodes(_expensive_nodes,    useful); // remove useless expensive nodes
 481   remove_useless_nodes(_reachability_fences, useful); // remove useless node recorded for post loop opts IGVN pass
 482   remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
 483   remove_useless_nodes(_inline_type_nodes,  useful); // remove useless inline type nodes
 484   remove_useless_nodes(_flat_access_nodes, useful);  // remove useless flat access nodes
 485 #ifdef ASSERT
 486   if (_modified_nodes != nullptr) {
 487     _modified_nodes->remove_useless_nodes(useful.member_set());
 488   }
 489 #endif
 490   remove_useless_nodes(_for_merge_stores_igvn, useful); // remove useless node recorded for merge stores IGVN pass
 491   remove_useless_unstable_if_traps(useful);          // remove useless unstable_if traps
 492   remove_useless_coarsened_locks(useful);            // remove useless coarsened locks nodes
 493 #ifdef ASSERT
 494   if (_modified_nodes != nullptr) {
 495     _modified_nodes->remove_useless_nodes(useful.member_set());
 496   }
 497 #endif
 498 
 499   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 500   bs->eliminate_useless_gc_barriers(useful, this);
 501   // clean up the late inline lists
 502   remove_useless_late_inlines(                &_late_inlines, useful);
 503   remove_useless_late_inlines(         &_string_late_inlines, useful);
 504   remove_useless_late_inlines(         &_boxing_late_inlines, useful);
 505   remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
 506   DEBUG_ONLY(verify_graph_edges(true /*check for no_dead_code*/, root_and_safepoints);)
 507 }
 508 
 509 // ============================================================================

 657 
 658 Compile::Compile(ciEnv* ci_env, ciMethod* target, int osr_bci,
 659                  Options options, DirectiveSet* directive)
 660     : Phase(Compiler),
 661       _compile_id(ci_env->compile_id()),
 662       _options(options),
 663       _method(target),
 664       _entry_bci(osr_bci),
 665       _ilt(nullptr),
 666       _stub_function(nullptr),
 667       _stub_name(nullptr),
 668       _stub_id(StubId::NO_STUBID),
 669       _stub_entry_point(nullptr),
 670       _max_node_limit(MaxNodeLimit),
 671       _node_count_inlining_cutoff(NodeCountInliningCutoff),
 672       _post_loop_opts_phase(false),
 673       _merge_stores_phase(false),
 674       _allow_macro_nodes(true),
 675       _inlining_progress(false),
 676       _inlining_incrementally(false),
 677       _strength_reduction(false),
 678       _do_cleanup(false),
 679       _has_reserved_stack_access(target->has_reserved_stack_access()),
 680       _has_circular_inline_type(false),
 681 #ifndef PRODUCT
 682       _igv_idx(0),
 683       _trace_opto_output(directive->TraceOptoOutputOption),
 684 #endif
 685       _clinit_barrier_on_entry(false),
 686       _stress_seed(0),
 687       _comp_arena(mtCompiler, Arena::Tag::tag_comp),
 688       _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 689       _env(ci_env),
 690       _directive(directive),
 691       _log(ci_env->log()),
 692       _first_failure_details(nullptr),
 693       _intrinsics(comp_arena(), 0, 0, nullptr),
 694       _macro_nodes(comp_arena(), 8, 0, nullptr),
 695       _parse_predicates(comp_arena(), 8, 0, nullptr),
 696       _template_assertion_predicate_opaques(comp_arena(), 8, 0, nullptr),
 697       _expensive_nodes(comp_arena(), 8, 0, nullptr),
 698       _reachability_fences(comp_arena(), 8, 0, nullptr),
 699       _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
 700       _inline_type_nodes (comp_arena(), 8, 0, nullptr),
 701       _flat_access_nodes(comp_arena(), 8, 0, nullptr),
 702       _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
 703       _unstable_if_traps(comp_arena(), 8, 0, nullptr),
 704       _coarsened_locks(comp_arena(), 8, 0, nullptr),
 705       _congraph(nullptr),
 706       NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 707       _unique(0),
 708       _dead_node_count(0),
 709       _dead_node_list(comp_arena()),
 710       _node_arena_one(mtCompiler, Arena::Tag::tag_node),
 711       _node_arena_two(mtCompiler, Arena::Tag::tag_node),
 712       _node_arena(&_node_arena_one),
 713       _mach_constant_base_node(nullptr),
 714       _Compile_types(mtCompiler, Arena::Tag::tag_type),
 715       _initial_gvn(nullptr),
 716       _igvn_worklist(nullptr),
 717       _types(nullptr),
 718       _node_hash(nullptr),
 719       _late_inlines(comp_arena(), 2, 0, nullptr),
 720       _string_late_inlines(comp_arena(), 2, 0, nullptr),
 721       _boxing_late_inlines(comp_arena(), 2, 0, nullptr),

 790 #define MINIMUM_NODE_HASH  1023
 791 
 792   // GVN that will be run immediately on new nodes
 793   uint estimated_size = method()->code_size()*4+64;
 794   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 795   _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
 796   _types = new (comp_arena()) Type_Array(comp_arena());
 797   _node_hash = new (comp_arena()) NodeHash(comp_arena(), estimated_size);
 798   PhaseGVN gvn;
 799   set_initial_gvn(&gvn);
 800 
 801   { // Scope for timing the parser
 802     TracePhase tp(_t_parser);
 803 
 804     // Put top into the hash table ASAP.
 805     initial_gvn()->transform(top());
 806 
 807     // Set up tf(), start(), and find a CallGenerator.
 808     CallGenerator* cg = nullptr;
 809     if (is_osr_compilation()) {
 810       init_tf(TypeFunc::make(method(), false, /* is_osr_compilation = */ true));
 811       StartNode* s = new StartOSRNode(root(), tf()->domain_sig());


 812       initial_gvn()->set_type_bottom(s);
 813       verify_start(s);
 814       cg = CallGenerator::for_osr(method(), entry_bci());
 815     } else {
 816       // Normal case.
 817       init_tf(TypeFunc::make(method(), false));
 818       StartNode* s = new StartNode(root(), tf()->domain_cc());
 819       initial_gvn()->set_type_bottom(s);
 820       verify_start(s);
 821       float past_uses = method()->interpreter_invocation_count();
 822       float expected_uses = past_uses;
 823       cg = CallGenerator::for_inline(method(), expected_uses);
 824     }
 825     if (failing())  return;
 826     if (cg == nullptr) {
 827       const char* reason = InlineTree::check_can_parse(method());
 828       assert(reason != nullptr, "expect reason for parse failure");
 829       stringStream ss;
 830       ss.print("cannot parse method: %s", reason);
 831       record_method_not_compilable(ss.as_string());
 832       return;
 833     }
 834 
 835     gvn.set_type(root(), root()->bottom_type());
 836 
 837     JVMState* jvms = build_start_state(start(), tf());
 838     if ((jvms = cg->generate(jvms)) == nullptr) {

 896 
 897 #ifndef PRODUCT
 898   if (should_print_ideal()) {
 899     print_ideal_ir("PrintIdeal");
 900   }
 901 #endif
 902 
 903 #ifdef ASSERT
 904   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 905   bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
 906 #endif
 907 
 908   // Dump compilation data to replay it.
 909   if (directive->DumpReplayOption) {
 910     env()->dump_replay_data(_compile_id);
 911   }
 912   if (directive->DumpInlineOption && (ilt() != nullptr)) {
 913     env()->dump_inline_data(_compile_id);
 914   }
 915 
 916   // Now that we know the size of all the monitors we can add fixed slots:
 917   // [...]
 918   // rsp+80: saved fp register
 919   // rsp+76: Fixed slot 7
 920   // rsp+72: Fixed slot 6 (stack increment)
 921   // rsp+68: Fixed slot 5
 922   // rsp+64: Fixed slot 4 (null marker)
 923   // rsp+60: Fixed slot 3
 924   // rsp+56: Fixed slot 2 (original deopt pc)
 925   // rsp+52: Fixed slot 1
 926   // rsp+48: Fixed slot 0 (monitors)
 927   // rsp+44: spill
 928   // [...]
 929 
 930   // One extra slot for the original deopt pc.
 931   int next_slot = fixed_slots();
 932   next_slot += VMRegImpl::slots_per_word;
 933 
 934   // One extra slot for the special stack increment value.
 935   if (needs_stack_repair()) {
 936     next_slot += VMRegImpl::slots_per_word;
 937   }
 938 
 939   // One extra slot to hold the null marker at scalarized returns.
 940   if (needs_nm_slot()) {
 941     next_slot += VMRegImpl::slots_per_word;
 942   }
 943   set_fixed_slots(next_slot);
 944 
 945   // Compute when to use implicit null checks. Used by matching trap based
 946   // nodes and NullCheck optimization.
 947   set_allowed_deopt_reasons();
 948 
 949   // Now generate code
 950   Code_Gen();
 951 }
 952 
 953 //------------------------------Compile----------------------------------------
 954 // Compile a runtime stub
 955 Compile::Compile(ciEnv* ci_env,
 956                  TypeFunc_generator generator,
 957                  address stub_function,
 958                  const char* stub_name,
 959                  StubId stub_id,
 960                  int is_fancy_jump,
 961                  bool pass_tls,
 962                  bool return_pc,
 963                  DirectiveSet* directive)
 964     : Phase(Compiler),
 965       _compile_id(0),
 966       _options(Options::for_runtime_stub()),
 967       _method(nullptr),
 968       _entry_bci(InvocationEntryBci),
 969       _stub_function(stub_function),
 970       _stub_name(stub_name),
 971       _stub_id(stub_id),
 972       _stub_entry_point(nullptr),
 973       _max_node_limit(MaxNodeLimit),
 974       _node_count_inlining_cutoff(NodeCountInliningCutoff),
 975       _post_loop_opts_phase(false),
 976       _merge_stores_phase(false),
 977       _allow_macro_nodes(true),
 978       _inlining_progress(false),
 979       _inlining_incrementally(false),
 980       _has_reserved_stack_access(false),
 981       _has_circular_inline_type(false),
 982 #ifndef PRODUCT
 983       _igv_idx(0),
 984       _trace_opto_output(directive->TraceOptoOutputOption),
 985 #endif
 986       _clinit_barrier_on_entry(false),
 987       _stress_seed(0),
 988       _comp_arena(mtCompiler, Arena::Tag::tag_comp),
 989       _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 990       _env(ci_env),
 991       _directive(directive),
 992       _log(ci_env->log()),
 993       _first_failure_details(nullptr),
 994       _reachability_fences(comp_arena(), 8, 0, nullptr),
 995       _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
 996       _for_merge_stores_igvn(comp_arena(), 8, 0, nullptr),
 997       _congraph(nullptr),
 998       NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 999       _unique(0),
1000       _dead_node_count(0),
1001       _dead_node_list(comp_arena()),

1117   _fixed_slots = 0;
1118   set_has_split_ifs(false);
1119   set_has_loops(false); // first approximation
1120   set_has_stringbuilder(false);
1121   set_has_boxed_value(false);
1122   _trap_can_recompile = false;  // no traps emitted yet
1123   _major_progress = true; // start out assuming good things will happen
1124   set_has_unsafe_access(false);
1125   set_max_vector_size(0);
1126   set_clear_upper_avx(false);  //false as default for clear upper bits of ymm registers
1127   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1128   set_decompile_count(0);
1129 
1130 #ifndef PRODUCT
1131   _phase_counter = 0;
1132   Copy::zero_to_bytes(_igv_phase_iter, sizeof(_igv_phase_iter));
1133 #endif
1134 
1135   set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
1136   _loop_opts_cnt = LoopOptsCount;
1137   _has_flat_accesses = false;
1138   _flat_accesses_share_alias = true;
1139   _scalarize_in_safepoints = false;
1140   _needs_nm_slot = false;
1141 
1142   set_do_inlining(Inline);
1143   set_max_inline_size(MaxInlineSize);
1144   set_freq_inline_size(FreqInlineSize);
1145   set_do_scheduling(OptoScheduling);
1146 
1147   set_do_vector_loop(false);
1148   set_has_monitors(false);
1149   set_has_scoped_access(false);
1150 
1151   if (AllowVectorizeOnDemand) {
1152     if (has_method() && _directive->VectorizeOption) {
1153       set_do_vector_loop(true);
1154       NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n",  method()->name()->as_quoted_ascii());})
1155     } else if (has_method() && method()->name() != nullptr &&
1156                method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
1157       set_do_vector_loop(true);
1158     }
1159   }
1160   set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
1161   NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n",  method()->name()->as_quoted_ascii());})

1393   // If this method has already thrown a range-check,
1394   // assume it was because we already tried range smearing
1395   // and it failed.
1396   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1397   return !already_trapped;
1398 }
1399 
1400 
1401 //------------------------------flatten_alias_type-----------------------------
1402 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1403   assert(do_aliasing(), "Aliasing should be enabled");
1404   int offset = tj->offset();
1405   TypePtr::PTR ptr = tj->ptr();
1406 
1407   // Known instance (scalarizable allocation) alias only with itself.
1408   bool is_known_inst = tj->isa_oopptr() != nullptr &&
1409                        tj->is_oopptr()->is_known_instance();
1410 
1411   // Process weird unsafe references.
1412   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1413     assert(InlineUnsafeOps || StressReflectiveCode || UseAcmpFastPath, "indeterminate pointers come only from unsafe ops");
1414     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1415     tj = TypeOopPtr::BOTTOM;
1416     ptr = tj->ptr();
1417     offset = tj->offset();
1418   }
1419 
1420   // Array pointers need some flattening
1421   const TypeAryPtr* ta = tj->isa_aryptr();




1422   if( ta && is_known_inst ) {
1423     if ( offset != Type::OffsetBot &&
1424          offset > arrayOopDesc::length_offset_in_bytes() ) {
1425       offset = Type::OffsetBot; // Flatten constant access into array body only
1426       tj = ta = ta->
1427               remove_speculative()->
1428               cast_to_ptr_type(ptr)->
1429               with_offset(offset);
1430     }
1431   } else if (ta != nullptr) {
1432     // Common slices
1433     if (offset == arrayOopDesc::length_offset_in_bytes()) {
1434       return TypeAryPtr::RANGE;
1435     } else if (offset == oopDesc::klass_offset_in_bytes()) {
1436       return TypeInstPtr::KLASS;
1437     } else if (offset == oopDesc::mark_offset_in_bytes()) {
1438       return TypeInstPtr::MARK;
1439     }
1440 
1441     // Remove size and stability
1442     const TypeAry* normalized_ary = TypeAry::make(ta->elem(), TypeInt::POS, false, ta->is_flat(), ta->is_not_flat(), ta->is_not_null_free(), ta->is_atomic());
1443     // Remove ptr, const_oop, and offset
1444     if (ta->elem() == Type::BOTTOM) {
1445       // Bottom array (meet of int[] and byte[] for example), accesses to it will be done with
1446       // Unsafe. This should alias with all arrays. For now just leave it as it is (this is
1447       // incorrect, see JDK-8331133).
1448       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, false, Type::Offset::bottom);
1449     } else if (ta->elem()->make_oopptr() != nullptr) {
1450       // Object arrays, keep field_offset
1451       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, nullptr, ta->klass_is_exact(), Type::Offset::bottom, Type::Offset(ta->field_offset()));

1452     } else {
1453       // Primitive arrays
1454       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, normalized_ary, ta->exact_klass(), true, Type::Offset::bottom);
1455     }
1456 
1457     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1458     // cannot be distinguished by bytecode alone.
1459     if (ta->elem() == TypeInt::BOOL) {
1460       tj = ta = TypeAryPtr::BYTES;
1461     }
1462 
1463     // All arrays of references share the same slice
1464     if (!ta->is_flat() && ta->elem()->make_oopptr() != nullptr) {
1465       const TypeAry* tary = TypeAry::make(TypeInstPtr::BOTTOM, TypeInt::POS, false, false, true, true, true);
1466       tj = ta = TypeAryPtr::make(TypePtr::BotPTR, nullptr, tary, nullptr, false, Type::Offset::bottom);
1467     }
1468 
1469     if (ta->is_flat()) {
1470       if (_flat_accesses_share_alias) {
1471         // Initially all flattened array accesses share a single slice
1472         tj = ta = TypeAryPtr::INLINES;
1473       } else {
1474         // Flat accesses are always exact
1475         tj = ta = ta->cast_to_exactness(true);
1476       }
1477     }
1478   }
1479 
1480   // Oop pointers need some flattening
1481   const TypeInstPtr *to = tj->isa_instptr();
1482   if (to && to != TypeOopPtr::BOTTOM) {
1483     ciInstanceKlass* ik = to->instance_klass();
1484     tj = to = to->cast_to_maybe_flat_in_array(); // flatten to maybe flat in array
1485     if( ptr == TypePtr::Constant ) {
1486       if (ik != ciEnv::current()->Class_klass() ||
1487           offset < ik->layout_helper_size_in_bytes()) {
1488         // No constant oop pointers (such as Strings); they alias with
1489         // unknown strings.
1490         assert(!is_known_inst, "not scalarizable allocation");
1491         tj = to = to->
1492                 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1493                 remove_speculative()->
1494                 cast_to_ptr_type(TypePtr::BotPTR)->
1495                 cast_to_exactness(false);
1496       }
1497     } else if( is_known_inst ) {
1498       tj = to; // Keep NotNull and klass_is_exact for instance type
1499     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1500       // During the 2nd round of IterGVN, NotNull castings are removed.
1501       // Make sure the Bottom and NotNull variants alias the same.
1502       // Also, make sure exact and non-exact variants alias the same.
1503       tj = to = to->
1504               remove_speculative()->
1505               cast_to_instance_id(TypeOopPtr::InstanceBot)->
1506               cast_to_ptr_type(TypePtr::BotPTR)->
1507               cast_to_exactness(false);
1508     }
1509     if (to->speculative() != nullptr) {
1510       tj = to = to->remove_speculative();
1511     }
1512     // Canonicalize the holder of this field
1513     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1514       // First handle header references such as a LoadKlassNode, even if the
1515       // object's klass is unloaded at compile time (4965979).
1516       if (!is_known_inst) { // Do it only for non-instance types
1517         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, nullptr, Type::Offset(offset));
1518       }
1519     } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) {
1520       // Static fields are in the space above the normal instance
1521       // fields in the java.lang.Class instance.
1522       if (ik != ciEnv::current()->Class_klass()) {
1523         to = nullptr;
1524         tj = TypeOopPtr::BOTTOM;
1525         offset = tj->offset();
1526       }
1527     } else {
1528       ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset);
1529       assert(offset < canonical_holder->layout_helper_size_in_bytes(), "");
1530       assert(tj->offset() == offset, "no change to offset expected");
1531       bool xk = to->klass_is_exact();
1532       int instance_id = to->instance_id();
1533 
1534       // If the input type's class is the holder: if exact, the type only includes interfaces implemented by the holder
1535       // but if not exact, it may include extra interfaces: build new type from the holder class to make sure only
1536       // its interfaces are included.
1537       if (xk && ik->equals(canonical_holder)) {
1538         assert(tj == TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, Type::Offset(offset), instance_id,
1539                                        TypePtr::MaybeFlat), "exact type should be canonical type");
1540       } else {
1541         assert(xk || !is_known_inst, "Known instance should be exact type");
1542         tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, is_known_inst, nullptr, Type::Offset(offset), instance_id,
1543                                     TypePtr::MaybeFlat);
1544       }
1545     }
1546   }
1547 
1548   // Klass pointers to object array klasses need some flattening
1549   const TypeKlassPtr *tk = tj->isa_klassptr();
1550   if( tk ) {
1551     // If we are referencing a field within a Klass, we need
1552     // to assume the worst case of an Object.  Both exact and
1553     // inexact types must flatten to the same alias class so
1554     // use NotNull as the PTR.
1555     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1556       tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull,
1557                                        env()->Object_klass(),
1558                                        Type::Offset(offset),
1559                                        TypePtr::MaybeFlat);
1560     }
1561 
1562     if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) {
1563       ciKlass* k = ciObjArrayKlass::make(env()->Object_klass());
1564       if (!k || !k->is_loaded()) {                  // Only fails for some -Xcomp runs
1565         tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), Type::Offset(offset), TypePtr::MaybeFlat);
1566       } else {
1567         tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, Type::Offset(offset), tk->is_not_flat(), tk->is_not_null_free(), tk->is_flat(), tk->is_null_free(), tk->is_atomic(), tk->is_aryklassptr()->is_refined_type());
1568       }
1569     }

1570     // Check for precise loads from the primary supertype array and force them
1571     // to the supertype cache alias index.  Check for generic array loads from
1572     // the primary supertype array and also force them to the supertype cache
1573     // alias index.  Since the same load can reach both, we need to merge
1574     // these 2 disparate memories into the same alias class.  Since the
1575     // primary supertype array is read-only, there's no chance of confusion
1576     // where we bypass an array load and an array store.
1577     int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1578     if (offset == Type::OffsetBot ||
1579         (offset >= primary_supers_offset &&
1580          offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1581         offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1582       offset = in_bytes(Klass::secondary_super_cache_offset());
1583       tj = tk = tk->with_offset(offset);
1584     }
1585   }
1586 
1587   // Flatten all Raw pointers together.
1588   if (tj->base() == Type::RawPtr)
1589     tj = TypeRawPtr::BOTTOM;

1679   intptr_t key = (intptr_t) adr_type;
1680   key ^= key >> logAliasCacheSize;
1681   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1682 }
1683 
1684 
1685 //-----------------------------grow_alias_types--------------------------------
1686 void Compile::grow_alias_types() {
1687   const int old_ats  = _max_alias_types; // how many before?
1688   const int new_ats  = old_ats;          // how many more?
1689   const int grow_ats = old_ats+new_ats;  // how many now?
1690   _max_alias_types = grow_ats;
1691   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), _alias_types, old_ats, grow_ats);
1692   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1693   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1694   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1695 }
1696 
1697 
1698 //--------------------------------find_alias_type------------------------------
1699 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field, bool uncached) {
1700   if (!do_aliasing()) {
1701     return alias_type(AliasIdxBot);
1702   }
1703 
1704   AliasCacheEntry* ace = nullptr;
1705   if (!uncached) {
1706     ace = probe_alias_cache(adr_type);
1707     if (ace->_adr_type == adr_type) {
1708       return alias_type(ace->_index);
1709     }
1710   }
1711 
1712   // Handle special cases.
1713   if (adr_type == nullptr)          return alias_type(AliasIdxTop);
1714   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1715 
1716   // Do it the slow way.
1717   const TypePtr* flat = flatten_alias_type(adr_type);
1718 
1719 #ifdef ASSERT
1720   {
1721     ResourceMark rm;
1722     assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1723            Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1724     assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1725            Type::str(adr_type));
1726     if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1727       const TypeOopPtr* foop = flat->is_oopptr();
1728       // Scalarizable allocations have exact klass always.
1729       bool exact = !foop->klass_is_exact() || foop->is_known_instance();

1739     if (alias_type(i)->adr_type() == flat) {
1740       idx = i;
1741       break;
1742     }
1743   }
1744 
1745   if (idx == AliasIdxTop) {
1746     if (no_create)  return nullptr;
1747     // Grow the array if necessary.
1748     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1749     // Add a new alias type.
1750     idx = _num_alias_types++;
1751     _alias_types[idx]->Init(idx, flat);
1752     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1753     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1754     if (flat->isa_instptr()) {
1755       if (flat->offset() == java_lang_Class::klass_offset()
1756           && flat->is_instptr()->instance_klass() == env()->Class_klass())
1757         alias_type(idx)->set_rewritable(false);
1758     }
1759     ciField* field = nullptr;
1760     if (flat->isa_aryptr()) {
1761 #ifdef ASSERT
1762       const int header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1763       // (T_BYTE has the weakest alignment and size restrictions...)
1764       assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1765 #endif
1766       const Type* elemtype = flat->is_aryptr()->elem();
1767       if (flat->offset() == TypePtr::OffsetBot) {
1768         alias_type(idx)->set_element(elemtype);
1769       }
1770       int field_offset = flat->is_aryptr()->field_offset().get();
1771       if (flat->is_flat() &&
1772           field_offset != Type::OffsetBot) {
1773         ciInlineKlass* vk = elemtype->inline_klass();
1774         field_offset += vk->payload_offset();
1775         field = vk->get_field_by_offset(field_offset, false);
1776       }
1777     }
1778     if (flat->isa_klassptr()) {
1779       if (UseCompactObjectHeaders) {
1780         if (flat->offset() == in_bytes(Klass::prototype_header_offset()))
1781           alias_type(idx)->set_rewritable(false);
1782       }
1783       if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1784         alias_type(idx)->set_rewritable(false);
1785       if (flat->offset() == in_bytes(Klass::misc_flags_offset()))
1786         alias_type(idx)->set_rewritable(false);
1787       if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1788         alias_type(idx)->set_rewritable(false);
1789       if (flat->offset() == in_bytes(Klass::layout_helper_offset()))
1790         alias_type(idx)->set_rewritable(false);
1791       if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1792         alias_type(idx)->set_rewritable(false);
1793     }
1794 
1795     if (flat->isa_instklassptr()) {
1796       if (flat->offset() == in_bytes(InstanceKlass::access_flags_offset())) {
1797         alias_type(idx)->set_rewritable(false);
1798       }
1799     }
1800     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1801     // but the base pointer type is not distinctive enough to identify
1802     // references into JavaThread.)
1803 
1804     // Check for final fields.
1805     const TypeInstPtr* tinst = flat->isa_instptr();
1806     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {

1807       if (tinst->const_oop() != nullptr &&
1808           tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1809           tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1810         // static field
1811         ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1812         field = k->get_field_by_offset(tinst->offset(), true);
1813       } else if (tinst->is_inlinetypeptr()) {
1814         // Inline type field
1815         ciInlineKlass* vk = tinst->inline_klass();
1816         field = vk->get_field_by_offset(tinst->offset(), false);
1817       } else {
1818         ciInstanceKlass *k = tinst->instance_klass();
1819         field = k->get_field_by_offset(tinst->offset(), false);
1820       }
1821     }
1822     assert(field == nullptr ||
1823            original_field == nullptr ||
1824            (field->holder() == original_field->holder() &&
1825             field->offset_in_bytes() == original_field->offset_in_bytes() &&
1826             field->is_static() == original_field->is_static()), "wrong field?");
1827     // Set field() and is_rewritable() attributes.
1828     if (field != nullptr) {
1829       alias_type(idx)->set_field(field);
1830       if (flat->isa_aryptr()) {
1831         // Fields of flat arrays are rewritable although they are declared final
1832         assert(flat->is_flat(), "must be a flat array");
1833         alias_type(idx)->set_rewritable(true);
1834       }
1835     }
1836   }
1837 
1838   // Fill the cache for next time.
1839   if (!uncached) {
1840     ace->_adr_type = adr_type;
1841     ace->_index    = idx;
1842     assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1843 
1844     // Might as well try to fill the cache for the flattened version, too.
1845     AliasCacheEntry* face = probe_alias_cache(flat);
1846     if (face->_adr_type == nullptr) {
1847       face->_adr_type = flat;
1848       face->_index    = idx;
1849       assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1850     }
1851   }
1852 
1853   return alias_type(idx);
1854 }
1855 
1856 
1857 Compile::AliasType* Compile::alias_type(ciField* field) {
1858   const TypeOopPtr* t;
1859   if (field->is_static())
1860     t = TypeInstPtr::make(field->holder()->java_mirror());
1861   else
1862     t = TypeOopPtr::make_from_klass_raw(field->holder());
1863   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1864   assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1865   return atp;
1866 }
1867 
1868 
1869 //------------------------------have_alias_type--------------------------------
1870 bool Compile::have_alias_type(const TypePtr* adr_type) {

1952   assert(!C->major_progress(), "not cleared");
1953 
1954   if (_for_post_loop_igvn.length() > 0) {
1955     while (_for_post_loop_igvn.length() > 0) {
1956       Node* n = _for_post_loop_igvn.pop();
1957       n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1958       igvn._worklist.push(n);
1959     }
1960     igvn.optimize();
1961     if (failing()) return;
1962     assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1963     assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1964 
1965     // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1966     if (C->major_progress()) {
1967       C->clear_major_progress(); // ensure that major progress is now clear
1968     }
1969   }
1970 }
1971 
1972 void Compile::add_inline_type(Node* n) {
1973   assert(n->is_InlineType(), "unexpected node");
1974   _inline_type_nodes.push(n);
1975 }
1976 
1977 void Compile::remove_inline_type(Node* n) {
1978   assert(n->is_InlineType(), "unexpected node");
1979   if (_inline_type_nodes.contains(n)) {
1980     _inline_type_nodes.remove(n);
1981   }
1982 }
1983 
1984 // Does the return value keep otherwise useless inline type allocations alive?
1985 static bool return_val_keeps_allocations_alive(Node* ret_val) {
1986   ResourceMark rm;
1987   Unique_Node_List wq;
1988   wq.push(ret_val);
1989   bool some_allocations = false;
1990   for (uint i = 0; i < wq.size(); i++) {
1991     Node* n = wq.at(i);
1992     if (n->outcnt() > 1) {
1993       // Some other use for the allocation
1994       return false;
1995     } else if (n->is_InlineType()) {
1996       wq.push(n->in(1));
1997     } else if (n->is_Phi()) {
1998       for (uint j = 1; j < n->req(); j++) {
1999         wq.push(n->in(j));
2000       }
2001     } else if (n->is_CheckCastPP() &&
2002                n->in(1)->is_Proj() &&
2003                n->in(1)->in(0)->is_Allocate()) {
2004       some_allocations = true;
2005     } else if (n->is_CheckCastPP()) {
2006       wq.push(n->in(1));
2007     }
2008   }
2009   return some_allocations;
2010 }
2011 
2012 bool Compile::clear_argument_if_only_used_as_buffer_at_calls(Node* result_cast, PhaseIterGVN& igvn) {
2013   ResourceMark rm;
2014   Unique_Node_List wq;
2015   wq.push(result_cast);
2016   Node_List calls;
2017   for (uint i = 0; i < wq.size(); ++i) {
2018     Node* n = wq.at(i);
2019     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2020       Node* u = n->fast_out(j);
2021       if (u->is_Phi()) {
2022         wq.push(u);
2023       } else if (u->is_InlineType() && u->as_InlineType()->get_oop() == n) {
2024         wq.push(u);
2025       } else if (u->is_CallJava()) {
2026         CallJavaNode* call = u->as_CallJava();
2027         if (call->method() != nullptr && call->method()->mismatch()) {
2028           return false;
2029         }
2030         uint nargs = call->tf()->domain_cc()->cnt();
2031         for (uint k = TypeFunc::Parms; k < nargs; k++) {
2032           Node* in = call->in(k);
2033           if (in == n && (call->method() == nullptr || !call->method()->is_scalarized_buffer_arg(k - TypeFunc::Parms))) {
2034             return false;
2035           }
2036         }
2037         calls.push(call);
2038       } else if (u->Opcode() == Op_EncodeP) {
2039         wq.push(u);
2040       } else if (u->is_AddP()) {
2041         wq.push(u);
2042       } else if (u->is_Store() && u->in(MemNode::Address) == n) {
2043         // storing to the buffer is fine
2044       } else if (u->is_SafePoint()) {
2045         SafePointNode* sfpt = u->as_SafePoint();
2046         int input = u->find_edge(n);
2047         JVMState* jvms = sfpt->jvms();
2048         if (jvms != nullptr) {
2049           if (input < (int)jvms->debug_start()) {
2050             return false;
2051           }
2052         }
2053       } else {
2054         return false;
2055       }
2056     }
2057   }
2058   for (uint i = 0; i < calls.size(); ++i) {
2059     CallJavaNode* call = calls.at(i)->as_CallJava();
2060     uint nargs = call->tf()->domain_cc()->cnt();
2061     for (uint k = TypeFunc::Parms; k < nargs; k++) {
2062       Node* in = call->in(k);
2063       if (wq.member(in)) {
2064         assert(call->method()->is_scalarized_buffer_arg(k - TypeFunc::Parms), "only buffer argument removed here");
2065         igvn.replace_input_of(call, k, igvn.zerocon(T_OBJECT));
2066       }
2067     }
2068   }
2069   return true;
2070 }
2071 
2072 void Compile::process_inline_types(PhaseIterGVN &igvn, bool remove) {
2073   // Make sure that the return value does not keep an otherwise unused allocation alive
2074   if (tf()->returns_inline_type_as_fields()) {
2075     Node* ret = nullptr;
2076     for (uint i = 1; i < root()->req(); i++) {
2077       Node* in = root()->in(i);
2078       if (in->Opcode() == Op_Return) {
2079         assert(ret == nullptr, "only one return");
2080         ret = in;
2081       }
2082     }
2083     if (ret != nullptr) {
2084       Node* ret_val = ret->in(TypeFunc::Parms);
2085       if (igvn.type(ret_val)->isa_oopptr() &&
2086           return_val_keeps_allocations_alive(ret_val)) {
2087         igvn.replace_input_of(ret, TypeFunc::Parms, InlineTypeNode::tagged_klass(igvn.type(ret_val)->inline_klass(), igvn));
2088         assert(ret_val->outcnt() == 0, "should be dead now");
2089         igvn.remove_dead_node(ret_val, PhaseIterGVN::NodeOrigin::Graph);
2090       }
2091     }
2092   }
2093   // if a newly allocated object is a value that's only passed as argument to calls as (possibly null) buffers, then
2094   // clear the call argument inputs so the allocation node can be removed
2095   for (int i = 0; i < C->macro_count(); ++i) {
2096     Node* macro_node = C->macro_node(i);
2097     if (macro_node->Opcode() == Op_Allocate) {
2098       AllocateNode* allocate = macro_node->as_Allocate();
2099       Node* result_cast = allocate->result_cast();
2100       if (result_cast != nullptr) {
2101         const Type* result_type = igvn.type(result_cast);
2102         if (result_type->is_inlinetypeptr()) {
2103           clear_argument_if_only_used_as_buffer_at_calls(result_cast, igvn);
2104         }
2105       }
2106     }
2107   }
2108 
2109   if (_inline_type_nodes.length() == 0) {
2110     // keep the graph canonical
2111     igvn.optimize();
2112     return;
2113   }
2114   // Scalarize inline types in safepoint debug info.
2115   // Delay this until all inlining is over to avoid getting inconsistent debug info.
2116   set_scalarize_in_safepoints(true);
2117   for (int i = _inline_type_nodes.length()-1; i >= 0; i--) {
2118     InlineTypeNode* vt = _inline_type_nodes.at(i)->as_InlineType();
2119     vt->make_scalar_in_safepoints(&igvn);
2120     igvn.record_for_igvn(vt);
2121   }
2122   if (remove) {
2123     // Remove inline type nodes by replacing them with their oop input
2124     while (_inline_type_nodes.length() > 0) {
2125       InlineTypeNode* vt = _inline_type_nodes.pop()->as_InlineType();
2126       if (vt->outcnt() == 0) {
2127         igvn.remove_dead_node(vt, PhaseIterGVN::NodeOrigin::Graph);
2128         continue;
2129       }
2130       for (DUIterator i = vt->outs(); vt->has_out(i); i++) {
2131         DEBUG_ONLY(bool must_be_buffered = false);
2132         Node* u = vt->out(i);
2133         // Check if any users are blackholes. If so, rewrite them to use either the
2134         // allocated buffer, or individual components, instead of the inline type node
2135         // that goes away.
2136         if (u->is_Blackhole()) {
2137           BlackholeNode* bh = u->as_Blackhole();
2138 
2139           // Unlink the old input
2140           int idx = bh->find_edge(vt);
2141           assert(idx != -1, "The edge should be there");
2142           bh->del_req(idx);
2143           --i;
2144 
2145           if (vt->is_allocated(&igvn)) {
2146             // Already has the allocated instance, blackhole that
2147             bh->add_req(vt->get_oop());
2148           } else {
2149             // Not allocated yet, blackhole the components
2150             for (uint c = 0; c < vt->field_count(); c++) {
2151               bh->add_req(vt->field_value(c));
2152             }
2153           }
2154 
2155           // Node modified, record for IGVN
2156           igvn.record_for_igvn(bh);
2157         }
2158 #ifdef ASSERT
2159         // Verify that inline type is buffered when replacing by oop
2160         else if (u->is_InlineType()) {
2161           // InlineType uses don't need buffering because they are about to be replaced as well
2162         } else if (u->is_Phi()) {
2163           // TODO 8302217 Remove this once InlineTypeNodes are reliably pushed through
2164         } else {
2165           must_be_buffered = true;
2166         }
2167         if (must_be_buffered && !vt->is_allocated(&igvn)) {
2168           vt->dump(0);
2169           u->dump(0);
2170           assert(false, "Should have been buffered");
2171         }
2172 #endif
2173       }
2174       igvn.replace_node(vt, vt->get_oop());
2175     }
2176   }
2177   igvn.optimize();
2178 }
2179 
2180 void Compile::add_flat_access(Node* n) {
2181   assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name());
2182   assert(!_flat_access_nodes.contains(n), "duplicate insertion");
2183   _flat_access_nodes.push(n);
2184 }
2185 
2186 void Compile::remove_flat_access(Node* n) {
2187   assert(n != nullptr && (n->Opcode() == Op_LoadFlat || n->Opcode() == Op_StoreFlat), "unexpected node %s", n == nullptr ? "nullptr" : n->Name());
2188   _flat_access_nodes.remove_if_existing(n);
2189 }
2190 
2191 void Compile::process_flat_accesses(PhaseIterGVN& igvn) {
2192   assert(igvn._worklist.size() == 0, "should be empty");
2193   igvn.set_delay_transform(true);
2194   for (int i = _flat_access_nodes.length() - 1; i >= 0; i--) {
2195     Node* n = _flat_access_nodes.at(i);
2196     assert(n != nullptr, "unexpected nullptr");
2197     if (n->is_LoadFlat()) {
2198       LoadFlatNode* loadn = n->as_LoadFlat();
2199       // Expending a flat load atomically means that we get a chunk of memory spanning multiple fields
2200       // that we chop with bitwise operations. That is too subtle for some optimizations, especially
2201       // constant folding when fields are constant. If we can get a constant object from which we are
2202       // flat-loading, we can simply replace the loads at compilation-time by the field of the constant
2203       // object.
2204       ciInstance* loaded_from = nullptr;
2205       if (FoldStableValues) {
2206         const TypeOopPtr* base_type = igvn.type(loadn->base())->is_oopptr();
2207         ciObject* oop = base_type->const_oop();
2208         int off = igvn.type(loadn->ptr())->isa_ptr()->offset();
2209 
2210         if (oop != nullptr && oop->is_instance()) {
2211           ciInstance* holder = oop->as_instance();
2212           ciKlass* klass = holder->klass();
2213           ciInstanceKlass* iklass = klass->as_instance_klass();
2214           ciField* field = iklass->get_non_flat_field_by_offset(off);
2215 
2216           if (field->is_stable()) {
2217             ciConstant fv = holder->field_value(field);
2218             if (is_reference_type(fv.basic_type()) && fv.as_object()->is_instance()) {
2219               // The field value is an object, not null. We can use stability.
2220               loaded_from = fv.as_object()->as_instance();
2221             }
2222           }
2223         } else if (oop != nullptr && oop->is_array() && off != Type::OffsetBot) {
2224           ciArray* array = oop->as_array();
2225           ciConstant elt = array->element_value_by_offset(off);
2226           const TypeAryPtr* aryptr = base_type->is_aryptr();
2227           if (aryptr->is_stable() && aryptr->is_atomic() && is_reference_type(elt.basic_type()) && elt.as_object()->is_instance()) {
2228             loaded_from = elt.as_object()->as_instance();
2229           }
2230         }
2231       }
2232 
2233       if (loaded_from != nullptr) {
2234         loadn->expand_constant(igvn, loaded_from);
2235       } else {
2236         loadn->expand_atomic(igvn);
2237       }
2238     } else {
2239       n->as_StoreFlat()->expand_atomic(igvn);
2240     }
2241   }
2242   _flat_access_nodes.clear_and_deallocate();
2243   igvn.set_delay_transform(false);
2244   igvn.optimize();
2245 }
2246 
2247 void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) {
2248   DEBUG_ONLY(igvn.verify_empty_worklist(nullptr));
2249   if (!_has_flat_accesses) {
2250     return;
2251   }
2252   // Initially, all flat array accesses share the same slice to
2253   // keep dependencies with Object[] array accesses (that could be
2254   // to a flat array) correct. We're done with parsing so we
2255   // now know all flat array accesses in this compile
2256   // unit. Let's move flat array accesses to their own slice,
2257   // one per element field. This should help memory access
2258   // optimizations.
2259   ResourceMark rm;
2260   Unique_Node_List wq;
2261   wq.push(root());
2262 
2263   Node_List mergememnodes;
2264   Node_List memnodes;
2265 
2266   // Alias index currently shared by all flat memory accesses
2267   int index = get_alias_index(TypeAryPtr::INLINES);
2268 
2269   // Find MergeMem nodes and flat array accesses
2270   for (uint i = 0; i < wq.size(); i++) {
2271     Node* n = wq.at(i);
2272     if (n->is_Mem()) {
2273       const TypePtr* adr_type = nullptr;
2274       adr_type = get_adr_type(get_alias_index(n->adr_type()));
2275       if (adr_type == TypeAryPtr::INLINES) {
2276         memnodes.push(n);
2277       }
2278     } else if (n->is_MergeMem()) {
2279       MergeMemNode* mm = n->as_MergeMem();
2280       if (mm->memory_at(index) != mm->base_memory()) {
2281         mergememnodes.push(n);
2282       }
2283     }
2284     for (uint j = 0; j < n->req(); j++) {
2285       Node* m = n->in(j);
2286       if (m != nullptr) {
2287         wq.push(m);
2288       }
2289     }
2290   }
2291 
2292   _flat_accesses_share_alias = false;
2293 
2294   // We are going to change the slice for the flat array
2295   // accesses so we need to clear the cache entries that refer to
2296   // them.
2297   for (uint i = 0; i < AliasCacheSize; i++) {
2298     AliasCacheEntry* ace = &_alias_cache[i];
2299     if (ace->_adr_type != nullptr &&
2300         ace->_adr_type->is_flat()) {
2301       ace->_adr_type = nullptr;
2302       ace->_index = (i != 0) ? 0 : AliasIdxTop; // Make sure the nullptr adr_type resolves to AliasIdxTop
2303     }
2304   }
2305 
2306 #ifdef ASSERT
2307   for (uint i = 0; i < memnodes.size(); i++) {
2308     Node* m = memnodes.at(i);
2309     const TypePtr* adr_type = m->adr_type();
2310     m->as_Mem()->set_adr_type(adr_type);
2311   }
2312 #endif // ASSERT
2313 
2314   int start_alias = num_alias_types(); // Start of new aliases
2315   Node_Stack stack(0);
2316 #ifdef ASSERT
2317   VectorSet seen(Thread::current()->resource_area());
2318 #endif
2319   // Now let's fix the memory graph so each flat array access
2320   // is moved to the right slice. Start from the MergeMem nodes.
2321   uint last = unique();
2322   for (uint i = 0; i < mergememnodes.size(); i++) {
2323     MergeMemNode* current = mergememnodes.at(i)->as_MergeMem();
2324     if (current->outcnt() == 0) {
2325       // This node is killed by a previous iteration
2326       continue;
2327     }
2328 
2329     Node* n = current->memory_at(index);
2330     MergeMemNode* mm = nullptr;
2331     do {
2332       // Follow memory edges through memory accesses, phis and
2333       // narrow membars and push nodes on the stack. Once we hit
2334       // bottom memory, we pop element off the stack one at a
2335       // time, in reverse order, and move them to the right slice
2336       // by changing their memory edges.
2337       if ((n->is_Phi() && n->adr_type() != TypePtr::BOTTOM) || n->is_Mem() ||
2338           (n->adr_type() == TypeAryPtr::INLINES && !n->is_NarrowMemProj())) {
2339         assert(!seen.test_set(n->_idx), "");
2340         // Uses (a load for instance) will need to be moved to the
2341         // right slice as well and will get a new memory state
2342         // that we don't know yet. The use could also be the
2343         // backedge of a loop. We put a place holder node between
2344         // the memory node and its uses. We replace that place
2345         // holder with the correct memory state once we know it,
2346         // i.e. when nodes are popped off the stack. Using the
2347         // place holder make the logic work in the presence of
2348         // loops.
2349         if (n->outcnt() > 1) {
2350           Node* place_holder = nullptr;
2351           assert(!n->has_out_with(Op_Node), "");
2352           for (DUIterator k = n->outs(); n->has_out(k); k++) {
2353             Node* u = n->out(k);
2354             if (u != current && u->_idx < last) {
2355               bool success = false;
2356               for (uint l = 0; l < u->req(); l++) {
2357                 if (!stack.is_empty() && u == stack.node() && l == stack.index()) {
2358                   continue;
2359                 }
2360                 Node* in = u->in(l);
2361                 if (in == n) {
2362                   if (place_holder == nullptr) {
2363                     place_holder = new Node(1);
2364                     place_holder->init_req(0, n);
2365                   }
2366                   igvn.replace_input_of(u, l, place_holder);
2367                   success = true;
2368                 }
2369               }
2370               if (success) {
2371                 --k;
2372               }
2373             }
2374           }
2375         }
2376         if (n->is_Phi()) {
2377           stack.push(n, 1);
2378           n = n->in(1);
2379         } else if (n->is_Mem()) {
2380           stack.push(n, n->req());
2381           n = n->in(MemNode::Memory);
2382         } else {
2383           assert(n->is_Proj() && n->in(0)->Opcode() == Op_MemBarCPUOrder, "");
2384           stack.push(n, n->req());
2385           n = n->in(0)->in(TypeFunc::Memory);
2386         }
2387       } else {
2388         assert(n->adr_type() == TypePtr::BOTTOM || (n->Opcode() == Op_Node && n->_idx >= last) || n->is_NarrowMemProj(), "");
2389         // Build a new MergeMem node to carry the new memory state
2390         // as we build it. IGVN should fold extraneous MergeMem
2391         // nodes.
2392         if (n->is_NarrowMemProj()) {
2393           // We need 1 NarrowMemProj for each slice of this array
2394           InitializeNode* init = n->in(0)->as_Initialize();
2395           AllocateNode* alloc = init->allocation();
2396           Node* klass_node = alloc->in(AllocateNode::KlassNode);
2397           const TypeAryKlassPtr* klass_type = klass_node->bottom_type()->isa_aryklassptr();
2398           assert(klass_type != nullptr, "must be an array");
2399           assert(klass_type->klass_is_exact(), "must be an exact klass");
2400           ciArrayKlass* klass = klass_type->exact_klass()->as_array_klass();
2401           assert(klass->is_flat_array_klass(), "must be a flat array");
2402           ciInlineKlass* elem_klass = klass->element_klass()->as_inline_klass();
2403           const TypeAryPtr* oop_type = klass_type->as_instance_type()->is_aryptr();
2404           assert(oop_type->klass_is_exact(), "must be an exact klass");
2405 
2406           Node* base = alloc->in(TypeFunc::Memory);
2407           assert(base->bottom_type() == Type::MEMORY, "the memory input of AllocateNode must be a memory");
2408           assert(base->adr_type() == TypePtr::BOTTOM, "the memory input of AllocateNode must be a bottom memory");
2409           // Must create a MergeMem with base as the base memory, do not clone if base is a
2410           // MergeMem because it may not be processed yet
2411           mm = MergeMemNode::make(nullptr);
2412           mm->set_base_memory(base);
2413           for (int j = 0; j < elem_klass->nof_nonstatic_fields(); j++) {
2414             int field_offset = elem_klass->nonstatic_field_at(j)->offset_in_bytes() - elem_klass->payload_offset();
2415             const TypeAryPtr* field_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(field_offset);
2416             int field_alias_idx = get_alias_index(field_ptr);
2417             assert(field_ptr == get_adr_type(field_alias_idx), "must match");
2418             Node* new_proj = new NarrowMemProjNode(init, field_ptr);
2419             igvn.register_new_node_with_optimizer(new_proj);
2420             mm->set_memory_at(field_alias_idx, new_proj);
2421           }
2422           if (!klass->is_elem_null_free()) {
2423             int nm_offset = elem_klass->null_marker_offset_in_payload();
2424             const TypeAryPtr* nm_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(nm_offset);
2425             int nm_alias_idx = get_alias_index(nm_ptr);
2426             assert(nm_ptr == get_adr_type(nm_alias_idx), "must match");
2427             Node* new_proj = new NarrowMemProjNode(init, nm_ptr);
2428             igvn.register_new_node_with_optimizer(new_proj);
2429             mm->set_memory_at(nm_alias_idx, new_proj);
2430           }
2431 
2432           // Replace all uses of the old NarrowMemProj with the correct state
2433           MergeMemNode* new_n = MergeMemNode::make(mm);
2434           igvn.register_new_node_with_optimizer(new_n);
2435           igvn.replace_node(n, new_n);
2436         } else {
2437           // Must create a MergeMem with n as the base memory, do not clone if n is a MergeMem
2438           // because it may not be processed yet
2439           mm = MergeMemNode::make(nullptr);
2440           mm->set_base_memory(n);
2441         }
2442 
2443         igvn.register_new_node_with_optimizer(mm);
2444         while (stack.size() > 0) {
2445           Node* m = stack.node();
2446           uint idx = stack.index();
2447           if (m->is_Mem()) {
2448             // Move memory node to its new slice
2449             const TypePtr* adr_type = m->adr_type();
2450             int alias = get_alias_index(adr_type);
2451             Node* prev = mm->memory_at(alias);
2452             igvn.replace_input_of(m, MemNode::Memory, prev);
2453             mm->set_memory_at(alias, m);
2454           } else if (m->is_Phi()) {
2455             // We need as many new phis as there are new aliases
2456             Node* new_phi_in = MergeMemNode::make(mm);
2457             igvn.register_new_node_with_optimizer(new_phi_in);
2458             igvn.replace_input_of(m, idx, new_phi_in);
2459             if (idx == m->req()-1) {
2460               Node* r = m->in(0);
2461               for (int j = start_alias; j < num_alias_types(); j++) {
2462                 const TypePtr* adr_type = get_adr_type(j);
2463                 if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2464                   continue;
2465                 }
2466                 Node* phi = new PhiNode(r, Type::MEMORY, get_adr_type(j));
2467                 igvn.register_new_node_with_optimizer(phi);
2468                 for (uint k = 1; k < m->req(); k++) {
2469                   phi->init_req(k, m->in(k)->as_MergeMem()->memory_at(j));
2470                 }
2471                 mm->set_memory_at(j, phi);
2472               }
2473               Node* base_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2474               igvn.register_new_node_with_optimizer(base_phi);
2475               for (uint k = 1; k < m->req(); k++) {
2476                 base_phi->init_req(k, m->in(k)->as_MergeMem()->base_memory());
2477               }
2478               mm->set_base_memory(base_phi);
2479             }
2480           } else {
2481             // This is a MemBarCPUOrder node from
2482             // Parse::array_load()/Parse::array_store(), in the
2483             // branch that handles flat arrays hidden under
2484             // an Object[] array. We also need one new membar per
2485             // new alias to keep the unknown access that the
2486             // membars protect properly ordered with accesses to
2487             // known flat array.
2488             assert(m->is_Proj(), "projection expected");
2489             Node* ctrl = m->in(0)->in(TypeFunc::Control);
2490             igvn.replace_input_of(m->in(0), TypeFunc::Control, top());
2491             for (int j = start_alias; j < num_alias_types(); j++) {
2492               const TypePtr* adr_type = get_adr_type(j);
2493               if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2494                 continue;
2495               }
2496               MemBarNode* mb = new MemBarCPUOrderNode(this, j, nullptr);
2497               igvn.register_new_node_with_optimizer(mb);
2498               Node* mem = mm->memory_at(j);
2499               mb->init_req(TypeFunc::Control, ctrl);
2500               mb->init_req(TypeFunc::Memory, mem);
2501               ctrl = new ProjNode(mb, TypeFunc::Control);
2502               igvn.register_new_node_with_optimizer(ctrl);
2503               mem = new ProjNode(mb, TypeFunc::Memory);
2504               igvn.register_new_node_with_optimizer(mem);
2505               mm->set_memory_at(j, mem);
2506             }
2507             igvn.replace_node(m->in(0)->as_Multi()->proj_out(TypeFunc::Control), ctrl);
2508           }
2509           if (idx < m->req()-1) {
2510             idx += 1;
2511             stack.set_index(idx);
2512             n = m->in(idx);
2513             break;
2514           }
2515           // Take care of place holder nodes
2516           if (m->has_out_with(Op_Node)) {
2517             Node* place_holder = m->find_out_with(Op_Node);
2518             if (place_holder != nullptr) {
2519               Node* mm_clone = mm->clone();
2520               igvn.register_new_node_with_optimizer(mm_clone);
2521               Node* hook = new Node(1);
2522               hook->init_req(0, mm);
2523               igvn.replace_node(place_holder, mm_clone);
2524               hook->destruct(&igvn);
2525             }
2526             assert(!m->has_out_with(Op_Node), "place holder should be gone now");
2527           }
2528           stack.pop();
2529         }
2530       }
2531     } while(stack.size() > 0);
2532     // Fix the memory state at the MergeMem we started from
2533     igvn.rehash_node_delayed(current);
2534     for (int j = start_alias; j < num_alias_types(); j++) {
2535       const TypePtr* adr_type = get_adr_type(j);
2536       if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2537         continue;
2538       }
2539       current->set_memory_at(j, mm);
2540     }
2541     current->set_memory_at(index, current->base_memory());
2542   }
2543   igvn.optimize();
2544 
2545 #ifdef ASSERT
2546   wq.clear();
2547   wq.push(root());
2548   for (uint i = 0; i < wq.size(); i++) {
2549     Node* n = wq.at(i);
2550     assert(n->adr_type() != TypeAryPtr::INLINES, "should have been removed from the graph");
2551     for (uint j = 0; j < n->req(); j++) {
2552       Node* m = n->in(j);
2553       if (m != nullptr) {
2554         wq.push(m);
2555       }
2556     }
2557   }
2558 #endif
2559 
2560   print_method(PHASE_SPLIT_INLINES_ARRAY, 2);
2561 }
2562 
2563 void Compile::record_for_merge_stores_igvn(Node* n) {
2564   if (!n->for_merge_stores_igvn()) {
2565     assert(!_for_merge_stores_igvn.contains(n), "duplicate");
2566     n->add_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2567     _for_merge_stores_igvn.append(n);
2568   }
2569 }
2570 
2571 void Compile::remove_from_merge_stores_igvn(Node* n) {
2572   n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2573   _for_merge_stores_igvn.remove(n);
2574 }
2575 
2576 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
2577 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
2578 // the stores, and we merge the wrong sequence of stores.
2579 // Example:
2580 //   StoreI RangeCheck StoreI StoreI RangeCheck StoreI
2581 // Apply MergeStores:
2582 //   StoreI RangeCheck [   StoreL  ] RangeCheck StoreI

2661       assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
2662       Bytecodes::Code c = iter.cur_bc();
2663       Node* lhs = nullptr;
2664       Node* rhs = nullptr;
2665       if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
2666         lhs = unc->peek_operand(0);
2667         rhs = unc->peek_operand(1);
2668       } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
2669         lhs = unc->peek_operand(0);
2670       }
2671 
2672       ResourceMark rm;
2673       const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
2674       assert(live_locals.is_valid(), "broken liveness info");
2675       int len = (int)live_locals.size();
2676 
2677       for (int i = 0; i < len; i++) {
2678         Node* local = unc->local(jvms, i);
2679         // kill local using the liveness of next_bci.
2680         // give up when the local looks like an operand to secure reexecution.
2681         if (!live_locals.at(i) && !local->is_top() && local != lhs && local != rhs) {
2682           uint idx = jvms->locoff() + i;
2683 #ifdef ASSERT
2684           if (PrintOpto && Verbose) {
2685             tty->print("[unstable_if] kill local#%d: ", idx);
2686             local->dump();
2687             tty->cr();
2688           }
2689 #endif
2690           igvn.replace_input_of(unc, idx, top());
2691           modified = true;
2692         }
2693       }
2694     }
2695 
2696     // keep the modified trap for late query
2697     if (modified) {
2698       trap->set_modified();
2699     } else {
2700       _unstable_if_traps.delete_at(i);
2701     }
2702   }
2703   igvn.optimize();
2704 }
2705 
2706 // StringOpts and late inlining of string methods
2707 void Compile::inline_string_calls(bool parse_time) {
2708   {
2709     // remove useless nodes to make the usage analysis simpler
2710     ResourceMark rm;
2711     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2712   }
2713 
2714   {
2715     ResourceMark rm;
2716     print_method(PHASE_BEFORE_STRINGOPTS, 3);

2908 
2909   if (_string_late_inlines.length() > 0) {
2910     assert(has_stringbuilder(), "inconsistent");
2911 
2912     inline_string_calls(false);
2913 
2914     if (failing())  return;
2915 
2916     inline_incrementally_cleanup(igvn);
2917   }
2918 
2919   set_inlining_incrementally(false);
2920 }
2921 
2922 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2923   // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2924   // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2925   // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2926   // as if "inlining_incrementally() == true" were set.
2927   assert(inlining_incrementally() == false, "not allowed");
2928   set_strength_reduction(true);
2929 #ifdef ASSERT
2930   Unique_Node_List* modified_nodes = _modified_nodes;
2931   _modified_nodes = nullptr;
2932 #endif
2933   assert(_late_inlines.length() > 0, "sanity");
2934 
2935   if (StressIncrementalInlining) {
2936     shuffle_late_inlines();
2937   }
2938 
2939   while (_late_inlines.length() > 0) {
2940     igvn_worklist()->ensure_empty(); // should be done with igvn
2941 
2942     while (inline_incrementally_one()) {
2943       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2944     }
2945     if (failing())  return;
2946 
2947     inline_incrementally_cleanup(igvn);
2948   }
2949   DEBUG_ONLY( _modified_nodes = modified_nodes; )
2950   set_strength_reduction(false);
2951 }
2952 
2953 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2954   if (_loop_opts_cnt > 0) {
2955     while (major_progress() && (_loop_opts_cnt > 0)) {
2956       TracePhase tp(_t_idealLoop);
2957       PhaseIdealLoop::optimize(igvn, mode);
2958       _loop_opts_cnt--;
2959       if (failing())  return false;
2960       if (major_progress()) {
2961         print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2962       }
2963     }
2964   }
2965   return true;
2966 }
2967 
2968 // Remove edges from "root" to each SafePoint at a backward branch.
2969 // They were inserted during parsing (see add_safepoint()) to make
2970 // infinite loops without calls or exceptions visible to root, i.e.,

3076     print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
3077   }
3078   assert(!has_vbox_nodes(), "sanity");
3079 
3080   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
3081     Compile::TracePhase tp(_t_renumberLive);
3082     igvn_worklist()->ensure_empty(); // should be done with igvn
3083     {
3084       ResourceMark rm;
3085       PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
3086     }
3087     igvn.reset();
3088     igvn.optimize(true);
3089     if (failing()) return;
3090   }
3091 
3092   // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
3093   // safepoints
3094   remove_root_to_sfpts_edges(igvn);
3095 
3096   // Process inline type nodes now that all inlining is over
3097   process_inline_types(igvn);
3098 
3099   adjust_flat_array_access_aliases(igvn);
3100 
3101   if (failing())  return;
3102 
3103   if (C->macro_count() > 0) {
3104     // Eliminate some macro nodes before EA to reduce analysis pressure
3105     PhaseMacroExpand mexp(igvn);
3106     mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
3107     if (failing()) {
3108       return;
3109     }
3110     igvn.set_delay_transform(false);
3111     print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3112   }
3113 
3114   _print_phase_loop_opts = has_loops();
3115   if (_print_phase_loop_opts) {
3116     print_method(PHASE_BEFORE_LOOP_OPTS, 2);
3117   }
3118 
3119   // Perform escape analysis
3120   if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
3121     if (has_loops()) {
3122       // Cleanup graph (remove dead nodes).
3123       TracePhase tp(_t_idealLoop);
3124       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
3125       if (failing()) {
3126         return;
3127       }
3128       print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
3129       if (C->macro_count() > 0) {
3130         // Eliminate some macro nodes before EA to reduce analysis pressure
3131         PhaseMacroExpand mexp(igvn);
3132         mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
3133         if (failing()) {
3134           return;
3135         }
3136         igvn.set_delay_transform(false);
3137         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3138       }
3139     }
3140 
3141     bool progress;

3142     do {
3143       ConnectionGraph::do_analysis(this, &igvn);
3144 
3145       if (failing())  return;
3146 
3147       int mcount = macro_count(); // Record number of allocations and locks before IGVN
3148 
3149       // Optimize out fields loads from scalar replaceable allocations.
3150       igvn.optimize(true);
3151       print_method(PHASE_ITER_GVN_AFTER_EA, 2);
3152 
3153       if (failing()) return;
3154 
3155       if (congraph() != nullptr && macro_count() > 0) {
3156         TracePhase tp(_t_macroEliminate);
3157         PhaseMacroExpand mexp(igvn);
3158         mexp.eliminate_macro_nodes();
3159         if (failing()) {
3160           return;
3161         }
3162         print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3163 
3164         igvn.set_delay_transform(false);



3165         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3166       }
3167 
3168       ConnectionGraph::verify_ram_nodes(this, root());
3169       if (failing())  return;
3170 
3171       progress = do_iterative_escape_analysis() &&
3172                  (macro_count() < mcount) &&
3173                  ConnectionGraph::has_candidates(this);
3174       // Try again if candidates exist and made progress
3175       // by removing some allocations and/or locks.
3176     } while (progress);
3177   }
3178 
3179   process_flat_accesses(igvn);
3180   if (failing()) {
3181     return;
3182   }
3183 
3184   // Loop transforms on the ideal graph.  Range Check Elimination,
3185   // peeling, unrolling, etc.
3186 
3187   // Set loop opts counter
3188   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
3189     {
3190       TracePhase tp(_t_idealLoop);
3191       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
3192       _loop_opts_cnt--;
3193       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
3194       if (failing())  return;
3195     }
3196     // Loop opts pass if partial peeling occurred in previous pass
3197     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
3198       TracePhase tp(_t_idealLoop);
3199       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
3200       _loop_opts_cnt--;
3201       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
3202       if (failing())  return;
3203     }

3251 
3252   // Once loop optimizations are over, it is safe to get rid of all reachability fence nodes and
3253   // migrate reachability edges to safepoints.
3254   if (OptimizeReachabilityFences && _reachability_fences.length() > 0) {
3255     TracePhase tp1(_t_idealLoop);
3256     TracePhase tp2(_t_reachability);
3257     PhaseIdealLoop::optimize(igvn, PostLoopOptsExpandReachabilityFences);
3258     print_method(PHASE_EXPAND_REACHABILITY_FENCES, 2);
3259     if (failing())  return;
3260     assert(_reachability_fences.length() == 0 || PreserveReachabilityFencesOnConstants, "no RF nodes allowed");
3261   }
3262 
3263   process_for_merge_stores_igvn(igvn);
3264 
3265   if (failing())  return;
3266 
3267 #ifdef ASSERT
3268   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
3269 #endif
3270 
3271   if (_late_inlines.length() > 0) {
3272     // More opportunities to optimize virtual and MH calls.
3273     // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
3274     process_late_inline_calls_no_inline(igvn);
3275     if (failing()) {
3276       return;
3277     }
3278     process_inline_types(igvn);
3279   }
3280   assert(_late_inlines.length() == 0, "late inline queue must be drained");
3281 
3282   {
3283     TracePhase tp(_t_macroExpand);
3284     PhaseMacroExpand mex(igvn);
3285     // Last attempt to eliminate macro nodes.
3286     mex.eliminate_macro_nodes();
3287     if (failing()) {
3288       return;
3289     }
3290 
3291     print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);

3292     // Do not allow new macro nodes once we start to eliminate and expand
3293     C->reset_allow_macro_nodes();
3294     // Last attempt to eliminate macro nodes before expand
3295     mex.eliminate_macro_nodes();
3296     if (failing()) {
3297       return;
3298     }
3299     mex.eliminate_opaque_looplimit_macro_nodes();
3300     if (failing()) {
3301       return;
3302     }
3303     print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3304     if (mex.expand_macro_nodes()) {
3305       assert(failing(), "must bail out w/ explicit message");
3306       return;
3307     }
3308     print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
3309   }
3310 
3311   // Process inline type nodes again and remove them. From here
3312   // on we don't need to keep track of field values anymore.
3313   process_inline_types(igvn, /* remove= */ true);
3314 
3315   {
3316     TracePhase tp(_t_barrierExpand);
3317     if (bs->expand_barriers(this, igvn)) {
3318       assert(failing(), "must bail out w/ explicit message");
3319       return;
3320     }
3321     print_method(PHASE_BARRIER_EXPANSION, 2);
3322   }
3323 
3324   if (C->max_vector_size() > 0) {
3325     C->optimize_logic_cones(igvn);
3326     igvn.optimize();
3327     if (failing()) return;
3328   }
3329 
3330   DEBUG_ONLY( _modified_nodes = nullptr; )
3331   DEBUG_ONLY( _late_inlines.clear(); )
3332 
3333   assert(igvn._worklist.size() == 0, "not empty");








3334  } // (End scope of igvn; run destructor if necessary for asserts.)
3335 
3336  check_no_dead_use();
3337 
3338  // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
3339  // to remove hashes to unlock nodes for modifications.
3340  C->node_hash()->clear();
3341 
3342  // A method with only infinite loops has no edges entering loops from root
3343  {
3344    TracePhase tp(_t_graphReshaping);
3345    if (final_graph_reshaping()) {
3346      assert(failing(), "must bail out w/ explicit message");
3347      return;
3348    }
3349  }
3350 
3351  print_method(PHASE_OPTIMIZE_FINISHED, 2);
3352  DEBUG_ONLY(set_phase_optimize_finished();)
3353 }

4012     n->subsume_by(sub, this);
4013   }
4014 }
4015 
4016 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
4017   switch( nop ) {
4018   case Op_Opaque1:              // Remove Opaque Nodes before matching
4019     n->subsume_by(n->in(1), this);
4020     break;
4021   case Op_CallLeafPure: {
4022     // If the pure call is not supported, then lower to a CallLeaf.
4023     if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
4024       CallNode* call = n->as_Call();
4025       CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
4026                                             call->_name, TypeRawPtr::BOTTOM);
4027       new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
4028       new_call->init_req(TypeFunc::I_O, C->top());
4029       new_call->init_req(TypeFunc::Memory, C->top());
4030       new_call->init_req(TypeFunc::ReturnAdr, C->top());
4031       new_call->init_req(TypeFunc::FramePtr, C->top());
4032       for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain_sig()->cnt(); i++) {
4033         new_call->init_req(i, call->in(i));
4034       }
4035       n->subsume_by(new_call, this);
4036     }
4037     break;
4038   }
4039   case Op_CallStaticJava:
4040   case Op_CallJava:
4041   case Op_CallDynamicJava:
4042     frc.inc_java_call_count(); // Count java call site;
4043   case Op_CallRuntime:
4044   case Op_CallLeaf:
4045   case Op_CallLeafVector:
4046   case Op_CallLeafNoFP: {
4047     assert (n->is_Call(), "");
4048     CallNode *call = n->as_Call();
4049     // See if uncommon argument is shared
4050     if (call->is_CallStaticJava() && call->as_CallStaticJava()->_name) {
4051       Node *n = call->in(TypeFunc::Parms);
4052       int nop = n->Opcode();

4059           nop != Op_DecodeNKlass &&
4060           !n->is_Mem() &&
4061           !n->is_Phi()) {
4062         Node *x = n->clone();
4063         call->set_req(TypeFunc::Parms, x);
4064       }
4065     }
4066     break;
4067   }
4068 
4069   // Mem nodes need explicit cases to satisfy assert(!n->is_Mem()) in default.
4070   case Op_StoreF:
4071   case Op_LoadF:
4072   case Op_StoreD:
4073   case Op_LoadD:
4074   case Op_LoadD_unaligned:
4075   case Op_StoreB:
4076   case Op_StoreC:
4077   case Op_StoreI:
4078   case Op_StoreL:
4079   case Op_StoreLSpecial:
4080   case Op_CompareAndSwapB:
4081   case Op_CompareAndSwapS:
4082   case Op_CompareAndSwapI:
4083   case Op_CompareAndSwapL:
4084   case Op_CompareAndSwapP:
4085   case Op_CompareAndSwapN:
4086   case Op_WeakCompareAndSwapB:
4087   case Op_WeakCompareAndSwapS:
4088   case Op_WeakCompareAndSwapI:
4089   case Op_WeakCompareAndSwapL:
4090   case Op_WeakCompareAndSwapP:
4091   case Op_WeakCompareAndSwapN:
4092   case Op_CompareAndExchangeB:
4093   case Op_CompareAndExchangeS:
4094   case Op_CompareAndExchangeI:
4095   case Op_CompareAndExchangeL:
4096   case Op_CompareAndExchangeP:
4097   case Op_CompareAndExchangeN:
4098   case Op_GetAndAddS:
4099   case Op_GetAndAddB:

4591           k->subsume_by(m, this);
4592         }
4593       }
4594     }
4595     break;
4596   }
4597   case Op_CmpUL: {
4598     if (!Matcher::has_match_rule(Op_CmpUL)) {
4599       // No support for unsigned long comparisons
4600       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
4601       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
4602       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
4603       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
4604       Node* andl = new AndLNode(orl, remove_sign_mask);
4605       Node* cmp = new CmpLNode(andl, n->in(2));
4606       n->subsume_by(cmp, this);
4607     }
4608     break;
4609   }
4610 #ifdef ASSERT
4611   case Op_InlineType: {
4612     n->dump(-1);
4613     assert(false, "inline type node was not removed");
4614     break;
4615   }
4616   case Op_ConNKlass: {
4617     const TypePtr* tp = n->as_Type()->type()->make_ptr();
4618     ciKlass* klass = tp->is_klassptr()->exact_klass();
4619     assert(klass->is_in_encoding_range(), "klass cannot be compressed");
4620     break;
4621   }
4622 #endif
4623   default:
4624     assert(!n->is_Call(), "");
4625     assert(!n->is_Mem(), "");
4626     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
4627     break;
4628   }
4629 }
4630 
4631 //------------------------------final_graph_reshaping_walk---------------------
4632 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
4633 // requires that the walk visits a node's inputs before visiting the node.
4634 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
4635   Unique_Node_List sfpt;

4968   }
4969 }
4970 
4971 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4972   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4973 }
4974 
4975 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4976   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4977 }
4978 
4979 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4980   if (holder->is_initialized()) {
4981     return false;
4982   }
4983   if (holder->is_being_initialized()) {
4984     if (accessing_method->holder() == holder) {
4985       // Access inside a class. The barrier can be elided when access happens in <clinit>,
4986       // <init>, or a static method. In all those cases, there was an initialization
4987       // barrier on the holder klass passed.
4988       if (accessing_method->is_class_initializer() ||
4989           accessing_method->is_object_constructor() ||
4990           accessing_method->is_static()) {
4991         return false;
4992       }
4993     } else if (accessing_method->holder()->is_subclass_of(holder)) {
4994       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4995       // In case of <init> or a static method, the barrier is on the subclass is not enough:
4996       // child class can become fully initialized while its parent class is still being initialized.
4997       if (accessing_method->is_class_initializer()) {
4998         return false;
4999       }
5000     }
5001     ciMethod* root = method(); // the root method of compilation
5002     if (root != accessing_method) {
5003       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
5004     }
5005   }
5006   return true;
5007 }
5008 
5009 #ifndef PRODUCT
5010 //------------------------------verify_bidirectional_edges---------------------
5011 // For each input edge to a node (ie - for each Use-Def edge), verify that
5012 // there is a corresponding Def-Use edge.
5013 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
5014   // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
5015   uint stack_size = live_nodes() >> 4;
5016   Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
5017   if (root_and_safepoints != nullptr) {

5047       if (in != nullptr && !in->is_top()) {
5048         // Count instances of `next`
5049         int cnt = 0;
5050         for (uint idx = 0; idx < in->_outcnt; idx++) {
5051           if (in->_out[idx] == n) {
5052             cnt++;
5053           }
5054         }
5055         assert(cnt > 0, "Failed to find Def-Use edge.");
5056         // Check for duplicate edges
5057         // walk the input array downcounting the input edges to n
5058         for (uint j = 0; j < length; j++) {
5059           if (n->in(j) == in) {
5060             cnt--;
5061           }
5062         }
5063         assert(cnt == 0, "Mismatched edge count.");
5064       } else if (in == nullptr) {
5065         assert(i == 0 || i >= n->req() ||
5066                n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
5067                (n->is_Allocate() && i >= AllocateNode::InlineType) ||
5068                (n->is_Unlock() && i == (n->req() - 1)) ||
5069                (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
5070               "only region, phi, arraycopy, allocate, unlock or membar nodes have null data edges");
5071       } else {
5072         assert(in->is_top(), "sanity");
5073         // Nothing to check.
5074       }
5075     }
5076   }
5077 }
5078 
5079 //------------------------------verify_graph_edges---------------------------
5080 // Walk the Graph and verify that there is a one-to-one correspondence
5081 // between Use-Def edges and Def-Use edges in the graph.
5082 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
5083   if (VerifyGraphEdges) {
5084     Unique_Node_List visited;
5085 
5086     // Call graph walk to check edges
5087     verify_bidirectional_edges(visited, root_and_safepoints);
5088     if (no_dead_code) {
5089       // Now make sure that no visited node is used by an unvisited node.
5090       bool dead_nodes = false;

5201 // (1) subklass is already limited to a subtype of superklass => always ok
5202 // (2) subklass does not overlap with superklass => always fail
5203 // (3) superklass has NO subtypes and we can check with a simple compare.
5204 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
5205   if (skip) {
5206     return SSC_full_test;       // Let caller generate the general case.
5207   }
5208 
5209   if (subk->is_java_subtype_of(superk)) {
5210     return SSC_always_true; // (0) and (1)  this test cannot fail
5211   }
5212 
5213   if (!subk->maybe_java_subtype_of(superk)) {
5214     return SSC_always_false; // (2) true path dead; no dynamic test needed
5215   }
5216 
5217   const Type* superelem = superk;
5218   if (superk->isa_aryklassptr()) {
5219     int ignored;
5220     superelem = superk->is_aryklassptr()->base_element_type(ignored);
5221 
5222     // Do not fold the subtype check to an array klass pointer comparison for null-able inline type arrays
5223     // because null-free [LMyValue <: null-able [LMyValue but the klasses are different. Perform a full test.
5224     if (!superk->is_aryklassptr()->is_null_free() && superk->is_aryklassptr()->elem()->isa_instklassptr() &&
5225         superk->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->is_inlinetype()) {
5226       return SSC_full_test;
5227     }
5228   }
5229 
5230   if (superelem->isa_instklassptr()) {
5231     ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
5232     if (!ik->has_subklass()) {
5233       if (!ik->is_final()) {
5234         // Add a dependency if there is a chance of a later subclass.
5235         dependencies()->assert_leaf_type(ik);
5236       }
5237       if (!superk->maybe_java_subtype_of(subk)) {
5238         return SSC_always_false;
5239       }
5240       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
5241     }
5242   } else {
5243     // A primitive array type has no subtypes.
5244     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
5245   }
5246 
5247   return SSC_full_test;

6040   } else {
6041     _debug_network_printer->update_compiled_method(C->method());
6042   }
6043   tty->print_cr("Method printed over network stream to IGV");
6044   _debug_network_printer->print(name, C->root(), visible_nodes, fr);
6045 }
6046 #endif // !PRODUCT
6047 
6048 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
6049   if (type != nullptr && phase->type(value)->higher_equal(type)) {
6050     return value;
6051   }
6052   Node* result = nullptr;
6053   if (bt == T_BYTE) {
6054     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
6055     result = new RShiftINode(result, phase->intcon(24));
6056   } else if (bt == T_BOOLEAN) {
6057     result = new AndINode(value, phase->intcon(0xFF));
6058   } else if (bt == T_CHAR) {
6059     result = new AndINode(value,phase->intcon(0xFFFF));
6060   } else if (bt == T_FLOAT) {
6061     result = new MoveI2FNode(value);
6062   } else {
6063     assert(bt == T_SHORT, "unexpected narrow type");
6064     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
6065     result = new RShiftINode(result, phase->intcon(16));
6066   }
6067   if (transform_res) {
6068     result = phase->transform(result);
6069   }
6070   return result;
6071 }
6072 
6073 void Compile::record_method_not_compilable_oom() {
6074   record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
6075 }
6076 
6077 #ifndef PRODUCT
6078 // Collects all the control inputs from nodes on the worklist and from their data dependencies
6079 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
6080   // Follow non-control edges until we reach CFG nodes
6081   for (uint i = 0; i < worklist.size(); i++) {
< prev index next >