1 /*
   2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   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 #ifndef SHARE_OPTO_COMPILE_HPP
  26 #define SHARE_OPTO_COMPILE_HPP
  27 
  28 #include "asm/codeBuffer.hpp"
  29 #include "ci/compilerInterface.hpp"
  30 #include "code/debugInfoRec.hpp"
  31 #include "compiler/compiler_globals.hpp"
  32 #include "compiler/compilerOracle.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/compilerEvent.hpp"
  35 #include "libadt/dict.hpp"
  36 #include "libadt/vectset.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "opto/idealGraphPrinter.hpp"
  40 #include "opto/phasetype.hpp"
  41 #include "opto/phase.hpp"
  42 #include "opto/regmask.hpp"
  43 #include "runtime/deoptimization.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/timerTrace.hpp"
  46 #include "runtime/vmThread.hpp"
  47 #include "utilities/ticks.hpp"
  48 
  49 class AbstractLockNode;
  50 class AddPNode;
  51 class Block;
  52 class Bundle;
  53 class CallGenerator;
  54 class CallNode;
  55 class CallStaticJavaNode;
  56 class CloneMap;
  57 class ConnectionGraph;
  58 class IdealGraphPrinter;
  59 class InlineTree;
  60 class Matcher;
  61 class MachConstantNode;
  62 class MachConstantBaseNode;
  63 class MachNode;
  64 class MachOper;
  65 class MachSafePointNode;
  66 class Node;
  67 class Node_Array;
  68 class Node_List;
  69 class Node_Notes;
  70 class NodeCloneInfo;
  71 class OptoReg;
  72 class PhaseCFG;
  73 class PhaseGVN;
  74 class PhaseIterGVN;
  75 class PhaseRegAlloc;
  76 class PhaseCCP;
  77 class PhaseOutput;
  78 class RootNode;
  79 class relocInfo;
  80 class StartNode;
  81 class SafePointNode;
  82 class JVMState;
  83 class Type;
  84 class TypeInt;
  85 class TypeInteger;
  86 class TypeKlassPtr;
  87 class TypePtr;
  88 class TypeOopPtr;
  89 class TypeFunc;
  90 class TypeVect;
  91 class Unique_Node_List;
  92 class UnstableIfTrap;
  93 class InlineTypeNode;
  94 class nmethod;
  95 class Node_Stack;
  96 struct Final_Reshape_Counts;
  97 class VerifyMeetResult;
  98 
  99 enum LoopOptsMode {
 100   LoopOptsDefault,
 101   LoopOptsNone,
 102   LoopOptsMaxUnroll,
 103   LoopOptsShenandoahExpand,
 104   LoopOptsShenandoahPostExpand,
 105   LoopOptsSkipSplitIf,
 106   LoopOptsVerify
 107 };
 108 
 109 // The type of all node counts and indexes.
 110 // It must hold at least 16 bits, but must also be fast to load and store.
 111 // This type, if less than 32 bits, could limit the number of possible nodes.
 112 // (To make this type platform-specific, move to globalDefinitions_xxx.hpp.)
 113 typedef unsigned int node_idx_t;
 114 
 115 class NodeCloneInfo {
 116  private:
 117   uint64_t _idx_clone_orig;
 118  public:
 119 
 120   void set_idx(node_idx_t idx) {
 121     _idx_clone_orig = (_idx_clone_orig & CONST64(0xFFFFFFFF00000000)) | idx;
 122   }
 123   node_idx_t idx() const { return (node_idx_t)(_idx_clone_orig & 0xFFFFFFFF); }
 124 
 125   void set_gen(int generation) {
 126     uint64_t g = (uint64_t)generation << 32;
 127     _idx_clone_orig = (_idx_clone_orig & 0xFFFFFFFF) | g;
 128   }
 129   int gen() const { return (int)(_idx_clone_orig >> 32); }
 130 
 131   void set(uint64_t x) { _idx_clone_orig = x; }
 132   void set(node_idx_t x, int g) { set_idx(x); set_gen(g); }
 133   uint64_t get() const { return _idx_clone_orig; }
 134 
 135   NodeCloneInfo(uint64_t idx_clone_orig) : _idx_clone_orig(idx_clone_orig) {}
 136   NodeCloneInfo(node_idx_t x, int g) : _idx_clone_orig(0) { set(x, g); }
 137 
 138   void dump() const;
 139 };
 140 
 141 class CloneMap {
 142   friend class Compile;
 143  private:
 144   bool      _debug;
 145   Dict*     _dict;
 146   int       _clone_idx;   // current cloning iteration/generation in loop unroll
 147  public:
 148   void*     _2p(node_idx_t key)   const          { return (void*)(intptr_t)key; } // 2 conversion functions to make gcc happy
 149   node_idx_t _2_node_idx_t(const void* k) const  { return (node_idx_t)(intptr_t)k; }
 150   Dict*     dict()                const          { return _dict; }
 151   void insert(node_idx_t key, uint64_t val)      { assert(_dict->operator[](_2p(key)) == nullptr, "key existed"); _dict->Insert(_2p(key), (void*)val); }
 152   void insert(node_idx_t key, NodeCloneInfo& ci) { insert(key, ci.get()); }
 153   void remove(node_idx_t key)                    { _dict->Delete(_2p(key)); }
 154   uint64_t value(node_idx_t key)  const          { return (uint64_t)_dict->operator[](_2p(key)); }
 155   node_idx_t idx(node_idx_t key)  const          { return NodeCloneInfo(value(key)).idx(); }
 156   int gen(node_idx_t key)         const          { return NodeCloneInfo(value(key)).gen(); }
 157   int gen(const void* k)          const          { return gen(_2_node_idx_t(k)); }
 158   int max_gen()                   const;
 159   void clone(Node* old, Node* nnn, int gen);
 160   void verify_insert_and_clone(Node* old, Node* nnn, int gen);
 161   void dump(node_idx_t key)       const;
 162 
 163   int  clone_idx() const                         { return _clone_idx; }
 164   void set_clone_idx(int x)                      { _clone_idx = x; }
 165   bool is_debug()                 const          { return _debug; }
 166   void set_debug(bool debug)                     { _debug = debug; }
 167 
 168   bool same_idx(node_idx_t k1, node_idx_t k2)  const { return idx(k1) == idx(k2); }
 169   bool same_gen(node_idx_t k1, node_idx_t k2)  const { return gen(k1) == gen(k2); }
 170 };
 171 
 172 class Options {
 173   friend class Compile;
 174   friend class VMStructs;
 175  private:
 176   const bool _subsume_loads;         // Load can be matched as part of a larger op.
 177   const bool _do_escape_analysis;    // Do escape analysis.
 178   const bool _do_iterative_escape_analysis;  // Do iterative escape analysis.
 179   const bool _eliminate_boxing;      // Do boxing elimination.
 180   const bool _do_locks_coarsening;   // Do locks coarsening
 181   const bool _install_code;          // Install the code that was compiled
 182  public:
 183   Options(bool subsume_loads, bool do_escape_analysis,
 184           bool do_iterative_escape_analysis,
 185           bool eliminate_boxing, bool do_locks_coarsening,
 186           bool install_code) :
 187           _subsume_loads(subsume_loads),
 188           _do_escape_analysis(do_escape_analysis),
 189           _do_iterative_escape_analysis(do_iterative_escape_analysis),
 190           _eliminate_boxing(eliminate_boxing),
 191           _do_locks_coarsening(do_locks_coarsening),
 192           _install_code(install_code) {
 193   }
 194 
 195   static Options for_runtime_stub() {
 196     return Options(
 197        /* subsume_loads = */ true,
 198        /* do_escape_analysis = */ false,
 199        /* do_iterative_escape_analysis = */ false,
 200        /* eliminate_boxing = */ false,
 201        /* do_lock_coarsening = */ false,
 202        /* install_code = */ true
 203     );
 204   }
 205 };
 206 
 207 //------------------------------Compile----------------------------------------
 208 // This class defines a top-level Compiler invocation.
 209 
 210 class Compile : public Phase {
 211   friend class VMStructs;
 212 
 213  public:
 214   // Fixed alias indexes.  (See also MergeMemNode.)
 215   enum {
 216     AliasIdxTop = 1,  // pseudo-index, aliases to nothing (used as sentinel value)
 217     AliasIdxBot = 2,  // pseudo-index, aliases to everything
 218     AliasIdxRaw = 3   // hard-wired index for TypeRawPtr::BOTTOM
 219   };
 220 
 221   // Variant of TraceTime(nullptr, &_t_accumulator, CITime);
 222   // Integrated with logging.  If logging is turned on, and CITimeVerbose is true,
 223   // then brackets are put into the log, with time stamps and node counts.
 224   // (The time collection itself is always conditionalized on CITime.)
 225   class TracePhase : public TraceTime {
 226    private:
 227     Compile*    C;
 228     CompileLog* _log;
 229     const char* _phase_name;
 230     bool _dolog;
 231    public:
 232     TracePhase(const char* name, elapsedTimer* accumulator);
 233     ~TracePhase();
 234   };
 235 
 236   // Information per category of alias (memory slice)
 237   class AliasType {
 238    private:
 239     friend class Compile;
 240 
 241     int             _index;         // unique index, used with MergeMemNode
 242     const TypePtr*  _adr_type;      // normalized address type
 243     ciField*        _field;         // relevant instance field, or null if none
 244     const Type*     _element;       // relevant array element type, or null if none
 245     bool            _is_rewritable; // false if the memory is write-once only
 246     int             _general_index; // if this is type is an instance, the general
 247                                     // type that this is an instance of
 248 
 249     void Init(int i, const TypePtr* at);
 250 
 251    public:
 252     int             index()         const { return _index; }
 253     const TypePtr*  adr_type()      const { return _adr_type; }
 254     ciField*        field()         const { return _field; }
 255     const Type*     element()       const { return _element; }
 256     bool            is_rewritable() const { return _is_rewritable; }
 257     bool            is_volatile()   const { return (_field ? _field->is_volatile() : false); }
 258     int             general_index() const { return (_general_index != 0) ? _general_index : _index; }
 259 
 260     void set_rewritable(bool z) { _is_rewritable = z; }
 261     void set_field(ciField* f) {
 262       assert(!_field,"");
 263       _field = f;
 264       if (f->is_final() || f->is_stable()) {
 265         // In the case of @Stable, multiple writes are possible but may be assumed to be no-ops.
 266         _is_rewritable = false;
 267       }
 268     }
 269     void set_element(const Type* e) {
 270       assert(_element == nullptr, "");
 271       _element = e;
 272     }
 273 
 274     BasicType basic_type() const;
 275 
 276     void print_on(outputStream* st) PRODUCT_RETURN;
 277   };
 278 
 279   enum {
 280     logAliasCacheSize = 6,
 281     AliasCacheSize = (1<<logAliasCacheSize)
 282   };
 283   struct AliasCacheEntry { const TypePtr* _adr_type; int _index; };  // simple duple type
 284   enum {
 285     trapHistLength = MethodData::_trap_hist_limit
 286   };
 287 
 288  private:
 289   // Fixed parameters to this compilation.
 290   const int             _compile_id;
 291   const Options         _options;               // Compilation options
 292   ciMethod*             _method;                // The method being compiled.
 293   int                   _entry_bci;             // entry bci for osr methods.
 294   const TypeFunc*       _tf;                    // My kind of signature
 295   InlineTree*           _ilt;                   // Ditto (temporary).
 296   address               _stub_function;         // VM entry for stub being compiled, or null
 297   const char*           _stub_name;             // Name of stub or adapter being compiled, or null
 298   address               _stub_entry_point;      // Compile code entry for generated stub, or null
 299 
 300   // Control of this compilation.
 301   int                   _max_inline_size;       // Max inline size for this compilation
 302   int                   _freq_inline_size;      // Max hot method inline size for this compilation
 303   int                   _fixed_slots;           // count of frame slots not allocated by the register
 304                                                 // allocator i.e. locks, original deopt pc, etc.
 305   uintx                 _max_node_limit;        // Max unique node count during a single compilation.
 306 
 307   bool                  _post_loop_opts_phase;  // Loop opts are finished.
 308 
 309   int                   _major_progress;        // Count of something big happening
 310   bool                  _inlining_progress;     // progress doing incremental inlining?
 311   bool                  _inlining_incrementally;// Are we doing incremental inlining (post parse)
 312   bool                  _do_cleanup;            // Cleanup is needed before proceeding with incremental inlining
 313   bool                  _has_loops;             // True if the method _may_ have some loops
 314   bool                  _has_split_ifs;         // True if the method _may_ have some split-if
 315   bool                  _has_unsafe_access;     // True if the method _may_ produce faults in unsafe loads or stores.
 316   bool                  _has_stringbuilder;     // True StringBuffers or StringBuilders are allocated
 317   bool                  _has_boxed_value;       // True if a boxed object is allocated
 318   bool                  _has_reserved_stack_access; // True if the method or an inlined method is annotated with ReservedStackAccess
 319   bool                  _has_circular_inline_type; // True if method loads an inline type with a circular, non-flattened field
 320   uint                  _max_vector_size;       // Maximum size of generated vectors
 321   bool                  _clear_upper_avx;       // Clear upper bits of ymm registers using vzeroupper
 322   uint                  _trap_hist[trapHistLength];  // Cumulative traps
 323   bool                  _trap_can_recompile;    // Have we emitted a recompiling trap?
 324   uint                  _decompile_count;       // Cumulative decompilation counts.
 325   bool                  _do_inlining;           // True if we intend to do inlining
 326   bool                  _do_scheduling;         // True if we intend to do scheduling
 327   bool                  _do_freq_based_layout;  // True if we intend to do frequency based block layout
 328   bool                  _do_vector_loop;        // True if allowed to execute loop in parallel iterations
 329   bool                  _use_cmove;             // True if CMove should be used without profitability analysis
 330   bool                  _do_aliasing;           // True if we intend to do aliasing
 331   bool                  _print_assembly;        // True if we should dump assembly code for this compilation
 332   bool                  _print_inlining;        // True if we should print inlining for this compilation
 333   bool                  _print_intrinsics;      // True if we should print intrinsics for this compilation
 334 #ifndef PRODUCT
 335   uint                  _igv_idx;               // Counter for IGV node identifiers
 336   bool                  _trace_opto_output;
 337   bool                  _parsed_irreducible_loop; // True if ciTypeFlow detected irreducible loops during parsing
 338 #endif
 339   bool                  _has_irreducible_loop;  // Found irreducible loops
 340   // JSR 292
 341   bool                  _has_method_handle_invokes; // True if this method has MethodHandle invokes.
 342   bool                  _has_monitors;          // Metadata transfered to nmethod to enable Continuations lock-detection fastpath
 343   RTMState              _rtm_state;             // State of Restricted Transactional Memory usage
 344   int                   _loop_opts_cnt;         // loop opts round
 345   bool                  _clinit_barrier_on_entry; // True if clinit barrier is needed on nmethod entry
 346   bool                  _has_flattened_accesses; // Any known flattened array accesses?
 347   bool                  _flattened_accesses_share_alias; // Initially all flattened array share a single slice
 348   bool                  _scalarize_in_safepoints; // Scalarize inline types in safepoint debug info
 349   uint                  _stress_seed;           // Seed for stress testing
 350 
 351   // Compilation environment.
 352   Arena                 _comp_arena;            // Arena with lifetime equivalent to Compile
 353   void*                 _barrier_set_state;     // Potential GC barrier state for Compile
 354   ciEnv*                _env;                   // CI interface
 355   DirectiveSet*         _directive;             // Compiler directive
 356   CompileLog*           _log;                   // from CompilerThread
 357   const char*           _failure_reason;        // for record_failure/failing pattern
 358   GrowableArray<CallGenerator*> _intrinsics;    // List of intrinsics.
 359   GrowableArray<Node*>  _macro_nodes;           // List of nodes which need to be expanded before matching.
 360   GrowableArray<Node*>  _parse_predicate_opaqs; // List of Opaque1 nodes for the Parse Predicates.
 361   GrowableArray<Node*>  _template_assertion_predicate_opaqs; // List of Opaque4 nodes for Template Assertion Predicates.
 362   GrowableArray<Node*>  _expensive_nodes;       // List of nodes that are expensive to compute and that we'd better not let the GVN freely common
 363   GrowableArray<Node*>  _for_post_loop_igvn;    // List of nodes for IGVN after loop opts are over
 364   GrowableArray<Node*>  _inline_type_nodes;     // List of InlineType nodes
 365   GrowableArray<UnstableIfTrap*> _unstable_if_traps;        // List of ifnodes after IGVN
 366   GrowableArray<Node_List*> _coarsened_locks;   // List of coarsened Lock and Unlock nodes
 367   ConnectionGraph*      _congraph;
 368 #ifndef PRODUCT
 369   IdealGraphPrinter*    _igv_printer;
 370   static IdealGraphPrinter* _debug_file_printer;
 371   static IdealGraphPrinter* _debug_network_printer;
 372 #endif
 373 
 374 
 375   // Node management
 376   uint                  _unique;                // Counter for unique Node indices
 377   VectorSet             _dead_node_list;        // Set of dead nodes
 378   uint                  _dead_node_count;       // Number of dead nodes; VectorSet::Size() is O(N).
 379                                                 // So use this to keep count and make the call O(1).
 380   DEBUG_ONLY(Unique_Node_List* _modified_nodes;)   // List of nodes which inputs were modified
 381   DEBUG_ONLY(bool       _phase_optimize_finished;) // Used for live node verification while creating new nodes
 382 
 383   Arena                 _node_arena;            // Arena for new-space Nodes
 384   Arena                 _old_arena;             // Arena for old-space Nodes, lifetime during xform
 385   RootNode*             _root;                  // Unique root of compilation, or null after bail-out.
 386   Node*                 _top;                   // Unique top node.  (Reset by various phases.)
 387 
 388   Node*                 _immutable_memory;      // Initial memory state
 389 
 390   Node*                 _recent_alloc_obj;
 391   Node*                 _recent_alloc_ctl;
 392 
 393   // Constant table
 394   MachConstantBaseNode* _mach_constant_base_node;  // Constant table base node singleton.
 395 
 396 
 397   // Blocked array of debugging and profiling information,
 398   // tracked per node.
 399   enum { _log2_node_notes_block_size = 8,
 400          _node_notes_block_size = (1<<_log2_node_notes_block_size)
 401   };
 402   GrowableArray<Node_Notes*>* _node_note_array;
 403   Node_Notes*           _default_node_notes;  // default notes for new nodes
 404 
 405   // After parsing and every bulk phase we hang onto the Root instruction.
 406   // The RootNode instruction is where the whole program begins.  It produces
 407   // the initial Control and BOTTOM for everybody else.
 408 
 409   // Type management
 410   Arena                 _Compile_types;         // Arena for all types
 411   Arena*                _type_arena;            // Alias for _Compile_types except in Initialize_shared()
 412   Dict*                 _type_dict;             // Intern table
 413   CloneMap              _clone_map;             // used for recording history of cloned nodes
 414   size_t                _type_last_size;        // Last allocation size (see Type::operator new/delete)
 415   ciMethod*             _last_tf_m;             // Cache for
 416   const TypeFunc*       _last_tf;               //  TypeFunc::make
 417   AliasType**           _alias_types;           // List of alias types seen so far.
 418   int                   _num_alias_types;       // Logical length of _alias_types
 419   int                   _max_alias_types;       // Physical length of _alias_types
 420   AliasCacheEntry       _alias_cache[AliasCacheSize]; // Gets aliases w/o data structure walking
 421 
 422   // Parsing, optimization
 423   PhaseGVN*             _initial_gvn;           // Results of parse-time PhaseGVN
 424   Unique_Node_List*     _for_igvn;              // Initial work-list for next round of Iterative GVN
 425 
 426   GrowableArray<CallGenerator*> _late_inlines;        // List of CallGenerators to be revisited after main parsing has finished.
 427   GrowableArray<CallGenerator*> _string_late_inlines; // same but for string operations
 428   GrowableArray<CallGenerator*> _boxing_late_inlines; // same but for boxing operations
 429 
 430   GrowableArray<CallGenerator*> _vector_reboxing_late_inlines; // same but for vector reboxing operations
 431 
 432   int                           _late_inlines_pos;    // Where in the queue should the next late inlining candidate go (emulate depth first inlining)
 433   uint                          _number_of_mh_late_inlines; // number of method handle late inlining still pending
 434 
 435   // Inlining may not happen in parse order which would make
 436   // PrintInlining output confusing. Keep track of PrintInlining
 437   // pieces in order.
 438   class PrintInliningBuffer : public CHeapObj<mtCompiler> {
 439    private:
 440     CallGenerator* _cg;
 441     stringStream   _ss;
 442     static const size_t default_stream_buffer_size = 128;
 443 
 444    public:
 445     PrintInliningBuffer()
 446       : _cg(nullptr), _ss(default_stream_buffer_size) {}
 447 
 448     stringStream* ss()             { return &_ss; }
 449     CallGenerator* cg()            { return _cg; }
 450     void set_cg(CallGenerator* cg) { _cg = cg; }
 451   };
 452 
 453   stringStream* _print_inlining_stream;
 454   GrowableArray<PrintInliningBuffer*>* _print_inlining_list;
 455   int _print_inlining_idx;
 456   char* _print_inlining_output;
 457 
 458   // Only keep nodes in the expensive node list that need to be optimized
 459   void cleanup_expensive_nodes(PhaseIterGVN &igvn);
 460   // Use for sorting expensive nodes to bring similar nodes together
 461   static int cmp_expensive_nodes(Node** n1, Node** n2);
 462   // Expensive nodes list already sorted?
 463   bool expensive_nodes_sorted() const;
 464   // Remove the speculative part of types and clean up the graph
 465   void remove_speculative_types(PhaseIterGVN &igvn);
 466 
 467   void* _replay_inline_data; // Pointer to data loaded from file
 468 
 469   void print_inlining_init();
 470   void print_inlining_reinit();
 471   void print_inlining_commit();
 472   void print_inlining_push();
 473   PrintInliningBuffer* print_inlining_current();
 474 
 475   void log_late_inline_failure(CallGenerator* cg, const char* msg);
 476   DEBUG_ONLY(bool _exception_backedge;)
 477 
 478  public:
 479 
 480   void* barrier_set_state() const { return _barrier_set_state; }
 481 
 482   stringStream* print_inlining_stream() {
 483     assert(print_inlining() || print_intrinsics(), "PrintInlining off?");
 484     return _print_inlining_stream;
 485   }
 486 
 487   void print_inlining_update(CallGenerator* cg);
 488   void print_inlining_update_delayed(CallGenerator* cg);
 489   void print_inlining_move_to(CallGenerator* cg);
 490   void print_inlining_assert_ready();
 491   void print_inlining_reset();
 492 
 493   void print_inlining(ciMethod* method, int inline_level, int bci, const char* msg = nullptr) {
 494     stringStream ss;
 495     CompileTask::print_inlining_inner(&ss, method, inline_level, bci, msg);
 496     print_inlining_stream()->print("%s", ss.freeze());
 497   }
 498 
 499 #ifndef PRODUCT
 500   IdealGraphPrinter* igv_printer() { return _igv_printer; }
 501 #endif
 502 
 503   void log_late_inline(CallGenerator* cg);
 504   void log_inline_id(CallGenerator* cg);
 505   void log_inline_failure(const char* msg);
 506 
 507   void* replay_inline_data() const { return _replay_inline_data; }
 508 
 509   // Dump inlining replay data to the stream.
 510   void dump_inline_data(outputStream* out);
 511   void dump_inline_data_reduced(outputStream* out);
 512 
 513  private:
 514   // Matching, CFG layout, allocation, code generation
 515   PhaseCFG*             _cfg;                   // Results of CFG finding
 516   int                   _java_calls;            // Number of java calls in the method
 517   int                   _inner_loops;           // Number of inner loops in the method
 518   Matcher*              _matcher;               // Engine to map ideal to machine instructions
 519   PhaseRegAlloc*        _regalloc;              // Results of register allocation.
 520   RegMask               _FIRST_STACK_mask;      // All stack slots usable for spills (depends on frame layout)
 521   Arena*                _indexSet_arena;        // control IndexSet allocation within PhaseChaitin
 522   void*                 _indexSet_free_block_list; // free list of IndexSet bit blocks
 523   int                   _interpreter_frame_size;
 524 
 525   PhaseOutput*          _output;
 526 
 527  public:
 528   // Accessors
 529 
 530   // The Compile instance currently active in this (compiler) thread.
 531   static Compile* current() {
 532     return (Compile*) ciEnv::current()->compiler_data();
 533   }
 534 
 535   int interpreter_frame_size() const            { return _interpreter_frame_size; }
 536 
 537   PhaseOutput*      output() const              { return _output; }
 538   void              set_output(PhaseOutput* o)  { _output = o; }
 539 
 540   // ID for this compilation.  Useful for setting breakpoints in the debugger.
 541   int               compile_id() const          { return _compile_id; }
 542   DirectiveSet*     directive() const           { return _directive; }
 543 
 544   // Does this compilation allow instructions to subsume loads?  User
 545   // instructions that subsume a load may result in an unschedulable
 546   // instruction sequence.
 547   bool              subsume_loads() const       { return _options._subsume_loads; }
 548   /** Do escape analysis. */
 549   bool              do_escape_analysis() const  { return _options._do_escape_analysis; }
 550   bool              do_iterative_escape_analysis() const  { return _options._do_iterative_escape_analysis; }
 551   /** Do boxing elimination. */
 552   bool              eliminate_boxing() const    { return _options._eliminate_boxing; }
 553   /** Do aggressive boxing elimination. */
 554   bool              aggressive_unboxing() const { return _options._eliminate_boxing && AggressiveUnboxing; }
 555   bool              should_install_code() const { return _options._install_code; }
 556   /** Do locks coarsening. */
 557   bool              do_locks_coarsening() const { return _options._do_locks_coarsening; }
 558 
 559   // Other fixed compilation parameters.
 560   ciMethod*         method() const              { return _method; }
 561   int               entry_bci() const           { return _entry_bci; }
 562   bool              is_osr_compilation() const  { return _entry_bci != InvocationEntryBci; }
 563   bool              is_method_compilation() const { return (_method != nullptr && !_method->flags().is_native()); }
 564   const TypeFunc*   tf() const                  { assert(_tf!=nullptr, ""); return _tf; }
 565   void         init_tf(const TypeFunc* tf)      { assert(_tf==nullptr, ""); _tf = tf; }
 566   InlineTree*       ilt() const                 { return _ilt; }
 567   address           stub_function() const       { return _stub_function; }
 568   const char*       stub_name() const           { return _stub_name; }
 569   address           stub_entry_point() const    { return _stub_entry_point; }
 570   void          set_stub_entry_point(address z) { _stub_entry_point = z; }
 571 
 572   // Control of this compilation.
 573   int               fixed_slots() const         { assert(_fixed_slots >= 0, "");         return _fixed_slots; }
 574   void          set_fixed_slots(int n)          { _fixed_slots = n; }
 575   int               major_progress() const      { return _major_progress; }
 576   void          set_inlining_progress(bool z)   { _inlining_progress = z; }
 577   int               inlining_progress() const   { return _inlining_progress; }
 578   void          set_inlining_incrementally(bool z) { _inlining_incrementally = z; }
 579   int               inlining_incrementally() const { return _inlining_incrementally; }
 580   void          set_do_cleanup(bool z)          { _do_cleanup = z; }
 581   int               do_cleanup() const          { return _do_cleanup; }
 582   void          set_major_progress()            { _major_progress++; }
 583   void          restore_major_progress(int progress) { _major_progress += progress; }
 584   void        clear_major_progress()            { _major_progress = 0; }
 585   int               max_inline_size() const     { return _max_inline_size; }
 586   void          set_freq_inline_size(int n)     { _freq_inline_size = n; }
 587   int               freq_inline_size() const    { return _freq_inline_size; }
 588   void          set_max_inline_size(int n)      { _max_inline_size = n; }
 589   bool              has_loops() const           { return _has_loops; }
 590   void          set_has_loops(bool z)           { _has_loops = z; }
 591   bool              has_split_ifs() const       { return _has_split_ifs; }
 592   void          set_has_split_ifs(bool z)       { _has_split_ifs = z; }
 593   bool              has_unsafe_access() const   { return _has_unsafe_access; }
 594   void          set_has_unsafe_access(bool z)   { _has_unsafe_access = z; }
 595   bool              has_stringbuilder() const   { return _has_stringbuilder; }
 596   void          set_has_stringbuilder(bool z)   { _has_stringbuilder = z; }
 597   bool              has_boxed_value() const     { return _has_boxed_value; }
 598   void          set_has_boxed_value(bool z)     { _has_boxed_value = z; }
 599   bool              has_reserved_stack_access() const { return _has_reserved_stack_access; }
 600   void          set_has_reserved_stack_access(bool z) { _has_reserved_stack_access = z; }
 601   bool              has_circular_inline_type() const { return _has_circular_inline_type; }
 602   void          set_has_circular_inline_type(bool z) { _has_circular_inline_type = z; }
 603   uint              max_vector_size() const     { return _max_vector_size; }
 604   void          set_max_vector_size(uint s)     { _max_vector_size = s; }
 605   bool              clear_upper_avx() const     { return _clear_upper_avx; }
 606   void          set_clear_upper_avx(bool s)     { _clear_upper_avx = s; }
 607   void          set_trap_count(uint r, uint c)  { assert(r < trapHistLength, "oob");        _trap_hist[r] = c; }
 608   uint              trap_count(uint r) const    { assert(r < trapHistLength, "oob"); return _trap_hist[r]; }
 609   bool              trap_can_recompile() const  { return _trap_can_recompile; }
 610   void          set_trap_can_recompile(bool z)  { _trap_can_recompile = z; }
 611   uint              decompile_count() const     { return _decompile_count; }
 612   void          set_decompile_count(uint c)     { _decompile_count = c; }
 613   bool              allow_range_check_smearing() const;
 614   bool              do_inlining() const         { return _do_inlining; }
 615   void          set_do_inlining(bool z)         { _do_inlining = z; }
 616   bool              do_scheduling() const       { return _do_scheduling; }
 617   void          set_do_scheduling(bool z)       { _do_scheduling = z; }
 618   bool              do_freq_based_layout() const{ return _do_freq_based_layout; }
 619   void          set_do_freq_based_layout(bool z){ _do_freq_based_layout = z; }
 620   bool              do_vector_loop() const      { return _do_vector_loop; }
 621   void          set_do_vector_loop(bool z)      { _do_vector_loop = z; }
 622   bool              use_cmove() const           { return _use_cmove; }
 623   void          set_use_cmove(bool z)           { _use_cmove = z; }
 624   bool              do_aliasing() const          { return _do_aliasing; }
 625   bool              print_assembly() const       { return _print_assembly; }
 626   void          set_print_assembly(bool z)       { _print_assembly = z; }
 627   bool              print_inlining() const       { return _print_inlining; }
 628   void          set_print_inlining(bool z)       { _print_inlining = z; }
 629   bool              print_intrinsics() const     { return _print_intrinsics; }
 630   void          set_print_intrinsics(bool z)     { _print_intrinsics = z; }
 631   RTMState          rtm_state()  const           { return _rtm_state; }
 632   void          set_rtm_state(RTMState s)        { _rtm_state = s; }
 633   bool              use_rtm() const              { return (_rtm_state & NoRTM) == 0; }
 634   bool          profile_rtm() const              { return _rtm_state == ProfileRTM; }
 635   uint              max_node_limit() const       { return (uint)_max_node_limit; }
 636   void          set_max_node_limit(uint n)       { _max_node_limit = n; }
 637   bool              clinit_barrier_on_entry()       { return _clinit_barrier_on_entry; }
 638   void          set_clinit_barrier_on_entry(bool z) { _clinit_barrier_on_entry = z; }
 639   void          set_flattened_accesses()         { _has_flattened_accesses = true; }
 640   bool          flattened_accesses_share_alias() const { return _flattened_accesses_share_alias; }
 641   void          set_flattened_accesses_share_alias(bool z) { _flattened_accesses_share_alias = z; }
 642   bool          scalarize_in_safepoints() const { return _scalarize_in_safepoints; }
 643   void          set_scalarize_in_safepoints(bool z) { _scalarize_in_safepoints = z; }
 644 
 645   // Support for scalarized inline type calling convention
 646   bool              has_scalarized_args() const  { return _method != nullptr && _method->has_scalarized_args(); }
 647   bool              needs_stack_repair()  const  { return _method != nullptr && _method->get_Method()->c2_needs_stack_repair(); }
 648 
 649   bool              has_monitors() const         { return _has_monitors; }
 650   void          set_has_monitors(bool v)         { _has_monitors = v; }
 651 
 652   // check the CompilerOracle for special behaviours for this compile
 653   bool          method_has_option(enum CompileCommand option) {
 654     return method() != nullptr && method()->has_option(option);
 655   }
 656 
 657 #ifndef PRODUCT
 658   uint          next_igv_idx()                  { return _igv_idx++; }
 659   bool          trace_opto_output() const       { return _trace_opto_output; }
 660   void          print_ideal_ir(const char* phase_name);
 661   bool          should_print_ideal() const      { return _directive->PrintIdealOption; }
 662   bool              parsed_irreducible_loop() const { return _parsed_irreducible_loop; }
 663   void          set_parsed_irreducible_loop(bool z) { _parsed_irreducible_loop = z; }
 664   int _in_dump_cnt;  // Required for dumping ir nodes.
 665 #endif
 666   bool              has_irreducible_loop() const { return _has_irreducible_loop; }
 667   void          set_has_irreducible_loop(bool z) { _has_irreducible_loop = z; }
 668 
 669   // JSR 292
 670   bool              has_method_handle_invokes() const { return _has_method_handle_invokes;     }
 671   void          set_has_method_handle_invokes(bool z) {        _has_method_handle_invokes = z; }
 672 
 673   Ticks _latest_stage_start_counter;
 674 
 675   void begin_method();
 676   void end_method();
 677   bool should_print_igv(int level);
 678   bool should_print_phase(CompilerPhaseType cpt);
 679 
 680   void print_method(CompilerPhaseType cpt, int level, Node* n = nullptr);
 681 
 682 #ifndef PRODUCT
 683   void igv_print_method_to_file(const char* phase_name = "Debug", bool append = false);
 684   void igv_print_method_to_network(const char* phase_name = "Debug");
 685   static IdealGraphPrinter* debug_file_printer() { return _debug_file_printer; }
 686   static IdealGraphPrinter* debug_network_printer() { return _debug_network_printer; }
 687 #endif
 688 
 689   int           macro_count()             const { return _macro_nodes.length(); }
 690   int           parse_predicate_count()   const { return _parse_predicate_opaqs.length(); }
 691   int           template_assertion_predicate_count() const { return _template_assertion_predicate_opaqs.length(); }
 692   int           expensive_count()         const { return _expensive_nodes.length(); }
 693   int           coarsened_count()         const { return _coarsened_locks.length(); }
 694 
 695   Node*         macro_node(int idx)       const { return _macro_nodes.at(idx); }
 696   Node*         parse_predicate_opaque1_node(int idx) const { return _parse_predicate_opaqs.at(idx); }
 697 
 698   Node* template_assertion_predicate_opaq_node(int idx) const {
 699     return _template_assertion_predicate_opaqs.at(idx);
 700   }
 701 
 702   Node*         expensive_node(int idx)   const { return _expensive_nodes.at(idx); }
 703 
 704   ConnectionGraph* congraph()                   { return _congraph;}
 705   void set_congraph(ConnectionGraph* congraph)  { _congraph = congraph;}
 706   void add_macro_node(Node * n) {
 707     //assert(n->is_macro(), "must be a macro node");
 708     assert(!_macro_nodes.contains(n), "duplicate entry in expand list");
 709     _macro_nodes.append(n);
 710   }
 711   void remove_macro_node(Node* n) {
 712     // this function may be called twice for a node so we can only remove it
 713     // if it's still existing.
 714     _macro_nodes.remove_if_existing(n);
 715     // remove from _parse_predicate_opaqs list also if it is there
 716     if (parse_predicate_count() > 0) {
 717       _parse_predicate_opaqs.remove_if_existing(n);
 718     }
 719     // Remove from coarsened locks list if present
 720     if (coarsened_count() > 0) {
 721       remove_coarsened_lock(n);
 722     }
 723   }
 724   void add_expensive_node(Node* n);
 725   void remove_expensive_node(Node* n) {
 726     _expensive_nodes.remove_if_existing(n);
 727   }
 728   void add_parse_predicate_opaq(Node* n) {
 729     assert(!_parse_predicate_opaqs.contains(n), "duplicate entry in Parse Predicate opaque1 list");
 730     assert(_macro_nodes.contains(n), "should have already been in macro list");
 731     _parse_predicate_opaqs.append(n);
 732   }
 733   void add_template_assertion_predicate_opaq(Node* n) {
 734     assert(!_template_assertion_predicate_opaqs.contains(n),
 735            "duplicate entry in template assertion predicate opaque4 list");
 736     _template_assertion_predicate_opaqs.append(n);
 737   }
 738   void remove_template_assertion_predicate_opaq(Node* n) {
 739     if (template_assertion_predicate_count() > 0) {
 740       _template_assertion_predicate_opaqs.remove_if_existing(n);
 741     }
 742   }
 743   void add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks);
 744   void remove_coarsened_lock(Node* n);
 745   bool coarsened_locks_consistent();
 746 
 747   bool       post_loop_opts_phase() { return _post_loop_opts_phase;  }
 748   void   set_post_loop_opts_phase() { _post_loop_opts_phase = true;  }
 749   void reset_post_loop_opts_phase() { _post_loop_opts_phase = false; }
 750 
 751   void record_for_post_loop_opts_igvn(Node* n);
 752   void remove_from_post_loop_opts_igvn(Node* n);
 753   void process_for_post_loop_opts_igvn(PhaseIterGVN& igvn);
 754 
 755   // Keep track of inline type nodes for later processing
 756   void add_inline_type(Node* n);
 757   void remove_inline_type(Node* n);
 758   void process_inline_types(PhaseIterGVN &igvn, bool remove = false);
 759 
 760   void adjust_flattened_array_access_aliases(PhaseIterGVN& igvn);
 761 
 762   void record_unstable_if_trap(UnstableIfTrap* trap);
 763   bool remove_unstable_if_trap(CallStaticJavaNode* unc, bool yield);
 764   void remove_useless_unstable_if_traps(Unique_Node_List &useful);
 765   void process_for_unstable_if_traps(PhaseIterGVN& igvn);
 766 
 767   void sort_macro_nodes();
 768 
 769   // Remove the opaque nodes that protect the Parse Predicates so that the unused checks and
 770   // uncommon traps will be eliminated from the graph.
 771   void cleanup_parse_predicates(PhaseIterGVN &igvn) const;
 772   bool is_predicate_opaq(Node* n) const {
 773     return _parse_predicate_opaqs.contains(n);
 774   }
 775 
 776   // Are there candidate expensive nodes for optimization?
 777   bool should_optimize_expensive_nodes(PhaseIterGVN &igvn);
 778   // Check whether n1 and n2 are similar
 779   static int cmp_expensive_nodes(Node* n1, Node* n2);
 780   // Sort expensive nodes to locate similar expensive nodes
 781   void sort_expensive_nodes();
 782 
 783   // Compilation environment.
 784   Arena*      comp_arena()           { return &_comp_arena; }
 785   ciEnv*      env() const            { return _env; }
 786   CompileLog* log() const            { return _log; }
 787   bool        failing() const        { return _env->failing() || _failure_reason != nullptr; }
 788   const char* failure_reason() const { return (_env->failing()) ? _env->failure_reason() : _failure_reason; }
 789 
 790   bool failure_reason_is(const char* r) const {
 791     return (r == _failure_reason) || (r != nullptr && _failure_reason != nullptr && strcmp(r, _failure_reason) == 0);
 792   }
 793 
 794   void record_failure(const char* reason);
 795   void record_method_not_compilable(const char* reason) {
 796     env()->record_method_not_compilable(reason);
 797     // Record failure reason.
 798     record_failure(reason);
 799   }
 800   bool check_node_count(uint margin, const char* reason) {
 801     if (live_nodes() + margin > max_node_limit()) {
 802       record_method_not_compilable(reason);
 803       return true;
 804     } else {
 805       return false;
 806     }
 807   }
 808 
 809   // Node management
 810   uint         unique() const              { return _unique; }
 811   uint         next_unique()               { return _unique++; }
 812   void         set_unique(uint i)          { _unique = i; }
 813   Arena*       node_arena()                { return &_node_arena; }
 814   Arena*       old_arena()                 { return &_old_arena; }
 815   RootNode*    root() const                { return _root; }
 816   void         set_root(RootNode* r)       { _root = r; }
 817   StartNode*   start() const;              // (Derived from root.)
 818   void         init_start(StartNode* s);
 819   Node*        immutable_memory();
 820 
 821   Node*        recent_alloc_ctl() const    { return _recent_alloc_ctl; }
 822   Node*        recent_alloc_obj() const    { return _recent_alloc_obj; }
 823   void         set_recent_alloc(Node* ctl, Node* obj) {
 824                                                   _recent_alloc_ctl = ctl;
 825                                                   _recent_alloc_obj = obj;
 826                                            }
 827   void         record_dead_node(uint idx)  { if (_dead_node_list.test_set(idx)) return;
 828                                              _dead_node_count++;
 829                                            }
 830   void         reset_dead_node_list()      { _dead_node_list.reset();
 831                                              _dead_node_count = 0;
 832                                            }
 833   uint          live_nodes() const         {
 834     int  val = _unique - _dead_node_count;
 835     assert (val >= 0, "number of tracked dead nodes %d more than created nodes %d", _unique, _dead_node_count);
 836             return (uint) val;
 837                                            }
 838 #ifdef ASSERT
 839   void         set_phase_optimize_finished() { _phase_optimize_finished = true; }
 840   bool         phase_optimize_finished() const { return _phase_optimize_finished; }
 841   uint         count_live_nodes_by_graph_walk();
 842   void         print_missing_nodes();
 843 #endif
 844 
 845   // Record modified nodes to check that they are put on IGVN worklist
 846   void         record_modified_node(Node* n) NOT_DEBUG_RETURN;
 847   void         remove_modified_node(Node* n) NOT_DEBUG_RETURN;
 848   DEBUG_ONLY( Unique_Node_List*   modified_nodes() const { return _modified_nodes; } )
 849 
 850   MachConstantBaseNode*     mach_constant_base_node();
 851   bool                  has_mach_constant_base_node() const { return _mach_constant_base_node != nullptr; }
 852   // Generated by adlc, true if CallNode requires MachConstantBase.
 853   bool                      needs_deep_clone_jvms();
 854 
 855   // Handy undefined Node
 856   Node*             top() const                 { return _top; }
 857 
 858   // these are used by guys who need to know about creation and transformation of top:
 859   Node*             cached_top_node()           { return _top; }
 860   void          set_cached_top_node(Node* tn);
 861 
 862   GrowableArray<Node_Notes*>* node_note_array() const { return _node_note_array; }
 863   void set_node_note_array(GrowableArray<Node_Notes*>* arr) { _node_note_array = arr; }
 864   Node_Notes* default_node_notes() const        { return _default_node_notes; }
 865   void    set_default_node_notes(Node_Notes* n) { _default_node_notes = n; }
 866 
 867   Node_Notes*       node_notes_at(int idx) {
 868     return locate_node_notes(_node_note_array, idx, false);
 869   }
 870   inline bool   set_node_notes_at(int idx, Node_Notes* value);
 871 
 872   // Copy notes from source to dest, if they exist.
 873   // Overwrite dest only if source provides something.
 874   // Return true if information was moved.
 875   bool copy_node_notes_to(Node* dest, Node* source);
 876 
 877   // Workhorse function to sort out the blocked Node_Notes array:
 878   inline Node_Notes* locate_node_notes(GrowableArray<Node_Notes*>* arr,
 879                                        int idx, bool can_grow = false);
 880 
 881   void grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by);
 882 
 883   // Type management
 884   Arena*            type_arena()                { return _type_arena; }
 885   Dict*             type_dict()                 { return _type_dict; }
 886   size_t            type_last_size()            { return _type_last_size; }
 887   int               num_alias_types()           { return _num_alias_types; }
 888 
 889   void          init_type_arena()                       { _type_arena = &_Compile_types; }
 890   void          set_type_arena(Arena* a)                { _type_arena = a; }
 891   void          set_type_dict(Dict* d)                  { _type_dict = d; }
 892   void          set_type_last_size(size_t sz)           { _type_last_size = sz; }
 893 
 894   const TypeFunc* last_tf(ciMethod* m) {
 895     return (m == _last_tf_m) ? _last_tf : nullptr;
 896   }
 897   void set_last_tf(ciMethod* m, const TypeFunc* tf) {
 898     assert(m != nullptr || tf == nullptr, "");
 899     _last_tf_m = m;
 900     _last_tf = tf;
 901   }
 902 
 903   AliasType*        alias_type(int                idx)  { assert(idx < num_alias_types(), "oob"); return _alias_types[idx]; }
 904   AliasType*        alias_type(const TypePtr* adr_type, ciField* field = nullptr, bool uncached = false) { return find_alias_type(adr_type, false, field, uncached); }
 905   bool         have_alias_type(const TypePtr* adr_type);
 906   AliasType*        alias_type(ciField*         field);
 907 
 908   int               get_alias_index(const TypePtr* at, bool uncached = false) { return alias_type(at, nullptr, uncached)->index(); }
 909   const TypePtr*    get_adr_type(uint aidx)             { return alias_type(aidx)->adr_type(); }
 910   int               get_general_index(uint aidx)        { return alias_type(aidx)->general_index(); }
 911 
 912   // Building nodes
 913   void              rethrow_exceptions(JVMState* jvms);
 914   void              return_values(JVMState* jvms);
 915   JVMState*         build_start_state(StartNode* start, const TypeFunc* tf);
 916 
 917   // Decide how to build a call.
 918   // The profile factor is a discount to apply to this site's interp. profile.
 919   CallGenerator*    call_generator(ciMethod* call_method, int vtable_index, bool call_does_dispatch,
 920                                    JVMState* jvms, bool allow_inline, float profile_factor, ciKlass* speculative_receiver_type = nullptr,
 921                                    bool allow_intrinsics = true);
 922   bool should_delay_inlining(ciMethod* call_method, JVMState* jvms) {
 923     return should_delay_string_inlining(call_method, jvms) ||
 924            should_delay_boxing_inlining(call_method, jvms) ||
 925            should_delay_vector_inlining(call_method, jvms);
 926   }
 927   bool should_delay_string_inlining(ciMethod* call_method, JVMState* jvms);
 928   bool should_delay_boxing_inlining(ciMethod* call_method, JVMState* jvms);
 929   bool should_delay_vector_inlining(ciMethod* call_method, JVMState* jvms);
 930   bool should_delay_vector_reboxing_inlining(ciMethod* call_method, JVMState* jvms);
 931 
 932   // Helper functions to identify inlining potential at call-site
 933   ciMethod* optimize_virtual_call(ciMethod* caller, ciInstanceKlass* klass,
 934                                   ciKlass* holder, ciMethod* callee,
 935                                   const TypeOopPtr* receiver_type, bool is_virtual,
 936                                   bool &call_does_dispatch, int &vtable_index,
 937                                   bool check_access = true);
 938   ciMethod* optimize_inlining(ciMethod* caller, ciInstanceKlass* klass, ciKlass* holder,
 939                               ciMethod* callee, const TypeOopPtr* receiver_type,
 940                               bool check_access = true);
 941 
 942   // Report if there were too many traps at a current method and bci.
 943   // Report if a trap was recorded, and/or PerMethodTrapLimit was exceeded.
 944   // If there is no MDO at all, report no trap unless told to assume it.
 945   bool too_many_traps(ciMethod* method, int bci, Deoptimization::DeoptReason reason);
 946   // This version, unspecific to a particular bci, asks if
 947   // PerMethodTrapLimit was exceeded for all inlined methods seen so far.
 948   bool too_many_traps(Deoptimization::DeoptReason reason,
 949                       // Privately used parameter for logging:
 950                       ciMethodData* logmd = nullptr);
 951   // Report if there were too many recompiles at a method and bci.
 952   bool too_many_recompiles(ciMethod* method, int bci, Deoptimization::DeoptReason reason);
 953   // Report if there were too many traps or recompiles at a method and bci.
 954   bool too_many_traps_or_recompiles(ciMethod* method, int bci, Deoptimization::DeoptReason reason) {
 955     return too_many_traps(method, bci, reason) ||
 956            too_many_recompiles(method, bci, reason);
 957   }
 958   // Return a bitset with the reasons where deoptimization is allowed,
 959   // i.e., where there were not too many uncommon traps.
 960   int _allowed_reasons;
 961   int      allowed_deopt_reasons() { return _allowed_reasons; }
 962   void set_allowed_deopt_reasons();
 963 
 964   // Parsing, optimization
 965   PhaseGVN*         initial_gvn()               { return _initial_gvn; }
 966   Unique_Node_List* for_igvn()                  { return _for_igvn; }
 967   inline void       record_for_igvn(Node* n);   // Body is after class Unique_Node_List in node.hpp.
 968   inline void       remove_for_igvn(Node* n);   // Body is after class Unique_Node_List in node.hpp.
 969   void          set_initial_gvn(PhaseGVN *gvn)           { _initial_gvn = gvn; }
 970   void          set_for_igvn(Unique_Node_List *for_igvn) { _for_igvn = for_igvn; }
 971 
 972   // Replace n by nn using initial_gvn, calling hash_delete and
 973   // record_for_igvn as needed.
 974   void gvn_replace_by(Node* n, Node* nn);
 975 
 976 
 977   void              identify_useful_nodes(Unique_Node_List &useful);
 978   void              update_dead_node_list(Unique_Node_List &useful);
 979   void              disconnect_useless_nodes(Unique_Node_List &useful, Unique_Node_List* worklist);
 980 
 981   void              remove_useless_node(Node* dead);
 982 
 983   // Record this CallGenerator for inlining at the end of parsing.
 984   void              add_late_inline(CallGenerator* cg)        {
 985     _late_inlines.insert_before(_late_inlines_pos, cg);
 986     _late_inlines_pos++;
 987   }
 988 
 989   void              prepend_late_inline(CallGenerator* cg)    {
 990     _late_inlines.insert_before(0, cg);
 991   }
 992 
 993   void              add_string_late_inline(CallGenerator* cg) {
 994     _string_late_inlines.push(cg);
 995   }
 996 
 997   void              add_boxing_late_inline(CallGenerator* cg) {
 998     _boxing_late_inlines.push(cg);
 999   }
