1 /*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "jit.h"
18
19 #include <dlfcn.h>
20
21 #include "art_method-inl.h"
22 #include "base/enums.h"
23 #include "base/file_utils.h"
24 #include "base/logging.h" // For VLOG.
25 #include "base/memfd.h"
26 #include "base/memory_tool.h"
27 #include "base/runtime_debug.h"
28 #include "base/scoped_flock.h"
29 #include "base/utils.h"
30 #include "class_root-inl.h"
31 #include "compilation_kind.h"
32 #include "debugger.h"
33 #include "dex/type_lookup_table.h"
34 #include "gc/space/image_space.h"
35 #include "entrypoints/entrypoint_utils-inl.h"
36 #include "entrypoints/runtime_asm_entrypoints.h"
37 #include "image-inl.h"
38 #include "interpreter/interpreter.h"
39 #include "jit-inl.h"
40 #include "jit_code_cache.h"
41 #include "jni/java_vm_ext.h"
42 #include "mirror/method_handle_impl.h"
43 #include "mirror/var_handle.h"
44 #include "oat_file.h"
45 #include "oat_file_manager.h"
46 #include "oat_quick_method_header.h"
47 #include "profile/profile_boot_info.h"
48 #include "profile/profile_compilation_info.h"
49 #include "profile_saver.h"
50 #include "runtime.h"
51 #include "runtime_options.h"
52 #include "stack.h"
53 #include "stack_map.h"
54 #include "thread-inl.h"
55 #include "thread_list.h"
56
57 using android::base::unique_fd;
58
59 namespace art {
60 namespace jit {
61
62 static constexpr bool kEnableOnStackReplacement = true;
63
64 // Maximum permitted threshold value.
65 static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
66
67 // Different compilation threshold constants. These can be overridden on the command line.
68
69 // Non-debug default
70 static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
71 // Fast-debug build.
72 static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
73 // Slow-debug build.
74 static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
75
76 // Different warm-up threshold constants. These default to the equivalent compile thresholds divided
77 // by 2, but can be overridden at the command-line.
78 static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
79 static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
80 static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
81 kJitSlowStressDefaultCompileThreshold / 2;
82
83 DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
84
85 // JIT compiler
86 void* Jit::jit_library_handle_ = nullptr;
87 JitCompilerInterface* Jit::jit_compiler_ = nullptr;
88 JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
89
CreateFromRuntimeArguments(const RuntimeArgumentMap & options)90 JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
91 auto* jit_options = new JitOptions;
92 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
93 jit_options->use_profiled_jit_compilation_ =
94 options.GetOrDefault(RuntimeArgumentMap::UseProfiledJitCompilation);
95
96 jit_options->code_cache_initial_capacity_ =
97 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
98 jit_options->code_cache_max_capacity_ =
99 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
100 jit_options->dump_info_on_shutdown_ =
101 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
102 jit_options->profile_saver_options_ =
103 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
104 jit_options->thread_pool_pthread_priority_ =
105 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
106 jit_options->zygote_thread_pool_pthread_priority_ =
107 options.GetOrDefault(RuntimeArgumentMap::JITZygotePoolThreadPthreadPriority);
108
109 // Set default compile threshold to aid with checking defaults.
110 jit_options->compile_threshold_ =
111 kIsDebugBuild
112 ? (Jit::kSlowMode
113 ? kJitSlowStressDefaultCompileThreshold
114 : kJitStressDefaultCompileThreshold)
115 : kJitDefaultCompileThreshold;
116
117 // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
118 const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
119
120 // Set default warm-up threshold to aid with checking defaults.
121 jit_options->warmup_threshold_ =
122 kIsDebugBuild ? (Jit::kSlowMode
123 ? kJitSlowStressDefaultWarmUpThreshold
124 : kJitStressDefaultWarmUpThreshold)
125 : kJitDefaultWarmUpThreshold;
126
127 // Warmup threshold should be less than compile threshold (so long as compile threshold is not
128 // zero == JIT-on-first-use).
129 DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
130 DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
131 jit_options->warmup_threshold_);
132
133 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
134 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
135 }
136 jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
137
138 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
139 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
140 }
141 jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
142
143 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
144 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
145 } else {
146 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
147 if (jit_options->osr_threshold_ > kJitMaxThreshold) {
148 jit_options->osr_threshold_ =
149 RoundDown(kJitMaxThreshold, kJitThresholdStep);
150 }
151 }
152 jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
153
154 // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
155 // threshold is 0).
156 if (jit_options->compile_threshold_ != 0) {
157 // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
158 jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
159 2u * kJitThresholdStep,
160 RoundDown(kJitMaxThreshold, kJitThresholdStep));
161 jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
162 kJitThresholdStep,
163 jit_options->osr_threshold_ - kJitThresholdStep);
164 jit_options->warmup_threshold_ =
165 std::clamp(jit_options->warmup_threshold_,
166 0u,
167 jit_options->compile_threshold_ - kJitThresholdStep);
168 }
169
170 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
171 jit_options->priority_thread_weight_ =
172 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
173 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
174 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
175 } else if (jit_options->priority_thread_weight_ == 0) {
176 LOG(FATAL) << "Priority thread weight cannot be 0.";
177 }
178 } else {
179 jit_options->priority_thread_weight_ = std::max(
180 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
181 static_cast<size_t>(1));
182 }
183
184 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
185 jit_options->invoke_transition_weight_ =
186 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
187 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
188 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
189 } else if (jit_options->invoke_transition_weight_ == 0) {
190 LOG(FATAL) << "Invoke transition weight cannot be 0.";
191 }
192 } else {
193 jit_options->invoke_transition_weight_ = std::max(
194 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
195 static_cast<size_t>(1));
196 }
197
198 return jit_options;
199 }
200
DumpInfo(std::ostream & os)201 void Jit::DumpInfo(std::ostream& os) {
202 code_cache_->Dump(os);
203 cumulative_timings_.Dump(os);
204 MutexLock mu(Thread::Current(), lock_);
205 memory_use_.PrintMemoryUse(os);
206 }
207
DumpForSigQuit(std::ostream & os)208 void Jit::DumpForSigQuit(std::ostream& os) {
209 DumpInfo(os);
210 ProfileSaver::DumpInstanceInfo(os);
211 }
212
AddTimingLogger(const TimingLogger & logger)213 void Jit::AddTimingLogger(const TimingLogger& logger) {
214 cumulative_timings_.AddLogger(logger);
215 }
216
Jit(JitCodeCache * code_cache,JitOptions * options)217 Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
218 : code_cache_(code_cache),
219 options_(options),
220 boot_completed_lock_("Jit::boot_completed_lock_"),
221 cumulative_timings_("JIT timings"),
222 memory_use_("Memory used for compilation", 16),
223 lock_("JIT memory use lock"),
224 zygote_mapping_methods_(),
225 fd_methods_(-1),
226 fd_methods_size_(0) {}
227
Create(JitCodeCache * code_cache,JitOptions * options)228 Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
229 if (jit_load_ == nullptr) {
230 LOG(WARNING) << "Not creating JIT: library not loaded";
231 return nullptr;
232 }
233 jit_compiler_ = (jit_load_)();
234 if (jit_compiler_ == nullptr) {
235 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
236 return nullptr;
237 }
238 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
239
240 // If the code collector is enabled, check if that still holds:
241 // With 'perf', we want a 1-1 mapping between an address and a method.
242 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
243 // so we will just disable jit-gc if we are doing that.
244 if (code_cache->GetGarbageCollectCode()) {
245 code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
246 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
247 }
248
249 VLOG(jit) << "JIT created with initial_capacity="
250 << PrettySize(options->GetCodeCacheInitialCapacity())
251 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
252 << ", compile_threshold=" << options->GetCompileThreshold()
253 << ", profile_saver_options=" << options->GetProfileSaverOptions();
254
255 // We want to know whether the compiler is compiling baseline, as this
256 // affects how we GC ProfilingInfos.
257 for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
258 if (option == "--baseline") {
259 options->SetUseBaselineCompiler();
260 break;
261 }
262 }
263
264 // Notify native debugger about the classes already loaded before the creation of the jit.
265 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
266 return jit.release();
267 }
268
269 template <typename T>
LoadSymbol(T * address,const char * name,std::string * error_msg)270 bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
271 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
272 if (*address == nullptr) {
273 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
274 return false;
275 }
276 return true;
277 }
278
LoadCompilerLibrary(std::string * error_msg)279 bool Jit::LoadCompilerLibrary(std::string* error_msg) {
280 jit_library_handle_ = dlopen(
281 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
282 if (jit_library_handle_ == nullptr) {
283 std::ostringstream oss;
284 oss << "JIT could not load libart-compiler.so: " << dlerror();
285 *error_msg = oss.str();
286 return false;
287 }
288 if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
289 dlclose(jit_library_handle_);
290 return false;
291 }
292 return true;
293 }
294
CompileMethod(ArtMethod * method,Thread * self,CompilationKind compilation_kind,bool prejit)295 bool Jit::CompileMethod(ArtMethod* method,
296 Thread* self,
297 CompilationKind compilation_kind,
298 bool prejit) {
299 DCHECK(Runtime::Current()->UseJitCompilation());
300 DCHECK(!method->IsRuntimeMethod());
301
302 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
303 // Don't compile the method if it has breakpoints.
304 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
305 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
306 << " due to not being safe to jit according to runtime-callbacks. For example, there"
307 << " could be breakpoints in this method.";
308 return false;
309 }
310
311 if (!method->IsCompilable()) {
312 DCHECK(method->GetDeclaringClass()->IsObsoleteObject() ||
313 method->IsProxyMethod()) << method->PrettyMethod();
314 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to method being made "
315 << "obsolete while waiting for JIT task to run. This probably happened due to "
316 << "concurrent structural class redefinition.";
317 return false;
318 }
319
320 // Don't compile the method if we are supposed to be deoptimized.
321 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
322 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
323 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
324 return false;
325 }
326
327 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
328 if ((compilation_kind == CompilationKind::kOsr) && GetCodeCache()->IsSharedRegion(*region)) {
329 VLOG(jit) << "JIT not osr compiling "
330 << method->PrettyMethod()
331 << " due to using shared region";
332 return false;
333 }
334
335 // If we get a request to compile a proxy method, we pass the actual Java method
336 // of that proxy method, as the compiler does not expect a proxy method.
337 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
338 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, compilation_kind, prejit)) {
339 return false;
340 }
341
342 VLOG(jit) << "Compiling method "
343 << ArtMethod::PrettyMethod(method_to_compile)
344 << " kind=" << compilation_kind;
345 bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, compilation_kind);
346 code_cache_->DoneCompiling(method_to_compile, self, compilation_kind);
347 if (!success) {
348 VLOG(jit) << "Failed to compile method "
349 << ArtMethod::PrettyMethod(method_to_compile)
350 << " kind=" << compilation_kind;
351 }
352 if (kIsDebugBuild) {
353 if (self->IsExceptionPending()) {
354 mirror::Throwable* exception = self->GetException();
355 LOG(FATAL) << "No pending exception expected after compiling "
356 << ArtMethod::PrettyMethod(method)
357 << ": "
358 << exception->Dump();
359 }
360 }
361 return success;
362 }
363
WaitForWorkersToBeCreated()364 void Jit::WaitForWorkersToBeCreated() {
365 if (thread_pool_ != nullptr) {
366 thread_pool_->WaitForWorkersToBeCreated();
367 }
368 }
369
DeleteThreadPool()370 void Jit::DeleteThreadPool() {
371 Thread* self = Thread::Current();
372 if (thread_pool_ != nullptr) {
373 std::unique_ptr<ThreadPool> pool;
374 {
375 ScopedSuspendAll ssa(__FUNCTION__);
376 // Clear thread_pool_ field while the threads are suspended.
377 // A mutator in the 'AddSamples' method will check against it.
378 pool = std::move(thread_pool_);
379 }
380
381 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
382 if (!kRunningOnMemoryTool) {
383 pool->StopWorkers(self);
384 pool->RemoveAllTasks(self);
385 }
386 // We could just suspend all threads, but we know those threads
387 // will finish in a short period, so it's not worth adding a suspend logic
388 // here. Besides, this is only done for shutdown.
389 pool->Wait(self, false, false);
390 }
391 }
392
StartProfileSaver(const std::string & profile_filename,const std::vector<std::string> & code_paths,const std::string & ref_profile_filename)393 void Jit::StartProfileSaver(const std::string& profile_filename,
394 const std::vector<std::string>& code_paths,
395 const std::string& ref_profile_filename) {
396 if (options_->GetSaveProfilingInfo()) {
397 ProfileSaver::Start(options_->GetProfileSaverOptions(),
398 profile_filename,
399 code_cache_,
400 code_paths,
401 ref_profile_filename);
402 }
403 }
404
StopProfileSaver()405 void Jit::StopProfileSaver() {
406 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
407 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
408 }
409 }
410
JitAtFirstUse()411 bool Jit::JitAtFirstUse() {
412 return HotMethodThreshold() == 0;
413 }
414
CanInvokeCompiledCode(ArtMethod * method)415 bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
416 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
417 }
418
~Jit()419 Jit::~Jit() {
420 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
421 if (options_->DumpJitInfoOnShutdown()) {
422 DumpInfo(LOG_STREAM(INFO));
423 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
424 }
425 DeleteThreadPool();
426 if (jit_compiler_ != nullptr) {
427 delete jit_compiler_;
428 jit_compiler_ = nullptr;
429 }
430 if (jit_library_handle_ != nullptr) {
431 dlclose(jit_library_handle_);
432 jit_library_handle_ = nullptr;
433 }
434 }
435
NewTypeLoadedIfUsingJit(mirror::Class * type)436 void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
437 if (!Runtime::Current()->UseJitCompilation()) {
438 // No need to notify if we only use the JIT to save profiles.
439 return;
440 }
441 jit::Jit* jit = Runtime::Current()->GetJit();
442 if (jit->jit_compiler_->GenerateDebugInfo()) {
443 jit_compiler_->TypesLoaded(&type, 1);
444 }
445 }
446
DumpTypeInfoForLoadedTypes(ClassLinker * linker)447 void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
448 struct CollectClasses : public ClassVisitor {
449 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
450 classes_.push_back(klass.Ptr());
451 return true;
452 }
453 std::vector<mirror::Class*> classes_;
454 };
455
456 if (jit_compiler_->GenerateDebugInfo()) {
457 ScopedObjectAccess so(Thread::Current());
458
459 CollectClasses visitor;
460 linker->VisitClasses(&visitor);
461 jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
462 }
463 }
464
465 extern "C" void art_quick_osr_stub(void** stack,
466 size_t stack_size_in_bytes,
467 const uint8_t* native_pc,
468 JValue* result,
469 const char* shorty,
470 Thread* self);
471
PrepareForOsr(ArtMethod * method,uint32_t dex_pc,uint32_t * vregs)472 OsrData* Jit::PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs) {
473 if (!kEnableOnStackReplacement) {
474 return nullptr;
475 }
476
477 // Cheap check if the method has been compiled already. That's an indicator that we should
478 // osr into it.
479 if (!GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
480 return nullptr;
481 }
482
483 // Fetch some data before looking up for an OSR method. We don't want thread
484 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
485 // method while we are being suspended.
486 CodeItemDataAccessor accessor(method->DexInstructionData());
487 const size_t number_of_vregs = accessor.RegistersSize();
488 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
489 OsrData* osr_data = nullptr;
490
491 {
492 ScopedAssertNoThreadSuspension sts("Holding OSR method");
493 const OatQuickMethodHeader* osr_method = GetCodeCache()->LookupOsrMethodHeader(method);
494 if (osr_method == nullptr) {
495 // No osr method yet, just return to the interpreter.
496 return nullptr;
497 }
498
499 CodeInfo code_info(osr_method);
500
501 // Find stack map starting at the target dex_pc.
502 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc);
503 if (!stack_map.IsValid()) {
504 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
505 // hope that the next branch has one.
506 return nullptr;
507 }
508
509 // We found a stack map, now fill the frame with dex register values from the interpreter's
510 // shadow frame.
511 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
512 DCHECK_EQ(vreg_map.size(), number_of_vregs);
513
514 size_t frame_size = osr_method->GetFrameSizeInBytes();
515
516 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
517 // stack.
518 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
519 // but that is engineering complexity not worth the effort for something like OSR.
520 osr_data = reinterpret_cast<OsrData*>(malloc(sizeof(OsrData) + frame_size));
521 if (osr_data == nullptr) {
522 return nullptr;
523 }
524 memset(osr_data, 0, sizeof(OsrData) + frame_size);
525 osr_data->frame_size = frame_size;
526
527 // Art ABI: ArtMethod is at the bottom of the stack.
528 osr_data->memory[0] = method;
529
530 if (vreg_map.empty()) {
531 // If we don't have a dex register map, then there are no live dex registers at
532 // this dex pc.
533 } else {
534 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
535 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
536 if (location == DexRegisterLocation::Kind::kNone) {
537 // Dex register is dead or uninitialized.
538 continue;
539 }
540
541 if (location == DexRegisterLocation::Kind::kConstant) {
542 // We skip constants because the compiled code knows how to handle them.
543 continue;
544 }
545
546 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
547
548 int32_t vreg_value = vregs[vreg];
549 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
550 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
551 DCHECK_GT(slot_offset, 0);
552 (reinterpret_cast<int32_t*>(osr_data->memory))[slot_offset / sizeof(int32_t)] = vreg_value;
553 }
554 }
555
556 osr_data->native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
557 osr_method->GetEntryPoint();
558 VLOG(jit) << "Jumping to "
559 << method_name
560 << "@"
561 << std::hex << reinterpret_cast<uintptr_t>(osr_data->native_pc);
562 }
563 return osr_data;
564 }
565
MaybeDoOnStackReplacement(Thread * thread,ArtMethod * method,uint32_t dex_pc,int32_t dex_pc_offset,JValue * result)566 bool Jit::MaybeDoOnStackReplacement(Thread* thread,
567 ArtMethod* method,
568 uint32_t dex_pc,
569 int32_t dex_pc_offset,
570 JValue* result) {
571 Jit* jit = Runtime::Current()->GetJit();
572 if (jit == nullptr) {
573 return false;
574 }
575
576 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
577 // Don't attempt to do an OSR if we are close to the stack limit. Since
578 // the interpreter frames are still on stack, OSR has the potential
579 // to stack overflow even for a simple loop.
580 // b/27094810.
581 return false;
582 }
583
584 // Get the actual Java method if this method is from a proxy class. The compiler
585 // and the JIT code cache do not expect methods from proxy classes.
586 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
587
588 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
589 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
590 // disable OSR when single stepping, but that's currently hard to know at this point.
591 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
592 return false;
593 }
594
595 ShadowFrame* shadow_frame = thread->GetManagedStack()->GetTopShadowFrame();
596 OsrData* osr_data = jit->PrepareForOsr(method,
597 dex_pc + dex_pc_offset,
598 shadow_frame->GetVRegArgs(0));
599
600 if (osr_data == nullptr) {
601 return false;
602 }
603
604 {
605 thread->PopShadowFrame();
606 ManagedStack fragment;
607 thread->PushManagedStackFragment(&fragment);
608 (*art_quick_osr_stub)(osr_data->memory,
609 osr_data->frame_size,
610 osr_data->native_pc,
611 result,
612 method->GetShorty(),
613 thread);
614
615 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
616 thread->DeoptimizeWithDeoptimizationException(result);
617 }
618 thread->PopManagedStackFragment(fragment);
619 }
620 free(osr_data);
621 thread->PushShadowFrame(shadow_frame);
622 VLOG(jit) << "Done running OSR code for " << method->PrettyMethod();
623 return true;
624 }
625
AddMemoryUsage(ArtMethod * method,size_t bytes)626 void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
627 if (bytes > 4 * MB) {
628 LOG(INFO) << "Compiler allocated "
629 << PrettySize(bytes)
630 << " to compile "
631 << ArtMethod::PrettyMethod(method);
632 }
633 MutexLock mu(Thread::Current(), lock_);
634 memory_use_.AddValue(bytes);
635 }
636
NotifyZygoteCompilationDone()637 void Jit::NotifyZygoteCompilationDone() {
638 if (fd_methods_ == -1) {
639 return;
640 }
641
642 size_t offset = 0;
643 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
644 const ImageHeader& header = space->GetImageHeader();
645 const ImageSection& section = header.GetMethodsSection();
646 // Because mremap works at page boundaries, we can only handle methods
647 // within a page range. For methods that falls above or below the range,
648 // the child processes will copy their contents to their private mapping
649 // in `child_mapping_methods`. See `MapBootImageMethods`.
650 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
651 uint8_t* page_end =
652 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
653 if (page_end > page_start) {
654 uint64_t capacity = page_end - page_start;
655 memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
656 offset += capacity;
657 }
658 }
659
660 // Do an msync to ensure we are not affected by writes still being in caches.
661 if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
662 PLOG(WARNING) << "Failed to sync boot image methods memory";
663 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
664 return;
665 }
666
667 // We don't need the shared mapping anymore, and we need to drop it in case
668 // the file hasn't been sealed writable.
669 zygote_mapping_methods_ = MemMap::Invalid();
670
671 // Seal writes now. Zygote and children will map the memory private in order
672 // to write to it.
673 if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
674 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
675 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
676 return;
677 }
678
679 std::string error_str;
680 MemMap child_mapping_methods = MemMap::MapFile(
681 fd_methods_size_,
682 PROT_READ | PROT_WRITE,
683 MAP_PRIVATE,
684 fd_methods_,
685 /* start= */ 0,
686 /* low_4gb= */ false,
687 "boot-image-methods",
688 &error_str);
689
690 if (!child_mapping_methods.IsValid()) {
691 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
692 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
693 return;
694 }
695
696 // Ensure the contents are the same as before: there was a window between
697 // the memcpy and the sealing where other processes could have changed the
698 // contents.
699 // Note this would not be needed if we could have used F_SEAL_FUTURE_WRITE,
700 // see b/143833776.
701 offset = 0;
702 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
703 const ImageHeader& header = space->GetImageHeader();
704 const ImageSection& section = header.GetMethodsSection();
705 // Because mremap works at page boundaries, we can only handle methods
706 // within a page range. For methods that falls above or below the range,
707 // the child processes will copy their contents to their private mapping
708 // in `child_mapping_methods`. See `MapBootImageMethods`.
709 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
710 uint8_t* page_end =
711 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
712 if (page_end > page_start) {
713 uint64_t capacity = page_end - page_start;
714 if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
715 LOG(WARNING) << "Contents differ in boot image methods data";
716 code_cache_->GetZygoteMap()->SetCompilationState(
717 ZygoteCompilationState::kNotifiedFailure);
718 return;
719 }
720 offset += capacity;
721 }
722 }
723
724 // Future spawned processes don't need the fd anymore.
725 fd_methods_.reset();
726
727 // In order to have the zygote and children share the memory, we also remap
728 // the memory into the zygote process.
729 offset = 0;
730 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
731 const ImageHeader& header = space->GetImageHeader();
732 const ImageSection& section = header.GetMethodsSection();
733 // Because mremap works at page boundaries, we can only handle methods
734 // within a page range. For methods that falls above or below the range,
735 // the child processes will copy their contents to their private mapping
736 // in `child_mapping_methods`. See `MapBootImageMethods`.
737 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
738 uint8_t* page_end =
739 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
740 if (page_end > page_start) {
741 uint64_t capacity = page_end - page_start;
742 if (mremap(child_mapping_methods.Begin() + offset,
743 capacity,
744 capacity,
745 MREMAP_FIXED | MREMAP_MAYMOVE,
746 page_start) == MAP_FAILED) {
747 // Failing to remap is safe as the process will just use the old
748 // contents.
749 PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
750 }
751 offset += capacity;
752 }
753 }
754
755 LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
756
757 // Mark that compilation of boot classpath is done, and memory can now be
758 // shared. Other processes will pick up this information.
759 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
760
761 // The private mapping created for this process has been mremaped. We can
762 // reset it.
763 child_mapping_methods.Reset();
764 }
765
766 class JitCompileTask final : public Task {
767 public:
768 enum class TaskKind {
769 kCompile,
770 kPreCompile,
771 };
772
JitCompileTask(ArtMethod * method,TaskKind task_kind,CompilationKind compilation_kind)773 JitCompileTask(ArtMethod* method, TaskKind task_kind, CompilationKind compilation_kind)
774 : method_(method), kind_(task_kind), compilation_kind_(compilation_kind), klass_(nullptr) {
775 ScopedObjectAccess soa(Thread::Current());
776 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
777 // until compilation is done.
778 // When we precompile, this is either with boot classpath methods, or main
779 // class loader methods, so we don't need to keep a global reference.
780 if (method->GetDeclaringClass()->GetClassLoader() != nullptr &&
781 kind_ != TaskKind::kPreCompile) {
782 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
783 CHECK(klass_ != nullptr);
784 }
785 }
786
~JitCompileTask()787 ~JitCompileTask() {
788 if (klass_ != nullptr) {
789 ScopedObjectAccess soa(Thread::Current());
790 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
791 }
792 }
793
Run(Thread * self)794 void Run(Thread* self) override {
795 {
796 ScopedObjectAccess soa(self);
797 switch (kind_) {
798 case TaskKind::kCompile:
799 case TaskKind::kPreCompile: {
800 Runtime::Current()->GetJit()->CompileMethod(
801 method_,
802 self,
803 compilation_kind_,
804 /* prejit= */ (kind_ == TaskKind::kPreCompile));
805 break;
806 }
807 }
808 }
809 ProfileSaver::NotifyJitActivity();
810 }
811
Finalize()812 void Finalize() override {
813 delete this;
814 }
815
816 private:
817 ArtMethod* const method_;
818 const TaskKind kind_;
819 const CompilationKind compilation_kind_;
820 jobject klass_;
821
822 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
823 };
824
GetProfileFile(const std::string & dex_location)825 static std::string GetProfileFile(const std::string& dex_location) {
826 // Hardcoded assumption where the profile file is.
827 // TODO(ngeoffray): this is brittle and we would need to change change if we
828 // wanted to do more eager JITting of methods in a profile. This is
829 // currently only for system server.
830 return dex_location + ".prof";
831 }
832
GetBootProfileFile(const std::string & profile)833 static std::string GetBootProfileFile(const std::string& profile) {
834 // The boot profile can be found next to the compilation profile, with a
835 // different extension.
836 return ReplaceFileExtension(profile, "bprof");
837 }
838
839 /**
840 * A JIT task to run after all profile compilation is done.
841 */
842 class JitDoneCompilingProfileTask final : public SelfDeletingTask {
843 public:
JitDoneCompilingProfileTask(const std::vector<const DexFile * > & dex_files)844 explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
845 : dex_files_(dex_files) {}
846
Run(Thread * self ATTRIBUTE_UNUSED)847 void Run(Thread* self ATTRIBUTE_UNUSED) override {
848 // Madvise DONTNEED dex files now that we're done compiling methods.
849 for (const DexFile* dex_file : dex_files_) {
850 if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
851 int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
852 RoundUp(dex_file->Size(), kPageSize),
853 MADV_DONTNEED);
854 if (result == -1) {
855 PLOG(WARNING) << "Madvise failed";
856 }
857 }
858 }
859
860 if (Runtime::Current()->IsZygote()) {
861 // Record that we are done compiling the profile.
862 Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
863 ZygoteCompilationState::kDone);
864 }
865 }
866
867 private:
868 std::vector<const DexFile*> dex_files_;
869
870 DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
871 };
872
873 /**
874 * A JIT task to run Java verification of boot classpath classes that were not
875 * verified at compile-time.
876 */
877 class ZygoteVerificationTask final : public Task {
878 public:
ZygoteVerificationTask()879 ZygoteVerificationTask() {}
880
Run(Thread * self)881 void Run(Thread* self) override {
882 // We are going to load class and run verification, which may also need to load
883 // classes. If the thread cannot load classes (typically when the runtime is
884 // debuggable), then just return.
885 if (!self->CanLoadClasses()) {
886 return;
887 }
888 Runtime* runtime = Runtime::Current();
889 ClassLinker* linker = runtime->GetClassLinker();
890 const std::vector<const DexFile*>& boot_class_path =
891 runtime->GetClassLinker()->GetBootClassPath();
892 ScopedObjectAccess soa(self);
893 StackHandleScope<1> hs(self);
894 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
895 uint64_t start_ns = ThreadCpuNanoTime();
896 uint64_t number_of_classes = 0;
897 for (const DexFile* dex_file : boot_class_path) {
898 if (dex_file->GetOatDexFile() != nullptr &&
899 dex_file->GetOatDexFile()->GetOatFile() != nullptr) {
900 // If backed by an .oat file, we have already run verification at
901 // compile-time. Note that some classes may still have failed
902 // verification there if they reference updatable mainline module
903 // classes.
904 continue;
905 }
906 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
907 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
908 const char* descriptor = dex_file->GetClassDescriptor(class_def);
909 ScopedNullHandle<mirror::ClassLoader> null_loader;
910 klass.Assign(linker->FindClass(self, descriptor, null_loader));
911 if (klass == nullptr) {
912 self->ClearException();
913 LOG(WARNING) << "Could not find " << descriptor;
914 continue;
915 }
916 ++number_of_classes;
917 if (linker->VerifyClass(self, /* verifier_deps= */ nullptr, klass) ==
918 verifier::FailureKind::kHardFailure) {
919 DCHECK(self->IsExceptionPending());
920 LOG(FATAL) << "Methods in the boot classpath failed to verify: "
921 << self->GetException()->Dump();
922 }
923 CHECK(!self->IsExceptionPending());
924 }
925 }
926 LOG(INFO) << "Verified "
927 << number_of_classes
928 << " classes from mainline modules in "
929 << PrettyDuration(ThreadCpuNanoTime() - start_ns);
930 }
931 };
932
933 class ZygoteTask final : public Task {
934 public:
ZygoteTask()935 ZygoteTask() {}
936
Run(Thread * self)937 void Run(Thread* self) override {
938 Runtime* runtime = Runtime::Current();
939 uint32_t added_to_queue = 0;
940 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
941 const std::string& profile_file = space->GetProfileFile();
942 if (profile_file.empty()) {
943 continue;
944 }
945 LOG(INFO) << "JIT Zygote looking at profile " << profile_file;
946
947 const std::vector<const DexFile*>& boot_class_path =
948 runtime->GetClassLinker()->GetBootClassPath();
949 ScopedNullHandle<mirror::ClassLoader> null_handle;
950 // We add to the queue for zygote so that we can fork processes in-between
951 // compilations.
952 if (Runtime::Current()->IsPrimaryZygote()) {
953 std::string boot_profile = GetBootProfileFile(profile_file);
954 // We avoid doing compilation at boot for the secondary zygote, as apps
955 // forked from it are not critical for boot.
956 added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
957 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
958 }
959 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
960 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
961 }
962
963 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
964 code_cache->GetZygoteMap()->Initialize(added_to_queue);
965 }
966
Finalize()967 void Finalize() override {
968 delete this;
969 }
970
971 private:
972 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
973 };
974
975 class JitProfileTask final : public Task {
976 public:
JitProfileTask(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)977 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
978 jobject class_loader) {
979 ScopedObjectAccess soa(Thread::Current());
980 StackHandleScope<1> hs(soa.Self());
981 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
982 soa.Decode<mirror::ClassLoader>(class_loader)));
983 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
984 for (const auto& dex_file : dex_files) {
985 dex_files_.push_back(dex_file.get());
986 // Register the dex file so that we can guarantee it doesn't get deleted
987 // while reading it during the task.
988 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
989 }
990 // We also create our own global ref to use this class loader later.
991 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
992 }
993
Run(Thread * self)994 void Run(Thread* self) override {
995 ScopedObjectAccess soa(self);
996 StackHandleScope<1> hs(self);
997 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
998 soa.Decode<mirror::ClassLoader>(class_loader_));
999
1000 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
1001 std::string boot_profile = GetBootProfileFile(profile);
1002
1003 Jit* jit = Runtime::Current()->GetJit();
1004
1005 jit->CompileMethodsFromBootProfile(
1006 self,
1007 dex_files_,
1008 boot_profile,
1009 loader,
1010 /* add_to_queue= */ false);
1011
1012 jit->CompileMethodsFromProfile(
1013 self,
1014 dex_files_,
1015 profile,
1016 loader,
1017 /* add_to_queue= */ true);
1018 }
1019
Finalize()1020 void Finalize() override {
1021 delete this;
1022 }
1023
~JitProfileTask()1024 ~JitProfileTask() {
1025 ScopedObjectAccess soa(Thread::Current());
1026 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
1027 }
1028
1029 private:
1030 std::vector<const DexFile*> dex_files_;
1031 jobject class_loader_;
1032
1033 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
1034 };
1035
CopyIfDifferent(void * s1,const void * s2,size_t n)1036 static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
1037 if (memcmp(s1, s2, n) != 0) {
1038 memcpy(s1, s2, n);
1039 }
1040 }
1041
MapBootImageMethods()1042 void Jit::MapBootImageMethods() {
1043 if (Runtime::Current()->IsJavaDebuggable()) {
1044 LOG(INFO) << "Not mapping boot image methods due to process being debuggable";
1045 return;
1046 }
1047 CHECK_NE(fd_methods_.get(), -1);
1048 if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
1049 LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
1050 // We don't need the fd anymore.
1051 fd_methods_.reset();
1052 return;
1053 }
1054
1055 std::string error_str;
1056 MemMap child_mapping_methods = MemMap::MapFile(
1057 fd_methods_size_,
1058 PROT_READ | PROT_WRITE,
1059 MAP_PRIVATE,
1060 fd_methods_,
1061 /* start= */ 0,
1062 /* low_4gb= */ false,
1063 "boot-image-methods",
1064 &error_str);
1065
1066 // We don't need the fd anymore.
1067 fd_methods_.reset();
1068
1069 if (!child_mapping_methods.IsValid()) {
1070 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
1071 return;
1072 }
1073 // We are going to mremap the child mapping into the image:
1074 //
1075 // ImageSection ChildMappingMethods
1076 //
1077 // section start --> -----------
1078 // | |
1079 // | |
1080 // page_start --> | | <----- -----------
1081 // | | | |
1082 // | | | |
1083 // | | | |
1084 // | | | |
1085 // | | | |
1086 // | | | |
1087 // | | | |
1088 // page_end --> | | <----- -----------
1089 // | |
1090 // section end --> -----------
1091 //
1092 size_t offset = 0;
1093 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1094 const ImageHeader& header = space->GetImageHeader();
1095 const ImageSection& section = header.GetMethodsSection();
1096 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1097 uint8_t* page_end =
1098 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1099 if (page_end <= page_start) {
1100 // Section doesn't contain one aligned entire page.
1101 continue;
1102 }
1103 uint64_t capacity = page_end - page_start;
1104 // Walk over methods in the boot image, and check for:
1105 // 1) methods whose class is not initialized in the process, but are in the
1106 // zygote process. For such methods, we need their entrypoints to be stubs
1107 // that do the initialization check.
1108 // 2) native methods whose data pointer is different than the one in the
1109 // zygote. Such methods may have had custom native implementation provided
1110 // by JNI RegisterNatives.
1111 header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
1112 // Methods in the boot image should never have their single
1113 // implementation flag set (and therefore never have a `data_` pointing
1114 // to an ArtMethod for single implementation).
1115 CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
1116 if (method.IsRuntimeMethod()) {
1117 return;
1118 }
1119
1120 // Pointer to the method we're currently using.
1121 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1122 // The data pointer of that method that we want to keep.
1123 uint8_t* data_pointer = pointer + ArtMethod::DataOffset(kRuntimePointerSize).Int32Value();
1124 if (method.IsNative() && data_pointer >= page_start && data_pointer < page_end) {
1125 // The data pointer of the ArtMethod in the shared memory we are going to remap into our
1126 // own mapping. This is the data that we will see after the remap.
1127 uint8_t* new_data_pointer =
1128 child_mapping_methods.Begin() + offset + (data_pointer - page_start);
1129 CopyIfDifferent(new_data_pointer, data_pointer, sizeof(void*));
1130 }
1131
1132 // The entrypoint of the method we're currently using and that we want to
1133 // keep.
1134 uint8_t* entry_point_pointer = pointer +
1135 ArtMethod::EntryPointFromQuickCompiledCodeOffset(kRuntimePointerSize).Int32Value();
1136 if (!method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() &&
1137 method.IsStatic() &&
1138 !method.IsConstructor() &&
1139 entry_point_pointer >= page_start &&
1140 entry_point_pointer < page_end) {
1141 // The entry point of the ArtMethod in the shared memory we are going to remap into our
1142 // own mapping. This is the entrypoint that we will see after the remap.
1143 uint8_t* new_entry_point_pointer =
1144 child_mapping_methods.Begin() + offset + (entry_point_pointer - page_start);
1145 CopyIfDifferent(new_entry_point_pointer, entry_point_pointer, sizeof(void*));
1146 }
1147 }, space->Begin(), kRuntimePointerSize);
1148
1149 // Map the memory in the boot image range.
1150 if (mremap(child_mapping_methods.Begin() + offset,
1151 capacity,
1152 capacity,
1153 MREMAP_FIXED | MREMAP_MAYMOVE,
1154 page_start) == MAP_FAILED) {
1155 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1156 }
1157 offset += capacity;
1158 }
1159
1160 // The private mapping created for this process has been mremaped. We can
1161 // reset it.
1162 child_mapping_methods.Reset();
1163 LOG(INFO) << "Successfully mapped boot image methods";
1164 }
1165
1166 // Return whether a boot image has a profile. This means we'll need to pre-JIT
1167 // methods in that profile for performance.
HasImageWithProfile()1168 static bool HasImageWithProfile() {
1169 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1170 if (!space->GetProfileFile().empty()) {
1171 return true;
1172 }
1173 }
1174 return false;
1175 }
1176
InZygoteUsingJit()1177 bool Jit::InZygoteUsingJit() {
1178 Runtime* runtime = Runtime::Current();
1179 return runtime->IsZygote() && HasImageWithProfile() && runtime->UseJitCompilation();
1180 }
1181
CreateThreadPool()1182 void Jit::CreateThreadPool() {
1183 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1184 // is not null when we instrument.
1185
1186 // We need peers as we may report the JIT thread, e.g., in the debugger.
1187 constexpr bool kJitPoolNeedsPeers = true;
1188 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1189
1190 Runtime* runtime = Runtime::Current();
1191 thread_pool_->SetPthreadPriority(
1192 runtime->IsZygote()
1193 ? options_->GetZygoteThreadPoolPthreadPriority()
1194 : options_->GetThreadPoolPthreadPriority());
1195 Start();
1196
1197 if (runtime->IsZygote()) {
1198 // To speed up class lookups, generate a type lookup table for
1199 // dex files not backed by oat file.
1200 for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
1201 if (dex_file->GetOatDexFile() == nullptr) {
1202 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1203 type_lookup_tables_.push_back(
1204 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1205 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1206 }
1207 }
1208
1209 // Add a task that will verify boot classpath jars that were not
1210 // pre-compiled.
1211 thread_pool_->AddTask(Thread::Current(), new ZygoteVerificationTask());
1212 }
1213
1214 if (InZygoteUsingJit()) {
1215 // If we have an image with a profile, request a JIT task to
1216 // compile all methods in that profile.
1217 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
1218
1219 // And create mappings to share boot image methods memory from the zygote to
1220 // child processes.
1221
1222 // Compute the total capacity required for the boot image methods.
1223 uint64_t total_capacity = 0;
1224 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1225 const ImageHeader& header = space->GetImageHeader();
1226 const ImageSection& section = header.GetMethodsSection();
1227 // Mappings need to be at the page level.
1228 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1229 uint8_t* page_end =
1230 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1231 if (page_end > page_start) {
1232 total_capacity += (page_end - page_start);
1233 }
1234 }
1235
1236 // Create the child and zygote mappings to the boot image methods.
1237 if (total_capacity > 0) {
1238 // Start with '/boot' and end with '.art' to match the pattern recognized
1239 // by android_os_Debug.cpp for boot images.
1240 const char* name = "/boot-image-methods.art";
1241 unique_fd mem_fd =
1242 unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING | MFD_CLOEXEC));
1243 if (mem_fd.get() == -1) {
1244 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1245 return;
1246 }
1247 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1248 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1249 return;
1250 }
1251 std::string error_str;
1252
1253 // Create the shared mapping eagerly, as this prevents other processes
1254 // from adding the writable seal.
1255 zygote_mapping_methods_ = MemMap::MapFile(
1256 total_capacity,
1257 PROT_READ | PROT_WRITE,
1258 MAP_SHARED,
1259 mem_fd,
1260 /* start= */ 0,
1261 /* low_4gb= */ false,
1262 "boot-image-methods",
1263 &error_str);
1264
1265 if (!zygote_mapping_methods_.IsValid()) {
1266 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1267 return;
1268 }
1269 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1270 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1271 zygote_mapping_methods_ = MemMap();
1272 return;
1273 }
1274
1275 // We should use the F_SEAL_FUTURE_WRITE flag, but this has unexpected
1276 // behavior on private mappings after fork (the mapping becomes shared between
1277 // parent and children), see b/143833776.
1278 // We will seal the write once we are done writing to the shared mapping.
1279 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1280 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1281 zygote_mapping_methods_ = MemMap();
1282 return;
1283 }
1284 fd_methods_ = unique_fd(mem_fd.release());
1285 fd_methods_size_ = total_capacity;
1286 }
1287 }
1288 }
1289
RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>> & dex_files,jobject class_loader)1290 void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
1291 jobject class_loader) {
1292 if (dex_files.empty()) {
1293 return;
1294 }
1295 Runtime* runtime = Runtime::Current();
1296 // If the runtime is debuggable, no need to precompile methods.
1297 if (runtime->IsSystemServer() &&
1298 UseJitCompilation() &&
1299 options_->UseProfiledJitCompilation() &&
1300 HasImageWithProfile() &&
1301 !runtime->IsJavaDebuggable()) {
1302 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1303 }
1304 }
1305
CompileMethodFromProfile(Thread * self,ClassLinker * class_linker,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool add_to_queue,bool compile_after_boot)1306 bool Jit::CompileMethodFromProfile(Thread* self,
1307 ClassLinker* class_linker,
1308 uint32_t method_idx,
1309 Handle<mirror::DexCache> dex_cache,
1310 Handle<mirror::ClassLoader> class_loader,
1311 bool add_to_queue,
1312 bool compile_after_boot) {
1313 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1314 method_idx, dex_cache, class_loader);
1315 if (method == nullptr) {
1316 self->ClearException();
1317 return false;
1318 }
1319 if (!method->IsCompilable() || !method->IsInvokable()) {
1320 return false;
1321 }
1322 if (method->IsPreCompiled()) {
1323 // Already seen by another profile.
1324 return false;
1325 }
1326 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1327 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1328 class_linker->IsQuickGenericJniStub(entry_point) ||
1329 (entry_point == interpreter::GetNterpEntryPoint()) ||
1330 // We explicitly check for the stub. The trampoline is for methods backed by
1331 // a .oat file that has a compiled version of the method.
1332 (entry_point == GetQuickResolutionStub())) {
1333 method->SetPreCompiled();
1334 if (!add_to_queue) {
1335 CompileMethod(method, self, CompilationKind::kOptimized, /* prejit= */ true);
1336 } else {
1337 Task* task = new JitCompileTask(
1338 method, JitCompileTask::TaskKind::kPreCompile, CompilationKind::kOptimized);
1339 if (compile_after_boot) {
1340 MutexLock mu(Thread::Current(), boot_completed_lock_);
1341 if (!boot_completed_) {
1342 tasks_after_boot_.push_back(task);
1343 return true;
1344 }
1345 DCHECK(tasks_after_boot_.empty());
1346 }
1347 thread_pool_->AddTask(self, task);
1348 return true;
1349 }
1350 }
1351 return false;
1352 }
1353
CompileMethodsFromBootProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1354 uint32_t Jit::CompileMethodsFromBootProfile(
1355 Thread* self,
1356 const std::vector<const DexFile*>& dex_files,
1357 const std::string& profile_file,
1358 Handle<mirror::ClassLoader> class_loader,
1359 bool add_to_queue) {
1360 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1361
1362 if (profile.Fd() == -1) {
1363 PLOG(WARNING) << "No boot profile: " << profile_file;
1364 return 0u;
1365 }
1366
1367 ProfileBootInfo profile_info;
1368 if (!profile_info.Load(profile.Fd(), dex_files)) {
1369 LOG(ERROR) << "Could not load profile file: " << profile_file;
1370 return 0u;
1371 }
1372
1373 ScopedObjectAccess soa(self);
1374 VariableSizedHandleScope handles(self);
1375 std::vector<Handle<mirror::DexCache>> dex_caches;
1376 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1377 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1378 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1379 }
1380
1381 uint32_t added_to_queue = 0;
1382 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1383 if (CompileMethodFromProfile(self,
1384 class_linker,
1385 pair.second,
1386 dex_caches[pair.first],
1387 class_loader,
1388 add_to_queue,
1389 /*compile_after_boot=*/false)) {
1390 ++added_to_queue;
1391 }
1392 }
1393 return added_to_queue;
1394 }
1395
CompileMethodsFromProfile(Thread * self,const std::vector<const DexFile * > & dex_files,const std::string & profile_file,Handle<mirror::ClassLoader> class_loader,bool add_to_queue)1396 uint32_t Jit::CompileMethodsFromProfile(
1397 Thread* self,
1398 const std::vector<const DexFile*>& dex_files,
1399 const std::string& profile_file,
1400 Handle<mirror::ClassLoader> class_loader,
1401 bool add_to_queue) {
1402
1403 if (profile_file.empty()) {
1404 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
1405 return 0u;
1406 }
1407
1408 // We don't generate boot profiles on device, therefore we don't
1409 // need to lock the file.
1410 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1411
1412 if (profile.Fd() == -1) {
1413 PLOG(WARNING) << "No profile: " << profile_file;
1414 return 0u;
1415 }
1416
1417 ProfileCompilationInfo profile_info;
1418 if (!profile_info.Load(profile.Fd())) {
1419 LOG(ERROR) << "Could not load profile file";
1420 return 0u;
1421 }
1422 ScopedObjectAccess soa(self);
1423 StackHandleScope<1> hs(self);
1424 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
1425 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1426 uint32_t added_to_queue = 0u;
1427 for (const DexFile* dex_file : dex_files) {
1428 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1429 // The ART module jars are already preopted.
1430 continue;
1431 }
1432
1433 std::set<dex::TypeIndex> class_types;
1434 std::set<uint16_t> all_methods;
1435 if (!profile_info.GetClassesAndMethods(*dex_file,
1436 &class_types,
1437 &all_methods,
1438 &all_methods,
1439 &all_methods)) {
1440 // This means the profile file did not reference the dex file, which is the case
1441 // if there's no classes and methods of that dex file in the profile.
1442 continue;
1443 }
1444 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1445 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
1446
1447 for (uint16_t method_idx : all_methods) {
1448 if (CompileMethodFromProfile(self,
1449 class_linker,
1450 method_idx,
1451 dex_cache,
1452 class_loader,
1453 add_to_queue,
1454 /*compile_after_boot=*/true)) {
1455 ++added_to_queue;
1456 }
1457 }
1458 }
1459
1460 // Add a task to run when all compilation is done.
1461 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
1462 MutexLock mu(Thread::Current(), boot_completed_lock_);
1463 if (!boot_completed_) {
1464 tasks_after_boot_.push_back(task);
1465 } else {
1466 DCHECK(tasks_after_boot_.empty());
1467 thread_pool_->AddTask(self, task);
1468 }
1469 return added_to_queue;
1470 }
1471
IgnoreSamplesForMethod(ArtMethod * method)1472 bool Jit::IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1473 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
1474 // We do not want to compile such methods.
1475 return true;
1476 }
1477 if (method->IsNative()) {
1478 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1479 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1480 klass == GetClassRoot<mirror::VarHandle>()) {
1481 // MethodHandle and VarHandle invocation methods are required to throw an
1482 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
1483 // implementations that raise the exception. We need to disable JIT compilation of these JNI
1484 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1485 // stubs. Since these stubs have different stack representations we can then crash in stack
1486 // walking (b/78151261).
1487 return true;
1488 }
1489 }
1490 return false;
1491 }
1492
MaybeCompileMethod(Thread * self,ArtMethod * method,uint32_t old_count,uint32_t new_count,bool with_backedges)1493 bool Jit::MaybeCompileMethod(Thread* self,
1494 ArtMethod* method,
1495 uint32_t old_count,
1496 uint32_t new_count,
1497 bool with_backedges) {
1498 if (thread_pool_ == nullptr) {
1499 return false;
1500 }
1501 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
1502 if (!NeedsClinitCheckBeforeCall(method) ||
1503 method->GetDeclaringClass()->IsVisiblyInitialized()) {
1504 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1505 if (entry_point != nullptr) {
1506 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1507 return true;
1508 }
1509 }
1510 }
1511
1512 if (IgnoreSamplesForMethod(method)) {
1513 return false;
1514 }
1515 if (HotMethodThreshold() == 0) {
1516 // Tests might request JIT on first use (compiled synchronously in the interpreter).
1517 return false;
1518 }
1519 DCHECK_GT(WarmMethodThreshold(), 0);
1520 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1521 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1522 DCHECK_GE(PriorityThreadWeight(), 1);
1523 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
1524
1525 if (UseJitCompilation()) {
1526 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1527 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1528 DCHECK(thread_pool_ != nullptr);
1529 thread_pool_->AddTask(
1530 self,
1531 new JitCompileTask(
1532 method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
1533 }
1534 }
1535 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
1536 if (!with_backedges) {
1537 return false;
1538 }
1539 DCHECK(!method->IsNative()); // No back edges reported for native methods.
1540 if (!code_cache_->IsOsrCompiled(method)) {
1541 DCHECK(thread_pool_ != nullptr);
1542 thread_pool_->AddTask(
1543 self,
1544 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1545 }
1546 }
1547 }
1548 return true;
1549 }
1550
EnqueueOptimizedCompilation(ArtMethod * method,Thread * self)1551 void Jit::EnqueueOptimizedCompilation(ArtMethod* method, Thread* self) {
1552 if (thread_pool_ == nullptr) {
1553 return;
1554 }
1555 // We arrive here after a baseline compiled code has reached its baseline
1556 // hotness threshold. If we're not only using the baseline compiler, enqueue a compilation
1557 // task that will compile optimize the method.
1558 if (!options_->UseBaselineCompiler()) {
1559 thread_pool_->AddTask(
1560 self,
1561 new JitCompileTask(method,
1562 JitCompileTask::TaskKind::kCompile,
1563 CompilationKind::kOptimized));
1564 }
1565 }
1566
1567 class ScopedSetRuntimeThread {
1568 public:
ScopedSetRuntimeThread(Thread * self)1569 explicit ScopedSetRuntimeThread(Thread* self)
1570 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1571 self_->SetIsRuntimeThread(true);
1572 }
1573
~ScopedSetRuntimeThread()1574 ~ScopedSetRuntimeThread() {
1575 self_->SetIsRuntimeThread(was_runtime_thread_);
1576 }
1577
1578 private:
1579 Thread* self_;
1580 bool was_runtime_thread_;
1581 };
1582
MethodEntered(Thread * thread,ArtMethod * method)1583 void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
1584 Runtime* runtime = Runtime::Current();
1585 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
1586 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
1587 if (np_method->IsCompilable()) {
1588 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1589 // conflicts with jitzygote optimizations.
1590 JitCompileTask compile_task(
1591 method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOptimized);
1592 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1593 ScopedSetRuntimeThread ssrt(thread);
1594 compile_task.Run(thread);
1595 }
1596 return;
1597 }
1598
1599 AddSamples(thread, method, 1, /* with_backedges= */false);
1600 }
1601
WaitForCompilationToFinish(Thread * self)1602 void Jit::WaitForCompilationToFinish(Thread* self) {
1603 if (thread_pool_ != nullptr) {
1604 thread_pool_->Wait(self, false, false);
1605 }
1606 }
1607
Stop()1608 void Jit::Stop() {
1609 Thread* self = Thread::Current();
1610 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1611 WaitForCompilationToFinish(self);
1612 GetThreadPool()->StopWorkers(self);
1613 WaitForCompilationToFinish(self);
1614 }
1615
Start()1616 void Jit::Start() {
1617 GetThreadPool()->StartWorkers(Thread::Current());
1618 }
1619
ScopedJitSuspend()1620 ScopedJitSuspend::ScopedJitSuspend() {
1621 jit::Jit* jit = Runtime::Current()->GetJit();
1622 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1623 if (was_on_) {
1624 jit->Stop();
1625 }
1626 }
1627
~ScopedJitSuspend()1628 ScopedJitSuspend::~ScopedJitSuspend() {
1629 if (was_on_) {
1630 DCHECK(Runtime::Current()->GetJit() != nullptr);
1631 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
1632 Runtime::Current()->GetJit()->Start();
1633 }
1634 }
1635
RunPollingThread(void * arg)1636 static void* RunPollingThread(void* arg) {
1637 Jit* jit = reinterpret_cast<Jit*>(arg);
1638 do {
1639 sleep(10);
1640 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
1641
1642 // We will suspend other threads: we can only do that if we're attached to the
1643 // runtime.
1644 Runtime* runtime = Runtime::Current();
1645 bool thread_attached = runtime->AttachCurrentThread(
1646 "BootImagePollingThread",
1647 /* as_daemon= */ true,
1648 /* thread_group= */ nullptr,
1649 /* create_peer= */ false);
1650 CHECK(thread_attached);
1651
1652 {
1653 // Prevent other threads from running while we are remapping the boot image
1654 // ArtMethod's. Native threads might still be running, but they cannot
1655 // change the contents of ArtMethod's.
1656 ScopedSuspendAll ssa(__FUNCTION__);
1657 runtime->GetJit()->MapBootImageMethods();
1658 }
1659
1660 Runtime::Current()->DetachCurrentThread();
1661 return nullptr;
1662 }
1663
PostForkChildAction(bool is_system_server,bool is_zygote)1664 void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
1665 // Clear the potential boot tasks inherited from the zygote.
1666 {
1667 MutexLock mu(Thread::Current(), boot_completed_lock_);
1668 tasks_after_boot_.clear();
1669 }
1670
1671 Runtime* const runtime = Runtime::Current();
1672 // Check if we'll need to remap the boot image methods.
1673 if (!is_zygote && fd_methods_ != -1) {
1674 // Create a thread that will poll the status of zygote compilation, and map
1675 // the private mapping of boot image methods.
1676 // For child zygote, we instead query IsCompilationNotified() post zygote fork.
1677 zygote_mapping_methods_.ResetInForkedProcess();
1678 pthread_t polling_thread;
1679 pthread_attr_t attr;
1680 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1681 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1682 "PTHREAD_CREATE_DETACHED");
1683 CHECK_PTHREAD_CALL(
1684 pthread_create,
1685 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1686 "Methods maps thread");
1687 }
1688
1689 if (is_zygote || runtime->IsSafeMode()) {
1690 // Delete the thread pool, we are not going to JIT.
1691 thread_pool_.reset(nullptr);
1692 return;
1693 }
1694 // At this point, the compiler options have been adjusted to the particular configuration
1695 // of the forked child. Parse them again.
1696 jit_compiler_->ParseCompilerOptions();
1697
1698 // Adjust the status of code cache collection: the status from zygote was to not collect.
1699 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
1700 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
1701
1702 if (is_system_server && HasImageWithProfile()) {
1703 // Disable garbage collection: we don't want it to delete methods we're compiling
1704 // through boot and system server profiles.
1705 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1706 code_cache_->SetGarbageCollectCode(false);
1707 }
1708
1709 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1710 // applies to a child.
1711 NativeDebugInfoPostFork();
1712 }
1713
PreZygoteFork()1714 void Jit::PreZygoteFork() {
1715 if (thread_pool_ == nullptr) {
1716 return;
1717 }
1718 thread_pool_->DeleteThreads();
1719
1720 NativeDebugInfoPreFork();
1721 }
1722
PostZygoteFork()1723 void Jit::PostZygoteFork() {
1724 Runtime* runtime = Runtime::Current();
1725 if (thread_pool_ == nullptr) {
1726 // If this is a child zygote, check if we need to remap the boot image
1727 // methods.
1728 if (runtime->IsZygote() &&
1729 fd_methods_ != -1 &&
1730 code_cache_->GetZygoteMap()->IsCompilationNotified()) {
1731 ScopedSuspendAll ssa(__FUNCTION__);
1732 MapBootImageMethods();
1733 }
1734 return;
1735 }
1736 if (runtime->IsZygote() && code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1737 // Copy the boot image methods data to the mappings we created to share
1738 // with the children. We do this here as we are the only thread running and
1739 // we don't risk other threads concurrently updating the ArtMethod's.
1740 CHECK_EQ(GetTaskCount(), 1);
1741 NotifyZygoteCompilationDone();
1742 CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1743 }
1744 thread_pool_->CreateThreads();
1745 thread_pool_->SetPthreadPriority(
1746 runtime->IsZygote()
1747 ? options_->GetZygoteThreadPoolPthreadPriority()
1748 : options_->GetThreadPoolPthreadPriority());
1749 }
1750
BootCompleted()1751 void Jit::BootCompleted() {
1752 Thread* self = Thread::Current();
1753 std::deque<Task*> tasks;
1754 {
1755 MutexLock mu(self, boot_completed_lock_);
1756 tasks = std::move(tasks_after_boot_);
1757 boot_completed_ = true;
1758 }
1759 for (Task* task : tasks) {
1760 thread_pool_->AddTask(self, task);
1761 }
1762 }
1763
CanEncodeMethod(ArtMethod * method,bool is_for_shared_region) const1764 bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1765 return !is_for_shared_region ||
1766 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
1767 }
1768
CanEncodeClass(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1769 bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1770 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
1771 }
1772
CanEncodeString(ObjPtr<mirror::String> string,bool is_for_shared_region) const1773 bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
1774 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
1775 }
1776
CanAssumeInitialized(ObjPtr<mirror::Class> cls,bool is_for_shared_region) const1777 bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1778 if (!is_for_shared_region) {
1779 return cls->IsInitialized();
1780 } else {
1781 // Look up the class status in the oat file.
1782 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1783 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1784 // In case we run without an image there won't be a backing oat file.
1785 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1786 return false;
1787 }
1788 uint16_t class_def_index = cls->GetDexClassDefIndex();
1789 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1790 }
1791 }
1792
EnqueueCompilationFromNterp(ArtMethod * method,Thread * self)1793 void Jit::EnqueueCompilationFromNterp(ArtMethod* method, Thread* self) {
1794 if (thread_pool_ == nullptr) {
1795 return;
1796 }
1797 if (GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1798 // If we already have compiled code for it, nterp may be stuck in a loop.
1799 // Compile OSR.
1800 thread_pool_->AddTask(
1801 self,
1802 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
1803 return;
1804 }
1805 if (GetCodeCache()->CanAllocateProfilingInfo()) {
1806 thread_pool_->AddTask(
1807 self,
1808 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
1809 } else {
1810 thread_pool_->AddTask(
1811 self,
1812 new JitCompileTask(method,
1813 JitCompileTask::TaskKind::kCompile,
1814 CompilationKind::kOptimized));
1815 }
1816 }
1817
1818 } // namespace jit
1819 } // namespace art
1820