hotspot/src/share/vm/shark/sharkCompiler.cpp
changeset 6187 4fa7845f7c14
child 7397 5b173b4ca846
equal deleted inserted replaced
6186:7eef4cda471c 6187:4fa7845f7c14
       
     1 /*
       
     2  * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
       
     3  * Copyright 2008, 2009, 2010 Red Hat, Inc.
       
     4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     5  *
       
     6  * This code is free software; you can redistribute it and/or modify it
       
     7  * under the terms of the GNU General Public License version 2 only, as
       
     8  * published by the Free Software Foundation.
       
     9  *
       
    10  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    13  * version 2 for more details (a copy is included in the LICENSE file that
       
    14  * accompanied this code).
       
    15  *
       
    16  * You should have received a copy of the GNU General Public License version
       
    17  * 2 along with this work; if not, write to the Free Software Foundation,
       
    18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    19  *
       
    20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    21  * or visit www.oracle.com if you need additional information or have any
       
    22  * questions.
       
    23  *
       
    24  */
       
    25 
       
    26 #include "incls/_precompiled.incl"
       
    27 #include "incls/_sharkCompiler.cpp.incl"
       
    28 
       
    29 #include <fnmatch.h>
       
    30 
       
    31 using namespace llvm;
       
    32 
       
    33 #if SHARK_LLVM_VERSION >= 27
       
    34 namespace {
       
    35   cl::opt<std::string>
       
    36   MCPU("mcpu");
       
    37 
       
    38   cl::list<std::string>
       
    39   MAttrs("mattr",
       
    40          cl::CommaSeparated);
       
    41 }
       
    42 #endif
       
    43 
       
    44 SharkCompiler::SharkCompiler()
       
    45   : AbstractCompiler() {
       
    46   // Create the lock to protect the memory manager and execution engine
       
    47   _execution_engine_lock = new Monitor(Mutex::leaf, "SharkExecutionEngineLock");
       
    48   MutexLocker locker(execution_engine_lock());
       
    49 
       
    50   // Make LLVM safe for multithreading
       
    51   if (!llvm_start_multithreaded())
       
    52     fatal("llvm_start_multithreaded() failed");
       
    53 
       
    54   // Initialize the native target
       
    55   InitializeNativeTarget();
       
    56 
       
    57   // Create the two contexts which we'll use
       
    58   _normal_context = new SharkContext("normal");
       
    59   _native_context = new SharkContext("native");
       
    60 
       
    61   // Create the memory manager
       
    62   _memory_manager = new SharkMemoryManager();
       
    63 
       
    64 #if SHARK_LLVM_VERSION >= 27
       
    65   // Finetune LLVM for the current host CPU.
       
    66   StringMap<bool> Features;
       
    67   bool gotCpuFeatures = llvm::sys::getHostCPUFeatures(Features);
       
    68   std::string cpu("-mcpu=" + llvm::sys::getHostCPUName());
       
    69 
       
    70   std::vector<const char*> args;
       
    71   args.push_back(""); // program name
       
    72   args.push_back(cpu.c_str());
       
    73 
       
    74   std::string mattr("-mattr=");
       
    75   if(gotCpuFeatures){
       
    76     for(StringMap<bool>::iterator I = Features.begin(),
       
    77       E = Features.end(); I != E; ++I){
       
    78       if(I->second){
       
    79         std::string attr(I->first());
       
    80         mattr+="+"+attr+",";
       
    81       }
       
    82     }
       
    83     args.push_back(mattr.c_str());
       
    84   }
       
    85 
       
    86   args.push_back(0);  // terminator
       
    87   cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]);
       
    88 
       
    89   // Create the JIT
       
    90   std::string ErrorMsg;
       
    91 
       
    92   EngineBuilder builder(_normal_context->module());
       
    93   builder.setMCPU(MCPU);
       
    94   builder.setMAttrs(MAttrs);
       
    95   builder.setJITMemoryManager(memory_manager());
       
    96   builder.setEngineKind(EngineKind::JIT);
       
    97   builder.setErrorStr(&ErrorMsg);
       
    98   _execution_engine = builder.create();
       
    99 
       
   100   if (!execution_engine()) {
       
   101     if (!ErrorMsg.empty())
       
   102       printf("Error while creating Shark JIT: %s\n",ErrorMsg.c_str());
       
   103     else
       
   104       printf("Unknown error while creating Shark JIT\n");
       
   105     exit(1);
       
   106   }
       
   107 
       
   108   execution_engine()->addModule(
       
   109     _native_context->module());
       
   110 #else
       
   111   _execution_engine = ExecutionEngine::createJIT(
       
   112     _normal_context->module_provider(),
       
   113     NULL, memory_manager(), CodeGenOpt::Default);
       
   114   execution_engine()->addModuleProvider(
       
   115     _native_context->module_provider());
       
   116 #endif
       
   117 
       
   118   // All done
       
   119   mark_initialized();
       
   120 }
       
   121 
       
   122 void SharkCompiler::initialize() {
       
   123   ShouldNotCallThis();
       
   124 }
       
   125 
       
   126 void SharkCompiler::compile_method(ciEnv*    env,
       
   127                                    ciMethod* target,
       
   128                                    int       entry_bci) {
       
   129   assert(is_initialized(), "should be");
       
   130   ResourceMark rm;
       
   131   const char *name = methodname(
       
   132     target->holder()->name()->as_utf8(), target->name()->as_utf8());
       
   133 
       
   134   // Do the typeflow analysis
       
   135   ciTypeFlow *flow;
       
   136   if (entry_bci == InvocationEntryBci)
       
   137     flow = target->get_flow_analysis();
       
   138   else
       
   139     flow = target->get_osr_flow_analysis(entry_bci);
       
   140   if (flow->failing())
       
   141     return;
       
   142   if (SharkPrintTypeflowOf != NULL) {
       
   143     if (!fnmatch(SharkPrintTypeflowOf, name, 0))
       
   144       flow->print_on(tty);
       
   145   }
       
   146 
       
   147   // Create the recorders
       
   148   Arena arena;
       
   149   env->set_oop_recorder(new OopRecorder(&arena));
       
   150   OopMapSet oopmaps;
       
   151   env->set_debug_info(new DebugInformationRecorder(env->oop_recorder()));
       
   152   env->debug_info()->set_oopmaps(&oopmaps);
       
   153   env->set_dependencies(new Dependencies(env));
       
   154 
       
   155   // Create the code buffer and builder
       
   156   CodeBuffer hscb("Shark", 256 * K, 64 * K);
       
   157   hscb.initialize_oop_recorder(env->oop_recorder());
       
   158   MacroAssembler *masm = new MacroAssembler(&hscb);
       
   159   SharkCodeBuffer cb(masm);
       
   160   SharkBuilder builder(&cb);
       
   161 
       
   162   // Emit the entry point
       
   163   SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry));
       
   164 
       
   165   // Build the LLVM IR for the method
       
   166   Function *function = SharkFunction::build(env, &builder, flow, name);
       
   167 
       
   168   // Generate native code.  It's unpleasant that we have to drop into
       
   169   // the VM to do this -- it blocks safepoints -- but I can't see any
       
   170   // other way to handle the locking.
       
   171   {
       
   172     ThreadInVMfromNative tiv(JavaThread::current());
       
   173     generate_native_code(entry, function, name);
       
   174   }
       
   175 
       
   176   // Install the method into the VM
       
   177   CodeOffsets offsets;
       
   178   offsets.set_value(CodeOffsets::Deopt, 0);
       
   179   offsets.set_value(CodeOffsets::Exceptions, 0);
       
   180   offsets.set_value(CodeOffsets::Verified_Entry,
       
   181                     target->is_static() ? 0 : wordSize);
       
   182 
       
   183   ExceptionHandlerTable handler_table;
       
   184   ImplicitExceptionTable inc_table;
       
   185 
       
   186   env->register_method(target,
       
   187                        entry_bci,
       
   188                        &offsets,
       
   189                        0,
       
   190                        &hscb,
       
   191                        0,
       
   192                        &oopmaps,
       
   193                        &handler_table,
       
   194                        &inc_table,
       
   195                        this,
       
   196                        env->comp_level(),
       
   197                        false,
       
   198                        false);
       
   199 }
       
   200 
       
   201 nmethod* SharkCompiler::generate_native_wrapper(MacroAssembler* masm,
       
   202                                                 methodHandle    target,
       
   203                                                 BasicType*      arg_types,
       
   204                                                 BasicType       return_type) {
       
   205   assert(is_initialized(), "should be");
       
   206   ResourceMark rm;
       
   207   const char *name = methodname(
       
   208     target->klass_name()->as_utf8(), target->name()->as_utf8());
       
   209 
       
   210   // Create the code buffer and builder
       
   211   SharkCodeBuffer cb(masm);
       
   212   SharkBuilder builder(&cb);
       
   213 
       
   214   // Emit the entry point
       
   215   SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry));
       
   216 
       
   217   // Build the LLVM IR for the method
       
   218   SharkNativeWrapper *wrapper = SharkNativeWrapper::build(
       
   219     &builder, target, name, arg_types, return_type);
       
   220 
       
   221   // Generate native code
       
   222   generate_native_code(entry, wrapper->function(), name);
       
   223 
       
   224   // Return the nmethod for installation in the VM
       
   225   return nmethod::new_native_nmethod(target,
       
   226                                      masm->code(),
       
   227                                      0,
       
   228                                      0,
       
   229                                      wrapper->frame_size(),
       
   230                                      wrapper->receiver_offset(),
       
   231                                      wrapper->lock_offset(),
       
   232                                      wrapper->oop_maps());
       
   233 }
       
   234 
       
   235 void SharkCompiler::generate_native_code(SharkEntry* entry,
       
   236                                          Function*   function,
       
   237                                          const char* name) {
       
   238   // Print the LLVM bitcode, if requested
       
   239   if (SharkPrintBitcodeOf != NULL) {
       
   240     if (!fnmatch(SharkPrintBitcodeOf, name, 0))
       
   241       function->dump();
       
   242   }
       
   243 
       
   244   // Compile to native code
       
   245   address code = NULL;
       
   246   context()->add_function(function);
       
   247   {
       
   248     MutexLocker locker(execution_engine_lock());
       
   249     free_queued_methods();
       
   250 
       
   251     if (SharkPrintAsmOf != NULL) {
       
   252 #if SHARK_LLVM_VERSION >= 27
       
   253 #ifndef NDEBUG
       
   254       if (!fnmatch(SharkPrintAsmOf, name, 0)) {
       
   255         llvm::SetCurrentDebugType(X86_ONLY("x86-emitter") NOT_X86("jit"));
       
   256         llvm::DebugFlag = true;
       
   257       }
       
   258       else {
       
   259         llvm::SetCurrentDebugType("");
       
   260         llvm::DebugFlag = false;
       
   261       }
       
   262 #endif // !NDEBUG
       
   263 #else
       
   264       // NB you need to patch LLVM with http://tinyurl.com/yf3baln for this
       
   265       std::vector<const char*> args;
       
   266       args.push_back(""); // program name
       
   267       if (!fnmatch(SharkPrintAsmOf, name, 0))
       
   268         args.push_back("-debug-only=x86-emitter");
       
   269       else
       
   270         args.push_back("-debug-only=none");
       
   271       args.push_back(0);  // terminator
       
   272       cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]);
       
   273 #endif // SHARK_LLVM_VERSION
       
   274     }
       
   275     memory_manager()->set_entry_for_function(function, entry);
       
   276     code = (address) execution_engine()->getPointerToFunction(function);
       
   277   }
       
   278   entry->set_entry_point(code);
       
   279   entry->set_function(function);
       
   280   entry->set_context(context());
       
   281   address code_start = entry->code_start();
       
   282   address code_limit = entry->code_limit();
       
   283 
       
   284   // Register generated code for profiling, etc
       
   285   if (JvmtiExport::should_post_dynamic_code_generated())
       
   286     JvmtiExport::post_dynamic_code_generated(name, code_start, code_limit);
       
   287 
       
   288   // Print debug information, if requested
       
   289   if (SharkTraceInstalls) {
       
   290     tty->print_cr(
       
   291       " [%p-%p): %s (%d bytes code)",
       
   292       code_start, code_limit, name, code_limit - code_start);
       
   293   }
       
   294 }
       
   295 
       
   296 void SharkCompiler::free_compiled_method(address code) {
       
   297   // This method may only be called when the VM is at a safepoint.
       
   298   // All _thread_in_vm threads will be waiting for the safepoint to
       
   299   // finish with the exception of the VM thread, so we can consider
       
   300   // ourself the owner of the execution engine lock even though we
       
   301   // can't actually acquire it at this time.
       
   302   assert(Thread::current()->is_VM_thread(), "must be called by VM thread");
       
   303   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
       
   304 
       
   305   SharkEntry *entry = (SharkEntry *) code;
       
   306   entry->context()->push_to_free_queue(entry->function());
       
   307 }
       
   308 
       
   309 void SharkCompiler::free_queued_methods() {
       
   310   // The free queue is protected by the execution engine lock
       
   311   assert(execution_engine_lock()->owned_by_self(), "should be");
       
   312 
       
   313   while (true) {
       
   314     Function *function = context()->pop_from_free_queue();
       
   315     if (function == NULL)
       
   316       break;
       
   317 
       
   318     execution_engine()->freeMachineCodeForFunction(function);
       
   319     function->eraseFromParent();
       
   320   }
       
   321 }
       
   322 
       
   323 const char* SharkCompiler::methodname(const char* klass, const char* method) {
       
   324   char *buf = NEW_RESOURCE_ARRAY(char, strlen(klass) + 2 + strlen(method) + 1);
       
   325 
       
   326   char *dst = buf;
       
   327   for (const char *c = klass; *c; c++) {
       
   328     if (*c == '/')
       
   329       *(dst++) = '.';
       
   330     else
       
   331       *(dst++) = *c;
       
   332   }
       
   333   *(dst++) = ':';
       
   334   *(dst++) = ':';
       
   335   for (const char *c = method; *c; c++) {
       
   336     *(dst++) = *c;
       
   337   }
       
   338   *(dst++) = '\0';
       
   339   return buf;
       
   340 }