• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef PANDA_RUNTIME_COMPILER_H_
16 #define PANDA_RUNTIME_COMPILER_H_
17 
18 #include "compiler/compile_method.h"
19 #include "compiler/compiler_task_runner.h"
20 #include "compiler/optimizer/ir/runtime_interface.h"
21 #include "libpandabase/mem/code_allocator.h"
22 #include "libpandabase/os/mutex.h"
23 #include "runtime/entrypoints/entrypoints.h"
24 #include "runtime/include/hclass.h"
25 #include "runtime/include/compiler_interface.h"
26 #include "runtime/include/coretypes/array.h"
27 #include "runtime/include/coretypes/tagged_value.h"
28 #include "runtime/include/locks.h"
29 #include "runtime/include/mem/panda_containers.h"
30 #include "runtime/include/method.h"
31 #include "runtime/include/runtime_options.h"
32 #include "runtime/interpreter/frame.h"
33 #include "runtime/mem/gc/gc_barrier_set.h"
34 #include "runtime/mem/tlab.h"
35 #include "runtime/compiler_thread_pool_worker.h"
36 #include "runtime/compiler_task_manager_worker.h"
37 #include "runtime/include/thread.h"
38 
39 #include "runtime/osr.h"
40 
41 namespace ark {
42 
43 using compiler::RuntimeInterface;
44 using compiler::UnresolvedTypesInterface;
45 
MethodCast(RuntimeInterface::MethodPtr method)46 inline ark::Method *MethodCast(RuntimeInterface::MethodPtr method)
47 {
48     return static_cast<ark::Method *>(method);
49 }
50 
51 struct ScopedMutatorLock : public os::memory::ReadLockHolder<MutatorLock> {
ScopedMutatorLockScopedMutatorLock52     ScopedMutatorLock() : os::memory::ReadLockHolder<MutatorLock>(*PandaVM::GetCurrent()->GetMutatorLock()) {}
53 };
54 
55 class PANDA_PUBLIC_API ClassHierarchyAnalysisWrapper : public compiler::IClassHierarchyAnalysis {
56 public:
GetSingleImplementation(RuntimeInterface::MethodPtr method)57     RuntimeInterface::MethodPtr GetSingleImplementation(RuntimeInterface::MethodPtr method) override
58     {
59         return static_cast<Method *>(method)->GetSingleImplementation();
60     }
IsSingleImplementation(RuntimeInterface::MethodPtr method)61     bool IsSingleImplementation(RuntimeInterface::MethodPtr method) override
62     {
63         return static_cast<Method *>(method)->HasSingleImplementation();
64     }
65     void AddDependency(RuntimeInterface::MethodPtr callee, RuntimeInterface::MethodPtr caller) override;
66 };
67 
68 class PANDA_PUBLIC_API InlineCachesWrapper : public compiler::InlineCachesInterface {
69 public:
70     CallKind GetClasses(RuntimeInterface::MethodPtr m, uintptr_t pc,
71                         ArenaVector<RuntimeInterface::ClassPtr> *classes) override;
72 };
73 
74 class PANDA_PUBLIC_API UnresolvedTypesWrapper : public UnresolvedTypesInterface {
75 public:
76     bool AddTableSlot(RuntimeInterface::MethodPtr method, uint32_t typeId, SlotKind kind) override;
77     uintptr_t GetTableSlot(RuntimeInterface::MethodPtr method, uint32_t typeId, SlotKind kind) const override;
78 
79 private:
80     PandaMap<RuntimeInterface::MethodPtr, PandaMap<std::pair<uint32_t, SlotKind>, uintptr_t>> slots_;
81 };
82 
83 class PANDA_PUBLIC_API PandaRuntimeInterface : public RuntimeInterface {
84 public:
GetRuntimeEntry()85     void *GetRuntimeEntry() override
86     {
87         return nullptr;
88     }
89 
GetCha()90     compiler::IClassHierarchyAnalysis *GetCha() override
91     {
92         return &cha_;
93     }
94 
GetInlineCaches()95     compiler::InlineCachesInterface *GetInlineCaches() override
96     {
97         return &inlineCaches_;
98     }
99 
GetUnresolvedTypes()100     compiler::UnresolvedTypesInterface *GetUnresolvedTypes() override
101     {
102         return &unresolvedTypes_;
103     }
104 
GetReturnReasonOk()105     unsigned GetReturnReasonOk() const override
106     {
107         return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_OK);
108     }
GetReturnReasonDeopt()109     unsigned GetReturnReasonDeopt() const override
110     {
111         return static_cast<unsigned>(CompilerInterface::ReturnReason::RET_DEOPTIMIZATION);
112     }
113 
ClassCast(ClassPtr cls)114     ark::Class *ClassCast(ClassPtr cls) const
115     {
116         return static_cast<ark::Class *>(cls);
117     }
118 
GetStackOverflowCheckOffset()119     size_t GetStackOverflowCheckOffset() const override
120     {
121         return ManagedThread::GetStackOverflowCheckOffset();
122     }
123 
124     /**********************************************************************************/
125     /// Binary file information
GetBinaryFileForMethod(MethodPtr method)126     BinaryFilePtr GetBinaryFileForMethod(MethodPtr method) const override
127     {
128         return const_cast<panda_file::File *>(MethodCast(method)->GetPandaFile());
129     }
130 
131     MethodId ResolveMethodIndex(MethodPtr parentMethod, MethodIndex index) const override;
132 
133     FieldId ResolveFieldIndex(MethodPtr parentMethod, FieldIndex index) const override;
134 
135     IdType ResolveTypeIndex(MethodPtr parentMethod, TypeIndex index) const override;
136 
137     /**********************************************************************************/
138     /// Method information
139     MethodPtr GetMethodById(MethodPtr parentMethod, MethodId id) const override;
140 
141     MethodId GetMethodId(MethodPtr method) const override;
142 
143     IntrinsicId GetIntrinsicId([[maybe_unused]] MethodPtr method) const override;
144 
145     uint64_t GetUniqMethodId(MethodPtr method) const override;
146 
147     MethodPtr ResolveVirtualMethod(ClassPtr cls, MethodPtr method) const override;
148 
149     MethodPtr ResolveInterfaceMethod(ClassPtr cls, MethodPtr method) const override;
150 
GetMethodReturnType(MethodPtr method)151     compiler::DataType::Type GetMethodReturnType(MethodPtr method) const override
152     {
153         return ToCompilerType(MethodCast(method)->GetEffectiveReturnType());
154     }
155 
156     IdType GetMethodReturnTypeId(MethodPtr method) const override;
157     IdType GetMethodArgReferenceTypeId(MethodPtr method, uint16_t num) const override;
158 
GetMethodTotalArgumentType(MethodPtr method,size_t index)159     compiler::DataType::Type GetMethodTotalArgumentType(MethodPtr method, size_t index) const override
160     {
161         return ToCompilerType(MethodCast(method)->GetEffectiveArgType(index));
162     }
GetMethodTotalArgumentsCount(MethodPtr method)163     size_t GetMethodTotalArgumentsCount(MethodPtr method) const override
164     {
165         return MethodCast(method)->GetNumArgs();
166     }
167 
168     bool IsMemoryBarrierRequired(MethodPtr method) const override;
169 
170     compiler::DataType::Type GetMethodReturnType(MethodPtr parentMethod, MethodId id) const override;
171 
172     compiler::DataType::Type GetMethodArgumentType(MethodPtr parentMethod, MethodId id, size_t index) const override;
173 
174     size_t GetMethodArgumentsCount(MethodPtr parentMethod, MethodId id) const override;
GetMethodArgumentsCount(MethodPtr method)175     size_t GetMethodArgumentsCount(MethodPtr method) const override
176     {
177         return MethodCast(method)->GetNumArgs();
178     }
GetMethodRegistersCount(MethodPtr method)179     size_t GetMethodRegistersCount(MethodPtr method) const override
180     {
181         return MethodCast(method)->GetNumVregs();
182     }
GetMethodCode(MethodPtr method)183     const uint8_t *GetMethodCode(MethodPtr method) const override
184     {
185         return MethodCast(method)->GetInstructions();
186     }
GetMethodCodeSize(MethodPtr method)187     size_t GetMethodCodeSize(MethodPtr method) const override
188     {
189         return MethodCast(method)->GetCodeSize();
190     }
GetMethodSourceLanguage(MethodPtr method)191     SourceLanguage GetMethodSourceLanguage(MethodPtr method) const override
192     {
193         return static_cast<SourceLanguage>(MethodCast(method)->GetClass()->GetSourceLang());
194     }
SetCompiledEntryPoint(MethodPtr method,void * ep)195     void SetCompiledEntryPoint(MethodPtr method, void *ep) override
196     {
197         MethodCast(method)->SetCompiledEntryPoint(ep);
198     }
TrySetOsrCode(MethodPtr method,void * ep)199     bool TrySetOsrCode(MethodPtr method, void *ep) override
200     {
201         ScopedMutatorLock lock;
202         // Ignore OSR code if method was deoptimized during OSR compilation
203         if (!static_cast<const Method *>(method)->HasCompiledCode()) {
204             return false;
205         }
206         CompilerInterface *compiler = Thread::GetCurrent()->GetVM()->GetCompiler();
207         ASSERT(compiler->GetOsrCode(static_cast<const Method *>(method)) == nullptr);
208         compiler->SetOsrCode(static_cast<const Method *>(method), ep);
209         return true;
210     }
GetOsrCode(MethodPtr method)211     void *GetOsrCode(MethodPtr method) override
212     {
213         return Thread::GetCurrent()->GetVM()->GetCompiler()->GetOsrCode(static_cast<const Method *>(method));
214     }
HasCompiledCode(MethodPtr method)215     bool HasCompiledCode(MethodPtr method) override
216     {
217         return MethodCast(method)->HasCompiledCode();
218     }
219 
IsInstantiable(ClassPtr klass)220     bool IsInstantiable(ClassPtr klass) const override
221     {
222         return ClassCast(klass)->IsInstantiable();
223     }
224 
GetAccessFlagAbstractMask()225     uint32_t GetAccessFlagAbstractMask() const override
226     {
227         return ark::ACC_ABSTRACT;
228     }
229 
GetVTableIndex(MethodPtr method)230     uint32_t GetVTableIndex(MethodPtr method) const override
231     {
232         return MethodCast(method)->GetVTableIndex();
233     }
234 
GetClassIdForField(MethodPtr method,size_t fieldId)235     size_t GetClassIdForField(MethodPtr method, size_t fieldId) const override
236     {
237         auto fda =
238             panda_file::FieldDataAccessor(*MethodCast(method)->GetPandaFile(), panda_file::File::EntityId(fieldId));
239         return fda.GetClassId().GetOffset();
240     }
241 
GetClassIdForField(FieldPtr field)242     size_t GetClassIdForField(FieldPtr field) const override
243     {
244         return FieldCast(field)->GetClass()->GetFileId().GetOffset();
245     }
246 
247     ClassPtr GetClassForField(FieldPtr field) const override;
248 
GetClassIdForMethod(MethodPtr method)249     uint32_t GetClassIdForMethod(MethodPtr method) const override
250     {
251         auto mda = panda_file::MethodDataAccessor(*MethodCast(method)->GetPandaFile(), MethodCast(method)->GetFileId());
252         return mda.GetClassId().GetOffset();
253     }
254 
GetClassIdForMethod(MethodPtr parentMethod,size_t methodId)255     uint32_t GetClassIdForMethod(MethodPtr parentMethod, size_t methodId) const override
256     {
257         auto mda = panda_file::MethodDataAccessor(*MethodCast(parentMethod)->GetPandaFile(),
258                                                   panda_file::File::EntityId(methodId));
259         return mda.GetClassId().GetOffset();
260     }
261 
262     bool HasNativeException(MethodPtr method) const override;
263     bool IsMethodExternal(MethodPtr parentMethod, MethodPtr calleeMethod) const override;
264 
IsMethodIntrinsic(MethodPtr method)265     bool IsMethodIntrinsic(MethodPtr method) const override
266     {
267         return MethodCast(method)->IsIntrinsic();
268     }
269 
IsMethodAbstract(MethodPtr method)270     bool IsMethodAbstract(MethodPtr method) const override
271     {
272         return MethodCast(method)->IsAbstract();
273     }
274 
275     bool IsMethodIntrinsic(MethodPtr parentMethod, MethodId id) const override;
276 
IsMethodFinal(MethodPtr method)277     bool IsMethodFinal(MethodPtr method) const override
278     {
279         return MethodCast(method)->IsFinal();
280     }
281 
282     bool IsMethodStatic(MethodPtr parentMethod, MethodId id) const override;
283     bool IsMethodStatic(MethodPtr method) const override;
284 
IsMethodCanBeInlined(MethodPtr method)285     bool IsMethodCanBeInlined(MethodPtr method) const override
286     {
287         auto methodPtr = MethodCast(method);
288         if (Runtime::GetCurrent()->GetOptions().GetVerificationMode() == VerificationMode::ON_THE_FLY &&
289             methodPtr->GetVerificationStage() != Method::VerificationStage::VERIFIED_OK) {
290             return false;
291         }
292         return !(methodPtr->IsIntrinsic() || methodPtr->IsNative() || methodPtr->IsAbstract());
293     }
294 
295     bool IsMethodStaticConstructor([[maybe_unused]] MethodPtr method) const override;
296 
GetFileName(MethodPtr method)297     std::string GetFileName(MethodPtr method) const override
298     {
299         return MethodCast(method)->GetPandaFile()->GetFilename();
300     }
301 
GetFullFileName(MethodPtr method)302     std::string GetFullFileName(MethodPtr method) const override
303     {
304         return MethodCast(method)->GetPandaFile()->GetFullFileName();
305     }
306 
GetClassNameFromMethod(MethodPtr method)307     std::string GetClassNameFromMethod(MethodPtr method) const override
308     {
309         ScopedMutatorLock lock;
310         return MethodCast(method)->GetClass()->GetName();
311     }
312 
GetClassName(ClassPtr cls)313     std::string GetClassName(ClassPtr cls) const override
314     {
315         ScopedMutatorLock lock;
316         return ClassCast(cls)->GetName();
317     }
318 
GetMethodName(MethodPtr method)319     std::string GetMethodName(MethodPtr method) const override
320     {
321         return utf::Mutf8AsCString(MethodCast(method)->GetName().data);
322     }
323 
GetLineNumberAndSourceFile(MethodPtr method,uint32_t pc)324     std::string GetLineNumberAndSourceFile(MethodPtr method, uint32_t pc) const override
325     {
326         return std::string(MethodCast(method)->GetLineNumberAndSourceFile(pc));
327     }
328 
GetBranchTakenCounter(MethodPtr method,uint32_t pc)329     int64_t GetBranchTakenCounter(MethodPtr method, uint32_t pc) const override
330     {
331         return MethodCast(method)->GetBranchTakenCounter(pc);
332     }
333 
GetBranchNotTakenCounter(MethodPtr method,uint32_t pc)334     int64_t GetBranchNotTakenCounter(MethodPtr method, uint32_t pc) const override
335     {
336         return MethodCast(method)->GetBranchNotTakenCounter(pc);
337     }
338 
GetThrowTakenCounter(MethodPtr method,uint32_t pc)339     int64_t GetThrowTakenCounter(MethodPtr method, uint32_t pc) const override
340     {
341         return MethodCast(method)->GetThrowTakenCounter(pc);
342     }
343 
GetMethodFullName(MethodPtr method,bool withSignature)344     std::string GetMethodFullName(MethodPtr method, bool withSignature) const override
345     {
346         return std::string(MethodCast(method)->GetFullName(withSignature));
347     }
348 
GetClass(MethodPtr method)349     ClassPtr GetClass(MethodPtr method) const override
350     {
351         ScopedMutatorLock lock;
352         return reinterpret_cast<ClassPtr>(MethodCast(method)->GetClass());
353     }
354 
355     std::string GetBytecodeString(MethodPtr method, uintptr_t pc) const override;
356 
357     ark::pandasm::LiteralArray GetLiteralArray(MethodPtr method, LiteralArrayId id) const override;
358 
359     bool IsInterfaceMethod(MethodPtr parentMethod, MethodId id) const override;
360 
361     bool IsInterfaceMethod(MethodPtr method) const override;
362 
IsInstanceConstructor(MethodPtr method)363     bool IsInstanceConstructor(MethodPtr method) const override
364     {
365         return MethodCast(method)->IsInstanceConstructor();
366     }
367 
IsDestroyed(MethodPtr method)368     bool IsDestroyed(MethodPtr method) const override
369     {
370         return MethodCast(method)->IsDestroyed();
371     }
372 
373     bool CanThrowException(MethodPtr method) const override;
374 
375     uint32_t FindCatchBlock(MethodPtr method, ClassPtr cls, uint32_t pc) const override;
376 
377     /**********************************************************************************/
378     /// Thread information
379     ::ark::mem::BarrierType GetPreType() const override;
380 
381     ::ark::mem::BarrierType GetPostType() const override;
382 
383     ::ark::mem::BarrierOperand GetBarrierOperand(::ark::mem::BarrierPosition barrierPosition,
384                                                  std::string_view operandName) const override;
385 
386     /**********************************************************************************/
387     /// Array information
388     uint32_t GetArrayElementSize(MethodPtr method, IdType id) const override;
389 
390     uint32_t GetMaxArrayLength(ClassPtr klass) const override;
391 
392     uintptr_t GetPointerToConstArrayData(MethodPtr method, IdType id) const override;
393 
394     size_t GetOffsetToConstArrayData(MethodPtr method, IdType id) const override;
395 
396     ClassPtr GetArrayU16Class(MethodPtr method) const override;
397     /**********************************************************************************/
398     /// String information
IsCompressedStringsEnabled()399     bool IsCompressedStringsEnabled() const override
400     {
401         return ark::coretypes::String::GetCompressedStringsEnabled();
402     }
403 
404     ObjectPointerType GetNonMovableString(MethodPtr method, StringId id) const override;
405 
406     ClassPtr GetStringClass(MethodPtr method) const override;
407 
408     /**********************************************************************************/
409     /// TLAB information
410     size_t GetTLABMaxSize() const override;
411 
GetTLABAlignment()412     size_t GetTLABAlignment() const override
413     {
414         return DEFAULT_ALIGNMENT_IN_BYTES;
415     }
416 
IsTrackTlabAlloc()417     bool IsTrackTlabAlloc() const override
418     {
419         return ark::mem::PANDA_TRACK_TLAB_ALLOCATIONS ||
420                Logger::IsLoggingOn(Logger::Level::DEBUG, Logger::Component::MM_OBJECT_EVENTS);
421     }
422 
423     /**********************************************************************************/
424     /// Object information
425     ClassPtr GetClass(MethodPtr method, IdType id) const override;
426 
427     compiler::ClassType GetClassType(MethodPtr method, IdType id) const override;
428     compiler::ClassType GetClassType(ClassPtr klassPtr) const override;
429 
430     bool IsArrayClass(MethodPtr method, IdType id) const override;
431 
432     bool IsStringClass(MethodPtr method, IdType id) const override;
433 
IsArrayClass(ClassPtr cls)434     bool IsArrayClass(ClassPtr cls) const override
435     {
436         return ClassCast(cls)->IsArrayClass();
437     }
438 
439     ClassPtr GetArrayElementClass(ClassPtr cls) const override;
440 
441     bool CheckStoreArray(ClassPtr arrayCls, ClassPtr strCls) const override;
442 
443     bool IsAssignableFrom(ClassPtr cls1, ClassPtr cls2) const override;
444 
GetObjectHashedStatusBitNum()445     size_t GetObjectHashedStatusBitNum() const override
446     {
447         static_assert(MarkWord::MarkWordRepresentation::STATUS_SIZE == 2);
448         static_assert(MarkWord::MarkWordRepresentation::STATUS_HASHED == 2);
449         // preconditions above allow just check one bit
450         return MarkWord::MarkWordRepresentation::STATUS_SHIFT + 1;
451     }
452 
GetObjectHashShift()453     size_t GetObjectHashShift() const override
454     {
455         return MarkWord::MarkWordRepresentation::HASH_SHIFT;
456     }
457 
GetObjectHashMask()458     size_t GetObjectHashMask() const override
459     {
460         return MarkWord::MarkWordRepresentation::HASH_MASK;
461     }
462 
GetStringCtorType(MethodPtr ctorMethod)463     compiler::StringCtorType GetStringCtorType(MethodPtr ctorMethod) const override
464     {
465         return (std::strcmp(utf::Mutf8AsCString(MethodCast(ctorMethod)->GetRefArgType(1).data), "[C") == 0)
466                    ? compiler::StringCtorType::CHAR_ARRAY
467                    : compiler::StringCtorType::STRING;
468     }
469 
470     /**********************************************************************************/
471     /// Class information
GetClassInitializedValue()472     uint8_t GetClassInitializedValue() const override
473     {
474         return static_cast<uint8_t>(ark::Class::State::INITIALIZED);
475     }
476 
477     std::optional<IdType> FindClassIdInFile(MethodPtr method, ClassPtr cls) const;
478     IdType GetClassIdWithinFile(MethodPtr method, ClassPtr cls) const override;
479     IdType GetLiteralArrayClassIdWithinFile(MethodPtr method, panda_file::LiteralTag tag) const override;
480     bool CanUseTlabForClass(ClassPtr klass) const override;
481 
GetClassSize(ClassPtr klass)482     size_t GetClassSize(ClassPtr klass) const override
483     {
484         return ClassCast(klass)->GetObjectSize();
485     }
486 
487     bool CanScalarReplaceObject(ClassPtr klass) const override;
488 
489     /**********************************************************************************/
490     /// Field information
491 
492     FieldPtr ResolveField(MethodPtr method, size_t id, bool allowExternal, uint32_t *classId) override;
493     compiler::DataType::Type GetFieldType(FieldPtr field) const override;
494     compiler::DataType::Type GetArrayComponentType(ClassPtr klass) const override;
495     compiler::DataType::Type GetFieldTypeById(MethodPtr parentMethod, IdType id) const override;
496     IdType GetFieldValueTypeId(MethodPtr method, IdType id) const override;
497     size_t GetFieldOffset(FieldPtr field) const override;
498     FieldPtr GetFieldByOffset(size_t offset) const override;
499     uintptr_t GetFieldClass(FieldPtr field) const override;
500     bool IsFieldVolatile(FieldPtr field) const override;
501     bool IsFieldFinal(FieldPtr field) const override;
502     bool IsFieldReadonly(FieldPtr field) const override;
503     bool HasFieldMetadata(FieldPtr field) const override;
504     uint64_t GetStaticFieldValue(FieldPtr fieldPtr) const override;
505 
GetFieldName(FieldPtr field)506     std::string GetFieldName(FieldPtr field) const override
507     {
508         return utf::Mutf8AsCString(FieldCast(field)->GetName().data);
509     }
510 
FieldCast(FieldPtr field)511     ark::Field *FieldCast(FieldPtr field) const
512     {
513         ASSERT(HasFieldMetadata(field));
514         return static_cast<ark::Field *>(field);
515     }
516 
517     FieldId GetFieldId(FieldPtr field) const override;
518 
519     /**********************************************************************************/
520     /// Type information
521 
522     PandaRuntimeInterface::ClassPtr ResolveType(MethodPtr method, size_t id) const override;
523 
524     bool IsClassInitialized(uintptr_t klass) const override;
525 
IsClassFinal(ClassPtr klass)526     bool IsClassFinal(ClassPtr klass) const override
527     {
528         return ClassCast(klass)->IsFinal();
529     }
530 
IsInterface(ClassPtr klass)531     bool IsInterface(ClassPtr klass) const override
532     {
533         return ClassCast(klass)->IsInterface();
534     }
535 
536     uintptr_t GetManagedType(uintptr_t klass) const override;
537 
TypeCast(uintptr_t klass)538     ark::Class *TypeCast(uintptr_t klass) const
539     {
540         return reinterpret_cast<ark::Class *>(klass);
541     }
542 
GetReferenceTypeMask()543     uint8_t GetReferenceTypeMask() const override
544     {
545         return static_cast<uint8_t>(panda_file::Type::TypeId::REFERENCE);
546     }
547 
548     /**********************************************************************************/
549     /// Entrypoints
550     uintptr_t GetIntrinsicAddress(bool runtimeCall, SourceLanguage lang, IntrinsicId id) const override;
551 
552     /**********************************************************************************/
553     /// Dynamic object information
554 
555     uint32_t GetFunctionTargetOffset(Arch arch) const override;
556 
GetDynamicPrimitiveUndefined()557     uint64_t GetDynamicPrimitiveUndefined() const override
558     {
559         return static_cast<uint64_t>(coretypes::TaggedValue::Undefined().GetRawData());
560     }
561 
GetDynamicPrimitiveFalse()562     uint64_t GetDynamicPrimitiveFalse() const override
563     {
564         return static_cast<uint64_t>(coretypes::TaggedValue::False().GetRawData());
565     }
566 
GetDynamicPrimitiveTrue()567     uint64_t GetDynamicPrimitiveTrue() const override
568     {
569         return static_cast<uint64_t>(coretypes::TaggedValue::True().GetRawData());
570     }
571 
572     uint32_t GetNativePointerTargetOffset(Arch arch) const override;
573 
574     bool HasSafepointDuringCall() const override;
575 
576     bool IsGcValidForFastPath(SourceLanguage lang) const;
577 
578     ThreadPtr CreateCompilerThread() override;
579 
580     void DestroyCompilerThread([[maybe_unused]] ThreadPtr thread) override;
581 
SetCurrentThread(ThreadPtr thread)582     void SetCurrentThread(ThreadPtr thread) const override
583     {
584         ASSERT(thread != Thread::GetCurrent());
585         Thread::SetCurrent(static_cast<ark::Thread *>(thread));
586     }
587 
GetCurrentThread()588     ThreadPtr GetCurrentThread() const override
589     {
590         return Thread::GetCurrent();
591     }
592 
593 private:
ToCompilerType(panda_file::Type type)594     static compiler::DataType::Type ToCompilerType(panda_file::Type type)
595     {
596         switch (type.GetId()) {
597             case panda_file::Type::TypeId::VOID:
598                 return compiler::DataType::VOID;
599             case panda_file::Type::TypeId::U1:
600                 return compiler::DataType::BOOL;
601             case panda_file::Type::TypeId::I8:
602                 return compiler::DataType::INT8;
603             case panda_file::Type::TypeId::U8:
604                 return compiler::DataType::UINT8;
605             case panda_file::Type::TypeId::I16:
606                 return compiler::DataType::INT16;
607             case panda_file::Type::TypeId::U16:
608                 return compiler::DataType::UINT16;
609             case panda_file::Type::TypeId::I32:
610                 return compiler::DataType::INT32;
611             case panda_file::Type::TypeId::U32:
612                 return compiler::DataType::UINT32;
613             case panda_file::Type::TypeId::I64:
614                 return compiler::DataType::INT64;
615             case panda_file::Type::TypeId::U64:
616                 return compiler::DataType::UINT64;
617             case panda_file::Type::TypeId::F32:
618                 return compiler::DataType::FLOAT32;
619             case panda_file::Type::TypeId::F64:
620                 return compiler::DataType::FLOAT64;
621             case panda_file::Type::TypeId::REFERENCE:
622                 return compiler::DataType::REFERENCE;
623             case panda_file::Type::TypeId::TAGGED:
624                 return compiler::DataType::ANY;
625             default:
626                 break;
627         }
628         UNREACHABLE();
629     }
630 
631 private:
632     ClassHierarchyAnalysisWrapper cha_;
633     InlineCachesWrapper inlineCaches_;
634     UnresolvedTypesWrapper unresolvedTypes_;
635 };
636 
637 class Compiler : public CompilerInterface {
638 public:
Compiler(CodeAllocator * codeAllocator,mem::InternalAllocatorPtr internalAllocator,const RuntimeOptions & options,mem::MemStatsType * memStats,compiler::RuntimeInterface * runtimeIface)639     explicit Compiler(CodeAllocator *codeAllocator, mem::InternalAllocatorPtr internalAllocator,
640                       const RuntimeOptions &options, mem::MemStatsType *memStats,
641                       compiler::RuntimeInterface *runtimeIface)
642         : codeAllocator_(codeAllocator),
643           internalAllocator_(internalAllocator),
644           gdbDebugInfoAllocator_(ark::SpaceType::SPACE_TYPE_COMPILER, memStats),
645           runtimeIface_(runtimeIface)
646     {
647         noAsyncJit_ = options.IsNoAsyncJit();
648         if (options.IsArkAot()) {
649             return;
650         }
651 
652         if ((Runtime::GetTaskScheduler() == nullptr) || noAsyncJit_) {
653             compilerWorker_ =
654                 internalAllocator_->New<CompilerThreadPoolWorker>(internalAllocator_, this, noAsyncJit_, options);
655         } else {
656             compilerWorker_ = internalAllocator_->New<CompilerTaskManagerWorker>(internalAllocator_, this);
657         }
658         InitializeWorker();
659         if (compiler::g_options.WasSetCompilerDumpJitStatsCsv()) {
660             jitStats_ = internalAllocator_->New<compiler::JITStats>(internalAllocator_);
661         }
662     }
663 
PreZygoteFork()664     void PreZygoteFork() override
665     {
666         FinalizeWorker();
667     }
668 
PostZygoteFork()669     void PostZygoteFork() override
670     {
671         InitializeWorker();
672     }
673 
FinalizeWorker()674     void FinalizeWorker() override
675     {
676         if (compilerWorker_ != nullptr) {
677             compilerWorker_->FinalizeWorker();
678         }
679     }
680 
681     void JoinWorker() override;
682 
683     bool IsCompilationExpired(Method *method, bool isOsr);
684 
~Compiler()685     ~Compiler() override
686     {
687         // We need to join thread first if runtime initialization fails and Destroy is not called
688         FinalizeWorker();
689         if (compilerWorker_ != nullptr) {
690             internalAllocator_->Delete(compilerWorker_);
691             compilerWorker_ = nullptr;
692         }
693         internalAllocator_->Delete(jitStats_);
694     }
695 
696     bool CompileMethod(Method *method, uintptr_t bytecodeOffset, bool osr, TaggedValue func) override;
697 
AddTask(CompilerTask && ctx,TaggedValue func)698     virtual void AddTask(CompilerTask &&ctx, [[maybe_unused]] TaggedValue func)
699     {
700         compilerWorker_->AddTask(std::move(ctx));
701     }
702 
703     template <compiler::TaskRunnerMode RUNNER_MODE>
704     void CompileMethodLocked(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
705 
706     /// Basic method, which starts compilation. Do not use.
707     template <compiler::TaskRunnerMode RUNNER_MODE>
708     void StartCompileMethod(compiler::CompilerTaskRunner<RUNNER_MODE> taskRunner);
709 
ScaleThreadPool(size_t numberOfThreads)710     void ScaleThreadPool(size_t numberOfThreads)
711     {
712         // Required for testing
713         GetThreadPool()->Scale(numberOfThreads);
714     }
715 
GetOsrCode(const Method * method)716     void *GetOsrCode(const Method *method) override
717     {
718         return osrCodeMap_.Get(method);
719     }
720 
SetOsrCode(const Method * method,void * ptr)721     void SetOsrCode(const Method *method, void *ptr) override
722     {
723         osrCodeMap_.Set(method, ptr);
724     }
725 
RemoveOsrCode(const Method * method)726     void RemoveOsrCode(const Method *method) override
727     {
728         osrCodeMap_.Remove(method);
729     }
730 
SetNoAsyncJit(bool v)731     void SetNoAsyncJit(bool v) override
732     {
733         noAsyncJit_ = v;
734     }
735 
IsNoAsyncJit()736     bool IsNoAsyncJit() override
737     {
738         return noAsyncJit_;
739     }
740 
GetRuntimeInterface()741     compiler::RuntimeInterface *GetRuntimeInterface()
742     {
743         return runtimeIface_;
744     }
745 
746 protected:
GetInternalAllocator()747     mem::InternalAllocatorPtr GetInternalAllocator()
748     {
749         return internalAllocator_;
750     }
751 
GetThreadPool()752     ThreadPool<CompilerTask, CompilerProcessor, Compiler *> *GetThreadPool()
753     {
754         ASSERT(Runtime::GetTaskScheduler() == nullptr || noAsyncJit_);
755         if (compilerWorker_ != nullptr) {
756             return static_cast<CompilerThreadPoolWorker *>(compilerWorker_)->GetThreadPool();
757         }
758         return nullptr;
759     }
760 
761 private:
InitializeWorker()762     void InitializeWorker()
763     {
764         if (compilerWorker_ != nullptr) {
765             compilerWorker_->InitializeWorker();
766         }
767     }
768 
769     CodeAllocator *codeAllocator_;
770     OsrCodeMap osrCodeMap_;
771     mem::InternalAllocatorPtr internalAllocator_;
772     // This allocator is used for GDB debug structures in context of JIT unwind info.
773     ArenaAllocator gdbDebugInfoAllocator_;
774     compiler::RuntimeInterface *runtimeIface_;
775     // The lock is used for compiler thread synchronization
776     os::memory::Mutex compilationLock_;
777     bool noAsyncJit_;
778     CompilerWorker *compilerWorker_ {nullptr};
779     compiler::JITStats *jitStats_ {nullptr};
780     NO_COPY_SEMANTIC(Compiler);
781     NO_MOVE_SEMANTIC(Compiler);
782 };
783 
784 #ifndef PANDA_PRODUCT_BUILD
785 uint8_t CompileMethodImpl(coretypes::String *fullMethodName, panda_file::SourceLang sourceLang);
786 #endif
787 
788 }  // namespace ark
789 
790 #endif  // PANDA_RUNTIME_COMPILER_H_
791