1000 
1001   void              add_vector_reboxing_late_inline(CallGenerator* cg) {
1002     _vector_reboxing_late_inlines.push(cg);
1003   }
1004 
1005   void remove_useless_nodes       (GrowableArray<Node*>&        node_list, Unique_Node_List &useful);
1006 
1007   void remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful);
1008   void remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Node* dead);
1009 
1010   void remove_useless_coarsened_locks(Unique_Node_List& useful);
1011 
1012   void process_print_inlining();
1013   void dump_print_inlining();
1014 
1015   bool over_inlining_cutoff() const {
1016     if (!inlining_incrementally()) {
1017       return unique() > (uint)NodeCountInliningCutoff;
1018     } else {
1019       // Give some room for incremental inlining algorithm to "breathe"
1020       // and avoid thrashing when live node count is close to the limit.
1021       // Keep in mind that live_nodes() isn't accurate during inlining until
1022       // dead node elimination step happens (see Compile::inline_incrementally).
1023       return live_nodes() > (uint)LiveNodeCountInliningCutoff * 11 / 10;
1024     }
1025   }
1026 
1027   void inc_number_of_mh_late_inlines() { _number_of_mh_late_inlines++; }
1028   void dec_number_of_mh_late_inlines() { assert(_number_of_mh_late_inlines > 0, "_number_of_mh_late_inlines < 0 !"); _number_of_mh_late_inlines--; }
1029   bool has_mh_late_inlines() const     { return _number_of_mh_late_inlines > 0; }
1030 
1031   bool inline_incrementally_one();
1032   void inline_incrementally_cleanup(PhaseIterGVN& igvn);
1033   void inline_incrementally(PhaseIterGVN& igvn);
1034   void inline_string_calls(bool parse_time);
1035   void inline_boxing_calls(PhaseIterGVN& igvn);
1036   bool optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode);
1037   void remove_root_to_sfpts_edges(PhaseIterGVN& igvn);
1038 
1039   void inline_vector_reboxing_calls();
1040   bool has_vbox_nodes();
1041 
1042   void process_late_inline_calls_no_inline(PhaseIterGVN& igvn);
1043 
1044   // Matching, CFG layout, allocation, code generation
1045   PhaseCFG*         cfg()                       { return _cfg; }
1046   bool              has_java_calls() const      { return _java_calls > 0; }
1047   int               java_calls() const          { return _java_calls; }
1048   int               inner_loops() const         { return _inner_loops; }
1049   Matcher*          matcher()                   { return _matcher; }
1050   PhaseRegAlloc*    regalloc()                  { return _regalloc; }
1051   RegMask&          FIRST_STACK_mask()          { return _FIRST_STACK_mask; }
1052   Arena*            indexSet_arena()            { return _indexSet_arena; }
1053   void*             indexSet_free_block_list()  { return _indexSet_free_block_list; }
1054   DebugInformationRecorder* debug_info()        { return env()->debug_info(); }
1055 
1056   void  update_interpreter_frame_size(int size) {
1057     if (_interpreter_frame_size < size) {
1058       _interpreter_frame_size = size;
1059     }
1060   }
1061 
1062   void          set_matcher(Matcher* m)                 { _matcher = m; }
1063 //void          set_regalloc(PhaseRegAlloc* ra)           { _regalloc = ra; }
1064   void          set_indexSet_arena(Arena* a)            { _indexSet_arena = a; }
1065   void          set_indexSet_free_block_list(void* p)   { _indexSet_free_block_list = p; }
1066 
1067   void  set_java_calls(int z) { _java_calls  = z; }
1068   void set_inner_loops(int z) { _inner_loops = z; }
1069 
1070   Dependencies* dependencies() { return env()->dependencies(); }
1071 
1072   // Major entry point.  Given a Scope, compile the associated method.
1073   // For normal compilations, entry_bci is InvocationEntryBci.  For on stack
1074   // replacement, entry_bci indicates the bytecode for which to compile a
1075   // continuation.
1076   Compile(ciEnv* ci_env, ciMethod* target,
1077           int entry_bci, Options options, DirectiveSet* directive);
1078 
1079   // Second major entry point.  From the TypeFunc signature, generate code
1080   // to pass arguments from the Java calling convention to the C calling
1081   // convention.
1082   Compile(ciEnv* ci_env, const TypeFunc *(*gen)(),
1083           address stub_function, const char *stub_name,
1084           int is_fancy_jump, bool pass_tls,
1085           bool return_pc, DirectiveSet* directive);
1086 
1087   ~Compile() {
1088     delete _print_inlining_stream;
1089   };
1090 
1091   // Are we compiling a method?
1092   bool has_method() { return method() != nullptr; }
1093 
1094   // Maybe print some information about this compile.
1095   void print_compile_messages();
1096 
1097   // Final graph reshaping, a post-pass after the regular optimizer is done.
1098   bool final_graph_reshaping();
1099 
1100   // returns true if adr is completely contained in the given alias category
1101   bool must_alias(const TypePtr* adr, int alias_idx);
1102 
1103   // returns true if adr overlaps with the given alias category
1104   bool can_alias(const TypePtr* adr, int alias_idx);
1105 
1106   // Stack slots that may be unused by the calling convention but must
1107   // otherwise be preserved.  On Intel this includes the return address.
1108   // On PowerPC it includes the 4 words holding the old TOC & LR glue.
1109   uint in_preserve_stack_slots() {
1110     return SharedRuntime::in_preserve_stack_slots();
1111   }
1112 
1113   // "Top of Stack" slots that may be unused by the calling convention but must
1114   // otherwise be preserved.
1115   // On Intel these are not necessary and the value can be zero.
1116   static uint out_preserve_stack_slots() {
1117     return SharedRuntime::out_preserve_stack_slots();
1118   }
1119 
1120   // Number of outgoing stack slots killed above the out_preserve_stack_slots
1121   // for calls to C.  Supports the var-args backing area for register parms.
1122   uint varargs_C_out_slots_killed() const;
1123 
1124   // Number of Stack Slots consumed by a synchronization entry
1125   int sync_stack_slots() const;
1126 
1127   // Compute the name of old_SP.  See <arch>.ad for frame layout.
1128   OptoReg::Name compute_old_SP();
1129 
1130  private:
1131   // Phase control:
1132   void Init(bool aliasing);                      // Prepare for a single compilation
1133   void Optimize();                               // Given a graph, optimize it
1134   void Code_Gen();                               // Generate code from a graph
1135 
1136   // Management of the AliasType table.
1137   void grow_alias_types();
1138   AliasCacheEntry* probe_alias_cache(const TypePtr* adr_type);
1139   const TypePtr *flatten_alias_type(const TypePtr* adr_type) const;
1140   AliasType* find_alias_type(const TypePtr* adr_type, bool no_create, ciField* field, bool uncached = false);
1141 
1142   void verify_top(Node*) const PRODUCT_RETURN;
1143 
1144   // Intrinsic setup.
1145   CallGenerator* make_vm_intrinsic(ciMethod* m, bool is_virtual);          // constructor
1146   int            intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found);  // helper
1147   CallGenerator* find_intrinsic(ciMethod* m, bool is_virtual);             // query fn
1148   void           register_intrinsic(CallGenerator* cg);                    // update fn
1149 
1150 #ifndef PRODUCT
1151   static juint  _intrinsic_hist_count[];
1152   static jubyte _intrinsic_hist_flags[];
1153 #endif
1154   // Function calls made by the public function final_graph_reshaping.
1155   // No need to be made public as they are not called elsewhere.
1156   void final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes);
1157   void final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes);
1158   void final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes);
1159   void eliminate_redundant_card_marks(Node* n);
1160 
1161   // Logic cone optimization.
1162   void optimize_logic_cones(PhaseIterGVN &igvn);
1163   void collect_logic_cone_roots(Unique_Node_List& list);
1164   void process_logic_cone_root(PhaseIterGVN &igvn, Node* n, VectorSet& visited);
1165   bool compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs);
1166   uint compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs);
1167   uint eval_macro_logic_op(uint func, uint op1, uint op2, uint op3);
1168   Node* xform_to_MacroLogicV(PhaseIterGVN &igvn, const TypeVect* vt, Unique_Node_List& partitions, Unique_Node_List& inputs);
1169   void check_no_dead_use() const NOT_DEBUG_RETURN;
1170 
1171  public:
1172 
1173   // Note:  Histogram array size is about 1 Kb.
1174   enum {                        // flag bits:
1175     _intrinsic_worked = 1,      // succeeded at least once
1176     _intrinsic_failed = 2,      // tried it but it failed
1177     _intrinsic_disabled = 4,    // was requested but disabled (e.g., -XX:-InlineUnsafeOps)
1178     _intrinsic_virtual = 8,     // was seen in the virtual form (rare)
1179     _intrinsic_both = 16        // was seen in the non-virtual form (usual)
1180   };
1181   // Update histogram.  Return boolean if this is a first-time occurrence.
1182   static bool gather_intrinsic_statistics(vmIntrinsics::ID id,
1183                                           bool is_virtual, int flags) PRODUCT_RETURN0;
1184   static void print_intrinsic_statistics() PRODUCT_RETURN;
1185 
1186   // Graph verification code
1187   // Walk the node list, verifying that there is a one-to-one
1188   // correspondence between Use-Def edges and Def-Use edges
1189   // The option no_dead_code enables stronger checks that the
1190   // graph is strongly connected from root in both directions.
1191   void verify_graph_edges(bool no_dead_code = false) PRODUCT_RETURN;
1192 
1193   // Verify bi-directional correspondence of edges
1194   void verify_bidirectional_edges(Unique_Node_List &visited);
1195 
1196   // End-of-run dumps.
1197   static void print_statistics() PRODUCT_RETURN;
1198 
1199   // Verify ADLC assumptions during startup
1200   static void adlc_verification() PRODUCT_RETURN;
1201 
1202   // Definitions of pd methods
1203   static void pd_compiler2_init();
1204 
1205   // Static parse-time type checking logic for gen_subtype_check:
1206   enum SubTypeCheckResult { SSC_always_false, SSC_always_true, SSC_easy_test, SSC_full_test };
1207   SubTypeCheckResult static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip = StressReflectiveCode);
1208 
1209   static Node* conv_I2X_index(PhaseGVN* phase, Node* offset, const TypeInt* sizetype,
1210                               // Optional control dependency (for example, on range check)
1211                               Node* ctrl = nullptr);
1212 
1213   // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
1214   static Node* constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency = false);
1215 
1216   Node* optimize_acmp(PhaseGVN* phase, Node* a, Node* b);
1217 
1218   // Auxiliary method for randomized fuzzing/stressing
1219   int random();
1220   bool randomized_select(int count);
1221 
1222   // supporting clone_map
1223   CloneMap&     clone_map();
1224   void          set_clone_map(Dict* d);
1225 
1226   bool needs_clinit_barrier(ciField* ik,         ciMethod* accessing_method);
1227   bool needs_clinit_barrier(ciMethod* ik,        ciMethod* accessing_method);
1228   bool needs_clinit_barrier(ciInstanceKlass* ik, ciMethod* accessing_method);
1229 
1230 #ifdef IA32
1231  private:
1232   bool _select_24_bit_instr;   // We selected an instruction with a 24-bit result
1233   bool _in_24_bit_fp_mode;     // We are emitting instructions with 24-bit results
1234 
1235   // Remember if this compilation changes hardware mode to 24-bit precision.
1236   void set_24_bit_selection_and_mode(bool selection, bool mode) {
1237     _select_24_bit_instr = selection;
1238     _in_24_bit_fp_mode   = mode;
1239   }
1240 
1241  public:
1242   bool select_24_bit_instr() const { return _select_24_bit_instr; }
1243   bool in_24_bit_fp_mode() const   { return _in_24_bit_fp_mode; }
1244 #endif // IA32
1245 #ifdef ASSERT
1246   VerifyMeetResult* _type_verify;
1247   void set_exception_backedge() { _exception_backedge = true; }
1248   bool has_exception_backedge() const { return _exception_backedge; }
1249 #endif
1250 
1251   static bool push_thru_add(PhaseGVN* phase, Node* z, const TypeInteger* tz, const TypeInteger*& rx, const TypeInteger*& ry,
1252                             BasicType out_bt, BasicType in_bt);
1253 
1254   static Node* narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res);
1255 };
1256 
1257 #endif // SHARE_OPTO_COMPILE_HPP