Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/c1/c1_Compilation.cpp
32285 views
/*1* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "c1/c1_CFGPrinter.hpp"26#include "c1/c1_Compilation.hpp"27#include "c1/c1_IR.hpp"28#include "c1/c1_LIRAssembler.hpp"29#include "c1/c1_LinearScan.hpp"30#include "c1/c1_MacroAssembler.hpp"31#include "c1/c1_ValueMap.hpp"32#include "c1/c1_ValueStack.hpp"33#include "code/debugInfoRec.hpp"34#include "compiler/compileLog.hpp"35#include "c1/c1_RangeCheckElimination.hpp"363738typedef enum {39_t_compile,40_t_setup,41_t_buildIR,42_t_optimize_blocks,43_t_optimize_null_checks,44_t_rangeCheckElimination,45_t_emit_lir,46_t_linearScan,47_t_lirGeneration,48_t_lir_schedule,49_t_codeemit,50_t_codeinstall,51max_phase_timers52} TimerName;5354static const char * timer_name[] = {55"compile",56"setup",57"buildIR",58"optimize_blocks",59"optimize_null_checks",60"rangeCheckElimination",61"emit_lir",62"linearScan",63"lirGeneration",64"lir_schedule",65"codeemit",66"codeinstall"67};6869static elapsedTimer timers[max_phase_timers];70static int totalInstructionNodes = 0;7172class PhaseTraceTime: public TraceTime {73private:74JavaThread* _thread;75CompileLog* _log;76TimerName _timer;7778public:79PhaseTraceTime(TimerName timer)80: TraceTime("", &timers[timer], CITime || CITimeEach, Verbose),81_log(NULL), _timer(timer)82{83if (Compilation::current() != NULL) {84_log = Compilation::current()->log();85}8687if (_log != NULL) {88_log->begin_head("phase name='%s'", timer_name[_timer]);89_log->stamp();90_log->end_head();91}92}9394~PhaseTraceTime() {95if (_log != NULL)96_log->done("phase name='%s'", timer_name[_timer]);97}98};99100// Implementation of Compilation101102103#ifndef PRODUCT104105void Compilation::maybe_print_current_instruction() {106if (_current_instruction != NULL && _last_instruction_printed != _current_instruction) {107_last_instruction_printed = _current_instruction;108_current_instruction->print_line();109}110}111#endif // PRODUCT112113114DebugInformationRecorder* Compilation::debug_info_recorder() const {115return _env->debug_info();116}117118119Dependencies* Compilation::dependency_recorder() const {120return _env->dependencies();121}122123124void Compilation::initialize() {125// Use an oop recorder bound to the CI environment.126// (The default oop recorder is ignorant of the CI.)127OopRecorder* ooprec = new OopRecorder(_env->arena());128_env->set_oop_recorder(ooprec);129_env->set_debug_info(new DebugInformationRecorder(ooprec));130debug_info_recorder()->set_oopmaps(new OopMapSet());131_env->set_dependencies(new Dependencies(_env));132}133134135void Compilation::build_hir() {136CHECK_BAILOUT();137138// setup ir139CompileLog* log = this->log();140if (log != NULL) {141log->begin_head("parse method='%d' ",142log->identify(_method));143log->stamp();144log->end_head();145}146_hir = new IR(this, method(), osr_bci());147if (log) log->done("parse");148if (!_hir->is_valid()) {149bailout("invalid parsing");150return;151}152153#ifndef PRODUCT154if (PrintCFGToFile) {155CFGPrinter::print_cfg(_hir, "After Generation of HIR", true, false);156}157#endif158159#ifndef PRODUCT160if (PrintCFG || PrintCFG0) { tty->print_cr("CFG after parsing"); _hir->print(true); }161if (PrintIR || PrintIR0 ) { tty->print_cr("IR after parsing"); _hir->print(false); }162#endif163164_hir->verify();165166if (UseC1Optimizations) {167NEEDS_CLEANUP168// optimization169PhaseTraceTime timeit(_t_optimize_blocks);170171_hir->optimize_blocks();172}173174_hir->verify();175176_hir->split_critical_edges();177178#ifndef PRODUCT179if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after optimizations"); _hir->print(true); }180if (PrintIR || PrintIR1 ) { tty->print_cr("IR after optimizations"); _hir->print(false); }181#endif182183_hir->verify();184185// compute block ordering for code generation186// the control flow must not be changed from here on187_hir->compute_code();188189if (UseGlobalValueNumbering) {190// No resource mark here! LoopInvariantCodeMotion can allocate ValueStack objects.191int instructions = Instruction::number_of_instructions();192GlobalValueNumbering gvn(_hir);193assert(instructions == Instruction::number_of_instructions(),194"shouldn't have created an instructions");195}196197_hir->verify();198199#ifndef PRODUCT200if (PrintCFGToFile) {201CFGPrinter::print_cfg(_hir, "Before RangeCheckElimination", true, false);202}203#endif204205if (RangeCheckElimination) {206if (_hir->osr_entry() == NULL) {207PhaseTraceTime timeit(_t_rangeCheckElimination);208RangeCheckElimination::eliminate(_hir);209}210}211212#ifndef PRODUCT213if (PrintCFGToFile) {214CFGPrinter::print_cfg(_hir, "After RangeCheckElimination", true, false);215}216#endif217218if (UseC1Optimizations) {219// loop invariant code motion reorders instructions and range220// check elimination adds new instructions so do null check221// elimination after.222NEEDS_CLEANUP223// optimization224PhaseTraceTime timeit(_t_optimize_null_checks);225226_hir->eliminate_null_checks();227}228229_hir->verify();230231// compute use counts after global value numbering232_hir->compute_use_counts();233234#ifndef PRODUCT235if (PrintCFG || PrintCFG2) { tty->print_cr("CFG before code generation"); _hir->code()->print(true); }236if (PrintIR || PrintIR2 ) { tty->print_cr("IR before code generation"); _hir->code()->print(false, true); }237#endif238239_hir->verify();240}241242243void Compilation::emit_lir() {244CHECK_BAILOUT();245246LIRGenerator gen(this, method());247{248PhaseTraceTime timeit(_t_lirGeneration);249hir()->iterate_linear_scan_order(&gen);250}251252CHECK_BAILOUT();253254{255PhaseTraceTime timeit(_t_linearScan);256257LinearScan* allocator = new LinearScan(hir(), &gen, frame_map());258set_allocator(allocator);259// Assign physical registers to LIR operands using a linear scan algorithm.260allocator->do_linear_scan();261CHECK_BAILOUT();262263_max_spills = allocator->max_spills();264}265266if (BailoutAfterLIR) {267if (PrintLIR && !bailed_out()) {268print_LIR(hir()->code());269}270bailout("Bailing out because of -XX:+BailoutAfterLIR");271}272}273274275void Compilation::emit_code_epilog(LIR_Assembler* assembler) {276CHECK_BAILOUT();277278CodeOffsets* code_offsets = assembler->offsets();279280// generate code or slow cases281assembler->emit_slow_case_stubs();282CHECK_BAILOUT();283284// generate exception adapters285assembler->emit_exception_entries(exception_info_list());286CHECK_BAILOUT();287288// Generate code for exception handler.289code_offsets->set_value(CodeOffsets::Exceptions, assembler->emit_exception_handler());290CHECK_BAILOUT();291292// Generate code for deopt handler.293code_offsets->set_value(CodeOffsets::Deopt, assembler->emit_deopt_handler());294CHECK_BAILOUT();295296// Emit the MethodHandle deopt handler code (if required).297if (has_method_handle_invokes()) {298// We can use the same code as for the normal deopt handler, we299// just need a different entry point address.300code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler());301CHECK_BAILOUT();302}303304// Emit the handler to remove the activation from the stack and305// dispatch to the caller.306offsets()->set_value(CodeOffsets::UnwindHandler, assembler->emit_unwind_handler());307308// done309masm()->flush();310}311312313bool Compilation::setup_code_buffer(CodeBuffer* code, int call_stub_estimate) {314// Preinitialize the consts section to some large size:315int locs_buffer_size = 20 * (relocInfo::length_limit + sizeof(relocInfo));316char* locs_buffer = NEW_RESOURCE_ARRAY(char, locs_buffer_size);317code->insts()->initialize_shared_locs((relocInfo*)locs_buffer,318locs_buffer_size / sizeof(relocInfo));319code->initialize_consts_size(Compilation::desired_max_constant_size());320// Call stubs + two deopt handlers (regular and MH) + exception handler321int stub_size = (call_stub_estimate * LIR_Assembler::call_stub_size) +322LIR_Assembler::exception_handler_size +323(2 * LIR_Assembler::deopt_handler_size);324if (stub_size >= code->insts_capacity()) return false;325code->initialize_stubs_size(stub_size);326return true;327}328329330int Compilation::emit_code_body() {331// emit code332if (!setup_code_buffer(code(), allocator()->num_calls())) {333BAILOUT_("size requested greater than avail code buffer size", 0);334}335code()->initialize_oop_recorder(env()->oop_recorder());336337_masm = new C1_MacroAssembler(code());338_masm->set_oop_recorder(env()->oop_recorder());339340LIR_Assembler lir_asm(this);341342lir_asm.emit_code(hir()->code());343CHECK_BAILOUT_(0);344345emit_code_epilog(&lir_asm);346CHECK_BAILOUT_(0);347348generate_exception_handler_table();349350#ifndef PRODUCT351if (PrintExceptionHandlers && Verbose) {352exception_handler_table()->print();353}354#endif /* PRODUCT */355356return frame_map()->framesize();357}358359360int Compilation::compile_java_method() {361assert(!method()->is_native(), "should not reach here");362363if (BailoutOnExceptionHandlers) {364if (method()->has_exception_handlers()) {365bailout("linear scan can't handle exception handlers");366}367}368369CHECK_BAILOUT_(no_frame_size);370371if (is_profiling() && !method()->ensure_method_data()) {372BAILOUT_("mdo allocation failed", no_frame_size);373}374375{376PhaseTraceTime timeit(_t_buildIR);377build_hir();378}379if (BailoutAfterHIR) {380BAILOUT_("Bailing out because of -XX:+BailoutAfterHIR", no_frame_size);381}382383384{385PhaseTraceTime timeit(_t_emit_lir);386387_frame_map = new FrameMap(method(), hir()->number_of_locks(), MAX2(4, hir()->max_stack()));388emit_lir();389}390CHECK_BAILOUT_(no_frame_size);391392{393PhaseTraceTime timeit(_t_codeemit);394return emit_code_body();395}396}397398void Compilation::install_code(int frame_size) {399// frame_size is in 32-bit words so adjust it intptr_t words400assert(frame_size == frame_map()->framesize(), "must match");401assert(in_bytes(frame_map()->framesize_in_bytes()) % sizeof(intptr_t) == 0, "must be at least pointer aligned");402_env->register_method(403method(),404osr_bci(),405&_offsets,406in_bytes(_frame_map->sp_offset_for_orig_pc()),407code(),408in_bytes(frame_map()->framesize_in_bytes()) / sizeof(intptr_t),409debug_info_recorder()->_oopmaps,410exception_handler_table(),411implicit_exception_table(),412compiler(),413_env->comp_level(),414has_unsafe_access(),415SharedRuntime::is_wide_vector(max_vector_size())416);417}418419420void Compilation::compile_method() {421// setup compilation422initialize();423424if (!method()->can_be_compiled()) {425// Prevent race condition 6328518.426// This can happen if the method is obsolete or breakpointed.427bailout("Bailing out because method is not compilable");428return;429}430431if (_env->jvmti_can_hotswap_or_post_breakpoint()) {432// We can assert evol_method because method->can_be_compiled is true.433dependency_recorder()->assert_evol_method(method());434}435436if (method()->break_at_execute()) {437BREAKPOINT;438}439440#ifndef PRODUCT441if (PrintCFGToFile) {442CFGPrinter::print_compilation(this);443}444#endif445446// compile method447int frame_size = compile_java_method();448449// bailout if method couldn't be compiled450// Note: make sure we mark the method as not compilable!451CHECK_BAILOUT();452453if (InstallMethods) {454// install code455PhaseTraceTime timeit(_t_codeinstall);456install_code(frame_size);457}458459if (log() != NULL) // Print code cache state into compiler log460log()->code_cache_state();461462totalInstructionNodes += Instruction::number_of_instructions();463}464465466void Compilation::generate_exception_handler_table() {467// Generate an ExceptionHandlerTable from the exception handler468// information accumulated during the compilation.469ExceptionInfoList* info_list = exception_info_list();470471if (info_list->length() == 0) {472return;473}474475// allocate some arrays for use by the collection code.476const int num_handlers = 5;477GrowableArray<intptr_t>* bcis = new GrowableArray<intptr_t>(num_handlers);478GrowableArray<intptr_t>* scope_depths = new GrowableArray<intptr_t>(num_handlers);479GrowableArray<intptr_t>* pcos = new GrowableArray<intptr_t>(num_handlers);480481for (int i = 0; i < info_list->length(); i++) {482ExceptionInfo* info = info_list->at(i);483XHandlers* handlers = info->exception_handlers();484485// empty the arrays486bcis->trunc_to(0);487scope_depths->trunc_to(0);488pcos->trunc_to(0);489490for (int i = 0; i < handlers->length(); i++) {491XHandler* handler = handlers->handler_at(i);492assert(handler->entry_pco() != -1, "must have been generated");493494int e = bcis->find(handler->handler_bci());495if (e >= 0 && scope_depths->at(e) == handler->scope_count()) {496// two different handlers are declared to dispatch to the same497// catch bci. During parsing we created edges for each498// handler but we really only need one. The exception handler499// table will also get unhappy if we try to declare both since500// it's nonsensical. Just skip this handler.501continue;502}503504bcis->append(handler->handler_bci());505if (handler->handler_bci() == -1) {506// insert a wildcard handler at scope depth 0 so that the507// exception lookup logic with find it.508scope_depths->append(0);509} else {510scope_depths->append(handler->scope_count());511}512pcos->append(handler->entry_pco());513514// stop processing once we hit a catch any515if (handler->is_catch_all()) {516assert(i == handlers->length() - 1, "catch all must be last handler");517}518}519exception_handler_table()->add_subtable(info->pco(), bcis, scope_depths, pcos);520}521}522523524Compilation::Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* method,525int osr_bci, BufferBlob* buffer_blob)526: _compiler(compiler)527, _env(env)528, _log(env->log())529, _method(method)530, _osr_bci(osr_bci)531, _hir(NULL)532, _max_spills(-1)533, _frame_map(NULL)534, _masm(NULL)535, _has_exception_handlers(false)536, _has_fpu_code(true) // pessimistic assumption537, _would_profile(false)538, _has_unsafe_access(false)539, _has_method_handle_invokes(false)540, _bailout_msg(NULL)541, _exception_info_list(NULL)542, _allocator(NULL)543, _next_id(0)544, _next_block_id(0)545, _code(buffer_blob)546, _has_access_indexed(false)547, _current_instruction(NULL)548, _interpreter_frame_size(0)549#ifndef PRODUCT550, _last_instruction_printed(NULL)551#endif // PRODUCT552{553PhaseTraceTime timeit(_t_compile);554_arena = Thread::current()->resource_area();555_env->set_compiler_data(this);556_exception_info_list = new ExceptionInfoList();557_implicit_exception_table.set_size(0);558compile_method();559if (bailed_out()) {560_env->record_method_not_compilable(bailout_msg(), !TieredCompilation);561if (is_profiling()) {562// Compilation failed, create MDO, which would signal the interpreter563// to start profiling on its own.564_method->ensure_method_data();565}566} else if (is_profiling()) {567ciMethodData *md = method->method_data_or_null();568if (md != NULL) {569md->set_would_profile(_would_profile);570}571}572}573574Compilation::~Compilation() {575_env->set_compiler_data(NULL);576}577578579void Compilation::add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers) {580#ifndef PRODUCT581if (PrintExceptionHandlers && Verbose) {582tty->print_cr(" added exception scope for pco %d", pco);583}584#endif585// Note: we do not have program counters for these exception handlers yet586exception_info_list()->push(new ExceptionInfo(pco, exception_handlers));587}588589590void Compilation::notice_inlined_method(ciMethod* method) {591_env->notice_inlined_method(method);592}593594595void Compilation::bailout(const char* msg) {596assert(msg != NULL, "bailout message must exist");597if (!bailed_out()) {598// keep first bailout message599if (PrintCompilation || PrintBailouts) tty->print_cr("compilation bailout: %s", msg);600_bailout_msg = msg;601}602}603604ciKlass* Compilation::cha_exact_type(ciType* type) {605if (type != NULL && type->is_loaded() && type->is_instance_klass()) {606ciInstanceKlass* ik = type->as_instance_klass();607assert(ik->exact_klass() == NULL, "no cha for final klass");608if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {609dependency_recorder()->assert_leaf_type(ik);610return ik;611}612}613return NULL;614}615616void Compilation::print_timers() {617// tty->print_cr(" Native methods : %6.3f s, Average : %2.3f", CompileBroker::_t_native_compilation.seconds(), CompileBroker::_t_native_compilation.seconds() / CompileBroker::_total_native_compile_count);618float total = timers[_t_setup].seconds() + timers[_t_buildIR].seconds() + timers[_t_emit_lir].seconds() + timers[_t_lir_schedule].seconds() + timers[_t_codeemit].seconds() + timers[_t_codeinstall].seconds();619620621tty->print_cr(" Detailed C1 Timings");622tty->print_cr(" Setup time: %6.3f s (%4.1f%%)", timers[_t_setup].seconds(), (timers[_t_setup].seconds() / total) * 100.0);623tty->print_cr(" Build IR: %6.3f s (%4.1f%%)", timers[_t_buildIR].seconds(), (timers[_t_buildIR].seconds() / total) * 100.0);624float t_optimizeIR = timers[_t_optimize_blocks].seconds() + timers[_t_optimize_null_checks].seconds();625tty->print_cr(" Optimize: %6.3f s (%4.1f%%)", t_optimizeIR, (t_optimizeIR / total) * 100.0);626tty->print_cr(" RCE: %6.3f s (%4.1f%%)", timers[_t_rangeCheckElimination].seconds(), (timers[_t_rangeCheckElimination].seconds() / total) * 100.0);627tty->print_cr(" Emit LIR: %6.3f s (%4.1f%%)", timers[_t_emit_lir].seconds(), (timers[_t_emit_lir].seconds() / total) * 100.0);628tty->print_cr(" LIR Gen: %6.3f s (%4.1f%%)", timers[_t_lirGeneration].seconds(), (timers[_t_lirGeneration].seconds() / total) * 100.0);629tty->print_cr(" Linear Scan: %6.3f s (%4.1f%%)", timers[_t_linearScan].seconds(), (timers[_t_linearScan].seconds() / total) * 100.0);630NOT_PRODUCT(LinearScan::print_timers(timers[_t_linearScan].seconds()));631tty->print_cr(" LIR Schedule: %6.3f s (%4.1f%%)", timers[_t_lir_schedule].seconds(), (timers[_t_lir_schedule].seconds() / total) * 100.0);632tty->print_cr(" Code Emission: %6.3f s (%4.1f%%)", timers[_t_codeemit].seconds(), (timers[_t_codeemit].seconds() / total) * 100.0);633tty->print_cr(" Code Installation: %6.3f s (%4.1f%%)", timers[_t_codeinstall].seconds(), (timers[_t_codeinstall].seconds() / total) * 100.0);634tty->print_cr(" Instruction Nodes: %6d nodes", totalInstructionNodes);635636NOT_PRODUCT(LinearScan::print_statistics());637}638639640#ifndef PRODUCT641void Compilation::compile_only_this_method() {642ResourceMark rm;643fileStream stream(fopen("c1_compile_only", "wt"));644stream.print_cr("# c1 compile only directives");645compile_only_this_scope(&stream, hir()->top_scope());646}647648649void Compilation::compile_only_this_scope(outputStream* st, IRScope* scope) {650st->print("CompileOnly=");651scope->method()->holder()->name()->print_symbol_on(st);652st->print(".");653scope->method()->name()->print_symbol_on(st);654st->cr();655}656657658void Compilation::exclude_this_method() {659fileStream stream(fopen(".hotspot_compiler", "at"));660stream.print("exclude ");661method()->holder()->name()->print_symbol_on(&stream);662stream.print(" ");663method()->name()->print_symbol_on(&stream);664stream.cr();665stream.cr();666}667#endif668669670