1 /* 2 * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. 3 * Copyright 2008, 2009, 2010, 2011 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 "precompiled.hpp" 27 #include "ci/ciEnv.hpp" 28 #include "ci/ciMethod.hpp" 29 #include "code/debugInfoRec.hpp" 30 #include "code/dependencies.hpp" 31 #include "code/exceptionHandlerTable.hpp" 32 #include "code/oopRecorder.hpp" 33 #include "compiler/abstractCompiler.hpp" 34 #include "compiler/oopMap.hpp" 35 #include "memory/resourceArea.hpp" 36 #include "shark/llvmHeaders.hpp" 37 #include "shark/sharkBuilder.hpp" 38 #include "shark/sharkCodeBuffer.hpp" 39 #include "shark/sharkCompiler.hpp" 40 #include "shark/sharkContext.hpp" 41 #include "shark/sharkEntry.hpp" 42 #include "shark/sharkFunction.hpp" 43 #include "shark/sharkMemoryManager.hpp" 44 #include "shark/sharkNativeWrapper.hpp" 45 #include "shark/shark_globals.hpp" 46 #include "utilities/debug.hpp" 47 48 #include <fnmatch.h> 49 50 using namespace llvm; 51 52 namespace { 53 cl::opt<std::string> 54 MCPU("mcpu"); 55 56 cl::list<std::string> 57 MAttrs("mattr", 58 cl::CommaSeparated); 59 } 60 61 SharkCompiler::SharkCompiler() 62 : AbstractCompiler(shark) { 63 // Create the lock to protect the memory manager and execution engine 64 _execution_engine_lock = new Monitor(Mutex::leaf, "SharkExecutionEngineLock"); 65 MutexLocker locker(execution_engine_lock()); 66 67 // Make LLVM safe for multithreading 68 if (!llvm_start_multithreaded()) 69 fatal("llvm_start_multithreaded() failed"); 70 71 // Initialize the native target 72 InitializeNativeTarget(); 73 74 // MCJIT require a native AsmPrinter 75 InitializeNativeTargetAsmPrinter(); 76 77 // Create the two contexts which we'll use 78 _normal_context = new SharkContext("normal"); 79 _native_context = new SharkContext("native"); 80 81 // Create the memory manager 82 _memory_manager = new SharkMemoryManager(); 83 84 // Finetune LLVM for the current host CPU. 85 StringMap<bool> Features; 86 bool gotCpuFeatures = llvm::sys::getHostCPUFeatures(Features); 87 std::string cpu("-mcpu=" + llvm::sys::getHostCPUName()); 88 89 std::vector<const char*> args; 90 args.push_back(""); // program name 91 args.push_back(cpu.c_str()); 92 93 std::string mattr("-mattr="); 94 if(gotCpuFeatures){ 95 for(StringMap<bool>::iterator I = Features.begin(), 96 E = Features.end(); I != E; ++I){ 97 if(I->second){ 98 std::string attr(I->first()); 99 mattr+="+"+attr+","; 100 } 101 } 102 args.push_back(mattr.c_str()); 103 } 104 105 args.push_back(0); // terminator 106 cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]); 107 108 // Create the JIT 109 std::string ErrorMsg; 110 111 EngineBuilder builder(_normal_context->module()); 112 builder.setMCPU(MCPU); 113 builder.setMAttrs(MAttrs); 114 builder.setJITMemoryManager(memory_manager()); 115 builder.setEngineKind(EngineKind::JIT); 116 builder.setErrorStr(&ErrorMsg); 117 if (! fnmatch(SharkOptimizationLevel, "None", 0)) { 118 tty->print_cr("Shark optimization level set to: None"); 119 builder.setOptLevel(llvm::CodeGenOpt::None); 120 } else if (! fnmatch(SharkOptimizationLevel, "Less", 0)) { 121 tty->print_cr("Shark optimization level set to: Less"); 122 builder.setOptLevel(llvm::CodeGenOpt::Less); 123 } else if (! fnmatch(SharkOptimizationLevel, "Aggressive", 0)) { 124 tty->print_cr("Shark optimization level set to: Aggressive"); 125 builder.setOptLevel(llvm::CodeGenOpt::Aggressive); 126 } // else Default is selected by, well, default :-) 127 _execution_engine = builder.create(); 128 129 if (!execution_engine()) { 130 if (!ErrorMsg.empty()) 131 printf("Error while creating Shark JIT: %s\n",ErrorMsg.c_str()); 132 else 133 printf("Unknown error while creating Shark JIT\n"); 134 exit(1); 135 } 136 137 execution_engine()->addModule(_native_context->module()); 138 139 // All done 140 set_state(initialized); 141 } 142 143 void SharkCompiler::initialize() { 144 ShouldNotCallThis(); 145 } 146 147 void SharkCompiler::compile_method(ciEnv* env, 148 ciMethod* target, 149 int entry_bci, 150 DirectiveSet* directive) { 151 assert(is_initialized(), "should be"); 152 ResourceMark rm; 153 const char *name = methodname( 154 target->holder()->name()->as_utf8(), target->name()->as_utf8()); 155 156 // Do the typeflow analysis 157 ciTypeFlow *flow; 158 if (entry_bci == InvocationEntryBci) 159 flow = target->get_flow_analysis(); 160 else 161 flow = target->get_osr_flow_analysis(entry_bci); 162 if (flow->failing()) 163 return; 164 if (SharkPrintTypeflowOf != NULL) { 165 if (!fnmatch(SharkPrintTypeflowOf, name, 0)) 166 flow->print_on(tty); 167 } 168 169 // Create the recorders 170 Arena arena; 171 env->set_oop_recorder(new OopRecorder(&arena)); 172 OopMapSet oopmaps; 173 env->set_debug_info(new DebugInformationRecorder(env->oop_recorder())); 174 env->debug_info()->set_oopmaps(&oopmaps); 175 env->set_dependencies(new Dependencies(env)); 176 177 // Create the code buffer and builder 178 CodeBuffer hscb("Shark", 256 * K, 64 * K); 179 hscb.initialize_oop_recorder(env->oop_recorder()); 180 MacroAssembler *masm = new MacroAssembler(&hscb); 181 SharkCodeBuffer cb(masm); 182 SharkBuilder builder(&cb); 183 184 // Emit the entry point 185 SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry)); 186 187 // Build the LLVM IR for the method 188 Function *function = SharkFunction::build(env, &builder, flow, name); 189 if (env->failing()) { 190 return; 191 } 192 193 // Generate native code. It's unpleasant that we have to drop into 194 // the VM to do this -- it blocks safepoints -- but I can't see any 195 // other way to handle the locking. 196 { 197 ThreadInVMfromNative tiv(JavaThread::current()); 198 generate_native_code(entry, function, name); 199 } 200 201 // Install the method into the VM 202 CodeOffsets offsets; 203 offsets.set_value(CodeOffsets::Deopt, 0); 204 offsets.set_value(CodeOffsets::Exceptions, 0); 205 offsets.set_value(CodeOffsets::Verified_Entry, 206 target->is_static() ? 0 : wordSize); 207 208 ExceptionHandlerTable handler_table; 209 ImplicitExceptionTable inc_table; 210 211 env->register_method(target, 212 entry_bci, 213 &offsets, 214 0, 215 &hscb, 216 0, 217 &oopmaps, 218 &handler_table, 219 &inc_table, 220 this, 221 false, 222 directive(), 223 false); 224 } 225 226 nmethod* SharkCompiler::generate_native_wrapper(MacroAssembler* masm, 227 const methodHandle& target, 228 int compile_id, 229 BasicType* arg_types, 230 BasicType return_type) { 231 assert(is_initialized(), "should be"); 232 ResourceMark rm; 233 const char *name = methodname( 234 target->klass_name()->as_utf8(), target->name()->as_utf8()); 235 236 // Create the code buffer and builder 237 SharkCodeBuffer cb(masm); 238 SharkBuilder builder(&cb); 239 240 // Emit the entry point 241 SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry)); 242 243 // Build the LLVM IR for the method 244 SharkNativeWrapper *wrapper = SharkNativeWrapper::build( 245 &builder, target, name, arg_types, return_type); 246 247 // Generate native code 248 generate_native_code(entry, wrapper->function(), name); 249 250 // Return the nmethod for installation in the VM 251 return nmethod::new_native_nmethod(target, 252 compile_id, 253 masm->code(), 254 0, 255 0, 256 wrapper->frame_size(), 257 wrapper->receiver_offset(), 258 wrapper->lock_offset(), 259 wrapper->oop_maps()); 260 } 261 262 void SharkCompiler::generate_native_code(SharkEntry* entry, 263 Function* function, 264 const char* name) { 265 // Print the LLVM bitcode, if requested 266 if (SharkPrintBitcodeOf != NULL) { 267 if (!fnmatch(SharkPrintBitcodeOf, name, 0)) 268 function->dump(); 269 } 270 271 if (SharkVerifyFunction != NULL) { 272 if (!fnmatch(SharkVerifyFunction, name, 0)) { 273 verifyFunction(*function); 274 } 275 } 276 277 // Compile to native code 278 address code = NULL; 279 context()->add_function(function); 280 { 281 MutexLocker locker(execution_engine_lock()); 282 free_queued_methods(); 283 284 #ifndef NDEBUG 285 #if SHARK_LLVM_VERSION <= 31 286 #define setCurrentDebugType SetCurrentDebugType 287 #endif 288 if (SharkPrintAsmOf != NULL) { 289 if (!fnmatch(SharkPrintAsmOf, name, 0)) { 290 llvm::setCurrentDebugType(X86_ONLY("x86-emitter") NOT_X86("jit")); 291 llvm::DebugFlag = true; 292 } 293 else { 294 llvm::setCurrentDebugType(""); 295 llvm::DebugFlag = false; 296 } 297 } 298 #ifdef setCurrentDebugType 299 #undef setCurrentDebugType 300 #endif 301 #endif // !NDEBUG 302 memory_manager()->set_entry_for_function(function, entry); 303 code = (address) execution_engine()->getPointerToFunction(function); 304 } 305 assert(code != NULL, "code must be != NULL"); 306 entry->set_entry_point(code); 307 entry->set_function(function); 308 entry->set_context(context()); 309 address code_start = entry->code_start(); 310 address code_limit = entry->code_limit(); 311 312 // Register generated code for profiling, etc 313 if (JvmtiExport::should_post_dynamic_code_generated()) 314 JvmtiExport::post_dynamic_code_generated(name, code_start, code_limit); 315 316 // Print debug information, if requested 317 if (SharkTraceInstalls) { 318 tty->print_cr( 319 " [%p-%p): %s (%d bytes code)", 320 code_start, code_limit, name, code_limit - code_start); 321 } 322 } 323 324 void SharkCompiler::free_compiled_method(address code) { 325 // This method may only be called when the VM is at a safepoint. 326 // All _thread_in_vm threads will be waiting for the safepoint to 327 // finish with the exception of the VM thread, so we can consider 328 // ourself the owner of the execution engine lock even though we 329 // can't actually acquire it at this time. 330 assert(Thread::current()->is_Compiler_thread(), "must be called by compiler thread"); 331 assert_locked_or_safepoint(CodeCache_lock); 332 333 SharkEntry *entry = (SharkEntry *) code; 334 entry->context()->push_to_free_queue(entry->function()); 335 } 336 337 void SharkCompiler::free_queued_methods() { 338 // The free queue is protected by the execution engine lock 339 assert(execution_engine_lock()->owned_by_self(), "should be"); 340 341 while (true) { 342 Function *function = context()->pop_from_free_queue(); 343 if (function == NULL) 344 break; 345 346 execution_engine()->freeMachineCodeForFunction(function); 347 function->eraseFromParent(); 348 } 349 } 350 351 const char* SharkCompiler::methodname(const char* klass, const char* method) { 352 char *buf = NEW_RESOURCE_ARRAY(char, strlen(klass) + 2 + strlen(method) + 1); 353 354 char *dst = buf; 355 for (const char *c = klass; *c; c++) { 356 if (*c == '/') 357 *(dst++) = '.'; 358 else 359 *(dst++) = *c; 360 } 361 *(dst++) = ':'; 362 *(dst++) = ':'; 363 for (const char *c = method; *c; c++) { 364 *(dst++) = *c; 365 } 366 *(dst++) = '\0'; 367 return buf; 368 } 369 370 void SharkCompiler::print_timers() { 371 // do nothing 372 }