1 /*
   2  * Copyright (c) 1999, 2012, 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 #include "precompiled.hpp"
  26 #include "c1/c1_CFGPrinter.hpp"
  27 #include "c1/c1_Compilation.hpp"
  28 #include "c1/c1_IR.hpp"
  29 #include "c1/c1_LIRAssembler.hpp"
  30 #include "c1/c1_LinearScan.hpp"
  31 #include "c1/c1_MacroAssembler.hpp"
  32 #include "c1/c1_ValueMap.hpp"
  33 #include "c1/c1_ValueStack.hpp"
  34 #include "code/debugInfoRec.hpp"
  35 #include "compiler/compileLog.hpp"
  36 
  37 
  38 typedef enum {
  39   _t_compile,
  40   _t_setup,
  41   _t_optimizeIR,
  42   _t_buildIR,
  43   _t_emit_lir,
  44   _t_linearScan,
  45   _t_lirGeneration,
  46   _t_lir_schedule,
  47   _t_codeemit,
  48   _t_codeinstall,
  49   max_phase_timers
  50 } TimerName;
  51 
  52 static const char * timer_name[] = {
  53   "compile",
  54   "setup",
  55   "optimizeIR",
  56   "buildIR",
  57   "emit_lir",
  58   "linearScan",
  59   "lirGeneration",
  60   "lir_schedule",
  61   "codeemit",
  62   "codeinstall"
  63 };
  64 
  65 static elapsedTimer timers[max_phase_timers];
  66 static int totalInstructionNodes = 0;
  67 
  68 class PhaseTraceTime: public TraceTime {
  69  private:
  70   JavaThread* _thread;
  71   CompileLog* _log;
  72 
  73  public:
  74   PhaseTraceTime(TimerName timer)
  75   : TraceTime("", &timers[timer], CITime || CITimeEach, Verbose), _log(NULL) {
  76     if (Compilation::current() != NULL) {
  77       _log = Compilation::current()->log();
  78     }
  79 
  80     if (_log != NULL) {
  81       _log->begin_head("phase name='%s'", timer_name[timer]);
  82       _log->stamp();
  83       _log->end_head();
  84     }
  85   }
  86 
  87   ~PhaseTraceTime() {
  88     if (_log != NULL)
  89       _log->done("phase");
  90   }
  91 };
  92 
  93 // Implementation of Compilation
  94 
  95 
  96 #ifndef PRODUCT
  97 
  98 void Compilation::maybe_print_current_instruction() {
  99   if (_current_instruction != NULL && _last_instruction_printed != _current_instruction) {
 100     _last_instruction_printed = _current_instruction;
 101     _current_instruction->print_line();
 102   }
 103 }
 104 #endif // PRODUCT
 105 
 106 
 107 DebugInformationRecorder* Compilation::debug_info_recorder() const {
 108   return _env->debug_info();
 109 }
 110 
 111 
 112 Dependencies* Compilation::dependency_recorder() const {
 113   return _env->dependencies();
 114 }
 115 
 116 
 117 void Compilation::initialize() {
 118   // Use an oop recorder bound to the CI environment.
 119   // (The default oop recorder is ignorant of the CI.)
 120   OopRecorder* ooprec = new OopRecorder(_env->arena());
 121   _env->set_oop_recorder(ooprec);
 122   _env->set_debug_info(new DebugInformationRecorder(ooprec));
 123   debug_info_recorder()->set_oopmaps(new OopMapSet());
 124   _env->set_dependencies(new Dependencies(_env));
 125 }
 126 
 127 
 128 void Compilation::build_hir() {
 129   CHECK_BAILOUT();
 130 
 131   // setup ir
 132   CompileLog* log = this->log();
 133   if (log != NULL) {
 134     log->begin_head("parse method='%d' ",
 135                     log->identify(_method));
 136     log->stamp();
 137     log->end_head();
 138   }
 139   _hir = new IR(this, method(), osr_bci());
 140   if (log)  log->done("parse");
 141   if (!_hir->is_valid()) {
 142     bailout("invalid parsing");
 143     return;
 144   }
 145 
 146 #ifndef PRODUCT
 147   if (PrintCFGToFile) {
 148     CFGPrinter::print_cfg(_hir, "After Generation of HIR", true, false);
 149   }
 150 #endif
 151 
 152 #ifndef PRODUCT
 153   if (PrintCFG || PrintCFG0) { tty->print_cr("CFG after parsing"); _hir->print(true); }
 154   if (PrintIR  || PrintIR0 ) { tty->print_cr("IR after parsing"); _hir->print(false); }
 155 #endif
 156 
 157   _hir->verify();
 158 
 159   if (UseC1Optimizations) {
 160     NEEDS_CLEANUP
 161     // optimization
 162     PhaseTraceTime timeit(_t_optimizeIR);
 163 
 164     _hir->optimize();
 165   }
 166 
 167   _hir->verify();
 168 
 169   _hir->split_critical_edges();
 170 
 171 #ifndef PRODUCT
 172   if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after optimizations"); _hir->print(true); }
 173   if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after optimizations"); _hir->print(false); }
 174 #endif
 175 
 176   _hir->verify();
 177 
 178   // compute block ordering for code generation
 179   // the control flow must not be changed from here on
 180   _hir->compute_code();
 181 
 182   if (UseGlobalValueNumbering) {
 183     ResourceMark rm;
 184     int instructions = Instruction::number_of_instructions();
 185     GlobalValueNumbering gvn(_hir);
 186     assert(instructions == Instruction::number_of_instructions(),
 187            "shouldn't have created an instructions");
 188   }
 189 
 190   // compute use counts after global value numbering
 191   _hir->compute_use_counts();
 192 
 193 #ifndef PRODUCT
 194   if (PrintCFG || PrintCFG2) { tty->print_cr("CFG before code generation"); _hir->code()->print(true); }
 195   if (PrintIR  || PrintIR2 ) { tty->print_cr("IR before code generation"); _hir->code()->print(false, true); }
 196 #endif
 197 
 198   _hir->verify();
 199 }
 200 
 201 
 202 void Compilation::emit_lir() {
 203   CHECK_BAILOUT();
 204 
 205   LIRGenerator gen(this, method());
 206   {
 207     PhaseTraceTime timeit(_t_lirGeneration);
 208     hir()->iterate_linear_scan_order(&gen);
 209   }
 210 
 211   CHECK_BAILOUT();
 212 
 213   {
 214     PhaseTraceTime timeit(_t_linearScan);
 215 
 216     LinearScan* allocator = new LinearScan(hir(), &gen, frame_map());
 217     set_allocator(allocator);
 218     // Assign physical registers to LIR operands using a linear scan algorithm.
 219     allocator->do_linear_scan();
 220     CHECK_BAILOUT();
 221 
 222     _max_spills = allocator->max_spills();
 223   }
 224 
 225   if (BailoutAfterLIR) {
 226     if (PrintLIR && !bailed_out()) {
 227       print_LIR(hir()->code());
 228     }
 229     bailout("Bailing out because of -XX:+BailoutAfterLIR");
 230   }
 231 }
 232 
 233 
 234 void Compilation::emit_code_epilog(LIR_Assembler* assembler) {
 235   CHECK_BAILOUT();
 236 
 237   CodeOffsets* code_offsets = assembler->offsets();
 238 
 239   // generate code or slow cases
 240   assembler->emit_slow_case_stubs();
 241   CHECK_BAILOUT();
 242 
 243   // generate exception adapters
 244   assembler->emit_exception_entries(exception_info_list());
 245   CHECK_BAILOUT();
 246 
 247   // Generate code for exception handler.
 248   code_offsets->set_value(CodeOffsets::Exceptions, assembler->emit_exception_handler());
 249   CHECK_BAILOUT();
 250 
 251   // Generate code for deopt handler.
 252   code_offsets->set_value(CodeOffsets::Deopt, assembler->emit_deopt_handler());
 253   CHECK_BAILOUT();
 254 
 255   // Emit the MethodHandle deopt handler code (if required).
 256   if (has_method_handle_invokes()) {
 257     // We can use the same code as for the normal deopt handler, we
 258     // just need a different entry point address.
 259     code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler());
 260     CHECK_BAILOUT();
 261   }
 262 
 263   // Emit the handler to remove the activation from the stack and
 264   // dispatch to the caller.
 265   offsets()->set_value(CodeOffsets::UnwindHandler, assembler->emit_unwind_handler());
 266 
 267   // done
 268   masm()->flush();
 269 }
 270 
 271 
 272 bool Compilation::setup_code_buffer(CodeBuffer* code, int call_stub_estimate) {
 273   // Preinitialize the consts section to some large size:
 274   int locs_buffer_size = 20 * (relocInfo::length_limit + sizeof(relocInfo));
 275   char* locs_buffer = NEW_RESOURCE_ARRAY(char, locs_buffer_size);
 276   code->insts()->initialize_shared_locs((relocInfo*)locs_buffer,
 277                                         locs_buffer_size / sizeof(relocInfo));
 278   code->initialize_consts_size(Compilation::desired_max_constant_size());
 279   // Call stubs + two deopt handlers (regular and MH) + exception handler
 280   int stub_size = (call_stub_estimate * LIR_Assembler::call_stub_size) +
 281                    LIR_Assembler::exception_handler_size +
 282                    (2 * LIR_Assembler::deopt_handler_size);
 283   if (stub_size >= code->insts_capacity()) return false;
 284   code->initialize_stubs_size(stub_size);
 285   return true;
 286 }
 287 
 288 
 289 int Compilation::emit_code_body() {
 290   // emit code
 291   if (!setup_code_buffer(code(), allocator()->num_calls())) {
 292     BAILOUT_("size requested greater than avail code buffer size", 0);
 293   }
 294   code()->initialize_oop_recorder(env()->oop_recorder());
 295 
 296   _masm = new C1_MacroAssembler(code());
 297   _masm->set_oop_recorder(env()->oop_recorder());
 298 
 299   LIR_Assembler lir_asm(this);
 300 
 301   lir_asm.emit_code(hir()->code());
 302   CHECK_BAILOUT_(0);
 303 
 304   emit_code_epilog(&lir_asm);
 305   CHECK_BAILOUT_(0);
 306 
 307   generate_exception_handler_table();
 308 
 309 #ifndef PRODUCT
 310   if (PrintExceptionHandlers && Verbose) {
 311     exception_handler_table()->print();
 312   }
 313 #endif /* PRODUCT */
 314 
 315   return frame_map()->framesize();
 316 }
 317 
 318 
 319 int Compilation::compile_java_method() {
 320   assert(!method()->is_native(), "should not reach here");
 321 
 322   if (BailoutOnExceptionHandlers) {
 323     if (method()->has_exception_handlers()) {
 324       bailout("linear scan can't handle exception handlers");
 325     }
 326   }
 327 
 328   CHECK_BAILOUT_(no_frame_size);
 329 
 330   if (is_profiling() && !method()->ensure_method_data()) {
 331     BAILOUT_("mdo allocation failed", no_frame_size);
 332   }
 333 
 334   {
 335     PhaseTraceTime timeit(_t_buildIR);
 336     build_hir();
 337   }
 338   if (BailoutAfterHIR) {
 339     BAILOUT_("Bailing out because of -XX:+BailoutAfterHIR", no_frame_size);
 340   }
 341 
 342 
 343   {
 344     PhaseTraceTime timeit(_t_emit_lir);
 345 
 346     _frame_map = new FrameMap(method(), hir()->number_of_locks(), MAX2(4, hir()->max_stack()));
 347     emit_lir();
 348   }
 349   CHECK_BAILOUT_(no_frame_size);
 350 
 351   {
 352     PhaseTraceTime timeit(_t_codeemit);
 353     return emit_code_body();
 354   }
 355 }
 356 
 357 void Compilation::install_code(int frame_size) {
 358   // frame_size is in 32-bit words so adjust it intptr_t words
 359   assert(frame_size == frame_map()->framesize(), "must match");
 360   assert(in_bytes(frame_map()->framesize_in_bytes()) % sizeof(intptr_t) == 0, "must be at least pointer aligned");
 361   _env->register_method(
 362     method(),
 363     osr_bci(),
 364     &_offsets,
 365     in_bytes(_frame_map->sp_offset_for_orig_pc()),
 366     code(),
 367     in_bytes(frame_map()->framesize_in_bytes()) / sizeof(intptr_t),
 368     debug_info_recorder()->_oopmaps,
 369     exception_handler_table(),
 370     implicit_exception_table(),
 371     compiler(),
 372     _env->comp_level(),
 373     has_unsafe_access(),
 374     SharedRuntime::is_wide_vector(max_vector_size())
 375   );
 376 }
 377 
 378 
 379 void Compilation::compile_method() {
 380   // setup compilation
 381   initialize();
 382 
 383   if (!method()->can_be_compiled()) {
 384     // Prevent race condition 6328518.
 385     // This can happen if the method is obsolete or breakpointed.
 386     bailout("Bailing out because method is not compilable");
 387     return;
 388   }
 389 
 390   if (_env->jvmti_can_hotswap_or_post_breakpoint()) {
 391     // We can assert evol_method because method->can_be_compiled is true.
 392     dependency_recorder()->assert_evol_method(method());
 393   }
 394 
 395   if (method()->break_at_execute()) {
 396     BREAKPOINT;
 397   }
 398 
 399 #ifndef PRODUCT
 400   if (PrintCFGToFile) {
 401     CFGPrinter::print_compilation(this);
 402   }
 403 #endif
 404 
 405   // compile method
 406   int frame_size = compile_java_method();
 407 
 408   // bailout if method couldn't be compiled
 409   // Note: make sure we mark the method as not compilable!
 410   CHECK_BAILOUT();
 411 
 412   if (InstallMethods) {
 413     // install code
 414     PhaseTraceTime timeit(_t_codeinstall);
 415     install_code(frame_size);
 416   }
 417 
 418   if (log() != NULL) // Print code cache state into compiler log
 419     log()->code_cache_state();
 420 
 421   totalInstructionNodes += Instruction::number_of_instructions();
 422 }
 423 
 424 
 425 void Compilation::generate_exception_handler_table() {
 426   // Generate an ExceptionHandlerTable from the exception handler
 427   // information accumulated during the compilation.
 428   ExceptionInfoList* info_list = exception_info_list();
 429 
 430   if (info_list->length() == 0) {
 431     return;
 432   }
 433 
 434   // allocate some arrays for use by the collection code.
 435   const int num_handlers = 5;
 436   GrowableArray<intptr_t>* bcis = new GrowableArray<intptr_t>(num_handlers);
 437   GrowableArray<intptr_t>* scope_depths = new GrowableArray<intptr_t>(num_handlers);
 438   GrowableArray<intptr_t>* pcos = new GrowableArray<intptr_t>(num_handlers);
 439 
 440   for (int i = 0; i < info_list->length(); i++) {
 441     ExceptionInfo* info = info_list->at(i);
 442     XHandlers* handlers = info->exception_handlers();
 443 
 444     // empty the arrays
 445     bcis->trunc_to(0);
 446     scope_depths->trunc_to(0);
 447     pcos->trunc_to(0);
 448 
 449     for (int i = 0; i < handlers->length(); i++) {
 450       XHandler* handler = handlers->handler_at(i);
 451       assert(handler->entry_pco() != -1, "must have been generated");
 452 
 453       int e = bcis->find(handler->handler_bci());
 454       if (e >= 0 && scope_depths->at(e) == handler->scope_count()) {
 455         // two different handlers are declared to dispatch to the same
 456         // catch bci.  During parsing we created edges for each
 457         // handler but we really only need one.  The exception handler
 458         // table will also get unhappy if we try to declare both since
 459         // it's nonsensical.  Just skip this handler.
 460         continue;
 461       }
 462 
 463       bcis->append(handler->handler_bci());
 464       if (handler->handler_bci() == -1) {
 465         // insert a wildcard handler at scope depth 0 so that the
 466         // exception lookup logic with find it.
 467         scope_depths->append(0);
 468       } else {
 469         scope_depths->append(handler->scope_count());
 470     }
 471       pcos->append(handler->entry_pco());
 472 
 473       // stop processing once we hit a catch any
 474       if (handler->is_catch_all()) {
 475         assert(i == handlers->length() - 1, "catch all must be last handler");
 476   }
 477     }
 478     exception_handler_table()->add_subtable(info->pco(), bcis, scope_depths, pcos);
 479   }
 480 }
 481 
 482 
 483 Compilation::Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* method,
 484                          int osr_bci, BufferBlob* buffer_blob)
 485 : _compiler(compiler)
 486 , _env(env)
 487 , _log(env->log())
 488 , _method(method)
 489 , _osr_bci(osr_bci)
 490 , _hir(NULL)
 491 , _max_spills(-1)
 492 , _frame_map(NULL)
 493 , _masm(NULL)
 494 , _has_exception_handlers(false)
 495 , _has_fpu_code(true)   // pessimistic assumption
 496 , _would_profile(false)
 497 , _has_unsafe_access(false)
 498 , _has_method_handle_invokes(false)
 499 , _bailout_msg(NULL)
 500 , _exception_info_list(NULL)
 501 , _allocator(NULL)
 502 , _next_id(0)
 503 , _next_block_id(0)
 504 , _code(buffer_blob)
 505 , _current_instruction(NULL)
 506 #ifndef PRODUCT
 507 , _last_instruction_printed(NULL)
 508 #endif // PRODUCT
 509 {
 510   PhaseTraceTime timeit(_t_compile);
 511   _arena = Thread::current()->resource_area();
 512   _env->set_compiler_data(this);
 513   _exception_info_list = new ExceptionInfoList();
 514   _implicit_exception_table.set_size(0);
 515   compile_method();
 516   if (bailed_out()) {
 517     _env->record_method_not_compilable(bailout_msg(), !TieredCompilation);
 518     if (is_profiling()) {
 519       // Compilation failed, create MDO, which would signal the interpreter
 520       // to start profiling on its own.
 521       _method->ensure_method_data();
 522     }
 523   } else if (is_profiling()) {
 524     ciMethodData *md = method->method_data_or_null();
 525     if (md != NULL) {
 526       md->set_would_profile(_would_profile);
 527     }
 528   }
 529 }
 530 
 531 Compilation::~Compilation() {
 532   _env->set_compiler_data(NULL);
 533 }
 534 
 535 
 536 void Compilation::add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers) {
 537 #ifndef PRODUCT
 538   if (PrintExceptionHandlers && Verbose) {
 539     tty->print_cr("  added exception scope for pco %d", pco);
 540   }
 541 #endif
 542   // Note: we do not have program counters for these exception handlers yet
 543   exception_info_list()->push(new ExceptionInfo(pco, exception_handlers));
 544 }
 545 
 546 
 547 void Compilation::notice_inlined_method(ciMethod* method) {
 548   _env->notice_inlined_method(method);
 549 }
 550 
 551 
 552 void Compilation::bailout(const char* msg) {
 553   assert(msg != NULL, "bailout message must exist");
 554   if (!bailed_out()) {
 555     // keep first bailout message
 556     if (PrintCompilation || PrintBailouts) tty->print_cr("compilation bailout: %s", msg);
 557     _bailout_msg = msg;
 558   }
 559 }
 560 
 561 
 562 void Compilation::print_timers() {
 563   // 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);
 564   float 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();
 565 
 566 
 567   tty->print_cr("    Detailed C1 Timings");
 568   tty->print_cr("       Setup time:        %6.3f s (%4.1f%%)",    timers[_t_setup].seconds(),           (timers[_t_setup].seconds() / total) * 100.0);
 569   tty->print_cr("       Build IR:          %6.3f s (%4.1f%%)",    timers[_t_buildIR].seconds(),         (timers[_t_buildIR].seconds() / total) * 100.0);
 570   tty->print_cr("         Optimize:           %6.3f s (%4.1f%%)", timers[_t_optimizeIR].seconds(),      (timers[_t_optimizeIR].seconds() / total) * 100.0);
 571   tty->print_cr("       Emit LIR:          %6.3f s (%4.1f%%)",    timers[_t_emit_lir].seconds(),        (timers[_t_emit_lir].seconds() / total) * 100.0);
 572   tty->print_cr("         LIR Gen:          %6.3f s (%4.1f%%)",   timers[_t_lirGeneration].seconds(), (timers[_t_lirGeneration].seconds() / total) * 100.0);
 573   tty->print_cr("         Linear Scan:      %6.3f s (%4.1f%%)",   timers[_t_linearScan].seconds(),    (timers[_t_linearScan].seconds() / total) * 100.0);
 574   NOT_PRODUCT(LinearScan::print_timers(timers[_t_linearScan].seconds()));
 575   tty->print_cr("       LIR Schedule:      %6.3f s (%4.1f%%)",    timers[_t_lir_schedule].seconds(),  (timers[_t_lir_schedule].seconds() / total) * 100.0);
 576   tty->print_cr("       Code Emission:     %6.3f s (%4.1f%%)",    timers[_t_codeemit].seconds(),        (timers[_t_codeemit].seconds() / total) * 100.0);
 577   tty->print_cr("       Code Installation: %6.3f s (%4.1f%%)",    timers[_t_codeinstall].seconds(),     (timers[_t_codeinstall].seconds() / total) * 100.0);
 578   tty->print_cr("       Instruction Nodes: %6d nodes",    totalInstructionNodes);
 579 
 580   NOT_PRODUCT(LinearScan::print_statistics());
 581 }
 582 
 583 
 584 #ifndef PRODUCT
 585 void Compilation::compile_only_this_method() {
 586   ResourceMark rm;
 587   fileStream stream(fopen("c1_compile_only", "wt"));
 588   stream.print_cr("# c1 compile only directives");
 589   compile_only_this_scope(&stream, hir()->top_scope());
 590 }
 591 
 592 
 593 void Compilation::compile_only_this_scope(outputStream* st, IRScope* scope) {
 594   st->print("CompileOnly=");
 595   scope->method()->holder()->name()->print_symbol_on(st);
 596   st->print(".");
 597   scope->method()->name()->print_symbol_on(st);
 598   st->cr();
 599 }
 600 
 601 
 602 void Compilation::exclude_this_method() {
 603   fileStream stream(fopen(".hotspot_compiler", "at"));
 604   stream.print("exclude ");
 605   method()->holder()->name()->print_symbol_on(&stream);
 606   stream.print(" ");
 607   method()->name()->print_symbol_on(&stream);
 608   stream.cr();
 609   stream.cr();
 610 }
 611 #endif