diff --git a/classpath/avian/Addendum.java b/classpath/avian/Addendum.java index 0335d41e8a..1615904439 100644 --- a/classpath/avian/Addendum.java +++ b/classpath/avian/Addendum.java @@ -11,7 +11,7 @@ package avian; public class Addendum { - public Object pool; + public Singleton pool; public Object annotationTable; public Object signature; } diff --git a/classpath/avian/ClassAddendum.java b/classpath/avian/ClassAddendum.java index 409c450799..30ef27249a 100644 --- a/classpath/avian/ClassAddendum.java +++ b/classpath/avian/ClassAddendum.java @@ -21,6 +21,10 @@ public class ClassAddendum extends Addendum { * extended by that class. */ public int declaredMethodCount; + + // Either a byte[] or a Pair, apparently... + // TODO: make it monomorphic public Object enclosingClass; + public Object enclosingMethod; } diff --git a/classpath/avian/Code.java b/classpath/avian/Code.java new file mode 100644 index 0000000000..957099107d --- /dev/null +++ b/classpath/avian/Code.java @@ -0,0 +1,5 @@ +package avian; + +abstract class Code { + // VM-visible fields in types.def +} diff --git a/classpath/avian/Continuations.java b/classpath/avian/Continuations.java index 8afde92fbd..dfbad847b5 100644 --- a/classpath/avian/Continuations.java +++ b/classpath/avian/Continuations.java @@ -302,11 +302,11 @@ public class Continuations { } private static class UnwindResult { - public final Callback continuation; + public final Continuation continuation; public final Object result; public final Throwable exception; - public UnwindResult(Callback continuation, Object result, + public UnwindResult(Continuation continuation, Object result, Throwable exception) { this.continuation = continuation; diff --git a/classpath/avian/Singleton.java b/classpath/avian/Singleton.java index 0c8a3db52f..ebb55f12dd 100644 --- a/classpath/avian/Singleton.java +++ b/classpath/avian/Singleton.java @@ -14,4 +14,6 @@ public abstract class Singleton { public static native int getInt(Object singleton, int offset); public static native long getLong(Object singleton, int offset); public static native Object getObject(Object singleton, int offset); + + // Fields in types.def } diff --git a/classpath/avian/VMClass.java b/classpath/avian/VMClass.java index b95726f42b..338808a83f 100644 --- a/classpath/avian/VMClass.java +++ b/classpath/avian/VMClass.java @@ -16,6 +16,7 @@ public class VMClass { public short fixedSize; public byte arrayElementSize; public byte arrayDimensions; + public VMClass arrayElementClass; public int runtimeDataIndex; public int[] objectMask; public byte[] name; @@ -35,7 +36,7 @@ public class VMClass { */ public VMMethod[] methodTable; public ClassAddendum addendum; - public Object staticTable; + public Singleton staticTable; public ClassLoader loader; public byte[] source; } diff --git a/classpath/avian/VMMethod.java b/classpath/avian/VMMethod.java index 25fc94e634..9d9fcc0785 100644 --- a/classpath/avian/VMMethod.java +++ b/classpath/avian/VMMethod.java @@ -23,7 +23,7 @@ public class VMMethod { public byte[] spec; public MethodAddendum addendum; public VMClass class_; - public Object code; + public Code code; public boolean hasAnnotations() { return addendum != null && addendum.annotationTable != null; diff --git a/classpath/java-io.cpp b/classpath/java-io.cpp index 42cab62f79..f9d477520f 100644 --- a/classpath/java-io.cpp +++ b/classpath/java-io.cpp @@ -20,40 +20,41 @@ #ifdef PLATFORM_WINDOWS -# define UNICODE +#define UNICODE -# include -# include -# include -# include +#include +#include +#include +#include -# define ACCESS _waccess -# define CLOSE _close -# define READ _read -# define WRITE _write -# define STAT _wstat -# define STRUCT_STAT struct _stat -# define MKDIR(path, mode) _wmkdir(path) -# define CHMOD(path, mode) _wchmod(path, mode) -# define REMOVE _wremove -# define RENAME _wrename -# define OPEN_MASK O_BINARY +#define ACCESS _waccess +#define CLOSE _close +#define READ _read +#define WRITE _write +#define STAT _wstat +#define STRUCT_STAT struct _stat +#define MKDIR(path, mode) _wmkdir(path) +#define CHMOD(path, mode) _wchmod(path, mode) +#define REMOVE _wremove +#define RENAME _wrename +#define OPEN_MASK O_BINARY -# define CHECK_X_OK R_OK +#define CHECK_X_OK R_OK -# ifdef _MSC_VER -# define S_ISREG(x) ((x) & _S_IFREG) -# define S_ISDIR(x) ((x) & _S_IFDIR) -# define S_IRUSR _S_IREAD -# define S_IWUSR _S_IWRITE -# define W_OK 2 -# define R_OK 4 -# else -# define OPEN _wopen -# endif +#ifdef _MSC_VER +#define S_ISREG(x) ((x)&_S_IFREG) +#define S_ISDIR(x) ((x)&_S_IFDIR) +#define S_IRUSR _S_IREAD +#define S_IWUSR _S_IWRITE +#define W_OK 2 +#define R_OK 4 +#else +#define OPEN _wopen +#endif -# define GET_CHARS GetStringChars -# define RELEASE_CHARS(path, chars) ReleaseStringChars(path, reinterpret_cast(chars)) +#define GET_CHARS GetStringChars +#define RELEASE_CHARS(path, chars) \ + ReleaseStringChars(path, reinterpret_cast(chars)) typedef wchar_t char_t; @@ -66,46 +67,49 @@ typedef wchar_t char_t; #endif #endif -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS -# include -# include -# include "sys/mman.h" +#include +#include +#include "sys/mman.h" -# define ACCESS access -# define OPEN open -# define CLOSE close -# define READ read -# define WRITE write -# define STAT stat -# define STRUCT_STAT struct stat -# define MKDIR mkdir -# define CHMOD chmod -# define REMOVE remove -# define RENAME rename -# define OPEN_MASK 0 +#define ACCESS access +#define OPEN open +#define CLOSE close +#define READ read +#define WRITE write +#define STAT stat +#define STRUCT_STAT struct stat +#define MKDIR mkdir +#define CHMOD chmod +#define REMOVE remove +#define RENAME rename +#define OPEN_MASK 0 -# define CHECK_X_OK X_OK +#define CHECK_X_OK X_OK -# define GET_CHARS GetStringUTFChars -# define RELEASE_CHARS ReleaseStringUTFChars +#define GET_CHARS GetStringUTFChars +#define RELEASE_CHARS ReleaseStringUTFChars typedef char char_t; -#endif // not PLATFORM_WINDOWS +#endif // not PLATFORM_WINDOWS #ifndef WINAPI_FAMILY -# ifndef WINAPI_PARTITION_DESKTOP -# define WINAPI_PARTITION_DESKTOP 1 -# endif +#ifndef WINAPI_PARTITION_DESKTOP +#define WINAPI_PARTITION_DESKTOP 1 +#endif -# ifndef WINAPI_FAMILY_PARTITION -# define WINAPI_FAMILY_PARTITION(x) (x) -# endif -#endif // WINAPI_FAMILY +#ifndef WINAPI_FAMILY_PARTITION +#define WINAPI_FAMILY_PARTITION(x) (x) +#endif +#endif // WINAPI_FAMILY #if !defined(SKIP_OPERATOR_NEW) -inline void* operator new(size_t, void* p) throw() { return p; } +inline void* operator new(size_t, void* p) throw() +{ + return p; +} #endif typedef const char_t* string_t; @@ -113,20 +117,18 @@ typedef const char_t* string_t; namespace { #ifdef _MSC_VER -inline int -OPEN(string_t path, int mask, int mode) +inline int OPEN(string_t path, int mask, int mode) { - int fd; + int fd; if (_wsopen_s(&fd, path, mask, _SH_DENYNO, mode) == 0) { - return fd; + return fd; } else { - return -1; + return -1; } } #endif -inline bool -exists(string_t path) +inline bool exists(string_t path) { #ifdef PLATFORM_WINDOWS return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; @@ -136,8 +138,7 @@ exists(string_t path) #endif } -inline int -doOpen(JNIEnv* e, string_t path, int mask) +inline int doOpen(JNIEnv* e, string_t path, int mask) { int fd = OPEN(path, mask | OPEN_MASK, S_IRUSR | S_IWUSR); if (fd == -1) { @@ -150,8 +151,7 @@ doOpen(JNIEnv* e, string_t path, int mask) return fd; } -inline void -doClose(JNIEnv* e, jint fd) +inline void doClose(JNIEnv* e, jint fd) { int r = CLOSE(fd); if (r == -1) { @@ -159,8 +159,7 @@ doClose(JNIEnv* e, jint fd) } } -inline int -doRead(JNIEnv* e, jint fd, jbyte* data, jint length) +inline int doRead(JNIEnv* e, jint fd, jbyte* data, jint length) { int r = READ(fd, data, length); if (r > 0) { @@ -170,11 +169,10 @@ doRead(JNIEnv* e, jint fd, jbyte* data, jint length) } else { throwNewErrno(e, "java/io/IOException"); return 0; - } + } } -inline void -doWrite(JNIEnv* e, jint fd, const jbyte* data, jint length) +inline void doWrite(JNIEnv* e, jint fd, const jbyte* data, jint length) { int r = WRITE(fd, data, length); if (r != length) { @@ -182,14 +180,16 @@ doWrite(JNIEnv* e, jint fd, const jbyte* data, jint length) } } - #ifdef PLATFORM_WINDOWS class Directory { public: - Directory(): handle(0), findNext(false) { } + Directory() : handle(0), findNext(false) + { + } - virtual string_t next() { + virtual string_t next() + { if (handle and handle != INVALID_HANDLE_VALUE) { if (findNext) { if (FindNextFileW(handle, &data)) { @@ -203,7 +203,8 @@ class Directory { return 0; } - virtual void dispose() { + virtual void dispose() + { if (handle and handle != INVALID_HANDLE_VALUE) { FindClose(handle); } @@ -215,33 +216,34 @@ class Directory { bool findNext; }; -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS -#endif // not PLATFORM_WINDOWS +#endif // not PLATFORM_WINDOWS +} // namespace -} // namespace - -static inline string_t getChars(JNIEnv* e, jstring path) { +static inline string_t getChars(JNIEnv* e, jstring path) +{ return reinterpret_cast(e->GET_CHARS(path, 0)); } -static inline void releaseChars(JNIEnv* e, jstring path, string_t chars) { +static inline void releaseChars(JNIEnv* e, jstring path, string_t chars) +{ e->RELEASE_CHARS(path, chars); } extern "C" JNIEXPORT jstring JNICALL -Java_java_io_File_toCanonicalPath(JNIEnv* /*e*/, jclass, jstring path) + Java_java_io_File_toCanonicalPath(JNIEnv* /*e*/, jclass, jstring path) { // todo return path; } extern "C" JNIEXPORT jstring JNICALL -Java_java_io_File_toAbsolutePath(JNIEnv* e UNUSED, jclass, jstring path) + Java_java_io_File_toAbsolutePath(JNIEnv* e UNUSED, jclass, jstring path) { #ifdef PLATFORM_WINDOWS -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) string_t chars = getChars(e, path); if (chars) { const unsigned BufferSize = MAX_PATH; @@ -250,25 +252,25 @@ Java_java_io_File_toAbsolutePath(JNIEnv* e UNUSED, jclass, jstring path) releaseChars(e, path, chars); if (success) { - return e->NewString - (reinterpret_cast(buffer), wcslen(buffer)); + return e->NewString(reinterpret_cast(buffer), + wcslen(buffer)); } } return path; -# else +#else string_t chars = getChars(e, path); - if(chars) { + if (chars) { std::wstring partialPath = chars; releaseChars(e, path, chars); std::wstring fullPath = AvianInterop::GetFullPath(partialPath); - return e->NewString - (reinterpret_cast(fullPath.c_str()), fullPath.length()); + return e->NewString(reinterpret_cast(fullPath.c_str()), + fullPath.length()); } return path; -# endif +#endif #else jstring result = path; string_t chars = getChars(e, path); @@ -290,62 +292,61 @@ Java_java_io_File_toAbsolutePath(JNIEnv* e UNUSED, jclass, jstring path) } extern "C" JNIEXPORT jlong JNICALL -Java_java_io_File_length(JNIEnv* e, jclass, jstring path) + Java_java_io_File_length(JNIEnv* e, jclass, jstring path) { - #ifdef PLATFORM_WINDOWS - // Option: without opening file - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx - string_t chars = getChars(e, path); - if(chars) { - LARGE_INTEGER fileSize; - #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - HANDLE file = CreateFileW - (chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); - #else - HANDLE file = CreateFile2 - (chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); - #endif - releaseChars(e, path, chars); - if (file == INVALID_HANDLE_VALUE) - return 0; - #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - if(!GetFileSizeEx(file, &fileSize)) - { - CloseHandle(file); - return 0; - } - #else - FILE_STANDARD_INFO info; - if(!GetFileInformationByHandleEx(file, FileStandardInfo, &info, sizeof(info))) - { - CloseHandle(file); - return 0; - } - fileSize = info.EndOfFile; - #endif - +#ifdef PLATFORM_WINDOWS + // Option: without opening file + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx + string_t chars = getChars(e, path); + if (chars) { + LARGE_INTEGER fileSize; +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + HANDLE file = CreateFileW( + chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); +#else + HANDLE file = CreateFile2( + chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); +#endif + releaseChars(e, path, chars); + if (file == INVALID_HANDLE_VALUE) + return 0; +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + if (!GetFileSizeEx(file, &fileSize)) { CloseHandle(file); - return static_cast(fileSize.QuadPart); + return 0; } - #else - - string_t chars = getChars(e, path); - if (chars) { - STRUCT_STAT s; - int r = STAT(chars, &s); - releaseChars(e, path, chars); - if (r == 0) { - return s.st_size; - } +#else + FILE_STANDARD_INFO info; + if (!GetFileInformationByHandleEx( + file, FileStandardInfo, &info, sizeof(info))) { + CloseHandle(file); + return 0; } + fileSize = info.EndOfFile; +#endif - #endif + CloseHandle(file); + return static_cast(fileSize.QuadPart); + } +#else + + string_t chars = getChars(e, path); + if (chars) { + STRUCT_STAT s; + int r = STAT(chars, &s); + releaseChars(e, path, chars); + if (r == 0) { + return s.st_size; + } + } + +#endif return 0; } extern "C" JNIEXPORT void JNICALL -Java_java_io_File_mkdir(JNIEnv* e, jclass, jstring path) + Java_java_io_File_mkdir(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -360,7 +361,7 @@ Java_java_io_File_mkdir(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_createNewFile(JNIEnv* e, jclass, jstring path) + Java_java_io_File_createNewFile(JNIEnv* e, jclass, jstring path) { bool result = false; string_t chars = getChars(e, path); @@ -382,7 +383,7 @@ Java_java_io_File_createNewFile(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT void JNICALL -Java_java_io_File_delete(JNIEnv* e, jclass, jstring path) + Java_java_io_File_delete(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -395,7 +396,7 @@ Java_java_io_File_delete(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_canRead(JNIEnv* e, jclass, jstring path) + Java_java_io_File_canRead(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -407,7 +408,7 @@ Java_java_io_File_canRead(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_canWrite(JNIEnv* e, jclass, jstring path) + Java_java_io_File_canWrite(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -419,7 +420,7 @@ Java_java_io_File_canWrite(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_canExecute(JNIEnv* e, jclass, jstring path) + Java_java_io_File_canExecute(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -432,13 +433,17 @@ Java_java_io_File_canExecute(JNIEnv* e, jclass, jstring path) #ifndef PLATFORM_WINDOWS extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_setExecutable(JNIEnv* e, jclass, jstring path, jboolean executable, jboolean ownerOnly) + Java_java_io_File_setExecutable(JNIEnv* e, + jclass, + jstring path, + jboolean executable, + jboolean ownerOnly) { string_t chars = getChars(e, path); - if(chars) { + if (chars) { jboolean v; int mask; - if(ownerOnly) { + if (ownerOnly) { mask = S_IXUSR; } else { mask = S_IXUSR | S_IXGRP | S_IXOTH; @@ -446,14 +451,14 @@ Java_java_io_File_setExecutable(JNIEnv* e, jclass, jstring path, jboolean execut STRUCT_STAT s; int r = STAT(chars, &s); - if(r == 0) { + if (r == 0) { int mode = s.st_mode; - if(executable) { + if (executable) { mode |= mask; } else { mode &= ~mask; } - if(CHMOD(chars, mode) != 0) { + if (CHMOD(chars, mode) != 0) { v = false; } else { v = true; @@ -467,10 +472,14 @@ Java_java_io_File_setExecutable(JNIEnv* e, jclass, jstring path, jboolean execut return false; } -#else // ifndef PLATFORM_WINDOWS +#else // ifndef PLATFORM_WINDOWS extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_setExecutable(JNIEnv*, jclass, jstring, jboolean executable, jboolean) + Java_java_io_File_setExecutable(JNIEnv*, + jclass, + jstring, + jboolean executable, + jboolean) { return executable; } @@ -478,7 +487,7 @@ Java_java_io_File_setExecutable(JNIEnv*, jclass, jstring, jboolean executable, j #endif extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_rename(JNIEnv* e, jclass, jstring old, jstring new_) + Java_java_io_File_rename(JNIEnv* e, jclass, jstring old, jstring new_) { string_t oldChars = getChars(e, old); string_t newChars = getChars(e, new_); @@ -499,7 +508,7 @@ Java_java_io_File_rename(JNIEnv* e, jclass, jstring old, jstring new_) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_isDirectory(JNIEnv* e, jclass, jstring path) + Java_java_io_File_isDirectory(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -514,7 +523,7 @@ Java_java_io_File_isDirectory(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_isFile(JNIEnv* e, jclass, jstring path) + Java_java_io_File_isFile(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -529,7 +538,7 @@ Java_java_io_File_isFile(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_io_File_exists(JNIEnv* e, jclass, jstring path) + Java_java_io_File_exists(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -542,61 +551,60 @@ Java_java_io_File_exists(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jlong JNICALL -Java_java_io_File_lastModified(JNIEnv* e, jclass, jstring path) + Java_java_io_File_lastModified(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { #ifdef PLATFORM_WINDOWS - // Option: without opening file - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - HANDLE hFile = CreateFileW - (chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); -# else - HANDLE hFile = CreateFile2 - (chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); -# endif - releaseChars(e, path, chars); - if (hFile == INVALID_HANDLE_VALUE) - return 0; - LARGE_INTEGER fileDate, filetimeToUnixEpochAdjustment; - filetimeToUnixEpochAdjustment.QuadPart = 11644473600000L * 10000L; -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - FILETIME fileLastWriteTime; - if (!GetFileTime(hFile, 0, 0, &fileLastWriteTime)) - { - CloseHandle(hFile); - return 0; - } - fileDate.HighPart = fileLastWriteTime.dwHighDateTime; - fileDate.LowPart = fileLastWriteTime.dwLowDateTime; -# else - FILE_BASIC_INFO fileInfo; - if (!GetFileInformationByHandleEx(hFile, FileBasicInfo, &fileInfo, sizeof(fileInfo))) - { - CloseHandle(hFile); - return 0; - } - fileDate = fileInfo.ChangeTime; -# endif - CloseHandle(hFile); - fileDate.QuadPart -= filetimeToUnixEpochAdjustment.QuadPart; - return fileDate.QuadPart / 10000000L; +// Option: without opening file +// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946(v=vs.85).aspx +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + HANDLE hFile = CreateFileW( + chars, FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); #else - struct stat fileStat; - int res = stat(chars, &fileStat); - releaseChars(e, path, chars); + HANDLE hFile = CreateFile2( + chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); +#endif + releaseChars(e, path, chars); + if (hFile == INVALID_HANDLE_VALUE) + return 0; + LARGE_INTEGER fileDate, filetimeToUnixEpochAdjustment; + filetimeToUnixEpochAdjustment.QuadPart = 11644473600000L * 10000L; +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + FILETIME fileLastWriteTime; + if (!GetFileTime(hFile, 0, 0, &fileLastWriteTime)) { + CloseHandle(hFile); + return 0; + } + fileDate.HighPart = fileLastWriteTime.dwHighDateTime; + fileDate.LowPart = fileLastWriteTime.dwLowDateTime; +#else + FILE_BASIC_INFO fileInfo; + if (!GetFileInformationByHandleEx( + hFile, FileBasicInfo, &fileInfo, sizeof(fileInfo))) { + CloseHandle(hFile); + return 0; + } + fileDate = fileInfo.ChangeTime; +#endif + CloseHandle(hFile); + fileDate.QuadPart -= filetimeToUnixEpochAdjustment.QuadPart; + return fileDate.QuadPart / 10000000L; +#else + struct stat fileStat; + int res = stat(chars, &fileStat); + releaseChars(e, path, chars); - if (res == -1) { - return 0; - } -# ifdef __APPLE__ - #define MTIME st_mtimespec -# else - #define MTIME st_mtim -# endif - return (static_cast(fileStat.MTIME.tv_sec) * 1000) + - (static_cast(fileStat.MTIME.tv_nsec) / (1000*1000)); + if (res == -1) { + return 0; + } +#ifdef __APPLE__ +#define MTIME st_mtimespec +#else +#define MTIME st_mtim +#endif + return (static_cast(fileStat.MTIME.tv_sec) * 1000) + + (static_cast(fileStat.MTIME.tv_nsec) / (1000 * 1000)); #endif } @@ -606,7 +614,7 @@ Java_java_io_File_lastModified(JNIEnv* e, jclass, jstring path) #ifdef PLATFORM_WINDOWS extern "C" JNIEXPORT jlong JNICALL -Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) + Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -620,11 +628,16 @@ Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) releaseChars(e, path, chars); Directory* d = new (malloc(sizeof(Directory))) Directory; - #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) d->handle = FindFirstFileW(RUNTIME_ARRAY_BODY(buffer), &(d->data)); - #else - d->handle = FindFirstFileExW(RUNTIME_ARRAY_BODY(buffer), FindExInfoStandard, &(d->data), FindExSearchNameMatch, NULL, 0); - #endif +#else + d->handle = FindFirstFileExW(RUNTIME_ARRAY_BODY(buffer), + FindExInfoStandard, + &(d->data), + FindExSearchNameMatch, + NULL, + 0); +#endif if (d->handle == INVALID_HANDLE_VALUE) { d->dispose(); d = 0; @@ -637,7 +650,7 @@ Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jstring JNICALL -Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) + Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) { Directory* d = reinterpret_cast(handle); @@ -656,15 +669,15 @@ Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) } extern "C" JNIEXPORT void JNICALL -Java_java_io_File_closeDir(JNIEnv* , jclass, jlong handle) + Java_java_io_File_closeDir(JNIEnv*, jclass, jlong handle) { reinterpret_cast(handle)->dispose(); } -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS extern "C" JNIEXPORT jlong JNICALL -Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) + Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) { string_t chars = getChars(e, path); if (chars) { @@ -677,18 +690,17 @@ Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path) } extern "C" JNIEXPORT jstring JNICALL -Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) + Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) { - struct dirent * directoryEntry; + struct dirent* directoryEntry; - if (handle!=0) { + if (handle != 0) { while (true) { directoryEntry = readdir(reinterpret_cast(handle)); if (directoryEntry == NULL) { return NULL; } else if (strcmp(directoryEntry->d_name, ".") == 0 - || strcmp(directoryEntry->d_name, "..") == 0) - { + || strcmp(directoryEntry->d_name, "..") == 0) { // skip . or .. and try again } else { return e->NewStringUTF(directoryEntry->d_name); @@ -699,30 +711,30 @@ Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle) } extern "C" JNIEXPORT void JNICALL -Java_java_io_File_closeDir(JNIEnv* , jclass, jlong handle) + Java_java_io_File_closeDir(JNIEnv*, jclass, jlong handle) { - if (handle!=0) { + if (handle != 0) { closedir(reinterpret_cast(handle)); } } -#endif // not PLATFORM_WINDOWS +#endif // not PLATFORM_WINDOWS extern "C" JNIEXPORT jint JNICALL -Java_java_io_FileInputStream_open(JNIEnv* e, jclass, jstring path) + Java_java_io_FileInputStream_open(JNIEnv* e, jclass, jstring path) { - string_t chars = getChars(e, path); + string_t chars = getChars(e, path); if (chars) { int fd = doOpen(e, chars, O_RDONLY); releaseChars(e, path, chars); - return fd; + return fd; } else { - return -1; + return -1; } } extern "C" JNIEXPORT jint JNICALL -Java_java_io_FileInputStream_read__I(JNIEnv* e, jclass, jint fd) + Java_java_io_FileInputStream_read__I(JNIEnv* e, jclass, jint fd) { jbyte data; int r = doRead(e, fd, &data, 1); @@ -734,13 +746,17 @@ Java_java_io_FileInputStream_read__I(JNIEnv* e, jclass, jint fd) } extern "C" JNIEXPORT jint JNICALL -Java_java_io_FileInputStream_read__I_3BII -(JNIEnv* e, jclass, jint fd, jbyteArray b, jint offset, jint length) + Java_java_io_FileInputStream_read__I_3BII(JNIEnv* e, + jclass, + jint fd, + jbyteArray b, + jint offset, + jint length) { jbyte* data = static_cast(malloc(length)); if (data == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return 0; + return 0; } int r = doRead(e, fd, data, length); @@ -753,19 +769,23 @@ Java_java_io_FileInputStream_read__I_3BII } extern "C" JNIEXPORT void JNICALL -Java_java_io_FileInputStream_close(JNIEnv* e, jclass, jint fd) + Java_java_io_FileInputStream_close(JNIEnv* e, jclass, jint fd) { doClose(e, fd); } extern "C" JNIEXPORT jint JNICALL -Java_java_io_FileOutputStream_open(JNIEnv* e, jclass, jstring path, jboolean append) + Java_java_io_FileOutputStream_open(JNIEnv* e, + jclass, + jstring path, + jboolean append) { string_t chars = getChars(e, path); if (chars) { - int fd = doOpen(e, chars, append - ? (O_WRONLY | O_CREAT | O_APPEND) - : (O_WRONLY | O_CREAT | O_TRUNC)); + int fd = doOpen(e, + chars, + append ? (O_WRONLY | O_CREAT | O_APPEND) + : (O_WRONLY | O_CREAT | O_TRUNC)); releaseChars(e, path, chars); return fd; } else { @@ -774,21 +794,25 @@ Java_java_io_FileOutputStream_open(JNIEnv* e, jclass, jstring path, jboolean app } extern "C" JNIEXPORT void JNICALL -Java_java_io_FileOutputStream_write__II(JNIEnv* e, jclass, jint fd, jint c) + Java_java_io_FileOutputStream_write__II(JNIEnv* e, jclass, jint fd, jint c) { jbyte data = c; doWrite(e, fd, &data, 1); } extern "C" JNIEXPORT void JNICALL -Java_java_io_FileOutputStream_write__I_3BII -(JNIEnv* e, jclass, jint fd, jbyteArray b, jint offset, jint length) + Java_java_io_FileOutputStream_write__I_3BII(JNIEnv* e, + jclass, + jint fd, + jbyteArray b, + jint offset, + jint length) { jbyte* data = static_cast(malloc(length)); if (data == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return; + return; } e->GetByteArrayRegion(b, offset, length, data); @@ -800,49 +824,53 @@ Java_java_io_FileOutputStream_write__I_3BII } extern "C" JNIEXPORT void JNICALL -Java_java_io_FileOutputStream_close(JNIEnv* e, jclass, jint fd) + Java_java_io_FileOutputStream_close(JNIEnv* e, jclass, jint fd) { doClose(e, fd); } extern "C" JNIEXPORT void JNICALL -Java_java_io_RandomAccessFile_open(JNIEnv* e, jclass, jstring path, - jboolean allowWrite, jlongArray result) + Java_java_io_RandomAccessFile_open(JNIEnv* e, + jclass, + jstring path, + jboolean allowWrite, + jlongArray result) { string_t chars = getChars(e, path); if (chars) { jlong peer = 0; jlong length = 0; int flags = (allowWrite ? O_RDWR | O_CREAT : O_RDONLY) | OPEN_MASK; - #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - #if defined(PLATFORM_WINDOWS) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if defined(PLATFORM_WINDOWS) int fd = ::_wopen(chars, flags); - #else +#else int fd = ::open((const char*)chars, flags, 0666); - #endif +#endif releaseChars(e, path, chars); if (fd == -1) { throwNewErrno(e, "java/io/IOException"); return; } struct ::stat fileStats; - if(::fstat(fd, &fileStats) == -1) { + if (::fstat(fd, &fileStats) == -1) { ::close(fd); throwNewErrno(e, "java/io/IOException"); return; } peer = fd; length = fileStats.st_size; - #else - HANDLE hFile = CreateFile2 - (chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); +#else + HANDLE hFile = CreateFile2( + chars, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); if (hFile == INVALID_HANDLE_VALUE) { throwNewErrno(e, "java/io/IOException"); return; } FILE_STANDARD_INFO info; - if(!GetFileInformationByHandleEx(hFile, FileStandardInfo, &info, sizeof(info))) { + if (!GetFileInformationByHandleEx( + hFile, FileStandardInfo, &info, sizeof(info))) { CloseHandle(hFile); throwNewErrno(e, "java/io/IOException"); return; @@ -850,7 +878,7 @@ Java_java_io_RandomAccessFile_open(JNIEnv* e, jclass, jstring path, peer = (jlong)hFile; length = info.EndOfFile.QuadPart; - #endif +#endif e->SetLongArrayRegion(result, 0, 1, &peer); e->SetLongArrayRegion(result, 1, 1, &length); @@ -858,24 +886,28 @@ Java_java_io_RandomAccessFile_open(JNIEnv* e, jclass, jstring path, } extern "C" JNIEXPORT jint JNICALL -Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, jclass, jlong peer, - jlong position, jbyteArray buffer, - int offset, int length) + Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, + jclass, + jlong peer, + jlong position, + jbyteArray buffer, + int offset, + int length) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) int fd = (int)peer; - if(::lseek(fd, position, SEEK_SET) == -1) { + if (::lseek(fd, position, SEEK_SET) == -1) { throwNewErrno(e, "java/io/IOException"); return -1; } - - uint8_t* dst = reinterpret_cast - (e->GetPrimitiveArrayCritical(buffer, 0)); + + uint8_t* dst + = reinterpret_cast(e->GetPrimitiveArrayCritical(buffer, 0)); int64_t bytesRead = ::read(fd, dst + offset, length); e->ReleasePrimitiveArrayCritical(buffer, dst, 0); - - if(bytesRead == -1) { + + if (bytesRead == -1) { throwNewErrno(e, "java/io/IOException"); return -1; } @@ -883,16 +915,16 @@ Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, jclass, jlong peer, HANDLE hFile = (HANDLE)peer; LARGE_INTEGER lPos; lPos.QuadPart = position; - if(!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) { + if (!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) { throwNewErrno(e, "java/io/IOException"); return -1; } - uint8_t* dst = reinterpret_cast - (e->GetPrimitiveArrayCritical(buffer, 0)); + uint8_t* dst + = reinterpret_cast(e->GetPrimitiveArrayCritical(buffer, 0)); DWORD bytesRead = 0; - if(!ReadFile(hFile, dst + offset, length, &bytesRead, nullptr)) { + if (!ReadFile(hFile, dst + offset, length, &bytesRead, nullptr)) { e->ReleasePrimitiveArrayCritical(buffer, dst, 0); throwNewErrno(e, "java/io/IOException"); return -1; @@ -904,24 +936,28 @@ Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, jclass, jlong peer, } extern "C" JNIEXPORT jint JNICALL -Java_java_io_RandomAccessFile_writeBytes(JNIEnv* e, jclass, jlong peer, - jlong position, jbyteArray buffer, - int offset, int length) + Java_java_io_RandomAccessFile_writeBytes(JNIEnv* e, + jclass, + jlong peer, + jlong position, + jbyteArray buffer, + int offset, + int length) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) int fd = (int)peer; - if(::lseek(fd, position, SEEK_SET) == -1) { + if (::lseek(fd, position, SEEK_SET) == -1) { throwNewErrno(e, "java/io/IOException"); return -1; } - uint8_t* dst = reinterpret_cast - (e->GetPrimitiveArrayCritical(buffer, 0)); + uint8_t* dst + = reinterpret_cast(e->GetPrimitiveArrayCritical(buffer, 0)); int64_t bytesWritten = ::write(fd, dst + offset, length); e->ReleasePrimitiveArrayCritical(buffer, dst, 0); - if(bytesWritten == -1) { + if (bytesWritten == -1) { throwNewErrno(e, "java/io/IOException"); return -1; } @@ -929,16 +965,16 @@ Java_java_io_RandomAccessFile_writeBytes(JNIEnv* e, jclass, jlong peer, HANDLE hFile = (HANDLE)peer; LARGE_INTEGER lPos; lPos.QuadPart = position; - if(!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) { + if (!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) { throwNewErrno(e, "java/io/IOException"); return -1; } - uint8_t* dst = reinterpret_cast - (e->GetPrimitiveArrayCritical(buffer, 0)); + uint8_t* dst + = reinterpret_cast(e->GetPrimitiveArrayCritical(buffer, 0)); DWORD bytesWritten = 0; - if(!WriteFile(hFile, dst + offset, length, &bytesWritten, nullptr)) { + if (!WriteFile(hFile, dst + offset, length, &bytesWritten, nullptr)) { e->ReleasePrimitiveArrayCritical(buffer, dst, 0); throwNewErrno(e, "java/io/IOException"); return -1; @@ -950,7 +986,7 @@ Java_java_io_RandomAccessFile_writeBytes(JNIEnv* e, jclass, jlong peer, } extern "C" JNIEXPORT void JNICALL -Java_java_io_RandomAccessFile_close(JNIEnv* /* e*/, jclass, jlong peer) + Java_java_io_RandomAccessFile_close(JNIEnv* /* e*/, jclass, jlong peer) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) int fd = (int)peer; diff --git a/classpath/java-lang.cpp b/classpath/java-lang.cpp index d96002c5bf..ae378e45d1 100644 --- a/classpath/java-lang.cpp +++ b/classpath/java-lang.cpp @@ -7,7 +7,7 @@ There is NO WARRANTY for this software. See license.txt for details. */ - + #include "math.h" #include "stdlib.h" #include "time.h" @@ -21,63 +21,63 @@ #ifdef PLATFORM_WINDOWS -# include "windows.h" -# include "winbase.h" -# include "io.h" -# include "tchar.h" -# include "float.h" -# include "sys/types.h" -# include "sys/timeb.h" -# define SO_PREFIX "" -# define SO_SUFFIX ".dll" +#include "windows.h" +#include "winbase.h" +#include "io.h" +#include "tchar.h" +#include "float.h" +#include "sys/types.h" +#include "sys/timeb.h" +#define SO_PREFIX "" +#define SO_SUFFIX ".dll" -# ifdef _MSC_VER -# define snprintf sprintf_s -# define isnan _isnan -# define isfinite _finite -# define strtof strtod -# endif +#ifdef _MSC_VER +#define snprintf sprintf_s +#define isnan _isnan +#define isfinite _finite +#define strtof strtod +#endif -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS -# define SO_PREFIX "lib" -# ifdef __APPLE__ -# define SO_SUFFIX ".jnilib" -# include -# if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE -# include -# endif -# else -# define SO_SUFFIX ".so" -# endif -# include "unistd.h" -# include "limits.h" -# include "signal.h" -# include "sys/time.h" -# include "sys/types.h" -# ifndef __ANDROID__ -# include "sys/sysctl.h" -# endif -# include "sys/utsname.h" -# include "sys/wait.h" +#define SO_PREFIX "lib" +#ifdef __APPLE__ +#define SO_SUFFIX ".jnilib" +#include +#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE +#include +#endif +#else +#define SO_SUFFIX ".so" +#endif +#include "unistd.h" +#include "limits.h" +#include "signal.h" +#include "sys/time.h" +#include "sys/types.h" +#ifndef __ANDROID__ +#include "sys/sysctl.h" +#endif +#include "sys/utsname.h" +#include "sys/wait.h" -#endif // not PLATFORM_WINDOWS +#endif // not PLATFORM_WINDOWS #ifndef WINAPI_FAMILY -# ifndef WINAPI_PARTITION_DESKTOP -# define WINAPI_PARTITION_DESKTOP 1 -# endif +#ifndef WINAPI_PARTITION_DESKTOP +#define WINAPI_PARTITION_DESKTOP 1 +#endif -# ifndef WINAPI_FAMILY_PARTITION -# define WINAPI_FAMILY_PARTITION(x) (x) -# endif +#ifndef WINAPI_FAMILY_PARTITION +#define WINAPI_FAMILY_PARTITION(x) (x) +#endif #else -# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) -# include "avian-interop.h" +#include "avian-interop.h" -# endif -#endif // WINAPI_FAMILY +#endif +#endif // WINAPI_FAMILY namespace { @@ -129,91 +129,107 @@ void add(JNIEnv* e, } #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - char* getErrorStr(DWORD err) { - LPSTR errorStr = 0; - if(!FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, LANG_SYSTEM_DEFAULT, (LPSTR)&errorStr, 0, 0)) - { - char* errStr = (char*) malloc(9 * sizeof(char)); - snprintf(errStr, 9, "%d", (int) err); - return errStr; - } - char* errStr = strdup(errorStr); - LocalFree(errorStr); +char* getErrorStr(DWORD err) +{ + LPSTR errorStr = 0; + if (!FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER + | FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, + err, + LANG_SYSTEM_DEFAULT, + (LPSTR)&errorStr, + 0, + 0)) { + char* errStr = (char*)malloc(9 * sizeof(char)); + snprintf(errStr, 9, "%d", (int)err); return errStr; } + char* errStr = strdup(errorStr); + LocalFree(errorStr); + return errStr; +} #else - char* getErrorStr(DWORD err) { - LPSTR errorStr = (LPSTR)malloc(4096); //NOTE: something constant - if(!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, LANG_SYSTEM_DEFAULT, errorStr, 0, 0)) - { - free(errorStr); - - char* errStr = (char*) malloc(9 * sizeof(char)); - snprintf(errStr, 9, "%d", (int) err); - return errStr; - } - char* errStr = strdup(errorStr); +char* getErrorStr(DWORD err) +{ + LPSTR errorStr = (LPSTR)malloc(4096); // NOTE: something constant + if (!FormatMessageA( + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, + err, + LANG_SYSTEM_DEFAULT, + errorStr, + 0, + 0)) { free(errorStr); + + char* errStr = (char*)malloc(9 * sizeof(char)); + snprintf(errStr, 9, "%d", (int)err); return errStr; } + char* errStr = strdup(errorStr); + free(errorStr); + return errStr; +} #endif #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - void makePipe(JNIEnv* e, HANDLE p[2]) - { - SECURITY_ATTRIBUTES sa; - sa.nLength = sizeof(sa); - sa.bInheritHandle = 1; - sa.lpSecurityDescriptor = 0; - - BOOL success = CreatePipe(p, p + 1, &sa, 0); - if (not success) { - throwNew(e, "java/io/IOException", getErrorStr(GetLastError())); - } +void makePipe(JNIEnv* e, HANDLE p[2]) +{ + SECURITY_ATTRIBUTES sa; + sa.nLength = sizeof(sa); + sa.bInheritHandle = 1; + sa.lpSecurityDescriptor = 0; + + BOOL success = CreatePipe(p, p + 1, &sa, 0); + if (not success) { + throwNew(e, "java/io/IOException", getErrorStr(GetLastError())); } +} #endif - - int descriptor(JNIEnv* e, HANDLE h) - { - int fd = _open_osfhandle(reinterpret_cast(h), 0); - if (fd == -1) { - throwNewErrno(e, "java/io/IOException"); - } - return fd; + +int descriptor(JNIEnv* e, HANDLE h) +{ + int fd = _open_osfhandle(reinterpret_cast(h), 0); + if (fd == -1) { + throwNewErrno(e, "java/io/IOException"); } + return fd; +} #else - void makePipe(JNIEnv* e, int p[2]) - { - if(pipe(p) != 0) { - throwNewErrno(e, "java/io/IOException"); - } +void makePipe(JNIEnv* e, int p[2]) +{ + if (pipe(p) != 0) { + throwNewErrno(e, "java/io/IOException"); } - - void safeClose(int &fd) - { - if(fd != -1) close(fd); - fd = -1; - } - - void close(int p[2]) - { - ::close(p[0]); - ::close(p[1]); - } - - void clean(JNIEnv* e, jobjectArray command, char** p) - { - int i = 0; - for(char** x = p; *x; ++x, ++i){ - jstring element = (jstring) e->GetObjectArrayElement(command, i); - e->ReleaseStringUTFChars(element, *x); - } - free(p); - } -#endif } -class Locale { // represents an ISO two-char language/country pair +void safeClose(int& fd) +{ + if (fd != -1) + close(fd); + fd = -1; +} + +void close(int p[2]) +{ + ::close(p[0]); + ::close(p[1]); +} + +void clean(JNIEnv* e, jobjectArray command, char** p) +{ + int i = 0; + for (char** x = p; *x; ++x, ++i) { + jstring element = (jstring)e->GetObjectArrayElement(command, i); + e->ReleaseStringUTFChars(element, *x); + } + free(p); +} +#endif +} + +class Locale { // represents an ISO two-char language/country pair static const unsigned FIELDLEN = 2; static const unsigned FIELDSIZE = FIELDLEN + 1; @@ -223,100 +239,120 @@ class Locale { // represents an ISO two-char language/country pair char language[FIELDSIZE]; char region[FIELDSIZE]; - bool isLanguage(const char* language) { - if (!language) return false; + bool isLanguage(const char* language) + { + if (!language) + return false; unsigned len = strlen(language); - if (len != FIELDLEN) return false; + if (len != FIELDLEN) + return false; const char* p = language - 1; - while (islower(*++p)) ; - if (*p != '\0') return false; + while (islower(*++p)) + ; + if (*p != '\0') + return false; return true; } - bool isRegion(const char* region) { - if (!region) return false; + bool isRegion(const char* region) + { + if (!region) + return false; unsigned len = strlen(region); - if (len != FIELDLEN) return false; + if (len != FIELDLEN) + return false; const char* p = region - 1; - while (isupper(*++p)) ; - if (*p != '\0') return false; + while (isupper(*++p)) + ; + if (*p != '\0') + return false; return true; } -public: - Locale(const char* language = "") { + public: + Locale(const char* language = "") + { Locale l(language, ""); *this = l; } - Locale(const char* language, const char* region) { + Locale(const char* language, const char* region) + { language = isLanguage(language) ? language : DEFAULT_LANGUAGE; region = isRegion(region) ? region : DEFAULT_REGION; memcpy(this->language, language, FIELDSIZE); memcpy(this->region, region, FIELDSIZE); } - Locale& operator=(const Locale& l) { + Locale& operator=(const Locale& l) + { memcpy(language, l.language, FIELDSIZE); memcpy(region, l.region, FIELDSIZE); return *this; } - const char* getLanguage() { return reinterpret_cast(language); } - const char* getRegion() { return reinterpret_cast(region); } + const char* getLanguage() + { + return reinterpret_cast(language); + } + const char* getRegion() + { + return reinterpret_cast(region); + } }; const char* Locale::DEFAULT_LANGUAGE = "en"; const char* Locale::DEFAULT_REGION = ""; #ifdef PLATFORM_WINDOWS -void appendN(char** dest, char ch, size_t length) { - for(size_t i = 0; i < length; i++) { +void appendN(char** dest, char ch, size_t length) +{ + for (size_t i = 0; i < length; i++) { *((*dest)++) = ch; } } -bool needsEscape(const char* src, size_t length) { +bool needsEscape(const char* src, size_t length) +{ const char* end = src + length; - for(const char* ptr = src; ptr < end; ptr++) { - switch(*ptr) { - case ' ': - case '\t': - case '\n': - case '\v': - case '"': - return true; + for (const char* ptr = src; ptr < end; ptr++) { + switch (*ptr) { + case ' ': + case '\t': + case '\n': + case '\v': + case '"': + return true; } } return false; - } -void copyAndEscape(char** dest, const char* src, size_t length) { +void copyAndEscape(char** dest, const char* src, size_t length) +{ char* destp = *dest; const char* end = src + length; - if(length != 0 && !needsEscape(src, length)) { - for(const char* ptr = src; ptr < end; ptr++) { + if (length != 0 && !needsEscape(src, length)) { + for (const char* ptr = src; ptr < end; ptr++) { *(destp++) = *ptr; } } else { - *(destp++) = '"'; - for(const char* ptr = src; ; ptr++) { + for (const char* ptr = src;; ptr++) { unsigned numBackslashes = 0; - while(ptr < end && *ptr == '\\') { + while (ptr < end && *ptr == '\\') { ptr++; numBackslashes++; } - if(ptr == end) { + if (ptr == end) { appendN(&destp, '\\', 2 * numBackslashes); break; - } else if(*ptr == '"') { + } else if (*ptr == '"') { appendN(&destp, '\\', 2 * numBackslashes + 1); *(destp++) = *ptr; } else { @@ -324,65 +360,73 @@ void copyAndEscape(char** dest, const char* src, size_t length) { *(destp++) = *ptr; } } - + *(destp++) = '"'; } *dest = destp; } -extern "C" JNIEXPORT void JNICALL -Java_java_lang_Runtime_exec(JNIEnv* e, jclass, - jobjectArray command, jlongArray process) +extern "C" JNIEXPORT void JNICALL + Java_java_lang_Runtime_exec(JNIEnv* e, + jclass, + jobjectArray command, + jlongArray process) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) int size = 0; - for (int i = 0; i < e->GetArrayLength(command); ++i){ - jstring element = (jstring) e->GetObjectArrayElement(command, i); - if(element) { + for (int i = 0; i < e->GetArrayLength(command); ++i) { + jstring element = (jstring)e->GetObjectArrayElement(command, i); + if (element) { // worst case, assuming every character is '"', and we escape all of them size += 2 * e->GetStringUTFLength(element) + 3; } else { - throwNew(e, "java/lang/NullPointerException", strdup("null string array element")); + throwNew(e, + "java/lang/NullPointerException", + strdup("null string array element")); } } - + RUNTIME_ARRAY(char, line, size); char* linep = RUNTIME_ARRAY_BODY(line); for (int i = 0; i < e->GetArrayLength(command); ++i) { - if (i) *(linep++) = _T(' '); - jstring element = (jstring) e->GetObjectArrayElement(command, i); - const char* s = e->GetStringUTFChars(element, 0); + if (i) + *(linep++) = _T(' '); + jstring element = (jstring)e->GetObjectArrayElement(command, i); + const char* s = e->GetStringUTFChars(element, 0); copyAndEscape(&linep, s, e->GetStringUTFLength(element)); e->ReleaseStringUTFChars(element, s); } *(linep++) = _T('\0'); - - HANDLE in[] = { 0, 0 }; - HANDLE out[] = { 0, 0 }; - HANDLE err[] = { 0, 0 }; - + + HANDLE in[] = {0, 0}; + HANDLE out[] = {0, 0}; + HANDLE err[] = {0, 0}; + makePipe(e, in); SetHandleInformation(in[0], HANDLE_FLAG_INHERIT, 0); jlong inDescriptor = static_cast(descriptor(e, in[0])); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; e->SetLongArrayRegion(process, 2, 1, &inDescriptor); makePipe(e, out); SetHandleInformation(out[1], HANDLE_FLAG_INHERIT, 0); jlong outDescriptor = static_cast(descriptor(e, out[1])); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; e->SetLongArrayRegion(process, 3, 1, &outDescriptor); makePipe(e, err); SetHandleInformation(err[0], HANDLE_FLAG_INHERIT, 0); jlong errDescriptor = static_cast(descriptor(e, err[0])); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; e->SetLongArrayRegion(process, 4, 1, &errDescriptor); - + PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); - + STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); @@ -390,37 +434,44 @@ Java_java_lang_Runtime_exec(JNIEnv* e, jclass, si.hStdOutput = in[1]; si.hStdInput = out[0]; si.hStdError = err[1]; - - BOOL success = CreateProcess(0, (LPSTR) RUNTIME_ARRAY_BODY(line), 0, 0, 1, + + BOOL success = CreateProcess(0, + (LPSTR)RUNTIME_ARRAY_BODY(line), + 0, + 0, + 1, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, - 0, 0, &si, &pi); + 0, + 0, + &si, + &pi); CloseHandle(in[1]); CloseHandle(out[0]); CloseHandle(err[1]); - + if (not success) { throwNew(e, "java/io/IOException", getErrorStr(GetLastError())); return; } - + jlong pid = reinterpret_cast(pi.hProcess); e->SetLongArrayRegion(process, 0, 1, &pid); - jlong tid = reinterpret_cast(pi.hThread); + jlong tid = reinterpret_cast(pi.hThread); e->SetLongArrayRegion(process, 1, 1, &tid); #else throwNew(e, "java/io/Exception", strdup("Not supported on WinRT/WinPhone8")); #endif } -extern "C" JNIEXPORT jint JNICALL -Java_java_lang_Runtime_waitFor(JNIEnv* e, jclass, jlong pid, jlong tid) +extern "C" JNIEXPORT jint JNICALL + Java_java_lang_Runtime_waitFor(JNIEnv* e, jclass, jlong pid, jlong tid) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) DWORD exitCode; WaitForSingleObject(reinterpret_cast(pid), INFINITE); BOOL success = GetExitCodeProcess(reinterpret_cast(pid), &exitCode); - if(not success){ + if (not success) { throwNew(e, "java/lang/Exception", getErrorStr(GetLastError())); } @@ -435,7 +486,8 @@ Java_java_lang_Runtime_waitFor(JNIEnv* e, jclass, jlong pid, jlong tid) } extern "C" JNIEXPORT void JNICALL -Java_java_lang_Runtime_kill(JNIEnv* e UNUSED, jclass, jlong pid) { + Java_java_lang_Runtime_kill(JNIEnv* e UNUSED, jclass, jlong pid) +{ #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) TerminateProcess(reinterpret_cast(pid), 1); #else @@ -443,7 +495,8 @@ Java_java_lang_Runtime_kill(JNIEnv* e UNUSED, jclass, jlong pid) { #endif } -Locale getLocale() { +Locale getLocale() +{ #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) const char* lang = ""; const char* reg = ""; @@ -452,77 +505,151 @@ Locale getLocale() { unsigned sublang = langid >> 10; switch (prilang) { - case 0x004: { - lang = "zh"; - switch (sublang) { - case 0x01: reg = "CN"; break; - case 0x02: reg = "TW"; break; - case 0x03: reg = "HK"; break; - case 0x04: reg = "SG"; break; - } - } break; - case 0x006: lang = "da"; reg = "DK"; break; - case 0x007: lang = "de"; reg = "DE"; break; - case 0x009: { - lang = "en"; - switch (sublang) { - case 0x01: reg = "US"; break; - case 0x02: reg = "GB"; break; - case 0x03: reg = "AU"; break; - case 0x04: reg = "CA"; break; - case 0x05: reg = "NZ"; break; - case 0x06: reg = "IE"; break; - case 0x07: reg = "ZA"; break; - case 0x10: reg = "IN"; break; - } - } break; - case 0x00a: { - lang = "es"; - switch (sublang) { - case 0x01: case 0x03: reg = "ES"; break; - case 0x02: reg = "MX"; break; - } - } break; - case 0x00c: { - lang = "fr"; - switch (sublang) { - case 0x01: reg = "FR"; break; - case 0x02: reg = "BE"; break; - case 0x03: reg = "CA"; break; - } - } break; - case 0x010: lang = "it"; reg = "IT"; break; - case 0x011: lang = "ja"; reg = "JP"; break; - case 0x012: lang = "ko"; reg = "KR"; break; - case 0x013: { - lang = "nl"; - switch (sublang) { - case 0x01: reg = "NL"; break; - case 0x02: reg = "BE"; break; - } - } break; - case 0x014: lang = "no"; reg = "NO"; break; - case 0x015: lang = "pl"; reg = "PL"; break; - case 0x016: { - lang = "pt"; - switch (sublang) { - case 0x01: reg = "BR"; break; - case 0x02: reg = "PT"; break; - } - } break; - case 0x018: lang = "ro"; reg = "RO"; break; - case 0x019: lang = "ru"; reg = "RU"; break; - case 0x01d: lang = "sv"; reg = "SE"; break; - default: lang = "en"; + case 0x004: { + lang = "zh"; + switch (sublang) { + case 0x01: + reg = "CN"; + break; + case 0x02: + reg = "TW"; + break; + case 0x03: + reg = "HK"; + break; + case 0x04: + reg = "SG"; + break; + } + } break; + case 0x006: + lang = "da"; + reg = "DK"; + break; + case 0x007: + lang = "de"; + reg = "DE"; + break; + case 0x009: { + lang = "en"; + switch (sublang) { + case 0x01: + reg = "US"; + break; + case 0x02: + reg = "GB"; + break; + case 0x03: + reg = "AU"; + break; + case 0x04: + reg = "CA"; + break; + case 0x05: + reg = "NZ"; + break; + case 0x06: + reg = "IE"; + break; + case 0x07: + reg = "ZA"; + break; + case 0x10: + reg = "IN"; + break; + } + } break; + case 0x00a: { + lang = "es"; + switch (sublang) { + case 0x01: + case 0x03: + reg = "ES"; + break; + case 0x02: + reg = "MX"; + break; + } + } break; + case 0x00c: { + lang = "fr"; + switch (sublang) { + case 0x01: + reg = "FR"; + break; + case 0x02: + reg = "BE"; + break; + case 0x03: + reg = "CA"; + break; + } + } break; + case 0x010: + lang = "it"; + reg = "IT"; + break; + case 0x011: + lang = "ja"; + reg = "JP"; + break; + case 0x012: + lang = "ko"; + reg = "KR"; + break; + case 0x013: { + lang = "nl"; + switch (sublang) { + case 0x01: + reg = "NL"; + break; + case 0x02: + reg = "BE"; + break; + } + } break; + case 0x014: + lang = "no"; + reg = "NO"; + break; + case 0x015: + lang = "pl"; + reg = "PL"; + break; + case 0x016: { + lang = "pt"; + switch (sublang) { + case 0x01: + reg = "BR"; + break; + case 0x02: + reg = "PT"; + break; + } + } break; + case 0x018: + lang = "ro"; + reg = "RO"; + break; + case 0x019: + lang = "ru"; + reg = "RU"; + break; + case 0x01d: + lang = "sv"; + reg = "SE"; + break; + default: + lang = "en"; } return Locale(lang, reg); #else std::wstring culture = AvianInterop::GetCurrentUICulture(); - char* cultureName = strdup(std::string(culture.begin(), culture.end()).c_str()); + char* cultureName + = strdup(std::string(culture.begin(), culture.end()).c_str()); char* delimiter = strchr(cultureName, '-'); - if(!delimiter) - { + if (!delimiter) { free(cultureName); return Locale("en", "US"); } @@ -535,44 +662,50 @@ Locale getLocale() { #endif } #else -extern "C" JNIEXPORT void JNICALL -Java_java_lang_Runtime_exec(JNIEnv* e, jclass, - jobjectArray command, jlongArray process) +extern "C" JNIEXPORT void JNICALL + Java_java_lang_Runtime_exec(JNIEnv* e, + jclass, + jobjectArray command, + jlongArray process) { - char** argv = static_cast - (malloc((e->GetArrayLength(command) + 1) * sizeof(char*))); + char** argv = static_cast( + malloc((e->GetArrayLength(command) + 1) * sizeof(char*))); int i; - for(i = 0; i < e->GetArrayLength(command); i++){ - jstring element = (jstring) e->GetObjectArrayElement(command, i); + for (i = 0; i < e->GetArrayLength(command); i++) { + jstring element = (jstring)e->GetObjectArrayElement(command, i); char* s = const_cast(e->GetStringUTFChars(element, 0)); argv[i] = s; } argv[i] = 0; - - int in[] = { -1, -1 }; - int out[] = { -1, -1 }; - int err[] = { -1, -1 }; - int msg[] = { -1, -1 }; - + + int in[] = {-1, -1}; + int out[] = {-1, -1}; + int err[] = {-1, -1}; + int msg[] = {-1, -1}; + makePipe(e, in); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; jlong inDescriptor = static_cast(in[0]); e->SetLongArrayRegion(process, 2, 1, &inDescriptor); makePipe(e, out); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; jlong outDescriptor = static_cast(out[1]); e->SetLongArrayRegion(process, 3, 1, &outDescriptor); makePipe(e, err); - if(e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; jlong errDescriptor = static_cast(err[0]); e->SetLongArrayRegion(process, 4, 1, &errDescriptor); makePipe(e, msg); - if(e->ExceptionCheck()) return; - if(fcntl(msg[1], F_SETFD, FD_CLOEXEC) != 0) { + if (e->ExceptionCheck()) + return; + if (fcntl(msg[1], F_SETFD, FD_CLOEXEC) != 0) { throwNewErrno(e, "java/io/IOException"); return; } - + #ifdef __QNX__ // fork(2) doesn't work in multithreaded QNX programs. See // http://www.qnx.com/developers/docs/6.4.1/neutrino/getting_started/s1_procs.html @@ -583,11 +716,11 @@ Java_java_lang_Runtime_exec(JNIEnv* e, jclass, // parent/child address space, so we use fork if we can. pid_t pid = fork(); #endif - switch(pid){ - case -1: // error + switch (pid) { + case -1: // error throwNewErrno(e, "java/io/IOException"); return; - case 0: { // child + case 0: { // child // Setup stdin, stdout and stderr dup2(in[1], 1); close(in); @@ -596,90 +729,97 @@ Java_java_lang_Runtime_exec(JNIEnv* e, jclass, dup2(err[1], 2); close(err); close(msg[0]); - + execvp(argv[0], argv); - + // Error if here int val = errno; ssize_t rv UNUSED = write(msg[1], &val, sizeof(val)); exit(127); } break; - - default: { //parent + + default: { // parent jlong JNIPid = static_cast(pid); e->SetLongArrayRegion(process, 0, 1, &JNIPid); - + safeClose(in[1]); safeClose(out[0]); safeClose(err[1]); safeClose(msg[1]); - + int val; int r = read(msg[0], &val, sizeof(val)); - if(r == -1) { + if (r == -1) { throwNewErrno(e, "java/io/IOException"); return; - } else if(r) { + } else if (r) { errno = val; throwNewErrno(e, "java/io/IOException"); return; } } break; } - + safeClose(msg[0]); clean(e, command, argv); - + fcntl(in[0], F_SETFD, FD_CLOEXEC); fcntl(out[1], F_SETFD, FD_CLOEXEC); fcntl(err[0], F_SETFD, FD_CLOEXEC); } -extern "C" JNIEXPORT jint JNICALL -Java_java_lang_Runtime_waitFor(JNIEnv*, jclass, jlong pid, jlong) +extern "C" JNIEXPORT jint JNICALL + Java_java_lang_Runtime_waitFor(JNIEnv*, jclass, jlong pid, jlong) { bool finished = false; int status; int exitCode; - while(!finished){ + while (!finished) { waitpid(pid, &status, 0); - if(WIFEXITED(status)){ + if (WIFEXITED(status)) { finished = true; exitCode = WEXITSTATUS(status); - } else if(WIFSIGNALED(status)){ + } else if (WIFSIGNALED(status)) { finished = true; exitCode = -1; } } - + return exitCode; } extern "C" JNIEXPORT void JNICALL -Java_java_lang_Runtime_kill(JNIEnv*, jclass, jlong pid) { + Java_java_lang_Runtime_kill(JNIEnv*, jclass, jlong pid) +{ kill((pid_t)pid, SIGTERM); } -Locale getLocale() { +Locale getLocale() +{ Locale fallback; const char* LANG = getenv("LANG"); - if (!LANG || strcmp(LANG, "C") == 0) return fallback; + if (!LANG || strcmp(LANG, "C") == 0) + return fallback; int len = strlen(LANG); - char buf[len + 1]; // + 1 for the '\0' char + char buf[len + 1]; // + 1 for the '\0' char memcpy(buf, LANG, len + 1); char* tracer = buf; const char* reg; - while (*tracer && *tracer != '_') ++tracer; - if (!*tracer) return fallback; + while (*tracer && *tracer != '_') + ++tracer; + if (!*tracer) + return fallback; *tracer = '\0'; reg = ++tracer; - while (*tracer && *tracer != '.') ++tracer; - if (tracer == reg) return fallback; + while (*tracer && *tracer != '.') + ++tracer; + if (tracer == reg) + return fallback; *tracer = '\0'; Locale locale(buf, reg); @@ -715,20 +855,20 @@ extern "C" JNIEXPORT jobjectArray JNICALL e->SetObjectArrayElement(array, index++, e->NewStringUTF("path.separator=;")); -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) e->SetObjectArrayElement(array, index++, e->NewStringUTF("os.name=Windows")); -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) e->SetObjectArrayElement( array, index++, e->NewStringUTF("os.name=Windows Phone")); -# else +#else e->SetObjectArrayElement( array, index++, e->NewStringUTF("os.name=Windows RT")); -# endif +#endif -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) { OSVERSIONINFO OSversion; OSversion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); @@ -742,45 +882,45 @@ extern "C" JNIEXPORT jobjectArray JNICALL static_cast(OSversion.dwMinorVersion)); } -# else +#else // Currently there is no alternative on WinRT/WP8 e->SetObjectArrayElement(array, index++, e->NewStringUTF("os.version=8.0")); -# endif +#endif -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) { WCHAR buffer[MAX_PATH]; GetTempPathW(MAX_PATH, buffer); add(e, array, index++, L"java.io.tmpdir=%ls", buffer); } -# else +#else add(e, array, index++, L"java.io.tmpdir=%ls", AvianInterop::GetTemporaryFolder().c_str()); -# endif +#endif -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) { WCHAR buffer[MAX_PATH]; GetCurrentDirectoryW(MAX_PATH, buffer); add(e, array, index++, L"user.dir=%ls", buffer); } -# else +#else add(e, array, index++, L"user.dir=%ls", AvianInterop::GetInstalledLocation().c_str()); -# endif +#endif -# if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #ifdef _MSC_VER { WCHAR buffer[MAX_PATH]; @@ -794,14 +934,14 @@ extern "C" JNIEXPORT jobjectArray JNICALL add(e, array, index++, L"user.home=%ls", _wgetenv(L"USERPROFILE")); #endif -# else +#else add(e, array, index++, L"user.home=%ls", AvianInterop::GetDocumentsLibraryLocation().c_str()); -# endif +#endif #else // not Windows e->SetObjectArrayElement( @@ -853,25 +993,27 @@ extern "C" JNIEXPORT jobjectArray JNICALL // support (neither of which is likely to be of great importance). #ifdef AVIAN_IOS namespace { - const char* environ[] = { 0 }; +const char* environ[] = {0}; } #elif defined __APPLE__ -# include -# define environ (*_NSGetEnviron()) -#elif defined(WINAPI_FAMILY) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#include +#define environ (*_NSGetEnviron()) +#elif defined(WINAPI_FAMILY) \ + && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) // WinRT/WP8 does not provide alternative for environment variables -char* environ[] = { 0 }; +char* environ[] = {0}; #else extern char** environ; #endif extern "C" JNIEXPORT jobjectArray JNICALL -Java_java_lang_System_getEnvironment(JNIEnv* env, jclass) { + Java_java_lang_System_getEnvironment(JNIEnv* env, jclass) +{ int length; - for (length = 0; environ[length] != 0; ++length) ; + for (length = 0; environ[length] != 0; ++length) + ; - jobjectArray stringArray = - env->NewObjectArray(length, env->FindClass("java/lang/String"), - env->NewStringUTF("")); + jobjectArray stringArray = env->NewObjectArray( + length, env->FindClass("java/lang/String"), env->NewStringUTF("")); for (int i = 0; i < length; i++) { jobject varString = env->NewStringUTF(environ[i]); @@ -882,7 +1024,7 @@ Java_java_lang_System_getEnvironment(JNIEnv* env, jclass) { } extern "C" JNIEXPORT jlong JNICALL -Java_java_lang_System_currentTimeMillis(JNIEnv*, jclass) + Java_java_lang_System_currentTimeMillis(JNIEnv*, jclass) { #ifdef PLATFORM_WINDOWS // We used to use _ftime here, but that only gives us 1-second @@ -890,18 +1032,18 @@ Java_java_lang_System_currentTimeMillis(JNIEnv*, jclass) // doesn't have it as of this writing. So we use this mess instead: FILETIME time; GetSystemTimeAsFileTime(&time); - return (((static_cast(time.dwHighDateTime) << 32) - | time.dwLowDateTime) / 10000) - 11644473600000LL; + return (((static_cast(time.dwHighDateTime) << 32) | time.dwLowDateTime) + / 10000) - 11644473600000LL; #else - timeval tv = { 0, 0 }; + timeval tv = {0, 0}; gettimeofday(&tv, 0); - return (static_cast(tv.tv_sec) * 1000) + - (static_cast(tv.tv_usec) / 1000); + return (static_cast(tv.tv_sec) * 1000) + + (static_cast(tv.tv_usec) / 1000); #endif } extern "C" JNIEXPORT jstring JNICALL -Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name) + Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name) { jstring r = 0; const char* chars = e->GetStringUTFChars(name, 0); @@ -909,8 +1051,7 @@ Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name) unsigned nameLength = strlen(chars); unsigned size = sizeof(SO_PREFIX) + nameLength + sizeof(SO_SUFFIX); RUNTIME_ARRAY(char, buffer, size); - snprintf - (RUNTIME_ARRAY_BODY(buffer), size, SO_PREFIX "%s" SO_SUFFIX, chars); + snprintf(RUNTIME_ARRAY_BODY(buffer), size, SO_PREFIX "%s" SO_SUFFIX, chars); r = e->NewStringUTF(RUNTIME_ARRAY_BODY(buffer)); e->ReleaseStringUTFChars(name, chars); @@ -919,20 +1060,22 @@ Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name) } extern "C" JNIEXPORT jboolean JNICALL -Java_java_lang_Double_isInfinite(JNIEnv*, jclass, jdouble val) + Java_java_lang_Double_isInfinite(JNIEnv*, jclass, jdouble val) { return !isfinite(val); } extern "C" JNIEXPORT jboolean JNICALL -Java_java_lang_Double_isNaN(JNIEnv*, jclass, jdouble val) + Java_java_lang_Double_isNaN(JNIEnv*, jclass, jdouble val) { return isnan(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Double_doubleFromString(JNIEnv*e, jclass, jstring s, - jintArray numDoublesRead) + Java_java_lang_Double_doubleFromString(JNIEnv* e, + jclass, + jstring s, + jintArray numDoublesRead) { const char* chars = e->GetStringUTFChars(s, 0); double d = 0.0; @@ -951,20 +1094,22 @@ Java_java_lang_Double_doubleFromString(JNIEnv*e, jclass, jstring s, } extern "C" JNIEXPORT jboolean JNICALL -Java_java_lang_Float_isInfinite(JNIEnv*, jclass, jfloat val) + Java_java_lang_Float_isInfinite(JNIEnv*, jclass, jfloat val) { return !isfinite(val); } extern "C" JNIEXPORT jboolean JNICALL -Java_java_lang_Float_isNaN(JNIEnv*, jclass, jfloat val) + Java_java_lang_Float_isNaN(JNIEnv*, jclass, jfloat val) { return isnan(val); } extern "C" JNIEXPORT jfloat JNICALL -Java_java_lang_Float_floatFromString(JNIEnv*e, jclass, jstring s, - jintArray numFloatsRead) + Java_java_lang_Float_floatFromString(JNIEnv* e, + jclass, + jstring s, + jintArray numFloatsRead) { const char* chars = e->GetStringUTFChars(s, 0); float f = 0.0; @@ -983,104 +1128,108 @@ Java_java_lang_Float_floatFromString(JNIEnv*e, jclass, jstring s, } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_sin(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_sin(JNIEnv*, jclass, jdouble val) { return sin(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_cos(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_cos(JNIEnv*, jclass, jdouble val) { return cos(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_tan(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_tan(JNIEnv*, jclass, jdouble val) { return tan(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_asin(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_asin(JNIEnv*, jclass, jdouble val) { return asin(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_acos(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_acos(JNIEnv*, jclass, jdouble val) { return acos(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_atan(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_atan(JNIEnv*, jclass, jdouble val) { return atan(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_atan2(JNIEnv*, jclass, jdouble y, jdouble x) + Java_java_lang_Math_atan2(JNIEnv*, jclass, jdouble y, jdouble x) { return atan2(y, x); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_sinh(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_sinh(JNIEnv*, jclass, jdouble val) { return sinh(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_cosh(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_cosh(JNIEnv*, jclass, jdouble val) { return cosh(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_tanh(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_tanh(JNIEnv*, jclass, jdouble val) { return tanh(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_sqrt(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_sqrt(JNIEnv*, jclass, jdouble val) { return sqrt(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_pow(JNIEnv*, jclass, jdouble val, jdouble exp) + Java_java_lang_Math_pow(JNIEnv*, jclass, jdouble val, jdouble exp) { return pow(val, exp); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_log(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_log(JNIEnv*, jclass, jdouble val) { return log(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_floor(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_floor(JNIEnv*, jclass, jdouble val) { return floor(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_ceil(JNIEnv*, jclass, jdouble val) + Java_java_lang_Math_ceil(JNIEnv*, jclass, jdouble val) { return ceil(val); } extern "C" JNIEXPORT jdouble JNICALL -Java_java_lang_Math_exp(JNIEnv*, jclass, jdouble exp) + Java_java_lang_Math_exp(JNIEnv*, jclass, jdouble exp) { return pow(M_E, exp); } extern "C" JNIEXPORT jint JNICALL -Java_java_lang_Double_fillBufferWithDouble(JNIEnv* e, jclass, jdouble val, - jbyteArray buffer, jint bufferSize) { + Java_java_lang_Double_fillBufferWithDouble(JNIEnv* e, + jclass, + jdouble val, + jbyteArray buffer, + jint bufferSize) +{ jboolean isCopy; jbyte* buf = e->GetByteArrayElements(buffer, &isCopy); jint count = snprintf(reinterpret_cast(buf), bufferSize, "%g", val); diff --git a/classpath/java-net.cpp b/classpath/java-net.cpp index de8090d26d..b6eaca086f 100644 --- a/classpath/java-net.cpp +++ b/classpath/java-net.cpp @@ -15,70 +15,87 @@ using namespace avian::classpath::sockets; -extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_init(JNIEnv* e, jclass) { - init(e); +extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_init(JNIEnv* e, jclass) +{ + init(e); } extern "C" JNIEXPORT SOCKET JNICALL -Java_java_net_Socket_create(JNIEnv* e, jclass) { - return create(e); + Java_java_net_Socket_create(JNIEnv* e, jclass) +{ + return create(e); +} + +extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_connect(JNIEnv* e, + jclass, + SOCKET sock, + long addr, + short port) +{ + connect(e, sock, addr, port); +} + +extern "C" JNIEXPORT void JNICALL Java_java_net_Socket_bind(JNIEnv* e, + jclass, + SOCKET sock, + long addr, + short port) +{ + bind(e, sock, addr, port); } extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_connect(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { - connect(e, sock, addr, port); + Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock) +{ + abort(e, sock); } extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_bind(JNIEnv* e, jclass, SOCKET sock, long addr, short port) { - bind(e, sock, addr, port); + Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock) +{ + close(e, sock); } extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock) { - abort(e, sock); + Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock) +{ + close_output(e, sock); } extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock) { - close(e, sock); + Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock) +{ + close_input(e, sock); } extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock) { - close_output(e, sock); -} - -extern "C" JNIEXPORT void JNICALL -Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock) { - close_input(e, sock); -} - -extern "C" JNIEXPORT void JNICALL -Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ - SOCKET& s = *(reinterpret_cast(&arguments[0])); - vm::object buffer_obj = reinterpret_cast(arguments[2]); - int32_t& start_pos = *(reinterpret_cast(&arguments[3])); - int32_t& count = *(reinterpret_cast(&arguments[4])); - char* buffer = reinterpret_cast(&vm::byteArrayBody(t, buffer_obj, start_pos)); - avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count); + Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments) +{ /* SOCKET s, object buffer_obj, int start_pos, int count */ + SOCKET& s = *(reinterpret_cast(&arguments[0])); + vm::GcByteArray* buffer_obj = vm::cast( + t, reinterpret_cast(arguments[2])); + int32_t& start_pos = *(reinterpret_cast(&arguments[3])); + int32_t& count = *(reinterpret_cast(&arguments[4])); + char* buffer = reinterpret_cast(&buffer_obj->body()[start_pos]); + avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT int64_t JNICALL -Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments) { /* SOCKET s, object buffer_obj, int start_pos, int count */ - SOCKET& s = *(reinterpret_cast(&arguments[0])); - vm::object buffer_obj = reinterpret_cast(arguments[2]); - int32_t& start_pos = *(reinterpret_cast(&arguments[3])); - int32_t& count = *(reinterpret_cast(&arguments[4])); - char* buffer = reinterpret_cast(&vm::byteArrayBody(t, buffer_obj, start_pos)); - return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count); + Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments) +{ /* SOCKET s, object buffer_obj, int start_pos, int count */ + SOCKET& s = *(reinterpret_cast(&arguments[0])); + vm::GcByteArray* buffer_obj = vm::cast( + t, reinterpret_cast(arguments[2])); + int32_t& start_pos = *(reinterpret_cast(&arguments[3])); + int32_t& count = *(reinterpret_cast(&arguments[4])); + char* buffer = reinterpret_cast(&buffer_obj->body()[start_pos]); + return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count); } extern "C" JNIEXPORT jint JNICALL -Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, - jclass, - jstring name) + Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, + jclass, + jstring name) { const char* chars = e->GetStringUTFChars(name, 0); if (chars) { @@ -105,8 +122,8 @@ Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, throwNew(e, "java/net/UnknownHostException", 0); return 0; } else { - int address = ntohl - (reinterpret_cast(result->ai_addr)->sin_addr.s_addr); + int address = ntohl( + reinterpret_cast(result->ai_addr)->sin_addr.s_addr); freeaddrinfo(result); return address; @@ -117,4 +134,3 @@ Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e, return 0; } } - diff --git a/classpath/java-nio.cpp b/classpath/java-nio.cpp index 065e8a45ff..2e2a86cb38 100644 --- a/classpath/java-nio.cpp +++ b/classpath/java-nio.cpp @@ -17,25 +17,25 @@ #include "jni-util.h" #ifdef PLATFORM_WINDOWS -# include -# include -# include -# ifdef _MSC_VER -# define snprintf sprintf_s -# else -# include -# endif +#include +#include +#include +#ifdef _MSC_VER +#define snprintf sprintf_s #else -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#endif +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif #define java_nio_channels_SelectionKey_OP_READ 1L @@ -47,12 +47,14 @@ typedef int socklen_t; #endif -inline void* operator new(size_t, void* p) throw() { return p; } +inline void* operator new(size_t, void* p) throw() +{ + return p; +} namespace { -inline jbyteArray -charsToArray(JNIEnv* e, const char* s) +inline jbyteArray charsToArray(JNIEnv* e, const char* s) { unsigned length = strlen(s); jbyteArray a = e->NewByteArray(length + 1); @@ -60,8 +62,7 @@ charsToArray(JNIEnv* e, const char* s) return a; } -inline void -doClose(int socket) +inline void doClose(int socket) { #ifdef PLATFORM_WINDOWS closesocket(socket); @@ -70,8 +71,7 @@ doClose(int socket) #endif } -inline jbyteArray -errorString(JNIEnv* e, int n) +inline jbyteArray errorString(JNIEnv* e, int n) { #ifdef _MSC_VER const unsigned size = 128; @@ -83,8 +83,7 @@ errorString(JNIEnv* e, int n) #endif } -inline jbyteArray -socketErrorString(JNIEnv* e, int n) +inline jbyteArray socketErrorString(JNIEnv* e, int n) { #ifdef PLATFORM_WINDOWS const unsigned size = 64; @@ -96,8 +95,7 @@ socketErrorString(JNIEnv* e, int n) #endif } -inline jbyteArray -errorString(JNIEnv* e) +inline jbyteArray errorString(JNIEnv* e) { #ifdef PLATFORM_WINDOWS const unsigned size = 64; @@ -109,8 +107,7 @@ errorString(JNIEnv* e) #endif } -void -throwIOException(JNIEnv* e, const char* s) +void throwIOException(JNIEnv* e, const char* s) { throwNew(e, "java/io/IOException", s); } @@ -128,20 +125,17 @@ void throwIOException(JNIEnv* e, jbyteArray a) } } -void -throwIOException(JNIEnv* e) +void throwIOException(JNIEnv* e) { throwIOException(e, errorString(e)); } -void -throwSocketException(JNIEnv* e, const char* s) +void throwSocketException(JNIEnv* e, const char* s) { throwNew(e, "java/net/SocketException", s); } -void -throwSocketException(JNIEnv* e, jbyteArray a) +void throwSocketException(JNIEnv* e, jbyteArray a) { size_t length = e->GetArrayLength(a); uint8_t* buf = static_cast(allocate(e, length)); @@ -154,8 +148,7 @@ throwSocketException(JNIEnv* e, jbyteArray a) } } -void -throwSocketException(JNIEnv* e) +void throwSocketException(JNIEnv* e) { throwSocketException(e, errorString(e)); } @@ -168,41 +161,36 @@ void init(sockaddr_in* address, jint host, jint port) address->sin_addr.s_addr = htonl(host); } -inline bool -einProgress(int error) +inline bool einProgress(int error) { #ifdef PLATFORM_WINDOWS - return error == WSAEINPROGRESS - or error == WSAEWOULDBLOCK; + return error == WSAEINPROGRESS or error == WSAEWOULDBLOCK; #else return error == EINPROGRESS; #endif } -inline bool -einProgress() +inline bool einProgress() { #ifdef PLATFORM_WINDOWS return WSAGetLastError() == WSAEINPROGRESS - or WSAGetLastError() == WSAEWOULDBLOCK; + or WSAGetLastError() == WSAEWOULDBLOCK; #else return errno == EINPROGRESS; #endif } -inline bool -eagain() +inline bool eagain() { #ifdef PLATFORM_WINDOWS return WSAGetLastError() == WSAEINPROGRESS - or WSAGetLastError() == WSAEWOULDBLOCK; + or WSAGetLastError() == WSAEWOULDBLOCK; #else return errno == EAGAIN; #endif } -bool -setBlocking(JNIEnv* e, int d, bool blocking) +bool setBlocking(JNIEnv* e, int d, bool blocking) { #ifdef PLATFORM_WINDOWS u_long a = (blocking ? 0 : 1); @@ -212,9 +200,10 @@ setBlocking(JNIEnv* e, int d, bool blocking) return false; } #else - int r = fcntl(d, F_SETFL, (blocking - ? (fcntl(d, F_GETFL) & (~O_NONBLOCK)) - : (fcntl(d, F_GETFL) | O_NONBLOCK))); + int r = fcntl(d, + F_SETFL, + (blocking ? (fcntl(d, F_GETFL) & (~O_NONBLOCK)) + : (fcntl(d, F_GETFL) | O_NONBLOCK))); if (r < 0) { throwIOException(e); return false; @@ -223,12 +212,11 @@ setBlocking(JNIEnv* e, int d, bool blocking) return true; } -bool -setTcpNoDelay(JNIEnv* e, int d, bool on) +bool setTcpNoDelay(JNIEnv* e, int d, bool on) { int flag = on; - int r = setsockopt - (d, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(int)); + int r = setsockopt( + d, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(int)); if (r < 0) { throwSocketException(e); return false; @@ -236,12 +224,15 @@ setTcpNoDelay(JNIEnv* e, int d, bool on) return true; } -void -doBind(JNIEnv* e, int s, sockaddr_in* address) +void doBind(JNIEnv* e, int s, sockaddr_in* address) { - { int opt = 1; - int r = ::setsockopt(s, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&opt), sizeof(int)); + { + int opt = 1; + int r = ::setsockopt(s, + SOL_SOCKET, + SO_REUSEADDR, + reinterpret_cast(&opt), + sizeof(int)); if (r != 0) { throwIOException(e); return; @@ -249,9 +240,13 @@ doBind(JNIEnv* e, int s, sockaddr_in* address) } #ifdef SO_NOSIGPIPE - { int opt = 1; - int r = ::setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, - reinterpret_cast(&opt), sizeof(int)); + { + int opt = 1; + int r = ::setsockopt(s, + SOL_SOCKET, + SO_NOSIGPIPE, + reinterpret_cast(&opt), + sizeof(int)); if (r != 0) { throwIOException(e); return; @@ -259,8 +254,9 @@ doBind(JNIEnv* e, int s, sockaddr_in* address) } #endif - { int r = ::bind - (s, reinterpret_cast(address), sizeof(sockaddr_in)); + { + int r + = ::bind(s, reinterpret_cast(address), sizeof(sockaddr_in)); if (r != 0) { throwIOException(e); return; @@ -268,8 +264,7 @@ doBind(JNIEnv* e, int s, sockaddr_in* address) } } -void -doListen(JNIEnv* e, int s) +void doListen(JNIEnv* e, int s) { int r = ::listen(s, 100); if (r != 0) { @@ -277,13 +272,12 @@ doListen(JNIEnv* e, int s) } } -void -doFinishConnect(JNIEnv* e, int socket) +void doFinishConnect(JNIEnv* e, int socket) { int error; socklen_t size = sizeof(int); - int r = getsockopt(socket, SOL_SOCKET, SO_ERROR, - reinterpret_cast(&error), &size); + int r = getsockopt( + socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &size); if (r != 0 or size != sizeof(int)) { throwIOException(e); @@ -292,11 +286,10 @@ doFinishConnect(JNIEnv* e, int socket) } } -bool -doConnect(JNIEnv* e, int s, sockaddr_in* address) +bool doConnect(JNIEnv* e, int s, sockaddr_in* address) { - int r = ::connect(s, reinterpret_cast(address), - sizeof(sockaddr_in)); + int r + = ::connect(s, reinterpret_cast(address), sizeof(sockaddr_in)); if (r == 0) { return true; } else if (not einProgress()) { @@ -307,8 +300,7 @@ doConnect(JNIEnv* e, int s, sockaddr_in* address) } } -int -doAccept(JNIEnv* e, int s) +int doAccept(JNIEnv* e, int s) { sockaddr address; socklen_t length = sizeof(address); @@ -321,8 +313,7 @@ doAccept(JNIEnv* e, int s) return -1; } -int -doRead(int fd, void* buffer, size_t count) +int doRead(int fd, void* buffer, size_t count) { #ifdef PLATFORM_WINDOWS return recv(fd, static_cast(buffer), count, 0); @@ -331,16 +322,15 @@ doRead(int fd, void* buffer, size_t count) #endif } -int -doRecv(int fd, void* buffer, size_t count, int32_t* host, int32_t* port) +int doRecv(int fd, void* buffer, size_t count, int32_t* host, int32_t* port) { sockaddr address; socklen_t length = sizeof(address); - int r = recvfrom - (fd, static_cast(buffer), count, 0, &address, &length); - + int r = recvfrom(fd, static_cast(buffer), count, 0, &address, &length); + if (r > 0) { - sockaddr_in a; memcpy(&a, &address, length); + sockaddr_in a; + memcpy(&a, &address, length); *host = ntohl(a.sin_addr.s_addr); *port = ntohs(a.sin_port); } else { @@ -351,8 +341,7 @@ doRecv(int fd, void* buffer, size_t count, int32_t* host, int32_t* port) return r; } -int -doWrite(int fd, const void* buffer, size_t count) +int doWrite(int fd, const void* buffer, size_t count) { #ifdef PLATFORM_WINDOWS return send(fd, static_cast(buffer), count, 0); @@ -382,11 +371,12 @@ int makeSocket(JNIEnv* e, int type = SOCK_STREAM, int protocol = IPPROTO_TCP) return s; } -} // namespace - +} // namespace extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_ServerSocketChannel_natDoAccept(JNIEnv *e, jclass, jint socket) + Java_java_nio_channels_ServerSocketChannel_natDoAccept(JNIEnv* e, + jclass, + jint socket) { return ::doAccept(e, socket); } @@ -432,29 +422,29 @@ extern "C" JNIEXPORT void JNICALL } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketChannel_configureBlocking(JNIEnv *e, - jclass, - jint socket, - jboolean blocking) + Java_java_nio_channels_SocketChannel_configureBlocking(JNIEnv* e, + jclass, + jint socket, + jboolean blocking) { setBlocking(e, socket, blocking); } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_DatagramChannel_configureBlocking(JNIEnv* e, - jclass c, - jint socket, - jboolean blocking) + Java_java_nio_channels_DatagramChannel_configureBlocking(JNIEnv* e, + jclass c, + jint socket, + jboolean blocking) { - return Java_java_nio_channels_SocketChannel_configureBlocking - (e, c, socket, blocking); + return Java_java_nio_channels_SocketChannel_configureBlocking( + e, c, socket, blocking); } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketChannel_natSetTcpNoDelay(JNIEnv *e, - jclass, - jint socket, - jboolean on) + Java_java_nio_channels_SocketChannel_natSetTcpNoDelay(JNIEnv* e, + jclass, + jint socket, + jboolean on) { setTcpNoDelay(e, socket, on); } @@ -498,21 +488,21 @@ extern "C" JNIEXPORT jboolean JNICALL } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketChannel_natFinishConnect(JNIEnv *e, - jclass, - jint socket) + Java_java_nio_channels_SocketChannel_natFinishConnect(JNIEnv* e, + jclass, + jint socket) { doFinishConnect(e, socket); } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_SocketChannel_natRead(JNIEnv *e, - jclass, - jint socket, - jbyteArray buffer, - jint offset, - jint length, - jboolean blocking) + Java_java_nio_channels_SocketChannel_natRead(JNIEnv* e, + jclass, + jint socket, + jbyteArray buffer, + jint offset, + jint length, + jboolean blocking) { int r; if (blocking) { @@ -520,8 +510,7 @@ Java_java_nio_channels_SocketChannel_natRead(JNIEnv *e, if (buf) { r = ::doRead(socket, buf, length); if (r > 0) { - e->SetByteArrayRegion - (buffer, offset, r, reinterpret_cast(buf)); + e->SetByteArrayRegion(buffer, offset, r, reinterpret_cast(buf)); } free(buf); } else { @@ -529,8 +518,8 @@ Java_java_nio_channels_SocketChannel_natRead(JNIEnv *e, } } else { jboolean isCopy; - uint8_t* buf = static_cast - (e->GetPrimitiveArrayCritical(buffer, &isCopy)); + uint8_t* buf + = static_cast(e->GetPrimitiveArrayCritical(buffer, &isCopy)); r = ::doRead(socket, buf + offset, length); @@ -550,14 +539,14 @@ Java_java_nio_channels_SocketChannel_natRead(JNIEnv *e, } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_DatagramChannel_receive(JNIEnv* e, - jclass, - jint socket, - jbyteArray buffer, - jint offset, - jint length, - jboolean blocking, - jintArray address) + Java_java_nio_channels_DatagramChannel_receive(JNIEnv* e, + jclass, + jint socket, + jbyteArray buffer, + jint offset, + jint length, + jboolean blocking, + jintArray address) { int r; int32_t host; @@ -567,8 +556,7 @@ Java_java_nio_channels_DatagramChannel_receive(JNIEnv* e, if (buf) { r = ::doRecv(socket, buf, length, &host, &port); if (r > 0) { - e->SetByteArrayRegion - (buffer, offset, r, reinterpret_cast(buf)); + e->SetByteArrayRegion(buffer, offset, r, reinterpret_cast(buf)); } free(buf); } else { @@ -576,8 +564,8 @@ Java_java_nio_channels_DatagramChannel_receive(JNIEnv* e, } } else { jboolean isCopy; - uint8_t* buf = static_cast - (e->GetPrimitiveArrayCritical(buffer, &isCopy)); + uint8_t* buf + = static_cast(e->GetPrimitiveArrayCritical(buffer, &isCopy)); r = ::doRecv(socket, buf + offset, length, &host, &port); @@ -593,28 +581,30 @@ Java_java_nio_channels_DatagramChannel_receive(JNIEnv* e, } else if (r == 0) { return -1; } else { - jint jhost = host; e->SetIntArrayRegion(address, 0, 1, &jhost); - jint jport = port; e->SetIntArrayRegion(address, 1, 1, &jport); + jint jhost = host; + e->SetIntArrayRegion(address, 0, 1, &jhost); + jint jport = port; + e->SetIntArrayRegion(address, 1, 1, &jport); } return r; } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_SocketChannel_natWrite(JNIEnv *e, - jclass, - jint socket, - jbyteArray buffer, - jint offset, - jint length, - jboolean blocking) + Java_java_nio_channels_SocketChannel_natWrite(JNIEnv* e, + jclass, + jint socket, + jbyteArray buffer, + jint offset, + jint length, + jboolean blocking) { int r; if (blocking) { uint8_t* buf = static_cast(allocate(e, length)); if (buf) { - e->GetByteArrayRegion - (buffer, offset, length, reinterpret_cast(buf)); + e->GetByteArrayRegion( + buffer, offset, length, reinterpret_cast(buf)); r = ::doWrite(socket, buf, length); free(buf); } else { @@ -622,8 +612,8 @@ Java_java_nio_channels_SocketChannel_natWrite(JNIEnv *e, } } else { jboolean isCopy; - uint8_t* buf = static_cast - (e->GetPrimitiveArrayCritical(buffer, &isCopy)); + uint8_t* buf + = static_cast(e->GetPrimitiveArrayCritical(buffer, &isCopy)); r = ::doWrite(socket, buf + offset, length); @@ -641,16 +631,16 @@ Java_java_nio_channels_SocketChannel_natWrite(JNIEnv *e, } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_DatagramChannel_write(JNIEnv* e, - jclass c, - jint socket, - jbyteArray buffer, - jint offset, - jint length, - jboolean blocking) + Java_java_nio_channels_DatagramChannel_write(JNIEnv* e, + jclass c, + jint socket, + jbyteArray buffer, + jint offset, + jint length, + jboolean blocking) { - return Java_java_nio_channels_SocketChannel_natWrite - (e, c, socket, buffer, offset, length, blocking); + return Java_java_nio_channels_SocketChannel_natWrite( + e, c, socket, buffer, offset, length, blocking); } extern "C" JNIEXPORT jint JNICALL @@ -699,14 +689,14 @@ extern "C" JNIEXPORT jint JNICALL } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketChannel_natThrowWriteError(JNIEnv *e, - jclass, - jint socket) + Java_java_nio_channels_SocketChannel_natThrowWriteError(JNIEnv* e, + jclass, + jint socket) { int error; socklen_t size = sizeof(int); - int r = getsockopt(socket, SOL_SOCKET, SO_ERROR, - reinterpret_cast(&error), &size); + int r = getsockopt( + socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &size); if (r != 0 or size != sizeof(int)) { throwIOException(e); } else if (error != 0) { @@ -715,17 +705,15 @@ Java_java_nio_channels_SocketChannel_natThrowWriteError(JNIEnv *e, } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketChannel_natCloseSocket(JNIEnv *, - jclass, - jint socket) + Java_java_nio_channels_SocketChannel_natCloseSocket(JNIEnv*, + jclass, + jint socket) { doClose(socket); } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_DatagramChannel_close(JNIEnv *, - jclass, - jint socket) + Java_java_nio_channels_DatagramChannel_close(JNIEnv*, jclass, jint socket) { doClose(socket); } @@ -739,69 +727,85 @@ class Pipe { // pipe descriptors or others. Thus, to implement // Selector.wakeup(), we make a socket connection via the loopback // interface and use it as a pipe. - Pipe(JNIEnv* e): connected_(false), listener_(-1), reader_(-1), writer_(-1) { + Pipe(JNIEnv* e) : connected_(false), listener_(-1), reader_(-1), writer_(-1) + { sockaddr_in address; address.sin_family = AF_INET; address.sin_port = 0; - address.sin_addr.s_addr = inet_addr("127.0.0.1"); //INADDR_LOOPBACK; + address.sin_addr.s_addr = inet_addr("127.0.0.1"); // INADDR_LOOPBACK; listener_ = makeSocket(e); - if (e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; setBlocking(e, listener_, false); ::doBind(e, listener_, &address); - if (e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; ::doListen(e, listener_); - if (e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; socklen_t length = sizeof(sockaddr_in); - int r = getsockname(listener_, reinterpret_cast(&address), - &length); + int r = getsockname( + listener_, reinterpret_cast(&address), &length); if (r) { throwIOException(e); return; } writer_ = makeSocket(e); - if (e->ExceptionCheck()) return; + if (e->ExceptionCheck()) + return; setBlocking(e, writer_, true); connected_ = ::doConnect(e, writer_, &address); } - void dispose() { - if (listener_ >= 0) ::doClose(listener_); - if (reader_ >= 0) ::doClose(reader_); - if (writer_ >= 0) ::doClose(writer_); + void dispose() + { + if (listener_ >= 0) + ::doClose(listener_); + if (reader_ >= 0) + ::doClose(reader_); + if (writer_ >= 0) + ::doClose(writer_); } - bool connected() { + bool connected() + { return connected_; } - void setConnected(bool v) { + void setConnected(bool v) + { connected_ = v; } - int listener() { + int listener() + { return listener_; } - void setListener(int v) { + void setListener(int v) + { listener_ = v; } - int reader() { + int reader() + { return reader_; } - void setReader(int v) { + void setReader(int v) + { reader_ = v; } - int writer() { + int writer() + { return writer_; } @@ -811,7 +815,8 @@ class Pipe { int reader_; int writer_; #else - Pipe(JNIEnv* e) { + Pipe(JNIEnv* e) + { if (::pipe(pipe) != 0) { throwIOException(e); return; @@ -824,21 +829,25 @@ class Pipe { open_ = true; } - void dispose() { + void dispose() + { ::doClose(pipe[0]); ::doClose(pipe[1]); open_ = false; } - bool connected() { + bool connected() + { return open_; } - int reader() { + int reader() + { return pipe[0]; } - int writer() { + int writer() + { return pipe[1]; } @@ -853,18 +862,21 @@ struct SelectorState { fd_set write; fd_set except; Pipe control; - SelectorState(JNIEnv* e) : control(e) { } + SelectorState(JNIEnv* e) : control(e) + { + } }; -} // namespace +} // namespace extern "C" JNIEXPORT jlong JNICALL -Java_java_nio_channels_SocketSelector_natInit(JNIEnv* e, jclass) + Java_java_nio_channels_SocketSelector_natInit(JNIEnv* e, jclass) { - void *mem = malloc(sizeof(SelectorState)); + void* mem = malloc(sizeof(SelectorState)); if (mem) { - SelectorState *s = new (mem) SelectorState(e); - if (e->ExceptionCheck()) return 0; + SelectorState* s = new (mem) SelectorState(e); + if (e->ExceptionCheck()) + return 0; if (s) { FD_ZERO(&(s->read)); @@ -878,7 +890,9 @@ Java_java_nio_channels_SocketSelector_natInit(JNIEnv* e, jclass) } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketSelector_natWakeup(JNIEnv *e, jclass, jlong state) + Java_java_nio_channels_SocketSelector_natWakeup(JNIEnv* e, + jclass, + jlong state) { SelectorState* s = reinterpret_cast(state); if (s->control.connected()) { @@ -891,7 +905,7 @@ Java_java_nio_channels_SocketSelector_natWakeup(JNIEnv *e, jclass, jlong state) } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketSelector_natClose(JNIEnv *, jclass, jlong state) + Java_java_nio_channels_SocketSelector_natClose(JNIEnv*, jclass, jlong state) { SelectorState* s = reinterpret_cast(state); s->control.dispose(); @@ -899,9 +913,10 @@ Java_java_nio_channels_SocketSelector_natClose(JNIEnv *, jclass, jlong state) } extern "C" JNIEXPORT void JNICALL -Java_java_nio_channels_SocketSelector_natSelectClearAll(JNIEnv *, jclass, - jint socket, - jlong state) + Java_java_nio_channels_SocketSelector_natSelectClearAll(JNIEnv*, + jclass, + jint socket, + jlong state) { SelectorState* s = reinterpret_cast(state); FD_CLR(static_cast(socket), &(s->read)); @@ -910,27 +925,30 @@ Java_java_nio_channels_SocketSelector_natSelectClearAll(JNIEnv *, jclass, } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_SocketSelector_natSelectUpdateInterestSet(JNIEnv *, - jclass, - jint socket, - jint interest, - jlong state, - jint max) + Java_java_nio_channels_SocketSelector_natSelectUpdateInterestSet( + JNIEnv*, + jclass, + jint socket, + jint interest, + jlong state, + jint max) { SelectorState* s = reinterpret_cast(state); - if (interest & (java_nio_channels_SelectionKey_OP_READ | - java_nio_channels_SelectionKey_OP_ACCEPT)) { + if (interest & (java_nio_channels_SelectionKey_OP_READ + | java_nio_channels_SelectionKey_OP_ACCEPT)) { FD_SET(static_cast(socket), &(s->read)); - if (max < socket) max = socket; + if (max < socket) + max = socket; } else { FD_CLR(static_cast(socket), &(s->read)); } - - if (interest & (java_nio_channels_SelectionKey_OP_WRITE | - java_nio_channels_SelectionKey_OP_CONNECT)) { + + if (interest & (java_nio_channels_SelectionKey_OP_WRITE + | java_nio_channels_SelectionKey_OP_CONNECT)) { FD_SET(static_cast(socket), &(s->write)); FD_SET(static_cast(socket), &(s->except)); - if (max < socket) max = socket; + if (max < socket) + max = socket; } else { FD_CLR(static_cast(socket), &(s->write)); } @@ -938,30 +956,34 @@ Java_java_nio_channels_SocketSelector_natSelectUpdateInterestSet(JNIEnv *, } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv *e, jclass, - jlong state, - jint max, - jlong interval) + Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv* e, + jclass, + jlong state, + jint max, + jlong interval) { SelectorState* s = reinterpret_cast(state); if (s->control.reader() >= 0) { int socket = s->control.reader(); FD_SET(static_cast(socket), &(s->read)); - if (max < socket) max = socket; + if (max < socket) + max = socket; } #ifdef PLATFORM_WINDOWS if (s->control.listener() >= 0) { int socket = s->control.listener(); FD_SET(static_cast(socket), &(s->read)); - if (max < socket) max = socket; + if (max < socket) + max = socket; } if (not s->control.connected()) { int socket = s->control.writer(); FD_SET(static_cast(socket), &(s->write)); FD_SET(static_cast(socket), &(s->except)); - if (max < socket) max = socket; + if (max < socket) + max = socket; } #endif @@ -986,17 +1008,16 @@ Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv *e, jclass, } #ifdef PLATFORM_WINDOWS - if (FD_ISSET(s->control.writer(), &(s->write)) or - FD_ISSET(s->control.writer(), &(s->except))) - { + if (FD_ISSET(s->control.writer(), &(s->write)) + or FD_ISSET(s->control.writer(), &(s->except))) { int socket = s->control.writer(); FD_CLR(static_cast(socket), &(s->write)); FD_CLR(static_cast(socket), &(s->except)); int error; socklen_t size = sizeof(int); - int r = getsockopt(socket, SOL_SOCKET, SO_ERROR, - reinterpret_cast(&error), &size); + int r = getsockopt( + socket, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &size); if (r != 0 or size != sizeof(int)) { throwIOException(e); } else if (error != 0) { @@ -1005,9 +1026,8 @@ Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv *e, jclass, s->control.setConnected(true); } - if (s->control.listener() >= 0 and - FD_ISSET(s->control.listener(), &(s->read))) - { + if (s->control.listener() >= 0 + and FD_ISSET(s->control.listener(), &(s->read))) { FD_CLR(static_cast(s->control.listener()), &(s->read)); s->control.setReader(::doAccept(e, s->control.listener())); @@ -1015,9 +1035,7 @@ Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv *e, jclass, } #endif - if (s->control.reader() >= 0 and - FD_ISSET(s->control.reader(), &(s->read))) - { + if (s->control.reader() >= 0 and FD_ISSET(s->control.reader(), &(s->read))) { FD_CLR(static_cast(s->control.reader()), &(s->read)); char c; @@ -1034,24 +1052,25 @@ Java_java_nio_channels_SocketSelector_natDoSocketSelect(JNIEnv *e, jclass, } extern "C" JNIEXPORT jint JNICALL -Java_java_nio_channels_SocketSelector_natUpdateReadySet(JNIEnv *, jclass, - jint socket, - jint interest, - jlong state) + Java_java_nio_channels_SocketSelector_natUpdateReadySet(JNIEnv*, + jclass, + jint socket, + jint interest, + jlong state) { SelectorState* s = reinterpret_cast(state); jint ready = 0; - + if (FD_ISSET(socket, &(s->read))) { if (interest & java_nio_channels_SelectionKey_OP_READ) { ready |= java_nio_channels_SelectionKey_OP_READ; } - + if (interest & java_nio_channels_SelectionKey_OP_ACCEPT) { ready |= java_nio_channels_SelectionKey_OP_ACCEPT; } } - + if (FD_ISSET(socket, &(s->write)) or FD_ISSET(socket, &(s->except))) { if (interest & java_nio_channels_SelectionKey_OP_WRITE) { ready |= java_nio_channels_SelectionKey_OP_WRITE; @@ -1059,15 +1078,14 @@ Java_java_nio_channels_SocketSelector_natUpdateReadySet(JNIEnv *, jclass, if (interest & java_nio_channels_SelectionKey_OP_CONNECT) { ready |= java_nio_channels_SelectionKey_OP_CONNECT; - } + } } return ready; } - extern "C" JNIEXPORT jboolean JNICALL -Java_java_nio_ByteOrder_isNativeBigEndian(JNIEnv *, jclass) + Java_java_nio_ByteOrder_isNativeBigEndian(JNIEnv*, jclass) { union { uint32_t i; diff --git a/classpath/java-util-zip.cpp b/classpath/java-util-zip.cpp index e6f20a77f2..13a934d1af 100644 --- a/classpath/java-util-zip.cpp +++ b/classpath/java-util-zip.cpp @@ -16,17 +16,16 @@ #include "jni-util.h" extern "C" JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_make -(JNIEnv* e, jclass, jboolean nowrap) + Java_java_util_zip_Inflater_make(JNIEnv* e, jclass, jboolean nowrap) { z_stream* s = static_cast(malloc(sizeof(z_stream))); if (s == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return 0; + return 0; } memset(s, 0, sizeof(z_stream)); - + int r = inflateInit2(s, (nowrap ? -15 : 15)); if (r != Z_OK) { free(s); @@ -38,7 +37,7 @@ Java_java_util_zip_Inflater_make } extern "C" JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_dispose(JNIEnv*, jclass, jlong peer) + Java_java_util_zip_Inflater_dispose(JNIEnv*, jclass, jlong peer) { z_stream* s = reinterpret_cast(peer); inflateEnd(s); @@ -46,39 +45,43 @@ Java_java_util_zip_Inflater_dispose(JNIEnv*, jclass, jlong peer) } extern "C" JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_inflate -(JNIEnv* e, jclass, jlong peer, - jbyteArray input, jint inputOffset, jint inputLength, - jbyteArray output, jint outputOffset, jint outputLength, - jintArray results) + Java_java_util_zip_Inflater_inflate(JNIEnv* e, + jclass, + jlong peer, + jbyteArray input, + jint inputOffset, + jint inputLength, + jbyteArray output, + jint outputOffset, + jint outputLength, + jintArray results) { z_stream* s = reinterpret_cast(peer); jbyte* in = static_cast(malloc(inputLength)); if (in == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return; + return; } jbyte* out = static_cast(malloc(outputLength)); if (out == 0) { free(in); throwNew(e, "java/lang/OutOfMemoryError", 0); - return; + return; } e->GetByteArrayRegion(input, inputOffset, inputLength, in); - + s->next_in = reinterpret_cast(in); s->avail_in = inputLength; s->next_out = reinterpret_cast(out); s->avail_out = outputLength; int r = inflate(s, Z_SYNC_FLUSH); - jint resultArray[3] - = { r, - static_cast(inputLength - s->avail_in), - static_cast(outputLength - s->avail_out) }; + jint resultArray[3] = {r, + static_cast(inputLength - s->avail_in), + static_cast(outputLength - s->avail_out)}; free(in); @@ -89,17 +92,19 @@ Java_java_util_zip_Inflater_inflate } extern "C" JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_make -(JNIEnv* e, jclass, jboolean nowrap, jint level) + Java_java_util_zip_Deflater_make(JNIEnv* e, + jclass, + jboolean nowrap, + jint level) { z_stream* s = static_cast(malloc(sizeof(z_stream))); if (s == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return 0; + return 0; } memset(s, 0, sizeof(z_stream)); - + int r = deflateInit2(s, level, (nowrap ? -15 : 15)); if (r != Z_OK) { free(s); @@ -111,7 +116,7 @@ Java_java_util_zip_Deflater_make } extern "C" JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_dispose(JNIEnv*, jclass, jlong peer) + Java_java_util_zip_Deflater_dispose(JNIEnv*, jclass, jlong peer) { z_stream* s = reinterpret_cast(peer); deflateEnd(s); @@ -119,39 +124,44 @@ Java_java_util_zip_Deflater_dispose(JNIEnv*, jclass, jlong peer) } extern "C" JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_deflate -(JNIEnv* e, jclass, jlong peer, - jbyteArray input, jint inputOffset, jint inputLength, - jbyteArray output, jint outputOffset, jint outputLength, - jboolean finish, jintArray results) + Java_java_util_zip_Deflater_deflate(JNIEnv* e, + jclass, + jlong peer, + jbyteArray input, + jint inputOffset, + jint inputLength, + jbyteArray output, + jint outputOffset, + jint outputLength, + jboolean finish, + jintArray results) { z_stream* s = reinterpret_cast(peer); jbyte* in = static_cast(malloc(inputLength)); if (in == 0) { throwNew(e, "java/lang/OutOfMemoryError", 0); - return; + return; } jbyte* out = static_cast(malloc(outputLength)); if (out == 0) { free(in); throwNew(e, "java/lang/OutOfMemoryError", 0); - return; + return; } e->GetByteArrayRegion(input, inputOffset, inputLength, in); - + s->next_in = reinterpret_cast(in); s->avail_in = inputLength; s->next_out = reinterpret_cast(out); s->avail_out = outputLength; int r = deflate(s, finish ? Z_FINISH : Z_NO_FLUSH); - jint resultArray[3] - = { r, - static_cast(inputLength - s->avail_in), - static_cast(outputLength - s->avail_out) }; + jint resultArray[3] = {r, + static_cast(inputLength - s->avail_in), + static_cast(outputLength - s->avail_out)}; free(in); diff --git a/classpath/java-util.cpp b/classpath/java-util.cpp index 270109f0d8..50a7f8778a 100644 --- a/classpath/java-util.cpp +++ b/classpath/java-util.cpp @@ -16,8 +16,7 @@ namespace { #if (!defined PLATFORM_WINDOWS) || (defined _MSC_VER) -void -removeNewline(char* s) +void removeNewline(char* s) { for (; s; ++s) { if (*s == '\n') { @@ -29,10 +28,10 @@ removeNewline(char* s) #endif -} // namespace +} // namespace extern "C" JNIEXPORT jstring JNICALL -Java_java_util_Date_toString(JNIEnv* e, jclass c UNUSED, jlong when) + Java_java_util_Date_toString(JNIEnv* e, jclass c UNUSED, jlong when) { const unsigned BufferSize UNUSED = 27; @@ -40,13 +39,13 @@ Java_java_util_Date_toString(JNIEnv* e, jclass c UNUSED, jlong when) #ifdef PLATFORM_WINDOWS e->MonitorEnter(c); -# ifdef _MSC_VER +#ifdef _MSC_VER char buffer[BufferSize]; ctime_s(buffer, BufferSize, &time); removeNewline(buffer); -# else +#else char* buffer = ctime(&time); -# endif +#endif jstring r = e->NewStringUTF(buffer); e->MonitorExit(c); return r; diff --git a/classpath/java/lang/Class.java b/classpath/java/lang/Class.java index 0999831a1b..53879ccf7e 100644 --- a/classpath/java/lang/Class.java +++ b/classpath/java/lang/Class.java @@ -171,8 +171,8 @@ public final class Class implements Type, AnnotatedElement { return SystemClassLoader.getClass(Classes.primitiveClass('D')); } - if (vmClass.staticTable == null) throw new AssertionError(); - return SystemClassLoader.getClass((VMClass) vmClass.staticTable); + if (vmClass.arrayElementClass == null) throw new AssertionError(); + return SystemClassLoader.getClass((VMClass) vmClass.arrayElementClass); } else { return null; } diff --git a/classpath/jni-util.h b/classpath/jni-util.h index 951aa43fc0..d04c5de64a 100644 --- a/classpath/jni-util.h +++ b/classpath/jni-util.h @@ -20,19 +20,18 @@ #undef JNIEXPORT #if (defined __MINGW32__) || (defined _MSC_VER) -# define PLATFORM_WINDOWS -# define PATH_SEPARATOR ';' -# define JNIEXPORT __declspec(dllexport) -#else // not (defined __MINGW32__) || (defined _MSC_VER) -# define PLATFORM_POSIX -# define PATH_SEPARATOR ':' -# define JNIEXPORT __attribute__ ((visibility("default"))) \ - __attribute__ ((used)) -#endif // not (defined __MINGW32__) || (defined _MSC_VER) +#define PLATFORM_WINDOWS +#define PATH_SEPARATOR ';' +#define JNIEXPORT __declspec(dllexport) +#else // not (defined __MINGW32__) || (defined _MSC_VER) +#define PLATFORM_POSIX +#define PATH_SEPARATOR ':' +#define JNIEXPORT __attribute__((visibility("default"))) __attribute__((used)) +#endif // not (defined __MINGW32__) || (defined _MSC_VER) #ifdef _MSC_VER -# define UNUSED +#define UNUSED typedef char int8_t; typedef unsigned char uint8_t; @@ -43,38 +42,37 @@ typedef unsigned int uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; -# define INT32_MAX 2147483647 +#define INT32_MAX 2147483647 -# define not ! -# define or || -# define and && -# define xor ^ +#define not! +#define or || +#define and && +#define xor ^ -# ifdef _M_IX86 -# define ARCH_x86_32 -# elif defined _M_X64 -# define ARCH_x86_64 -# endif +#ifdef _M_IX86 +#define ARCH_x86_32 +#elif defined _M_X64 +#define ARCH_x86_64 +#endif -#else // not _MSC_VER +#else // not _MSC_VER -# define UNUSED __attribute__((unused)) +#define UNUSED __attribute__((unused)) -# include "stdint.h" -# include "errno.h" +#include "stdint.h" +#include "errno.h" -# ifdef __i386__ -# define ARCH_x86_32 -# elif defined __x86_64__ -# define ARCH_x86_64 -# elif defined __arm__ -# define ARCH_arm -# endif +#ifdef __i386__ +#define ARCH_x86_32 +#elif defined __x86_64__ +#define ARCH_x86_64 +#elif defined __arm__ +#define ARCH_arm +#endif -#endif // not _MSC_VER +#endif // not _MSC_VER -inline void -throwNew(JNIEnv* e, const char* class_, const char* message, ...) +inline void throwNew(JNIEnv* e, const char* class_, const char* message, ...) { jclass c = e->FindClass(class_); if (c) { @@ -90,7 +88,7 @@ throwNew(JNIEnv* e, const char* class_, const char* message, ...) vsnprintf(buffer, BufferSize - 1, message, list); #endif va_end(list); - + e->ThrowNew(c, buffer); } else { e->ThrowNew(c, 0); @@ -99,8 +97,7 @@ throwNew(JNIEnv* e, const char* class_, const char* message, ...) } } -inline void -throwNewErrno(JNIEnv* e, const char* class_) +inline void throwNewErrno(JNIEnv* e, const char* class_) { #ifdef _MSC_VER const unsigned size = 128; @@ -112,8 +109,7 @@ throwNewErrno(JNIEnv* e, const char* class_) #endif } -inline void* -allocate(JNIEnv* e, unsigned size) +inline void* allocate(JNIEnv* e, unsigned size) { void* p = malloc(size); if (p == 0) { @@ -122,4 +118,4 @@ allocate(JNIEnv* e, unsigned size) return p; } -#endif//JNI_UTIL +#endif // JNI_UTIL diff --git a/classpath/sockets.cpp b/classpath/sockets.cpp index b66b6de016..3a4b6fe8e5 100644 --- a/classpath/sockets.cpp +++ b/classpath/sockets.cpp @@ -19,166 +19,183 @@ namespace avian { namespace classpath { namespace sockets { -int last_socket_error() { +int last_socket_error() +{ #ifdef PLATFORM_WINDOWS - int error = WSAGetLastError(); + int error = WSAGetLastError(); #else - int error = errno; + int error = errno; #endif - return error; + return error; } - -void init(JNIEnv* ONLY_ON_WINDOWS(e)) { +void init(JNIEnv* ONLY_ON_WINDOWS(e)) +{ #ifdef PLATFORM_WINDOWS static bool wsaInitialized = false; if (not wsaInitialized) { - WSADATA data; - int r = WSAStartup(MAKEWORD(2, 2), &data); - if (r or LOBYTE(data.wVersion) != 2 or HIBYTE(data.wVersion) != 2) { - throwNew(e, "java/io/IOException", "WSAStartup failed"); - } else { - wsaInitialized = true; - } + WSADATA data; + int r = WSAStartup(MAKEWORD(2, 2), &data); + if (r or LOBYTE(data.wVersion) != 2 or HIBYTE(data.wVersion) != 2) { + throwNew(e, "java/io/IOException", "WSAStartup failed"); + } else { + wsaInitialized = true; + } } #endif } -SOCKET create(JNIEnv* e) { - SOCKET sock; - if (INVALID_SOCKET == (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) { - char buf[255]; - sprintf(buf, "Can't create a socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return 0; // This doesn't matter cause we have risen an exception - } - return sock; +SOCKET create(JNIEnv* e) +{ + SOCKET sock; + if (INVALID_SOCKET == (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) { + char buf[255]; + sprintf( + buf, "Can't create a socket. System error: %d", last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return 0; // This doesn't matter cause we have risen an exception + } + return sock; } -void connect(JNIEnv* e, SOCKET sock, long addr, short port) { - sockaddr_in adr; - adr.sin_family = AF_INET; +void connect(JNIEnv* e, SOCKET sock, long addr, short port) +{ + sockaddr_in adr; + adr.sin_family = AF_INET; #ifdef PLATFORM_WINDOWS - adr.sin_addr.S_un.S_addr = htonl(addr); + adr.sin_addr.S_un.S_addr = htonl(addr); #else - adr.sin_addr.s_addr = htonl(addr); + adr.sin_addr.s_addr = htonl(addr); #endif - adr.sin_port = htons (port); + adr.sin_port = htons(port); - if (SOCKET_ERROR == ::connect(sock, (sockaddr* )&adr, sizeof(adr))) - { - char buf[255]; - sprintf(buf, "Can't connect a socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return; - } + if (SOCKET_ERROR == ::connect(sock, (sockaddr*)&adr, sizeof(adr))) { + char buf[255]; + sprintf( + buf, "Can't connect a socket. System error: %d", last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return; + } } -void bind(JNIEnv* e, SOCKET sock, long addr, short port) { - sockaddr_in adr; - adr.sin_family = AF_INET; +void bind(JNIEnv* e, SOCKET sock, long addr, short port) +{ + sockaddr_in adr; + adr.sin_family = AF_INET; #ifdef PLATFORM_WINDOWS - adr.sin_addr.S_un.S_addr = htonl(addr); + adr.sin_addr.S_un.S_addr = htonl(addr); #else - adr.sin_addr.s_addr = htonl(addr); + adr.sin_addr.s_addr = htonl(addr); #endif - adr.sin_port = htons (port); + adr.sin_port = htons(port); - if (SOCKET_ERROR == ::bind(sock, (sockaddr* )&adr, sizeof(adr))) - { - char buf[255]; - sprintf(buf, "Can't bind a socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return; - } + if (SOCKET_ERROR == ::bind(sock, (sockaddr*)&adr, sizeof(adr))) { + char buf[255]; + sprintf(buf, "Can't bind a socket. System error: %d", last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return; + } } -SOCKET accept(JNIEnv* e, SOCKET sock, long* client_addr, short* client_port) { - sockaddr_in adr; - SOCKET client_socket = ::accept(sock, (sockaddr* )&adr, NULL); - if (INVALID_SOCKET == client_socket) { - char buf[255]; - sprintf(buf, "Can't accept the incoming connection. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return INVALID_SOCKET; - } +SOCKET accept(JNIEnv* e, SOCKET sock, long* client_addr, short* client_port) +{ + sockaddr_in adr; + SOCKET client_socket = ::accept(sock, (sockaddr*)&adr, NULL); + if (INVALID_SOCKET == client_socket) { + char buf[255]; + sprintf(buf, + "Can't accept the incoming connection. System error: %d", + last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return INVALID_SOCKET; + } - if (client_addr != NULL) { - #ifdef PLATFORM_WINDOWS - *client_addr = ntohl(adr.sin_addr.S_un.S_addr); - #else - *client_addr = ntohl(adr.sin_addr.s_addr); - #endif - } + if (client_addr != NULL) { +#ifdef PLATFORM_WINDOWS + *client_addr = ntohl(adr.sin_addr.S_un.S_addr); +#else + *client_addr = ntohl(adr.sin_addr.s_addr); +#endif + } - if (client_port != NULL) { - *client_port = ntohs (adr.sin_port); - } + if (client_port != NULL) { + *client_port = ntohs(adr.sin_port); + } - return client_socket; + return client_socket; } -void send(JNIEnv* e, SOCKET sock, const char* buff_ptr, int buff_size) { - if (SOCKET_ERROR == ::send(sock, buff_ptr, buff_size, 0)) { - char buf[255]; - sprintf(buf, "Can't send data through the socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return; - } +void send(JNIEnv* e, SOCKET sock, const char* buff_ptr, int buff_size) +{ + if (SOCKET_ERROR == ::send(sock, buff_ptr, buff_size, 0)) { + char buf[255]; + sprintf(buf, + "Can't send data through the socket. System error: %d", + last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return; + } } -int recv(JNIEnv* e, SOCKET sock, char* buff_ptr, int buff_size) { - int length = ::recv(sock, buff_ptr, buff_size, 0); - if (SOCKET_ERROR == length) { - char buf[255]; - sprintf(buf, "Can't receive data through the socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - return 0; // This doesn't matter cause we have risen an exception - } - return length; +int recv(JNIEnv* e, SOCKET sock, char* buff_ptr, int buff_size) +{ + int length = ::recv(sock, buff_ptr, buff_size, 0); + if (SOCKET_ERROR == length) { + char buf[255]; + sprintf(buf, + "Can't receive data through the socket. System error: %d", + last_socket_error()); + throwNew(e, "java/io/IOException", buf); + return 0; // This doesn't matter cause we have risen an exception + } + return length; } -void abort(JNIEnv* e, SOCKET sock) { - if (SOCKET_ERROR == ::closesocket(sock)) { - char buf[255]; - sprintf(buf, "Can't close the socket. System error: %d", last_socket_error()); - throwNew(e, "java/io/IOException", buf); - } +void abort(JNIEnv* e, SOCKET sock) +{ + if (SOCKET_ERROR == ::closesocket(sock)) { + char buf[255]; + sprintf( + buf, "Can't close the socket. System error: %d", last_socket_error()); + throwNew(e, "java/io/IOException", buf); + } } -void close(JNIEnv* e, SOCKET sock) { - if (SOCKET_ERROR == ::shutdown(sock, SD_BOTH)) { - int errcode = last_socket_error(); - if (errcode != ENOTCONN) { - char buf[255]; - sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); - throwNew(e, "java/io/IOException", buf); - } - } +void close(JNIEnv* e, SOCKET sock) +{ + if (SOCKET_ERROR == ::shutdown(sock, SD_BOTH)) { + int errcode = last_socket_error(); + if (errcode != ENOTCONN) { + char buf[255]; + sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); + throwNew(e, "java/io/IOException", buf); + } + } } -void close_input(JNIEnv* e, SOCKET sock) { - if (SOCKET_ERROR == ::shutdown(sock, SD_RECEIVE)) { - int errcode = last_socket_error(); - if (errcode != ENOTCONN) { - char buf[255]; - sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); - throwNew(e, "java/io/IOException", buf); - } - } -} - -void close_output(JNIEnv* e, SOCKET sock) { - if (SOCKET_ERROR == ::shutdown(sock, SD_SEND)) { - int errcode = last_socket_error(); - if (errcode != ENOTCONN) { - char buf[255]; - sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); - throwNew(e, "java/io/IOException", buf); - } - } +void close_input(JNIEnv* e, SOCKET sock) +{ + if (SOCKET_ERROR == ::shutdown(sock, SD_RECEIVE)) { + int errcode = last_socket_error(); + if (errcode != ENOTCONN) { + char buf[255]; + sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); + throwNew(e, "java/io/IOException", buf); + } + } } +void close_output(JNIEnv* e, SOCKET sock) +{ + if (SOCKET_ERROR == ::shutdown(sock, SD_SEND)) { + int errcode = last_socket_error(); + if (errcode != ENOTCONN) { + char buf[255]; + sprintf(buf, "Can't shutdown the socket. System error: %d", errcode); + throwNew(e, "java/io/IOException", buf); + } + } +} } } } diff --git a/classpath/sockets.h b/classpath/sockets.h index 570c70265f..00c968b14b 100644 --- a/classpath/sockets.h +++ b/classpath/sockets.h @@ -8,7 +8,6 @@ There is NO WARRANTY for this software. See license.txt for details. */ - /* * This file represents a simple cross-platform JNI sockets API * It is used from different classes of the default Avian classpath @@ -22,28 +21,28 @@ #include "jni-util.h" #ifdef PLATFORM_WINDOWS -# include +#include -# define ONLY_ON_WINDOWS(x) x +#define ONLY_ON_WINDOWS(x) x -# ifndef ENOTCONN -# define ENOTCONN WSAENOTCONN -# endif +#ifndef ENOTCONN +#define ENOTCONN WSAENOTCONN +#endif #else -# include -# include -# include -# include +#include +#include +#include +#include -# define ONLY_ON_WINDOWS(x) -# define SOCKET int -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 -# define closesocket(x) close(x) +#define ONLY_ON_WINDOWS(x) +#define SOCKET int +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define closesocket(x) close(x) -# define SD_RECEIVE SHUT_RD -# define SD_SEND SHUT_WR -# define SD_BOTH SHUT_RDWR +#define SD_RECEIVE SHUT_RD +#define SD_SEND SHUT_WR +#define SD_BOTH SHUT_RDWR #endif @@ -69,7 +68,6 @@ void abort(JNIEnv* e, SOCKET sock); void close(JNIEnv* e, SOCKET sock); void close_input(JNIEnv* e, SOCKET sock); void close_output(JNIEnv* e, SOCKET sock); - } } } diff --git a/include/avian/codegen/architecture.h b/include/avian/codegen/architecture.h index 0c82fbc207..91a41551f0 100644 --- a/include/avian/codegen/architecture.h +++ b/include/avian/codegen/architecture.h @@ -30,116 +30,126 @@ class Assembler; class RegisterFile; class OperandMask { -public: + public: uint8_t typeMask; uint64_t registerMask; - OperandMask(uint8_t typeMask, uint64_t registerMask): - typeMask(typeMask), - registerMask(registerMask) - { } + OperandMask(uint8_t typeMask, uint64_t registerMask) + : typeMask(typeMask), registerMask(registerMask) + { + } - OperandMask(): - typeMask(~0), - registerMask(~static_cast(0)) - { } + OperandMask() : typeMask(~0), registerMask(~static_cast(0)) + { + } }; class Architecture { -public: -virtual unsigned floatRegisterSize() = 0; + public: + virtual unsigned floatRegisterSize() = 0; -virtual const RegisterFile* registerFile() = 0; + virtual const RegisterFile* registerFile() = 0; -virtual int scratch() = 0; -virtual int stack() = 0; -virtual int thread() = 0; -virtual int returnLow() = 0; -virtual int returnHigh() = 0; -virtual int virtualCallTarget() = 0; -virtual int virtualCallIndex() = 0; + virtual int scratch() = 0; + virtual int stack() = 0; + virtual int thread() = 0; + virtual int returnLow() = 0; + virtual int returnHigh() = 0; + virtual int virtualCallTarget() = 0; + virtual int virtualCallIndex() = 0; -virtual ir::TargetInfo targetInfo() = 0; + virtual ir::TargetInfo targetInfo() = 0; -virtual bool bigEndian() = 0; + virtual bool bigEndian() = 0; -virtual uintptr_t maximumImmediateJump() = 0; + virtual uintptr_t maximumImmediateJump() = 0; -virtual bool alwaysCondensed(lir::BinaryOperation op) = 0; -virtual bool alwaysCondensed(lir::TernaryOperation op) = 0; + virtual bool alwaysCondensed(lir::BinaryOperation op) = 0; + virtual bool alwaysCondensed(lir::TernaryOperation op) = 0; -virtual bool reserved(int register_) = 0; + virtual bool reserved(int register_) = 0; -virtual unsigned frameFootprint(unsigned footprint) = 0; -virtual unsigned argumentFootprint(unsigned footprint) = 0; -virtual bool argumentAlignment() = 0; -virtual bool argumentRegisterAlignment() = 0; -virtual unsigned argumentRegisterCount() = 0; -virtual int argumentRegister(unsigned index) = 0; + virtual unsigned frameFootprint(unsigned footprint) = 0; + virtual unsigned argumentFootprint(unsigned footprint) = 0; + virtual bool argumentAlignment() = 0; + virtual bool argumentRegisterAlignment() = 0; + virtual unsigned argumentRegisterCount() = 0; + virtual int argumentRegister(unsigned index) = 0; -virtual bool hasLinkRegister() = 0; + virtual bool hasLinkRegister() = 0; -virtual unsigned stackAlignmentInWords() = 0; + virtual unsigned stackAlignmentInWords() = 0; -virtual bool matchCall(void* returnAddress, void* target) = 0; + virtual bool matchCall(void* returnAddress, void* target) = 0; -virtual void updateCall(lir::UnaryOperation op, void* returnAddress, - void* newTarget) = 0; + virtual void updateCall(lir::UnaryOperation op, + void* returnAddress, + void* newTarget) = 0; -virtual void setConstant(void* dst, uint64_t constant) = 0; + virtual void setConstant(void* dst, uint64_t constant) = 0; -virtual unsigned alignFrameSize(unsigned sizeInWords) = 0; + virtual unsigned alignFrameSize(unsigned sizeInWords) = 0; -virtual void nextFrame(void* start, unsigned size, unsigned footprint, - void* link, bool mostRecent, - int targetParameterFootprint, void** ip, - void** stack) = 0; -virtual void* frameIp(void* stack) = 0; -virtual unsigned frameHeaderSize() = 0; -virtual unsigned frameReturnAddressSize() = 0; -virtual unsigned frameFooterSize() = 0; -virtual int returnAddressOffset() = 0; -virtual int framePointerOffset() = 0; + virtual void nextFrame(void* start, + unsigned size, + unsigned footprint, + void* link, + bool mostRecent, + int targetParameterFootprint, + void** ip, + void** stack) = 0; + virtual void* frameIp(void* stack) = 0; + virtual unsigned frameHeaderSize() = 0; + virtual unsigned frameReturnAddressSize() = 0; + virtual unsigned frameFooterSize() = 0; + virtual int returnAddressOffset() = 0; + virtual int framePointerOffset() = 0; -virtual void plan -(lir::UnaryOperation op, - unsigned aSize, OperandMask& aMask, - bool* thunk) = 0; + virtual void plan(lir::UnaryOperation op, + unsigned aSize, + OperandMask& aMask, + bool* thunk) = 0; -virtual void planSource -(lir::BinaryOperation op, - unsigned aSize, OperandMask& aMask, - unsigned bSize, bool* thunk) = 0; - -virtual void planDestination -(lir::BinaryOperation op, - unsigned aSize, const OperandMask& aMask, - unsigned bSize, OperandMask& bMask) = 0; + virtual void planSource(lir::BinaryOperation op, + unsigned aSize, + OperandMask& aMask, + unsigned bSize, + bool* thunk) = 0; -virtual void planMove -(unsigned size, OperandMask& src, - OperandMask& tmp, - const OperandMask& dst) = 0; + virtual void planDestination(lir::BinaryOperation op, + unsigned aSize, + const OperandMask& aMask, + unsigned bSize, + OperandMask& bMask) = 0; -virtual void planSource -(lir::TernaryOperation op, - unsigned aSize, OperandMask& aMask, - unsigned bSize, OperandMask& bMask, - unsigned cSize, bool* thunk) = 0; + virtual void planMove(unsigned size, + OperandMask& src, + OperandMask& tmp, + const OperandMask& dst) = 0; -virtual void planDestination -(lir::TernaryOperation op, - unsigned aSize, const OperandMask& aMask, - unsigned bSize, const OperandMask& bMask, - unsigned cSize, OperandMask& cMask) = 0; + virtual void planSource(lir::TernaryOperation op, + unsigned aSize, + OperandMask& aMask, + unsigned bSize, + OperandMask& bMask, + unsigned cSize, + bool* thunk) = 0; -virtual Assembler* makeAssembler(util::Allocator*, vm::Zone*) = 0; + virtual void planDestination(lir::TernaryOperation op, + unsigned aSize, + const OperandMask& aMask, + unsigned bSize, + const OperandMask& bMask, + unsigned cSize, + OperandMask& cMask) = 0; -virtual void acquire() = 0; -virtual void release() = 0; + virtual Assembler* makeAssembler(util::Allocator*, vm::Zone*) = 0; + + virtual void acquire() = 0; + virtual void release() = 0; }; -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ARCHITECTURE_H +#endif // AVIAN_CODEGEN_ARCHITECTURE_H diff --git a/include/avian/codegen/assembler.h b/include/avian/codegen/assembler.h index 49a7664d6d..66e7ed53d6 100644 --- a/include/avian/codegen/assembler.h +++ b/include/avian/codegen/assembler.h @@ -23,16 +23,17 @@ namespace codegen { class Architecture; class OperandInfo { -public: + public: const unsigned size; const lir::OperandType type; lir::Operand* const operand; - inline OperandInfo(unsigned size, lir::OperandType type, lir::Operand* operand): - size(size), - type(type), - operand(operand) - { } + inline OperandInfo(unsigned size, + lir::OperandType type, + lir::Operand* operand) + : size(size), type(type), operand(operand) + { + } }; #ifdef AVIAN_TAILS @@ -49,11 +50,9 @@ const bool UseFramePointer = false; class Assembler { public: - class Client { public: - virtual int acquireTemporary - (uint32_t mask = ~static_cast(0)) = 0; + virtual int acquireTemporary(uint32_t mask = ~static_cast(0)) = 0; virtual void releaseTemporary(int r) = 0; virtual void save(int r) = 0; @@ -75,20 +74,23 @@ class Assembler { virtual void allocateFrame(unsigned footprint) = 0; virtual void adjustFrame(unsigned difference) = 0; virtual void popFrame(unsigned footprint) = 0; - virtual void popFrameForTailCall(unsigned footprint, int offset, + virtual void popFrameForTailCall(unsigned footprint, + int offset, int returnAddressSurrogate, int framePointerSurrogate) = 0; virtual void popFrameAndPopArgumentsAndReturn(unsigned frameFootprint, - unsigned argumentFootprint) - = 0; + unsigned argumentFootprint) = 0; virtual void popFrameAndUpdateStackAndReturn(unsigned frameFootprint, unsigned stackOffsetFromThread) - = 0; + = 0; virtual void apply(lir::Operation op) = 0; virtual void apply(lir::UnaryOperation op, OperandInfo a) = 0; virtual void apply(lir::BinaryOperation op, OperandInfo a, OperandInfo b) = 0; - virtual void apply(lir::TernaryOperation op, OperandInfo a, OperandInfo b, OperandInfo c) = 0; + virtual void apply(lir::TernaryOperation op, + OperandInfo a, + OperandInfo b, + OperandInfo c) = 0; virtual void setDestination(uint8_t* dst) = 0; @@ -107,7 +109,7 @@ class Assembler { virtual void dispose() = 0; }; -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_H +#endif // AVIAN_CODEGEN_ASSEMBLER_H diff --git a/include/avian/codegen/compiler.h b/include/avian/codegen/compiler.h index 099ae15ca5..6b38e91054 100644 --- a/include/avian/codegen/compiler.h +++ b/include/avian/codegen/compiler.h @@ -30,24 +30,30 @@ class Compiler { class Client { public: virtual intptr_t getThunk(lir::UnaryOperation op, unsigned size) = 0; - virtual intptr_t getThunk(lir::BinaryOperation op, unsigned size, + virtual intptr_t getThunk(lir::BinaryOperation op, + unsigned size, unsigned resultSize) = 0; - virtual intptr_t getThunk(lir::TernaryOperation op, unsigned size, - unsigned resultSize, bool* threadParameter) = 0; + virtual intptr_t getThunk(lir::TernaryOperation op, + unsigned size, + unsigned resultSize, + bool* threadParameter) = 0; }; - static const unsigned Aligned = 1 << 0; + static const unsigned Aligned = 1 << 0; static const unsigned NoReturn = 1 << 1; static const unsigned TailJump = 1 << 2; static const unsigned LongJumpOrCall = 1 << 3; - class State { }; + class State { + }; virtual State* saveState() = 0; virtual void restoreState(State* state) = 0; - virtual void init(unsigned logicalCodeSize, unsigned parameterFootprint, - unsigned localFootprint, unsigned alignedFrameSize) = 0; + virtual void init(unsigned logicalCodeSize, + unsigned parameterFootprint, + unsigned localFootprint, + unsigned alignedFrameSize) = 0; virtual void extendLogicalCode(unsigned more) = 0; @@ -128,8 +134,7 @@ class Compiler { ir::Type type, ir::Value* a, ir::Value* b) = 0; - virtual ir::Value* unaryOp(lir::BinaryOperation op, - ir::Value* a) = 0; + virtual ir::Value* unaryOp(lir::BinaryOperation op, ir::Value* a) = 0; virtual void nullaryOp(lir::Operation op) = 0; virtual ir::Value* f2f(ir::Type resType, ir::Value* a) = 0; @@ -145,11 +150,12 @@ class Compiler { virtual void dispose() = 0; }; -Compiler* -makeCompiler(vm::System* system, Assembler* assembler, vm::Zone* zone, - Compiler::Client* client); +Compiler* makeCompiler(vm::System* system, + Assembler* assembler, + vm::Zone* zone, + Compiler::Client* client); -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_H +#endif // AVIAN_CODEGEN_COMPILER_H diff --git a/include/avian/codegen/lir.h b/include/avian/codegen/lir.h index a8b48ce8c2..251e31aadd 100644 --- a/include/avian/codegen/lir.h +++ b/include/avian/codegen/lir.h @@ -17,71 +17,67 @@ class Promise; namespace lir { enum Operation { - #define LIR_OP_0(x) x, - #define LIR_OP_1(x) - #define LIR_OP_2(x) - #define LIR_OP_3(x) - #include "lir-ops.inc.cpp" - #undef LIR_OP_0 - #undef LIR_OP_1 - #undef LIR_OP_2 - #undef LIR_OP_3 +#define LIR_OP_0(x) x, +#define LIR_OP_1(x) +#define LIR_OP_2(x) +#define LIR_OP_3(x) +#include "lir-ops.inc.cpp" +#undef LIR_OP_0 +#undef LIR_OP_1 +#undef LIR_OP_2 +#undef LIR_OP_3 }; const unsigned OperationCount = Trap + 1; enum UnaryOperation { - #define LIR_OP_0(x) - #define LIR_OP_1(x) x, - #define LIR_OP_2(x) - #define LIR_OP_3(x) - #include "lir-ops.inc.cpp" - #undef LIR_OP_0 - #undef LIR_OP_1 - #undef LIR_OP_2 - #undef LIR_OP_3 - +#define LIR_OP_0(x) +#define LIR_OP_1(x) x, +#define LIR_OP_2(x) +#define LIR_OP_3(x) +#include "lir-ops.inc.cpp" +#undef LIR_OP_0 +#undef LIR_OP_1 +#undef LIR_OP_2 +#undef LIR_OP_3 NoUnaryOperation = -1 }; const unsigned UnaryOperationCount = AlignedJump + 1; enum BinaryOperation { - #define LIR_OP_0(x) - #define LIR_OP_1(x) - #define LIR_OP_2(x) x, - #define LIR_OP_3(x) - #include "lir-ops.inc.cpp" - #undef LIR_OP_0 - #undef LIR_OP_1 - #undef LIR_OP_2 - #undef LIR_OP_3 - +#define LIR_OP_0(x) +#define LIR_OP_1(x) +#define LIR_OP_2(x) x, +#define LIR_OP_3(x) +#include "lir-ops.inc.cpp" +#undef LIR_OP_0 +#undef LIR_OP_1 +#undef LIR_OP_2 +#undef LIR_OP_3 NoBinaryOperation = -1 }; const unsigned BinaryOperationCount = Absolute + 1; enum TernaryOperation { - #define LIR_OP_0(x) - #define LIR_OP_1(x) - #define LIR_OP_2(x) - #define LIR_OP_3(x) x, - #include "lir-ops.inc.cpp" - #undef LIR_OP_0 - #undef LIR_OP_1 - #undef LIR_OP_2 - #undef LIR_OP_3 - +#define LIR_OP_0(x) +#define LIR_OP_1(x) +#define LIR_OP_2(x) +#define LIR_OP_3(x) x, +#include "lir-ops.inc.cpp" +#undef LIR_OP_0 +#undef LIR_OP_1 +#undef LIR_OP_2 +#undef LIR_OP_3 NoTernaryOperation = -1 }; -const unsigned TernaryOperationCount -= JumpIfFloatGreaterOrEqualOrUnordered + 1; +const unsigned TernaryOperationCount = JumpIfFloatGreaterOrEqualOrUnordered + 1; const unsigned NonBranchTernaryOperationCount = FloatMin + 1; -const unsigned BranchOperationCount -= JumpIfFloatGreaterOrEqualOrUnordered - FloatMin; +const unsigned BranchOperationCount = JumpIfFloatGreaterOrEqualOrUnordered + - FloatMin; enum OperandType { ConstantOperand, @@ -90,72 +86,84 @@ enum OperandType { MemoryOperand }; -enum ValueType { - ValueGeneral, - ValueFloat -}; +enum ValueType { ValueGeneral, ValueFloat }; const unsigned OperandTypeCount = MemoryOperand + 1; const int NoRegister = -1; -inline bool isBranch(lir::TernaryOperation op) { +inline bool isBranch(lir::TernaryOperation op) +{ return op > FloatMin; } -inline bool isFloatBranch(lir::TernaryOperation op) { +inline bool isFloatBranch(lir::TernaryOperation op) +{ return op > JumpIfNotEqual; } -inline bool isGeneralBranch(lir::TernaryOperation op) { +inline bool isGeneralBranch(lir::TernaryOperation op) +{ return isBranch(op) && !isFloatBranch(op); } -inline bool isGeneralBinaryOp(lir::TernaryOperation op) { +inline bool isGeneralBinaryOp(lir::TernaryOperation op) +{ return op < FloatAdd; } -inline bool isFloatBinaryOp(lir::TernaryOperation op) { +inline bool isFloatBinaryOp(lir::TernaryOperation op) +{ return op >= FloatAdd && op <= FloatMin; } -inline bool isGeneralUnaryOp(lir::BinaryOperation op) { +inline bool isGeneralUnaryOp(lir::BinaryOperation op) +{ return op == Negate || op == Absolute; } -inline bool isFloatUnaryOp(lir::BinaryOperation op) { +inline bool isFloatUnaryOp(lir::BinaryOperation op) +{ return op == FloatNegate || op == FloatSquareRoot || op == FloatAbsolute; } -class Operand { }; +class Operand { +}; -class Constant: public Operand { +class Constant : public Operand { public: - Constant(Promise* value): value(value) { } + Constant(Promise* value) : value(value) + { + } Promise* value; }; -class Address: public Operand { +class Address : public Operand { public: - Address(Promise* address): address(address) { } + Address(Promise* address) : address(address) + { + } Promise* address; }; -class Register: public Operand { +class Register : public Operand { public: - Register(int low, int high = NoRegister): low(low), high(high) { } + Register(int low, int high = NoRegister) : low(low), high(high) + { + } int low; int high; }; -class Memory: public Operand { +class Memory : public Operand { public: - Memory(int base, int offset, int index = NoRegister, unsigned scale = 1): - base(base), offset(offset), index(index), scale(scale) - { } + Memory(int base, int offset, int index = NoRegister, unsigned scale = 1) + : base(base), offset(offset), index(index), scale(scale) + { + } int base; int offset; @@ -163,8 +171,8 @@ class Memory: public Operand { unsigned scale; }; -} // namespace lir -} // namespace codegen -} // namespace avian +} // namespace lir +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_LIR_H +#endif // AVIAN_CODEGEN_LIR_H diff --git a/include/avian/codegen/promise.h b/include/avian/codegen/promise.h index c1afc6a447..6d683533dc 100644 --- a/include/avian/codegen/promise.h +++ b/include/avian/codegen/promise.h @@ -29,35 +29,45 @@ class Promise { virtual int64_t value() = 0; virtual bool resolved() = 0; - virtual Listener* listen(unsigned) { return 0; } + virtual Listener* listen(unsigned) + { + return 0; + } }; -class ResolvedPromise: public Promise { +class ResolvedPromise : public Promise { public: - ResolvedPromise(int64_t value): value_(value) { } + ResolvedPromise(int64_t value) : value_(value) + { + } - virtual int64_t value() { + virtual int64_t value() + { return value_; } - virtual bool resolved() { + virtual bool resolved() + { return true; } int64_t value_; }; -class ShiftMaskPromise: public Promise { +class ShiftMaskPromise : public Promise { public: - ShiftMaskPromise(Promise* base, unsigned shift, int64_t mask): - base(base), shift(shift), mask(mask) - { } + ShiftMaskPromise(Promise* base, unsigned shift, int64_t mask) + : base(base), shift(shift), mask(mask) + { + } - virtual int64_t value() { + virtual int64_t value() + { return (base->value() >> shift) & mask; } - virtual bool resolved() { + virtual bool resolved() + { return base->resolved(); } @@ -66,17 +76,19 @@ class ShiftMaskPromise: public Promise { int64_t mask; }; -class CombinedPromise: public Promise { +class CombinedPromise : public Promise { public: - CombinedPromise(Promise* low, Promise* high): - low(low), high(high) - { } + CombinedPromise(Promise* low, Promise* high) : low(low), high(high) + { + } - virtual int64_t value() { + virtual int64_t value() + { return low->value() | (high->value() << 32); } - virtual bool resolved() { + virtual bool resolved() + { return low->resolved() and high->resolved(); } @@ -84,17 +96,19 @@ class CombinedPromise: public Promise { Promise* high; }; -class OffsetPromise: public Promise { +class OffsetPromise : public Promise { public: - OffsetPromise(Promise* base, int64_t offset): - base(base), offset(offset) - { } + OffsetPromise(Promise* base, int64_t offset) : base(base), offset(offset) + { + } - virtual int64_t value() { + virtual int64_t value() + { return base->value() + offset; } - virtual bool resolved() { + virtual bool resolved() + { return base->resolved(); } @@ -102,21 +116,25 @@ class OffsetPromise: public Promise { int64_t offset; }; -class ListenPromise: public Promise { +class ListenPromise : public Promise { public: ListenPromise(vm::System* s, util::Allocator* allocator) : s(s), allocator(allocator), listener(0) - { } + { + } - virtual int64_t value() { + virtual int64_t value() + { abort(s); } - virtual bool resolved() { + virtual bool resolved() + { return false; } - virtual Listener* listen(unsigned sizeInBytes) { + virtual Listener* listen(unsigned sizeInBytes) + { Listener* l = static_cast(allocator->allocate(sizeInBytes)); l->next = listener; listener = l; @@ -129,24 +147,28 @@ class ListenPromise: public Promise { Promise* promise; }; -class DelayedPromise: public ListenPromise { +class DelayedPromise : public ListenPromise { public: DelayedPromise(vm::System* s, util::Allocator* allocator, Promise* basis, DelayedPromise* next) : ListenPromise(s, allocator), basis(basis), next(next) - { } + { + } - virtual int64_t value() { + virtual int64_t value() + { abort(s); } - virtual bool resolved() { + virtual bool resolved() + { return false; } - virtual Listener* listen(unsigned sizeInBytes) { + virtual Listener* listen(unsigned sizeInBytes) + { Listener* l = static_cast(allocator->allocate(sizeInBytes)); l->next = listener; listener = l; @@ -157,7 +179,7 @@ class DelayedPromise: public ListenPromise { DelayedPromise* next; }; -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_PROMISE_H \ No newline at end of file +#endif // AVIAN_CODEGEN_PROMISE_H diff --git a/include/avian/codegen/registers.h b/include/avian/codegen/registers.h index 4819d60043..f152084605 100644 --- a/include/avian/codegen/registers.h +++ b/include/avian/codegen/registers.h @@ -17,7 +17,7 @@ namespace avian { namespace codegen { class RegisterMask { -public: + public: uint32_t mask; uint8_t start; uint8_t limit; @@ -25,49 +25,52 @@ public: static unsigned maskStart(uint32_t mask); static unsigned maskLimit(uint32_t mask); - inline RegisterMask(uint32_t mask): - mask(mask), - start(maskStart(mask)), - limit(maskLimit(mask)) - { } + inline RegisterMask(uint32_t mask) + : mask(mask), start(maskStart(mask)), limit(maskLimit(mask)) + { + } }; class RegisterFile { -public: + public: RegisterMask allRegisters; RegisterMask generalRegisters; RegisterMask floatRegisters; - inline RegisterFile(uint32_t generalRegisterMask, uint32_t floatRegisterMask): - allRegisters(generalRegisterMask | floatRegisterMask), - generalRegisters(generalRegisterMask), - floatRegisters(floatRegisterMask) - { } + inline RegisterFile(uint32_t generalRegisterMask, uint32_t floatRegisterMask) + : allRegisters(generalRegisterMask | floatRegisterMask), + generalRegisters(generalRegisterMask), + floatRegisters(floatRegisterMask) + { + } }; class RegisterIterator { -public: + public: int index; const RegisterMask& mask; - inline RegisterIterator(const RegisterMask& mask): - index(mask.start), - mask(mask) {} + inline RegisterIterator(const RegisterMask& mask) + : index(mask.start), mask(mask) + { + } - inline bool hasNext() { + inline bool hasNext() + { return index < mask.limit; } - inline int next() { + inline int next() + { int r = index; do { index++; - } while(index < mask.limit && !(mask.mask & (1 << index))); + } while (index < mask.limit && !(mask.mask & (1 << index))); return r; } }; -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_REGISTERS_H \ No newline at end of file +#endif // AVIAN_CODEGEN_REGISTERS_H diff --git a/include/avian/codegen/runtime.h b/include/avian/codegen/runtime.h index 4f31e65871..c69e8773e7 100644 --- a/include/avian/codegen/runtime.h +++ b/include/avian/codegen/runtime.h @@ -47,8 +47,8 @@ uint64_t intToFloat(int32_t a); uint64_t longToDouble(int64_t a); uint64_t longToFloat(int64_t a); -} // namespace runtime -} // namespace codegen -} // namespace avian +} // namespace runtime +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_RUNTIME_H +#endif // AVIAN_CODEGEN_RUNTIME_H diff --git a/include/avian/codegen/targets.h b/include/avian/codegen/targets.h index 9e8eb8a335..0169c6025f 100644 --- a/include/avian/codegen/targets.h +++ b/include/avian/codegen/targets.h @@ -20,12 +20,13 @@ namespace codegen { class Architecture; -Architecture* makeArchitectureNative(vm::System* system, bool useNativeFeatures); +Architecture* makeArchitectureNative(vm::System* system, + bool useNativeFeatures); Architecture* makeArchitectureX86(vm::System* system, bool useNativeFeatures); Architecture* makeArchitectureArm(vm::System* system, bool useNativeFeatures); -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_TARGETS_H +#endif // AVIAN_CODEGEN_TARGETS_H diff --git a/include/avian/heap/heap.h b/include/avian/heap/heap.h index e17dbadbdd..e4e5ba929f 100644 --- a/include/avian/heap/heap.h +++ b/include/avian/heap/heap.h @@ -24,17 +24,9 @@ const unsigned FixieTenureThreshold = TenureThreshold + 2; class Heap : public avian::util::Allocator { public: - enum CollectionType { - MinorCollection, - MajorCollection - }; + enum CollectionType { MinorCollection, MajorCollection }; - enum Status { - Null, - Reachable, - Unreachable, - Tenured - }; + enum Status { Null, Reachable, Unreachable, Tenured }; class Visitor { public: @@ -62,7 +54,8 @@ class Heap : public avian::util::Allocator { virtual unsigned remaining() = 0; virtual unsigned limit() = 0; virtual bool limitExceeded(int pendingAllocation = 0) = 0; - virtual void collect(CollectionType type, unsigned footprint, + virtual void collect(CollectionType type, + unsigned footprint, int pendingAllocation) = 0; virtual unsigned fixedFootprint(unsigned sizeInWords, bool objectMask) = 0; virtual void* allocateFixed(avian::util::Allocator* allocator, @@ -74,6 +67,13 @@ class Heap : public avian::util::Allocator { virtual void mark(void* p, unsigned offset, unsigned count) = 0; virtual void pad(void* p) = 0; virtual void* follow(void* p) = 0; + + template + T* follow(T* p) + { + return static_cast(follow(static_cast(p))); + } + virtual void postVisit() = 0; virtual Status status(void* p) = 0; virtual CollectionType collectionType() = 0; @@ -83,6 +83,6 @@ class Heap : public avian::util::Allocator { Heap* makeHeap(System* system, unsigned limit); -} // namespace vm +} // namespace vm -#endif//HEAP_H +#endif // HEAP_H diff --git a/include/avian/system/signal.h b/include/avian/system/signal.h index 092491e1bc..60c9a1fb28 100644 --- a/include/avian/system/signal.h +++ b/include/avian/system/signal.h @@ -21,7 +21,8 @@ namespace system { // order to trigger the crash dump logic. NO_RETURN void crash(); -// Registrar for unix-like "signals" (implemented with structured exceptions on windows). +// Registrar for unix-like "signals" (implemented with structured exceptions on +// windows). // TODO: remove dependence on generated code having a well-known "thread" // register. Use a thread-local variable instead. class SignalRegistrar { @@ -40,7 +41,6 @@ class SignalRegistrar { // "Segmentation fault" exceptions (mostly null pointer dereference, but // generally access to any non-mapped memory) SegFault, - DivideByZero, }; @@ -72,11 +72,10 @@ class SignalRegistrar { struct Data; private: - Data* data; }; -} // namespace system -} // namespace avian +} // namespace system +} // namespace avian #endif diff --git a/include/avian/system/system.h b/include/avian/system/system.h index a65efae5f6..ea31823f46 100644 --- a/include/avian/system/system.h +++ b/include/avian/system/system.h @@ -21,12 +21,7 @@ class System : public avian::util::Aborter { public: typedef intptr_t Status; - enum FileType { - TypeUnknown, - TypeDoesNotExist, - TypeFile, - TypeDirectory - }; + enum FileType { TypeUnknown, TypeDoesNotExist, TypeFile, TypeDirectory }; class Thread { public: @@ -100,11 +95,13 @@ class System : public avian::util::Aborter { class MonitorResource { public: - MonitorResource(System::Thread* t, System::Monitor* m): t(t), m(m) { + MonitorResource(System::Thread* t, System::Monitor* m) : t(t), m(m) + { m->acquire(t); } - ~MonitorResource() { + ~MonitorResource() + { m->release(t); } @@ -126,8 +123,8 @@ class System : public avian::util::Aborter { virtual Status make(Monitor**) = 0; virtual Status make(Local**) = 0; - virtual Status visit(Thread* thread, Thread* target, - ThreadVisitor* visitor) = 0; + virtual Status visit(Thread* thread, Thread* target, ThreadVisitor* visitor) + = 0; virtual Status map(Region**, const char* name) = 0; virtual FileType stat(const char* name, unsigned* length) = 0; @@ -145,47 +142,46 @@ class System : public avian::util::Aborter { virtual void dispose() = 0; }; -inline void* -allocate(System* s, unsigned size) +inline void* allocate(System* s, unsigned size) { void* p = s->tryAllocate(size); - if (p == 0) s->abort(); + if (p == 0) + s->abort(); return p; } #define ACQUIRE_MONITOR(t, m) \ - System::MonitorResource MAKE_NAME(monitorResource_) (t, m) + System::MonitorResource MAKE_NAME(monitorResource_)(t, m) -inline avian::util::Aborter* getAborter(System* s) { +inline avian::util::Aborter* getAborter(System* s) +{ return s; } -inline void NO_RETURN -sysAbort(System* s) +inline void NO_RETURN sysAbort(System* s) { abort(s); } // #ifdef NDEBUG -// # define assert(a, b) +// # define assertT(a, b) // # define vm_assert(a, b) // #else // not NDEBUG // inline void -// assert(System* s, bool v) +// assertT(System* s, bool v) // { // expect(s, v); // } -// # define vm_assert(a, b) vm::assert(a, b) +// # define vm_assert(a, b) vm::assertT(a, b) // #endif // not NDEBUG -AVIAN_EXPORT System* -makeSystem(); +AVIAN_EXPORT System* makeSystem(); -} // namespace vm +} // namespace vm -#endif//SYSTEM_H +#endif // SYSTEM_H diff --git a/include/avian/tools/object-writer/tools.h b/include/avian/tools/object-writer/tools.h index 1785a0c5a8..ea7651de5c 100644 --- a/include/avian/tools/object-writer/tools.h +++ b/include/avian/tools/object-writer/tools.h @@ -23,16 +23,17 @@ namespace avian { namespace tools { class OutputStream { -public: + public: virtual void writeChunk(const void* data, size_t size) = 0; virtual void write(uint8_t byte); virtual void writeRepeat(uint8_t byte, size_t size); }; class FileOutputStream : public OutputStream { -private: + private: FILE* file; -public: + + public: FileOutputStream(const char* name); ~FileOutputStream(); @@ -43,20 +44,22 @@ public: }; class SymbolInfo { -public: + public: unsigned addr; util::String name; - inline SymbolInfo(uint64_t addr, const util::String& name): - addr(addr), - name(name) {} + inline SymbolInfo(uint64_t addr, const util::String& name) + : addr(addr), name(name) + { + } - inline SymbolInfo(): - name("") {} + inline SymbolInfo() : name("") + { + } }; class Buffer { -public: + public: size_t capacity; size_t length; uint8_t* data; @@ -69,7 +72,7 @@ public: }; class StringTable : public Buffer { -public: + public: unsigned add(util::String str); }; @@ -103,7 +106,7 @@ class DynamicArray : public util::Slice { }; class PlatformInfo { -public: + public: enum Format { Elf = AVIAN_FORMAT_ELF, Pe = AVIAN_FORMAT_PE, @@ -124,33 +127,31 @@ public: static Format formatFromString(const char* format); static Architecture archFromString(const char* arch); - inline PlatformInfo(Format format, Architecture arch): - format(format), - arch(arch) {} + inline PlatformInfo(Format format, Architecture arch) + : format(format), arch(arch) + { + } - inline bool operator == (const PlatformInfo& other) { + inline bool operator==(const PlatformInfo& other) + { return format == other.format && arch == other.arch; } }; class Platform { -private: + private: Platform* next; static Platform* first; -public: + + public: PlatformInfo info; - inline Platform(PlatformInfo info): - next(first), - info(info) + inline Platform(PlatformInfo info) : next(first), info(info) { first = this; } - enum AccessFlags { - Writable = 1 << 0, - Executable = 1 << 1 - }; + enum AccessFlags { Writable = 1 << 0, Executable = 1 << 1 }; virtual bool writeObject(OutputStream* out, util::Slice symbols, @@ -161,9 +162,8 @@ public: static Platform* getPlatform(PlatformInfo info); }; -} // namespace tools +} // namespace tools -} // namespace avian +} // namespace avian #endif - diff --git a/include/avian/util/abort.h b/include/avian/util/abort.h index 2619492141..e65c9afb8a 100644 --- a/include/avian/util/abort.h +++ b/include/avian/util/abort.h @@ -19,7 +19,7 @@ namespace avian { namespace util { class Aborter { -public: + public: virtual void NO_RETURN abort() = 0; }; @@ -28,29 +28,32 @@ inline Aborter* getAborter(Aborter* a) return a; } -template -inline void NO_RETURN abort(T t) { +template +inline void NO_RETURN abort(T t) +{ getAborter(t)->abort(); ::abort(); } -template -inline void expect(T t, bool v) { - if(UNLIKELY(!v)) { +template +inline void expect(T t, bool v) +{ + if (UNLIKELY(!v)) { abort(t); } } #ifdef NDEBUG -#define assert(t, v) +#define assertT(t, v) #else -template -inline void assert(T t, bool v) { +template +inline void assertT(T t, bool v) +{ expect(t, v); } #endif -} // namespace util -} // namespace avian +} // namespace util +} // namespace avian -#endif // AVIAN_UTIL_ABORT_H +#endif // AVIAN_UTIL_ABORT_H diff --git a/include/avian/util/arg-parser.h b/include/avian/util/arg-parser.h index e0fbf4ac1d..09b986c0eb 100644 --- a/include/avian/util/arg-parser.h +++ b/include/avian/util/arg-parser.h @@ -17,18 +17,21 @@ namespace util { class Arg; class ArgParser { -public: - Arg* first; - Arg** last; - + public: ArgParser(); bool parse(int ac, const char* const* av); void printUsage(const char* exe); + + private: + friend class Arg; + + Arg* first; + Arg** last; }; class Arg { -public: + public: Arg* next; bool required; const char* name; @@ -39,8 +42,7 @@ public: Arg(ArgParser& parser, bool required, const char* name, const char* desc); }; +} // namespace avian +} // namespace util -} // namespace avian -} // namespace util - -#endif // AVIAN_UTIL_ARG_PARSER_H \ No newline at end of file +#endif // AVIAN_UTIL_ARG_PARSER_H diff --git a/include/avian/util/hash.h b/include/avian/util/hash.h new file mode 100644 index 0000000000..60c2831a2c --- /dev/null +++ b/include/avian/util/hash.h @@ -0,0 +1,57 @@ +/* Copyright (c) 2008-2014, Avian Contributors + + Permission to use, copy, modify, and/or distribute this software + for any purpose with or without fee is hereby granted, provided + that the above copyright notice and this permission notice appear + in all copies. + + There is NO WARRANTY for this software. See license.txt for + details. */ + +#ifndef AVIAN_UTIL_HASH_H +#define AVIAN_UTIL_HASH_H + +#include "slice.h" + +namespace avian { +namespace util { + +inline uint32_t hash(const char* s) +{ + uint32_t h = 0; + for (unsigned i = 0; s[i]; ++i) { + h = (h * 31) + s[i]; + } + return h; +} + +inline uint32_t hash(Slice data) +{ + const uint8_t* s = data.begin(); + uint32_t h = 0; + for (size_t i = 0; i < data.count; ++i) { + h = (h * 31) + s[i]; + } + return h; +} + +inline uint32_t hash(Slice data) +{ + return hash(Slice( + reinterpret_cast(data.begin()), data.count)); +} + +inline uint32_t hash(Slice data) +{ + const uint16_t* s = data.begin(); + uint32_t h = 0; + for (size_t i = 0; i < data.count; ++i) { + h = (h * 31) + s[i]; + } + return h; +} + +} // namespace util +} // namespace avian + +#endif // AVIAN_UTIL_HASH_H diff --git a/include/avian/util/list.h b/include/avian/util/list.h index e621d30d77..2e58d97eeb 100644 --- a/include/avian/util/list.h +++ b/include/avian/util/list.h @@ -18,16 +18,17 @@ namespace util { template class List { -public: - List(const T& item, List* next): - item(item), - next(next) {} + public: + List(const T& item, List* next) : item(item), next(next) + { + } - unsigned count() { + unsigned count() + { unsigned count = 0; List* c = this; while (c) { - ++ count; + ++count; c = c->next; } return count; diff --git a/include/avian/util/math.h b/include/avian/util/math.h index bf66dbb922..611686826f 100644 --- a/include/avian/util/math.h +++ b/include/avian/util/math.h @@ -17,40 +17,51 @@ namespace avian { namespace util { -inline unsigned max(unsigned a, unsigned b) { +inline unsigned max(unsigned a, unsigned b) +{ return (a > b ? a : b); } -inline unsigned min(unsigned a, unsigned b) { +inline unsigned min(unsigned a, unsigned b) +{ return (a < b ? a : b); } -inline unsigned avg(unsigned a, unsigned b) { +inline unsigned avg(unsigned a, unsigned b) +{ return (a + b) / 2; } -inline unsigned ceilingDivide(unsigned n, unsigned d) { +inline unsigned ceilingDivide(unsigned n, unsigned d) +{ return (n + d - 1) / d; } -inline bool powerOfTwo(unsigned n) { - for (; n > 2; n >>= 1) if (n & 1) return false; +inline bool powerOfTwo(unsigned n) +{ + for (; n > 2; n >>= 1) + if (n & 1) + return false; return true; } -inline unsigned nextPowerOfTwo(unsigned n) { +inline unsigned nextPowerOfTwo(unsigned n) +{ unsigned r = 1; - while (r < n) r <<= 1; + while (r < n) + r <<= 1; return r; } -inline unsigned log(unsigned n) { +inline unsigned log(unsigned n) +{ unsigned r = 0; - for (unsigned i = 1; i < n; ++r) i <<= 1; + for (unsigned i = 1; i < n; ++r) + i <<= 1; return r; } - -} // namespace util -} // namespace avian -#endif // AVIAN_UTIL_MATH_H +} // namespace util +} // namespace avian + +#endif // AVIAN_UTIL_MATH_H diff --git a/include/avian/util/runtime-array.h b/include/avian/util/runtime-array.h index d30633ae86..bbbe8854c6 100644 --- a/include/avian/util/runtime-array.h +++ b/include/avian/util/runtime-array.h @@ -16,25 +16,26 @@ template class RuntimeArray { public: - RuntimeArray(unsigned size): - body(static_cast(malloc(size * sizeof(T)))) - { } + RuntimeArray(unsigned size) : body(static_cast(malloc(size * sizeof(T)))) + { + } - ~RuntimeArray() { + ~RuntimeArray() + { free(body); } T* body; }; -# define RUNTIME_ARRAY(type, name, size) RuntimeArray name(size); -# define RUNTIME_ARRAY_BODY(name) name.body +#define RUNTIME_ARRAY(type, name, size) RuntimeArray name(size); +#define RUNTIME_ARRAY_BODY(name) name.body -#else // not _MSC_VER +#else // not _MSC_VER -# define RUNTIME_ARRAY(type, name, size) type name##_body[size]; -# define RUNTIME_ARRAY_BODY(name) name##_body +#define RUNTIME_ARRAY(type, name, size) type name##_body[size]; +#define RUNTIME_ARRAY_BODY(name) name##_body #endif -#endif // AVIAN_UTIL_RUNTIME_ARRAY_H +#endif // AVIAN_UTIL_RUNTIME_ARRAY_H diff --git a/include/avian/util/slice.h b/include/avian/util/slice.h index 51b1ad918e..69667b63c4 100644 --- a/include/avian/util/slice.h +++ b/include/avian/util/slice.h @@ -18,6 +18,19 @@ namespace avian { namespace util { +template +struct NonConst; + +template +struct NonConst { + typedef T Type; +}; + +template +struct NonConst { + typedef T Type; +}; + template class Slice { public: @@ -28,7 +41,8 @@ class Slice { { } - inline Slice(const Slice& copy) : items(copy.items), count(copy.count) + inline Slice(const Slice::Type>& copy) + : items(copy.items), count(copy.count) { } @@ -48,6 +62,13 @@ class Slice { return items + count; } + inline Slice subslice(size_t begin, size_t count) + { + ASSERT(begin <= this->count); + ASSERT(begin + count <= this->count); + return Slice(this->begin() + begin, count); + } + static Slice alloc(Allocator* a, size_t count) { return Slice((T*)a->allocate(sizeof(T) * count), count); diff --git a/include/avian/util/stream.h b/include/avian/util/stream.h index 9a347e2d4c..dd9d324518 100644 --- a/include/avian/util/stream.h +++ b/include/avian/util/stream.h @@ -22,19 +22,23 @@ class AbstractStream { virtual void handleError() = 0; }; - AbstractStream(Client* client, unsigned size): - client(client), size(size), position_(0) - { } + AbstractStream(Client* client, unsigned size) + : client(client), size(size), position_(0) + { + } - unsigned position() { + unsigned position() + { return position_; } - void setPosition(unsigned p) { + void setPosition(unsigned p) + { position_ = p; } - void skip(unsigned size) { + void skip(unsigned size) + { if (size > this->size - position_) { client->handleError(); } else { @@ -42,7 +46,8 @@ class AbstractStream { } } - void read(uint8_t* dst, unsigned size) { + void read(uint8_t* dst, unsigned size) + { if (size > this->size - position_) { memset(dst, 0, size); @@ -53,35 +58,41 @@ class AbstractStream { } } - uint8_t read1() { + uint8_t read1() + { uint8_t v; read(&v, 1); return v; } - uint16_t read2() { + uint16_t read2() + { uint16_t a = read1(); uint16_t b = read1(); return (a << 8) | b; } - uint32_t read4() { + uint32_t read4() + { uint32_t a = read2(); uint32_t b = read2(); return (a << 16) | b; } - uint64_t read8() { + uint64_t read8() + { uint64_t a = read4(); uint64_t b = read4(); return (a << 32) | b; } - uint32_t readFloat() { + uint32_t readFloat() + { return read4(); } - uint64_t readDouble() { + uint64_t readDouble() + { return read8(); } @@ -94,20 +105,22 @@ class AbstractStream { unsigned position_; }; -class Stream: public AbstractStream { +class Stream : public AbstractStream { public: - Stream(Client* client, const uint8_t* data, unsigned size): - AbstractStream(client, size), data(data) - { } + Stream(Client* client, const uint8_t* data, unsigned size) + : AbstractStream(client, size), data(data) + { + } private: - virtual void copy(uint8_t* dst, unsigned offset, unsigned size) { + virtual void copy(uint8_t* dst, unsigned offset, unsigned size) + { memcpy(dst, data + offset, size); } const uint8_t* data; }; -} // namespace vm +} // namespace vm -#endif//STREAM_H +#endif // STREAM_H diff --git a/include/avian/util/string.h b/include/avian/util/string.h index aecce3ce9c..704dd9a5b1 100644 --- a/include/avian/util/string.h +++ b/include/avian/util/string.h @@ -17,38 +17,43 @@ namespace avian { namespace util { class String { -public: + public: const char* text; size_t length; - String(const char* text): - text(text), - length(strlen(text)) {} - - inline String(const char* text, size_t length): - text(text), - length(length) {} + String(const char* text) : text(text), length(strlen(text)) + { + } + + inline String(const char* text, size_t length) : text(text), length(length) + { + } }; class Tokenizer { public: + Tokenizer(const char* s, char delimiter) + : s(s), limit(0), delimiter(delimiter) + { + } - Tokenizer(const char* s, char delimiter): - s(s), limit(0), delimiter(delimiter) - { } + Tokenizer(String str, char delimiter) + : s(str.text), limit(str.text + str.length), delimiter(delimiter) + { + } - Tokenizer(String str, char delimiter): - s(str.text), limit(str.text + str.length), delimiter(delimiter) - { } - - bool hasMore() { - while (s != limit and *s == delimiter) ++s; + bool hasMore() + { + while (s != limit and *s == delimiter) + ++s; return s != limit and *s != 0; } - String next() { + String next() + { const char* p = s; - while (s != limit and *s and *s != delimiter) ++s; + while (s != limit and *s and *s != delimiter) + ++s; return String(p, s - p); } @@ -57,7 +62,7 @@ class Tokenizer { char delimiter; }; -} // namespace util -} // namespace avain +} // namespace util +} // namespace avain -#endif//AVIAN_UTIL_STRING_H +#endif // AVIAN_UTIL_STRING_H diff --git a/makefile b/makefile index e0d02c98b2..734c03a2c8 100755 --- a/makefile +++ b/makefile @@ -443,6 +443,7 @@ asm-format = S as = $(cc) ld = $(cc) build-ld = $(build-cc) +build-ld-cpp = $(build-cxx) default-remote-test-host = localhost default-remote-test-port = 22 @@ -1268,7 +1269,8 @@ generator-sources = \ $(src)/tools/type-generator/main.cpp \ $(src)/system/$(build-system).cpp \ $(src)/system/$(build-system)/signal.cpp \ - $(src)/finder.cpp + $(src)/finder.cpp \ + $(src)/util/arg-parser.cpp ifneq ($(lzma),) common-cflags += -I$(lzma) -DAVIAN_USE_LZMA -D_7ZIP_ST @@ -1353,6 +1355,7 @@ ifneq ($(classpath),avian) # them to synthesize a class: classpath-sources := \ $(classpath-src)/avian/Addendum.java \ + $(classpath-src)/avian/Code.java \ $(classpath-src)/avian/AnnotationInvocationHandler.java \ $(classpath-src)/avian/Assembler.java \ $(classpath-src)/avian/Callback.java \ @@ -1573,7 +1576,7 @@ gen-arg = $(shell echo $(1) | sed -e 's:$(build)/type-\(.*\)\.cpp:\1:') $(generated-code): %.cpp: $(src)/types.def $(generator) $(classpath-dep) @echo "generating $(@)" @mkdir -p $(dir $(@)) - $(generator) $(boot-classpath) $(<) $(@) $(call gen-arg,$(@)) + $(generator) -cp $(boot-classpath) -i $(<) -o $(@) -t $(call gen-arg,$(@)) $(classpath-build)/%.class: $(classpath-src)/%.java @echo $(<) @@ -1982,7 +1985,7 @@ endif $(generator): $(generator-objects) $(generator-lzma-objects) @echo "linking $(@)" - $(build-ld) $(^) $(build-lflags) -o $(@) + $(build-ld-cpp) $(^) $(build-lflags) -o $(@) $(openjdk-objects): $(build)/openjdk/%-openjdk.o: $(openjdk-src)/%.c \ $(openjdk-headers-dep) diff --git a/src/android/stubs.cpp b/src/android/stubs.cpp index 5d94b17292..7fe9362a3d 100644 --- a/src/android/stubs.cpp +++ b/src/android/stubs.cpp @@ -11,8 +11,7 @@ struct JniConstants { static void init(_JNIEnv* env); }; -void -JniConstants::init(_JNIEnv*) +void JniConstants::init(_JNIEnv*) { // ignore } diff --git a/src/avian/alloc-vector.h b/src/avian/alloc-vector.h index c7aa0d1ddd..a859864d7c 100644 --- a/src/avian/alloc-vector.h +++ b/src/avian/alloc-vector.h @@ -33,13 +33,16 @@ class Vector { data(0, 0), position(0), minimumCapacity(minimumCapacity) - { } + { + } - ~Vector() { + ~Vector() + { dispose(); } - void dispose() { + void dispose() + { if (data.items and minimumCapacity > 0) { allocator->free(data.items, data.count); data.items = 0; @@ -50,7 +53,7 @@ class Vector { void ensure(size_t space) { if (position + space > data.count) { - assert(a, minimumCapacity > 0); + assertT(a, minimumCapacity > 0); size_t newCapacity = avian::util::max( position + space, avian::util::max(minimumCapacity, data.count * 2)); @@ -64,13 +67,13 @@ class Vector { void get(size_t offset, void* dst, size_t size) { - assert(a, offset + size <= position); + assertT(a, offset + size <= position); memcpy(dst, data.begin() + offset, size); } void set(size_t offset, const void* src, size_t size) { - assert(a, offset + size <= position); + assertT(a, offset + size <= position); memcpy(data.begin() + offset, src, size); } @@ -95,57 +98,67 @@ class Vector { return r; } - void append(uint8_t v) { + void append(uint8_t v) + { append(&v, 1); } - void append2(uint16_t v) { + void append2(uint16_t v) + { append(&v, 2); } - void append4(uint32_t v) { + void append4(uint32_t v) + { append(&v, 4); } - void appendTargetAddress(target_uintptr_t v) { + void appendTargetAddress(target_uintptr_t v) + { append(&v, TargetBytesPerWord); } - void appendAddress(uintptr_t v) { + void appendAddress(uintptr_t v) + { append(&v, BytesPerWord); } - void appendAddress(void* v) { + void appendAddress(void* v) + { append(&v, BytesPerWord); } void set2(size_t offset, uint16_t v) { - assert(a, offset <= position - 2); + assertT(a, offset <= position - 2); memcpy(data.begin() + offset, &v, 2); } size_t get(size_t offset) { - uint8_t v; get(offset, &v, 1); + uint8_t v; + get(offset, &v, 1); return v; } size_t get2(size_t offset) { - uint16_t v; get(offset, &v, 2); + uint16_t v; + get(offset, &v, 2); return v; } size_t get4(size_t offset) { - uint32_t v; get(offset, &v, 4); + uint32_t v; + get(offset, &v, 4); return v; } uintptr_t getAddress(size_t offset) { - uintptr_t v; get(offset, &v, BytesPerWord); + uintptr_t v; + get(offset, &v, BytesPerWord); return v; } @@ -157,7 +170,7 @@ class Vector { template T* peek(size_t offset) { - assert(a, offset + sizeof(T) <= position); + assertT(a, offset + sizeof(T) <= position); return reinterpret_cast(data.begin() + offset); } @@ -168,6 +181,6 @@ class Vector { size_t minimumCapacity; }; -} // namespace vm +} // namespace vm -#endif//VECTOR_H +#endif // VECTOR_H diff --git a/src/avian/arch.h b/src/avian/arch.h index 0cb12f9142..cf717b0369 100644 --- a/src/avian/arch.h +++ b/src/avian/arch.h @@ -12,39 +12,41 @@ #define ARCH_H #ifdef _MSC_VER -# include "windows.h" -# pragma push_macro("assert") -# include "intrin.h" -# pragma pop_macro("assert") -# undef interface +#include "windows.h" +#pragma push_macro("assert") +#include "intrin.h" +#pragma pop_macro("assert") +#undef interface #endif #include "avian/common.h" -extern "C" void NO_RETURN -vmJump(void* address, void* frame, void* stack, void* thread, - uintptr_t returnLow, uintptr_t returnHigh); +extern "C" void NO_RETURN vmJump(void* address, + void* frame, + void* stack, + void* thread, + uintptr_t returnLow, + uintptr_t returnHigh); namespace vm { -inline void -compileTimeMemoryBarrier() +inline void compileTimeMemoryBarrier() { #ifdef _MSC_VER _ReadWriteBarrier(); #else - __asm__ __volatile__("": : :"memory"); + __asm__ __volatile__("" : : : "memory"); #endif } -} // namespace vm +} // namespace vm #if (defined ARCH_x86_32) || (defined ARCH_x86_64) -# include "x86.h" +#include "x86.h" #elif defined ARCH_arm -# include "arm.h" +#include "arm.h" #else -# error unsupported architecture +#error unsupported architecture #endif -#endif//ARCH_H +#endif // ARCH_H diff --git a/src/avian/arm.h b/src/avian/arm.h index 37edcb7fb7..f3b86fd256 100644 --- a/src/avian/arm.h +++ b/src/avian/arm.h @@ -16,61 +16,62 @@ #include #ifdef __APPLE__ -# include "libkern/OSAtomic.h" -# include "libkern/OSCacheControl.h" -# include "mach/mach_types.h" -# include "mach/thread_act.h" -# include "mach/thread_status.h" +#include "libkern/OSAtomic.h" +#include "libkern/OSCacheControl.h" +#include "mach/mach_types.h" +#include "mach/thread_act.h" +#include "mach/thread_status.h" -# define THREAD_STATE ARM_THREAD_STATE -# define THREAD_STATE_TYPE arm_thread_state_t -# define THREAD_STATE_COUNT ARM_THREAD_STATE_COUNT +#define THREAD_STATE ARM_THREAD_STATE +#define THREAD_STATE_TYPE arm_thread_state_t +#define THREAD_STATE_COUNT ARM_THREAD_STATE_COUNT -# if __DARWIN_UNIX03 && defined(_STRUCT_ARM_EXCEPTION_STATE) -# define FIELD(x) __##x -# else -# define FIELD(x) x -# endif - -# define THREAD_STATE_IP(state) ((state).FIELD(pc)) -# define THREAD_STATE_STACK(state) ((state).FIELD(sp)) -# define THREAD_STATE_THREAD(state) ((state).FIELD(r[8])) -# define THREAD_STATE_LINK(state) ((state).FIELD(lr)) - -# define IP_REGISTER(context) \ - THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) -# define STACK_REGISTER(context) \ - THREAD_STATE_STACK(context->uc_mcontext->FIELD(ss)) -# define THREAD_REGISTER(context) \ - THREAD_STATE_THREAD(context->uc_mcontext->FIELD(ss)) -# define LINK_REGISTER(context) \ - THREAD_STATE_LINK(context->uc_mcontext->FIELD(ss)) -#elif (defined __QNX__) -# include "arm/smpxchg.h" -# include "sys/mman.h" - -# define IP_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_PC]) -# define STACK_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_SP]) -# define THREAD_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_IP]) -# define LINK_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_LR]) +#if __DARWIN_UNIX03 && defined(_STRUCT_ARM_EXCEPTION_STATE) +#define FIELD(x) __##x #else -# define IP_REGISTER(context) (context->uc_mcontext.arm_pc) -# define STACK_REGISTER(context) (context->uc_mcontext.arm_sp) -# define THREAD_REGISTER(context) (context->uc_mcontext.arm_ip) -# define LINK_REGISTER(context) (context->uc_mcontext.arm_lr) +#define FIELD(x) x +#endif + +#define THREAD_STATE_IP(state) ((state).FIELD(pc)) +#define THREAD_STATE_STACK(state) ((state).FIELD(sp)) +#define THREAD_STATE_THREAD(state) ((state).FIELD(r[8])) +#define THREAD_STATE_LINK(state) ((state).FIELD(lr)) + +#define IP_REGISTER(context) THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) +#define STACK_REGISTER(context) \ + THREAD_STATE_STACK(context->uc_mcontext->FIELD(ss)) +#define THREAD_REGISTER(context) \ + THREAD_STATE_THREAD(context->uc_mcontext->FIELD(ss)) +#define LINK_REGISTER(context) \ + THREAD_STATE_LINK(context->uc_mcontext->FIELD(ss)) +#elif(defined __QNX__) +#include "arm/smpxchg.h" +#include "sys/mman.h" + +#define IP_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_PC]) +#define STACK_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_SP]) +#define THREAD_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_IP]) +#define LINK_REGISTER(context) (context->uc_mcontext.cpu.gpr[ARM_REG_LR]) +#else +#define IP_REGISTER(context) (context->uc_mcontext.arm_pc) +#define STACK_REGISTER(context) (context->uc_mcontext.arm_sp) +#define THREAD_REGISTER(context) (context->uc_mcontext.arm_ip) +#define LINK_REGISTER(context) (context->uc_mcontext.arm_lr) #endif #define VA_LIST(x) (&(x)) -extern "C" uint64_t -vmNativeCall(void* function, unsigned stackTotal, void* memoryTable, - unsigned memoryCount, void* gprTable, void* vfpTable, - unsigned returnType); +extern "C" uint64_t vmNativeCall(void* function, + unsigned stackTotal, + void* memoryTable, + unsigned memoryCount, + void* gprTable, + void* vfpTable, + unsigned returnType); namespace vm { -inline void -trap() +inline void trap() { #ifdef _MSC_VER __debugbreak(); @@ -86,23 +87,21 @@ trap() // performant choice. #ifndef _MSC_VER -inline void -memoryBarrier() +inline void memoryBarrier() { #ifdef __APPLE__ OSMemoryBarrier(); -#elif (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) +#elif(__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) return __sync_synchronize(); -#elif (! defined AVIAN_ASSUME_ARMV6) - __asm__ __volatile__ ("dmb" : : : "memory"); +#elif(!defined AVIAN_ASSUME_ARMV6) + __asm__ __volatile__("dmb" : : : "memory"); #else - __asm__ __volatile__ ("" : : : "memory"); + __asm__ __volatile__("" : : : "memory"); #endif } #endif -inline void -storeStoreMemoryBarrier() +inline void storeStoreMemoryBarrier() { #ifdef _MSC_VER _ReadWriteBarrier(); @@ -111,8 +110,7 @@ storeStoreMemoryBarrier() #endif } -inline void -storeLoadMemoryBarrier() +inline void storeLoadMemoryBarrier() { #ifdef _MSC_VER MemoryBarrier(); @@ -121,8 +119,7 @@ storeLoadMemoryBarrier() #endif } -inline void -loadMemoryBarrier() +inline void loadMemoryBarrier() { #ifdef _MSC_VER _ReadWriteBarrier(); @@ -135,52 +132,54 @@ loadMemoryBarrier() #if defined(__ANDROID__) // http://code.google.com/p/android/issues/detail?id=1803 -extern "C" void __clear_cache (void *beg __attribute__((__unused__)), void *end __attribute__((__unused__))); +extern "C" void __clear_cache(void* beg __attribute__((__unused__)), + void* end __attribute__((__unused__))); #endif -inline void -syncInstructionCache(const void* start, unsigned size) +inline void syncInstructionCache(const void* start, unsigned size) { #ifdef __APPLE__ sys_icache_invalidate(const_cast(start), size); -#elif (defined __QNX__) +#elif(defined __QNX__) msync(const_cast(start), size, MS_INVALIDATE_ICACHE); #else - __clear_cache - (const_cast(start), - const_cast(static_cast(start) + size)); + __clear_cache( + const_cast(start), + const_cast(static_cast(start) + size)); #endif } -#endif // AVIAN_AOT_ONLY +#endif // AVIAN_AOT_ONLY #ifndef __APPLE__ -typedef int (__kernel_cmpxchg_t)(int oldval, int newval, int *ptr); -# define __kernel_cmpxchg (*(__kernel_cmpxchg_t *)0xffff0fc0) +typedef int(__kernel_cmpxchg_t)(int oldval, int newval, int* ptr); +#define __kernel_cmpxchg (*(__kernel_cmpxchg_t*)0xffff0fc0) #endif -inline bool -atomicCompareAndSwap32(uint32_t* p, uint32_t old, uint32_t new_) +inline bool atomicCompareAndSwap32(uint32_t* p, uint32_t old, uint32_t new_) { #ifdef __APPLE__ - return OSAtomicCompareAndSwap32Barrier(old, new_, reinterpret_cast(p)); -#elif (defined __QNX__) + return OSAtomicCompareAndSwap32Barrier( + old, new_, reinterpret_cast(p)); +#elif(defined __QNX__) return old == _smp_cmpxchg(p, old, new_); #else - int r = __kernel_cmpxchg(static_cast(old), static_cast(new_), reinterpret_cast(p)); + int r = __kernel_cmpxchg( + static_cast(old), static_cast(new_), reinterpret_cast(p)); return (!r ? true : false); #endif } -inline bool -atomicCompareAndSwap(uintptr_t* p, uintptr_t old, uintptr_t new_) +inline bool atomicCompareAndSwap(uintptr_t* p, uintptr_t old, uintptr_t new_) { return atomicCompareAndSwap32(reinterpret_cast(p), old, new_); } -inline uint64_t -dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, - unsigned argumentCount, unsigned argumentsSize UNUSED, - unsigned returnType) +inline uint64_t dynamicCall(void* function, + uintptr_t* arguments, + uint8_t* argumentTypes, + unsigned argumentCount, + unsigned argumentsSize UNUSED, + unsigned returnType) { #ifdef __APPLE__ const unsigned Alignment = 1; @@ -197,34 +196,37 @@ dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, unsigned vfpIndex = 0; unsigned vfpBackfillIndex UNUSED = 0; - RUNTIME_ARRAY(uintptr_t, stack, (argumentCount * 8) / BytesPerWord); // is > argumentSize to account for padding + RUNTIME_ARRAY(uintptr_t, + stack, + (argumentCount * 8) + / BytesPerWord); // is > argumentSize to account for padding unsigned stackIndex = 0; unsigned ai = 0; - for (unsigned ati = 0; ati < argumentCount; ++ ati) { + for (unsigned ati = 0; ati < argumentCount; ++ati) { switch (argumentTypes[ati]) { case DOUBLE_TYPE: #if defined(__ARM_PCS_VFP) - { - if (vfpIndex + Alignment <= VfpCount) { - if (vfpIndex % Alignment) { - vfpBackfillIndex = vfpIndex; - ++ vfpIndex; - } - - memcpy(vfpTable + vfpIndex, arguments + ai, 8); - vfpIndex += 8 / BytesPerWord; - } else { - vfpIndex = VfpCount; - if (stackIndex % Alignment) { - ++ stackIndex; - } - - memcpy(RUNTIME_ARRAY_BODY(stack) + stackIndex, arguments + ai, 8); - stackIndex += 8 / BytesPerWord; + { + if (vfpIndex + Alignment <= VfpCount) { + if (vfpIndex % Alignment) { + vfpBackfillIndex = vfpIndex; + ++vfpIndex; } - ai += 8 / BytesPerWord; - } break; + + memcpy(vfpTable + vfpIndex, arguments + ai, 8); + vfpIndex += 8 / BytesPerWord; + } else { + vfpIndex = VfpCount; + if (stackIndex % Alignment) { + ++stackIndex; + } + + memcpy(RUNTIME_ARRAY_BODY(stack) + stackIndex, arguments + ai, 8); + stackIndex += 8 / BytesPerWord; + } + ai += 8 / BytesPerWord; + } break; case FLOAT_TYPE: if (vfpBackfillIndex) { @@ -235,26 +237,24 @@ dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, } else { RUNTIME_ARRAY_BODY(stack)[stackIndex++] = arguments[ai]; } - ++ ai; + ++ai; break; #endif case INT64_TYPE: { - if (gprIndex + Alignment <= GprCount) { // pass argument in register(s) - if (Alignment == 1 - and BytesPerWord < 8 - and gprIndex + Alignment == GprCount) - { + if (gprIndex + Alignment <= GprCount) { // pass argument in register(s) + if (Alignment == 1 and BytesPerWord < 8 + and gprIndex + Alignment == GprCount) { gprTable[gprIndex++] = arguments[ai]; RUNTIME_ARRAY_BODY(stack)[stackIndex++] = arguments[ai + 1]; } else { if (gprIndex % Alignment) { ++gprIndex; } - + memcpy(gprTable + gprIndex, arguments + ai, 8); gprIndex += 8 / BytesPerWord; } - } else { // pass argument on stack + } else { // pass argument on stack gprIndex = GprCount; if (stackIndex % Alignment) { ++stackIndex; @@ -272,27 +272,30 @@ dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, } else { RUNTIME_ARRAY_BODY(stack)[stackIndex++] = arguments[ai]; } - ++ ai; + ++ai; } break; } } - if (gprIndex < GprCount) { // pad since assembly loads all GPRs - memset(gprTable + gprIndex, 0, (GprCount-gprIndex)*4); + if (gprIndex < GprCount) { // pad since assembly loads all GPRs + memset(gprTable + gprIndex, 0, (GprCount - gprIndex) * 4); gprIndex = GprCount; } if (vfpIndex < VfpCount) { - memset(vfpTable + vfpIndex, 0, (VfpCount-vfpIndex)*4); + memset(vfpTable + vfpIndex, 0, (VfpCount - vfpIndex) * 4); vfpIndex = VfpCount; } - unsigned stackSize = stackIndex*BytesPerWord + ((stackIndex & 1) << 2); - return vmNativeCall - (function, stackSize, RUNTIME_ARRAY_BODY(stack), stackIndex * BytesPerWord, - (gprIndex ? gprTable : 0), - (vfpIndex ? vfpTable : 0), returnType); + unsigned stackSize = stackIndex * BytesPerWord + ((stackIndex & 1) << 2); + return vmNativeCall(function, + stackSize, + RUNTIME_ARRAY_BODY(stack), + stackIndex * BytesPerWord, + (gprIndex ? gprTable : 0), + (vfpIndex ? vfpTable : 0), + returnType); } -} // namespace vm +} // namespace vm -#endif // ARM_H +#endif // ARM_H diff --git a/src/avian/bootimage.h b/src/avian/bootimage.h index e5b3b661dd..51796918d9 100644 --- a/src/avian/bootimage.h +++ b/src/avian/bootimage.h @@ -24,13 +24,14 @@ class BootImage { public: class Thunk { public: - Thunk(): - start(0), frameSavedOffset(0), length(0) - { } + Thunk() : start(0), frameSavedOffset(0), length(0) + { + } - Thunk(uint32_t start, uint32_t frameSavedOffset, uint32_t length): - start(start), frameSavedOffset(frameSavedOffset), length(length) - { } + Thunk(uint32_t start, uint32_t frameSavedOffset, uint32_t length) + : start(start), frameSavedOffset(frameSavedOffset), length(length) + { + } uint32_t start; uint32_t frameSavedOffset; @@ -53,9 +54,11 @@ class BootImage { ThunkCollection thunks; } PACKED; +class GcField; + class OffsetResolver { public: - virtual unsigned fieldOffset(Thread*, object) = 0; + virtual unsigned fieldOffset(Thread*, GcField*) = 0; }; #define NAME(x) Target##x @@ -70,6 +73,6 @@ class OffsetResolver { #undef LABEL #undef NAME -} // namespace vm +} // namespace vm -#endif//BOOTIMAGE_H +#endif // BOOTIMAGE_H diff --git a/src/avian/classpath-common.h b/src/avian/classpath-common.h index 12de97659b..9f625cbd3a 100644 --- a/src/avian/classpath-common.h +++ b/src/avian/classpath-common.h @@ -18,31 +18,28 @@ using namespace avian::util; namespace vm { -object -getTrace(Thread* t, unsigned skipCount) +object getTrace(Thread* t, unsigned skipCount) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t, int skipCount): - t(t), trace(0), skipCount(skipCount) - { } + Visitor(Thread* t, int skipCount) : t(t), trace(0), skipCount(skipCount) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { if (skipCount == 0) { - object method = walker->method(); - if (isAssignableFrom - (t, type(t, Machine::ThrowableType), methodClass(t, method)) + GcMethod* method = walker->method(); + if (isAssignableFrom(t, type(t, GcThrowable::Type), method->class_()) and vm::strcmp(reinterpret_cast(""), - &byteArrayBody(t, methodName(t, method), 0)) - == 0) - { + method->name()->body().begin()) == 0) { return true; } else { trace = makeTrace(t, walker); return false; } } else { - -- skipCount; + --skipCount; return true; } } @@ -54,38 +51,37 @@ getTrace(Thread* t, unsigned skipCount) t->m->processor->walkStack(t, &v); - if (v.trace == 0) v.trace = makeObjectArray(t, 0); + if (v.trace == 0) + v.trace = makeObjectArray(t, 0); return v.trace; } -bool -compatibleArrayTypes(Thread* t, object a, object b) +bool compatibleArrayTypes(Thread* t UNUSED, GcClass* a, GcClass* b) { - return classArrayElementSize(t, a) - and classArrayElementSize(t, b) - and (a == b - or (not ((classVmFlags(t, a) & PrimitiveFlag) - or (classVmFlags(t, b) & PrimitiveFlag)))); + return a->arrayElementSize() and b->arrayElementSize() + and (a == b or (not((a->vmFlags() & PrimitiveFlag) + or (b->vmFlags() & PrimitiveFlag)))); } -void -arrayCopy(Thread* t, object src, int32_t srcOffset, object dst, - int32_t dstOffset, int32_t length) +void arrayCopy(Thread* t, + object src, + int32_t srcOffset, + object dst, + int32_t dstOffset, + int32_t length) { if (LIKELY(src and dst)) { - if (LIKELY(compatibleArrayTypes - (t, objectClass(t, src), objectClass(t, dst)))) - { - unsigned elementSize = classArrayElementSize(t, objectClass(t, src)); + if (LIKELY(compatibleArrayTypes( + t, objectClass(t, src), objectClass(t, dst)))) { + unsigned elementSize = objectClass(t, src)->arrayElementSize(); if (LIKELY(elementSize)) { intptr_t sl = fieldAtOffset(src, BytesPerWord); intptr_t dl = fieldAtOffset(dst, BytesPerWord); if (LIKELY(length > 0)) { - if (LIKELY(srcOffset >= 0 and srcOffset + length <= sl and - dstOffset >= 0 and dstOffset + length <= dl)) - { + if (LIKELY(srcOffset >= 0 and srcOffset + length <= sl + and dstOffset >= 0 and dstOffset + length <= dl)) { uint8_t* sbody = &fieldAtOffset(src, ArrayBody); uint8_t* dbody = &fieldAtOffset(dst, ArrayBody); if (src == dst) { @@ -98,13 +94,13 @@ arrayCopy(Thread* t, object src, int32_t srcOffset, object dst, length * elementSize); } - if (classObjectMask(t, objectClass(t, dst))) { + if (objectClass(t, dst)->objectMask()) { mark(t, dst, ArrayBody + (dstOffset * BytesPerWord), length); } return; } else { - throwNew(t, Machine::IndexOutOfBoundsExceptionType); + throwNew(t, GcIndexOutOfBoundsException::Type); } } else { return; @@ -112,15 +108,14 @@ arrayCopy(Thread* t, object src, int32_t srcOffset, object dst, } } } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); return; } - throwNew(t, Machine::ArrayStoreExceptionType); + throwNew(t, GcArrayStoreException::Type); } -void -runOnLoadIfFound(Thread* t, System::Library* library) +void runOnLoadIfFound(Thread* t, System::Library* library) { void* p = library->resolve("JNI_OnLoad"); @@ -134,14 +129,13 @@ runOnLoadIfFound(Thread* t, System::Library* library) #endif if (p) { - jint (JNICALL * JNI_OnLoad)(Machine*, void*); + jint(JNICALL * JNI_OnLoad)(Machine*, void*); memcpy(&JNI_OnLoad, &p, sizeof(void*)); JNI_OnLoad(t->m, 0); } } -System::Library* -loadLibrary(Thread* t, const char* name) +System::Library* loadLibrary(Thread* t, const char* name) { ACQUIRE(t, t->m->classLock); @@ -163,9 +157,12 @@ loadLibrary(Thread* t, const char* name) } } -System::Library* -loadLibrary(Thread* t, const char* path, const char* name, bool mapName, - bool runOnLoad, bool throw_ = true) +System::Library* loadLibrary(Thread* t, + const char* path, + const char* name, + bool mapName, + bool runOnLoad, + bool throw_ = true) { ACQUIRE(t, t->m->classLock); @@ -177,8 +174,7 @@ loadLibrary(Thread* t, const char* path, const char* name, bool mapName, const char* s = builtins; while (*s) { if (::strncmp(s, name, nameLength) == 0 - and (s[nameLength] == ',' or s[nameLength] == 0)) - { + and (s[nameLength] == ',' or s[nameLength] == 0)) { // library is built in to this executable if (runOnLoad and not t->m->triedBuiltinOnLoad) { t->m->triedBuiltinOnLoad = true; @@ -188,8 +184,10 @@ loadLibrary(Thread* t, const char* path, const char* name, bool mapName, } return t->m->libraries; } else { - while (*s and *s != ',') ++ s; - if (*s) ++ s; + while (*s and *s != ',') + ++s; + if (*s) + ++s; } } } @@ -198,8 +196,7 @@ loadLibrary(Thread* t, const char* path, const char* name, bool mapName, const char* suffix = t->m->system->librarySuffix(); unsigned mappedNameLength = nameLength + strlen(prefix) + strlen(suffix); - mappedName = static_cast - (t->m->heap->allocate(mappedNameLength + 1)); + mappedName = static_cast(t->m->heap->allocate(mappedNameLength + 1)); snprintf(mappedName, mappedNameLength + 1, "%s%s%s", prefix, name, suffix); @@ -209,25 +206,28 @@ loadLibrary(Thread* t, const char* path, const char* name, bool mapName, mappedName = 0; } - THREAD_RESOURCE2 - (t, char*, mappedName, unsigned, nameLength, if (mappedName) { - t->m->heap->free(mappedName, nameLength + 1); - }); + THREAD_RESOURCE2(t, char*, mappedName, unsigned, nameLength, if (mappedName) { + t->m->heap->free(mappedName, nameLength + 1); + }); System::Library* lib = 0; for (Tokenizer tokenizer(path, t->m->system->pathSeparator()); - tokenizer.hasMore();) - { + tokenizer.hasMore();) { String token(tokenizer.next()); unsigned fullNameLength = token.length + 1 + nameLength; THREAD_RUNTIME_ARRAY(t, char, fullName, fullNameLength + 1); - snprintf(RUNTIME_ARRAY_BODY(fullName), fullNameLength + 1, - "%.*s/%s", token.length, token.text, name); + snprintf(RUNTIME_ARRAY_BODY(fullName), + fullNameLength + 1, + "%.*s/%s", + token.length, + token.text, + name); lib = loadLibrary(t, RUNTIME_ARRAY_BODY(fullName)); - if (lib) break; + if (lib) + break; } if (lib == 0) { @@ -239,109 +239,121 @@ loadLibrary(Thread* t, const char* path, const char* name, bool mapName, runOnLoadIfFound(t, lib); } } else if (throw_) { - throwNew(t, Machine::UnsatisfiedLinkErrorType, - "library not found in %s: %s", path, name); + throwNew(t, + GcUnsatisfiedLinkError::Type, + "library not found in %s: %s", + path, + name); } return lib; } -object -clone(Thread* t, object o) +object clone(Thread* t, object o) { PROTECT(t, o); - object class_ = objectClass(t, o); + GcClass* class_ = objectClass(t, o); unsigned size = baseSize(t, o, class_) * BytesPerWord; object clone; - if (classArrayElementSize(t, class_)) { - clone = static_cast(allocate(t, size, classObjectMask(t, class_))); + if (class_->arrayElementSize()) { + clone = static_cast(allocate(t, size, class_->objectMask())); memcpy(clone, o, size); // clear any object header flags: setObjectClass(t, o, objectClass(t, o)); - } else if (instanceOf(t, type(t, Machine::CloneableType), o)) { + } else if (instanceOf(t, type(t, GcCloneable::Type), o)) { clone = make(t, class_); memcpy(reinterpret_cast(clone) + 1, reinterpret_cast(o) + 1, size - BytesPerWord); } else { - object classNameSlash = className(t, objectClass(t, o)); - THREAD_RUNTIME_ARRAY(t, char, classNameDot, byteArrayLength(t, classNameSlash)); - replace('/', '.', RUNTIME_ARRAY_BODY(classNameDot), - reinterpret_cast(&byteArrayBody(t, classNameSlash, 0))); - throwNew(t, Machine::CloneNotSupportedExceptionType, "%s", + GcByteArray* classNameSlash = objectClass(t, o)->name(); + THREAD_RUNTIME_ARRAY(t, char, classNameDot, classNameSlash->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(classNameDot), + reinterpret_cast(classNameSlash->body().begin())); + throwNew(t, + GcCloneNotSupportedException::Type, + "%s", RUNTIME_ARRAY_BODY(classNameDot)); } return clone; } -object -makeStackTraceElement(Thread* t, object e) +GcStackTraceElement* makeStackTraceElement(Thread* t, GcTraceElement* e) { PROTECT(t, e); - object class_ = className(t, methodClass(t, traceElementMethod(t, e))); - PROTECT(t, class_); - - THREAD_RUNTIME_ARRAY(t, char, s, byteArrayLength(t, class_)); - replace('/', '.', RUNTIME_ARRAY_BODY(s), - reinterpret_cast(&byteArrayBody(t, class_, 0))); - class_ = makeString(t, "%s", RUNTIME_ARRAY_BODY(s)); - - object method = methodName(t, traceElementMethod(t, e)); + GcMethod* method = cast(t, e->method()); PROTECT(t, method); - method = t->m->classpath->makeString - (t, method, 0, byteArrayLength(t, method) - 1); + GcByteArray* class_name = method->class_()->name(); + PROTECT(t, class_name); - unsigned line = t->m->processor->lineNumber - (t, traceElementMethod(t, e), traceElementIp(t, e)); + THREAD_RUNTIME_ARRAY(t, char, s, class_name->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(s), + reinterpret_cast(class_name->body().begin())); + GcString* class_name_string = makeString(t, "%s", RUNTIME_ARRAY_BODY(s)); + PROTECT(t, class_name_string); - object file = classSourceFile(t, methodClass(t, traceElementMethod(t, e))); - file = file ? t->m->classpath->makeString - (t, file, 0, byteArrayLength(t, file) - 1) : 0; + GcByteArray* method_name = method->name(); + PROTECT(t, method_name); - return makeStackTraceElement(t, class_, method, file, line); + GcString* method_name_string = t->m->classpath->makeString( + t, method_name, 0, method_name->length() - 1); + PROTECT(t, method_name_string); + + unsigned line = t->m->processor->lineNumber(t, method, e->ip()); + + GcByteArray* file = method->class_()->sourceFile(); + GcString* file_string + = file ? t->m->classpath->makeString(t, file, 0, file->length() - 1) : 0; + + return makeStackTraceElement( + t, class_name_string, method_name_string, file_string, line); } -object -translateInvokeResult(Thread* t, unsigned returnCode, object o) +GcObject* translateInvokeResult(Thread* t, unsigned returnCode, object o) { switch (returnCode) { case ByteField: - return makeByte(t, intValue(t, o)); + return makeByte(t, cast(t, o)->value()); case BooleanField: - return makeBoolean(t, intValue(t, o) != 0); + return makeBoolean(t, cast(t, o)->value() != 0); case CharField: - return makeChar(t, intValue(t, o)); + return makeChar(t, cast(t, o)->value()); case ShortField: - return makeShort(t, intValue(t, o)); + return makeShort(t, cast(t, o)->value()); case FloatField: - return makeFloat(t, intValue(t, o)); + return makeFloat(t, cast(t, o)->value()); case IntField: case LongField: case ObjectField: case VoidField: - return o; + return reinterpret_cast(o); case DoubleField: - return makeDouble(t, longValue(t, o)); + return makeDouble(t, cast(t, o)->value()); default: abort(t); } } -object -resolveClassBySpec(Thread* t, object loader, const char* spec, - unsigned specLength) +GcClass* resolveClassBySpec(Thread* t, + GcClassLoader* loader, + const char* spec, + unsigned specLength) { switch (*spec) { case 'L': { @@ -350,7 +362,7 @@ resolveClassBySpec(Thread* t, object loader, const char* spec, RUNTIME_ARRAY_BODY(s)[specLength - 2] = 0; return resolveClass(t, loader, RUNTIME_ARRAY_BODY(s)); } - + case '[': { THREAD_RUNTIME_ARRAY(t, char, s, specLength + 1); memcpy(RUNTIME_ARRAY_BODY(s), spec, specLength); @@ -363,69 +375,79 @@ resolveClassBySpec(Thread* t, object loader, const char* spec, } } -object -resolveJType(Thread* t, object loader, const char* spec, unsigned specLength) +GcJclass* resolveJType(Thread* t, + GcClassLoader* loader, + const char* spec, + unsigned specLength) { return getJClass(t, resolveClassBySpec(t, loader, spec, specLength)); } -object -resolveParameterTypes(Thread* t, object loader, object spec, - unsigned* parameterCount, unsigned* returnTypeSpec) +GcPair* resolveParameterTypes(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + unsigned* parameterCount, + unsigned* returnTypeSpec) { PROTECT(t, loader); PROTECT(t, spec); - object list = 0; + GcPair* list = 0; PROTECT(t, list); unsigned offset = 1; unsigned count = 0; - while (byteArrayBody(t, spec, offset) != ')') { - switch (byteArrayBody(t, spec, offset)) { + while (spec->body()[offset] != ')') { + switch (spec->body()[offset]) { case 'L': { unsigned start = offset; - ++ offset; - while (byteArrayBody(t, spec, offset) != ';') ++ offset; - ++ offset; + ++offset; + while (spec->body()[offset] != ';') + ++offset; + ++offset; + + GcClass* type + = resolveClassBySpec(t, + loader, + reinterpret_cast(&spec->body()[start]), + offset - start); - object type = resolveClassBySpec - (t, loader, reinterpret_cast(&byteArrayBody(t, spec, start)), - offset - start); - list = makePair(t, type, list); - ++ count; + ++count; } break; - + case '[': { unsigned start = offset; - while (byteArrayBody(t, spec, offset) == '[') ++ offset; - switch (byteArrayBody(t, spec, offset)) { + while (spec->body()[offset] == '[') + ++offset; + switch (spec->body()[offset]) { case 'L': - ++ offset; - while (byteArrayBody(t, spec, offset) != ';') ++ offset; - ++ offset; + ++offset; + while (spec->body()[offset] != ';') + ++offset; + ++offset; break; default: - ++ offset; + ++offset; break; } - - object type = resolveClassBySpec - (t, loader, reinterpret_cast(&byteArrayBody(t, spec, start)), - offset - start); - + + GcClass* type + = resolveClassBySpec(t, + loader, + reinterpret_cast(&spec->body()[start]), + offset - start); + list = makePair(t, type, list); - ++ count; + ++count; } break; default: - list = makePair - (t, primitiveClass(t, byteArrayBody(t, spec, offset)), list); - ++ offset; - ++ count; + list = makePair(t, primitiveClass(t, spec->body()[offset]), list); + ++offset; + ++count; break; } } @@ -435,109 +457,125 @@ resolveParameterTypes(Thread* t, object loader, object spec, return list; } -object -resolveParameterJTypes(Thread* t, object loader, object spec, - unsigned* parameterCount, unsigned* returnTypeSpec) +object resolveParameterJTypes(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + unsigned* parameterCount, + unsigned* returnTypeSpec) { - object list = resolveParameterTypes - (t, loader, spec, parameterCount, returnTypeSpec); + GcPair* list + = resolveParameterTypes(t, loader, spec, parameterCount, returnTypeSpec); PROTECT(t, list); - - object array = makeObjectArray - (t, type(t, Machine::JclassType), *parameterCount); + + object array = makeObjectArray(t, type(t, GcJclass::Type), *parameterCount); PROTECT(t, array); for (int i = *parameterCount - 1; i >= 0; --i) { - object c = getJClass(t, pairFirst(t, list)); - set(t, array, ArrayBody + (i * BytesPerWord), c); - list = pairSecond(t, list); + object c = getJClass(t, cast(t, list->first())); + reinterpret_cast(array)->setBodyElement(t, i, c); + list = cast(t, list->second()); } return array; } -object -resolveExceptionJTypes(Thread* t, object loader, object addendum) +object resolveExceptionJTypes(Thread* t, + GcClassLoader* loader, + GcMethodAddendum* addendum) { - if (addendum == 0 or methodAddendumExceptionTable(t, addendum) == 0) { - return makeObjectArray(t, type(t, Machine::JclassType), 0); + if (addendum == 0 or addendum->exceptionTable() == 0) { + return makeObjectArray(t, type(t, GcJclass::Type), 0); } PROTECT(t, loader); PROTECT(t, addendum); - object array = makeObjectArray - (t, type(t, Machine::JclassType), - shortArrayLength(t, methodAddendumExceptionTable(t, addendum))); + GcShortArray* exceptionTable + = cast(t, addendum->exceptionTable()); + PROTECT(t, exceptionTable); + + object array + = makeObjectArray(t, type(t, GcJclass::Type), exceptionTable->length()); PROTECT(t, array); - for (unsigned i = 0; i < shortArrayLength - (t, methodAddendumExceptionTable(t, addendum)); ++i) - { - uint16_t index = shortArrayBody - (t, methodAddendumExceptionTable(t, addendum), i) - 1; + for (unsigned i = 0; i < exceptionTable->length(); ++i) { + uint16_t index = exceptionTable->body()[i] - 1; - object o = singletonObject(t, addendumPool(t, addendum), index); + object o = singletonObject(t, addendum->pool()->as(t), index); - if (objectClass(t, o) == type(t, Machine::ReferenceType)) { - o = resolveClass(t, loader, referenceName(t, o)); - - set(t, addendumPool(t, addendum), SingletonBody + (index * BytesPerWord), - o); + if (objectClass(t, o) == type(t, GcReference::Type)) { + o = resolveClass(t, loader, cast(t, o)->name()); + + addendum->pool()->setBodyElement( + t, index, reinterpret_cast(o)); } - o = getJClass(t, o); + o = getJClass(t, cast(t, o)); - set(t, array, ArrayBody + (i * BytesPerWord), o); + reinterpret_cast(array)->setBodyElement(t, i, o); } return array; } -object -invoke(Thread* t, object method, object instance, object args) +object invoke(Thread* t, GcMethod* method, object instance, object args) { PROTECT(t, method); PROTECT(t, instance); PROTECT(t, args); - if (methodFlags(t, method) & ACC_STATIC) { + if (method->flags() & ACC_STATIC) { instance = 0; } if ((args == 0 ? 0 : objectArrayLength(t, args)) - != methodParameterCount(t, method)) - { - throwNew(t, Machine::IllegalArgumentExceptionType); + != method->parameterCount()) { + throwNew(t, GcIllegalArgumentException::Type); } - if (methodParameterCount(t, method)) { - unsigned specLength = byteArrayLength(t, methodSpec(t, method)); + if (method->parameterCount()) { + unsigned specLength = method->spec()->length(); THREAD_RUNTIME_ARRAY(t, char, spec, specLength); - memcpy(RUNTIME_ARRAY_BODY(spec), - &byteArrayBody(t, methodSpec(t, method), 0), specLength); + memcpy( + RUNTIME_ARRAY_BODY(spec), method->spec()->body().begin(), specLength); unsigned i = 0; for (MethodSpecIterator it(t, RUNTIME_ARRAY_BODY(spec)); it.hasNext();) { - object type; + GcClass* type; bool objectType = false; const char* p = it.next(); switch (*p) { - case 'Z': type = vm::type(t, Machine::BooleanType); break; - case 'B': type = vm::type(t, Machine::ByteType); break; - case 'S': type = vm::type(t, Machine::ShortType); break; - case 'C': type = vm::type(t, Machine::CharType); break; - case 'I': type = vm::type(t, Machine::IntType); break; - case 'F': type = vm::type(t, Machine::FloatType); break; - case 'J': type = vm::type(t, Machine::LongType); break; - case 'D': type = vm::type(t, Machine::DoubleType); break; + case 'Z': + type = vm::type(t, GcBoolean::Type); + break; + case 'B': + type = vm::type(t, GcByte::Type); + break; + case 'S': + type = vm::type(t, GcShort::Type); + break; + case 'C': + type = vm::type(t, GcChar::Type); + break; + case 'I': + type = vm::type(t, GcInt::Type); + break; + case 'F': + type = vm::type(t, GcFloat::Type); + break; + case 'J': + type = vm::type(t, GcLong::Type); + break; + case 'D': + type = vm::type(t, GcDouble::Type); + break; case 'L': case '[': { objectType = true; unsigned nameLength; if (*p == 'L') { - ++ p; + ++p; nameLength = it.s - p; } else { nameLength = (it.s - p) + 1; @@ -545,9 +583,8 @@ invoke(Thread* t, object method, object instance, object args) THREAD_RUNTIME_ARRAY(t, char, name, nameLength); memcpy(RUNTIME_ARRAY_BODY(name), p, nameLength - 1); RUNTIME_ARRAY_BODY(name)[nameLength - 1] = 0; - type = resolveClass - (t, classLoader(t, methodClass(t, method)), - RUNTIME_ARRAY_BODY(name)); + type = resolveClass( + t, method->class_()->loader(), RUNTIME_ARRAY_BODY(name)); } break; default: @@ -556,28 +593,33 @@ invoke(Thread* t, object method, object instance, object args) object arg = objectArrayBody(t, args, i++); if ((arg == 0 and (not objectType)) - or (arg and (not instanceOf(t, type, arg)))) - { - // fprintf(stderr, "%s is not a %s\n", arg ? &byteArrayBody(t, className(t, objectClass(t, arg)), 0) : reinterpret_cast(""), &byteArrayBody(t, className(t, type), 0)); + or (arg and (not instanceOf(t, type, arg)))) { + if (false) { + fprintf(stderr, + "%s is not a %s\n", + arg ? objectClass(t, arg)->name()->body().begin() + : reinterpret_cast(""), + type->name()->body().begin()); + } - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } } } - initClass(t, methodClass(t, method)); + initClass(t, method->class_()); - unsigned returnCode = methodReturnCode(t, method); + unsigned returnCode = method->returnCode(); THREAD_RESOURCE0(t, { - if (t->exception) { - t->exception = makeThrowable - (t, Machine::InvocationTargetExceptionType, 0, 0, t->exception); - - set(t, t->exception, InvocationTargetExceptionTarget, - throwableCause(t, t->exception)); - } - }); + if (t->exception) { + t->exception = makeThrowable( + t, GcInvocationTargetException::Type, 0, 0, t->exception); + + t->exception->as(t) + ->setTarget(t, t->exception->cause()); + } + }); object result; if (args) { @@ -591,66 +633,70 @@ invoke(Thread* t, object method, object instance, object args) // only safe to call during bootstrap when there's only one thread // running: -void -intercept(Thread* t, object c, const char* name, const char* spec, - void* function, bool updateRuntimeData) +void intercept(Thread* t, + GcClass* c, + const char* name, + const char* spec, + void* function, + bool updateRuntimeData) { - object m = findMethodOrNull(t, c, name, spec); + GcMethod* m = findMethodOrNull(t, c, name, spec); if (m) { PROTECT(t, m); - methodFlags(t, m) |= ACC_NATIVE; + m->flags() |= ACC_NATIVE; if (updateRuntimeData) { - object clone = methodClone(t, m); + GcMethod* clone = methodClone(t, m); // make clone private to prevent vtable updates at compilation // time. Otherwise, our interception might be bypassed by calls // through the vtable. - methodFlags(t, clone) |= ACC_PRIVATE; + clone->flags() |= ACC_PRIVATE; + + GcNativeIntercept* native = makeNativeIntercept(t, function, true, clone); - object native = makeNativeIntercept(t, function, true, clone); - PROTECT(t, native); - - object runtimeData = getMethodRuntimeData(t, m); - - set(t, runtimeData, MethodRuntimeDataNative, native); + + GcMethodRuntimeData* runtimeData = getMethodRuntimeData(t, m); + + runtimeData->setNative(t, native->as(t)); } } else { // If we can't find the method, just ignore it, since ProGuard may // have stripped it out as unused. Otherwise, the code below can - // be uncommented for debugging purposes. + // be enabled for debugging purposes. - // fprintf(stderr, "unable to find %s%s in %s\n", - // name, spec, &byteArrayBody(t, className(t, c), 0)); + if (false) { + fprintf(stderr, + "unable to find %s%s in %s\n", + name, + spec, + c->name()->body().begin()); - // abort(t); + abort(t); + } } } -Finder* -getFinder(Thread* t, const char* name, unsigned nameLength) +Finder* getFinder(Thread* t, const char* name, unsigned nameLength) { ACQUIRE(t, t->m->referenceLock); - - for (object p = root(t, Machine::VirtualFileFinders); - p; p = finderNext(t, p)) - { - if (byteArrayLength(t, finderName(t, p)) == nameLength - and strncmp(reinterpret_cast - (&byteArrayBody(t, finderName(t, p), 0)), - name, nameLength)) - { - return static_cast(finderFinder(t, p)); + + for (GcFinder* p = roots(t)->virtualFileFinders(); p; p = p->next()) { + if (p->name()->length() == nameLength + and strncmp(reinterpret_cast(p->name()->body().begin()), + name, + nameLength)) { + return static_cast(p->finder()); } } - object n = makeByteArray(t, nameLength + 1); - memcpy(&byteArrayBody(t, n, 0), name, nameLength); + GcByteArray* n = makeByteArray(t, nameLength + 1); + memcpy(n->body().begin(), name, nameLength); - void* p = t->m->libraries->resolve - (reinterpret_cast(&byteArrayBody(t, n, 0))); + void* p = t->m->libraries->resolve( + reinterpret_cast(n->body().begin())); if (p) { uint8_t* (*function)(unsigned*); @@ -660,10 +706,9 @@ getFinder(Thread* t, const char* name, unsigned nameLength) uint8_t* data = function(&size); if (data) { Finder* f = makeFinder(t->m->system, t->m->heap, data, size); - object finder = makeFinder - (t, f, n, root(t, Machine::VirtualFileFinders)); + GcFinder* finder = makeFinder(t, f, n, roots(t)->virtualFileFinders()); - setRoot(t, Machine::VirtualFileFinders, finder); + roots(t)->setVirtualFileFinders(t, finder); return f; } @@ -672,44 +717,39 @@ getFinder(Thread* t, const char* name, unsigned nameLength) return 0; } -object -getDeclaredClasses(Thread* t, object c, bool publicOnly) +object getDeclaredClasses(Thread* t, GcClass* c, bool publicOnly) { - object addendum = classAddendum(t, c); + GcClassAddendum* addendum = c->addendum(); if (addendum) { - object table = classAddendumInnerClassTable(t, addendum); + GcArray* table = cast(t, addendum->innerClassTable()); if (table) { PROTECT(t, table); unsigned count = 0; - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object reference = arrayBody(t, table, i); - object outer = innerClassReferenceOuter(t, reference); - if (outer and byteArrayEqual(t, outer, className(t, c)) - and ((not publicOnly) - or (innerClassReferenceFlags(t, reference) & ACC_PUBLIC))) - { - ++ count; + for (unsigned i = 0; i < table->length(); ++i) { + GcInnerClassReference* reference + = cast(t, table->body()[i]); + GcByteArray* outer = reference->outer(); + if (outer and byteArrayEqual(t, outer, c->name()) + and ((not publicOnly) or (reference->flags() & ACC_PUBLIC))) { + ++count; } } - object result = makeObjectArray(t, type(t, Machine::JclassType), count); + object result = makeObjectArray(t, type(t, GcJclass::Type), count); PROTECT(t, result); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object reference = arrayBody(t, table, i); - object outer = innerClassReferenceOuter(t, reference); - if (outer and byteArrayEqual(t, outer, className(t, c)) - and ((not publicOnly) - or (innerClassReferenceFlags(t, reference) & ACC_PUBLIC))) - { - object inner = getJClass - (t, resolveClass - (t, classLoader(t, c), - innerClassReferenceInner(t, arrayBody(t, table, i)))); - - -- count; - set(t, result, ArrayBody + (count * BytesPerWord), inner); + for (unsigned i = 0; i < table->length(); ++i) { + GcInnerClassReference* reference + = cast(t, table->body()[i]); + GcByteArray* outer = reference->outer(); + if (outer and byteArrayEqual(t, outer, c->name()) + and ((not publicOnly) or (reference->flags() & ACC_PUBLIC))) { + object inner + = getJClass(t, resolveClass(t, c->loader(), reference->inner())); + + --count; + reinterpret_cast(result)->setBodyElement(t, count, inner); } } @@ -717,25 +757,22 @@ getDeclaredClasses(Thread* t, object c, bool publicOnly) } } - return makeObjectArray(t, type(t, Machine::JclassType), 0); + return makeObjectArray(t, type(t, GcJclass::Type), 0); } -object -getDeclaringClass(Thread* t, object c) +GcJclass* getDeclaringClass(Thread* t, GcClass* c) { - object addendum = classAddendum(t, c); + GcClassAddendum* addendum = c->addendum(); if (addendum) { - object table = classAddendumInnerClassTable(t, addendum); + GcArray* table = cast(t, addendum->innerClassTable()); if (table) { - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object reference = arrayBody(t, table, i); - if (innerClassReferenceOuter(t, reference) and strcmp - (&byteArrayBody(t, innerClassReferenceInner(t, reference), 0), - &byteArrayBody(t, className(t, c), 0)) == 0) - { - return getJClass - (t, resolveClass - (t, classLoader(t, c), innerClassReferenceOuter(t, reference))); + for (unsigned i = 0; i < table->length(); ++i) { + GcInnerClassReference* reference + = cast(t, table->body()[i]); + if (reference->outer() + and strcmp(reference->inner()->body().begin(), + c->name()->body().begin()) == 0) { + return getJClass(t, resolveClass(t, c->loader(), reference->outer())); } } } @@ -744,28 +781,26 @@ getDeclaringClass(Thread* t, object c) return 0; } -unsigned -classModifiers(Thread* t, object c) +unsigned classModifiers(Thread* t, GcClass* c) { - object addendum = classAddendum(t, c); + GcClassAddendum* addendum = c->addendum(); if (addendum) { - object table = classAddendumInnerClassTable(t, addendum); + GcArray* table = cast(t, addendum->innerClassTable()); if (table) { - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object reference = arrayBody(t, table, i); - if (0 == strcmp - (&byteArrayBody(t, className(t, c), 0), - &byteArrayBody(t, innerClassReferenceInner(t, reference), 0))) - { - return innerClassReferenceFlags(t, reference); - } + for (unsigned i = 0; i < table->length(); ++i) { + GcInnerClassReference* reference + = cast(t, table->body()[i]); + if (0 == strcmp(c->name()->body().begin(), + reference->inner()->body().begin())) { + return reference->flags(); + } } } } - return classFlags(t, c); + return c->flags(); } -} // namespace vm +} // namespace vm -#endif//CLASSPATH_COMMON_H +#endif // CLASSPATH_COMMON_H diff --git a/src/avian/common.h b/src/avian/common.h index cd70124464..d3d5c98adb 100644 --- a/src/avian/common.h +++ b/src/avian/common.h @@ -12,9 +12,11 @@ #define AVIAN_COMMON_H #ifndef __STDC_CONSTANT_MACROS -# define __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS #endif +#include + #include "stdlib.h" #include "stdarg.h" #include "stddef.h" @@ -29,11 +31,11 @@ #include #ifdef linux -# undef linux +#undef linux #endif // don't complain about using 'this' in member initializers: -# pragma warning(disable:4355) +#pragma warning(disable : 4355) #define strncasecmp _strnicmp @@ -41,193 +43,195 @@ #define FP_INFINITE 1 #define FP_UNDEF 2 -inline int fpclassify(double d) { - - switch(_fpclass(d)) { - case _FPCLASS_SNAN: - case _FPCLASS_QNAN: - return FP_NAN; - case _FPCLASS_PINF: - case _FPCLASS_NINF: - return FP_INFINITE; - } - return FP_UNDEF; +inline int fpclassify(double d) +{ + switch (_fpclass(d)) { + case _FPCLASS_SNAN: + case _FPCLASS_QNAN: + return FP_NAN; + case _FPCLASS_PINF: + case _FPCLASS_NINF: + return FP_INFINITE; + } + return FP_UNDEF; } -inline int signbit(double d) { - return _copysign(1.0, d) < 0; +inline int signbit(double d) +{ + return _copysign(1.0, d) < 0; } -# define not ! -# define or || -# define and && -# define xor ^ +#define not! +#define or || +#define and && +#define xor ^ -# define LIKELY(v) v -# define UNLIKELY(v) v +#define LIKELY(v) v +#define UNLIKELY(v) v -# define UNUSED +#define UNUSED -# define NO_RETURN __declspec(noreturn) +#define NO_RETURN __declspec(noreturn) -# define PACKED +#define PACKED -# define PLATFORM_WINDOWS +#define PLATFORM_WINDOWS -# ifdef _M_IX86 +#ifdef _M_IX86 typedef int32_t intptr_t; typedef uint32_t uintptr_t; -# define ARCH_x86_32 -# define BYTES_PER_WORD 4 -# elif defined _M_X64 +#define ARCH_x86_32 +#define BYTES_PER_WORD 4 +#elif defined _M_X64 typedef int64_t intptr_t; typedef uint64_t uintptr_t; -# define ARCH_x86_64 -# define BYTES_PER_WORD 8 -# elif defined _M_ARM_FP +#define ARCH_x86_64 +#define BYTES_PER_WORD 8 +#elif defined _M_ARM_FP typedef int32_t intptr_t; typedef uint32_t uintptr_t; -# define ARCH_arm -# define BYTES_PER_WORD 4 -# else -# error "unsupported architecture" -# endif +#define ARCH_arm +#define BYTES_PER_WORD 4 +#else +#error "unsupported architecture" +#endif namespace vm { typedef intptr_t intptr_alias_t; -} // namespace vm +} // namespace vm -#else // not _MSC_VER +#else // not _MSC_VER -# include +#include -# define BYTES_PER_WORD __SIZEOF_POINTER__ +#define BYTES_PER_WORD __SIZEOF_POINTER__ -# define LIKELY(v) __builtin_expect((v) != 0, true) -# define UNLIKELY(v) __builtin_expect((v) != 0, false) +#define LIKELY(v) __builtin_expect((v) != 0, true) +#define UNLIKELY(v) __builtin_expect((v) != 0, false) -# define UNUSED __attribute__((unused)) +#define UNUSED __attribute__((unused)) -# define NO_RETURN __attribute__((noreturn)) +#define NO_RETURN __attribute__((noreturn)) -# define PACKED __attribute__((packed)) +#define PACKED __attribute__((packed)) -# ifdef __MINGW32__ -# define PLATFORM_WINDOWS -# endif +#ifdef __MINGW32__ +#define PLATFORM_WINDOWS +#endif -# ifdef __i386__ -# define ARCH_x86_32 -# elif defined __x86_64__ -# define ARCH_x86_64 -# elif defined __arm__ -# define ARCH_arm -# else -# error "unsupported architecture" -# endif +#ifdef __i386__ +#define ARCH_x86_32 +#elif defined __x86_64__ +#define ARCH_x86_64 +#elif defined __arm__ +#define ARCH_arm +#else +#error "unsupported architecture" +#endif namespace vm { typedef intptr_t __attribute__((__may_alias__)) intptr_alias_t; -} // namespace vm +} // namespace vm -#endif // not _MSC_VER +#endif // not _MSC_VER #ifdef PLATFORM_WINDOWS -# define AVIAN_EXPORT __declspec(dllexport) -# define PATH_SEPARATOR ';' -#else // not PLATFORM_WINDOWS -# define AVIAN_EXPORT __attribute__ ((visibility("default"))) \ - __attribute__ ((used)) -# define PATH_SEPARATOR ':' -#endif // not PLATFORM_WINDOWS +#define AVIAN_EXPORT __declspec(dllexport) +#define PATH_SEPARATOR ';' +#else // not PLATFORM_WINDOWS +#define AVIAN_EXPORT \ + __attribute__((visibility("default"))) __attribute__((used)) +#define PATH_SEPARATOR ':' +#endif // not PLATFORM_WINDOWS #if (defined ARCH_x86_32) || (defined ARCH_arm) -# define LD "ld" -# if (defined _MSC_VER) || ((defined __MINGW32__) && __GNUC__ >= 4) -# define LLD "I64d" -# else -# define LLD "lld" -# endif -# ifdef __APPLE__ -# define ULD "lu" -# define LX "lx" -# else -# define LX "x" -# define ULD "u" -# endif -#elif defined ARCH_x86_64 -# define LD "ld" -# define LX "lx" -# if (defined _MSC_VER) || (defined __MINGW32__) -# define LLD "I64d" -# define ULD "I64x" -# else -# ifdef __APPLE__ -# define LLD "lld" -# else -# define LLD "ld" -# endif -# define ULD "lu" -# endif +#define LD "ld" +#if (defined _MSC_VER) || ((defined __MINGW32__) && __GNUC__ >= 4) +#define LLD "I64d" #else -# error "Unsupported architecture" +#define LLD "lld" +#endif +#ifdef __APPLE__ +#define ULD "lu" +#define LX "lx" +#else +#define LX "x" +#define ULD "u" +#endif +#elif defined ARCH_x86_64 +#define LD "ld" +#define LX "lx" +#if (defined _MSC_VER) || (defined __MINGW32__) +#define LLD "I64d" +#define ULD "I64x" +#else +#ifdef __APPLE__ +#define LLD "lld" +#else +#define LLD "ld" +#endif +#define ULD "lu" +#endif +#else +#error "Unsupported architecture" #endif #ifdef PLATFORM_WINDOWS -# define SO_PREFIX "" +#define SO_PREFIX "" #else -# define SO_PREFIX "lib" +#define SO_PREFIX "lib" #endif #ifdef __APPLE__ -# define SO_SUFFIX ".dylib" +#define SO_SUFFIX ".dylib" #elif defined PLATFORM_WINDOWS -# define SO_SUFFIX ".dll" +#define SO_SUFFIX ".dll" #else -# define SO_SUFFIX ".so" +#define SO_SUFFIX ".so" #endif #define MACRO_XY(X, Y) X##Y #define MACRO_MakeNameXY(FX, LINE) MACRO_XY(FX, LINE) #define MAKE_NAME(FX) MACRO_MakeNameXY(FX, __LINE__) -#define RESOURCE(type, name, release) \ - class MAKE_NAME(Resource_) { \ - public: \ - MAKE_NAME(Resource_)(type name): name(name) { } \ - ~MAKE_NAME(Resource_)() { release; } \ - \ - private: \ - type name; \ +#define RESOURCE(type, name, release) \ + class MAKE_NAME(Resource_) { \ + public: \ + MAKE_NAME(Resource_)(type name) : name(name) \ + { \ + } \ + ~MAKE_NAME(Resource_)() \ + { \ + release; \ + } \ + \ + private: \ + type name; \ } MAKE_NAME(resource_)(name); #ifdef _MSC_VER -# pragma warning( disable : 4291 ) +#pragma warning(disable : 4291) #endif -inline void* operator new(size_t, void* p) throw() { return p; } namespace vm { -inline intptr_alias_t& -alias(void* p, unsigned offset) +inline intptr_alias_t& alias(void* p, unsigned offset) { return *reinterpret_cast(static_cast(p) + offset); } #ifdef _MSC_VER -inline int -vsnprintf(char* dst, size_t size, const char* format, va_list a) +inline int vsnprintf(char* dst, size_t size, const char* format, va_list a) { return vsnprintf_s(dst, size, _TRUNCATE, format, a); } -inline int -snprintf(char* dst, size_t size, const char* format, ...) +inline int snprintf(char* dst, size_t size, const char* format, ...) { va_list a; va_start(a, format); @@ -236,8 +240,7 @@ snprintf(char* dst, size_t size, const char* format, ...) return r; } -inline FILE* -fopen(const char* name, const char* mode) +inline FILE* fopen(const char* name, const char* mode) { FILE* file; if (fopen_s(&file, name, mode) == 0) { @@ -247,16 +250,14 @@ fopen(const char* name, const char* mode) } } -#else // not _MSC_VER +#else // not _MSC_VER -inline int -vsnprintf(char* dst, size_t size, const char* format, va_list a) +inline int vsnprintf(char* dst, size_t size, const char* format, va_list a) { return ::vsnprintf(dst, size, format, a); } -inline int -snprintf(char* dst, size_t size, const char* format, ...) +inline int snprintf(char* dst, size_t size, const char* format, ...) { va_list a; va_start(a, format); @@ -265,116 +266,105 @@ snprintf(char* dst, size_t size, const char* format, ...) return r; } -inline FILE* -fopen(const char* name, const char* mode) +inline FILE* fopen(const char* name, const char* mode) { return ::fopen(name, mode); } -#endif // not _MSC_VER +#endif // not _MSC_VER const unsigned BytesPerWord = sizeof(uintptr_t); const unsigned BitsPerWord = BytesPerWord * 8; -const uintptr_t PointerMask -= ((~static_cast(0)) / BytesPerWord) * BytesPerWord; +const uintptr_t PointerMask = ((~static_cast(0)) / BytesPerWord) + * BytesPerWord; const unsigned LikelyPageSizeInBytes = 4 * 1024; -inline unsigned -pad(unsigned n, unsigned alignment) +inline unsigned pad(unsigned n, unsigned alignment) { return (n + (alignment - 1)) & ~(alignment - 1); } -inline unsigned -pad(unsigned n) +inline unsigned pad(unsigned n) { return pad(n, BytesPerWord); } -inline uintptr_t -padWord(uintptr_t n, uintptr_t alignment) +inline uintptr_t padWord(uintptr_t n, uintptr_t alignment) { return (n + (alignment - 1)) & ~(alignment - 1); } -inline uintptr_t -padWord(uintptr_t n) +inline uintptr_t padWord(uintptr_t n) { return padWord(n, BytesPerWord); } -inline bool fitsInInt8(int64_t v) { +inline bool fitsInInt8(int64_t v) +{ return v == static_cast(v); } -inline bool fitsInInt16(int64_t v) { +inline bool fitsInInt16(int64_t v) +{ return v == static_cast(v); } -inline bool fitsInInt32(int64_t v) { +inline bool fitsInInt32(int64_t v) +{ return v == static_cast(v); } template -inline unsigned -wordOf(unsigned i) +inline unsigned wordOf(unsigned i) { return i / (sizeof(T) * 8); } -inline unsigned -wordOf(unsigned i) +inline unsigned wordOf(unsigned i) { return wordOf(i); } template -inline unsigned -bitOf(unsigned i) +inline unsigned bitOf(unsigned i) { return i % (sizeof(T) * 8); } -inline unsigned -bitOf(unsigned i) +inline unsigned bitOf(unsigned i) { return bitOf(i); } template -inline unsigned -indexOf(unsigned word, unsigned bit) +inline unsigned indexOf(unsigned word, unsigned bit) { return (word * (sizeof(T) * 8)) + bit; } -inline unsigned -indexOf(unsigned word, unsigned bit) +inline unsigned indexOf(unsigned word, unsigned bit) { return indexOf(word, bit); } template -inline void -markBit(T* map, unsigned i) +inline void markBit(T* map, unsigned i) { map[wordOf(i)] |= static_cast(1) << bitOf(i); } template -inline void -clearBit(T* map, unsigned i) +inline void clearBit(T* map, unsigned i) { map[wordOf(i)] &= ~(static_cast(1) << bitOf(i)); } template -inline unsigned -getBit(T* map, unsigned i) +inline unsigned getBit(T* map, unsigned i) { return (map[wordOf(i)] & (static_cast(1) << bitOf(i))) - >> bitOf(i); + >> bitOf(i); } // todo: the following (clearBits, setBits, and getBits) could be made @@ -382,8 +372,7 @@ getBit(T* map, unsigned i) // a time: template -inline void -clearBits(T* map, unsigned bitsPerRecord, unsigned index) +inline void clearBits(T* map, unsigned bitsPerRecord, unsigned index) { for (unsigned i = index, limit = index + bitsPerRecord; i < limit; ++i) { clearBit(map, i); @@ -391,18 +380,19 @@ clearBits(T* map, unsigned bitsPerRecord, unsigned index) } template -inline void -setBits(T* map, unsigned bitsPerRecord, int index, unsigned v) +inline void setBits(T* map, unsigned bitsPerRecord, int index, unsigned v) { for (int i = index + bitsPerRecord - 1; i >= index; --i) { - if (v & 1) markBit(map, i); else clearBit(map, i); + if (v & 1) + markBit(map, i); + else + clearBit(map, i); v >>= 1; } } template -inline unsigned -getBits(T* map, unsigned bitsPerRecord, unsigned index) +inline unsigned getBits(T* map, unsigned bitsPerRecord, unsigned index) { unsigned v = 0; for (unsigned i = index, limit = index + bitsPerRecord; i < limit; ++i) { @@ -413,122 +403,80 @@ getBits(T* map, unsigned bitsPerRecord, unsigned index) } template -inline T& -fieldAtOffset(void* p, unsigned offset) +inline T& fieldAtOffset(void* p, unsigned offset) { return *reinterpret_cast(static_cast(p) + offset); } template -inline T* -maskAlignedPointer(T* p) +inline T* maskAlignedPointer(T* p) { return reinterpret_cast(reinterpret_cast(p) & PointerMask); } -inline uint32_t -hash(const char* s) -{ - uint32_t h = 0; - for (unsigned i = 0; s[i]; ++i) { - h = (h * 31) + s[i]; - } - return h; -} - -inline uint32_t -hash(const uint8_t* s, unsigned length) -{ - uint32_t h = 0; - for (unsigned i = 0; i < length; ++i) { - h = (h * 31) + s[i]; - } - return h; -} - -inline uint32_t -hash(const int8_t* s, unsigned length) -{ - return hash(reinterpret_cast(s), length); -} - -inline uint32_t -hash(const uint16_t* s, unsigned length) -{ - uint32_t h = 0; - for (unsigned i = 0; i < length; ++i) { - h = (h * 31) + s[i]; - } - return h; -} - -inline void -write4(uint8_t* dst, uint32_t v) +inline void write4(uint8_t* dst, uint32_t v) { memcpy(dst, &v, 4); } -inline uint32_t -floatToBits(float f) +inline uint32_t floatToBits(float f) { - uint32_t bits; memcpy(&bits, &f, 4); + uint32_t bits; + memcpy(&bits, &f, 4); return bits; } -inline uint64_t -doubleToBits(double d) +inline uint64_t doubleToBits(double d) { - uint64_t bits; memcpy(&bits, &d, 8); + uint64_t bits; + memcpy(&bits, &d, 8); return bits; } -inline double -bitsToDouble(uint64_t bits) +inline double bitsToDouble(uint64_t bits) { - double d; memcpy(&d, &bits, 8); + double d; + memcpy(&d, &bits, 8); return d; } -inline float -bitsToFloat(uint32_t bits) +inline float bitsToFloat(uint32_t bits) { - float f; memcpy(&f, &bits, 4); + float f; + memcpy(&f, &bits, 4); return f; } -inline int -difference(void* a, void* b) +inline int difference(void* a, void* b) { return reinterpret_cast(a) - reinterpret_cast(b); } template -inline void* -voidPointer(T function) +inline void* voidPointer(T function) { void* p; memcpy(&p, &function, sizeof(void*)); return p; } -inline void -replace(char a, char b, char* c) +inline void replace(char a, char b, char* c) { - for (; *c; ++c) if (*c == a) *c = b; + for (; *c; ++c) + if (*c == a) + *c = b; } -inline void -replace(char a, char b, char* dst, const char* src) +inline void replace(char a, char b, char* dst, const char* src) { unsigned i = 0; - for (; src[i]; ++ i) { + for (; src[i]; ++i) { dst[i] = src[i] == a ? b : src[i]; } dst[i] = 0; } -inline bool -equal(const void* a, unsigned al, const void* b, unsigned bl) +inline bool equal(const void* a, unsigned al, const void* b, unsigned bl) { if (al == bl) { return memcmp(a, b, al) == 0; @@ -537,6 +485,6 @@ equal(const void* a, unsigned al, const void* b, unsigned bl) } } -} // namespace vm +} // namespace vm -#endif // AVIAN_COMMON_H +#endif // AVIAN_COMMON_H diff --git a/src/avian/constants.h b/src/avian/constants.h index 5fa836c875..133c2e9ad5 100644 --- a/src/avian/constants.h +++ b/src/avian/constants.h @@ -248,35 +248,35 @@ enum Constant { CONSTANT_Utf8 = 1 }; -const unsigned ACC_PUBLIC = 1 << 0; -const unsigned ACC_PRIVATE = 1 << 1; -const unsigned ACC_PROTECTED = 1 << 2; -const unsigned ACC_STATIC = 1 << 3; -const unsigned ACC_FINAL = 1 << 4; -const unsigned ACC_SUPER = 1 << 5; +const unsigned ACC_PUBLIC = 1 << 0; +const unsigned ACC_PRIVATE = 1 << 1; +const unsigned ACC_PROTECTED = 1 << 2; +const unsigned ACC_STATIC = 1 << 3; +const unsigned ACC_FINAL = 1 << 4; +const unsigned ACC_SUPER = 1 << 5; const unsigned ACC_SYNCHRONIZED = ACC_SUPER; -const unsigned ACC_VOLATILE = 1 << 6; -const unsigned ACC_TRANSIENT = 1 << 7; -const unsigned ACC_NATIVE = 1 << 8; -const unsigned ACC_INTERFACE = 1 << 9; -const unsigned ACC_ABSTRACT = 1 << 10; -const unsigned ACC_STRICT = 1 << 11; +const unsigned ACC_VOLATILE = 1 << 6; +const unsigned ACC_TRANSIENT = 1 << 7; +const unsigned ACC_NATIVE = 1 << 8; +const unsigned ACC_INTERFACE = 1 << 9; +const unsigned ACC_ABSTRACT = 1 << 10; +const unsigned ACC_STRICT = 1 << 11; const int AVIAN_JNI_COMMIT = 1; -const int AVIAN_JNI_ABORT = 2; +const int AVIAN_JNI_ABORT = 2; -const int AVIAN_JNI_OK = 0; -const int AVIAN_JNI_ERR = -1; +const int AVIAN_JNI_OK = 0; +const int AVIAN_JNI_ERR = -1; const int AVIAN_JNI_EDETACHED = -2; -const int AVIAN_JNI_EVERSION = -3; -const int AVIAN_JNI_ENOMEM = -4; -const int AVIAN_JNI_EEXIST = -5; -const int AVIAN_JNI_EINVAL = -6; +const int AVIAN_JNI_EVERSION = -3; +const int AVIAN_JNI_ENOMEM = -4; +const int AVIAN_JNI_EEXIST = -5; +const int AVIAN_JNI_EINVAL = -6; const int AVIAN_JNI_VERSION_1_1 = 0x00010001; const int AVIAN_JNI_VERSION_1_2 = 0x00010002; const int AVIAN_JNI_VERSION_1_4 = 0x00010004; -} // namespace vm +} // namespace vm -#endif//CONSTANTS_H +#endif // CONSTANTS_H diff --git a/src/avian/environment.h b/src/avian/environment.h index 147b866d87..8df211b559 100644 --- a/src/avian/environment.h +++ b/src/avian/environment.h @@ -30,4 +30,3 @@ #define AVIAN_ARCH_ARM (3 << 8) #endif - diff --git a/src/avian/finder.h b/src/avian/finder.h index 5089940ef7..cb37d2789b 100644 --- a/src/avian/finder.h +++ b/src/avian/finder.h @@ -30,96 +30,113 @@ const unsigned EntrySignature = 0x02014b50; const unsigned CentralDirectorySearchStart = 22; -inline uint16_t get2(const uint8_t* p) { - return - (static_cast(p[1]) << 8) | - (static_cast(p[0]) ); +inline uint16_t get2(const uint8_t* p) +{ + return (static_cast(p[1]) << 8) | (static_cast(p[0])); } -inline uint32_t get4(const uint8_t* p) { - return - (static_cast(p[3]) << 24) | - (static_cast(p[2]) << 16) | - (static_cast(p[1]) << 8) | - (static_cast(p[0]) ); +inline uint32_t get4(const uint8_t* p) +{ + return (static_cast(p[3]) << 24) + | (static_cast(p[2]) << 16) + | (static_cast(p[1]) << 8) | (static_cast(p[0])); } -inline uint32_t signature(const uint8_t* p) { +inline uint32_t signature(const uint8_t* p) +{ return get4(p); } -inline uint16_t compressionMethod(const uint8_t* centralHeader) { +inline uint16_t compressionMethod(const uint8_t* centralHeader) +{ return get2(centralHeader + 10); } -inline uint32_t fileTime(const uint8_t* centralHeader) { +inline uint32_t fileTime(const uint8_t* centralHeader) +{ return get4(centralHeader + 12); } -inline uint32_t fileCRC(const uint8_t* centralHeader) { +inline uint32_t fileCRC(const uint8_t* centralHeader) +{ return get4(centralHeader + 16); } -inline uint32_t compressedSize(const uint8_t* centralHeader) { +inline uint32_t compressedSize(const uint8_t* centralHeader) +{ return get4(centralHeader + 20); } -inline uint32_t uncompressedSize(const uint8_t* centralHeader) { +inline uint32_t uncompressedSize(const uint8_t* centralHeader) +{ return get4(centralHeader + 24); } -inline uint16_t fileNameLength(const uint8_t* centralHeader) { +inline uint16_t fileNameLength(const uint8_t* centralHeader) +{ return get2(centralHeader + 28); } -inline uint16_t extraFieldLength(const uint8_t* centralHeader) { +inline uint16_t extraFieldLength(const uint8_t* centralHeader) +{ return get2(centralHeader + 30); } -inline uint16_t commentFieldLength(const uint8_t* centralHeader) { +inline uint16_t commentFieldLength(const uint8_t* centralHeader) +{ return get2(centralHeader + 32); } -inline uint32_t localHeaderOffset(const uint8_t* centralHeader) { +inline uint32_t localHeaderOffset(const uint8_t* centralHeader) +{ return get4(centralHeader + 42); } -inline uint16_t localFileNameLength(const uint8_t* localHeader) { +inline uint16_t localFileNameLength(const uint8_t* localHeader) +{ return get2(localHeader + 26); } -inline uint16_t localExtraFieldLength(const uint8_t* localHeader) { +inline uint16_t localExtraFieldLength(const uint8_t* localHeader) +{ return get2(localHeader + 28); } -inline uint32_t centralDirectoryOffset(const uint8_t* centralHeader) { +inline uint32_t centralDirectoryOffset(const uint8_t* centralHeader) +{ return get4(centralHeader + 16); } -inline const uint8_t* fileName(const uint8_t* centralHeader) { +inline const uint8_t* fileName(const uint8_t* centralHeader) +{ return centralHeader + 46; } -inline const uint8_t* fileData(const uint8_t* localHeader) { - return localHeader + LocalHeaderSize + localFileNameLength(localHeader) + - localExtraFieldLength(localHeader); +inline const uint8_t* fileData(const uint8_t* localHeader) +{ + return localHeader + LocalHeaderSize + localFileNameLength(localHeader) + + localExtraFieldLength(localHeader); } -inline const uint8_t* endOfEntry(const uint8_t* p) { - return p + HeaderSize + fileNameLength(p) + extraFieldLength(p) + - commentFieldLength(p); +inline const uint8_t* endOfEntry(const uint8_t* p) +{ + return p + HeaderSize + fileNameLength(p) + extraFieldLength(p) + + commentFieldLength(p); } -inline bool -readLine(const uint8_t* base, unsigned total, unsigned* start, - unsigned* length) +inline bool readLine(const uint8_t* base, + unsigned total, + unsigned* start, + unsigned* length) { const uint8_t* p = base + *start; const uint8_t* end = base + total; - while (p != end and (*p == '\n' or *p == '\r')) ++ p; + while (p != end and (*p == '\n' or *p == '\r')) + ++p; *start = p - base; - while (p != end and not (*p == '\n' or *p == '\r')) ++ p; + while (p != end and not(*p == '\n' or *p == '\r')) + ++p; *length = (p - base) - *start; @@ -136,22 +153,26 @@ class Finder { class Iterator { public: - Iterator(Finder* finder): - it(finder->iterator()), - current(it->next(¤tSize)) - { } + Iterator(Finder* finder) + : it(finder->iterator()), current(it->next(¤tSize)) + { + } - ~Iterator() { + ~Iterator() + { it->dispose(); } - bool hasMore() { - if (current) return true; + bool hasMore() + { + if (current) + return true; current = it->next(¤tSize); return current != 0; } - const char* next(unsigned* size) { + const char* next(unsigned* size) + { if (hasMore()) { *size = currentSize; const char* v = current; @@ -173,7 +194,8 @@ class Finder { unsigned* length, bool tryDirectory = false) = 0; virtual const char* urlPrefix(const char* name) = 0; - virtual const char* nextUrlPrefix(const char* name, void *&finderElementPtr) = 0; + virtual const char* nextUrlPrefix(const char* name, void*& finderElementPtr) + = 0; virtual const char* sourceUrl(const char* name) = 0; virtual const char* path() = 0; virtual void dispose() = 0; @@ -189,6 +211,6 @@ Finder* makeFinder(System* s, const uint8_t* jarData, unsigned jarLength); -} // namespace vm +} // namespace vm -#endif//FINDER_H +#endif // FINDER_H diff --git a/src/avian/heapwalk.h b/src/avian/heapwalk.h index ae1d0df2d8..b104638b3f 100644 --- a/src/avian/heapwalk.h +++ b/src/avian/heapwalk.h @@ -29,8 +29,8 @@ class HeapVisitor { virtual void root() = 0; virtual unsigned visitNew(object value) = 0; virtual void visitOld(object value, unsigned number) = 0; - virtual void push(object parent, unsigned parentNumber, - unsigned childOffset) = 0; + virtual void push(object parent, unsigned parentNumber, unsigned childOffset) + = 0; virtual void pop() = 0; }; @@ -42,9 +42,8 @@ class HeapWalker { virtual void dispose() = 0; }; -HeapWalker* -makeHeapWalker(Thread* t, HeapVisitor* v); +HeapWalker* makeHeapWalker(Thread* t, HeapVisitor* v); -} // namespace vm +} // namespace vm -#endif//HEAPWALK_H +#endif // HEAPWALK_H diff --git a/src/avian/java-common.h b/src/avian/java-common.h index 4ea663b00e..3ed4827989 100644 --- a/src/avian/java-common.h +++ b/src/avian/java-common.h @@ -16,9 +16,10 @@ namespace vm { class Machine; class Thread; -struct Object { }; +class GcObject; +; -typedef Object* object; +typedef GcObject* object; typedef uint8_t jboolean; typedef int8_t jbyte; @@ -33,37 +34,50 @@ typedef jint jsize; typedef object* jobject; -typedef jobject jclass; -typedef jobject jthrowable; -typedef jobject jstring; +class GcString; +class GcJclass; +class GcThrowable; +class GcBooleanArray; +class GcByteArray; +class GcCharArray; +class GcShortArray; +class GcIntArray; +class GcLongArray; +class GcFloatArray; +class GcDoubleArray; +class GcObjectArray; + +typedef GcJclass** jclass; +typedef GcThrowable** jthrowable; +typedef GcString** jstring; typedef jobject jweak; typedef jobject jarray; -typedef jarray jbooleanArray; -typedef jarray jbyteArray; -typedef jarray jcharArray; -typedef jarray jshortArray; -typedef jarray jintArray; -typedef jarray jlongArray; -typedef jarray jfloatArray; -typedef jarray jdoubleArray; -typedef jarray jobjectArray; +typedef GcBooleanArray** jbooleanArray; +typedef GcByteArray** jbyteArray; +typedef GcCharArray** jcharArray; +typedef GcShortArray** jshortArray; +typedef GcIntArray** jintArray; +typedef GcLongArray** jlongArray; +typedef GcFloatArray** jfloatArray; +typedef GcDoubleArray** jdoubleArray; +typedef GcObjectArray** jobjectArray; typedef uintptr_t jfieldID; typedef uintptr_t jmethodID; union jvalue { jboolean z; - jbyte b; - jchar c; - jshort s; - jint i; - jlong j; - jfloat f; - jdouble d; - jobject l; + jbyte b; + jchar c; + jshort s; + jint i; + jlong j; + jfloat f; + jdouble d; + jobject l; }; -} // namespace vm +} // namespace vm -#endif // JAVA_COMMON_H +#endif // JAVA_COMMON_H diff --git a/src/avian/jnienv.h b/src/avian/jnienv.h index 50826733cb..2e9ae3d882 100644 --- a/src/avian/jnienv.h +++ b/src/avian/jnienv.h @@ -27,9 +27,8 @@ namespace vm { -void -populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable); +void populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable); -} // namespace vm +} // namespace vm -#endif//JNIENV_H +#endif // JNIENV_H diff --git a/src/avian/lzma-util.h b/src/avian/lzma-util.h index 73e8bcd294..bb60d2ba25 100644 --- a/src/avian/lzma-util.h +++ b/src/avian/lzma-util.h @@ -22,7 +22,8 @@ const unsigned Padding = 16; class LzmaAllocator { public: - LzmaAllocator(avian::util::Allocator* a): a(a) { + LzmaAllocator(avian::util::Allocator* a) : a(a) + { allocator.Alloc = allocate; allocator.Free = free; } @@ -30,15 +31,17 @@ class LzmaAllocator { ISzAlloc allocator; avian::util::Allocator* a; - static void* allocate(void* allocator, size_t size) { - uint8_t* p = static_cast - (static_cast(allocator)->a->allocate(size + Padding)); + static void* allocate(void* allocator, size_t size) + { + uint8_t* p = static_cast( + static_cast(allocator)->a->allocate(size + Padding)); int32_t size32 = size; memcpy(p, &size32, 4); return p + Padding; } - static void free(void* allocator, void* address) { + static void free(void* allocator, void* address) + { if (address) { void* p = static_cast(address) - Padding; int32_t size32; @@ -48,6 +51,6 @@ class LzmaAllocator { } }; -} // namespace vm +} // namespace vm -#endif // LZMA_UTIL_H +#endif // LZMA_UTIL_H diff --git a/src/avian/lzma.h b/src/avian/lzma.h index 04afa81462..12642ded3f 100644 --- a/src/avian/lzma.h +++ b/src/avian/lzma.h @@ -33,6 +33,6 @@ uint8_t* encodeLZMA(System* s, unsigned inSize, unsigned* outSize); -} // namespace vm +} // namespace vm -#endif // LZMA_H +#endif // LZMA_H diff --git a/src/avian/machine.h b/src/avian/machine.h index f0cc3c3252..4245dbb952 100644 --- a/src/avian/machine.h +++ b/src/avian/machine.h @@ -16,6 +16,7 @@ #include #include #include +#include #include "avian/finder.h" #include "avian/processor.h" #include "avian/constants.h" @@ -24,77 +25,104 @@ using namespace avian::util; #ifdef PLATFORM_WINDOWS -# define JNICALL __stdcall +#define JNICALL __stdcall #else -# define JNICALL +#define JNICALL #endif -#define PROTECT(thread, name) \ - Thread::SingleProtector MAKE_NAME(protector_) (thread, &name); +#define PROTECT(thread, name) \ + Thread::SingleProtector MAKE_NAME(protector_)(thread, &name); -#define ACQUIRE(t, x) MonitorResource MAKE_NAME(monitorResource_) (t, x) +#define ACQUIRE(t, x) MonitorResource MAKE_NAME(monitorResource_)(t, x) #define ACQUIRE_OBJECT(t, x) \ - ObjectMonitorResource MAKE_NAME(monitorResource_) (t, x) + ObjectMonitorResource MAKE_NAME(monitorResource_)(t, x) #define ACQUIRE_FIELD_FOR_READ(t, field) \ - FieldReadResource MAKE_NAME(monitorResource_) (t, field) + FieldReadResource MAKE_NAME(monitorResource_)(t, field) #define ACQUIRE_FIELD_FOR_WRITE(t, field) \ - FieldWriteResource MAKE_NAME(monitorResource_) (t, field) + FieldWriteResource MAKE_NAME(monitorResource_)(t, field) -#define ACQUIRE_RAW(t, x) RawMonitorResource MAKE_NAME(monitorResource_) (t, x) +#define ACQUIRE_RAW(t, x) RawMonitorResource MAKE_NAME(monitorResource_)(t, x) -#define ENTER(t, state) StateResource MAKE_NAME(stateResource_) (t, state) +#define ENTER(t, state) StateResource MAKE_NAME(stateResource_)(t, state) -#define THREAD_RESOURCE0(t, releaseBody) \ - class MAKE_NAME(Resource_): public Thread::AutoResource { \ - public: \ - MAKE_NAME(Resource_)(Thread* t): AutoResource(t) { } \ - ~MAKE_NAME(Resource_)() { releaseBody; } \ - virtual void release() \ - { this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); } \ +#define THREAD_RESOURCE0(t, releaseBody) \ + class MAKE_NAME(Resource_) : public Thread::AutoResource { \ + public: \ + MAKE_NAME(Resource_)(Thread * t) : AutoResource(t) \ + { \ + } \ + ~MAKE_NAME(Resource_)() \ + { \ + releaseBody; \ + } \ + virtual void release() \ + { \ + this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); \ + } \ } MAKE_NAME(resource_)(t); -#define OBJECT_RESOURCE(t, name, releaseBody) \ - class MAKE_NAME(Resource_): public Thread::AutoResource { \ - public: \ - MAKE_NAME(Resource_)(Thread* t, object name): \ - AutoResource(t), name(name), protector(t, &(this->name)) { } \ - ~MAKE_NAME(Resource_)() { releaseBody; } \ - virtual void release() \ - { this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); } \ - \ - private: \ - object name; \ - Thread::SingleProtector protector; \ +#define OBJECT_RESOURCE(t, name, releaseBody) \ + class MAKE_NAME(Resource_) : public Thread::AutoResource { \ + public: \ + MAKE_NAME(Resource_)(Thread * t, object name) \ + : AutoResource(t), name(name), protector(t, &(this->name)) \ + { \ + } \ + ~MAKE_NAME(Resource_)() \ + { \ + releaseBody; \ + } \ + virtual void release() \ + { \ + this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); \ + } \ + \ + private: \ + object name; \ + Thread::SingleProtector protector; \ } MAKE_NAME(resource_)(t, name); -#define THREAD_RESOURCE(t, type, name, releaseBody) \ - class MAKE_NAME(Resource_): public Thread::AutoResource { \ - public: \ - MAKE_NAME(Resource_)(Thread* t, type name): \ - AutoResource(t), name(name) { } \ - ~MAKE_NAME(Resource_)() { releaseBody; } \ - virtual void release() \ - { this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); } \ - \ - private: \ - type name; \ +#define THREAD_RESOURCE(t, type, name, releaseBody) \ + class MAKE_NAME(Resource_) : public Thread::AutoResource { \ + public: \ + MAKE_NAME(Resource_)(Thread * t, type name) : AutoResource(t), name(name) \ + { \ + } \ + ~MAKE_NAME(Resource_)() \ + { \ + releaseBody; \ + } \ + virtual void release() \ + { \ + this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); \ + } \ + \ + private: \ + type name; \ } MAKE_NAME(resource_)(t, name); -#define THREAD_RESOURCE2(t, type1, name1, type2, name2, releaseBody) \ - class MAKE_NAME(Resource_): public Thread::AutoResource { \ - public: \ - MAKE_NAME(Resource_)(Thread* t, type1 name1, type2 name2): \ - AutoResource(t), name1(name1), name2(name2) { } \ - ~MAKE_NAME(Resource_)() { releaseBody; } \ - virtual void release() \ - { this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); } \ - \ - private: \ - type1 name1; \ - type2 name2; \ +#define THREAD_RESOURCE2(t, type1, name1, type2, name2, releaseBody) \ + class MAKE_NAME(Resource_) : public Thread::AutoResource { \ + public: \ + MAKE_NAME(Resource_)(Thread * t, type1 name1, type2 name2) \ + : AutoResource(t), name1(name1), name2(name2) \ + { \ + } \ + ~MAKE_NAME(Resource_)() \ + { \ + releaseBody; \ + } \ + virtual void release() \ + { \ + this->MAKE_NAME(Resource_)::~MAKE_NAME(Resource_)(); \ + } \ + \ + private: \ + type1 name1; \ + type2 name2; \ } MAKE_NAME(resource_)(t, name1, name2); namespace vm { @@ -115,13 +143,13 @@ const unsigned ThreadHeapSizeInBytes = 64 * 1024; const unsigned ThreadHeapSizeInWords = ThreadHeapSizeInBytes / BytesPerWord; const unsigned ThreadBackupHeapSizeInBytes = 2 * 1024; -const unsigned ThreadBackupHeapSizeInWords -= ThreadBackupHeapSizeInBytes / BytesPerWord; +const unsigned ThreadBackupHeapSizeInWords = ThreadBackupHeapSizeInBytes + / BytesPerWord; const unsigned ThreadHeapPoolSize = 64; -const unsigned FixedFootprintThresholdInBytes -= ThreadHeapPoolSize * ThreadHeapSizeInBytes; +const unsigned FixedFootprintThresholdInBytes = ThreadHeapPoolSize + * ThreadHeapSizeInBytes; // number of zombie threads which may accumulate before we force a GC // to clean them up: @@ -141,7 +169,7 @@ enum FieldCode { }; enum StackTag { - IntTag, // must be zero + IntTag, // must be zero ObjectTag }; @@ -184,25 +212,15 @@ struct JavaVMVTable { void* reserved1; void* reserved2; - jint - (JNICALL *DestroyJavaVM) - (JavaVM*); + jint(JNICALL* DestroyJavaVM)(JavaVM*); - jint - (JNICALL *AttachCurrentThread) - (JavaVM*, JNIEnv**, void*); + jint(JNICALL* AttachCurrentThread)(JavaVM*, JNIEnv**, void*); - jint - (JNICALL *DetachCurrentThread) - (JavaVM*); + jint(JNICALL* DetachCurrentThread)(JavaVM*); - jint - (JNICALL *GetEnv) - (JavaVM*, JNIEnv**, jint); + jint(JNICALL* GetEnv)(JavaVM*, JNIEnv**, jint); - jint - (JNICALL *AttachCurrentThreadAsDaemon) - (JavaVM*, JNIEnv**, void*); + jint(JNICALL* AttachCurrentThreadAsDaemon)(JavaVM*, JNIEnv**, void*); }; struct JNIEnvVTable { @@ -211,960 +229,719 @@ struct JNIEnvVTable { void* reserved2; void* reserved3; - jint - (JNICALL *GetVersion) - (JNIEnv*); + jint(JNICALL* GetVersion)(JNIEnv*); - jclass - (JNICALL *DefineClass) - (JNIEnv*, const char*, jobject, const jbyte*, jsize); + jclass( + JNICALL* DefineClass)(JNIEnv*, const char*, jobject, const jbyte*, jsize); - jclass - (JNICALL *FindClass) - (JNIEnv*, const char*); + jclass(JNICALL* FindClass)(JNIEnv*, const char*); - jmethodID - (JNICALL *FromReflectedMethod) - (JNIEnv*, jobject); + jmethodID(JNICALL* FromReflectedMethod)(JNIEnv*, jobject); - jfieldID - (JNICALL *FromReflectedField) - (JNIEnv*, jobject); + jfieldID(JNICALL* FromReflectedField)(JNIEnv*, jobject); - jobject - (JNICALL *ToReflectedMethod) - (JNIEnv*, jclass, jmethodID, jboolean); + jobject(JNICALL* ToReflectedMethod)(JNIEnv*, jclass, jmethodID, jboolean); - jclass - (JNICALL *GetSuperclass) - (JNIEnv*, jclass); + jclass(JNICALL* GetSuperclass)(JNIEnv*, jclass); - jboolean - (JNICALL *IsAssignableFrom) - (JNIEnv*, jclass, jclass); + jboolean(JNICALL* IsAssignableFrom)(JNIEnv*, jclass, jclass); - jobject - (JNICALL *ToReflectedField) - (JNIEnv*, jclass, jfieldID, jboolean); + jobject(JNICALL* ToReflectedField)(JNIEnv*, jclass, jfieldID, jboolean); - jint - (JNICALL *Throw) - (JNIEnv*, jthrowable); + jint(JNICALL* Throw)(JNIEnv*, jthrowable); - jint - (JNICALL *ThrowNew) - (JNIEnv*, jclass, const char*); + jint(JNICALL* ThrowNew)(JNIEnv*, jclass, const char*); - jthrowable - (JNICALL *ExceptionOccurred) - (JNIEnv*); + jthrowable(JNICALL* ExceptionOccurred)(JNIEnv*); - void - (JNICALL *ExceptionDescribe) - (JNIEnv*); + void(JNICALL* ExceptionDescribe)(JNIEnv*); - void - (JNICALL *ExceptionClear) - (JNIEnv*); + void(JNICALL* ExceptionClear)(JNIEnv*); - void - (JNICALL *FatalError) - (JNIEnv*, const char*); + void(JNICALL* FatalError)(JNIEnv*, const char*); - jint - (JNICALL *PushLocalFrame) - (JNIEnv*, jint); + jint(JNICALL* PushLocalFrame)(JNIEnv*, jint); - jobject - (JNICALL *PopLocalFrame) - (JNIEnv*, jobject); + jobject(JNICALL* PopLocalFrame)(JNIEnv*, jobject); - jobject - (JNICALL *NewGlobalRef) - (JNIEnv*, jobject); + jobject(JNICALL* NewGlobalRef)(JNIEnv*, jobject); - void - (JNICALL *DeleteGlobalRef) - (JNIEnv*, jobject); + void(JNICALL* DeleteGlobalRef)(JNIEnv*, jobject); - void - (JNICALL *DeleteLocalRef) - (JNIEnv*, jobject); + void(JNICALL* DeleteLocalRef)(JNIEnv*, jobject); - jboolean - (JNICALL *IsSameObject) - (JNIEnv*, jobject, jobject); + jboolean(JNICALL* IsSameObject)(JNIEnv*, jobject, jobject); - jobject - (JNICALL *NewLocalRef) - (JNIEnv*, jobject); + jobject(JNICALL* NewLocalRef)(JNIEnv*, jobject); - jint - (JNICALL *EnsureLocalCapacity) - (JNIEnv*, jint); + jint(JNICALL* EnsureLocalCapacity)(JNIEnv*, jint); - jobject - (JNICALL *AllocObject) - (JNIEnv*, jclass); + jobject(JNICALL* AllocObject)(JNIEnv*, jclass); - jobject - (JNICALL *NewObject) - (JNIEnv*, jclass, jmethodID, ...); + jobject(JNICALL* NewObject)(JNIEnv*, jclass, jmethodID, ...); - jobject - (JNICALL *NewObjectV) - (JNIEnv*, jclass, jmethodID, va_list); + jobject(JNICALL* NewObjectV)(JNIEnv*, jclass, jmethodID, va_list); - jobject - (JNICALL *NewObjectA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jobject(JNICALL* NewObjectA)(JNIEnv*, jclass, jmethodID, const jvalue*); - jclass - (JNICALL *GetObjectClass) - (JNIEnv*, jobject); + jclass(JNICALL* GetObjectClass)(JNIEnv*, jobject); - jboolean - (JNICALL *IsInstanceOf) - (JNIEnv*, jobject, jclass); + jboolean(JNICALL* IsInstanceOf)(JNIEnv*, jobject, jclass); - jmethodID - (JNICALL *GetMethodID) - (JNIEnv*, jclass, const char*, const char*); + jmethodID(JNICALL* GetMethodID)(JNIEnv*, jclass, const char*, const char*); - jobject - (JNICALL *CallObjectMethod) - (JNIEnv*, jobject, jmethodID, ...); + jobject(JNICALL* CallObjectMethod)(JNIEnv*, jobject, jmethodID, ...); - jobject - (JNICALL *CallObjectMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jobject(JNICALL* CallObjectMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jobject - (JNICALL *CallObjectMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jobject(JNICALL* CallObjectMethodA)(JNIEnv*, + jobject, + jmethodID, + const jvalue*); - jboolean - (JNICALL *CallBooleanMethod) - (JNIEnv*, jobject, jmethodID, ...); + jboolean(JNICALL* CallBooleanMethod)(JNIEnv*, jobject, jmethodID, ...); - jboolean - (JNICALL *CallBooleanMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jboolean(JNICALL* CallBooleanMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jboolean - (JNICALL *CallBooleanMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jboolean(JNICALL* CallBooleanMethodA)(JNIEnv*, + jobject, + jmethodID, + const jvalue*); - jbyte - (JNICALL *CallByteMethod) - (JNIEnv*, jobject, jmethodID, ...); + jbyte(JNICALL* CallByteMethod)(JNIEnv*, jobject, jmethodID, ...); - jbyte - (JNICALL *CallByteMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jbyte(JNICALL* CallByteMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jbyte - (JNICALL *CallByteMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jbyte(JNICALL* CallByteMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jchar - (JNICALL *CallCharMethod) - (JNIEnv*, jobject, jmethodID, ...); + jchar(JNICALL* CallCharMethod)(JNIEnv*, jobject, jmethodID, ...); - jchar - (JNICALL *CallCharMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jchar(JNICALL* CallCharMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jchar - (JNICALL *CallCharMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jchar(JNICALL* CallCharMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jshort - (JNICALL *CallShortMethod) - (JNIEnv*, jobject, jmethodID, ...); + jshort(JNICALL* CallShortMethod)(JNIEnv*, jobject, jmethodID, ...); - jshort - (JNICALL *CallShortMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jshort(JNICALL* CallShortMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jshort - (JNICALL *CallShortMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jshort(JNICALL* CallShortMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jint - (JNICALL *CallIntMethod) - (JNIEnv*, jobject, jmethodID, ...); + jint(JNICALL* CallIntMethod)(JNIEnv*, jobject, jmethodID, ...); - jint - (JNICALL *CallIntMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jint(JNICALL* CallIntMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jint - (JNICALL *CallIntMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jint(JNICALL* CallIntMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jlong - (JNICALL *CallLongMethod) - (JNIEnv*, jobject, jmethodID, ...); + jlong(JNICALL* CallLongMethod)(JNIEnv*, jobject, jmethodID, ...); - jlong - (JNICALL *CallLongMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jlong(JNICALL* CallLongMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jlong - (JNICALL *CallLongMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jlong(JNICALL* CallLongMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jfloat - (JNICALL *CallFloatMethod) - (JNIEnv*, jobject, jmethodID, ...); + jfloat(JNICALL* CallFloatMethod)(JNIEnv*, jobject, jmethodID, ...); - jfloat - (JNICALL *CallFloatMethodV) - (JNIEnv*, jobject, jmethodID, va_list); + jfloat(JNICALL* CallFloatMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jfloat - (JNICALL *CallFloatMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); + jfloat(JNICALL* CallFloatMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - jdouble - (JNICALL *CallDoubleMethod) - (JNIEnv*, jobject, jmethodID, ...); + jdouble(JNICALL* CallDoubleMethod)(JNIEnv*, jobject, jmethodID, ...); - jdouble - (JNICALL *CallDoubleMethodV) - (JNIEnv*, jobject, jmethodID, va_list); - - jdouble - (JNICALL *CallDoubleMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); - - void - (JNICALL *CallVoidMethod) - (JNIEnv*, jobject, jmethodID, ...); - - void - (JNICALL *CallVoidMethodV) - (JNIEnv*, jobject, jmethodID, va_list); - - void - (JNICALL *CallVoidMethodA) - (JNIEnv*, jobject, jmethodID, const jvalue*); - - jobject - (JNICALL *CallNonvirtualObjectMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jobject - (JNICALL *CallNonvirtualObjectMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jobject - (JNICALL *CallNonvirtualObjectMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jboolean - (JNICALL *CallNonvirtualBooleanMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jboolean - (JNICALL *CallNonvirtualBooleanMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jboolean - (JNICALL *CallNonvirtualBooleanMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jbyte - (JNICALL *CallNonvirtualByteMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jbyte - (JNICALL *CallNonvirtualByteMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jbyte - (JNICALL *CallNonvirtualByteMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jchar - (JNICALL *CallNonvirtualCharMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jchar - (JNICALL *CallNonvirtualCharMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jchar - (JNICALL *CallNonvirtualCharMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jshort - (JNICALL *CallNonvirtualShortMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jshort - (JNICALL *CallNonvirtualShortMethodV) - (JNIEnv*, jobject, jclass, jmethodID, - va_list); - - jshort - (JNICALL *CallNonvirtualShortMethodA) - (JNIEnv*, jobject, jclass, jmethodID, - const jvalue*); - - jint - (JNICALL *CallNonvirtualIntMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jint - (JNICALL *CallNonvirtualIntMethodV) - (JNIEnv*, jobject, jclass, jmethodID, - va_list); - - jint - (JNICALL *CallNonvirtualIntMethodA) - (JNIEnv*, jobject, jclass, jmethodID, - const jvalue*); - - jlong - (JNICALL *CallNonvirtualLongMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jlong - (JNICALL *CallNonvirtualLongMethodV) - (JNIEnv*, jobject, jclass, jmethodID, - va_list); - jlong - (JNICALL *CallNonvirtualLongMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jfloat - (JNICALL *CallNonvirtualFloatMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jfloat - (JNICALL *CallNonvirtualFloatMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jfloat - (JNICALL *CallNonvirtualFloatMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jdouble - (JNICALL *CallNonvirtualDoubleMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - jdouble - (JNICALL *CallNonvirtualDoubleMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - jdouble - (JNICALL *CallNonvirtualDoubleMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - void - (JNICALL *CallNonvirtualVoidMethod) - (JNIEnv*, jobject, jclass, jmethodID, ...); - - void - (JNICALL *CallNonvirtualVoidMethodV) - (JNIEnv*, jobject, jclass, jmethodID, va_list); - - void - (JNICALL *CallNonvirtualVoidMethodA) - (JNIEnv*, jobject, jclass, jmethodID, const jvalue*); - - jfieldID - (JNICALL *GetFieldID) - (JNIEnv*, jclass, const char*, const char*); - - jobject - (JNICALL *GetObjectField) - (JNIEnv*, jobject, jfieldID); - - jboolean - (JNICALL *GetBooleanField) - (JNIEnv*, jobject, jfieldID); - - jbyte - (JNICALL *GetByteField) - (JNIEnv*, jobject, jfieldID); - - jchar - (JNICALL *GetCharField) - (JNIEnv*, jobject, jfieldID); - - jshort - (JNICALL *GetShortField) - (JNIEnv*, jobject, jfieldID); - - jint - (JNICALL *GetIntField) - (JNIEnv*, jobject, jfieldID); - - jlong - (JNICALL *GetLongField) - (JNIEnv*, jobject, jfieldID); - - jfloat - (JNICALL *GetFloatField) - (JNIEnv*, jobject, jfieldID); - - jdouble - (JNICALL *GetDoubleField) - (JNIEnv*, jobject, jfieldID); - - void - (JNICALL *SetObjectField) - (JNIEnv*, jobject, jfieldID, jobject); - - void - (JNICALL *SetBooleanField) - (JNIEnv*, jobject, jfieldID, jboolean); - - void - (JNICALL *SetByteField) - (JNIEnv*, jobject, jfieldID, jbyte); + jdouble(JNICALL* CallDoubleMethodV)(JNIEnv*, jobject, jmethodID, va_list); - void - (JNICALL *SetCharField) - (JNIEnv*, jobject, jfieldID, jchar); + jdouble(JNICALL* CallDoubleMethodA)(JNIEnv*, + jobject, + jmethodID, + const jvalue*); - void - (JNICALL *SetShortField) - (JNIEnv*, jobject, jfieldID, jshort); + void(JNICALL* CallVoidMethod)(JNIEnv*, jobject, jmethodID, ...); - void - (JNICALL *SetIntField) - (JNIEnv*, jobject, jfieldID, jint); + void(JNICALL* CallVoidMethodV)(JNIEnv*, jobject, jmethodID, va_list); - void - (JNICALL *SetLongField) - (JNIEnv*, jobject, jfieldID, jlong); + void(JNICALL* CallVoidMethodA)(JNIEnv*, jobject, jmethodID, const jvalue*); - void - (JNICALL *SetFloatField) - (JNIEnv*, jobject, jfieldID, jfloat); + jobject(JNICALL* CallNonvirtualObjectMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); - void - (JNICALL *SetDoubleField) - (JNIEnv*, jobject, jfieldID, jdouble); + jobject(JNICALL* CallNonvirtualObjectMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); - jmethodID - (JNICALL *GetStaticMethodID) - (JNIEnv*, jclass, const char*, const char*); + jobject(JNICALL* CallNonvirtualObjectMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); - jobject - (JNICALL *CallStaticObjectMethod) - (JNIEnv*, jclass, jmethodID, ...); + jboolean(JNICALL* CallNonvirtualBooleanMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); - jobject - (JNICALL *CallStaticObjectMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jboolean(JNICALL* CallNonvirtualBooleanMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); - jobject - (JNICALL *CallStaticObjectMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jboolean(JNICALL* CallNonvirtualBooleanMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jbyte(JNICALL* CallNonvirtualByteMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jbyte(JNICALL* CallNonvirtualByteMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jbyte(JNICALL* CallNonvirtualByteMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jchar(JNICALL* CallNonvirtualCharMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jchar(JNICALL* CallNonvirtualCharMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jchar(JNICALL* CallNonvirtualCharMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jshort(JNICALL* CallNonvirtualShortMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jshort(JNICALL* CallNonvirtualShortMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jshort(JNICALL* CallNonvirtualShortMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jint(JNICALL* CallNonvirtualIntMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jint(JNICALL* CallNonvirtualIntMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jint(JNICALL* CallNonvirtualIntMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jlong(JNICALL* CallNonvirtualLongMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jlong(JNICALL* CallNonvirtualLongMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + jlong(JNICALL* CallNonvirtualLongMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jfloat(JNICALL* CallNonvirtualFloatMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jfloat(JNICALL* CallNonvirtualFloatMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jfloat(JNICALL* CallNonvirtualFloatMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); + + jdouble(JNICALL* CallNonvirtualDoubleMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); + + jdouble(JNICALL* CallNonvirtualDoubleMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); + + jdouble(JNICALL* CallNonvirtualDoubleMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); - jboolean - (JNICALL *CallStaticBooleanMethod) - (JNIEnv*, jclass, jmethodID, ...); + void(JNICALL* CallNonvirtualVoidMethod)(JNIEnv*, + jobject, + jclass, + jmethodID, + ...); - jboolean - (JNICALL *CallStaticBooleanMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + void(JNICALL* CallNonvirtualVoidMethodV)(JNIEnv*, + jobject, + jclass, + jmethodID, + va_list); - jboolean - (JNICALL *CallStaticBooleanMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + void(JNICALL* CallNonvirtualVoidMethodA)(JNIEnv*, + jobject, + jclass, + jmethodID, + const jvalue*); - jbyte - (JNICALL *CallStaticByteMethod) - (JNIEnv*, jclass, jmethodID, ...); + jfieldID(JNICALL* GetFieldID)(JNIEnv*, jclass, const char*, const char*); - jbyte - (JNICALL *CallStaticByteMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jobject(JNICALL* GetObjectField)(JNIEnv*, jobject, jfieldID); - jbyte - (JNICALL *CallStaticByteMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jboolean(JNICALL* GetBooleanField)(JNIEnv*, jobject, jfieldID); - jchar - (JNICALL *CallStaticCharMethod) - (JNIEnv*, jclass, jmethodID, ...); + jbyte(JNICALL* GetByteField)(JNIEnv*, jobject, jfieldID); - jchar - (JNICALL *CallStaticCharMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jchar(JNICALL* GetCharField)(JNIEnv*, jobject, jfieldID); - jchar - (JNICALL *CallStaticCharMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jshort(JNICALL* GetShortField)(JNIEnv*, jobject, jfieldID); - jshort - (JNICALL *CallStaticShortMethod) - (JNIEnv*, jclass, jmethodID, ...); + jint(JNICALL* GetIntField)(JNIEnv*, jobject, jfieldID); - jshort - (JNICALL *CallStaticShortMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jlong(JNICALL* GetLongField)(JNIEnv*, jobject, jfieldID); - jshort - (JNICALL *CallStaticShortMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jfloat(JNICALL* GetFloatField)(JNIEnv*, jobject, jfieldID); - jint - (JNICALL *CallStaticIntMethod) - (JNIEnv*, jclass, jmethodID, ...); + jdouble(JNICALL* GetDoubleField)(JNIEnv*, jobject, jfieldID); - jint - (JNICALL *CallStaticIntMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + void(JNICALL* SetObjectField)(JNIEnv*, jobject, jfieldID, jobject); - jint - (JNICALL *CallStaticIntMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + void(JNICALL* SetBooleanField)(JNIEnv*, jobject, jfieldID, jboolean); - jlong - (JNICALL *CallStaticLongMethod) - (JNIEnv*, jclass, jmethodID, ...); + void(JNICALL* SetByteField)(JNIEnv*, jobject, jfieldID, jbyte); - jlong - (JNICALL *CallStaticLongMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + void(JNICALL* SetCharField)(JNIEnv*, jobject, jfieldID, jchar); - jlong - (JNICALL *CallStaticLongMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + void(JNICALL* SetShortField)(JNIEnv*, jobject, jfieldID, jshort); - jfloat - (JNICALL *CallStaticFloatMethod) - (JNIEnv*, jclass, jmethodID, ...); + void(JNICALL* SetIntField)(JNIEnv*, jobject, jfieldID, jint); - jfloat - (JNICALL *CallStaticFloatMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + void(JNICALL* SetLongField)(JNIEnv*, jobject, jfieldID, jlong); - jfloat - (JNICALL *CallStaticFloatMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + void(JNICALL* SetFloatField)(JNIEnv*, jobject, jfieldID, jfloat); - jdouble - (JNICALL *CallStaticDoubleMethod) - (JNIEnv*, jclass, jmethodID, ...); + void(JNICALL* SetDoubleField)(JNIEnv*, jobject, jfieldID, jdouble); - jdouble - (JNICALL *CallStaticDoubleMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jmethodID(JNICALL* GetStaticMethodID)(JNIEnv*, + jclass, + const char*, + const char*); - jdouble - (JNICALL *CallStaticDoubleMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jobject(JNICALL* CallStaticObjectMethod)(JNIEnv*, jclass, jmethodID, ...); - void - (JNICALL *CallStaticVoidMethod) - (JNIEnv*, jclass, jmethodID, ...); + jobject(JNICALL* CallStaticObjectMethodV)(JNIEnv*, + jclass, + jmethodID, + va_list); - void - (JNICALL *CallStaticVoidMethodV) - (JNIEnv*, jclass, jmethodID, va_list); + jobject(JNICALL* CallStaticObjectMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - void - (JNICALL *CallStaticVoidMethodA) - (JNIEnv*, jclass, jmethodID, const jvalue*); + jboolean(JNICALL* CallStaticBooleanMethod)(JNIEnv*, jclass, jmethodID, ...); - jfieldID - (JNICALL *GetStaticFieldID) - (JNIEnv*, jclass, const char*, const char*); + jboolean(JNICALL* CallStaticBooleanMethodV)(JNIEnv*, + jclass, + jmethodID, + va_list); - jobject - (JNICALL *GetStaticObjectField) - (JNIEnv*, jclass, jfieldID); + jboolean(JNICALL* CallStaticBooleanMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - jboolean - (JNICALL *GetStaticBooleanField) - (JNIEnv*, jclass, jfieldID); + jbyte(JNICALL* CallStaticByteMethod)(JNIEnv*, jclass, jmethodID, ...); - jbyte - (JNICALL *GetStaticByteField) - (JNIEnv*, jclass, jfieldID); + jbyte(JNICALL* CallStaticByteMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jchar - (JNICALL *GetStaticCharField) - (JNIEnv*, jclass, jfieldID); + jbyte(JNICALL* CallStaticByteMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - jshort - (JNICALL *GetStaticShortField) - (JNIEnv*, jclass, jfieldID); + jchar(JNICALL* CallStaticCharMethod)(JNIEnv*, jclass, jmethodID, ...); - jint - (JNICALL *GetStaticIntField) - (JNIEnv*, jclass, jfieldID); + jchar(JNICALL* CallStaticCharMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jlong - (JNICALL *GetStaticLongField) - (JNIEnv*, jclass, jfieldID); + jchar(JNICALL* CallStaticCharMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - jfloat - (JNICALL *GetStaticFloatField) - (JNIEnv*, jclass, jfieldID); + jshort(JNICALL* CallStaticShortMethod)(JNIEnv*, jclass, jmethodID, ...); - jdouble - (JNICALL *GetStaticDoubleField) - (JNIEnv*, jclass, jfieldID); + jshort(JNICALL* CallStaticShortMethodV)(JNIEnv*, jclass, jmethodID, va_list); - void - (JNICALL *SetStaticObjectField) - (JNIEnv*, jclass, jfieldID, jobject); + jshort(JNICALL* CallStaticShortMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - void - (JNICALL *SetStaticBooleanField) - (JNIEnv*, jclass, jfieldID, jboolean); + jint(JNICALL* CallStaticIntMethod)(JNIEnv*, jclass, jmethodID, ...); - void - (JNICALL *SetStaticByteField) - (JNIEnv*, jclass, jfieldID, jbyte); + jint(JNICALL* CallStaticIntMethodV)(JNIEnv*, jclass, jmethodID, va_list); - void - (JNICALL *SetStaticCharField) - (JNIEnv*, jclass, jfieldID, jchar); + jint(JNICALL* CallStaticIntMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - void - (JNICALL *SetStaticShortField) - (JNIEnv*, jclass, jfieldID, jshort); + jlong(JNICALL* CallStaticLongMethod)(JNIEnv*, jclass, jmethodID, ...); - void - (JNICALL *SetStaticIntField) - (JNIEnv*, jclass, jfieldID, jint); + jlong(JNICALL* CallStaticLongMethodV)(JNIEnv*, jclass, jmethodID, va_list); - void - (JNICALL *SetStaticLongField) - (JNIEnv*, jclass, jfieldID, jlong); + jlong(JNICALL* CallStaticLongMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - void - (JNICALL *SetStaticFloatField) - (JNIEnv*, jclass, jfieldID, jfloat); + jfloat(JNICALL* CallStaticFloatMethod)(JNIEnv*, jclass, jmethodID, ...); - void - (JNICALL *SetStaticDoubleField) - (JNIEnv*, jclass, jfieldID, jdouble); + jfloat(JNICALL* CallStaticFloatMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jstring - (JNICALL *NewString) - (JNIEnv*, const jchar*, jsize); + jfloat(JNICALL* CallStaticFloatMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - jsize - (JNICALL *GetStringLength) - (JNIEnv*, jstring); + jdouble(JNICALL* CallStaticDoubleMethod)(JNIEnv*, jclass, jmethodID, ...); - const jchar* - (JNICALL *GetStringChars) - (JNIEnv*, jstring, jboolean*); + jdouble(JNICALL* CallStaticDoubleMethodV)(JNIEnv*, + jclass, + jmethodID, + va_list); - void - (JNICALL *ReleaseStringChars) - (JNIEnv*, jstring, const jchar*); + jdouble(JNICALL* CallStaticDoubleMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - jstring - (JNICALL *NewStringUTF) - (JNIEnv*, const char*); + void(JNICALL* CallStaticVoidMethod)(JNIEnv*, jclass, jmethodID, ...); - jsize - (JNICALL *GetStringUTFLength) - (JNIEnv*, jstring); + void(JNICALL* CallStaticVoidMethodV)(JNIEnv*, jclass, jmethodID, va_list); - const char* - (JNICALL *GetStringUTFChars) - (JNIEnv*, jstring, jboolean*); + void(JNICALL* CallStaticVoidMethodA)(JNIEnv*, + jclass, + jmethodID, + const jvalue*); - void - (JNICALL *ReleaseStringUTFChars) - (JNIEnv*, jstring, const char*); + jfieldID(JNICALL* GetStaticFieldID)(JNIEnv*, + jclass, + const char*, + const char*); - jsize - (JNICALL *GetArrayLength) - (JNIEnv*, jarray); + jobject(JNICALL* GetStaticObjectField)(JNIEnv*, jclass, jfieldID); - jobjectArray - (JNICALL *NewObjectArray) - (JNIEnv*, jsize, jclass, jobject); + jboolean(JNICALL* GetStaticBooleanField)(JNIEnv*, jclass, jfieldID); - jobject - (JNICALL *GetObjectArrayElement) - (JNIEnv*, jobjectArray, jsize); + jbyte(JNICALL* GetStaticByteField)(JNIEnv*, jclass, jfieldID); - void - (JNICALL *SetObjectArrayElement) - (JNIEnv*, jobjectArray, jsize, jobject); + jchar(JNICALL* GetStaticCharField)(JNIEnv*, jclass, jfieldID); - jbooleanArray - (JNICALL *NewBooleanArray) - (JNIEnv*, jsize); + jshort(JNICALL* GetStaticShortField)(JNIEnv*, jclass, jfieldID); - jbyteArray - (JNICALL *NewByteArray) - (JNIEnv*, jsize); + jint(JNICALL* GetStaticIntField)(JNIEnv*, jclass, jfieldID); - jcharArray - (JNICALL *NewCharArray) - (JNIEnv*, jsize); + jlong(JNICALL* GetStaticLongField)(JNIEnv*, jclass, jfieldID); - jshortArray - (JNICALL *NewShortArray) - (JNIEnv*, jsize); + jfloat(JNICALL* GetStaticFloatField)(JNIEnv*, jclass, jfieldID); - jintArray - (JNICALL *NewIntArray) - (JNIEnv*, jsize); + jdouble(JNICALL* GetStaticDoubleField)(JNIEnv*, jclass, jfieldID); - jlongArray - (JNICALL *NewLongArray) - (JNIEnv*, jsize); + void(JNICALL* SetStaticObjectField)(JNIEnv*, jclass, jfieldID, jobject); - jfloatArray - (JNICALL *NewFloatArray) - (JNIEnv*, jsize); + void(JNICALL* SetStaticBooleanField)(JNIEnv*, jclass, jfieldID, jboolean); - jdoubleArray - (JNICALL *NewDoubleArray) - (JNIEnv*, jsize); + void(JNICALL* SetStaticByteField)(JNIEnv*, jclass, jfieldID, jbyte); - jboolean* - (JNICALL *GetBooleanArrayElements) - (JNIEnv*, jbooleanArray, jboolean*); + void(JNICALL* SetStaticCharField)(JNIEnv*, jclass, jfieldID, jchar); - jbyte* - (JNICALL *GetByteArrayElements) - (JNIEnv*, jbyteArray, jboolean*); + void(JNICALL* SetStaticShortField)(JNIEnv*, jclass, jfieldID, jshort); - jchar* - (JNICALL *GetCharArrayElements) - (JNIEnv*, jcharArray, jboolean*); + void(JNICALL* SetStaticIntField)(JNIEnv*, jclass, jfieldID, jint); - jshort* - (JNICALL *GetShortArrayElements) - (JNIEnv*, jshortArray, jboolean*); + void(JNICALL* SetStaticLongField)(JNIEnv*, jclass, jfieldID, jlong); - jint* - (JNICALL *GetIntArrayElements) - (JNIEnv*, jintArray, jboolean*); + void(JNICALL* SetStaticFloatField)(JNIEnv*, jclass, jfieldID, jfloat); - jlong* - (JNICALL *GetLongArrayElements) - (JNIEnv*, jlongArray, jboolean*); + void(JNICALL* SetStaticDoubleField)(JNIEnv*, jclass, jfieldID, jdouble); - jfloat* - (JNICALL *GetFloatArrayElements) - (JNIEnv*, jfloatArray, jboolean*); + jstring(JNICALL* NewString)(JNIEnv*, const jchar*, jsize); - jdouble* - (JNICALL *GetDoubleArrayElements) - (JNIEnv*, jdoubleArray, jboolean*); + jsize(JNICALL* GetStringLength)(JNIEnv*, jstring); - void - (JNICALL *ReleaseBooleanArrayElements) - (JNIEnv*, jbooleanArray, jboolean*, jint); + const jchar*(JNICALL* GetStringChars)(JNIEnv*, jstring, jboolean*); - void - (JNICALL *ReleaseByteArrayElements) - (JNIEnv*, jbyteArray, jbyte*, jint); + void(JNICALL* ReleaseStringChars)(JNIEnv*, jstring, const jchar*); - void - (JNICALL *ReleaseCharArrayElements) - (JNIEnv*, jcharArray, jchar*, jint); + jstring(JNICALL* NewStringUTF)(JNIEnv*, const char*); - void - (JNICALL *ReleaseShortArrayElements) - (JNIEnv*, jshortArray, jshort*, jint); + jsize(JNICALL* GetStringUTFLength)(JNIEnv*, jstring); - void - (JNICALL *ReleaseIntArrayElements) - (JNIEnv*, jintArray, jint*, jint); + const char*(JNICALL* GetStringUTFChars)(JNIEnv*, jstring, jboolean*); - void - (JNICALL *ReleaseLongArrayElements) - (JNIEnv*, jlongArray, jlong*, jint); + void(JNICALL* ReleaseStringUTFChars)(JNIEnv*, jstring, const char*); - void - (JNICALL *ReleaseFloatArrayElements) - (JNIEnv*, jfloatArray, jfloat*, jint); + jsize(JNICALL* GetArrayLength)(JNIEnv*, jarray); - void - (JNICALL *ReleaseDoubleArrayElements) - (JNIEnv*, jdoubleArray, jdouble*, jint); + jobjectArray(JNICALL* NewObjectArray)(JNIEnv*, jsize, jclass, jobject); - void - (JNICALL *GetBooleanArrayRegion) - (JNIEnv*, jbooleanArray, jsize, jsize, jboolean*); + jobject(JNICALL* GetObjectArrayElement)(JNIEnv*, jobjectArray, jsize); - void - (JNICALL *GetByteArrayRegion) - (JNIEnv*, jbyteArray, jsize, jsize, jbyte*); + void(JNICALL* SetObjectArrayElement)(JNIEnv*, jobjectArray, jsize, jobject); - void - (JNICALL *GetCharArrayRegion) - (JNIEnv*, jcharArray, jsize, jsize, jchar*); + jbooleanArray(JNICALL* NewBooleanArray)(JNIEnv*, jsize); - void - (JNICALL *GetShortArrayRegion) - (JNIEnv*, jshortArray, jsize, jsize, jshort*); + jbyteArray(JNICALL* NewByteArray)(JNIEnv*, jsize); - void - (JNICALL *GetIntArrayRegion) - (JNIEnv*, jintArray, jsize, jsize, jint*); + jcharArray(JNICALL* NewCharArray)(JNIEnv*, jsize); - void - (JNICALL *GetLongArrayRegion) - (JNIEnv*, jlongArray, jsize, jsize, jlong*); + jshortArray(JNICALL* NewShortArray)(JNIEnv*, jsize); - void - (JNICALL *GetFloatArrayRegion) - (JNIEnv*, jfloatArray, jsize, jsize, jfloat*); + jintArray(JNICALL* NewIntArray)(JNIEnv*, jsize); - void - (JNICALL *GetDoubleArrayRegion) - (JNIEnv*, jdoubleArray, jsize, jsize, jdouble*); + jlongArray(JNICALL* NewLongArray)(JNIEnv*, jsize); - void - (JNICALL *SetBooleanArrayRegion) - (JNIEnv*, jbooleanArray, jsize, jsize, const jboolean*); + jfloatArray(JNICALL* NewFloatArray)(JNIEnv*, jsize); - void - (JNICALL *SetByteArrayRegion) - (JNIEnv*, jbyteArray, jsize, jsize, const jbyte*); + jdoubleArray(JNICALL* NewDoubleArray)(JNIEnv*, jsize); - void - (JNICALL *SetCharArrayRegion) - (JNIEnv*, jcharArray, jsize, jsize, const jchar*); + jboolean*(JNICALL* GetBooleanArrayElements)(JNIEnv*, + jbooleanArray, + jboolean*); - void - (JNICALL *SetShortArrayRegion) - (JNIEnv*, jshortArray, jsize, jsize, const jshort*); + jbyte*(JNICALL* GetByteArrayElements)(JNIEnv*, jbyteArray, jboolean*); - void - (JNICALL *SetIntArrayRegion) - (JNIEnv*, jintArray, jsize, jsize, const jint*); + jchar*(JNICALL* GetCharArrayElements)(JNIEnv*, jcharArray, jboolean*); - void - (JNICALL *SetLongArrayRegion) - (JNIEnv*, jlongArray, jsize, jsize, const jlong*); + jshort*(JNICALL* GetShortArrayElements)(JNIEnv*, jshortArray, jboolean*); - void - (JNICALL *SetFloatArrayRegion) - (JNIEnv*, jfloatArray, jsize, jsize, const jfloat*); + jint*(JNICALL* GetIntArrayElements)(JNIEnv*, jintArray, jboolean*); - void - (JNICALL *SetDoubleArrayRegion) - (JNIEnv*, jdoubleArray, jsize, jsize, const jdouble*); + jlong*(JNICALL* GetLongArrayElements)(JNIEnv*, jlongArray, jboolean*); - jint - (JNICALL *RegisterNatives) - (JNIEnv*, jclass, const JNINativeMethod*, jint); + jfloat*(JNICALL* GetFloatArrayElements)(JNIEnv*, jfloatArray, jboolean*); - jint - (JNICALL *UnregisterNatives) - (JNIEnv*, jclass); + jdouble*(JNICALL* GetDoubleArrayElements)(JNIEnv*, jdoubleArray, jboolean*); - jint - (JNICALL *MonitorEnter) - (JNIEnv*, jobject); + void(JNICALL* ReleaseBooleanArrayElements)(JNIEnv*, + jbooleanArray, + jboolean*, + jint); - jint - (JNICALL *MonitorExit) - (JNIEnv*, jobject); + void(JNICALL* ReleaseByteArrayElements)(JNIEnv*, jbyteArray, jbyte*, jint); - jint - (JNICALL *GetJavaVM) - (JNIEnv*, JavaVM**); + void(JNICALL* ReleaseCharArrayElements)(JNIEnv*, jcharArray, jchar*, jint); - void - (JNICALL *GetStringRegion) - (JNIEnv*, jstring, jsize, jsize, jchar*); + void(JNICALL* ReleaseShortArrayElements)(JNIEnv*, jshortArray, jshort*, jint); - void - (JNICALL *GetStringUTFRegion) - (JNIEnv*, jstring, jsize, jsize, char*); + void(JNICALL* ReleaseIntArrayElements)(JNIEnv*, jintArray, jint*, jint); - void* - (JNICALL *GetPrimitiveArrayCritical) - (JNIEnv*, jarray, jboolean*); + void(JNICALL* ReleaseLongArrayElements)(JNIEnv*, jlongArray, jlong*, jint); - void - (JNICALL *ReleasePrimitiveArrayCritical) - (JNIEnv*, jarray, void*, jint); + void(JNICALL* ReleaseFloatArrayElements)(JNIEnv*, jfloatArray, jfloat*, jint); - const jchar* - (JNICALL *GetStringCritical) - (JNIEnv*, jstring, jboolean*); + void(JNICALL* ReleaseDoubleArrayElements)(JNIEnv*, + jdoubleArray, + jdouble*, + jint); - void - (JNICALL *ReleaseStringCritical) - (JNIEnv*, jstring, const jchar*); + void(JNICALL* GetBooleanArrayRegion)(JNIEnv*, + jbooleanArray, + jsize, + jsize, + jboolean*); - jweak - (JNICALL *NewWeakGlobalRef) - (JNIEnv*, jobject); + void(JNICALL* GetByteArrayRegion)(JNIEnv*, jbyteArray, jsize, jsize, jbyte*); - void - (JNICALL *DeleteWeakGlobalRef) - (JNIEnv*, jweak); + void(JNICALL* GetCharArrayRegion)(JNIEnv*, jcharArray, jsize, jsize, jchar*); - jboolean - (JNICALL *ExceptionCheck) - (JNIEnv*); + void(JNICALL* GetShortArrayRegion)(JNIEnv*, + jshortArray, + jsize, + jsize, + jshort*); - jobject - (JNICALL *NewDirectByteBuffer) - (JNIEnv*, void*, jlong); + void(JNICALL* GetIntArrayRegion)(JNIEnv*, jintArray, jsize, jsize, jint*); - void* - (JNICALL *GetDirectBufferAddress) - (JNIEnv* env, jobject); + void(JNICALL* GetLongArrayRegion)(JNIEnv*, jlongArray, jsize, jsize, jlong*); - jlong - (JNICALL *GetDirectBufferCapacity) - (JNIEnv*, jobject); + void(JNICALL* GetFloatArrayRegion)(JNIEnv*, + jfloatArray, + jsize, + jsize, + jfloat*); + void(JNICALL* GetDoubleArrayRegion)(JNIEnv*, + jdoubleArray, + jsize, + jsize, + jdouble*); + + void(JNICALL* SetBooleanArrayRegion)(JNIEnv*, + jbooleanArray, + jsize, + jsize, + const jboolean*); + + void(JNICALL* SetByteArrayRegion)(JNIEnv*, + jbyteArray, + jsize, + jsize, + const jbyte*); + + void(JNICALL* SetCharArrayRegion)(JNIEnv*, + jcharArray, + jsize, + jsize, + const jchar*); + + void(JNICALL* SetShortArrayRegion)(JNIEnv*, + jshortArray, + jsize, + jsize, + const jshort*); + + void(JNICALL* SetIntArrayRegion)(JNIEnv*, + jintArray, + jsize, + jsize, + const jint*); + + void(JNICALL* SetLongArrayRegion)(JNIEnv*, + jlongArray, + jsize, + jsize, + const jlong*); + + void(JNICALL* SetFloatArrayRegion)(JNIEnv*, + jfloatArray, + jsize, + jsize, + const jfloat*); + + void(JNICALL* SetDoubleArrayRegion)(JNIEnv*, + jdoubleArray, + jsize, + jsize, + const jdouble*); + + jint(JNICALL* RegisterNatives)(JNIEnv*, jclass, const JNINativeMethod*, jint); + + jint(JNICALL* UnregisterNatives)(JNIEnv*, jclass); + + jint(JNICALL* MonitorEnter)(JNIEnv*, jobject); + + jint(JNICALL* MonitorExit)(JNIEnv*, jobject); + + jint(JNICALL* GetJavaVM)(JNIEnv*, JavaVM**); + + void(JNICALL* GetStringRegion)(JNIEnv*, jstring, jsize, jsize, jchar*); + + void(JNICALL* GetStringUTFRegion)(JNIEnv*, jstring, jsize, jsize, char*); + + void*(JNICALL* GetPrimitiveArrayCritical)(JNIEnv*, jarray, jboolean*); + + void(JNICALL* ReleasePrimitiveArrayCritical)(JNIEnv*, jarray, void*, jint); + + const jchar*(JNICALL* GetStringCritical)(JNIEnv*, jstring, jboolean*); + + void(JNICALL* ReleaseStringCritical)(JNIEnv*, jstring, const jchar*); + + jweak(JNICALL* NewWeakGlobalRef)(JNIEnv*, jobject); + + void(JNICALL* DeleteWeakGlobalRef)(JNIEnv*, jweak); + + jboolean(JNICALL* ExceptionCheck)(JNIEnv*); + + jobject(JNICALL* NewDirectByteBuffer)(JNIEnv*, void*, jlong); + + void*(JNICALL* GetDirectBufferAddress)(JNIEnv* env, jobject); + + jlong(JNICALL* GetDirectBufferCapacity)(JNIEnv*, jobject); }; -inline void -atomicOr(uint32_t* p, int v) +inline void atomicOr(uint32_t* p, int v) { - for (uint32_t old = *p; - not atomicCompareAndSwap32(p, old, old | v); - old = *p) - { } + for (uint32_t old = *p; not atomicCompareAndSwap32(p, old, old | v); + old = *p) { + } } -inline void -atomicAnd(uint32_t* p, int v) +inline void atomicAnd(uint32_t* p, int v) { - for (uint32_t old = *p; - not atomicCompareAndSwap32(p, old, old & v); - old = *p) - { } + for (uint32_t old = *p; not atomicCompareAndSwap32(p, old, old & v); + old = *p) { + } } -inline int -strcmp(const int8_t* a, const int8_t* b) +inline int strcmp(const int8_t* a, const int8_t* b) { return ::strcmp(reinterpret_cast(a), reinterpret_cast(b)); } -void -noop(); +void noop(); class Reference { public: - Reference(object target, Reference** handle, bool weak): - target(target), - next(*handle), - handle(handle), - count(0), - weak(weak) + Reference(object target, Reference** handle, bool weak) + : target(target), next(*handle), handle(handle), count(0), weak(weak) { if (next) { next->handle = &next; @@ -1181,56 +958,58 @@ class Reference { class Classpath; -class Machine { +class Gc { public: enum Type { #include "type-enums.cpp" }; +}; +class GcObject { + public: + template + T* as(Thread* t); + + template + bool isa(Thread* t); + + protected: + template + T& field_at(size_t offset) + { + return *reinterpret_cast(reinterpret_cast(this) + offset); + } +}; + +class GcFinalizer; +class GcClassLoader; +class GcJreference; +class GcArray; +class GcThrowable; +class GcRoots; + +class Machine { + public: enum AllocationType { MovableAllocation, FixedAllocation, ImmortalAllocation }; - enum Root { - BootLoader, - AppLoader, - BootstrapClassMap, - PackageMap, - FindLoadedClassMethod, - LoadClassMethod, - MonitorMap, - StringMap, - ByteArrayMap, - PoolMap, - ClassRuntimeDataTable, - MethodRuntimeDataTable, - JNIMethodTable, - JNIFieldTable, - ShutdownHooks, - FinalizerThread, - ObjectsToFinalize, - ObjectsToClean, - NullPointerException, - ArithmeticException, - ArrayIndexOutOfBoundsException, - OutOfMemoryError, - Shutdown, - VirtualFileFinders, - VirtualFiles, - ArrayInterfaceTable, - ThreadTerminated - }; + Machine(System* system, + Heap* heap, + Finder* bootFinder, + Finder* appFinder, + Processor* processor, + Classpath* classpath, + const char** properties, + unsigned propertyCount, + const char** arguments, + unsigned argumentCount, + unsigned stackSizeInBytes); - static const unsigned RootCount = ThreadTerminated + 1; - - Machine(System* system, Heap* heap, Finder* bootFinder, Finder* appFinder, - Processor* processor, Classpath* classpath, const char** properties, - unsigned propertyCount, const char** arguments, - unsigned argumentCount, unsigned stackSizeInBytes); - - ~Machine() { + ~Machine() + { dispose(); } @@ -1267,13 +1046,13 @@ class Machine { System::Library* libraries; FILE* errorLog; BootImage* bootimage; - object types; - object roots; - object finalizers; - object tenuredFinalizers; - object finalizeQueue; - object weakReferences; - object tenuredWeakReferences; + GcArray* types; + GcRoots* roots; + GcFinalizer* finalizers; + GcFinalizer* tenuredFinalizers; + GcFinalizer* finalizeQueue; + GcJreference* weakReferences; + GcJreference* tenuredWeakReferences; bool unsafe; bool collecting; bool triedBuiltinOnLoad; @@ -1286,44 +1065,39 @@ class Machine { unsigned bootimageSize; }; -void -printTrace(Thread* t, object exception); +void printTrace(Thread* t, GcThrowable* exception); -uint8_t& -threadInterrupted(Thread* t, object thread); - -void -enterActiveState(Thread* t); +void enterActiveState(Thread* t); #ifdef VM_STRESS inline void stress(Thread* t); -#else // not VM_STRESS +#else // not VM_STRESS #define stress(t) -#endif // not VM_STRESS +#endif // not VM_STRESS -uint64_t -runThread(Thread*, uintptr_t*); +uint64_t runThread(Thread*, uintptr_t*); -uint64_t -run(Thread* t, uint64_t (*function)(Thread*, uintptr_t*), - uintptr_t* arguments); +uint64_t run(Thread* t, + uint64_t (*function)(Thread*, uintptr_t*), + uintptr_t* arguments); -void -checkDaemon(Thread* t); +void checkDaemon(Thread* t); -object& -root(Thread* t, Machine::Root root); +GcRoots* roots(Thread* t); -extern "C" uint64_t -vmRun(uint64_t (*function)(Thread*, uintptr_t*), uintptr_t* arguments, - void* checkpoint); +extern "C" uint64_t vmRun(uint64_t (*function)(Thread*, uintptr_t*), + uintptr_t* arguments, + void* checkpoint); -extern "C" void -vmRun_returnAddress(); +extern "C" void vmRun_returnAddress(); + +class GcThread; +class GcThrowable; +class GcString; class Thread { public: @@ -1348,11 +1122,13 @@ class Thread { class Protector { public: - Protector(Thread* t): t(t), next(t->protector) { + Protector(Thread* t) : t(t), next(t->protector) + { t->protector = this; } - ~Protector() { + ~Protector() + { t->protector = next; } @@ -1362,20 +1138,24 @@ class Thread { Protector* next; }; - class SingleProtector: public Protector { + class SingleProtector : public Protector { public: - SingleProtector(Thread* t, object* p): Protector(t), p(p) { } + SingleProtector(Thread* t, void* p) : Protector(t), p(p) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(p); } - object* p; + void* p; }; class Resource { public: - Resource(Thread* t, Resource* next): t(t), next(next) { + Resource(Thread* t, Resource* next) : t(t), next(next) + { t->resource = this; } @@ -1385,45 +1165,49 @@ class Thread { Resource* next; }; - class AutoResource: public Resource { + class AutoResource : public Resource { public: - AutoResource(Thread* t): Resource(t, t->resource) { } + AutoResource(Thread* t) : Resource(t, t->resource) + { + } - ~AutoResource() { + ~AutoResource() + { t->resource = next; } virtual void release() = 0; - }; - class ClassInitStack: public AutoResource { + class ClassInitStack : public AutoResource { public: - ClassInitStack(Thread* t, object class_): - AutoResource(t), - next(t->classInitStack), - class_(class_), - protector(t, &(this->class_)) + ClassInitStack(Thread* t, GcClass* class_) + : AutoResource(t), + next(t->classInitStack), + class_(class_), + protector(t, &(this->class_)) { t->classInitStack = this; } - ~ClassInitStack() { + ~ClassInitStack() + { t->classInitStack = next; } - virtual void release() { + virtual void release() + { this->ClassInitStack::~ClassInitStack(); } ClassInitStack* next; - object class_; + GcClass* class_; SingleProtector protector; }; - class LibraryLoadStack: public AutoResource { + class LibraryLoadStack : public AutoResource { public: - LibraryLoadStack(Thread* t, object classLoader) + LibraryLoadStack(Thread* t, GcClassLoader* classLoader) : AutoResource(t), next(t->libraryLoadStack), classLoader(classLoader), @@ -1432,32 +1216,35 @@ class Thread { t->libraryLoadStack = this; } - ~LibraryLoadStack() { + ~LibraryLoadStack() + { t->libraryLoadStack = next; } - virtual void release() { + virtual void release() + { this->LibraryLoadStack::~LibraryLoadStack(); } LibraryLoadStack* next; - object classLoader; + GcClassLoader* classLoader; SingleProtector protector; }; class Checkpoint { public: - Checkpoint(Thread* t): - t(t), - next(t->checkpoint), - resource(t->resource), - protector(t->protector), - noThrow(false) + Checkpoint(Thread* t) + : t(t), + next(t->checkpoint), + resource(t->resource), + protector(t->protector), + noThrow(false) { t->checkpoint = this; } - ~Checkpoint() { + ~Checkpoint() + { t->checkpoint = next; } @@ -1470,14 +1257,14 @@ class Thread { bool noThrow; }; - class RunCheckpoint: public Checkpoint { + class RunCheckpoint : public Checkpoint { public: - RunCheckpoint(Thread* t): - Checkpoint(t), - stack(0) - { } + RunCheckpoint(Thread* t) : Checkpoint(t), stack(0) + { + } - virtual void unwind() { + virtual void unwind() + { void* stack = this->stack; this->stack = 0; expect(t->m->system, stack); @@ -1487,38 +1274,27 @@ class Thread { void* stack; }; - class Runnable: public System::Runnable { + class Runnable : public System::Runnable { public: - Runnable(Thread* t): t(t) { } + Runnable(Thread* t) : t(t) + { + } - virtual void attach(System::Thread* st) { + virtual void attach(System::Thread* st) + { t->systemThread = st; } - virtual void run() { - enterActiveState(t); + virtual void run(); - vm::run(t, runThread, 0); + virtual bool interrupted(); - if (t->exception and t->exception != root(t, Machine::Shutdown)) { - printTrace(t, t->exception); - } - - t->exit(); - } - - virtual bool interrupted() { - return t->javaThread and threadInterrupted(t, t->javaThread); - } - - virtual void setInterrupted(bool v) { - threadInterrupted(t, t->javaThread) = v; - } + virtual void setInterrupted(bool v); Thread* t; }; - Thread(Machine* m, object javaThread, Thread* parent); + Thread(Machine* m, GcThread* javaThread, Thread* parent); void init(); void exit(); @@ -1534,8 +1310,8 @@ class Thread { unsigned criticalLevel; System::Thread* systemThread; System::Monitor* lock; - object javaThread; - object exception; + GcThread* javaThread; + GcThrowable* exception; unsigned heapIndex; unsigned heapOffset; Protector* protector; @@ -1551,90 +1327,81 @@ class Thread { unsigned flags; }; +class GcJfield; + class Classpath { public: - virtual object - makeJclass(Thread* t, object class_) = 0; + virtual GcJclass* makeJclass(Thread* t, GcClass* class_) = 0; - virtual object - makeString(Thread* t, object array, int32_t offset, int32_t length) = 0; + virtual GcString* makeString(Thread* t, + object array, + int32_t offset, + int32_t length) = 0; - virtual object - makeThread(Thread* t, Thread* parent) = 0; + virtual GcThread* makeThread(Thread* t, Thread* parent) = 0; - virtual object - makeJMethod(Thread* t, object vmMethod) = 0; + virtual object makeJMethod(Thread* t, GcMethod* vmMethod) = 0; - virtual object - getVMMethod(Thread* t, object jmethod) = 0; + virtual GcMethod* getVMMethod(Thread* t, object jmethod) = 0; - virtual object - makeJField(Thread* t, object vmField) = 0; + virtual object makeJField(Thread* t, GcField* vmField) = 0; - virtual object - getVMField(Thread* t, object jfield) = 0; + virtual GcField* getVMField(Thread* t, GcJfield* jfield) = 0; - virtual void - clearInterrupted(Thread* t) = 0; + virtual void clearInterrupted(Thread* t) = 0; - virtual void - runThread(Thread* t) = 0; + virtual void runThread(Thread* t) = 0; - virtual void - resolveNative(Thread* t, object method) = 0; + virtual void resolveNative(Thread* t, GcMethod* method) = 0; - virtual void - interceptMethods(Thread* t) = 0; + virtual void interceptMethods(Thread* t) = 0; - virtual void - preBoot(Thread* t) = 0; + virtual void preBoot(Thread* t) = 0; virtual bool mayInitClasses() = 0; - virtual void - boot(Thread* t) = 0; + virtual void boot(Thread* t) = 0; - virtual const char* - bootClasspath() = 0; + virtual const char* bootClasspath() = 0; - virtual object - makeDirectByteBuffer(Thread* t, void* p, jlong capacity) = 0; + virtual object makeDirectByteBuffer(Thread* t, void* p, jlong capacity) = 0; - virtual void* - getDirectBufferAddress(Thread* t, object buffer) = 0; + virtual void* getDirectBufferAddress(Thread* t, object buffer) = 0; - virtual int64_t - getDirectBufferCapacity(Thread* t, object buffer) = 0; + virtual int64_t getDirectBufferCapacity(Thread* t, object buffer) = 0; - virtual bool - canTailCall(Thread* t, object caller, object calleeClassName, - object calleeMethodName, object calleeMethodSpec) = 0; + virtual bool canTailCall(Thread* t, + GcMethod* caller, + GcByteArray* calleeClassName, + GcByteArray* calleeMethodName, + GcByteArray* calleeMethodSpec) = 0; - virtual object libraryClassLoader(Thread* t, object caller) = 0; + virtual GcClassLoader* libraryClassLoader(Thread* t, GcMethod* caller) = 0; - virtual void - shutDown(Thread* t) = 0; + virtual void shutDown(Thread* t) = 0; - virtual void - dispose() = 0; + virtual void dispose() = 0; }; #ifdef _MSC_VER template -class ThreadRuntimeArray: public Thread::AutoResource { +class ThreadRuntimeArray : public Thread::AutoResource { public: - ThreadRuntimeArray(Thread* t, unsigned size): - AutoResource(t), - body(static_cast(t->m->heap->allocate(size * sizeof(T)))), - size(size) - { } + ThreadRuntimeArray(Thread* t, unsigned size) + : AutoResource(t), + body(static_cast(t->m->heap->allocate(size * sizeof(T)))), + size(size) + { + } - ~ThreadRuntimeArray() { + ~ThreadRuntimeArray() + { t->m->heap->free(body, size * sizeof(T)); } - virtual void release() { + virtual void release() + { ThreadRuntimeArray::~ThreadRuntimeArray(); } @@ -1642,54 +1409,55 @@ class ThreadRuntimeArray: public Thread::AutoResource { unsigned size; }; -# define THREAD_RUNTIME_ARRAY(thread, type, name, size) \ +#define THREAD_RUNTIME_ARRAY(thread, type, name, size) \ ThreadRuntimeArray name(thread, size); -#else // not _MSC_VER +#else // not _MSC_VER -# define THREAD_RUNTIME_ARRAY(thread, type, name, size) \ - type name##_body[size]; +#define THREAD_RUNTIME_ARRAY(thread, type, name, size) type name##_body[size]; -#endif // not _MSC_VER +#endif // not _MSC_VER -Classpath* -makeClasspath(System* system, Allocator* allocator, const char* javaHome, - const char* embedPrefix); +Classpath* makeClasspath(System* system, + Allocator* allocator, + const char* javaHome, + const char* embedPrefix); -typedef uint64_t (JNICALL *FastNativeFunction)(Thread*, object, uintptr_t*); +typedef uint64_t(JNICALL* FastNativeFunction)(Thread*, GcMethod*, uintptr_t*); -inline object -objectClass(Thread*, object o) +inline GcClass* objectClass(Thread*, object o) { - return maskAlignedPointer(fieldAtOffset(o, 0)); + return reinterpret_cast( + maskAlignedPointer(fieldAtOffset(o, 0))); } -inline unsigned -stackSizeInWords(Thread* t) +inline unsigned stackSizeInWords(Thread* t) { return t->m->stackSizeInBytes / BytesPerWord; } -void -enter(Thread* t, Thread::State state); +void enter(Thread* t, Thread::State state); -inline void -enterActiveState(Thread* t) +inline void enterActiveState(Thread* t) { enter(t, Thread::ActiveState); } -class StateResource: public Thread::AutoResource { +class StateResource : public Thread::AutoResource { public: - StateResource(Thread* t, Thread::State state): - AutoResource(t), oldState(t->state) + StateResource(Thread* t, Thread::State state) + : AutoResource(t), oldState(t->state) { enter(t, state); } - ~StateResource() { enter(t, oldState); } + ~StateResource() + { + enter(t, oldState); + } - virtual void release() { + virtual void release() + { this->StateResource::~StateResource(); } @@ -1697,8 +1465,7 @@ class StateResource: public Thread::AutoResource { Thread::State oldState; }; -inline void -dispose(Thread* t, Reference* r) +inline void dispose(Thread* t, Reference* r) { *(r->handle) = r->next; if (r->next) { @@ -1707,52 +1474,44 @@ dispose(Thread* t, Reference* r) t->m->heap->free(r, sizeof(*r)); } -inline void -acquire(Thread*, Reference* r) +inline void acquire(Thread*, Reference* r) { - ++ r->count; + ++r->count; } -inline void -release(Thread* t, Reference* r) +inline void release(Thread* t, Reference* r) { - if ((-- r->count) == 0) { + if ((--r->count) == 0) { dispose(t, r); } } -void -collect(Thread* t, Heap::CollectionType type, int pendingAllocation = 0); +void collect(Thread* t, Heap::CollectionType type, int pendingAllocation = 0); -void -shutDown(Thread* t); +void shutDown(Thread* t); #ifdef VM_STRESS -inline void -stress(Thread* t) +inline void stress(Thread* t) { if ((not t->m->unsafe) and (t->flags & (Thread::StressFlag | Thread::TracingFlag)) == 0 - and t->state != Thread::NoState - and t->state != Thread::IdleState) - { + and t->state != Thread::NoState and t->state != Thread::IdleState) { atomicOr(&(t->flags), Thread::StressFlag); -# ifdef VM_STRESS_MAJOR +#ifdef VM_STRESS_MAJOR collect(t, Heap::MajorCollection); -# else // not VM_STRESS_MAJOR +#else // not VM_STRESS_MAJOR collect(t, Heap::MinorCollection); -# endif // not VM_STRESS_MAJOR +#endif // not VM_STRESS_MAJOR atomicAnd(&(t->flags), ~Thread::StressFlag); } } -#endif // not VM_STRESS +#endif // not VM_STRESS -inline void -acquire(Thread* t, System::Monitor* m) +inline void acquire(Thread* t, System::Monitor* m) { if (not m->tryAcquire(t->systemThread)) { ENTER(t, Thread::IdleState); @@ -1762,25 +1521,25 @@ acquire(Thread* t, System::Monitor* m) stress(t); } -inline void -release(Thread* t, System::Monitor* m) +inline void release(Thread* t, System::Monitor* m) { m->release(t->systemThread); } -class MonitorResource: public Thread::AutoResource { +class MonitorResource : public Thread::AutoResource { public: - MonitorResource(Thread* t, System::Monitor* m): - AutoResource(t), m(m) + MonitorResource(Thread* t, System::Monitor* m) : AutoResource(t), m(m) { acquire(t, m); } - ~MonitorResource() { + ~MonitorResource() + { vm::release(t, m); } - virtual void release() { + virtual void release() + { this->MonitorResource::~MonitorResource(); } @@ -1788,20 +1547,22 @@ class MonitorResource: public Thread::AutoResource { System::Monitor* m; }; -class RawMonitorResource: public Thread::Resource { +class RawMonitorResource : public Thread::Resource { public: - RawMonitorResource(Thread* t, System::Monitor* m): - Resource(t, t->resource), m(m) + RawMonitorResource(Thread* t, System::Monitor* m) + : Resource(t, t->resource), m(m) { m->acquire(t->systemThread); } - ~RawMonitorResource() { + ~RawMonitorResource() + { t->resource = next; vm::release(t, m); } - virtual void release() { + virtual void release() + { this->RawMonitorResource::~RawMonitorResource(); } @@ -1809,16 +1570,15 @@ class RawMonitorResource: public Thread::Resource { System::Monitor* m; }; -inline Aborter* getAborter(Thread* t) { +inline Aborter* getAborter(Thread* t) +{ return t->m->system; } -inline bool -ensure(Thread* t, unsigned sizeInBytes) +inline bool ensure(Thread* t, unsigned sizeInBytes) { if (t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) - > ThreadHeapSizeInWords) - { + > ThreadHeapSizeInWords) { if (sizeInBytes <= ThreadBackupHeapSizeInBytes) { expect(t, (t->flags & Thread::UseBackupHeapFlag) == 0); @@ -1833,78 +1593,78 @@ ensure(Thread* t, unsigned sizeInBytes) } } -object -allocate2(Thread* t, unsigned sizeInBytes, bool objectMask); +object allocate2(Thread* t, unsigned sizeInBytes, bool objectMask); -object -allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, - unsigned sizeInBytes, bool objectMask); +object allocate3(Thread* t, + Allocator* allocator, + Machine::AllocationType type, + unsigned sizeInBytes, + bool objectMask); -inline object -allocateSmall(Thread* t, unsigned sizeInBytes) +inline object allocateSmall(Thread* t, unsigned sizeInBytes) { - assert(t, t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) - <= ThreadHeapSizeInWords); + assertT(t, + t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) + <= ThreadHeapSizeInWords); object o = reinterpret_cast(t->heap + t->heapIndex); t->heapIndex += ceilingDivide(sizeInBytes, BytesPerWord); return o; } -inline object -allocate(Thread* t, unsigned sizeInBytes, bool objectMask) +inline object allocate(Thread* t, unsigned sizeInBytes, bool objectMask) { stress(t); if (UNLIKELY(t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) - > ThreadHeapSizeInWords - or t->m->exclusive)) - { + > ThreadHeapSizeInWords or t->m->exclusive)) { return allocate2(t, sizeInBytes, objectMask); } else { - assert(t, t->criticalLevel == 0); + assertT(t, t->criticalLevel == 0); return allocateSmall(t, sizeInBytes); } } -inline void -mark(Thread* t, object o, unsigned offset, unsigned count) +inline void mark(Thread* t, object o, unsigned offset, unsigned count) { t->m->heap->mark(o, offset / BytesPerWord, count); } -inline void -mark(Thread* t, object o, unsigned offset) +inline void mark(Thread* t, object o, unsigned offset) { t->m->heap->mark(o, offset / BytesPerWord, 1); } -inline void -set(Thread* t, object target, unsigned offset, object value) +inline void setField(Thread* t, object target, unsigned offset, object value) { fieldAtOffset(target, offset) = value; mark(t, target, offset); } -inline void -setObjectClass(Thread*, object o, object value) +inline void setObject(Thread* t, + GcObject* target, + unsigned offset, + GcObject* value) { - fieldAtOffset(o, 0) - = reinterpret_cast - (reinterpret_cast(value) - | (reinterpret_cast - (fieldAtOffset(o, 0)) & (~PointerMask))); + setField(t, target, offset, value); } -inline const char* -findProperty(Machine* m, const char* name) +inline void setObjectClass(Thread*, object o, GcClass* c) +{ + fieldAtOffset(o, 0) = reinterpret_cast( + reinterpret_cast(c) + | (reinterpret_cast(fieldAtOffset(o, 0)) + & (~PointerMask))); +} + +inline const char* findProperty(Machine* m, const char* name) { for (unsigned i = 0; i < m->propertyCount; ++i) { const char* p = m->properties[i]; const char* n = name; while (*p and *p != '=' and *n and *p == *n) { - ++ p; - ++ n; + ++p; + ++n; } if (*p == '=' and *n == 0) { return p + 1; @@ -1913,46 +1673,106 @@ findProperty(Machine* m, const char* name) return 0; } -inline const char* -findProperty(Thread* t, const char* name) +inline const char* findProperty(Thread* t, const char* name) { return findProperty(t->m, name); } -object& -arrayBodyUnsafe(Thread*, object, unsigned); +object arrayBodyUnsafe(Thread*, GcArray*, unsigned); -bool -instanceOf(Thread* t, object class_, object o); +bool instanceOf(Thread* t, GcClass* class_, object o); + +template +T* GcObject::as(Thread* t UNUSED) +{ + if (this == 0) { + return 0; + } + assertT(t, + t->m->unsafe || instanceOf(t, + reinterpret_cast(arrayBodyUnsafe( + t, t->m->types, T::Type)), + this)); + return static_cast(this); +} + +template +bool GcObject::isa(Thread* t) +{ + return instanceOf( + t, + reinterpret_cast(arrayBodyUnsafe(t, t->m->types, T::Type)), + this); +} + +template +T* cast(Thread* t UNUSED, object o) +{ + if (o == 0) { + return 0; + } + assertT(t, + t->m->unsafe || instanceOf(t, + reinterpret_cast(arrayBodyUnsafe( + t, t->m->types, T::Type)), + o)); + return reinterpret_cast(o); +} #include "type-declarations.cpp" -inline uint64_t -runRaw(Thread* t, - uint64_t (*function)(Thread*, uintptr_t*), uintptr_t* arguments) +inline object arrayBodyUnsafe(Thread*, GcArray* a, unsigned index) +{ + return a->body()[index]; +} + +inline void Thread::Runnable::run() +{ + enterActiveState(t); + + vm::run(t, runThread, 0); + + if (t->exception and t->exception != roots(t)->shutdownInProgress()) { + printTrace(t, t->exception); + } + + t->exit(); +} + +inline bool Thread::Runnable::interrupted() +{ + return t->javaThread and t->javaThread->interrupted(); +} + +inline void Thread::Runnable::setInterrupted(bool v) +{ + t->javaThread->interrupted() = v; +} + +inline uint64_t runRaw(Thread* t, + uint64_t (*function)(Thread*, uintptr_t*), + uintptr_t* arguments) { Thread::RunCheckpoint checkpoint(t); return vmRun(function, arguments, &checkpoint); } -inline uint64_t -run(Thread* t, uint64_t (*function)(Thread*, uintptr_t*), uintptr_t* arguments) +inline uint64_t run(Thread* t, + uint64_t (*function)(Thread*, uintptr_t*), + uintptr_t* arguments) { ENTER(t, Thread::ActiveState); return runRaw(t, function, arguments); } -inline void -runJavaThread(Thread* t) +inline void runJavaThread(Thread* t) { t->m->classpath->runThread(t); } -void -runFinalizeThread(Thread* t); +void runFinalizeThread(Thread* t); -inline uint64_t -runThread(Thread* t, uintptr_t*) +inline uint64_t runThread(Thread* t, uintptr_t*) { t->m->localThread->set(t); @@ -1967,63 +1787,62 @@ runThread(Thread* t, uintptr_t*) return 1; } -inline bool -startThread(Thread* t, Thread* p) +inline bool startThread(Thread* t, Thread* p) { p->flags |= Thread::JoinFlag; return t->m->system->success(t->m->system->start(&(p->runnable))); } -inline void -addThread(Thread* t, Thread* p) +inline void addThread(Thread* t, Thread* p) { ACQUIRE_RAW(t, t->m->stateLock); - assert(t, p->state == Thread::NoState); - expect(t, t->state == Thread::ActiveState || t->state == Thread::ExclusiveState || t->state == Thread::NoState); + assertT(t, p->state == Thread::NoState); + expect(t, + t->state == Thread::ActiveState || t->state == Thread::ExclusiveState + || t->state == Thread::NoState); p->state = Thread::IdleState; - ++ t->m->threadCount; - ++ t->m->liveCount; + ++t->m->threadCount; + ++t->m->liveCount; p->peer = p->parent->child; p->parent->child = p; if (p->javaThread) { - threadPeer(t, p->javaThread) = reinterpret_cast(p); + p->javaThread->peer() = reinterpret_cast(p); } } -inline void -removeThread(Thread* t, Thread* p) +inline void removeThread(Thread* t, Thread* p) { ACQUIRE_RAW(t, t->m->stateLock); - assert(t, p->state == Thread::IdleState); + assertT(t, p->state == Thread::IdleState); - -- t->m->liveCount; - -- t->m->threadCount; + --t->m->liveCount; + --t->m->threadCount; t->m->stateLock->notifyAll(t->systemThread); p->parent->child = p->peer; if (p->javaThread) { - threadPeer(t, p->javaThread) = 0; + p->javaThread->peer() = 0; } p->dispose(); } -inline Thread* -startThread(Thread* t, object javaThread) +inline Thread* startThread(Thread* t, GcThread* javaThread) { - { PROTECT(t, javaThread); - + { + PROTECT(t, javaThread); + stress(t); ACQUIRE_RAW(t, t->m->stateLock); - + if (t->m->threadCount > t->m->liveCount + ZombieCollectionThreshold) { collect(t, Heap::MinorCollection); } @@ -2041,37 +1860,34 @@ startThread(Thread* t, object javaThread) } } -inline void -registerDaemon(Thread* t) +inline void registerDaemon(Thread* t) { ACQUIRE_RAW(t, t->m->stateLock); atomicOr(&(t->flags), Thread::DaemonFlag); - ++ t->m->daemonCount; - + ++t->m->daemonCount; + t->m->stateLock->notifyAll(t->systemThread); } -inline void -checkDaemon(Thread* t) +inline void checkDaemon(Thread* t) { - if (threadDaemon(t, t->javaThread)) { + if (t->javaThread->daemon()) { registerDaemon(t); } } -inline uint64_t -initAttachedThread(Thread* t, uintptr_t* arguments) +inline uint64_t initAttachedThread(Thread* t, uintptr_t* arguments) { bool daemon = arguments[0]; t->javaThread = t->m->classpath->makeThread(t, t->m->rootThread); - threadPeer(t, t->javaThread) = reinterpret_cast(t); + t->javaThread->peer() = reinterpret_cast(t); if (daemon) { - threadDaemon(t, t->javaThread) = true; + t->javaThread->daemon() = true; registerDaemon(t); } @@ -2081,8 +1897,7 @@ initAttachedThread(Thread* t, uintptr_t* arguments) return 1; } -inline Thread* -attachThread(Machine* m, bool daemon) +inline Thread* attachThread(Machine* m, bool daemon) { Thread* t = m->processor->makeThread(m, 0, m->rootThread); m->system->attach(&(t->runnable)); @@ -2091,7 +1906,7 @@ attachThread(Machine* m, bool daemon) enter(t, Thread::ActiveState); - uintptr_t arguments[] = { daemon }; + uintptr_t arguments[] = {daemon}; if (run(t, initAttachedThread, arguments)) { enter(t, Thread::IdleState); @@ -2102,218 +1917,197 @@ attachThread(Machine* m, bool daemon) } } -inline object& -root(Thread* t, Machine::Root root) +inline GcRoots* roots(Thread* t) { - return arrayBody(t, t->m->roots, root); + return t->m->roots; } -inline void -setRoot(Thread* t, Machine::Root root, object value) +inline GcClass* type(Thread* t, Gc::Type type) { - set(t, t->m->roots, ArrayBody + (root * BytesPerWord), value); + return cast(t, t->m->types->body()[type]); } -inline object -type(Thread* t, Machine::Type type) +inline void setType(Thread* t, Gc::Type type, GcClass* value) { - return arrayBody(t, t->m->types, type); + t->m->types->setBodyElement(t, type, value); } -inline void -setType(Thread* t, Machine::Type type, object value) -{ - set(t, t->m->types, ArrayBody + (type * BytesPerWord), value); -} - -inline bool -objectFixed(Thread*, object o) +inline bool objectFixed(Thread*, object o) { return (alias(o, 0) & (~PointerMask)) == FixedMark; } -inline bool -objectExtended(Thread*, object o) +inline bool objectExtended(Thread*, object o) { return (alias(o, 0) & (~PointerMask)) == ExtendedMark; } -inline bool -hashTaken(Thread*, object o) +inline bool hashTaken(Thread*, object o) { return (alias(o, 0) & (~PointerMask)) == HashTakenMark; } -inline unsigned -baseSize(Thread* t, object o, object class_) +inline unsigned baseSize(Thread* t UNUSED, object o, GcClass* class_) { - assert(t, classFixedSize(t, class_) >= BytesPerWord); + assertT(t, class_->fixedSize() >= BytesPerWord); - return ceilingDivide(classFixedSize(t, class_), BytesPerWord) - + ceilingDivide(classArrayElementSize(t, class_) - * fieldAtOffset(o, classFixedSize(t, class_) - BytesPerWord), - BytesPerWord); + return ceilingDivide(class_->fixedSize(), BytesPerWord) + + ceilingDivide(class_->arrayElementSize() + * fieldAtOffset( + o, class_->fixedSize() - BytesPerWord), + BytesPerWord); } -object -makeTrace(Thread* t, Processor::StackWalker* walker); +object makeTrace(Thread* t, Processor::StackWalker* walker); -object -makeTrace(Thread* t, Thread* target); +object makeTrace(Thread* t, Thread* target); -inline object -makeTrace(Thread* t) +inline object makeTrace(Thread* t) { return makeTrace(t, t); } -inline object -makeNew(Thread* t, object class_) +inline object makeNew(Thread* t, GcClass* class_) { - assert(t, t->state == Thread::NoState or t->state == Thread::ActiveState); + assertT(t, t->state == Thread::NoState or t->state == Thread::ActiveState); PROTECT(t, class_); - unsigned sizeInBytes = pad(classFixedSize(t, class_)); - assert(t, sizeInBytes); - object instance = allocate(t, sizeInBytes, classObjectMask(t, class_)); + unsigned sizeInBytes = pad(class_->fixedSize()); + assertT(t, sizeInBytes); + object instance = allocate(t, sizeInBytes, class_->objectMask()); setObjectClass(t, instance, class_); return instance; } -object -makeNewGeneral(Thread* t, object class_); +object makeNewGeneral(Thread* t, GcClass* class_); -inline object -make(Thread* t, object class_) +inline object make(Thread* t, GcClass* class_) { - if (UNLIKELY(classVmFlags(t, class_) - & (WeakReferenceFlag | HasFinalizerFlag))) - { + if (UNLIKELY(class_->vmFlags() & (WeakReferenceFlag | HasFinalizerFlag))) { return makeNewGeneral(t, class_); } else { return makeNew(t, class_); } } -object -makeByteArrayV(Thread* t, const char* format, va_list a, int size); +GcByteArray* makeByteArrayV(Thread* t, const char* format, va_list a, int size); -object -makeByteArray(Thread* t, const char* format, ...); +GcByteArray* makeByteArray(Thread* t, const char* format, ...); -object -makeString(Thread* t, const char* format, ...); +GcString* makeString(Thread* t, const char* format, ...); #ifndef HAVE_StringOffset -inline unsigned -stringLength(Thread* t, object string) +inline uint32_t GcString::length(Thread* t) { - return charArrayLength(t, stringData(t, string)); + return cast(t, this->data())->length(); } -inline unsigned -stringOffset(Thread*, object) +inline uint32_t GcString::offset(Thread*) { return 0; } -# ifndef HAVE_StringHash32 +#ifndef HAVE_StringHash32 -inline object -makeString(Thread* t, object data, int32_t hash, int32_t) +inline GcString* makeString(Thread* t, object data, int32_t hash, int32_t) { return makeString(t, data, hash); } -# endif // not HAVE_StringHash32 +#endif // not HAVE_StringHash32 -inline object -makeString(Thread* t, object data, unsigned offset, unsigned length, unsigned) +inline GcString* makeString(Thread* t, + object odata, + unsigned offset, + unsigned length, + unsigned) { - if (offset == 0 and length == charArrayLength(t, data)) { - return makeString(t, data, 0, 0); + GcCharArray* data = cast(t, odata); + if (offset == 0 and length == data->length()) { + return makeString(t, reinterpret_cast(data), 0, 0); } else { PROTECT(t, data); - object array = makeCharArray(t, length); + GcCharArray* array = makeCharArray(t, length); - memcpy(&charArrayBody(t, array, 0), &charArrayBody(t, data, offset), - length * 2); + memcpy(array->body().begin(), &data->body()[offset], length * 2); - return makeString(t, array, 0, 0); + return makeString(t, reinterpret_cast(array), 0, 0); } } -#endif // not HAVE_StringOffset +#endif // not HAVE_StringOffset -int -stringUTFLength(Thread* t, object string, unsigned start, unsigned length); +int stringUTFLength(Thread* t, + GcString* string, + unsigned start, + unsigned length); -inline int -stringUTFLength(Thread* t, object string) +inline int stringUTFLength(Thread* t, GcString* string) { - return stringUTFLength(t, string, 0, stringLength(t, string)); + return stringUTFLength(t, string, 0, string->length(t)); } -void -stringChars(Thread* t, object string, unsigned start, unsigned length, - char* chars); +void stringChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + char* chars); -inline void -stringChars(Thread* t, object string, char* chars) +inline void stringChars(Thread* t, GcString* string, char* chars) { - stringChars(t, string, 0, stringLength(t, string), chars); + stringChars(t, string, 0, string->length(t), chars); } -void -stringChars(Thread* t, object string, unsigned start, unsigned length, - uint16_t* chars); +void stringChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + uint16_t* chars); -inline void -stringChars(Thread* t, object string, uint16_t* chars) +inline void stringChars(Thread* t, GcString* string, uint16_t* chars) { - stringChars(t, string, 0, stringLength(t, string), chars); + stringChars(t, string, 0, string->length(t), chars); } -void -stringUTFChars(Thread* t, object string, unsigned start, unsigned length, - char* chars, unsigned charsLength); +void stringUTFChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + char* chars, + unsigned charsLength); -inline void -stringUTFChars(Thread* t, object string, char* chars, unsigned charsLength) +inline void stringUTFChars(Thread* t, + GcString* string, + char* chars, + unsigned charsLength) { - stringUTFChars(t, string, 0, stringLength(t, string), chars, charsLength); + stringUTFChars(t, string, 0, string->length(t), chars, charsLength); } -bool -isAssignableFrom(Thread* t, object a, object b); +bool isAssignableFrom(Thread* t, GcClass* a, GcClass* b); -object -classInitializer(Thread* t, object class_); +GcMethod* classInitializer(Thread* t, GcClass* class_); -object -frameMethod(Thread* t, int frame); +object frameMethod(Thread* t, int frame); -inline uintptr_t& -extendedWord(Thread* t UNUSED, object o, unsigned baseSize) +inline uintptr_t& extendedWord(Thread* t UNUSED, object o, unsigned baseSize) { - assert(t, objectExtended(t, o)); + assertT(t, objectExtended(t, o)); return fieldAtOffset(o, baseSize * BytesPerWord); } -inline unsigned -extendedSize(Thread* t, object o, unsigned baseSize) +inline unsigned extendedSize(Thread* t, object o, unsigned baseSize) { return baseSize + objectExtended(t, o); } -inline void -markHashTaken(Thread* t, object o) +inline void markHashTaken(Thread* t, object o) { - assert(t, not objectExtended(t, o)); - assert(t, not objectFixed(t, o)); + assertT(t, not objectExtended(t, o)); + assertT(t, not objectFixed(t, o)); ACQUIRE_RAW(t, t->m->heapLock); @@ -2321,8 +2115,7 @@ markHashTaken(Thread* t, object o) t->m->heap->pad(o); } -inline uint32_t -takeHash(Thread*, object o) +inline uint32_t takeHash(Thread*, object o) { // some broken code implicitly relies on System.identityHashCode // always returning a non-negative number (e.g. old versions of @@ -2331,8 +2124,7 @@ takeHash(Thread*, object o) return (reinterpret_cast(o) / BytesPerWord) & 0x7FFFFFFF; } -inline uint32_t -objectHash(Thread* t, object o) +inline uint32_t objectHash(Thread* t, object o) { if (objectExtended(t, o)) { return extendedWord(t, o, baseSize(t, o, objectClass(t, o))); @@ -2344,67 +2136,65 @@ objectHash(Thread* t, object o) } } -inline bool -objectEqual(Thread*, object a, object b) +inline bool objectEqual(Thread*, object a, object b) { return a == b; } -inline uint32_t -byteArrayHash(Thread* t, object array) +inline uint32_t byteArrayHash(Thread* t UNUSED, object ao) { - return hash(&byteArrayBody(t, array, 0), byteArrayLength(t, array)); + GcByteArray* a = cast(t, ao); + return hash(a->body()); } -inline uint32_t -charArrayHash(Thread* t, object array) +inline uint32_t charArrayHash(Thread* t UNUSED, object ao) { - return hash(&charArrayBody(t, array, 0), charArrayLength(t, array)); + GcByteArray* a = cast(t, ao); + return hash(a->body()); } -inline bool -byteArrayEqual(Thread* t, object a, object b) +inline bool byteArrayEqual(Thread* t UNUSED, object ao, object bo) { - return a == b or - ((byteArrayLength(t, a) == byteArrayLength(t, b)) and - memcmp(&byteArrayBody(t, a, 0), &byteArrayBody(t, b, 0), - byteArrayLength(t, a)) == 0); + GcByteArray* a = cast(t, ao); + GcByteArray* b = cast(t, bo); + return a == b + or ((a->length() == b->length()) + and memcmp(a->body().begin(), b->body().begin(), a->length()) + == 0); } -inline uint32_t -stringHash(Thread* t, object s) +inline uint32_t stringHash(Thread* t, object so) { - if (stringHashCode(t, s) == 0 and stringLength(t, s)) { - object data = stringData(t, s); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { - stringHashCode(t, s) = hash - (&byteArrayBody(t, data, stringOffset(t, s)), stringLength(t, s)); + GcString* s = cast(t, so); + if (s->hashCode() == 0 and s->length(t)) { + if (objectClass(t, s->data()) == type(t, GcByteArray::Type)) { + s->hashCode() = hash(cast(t, s->data())->body().subslice( + s->offset(t), s->length(t))); } else { - stringHashCode(t, s) = hash - (&charArrayBody(t, data, stringOffset(t, s)), stringLength(t, s)); + s->hashCode() = hash(cast(t, s->data())->body().subslice( + s->offset(t), s->length(t))); } } - return stringHashCode(t, s); + return s->hashCode(); } -inline uint16_t -stringCharAt(Thread* t, object s, int i) +inline uint16_t stringCharAt(Thread* t, GcString* s, int i) { - object data = stringData(t, s); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { - return byteArrayBody(t, data, stringOffset(t, s) + i); + if (objectClass(t, s->data()) == type(t, GcByteArray::Type)) { + return cast(t, s->data())->body()[s->offset(t) + i]; } else { - return charArrayBody(t, data, stringOffset(t, s) + i); + return cast(t, s->data())->body()[s->offset(t) + i]; } } -inline bool -stringEqual(Thread* t, object a, object b) +inline bool stringEqual(Thread* t, object ao, object bo) { + GcString* a = cast(t, ao); + GcString* b = cast(t, bo); if (a == b) { return true; - } else if (stringLength(t, a) == stringLength(t, b)) { - for (unsigned i = 0; i < stringLength(t, a); ++i) { + } else if (a->length(t) == b->length(t)) { + for (unsigned i = 0; i < a->length(t); ++i) { if (stringCharAt(t, a, i) != stringCharAt(t, b, i)) { return false; } @@ -2415,66 +2205,71 @@ stringEqual(Thread* t, object a, object b) } } -inline uint32_t -methodHash(Thread* t, object method) +inline uint32_t methodHash(Thread* t, object mo) { - return byteArrayHash(t, methodName(t, method)) - ^ byteArrayHash(t, methodSpec(t, method)); + GcMethod* method = cast(t, mo); + return byteArrayHash(t, method->name()) ^ byteArrayHash(t, method->spec()); } -inline bool -methodEqual(Thread* t, object a, object b) +inline bool methodEqual(Thread* t, object ao, object bo) { - return a == b or - (byteArrayEqual(t, methodName(t, a), methodName(t, b)) and - byteArrayEqual(t, methodSpec(t, a), methodSpec(t, b))); + GcMethod* a = cast(t, ao); + GcMethod* b = cast(t, bo); + return a == b or (byteArrayEqual(t, a->name(), b->name()) + and byteArrayEqual(t, a->spec(), b->spec())); } class MethodSpecIterator { public: - MethodSpecIterator(Thread* t, const char* s): - t(t), s(s + 1) - { } + MethodSpecIterator(Thread* t, const char* s) : t(t), s(s + 1) + { + } - const char* next() { - assert(t, *s != ')'); + const char* next() + { + assertT(t, *s != ')'); const char* p = s; switch (*s) { case 'L': - while (*s and *s != ';') ++ s; - ++ s; + while (*s and *s != ';') + ++s; + ++s; break; case '[': - while (*s == '[') ++ s; + while (*s == '[') + ++s; switch (*s) { case 'L': - while (*s and *s != ';') ++ s; - ++ s; + while (*s and *s != ';') + ++s; + ++s; break; default: - ++ s; + ++s; break; } break; - + default: - ++ s; + ++s; break; } - + return p; } - bool hasNext() { + bool hasNext() + { return *s != ')'; } - const char* returnSpec() { - assert(t, *s == ')'); + const char* returnSpec() + { + assertT(t, *s == ')'); return s + 1; } @@ -2482,17 +2277,13 @@ class MethodSpecIterator { const char* s; }; -unsigned -fieldCode(Thread* t, unsigned javaCode); +unsigned fieldCode(Thread* t, unsigned javaCode); -unsigned -fieldType(Thread* t, unsigned code); +unsigned fieldType(Thread* t, unsigned code); -unsigned -primitiveSize(Thread* t, unsigned code); +unsigned primitiveSize(Thread* t, unsigned code); -inline unsigned -fieldSize(Thread* t, unsigned code) +inline unsigned fieldSize(Thread* t, unsigned code) { if (code == ObjectField) { return BytesPerWord; @@ -2501,22 +2292,23 @@ fieldSize(Thread* t, unsigned code) } } -inline unsigned -fieldSize(Thread* t, object field) +inline unsigned fieldSize(Thread* t, GcField* field) { - return fieldSize(t, fieldCode(t, field)); + return fieldSize(t, field->code()); } -inline void -scanMethodSpec(Thread* t, const char* s, bool static_, - unsigned* parameterCount, unsigned* parameterFootprint, - unsigned* returnCode) +inline void scanMethodSpec(Thread* t, + const char* s, + bool static_, + unsigned* parameterCount, + unsigned* parameterFootprint, + unsigned* returnCode) { unsigned count = 0; unsigned footprint = 0; MethodSpecIterator it(t, s); while (it.hasNext()) { - ++ count; + ++count; switch (*it.next()) { case 'J': case 'D': @@ -2524,13 +2316,13 @@ scanMethodSpec(Thread* t, const char* s, bool static_, break; default: - ++ footprint; - break; + ++footprint; + break; } } if (not static_) { - ++ footprint; + ++footprint; } *parameterCount = count; @@ -2538,149 +2330,161 @@ scanMethodSpec(Thread* t, const char* s, bool static_, *returnCode = fieldCode(t, *it.returnSpec()); } -object -findLoadedClass(Thread* t, object loader, object spec); +GcClass* findLoadedClass(Thread* t, GcClassLoader* loader, GcByteArray* spec); -inline bool -emptyMethod(Thread* t, object method) +inline bool emptyMethod(Thread* t UNUSED, GcMethod* method) { - return ((methodFlags(t, method) & ACC_NATIVE) == 0) - and (codeLength(t, methodCode(t, method)) == 1) - and (codeBody(t, methodCode(t, method), 0) == return_); + return ((method->flags() & ACC_NATIVE) == 0) + and (method->code()->length() == 1) + and (method->code()->body()[0] == return_); } -object -parseUtf8(Thread* t, const char* data, unsigned length); +object parseUtf8(Thread* t, const char* data, unsigned length); -object -parseUtf8(Thread* t, object array); +object parseUtf8(Thread* t, GcByteArray* array); -object -parseClass(Thread* t, object loader, const uint8_t* data, unsigned length, - Machine::Type throwType = Machine::NoClassDefFoundErrorType); +GcClass* parseClass(Thread* t, + GcClassLoader* loader, + const uint8_t* data, + unsigned length, + Gc::Type throwType = GcNoClassDefFoundError::Type); -object -resolveClass(Thread* t, object loader, object name, bool throw_ = true, - Machine::Type throwType = Machine::NoClassDefFoundErrorType); +GcClass* resolveClass(Thread* t, + GcClassLoader* loader, + GcByteArray* name, + bool throw_ = true, + Gc::Type throwType = GcNoClassDefFoundError::Type); -inline object -resolveClass(Thread* t, object loader, const char* name, bool throw_ = true, - Machine::Type throwType = Machine::NoClassDefFoundErrorType) +inline GcClass* resolveClass(Thread* t, + GcClassLoader* loader, + const char* name, + bool throw_ = true, + Gc::Type throwType = GcNoClassDefFoundError::Type) { PROTECT(t, loader); - object n = makeByteArray(t, "%s", name); + GcByteArray* n = makeByteArray(t, "%s", name); return resolveClass(t, loader, n, throw_, throwType); } -object -resolveSystemClass -(Thread* t, object loader, object name, bool throw_ = true, - Machine::Type throwType = Machine::NoClassDefFoundErrorType); +GcClass* resolveSystemClass(Thread* t, + GcClassLoader* loader, + GcByteArray* name, + bool throw_ = true, + Gc::Type throwType = GcNoClassDefFoundError::Type); -inline object -resolveSystemClass(Thread* t, object loader, const char* name) +inline GcClass* resolveSystemClass(Thread* t, + GcClassLoader* loader, + const char* name) { return resolveSystemClass(t, loader, makeByteArray(t, "%s", name)); } -void -linkClass(Thread* t, object loader, object class_); +void linkClass(Thread* t, GcClassLoader* loader, GcClass* class_); -object -resolveMethod(Thread* t, object class_, const char* methodName, - const char* methodSpec); +GcMethod* resolveMethod(Thread* t, + GcClass* class_, + const char* methodName, + const char* methodSpec); -inline object -resolveMethod(Thread* t, object loader, const char* className, - const char* methodName, const char* methodSpec) +inline GcMethod* resolveMethod(Thread* t, + GcClassLoader* loader, + const char* className, + const char* methodName, + const char* methodSpec) { - return resolveMethod - (t, resolveClass(t, loader, className), methodName, methodSpec); + return resolveMethod( + t, resolveClass(t, loader, className), methodName, methodSpec); } -object -resolveField(Thread* t, object class_, const char* fieldName, - const char* fieldSpec); +GcField* resolveField(Thread* t, + GcClass* class_, + const char* fieldName, + const char* fieldSpec); -inline object -resolveField(Thread* t, object loader, const char* className, - const char* fieldName, const char* fieldSpec) +inline GcField* resolveField(Thread* t, + GcClassLoader* loader, + const char* className, + const char* fieldName, + const char* fieldSpec) { - return resolveField - (t, resolveClass(t, loader, className), fieldName, fieldSpec); + return resolveField( + t, resolveClass(t, loader, className), fieldName, fieldSpec); } -bool -classNeedsInit(Thread* t, object c); +bool classNeedsInit(Thread* t, GcClass* c); -bool -preInitClass(Thread* t, object c); +bool preInitClass(Thread* t, GcClass* c); -void -postInitClass(Thread* t, object c); +void postInitClass(Thread* t, GcClass* c); -void -initClass(Thread* t, object c); +void initClass(Thread* t, GcClass* c); -object -resolveObjectArrayClass(Thread* t, object loader, object elementClass); +GcClass* resolveObjectArrayClass(Thread* t, + GcClassLoader* loader, + GcClass* elementClass); -object -makeObjectArray(Thread* t, object elementClass, unsigned count); +object makeObjectArray(Thread* t, GcClass* elementClass, unsigned count); -inline object -makeObjectArray(Thread* t, unsigned count) +inline object makeObjectArray(Thread* t, unsigned count) { - return makeObjectArray(t, type(t, Machine::JobjectType), count); + return makeObjectArray(t, type(t, GcJobject::Type), count); } -object -findFieldInClass(Thread* t, object class_, object name, object spec); +object findFieldInClass(Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec); -inline object -findFieldInClass2(Thread* t, object class_, const char* name, const char* spec) +inline object findFieldInClass2(Thread* t, + GcClass* class_, + const char* name, + const char* spec) { PROTECT(t, class_); - object n = makeByteArray(t, "%s", name); + GcByteArray* n = makeByteArray(t, "%s", name); PROTECT(t, n); - object s = makeByteArray(t, "%s", spec); + GcByteArray* s = makeByteArray(t, "%s", spec); return findFieldInClass(t, class_, n, s); } -object -findMethodInClass(Thread* t, object class_, object name, object spec); +object findMethodInClass(Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec); -inline object -makeThrowable -(Thread* t, Machine::Type type, object message = 0, object trace = 0, - object cause = 0) +inline GcThrowable* makeThrowable(Thread* t, + Gc::Type type, + GcString* message = 0, + object trace = 0, + GcThrowable* cause = 0) { PROTECT(t, message); PROTECT(t, trace); PROTECT(t, cause); - + if (trace == 0) { trace = makeTrace(t); } - object result = make(t, vm::type(t, type)); - - set(t, result, ThrowableMessage, message); - set(t, result, ThrowableTrace, trace); - set(t, result, ThrowableCause, cause); + GcThrowable* result = cast(t, make(t, vm::type(t, type))); + + result->setMessage(t, message); + result->setTrace(t, trace); + result->setCause(t, cause); return result; } -inline object -makeThrowableV(Thread* t, Machine::Type type, const char* format, va_list a, - int size) +inline GcThrowable* makeThrowableV(Thread* t, + Gc::Type type, + const char* format, + va_list a, + int size) { - object s = makeByteArrayV(t, format, a, size); + GcByteArray* s = makeByteArrayV(t, format, a, size); if (s) { - object message = t->m->classpath->makeString - (t, s, 0, byteArrayLength(t, s) - 1); + GcString* message = t->m->classpath->makeString(t, s, 0, s->length() - 1); return makeThrowable(t, type, message); } else { @@ -2688,14 +2492,16 @@ makeThrowableV(Thread* t, Machine::Type type, const char* format, va_list a, } } -inline object -makeThrowable(Thread* t, Machine::Type type, const char* format, ...) +inline GcThrowable* makeThrowable(Thread* t, + Gc::Type type, + const char* format, + ...) { int size = 256; while (true) { va_list a; va_start(a, format); - object r = makeThrowableV(t, type, format, a, size); + GcThrowable* r = makeThrowableV(t, type, format, a, size); va_end(a); if (r) { @@ -2706,33 +2512,28 @@ makeThrowable(Thread* t, Machine::Type type, const char* format, ...) } } -void -popResources(Thread* t); +void popResources(Thread* t); -} // namespace vm +} // namespace vm -AVIAN_EXPORT void -vmPrintTrace(vm::Thread* t); +AVIAN_EXPORT void vmPrintTrace(vm::Thread* t); -AVIAN_EXPORT void -vmfPrintTrace(vm::Thread* t, FILE* out); +AVIAN_EXPORT void vmfPrintTrace(vm::Thread* t, FILE* out); namespace vm { -void -dumpHeap(Thread* t, FILE* out); +void dumpHeap(Thread* t, FILE* out); -inline void NO_RETURN -throw_(Thread* t, object e) +inline void NO_RETURN throw_(Thread* t, GcThrowable* e) { - assert(t, t->exception == 0); - assert(t, e); + assertT(t, t->exception == 0); + assertT(t, e); expect(t, not t->checkpoint->noThrow); t->exception = e; - if (objectClass(t, e) == type(t, Machine::OutOfMemoryErrorType)) { + if (objectClass(t, e) == type(t, GcOutOfMemoryError::Type)) { #ifdef AVIAN_HEAPDUMP if (not t->m->dumpedHeapOnOOM) { t->m->dumpedHeapOnOOM = true; @@ -2745,7 +2546,7 @@ throw_(Thread* t, object e) } } } -#endif//AVIAN_HEAPDUMP +#endif // AVIAN_HEAPDUMP if (AbortOnOutOfMemoryError) { fprintf(stderr, "OutOfMemoryError\n"); @@ -2763,22 +2564,23 @@ throw_(Thread* t, object e) abort(t); } -inline void NO_RETURN -throwNew -(Thread* t, Machine::Type type, object message = 0, object trace = 0, - object cause = 0) +inline void NO_RETURN throwNew(Thread* t, + Gc::Type type, + GcString* message = 0, + object trace = 0, + GcThrowable* cause = 0) { throw_(t, makeThrowable(t, type, message, trace, cause)); } inline void NO_RETURN -throwNew(Thread* t, Machine::Type type, const char* format, ...) + throwNew(Thread* t, Gc::Type type, const char* format, ...) { int size = 256; while (true) { va_list a; va_start(a, format); - object r = makeThrowableV(t, type, format, a, size); + GcThrowable* r = makeThrowableV(t, type, format, a, size); va_end(a); if (r) { @@ -2789,93 +2591,106 @@ throwNew(Thread* t, Machine::Type type, const char* format, ...) } } -object -findInHierarchyOrNull(Thread* t, object class_, object name, object spec, - object (*find)(Thread*, object, object, object)); +object findInHierarchyOrNull( + Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec, + object (*find)(Thread*, GcClass*, GcByteArray*, GcByteArray*)); -inline object -findInHierarchy(Thread* t, object class_, object name, object spec, - object (*find)(Thread*, object, object, object), - Machine::Type errorType, bool throw_ = true) +inline object findInHierarchy( + Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec, + object (*find)(Thread*, GcClass*, GcByteArray*, GcByteArray*), + Gc::Type errorType, + bool throw_ = true) { object o = findInHierarchyOrNull(t, class_, name, spec, find); if (throw_ and o == 0) { - throwNew(t, errorType, "%s %s not found in %s", - &byteArrayBody(t, name, 0), - &byteArrayBody(t, spec, 0), - &byteArrayBody(t, className(t, class_), 0)); + throwNew(t, + errorType, + "%s %s not found in %s", + name->body().begin(), + spec->body().begin(), + class_->name()->body().begin()); } return o; } -inline object -findMethod(Thread* t, object class_, object name, object spec) +inline GcMethod* findMethod(Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec) { - return findInHierarchy - (t, class_, name, spec, findMethodInClass, Machine::NoSuchMethodErrorType); + return cast( + t, + findInHierarchy( + t, class_, name, spec, findMethodInClass, GcNoSuchMethodError::Type)); } -inline object -findMethodOrNull(Thread* t, object class_, const char* name, const char* spec) +inline GcMethod* findMethodOrNull(Thread* t, + GcClass* class_, + const char* name, + const char* spec) { PROTECT(t, class_); - object n = makeByteArray(t, "%s", name); + GcByteArray* n = makeByteArray(t, "%s", name); PROTECT(t, n); - object s = makeByteArray(t, "%s", spec); - return findInHierarchyOrNull(t, class_, n, s, findMethodInClass); + GcByteArray* s = makeByteArray(t, "%s", spec); + return cast( + t, findInHierarchyOrNull(t, class_, n, s, findMethodInClass)); } -inline object -findVirtualMethod(Thread* t, object method, object class_) +inline GcMethod* findVirtualMethod(Thread* t, GcMethod* method, GcClass* class_) { - return arrayBody(t, classVirtualTable(t, class_), methodOffset(t, method)); + return cast( + t, cast(t, class_->virtualTable())->body()[method->offset()]); } -inline object -findInterfaceMethod(Thread* t, object method, object class_) +inline GcMethod* findInterfaceMethod(Thread* t, + GcMethod* method, + GcClass* class_) { - assert(t, (classVmFlags(t, class_) & BootstrapFlag) == 0); + assertT(t, (class_->vmFlags() & BootstrapFlag) == 0); - object interface = methodClass(t, method); - object itable = classInterfaceTable(t, class_); - for (unsigned i = 0; i < arrayLength(t, itable); i += 2) { - if (arrayBody(t, itable, i) == interface) { - return arrayBody - (t, arrayBody(t, itable, i + 1), methodOffset(t, method)); + GcClass* interface = method->class_(); + GcArray* itable = cast(t, class_->interfaceTable()); + for (unsigned i = 0; i < itable->length(); i += 2) { + if (itable->body()[i] == interface) { + return cast( + t, cast(t, itable->body()[i + 1])->body()[method->offset()]); } } abort(t); } -inline unsigned -objectArrayLength(Thread* t UNUSED, object array) +inline unsigned objectArrayLength(Thread* t UNUSED, object array) { - assert(t, classFixedSize(t, objectClass(t, array)) == BytesPerWord * 2); - assert(t, classArrayElementSize(t, objectClass(t, array)) == BytesPerWord); + assertT(t, objectClass(t, array)->fixedSize() == BytesPerWord * 2); + assertT(t, objectClass(t, array)->arrayElementSize() == BytesPerWord); return fieldAtOffset(array, BytesPerWord); } -inline object& -objectArrayBody(Thread* t UNUSED, object array, unsigned index) +inline object& objectArrayBody(Thread* t UNUSED, object array, unsigned index) { - assert(t, classFixedSize(t, objectClass(t, array)) == BytesPerWord * 2); - assert(t, classArrayElementSize(t, objectClass(t, array)) == BytesPerWord); - assert(t, classObjectMask(t, objectClass(t, array)) - == classObjectMask(t, arrayBody - (t, t->m->types, Machine::ArrayType))); + assertT(t, objectClass(t, array)->fixedSize() == BytesPerWord * 2); + assertT(t, objectClass(t, array)->arrayElementSize() == BytesPerWord); + assertT( + t, + objectClass(t, array)->objectMask() + == cast(t, t->m->types->body()[GcArray::Type])->objectMask()); return fieldAtOffset(array, ArrayBody + (index * BytesPerWord)); } -unsigned -parameterFootprint(Thread* t, const char* s, bool static_); +unsigned parameterFootprint(Thread* t, const char* s, bool static_); -void -addFinalizer(Thread* t, object target, void (*finalize)(Thread*, object)); +void addFinalizer(Thread* t, object target, void (*finalize)(Thread*, object)); -inline bool -acquireSystem(Thread* t, Thread* target) +inline bool acquireSystem(Thread* t, Thread* target) { ACQUIRE_RAW(t, t->m->stateLock); @@ -2887,24 +2702,24 @@ acquireSystem(Thread* t, Thread* target) } } -inline void -releaseSystem(Thread* t, Thread* target) +inline void releaseSystem(Thread* t, Thread* target) { ACQUIRE_RAW(t, t->m->stateLock); - assert(t, t->state != Thread::JoinedState); + assertT(t, t->state != Thread::JoinedState); atomicAnd(&(target->flags), ~Thread::SystemFlag); } -inline bool -atomicCompareAndSwapObject(Thread* t, object target, unsigned offset, - object old, object new_) +inline bool atomicCompareAndSwapObject(Thread* t, + object target, + unsigned offset, + object old, + object new_) { if (atomicCompareAndSwap(&fieldAtOffset(target, offset), reinterpret_cast(old), - reinterpret_cast(new_))) - { + reinterpret_cast(new_))) { mark(t, target, offset); return true; } else { @@ -2916,8 +2731,9 @@ atomicCompareAndSwapObject(Thread* t, object target, unsigned offset, // monitorAtomicPollAcquire) use the Michael and Scott Non-Blocking // Queue Algorithm: http://www.cs.rochester.edu/u/michael/PODC96.html -inline void -monitorAtomicAppendAcquire(Thread* t, object monitor, object node) +inline void monitorAtomicAppendAcquire(Thread* t, + GcMonitor* monitor, + GcMonitorNode* node) { if (node == 0) { PROTECT(t, monitor); @@ -2926,59 +2742,55 @@ monitorAtomicAppendAcquire(Thread* t, object monitor, object node) } while (true) { - object tail = monitorAcquireTail(t, monitor); - - loadMemoryBarrier(); - - object next = monitorNodeNext(t, tail); + GcMonitorNode* tail = cast(t, monitor->acquireTail()); loadMemoryBarrier(); - if (tail == monitorAcquireTail(t, monitor)) { + object next = tail->next(); + + loadMemoryBarrier(); + + if (tail == cast(t, monitor->acquireTail())) { if (next) { - atomicCompareAndSwapObject - (t, monitor, MonitorAcquireTail, tail, next); - } else if (atomicCompareAndSwapObject - (t, tail, MonitorNodeNext, 0, node)) - { - atomicCompareAndSwapObject - (t, monitor, MonitorAcquireTail, tail, node); + atomicCompareAndSwapObject(t, monitor, MonitorAcquireTail, tail, next); + } else if (atomicCompareAndSwapObject( + t, tail, MonitorNodeNext, 0, node)) { + atomicCompareAndSwapObject(t, monitor, MonitorAcquireTail, tail, node); return; } } } } -inline Thread* -monitorAtomicPollAcquire(Thread* t, object monitor, bool remove) +inline Thread* monitorAtomicPollAcquire(Thread* t, + GcMonitor* monitor, + bool remove) { while (true) { - object head = monitorAcquireHead(t, monitor); + GcMonitorNode* head = cast(t, monitor->acquireHead()); loadMemoryBarrier(); - object tail = monitorAcquireTail(t, monitor); + GcMonitorNode* tail = cast(t, monitor->acquireTail()); loadMemoryBarrier(); - object next = monitorNodeNext(t, head); + GcMonitorNode* next = cast(t, head->next()); loadMemoryBarrier(); - if (head == monitorAcquireHead(t, monitor)) { + if (head == cast(t, monitor->acquireHead())) { if (head == tail) { if (next) { - atomicCompareAndSwapObject - (t, monitor, MonitorAcquireTail, tail, next); + atomicCompareAndSwapObject( + t, monitor, MonitorAcquireTail, tail, next); } else { return 0; } } else { - Thread* value = static_cast(monitorNodeValue(t, next)); - if ((not remove) - or atomicCompareAndSwapObject - (t, monitor, MonitorAcquireHead, head, next)) - { + Thread* value = static_cast(next->value()); + if ((not remove) or atomicCompareAndSwapObject( + t, monitor, MonitorAcquireHead, head, next)) { return value; } } @@ -2986,24 +2798,24 @@ monitorAtomicPollAcquire(Thread* t, object monitor, bool remove) } } -inline bool -monitorTryAcquire(Thread* t, object monitor) +inline bool monitorTryAcquire(Thread* t, GcMonitor* monitor) { - if (monitorOwner(t, monitor) == t + if (monitor->owner() == t or (monitorAtomicPollAcquire(t, monitor, false) == 0 - and atomicCompareAndSwap - (reinterpret_cast(&monitorOwner(t, monitor)), 0, - reinterpret_cast(t)))) - { - ++ monitorDepth(t, monitor); + and atomicCompareAndSwap( + reinterpret_cast(&monitor->owner()), + 0, + reinterpret_cast(t)))) { + ++monitor->depth(); return true; } else { return false; } } -inline void -monitorAcquire(Thread* t, object monitor, object node = 0) +inline void monitorAcquire(Thread* t, + GcMonitor* monitor, + GcMonitorNode* node = 0) { if (not monitorTryAcquire(t, monitor)) { PROTECT(t, monitor); @@ -3012,44 +2824,43 @@ monitorAcquire(Thread* t, object monitor, object node = 0) ACQUIRE(t, t->lock); monitorAtomicAppendAcquire(t, monitor, node); - + // note that we don't try to acquire the lock until we're first in // line, both because it's fair and because we don't support // removing elements from arbitrary positions in the queue - while (not (t == monitorAtomicPollAcquire(t, monitor, false) - and atomicCompareAndSwap - (reinterpret_cast(&monitorOwner(t, monitor)), 0, - reinterpret_cast(t)))) - { + while (not(t == monitorAtomicPollAcquire(t, monitor, false) + and atomicCompareAndSwap( + reinterpret_cast(&monitor->owner()), + 0, + reinterpret_cast(t)))) { ENTER(t, Thread::IdleState); - + t->lock->wait(t->systemThread, 0); } expect(t, t == monitorAtomicPollAcquire(t, monitor, true)); - - ++ monitorDepth(t, monitor); + + ++monitor->depth(); } - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); } -inline void -monitorRelease(Thread* t, object monitor) +inline void monitorRelease(Thread* t, GcMonitor* monitor) { - expect(t, monitorOwner(t, monitor) == t); + expect(t, monitor->owner() == t); - if (-- monitorDepth(t, monitor) == 0) { - monitorOwner(t, monitor) = 0; + if (--monitor->depth() == 0) { + monitor->owner() = 0; storeLoadMemoryBarrier(); - + Thread* next = monitorAtomicPollAcquire(t, monitor, false); if (next and acquireSystem(t, next)) { ACQUIRE(t, next->lock); - + next->lock->notify(t->systemThread); releaseSystem(t, next); @@ -3057,44 +2868,41 @@ monitorRelease(Thread* t, object monitor) } } -inline void -monitorAppendWait(Thread* t, object monitor) +inline void monitorAppendWait(Thread* t, GcMonitor* monitor) { - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); expect(t, (t->flags & Thread::WaitingFlag) == 0); expect(t, t->waitNext == 0); atomicOr(&(t->flags), Thread::WaitingFlag); - if (monitorWaitTail(t, monitor)) { - static_cast(monitorWaitTail(t, monitor))->waitNext = t; + if (monitor->waitTail()) { + static_cast(monitor->waitTail())->waitNext = t; } else { - monitorWaitHead(t, monitor) = t; + monitor->waitHead() = t; } - monitorWaitTail(t, monitor) = t; + monitor->waitTail() = t; } -inline void -monitorRemoveWait(Thread* t, object monitor) +inline void monitorRemoveWait(Thread* t, GcMonitor* monitor) { - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); Thread* previous = 0; - for (Thread* current = static_cast(monitorWaitHead(t, monitor)); - current; current = current->waitNext) - { + for (Thread* current = static_cast(monitor->waitHead()); current; + current = current->waitNext) { if (t == current) { - if (t == monitorWaitHead(t, monitor)) { - monitorWaitHead(t, monitor) = t->waitNext; + if (t == monitor->waitHead()) { + monitor->waitHead() = t->waitNext; } else { previous->waitNext = t->waitNext; } - if (t == monitorWaitTail(t, monitor)) { - assert(t, t->waitNext == 0); - monitorWaitTail(t, monitor) = previous; + if (t == monitor->waitTail()) { + assertT(t, t->waitNext == 0); + monitor->waitTail() = previous; } t->waitNext = 0; @@ -3109,14 +2917,12 @@ monitorRemoveWait(Thread* t, object monitor) abort(t); } -inline bool -monitorFindWait(Thread* t, object monitor) +inline bool monitorFindWait(Thread* t, GcMonitor* monitor) { - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); - for (Thread* current = static_cast(monitorWaitHead(t, monitor)); - current; current = current->waitNext) - { + for (Thread* current = static_cast(monitor->waitHead()); current; + current = current->waitNext) { if (t == current) { return true; } @@ -3125,10 +2931,9 @@ monitorFindWait(Thread* t, object monitor) return false; } -inline bool -monitorWait(Thread* t, object monitor, int64_t time) +inline bool monitorWait(Thread* t, GcMonitor* monitor, int64_t time) { - expect(t, monitorOwner(t, monitor) == t); + expect(t, monitor->owner() == t); bool interrupted; unsigned depth; @@ -3137,15 +2942,16 @@ monitorWait(Thread* t, object monitor, int64_t time) // pre-allocate monitor node so we don't get an OutOfMemoryError // when we try to re-acquire the monitor below - object monitorNode = makeMonitorNode(t, t, 0); + GcMonitorNode* monitorNode = makeMonitorNode(t, t, 0); PROTECT(t, monitorNode); - { ACQUIRE(t, t->lock); + { + ACQUIRE(t, t->lock); monitorAppendWait(t, monitor); - depth = monitorDepth(t, monitor); - monitorDepth(t, monitor) = 1; + depth = monitor->depth(); + monitor->depth() = 1; monitorRelease(t, monitor); @@ -3156,7 +2962,7 @@ monitorWait(Thread* t, object monitor, int64_t time) monitorAcquire(t, monitor, monitorNode); - monitorDepth(t, monitor) = depth; + monitor->depth() = depth; if (t->flags & Thread::WaitingFlag) { monitorRemoveWait(t, monitor); @@ -3164,37 +2970,35 @@ monitorWait(Thread* t, object monitor, int64_t time) expect(t, not monitorFindWait(t, monitor)); } - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); return interrupted; } -inline Thread* -monitorPollWait(Thread* t, object monitor) +inline Thread* monitorPollWait(Thread* t UNUSED, GcMonitor* monitor) { - assert(t, monitorOwner(t, monitor) == t); + assertT(t, monitor->owner() == t); - Thread* next = static_cast(monitorWaitHead(t, monitor)); + Thread* next = static_cast(monitor->waitHead()); if (next) { - monitorWaitHead(t, monitor) = next->waitNext; + monitor->waitHead() = next->waitNext; atomicAnd(&(next->flags), ~Thread::WaitingFlag); next->waitNext = 0; - if (next == monitorWaitTail(t, monitor)) { - monitorWaitTail(t, monitor) = 0; + if (next == monitor->waitTail()) { + monitor->waitTail() = 0; } } else { - assert(t, monitorWaitTail(t, monitor) == 0); + assertT(t, monitor->waitTail() == 0); } return next; } -inline bool -monitorNotify(Thread* t, object monitor) +inline bool monitorNotify(Thread* t, GcMonitor* monitor) { - expect(t, monitorOwner(t, monitor) == t); - + expect(t, monitor->owner() == t); + Thread* next = monitorPollWait(t, monitor); if (next) { @@ -3208,41 +3012,42 @@ monitorNotify(Thread* t, object monitor) } } -inline void -monitorNotifyAll(Thread* t, object monitor) +inline void monitorNotifyAll(Thread* t, GcMonitor* monitor) { PROTECT(t, monitor); - while (monitorNotify(t, monitor)) { } + while (monitorNotify(t, monitor)) { + } } class ObjectMonitorResource { public: - ObjectMonitorResource(Thread* t, object o): o(o), protector(t, &(this->o)) { + ObjectMonitorResource(Thread* t, GcMonitor* o) + : o(o), protector(t, &(this->o)) + { monitorAcquire(protector.t, o); } - ~ObjectMonitorResource() { + ~ObjectMonitorResource() + { monitorRelease(protector.t, o); } private: - object o; + GcMonitor* o; Thread::SingleProtector protector; }; -object -objectMonitor(Thread* t, object o, bool createNew); +GcMonitor* objectMonitor(Thread* t, object o, bool createNew); -inline void -acquire(Thread* t, object o) +inline void acquire(Thread* t, object o) { unsigned hash; if (DebugMonitors) { hash = objectHash(t, o); } - object m = objectMonitor(t, o, true); + GcMonitor* m = objectMonitor(t, o, true); if (DebugMonitors) { fprintf(stderr, "thread %p acquires %p for %x\n", t, m, hash); @@ -3251,15 +3056,14 @@ acquire(Thread* t, object o) monitorAcquire(t, m); } -inline void -release(Thread* t, object o) +inline void release(Thread* t, object o) { unsigned hash; if (DebugMonitors) { hash = objectHash(t, o); } - object m = objectMonitor(t, o, false); + GcMonitor* m = objectMonitor(t, o, false); if (DebugMonitors) { fprintf(stderr, "thread %p releases %p for %x\n", t, m, hash); @@ -3268,22 +3072,25 @@ release(Thread* t, object o) monitorRelease(t, m); } -inline void -wait(Thread* t, object o, int64_t milliseconds) +inline void wait(Thread* t, object o, int64_t milliseconds) { unsigned hash; if (DebugMonitors) { hash = objectHash(t, o); } - object m = objectMonitor(t, o, false); + GcMonitor* m = objectMonitor(t, o, false); if (DebugMonitors) { - fprintf(stderr, "thread %p waits %d millis on %p for %x\n", - t, static_cast(milliseconds), m, hash); + fprintf(stderr, + "thread %p waits %d millis on %p for %x\n", + t, + static_cast(milliseconds), + m, + hash); } - if (m and monitorOwner(t, m) == t) { + if (m and m->owner() == t) { PROTECT(t, m); bool interrupted = monitorWait(t, m, milliseconds); @@ -3291,64 +3098,62 @@ wait(Thread* t, object o, int64_t milliseconds) if (interrupted) { if (t->m->alive or (t->flags & Thread::DaemonFlag) == 0) { t->m->classpath->clearInterrupted(t); - throwNew(t, Machine::InterruptedExceptionType); + throwNew(t, GcInterruptedException::Type); } else { - throw_(t, root(t, Machine::Shutdown)); + throw_(t, roots(t)->shutdownInProgress()); } } } else { - throwNew(t, Machine::IllegalMonitorStateExceptionType); + throwNew(t, GcIllegalMonitorStateException::Type); } if (DebugMonitors) { - fprintf(stderr, "thread %p wakes up on %p for %x\n", - t, m, hash); + fprintf(stderr, "thread %p wakes up on %p for %x\n", t, m, hash); } stress(t); } -inline void -notify(Thread* t, object o) +inline void notify(Thread* t, object o) { unsigned hash; if (DebugMonitors) { hash = objectHash(t, o); } - object m = objectMonitor(t, o, false); + GcMonitor* m = objectMonitor(t, o, false); if (DebugMonitors) { - fprintf(stderr, "thread %p notifies on %p for %x\n", - t, m, hash); + fprintf(stderr, "thread %p notifies on %p for %x\n", t, m, hash); } - if (m and monitorOwner(t, m) == t) { + if (m and m->owner() == t) { monitorNotify(t, m); } else { - throwNew(t, Machine::IllegalMonitorStateExceptionType); + throwNew(t, GcIllegalMonitorStateException::Type); } } -inline void -notifyAll(Thread* t, object o) +inline void notifyAll(Thread* t, object o) { - object m = objectMonitor(t, o, false); + GcMonitor* m = objectMonitor(t, o, false); if (DebugMonitors) { - fprintf(stderr, "thread %p notifies all on %p for %x\n", - t, m, objectHash(t, o)); + fprintf(stderr, + "thread %p notifies all on %p for %x\n", + t, + m, + objectHash(t, o)); } - if (m and monitorOwner(t, m) == t) { + if (m and m->owner() == t) { monitorNotifyAll(t, m); } else { - throwNew(t, Machine::IllegalMonitorStateExceptionType); + throwNew(t, GcIllegalMonitorStateException::Type); } } -inline void -interrupt(Thread* t, Thread* target) +inline void interrupt(Thread* t, Thread* target) { if (acquireSystem(t, target)) { target->systemThread->interrupt(); @@ -3356,8 +3161,7 @@ interrupt(Thread* t, Thread* target) } } -inline bool -getAndClearInterrupted(Thread* t, Thread* target) +inline bool getAndClearInterrupted(Thread* t, Thread* target) { if (acquireSystem(t, target)) { bool result = target->systemThread->getAndClearInterrupted(); @@ -3368,47 +3172,37 @@ getAndClearInterrupted(Thread* t, Thread* target) } } -inline bool -exceptionMatch(Thread* t, object type, object exception) +inline bool exceptionMatch(Thread* t, GcClass* type, GcThrowable* exception) { - return type == 0 - or (exception != root(t, Machine::Shutdown) - and instanceOf(t, type, t->exception)); + return type == 0 or (exception != roots(t)->shutdownInProgress() + and instanceOf(t, type, t->exception)); } -object -intern(Thread* t, object s); +object intern(Thread* t, object s); -void -walk(Thread* t, Heap::Walker* w, object o, unsigned start); +void walk(Thread* t, Heap::Walker* w, object o, unsigned start); -int -walkNext(Thread* t, object o, int previous); +int walkNext(Thread* t, object o, int previous); -void -visitRoots(Machine* m, Heap::Visitor* v); +void visitRoots(Machine* m, Heap::Visitor* v); -inline jobject -makeLocalReference(Thread* t, object o) +inline jobject makeLocalReference(Thread* t, object o) { return t->m->processor->makeLocalReference(t, o); } -inline void -disposeLocalReference(Thread* t, jobject r) +inline void disposeLocalReference(Thread* t, jobject r) { t->m->processor->disposeLocalReference(t, r); } -inline bool -methodVirtual(Thread* t, object method) +inline bool methodVirtual(Thread* t UNUSED, GcMethod* method) { - return (methodFlags(t, method) & (ACC_STATIC | ACC_PRIVATE)) == 0 - and byteArrayBody(t, methodName(t, method), 0) != '<'; + return (method->flags() & (ACC_STATIC | ACC_PRIVATE)) == 0 + and method->name()->body()[0] != '<'; } -inline unsigned -singletonMaskSize(unsigned count, unsigned bitsPerWord) +inline unsigned singletonMaskSize(unsigned count, unsigned bitsPerWord) { if (count) { return ceilingDivide(count + 2, bitsPerWord); @@ -3416,201 +3210,215 @@ singletonMaskSize(unsigned count, unsigned bitsPerWord) return 0; } -inline unsigned -singletonMaskSize(unsigned count) +inline unsigned singletonMaskSize(unsigned count) { return singletonMaskSize(count, BitsPerWord); } -inline unsigned -singletonMaskSize(Thread* t, object singleton) +inline unsigned singletonMaskSize(Thread* t UNUSED, GcSingleton* singleton) { - unsigned length = singletonLength(t, singleton); + unsigned length = singleton->length(); if (length) { return ceilingDivide(length + 2, BitsPerWord + 1); } return 0; } -inline unsigned -singletonCount(Thread* t, object singleton) +inline unsigned singletonCount(Thread* t, GcSingleton* singleton) { - return singletonLength(t, singleton) - singletonMaskSize(t, singleton); + return singleton->length() - singletonMaskSize(t, singleton); } -inline uint32_t* -singletonMask(Thread* t, object singleton) +inline uint32_t* singletonMask(Thread* t UNUSED, GcSingleton* singleton) { - assert(t, singletonLength(t, singleton)); - return reinterpret_cast - (&singletonBody(t, singleton, singletonCount(t, singleton))); + assertT(t, singleton->length()); + return reinterpret_cast( + &singleton->body()[singletonCount(t, singleton)]); } -inline void -singletonMarkObject(uint32_t* mask, unsigned index) +inline void singletonMarkObject(uint32_t* mask, unsigned index) { - mask[(index + 2) / 32] - |= (static_cast(1) << ((index + 2) % 32)); + mask[(index + 2) / 32] |= (static_cast(1) << ((index + 2) % 32)); } -inline void -singletonMarkObject(Thread* t, object singleton, unsigned index) +inline void singletonMarkObject(Thread* t, + GcSingleton* singleton, + unsigned index) { singletonMarkObject(singletonMask(t, singleton), index); } -inline bool -singletonIsObject(Thread* t, object singleton, unsigned index) +inline bool singletonIsObject(Thread* t, GcSingleton* singleton, unsigned index) { - assert(t, index < singletonCount(t, singleton)); + assertT(t, index < singletonCount(t, singleton)); return (singletonMask(t, singleton)[(index + 2) / 32] & (static_cast(1) << ((index + 2) % 32))) != 0; } -inline object& -singletonObject(Thread* t, object singleton, unsigned index) +inline object& singletonObject(Thread* t UNUSED, + GcSingleton* singleton, + unsigned index) { - assert(t, singletonIsObject(t, singleton, index)); - return reinterpret_cast(singletonBody(t, singleton, index)); + assertT(t, singletonIsObject(t, singleton, index)); + return reinterpret_cast(singleton->body()[index]); } -inline uintptr_t& -singletonValue(Thread* t, object singleton, unsigned index) +inline uintptr_t& singletonValue(Thread* t UNUSED, + GcSingleton* singleton, + unsigned index) { - assert(t, not singletonIsObject(t, singleton, index)); - return singletonBody(t, singleton, index); + assertT(t, not singletonIsObject(t, singleton, index)); + return singleton->body()[index]; } -inline object -makeSingletonOfSize(Thread* t, unsigned count) +inline GcSingleton* makeSingletonOfSize(Thread* t, unsigned count) { - object o = makeSingleton(t, count + singletonMaskSize(count)); - assert(t, singletonLength(t, o) == count + singletonMaskSize(t, o)); + GcSingleton* o = makeSingleton(t, count + singletonMaskSize(count)); + assertT(t, o->length() == count + singletonMaskSize(t, o)); if (count) { singletonMask(t, o)[0] = 1; } return o; } -inline void -singletonSetBit(Thread* t, object singleton, unsigned start, unsigned index) +inline void singletonSetBit(Thread* t, + GcSingleton* singleton, + unsigned start, + unsigned index) { singletonValue(t, singleton, start + (index / BitsPerWord)) - |= static_cast(1) << (index % BitsPerWord); + |= static_cast(1) << (index % BitsPerWord); } -inline bool -singletonBit(Thread* t, object singleton, unsigned start, unsigned index) +inline bool singletonBit(Thread* t, + GcSingleton* singleton, + unsigned start, + unsigned index) { return (singletonValue(t, singleton, start + (index / BitsPerWord)) & (static_cast(1) << (index % BitsPerWord))) != 0; } -inline unsigned -poolMaskSize(unsigned count, unsigned bitsPerWord) +inline unsigned poolMaskSize(unsigned count, unsigned bitsPerWord) { return ceilingDivide(count, bitsPerWord); } -inline unsigned -poolMaskSize(unsigned count) +inline unsigned poolMaskSize(unsigned count) { return poolMaskSize(count, BitsPerWord); } -inline unsigned -poolMaskSize(Thread* t, object pool) +inline unsigned poolMaskSize(Thread* t, GcSingleton* pool) { return ceilingDivide(singletonCount(t, pool), BitsPerWord + 1); } -inline unsigned -poolSize(Thread* t, object pool) +inline unsigned poolSize(Thread* t, GcSingleton* pool) { return singletonCount(t, pool) - poolMaskSize(t, pool); } -inline object -resolveClassInObject(Thread* t, object loader, object container, - unsigned classOffset, bool throw_ = true) +inline GcClass* resolveClassInObject(Thread* t, + GcClassLoader* loader, + object container, + unsigned classOffset, + bool throw_ = true) { object o = fieldAtOffset(container, classOffset); - loadMemoryBarrier(); + loadMemoryBarrier(); - if (objectClass(t, o) == type(t, Machine::ByteArrayType)) { + if (objectClass(t, o) == type(t, GcByteArray::Type)) { + GcByteArray* name = cast(t, o); PROTECT(t, container); - o = resolveClass(t, loader, o, throw_); - - if (o) { + GcClass* c = resolveClass(t, loader, name, throw_); + + if (c) { storeStoreMemoryBarrier(); - set(t, container, classOffset, o); + setField(t, container, classOffset, c); } + + return c; } - return o; + return cast(t, o); } -inline object -resolveClassInPool(Thread* t, object loader, object method, unsigned index, - bool throw_ = true) +inline GcClass* resolveClassInPool(Thread* t, + GcClassLoader* loader, + GcMethod* method, + unsigned index, + bool throw_ = true) { - object o = singletonObject(t, codePool(t, methodCode(t, method)), index); + object o = singletonObject(t, method->code()->pool(), index); loadMemoryBarrier(); - if (objectClass(t, o) == type(t, Machine::ReferenceType)) { + if (objectClass(t, o) == type(t, GcReference::Type)) { PROTECT(t, method); - o = resolveClass(t, loader, referenceName(t, o), throw_); - - if (o) { + GcClass* c + = resolveClass(t, loader, cast(t, o)->name(), throw_); + + if (c) { storeStoreMemoryBarrier(); - set(t, codePool(t, methodCode(t, method)), - SingletonBody + (index * BytesPerWord), o); + method->code()->pool()->setBodyElement( + t, index, reinterpret_cast(c)); } + return c; } - return o; + return cast(t, o); } -inline object -resolveClassInPool(Thread* t, object method, unsigned index, - bool throw_ = true) +inline GcClass* resolveClassInPool(Thread* t, + GcMethod* method, + unsigned index, + bool throw_ = true) { - return resolveClassInPool(t, classLoader(t, methodClass(t, method)), - method, index, throw_); + return resolveClassInPool( + t, method->class_()->loader(), method, index, throw_); } -inline object -resolve(Thread* t, object loader, object method, unsigned index, - object (*find)(vm::Thread*, object, object, object), - Machine::Type errorType, bool throw_ = true) +inline object resolve( + Thread* t, + GcClassLoader* loader, + GcMethod* method, + unsigned index, + object (*find)(vm::Thread*, GcClass*, GcByteArray*, GcByteArray*), + Gc::Type errorType, + bool throw_ = true) { - object o = singletonObject(t, codePool(t, methodCode(t, method)), index); + object o = singletonObject(t, method->code()->pool(), index); - loadMemoryBarrier(); + loadMemoryBarrier(); - if (objectClass(t, o) == type(t, Machine::ReferenceType)) { + if (objectClass(t, o) == type(t, GcReference::Type)) { PROTECT(t, method); - object reference = o; + GcReference* reference = cast(t, o); PROTECT(t, reference); - object class_ = resolveClassInObject(t, loader, o, ReferenceClass, throw_); - + GcClass* class_ + = resolveClassInObject(t, loader, o, ReferenceClass, throw_); + if (class_) { - o = findInHierarchy - (t, class_, referenceName(t, reference), referenceSpec(t, reference), - find, errorType, throw_); - + o = findInHierarchy(t, + class_, + reference->name(), + reference->spec(), + find, + errorType, + throw_); + if (o) { storeStoreMemoryBarrier(); - set(t, codePool(t, methodCode(t, method)), - SingletonBody + (index * BytesPerWord), o); + method->code()->pool()->setBodyElement( + t, index, reinterpret_cast(o)); } } else { o = 0; @@ -3620,42 +3428,45 @@ resolve(Thread* t, object loader, object method, unsigned index, return o; } -inline object -resolveField(Thread* t, object loader, object method, unsigned index, - bool throw_ = true) +inline GcField* resolveField(Thread* t, + GcClassLoader* loader, + GcMethod* method, + unsigned index, + bool throw_ = true) { - return resolve(t, loader, method, index, findFieldInClass, - Machine::NoSuchFieldErrorType, throw_); + return cast(t, + resolve(t, + loader, + method, + index, + findFieldInClass, + GcNoSuchFieldError::Type, + throw_)); } -inline object -resolveField(Thread* t, object method, unsigned index, bool throw_ = true) +inline GcField* resolveField(Thread* t, + GcMethod* method, + unsigned index, + bool throw_ = true) { - return resolveField - (t, classLoader(t, methodClass(t, method)), method, index, throw_); + return resolveField(t, method->class_()->loader(), method, index, throw_); } -inline void -acquireFieldForRead(Thread* t, object field) +inline void acquireFieldForRead(Thread* t, GcField* field) { - if (UNLIKELY((fieldFlags(t, field) & ACC_VOLATILE) - and BytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField))) - { - acquire(t, field); + if (UNLIKELY( + (field->flags() & ACC_VOLATILE) and BytesPerWord == 4 + and (field->code() == DoubleField or field->code() == LongField))) { + acquire(t, field); } } -inline void -releaseFieldForRead(Thread* t, object field) +inline void releaseFieldForRead(Thread* t, GcField* field) { - if (UNLIKELY(fieldFlags(t, field) & ACC_VOLATILE)) { + if (UNLIKELY(field->flags() & ACC_VOLATILE)) { if (BytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField)) - { - release(t, field); + and (field->code() == DoubleField or field->code() == LongField)) { + release(t, field); } else { loadMemoryBarrier(); } @@ -3664,43 +3475,39 @@ releaseFieldForRead(Thread* t, object field) class FieldReadResource { public: - FieldReadResource(Thread* t, object o): o(o), protector(t, &(this->o)) { + FieldReadResource(Thread* t, GcField* o) : o(o), protector(t, &(this->o)) + { acquireFieldForRead(protector.t, o); } - ~FieldReadResource() { + ~FieldReadResource() + { releaseFieldForRead(protector.t, o); } private: - object o; + GcField* o; Thread::SingleProtector protector; }; -inline void -acquireFieldForWrite(Thread* t, object field) +inline void acquireFieldForWrite(Thread* t, GcField* field) { - if (UNLIKELY(fieldFlags(t, field) & ACC_VOLATILE)) { + if (UNLIKELY(field->flags() & ACC_VOLATILE)) { if (BytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField)) - { - acquire(t, field); + and (field->code() == DoubleField or field->code() == LongField)) { + acquire(t, field); } else { storeStoreMemoryBarrier(); } } } -inline void -releaseFieldForWrite(Thread* t, object field) +inline void releaseFieldForWrite(Thread* t, GcField* field) { - if (UNLIKELY(fieldFlags(t, field) & ACC_VOLATILE)) { + if (UNLIKELY(field->flags() & ACC_VOLATILE)) { if (BytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField)) - { - release(t, field); + and (field->code() == DoubleField or field->code() == LongField)) { + release(t, field); } else { storeLoadMemoryBarrier(); } @@ -3709,75 +3516,86 @@ releaseFieldForWrite(Thread* t, object field) class FieldWriteResource { public: - FieldWriteResource(Thread* t, object o): o(o), protector(t, &(this->o)) { + FieldWriteResource(Thread* t, GcField* o) : o(o), protector(t, &(this->o)) + { acquireFieldForWrite(protector.t, o); } - ~FieldWriteResource() { + ~FieldWriteResource() + { releaseFieldForWrite(protector.t, o); } private: - object o; + GcField* o; Thread::SingleProtector protector; }; -inline object -resolveMethod(Thread* t, object loader, object method, unsigned index, - bool throw_ = true) +inline GcMethod* resolveMethod(Thread* t, + GcClassLoader* loader, + GcMethod* method, + unsigned index, + bool throw_ = true) { - return resolve(t, loader, method, index, findMethodInClass, - Machine::NoSuchMethodErrorType, throw_); + return cast(t, + resolve(t, + loader, + method, + index, + findMethodInClass, + GcNoSuchMethodError::Type, + throw_)); } -inline object -resolveMethod(Thread* t, object method, unsigned index, bool throw_ = true) +inline GcMethod* resolveMethod(Thread* t, + GcMethod* method, + unsigned index, + bool throw_ = true) { - return resolveMethod - (t, classLoader(t, methodClass(t, method)), method, index, throw_); + return resolveMethod(t, method->class_()->loader(), method, index, throw_); } -object -vectorAppend(Thread*, object, object); +GcVector* vectorAppend(Thread*, GcVector*, object); -inline object -getClassRuntimeDataIfExists(Thread* t, object c) +inline GcClassRuntimeData* getClassRuntimeDataIfExists(Thread* t, GcClass* c) { - if (classRuntimeDataIndex(t, c)) { - return vectorBody(t, root(t, Machine::ClassRuntimeDataTable), - classRuntimeDataIndex(t, c) - 1); + if (c->runtimeDataIndex()) { + return cast( + t, + roots(t)->classRuntimeDataTable()->body()[c->runtimeDataIndex() - 1]); } else { return 0; } } -inline object -getClassRuntimeData(Thread* t, object c) +inline GcClassRuntimeData* getClassRuntimeData(Thread* t, GcClass* c) { - if (classRuntimeDataIndex(t, c) == 0) { + if (c->runtimeDataIndex() == 0) { PROTECT(t, c); ACQUIRE(t, t->m->classLock); - if (classRuntimeDataIndex(t, c) == 0) { - object runtimeData = makeClassRuntimeData(t, 0, 0, 0, 0); + if (c->runtimeDataIndex() == 0) { + GcClassRuntimeData* runtimeData = makeClassRuntimeData(t, 0, 0, 0, 0); - setRoot(t, Machine::ClassRuntimeDataTable, vectorAppend - (t, root(t, Machine::ClassRuntimeDataTable), runtimeData)); + { + GcVector* v + = vectorAppend(t, roots(t)->classRuntimeDataTable(), runtimeData); + // sequence point, for gc (don't recombine statements) + roots(t)->setClassRuntimeDataTable(t, v); + } - classRuntimeDataIndex(t, c) = vectorSize - (t, root(t, Machine::ClassRuntimeDataTable)); + c->runtimeDataIndex() = roots(t)->classRuntimeDataTable()->size(); } } - return vectorBody(t, root(t, Machine::ClassRuntimeDataTable), - classRuntimeDataIndex(t, c) - 1); + return cast( + t, roots(t)->classRuntimeDataTable()->body()[c->runtimeDataIndex() - 1]); } -inline object -getMethodRuntimeData(Thread* t, object method) +inline GcMethodRuntimeData* getMethodRuntimeData(Thread* t, GcMethod* method) { - int index = methodRuntimeDataIndex(t, method); + int index = method->runtimeDataIndex(); loadMemoryBarrier(); @@ -3786,188 +3604,191 @@ getMethodRuntimeData(Thread* t, object method) ACQUIRE(t, t->m->classLock); - if (methodRuntimeDataIndex(t, method) == 0) { - object runtimeData = makeMethodRuntimeData(t, 0); + if (method->runtimeDataIndex() == 0) { + GcMethodRuntimeData* runtimeData = makeMethodRuntimeData(t, 0); - setRoot(t, Machine::MethodRuntimeDataTable, vectorAppend - (t, root(t, Machine::MethodRuntimeDataTable), runtimeData)); + { + GcVector* v + = vectorAppend(t, roots(t)->methodRuntimeDataTable(), runtimeData); + // sequence point, for gc (don't recombine statements) + roots(t)->setMethodRuntimeDataTable(t, v); + } storeStoreMemoryBarrier(); - methodRuntimeDataIndex(t, method) = vectorSize - (t, root(t, Machine::MethodRuntimeDataTable)); + method->runtimeDataIndex() = roots(t)->methodRuntimeDataTable()->size(); } } - return vectorBody(t, root(t, Machine::MethodRuntimeDataTable), - methodRuntimeDataIndex(t, method) - 1); + return cast(t, + roots(t)->methodRuntimeDataTable()->body() + [method->runtimeDataIndex() - 1]); } -inline object -getJClass(Thread* t, object c) +inline GcJclass* getJClass(Thread* t, GcClass* c) { PROTECT(t, c); - object jclass = classRuntimeDataJclass(t, getClassRuntimeData(t, c)); + GcJclass* jclass = cast(t, getClassRuntimeData(t, c)->jclass()); loadMemoryBarrier(); if (jclass == 0) { ACQUIRE(t, t->m->classLock); - jclass = classRuntimeDataJclass(t, getClassRuntimeData(t, c)); + jclass = cast(t, getClassRuntimeData(t, c)->jclass()); if (jclass == 0) { jclass = t->m->classpath->makeJclass(t, c); storeStoreMemoryBarrier(); - - set(t, getClassRuntimeData(t, c), ClassRuntimeDataJclass, jclass); + + getClassRuntimeData(t, c)->setJclass(t, jclass); } } return jclass; } -inline object -primitiveClass(Thread* t, char name) +inline GcClass* primitiveClass(Thread* t, char name) { switch (name) { - case 'B': return type(t, Machine::JbyteType); - case 'C': return type(t, Machine::JcharType); - case 'D': return type(t, Machine::JdoubleType); - case 'F': return type(t, Machine::JfloatType); - case 'I': return type(t, Machine::JintType); - case 'J': return type(t, Machine::JlongType); - case 'S': return type(t, Machine::JshortType); - case 'V': return type(t, Machine::JvoidType); - case 'Z': return type(t, Machine::JbooleanType); - default: throwNew(t, Machine::IllegalArgumentExceptionType); + case 'B': + return type(t, GcJbyte::Type); + case 'C': + return type(t, GcJchar::Type); + case 'D': + return type(t, GcJdouble::Type); + case 'F': + return type(t, GcJfloat::Type); + case 'I': + return type(t, GcJint::Type); + case 'J': + return type(t, GcJlong::Type); + case 'S': + return type(t, GcJshort::Type); + case 'V': + return type(t, GcJvoid::Type); + case 'Z': + return type(t, GcJboolean::Type); + default: + throwNew(t, GcIllegalArgumentException::Type); } } - -inline void -registerNative(Thread* t, object method, void* function) + +inline void registerNative(Thread* t, GcMethod* method, void* function) { PROTECT(t, method); - expect(t, methodFlags(t, method) & ACC_NATIVE); + expect(t, method->flags() & ACC_NATIVE); - object native = makeNative(t, function, false); + GcNative* native = makeNative(t, function, false); PROTECT(t, native); - object runtimeData = getMethodRuntimeData(t, method); + GcMethodRuntimeData* runtimeData = getMethodRuntimeData(t, method); // ensure other threads only see the methodRuntimeDataNative field // populated once the object it points to has been populated: storeStoreMemoryBarrier(); - set(t, runtimeData, MethodRuntimeDataNative, native); + runtimeData->setNative(t, native); } -inline void -unregisterNatives(Thread* t, object c) +inline void unregisterNatives(Thread* t, GcClass* c) { - if (classMethodTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) { - object method = arrayBody(t, classMethodTable(t, c), i); - if (methodFlags(t, method) & ACC_NATIVE) { - set(t, getMethodRuntimeData(t, method), MethodRuntimeDataNative, 0); + GcArray* table = cast(t, c->methodTable()); + if (table) { + for (unsigned i = 0; i < table->length(); ++i) { + GcMethod* method = cast(t, table->body()[i]); + if (method->flags() & ACC_NATIVE) { + getMethodRuntimeData(t, method)->setNative(t, 0); } } } } -void -populateMultiArray(Thread* t, object array, int32_t* counts, - unsigned index, unsigned dimensions); +void populateMultiArray(Thread* t, + object array, + int32_t* counts, + unsigned index, + unsigned dimensions); -object -getCaller(Thread* t, unsigned target, bool skipMethodInvoke = false); +GcMethod* getCaller(Thread* t, unsigned target, bool skipMethodInvoke = false); -object -defineClass(Thread* t, object loader, const uint8_t* buffer, unsigned length); +object defineClass(Thread* t, + GcClassLoader* loader, + const uint8_t* buffer, + unsigned length); -inline object -methodClone(Thread* t, object method) +inline GcMethod* methodClone(Thread* t, GcMethod* method) { - return makeMethod - (t, methodVmFlags(t, method), - methodReturnCode(t, method), - methodParameterCount(t, method), - methodParameterFootprint(t, method), - methodFlags(t, method), - methodOffset(t, method), - methodNativeID(t, method), - methodRuntimeDataIndex(t, method), - methodName(t, method), - methodSpec(t, method), - methodAddendum(t, method), - methodClass(t, method), - methodCode(t, method)); + return makeMethod(t, + method->vmFlags(), + method->returnCode(), + method->parameterCount(), + method->parameterFootprint(), + method->flags(), + method->offset(), + method->nativeID(), + method->runtimeDataIndex(), + method->name(), + method->spec(), + method->addendum(), + method->class_(), + method->code()); } -inline uint64_t -exceptionHandler(uint64_t start, uint64_t end, uint64_t ip, uint64_t catchType) +inline uint64_t exceptionHandler(uint64_t start, + uint64_t end, + uint64_t ip, + uint64_t catchType) { return (start << 48) | (end << 32) | (ip << 16) | catchType; } -inline unsigned -exceptionHandlerStart(uint64_t eh) +inline unsigned exceptionHandlerStart(uint64_t eh) { return eh >> 48; } -inline unsigned -exceptionHandlerEnd(uint64_t eh) +inline unsigned exceptionHandlerEnd(uint64_t eh) { return (eh >> 32) & 0xFFFF; } -inline unsigned -exceptionHandlerIp(uint64_t eh) +inline unsigned exceptionHandlerIp(uint64_t eh) { return (eh >> 16) & 0xFFFF; } -inline unsigned -exceptionHandlerCatchType(uint64_t eh) +inline unsigned exceptionHandlerCatchType(uint64_t eh) { return eh & 0xFFFF; } -inline uint64_t -lineNumber(uint64_t ip, uint64_t line) +inline uint64_t lineNumber(uint64_t ip, uint64_t line) { return (ip << 32) | line; } -inline unsigned -lineNumberIp(uint64_t ln) +inline unsigned lineNumberIp(uint64_t ln) { return ln >> 32; } -inline unsigned -lineNumberLine(uint64_t ln) +inline unsigned lineNumberLine(uint64_t ln) { return ln & 0xFFFFFFFF; } -object -interruptLock(Thread* t, object thread); +object interruptLock(Thread* t, GcThread* thread); -void -clearInterrupted(Thread* t); +void clearInterrupted(Thread* t); -void -threadInterrupt(Thread* t, object thread); +void threadInterrupt(Thread* t, GcThread* thread); -bool -threadIsInterrupted(Thread* t, object thread, bool clear); +bool threadIsInterrupted(Thread* t, GcThread* thread, bool clear); -inline FILE* -errorLog(Thread* t) +inline FILE* errorLog(Thread* t) { if (t->m->errorLog == 0) { const char* path = findProperty(t, "avian.error.log"); @@ -3981,9 +3802,10 @@ errorLog(Thread* t) return t->m->errorLog; } -} // namespace vm +} // namespace vm -AVIAN_EXPORT void* -vmAddressFromLine(vm::Thread* t, vm::object m, unsigned line); +AVIAN_EXPORT void* vmAddressFromLine(vm::Thread* t, + vm::object m, + unsigned line); -#endif//MACHINE_H +#endif // MACHINE_H diff --git a/src/avian/process.h b/src/avian/process.h index d532e162be..d1e94a1c7c 100644 --- a/src/avian/process.h +++ b/src/avian/process.h @@ -18,28 +18,25 @@ namespace vm { -inline int16_t -codeReadInt16(Thread* t, object code, unsigned& ip) +inline int16_t codeReadInt16(Thread* t UNUSED, GcCode* code, unsigned& ip) { - uint8_t v1 = codeBody(t, code, ip++); - uint8_t v2 = codeBody(t, code, ip++); + uint8_t v1 = code->body()[ip++]; + uint8_t v2 = code->body()[ip++]; return ((v1 << 8) | v2); } -inline int32_t -codeReadInt32(Thread* t, object code, unsigned& ip) +inline int32_t codeReadInt32(Thread* t UNUSED, GcCode* code, unsigned& ip) { - uint8_t v1 = codeBody(t, code, ip++); - uint8_t v2 = codeBody(t, code, ip++); - uint8_t v3 = codeBody(t, code, ip++); - uint8_t v4 = codeBody(t, code, ip++); + uint8_t v1 = code->body()[ip++]; + uint8_t v2 = code->body()[ip++]; + uint8_t v3 = code->body()[ip++]; + uint8_t v4 = code->body()[ip++]; return ((v1 << 24) | (v2 << 16) | (v3 << 8) | v4); } -inline bool -isSuperclass(Thread* t, object class_, object base) +inline bool isSuperclass(Thread* t UNUSED, GcClass* class_, GcClass* base) { - for (object oc = classSuper(t, base); oc; oc = classSuper(t, oc)) { + for (GcClass* oc = base->super(); oc; oc = oc->super()) { if (oc == class_) { return true; } @@ -47,21 +44,18 @@ isSuperclass(Thread* t, object class_, object base) return false; } -inline bool -isSpecialMethod(Thread* t, object method, object class_) +inline bool isSpecialMethod(Thread* t, GcMethod* method, GcClass* class_) { - return (classFlags(t, class_) & ACC_SUPER) - and strcmp(reinterpret_cast(""), - &byteArrayBody(t, methodName(t, method), 0)) != 0 - and isSuperclass(t, methodClass(t, method), class_); + return (class_->flags() & ACC_SUPER) + and strcmp(reinterpret_cast(""), + method->name()->body().begin()) != 0 + and isSuperclass(t, method->class_(), class_); } -void -resolveNative(Thread* t, object method); +void resolveNative(Thread* t, GcMethod* method); -int -findLineNumber(Thread* t, object method, unsigned ip); +int findLineNumber(Thread* t, GcMethod* method, unsigned ip); -} // namespace vm +} // namespace vm -#endif//PROCESS_H +#endif // PROCESS_H diff --git a/src/avian/processor.h b/src/avian/processor.h index 3f92096891..1a9f3ec43a 100644 --- a/src/avian/processor.h +++ b/src/avian/processor.h @@ -32,6 +32,21 @@ class Slice; namespace vm { +class GcByteArray; +class GcCode; +class GcClass; +class GcMethod; +class GcMethodAddendum; +class GcIntArray; +class GcContinuation; +class GcThrowable; +class GcThread; +class GcClassAddendum; +class GcClassLoader; +class GcArray; +class GcSingleton; +class GcTriple; + class Processor { public: class StackWalker; @@ -45,7 +60,7 @@ class Processor { public: virtual void walk(StackVisitor* v) = 0; - virtual object method() = 0; + virtual GcMethod* method() = 0; virtual int ip() = 0; @@ -54,139 +69,136 @@ class Processor { class CompilationHandler { public: - virtual void compiled(const void* code, unsigned size, unsigned frameSize, const char* name) = 0; + virtual void compiled(const void* code, + unsigned size, + unsigned frameSize, + const char* name) = 0; virtual void dispose() = 0; }; - virtual Thread* - makeThread(Machine* m, object javaThread, Thread* parent) = 0; + virtual Thread* makeThread(Machine* m, GcThread* javaThread, Thread* parent) + = 0; - virtual object - makeMethod(Thread* t, - uint8_t vmFlags, - uint8_t returnCode, - uint8_t parameterCount, - uint8_t parameterFootprint, - uint16_t flags, - uint16_t offset, - object name, - object spec, - object addendum, - object class_, - object code) = 0; + virtual GcMethod* makeMethod(Thread* t, + uint8_t vmFlags, + uint8_t returnCode, + uint8_t parameterCount, + uint8_t parameterFootprint, + uint16_t flags, + uint16_t offset, + GcByteArray* name, + GcByteArray* spec, + GcMethodAddendum* addendum, + GcClass* class_, + GcCode* code) = 0; - virtual object - makeClass(Thread* t, - uint16_t flags, - uint16_t vmFlags, - uint16_t fixedSize, - uint8_t arrayElementSize, - uint8_t arrayDimensions, - object objectMask, - object name, - object sourceFile, - object super, - object interfaceTable, - object virtualTable, - object fieldTable, - object methodTable, - object addendum, - object staticTable, - object loader, - unsigned vtableLength) = 0; + virtual GcClass* makeClass(Thread* t, + uint16_t flags, + uint16_t vmFlags, + uint16_t fixedSize, + uint8_t arrayElementSize, + uint8_t arrayDimensions, + GcClass* arrayElementClass, + GcIntArray* objectMask, + GcByteArray* name, + GcByteArray* sourceFile, + GcClass* super, + object interfaceTable, + object virtualTable, + object fieldTable, + object methodTable, + GcClassAddendum* addendum, + GcSingleton* staticTable, + GcClassLoader* loader, + unsigned vtableLength) = 0; - virtual void - initVtable(Thread* t, object c) = 0; + virtual void initVtable(Thread* t, GcClass* c) = 0; - virtual void - visitObjects(Thread* t, Heap::Visitor* v) = 0; + virtual void visitObjects(Thread* t, Heap::Visitor* v) = 0; - virtual void - walkStack(Thread* t, StackVisitor* v) = 0; + virtual void walkStack(Thread* t, StackVisitor* v) = 0; - virtual int - lineNumber(Thread* t, object method, int ip) = 0; + virtual int lineNumber(Thread* t, GcMethod* method, int ip) = 0; - virtual object* - makeLocalReference(Thread* t, object o) = 0; + virtual object* makeLocalReference(Thread* t, object o) = 0; - virtual void - disposeLocalReference(Thread* t, object* r) = 0; + virtual void disposeLocalReference(Thread* t, object* r) = 0; - virtual bool - pushLocalFrame(Thread* t, unsigned capacity) = 0; + virtual bool pushLocalFrame(Thread* t, unsigned capacity) = 0; - virtual void - popLocalFrame(Thread* t) = 0; + virtual void popLocalFrame(Thread* t) = 0; - virtual object - invokeArray(Thread* t, object method, object this_, object arguments) = 0; + virtual object invokeArray(Thread* t, + GcMethod* method, + object this_, + object arguments) = 0; - virtual object - invokeArray(Thread* t, object method, object this_, const jvalue* arguments) - = 0; + virtual object invokeArray(Thread* t, + GcMethod* method, + object this_, + const jvalue* arguments) = 0; - virtual object - invokeList(Thread* t, object method, object this_, bool indirectObjects, - va_list arguments) = 0; + virtual object invokeList(Thread* t, + GcMethod* method, + object this_, + bool indirectObjects, + va_list arguments) = 0; - virtual object - invokeList(Thread* t, object loader, const char* className, - const char* methodName, const char* methodSpec, - object this_, va_list arguments) = 0; + virtual object invokeList(Thread* t, + GcClassLoader* loader, + const char* className, + const char* methodName, + const char* methodSpec, + object this_, + va_list arguments) = 0; - virtual void - dispose(Thread* t) = 0; + virtual void dispose(Thread* t) = 0; - virtual void - dispose() = 0; + virtual void dispose() = 0; - virtual object - getStackTrace(Thread* t, Thread* target) = 0; + virtual object getStackTrace(Thread* t, Thread* target) = 0; virtual void initialize(BootImage* image, avian::util::Slice code) = 0; - virtual void - addCompilationHandler(CompilationHandler* handler) = 0; + virtual void addCompilationHandler(CompilationHandler* handler) = 0; - virtual void - compileMethod(Thread* t, Zone* zone, object* constants, object* calls, - avian::codegen::DelayedPromise** addresses, object method, - OffsetResolver* resolver) = 0; + virtual void compileMethod(Thread* t, + Zone* zone, + GcTriple** constants, + GcTriple** calls, + avian::codegen::DelayedPromise** addresses, + GcMethod* method, + OffsetResolver* resolver) = 0; - virtual void - visitRoots(Thread* t, HeapWalker* w) = 0; + virtual void visitRoots(Thread* t, HeapWalker* w) = 0; - virtual void - normalizeVirtualThunks(Thread* t) = 0; + virtual void normalizeVirtualThunks(Thread* t) = 0; - virtual unsigned* - makeCallTable(Thread* t, HeapWalker* w) = 0; + virtual unsigned* makeCallTable(Thread* t, HeapWalker* w) = 0; - virtual void - boot(Thread* t, BootImage* image, uint8_t* code) = 0; + virtual void boot(Thread* t, BootImage* image, uint8_t* code) = 0; - virtual void - callWithCurrentContinuation(Thread* t, object receiver) = 0; + virtual void callWithCurrentContinuation(Thread* t, object receiver) = 0; - virtual void - dynamicWind(Thread* t, object before, object thunk, object after) = 0; + virtual void dynamicWind(Thread* t, object before, object thunk, object after) + = 0; - virtual void - feedResultToContinuation(Thread* t, object continuation, object result) = 0; + virtual void feedResultToContinuation(Thread* t, + GcContinuation* continuation, + object result) = 0; - virtual void - feedExceptionToContinuation(Thread* t, object continuation, - object exception) = 0; + virtual void feedExceptionToContinuation(Thread* t, + GcContinuation* continuation, + GcThrowable* exception) = 0; - virtual void - walkContinuationBody(Thread* t, Heap::Walker* w, object o, unsigned start) - = 0; + virtual void walkContinuationBody(Thread* t, + Heap::Walker* w, + object o, + unsigned start) = 0; - object - invoke(Thread* t, object method, object this_, ...) + object invoke(Thread* t, GcMethod* method, object this_, ...) { va_list a; va_start(a, this_); @@ -198,15 +210,19 @@ class Processor { return r; } - object - invoke(Thread* t, object loader, const char* className, - const char* methodName, const char* methodSpec, object this_, ...) + object invoke(Thread* t, + GcClassLoader* loader, + const char* className, + const char* methodName, + const char* methodSpec, + object this_, + ...) { va_list a; va_start(a, this_); - object r = invokeList - (t, loader, className, methodName, methodSpec, this_, a); + object r + = invokeList(t, loader, className, methodName, methodSpec, this_, a); va_end(a); @@ -219,6 +235,6 @@ Processor* makeProcessor(System* system, const char* crashDumpDirectory, bool useNativeFeatures); -} // namespace vm +} // namespace vm -#endif//PROCESSOR_H +#endif // PROCESSOR_H diff --git a/src/avian/target-fields.h b/src/avian/target-fields.h index 9efc1212e8..70c6dd22b6 100644 --- a/src/avian/target-fields.h +++ b/src/avian/target-fields.h @@ -11,9 +11,8 @@ #ifndef AVIAN_TARGET_FIELDS_H #define AVIAN_TARGET_FIELDS_H - #ifdef TARGET_BYTES_PER_WORD -# if (TARGET_BYTES_PER_WORD == 8) +#if (TARGET_BYTES_PER_WORD == 8) #define TARGET_THREAD_EXCEPTION 80 #define TARGET_THREAD_EXCEPTIONSTACKADJUSTMENT 2264 @@ -33,7 +32,7 @@ #define TARGET_THREAD_THUNKTABLE 2328 #define TARGET_THREAD_STACKLIMIT 2376 -# elif (TARGET_BYTES_PER_WORD == 4) +#elif(TARGET_BYTES_PER_WORD == 4) #define TARGET_THREAD_EXCEPTION 44 #define TARGET_THREAD_EXCEPTIONSTACKADJUSTMENT 2168 @@ -53,12 +52,11 @@ #define TARGET_THREAD_THUNKTABLE 2200 #define TARGET_THREAD_STACKLIMIT 2224 -# else -# error -# endif #else -# error +#error +#endif +#else +#error #endif #endif - diff --git a/src/avian/target.h b/src/avian/target.h index f9e77291a7..dd354b66eb 100644 --- a/src/avian/target.h +++ b/src/avian/target.h @@ -17,96 +17,82 @@ namespace vm { template -inline T -targetV1(T v) +inline T targetV1(T v) { return v; } template -inline T -swapV2(T v) +inline T swapV2(T v) { - return (((v >> 8) & 0xFF) | - ((v << 8))); + return (((v >> 8) & 0xFF) | ((v << 8))); } template -inline T -swapV4(T v) +inline T swapV4(T v) { - return (((v >> 24) & 0x000000FF) | - ((v >> 8) & 0x0000FF00) | - ((v << 8) & 0x00FF0000) | - ((v << 24))); + return (((v >> 24) & 0x000000FF) | ((v >> 8) & 0x0000FF00) + | ((v << 8) & 0x00FF0000) | ((v << 24))); } template -inline T -swapV8(T v) +inline T swapV8(T v) { - return (((static_cast(v) >> 56) & UINT64_C(0x00000000000000FF)) | - ((static_cast(v) >> 40) & UINT64_C(0x000000000000FF00)) | - ((static_cast(v) >> 24) & UINT64_C(0x0000000000FF0000)) | - ((static_cast(v) >> 8) & UINT64_C(0x00000000FF000000)) | - ((static_cast(v) << 8) & UINT64_C(0x000000FF00000000)) | - ((static_cast(v) << 24) & UINT64_C(0x0000FF0000000000)) | - ((static_cast(v) << 40) & UINT64_C(0x00FF000000000000)) | - ((static_cast(v) << 56))); + return (((static_cast(v) >> 56) & UINT64_C(0x00000000000000FF)) + | ((static_cast(v) >> 40) & UINT64_C(0x000000000000FF00)) + | ((static_cast(v) >> 24) & UINT64_C(0x0000000000FF0000)) + | ((static_cast(v) >> 8) & UINT64_C(0x00000000FF000000)) + | ((static_cast(v) << 8) & UINT64_C(0x000000FF00000000)) + | ((static_cast(v) << 24) & UINT64_C(0x0000FF0000000000)) + | ((static_cast(v) << 40) & UINT64_C(0x00FF000000000000)) + | ((static_cast(v) << 56))); } #ifdef TARGET_OPPOSITE_ENDIAN template -inline T -targetV2(T v) +inline T targetV2(T v) { return swapV2(v); } template -inline T -targetV4(T v) +inline T targetV4(T v) { return swapV4(v); } template -inline T -targetV8(T v) +inline T targetV8(T v) { return swapV8(v); } #else template -inline T -targetV2(T v) +inline T targetV2(T v) { return v; } template -inline T -targetV4(T v) +inline T targetV4(T v) { return v; } template -inline T -targetV8(T v) +inline T targetV8(T v) { return v; } #endif #ifdef TARGET_BYTES_PER_WORD -# if (TARGET_BYTES_PER_WORD == 8) +#if (TARGET_BYTES_PER_WORD == 8) template -inline T -targetVW(T v) +inline T targetVW(T v) { return targetV8(v); } @@ -116,15 +102,14 @@ typedef int64_t target_intptr_t; const unsigned TargetClassFixedSize = 12; const unsigned TargetClassArrayElementSize = 14; -const unsigned TargetClassVtable = 128; +const unsigned TargetClassVtable = 136; const unsigned TargetFieldOffset = 12; -# elif (TARGET_BYTES_PER_WORD == 4) +#elif(TARGET_BYTES_PER_WORD == 4) template -inline T -targetVW(T v) +inline T targetVW(T v) { return targetV4(v); } @@ -134,15 +119,15 @@ typedef int32_t target_intptr_t; const unsigned TargetClassFixedSize = 8; const unsigned TargetClassArrayElementSize = 10; -const unsigned TargetClassVtable = 68; +const unsigned TargetClassVtable = 72; const unsigned TargetFieldOffset = 8; -# else -# error -# endif #else -# error +#error +#endif +#else +#error #endif const unsigned TargetBytesPerWord = TARGET_BYTES_PER_WORD; @@ -150,19 +135,18 @@ const unsigned TargetBytesPerWord = TARGET_BYTES_PER_WORD; const unsigned TargetBitsPerWord = TargetBytesPerWord * 8; const target_uintptr_t TargetPointerMask -= ((~static_cast(0)) / TargetBytesPerWord) - * TargetBytesPerWord; + = ((~static_cast(0)) / TargetBytesPerWord) + * TargetBytesPerWord; const unsigned TargetArrayLength = TargetBytesPerWord; const unsigned TargetArrayBody = TargetBytesPerWord * 2; -inline void -targetMarkBit(target_uintptr_t* map, unsigned i) +inline void targetMarkBit(target_uintptr_t* map, unsigned i) { - map[wordOf(i)] |= - targetVW(static_cast(1) << bitOf(i)); + map[wordOf(i)] |= targetVW(static_cast(1) + << bitOf(i)); } -} // namespace vm +} // namespace vm -#endif//TARGET_H +#endif // TARGET_H diff --git a/src/avian/types.h b/src/avian/types.h index d2ff41669d..6e0e396641 100644 --- a/src/avian/types.h +++ b/src/avian/types.h @@ -20,4 +20,4 @@ #define DOUBLE_TYPE 6 #define POINTER_TYPE 7 -#endif//TYPES_H +#endif // TYPES_H diff --git a/src/avian/util.h b/src/avian/util.h index 993abf1829..852d480499 100644 --- a/src/avian/util.h +++ b/src/avian/util.h @@ -16,49 +16,58 @@ namespace vm { -object -hashMapFindNode(Thread* t, object map, object key, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)); +GcTriple* hashMapFindNode(Thread* t, + GcHashMap* map, + object key, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)); -inline object -hashMapFind(Thread* t, object map, object key, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)) +inline object hashMapFind(Thread* t, + GcHashMap* map, + object key, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)) { - object n = hashMapFindNode(t, map, key, hash, equal); - return (n ? tripleSecond(t, n) : 0); + GcTriple* n = hashMapFindNode(t, map, key, hash, equal); + return (n ? n->second() : 0); } -void -hashMapResize(Thread* t, object map, uint32_t (*hash)(Thread*, object), - unsigned size); - -void -hashMapInsert(Thread* t, object map, object key, object value, - uint32_t (*hash)(Thread*, object)); - -inline bool -hashMapInsertOrReplace(Thread* t, object map, object key, object value, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)) -{ - object n = hashMapFindNode(t, map, key, hash, equal); - if (n == 0) { - hashMapInsert(t, map, key, value, hash); - return true; - } else { - set(t, n, TripleSecond, value); - return false; - } -} - -inline bool -hashMapInsertMaybe(Thread* t, object map, object key, object value, +void hashMapResize(Thread* t, + GcHashMap* map, uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)) + unsigned size); + +void hashMapInsert(Thread* t, + GcHashMap* map, + object key, + object value, + uint32_t (*hash)(Thread*, object)); + +inline bool hashMapInsertOrReplace(Thread* t, + GcHashMap* map, + object key, + object value, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)) { - object n = hashMapFindNode(t, map, key, hash, equal); + GcTriple* n = hashMapFindNode(t, map, key, hash, equal); + if (n == 0) { + hashMapInsert(t, map, key, value, hash); + return true; + } else { + n->setSecond(t, value); + return false; + } +} + +inline bool hashMapInsertMaybe(Thread* t, + GcHashMap* map, + object key, + object value, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)) +{ + GcTriple* n = hashMapFindNode(t, map, key, hash, equal); if (n == 0) { hashMapInsert(t, map, key, value, hash); return true; @@ -67,53 +76,58 @@ hashMapInsertMaybe(Thread* t, object map, object key, object value, } } -object -hashMapRemove(Thread* t, object map, object key, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)); +object hashMapRemove(Thread* t, + GcHashMap* map, + object key, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)); -object -hashMapIterator(Thread* t, object map); +object hashMapIterator(Thread* t, GcHashMap* map); -object -hashMapIteratorNext(Thread* t, object it); +object hashMapIteratorNext(Thread* t, object it); -void -listAppend(Thread* t, object list, object value); +void listAppend(Thread* t, GcList* list, object value); -object -vectorAppend(Thread* t, object vector, object value); +GcVector* vectorAppend(Thread* t, GcVector* vector, object value); -object -growArray(Thread* t, object array); +object growArray(Thread* t, object array); -object -treeQuery(Thread* t, object tree, intptr_t key, object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)); +object treeQuery(Thread* t, + GcTreeNode* tree, + intptr_t key, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)); -object -treeInsert(Thread* t, Zone* zone, object tree, intptr_t key, object value, - object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)); +GcTreeNode* treeInsert(Thread* t, + Zone* zone, + GcTreeNode* tree, + intptr_t key, + object value, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)); -void -treeUpdate(Thread* t, object tree, intptr_t key, object value, object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)); +void treeUpdate(Thread* t, + GcTreeNode* tree, + intptr_t key, + object value, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)); -class HashMapIterator: public Thread::Protector { +class HashMapIterator : public Thread::Protector { public: - HashMapIterator(Thread* t, object map): - Protector(t), map(map), node(0), index(0) + HashMapIterator(Thread* t, GcHashMap* map) + : Protector(t), map(map), node(0), index(0) { find(); } - void find() { - object array = hashMapArray(t, map); + void find() + { + GcArray* array = map->array(); if (array) { - for (unsigned i = index; i < arrayLength(t, array); ++i) { - if (arrayBody(t, array, i)) { - node = arrayBody(t, array, i); + for (unsigned i = index; i < array->length(); ++i) { + if (array->body()[i]) { + node = cast(t, array->body()[i]); index = i + 1; return; } @@ -122,15 +136,17 @@ class HashMapIterator: public Thread::Protector { node = 0; } - bool hasMore() { + bool hasMore() + { return node != 0; } - object next() { + GcTriple* next() + { if (node) { - object n = node; - if (tripleThird(t, node)) { - node = tripleThird(t, node); + GcTriple* n = node; + if (node->third()) { + node = cast(t, node->third()); } else { find(); } @@ -140,16 +156,17 @@ class HashMapIterator: public Thread::Protector { } } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&map); v->visit(&node); } - object map; - object node; + GcHashMap* map; + GcTriple* node; unsigned index; }; -} // vm +} // vm -#endif//UTIL_H +#endif // UTIL_H diff --git a/src/avian/x86.h b/src/avian/x86.h index 25ff5b560f..c4cd4e58b4 100644 --- a/src/avian/x86.h +++ b/src/avian/x86.h @@ -15,150 +15,164 @@ #include "avian/common.h" #ifdef _MSC_VER -# include "windows.h" -# pragma push_macro("assert") -# include "intrin.h" -# pragma pop_macro("assert") -# undef interface +#include "windows.h" +#pragma push_macro("assert") +#include "intrin.h" +#pragma pop_macro("assert") +#undef interface #endif #if (defined ARCH_x86_32) || (defined PLATFORM_WINDOWS) -# define VA_LIST(x) (&(x)) +#define VA_LIST(x) (&(x)) #else -# define VA_LIST(x) (x) +#define VA_LIST(x) (x) #endif #ifdef __APPLE__ -# include "mach/mach_types.h" -# include "mach/thread_act.h" -# include "mach/thread_status.h" +#include "mach/mach_types.h" +#include "mach/thread_act.h" +#include "mach/thread_status.h" -# if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32) -# define FIELD(x) __##x -# else -# define FIELD(x) x -# endif +#if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32) +#define FIELD(x) __##x +#else +#define FIELD(x) x +#endif #endif #ifdef ARCH_x86_32 -# ifdef __APPLE__ -# define THREAD_STATE x86_THREAD_STATE32 -# define THREAD_STATE_TYPE x86_thread_state32_t -# define THREAD_STATE_COUNT x86_THREAD_STATE32_COUNT +#ifdef __APPLE__ +#define THREAD_STATE x86_THREAD_STATE32 +#define THREAD_STATE_TYPE x86_thread_state32_t +#define THREAD_STATE_COUNT x86_THREAD_STATE32_COUNT -# define THREAD_STATE_IP(state) ((state).FIELD(eip)) -# define THREAD_STATE_STACK(state) ((state).FIELD(esp)) -# define THREAD_STATE_THREAD(state) ((state).FIELD(ebx)) -# define THREAD_STATE_LINK(state) ((state).FIELD(ecx)) -# define THREAD_STATE_FRAME(state) ((state).FIELD(ebp)) +#define THREAD_STATE_IP(state) ((state).FIELD(eip)) +#define THREAD_STATE_STACK(state) ((state).FIELD(esp)) +#define THREAD_STATE_THREAD(state) ((state).FIELD(ebx)) +#define THREAD_STATE_LINK(state) ((state).FIELD(ecx)) +#define THREAD_STATE_FRAME(state) ((state).FIELD(ebp)) -# define IP_REGISTER(context) \ - THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) -# define STACK_REGISTER(context) \ +#define IP_REGISTER(context) THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) +#define STACK_REGISTER(context) \ THREAD_STATE_STACK(context->uc_mcontext->FIELD(ss)) -# define THREAD_REGISTER(context) \ +#define THREAD_REGISTER(context) \ THREAD_STATE_THREAD(context->uc_mcontext->FIELD(ss)) -# define LINK_REGISTER(context) \ +#define LINK_REGISTER(context) \ THREAD_STATE_LINK(context->uc_mcontext->FIELD(ss)) -# define FRAME_REGISTER(context) \ +#define FRAME_REGISTER(context) \ THREAD_STATE_FRAME(context->uc_mcontext->FIELD(ss)) -# elif (defined __QNX__) -# define IP_REGISTER(context) (context->uc_mcontext.cpu.eip) -# define STACK_REGISTER(context) (context->uc_mcontext.cpu.esp) -# define THREAD_REGISTER(context) (context->uc_mcontext.cpu.ebx) -# define LINK_REGISTER(context) (context->uc_mcontext.cpu.ecx) -# define FRAME_REGISTER(context) (context->uc_mcontext.cpu.ebp) -# elif (defined __FreeBSD__) -# define IP_REGISTER(context) (context->uc_mcontext.mc_eip) -# define STACK_REGISTER(context) (context->uc_mcontext.mc_esp) -# define THREAD_REGISTER(context) (context->uc_mcontext.mc_ebx) -# define LINK_REGISTER(context) (context->uc_mcontext.mc_ecx) -# define FRAME_REGISTER(context) (context->uc_mcontext.mc_ebp) -# else -# define IP_REGISTER(context) (context->uc_mcontext.gregs[REG_EIP]) -# define STACK_REGISTER(context) (context->uc_mcontext.gregs[REG_ESP]) -# define THREAD_REGISTER(context) (context->uc_mcontext.gregs[REG_EBX]) -# define LINK_REGISTER(context) (context->uc_mcontext.gregs[REG_ECX]) -# define FRAME_REGISTER(context) (context->uc_mcontext.gregs[REG_EBP]) -# endif +#elif(defined __QNX__) +#define IP_REGISTER(context) (context->uc_mcontext.cpu.eip) +#define STACK_REGISTER(context) (context->uc_mcontext.cpu.esp) +#define THREAD_REGISTER(context) (context->uc_mcontext.cpu.ebx) +#define LINK_REGISTER(context) (context->uc_mcontext.cpu.ecx) +#define FRAME_REGISTER(context) (context->uc_mcontext.cpu.ebp) +#elif(defined __FreeBSD__) +#define IP_REGISTER(context) (context->uc_mcontext.mc_eip) +#define STACK_REGISTER(context) (context->uc_mcontext.mc_esp) +#define THREAD_REGISTER(context) (context->uc_mcontext.mc_ebx) +#define LINK_REGISTER(context) (context->uc_mcontext.mc_ecx) +#define FRAME_REGISTER(context) (context->uc_mcontext.mc_ebp) +#else +#define IP_REGISTER(context) (context->uc_mcontext.gregs[REG_EIP]) +#define STACK_REGISTER(context) (context->uc_mcontext.gregs[REG_ESP]) +#define THREAD_REGISTER(context) (context->uc_mcontext.gregs[REG_EBX]) +#define LINK_REGISTER(context) (context->uc_mcontext.gregs[REG_ECX]) +#define FRAME_REGISTER(context) (context->uc_mcontext.gregs[REG_EBP]) +#endif -extern "C" uint64_t -vmNativeCall(void* function, void* stack, unsigned stackSize, - unsigned returnType); +extern "C" uint64_t vmNativeCall(void* function, + void* stack, + unsigned stackSize, + unsigned returnType); namespace vm { -inline uint64_t -dynamicCall(void* function, uintptr_t* arguments, uint8_t*, - unsigned, unsigned argumentsSize, unsigned returnType) +inline uint64_t dynamicCall(void* function, + uintptr_t* arguments, + uint8_t*, + unsigned, + unsigned argumentsSize, + unsigned returnType) { return vmNativeCall(function, arguments, argumentsSize, returnType); } -} // namespace vm +} // namespace vm #elif defined ARCH_x86_64 -# ifdef __APPLE__ -# define THREAD_STATE x86_THREAD_STATE64 -# define THREAD_STATE_TYPE x86_thread_state64_t -# define THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT +#ifdef __APPLE__ +#define THREAD_STATE x86_THREAD_STATE64 +#define THREAD_STATE_TYPE x86_thread_state64_t +#define THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT -# define THREAD_STATE_IP(state) ((state).FIELD(rip)) -# define THREAD_STATE_STACK(state) ((state).FIELD(rsp)) -# define THREAD_STATE_THREAD(state) ((state).FIELD(rbx)) -# define THREAD_STATE_LINK(state) ((state).FIELD(rcx)) -# define THREAD_STATE_FRAME(state) ((state).FIELD(rbp)) +#define THREAD_STATE_IP(state) ((state).FIELD(rip)) +#define THREAD_STATE_STACK(state) ((state).FIELD(rsp)) +#define THREAD_STATE_THREAD(state) ((state).FIELD(rbx)) +#define THREAD_STATE_LINK(state) ((state).FIELD(rcx)) +#define THREAD_STATE_FRAME(state) ((state).FIELD(rbp)) -# define IP_REGISTER(context) \ - THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) -# define STACK_REGISTER(context) \ +#define IP_REGISTER(context) THREAD_STATE_IP(context->uc_mcontext->FIELD(ss)) +#define STACK_REGISTER(context) \ THREAD_STATE_STACK(context->uc_mcontext->FIELD(ss)) -# define THREAD_REGISTER(context) \ +#define THREAD_REGISTER(context) \ THREAD_STATE_THREAD(context->uc_mcontext->FIELD(ss)) -# define LINK_REGISTER(context) \ +#define LINK_REGISTER(context) \ THREAD_STATE_LINK(context->uc_mcontext->FIELD(ss)) -# define FRAME_REGISTER(context) \ +#define FRAME_REGISTER(context) \ THREAD_STATE_FRAME(context->uc_mcontext->FIELD(ss)) -# elif (defined __FreeBSD__) -# define IP_REGISTER(context) (context->uc_mcontext.mc_rip) -# define STACK_REGISTER(context) (context->uc_mcontext.mc_rsp) -# define THREAD_REGISTER(context) (context->uc_mcontext.mc_rbx) -# define LINK_REGISTER(context) (context->uc_mcontext.mc_rcx) -# define FRAME_REGISTER(context) (context->uc_mcontext.mc_rbp) -# else -# define IP_REGISTER(context) (context->uc_mcontext.gregs[REG_RIP]) -# define STACK_REGISTER(context) (context->uc_mcontext.gregs[REG_RSP]) -# define THREAD_REGISTER(context) (context->uc_mcontext.gregs[REG_RBX]) -# define LINK_REGISTER(context) (context->uc_mcontext.gregs[REG_RCX]) -# define FRAME_REGISTER(context) (context->uc_mcontext.gregs[REG_RBP]) -# endif +#elif(defined __FreeBSD__) +#define IP_REGISTER(context) (context->uc_mcontext.mc_rip) +#define STACK_REGISTER(context) (context->uc_mcontext.mc_rsp) +#define THREAD_REGISTER(context) (context->uc_mcontext.mc_rbx) +#define LINK_REGISTER(context) (context->uc_mcontext.mc_rcx) +#define FRAME_REGISTER(context) (context->uc_mcontext.mc_rbp) +#else +#define IP_REGISTER(context) (context->uc_mcontext.gregs[REG_RIP]) +#define STACK_REGISTER(context) (context->uc_mcontext.gregs[REG_RSP]) +#define THREAD_REGISTER(context) (context->uc_mcontext.gregs[REG_RBX]) +#define LINK_REGISTER(context) (context->uc_mcontext.gregs[REG_RCX]) +#define FRAME_REGISTER(context) (context->uc_mcontext.gregs[REG_RBP]) +#endif extern "C" uint64_t -# ifdef PLATFORM_WINDOWS -vmNativeCall(void* function, void* stack, unsigned stackSize, - unsigned returnType); -# else -vmNativeCall(void* function, void* stack, unsigned stackSize, - void* gprTable, void* sseTable, unsigned returnType); -# endif +#ifdef PLATFORM_WINDOWS + vmNativeCall(void* function, + void* stack, + unsigned stackSize, + unsigned returnType); +#else + vmNativeCall(void* function, + void* stack, + unsigned stackSize, + void* gprTable, + void* sseTable, + unsigned returnType); +#endif namespace vm { -# ifdef PLATFORM_WINDOWS -inline uint64_t -dynamicCall(void* function, uint64_t* arguments, UNUSED uint8_t* argumentTypes, - unsigned argumentCount, unsigned, unsigned returnType) +#ifdef PLATFORM_WINDOWS +inline uint64_t dynamicCall(void* function, + uint64_t* arguments, + UNUSED uint8_t* argumentTypes, + unsigned argumentCount, + unsigned, + unsigned returnType) { return vmNativeCall(function, arguments, argumentCount, returnType); } -# else -inline uint64_t -dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, - unsigned argumentCount, unsigned, unsigned returnType) +#else +inline uint64_t dynamicCall(void* function, + uintptr_t* arguments, + uint8_t* argumentTypes, + unsigned argumentCount, + unsigned, + unsigned returnType) { const unsigned GprCount = 6; uint64_t gprTable[GprCount]; @@ -192,22 +206,24 @@ dynamicCall(void* function, uintptr_t* arguments, uint8_t* argumentTypes, } } - return vmNativeCall(function, stack, stackIndex * BytesPerWord, + return vmNativeCall(function, + stack, + stackIndex * BytesPerWord, (gprIndex ? gprTable : 0), - (sseIndex ? sseTable : 0), returnType); + (sseIndex ? sseTable : 0), + returnType); } #endif -} // namespace vm +} // namespace vm #else -# error unsupported architecture +#error unsupported architecture #endif namespace vm { -inline void -trap() +inline void trap() { #ifdef _MSC_VER __asm int 3 @@ -216,50 +232,44 @@ trap() #endif } -inline void -programOrderMemoryBarrier() +inline void programOrderMemoryBarrier() { compileTimeMemoryBarrier(); } -inline void -storeStoreMemoryBarrier() +inline void storeStoreMemoryBarrier() { programOrderMemoryBarrier(); } -inline void -storeLoadMemoryBarrier() +inline void storeLoadMemoryBarrier() { #ifdef _MSC_VER MemoryBarrier(); #elif defined ARCH_x86_32 - __asm__ __volatile__("lock; addl $0,0(%%esp)": : :"memory"); + __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory"); #elif defined ARCH_x86_64 - __asm__ __volatile__("mfence": : :"memory"); -#endif // ARCH_x86_64 + __asm__ __volatile__("mfence" : : : "memory"); +#endif // ARCH_x86_64 } -inline void -loadMemoryBarrier() +inline void loadMemoryBarrier() { programOrderMemoryBarrier(); } -inline void -syncInstructionCache(const void*, unsigned) +inline void syncInstructionCache(const void*, unsigned) { programOrderMemoryBarrier(); } #ifdef USE_ATOMIC_OPERATIONS -inline bool -atomicCompareAndSwap32(uint32_t* p, uint32_t old, uint32_t new_) +inline bool atomicCompareAndSwap32(uint32_t* p, uint32_t old, uint32_t new_) { #ifdef _MSC_VER - return old == InterlockedCompareExchange - (reinterpret_cast(p), new_, old); -#elif (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) + return old + == InterlockedCompareExchange(reinterpret_cast(p), new_, old); +#elif(__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) return __sync_bool_compare_and_swap(p, old, new_); #else uint8_t result; @@ -275,13 +285,12 @@ atomicCompareAndSwap32(uint32_t* p, uint32_t old, uint32_t new_) #define AVIAN_HAS_CAS64 -inline bool -atomicCompareAndSwap64(uint64_t* p, uint64_t old, uint64_t new_) +inline bool atomicCompareAndSwap64(uint64_t* p, uint64_t old, uint64_t new_) { #ifdef _MSC_VER - return old == InterlockedCompareExchange64 - (reinterpret_cast(p), new_, old); -#elif (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) + return old == InterlockedCompareExchange64( + reinterpret_cast(p), new_, old); +#elif(__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1) return __sync_bool_compare_and_swap(p, old, new_); #elif defined ARCH_x86_32 uint8_t result; @@ -308,17 +317,16 @@ atomicCompareAndSwap64(uint64_t* p, uint64_t old, uint64_t new_) #endif } -inline bool -atomicCompareAndSwap(uintptr_t* p, uintptr_t old, uintptr_t new_) +inline bool atomicCompareAndSwap(uintptr_t* p, uintptr_t old, uintptr_t new_) { #ifdef ARCH_x86_32 return atomicCompareAndSwap32(reinterpret_cast(p), old, new_); #elif defined ARCH_x86_64 return atomicCompareAndSwap64(reinterpret_cast(p), old, new_); -#endif // ARCH_x86_64 +#endif // ARCH_x86_64 } -#endif // USE_ATOMIC_OPERATIONS +#endif // USE_ATOMIC_OPERATIONS -} // namespace vm +} // namespace vm -#endif//X86_H +#endif // X86_H diff --git a/src/avian/zlib-custom.h b/src/avian/zlib-custom.h index 9d749a70a5..de4e05616c 100644 --- a/src/avian/zlib-custom.h +++ b/src/avian/zlib-custom.h @@ -13,11 +13,19 @@ #ifdef inflateInit2 #undef inflateInit2 #define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, static_cast(sizeof(z_stream))) + inflateInit2_( \ + (strm), (windowBits), ZLIB_VERSION, static_cast(sizeof(z_stream))) #endif #ifdef deflateInit2 #undef deflateInit2 #define deflateInit2(strm, level, windowBits) \ - deflateInit2_((strm), (level), Z_DEFLATED, (windowBits), 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, static_cast(sizeof(z_stream))) + deflateInit2_((strm), \ + (level), \ + Z_DEFLATED, \ + (windowBits), \ + 8, \ + Z_DEFAULT_STRATEGY, \ + ZLIB_VERSION, \ + static_cast(sizeof(z_stream))) #endif diff --git a/src/avian/zone.h b/src/avian/zone.h index cc0db700b8..71e80aec90 100644 --- a/src/avian/zone.h +++ b/src/avian/zone.h @@ -21,9 +21,9 @@ class Zone : public avian::util::Allocator { public: class Segment { public: - Segment(Segment* next, unsigned size): - next(next), size(size), position(0) - { } + Segment(Segment* next, unsigned size) : next(next), size(size), position(0) + { + } Segment* next; uintptr_t size; @@ -31,19 +31,23 @@ class Zone : public avian::util::Allocator { uint8_t data[0]; }; - Zone(System* s, Allocator* allocator, unsigned minimumFootprint): - s(s), - allocator(allocator), - segment(0), - minimumFootprint(minimumFootprint < sizeof(Segment) ? 0 : - minimumFootprint - sizeof(Segment)) - { } + Zone(System* s, Allocator* allocator, unsigned minimumFootprint) + : s(s), + allocator(allocator), + segment(0), + minimumFootprint(minimumFootprint < sizeof(Segment) + ? 0 + : minimumFootprint - sizeof(Segment)) + { + } - ~Zone() { + ~Zone() + { dispose(); } - void dispose() { + void dispose() + { for (Segment* seg = segment, *next; seg; seg = next) { next = seg->next; allocator->free(seg, sizeof(Segment) + seg->size); @@ -52,18 +56,20 @@ class Zone : public avian::util::Allocator { segment = 0; } - static unsigned padToPage(unsigned size) { - return (size + (LikelyPageSizeInBytes - 1)) - & ~(LikelyPageSizeInBytes - 1); + static unsigned padToPage(unsigned size) + { + return (size + (LikelyPageSizeInBytes - 1)) & ~(LikelyPageSizeInBytes - 1); } - bool tryEnsure(unsigned space) { + bool tryEnsure(unsigned space) + { if (segment == 0 or segment->position + space > segment->size) { - unsigned size = padToPage - (avian::util::max - (space, avian::util::max - (minimumFootprint, segment == 0 ? 0 : segment->size * 2)) - + sizeof(Segment)); + unsigned size = padToPage( + avian::util::max( + space, + avian::util::max(minimumFootprint, + segment == 0 ? 0 : segment->size * 2)) + + sizeof(Segment)); void* p = allocator->tryAllocate(size); if (p == 0) { @@ -79,16 +85,18 @@ class Zone : public avian::util::Allocator { return true; } - void ensure(unsigned space) { + void ensure(unsigned space) + { if (segment == 0 or segment->position + space > segment->size) { unsigned size = padToPage(space + sizeof(Segment)); segment = new (allocator->allocate(size)) - Segment(segment, size - sizeof(Segment)); + Segment(segment, size - sizeof(Segment)); } } - virtual void* tryAllocate(unsigned size) { + virtual void* tryAllocate(unsigned size) + { size = pad(size); if (tryEnsure(size)) { void* r = segment->data + segment->position; @@ -99,7 +107,8 @@ class Zone : public avian::util::Allocator { } } - virtual void* allocate(unsigned size) { + virtual void* allocate(unsigned size) + { size = pad(size); void* p = tryAllocate(size); if (p) { @@ -112,7 +121,8 @@ class Zone : public avian::util::Allocator { } } - void* peek(unsigned size) { + void* peek(unsigned size) + { size = pad(size); Segment* s = segment; while (s->position < size) { @@ -122,7 +132,8 @@ class Zone : public avian::util::Allocator { return s->data + (s->position - size); } - void pop(unsigned size) { + void pop(unsigned size) + { size = pad(size); Segment* s = segment; while (s->position < size) { @@ -135,11 +146,12 @@ class Zone : public avian::util::Allocator { segment = s; } - virtual void free(const void*, unsigned) { + virtual void free(const void*, unsigned) + { // not supported abort(s); } - + System* s; Allocator* allocator; void* context; @@ -147,6 +159,6 @@ class Zone : public avian::util::Allocator { unsigned minimumFootprint; }; -} // namespace vm +} // namespace vm -#endif//ZONE_H +#endif // ZONE_H diff --git a/src/boot-javahome.cpp b/src/boot-javahome.cpp index a8df5b4b47..c44fb94b9e 100644 --- a/src/boot-javahome.cpp +++ b/src/boot-javahome.cpp @@ -12,26 +12,23 @@ #ifdef BOOT_JAVAHOME -#if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) -# define SYMBOL(x) binary_javahome_jar_##x +#if (!defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) +#define SYMBOL(x) binary_javahome_jar_##x #else -# define SYMBOL(x) _binary_javahome_jar_##x +#define SYMBOL(x) _binary_javahome_jar_##x #endif extern "C" { +extern const uint8_t SYMBOL(start)[]; +extern const uint8_t SYMBOL(end)[]; - extern const uint8_t SYMBOL(start)[]; - extern const uint8_t SYMBOL(end)[]; - - AVIAN_EXPORT const uint8_t* - javahomeJar(unsigned* size) - { - *size = SYMBOL(end) - SYMBOL(start); - return SYMBOL(start); - } - +AVIAN_EXPORT const uint8_t* javahomeJar(unsigned* size) +{ + *size = SYMBOL(end) - SYMBOL(start); + return SYMBOL(start); +} } #undef SYMBOL -#endif//BOOT_JAVAHOME +#endif // BOOT_JAVAHOME diff --git a/src/boot.cpp b/src/boot.cpp index f641751918..f2e0397975 100644 --- a/src/boot.cpp +++ b/src/boot.cpp @@ -14,68 +14,64 @@ // since we aren't linking against libstdc++, we must implement this // ourselves: -extern "C" void __cxa_pure_virtual(void) { abort(); } +extern "C" void __cxa_pure_virtual(void) +{ + abort(); +} #ifdef BOOT_IMAGE -#if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) -# define BOOTIMAGE_SYMBOL(x) binary_bootimage_bin_##x -# define CODEIMAGE_SYMBOL(x) binary_codeimage_bin_##x +#if (!defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) +#define BOOTIMAGE_SYMBOL(x) binary_bootimage_bin_##x +#define CODEIMAGE_SYMBOL(x) binary_codeimage_bin_##x #else -# define BOOTIMAGE_SYMBOL(x) _binary_bootimage_bin_##x -# define CODEIMAGE_SYMBOL(x) _binary_codeimage_bin_##x +#define BOOTIMAGE_SYMBOL(x) _binary_bootimage_bin_##x +#define CODEIMAGE_SYMBOL(x) _binary_codeimage_bin_##x #endif extern "C" { +extern const uint8_t BOOTIMAGE_SYMBOL(start)[]; +extern const uint8_t BOOTIMAGE_SYMBOL(end)[]; - extern const uint8_t BOOTIMAGE_SYMBOL(start)[]; - extern const uint8_t BOOTIMAGE_SYMBOL(end)[]; +AVIAN_EXPORT const uint8_t* bootimageBin(unsigned* size) +{ + *size = BOOTIMAGE_SYMBOL(end) - BOOTIMAGE_SYMBOL(start); + return BOOTIMAGE_SYMBOL(start); +} - AVIAN_EXPORT const uint8_t* - bootimageBin(unsigned* size) - { - *size = BOOTIMAGE_SYMBOL(end) - BOOTIMAGE_SYMBOL(start); - return BOOTIMAGE_SYMBOL(start); - } - - extern const uint8_t CODEIMAGE_SYMBOL(start)[]; - extern const uint8_t CODEIMAGE_SYMBOL(end)[]; - - AVIAN_EXPORT const uint8_t* - codeimageBin(unsigned* size) - { - *size = CODEIMAGE_SYMBOL(end) - CODEIMAGE_SYMBOL(start); - return CODEIMAGE_SYMBOL(start); - } +extern const uint8_t CODEIMAGE_SYMBOL(start)[]; +extern const uint8_t CODEIMAGE_SYMBOL(end)[]; +AVIAN_EXPORT const uint8_t* codeimageBin(unsigned* size) +{ + *size = CODEIMAGE_SYMBOL(end) - CODEIMAGE_SYMBOL(start); + return CODEIMAGE_SYMBOL(start); +} } #undef SYMBOL -#endif//BOOT_IMAGE +#endif // BOOT_IMAGE #ifdef BOOT_CLASSPATH -#if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) -# define SYMBOL(x) binary_classpath_jar_##x +#if (!defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) +#define SYMBOL(x) binary_classpath_jar_##x #else -# define SYMBOL(x) _binary_classpath_jar_##x +#define SYMBOL(x) _binary_classpath_jar_##x #endif extern "C" { +extern const uint8_t SYMBOL(start)[]; +extern const uint8_t SYMBOL(end)[]; - extern const uint8_t SYMBOL(start)[]; - extern const uint8_t SYMBOL(end)[]; - - AVIAN_EXPORT const uint8_t* - classpathJar(unsigned* size) - { - *size = SYMBOL(end) - SYMBOL(start); - return SYMBOL(start); - } - +AVIAN_EXPORT const uint8_t* classpathJar(unsigned* size) +{ + *size = SYMBOL(end) - SYMBOL(start); + return SYMBOL(start); +} } #undef SYMBOL -#endif//BOOT_CLASSPATH +#endif // BOOT_CLASSPATH diff --git a/src/bootimage-fields.cpp b/src/bootimage-fields.cpp index a090268de2..761eef88e5 100644 --- a/src/bootimage-fields.cpp +++ b/src/bootimage-fields.cpp @@ -1,6 +1,6 @@ #ifndef FIELD -# define FIELD(name) -# define FIELD_DEFINED +#define FIELD(name) +#define FIELD_DEFINED #endif FIELD(magic) @@ -23,13 +23,13 @@ FIELD(methodTreeSentinal) FIELD(virtualThunks) #ifdef FIELD_DEFINED -# undef FIELD -# undef FIELD_DEFINED +#undef FIELD +#undef FIELD_DEFINED #endif #ifndef THUNK_FIELD -# define THUNK_FIELD(name) -# define THUNK_FIELD_DEFINED +#define THUNK_FIELD(name) +#define THUNK_FIELD_DEFINED #endif THUNK_FIELD(default_); @@ -40,6 +40,6 @@ THUNK_FIELD(stackOverflow); THUNK_FIELD(table); #ifdef THUNK_FIELD_DEFINED -# undef THUNK_FIELD -# undef THUNK_FIELD_DEFINED +#undef THUNK_FIELD +#undef THUNK_FIELD_DEFINED #endif diff --git a/src/bootimage-template.cpp b/src/bootimage-template.cpp index bf32267ece..e8f080cfb2 100644 --- a/src/bootimage-template.cpp +++ b/src/bootimage-template.cpp @@ -1,26 +1,25 @@ const unsigned NAME(BootMask) = (~static_cast(0)) - / NAME(BytesPerWord); + / NAME(BytesPerWord); const unsigned NAME(BootShift) = 32 - avian::util::log(NAME(BytesPerWord)); const unsigned NAME(BootFlatConstant) = 1 << NAME(BootShift); const unsigned NAME(BootHeapOffset) = 1 << (NAME(BootShift) + 1); -inline unsigned -LABEL(codeMapSize)(unsigned codeSize) +inline unsigned LABEL(codeMapSize)(unsigned codeSize) { - return avian::util::ceilingDivide(codeSize, TargetBitsPerWord) * TargetBytesPerWord; + return avian::util::ceilingDivide(codeSize, TargetBitsPerWord) + * TargetBytesPerWord; } -inline unsigned -LABEL(heapMapSize)(unsigned heapSize) +inline unsigned LABEL(heapMapSize)(unsigned heapSize) { - return avian::util::ceilingDivide(heapSize, TargetBitsPerWord * TargetBytesPerWord) - * TargetBytesPerWord; + return avian::util::ceilingDivide(heapSize, + TargetBitsPerWord * TargetBytesPerWord) + * TargetBytesPerWord; } -inline object -LABEL(bootObject)(LABEL(uintptr_t)* heap, unsigned offset) +inline object LABEL(bootObject)(LABEL(uintptr_t) * heap, unsigned offset) { if (offset) { return reinterpret_cast(heap + offset - 1); diff --git a/src/builtin.cpp b/src/builtin.cpp index 356d02e6ce..b6fd26b75e 100644 --- a/src/builtin.cpp +++ b/src/builtin.cpp @@ -19,53 +19,53 @@ using namespace vm; namespace { -int64_t -search(Thread* t, object loader, object name, - object (*op)(Thread*, object, object), bool replaceDots) +int64_t search(Thread* t, + GcClassLoader* loader, + GcString* name, + GcClass* (*op)(Thread*, GcClassLoader*, GcByteArray*), + bool replaceDots) { if (LIKELY(name)) { PROTECT(t, loader); PROTECT(t, name); - object n = makeByteArray(t, stringLength(t, name) + 1); - char* s = reinterpret_cast(&byteArrayBody(t, n, 0)); + GcByteArray* n = makeByteArray(t, name->length(t) + 1); + char* s = reinterpret_cast(n->body().begin()); stringChars(t, name, s); - + if (replaceDots) { replace('.', '/', s); } return reinterpret_cast(op(t, loader, n)); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -object -resolveSystemClassThrow(Thread* t, object loader, object spec) +GcClass* resolveSystemClassThrow(Thread* t, + GcClassLoader* loader, + GcByteArray* spec) { - return resolveSystemClass - (t, loader, spec, true, Machine::ClassNotFoundExceptionType); + return resolveSystemClass( + t, loader, spec, true, GcClassNotFoundException::Type); } -object -fieldForOffsetInClass(Thread* t, object c, unsigned offset) +GcField* fieldForOffsetInClass(Thread* t, GcClass* c, unsigned offset) { - object super = classSuper(t, c); + GcClass* super = c->super(); if (super) { - object field = fieldForOffsetInClass(t, super, offset); + GcField* field = fieldForOffsetInClass(t, super, offset); if (field) { return field; } } - object table = classFieldTable(t, c); + object table = c->fieldTable(); if (table) { for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { - object field = objectArrayBody(t, table, i); - if ((fieldFlags(t, field) & ACC_STATIC) == 0 - and fieldOffset(t, field) == offset) - { + GcField* field = cast(t, objectArrayBody(t, table, i)); + if ((field->flags() & ACC_STATIC) == 0 and field->offset() == offset) { return field; } } @@ -74,26 +74,23 @@ fieldForOffsetInClass(Thread* t, object c, unsigned offset) return 0; } -object -fieldForOffset(Thread* t, object o, unsigned offset) +GcField* fieldForOffset(Thread* t, GcSingleton* o, unsigned offset) { - object c = objectClass(t, o); - if (classVmFlags(t, c) & SingletonFlag) { - c = singletonObject(t, o, 0); - object table = classFieldTable(t, c); + GcClass* c = objectClass(t, o); + if (c->vmFlags() & SingletonFlag) { + c = cast(t, singletonObject(t, o, 0)); + object table = c->fieldTable(); if (table) { for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { - object field = objectArrayBody(t, table, i); - if ((fieldFlags(t, field) & ACC_STATIC) - and fieldOffset(t, field) == offset) - { + GcField* field = cast(t, objectArrayBody(t, table, i)); + if ((field->flags() & ACC_STATIC) and field->offset() == offset) { return field; } } } abort(t); } else { - object field = fieldForOffsetInClass(t, c, offset); + GcField* field = fieldForOffsetInClass(t, c, offset); if (field) { return field; } else { @@ -102,167 +99,178 @@ fieldForOffset(Thread* t, object o, unsigned offset) } } -} // namespace +} // namespace extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Classes_initialize -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_initialize(Thread* t, object, uintptr_t* arguments) { - object this_ = reinterpret_cast(arguments[0]); + GcClass* this_ = cast(t, reinterpret_cast(arguments[0])); initClass(t, this_); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Classes_acquireClassLock -(Thread* t, object, uintptr_t*) + Avian_avian_Classes_acquireClassLock(Thread* t, object, uintptr_t*) { acquire(t, t->m->classLock); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Classes_releaseClassLock -(Thread* t, object, uintptr_t*) + Avian_avian_Classes_releaseClassLock(Thread* t, object, uintptr_t*) { release(t, t->m->classLock); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_resolveVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_resolveVMClass(Thread* t, object, uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); - object spec = reinterpret_cast(arguments[1]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); + GcByteArray* spec + = cast(t, reinterpret_cast(arguments[1])); - return reinterpret_cast - (resolveClass(t, loader, spec, true, Machine::ClassNotFoundExceptionType)); + return reinterpret_cast( + resolveClass(t, loader, spec, true, GcClassNotFoundException::Type)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_defineVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_defineVMClass(Thread* t, object, uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); - object b = reinterpret_cast(arguments[1]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); + GcByteArray* b = cast(t, reinterpret_cast(arguments[1])); int offset = arguments[2]; int length = arguments[3]; - uint8_t* buffer = static_cast - (t->m->heap->allocate(length)); - - THREAD_RESOURCE2(t, uint8_t*, buffer, int, length, - t->m->heap->free(buffer, length)); + uint8_t* buffer = static_cast(t->m->heap->allocate(length)); - memcpy(buffer, &byteArrayBody(t, b, offset), length); + THREAD_RESOURCE2( + t, uint8_t*, buffer, int, length, t->m->heap->free(buffer, length)); + + memcpy(buffer, &b->body()[offset], length); return reinterpret_cast(defineClass(t, loader, buffer, length)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_findLoadedVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_findLoadedVMClass(Thread* t, + object, + uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); - object name = reinterpret_cast(arguments[1]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); + GcString* name = cast(t, reinterpret_cast(arguments[1])); return search(t, loader, name, findLoadedClass, true); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_vmClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_vmClass(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (jclassVmClass(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + cast(t, reinterpret_cast(arguments[0]))->vmClass()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_findVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_findVMClass(Thread* t, + object, + uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); - object name = reinterpret_cast(arguments[1]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); + GcString* name = cast(t, reinterpret_cast(arguments[1])); return search(t, loader, name, resolveSystemClassThrow, true); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_resourceURLPrefix -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_resourceURLPrefix(Thread* t, + object, + uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); - object name = reinterpret_cast(arguments[1]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); + GcString* name = cast(t, reinterpret_cast(arguments[1])); if (LIKELY(name)) { - THREAD_RUNTIME_ARRAY(t, char, n, stringLength(t, name) + 1); + THREAD_RUNTIME_ARRAY(t, char, n, name->length(t) + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(n)); - const char* name = static_cast - (systemClassLoaderFinder(t, loader))->urlPrefix(RUNTIME_ARRAY_BODY(n)); + const char* name + = static_cast(loader->as(t)->finder()) + ->urlPrefix(RUNTIME_ARRAY_BODY(n)); return name ? reinterpret_cast(makeString(t, "%s", name)) : 0; } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_00024ResourceEnumeration_nextResourceURLPrefix -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_00024ResourceEnumeration_nextResourceURLPrefix( + Thread* t, + object, + uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[1]); - object name = reinterpret_cast(arguments[2]); - object finderElementPtrPtr = reinterpret_cast(arguments[3]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[1])); + GcString* name = cast(t, reinterpret_cast(arguments[2])); + GcLongArray* finderElementPtrPtr + = cast(t, reinterpret_cast(arguments[3])); if (LIKELY(name) && LIKELY(finderElementPtrPtr)) { - THREAD_RUNTIME_ARRAY(t, char, n, stringLength(t, name) + 1); + THREAD_RUNTIME_ARRAY(t, char, n, name->length(t) + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(n)); - void *&finderElementPtr = reinterpret_cast(longArrayBody(t, - finderElementPtrPtr, 0)); - const char* name = static_cast - (systemClassLoaderFinder(t, loader))->nextUrlPrefix(RUNTIME_ARRAY_BODY(n), - finderElementPtr); + void*& finderElementPtr + = reinterpret_cast(finderElementPtrPtr->body()[0]); + const char* name + = static_cast(loader->as(t)->finder()) + ->nextUrlPrefix(RUNTIME_ARRAY_BODY(n), finderElementPtr); return name ? reinterpret_cast(makeString(t, "%s", name)) : 0; } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_getClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_getClass(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (getJClass(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + getJClass(t, cast(t, reinterpret_cast(arguments[0])))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_getPackageSource -(Thread* t, object, uintptr_t* arguments) + Avian_avian_SystemClassLoader_getPackageSource(Thread* t, + object, + uintptr_t* arguments) { - object name = reinterpret_cast(arguments[0]); + GcString* name = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, name); ACQUIRE(t, t->m->classLock); - THREAD_RUNTIME_ARRAY(t, char, chars, stringLength(t, name) + 2); + THREAD_RUNTIME_ARRAY(t, char, chars, name->length(t) + 2); stringChars(t, name, RUNTIME_ARRAY_BODY(chars)); replace('.', '/', RUNTIME_ARRAY_BODY(chars)); - RUNTIME_ARRAY_BODY(chars)[stringLength(t, name)] = '/'; - RUNTIME_ARRAY_BODY(chars)[stringLength(t, name) + 1] = 0; + RUNTIME_ARRAY_BODY(chars)[name->length(t)] = '/'; + RUNTIME_ARRAY_BODY(chars)[name->length(t) + 1] = 0; - object key = makeByteArray(t, RUNTIME_ARRAY_BODY(chars)); + GcByteArray* key = makeByteArray(t, RUNTIME_ARRAY_BODY(chars)); - object array = hashMapFind - (t, root(t, Machine::PackageMap), key, byteArrayHash, byteArrayEqual); + GcByteArray* array = cast( + t, + hashMapFind( + t, roots(t)->packageMap(), key, byteArrayHash, byteArrayEqual)); if (array) { - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeString - (t, array, 0, byteArrayLength(t, array)))); + return reinterpret_cast(makeLocalReference( + t, t->m->classpath->makeString(t, array, 0, array->length()))); } else { return 0; } @@ -271,8 +279,7 @@ Avian_avian_SystemClassLoader_getPackageSource #ifdef AVIAN_HEAPDUMP extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Machine_dumpHeap -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Machine_dumpHeap(Thread* t, object, uintptr_t* arguments) { object outputFile = reinterpret_cast(*arguments); @@ -281,21 +288,23 @@ Avian_avian_Machine_dumpHeap stringChars(t, outputFile, RUNTIME_ARRAY_BODY(n)); FILE* out = vm::fopen(RUNTIME_ARRAY_BODY(n), "wb"); if (out) { - { ENTER(t, Thread::ExclusiveState); + { + ENTER(t, Thread::ExclusiveState); dumpHeap(t, out); } fclose(out); } else { - throwNew(t, Machine::RuntimeExceptionType, "file not found: %s", + throwNew(t, + GcRuntimeException::Type, + "file not found: %s", RUNTIME_ARRAY_BODY(n)); } } -#endif//AVIAN_HEAPDUMP +#endif // AVIAN_HEAPDUMP extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Runtime_exit -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Runtime_exit(Thread* t, object, uintptr_t* arguments) { shutDown(t); @@ -303,27 +312,27 @@ Avian_java_lang_Runtime_exit } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Runtime_freeMemory -(Thread* t, object, uintptr_t*) + Avian_java_lang_Runtime_freeMemory(Thread* t, object, uintptr_t*) { return t->m->heap->remaining(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Runtime_totalMemory -(Thread* t, object, uintptr_t*) + Avian_java_lang_Runtime_totalMemory(Thread* t, object, uintptr_t*) { return t->m->heap->limit(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_getContentLength -(Thread* t, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_getContentLength( + Thread* t, + object, + uintptr_t* arguments) { - object path = reinterpret_cast(*arguments); + GcString* path = cast(t, reinterpret_cast(*arguments)); if (LIKELY(path)) { - THREAD_RUNTIME_ARRAY(t, char, p, stringLength(t, path) + 1); + THREAD_RUNTIME_ARRAY(t, char, p, path->length(t) + 1); stringChars(t, path, RUNTIME_ARRAY_BODY(p)); System::Region* r = t->m->bootFinder->find(RUNTIME_ARRAY_BODY(p)); @@ -341,13 +350,15 @@ Avian_avian_avianvmresource_Handler_00024ResourceInputStream_getContentLength } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_open -(Thread* t, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_open( + Thread* t, + object, + uintptr_t* arguments) { - object path = reinterpret_cast(*arguments); + GcString* path = cast(t, reinterpret_cast(*arguments)); if (LIKELY(path)) { - THREAD_RUNTIME_ARRAY(t, char, p, stringLength(t, path) + 1); + THREAD_RUNTIME_ARRAY(t, char, p, path->length(t) + 1); stringChars(t, path, RUNTIME_ARRAY_BODY(p)); System::Region* r = t->m->bootFinder->find(RUNTIME_ARRAY_BODY(p)); @@ -357,15 +368,18 @@ Avian_avian_avianvmresource_Handler_00024ResourceInputStream_open return reinterpret_cast(r); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_available -(Thread*, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_available( + Thread*, + object, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); int32_t position = arguments[2]; System::Region* region = reinterpret_cast(peer); @@ -373,10 +387,13 @@ Avian_avian_avianvmresource_Handler_00024ResourceInputStream_available } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI -(Thread*, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI( + Thread*, + object, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); int32_t position = arguments[2]; System::Region* region = reinterpret_cast(peer); @@ -388,17 +405,22 @@ Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI_3BII -(Thread* t, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI_3BII( + Thread* t, + object, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); int32_t position = arguments[2]; - object buffer = reinterpret_cast(arguments[3]); + GcByteArray* buffer + = cast(t, reinterpret_cast(arguments[3])); int32_t offset = arguments[4]; int32_t length = arguments[5]; - if (length == 0) return 0; - + if (length == 0) + return 0; + System::Region* region = reinterpret_cast(peer); if (length > static_cast(region->length()) - position) { length = static_cast(region->length()) - position; @@ -406,120 +428,138 @@ Avian_avian_avianvmresource_Handler_00024ResourceInputStream_read__JI_3BII if (length <= 0) { return -1; } else { - memcpy(&byteArrayBody(t, buffer, offset), region->start() + position, - length); + memcpy(&buffer->body()[offset], region->start() + position, length); return length; } } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_avianvmresource_Handler_00024ResourceInputStream_close -(Thread*, object, uintptr_t* arguments) + Avian_avian_avianvmresource_Handler_00024ResourceInputStream_close( + Thread*, + object, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); reinterpret_cast(peer)->dispose(); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Continuations_callWithCurrentContinuation -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Continuations_callWithCurrentContinuation(Thread* t, + object, + uintptr_t* arguments) { - t->m->processor->callWithCurrentContinuation - (t, reinterpret_cast(*arguments)); + t->m->processor->callWithCurrentContinuation( + t, reinterpret_cast(*arguments)); abort(t); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Continuations_dynamicWind2 -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Continuations_dynamicWind2(Thread* t, + object, + uintptr_t* arguments) { - t->m->processor->dynamicWind - (t, reinterpret_cast(arguments[0]), - reinterpret_cast(arguments[1]), - reinterpret_cast(arguments[2])); + t->m->processor->dynamicWind(t, + reinterpret_cast(arguments[0]), + reinterpret_cast(arguments[1]), + reinterpret_cast(arguments[2])); abort(t); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Continuations_00024Continuation_handleResult -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Continuations_00024Continuation_handleResult( + Thread* t, + object, + uintptr_t* arguments) { - t->m->processor->feedResultToContinuation - (t, reinterpret_cast(arguments[0]), - reinterpret_cast(arguments[1])); + t->m->processor->feedResultToContinuation( + t, + cast(t, reinterpret_cast(arguments[0])), + reinterpret_cast(arguments[1])); abort(t); } extern "C" AVIAN_EXPORT void JNICALL -Avian_avian_Continuations_00024Continuation_handleException -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Continuations_00024Continuation_handleException( + Thread* t, + object, + uintptr_t* arguments) { - t->m->processor->feedExceptionToContinuation - (t, reinterpret_cast(arguments[0]), - reinterpret_cast(arguments[1])); + t->m->processor->feedExceptionToContinuation( + t, + cast(t, reinterpret_cast(arguments[0])), + cast(t, reinterpret_cast(arguments[1]))); abort(t); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Singleton_getObject -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Singleton_getObject(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (singletonObject(t, reinterpret_cast(arguments[0]), arguments[1])); + return reinterpret_cast(singletonObject( + t, + cast(t, reinterpret_cast(arguments[0])), + arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Singleton_getInt -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Singleton_getInt(Thread* t, object, uintptr_t* arguments) { - return singletonValue - (t, reinterpret_cast(arguments[0]), arguments[1]); + return singletonValue( + t, + cast(t, reinterpret_cast(arguments[0])), + arguments[1]); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Singleton_getLong -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Singleton_getLong(Thread* t, object, uintptr_t* arguments) { int64_t v; - memcpy(&v, &singletonValue - (t, reinterpret_cast(arguments[0]), arguments[1]), 8); + memcpy(&v, + &singletonValue( + t, + cast(t, reinterpret_cast(arguments[0])), + arguments[1]), + 8); return v; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_allocateMemory -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_allocateMemory(Thread* t, + object, + uintptr_t* arguments) { - int64_t size; memcpy(&size, arguments + 1, 8); + int64_t size; + memcpy(&size, arguments + 1, 8); void* p = malloc(size); if (p) { return reinterpret_cast(p); } else { - throwNew(t, Machine::OutOfMemoryErrorType); + throwNew(t, GcOutOfMemoryError::Type); } } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_freeMemory -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_freeMemory(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); if (p) { free(reinterpret_cast(p)); } } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_setMemory -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_setMemory(Thread* t, object, uintptr_t* arguments) { object base = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); - int64_t count; memcpy(&count, arguments + 4, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); + int64_t count; + memcpy(&count, arguments + 4, 8); int8_t value = arguments[6]; PROTECT(t, base); @@ -538,280 +578,295 @@ Avian_sun_misc_Unsafe_setMemory // so these versions will be ignored. extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putByte__JB -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putByte__JB(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); int8_t v = arguments[3]; *reinterpret_cast(p) = v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putShort__JS -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putShort__JS(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); int16_t v = arguments[3]; *reinterpret_cast(p) = v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putChar__JC -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putChar__JC(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putShort__JS(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putInt__JI -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putInt__JI(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); int32_t v = arguments[3]; *reinterpret_cast(p) = v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putFloat__JF -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putFloat__JF(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putInt__JI(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putLong__JJ -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putLong__JJ(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); - int64_t v; memcpy(&v, arguments + 3, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); + int64_t v; + memcpy(&v, arguments + 3, 8); *reinterpret_cast(p) = v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putDouble__JD -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putDouble__JD(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putLong__JJ(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putAddress__JJ -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putAddress__JJ(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); - int64_t v; memcpy(&v, arguments + 3, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); + int64_t v; + memcpy(&v, arguments + 3, 8); *reinterpret_cast(p) = v; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getByte__J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getByte__J(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); return *reinterpret_cast(p); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getShort__J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getShort__J(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); return *reinterpret_cast(p); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getChar__J -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getChar__J(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getShort__J(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getInt__J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getInt__J(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); return *reinterpret_cast(p); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getFloat__J -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getFloat__J(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getInt__J(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getLong__J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getLong__J(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); return *reinterpret_cast(p); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getDouble__J -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getDouble__J(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getLong__J(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getAddress__J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getAddress__J(Thread*, object, uintptr_t* arguments) { - int64_t p; memcpy(&p, arguments + 1, 8); + int64_t p; + memcpy(&p, arguments + 1, 8); return *reinterpret_cast(p); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_copyMemory -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_copyMemory(Thread* t, object, uintptr_t* arguments) { object srcBase = reinterpret_cast(arguments[1]); - int64_t srcOffset; memcpy(&srcOffset, arguments + 2, 8); + int64_t srcOffset; + memcpy(&srcOffset, arguments + 2, 8); object dstBase = reinterpret_cast(arguments[4]); - int64_t dstOffset; memcpy(&dstOffset, arguments + 5, 8); - int64_t count; memcpy(&count, arguments + 7, 8); + int64_t dstOffset; + memcpy(&dstOffset, arguments + 5, 8); + int64_t count; + memcpy(&count, arguments + 7, 8); PROTECT(t, srcBase); PROTECT(t, dstBase); ACQUIRE(t, t->m->referenceLock); - void* src = srcBase - ? &fieldAtOffset(srcBase, srcOffset) - : reinterpret_cast(srcOffset); + void* src = srcBase ? &fieldAtOffset(srcBase, srcOffset) + : reinterpret_cast(srcOffset); - void* dst = dstBase - ? &fieldAtOffset(dstBase, dstOffset) - : reinterpret_cast(dstOffset); + void* dst = dstBase ? &fieldAtOffset(dstBase, dstOffset) + : reinterpret_cast(dstOffset); memcpy(dst, src, count); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_arrayBaseOffset -(Thread*, object, uintptr_t*) + Avian_sun_misc_Unsafe_arrayBaseOffset(Thread*, object, uintptr_t*) { return ArrayBody; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_arrayIndexScale -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_arrayIndexScale(Thread* t, + object, + uintptr_t* arguments) { - object c = jclassVmClass(t, reinterpret_cast(arguments[1])); + GcClass* c + = cast(t, reinterpret_cast(arguments[1]))->vmClass(); - if (c == type(t, Machine::BooleanArrayType) - || c == type(t, Machine::ByteArrayType)) + if (c == type(t, GcBooleanArray::Type) || c == type(t, GcByteArray::Type)) return 1; - else if (c == type(t, Machine::ShortArrayType) - || c == type(t, Machine::CharArrayType)) + else if (c == type(t, GcShortArray::Type) || c == type(t, GcCharArray::Type)) return 2; - else if (c == type(t, Machine::IntArrayType) - || c == type(t, Machine::FloatArrayType)) + else if (c == type(t, GcIntArray::Type) || c == type(t, GcFloatArray::Type)) return 4; - else if (c == type(t, Machine::LongArrayType) - || c == type(t, Machine::DoubleArrayType)) + else if (c == type(t, GcLongArray::Type) || c == type(t, GcDoubleArray::Type)) return 8; else return BytesPerWord; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_nio_FixedArrayByteBuffer_allocateFixed -(Thread* t, object, uintptr_t* arguments) + Avian_java_nio_FixedArrayByteBuffer_allocateFixed(Thread* t, + object, + uintptr_t* arguments) { int capacity = arguments[0]; - object address = reinterpret_cast(arguments[1]); + GcLongArray* address + = cast(t, reinterpret_cast(arguments[1])); PROTECT(t, address); - object array = allocate3 - (t, t->m->heap, Machine::FixedAllocation, ArrayBody + capacity, false); + GcArray* array = reinterpret_cast(allocate3( + t, t->m->heap, Machine::FixedAllocation, ArrayBody + capacity, false)); - setObjectClass(t, array, type(t, Machine::ByteArrayType)); - byteArrayLength(t, array) = capacity; + setObjectClass( + t, reinterpret_cast(array), type(t, GcByteArray::Type)); + array->length() = capacity; - longArrayBody(t, address, 0) = reinterpret_cast(array) + ArrayBody; + address->body()[0] = reinterpret_cast(array) + ArrayBody; return reinterpret_cast(array); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getObject -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getObject(Thread*, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putObject -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putObject(Thread* t, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); uintptr_t value = arguments[4]; - set(t, o, offset, reinterpret_cast(value)); + setField(t, o, offset, reinterpret_cast(value)); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putObjectVolatile -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putObjectVolatile(Thread* t, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); object value = reinterpret_cast(arguments[4]); - + storeStoreMemoryBarrier(); - set(t, o, offset, reinterpret_cast(value)); + setField(t, o, offset, value); storeLoadMemoryBarrier(); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putOrderedObject -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putOrderedObject(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putObjectVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getObjectVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getObjectVolatile(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); - + int64_t offset; + memcpy(&offset, arguments + 2, 8); + uintptr_t value = fieldAtOffset(o, offset); loadMemoryBarrier(); return value; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_compareAndSwapObject -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_compareAndSwapObject(Thread* t, + object, + uintptr_t* arguments) { object target = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); uintptr_t expect = arguments[4]; uintptr_t update = arguments[5]; - bool success = atomicCompareAndSwap - (&fieldAtOffset(target, offset), expect, update); + bool success = atomicCompareAndSwap( + &fieldAtOffset(target, offset), expect, update); if (success) { mark(t, target, offset); @@ -821,30 +876,36 @@ Avian_sun_misc_Unsafe_compareAndSwapObject } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_compareAndSwapInt -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_compareAndSwapInt(Thread*, + object, + uintptr_t* arguments) { object target = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); uint32_t expect = arguments[4]; uint32_t update = arguments[5]; - return atomicCompareAndSwap32 - (&fieldAtOffset(target, offset), expect, update); + return atomicCompareAndSwap32( + &fieldAtOffset(target, offset), expect, update); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_compareAndSwapLong -(Thread* t UNUSED, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_compareAndSwapLong(Thread* t UNUSED, + object, + uintptr_t* arguments) { object target = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); - uint64_t expect; memcpy(&expect, arguments + 4, 8); - uint64_t update; memcpy(&update, arguments + 6, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); + uint64_t expect; + memcpy(&expect, arguments + 4, 8); + uint64_t update; + memcpy(&update, arguments + 6, 8); #ifdef AVIAN_HAS_CAS64 - return atomicCompareAndSwap64 - (&fieldAtOffset(target, offset), expect, update); + return atomicCompareAndSwap64( + &fieldAtOffset(target, offset), expect, update); #else PROTECT(t, target); ACQUIRE_FIELD_FOR_WRITE(t, fieldForOffset(t, target, offset)); @@ -858,29 +919,31 @@ Avian_sun_misc_Unsafe_compareAndSwapLong } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getLongVolatile -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getLongVolatile(Thread* t, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); object lock; if (BytesPerWord < 8) { - if (classArrayDimensions(t, objectClass(t, o))) { + if (objectClass(t, o)->arrayDimensions()) { lock = objectClass(t, o); } else { - lock = fieldForOffset(t, o, offset); + lock = fieldForOffset(t, cast(t, o), offset); } PROTECT(t, o); PROTECT(t, lock); - acquire(t, lock); + acquire(t, lock); } int64_t result = fieldAtOffset(o, offset); if (BytesPerWord < 8) { - release(t, lock); + release(t, lock); } else { loadMemoryBarrier(); } @@ -889,24 +952,27 @@ Avian_sun_misc_Unsafe_getLongVolatile } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putLongVolatile -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putLongVolatile(Thread* t, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); - int64_t value; memcpy(&value, arguments + 4, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); + int64_t value; + memcpy(&value, arguments + 4, 8); object lock; if (BytesPerWord < 8) { - if (classArrayDimensions(t, objectClass(t, o))) { + if (objectClass(t, o)->arrayDimensions()) { lock = objectClass(t, o); } else { - lock = fieldForOffset(t, o, offset); + lock = fieldForOffset(t, cast(t, o), offset); } PROTECT(t, o); PROTECT(t, lock); - acquire(t, lock); + acquire(t, lock); } else { storeStoreMemoryBarrier(); } @@ -921,8 +987,9 @@ Avian_sun_misc_Unsafe_putLongVolatile } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putOrderedLong -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putOrderedLong(Thread* t, + object method, + uintptr_t* arguments) { // todo: we might be able to use weaker barriers here than // putLongVolatile does @@ -930,24 +997,23 @@ Avian_sun_misc_Unsafe_putOrderedLong } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_unpark -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_unpark(Thread* t, object, uintptr_t* arguments) { - object thread = reinterpret_cast(arguments[1]); - - monitorAcquire(t, interruptLock(t, thread)); - threadUnparked(t, thread) = true; - monitorNotify(t, interruptLock(t, thread)); - monitorRelease(t, interruptLock(t, thread)); + GcThread* thread = cast(t, reinterpret_cast(arguments[1])); + + monitorAcquire(t, cast(t, interruptLock(t, thread))); + thread->unparked() = true; + monitorNotify(t, cast(t, interruptLock(t, thread))); + monitorRelease(t, cast(t, interruptLock(t, thread))); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_park -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_park(Thread* t, object, uintptr_t* arguments) { bool absolute = arguments[1]; - int64_t time; memcpy(&time, arguments + 2, 8); - + int64_t time; + memcpy(&time, arguments + 2, 8); + int64_t then = t->m->system->now(); if (absolute) { @@ -962,55 +1028,56 @@ Avian_sun_misc_Unsafe_park time = (time / (1000 * 1000)) + 1; } - monitorAcquire(t, interruptLock(t, t->javaThread)); + monitorAcquire(t, cast(t, interruptLock(t, t->javaThread))); bool interrupted = false; while (time >= 0 - and (not (threadUnparked(t, t->javaThread) - or threadInterrupted(t, t->javaThread) - or (interrupted = monitorWait - (t, interruptLock(t, t->javaThread), time))))) - { + and (not(t->javaThread->unparked() or t->javaThread->interrupted() + or (interrupted = monitorWait( + t, + cast(t, interruptLock(t, t->javaThread)), + time))))) { int64_t now = t->m->system->now(); time -= now - then; then = now; - + if (time == 0) { break; } } if (interrupted) { - threadInterrupted(t, t->javaThread) = true; + t->javaThread->interrupted() = true; } - threadUnparked(t, t->javaThread) = false; - monitorRelease(t, interruptLock(t, t->javaThread)); + t->javaThread->unparked() = false; + monitorRelease(t, cast(t, interruptLock(t, t->javaThread))); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putIntVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putIntVolatile(Thread*, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int32_t value = arguments[4]; - + storeStoreMemoryBarrier(); fieldAtOffset(o, offset) = value; storeLoadMemoryBarrier(); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putOrderedInt -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putOrderedInt(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putIntVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getIntVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getIntVolatile(Thread*, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int32_t result = fieldAtOffset(o, offset); loadMemoryBarrier(); @@ -1018,24 +1085,24 @@ Avian_sun_misc_Unsafe_getIntVolatile } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putByteVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putByteVolatile(Thread*, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int8_t value = arguments[4]; - + storeStoreMemoryBarrier(); fieldAtOffset(o, offset) = value; storeLoadMemoryBarrier(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getByteVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getByteVolatile(Thread*, object, uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int8_t result = fieldAtOffset(o, offset); loadMemoryBarrier(); @@ -1043,38 +1110,44 @@ Avian_sun_misc_Unsafe_getByteVolatile } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putBooleanVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putBooleanVolatile(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putByteVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getBooleanVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getBooleanVolatile(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getByteVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putShortVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putShortVolatile(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int16_t value = arguments[4]; - + storeStoreMemoryBarrier(); fieldAtOffset(o, offset) = value; storeLoadMemoryBarrier(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getShortVolatile -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getShortVolatile(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int16_t result = fieldAtOffset(o, offset); loadMemoryBarrier(); @@ -1082,57 +1155,63 @@ Avian_sun_misc_Unsafe_getShortVolatile } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putCharVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putCharVolatile(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putShortVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getCharVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getCharVolatile(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getShortVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putFloatVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putFloatVolatile(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putIntVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getFloatVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getFloatVolatile(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getIntVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putDoubleVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putDoubleVolatile(Thread* t, + object method, + uintptr_t* arguments) { Avian_sun_misc_Unsafe_putLongVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getDoubleVolatile -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getDoubleVolatile(Thread* t, + object method, + uintptr_t* arguments) { return Avian_sun_misc_Unsafe_getLongVolatile(t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_throwException -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_throwException(Thread* t, + object, + uintptr_t* arguments) { - vm::throw_(t, reinterpret_cast(arguments[1])); + vm::throw_(t, cast(t, reinterpret_cast(arguments[1]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_primitiveClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_primitiveClass(Thread* t, object, uintptr_t* arguments) { return reinterpret_cast(primitiveClass(t, arguments[0])); } diff --git a/src/classpath-android.cpp b/src/classpath-android.cpp index 7d9e6d3dc3..cdd1c4d589 100644 --- a/src/classpath-android.cpp +++ b/src/classpath-android.cpp @@ -25,39 +25,37 @@ extern "C" int JNI_OnLoad(JavaVM*, void*); #include "avian/util.h" #ifdef PLATFORM_WINDOWS -const char* getErrnoDescription(int err); // This function is defined in mingw-extensions.cpp +const char* getErrnoDescription( + int err); // This function is defined in mingw-extensions.cpp #endif using namespace vm; extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_defineVMClass -(Thread*, object, uintptr_t*); + Avian_avian_Classes_defineVMClass(Thread*, object, uintptr_t*); namespace { namespace local { -void* -getDirectBufferAddress(Thread* t, object b) +void* getDirectBufferAddress(Thread* t, object b) { PROTECT(t, b); - object field = resolveField - (t, objectClass(t, b), "effectiveDirectAddress", "J"); + GcField* field + = resolveField(t, objectClass(t, b), "effectiveDirectAddress", "J"); - return reinterpret_cast - (fieldAtOffset(b, fieldOffset(t, field))); + return reinterpret_cast(fieldAtOffset(b, field->offset())); } -void JNICALL -loadLibrary(Thread* t, object, uintptr_t* arguments) +void JNICALL loadLibrary(Thread* t, object, uintptr_t* arguments) { - object name = reinterpret_cast(arguments[1]); + GcString* name = cast(t, reinterpret_cast(arguments[1])); - Thread::LibraryLoadStack stack(t, reinterpret_cast(arguments[2])); + Thread::LibraryLoadStack stack( + t, cast(t, reinterpret_cast(arguments[2]))); - unsigned length = stringLength(t, name); + unsigned length = name->length(t); THREAD_RUNTIME_ARRAY(t, char, n, length + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(n)); @@ -71,158 +69,159 @@ loadLibrary(Thread* t, object, uintptr_t* arguments) } } -void JNICALL -finalizeAllEnqueued(Thread*, object, uintptr_t*) +void JNICALL finalizeAllEnqueued(Thread*, object, uintptr_t*) { // ignore } -int64_t JNICALL -appLoader(Thread* t, object, uintptr_t*) +int64_t JNICALL appLoader(Thread* t, object, uintptr_t*) { - return reinterpret_cast(root(t, Machine::AppLoader)); + return reinterpret_cast(roots(t)->appLoader()); } -int64_t JNICALL -defineClass(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL defineClass(Thread* t, object method, uintptr_t* arguments) { - uintptr_t args[] - = { arguments[0], arguments[2], arguments[3], arguments[4] }; + uintptr_t args[] = {arguments[0], arguments[2], arguments[3], arguments[4]}; int64_t v = Avian_avian_Classes_defineVMClass(t, method, args); if (v) { - return reinterpret_cast - (getJClass(t, reinterpret_cast(v))); + return reinterpret_cast( + getJClass(t, cast(t, reinterpret_cast(v)))); } else { return 0; - } + } } -int64_t JNICALL -mapData(Thread*, object, uintptr_t*); +int64_t JNICALL mapData(Thread*, object, uintptr_t*); -void JNICALL -closeMemoryMappedFile(Thread*, object, uintptr_t*); +void JNICALL closeMemoryMappedFile(Thread*, GcMethod*, uintptr_t*); -object -makeMethodOrConstructor(Thread* t, object c, unsigned index) +object makeMethodOrConstructor(Thread* t, GcJclass* c, unsigned index) { PROTECT(t, c); - object method = arrayBody - (t, classMethodTable(t, jclassVmClass(t, c)), index); + GcMethod* method = cast( + t, cast(t, c->vmClass()->methodTable())->body()[index]); PROTECT(t, method); unsigned parameterCount; unsigned returnTypeSpec; - object parameterTypes = resolveParameterJTypes - (t, classLoader(t, methodClass(t, method)), methodSpec(t, method), - ¶meterCount, &returnTypeSpec); + object parameterTypes = resolveParameterJTypes(t, + method->class_()->loader(), + method->spec(), + ¶meterCount, + &returnTypeSpec); PROTECT(t, parameterTypes); - object returnType = resolveJType - (t, classLoader(t, methodClass(t, method)), reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), returnTypeSpec)), - byteArrayLength(t, methodSpec(t, method)) - 1 - returnTypeSpec); + GcJclass* returnType = resolveJType( + t, + method->class_()->loader(), + reinterpret_cast(&method->spec()->body()[returnTypeSpec]), + method->spec()->length() - 1 - returnTypeSpec); PROTECT(t, returnType); - object exceptionTypes = resolveExceptionJTypes - (t, classLoader(t, methodClass(t, method)), methodAddendum(t, method)); + object exceptionTypes = resolveExceptionJTypes( + t, method->class_()->loader(), method->addendum()); - if (byteArrayBody(t, methodName(t, method), 0) == '<') { - return makeJconstructor - (t, 0, c, parameterTypes, exceptionTypes, 0, 0, 0, 0, index); + if (method->name()->body()[0] == '<') { + return makeJconstructor( + t, 0, c, parameterTypes, exceptionTypes, 0, 0, 0, 0, index); } else { PROTECT(t, exceptionTypes); - - object name = t->m->classpath->makeString - (t, methodName(t, method), 0, - byteArrayLength(t, methodName(t, method)) - 1); - return makeJmethod - (t, 0, index, c, name, parameterTypes, exceptionTypes, returnType, 0, 0, - 0, 0, 0); + GcString* name = t->m->classpath->makeString( + t, method->name(), 0, method->name()->length() - 1); + + return makeJmethod(t, + 0, + index, + c, + name, + parameterTypes, + exceptionTypes, + returnType, + 0, + 0, + 0, + 0, + 0); } } -object -makeField(Thread* t, object c, unsigned index) +object makeField(Thread* t, GcJclass* c, unsigned index) { PROTECT(t, c); - object field = arrayBody - (t, classFieldTable(t, jclassVmClass(t, c)), index); + GcField* field = cast( + t, cast(t, c->vmClass()->fieldTable())->body()[index]); PROTECT(t, field); - object type = getJClass - (t, resolveClassBySpec - (t, classLoader(t, fieldClass(t, field)), - reinterpret_cast - (&byteArrayBody(t, fieldSpec(t, field), 0)), - byteArrayLength(t, fieldSpec(t, field)) - 1)); + GcJclass* type = getJClass( + t, + resolveClassBySpec(t, + field->class_()->loader(), + reinterpret_cast(field->spec()->body().begin()), + field->spec()->length() - 1)); PROTECT(t, type); - - object name = t->m->classpath->makeString - (t, fieldName(t, field), 0, - byteArrayLength(t, fieldName(t, field)) - 1); + + GcString* name = t->m->classpath->makeString( + t, field->name(), 0, field->name()->length() - 1); return makeJfield(t, 0, c, type, 0, 0, name, index); } -void initVmThread(Thread* t, object thread, unsigned offset) +void initVmThread(Thread* t, GcThread* thread, unsigned offset) { PROTECT(t, thread); if (fieldAtOffset(thread, offset) == 0) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/VMThread"); + GcClass* c = resolveClass(t, roots(t)->bootLoader(), "java/lang/VMThread"); PROTECT(t, c); object instance = makeNew(t, c); PROTECT(t, instance); - object constructor = resolveMethod - (t, c, "", "(Ljava/lang/Thread;)V"); + GcMethod* constructor + = resolveMethod(t, c, "", "(Ljava/lang/Thread;)V"); t->m->processor->invoke(t, constructor, instance, thread); - set(t, thread, offset, instance); + setField(t, thread, offset, instance); } - if (threadGroup(t, thread) == 0) { - set(t, thread, ThreadGroup, threadGroup(t, t->javaThread)); - expect(t, threadGroup(t, thread)); + if (thread->group() == 0) { + thread->setGroup(t, t->javaThread->group()); + expect(t, thread->group()); } } -void initVmThread(Thread* t, object thread) +void initVmThread(Thread* t, GcThread* thread) { - initVmThread( - t, - thread, - fieldOffset( - t, - resolveField( - t, objectClass(t, thread), "vmThread", "Ljava/lang/VMThread;"))); + initVmThread(t, + thread, + resolveField(t, + objectClass(t, thread), + "vmThread", + "Ljava/lang/VMThread;")->offset()); } -object -translateStackTrace(Thread* t, object raw) +object translateStackTrace(Thread* t, object raw) { PROTECT(t, raw); - - object array = makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), "java/lang/StackTraceElement"), - objectArrayLength(t, raw)); + + object array = makeObjectArray( + t, + resolveClass(t, roots(t)->bootLoader(), "java/lang/StackTraceElement"), + objectArrayLength(t, raw)); PROTECT(t, array); for (unsigned i = 0; i < objectArrayLength(t, array); ++i) { - object e = makeStackTraceElement(t, objectArrayBody(t, raw, i)); + GcStackTraceElement* e = makeStackTraceElement( + t, cast(t, objectArrayBody(t, raw, i))); - set(t, array, ArrayBody + (i * BytesPerWord), e); + setField(t, array, ArrayBody + (i * BytesPerWord), e); } return array; @@ -232,149 +231,154 @@ class MyClasspath : public Classpath { public: MyClasspath(Allocator* allocator) : allocator(allocator), tzdata(0), mayInitClasses_(false) - { } + { + } - virtual object - makeJclass(Thread* t, object class_) + virtual GcJclass* makeJclass(Thread* t, GcClass* class_) { PROTECT(t, class_); - object c = allocate(t, FixedSizeOfJclass, true); - setObjectClass(t, c, type(t, Machine::JclassType)); - set(t, c, JclassVmClass, class_); + GcJclass* c + = reinterpret_cast(allocate(t, GcJclass::FixedSize, true)); + setObjectClass(t, c, type(t, GcJclass::Type)); + c->setVmClass(t, class_); return c; } - virtual object - makeString(Thread* t, object array, int32_t offset, int32_t length) + virtual GcString* makeString(Thread* t, + object array, + int32_t offset, + int32_t length) { - if (objectClass(t, array) == type(t, Machine::ByteArrayType)) { + if (objectClass(t, array) == type(t, GcByteArray::Type)) { + GcByteArray* byteArray = cast(t, array); PROTECT(t, array); - - object charArray = makeCharArray(t, length); - for (int i = 0; i < length; ++i) { - expect(t, (byteArrayBody(t, array, offset + i) & 0x80) == 0); + PROTECT(t, byteArray); - charArrayBody(t, charArray, i) = byteArrayBody(t, array, offset + i); + GcCharArray* charArray = makeCharArray(t, length); + for (int i = 0; i < length; ++i) { + expect(t, (byteArray->body()[offset + i] & 0x80) == 0); + + charArray->body()[i] = byteArray->body()[offset + i]; } array = charArray; } else { - expect(t, objectClass(t, array) == type(t, Machine::CharArrayType)); + expect(t, objectClass(t, array) == type(t, GcCharArray::Type)); } return vm::makeString(t, array, offset, length, 0); } - virtual object - makeThread(Thread* t, Thread* parent) + virtual GcThread* makeThread(Thread* t, Thread* parent) { const unsigned NormalPriority = 5; - object group = 0; + GcThreadGroup* group = 0; PROTECT(t, group); if (parent) { - group = threadGroup(t, parent->javaThread); + group = parent->javaThread->group(); } else { - resolveSystemClass - (t, root(t, Machine::BootLoader), - className(t, type(t, Machine::ThreadGroupType)), false); + resolveSystemClass(t, + roots(t)->bootLoader(), + type(t, GcThreadGroup::Type)->name(), + false); - group = makeNew(t, type(t, Machine::ThreadGroupType)); + group = cast(t, makeNew(t, type(t, GcThreadGroup::Type))); - object constructor = resolveMethod - (t, type(t, Machine::ThreadGroupType), "", "()V"); + GcMethod* constructor + = resolveMethod(t, type(t, GcThreadGroup::Type), "", "()V"); t->m->processor->invoke(t, constructor, group); } - resolveSystemClass - (t, root(t, Machine::BootLoader), - className(t, type(t, Machine::ThreadType)), false); - - object thread = makeNew(t, type(t, Machine::ThreadType)); + resolveSystemClass( + t, roots(t)->bootLoader(), type(t, GcThread::Type)->name(), false); + + GcThread* thread = cast(t, makeNew(t, type(t, GcThread::Type))); PROTECT(t, thread); - object constructor = resolveMethod - (t, type(t, Machine::ThreadType), "", - "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V"); + GcMethod* constructor + = resolveMethod(t, + type(t, GcThread::Type), + "", + "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V"); - t->m->processor->invoke - (t, constructor, thread, group, 0, NormalPriority, false); + t->m->processor->invoke( + t, constructor, thread, group, 0, NormalPriority, false); - set(t, thread, ThreadContextClassLoader, root(t, Machine::AppLoader)); + thread->setContextClassLoader(t, roots(t)->appLoader()); initVmThread(t, thread); return thread; } - virtual object - makeJMethod(Thread* t, object vmMethod) + virtual object makeJMethod(Thread* t, GcMethod* vmMethod) { - object table = classMethodTable(t, methodClass(t, vmMethod)); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - if (vmMethod == arrayBody(t, table, i)) { - return makeMethodOrConstructor - (t, getJClass(t, methodClass(t, vmMethod)), i); + GcArray* table = cast(t, vmMethod->class_()->methodTable()); + for (unsigned i = 0; i < table->length(); ++i) { + if (vmMethod == table->body()[i]) { + return makeMethodOrConstructor(t, getJClass(t, vmMethod->class_()), i); } } abort(t); } - virtual object - getVMMethod(Thread* t, object jmethod) + virtual GcMethod* getVMMethod(Thread* t, object jmethod) { - return objectClass(t, jmethod) == type(t, Machine::JmethodType) - ? arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jmethodDeclaringClass(t, jmethod))), - jmethodSlot(t, jmethod)) - : arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jconstructorDeclaringClass(t, jmethod))), - jconstructorSlot(t, jmethod)); + return cast( + t, + objectClass(t, jmethod) == type(t, GcJmethod::Type) + ? cast(t, + cast(t, jmethod) + ->declaringClass() + ->vmClass() + ->methodTable()) + ->body()[cast(t, jmethod)->slot()] + : cast(t, + cast(t, jmethod) + ->declaringClass() + ->vmClass() + ->methodTable()) + ->body()[cast(t, jmethod)->slot()]); } - virtual object - makeJField(Thread* t, object vmField) + virtual object makeJField(Thread* t, GcField* vmField) { - object table = classFieldTable(t, fieldClass(t, vmField)); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - if (vmField == arrayBody(t, table, i)) { - return makeField(t, getJClass(t, fieldClass(t, vmField)), i); + GcArray* table = cast(t, vmField->class_()->fieldTable()); + for (unsigned i = 0; i < table->length(); ++i) { + if (vmField == table->body()[i]) { + return makeField(t, getJClass(t, vmField->class_()), i); } } abort(t); } - virtual object - getVMField(Thread* t, object jfield) + virtual GcField* getVMField(Thread* t, GcJfield* jfield) { - return arrayBody - (t, classFieldTable - (t, jclassVmClass(t, jfieldDeclaringClass(t, jfield))), - jfieldSlot(t, jfield)); + return cast( + t, + cast(t, jfield->declaringClass()->vmClass()->fieldTable()) + ->body()[jfield->slot()]); } - virtual void - clearInterrupted(Thread*) + virtual void clearInterrupted(Thread*) { // ignore } - virtual void - runThread(Thread* t) + virtual void runThread(Thread* t) { // force monitor creation so we don't get an OutOfMemory error // later when we try to acquire it: objectMonitor(t, t->javaThread, true); - object field = resolveField( + GcField* field = resolveField( t, objectClass(t, t->javaThread), "vmThread", "Ljava/lang/VMThread;"); - unsigned offset = fieldOffset(t, field); + unsigned offset = field->offset(); THREAD_RESOURCE(t, unsigned, offset, { object vmt = fieldAtOffset(t->javaThread, offset); @@ -394,101 +398,122 @@ class MyClasspath : public Classpath { initVmThread(t, t->javaThread, offset); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "java/lang/Thread", "run", "()V"); + GcMethod* method = resolveMethod( + t, roots(t)->bootLoader(), "java/lang/Thread", "run", "()V"); t->m->processor->invoke(t, method, t->javaThread); } - virtual void - resolveNative(Thread* t, object method) + virtual void resolveNative(Thread* t, GcMethod* method) { vm::resolveNative(t, method); } - void - interceptMethods(Thread* t, bool updateRuntimeData) + void interceptMethods(Thread* t, bool updateRuntimeData) { - { object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/Runtime", false); + { + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/lang/Runtime", false); if (c) { PROTECT(t, c); - intercept(t, c, "loadLibrary", + intercept(t, + c, + "loadLibrary", "(Ljava/lang/String;Ljava/lang/ClassLoader;)V", - voidPointer(loadLibrary), updateRuntimeData); + voidPointer(loadLibrary), + updateRuntimeData); } } - { object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/ref/FinalizerReference", - false); + { + GcClass* c = resolveClass( + t, roots(t)->bootLoader(), "java/lang/ref/FinalizerReference", false); if (c) { PROTECT(t, c); - intercept(t, c, "finalizeAllEnqueued", "()V", - voidPointer(finalizeAllEnqueued), updateRuntimeData); + intercept(t, + c, + "finalizeAllEnqueued", + "()V", + voidPointer(finalizeAllEnqueued), + updateRuntimeData); } } - { object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/ClassLoader", false); + { + GcClass* c = resolveClass( + t, roots(t)->bootLoader(), "java/lang/ClassLoader", false); if (c) { PROTECT(t, c); - intercept(t, c, "createSystemClassLoader", "()Ljava/lang/ClassLoader;", - voidPointer(appLoader), updateRuntimeData); + intercept(t, + c, + "createSystemClassLoader", + "()Ljava/lang/ClassLoader;", + voidPointer(appLoader), + updateRuntimeData); - intercept(t, c, "defineClass", + intercept(t, + c, + "defineClass", "(Ljava/lang/String;[BII)Ljava/lang/Class;", - voidPointer(defineClass), updateRuntimeData); + voidPointer(defineClass), + updateRuntimeData); } } - { object c = resolveClass - (t, root(t, Machine::BootLoader), "libcore/util/ZoneInfoDB", false); + { + GcClass* c = resolveClass( + t, roots(t)->bootLoader(), "libcore/util/ZoneInfoDB", false); if (c) { PROTECT(t, c); - intercept(t, c, "mapData", "()Llibcore/io/MemoryMappedFile;", - voidPointer(mapData), updateRuntimeData); + intercept(t, + c, + "mapData", + "()Llibcore/io/MemoryMappedFile;", + voidPointer(mapData), + updateRuntimeData); } } - { object c = resolveClass - (t, root(t, Machine::BootLoader), "libcore/io/MemoryMappedFile", - false); + { + GcClass* c = resolveClass( + t, roots(t)->bootLoader(), "libcore/io/MemoryMappedFile", false); if (c) { PROTECT(t, c); - intercept(t, c, "close", "()V", voidPointer(closeMemoryMappedFile), + intercept(t, + c, + "close", + "()V", + voidPointer(closeMemoryMappedFile), updateRuntimeData); } } } - virtual void - interceptMethods(Thread* t) + virtual void interceptMethods(Thread* t) { interceptMethods(t, false); } - virtual void - preBoot(Thread* t) + virtual void preBoot(Thread* t) { - // Android's System.initSystemProperties throws an NPE if - // LD_LIBRARY_PATH is not set as of this writing: +// Android's System.initSystemProperties throws an NPE if +// LD_LIBRARY_PATH is not set as of this writing: #ifdef PLATFORM_WINDOWS _wputenv(L"LD_LIBRARY_PATH=(dummy)"); -#elif (! defined AVIAN_IOS) +#elif(!defined AVIAN_IOS) setenv("LD_LIBRARY_PATH", "", false); #endif - + interceptMethods(t, true); JniConstants::init(reinterpret_cast<_JNIEnv*>(t)); @@ -503,92 +528,85 @@ class MyClasspath : public Classpath { return mayInitClasses_; } - virtual void - boot(Thread* t) + virtual void boot(Thread* t) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/ClassLoader"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/lang/ClassLoader"); PROTECT(t, c); - object constructor = resolveMethod - (t, c, "", "(Ljava/lang/ClassLoader;Z)V"); + GcMethod* constructor + = resolveMethod(t, c, "", "(Ljava/lang/ClassLoader;Z)V"); PROTECT(t, constructor); - t->m->processor->invoke - (t, constructor, root(t, Machine::BootLoader), 0, true); + t->m->processor->invoke(t, constructor, roots(t)->bootLoader(), 0, true); - t->m->processor->invoke - (t, constructor, root(t, Machine::AppLoader), - root(t, Machine::BootLoader), false); + t->m->processor->invoke( + t, constructor, roots(t)->appLoader(), roots(t)->bootLoader(), false); } - virtual const char* - bootClasspath() + virtual const char* bootClasspath() { return AVIAN_CLASSPATH; } - virtual object - makeDirectByteBuffer(Thread* t, void* p, jlong capacity) + virtual object makeDirectByteBuffer(Thread* t, void* p, jlong capacity) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/nio/DirectByteBuffer"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/nio/DirectByteBuffer"); PROTECT(t, c); object instance = makeNew(t, c); PROTECT(t, instance); - object constructor = resolveMethod(t, c, "", "(JI)V"); + GcMethod* constructor = resolveMethod(t, c, "", "(JI)V"); - t->m->processor->invoke - (t, constructor, instance, reinterpret_cast(p), - static_cast(capacity)); + t->m->processor->invoke(t, + constructor, + instance, + reinterpret_cast(p), + static_cast(capacity)); return instance; } - virtual void* - getDirectBufferAddress(Thread* t, object b) + virtual void* getDirectBufferAddress(Thread* t, object b) { return local::getDirectBufferAddress(t, b); } - virtual int64_t - getDirectBufferCapacity(Thread* t, object b) + virtual int64_t getDirectBufferCapacity(Thread* t, object b) { PROTECT(t, b); - object field = resolveField - (t, objectClass(t, b), "capacity", "I"); + GcField* field = resolveField(t, objectClass(t, b), "capacity", "I"); - return fieldAtOffset(b, fieldOffset(t, field)); + return fieldAtOffset(b, field->offset()); } - virtual bool - canTailCall(Thread*, object, object, object, object) + virtual bool canTailCall(Thread*, + GcMethod*, + GcByteArray*, + GcByteArray*, + GcByteArray*) { return true; } - virtual object libraryClassLoader(Thread* t, object caller) + virtual GcClassLoader* libraryClassLoader(Thread* t, GcMethod* caller) { - return strcmp( - "java/lang/Runtime", - reinterpret_cast( - &byteArrayBody(t, className(t, methodClass(t, caller)), 0))) - == 0 + return strcmp("java/lang/Runtime", + reinterpret_cast( + caller->class_()->name()->body().begin())) == 0 ? t->libraryLoadStack->classLoader - : classLoader(t, methodClass(t, caller)); + : caller->class_()->loader(); } - virtual void - shutDown(Thread*) + virtual void shutDown(Thread*) { // ignore } - virtual void - dispose() + virtual void dispose() { if (tzdata) { tzdata->dispose(); @@ -601,18 +619,17 @@ class MyClasspath : public Classpath { bool mayInitClasses_; }; -int64_t JNICALL -mapData(Thread* t, object, uintptr_t*) +int64_t JNICALL mapData(Thread* t, object, uintptr_t*) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "libcore/io/MemoryMappedFile"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "libcore/io/MemoryMappedFile"); PROTECT(t, c); - + object instance = makeNew(t, c); PROTECT(t, instance); - - object constructor = resolveMethod(t, c, "", "(JJ)V"); - + + GcMethod* constructor = resolveMethod(t, c, "", "(JJ)V"); + const char* jar = "javahomeJar"; Finder* finder = getFinder(t, jar, strlen(jar)); if (finder) { @@ -624,19 +641,21 @@ mapData(Thread* t, object, uintptr_t*) cp->tzdata = r; - t->m->processor->invoke - (t, constructor, instance, reinterpret_cast(r->start()), - static_cast(r->length())); + t->m->processor->invoke(t, + constructor, + instance, + reinterpret_cast(r->start()), + static_cast(r->length())); return reinterpret_cast(instance); } } - throwNew(t, Machine::RuntimeExceptionType); + throwNew(t, GcRuntimeException::Type); } void JNICALL -closeMemoryMappedFile(Thread* t, object method, uintptr_t* arguments) + closeMemoryMappedFile(Thread* t, GcMethod* method, uintptr_t* arguments) { object file = reinterpret_cast(arguments[0]); PROTECT(t, file); @@ -644,52 +663,53 @@ closeMemoryMappedFile(Thread* t, object method, uintptr_t* arguments) MyClasspath* cp = static_cast(t->m->classpath); if (cp->tzdata) { - object field = resolveField(t, objectClass(t, file), "address", "J"); - - if (fieldAtOffset(file, fieldOffset(t, field)) - == reinterpret_cast(cp->tzdata->start())) - { + GcField* field = resolveField(t, objectClass(t, file), "address", "J"); + + if (fieldAtOffset(file, field->offset()) + == reinterpret_cast(cp->tzdata->start())) { cp->tzdata->dispose(); cp->tzdata = 0; - fieldAtOffset(file, fieldOffset(t, field)) = 0; + fieldAtOffset(file, field->offset()) = 0; return; } } - t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - file); + t->m->processor->invoke(t, + cast(t, + getMethodRuntimeData(t, method) + ->native() + ->as(t) + ->original()), + file); } -bool -matchType(Thread* t, object field, object o) +bool matchType(Thread* t, GcField* field, object o) { - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: - return objectClass(t, o) == type(t, Machine::ByteType); + return objectClass(t, o) == type(t, GcByte::Type); case BooleanField: - return objectClass(t, o) == type(t, Machine::BooleanType); + return objectClass(t, o) == type(t, GcBoolean::Type); case CharField: - return objectClass(t, o) == type(t, Machine::CharType); + return objectClass(t, o) == type(t, GcChar::Type); case ShortField: - return objectClass(t, o) == type(t, Machine::ShortType); + return objectClass(t, o) == type(t, GcShort::Type); case IntField: - return objectClass(t, o) == type(t, Machine::IntType); + return objectClass(t, o) == type(t, GcInt::Type); case LongField: - return objectClass(t, o) == type(t, Machine::LongType); + return objectClass(t, o) == type(t, GcLong::Type); case FloatField: - return objectClass(t, o) == type(t, Machine::FloatType); + return objectClass(t, o) == type(t, GcFloat::Type); case DoubleField: - return objectClass(t, o) == type(t, Machine::DoubleType); + return objectClass(t, o) == type(t, GcDouble::Type); case ObjectField: if (o == 0) { @@ -697,47 +717,45 @@ matchType(Thread* t, object field, object o) } else { PROTECT(t, o); - object spec; - if (byteArrayBody(t, fieldSpec(t, field), 0) == '[') { - spec = fieldSpec(t, field);; + GcByteArray* spec; + if (field->spec()->body()[0] == '[') { + spec = field->spec(); } else { - spec = makeByteArray(t, byteArrayLength(t, fieldSpec(t, field)) - 2); - - memcpy(&byteArrayBody(t, spec, 0), - &byteArrayBody(t, fieldSpec(t, field), 1), - byteArrayLength(t, fieldSpec(t, field)) - 3); + spec = makeByteArray(t, field->spec()->length() - 2); - byteArrayBody - (t, spec, byteArrayLength(t, fieldSpec(t, field)) - 3) = 0; + memcpy(spec->body().begin(), + &field->spec()->body()[1], + field->spec()->length() - 3); + + spec->body()[field->spec()->length() - 3] = 0; } - return instanceOf - (t, resolveClass(t, classLoader(t, fieldClass(t, field)), spec), o); + return instanceOf(t, resolveClass(t, field->class_()->loader(), spec), o); } - default: abort(t); + default: + abort(t); } } -object -getField(Thread* t, object field, object instance) +object getField(Thread* t, GcField* field, object instance) { PROTECT(t, field); PROTECT(t, instance); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); object target; - if (fieldFlags(t, field) & ACC_STATIC) { - target = classStaticTable(t, fieldClass(t, field)); - } else if (instanceOf(t, fieldClass(t, field), instance)){ + if (field->flags() & ACC_STATIC) { + target = field->class_()->staticTable(); + } else if (instanceOf(t, field->class_(), instance)) { target = instance; } else { - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } - unsigned offset = fieldOffset(t, field); - switch (fieldCode(t, field)) { + unsigned offset = field->offset(); + switch (field->code()) { case ByteField: return makeByte(t, fieldAtOffset(target, offset)); @@ -765,93 +783,97 @@ getField(Thread* t, object field, object instance) case ObjectField: return fieldAtOffset(target, offset); - default: abort(t); + default: + abort(t); } } -void -setField(Thread* t, object field, object instance, object value) +void setField(Thread* t, GcField* field, object instance, object value) { PROTECT(t, field); PROTECT(t, instance); PROTECT(t, value); if (not matchType(t, field, value)) { - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } object target; - if ((fieldFlags(t, field) & ACC_STATIC) != 0) { - target = classStaticTable(t, fieldClass(t, field)); - } else if (instanceOf(t, fieldClass(t, field), instance)){ + if ((field->flags() & ACC_STATIC) != 0) { + target = field->class_()->staticTable(); + } else if (instanceOf(t, field->class_(), instance)) { target = instance; } else { - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } PROTECT(t, target); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); - unsigned offset = fieldOffset(t, field); - switch (fieldCode(t, field)) { + unsigned offset = field->offset(); + switch (field->code()) { case ByteField: - fieldAtOffset(target, offset) = byteValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case BooleanField: - fieldAtOffset(target, offset) = booleanValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case CharField: - fieldAtOffset(target, offset) = charValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case ShortField: - fieldAtOffset(target, offset) = shortValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case IntField: - fieldAtOffset(target, offset) = intValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case LongField: - fieldAtOffset(target, offset) = longValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case FloatField: - fieldAtOffset(target, offset) = floatValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case DoubleField: - fieldAtOffset(target, offset) = doubleValue(t, value); + fieldAtOffset(target, offset) = cast(t, value)->value(); break; case ObjectField: - set(t, target, offset, value); + setField(t, target, offset, value); break; - default: abort(t); + default: + abort(t); } } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -Classpath* -makeClasspath(System*, Allocator* allocator, const char*, const char*) +Classpath* makeClasspath(System*, + Allocator* allocator, + const char*, + const char*) { return new (allocator->allocate(sizeof(local::MyClasspath))) - local::MyClasspath(allocator); + local::MyClasspath(allocator); } -} // namespace vm +} // namespace vm -extern "C" int -jniRegisterNativeMethods(JNIEnv* e, const char* className, - const JNINativeMethod* methods, int methodCount) +extern "C" int jniRegisterNativeMethods(JNIEnv* e, + const char* className, + const JNINativeMethod* methods, + int methodCount) { jclass c = e->vtable->FindClass(e, className); @@ -864,14 +886,14 @@ jniRegisterNativeMethods(JNIEnv* e, const char* className, return 0; } -extern "C" void -jniLogException(JNIEnv*, int, const char*, jthrowable) +extern "C" void jniLogException(JNIEnv*, int, const char*, jthrowable) { // ignore } -extern "C" int -jniThrowException(JNIEnv* e, const char* className, const char* message) +extern "C" int jniThrowException(JNIEnv* e, + const char* className, + const char* message) { jclass c = e->vtable->FindClass(e, className); @@ -882,9 +904,10 @@ jniThrowException(JNIEnv* e, const char* className, const char* message) return 0; } -extern "C" int -jniThrowExceptionFmt(JNIEnv* e, const char* className, const char* format, - va_list args) +extern "C" int jniThrowExceptionFmt(JNIEnv* e, + const char* className, + const char* format, + va_list args) { const unsigned size = 4096; char buffer[size]; @@ -892,26 +915,22 @@ jniThrowExceptionFmt(JNIEnv* e, const char* className, const char* format, return jniThrowException(e, className, buffer); } -extern "C" int -jniThrowNullPointerException(JNIEnv* e, const char* message) +extern "C" int jniThrowNullPointerException(JNIEnv* e, const char* message) { return jniThrowException(e, "java/lang/NullPointerException", message); } -extern "C" int -jniThrowRuntimeException(JNIEnv* e, const char* message) +extern "C" int jniThrowRuntimeException(JNIEnv* e, const char* message) { return jniThrowException(e, "java/lang/RuntimeException", message); } -extern "C" int -jniThrowIOException(JNIEnv* e, const char* message) +extern "C" int jniThrowIOException(JNIEnv* e, const char* message) { return jniThrowException(e, "java/lang/IOException", message); } -extern "C" const char* -jniStrError(int error, char* buffer, size_t length) +extern "C" const char* jniStrError(int error, char* buffer, size_t length) { #ifdef PLATFORM_WINDOWS const char* s = getErrnoDescription(error); @@ -933,20 +952,20 @@ jniStrError(int error, char* buffer, size_t length) /* * Android log priority values (as text) */ -const char * const androidLogPriorityTitles[] = { - "UNKNOWN", - "DEFAULT", - "VERBOSE", - "DEBUG", - "INFO", - "WARNING", - "ERROR", - "FATAL", - "SILENT" -}; +const char* const androidLogPriorityTitles[] = {"UNKNOWN", + "DEFAULT", + "VERBOSE", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "FATAL", + "SILENT"}; -extern "C" int -__android_log_print(int priority, const char* tag, const char* format, ...) +extern "C" int __android_log_print(int priority, + const char* tag, + const char* format, + ...) { va_list a; const unsigned size = 4096; @@ -957,45 +976,55 @@ __android_log_print(int priority, const char* tag, const char* format, ...) va_end(a); #ifndef PLATFORM_WINDOWS - return printf("[%s] %s: %s\n", androidLogPriorityTitles[priority], tag, buffer); + return printf( + "[%s] %s: %s\n", androidLogPriorityTitles[priority], tag, buffer); #else - return __mingw_fprintf(stderr, "[%s] %s: %s\n", androidLogPriorityTitles[priority], tag, buffer); + return __mingw_fprintf( + stderr, "[%s] %s: %s\n", androidLogPriorityTitles[priority], tag, buffer); #endif } -extern "C" int -jniGetFDFromFileDescriptor(JNIEnv* e, jobject descriptor) +extern "C" int jniGetFDFromFileDescriptor(JNIEnv* e, jobject descriptor) { - return e->vtable->GetIntField - (e, descriptor, e->vtable->GetFieldID - (e, e->vtable->FindClass - (e, "java/io/FileDescriptor"), "descriptor", "I")); + return e->vtable->GetIntField( + e, + descriptor, + e->vtable->GetFieldID(e, + e->vtable->FindClass(e, "java/io/FileDescriptor"), + "descriptor", + "I")); } -extern "C" void -jniSetFileDescriptorOfFD(JNIEnv* e, jobject descriptor, int value) +extern "C" void jniSetFileDescriptorOfFD(JNIEnv* e, + jobject descriptor, + int value) { - e->vtable->SetIntField - (e, descriptor, e->vtable->GetFieldID - (e, e->vtable->FindClass - (e, "java/io/FileDescriptor"), "descriptor", "I"), value); + e->vtable->SetIntField( + e, + descriptor, + e->vtable->GetFieldID(e, + e->vtable->FindClass(e, "java/io/FileDescriptor"), + "descriptor", + "I"), + value); } -extern "C" jobject -jniCreateFileDescriptor(JNIEnv* e, int fd) +extern "C" jobject jniCreateFileDescriptor(JNIEnv* e, int fd) { - jobject descriptor = e->vtable->NewObject - (e, e->vtable->FindClass(e, "java/io/FileDescriptor"), - e->vtable->GetMethodID - (e, e->vtable->FindClass(e, "java/io/FileDescriptor"), "", "()V")); + jobject descriptor = e->vtable->NewObject( + e, + e->vtable->FindClass(e, "java/io/FileDescriptor"), + e->vtable->GetMethodID(e, + e->vtable->FindClass(e, "java/io/FileDescriptor"), + "", + "()V")); jniSetFileDescriptorOfFD(e, descriptor, fd); return descriptor; } -int -register_org_apache_harmony_dalvik_NativeTestTarget(_JNIEnv*) +int register_org_apache_harmony_dalvik_NativeTestTarget(_JNIEnv*) { // ignore return 0; @@ -1008,15 +1037,14 @@ int register_java_math_NativeBN(_JNIEnv*) } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_compareTo -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_compareTo(Thread* t, object, uintptr_t* arguments) { - object a = reinterpret_cast(arguments[0]); - object b = reinterpret_cast(arguments[1]); + GcString* a = cast(t, reinterpret_cast(arguments[0])); + GcString* b = cast(t, reinterpret_cast(arguments[1])); - unsigned length = stringLength(t, a); - if (length > stringLength(t, b)) { - length = stringLength(t, b); + unsigned length = a->length(t); + if (length > b->length(t)) { + length = b->length(t); } for (unsigned i = 0; i < length; ++i) { @@ -1026,56 +1054,53 @@ Avian_java_lang_String_compareTo } } - return stringLength(t, a) - stringLength(t, b); + return a->length(t) - b->length(t); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_isEmpty -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_isEmpty(Thread* t, object, uintptr_t* arguments) { - return stringLength(t, reinterpret_cast(arguments[0])) == 0; + return cast(t, reinterpret_cast(arguments[0]))->length(t) + == 0; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_length -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_length(Thread* t, object, uintptr_t* arguments) { - return stringLength(t, reinterpret_cast(arguments[0])); + return cast(t, reinterpret_cast(arguments[0]))->length(t); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_intern -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_intern(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (intern(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + intern(t, reinterpret_cast(arguments[0]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_charAt -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_charAt(Thread* t, object, uintptr_t* arguments) { - return stringCharAt(t, reinterpret_cast(arguments[0]), arguments[1]); + return stringCharAt(t, + cast(t, reinterpret_cast(arguments[0])), + arguments[1]); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_equals -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_equals(Thread* t, object, uintptr_t* arguments) { - return arguments[1] and stringEqual - (t, reinterpret_cast(arguments[0]), - reinterpret_cast(arguments[1])); + return arguments[1] and stringEqual(t, + reinterpret_cast(arguments[0]), + reinterpret_cast(arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_fastIndexOf -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_fastIndexOf(Thread* t, object, uintptr_t* arguments) { - object s = reinterpret_cast(arguments[0]); + GcString* s = cast(t, reinterpret_cast(arguments[0])); unsigned c = arguments[1]; unsigned start = arguments[2]; - for (unsigned i = start; i < stringLength(t, s); ++i) { + for (unsigned i = start; i < s->length(t); ++i) { if (stringCharAt(t, s, i) == c) { return i; } @@ -1085,77 +1110,89 @@ Avian_java_lang_String_fastIndexOf } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getInterfaces -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getInterfaces(Thread* t, object, uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); - object addendum = classAddendum(t, jclassVmClass(t, c)); + GcClassAddendum* addendum = c->vmClass()->addendum(); if (addendum) { - object table = classAddendumInterfaceTable(t, addendum); + GcArray* table = cast(t, addendum->interfaceTable()); if (table) { PROTECT(t, table); - object array = makeObjectArray(t, arrayLength(t, table)); + object array = makeObjectArray(t, table->length()); PROTECT(t, array); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object c = getJClass(t, arrayBody(t, table, i)); - set(t, array, ArrayBody + (i * BytesPerWord), c); + for (unsigned i = 0; i < table->length(); ++i) { + GcJclass* c = getJClass(t, cast(t, table->body()[i])); + setField(t, + array, + ArrayBody + (i * BytesPerWord), + reinterpret_cast(c)); } return reinterpret_cast(array); } } - return reinterpret_cast - (makeObjectArray(t, type(t, Machine::JclassType), 0)); + return reinterpret_cast( + makeObjectArray(t, type(t, GcJclass::Type), 0)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaredClasses -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaredClasses(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (getDeclaredClasses - (t, jclassVmClass(t, reinterpret_cast(arguments[0])), + return reinterpret_cast(getDeclaredClasses( + t, + cast(t, reinterpret_cast(arguments[0]))->vmClass(), arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaringClass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaringClass(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (getDeclaringClass - (t, jclassVmClass(t, reinterpret_cast(arguments[0])))); + return reinterpret_cast(getDeclaringClass( + t, cast(t, reinterpret_cast(arguments[0]))->vmClass())); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getEnclosingMethod -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getEnclosingMethod(Thread* t, + object, + uintptr_t* arguments) { - object c = jclassVmClass(t, reinterpret_cast(arguments[0])); + GcClass* c + = cast(t, reinterpret_cast(arguments[0]))->vmClass(); PROTECT(t, c); - object addendum = classAddendum(t, c); + GcClassAddendum* addendum = c->addendum(); if (addendum) { - object enclosingClass = classAddendumEnclosingClass(t, addendum); + object enclosingClass = addendum->enclosingClass(); if (enclosingClass) { PROTECT(t, enclosingClass); - enclosingClass = getJClass - (t, resolveClass(t, classLoader(t, c), enclosingClass)); + // enclosingClass = getJClass + // (t, resolveClass(t, classLoader(t, c), enclosingClass)); - object enclosingMethod = classAddendumEnclosingMethod(t, addendum); + object enclosingMethod = addendum->enclosingMethod(); if (enclosingMethod) { PROTECT(t, enclosingMethod); - return reinterpret_cast - (t->m->classpath->makeJMethod - (t, findMethodInClass - (t, enclosingClass, pairFirst(t, enclosingMethod), - pairSecond(t, enclosingMethod)))); + abort(t); + // TODO: the following violates type safety; enclosingClass at this + // point is a GcJclass (having come from "getJClass()") - but the method + // expects a GcClass. + // Figure it out. + + // return reinterpret_cast + // (t->m->classpath->makeJMethod + // (t, findMethodInClass + // (t, cast(t, enclosingClass), pairFirst(t, + // enclosingMethod), + // pairSecond(t, enclosingMethod)))); } } } @@ -1163,19 +1200,22 @@ Avian_java_lang_Class_getEnclosingMethod } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getEnclosingConstructor -(Thread* t, object method, uintptr_t* arguments) + Avian_java_lang_Class_getEnclosingConstructor(Thread* t, + object method, + uintptr_t* arguments) { return Avian_java_lang_Class_getEnclosingMethod(t, method, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_newInstanceImpl -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_newInstanceImpl(Thread* t, + object, + uintptr_t* arguments) { - object c = jclassVmClass(t, reinterpret_cast(arguments[0])); + GcClass* c + = cast(t, reinterpret_cast(arguments[0]))->vmClass(); - object method = resolveMethod(t, c, "", "()V"); + GcMethod* method = resolveMethod(t, c, "", "()V"); PROTECT(t, method); object instance = makeNew(t, c); @@ -1187,61 +1227,66 @@ Avian_java_lang_Class_newInstanceImpl } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getComponentType -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getComponentType(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); - if (classArrayDimensions(t, jclassVmClass(t, c))) { - uint8_t n = byteArrayBody(t, className(t, jclassVmClass(t, c)), 1); + if (c->vmClass()->arrayDimensions()) { + uint8_t n = c->vmClass()->name()->body()[1]; if (n != 'L' and n != '[') { - return reinterpret_cast - (getJClass(t, primitiveClass(t, n))); + return reinterpret_cast(getJClass(t, primitiveClass(t, n))); } else { - return reinterpret_cast - (getJClass(t, classStaticTable(t, jclassVmClass(t, c)))); - } + return reinterpret_cast( + getJClass(t, c->vmClass()->arrayElementClass())); + } } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_classForName -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_classForName(Thread* t, object, uintptr_t* arguments) { object name = reinterpret_cast(arguments[0]); PROTECT(t, name); - object loader = reinterpret_cast(arguments[2]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[2])); PROTECT(t, loader); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "forName", - "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"); + GcMethod* method = resolveMethod( + t, + roots(t)->bootLoader(), + "avian/Classes", + "forName", + "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"); - return reinterpret_cast - (t->m->processor->invoke - (t, method, 0, name, static_cast(arguments[1]), loader)); + return reinterpret_cast(t->m->processor->invoke( + t, method, 0, name, static_cast(arguments[1]), loader)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaredField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaredField(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, c); object name = reinterpret_cast(arguments[1]); PROTECT(t, name); - - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "findField", - "(Lavian/VMClass;Ljava/lang/String;)I"); - int index = intValue - (t, t->m->processor->invoke - (t, method, 0, jclassVmClass(t, c), name)); + GcMethod* method = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "findField", + "(Lavian/VMClass;Ljava/lang/String;)I"); + + int index = cast( + t, t->m->processor->invoke(t, method, 0, c->vmClass(), name)) + ->value(); if (index >= 0) { return reinterpret_cast(local::makeField(t, c, index)); @@ -1251,10 +1296,11 @@ Avian_java_lang_Class_getDeclaredField } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaredConstructorOrMethod -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaredConstructorOrMethod(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, c); object name = reinterpret_cast(arguments[1]); @@ -1262,117 +1308,122 @@ Avian_java_lang_Class_getDeclaredConstructorOrMethod object parameterTypes = reinterpret_cast(arguments[2]); PROTECT(t, parameterTypes); - - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "findMethod", - "(Lavian/VMClass;Ljava/lang/String;[Ljava/lang/Class;)I"); - int index = intValue - (t, t->m->processor->invoke - (t, method, 0, jclassVmClass(t, c), name, parameterTypes)); + GcMethod* method + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "findMethod", + "(Lavian/VMClass;Ljava/lang/String;[Ljava/lang/Class;)I"); + + int index = cast(t, + t->m->processor->invoke( + t, method, 0, c->vmClass(), name, parameterTypes)) + ->value(); if (index >= 0) { - return reinterpret_cast - (local::makeMethodOrConstructor(t, c, index)); + return reinterpret_cast( + local::makeMethodOrConstructor(t, c, index)); } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_SystemClassLoader_findLoadedVMClass -(Thread*, object, uintptr_t*); + Avian_avian_SystemClassLoader_findLoadedVMClass(Thread*, + object, + uintptr_t*); extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMClassLoader_findLoadedClass -(Thread* t, object method, uintptr_t* arguments) + Avian_java_lang_VMClassLoader_findLoadedClass(Thread* t, + object method, + uintptr_t* arguments) { - int64_t v = Avian_avian_SystemClassLoader_findLoadedVMClass - (t, method, arguments); + int64_t v + = Avian_avian_SystemClassLoader_findLoadedVMClass(t, method, arguments); if (v) { - return reinterpret_cast - (getJClass(t, reinterpret_cast(v))); + return reinterpret_cast( + getJClass(t, cast(t, reinterpret_cast(v)))); } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMClassLoader_defineClass__Ljava_lang_ClassLoader_2Ljava_lang_String_2_3BII -(Thread* t, object method, uintptr_t* arguments) + Avian_java_lang_VMClassLoader_defineClass__Ljava_lang_ClassLoader_2Ljava_lang_String_2_3BII( + Thread* t, + object method, + uintptr_t* arguments) { - uintptr_t args[] - = { arguments[0], arguments[2], arguments[3], arguments[4] }; + uintptr_t args[] = {arguments[0], arguments[2], arguments[3], arguments[4]}; int64_t v = Avian_avian_Classes_defineVMClass(t, method, args); if (v) { - return reinterpret_cast - (getJClass(t, reinterpret_cast(v))); + return reinterpret_cast( + getJClass(t, cast(t, reinterpret_cast(v)))); } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_bootClassPath -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMRuntime_bootClassPath(Thread* t, object, uintptr_t*) { - return reinterpret_cast(root(t, Machine::BootLoader)); + return reinterpret_cast(roots(t)->bootLoader()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_classPath -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMRuntime_classPath(Thread* t, object, uintptr_t*) { - return reinterpret_cast(root(t, Machine::AppLoader)); + return reinterpret_cast(roots(t)->appLoader()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_vmVersion -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMRuntime_vmVersion(Thread* t, object, uintptr_t*) { return reinterpret_cast(makeString(t, "%s", AVIAN_VERSION)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_properties -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMRuntime_properties(Thread* t, object, uintptr_t*) { - object array = makeObjectArray( - t, type(t, Machine::StringType), t->m->propertyCount + 1); + object array + = makeObjectArray(t, type(t, GcString::Type), t->m->propertyCount + 1); PROTECT(t, array); unsigned i; for (i = 0; i < t->m->propertyCount; ++i) { - object s = makeString(t, "%s", t->m->properties[i]); - set(t, array, ArrayBody + (i * BytesPerWord), s); + GcString* s = makeString(t, "%s", t->m->properties[i]); + setField( + t, array, ArrayBody + (i * BytesPerWord), reinterpret_cast(s)); } { - object s = makeString(t, "%s", "java.protocol.handler.pkgs=avian"); - set(t, array, ArrayBody + (i++ * BytesPerWord), s); + GcString* s = makeString(t, "%s", "java.protocol.handler.pkgs=avian"); + setField(t, + array, + ArrayBody + (i++ * BytesPerWord), + reinterpret_cast(s)); } return reinterpret_cast(array); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Runtime_gc -(Thread* t, object, uintptr_t*) + Avian_java_lang_Runtime_gc(Thread* t, object, uintptr_t*) { collect(t, Heap::MajorCollection); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Runtime_nativeLoad -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Runtime_nativeLoad(Thread* t, object, uintptr_t* arguments) { - object name = reinterpret_cast(arguments[0]); + GcString* name = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, name); - unsigned length = stringLength(t, name); + unsigned length = name->length(t); THREAD_RUNTIME_ARRAY(t, char, n, length + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(n)); @@ -1384,10 +1435,10 @@ Avian_java_lang_Runtime_nativeLoad } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_System_arraycopy -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_System_arraycopy(Thread* t, object, uintptr_t* arguments) { - arrayCopy(t, reinterpret_cast(arguments[0]), + arrayCopy(t, + reinterpret_cast(arguments[0]), arguments[1], reinterpret_cast(arguments[2]), arguments[3], @@ -1395,73 +1446,71 @@ Avian_java_lang_System_arraycopy } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_objectFieldOffset -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_objectFieldOffset(Thread* t, + object, + uintptr_t* arguments) { - object jfield = reinterpret_cast(arguments[1]); - return fieldOffset - (t, arrayBody - (t, classFieldTable - (t, jclassVmClass(t, jfieldDeclaringClass(t, jfield))), - jfieldSlot(t, jfield))); + GcJfield* jfield = cast(t, reinterpret_cast(arguments[1])); + return cast( + t, + cast(t, jfield->declaringClass()->vmClass()->fieldTable()) + ->body()[jfield->slot()])->offset(); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_VMThread_interrupt -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_VMThread_interrupt(Thread* t, object, uintptr_t* arguments) { object vmThread = reinterpret_cast(arguments[0]); PROTECT(t, vmThread); - object field = resolveField - (t, objectClass(t, vmThread), "thread", "Ljava/lang/Thread;"); + GcField* field = resolveField( + t, objectClass(t, vmThread), "thread", "Ljava/lang/Thread;"); - interrupt - (t, reinterpret_cast - (threadPeer(t, fieldAtOffset(vmThread, fieldOffset(t, field))))); + interrupt( + t, + reinterpret_cast( + cast(t, fieldAtOffset(vmThread, field->offset())) + ->peer())); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMThread_interrupted -(Thread* t, object, uintptr_t*) + Avian_java_lang_VMThread_interrupted(Thread* t, object, uintptr_t*) { return getAndClearInterrupted(t, t); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMThread_isInterrupted -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_VMThread_isInterrupted(Thread* t, + object, + uintptr_t* arguments) { object vmThread = reinterpret_cast(arguments[0]); PROTECT(t, vmThread); - object field = resolveField - (t, objectClass(t, vmThread), "thread", "Ljava/lang/Thread;"); + GcField* field = resolveField( + t, objectClass(t, vmThread), "thread", "Ljava/lang/Thread;"); - return threadInterrupted - (t, fieldAtOffset(vmThread, fieldOffset(t, field))); + return cast(t, fieldAtOffset(vmThread, field->offset())) + ->interrupted(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMThread_getStatus -(Thread*, object, uintptr_t*) + Avian_java_lang_VMThread_getStatus(Thread*, object, uintptr_t*) { // todo return 1; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_VMThread_currentThread -(Thread* t, object, uintptr_t*) + Avian_java_lang_VMThread_currentThread(Thread* t, object, uintptr_t*) { return reinterpret_cast(t->javaThread); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_VMThread_create -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_VMThread_create(Thread* t, object, uintptr_t* arguments) { - object thread = reinterpret_cast(arguments[0]); + GcThread* thread = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, thread); local::initVmThread(t, thread); @@ -1469,58 +1518,60 @@ Avian_java_lang_VMThread_create } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_VMThread_sleep -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_VMThread_sleep(Thread* t, object, uintptr_t* arguments) { - int64_t milliseconds; memcpy(&milliseconds, arguments, 8); - if (arguments[2] > 0) ++ milliseconds; - if (milliseconds <= 0) milliseconds = 1; + int64_t milliseconds; + memcpy(&milliseconds, arguments, 8); + if (arguments[2] > 0) + ++milliseconds; + if (milliseconds <= 0) + milliseconds = 1; - if (threadSleepLock(t, t->javaThread) == 0) { + if (t->javaThread->sleepLock() == 0) { object lock = makeJobject(t); - set(t, t->javaThread, ThreadSleepLock, lock); + t->javaThread->setSleepLock(t, lock); } - acquire(t, threadSleepLock(t, t->javaThread)); - vm::wait(t, threadSleepLock(t, t->javaThread), milliseconds); - release(t, threadSleepLock(t, t->javaThread)); + acquire(t, t->javaThread->sleepLock()); + vm::wait(t, t->javaThread->sleepLock(), milliseconds); + release(t, t->javaThread->sleepLock()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMStack_getThreadStackTrace -(Thread* t, object, uintptr_t* arguments) + Avian_dalvik_system_VMStack_getThreadStackTrace(Thread* t, + object, + uintptr_t* arguments) { - Thread* p = reinterpret_cast - (threadPeer(t, reinterpret_cast(arguments[0]))); + Thread* p = reinterpret_cast( + cast(t, reinterpret_cast(arguments[0]))->peer()); - return reinterpret_cast - (local::translateStackTrace - (t, p == t - ? makeTrace(t) - : t->m->processor->getStackTrace(t, p))); + return reinterpret_cast(local::translateStackTrace( + t, p == t ? makeTrace(t) : t->m->processor->getStackTrace(t, p))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMStack_getCallingClassLoader -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMStack_getCallingClassLoader(Thread* t, + object, + uintptr_t*) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t): - t(t), loader(0), counter(2) - { } + Visitor(Thread* t) : t(t), loader(0), counter(2) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { if (counter--) { return true; } else { - this->loader = classLoader(t, methodClass(t, walker->method())); + this->loader = walker->method()->class_()->loader(); return false; } } Thread* t; - object loader; + GcClassLoader* loader; unsigned counter; } v(t); @@ -1530,34 +1581,33 @@ Avian_dalvik_system_VMStack_getCallingClassLoader } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMStack_getClasses -(Thread* t, object, uintptr_t*) + Avian_dalvik_system_VMStack_getClasses(Thread* t, object, uintptr_t*) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t): - t(t), array(0), counter(0) - { } + Visitor(Thread* t) : t(t), array(0), counter(0) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { if (counter < 2) { return true; } else { if (array == 0) { - array = makeObjectArray - (t, type(t, Machine::JclassType), walker->count()); + array = makeObjectArray(t, type(t, GcJclass::Type), walker->count()); } - object c = getJClass(t, methodClass(t, walker->method())); - - assert(t, counter - 2 < objectArrayLength(t, array)); + GcJclass* c = getJClass(t, walker->method()->class_()); - set(t, array, ArrayBody + ((counter - 2) * BytesPerWord), c); + assertT(t, counter - 2 < objectArrayLength(t, array)); + + setField(t, array, ArrayBody + ((counter - 2) * BytesPerWord), c); return true; } - ++ counter; + ++counter; } Thread* t; @@ -1569,83 +1619,75 @@ Avian_dalvik_system_VMStack_getClasses t->m->processor->walkStack(t, &v); - return reinterpret_cast - (v.array ? v.array : makeObjectArray(t, type(t, Machine::JclassType), 0)); + return reinterpret_cast( + v.array ? v.array : makeObjectArray(t, type(t, GcJclass::Type), 0)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_min -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_min(Thread*, object, uintptr_t* arguments) { return min(static_cast(arguments[0]), static_cast(arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_max -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_max(Thread*, object, uintptr_t* arguments) { return max(static_cast(arguments[0]), static_cast(arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_cos -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_cos(Thread*, object, uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); return doubleToBits(cos(bitsToDouble(v))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_sin -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_sin(Thread*, object, uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); return doubleToBits(sin(bitsToDouble(v))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_sqrt -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_sqrt(Thread*, object, uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); return doubleToBits(sqrt(bitsToDouble(v))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_abs__I -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_abs__I(Thread*, object, uintptr_t* arguments) { return abs(static_cast(arguments[0])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_abs__J -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_abs__J(Thread*, object, uintptr_t* arguments) { return llabs(arguments[0]); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Math_abs__F -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Math_abs__F(Thread*, object, uintptr_t* arguments) { return floatToBits(abs(bitsToFloat(arguments[0]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Float_intBitsToFloat -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Float_intBitsToFloat(Thread*, object, uintptr_t* arguments) { return arguments[0]; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Float_floatToIntBits -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Float_floatToIntBits(Thread*, object, uintptr_t* arguments) { if (((arguments[0] & 0x7F800000) == 0x7F800000) - and ((arguments[0] & 0x007FFFFF) != 0)) - { + and ((arguments[0] & 0x007FFFFF) != 0)) { return 0x7fc00000; } else { return arguments[0]; @@ -1653,10 +1695,12 @@ Avian_java_lang_Float_floatToIntBits } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Double_doubleToRawLongBits -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Double_doubleToRawLongBits(Thread*, + object, + uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); // todo: do we need to do NaN checks as in // Avian_java_lang_Float_floatToIntBits above? If so, update // Double.doubleToRawLongBits in the Avian class library too. @@ -1664,114 +1708,112 @@ Avian_java_lang_Double_doubleToRawLongBits } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Object_wait -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_wait(Thread* t, object, uintptr_t* arguments) { - jlong milliseconds; memcpy(&milliseconds, arguments + 1, sizeof(jlong)); + jlong milliseconds; + memcpy(&milliseconds, arguments + 1, sizeof(jlong)); wait(t, reinterpret_cast(arguments[0]), milliseconds); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Object_notifyAll -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_notifyAll(Thread* t, object, uintptr_t* arguments) { notifyAll(t, reinterpret_cast(arguments[0])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_getClass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_getClass(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (getJClass(t, objectClass(t, reinterpret_cast(arguments[0])))); + return reinterpret_cast( + getJClass(t, objectClass(t, reinterpret_cast(arguments[0])))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_hashCode -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_hashCode(Thread* t, object, uintptr_t* arguments) { return objectHash(t, reinterpret_cast(arguments[0])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_internalClone -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_internalClone(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (clone(t, reinterpret_cast(arguments[1]))); + return reinterpret_cast( + clone(t, reinterpret_cast(arguments[1]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getModifiers -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getModifiers(Thread* t, object, uintptr_t* arguments) { - return classModifiers - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))); + return classModifiers( + t, cast(t, reinterpret_cast(arguments[0]))->vmClass()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getSuperclass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getSuperclass(Thread* t, object, uintptr_t* arguments) { - object c = jclassVmClass(t, reinterpret_cast(arguments[0])); - if (classFlags(t, c) & ACC_INTERFACE) { + GcClass* c + = cast(t, reinterpret_cast(arguments[0]))->vmClass(); + if (c->flags() & ACC_INTERFACE) { return 0; } else { - object s = classSuper(t, c); + GcClass* s = c->super(); return s ? reinterpret_cast(getJClass(t, s)) : 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_desiredAssertionStatus -(Thread*, object, uintptr_t*) + Avian_java_lang_Class_desiredAssertionStatus(Thread*, object, uintptr_t*) { return 1; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getNameNative -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getNameNative(Thread* t, object, uintptr_t* arguments) { - object name = className - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))); + GcByteArray* name = cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->name(); - THREAD_RUNTIME_ARRAY(t, char, s, byteArrayLength(t, name)); - replace('/', '.', RUNTIME_ARRAY_BODY(s), - reinterpret_cast(&byteArrayBody(t, name, 0))); + THREAD_RUNTIME_ARRAY(t, char, s, name->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(s), + reinterpret_cast(name->body().begin())); - return reinterpret_cast - (makeString(t, "%s", RUNTIME_ARRAY_BODY(s))); + return reinterpret_cast( + makeString(t, "%s", RUNTIME_ARRAY_BODY(s))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_isInterface -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_isInterface(Thread* t, object, uintptr_t* arguments) { - return (classFlags - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))) - & ACC_INTERFACE) != 0; + return (cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->flags() & ACC_INTERFACE) != 0; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_isPrimitive -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_isPrimitive(Thread* t, object, uintptr_t* arguments) { - return (classVmFlags - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))) - & PrimitiveFlag) != 0; + return (cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->vmFlags() & PrimitiveFlag) != 0; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_isAnonymousClass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_isAnonymousClass(Thread* t, + object, + uintptr_t* arguments) { - object name = className - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))); + GcByteArray* name = cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->name(); - for (unsigned i = 0; i < byteArrayLength(t, name) - 1; ++i) { - int c = byteArrayBody(t, name, i); + for (unsigned i = 0; i < name->length() - 1; ++i) { + int c = name->body()[i]; if (c != '$' and (c < '0' or c > '9')) { return false; } @@ -1781,119 +1823,135 @@ Avian_java_lang_Class_isAnonymousClass } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getClassLoader -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getClassLoader(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (classLoader - (t, jclassVmClass(t, reinterpret_cast(arguments[0])))); + return reinterpret_cast( + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->loader()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_isAssignableFrom -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_isAssignableFrom(Thread* t, + object, + uintptr_t* arguments) { - object this_ = reinterpret_cast(arguments[0]); - object that = reinterpret_cast(arguments[1]); + GcJclass* this_ = cast(t, reinterpret_cast(arguments[0])); + GcJclass* that = cast(t, reinterpret_cast(arguments[1])); if (LIKELY(that)) { - return isAssignableFrom - (t, jclassVmClass(t, this_), jclassVmClass(t, that)); + return isAssignableFrom(t, this_->vmClass(), that->vmClass()); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_isInstance -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_isInstance(Thread* t, object, uintptr_t* arguments) { - object this_ = reinterpret_cast(arguments[0]); + GcJclass* this_ = cast(t, reinterpret_cast(arguments[0])); object o = reinterpret_cast(arguments[1]); if (o) { - return instanceOf(t, jclassVmClass(t, this_), o); + return instanceOf(t, this_->vmClass(), o); } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaredMethods -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaredMethods(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, c); bool publicOnly = arguments[1]; - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getMethods", - "(Lavian/VMClass;Z)[Ljava/lang/reflect/Method;"); + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getMethods", + "(Lavian/VMClass;Z)[Ljava/lang/reflect/Method;"); - return reinterpret_cast - (t->m->processor->invoke(t, get, 0, jclassVmClass(t, c), publicOnly)); + return reinterpret_cast( + t->m->processor->invoke(t, get, 0, c->vmClass(), publicOnly)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getDeclaredFields -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getDeclaredFields(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, reinterpret_cast(arguments[0])); PROTECT(t, c); bool publicOnly = arguments[1]; - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getFields", - "(Lavian/VMClass;Z)[Ljava/lang/reflect/Field;"); + GcMethod* get = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getFields", + "(Lavian/VMClass;Z)[Ljava/lang/reflect/Field;"); - return reinterpret_cast - (t->m->processor->invoke(t, get, 0, jclassVmClass(t, c), publicOnly)); + return reinterpret_cast( + t->m->processor->invoke(t, get, 0, c->vmClass(), publicOnly)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_invokeNative -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_invokeNative(Thread* t, + object, + uintptr_t* arguments) { object instance = reinterpret_cast(arguments[1]); object args = reinterpret_cast(arguments[2]); - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[3]))), - arguments[6]); + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[3])) + ->vmClass() + ->methodTable())->body()[arguments[6]]); return reinterpret_cast(invoke(t, method, instance, args)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_getMethodModifiers -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_getMethodModifiers(Thread* t, + object, + uintptr_t* arguments) { - return methodFlags - (t, arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1])); + return cast( + t, + cast( + t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->methodTable())->body()[arguments[1]])->flags(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_isAnnotationPresent -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_isAnnotationPresent(Thread* t, + object, + uintptr_t* arguments) { - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->methodTable())->body()[arguments[1]]); - object addendum = methodAddendum(t, method); + GcMethodAddendum* addendum = method->addendum(); if (addendum) { - object table = addendumAnnotationTable(t, addendum); + object table = addendum->annotationTable(); if (table) { for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { if (objectArrayBody(t, objectArrayBody(t, table, i), 1) - == reinterpret_cast(arguments[2])) - { + == reinterpret_cast(arguments[2])) { return true; } } @@ -1904,34 +1962,41 @@ Avian_java_lang_reflect_Method_isAnnotationPresent } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_getAnnotation -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_getAnnotation(Thread* t, + object, + uintptr_t* arguments) { - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->methodTable())->body()[arguments[1]]); - object addendum = methodAddendum(t, method); + GcMethodAddendum* addendum = method->addendum(); if (addendum) { - object table = addendumAnnotationTable(t, addendum); + object table = addendum->annotationTable(); if (table) { for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { if (objectArrayBody(t, objectArrayBody(t, table, i), 1) - == reinterpret_cast(arguments[2])) - { + == reinterpret_cast(arguments[2])) { PROTECT(t, method); PROTECT(t, table); - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getAnnotation", - "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" - "Ljava/lang/annotation/Annotation;"); + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getAnnotation", + "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" + "Ljava/lang/annotation/Annotation;"); - return reinterpret_cast - (t->m->processor->invoke - (t, get, 0, classLoader(t, methodClass(t, method)), - objectArrayBody(t, table, i))); + return reinterpret_cast( + t->m->processor->invoke(t, + get, + 0, + method->class_()->loader(), + objectArrayBody(t, table, i))); } } } @@ -1941,95 +2006,48 @@ Avian_java_lang_reflect_Method_getAnnotation } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_getDeclaredAnnotations -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_getDeclaredAnnotations(Thread* t, + object, + uintptr_t* arguments) { - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->methodTable())->body()[arguments[1]]); - object addendum = methodAddendum(t, method); + GcMethodAddendum* addendum = method->addendum(); if (addendum) { - object table = addendumAnnotationTable(t, addendum); + object table = addendum->annotationTable(); if (table) { PROTECT(t, method); PROTECT(t, table); - object array = makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), "java/lang/annotation/Annotation"), - objectArrayLength(t, table)); + object array = makeObjectArray( + t, + resolveClass( + t, roots(t)->bootLoader(), "java/lang/annotation/Annotation"), + objectArrayLength(t, table)); PROTECT(t, array); - - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getAnnotation", - "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" - "Ljava/lang/annotation/Annotation;"); + + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getAnnotation", + "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" + "Ljava/lang/annotation/Annotation;"); PROTECT(t, get); for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { - object a = t->m->processor->invoke - (t, get, 0, classLoader(t, methodClass(t, method)), - objectArrayBody(t, table, i)); + object a = t->m->processor->invoke(t, + get, + 0, + method->class_()->loader(), + objectArrayBody(t, table, i)); - set(t, array, ArrayBody + (i * BytesPerWord), a); - } - - return reinterpret_cast(array); - } - } - - return reinterpret_cast - (makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), "java/lang/annotation/Annotation"), - 0)); -} - -extern "C" AVIAN_EXPORT int64_t JNICALL - Avian_java_lang_reflect_Field_getDeclaredAnnotations(Thread* t, - object, - uintptr_t* arguments) -{ - object field = arrayBody( - t, - classFieldTable( - t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); - - object addendum = fieldAddendum(t, field); - if (addendum) { - object table = addendumAnnotationTable(t, addendum); - if (table) { - PROTECT(t, field); - PROTECT(t, table); - - object array - = makeObjectArray(t, - resolveClass(t, - root(t, Machine::BootLoader), - "java/lang/annotation/Annotation"), - objectArrayLength(t, table)); - PROTECT(t, array); - - object get = resolveMethod(t, - root(t, Machine::BootLoader), - "avian/Classes", - "getAnnotation", - "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" - "Ljava/lang/annotation/Annotation;"); - PROTECT(t, get); - - for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { - object a - = t->m->processor->invoke(t, - get, - 0, - classLoader(t, reinterpret_cast(arguments[0])), - objectArrayBody(t, table, i)); - - set(t, array, ArrayBody + (i * BytesPerWord), a); + setField(t, array, ArrayBody + (i * BytesPerWord), a); } return reinterpret_cast(array); @@ -2039,48 +2057,112 @@ extern "C" AVIAN_EXPORT int64_t JNICALL return reinterpret_cast(makeObjectArray( t, resolveClass( - t, root(t, Machine::BootLoader), "java/lang/annotation/Annotation"), + t, roots(t)->bootLoader(), "java/lang/annotation/Annotation"), 0)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_getDefaultValue -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getDeclaredAnnotations(Thread* t, + object, + uintptr_t* arguments) { - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[1]))), - arguments[2]); + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->fieldTable())->body()[arguments[1]]); - object addendum = methodAddendum(t, method); + GcFieldAddendum* addendum = field->addendum(); if (addendum) { - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", - "getAnnotationDefaultValue", - "(Ljava/lang/ClassLoader;Lavian/MethodAddendum;)" - "Ljava/lang/Object;"); + object table = addendum->annotationTable(); + if (table) { + PROTECT(t, field); + PROTECT(t, table); - return reinterpret_cast - (t->m->processor->invoke - (t, get, 0, classLoader(t, methodClass(t, method)), addendum)); + object array = makeObjectArray( + t, + resolveClass( + t, roots(t)->bootLoader(), "java/lang/annotation/Annotation"), + objectArrayLength(t, table)); + PROTECT(t, array); + + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getAnnotation", + "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" + "Ljava/lang/annotation/Annotation;"); + PROTECT(t, get); + + for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { + object a = t->m->processor->invoke( + t, + get, + 0, + cast(t, reinterpret_cast(arguments[0]))->loader(), + objectArrayBody(t, table, i)); + + setField(t, array, ArrayBody + (i * BytesPerWord), a); + } + + return reinterpret_cast(array); + } + } + + return reinterpret_cast(makeObjectArray( + t, + resolveClass( + t, roots(t)->bootLoader(), "java/lang/annotation/Annotation"), + 0)); +} + +extern "C" AVIAN_EXPORT int64_t JNICALL + Avian_java_lang_reflect_Method_getDefaultValue(Thread* t, + object, + uintptr_t* arguments) +{ + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[1])) + ->vmClass() + ->methodTable())->body()[arguments[2]]); + + GcMethodAddendum* addendum = method->addendum(); + if (addendum) { + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getAnnotationDefaultValue", + "(Ljava/lang/ClassLoader;Lavian/MethodAddendum;)" + "Ljava/lang/Object;"); + + return reinterpret_cast(t->m->processor->invoke( + t, get, 0, method->class_()->loader(), addendum)); } return 0; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Constructor_constructNative -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Constructor_constructNative(Thread* t, + object, + uintptr_t* arguments) { object args = reinterpret_cast(arguments[1]); PROTECT(t, args); - object c = jclassVmClass(t, reinterpret_cast(arguments[2])); + GcClass* c + = cast(t, reinterpret_cast(arguments[2]))->vmClass(); PROTECT(t, c); initClass(t, c); - object method = arrayBody(t, classMethodTable(t, c), arguments[4]); + GcMethod* method = cast( + t, cast(t, c->methodTable())->body()[arguments[4]]); PROTECT(t, method); object instance = makeNew(t, c); @@ -2092,14 +2174,17 @@ Avian_java_lang_reflect_Constructor_constructNative } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getField(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[2]))), - arguments[4]); - + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[2])) + ->vmClass() + ->fieldTable())->body()[arguments[4]]); + PROTECT(t, field); object instance = reinterpret_cast(arguments[1]); @@ -2109,48 +2194,57 @@ Avian_java_lang_reflect_Field_getField } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getIField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getIField(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[2]))), - arguments[4]); - + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[2])) + ->vmClass() + ->fieldTable())->body()[arguments[4]]); + PROTECT(t, field); object instance = reinterpret_cast(arguments[1]); PROTECT(t, instance); - return intValue(t, local::getField(t, field, instance)); + return cast(t, local::getField(t, field, instance))->value(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getJField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getJField(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[2]))), - arguments[4]); - + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[2])) + ->vmClass() + ->fieldTable())->body()[arguments[4]]); + PROTECT(t, field); object instance = reinterpret_cast(arguments[1]); PROTECT(t, instance); - return longValue(t, local::getField(t, field, instance)); + return cast(t, local::getField(t, field, instance))->value(); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_reflect_Field_setField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_setField(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[2]))), - arguments[4]); - + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[2])) + ->vmClass() + ->fieldTable())->body()[arguments[4]]); + PROTECT(t, field); object instance = reinterpret_cast(arguments[1]); @@ -2163,62 +2257,75 @@ Avian_java_lang_reflect_Field_setField } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_reflect_Field_setIField -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_setIField(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[2]))), - arguments[4]); + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[2])) + ->vmClass() + ->fieldTable())->body()[arguments[4]]); object instance = reinterpret_cast(arguments[1]); PROTECT(t, instance); - object value = makeInt(t, arguments[7]); + object value = reinterpret_cast(makeInt(t, arguments[7])); local::setField(t, field, instance, value); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getFieldModifiers -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getFieldModifiers(Thread* t, + object, + uintptr_t* arguments) { - return fieldFlags - (t, arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[1]))), - arguments[2])); + return cast( + t, + cast( + t, + cast(t, reinterpret_cast(arguments[1])) + ->vmClass() + ->fieldTable())->body()[arguments[2]])->flags(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getAnnotation -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getAnnotation(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->fieldTable())->body()[arguments[1]]); - object addendum = fieldAddendum(t, field); + GcFieldAddendum* addendum = field->addendum(); if (addendum) { - object table = addendumAnnotationTable(t, addendum); + object table = addendum->annotationTable(); if (table) { for (unsigned i = 0; i < objectArrayLength(t, table); ++i) { if (objectArrayBody(t, objectArrayBody(t, table, i), 1) - == reinterpret_cast(arguments[2])) - { + == reinterpret_cast(arguments[2])) { PROTECT(t, field); PROTECT(t, table); - object get = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getAnnotation", - "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" - "Ljava/lang/annotation/Annotation;"); + GcMethod* get + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getAnnotation", + "(Ljava/lang/ClassLoader;[Ljava/lang/Object;)" + "Ljava/lang/annotation/Annotation;"); - return reinterpret_cast - (t->m->processor->invoke - (t, get, 0, classLoader(t, fieldClass(t, field)), - objectArrayBody(t, table, i))); + return reinterpret_cast( + t->m->processor->invoke(t, + get, + 0, + field->class_()->loader(), + objectArrayBody(t, table, i))); } } } @@ -2228,25 +2335,28 @@ Avian_java_lang_reflect_Field_getAnnotation } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getSignatureAnnotation -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getSignatureAnnotation(Thread* t, + object, + uintptr_t* arguments) { - object field = arrayBody - (t, classFieldTable - (t, jclassVmClass(t, reinterpret_cast(arguments[1]))), - arguments[2]); + GcField* field = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[1])) + ->vmClass() + ->fieldTable())->body()[arguments[2]]); - object addendum = fieldAddendum(t, field); + GcFieldAddendum* addendum = field->addendum(); if (addendum) { - object signature = addendumSignature(t, addendum); + GcByteArray* signature = cast(t, addendum->signature()); if (signature) { object array = makeObjectArray(t, 1); PROTECT(t, array); - - object string = t->m->classpath->makeString - (t, signature, 0, byteArrayLength(t, signature) - 1); - - set(t, array, ArrayBody, string); + + GcString* string = t->m->classpath->makeString( + t, signature, 0, signature->length() - 1); + + setField(t, array, ArrayBody, string); return reinterpret_cast(array); } @@ -2256,68 +2366,73 @@ Avian_java_lang_reflect_Field_getSignatureAnnotation } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Throwable_nativeFillInStackTrace -(Thread* t, object, uintptr_t*) + Avian_java_lang_Throwable_nativeFillInStackTrace(Thread* t, + object, + uintptr_t*) { return reinterpret_cast(getTrace(t, 2)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Throwable_nativeGetStackTrace -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Throwable_nativeGetStackTrace(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (local::translateStackTrace(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + local::translateStackTrace(t, reinterpret_cast(arguments[0]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_makeMethod -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_makeMethod(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (local::makeMethodOrConstructor - (t, reinterpret_cast(arguments[0]), arguments[1])); -} - -extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_makeField -(Thread* t, object, uintptr_t* arguments) -{ - return reinterpret_cast - (local::makeField - (t, reinterpret_cast(arguments[0]), arguments[1])); -} - -extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Array_createObjectArray -(Thread* t, object, uintptr_t* arguments) -{ - return reinterpret_cast - (makeObjectArray - (t, jclassVmClass(t, reinterpret_cast(arguments[0])), + return reinterpret_cast(local::makeMethodOrConstructor( + t, + cast(t, reinterpret_cast(arguments[0])), arguments[1])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_nio_ByteOrder_isLittleEndian -(Thread*, object, uintptr_t*) + Avian_avian_Classes_makeField(Thread* t, object, uintptr_t* arguments) +{ + return reinterpret_cast(local::makeField( + t, + cast(t, reinterpret_cast(arguments[0])), + arguments[1])); +} + +extern "C" AVIAN_EXPORT int64_t JNICALL + Avian_java_lang_reflect_Array_createObjectArray(Thread* t, + object, + uintptr_t* arguments) +{ + return reinterpret_cast(makeObjectArray( + t, + cast(t, reinterpret_cast(arguments[0]))->vmClass(), + arguments[1])); +} + +extern "C" AVIAN_EXPORT int64_t JNICALL + Avian_java_nio_ByteOrder_isLittleEndian(Thread*, object, uintptr_t*) { return true; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_newNonMovableArray -(Thread* t, object, uintptr_t* arguments) + Avian_dalvik_system_VMRuntime_newNonMovableArray(Thread* t, + object, + uintptr_t* arguments) { - if (jclassVmClass(t, reinterpret_cast(arguments[1])) - == type(t, Machine::JbyteType)) - { - object array = allocate3 - (t, t->m->heap, Machine::FixedAllocation, - ArrayBody + arguments[2], false); + if (cast(t, reinterpret_cast(arguments[1]))->vmClass() + == type(t, GcJbyte::Type)) { + GcByteArray* array + = reinterpret_cast(allocate3(t, + t->m->heap, + Machine::FixedAllocation, + ArrayBody + arguments[2], + false)); - setObjectClass(t, array, type(t, Machine::ByteArrayType)); - byteArrayLength(t, array) = arguments[2]; + setObjectClass(t, array, type(t, GcByteArray::Type)); + array->length() = arguments[2]; return reinterpret_cast(array); } else { @@ -2327,18 +2442,20 @@ Avian_dalvik_system_VMRuntime_newNonMovableArray } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_dalvik_system_VMRuntime_addressOf -(Thread*, object, uintptr_t* arguments) + Avian_dalvik_system_VMRuntime_addressOf(Thread*, + object, + uintptr_t* arguments) { return arguments[1] + ArrayBody; } extern "C" AVIAN_EXPORT void JNICALL -Avian_libcore_io_Memory_pokeLong -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_pokeLong(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); - int64_t v; memcpy(&v, arguments + 2, 8); + int64_t address; + memcpy(&address, arguments, 8); + int64_t v; + memcpy(&v, arguments + 2, 8); if (arguments[4]) { v = swapV8(v); } @@ -2346,159 +2463,170 @@ Avian_libcore_io_Memory_pokeLong } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Memory_peekLong -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_peekLong(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); - int64_t v; memcpy(&v, reinterpret_cast(address), 8); + int64_t address; + memcpy(&address, arguments, 8); + int64_t v; + memcpy(&v, reinterpret_cast(address), 8); return arguments[2] ? swapV8(v) : v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_libcore_io_Memory_pokeInt -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_pokeInt(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); + int64_t address; + memcpy(&address, arguments, 8); int32_t v = arguments[3] ? swapV4(arguments[2]) : arguments[2]; memcpy(reinterpret_cast(address), &v, 4); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Memory_peekInt -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_peekInt(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); - int32_t v; memcpy(&v, reinterpret_cast(address), 4); + int64_t address; + memcpy(&address, arguments, 8); + int32_t v; + memcpy(&v, reinterpret_cast(address), 4); return arguments[2] ? swapV4(v) : v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_libcore_io_Memory_pokeShort -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_pokeShort(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); + int64_t address; + memcpy(&address, arguments, 8); int16_t v = arguments[3] ? swapV2(arguments[2]) : arguments[2]; memcpy(reinterpret_cast(address), &v, 2); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Memory_peekShort -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_peekShort(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); - int16_t v; memcpy(&v, reinterpret_cast(address), 2); + int64_t address; + memcpy(&address, arguments, 8); + int16_t v; + memcpy(&v, reinterpret_cast(address), 2); return arguments[2] ? swapV2(v) : v; } extern "C" AVIAN_EXPORT void JNICALL -Avian_libcore_io_Memory_pokeByte -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_pokeByte(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); + int64_t address; + memcpy(&address, arguments, 8); *reinterpret_cast(address) = arguments[2]; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Memory_peekByte -(Thread*, object, uintptr_t* arguments) + Avian_libcore_io_Memory_peekByte(Thread*, object, uintptr_t* arguments) { - int64_t address; memcpy(&address, arguments, 8); + int64_t address; + memcpy(&address, arguments, 8); return *reinterpret_cast(address); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_System_nanoTime -(Thread* t, object, uintptr_t*) + Avian_java_lang_System_nanoTime(Thread* t, object, uintptr_t*) { return t->m->system->now() * 1000 * 1000; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_System_currentTimeMillis -(Thread* t, object, uintptr_t*) + Avian_java_lang_System_currentTimeMillis(Thread* t, object, uintptr_t*) { return t->m->system->now(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_System_identityHashCode -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_System_identityHashCode(Thread* t, + object, + uintptr_t* arguments) { return objectHash(t, reinterpret_cast(arguments[0])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8 -(Thread*, object, uintptr_t*) + Avian_java_util_concurrent_atomic_AtomicLong_VMSupportsCS8(Thread*, + object, + uintptr_t*) { return true; } #ifdef PLATFORM_WINDOWS -# include +#include -void register_java_io_Console(_JNIEnv*) { } -void register_java_lang_ProcessManager(_JNIEnv*) { } -void register_libcore_net_RawSocket(_JNIEnv*) { } -//void register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(_JNIEnv*) { } +void register_java_io_Console(_JNIEnv*) +{ +} +void register_java_lang_ProcessManager(_JNIEnv*) +{ +} +void register_libcore_net_RawSocket(_JNIEnv*) +{ +} +// void register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(_JNIEnv*) { +// } extern "C" AVIAN_EXPORT void JNICALL -Avian_libcore_io_OsConstants_initConstants -(Thread* t, object method, uintptr_t*) + Avian_libcore_io_OsConstants_initConstants(Thread* t, + object method, + uintptr_t*) { - object c = methodClass(t, method); + object c = method->class_(); PROTECT(t, c); object table = classStaticTable(t, c); PROTECT(t, table); - object field = resolveField(t, c, "STDIN_FILENO", "I"); - fieldAtOffset(table, fieldOffset(t, field)) = 0; + GcField* field = resolveField(t, c, "STDIN_FILENO", "I"); + fieldAtOffset(table, field->offset()) = 0; field = resolveField(t, c, "STDOUT_FILENO", "I"); - fieldAtOffset(table, fieldOffset(t, field)) = 1; + fieldAtOffset(table, field->offset()) = 1; field = resolveField(t, c, "STDERR_FILENO", "I"); - fieldAtOffset(table, fieldOffset(t, field)) = 2; + fieldAtOffset(table, field->offset()) = 2; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Posix_getenv(Thread* t, object, uintptr_t* arguments) + Avian_libcore_io_Posix_getenv(Thread* t, object, uintptr_t* arguments) { object name = reinterpret_cast(arguments[1]); - THREAD_RUNTIME_ARRAY(t, uint16_t, chars, stringLength(t, name) + 1); + THREAD_RUNTIME_ARRAY(t, uint16_t, chars, name->length(t) + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(chars)); - wchar_t* value = _wgetenv - (reinterpret_cast(RUNTIME_ARRAY_BODY(chars))); + wchar_t* value + = _wgetenv(reinterpret_cast(RUNTIME_ARRAY_BODY(chars))); if (value) { unsigned size = wcslen(value); - + object a = makeCharArray(t, size); if (size) { memcpy(&charArrayBody(t, a, 0), value, size * sizeof(jchar)); } - - return reinterpret_cast - (t->m->classpath->makeString(t, a, 0, size)); + + return reinterpret_cast( + t->m->classpath->makeString(t, a, 0, size)); } else { return 0; } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Posix_uname(Thread* t, object, uintptr_t*) + Avian_libcore_io_Posix_uname(Thread* t, object, uintptr_t*) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "libcore/io/StructUtsname"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "libcore/io/StructUtsname"); PROTECT(t, c); - + object instance = makeNew(t, c); PROTECT(t, instance); - + #ifdef ARCH_x86_32 object arch = makeString(t, "x86"); #elif defined ARCH_x86_64 @@ -2509,24 +2637,30 @@ Avian_libcore_io_Posix_uname(Thread* t, object, uintptr_t*) object arch = makeString(t, "unknown"); #endif - set(t, instance, fieldOffset - (t, resolveField(t, c, "machine", "Ljava/lang/String;")), arch); + set(t, + instance, + fieldOffset(t, resolveField(t, c, "machine", "Ljava/lang/String;")), + arch); object platform = makeString(t, "Windows"); - set(t, instance, fieldOffset - (t, resolveField(t, c, "sysname", "Ljava/lang/String;")), platform); + set(t, + instance, + fieldOffset(t, resolveField(t, c, "sysname", "Ljava/lang/String;")), + platform); object version = makeString(t, "unknown"); - set(t, instance, fieldOffset - (t, resolveField(t, c, "release", "Ljava/lang/String;")), version); + set(t, + instance, + fieldOffset(t, resolveField(t, c, "release", "Ljava/lang/String;")), + version); return reinterpret_cast(instance); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_libcore_io_Posix_writeBytes(Thread* t, object, uintptr_t* arguments) + Avian_libcore_io_Posix_writeBytes(Thread* t, object, uintptr_t* arguments) { object fd = reinterpret_cast(arguments[1]); PROTECT(t, fd); @@ -2540,23 +2674,28 @@ Avian_libcore_io_Posix_writeBytes(Thread* t, object, uintptr_t* arguments) int d = jniGetFDFromFileDescriptor(t, &fd); int r; - if (objectClass(t, buffer) == type(t, Machine::ByteArrayType)) { + if (objectClass(t, buffer) == type(t, GcByteArray::Type)) { void* tmp = t->m->heap->allocate(count); memcpy(tmp, &byteArrayBody(t, buffer, offset), count); - { ENTER(t, Thread::IdleState); + { + ENTER(t, Thread::IdleState); r = _write(d, tmp, count); } t->m->heap->free(tmp, count); } else { void* p = local::getDirectBufferAddress(t, buffer); - { ENTER(t, Thread::IdleState); + { + ENTER(t, Thread::IdleState); r = _write(d, p, count); } } if (r < 0) { THREAD_RUNTIME_ARRAY(t, char, message, 256); - throwNew(t, Machine::RuntimeExceptionType, "writeBytes %d: %s", d, + throwNew(t, + GcRuntimeException::Type, + "writeBytes %d: %s", + d, jniStrError(errno, RUNTIME_ARRAY_BODY(message), 0)); } else { return r; diff --git a/src/classpath-avian.cpp b/src/classpath-avian.cpp index 7bed10ce32..86626215d2 100644 --- a/src/classpath-avian.cpp +++ b/src/classpath-avian.cpp @@ -22,28 +22,28 @@ namespace local { class MyClasspath : public Classpath { public: - MyClasspath(Allocator* allocator): - allocator(allocator) - { } + MyClasspath(Allocator* allocator) : allocator(allocator) + { + } - virtual object - makeJclass(Thread* t, object class_) + virtual GcJclass* makeJclass(Thread* t, GcClass* class_) { return vm::makeJclass(t, class_); } - virtual object - makeString(Thread* t, object array, int32_t offset, int32_t length) + virtual GcString* makeString(Thread* t, + object array, + int32_t offset, + int32_t length) { return vm::makeString(t, array, offset, length, 0); } - virtual object - makeThread(Thread* t, Thread* parent) + virtual GcThread* makeThread(Thread* t, Thread* parent) { - object group; + GcThreadGroup* group; if (parent) { - group = threadGroup(t, parent->javaThread); + group = parent->javaThread->group(); } else { group = makeThreadGroup(t, 0, 0, 0); } @@ -51,72 +51,79 @@ class MyClasspath : public Classpath { const unsigned NewState = 0; const unsigned NormalPriority = 5; - return vm::makeThread - (t, 0, 0, 0, 0, 0, NewState, NormalPriority, 0, 0, 0, - root(t, Machine::AppLoader), 0, 0, group, 0); + return vm::makeThread(t, + 0, + 0, + 0, + 0, + 0, + NewState, + NormalPriority, + 0, + 0, + 0, + roots(t)->appLoader(), + 0, + 0, + group, + 0); } - virtual object - makeJMethod(Thread* t, object vmMethod) + virtual object makeJMethod(Thread* t, GcMethod* vmMethod) { PROTECT(t, vmMethod); - object jmethod = makeJmethod(t, vmMethod, false); + GcJmethod* jmethod = makeJmethod(t, vmMethod, false); - return byteArrayBody(t, methodName(t, vmMethod), 0) == '<' - ? makeJconstructor(t, jmethod) : jmethod; + return vmMethod->name()->body()[0] == '<' + ? (object)makeJconstructor(t, jmethod) + : (object)jmethod; } - virtual object - getVMMethod(Thread* t, object jmethod) + virtual GcMethod* getVMMethod(Thread* t, object jmethod) { - return objectClass(t, jmethod) == type(t, Machine::JmethodType) - ? jmethodVmMethod(t, jmethod) - : jmethodVmMethod(t, jconstructorMethod(t, jmethod)); + return objectClass(t, jmethod) == type(t, GcJmethod::Type) + ? cast(t, jmethod)->vmMethod() + : cast(t, jmethod)->method()->vmMethod(); } - virtual object - makeJField(Thread* t, object vmField) + virtual object makeJField(Thread* t, GcField* vmField) { return makeJfield(t, vmField, false); } - virtual object - getVMField(Thread* t, object jfield) + virtual GcField* getVMField(Thread* t UNUSED, GcJfield* jfield) { - return jfieldVmField(t, jfield); + return jfield->vmField(); } - virtual void - clearInterrupted(Thread*) + virtual void clearInterrupted(Thread*) { // ignore } - virtual void - runThread(Thread* t) + virtual void runThread(Thread* t) { - object method = resolveMethod - (t, root(t, Machine::BootLoader), "java/lang/Thread", "run", - "(Ljava/lang/Thread;)V"); + GcMethod* method = resolveMethod(t, + roots(t)->bootLoader(), + "java/lang/Thread", + "run", + "(Ljava/lang/Thread;)V"); t->m->processor->invoke(t, method, 0, t->javaThread); } - virtual void - resolveNative(Thread* t, object method) + virtual void resolveNative(Thread* t, GcMethod* method) { vm::resolveNative(t, method); } - virtual void - interceptMethods(Thread*) + virtual void interceptMethods(Thread*) { // ignore } - virtual void - preBoot(Thread*) + virtual void preBoot(Thread*) { // ignore } @@ -126,64 +133,59 @@ class MyClasspath : public Classpath { return true; } - virtual void - boot(Thread*) + virtual void boot(Thread*) { // ignore } - virtual const char* - bootClasspath() + virtual const char* bootClasspath() { return AVIAN_CLASSPATH; } - virtual object - makeDirectByteBuffer(Thread* t, void* p, jlong capacity) + virtual object makeDirectByteBuffer(Thread* t, void* p, jlong capacity) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/nio/DirectByteBuffer"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/nio/DirectByteBuffer"); PROTECT(t, c); object instance = makeNew(t, c); PROTECT(t, instance); - object constructor = resolveMethod(t, c, "", "(JI)V"); + GcMethod* constructor = resolveMethod(t, c, "", "(JI)V"); - t->m->processor->invoke - (t, constructor, instance, reinterpret_cast(p), - static_cast(capacity)); + t->m->processor->invoke(t, + constructor, + instance, + reinterpret_cast(p), + static_cast(capacity)); return instance; } - virtual void* - getDirectBufferAddress(Thread* t, object b) + virtual void* getDirectBufferAddress(Thread* t, object b) { PROTECT(t, b); - object field = resolveField(t, objectClass(t, b), "address", "J"); + GcField* field = resolveField(t, objectClass(t, b), "address", "J"); - return reinterpret_cast - (fieldAtOffset(b, fieldOffset(t, field))); + return reinterpret_cast(fieldAtOffset(b, field->offset())); } - virtual int64_t - getDirectBufferCapacity(Thread* t, object b) + virtual int64_t getDirectBufferCapacity(Thread* t, object b) { PROTECT(t, b); - object field = resolveField - (t, objectClass(t, b), "capacity", "I"); + GcField* field = resolveField(t, objectClass(t, b), "capacity", "I"); - return fieldAtOffset(b, fieldOffset(t, field)); + return fieldAtOffset(b, field->offset()); } - virtual bool canTailCall(Thread* t, - object, - object calleeClassName, - object calleeMethodName, - object) + virtual bool canTailCall(Thread* t UNUSED, + GcMethod*, + GcByteArray* calleeClassName, + GcByteArray* calleeMethodName, + GcByteArray*) { // we can't tail call System.load[Library] or // Runtime.load[Library] due to their use of @@ -192,34 +194,30 @@ class MyClasspath : public Classpath { return ( (strcmp("loadLibrary", - reinterpret_cast(&byteArrayBody(t, calleeMethodName, 0))) + reinterpret_cast(calleeMethodName->body().begin())) and strcmp("load", - reinterpret_cast( - &byteArrayBody(t, calleeMethodName, 0)))) - or (strcmp( - "java/lang/System", - reinterpret_cast(&byteArrayBody(t, calleeClassName, 0))) - and strcmp("java/lang/Runtime", - reinterpret_cast( - &byteArrayBody(t, calleeClassName, 0))))); + reinterpret_cast(calleeMethodName->body().begin()))) + or (strcmp("java/lang/System", + reinterpret_cast(calleeClassName->body().begin())) + and strcmp( + "java/lang/Runtime", + reinterpret_cast(calleeClassName->body().begin())))); } - virtual object libraryClassLoader(Thread* t, object caller) + virtual GcClassLoader* libraryClassLoader(Thread* t, GcMethod* caller) { - return (methodClass(t, caller) == type(t, Machine::ClassLoaderType) + return (caller->class_() == type(t, Gc::ClassLoaderType) and t->libraryLoadStack) ? t->libraryLoadStack->classLoader - : classLoader(t, methodClass(t, caller)); + : caller->class_()->loader(); } - virtual void - shutDown(Thread*) + virtual void shutDown(Thread*) { // ignore } - virtual void - dispose() + virtual void dispose() { allocator->free(this, sizeof(*this)); } @@ -227,71 +225,72 @@ class MyClasspath : public Classpath { Allocator* allocator; }; -void -enumerateThreads(Thread* t, Thread* x, object array, unsigned* index, - unsigned limit) +void enumerateThreads(Thread* t, + Thread* x, + GcArray* array, + unsigned* index, + unsigned limit) { if (*index < limit) { - set(t, array, ArrayBody + (*index * BytesPerWord), x->javaThread); - ++ (*index); + array->setBodyElement(t, *index, x->javaThread); + ++(*index); - if (x->peer) enumerateThreads(t, x->peer, array, index, limit); - - if (x->child) enumerateThreads(t, x->child, array, index, limit); + if (x->peer) + enumerateThreads(t, x->peer, array, index, limit); + + if (x->child) + enumerateThreads(t, x->child, array, index, limit); } } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -Classpath* -makeClasspath(System*, Allocator* allocator, const char*, const char*) +Classpath* makeClasspath(System*, + Allocator* allocator, + const char*, + const char*) { return new (allocator->allocate(sizeof(local::MyClasspath))) - local::MyClasspath(allocator); + local::MyClasspath(allocator); } -} // namespace vm +} // namespace vm extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_toString -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_toString(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); unsigned hash = objectHash(t, this_); - object s = makeString - (t, "%s@0x%x", - &byteArrayBody(t, className(t, objectClass(t, this_)), 0), - hash); + GcString* s = makeString( + t, "%s@0x%x", objectClass(t, this_)->name()->body().begin(), hash); return reinterpret_cast(s); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_getVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_getVMClass(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (objectClass(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + objectClass(t, reinterpret_cast(arguments[0]))); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Object_wait -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_wait(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); - int64_t milliseconds; memcpy(&milliseconds, arguments + 1, 8); + int64_t milliseconds; + memcpy(&milliseconds, arguments + 1, 8); vm::wait(t, this_, milliseconds); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Object_notify -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_notify(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); @@ -299,8 +298,7 @@ Avian_java_lang_Object_notify } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Object_notifyAll -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_notifyAll(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); @@ -308,8 +306,7 @@ Avian_java_lang_Object_notifyAll } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_hashCode -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_hashCode(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); @@ -317,53 +314,55 @@ Avian_java_lang_Object_hashCode } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Object_clone -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Object_clone(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (clone(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + clone(t, reinterpret_cast(arguments[0]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_io_ObjectInputStream_makeInstance -(Thread* t, object, uintptr_t* arguments) + Avian_java_io_ObjectInputStream_makeInstance(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcClass* c = cast(t, reinterpret_cast(arguments[0])); return reinterpret_cast(make(t, c)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_LegacyObjectInputStream_makeInstance -(Thread* t, object, uintptr_t* arguments) + Avian_avian_LegacyObjectInputStream_makeInstance(Thread* t, + object, + uintptr_t* arguments) { return Avian_java_io_ObjectInputStream_makeInstance(t, NULL, arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getPrimitive -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getPrimitive(Thread* t, + object, + uintptr_t* arguments) { object instance = reinterpret_cast(arguments[0]); int code = arguments[1]; int offset = arguments[2]; switch (code) { - case ByteField: + case ByteField: return fieldAtOffset(instance, offset); - case BooleanField: + case BooleanField: return fieldAtOffset(instance, offset); - case CharField: + case CharField: return fieldAtOffset(instance, offset); - case ShortField: + case ShortField: return fieldAtOffset(instance, offset); - case IntField: + case IntField: return fieldAtOffset(instance, offset); - case LongField: + case LongField: return fieldAtOffset(instance, offset); - case FloatField: + case FloatField: return fieldAtOffset(instance, offset); - case DoubleField: + case DoubleField: return fieldAtOffset(instance, offset); default: abort(t); @@ -371,8 +370,9 @@ Avian_java_lang_reflect_Field_getPrimitive } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Field_getObject -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_getObject(Thread*, + object, + uintptr_t* arguments) { object instance = reinterpret_cast(arguments[0]); int offset = arguments[1]; @@ -381,13 +381,15 @@ Avian_java_lang_reflect_Field_getObject } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_reflect_Field_setPrimitive -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_setPrimitive(Thread* t, + object, + uintptr_t* arguments) { object instance = reinterpret_cast(arguments[0]); int code = arguments[1]; int offset = arguments[2]; - int64_t value; memcpy(&value, arguments + 3, 8); + int64_t value; + memcpy(&value, arguments + 3, 8); switch (code) { case ByteField: @@ -402,16 +404,16 @@ Avian_java_lang_reflect_Field_setPrimitive case ShortField: fieldAtOffset(instance, offset) = static_cast(value); break; - case IntField: + case IntField: fieldAtOffset(instance, offset) = static_cast(value); break; - case LongField: + case LongField: fieldAtOffset(instance, offset) = static_cast(value); break; - case FloatField: + case FloatField: fieldAtOffset(instance, offset) = static_cast(value); break; - case DoubleField: + case DoubleField: fieldAtOffset(instance, offset) = static_cast(value); break; default: @@ -420,118 +422,125 @@ Avian_java_lang_reflect_Field_setPrimitive } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_reflect_Field_setObject -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Field_setObject(Thread* t, + object, + uintptr_t* arguments) { object instance = reinterpret_cast(arguments[0]); int offset = arguments[1]; object value = reinterpret_cast(arguments[2]); - set(t, instance, offset, value); + setField(t, instance, offset, value); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Constructor_make -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Constructor_make(Thread* t, + object, + uintptr_t* arguments) { - object c = reinterpret_cast(arguments[0]); + GcClass* c = cast(t, reinterpret_cast(arguments[0])); return reinterpret_cast(make(t, c)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_getCaller -(Thread* t, object, uintptr_t*) + Avian_java_lang_reflect_Method_getCaller(Thread* t, object, uintptr_t*) { return reinterpret_cast(getCaller(t, 2)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Method_invoke -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Method_invoke(Thread* t, + object, + uintptr_t* arguments) { - object method = reinterpret_cast(arguments[0]); + GcMethod* method = cast(t, reinterpret_cast(arguments[0])); object instance = reinterpret_cast(arguments[1]); object args = reinterpret_cast(arguments[2]); THREAD_RESOURCE0(t, { - if (t->exception) { - object exception = t->exception; - t->exception = makeThrowable - (t, Machine::InvocationTargetExceptionType, 0, 0, exception); - } - }); + if (t->exception) { + GcThrowable* exception = t->exception; + t->exception = makeThrowable( + t, GcInvocationTargetException::Type, 0, 0, exception); + } + }); - unsigned returnCode = methodReturnCode(t, method); + unsigned returnCode = method->returnCode(); - return reinterpret_cast - (translateInvokeResult - (t, returnCode, t->m->processor->invokeArray(t, method, instance, args))); + return reinterpret_cast(translateInvokeResult( + t, returnCode, t->m->processor->invokeArray(t, method, instance, args))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Array_getLength -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Array_getLength(Thread* t, + object, + uintptr_t* arguments) { object array = reinterpret_cast(arguments[0]); if (LIKELY(array)) { - unsigned elementSize = classArrayElementSize(t, objectClass(t, array)); + unsigned elementSize = objectClass(t, array)->arrayElementSize(); if (LIKELY(elementSize)) { return fieldAtOffset(array, BytesPerWord); } else { - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_reflect_Array_makeObjectArray -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_reflect_Array_makeObjectArray(Thread* t, + object, + uintptr_t* arguments) { - object elementType = reinterpret_cast(arguments[0]); + GcJclass* elementType + = cast(t, reinterpret_cast(arguments[0])); int length = arguments[1]; - return reinterpret_cast - (makeObjectArray(t, jclassVmClass(t, elementType), length)); + return reinterpret_cast( + makeObjectArray(t, elementType->vmClass(), length)); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Float_floatToRawIntBits -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Float_floatToRawIntBits(Thread*, + object, + uintptr_t* arguments) { return static_cast(*arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Float_intBitsToFloat -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Float_intBitsToFloat(Thread*, object, uintptr_t* arguments) { return static_cast(*arguments); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Double_doubleToRawLongBits -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Double_doubleToRawLongBits(Thread*, + object, + uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); return v; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Double_longBitsToDouble -(Thread*, object, uintptr_t* arguments) + Avian_java_lang_Double_longBitsToDouble(Thread*, + object, + uintptr_t* arguments) { - int64_t v; memcpy(&v, arguments, 8); + int64_t v; + memcpy(&v, arguments, 8); return v; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_String_intern -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_String_intern(Thread* t, object, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); @@ -542,22 +551,22 @@ extern "C" AVIAN_EXPORT int64_t JNICALL Avian_java_lang_System_getVMProperties(Thread* t, object, uintptr_t*) { object array - = makeObjectArray(t, type(t, Machine::StringType), t->m->propertyCount); + = makeObjectArray(t, type(t, GcString::Type), t->m->propertyCount); PROTECT(t, array); for (unsigned i = 0; i < t->m->propertyCount; ++i) { - object s = makeString(t, "%s", t->m->properties[i]); - set(t, array, ArrayBody + (i * BytesPerWord), s); + GcString* s = makeString(t, "%s", t->m->properties[i]); + reinterpret_cast(array)->setBodyElement(t, i, s); } return reinterpret_cast(array); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_System_arraycopy -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_System_arraycopy(Thread* t, object, uintptr_t* arguments) { - arrayCopy(t, reinterpret_cast(arguments[0]), + arrayCopy(t, + reinterpret_cast(arguments[0]), arguments[1], reinterpret_cast(arguments[2]), arguments[3], @@ -565,37 +574,39 @@ Avian_java_lang_System_arraycopy } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_System_identityHashCode -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_System_identityHashCode(Thread* t, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[0]); if (LIKELY(o)) { return objectHash(t, o); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL Avian_java_lang_ClassLoader_getCaller(Thread* t, object, uintptr_t*) { - return reinterpret_cast( - getJClass(t, methodClass(t, getCaller(t, 2)))); + return reinterpret_cast(getJClass(t, getCaller(t, 2)->class_())); } extern "C" AVIAN_EXPORT void JNICALL Avian_java_lang_ClassLoader_load(Thread* t, object, uintptr_t* arguments) { - object name = reinterpret_cast(arguments[0]); + GcString* name = cast(t, reinterpret_cast(arguments[0])); Thread::LibraryLoadStack stack( t, - classLoader(t, jclassVmClass(t, reinterpret_cast(arguments[1])))); + cast(t, reinterpret_cast(arguments[1])) + ->vmClass() + ->loader()); bool mapName = arguments[2]; - unsigned length = stringLength(t, name); + unsigned length = name->length(t); THREAD_RUNTIME_ARRAY(t, char, n, length + 1); stringChars(t, name, RUNTIME_ARRAY_BODY(n)); @@ -603,155 +614,159 @@ extern "C" AVIAN_EXPORT void JNICALL } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Runtime_gc -(Thread* t, object, uintptr_t*) + Avian_java_lang_Runtime_gc(Thread* t, object, uintptr_t*) { collect(t, Heap::MajorCollection); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Runtime_addShutdownHook -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Runtime_addShutdownHook(Thread* t, + object, + uintptr_t* arguments) { object hook = reinterpret_cast(arguments[1]); PROTECT(t, hook); ACQUIRE(t, t->m->shutdownLock); - setRoot(t, Machine::ShutdownHooks, - makePair(t, hook, root(t, Machine::ShutdownHooks))); + GcPair* p = makePair(t, hook, roots(t)->shutdownHooks()); + // sequence point, for gc (don't recombine statements) + roots(t)->setShutdownHooks(t, p); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Throwable_trace -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Throwable_trace(Thread* t, object, uintptr_t* arguments) { return reinterpret_cast(getTrace(t, arguments[0])); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Throwable_resolveTrace -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Throwable_resolveTrace(Thread* t, + object, + uintptr_t* arguments) { object trace = reinterpret_cast(*arguments); PROTECT(t, trace); unsigned length = objectArrayLength(t, trace); - object elementType = type(t, Machine::StackTraceElementType); + GcClass* elementType = type(t, GcStackTraceElement::Type); object array = makeObjectArray(t, elementType, length); PROTECT(t, array); for (unsigned i = 0; i < length; ++i) { - object ste = makeStackTraceElement(t, objectArrayBody(t, trace, i)); - set(t, array, ArrayBody + (i * BytesPerWord), ste); + GcStackTraceElement* ste = makeStackTraceElement( + t, cast(t, objectArrayBody(t, trace, i))); + reinterpret_cast(array)->setBodyElement(t, i, ste); } return reinterpret_cast(array); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_currentThread -(Thread* t, object, uintptr_t*) + Avian_java_lang_Thread_currentThread(Thread* t, object, uintptr_t*) { return reinterpret_cast(t->javaThread); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_doStart -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Thread_doStart(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (startThread(t, reinterpret_cast(*arguments))); + return reinterpret_cast( + startThread(t, cast(t, reinterpret_cast(*arguments)))); } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Thread_interrupt -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Thread_interrupt(Thread* t, object, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); threadInterrupt(t, reinterpret_cast(peer)->javaThread); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_interrupted -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Thread_interrupted(Thread* t, object, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); - return threadIsInterrupted - (t, reinterpret_cast(peer)->javaThread, true); + return threadIsInterrupted( + t, reinterpret_cast(peer)->javaThread, true); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_getStackTrace -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Thread_getStackTrace(Thread* t, + object, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); if (reinterpret_cast(peer) == t) { return reinterpret_cast(makeTrace(t)); } else { - return reinterpret_cast - (t->m->processor->getStackTrace(t, reinterpret_cast(peer))); + return reinterpret_cast( + t->m->processor->getStackTrace(t, reinterpret_cast(peer))); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_activeCount -(Thread* t, object, uintptr_t*) + Avian_java_lang_Thread_activeCount(Thread* t, object, uintptr_t*) { return t->m->liveCount; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Thread_enumerate -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Thread_enumerate(Thread* t, object, uintptr_t* arguments) { - object array = reinterpret_cast(*arguments); + GcArray* array = cast(t, reinterpret_cast(*arguments)); ACQUIRE_RAW(t, t->m->stateLock); - unsigned count = min(t->m->liveCount, objectArrayLength(t, array)); + unsigned count = min(t->m->liveCount, + objectArrayLength(t, reinterpret_cast(array))); unsigned index = 0; local::enumerateThreads(t, t->m->rootThread, array, &index, count); return count; } extern "C" AVIAN_EXPORT void JNICALL -Avian_java_lang_Thread_yield -(Thread* t, object, uintptr_t*) + Avian_java_lang_Thread_yield(Thread* t, object, uintptr_t*) { t->m->system->yield(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Atomic_getOffset -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Atomic_getOffset(Thread* t, object, uintptr_t* arguments) { - return fieldOffset - (t, jfieldVmField(t, reinterpret_cast(arguments[0]))); + return cast(t, reinterpret_cast(arguments[0])) + ->vmField() + ->offset(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_objectFieldOffset -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_objectFieldOffset(Thread* t, + object, + uintptr_t* arguments) { - return fieldOffset - (t, jfieldVmField(t, reinterpret_cast(arguments[1]))); + return cast(t, reinterpret_cast(arguments[1])) + ->vmField() + ->offset(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Atomic_compareAndSwapObject -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Atomic_compareAndSwapObject(Thread* t, + object, + uintptr_t* arguments) { object target = reinterpret_cast(arguments[0]); - int64_t offset; memcpy(&offset, arguments + 1, 8); + int64_t offset; + memcpy(&offset, arguments + 1, 8); uintptr_t expect = arguments[3]; uintptr_t update = arguments[4]; - bool success = atomicCompareAndSwap - (&fieldAtOffset(target, offset), expect, update); + bool success = atomicCompareAndSwap( + &fieldAtOffset(target, offset), expect, update); if (success) { mark(t, target, offset); @@ -761,60 +776,61 @@ Avian_avian_Atomic_compareAndSwapObject } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_isAssignableFrom -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_isAssignableFrom(Thread* t, + object, + uintptr_t* arguments) { - object this_ = reinterpret_cast(arguments[0]); - object that = reinterpret_cast(arguments[1]); + GcClass* this_ = cast(t, reinterpret_cast(arguments[0])); + GcClass* that = cast(t, reinterpret_cast(arguments[1])); if (LIKELY(that)) { return vm::isAssignableFrom(t, this_, that); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_getVMClass -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_getVMClass(Thread* t, object, uintptr_t* arguments) { - return reinterpret_cast - (objectClass(t, reinterpret_cast(arguments[0]))); + return reinterpret_cast( + objectClass(t, reinterpret_cast(arguments[0]))); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_avian_Classes_makeMethod -(Thread* t, object, uintptr_t* arguments) + Avian_avian_Classes_makeMethod(Thread* t, object, uintptr_t* arguments) { - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, reinterpret_cast(arguments[0]))), - arguments[1]); + GcMethod* method = cast( + t, + cast(t, + cast(t, reinterpret_cast(arguments[0])) + ->vmClass() + ->methodTable())->body()[arguments[1]]); PROTECT(t, method); - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/reflect/Method"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/lang/reflect/Method"); PROTECT(t, c); object instance = makeNew(t, c); PROTECT(t, instance); - object constructor = resolveMethod(t, c, "", "(Lavian/VMMethod;)V"); + GcMethod* constructor = resolveMethod(t, c, "", "(Lavian/VMMethod;)V"); t->m->processor->invoke(t, constructor, instance, method); - if (byteArrayBody(t, methodName(t, method), 0) == '<') { - method = instance; + if (method->name()->body()[0] == '<') { + object oldInstance = instance; - c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/reflect/Constructor"); + c = resolveClass( + t, roots(t)->bootLoader(), "java/lang/reflect/Constructor"); object instance = makeNew(t, c); - object constructor = resolveMethod - (t, c, "", "(Ljava/lang/Method;)V"); + GcMethod* constructor + = resolveMethod(t, c, "", "(Ljava/lang/Method;)V"); - t->m->processor->invoke(t, constructor, instance, method); + t->m->processor->invoke(t, constructor, instance, oldInstance); } return reinterpret_cast(instance); diff --git a/src/classpath-openjdk.cpp b/src/classpath-openjdk.cpp index 6e63aa454f..8e7ee8db14 100644 --- a/src/classpath-openjdk.cpp +++ b/src/classpath-openjdk.cpp @@ -15,72 +15,72 @@ #ifdef PLATFORM_WINDOWS -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include -# undef interface +#undef interface -# define CLOSE _close -# define READ _read -# define WRITE _write -# define FSTAT _fstat -# define STAT _stat -# define LSEEK _lseek +#define CLOSE _close +#define READ _read +#define WRITE _write +#define FSTAT _fstat +#define STAT _stat +#define LSEEK _lseek -# define S_ISSOCK(x) false +#define S_ISSOCK(x) false -# ifdef _MSC_VER -# define S_ISREG(x) ((x) | _S_IFREG) -# define S_ISDIR(x) ((x) | _S_IFDIR) -# define S_IRUSR _S_IREAD -# define S_IWUSR _S_IWRITE -# else -# define OPEN _open -# endif +#ifdef _MSC_VER +#define S_ISREG(x) ((x) | _S_IFREG) +#define S_ISDIR(x) ((x) | _S_IFDIR) +#define S_IRUSR _S_IREAD +#define S_IWUSR _S_IWRITE +#else +#define OPEN _open +#endif -# define O_RDONLY _O_RDONLY +#define O_RDONLY _O_RDONLY -# if (defined AVIAN_OPENJDK_SRC) \ - || ((defined __x86_64__) && (defined __MINGW32__)) -# define EXPORT(x) x -# else -# define EXPORT(x) _##x -# endif +#if (defined AVIAN_OPENJDK_SRC) \ + || ((defined __x86_64__) && (defined __MINGW32__)) +#define EXPORT(x) x +#else +#define EXPORT(x) _##x +#endif typedef int socklen_t; -# define RTLD_DEFAULT 0 +#define RTLD_DEFAULT 0 -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# define OPEN open -# define CLOSE close -# define READ read -# define WRITE write -# define STAT stat -# define FSTAT fstat -# define LSEEK lseek +#define OPEN open +#define CLOSE close +#define READ read +#define WRITE write +#define STAT stat +#define FSTAT fstat +#define LSEEK lseek -# define EXPORT(x) x +#define EXPORT(x) x -#endif // not PLATFORM_WINDOWS +#endif // not PLATFORM_WINDOWS #define JVM_EEXIST -100 @@ -89,14 +89,13 @@ using namespace vm; namespace { #ifdef _MSC_VER -inline int -OPEN(string_t path, int mask, int mode) +inline int OPEN(string_t path, int mask, int mode) { - int fd; + int fd; if (_wsopen_s(&fd, path, mask, _SH_DENYNO, mode) == 0) { - return fd; + return fd; } else { - return -1; + return -1; } } #endif @@ -156,130 +155,78 @@ struct JmmInterface { void* reserved1; void* reserved2; - jint - (JNICALL *GetVersion) - (JNIEnv*); + jint(JNICALL* GetVersion)(JNIEnv*); - jint - (JNICALL *GetOptionalSupport) - (JNIEnv*, jmmOptionalSupport*); + jint(JNICALL* GetOptionalSupport)(JNIEnv*, jmmOptionalSupport*); - jobject - (JNICALL *GetInputArguments) - (JNIEnv*); + jobject(JNICALL* GetInputArguments)(JNIEnv*); - jint - (JNICALL *GetThreadInfo) - (JNIEnv*, jlongArray, jint, jobjectArray); + jint(JNICALL* GetThreadInfo)(JNIEnv*, jlongArray, jint, jobjectArray); - jobjectArray - (JNICALL *GetInputArgumentArray) - (JNIEnv*); + jobjectArray(JNICALL* GetInputArgumentArray)(JNIEnv*); - jobjectArray - (JNICALL *GetMemoryPools) - (JNIEnv*, jobject); + jobjectArray(JNICALL* GetMemoryPools)(JNIEnv*, jobject); - jobjectArray - (JNICALL *GetMemoryManagers) - (JNIEnv*, jobject); + jobjectArray(JNICALL* GetMemoryManagers)(JNIEnv*, jobject); - jobject - (JNICALL *GetMemoryPoolUsage) - (JNIEnv*, jobject); + jobject(JNICALL* GetMemoryPoolUsage)(JNIEnv*, jobject); - jobject - (JNICALL *GetPeakMemoryPoolUsage) - (JNIEnv*, jobject); + jobject(JNICALL* GetPeakMemoryPoolUsage)(JNIEnv*, jobject); void* reserved4; - jobject - (JNICALL *GetMemoryUsage) - (JNIEnv*, jboolean); + jobject(JNICALL* GetMemoryUsage)(JNIEnv*, jboolean); - jlong - (JNICALL *GetLongAttribute) - (JNIEnv*, jobject, jmmLongAttribute); + jlong(JNICALL* GetLongAttribute)(JNIEnv*, jobject, jmmLongAttribute); - jboolean (JNICALL *GetBoolAttribute) - (JNIEnv*, jmmBoolAttribute); + jboolean(JNICALL* GetBoolAttribute)(JNIEnv*, jmmBoolAttribute); - jboolean - (JNICALL *SetBoolAttribute) - (JNIEnv*, jmmBoolAttribute, jboolean); + jboolean(JNICALL* SetBoolAttribute)(JNIEnv*, jmmBoolAttribute, jboolean); - jint - (JNICALL *GetLongAttributes) - (JNIEnv*, jobject, jmmLongAttribute*, jint, jlong*); + jint(JNICALL* GetLongAttributes)(JNIEnv*, + jobject, + jmmLongAttribute*, + jint, + jlong*); - jobjectArray - (JNICALL *FindCircularBlockedThreads) - (JNIEnv*); + jobjectArray(JNICALL* FindCircularBlockedThreads)(JNIEnv*); - jlong - (JNICALL *GetThreadCpuTime) - (JNIEnv*, jlong); + jlong(JNICALL* GetThreadCpuTime)(JNIEnv*, jlong); - jobjectArray - (JNICALL *GetVMGlobalNames) - (JNIEnv*); + jobjectArray(JNICALL* GetVMGlobalNames)(JNIEnv*); - jint - (JNICALL *GetVMGlobals) - (JNIEnv*, jobjectArray, jmmVMGlobal*, jint); + jint(JNICALL* GetVMGlobals)(JNIEnv*, jobjectArray, jmmVMGlobal*, jint); - jint - (JNICALL *GetInternalThreadTimes) - (JNIEnv*, jobjectArray, jlongArray); + jint(JNICALL* GetInternalThreadTimes)(JNIEnv*, jobjectArray, jlongArray); - jboolean - (JNICALL *ResetStatistic) - (JNIEnv*, jvalue, jmmStatisticType); + jboolean(JNICALL* ResetStatistic)(JNIEnv*, jvalue, jmmStatisticType); - void - (JNICALL *SetPoolSensor) - (JNIEnv*, jobject, jmmThresholdType, jobject); + void(JNICALL* SetPoolSensor)(JNIEnv*, jobject, jmmThresholdType, jobject); - jlong - (JNICALL *SetPoolThreshold) - (JNIEnv*, jobject, jmmThresholdType, jlong); + jlong(JNICALL* SetPoolThreshold)(JNIEnv*, jobject, jmmThresholdType, jlong); - jobject - (JNICALL *GetPoolCollectionUsage) - (JNIEnv*, jobject); + jobject(JNICALL* GetPoolCollectionUsage)(JNIEnv*, jobject); - jint - (JNICALL *GetGCExtAttributeInfo) - (JNIEnv*, jobject, jmmExtAttributeInfo*, jint); + jint(JNICALL* GetGCExtAttributeInfo)(JNIEnv*, + jobject, + jmmExtAttributeInfo*, + jint); - void - (JNICALL *GetLastGCStat) - (JNIEnv*, jobject, jmmGCStat*); + void(JNICALL* GetLastGCStat)(JNIEnv*, jobject, jmmGCStat*); - jlong - (JNICALL *GetThreadCpuTimeWithKind) - (JNIEnv*, jlong, jboolean); + jlong(JNICALL* GetThreadCpuTimeWithKind)(JNIEnv*, jlong, jboolean); void* reserved5; - jint - (JNICALL *DumpHeap0) - (JNIEnv*, jstring, jboolean); + jint(JNICALL* DumpHeap0)(JNIEnv*, jstring, jboolean); - jobjectArray - (JNICALL *FindDeadlocks) - (JNIEnv*, jboolean); + jobjectArray(JNICALL* FindDeadlocks)(JNIEnv*, jboolean); - void - (JNICALL *SetVMGlobal) - (JNIEnv*, jstring, jvalue ); + void(JNICALL* SetVMGlobal)(JNIEnv*, jstring, jvalue); void* reserved6; - jobjectArray - (JNICALL *DumpThreads) - (JNIEnv*, jlongArray, jboolean, jboolean); + jobjectArray(JNICALL* DumpThreads)(JNIEnv*, jlongArray, jboolean, jboolean); }; const unsigned InterfaceVersion = 4; @@ -290,8 +237,7 @@ const int VirtualFileBase = 1000000000; Machine* globalMachine; -const char* -primitiveName(Thread* t, object c) +const char* primitiveName(Thread* t, GcClass* c) { if (c == primitiveClass(t, 'V')) { return "void"; @@ -316,65 +262,65 @@ primitiveName(Thread* t, object c) } } -object -getClassName(Thread* t, object c) +GcByteArray* getClassName(Thread* t, GcClass* c) { - if (className(t, c) == 0) { - if (classVmFlags(t, c) & PrimitiveFlag) { + if (c->name() == 0) { + if (c->vmFlags() & PrimitiveFlag) { PROTECT(t, c); - - object name = makeByteArray(t, primitiveName(t, c)); - set(t, c, ClassName, name); + GcByteArray* name = makeByteArray(t, primitiveName(t, c)); + + c->setName(t, name); } else { abort(t); } } - return className(t, c); + return c->name(); } -object -makeClassNameString(Thread* t, object name) +GcString* makeClassNameString(Thread* t, GcByteArray* name) { - THREAD_RUNTIME_ARRAY(t, char, s, byteArrayLength(t, name)); - replace('/', '.', RUNTIME_ARRAY_BODY(s), - reinterpret_cast(&byteArrayBody(t, name, 0))); + THREAD_RUNTIME_ARRAY(t, char, s, name->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(s), + reinterpret_cast(name->body().begin())); return makeString(t, "%s", RUNTIME_ARRAY_BODY(s)); } -object -makeJmethod(Thread* t, object vmMethod, int index = -1); +object makeJmethod(Thread* t, GcMethod* vmMethod, int index = -1); -object -makeJconstructor(Thread* t, object vmMethod, int index = -1); +object makeJconstructor(Thread* t, GcMethod* vmMethod, int index = -1); -object -makeJfield(Thread* t, object vmField, int index = -1); +object makeJfield(Thread* t, GcField* vmField, int index = -1); #ifdef AVIAN_OPENJDK_SRC -void -interceptFileOperations(Thread*, bool); +void interceptFileOperations(Thread*, bool); #endif class MyClasspath : public Classpath { public: - MyClasspath(System* s, Allocator* allocator, const char* javaHome, - const char* embedPrefix): - allocator(allocator), ranNetOnLoad(0), ranManagementOnLoad(0) + MyClasspath(System* s, + Allocator* allocator, + const char* javaHome, + const char* embedPrefix) + : allocator(allocator), ranNetOnLoad(0), ranManagementOnLoad(0) { class StringBuilder { public: - StringBuilder(System* s, Allocator* allocator): - s(s), - allocator(allocator), - bufferSize(1024), - buffer(static_cast(allocator->allocate(bufferSize))), - offset(0) - { } + StringBuilder(System* s, Allocator* allocator) + : s(s), + allocator(allocator), + bufferSize(1024), + buffer(static_cast(allocator->allocate(bufferSize))), + offset(0) + { + } - void ensure(unsigned capacity) { + void ensure(unsigned capacity) + { if (capacity > bufferSize) { unsigned size = max(bufferSize * 2, capacity); char* b = static_cast(allocator->allocate(size)); @@ -384,28 +330,30 @@ class MyClasspath : public Classpath { } allocator->free(buffer, bufferSize); - + buffer = b; bufferSize = size; } } - void append(const char* append) { + void append(const char* append) + { unsigned length = strlen(append); ensure(offset + length + 1); - + strncpy(buffer + offset, append, length + 1); - + offset += length; } - void append(char c) { + void append(char c) + { ensure(2); - + buffer[offset] = c; buffer[offset + 1] = 0; - ++ offset; + ++offset; } System* s; @@ -441,18 +389,18 @@ class MyClasspath : public Classpath { unsigned libraryPathOffset = sb.offset; sb.append(javaHome); #ifdef PLATFORM_WINDOWS -# define LIB_DIR "/bin" +#define LIB_DIR "/bin" #elif defined __APPLE__ -# define LIB_DIR "/lib" +#define LIB_DIR "/lib" #elif defined ARCH_x86_64 -# define LIB_DIR "/lib/amd64" +#define LIB_DIR "/lib/amd64" #elif defined ARCH_arm -# define LIB_DIR "/lib/arm" +#define LIB_DIR "/lib/arm" #else - // todo: handle other architectures -# define LIB_DIR "/lib/i386" +// todo: handle other architectures +#define LIB_DIR "/lib/i386" #endif - + #ifdef PLATFORM_WINDOWS sb.append(LIB_DIR); #else @@ -481,184 +429,190 @@ class MyClasspath : public Classpath { this->bufferSize = sb.bufferSize; } - virtual object - makeJclass(Thread* t, object class_) + virtual GcJclass* makeJclass(Thread* t, GcClass* class_) { PROTECT(t, class_); - object name = makeClassNameString(t, getClassName(t, class_)); + GcString* name = makeClassNameString(t, getClassName(t, class_)); PROTECT(t, name); - object c = allocate(t, FixedSizeOfJclass, true); - setObjectClass(t, c, type(t, Machine::JclassType)); - set(t, c, JclassName, name); - set(t, c, JclassVmClass, class_); + GcJclass* c + = reinterpret_cast(allocate(t, GcJclass::FixedSize, true)); + setObjectClass(t, c, type(t, GcJclass::Type)); + c->setName(t, name); + c->setVmClass(t, class_); return c; } - virtual object - makeString(Thread* t, object array, int32_t offset, int32_t length) + virtual GcString* makeString(Thread* t, + object oarray, + int32_t offset, + int32_t length) { - if (objectClass(t, array) == type(t, Machine::ByteArrayType)) { + if (objectClass(t, oarray) == type(t, GcByteArray::Type)) { + GcByteArray* array = cast(t, oarray); PROTECT(t, array); - - object charArray = makeCharArray(t, length); + + GcCharArray* charArray = makeCharArray(t, length); for (int i = 0; i < length; ++i) { - if (byteArrayBody(t, array, offset + i) & 0x80) { - object constructor = resolveMethod - (t, type(t, Machine::StringType), "", - "([BIILjava/lang/String;)V"); + if (array->body()[offset + i] & 0x80) { + GcMethod* constructor = resolveMethod(t, + type(t, GcString::Type), + "", + "([BIILjava/lang/String;)V"); PROTECT(t, constructor); - object utf8 = vm::makeString(t, "UTF8"); + GcString* utf8 = vm::makeString(t, "UTF8"); PROTECT(t, utf8); - object s = makeNew(t, type(t, Machine::StringType)); + object s = makeNew(t, type(t, GcString::Type)); PROTECT(t, s); - t->m->processor->invoke - (t, constructor, s, array, offset, length, utf8); + t->m->processor->invoke( + t, constructor, s, array, offset, length, utf8); - return s; + return cast(t, s); } - charArrayBody(t, charArray, i) = byteArrayBody(t, array, offset + i); + charArray->body()[i] = array->body()[offset + i]; } - array = charArray; + oarray = charArray; } else { - expect(t, objectClass(t, array) == type(t, Machine::CharArrayType)); + expect(t, objectClass(t, oarray) == type(t, GcCharArray::Type)); } - return vm::makeString(t, array, offset, length, 0); + return vm::makeString(t, oarray, offset, length, 0); } - virtual object - makeThread(Thread* t, Thread* parent) + virtual GcThread* makeThread(Thread* t, Thread* parent) { const unsigned MaxPriority = 10; const unsigned NormalPriority = 5; - object group; + GcThreadGroup* group; if (parent) { - group = threadGroup(t, parent->javaThread); + group = parent->javaThread->group(); } else { - group = allocate(t, FixedSizeOfThreadGroup, true); - setObjectClass(t, group, type(t, Machine::ThreadGroupType)); - threadGroupMaxPriority(t, group) = MaxPriority; + group = reinterpret_cast( + allocate(t, GcThreadGroup::FixedSize, true)); + setObjectClass(t, group, type(t, GcThreadGroup::Type)); + group->maxPriority() = MaxPriority; } PROTECT(t, group); - - object thread = allocate(t, FixedSizeOfThread, true); - setObjectClass(t, thread, type(t, Machine::ThreadType)); - threadPriority(t, thread) = NormalPriority; - threadGroup(t, thread) = group; - threadContextClassLoader(t, thread) = root(t, Machine::AppLoader); + + GcThread* thread + = reinterpret_cast(allocate(t, GcThread::FixedSize, true)); + setObjectClass(t, thread, type(t, GcThread::Type)); + thread->priority() = NormalPriority; + + thread->setGroup(t, group); + + thread->setContextClassLoader(t, roots(t)->appLoader()); PROTECT(t, thread); - object blockerLock = makeJobject(t); - set(t, thread, ThreadBlockerLock, blockerLock); + GcJobject* blockerLock = makeJobject(t); + thread->setBlockerLock(t, blockerLock); const unsigned BufferSize = 256; char buffer[BufferSize]; unsigned length = vm::snprintf(buffer, BufferSize, "Thread-%p", thread); - object name = makeCharArray(t, length); + GcCharArray* name = makeCharArray(t, length); for (unsigned i = 0; i < length; ++i) { - charArrayBody(t, name, i) = buffer[i]; + name->body()[i] = buffer[i]; } - set(t, thread, ThreadName, name); + thread->setName(t, name); return thread; } - virtual object - makeJMethod(Thread* t, object vmMethod) + virtual object makeJMethod(Thread* t, GcMethod* vmMethod) { PROTECT(t, vmMethod); - return byteArrayBody(t, methodName(t, vmMethod), 0) == '<' - ? makeJconstructor(t, vmMethod) - : makeJmethod(t, vmMethod); + return vmMethod->name()->body()[0] == '<' ? makeJconstructor(t, vmMethod) + : makeJmethod(t, vmMethod); } - virtual object - getVMMethod(Thread* t, object jmethod) + virtual GcMethod* getVMMethod(Thread* t, object jmethod) { - return objectClass(t, jmethod) == type(t, Machine::JmethodType) - ? arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jmethodClazz(t, jmethod))), - jmethodSlot(t, jmethod)) - : arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jconstructorClazz(t, jmethod))), - jconstructorSlot(t, jmethod)); + return cast( + t, + objectClass(t, jmethod) == type(t, GcJmethod::Type) + ? cast(t, + cast(t, jmethod) + ->clazz() + ->vmClass() + ->methodTable()) + ->body()[cast(t, jmethod)->slot()] + : cast(t, + cast(t, jmethod) + ->clazz() + ->vmClass() + ->methodTable()) + ->body()[cast(t, jmethod)->slot()]); } - virtual object - makeJField(Thread* t, object vmField) + virtual object makeJField(Thread* t, GcField* vmField) { return makeJfield(t, vmField); } - virtual object - getVMField(Thread* t, object jfield) + virtual GcField* getVMField(Thread* t, GcJfield* jfield) { - return arrayBody - (t, classFieldTable - (t, jclassVmClass(t, jfieldClazz(t, jfield))), jfieldSlot(t, jfield)); + return cast( + t, + cast(t, jfield->clazz()->vmClass()->fieldTable()) + ->body()[jfield->slot()]); } - virtual void - clearInterrupted(Thread* t) + virtual void clearInterrupted(Thread* t) { vm::clearInterrupted(t); } - virtual void - runThread(Thread* t) + virtual void runThread(Thread* t) { // force monitor creation so we don't get an OutOfMemory error // later when we try to acquire it: objectMonitor(t, t->javaThread, true); THREAD_RESOURCE0(t, { - vm::acquire(t, t->javaThread); - t->flags &= ~Thread::ActiveFlag; - vm::notifyAll(t, t->javaThread); - vm::release(t, t->javaThread); + vm::acquire(t, t->javaThread); + t->flags &= ~Thread::ActiveFlag; + vm::notifyAll(t, t->javaThread); + vm::release(t, t->javaThread); - object e = t->exception; - PROTECT(t, e); + GcThrowable* e = t->exception; + PROTECT(t, e); - t->exception = 0; + t->exception = 0; - t->m->processor->invoke - (t, root(t, Machine::ThreadTerminated), - threadGroup(t, t->javaThread), t->javaThread); + t->m->processor->invoke(t, + cast(t, roots(t)->threadTerminated()), + t->javaThread->group(), + t->javaThread); - t->exception = e; + t->exception = e; }); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "java/lang/Thread", "run", "()V"); + GcMethod* method = resolveMethod( + t, roots(t)->bootLoader(), "java/lang/Thread", "run", "()V"); t->m->processor->invoke(t, method, t->javaThread); } - virtual void - resolveNative(Thread* t, object method) + virtual void resolveNative(Thread* t, GcMethod* method) { if (strcmp(reinterpret_cast("sun/font/SunFontManager"), - &byteArrayBody(t, className(t, methodClass(t, method)), 0)) == 0 + method->class_()->name()->body().begin()) == 0 and strcmp(reinterpret_cast("initIDs"), - &byteArrayBody(t, methodName(t, method), 0)) == 0 + method->name()->body().begin()) == 0 and strcmp(reinterpret_cast("()V"), - &byteArrayBody(t, methodSpec(t, method), 0)) == 0) - { + method->spec()->body().begin()) == 0) { PROTECT(t, method); expect(t, loadLibrary(t, libraryPath, "fontmanager", true, true)); @@ -667,16 +621,14 @@ class MyClasspath : public Classpath { vm::resolveNative(t, method); } - virtual void - interceptMethods(Thread* t UNUSED) + virtual void interceptMethods(Thread* t UNUSED) { #ifdef AVIAN_OPENJDK_SRC interceptFileOperations(t, false); #endif } - virtual void - preBoot(Thread*) + virtual void preBoot(Thread*) { // ignore } @@ -686,208 +638,226 @@ class MyClasspath : public Classpath { return true; } - virtual void - boot(Thread* t) + virtual void boot(Thread* t) { globalMachine = t->m; - resolveSystemClass(t, root(t, Machine::BootLoader), - className(t, type(t, Machine::ClassLoaderType))); + resolveSystemClass( + t, roots(t)->bootLoader(), type(t, GcClassLoader::Type)->name()); - setRoot(t, Machine::ThreadTerminated, resolveMethod - (t, root(t, Machine::BootLoader), "java/lang/ThreadGroup", - "threadTerminated", "(Ljava/lang/Thread;)V")); + GcMethod* method = resolveMethod(t, + roots(t)->bootLoader(), + "java/lang/ThreadGroup", + "threadTerminated", + "(Ljava/lang/Thread;)V"); + // sequence point, for gc (don't recombine statements) + roots(t)->setThreadTerminated(t, method); #ifdef AVIAN_OPENJDK_SRC interceptFileOperations(t, true); -#else // not AVIAN_OPENJDK_SRC +#else // not AVIAN_OPENJDK_SRC expect(t, loadLibrary(t, libraryPath, "verify", true, true)); expect(t, loadLibrary(t, libraryPath, "java", true, true)); -#endif // not AVIAN_OPENJDK_SRC +#endif // not AVIAN_OPENJDK_SRC - { object assertionLock = resolveField - (t, type(t, Machine::ClassLoaderType), "assertionLock", - "Ljava/lang/Object;"); + { + GcField* assertionLock = resolveField(t, + type(t, GcClassLoader::Type), + "assertionLock", + "Ljava/lang/Object;"); - set(t, root(t, Machine::BootLoader), fieldOffset(t, assertionLock), - root(t, Machine::BootLoader)); + setField(t, + roots(t)->bootLoader(), + assertionLock->offset(), + roots(t)->bootLoader()); } - { object class_ = resolveClass - (t, root(t, Machine::BootLoader), "java/util/Properties", true, - Machine::NoClassDefFoundErrorType); + { + GcClass* class_ = resolveClass(t, + roots(t)->bootLoader(), + "java/util/Properties", + true, + GcNoClassDefFoundError::Type); PROTECT(t, class_); - + object instance = makeNew(t, class_); PROTECT(t, instance); - object constructor = resolveMethod(t, class_, "", "()V"); + GcMethod* constructor = resolveMethod(t, class_, "", "()V"); t->m->processor->invoke(t, constructor, instance); - t->m->processor->invoke - (t, root(t, Machine::BootLoader), "java/lang/System", - "setProperties", "(Ljava/util/Properties;)V", 0, instance); + t->m->processor->invoke(t, + roots(t)->bootLoader(), + "java/lang/System", + "setProperties", + "(Ljava/util/Properties;)V", + 0, + instance); } - { object constructor = resolveMethod - (t, type(t, Machine::ClassLoaderType), "", - "(Ljava/lang/ClassLoader;)V"); + { + GcMethod* constructor = resolveMethod(t, + type(t, GcClassLoader::Type), + "", + "(Ljava/lang/ClassLoader;)V"); PROTECT(t, constructor); - t->m->processor->invoke(t, constructor, root(t, Machine::BootLoader), 0); + t->m->processor->invoke(t, constructor, roots(t)->bootLoader(), 0); - t->m->processor->invoke - (t, constructor, root(t, Machine::AppLoader), - root(t, Machine::BootLoader)); + t->m->processor->invoke( + t, constructor, roots(t)->appLoader(), roots(t)->bootLoader()); } - { object scl = resolveField - (t, type(t, Machine::ClassLoaderType), "scl", - "Ljava/lang/ClassLoader;"); + { + GcField* scl = resolveField( + t, type(t, GcClassLoader::Type), "scl", "Ljava/lang/ClassLoader;"); PROTECT(t, scl); - object sclSet = resolveField - (t, type(t, Machine::ClassLoaderType), "sclSet", "Z"); + GcField* sclSet + = resolveField(t, type(t, GcClassLoader::Type), "sclSet", "Z"); - set(t, classStaticTable(t, type(t, Machine::ClassLoaderType)), - fieldOffset(t, scl), root(t, Machine::AppLoader)); + setField(t, + type(t, GcClassLoader::Type)->staticTable(), + scl->offset(), + roots(t)->appLoader()); - fieldAtOffset(classStaticTable(t, type(t, Machine::ClassLoaderType)), - fieldOffset(t, sclSet)) = true; + fieldAtOffset(type(t, GcClassLoader::Type)->staticTable(), + sclSet->offset()) = true; } - t->m->processor->invoke - (t, root(t, Machine::BootLoader), "java/lang/System", - "initializeSystemClass", "()V", 0); + t->m->processor->invoke(t, + roots(t)->bootLoader(), + "java/lang/System", + "initializeSystemClass", + "()V", + 0); - t->m->processor->invoke - (t, root(t, Machine::BootLoader), "sun/misc/Launcher", - "getLauncher", "()Lsun/misc/Launcher;", 0); + t->m->processor->invoke(t, + roots(t)->bootLoader(), + "sun/misc/Launcher", + "getLauncher", + "()Lsun/misc/Launcher;", + 0); - set(t, t->javaThread, ThreadContextClassLoader, - root(t, Machine::AppLoader)); + t->javaThread->setContextClassLoader(t, roots(t)->appLoader()); } - virtual const char* - bootClasspath() + virtual const char* bootClasspath() { return classpath; } - virtual object - makeDirectByteBuffer(Thread* t, void* p, jlong capacity) + virtual object makeDirectByteBuffer(Thread* t, void* p, jlong capacity) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/nio/DirectByteBuffer"); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/nio/DirectByteBuffer"); PROTECT(t, c); object instance = makeNew(t, c); PROTECT(t, instance); - object constructor = resolveMethod(t, c, "", "(JI)V"); + GcMethod* constructor = resolveMethod(t, c, "", "(JI)V"); - t->m->processor->invoke - (t, constructor, instance, reinterpret_cast(p), - static_cast(capacity)); + t->m->processor->invoke(t, + constructor, + instance, + reinterpret_cast(p), + static_cast(capacity)); return instance; } - virtual void* - getDirectBufferAddress(Thread* t, object b) + virtual void* getDirectBufferAddress(Thread* t, object b) { PROTECT(t, b); - object field = resolveField(t, objectClass(t, b), "address", "J"); + GcField* field = resolveField(t, objectClass(t, b), "address", "J"); - return reinterpret_cast - (fieldAtOffset(b, fieldOffset(t, field))); + return reinterpret_cast(fieldAtOffset(b, field->offset())); } - virtual int64_t - getDirectBufferCapacity(Thread* t, object b) + virtual int64_t getDirectBufferCapacity(Thread* t, object b) { PROTECT(t, b); - object field = resolveField - (t, objectClass(t, b), "capacity", "I"); + GcField* field = resolveField(t, objectClass(t, b), "capacity", "I"); - return fieldAtOffset(b, fieldOffset(t, field)); + return fieldAtOffset(b, field->offset()); } - virtual bool - canTailCall(Thread* t, object, object calleeClassName, - object calleeMethodName, object) + virtual bool canTailCall(Thread* t UNUSED, + GcMethod*, + GcByteArray* calleeClassName, + GcByteArray* calleeMethodName, + GcByteArray*) { // we can't tail call System.loadLibrary or Runtime.loadLibrary // due to their use of System.getCallerClass, which gets confused // if we elide stack frames. - return (strcmp("loadLibrary", reinterpret_cast - (&byteArrayBody(t, calleeMethodName, 0))) - or (strcmp("java/lang/System", reinterpret_cast - (&byteArrayBody(t, calleeClassName, 0))) - and strcmp("java/lang/Runtime", reinterpret_cast - (&byteArrayBody(t, calleeClassName, 0))))) + return (strcmp("loadLibrary", + reinterpret_cast(calleeMethodName->body().begin())) + or (strcmp("java/lang/System", + reinterpret_cast(calleeClassName->body().begin())) + and strcmp("java/lang/Runtime", + reinterpret_cast( + calleeClassName->body().begin())))) - // and we can't tail call Reflection.getCallerClass because the - // number of stack frames will be wrong - - and (strcmp("getCallerClass", reinterpret_cast - (&byteArrayBody(t, calleeMethodName, 0))) - or strcmp("sun/reflect/Reflection", reinterpret_cast - (&byteArrayBody(t, calleeClassName, 0)))); + // and we can't tail call Reflection.getCallerClass because the + // number of stack frames will be wrong + and (strcmp( + "getCallerClass", + reinterpret_cast(calleeMethodName->body().begin())) + or strcmp("sun/reflect/Reflection", + reinterpret_cast( + calleeClassName->body().begin()))); } - virtual object libraryClassLoader(Thread* t, object caller) + virtual GcClassLoader* libraryClassLoader(Thread* t, GcMethod* caller) { #ifdef AVIAN_OPENJDK_SRC - return (methodClass(t, caller) == type(t, Machine::ClassLoaderType) + return (caller->class_() == type(t, Machine::ClassLoaderType) and t->libraryLoadStack) ? t->libraryLoadStack->classLoader #else - return strcmp( - "java/lang/ClassLoader$NativeLibrary", - reinterpret_cast( - &byteArrayBody(t, className(t, methodClass(t, caller)), 0))) - == 0 - ? classLoader( + return strcmp("java/lang/ClassLoader$NativeLibrary", + reinterpret_cast( + caller->class_()->name()->body().begin())) == 0 + ? cast( t, - jclassVmClass(t, - t->m->processor->invoke( - t, - resolveMethod(t, - methodClass(t, caller), - "getFromClass", - "()Ljava/lang/Class;"), - 0))) + cast(t, + t->m->processor->invoke( + t, + resolveMethod(t, + caller->class_(), + "getFromClass", + "()Ljava/lang/Class;"), + 0))->vmClass())->loader() #endif - : classLoader(t, methodClass(t, caller)); + : caller->class_()->loader(); } - virtual void - shutDown(Thread* t) + virtual void shutDown(Thread* t) { - object c = resolveClass - (t, root(t, Machine::BootLoader), "java/lang/Shutdown", false); + GcClass* c + = resolveClass(t, roots(t)->bootLoader(), "java/lang/Shutdown", false); if (c) { - object m = findMethodOrNull(t, c, "shutdown", "()V"); - + GcMethod* m = findMethodOrNull(t, c, "shutdown", "()V"); + if (m) { t->m->processor->invoke(t, m, 0); } } } - virtual void - dispose() - { + virtual void dispose() + { allocator->free(buffer, bufferSize); allocator->free(this, sizeof(*this)); } @@ -926,19 +896,18 @@ struct JVM_ExceptionTableEntryType { struct jvm_version_info { unsigned jvm_version; - unsigned update_version: 8; - unsigned special_update_version: 8; - unsigned reserved1: 16; + unsigned update_version : 8; + unsigned special_update_version : 8; + unsigned reserved1 : 16; unsigned reserved2; - unsigned is_attach_supported: 1; - unsigned is_kernel_jvm: 1; - unsigned: 30; - unsigned: 32; - unsigned: 32; + unsigned is_attach_supported : 1; + unsigned is_kernel_jvm : 1; + unsigned : 30; + unsigned : 32; + unsigned : 32; }; -bool -pathEqual(const char* a, const char* b, unsigned length) +bool pathEqual(const char* a, const char* b, unsigned length) { #ifdef PLATFORM_WINDOWS return strncasecmp(a, b, length) == 0; @@ -949,10 +918,12 @@ pathEqual(const char* a, const char* b, unsigned length) class EmbeddedFile { public: - EmbeddedFile(MyClasspath* cp, const char* path, unsigned pathLength) { + EmbeddedFile(MyClasspath* cp, const char* path, unsigned pathLength) + { if (pathEqual(cp->embedPrefix, path, cp->embedPrefixLength)) { const char* p = path + cp->embedPrefixLength; - while (*p == '/') ++ p; + while (*p == '/') + ++p; this->jar = p; @@ -963,17 +934,19 @@ class EmbeddedFile { return; } - while (*p and *p != '/') ++p; - + while (*p and *p != '/') + ++p; + this->jarLength = p - this->jar; - while (*p == '/') ++p; + while (*p == '/') + ++p; this->path = p; this->pathLength = pathLength - (p - path); } else { this->jar = 0; - this->jarLength =0; + this->jarLength = 0; this->path = 0; this->pathLength = 0; } @@ -987,8 +960,7 @@ class EmbeddedFile { #ifdef AVIAN_OPENJDK_SRC int64_t JNICALL -getFileAttributes -(Thread* t, object method, uintptr_t* arguments) + getFileAttributes(Thread* t, object method, uintptr_t* arguments) { const unsigned Exists = 1; const unsigned Regular = 2; @@ -1018,30 +990,36 @@ getFileAttributes unsigned length; System::FileType type = finder->stat(ef.path, &length, true); switch (type) { - case System::TypeUnknown: return Exists; - case System::TypeDoesNotExist: return 0; - case System::TypeFile: return Exists | Regular; - case System::TypeDirectory: return Exists | Directory; - default: abort(t); + case System::TypeUnknown: + return Exists; + case System::TypeDoesNotExist: + return 0; + case System::TypeFile: + return Exists | Regular; + case System::TypeDirectory: + return Exists | Directory; + default: + abort(t); } } else { return 0; } } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - reinterpret_cast(arguments[0]), file)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + reinterpret_cast(arguments[0]), + file)); } } -int64_t JNICALL -checkFileAccess -(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL checkFileAccess(Thread* t, object method, uintptr_t* arguments) { const unsigned Read = 4; - + MyClasspath* cp = static_cast(t->m->classpath); object file = reinterpret_cast(arguments[1]); @@ -1067,27 +1045,33 @@ checkFileAccess unsigned length; System::FileType type = finder->stat(ef.path, &length, true); switch (type) { - case System::TypeDoesNotExist: return false; + case System::TypeDoesNotExist: + return false; case System::TypeUnknown: case System::TypeFile: - case System::TypeDirectory: return mask == Read; - default: abort(t); + case System::TypeDirectory: + return mask == Read; + default: + abort(t); } } else { return 0; } } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - reinterpret_cast(arguments[0]), file, mask)) != 0; + return intValue(t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, + methodRuntimeDataNative( + t, getMethodRuntimeData(t, method))), + reinterpret_cast(arguments[0]), + file, + mask)) != 0; } } -int64_t JNICALL -getFileLength -(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL getFileLength(Thread* t, object method, uintptr_t* arguments) { MyClasspath* cp = static_cast(t->m->classpath); @@ -1098,7 +1082,7 @@ getFileLength stringChars(t, path, RUNTIME_ARRAY_BODY(p)); replace('\\', '/', RUNTIME_ARRAY_BODY(p)); - EmbeddedFile ef(cp, RUNTIME_ARRAY_BODY(p), stringLength(t, path)); + EmbeddedFile ef(cp, RUNTIME_ARRAY_BODY(p), stringLength(t, path)); if (ef.jar) { if (ef.jarLength == 0) { return 0; @@ -1117,16 +1101,18 @@ getFileLength return 0; } else { - return longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - reinterpret_cast(arguments[0]), file)); + return longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + reinterpret_cast(arguments[0]), + file)); } } -void JNICALL -openFile(Thread* t, object method, uintptr_t* arguments) +void JNICALL openFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); object path = reinterpret_cast(arguments[1]); @@ -1140,17 +1126,17 @@ openFile(Thread* t, object method, uintptr_t* arguments) EmbeddedFile ef(cp, RUNTIME_ARRAY_BODY(p), stringLength(t, path)); if (ef.jar) { if (ef.jarLength == 0 or ef.pathLength == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } Finder* finder = getFinder(t, ef.jar, ef.jarLength); if (finder == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } System::Region* r = finder->find(ef.path); if (r == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } PROTECT(t, this_); @@ -1158,58 +1144,60 @@ openFile(Thread* t, object method, uintptr_t* arguments) ACQUIRE(t, t->m->referenceLock); int index = -1; - unsigned oldLength = root(t, Machine::VirtualFiles) - ? arrayLength(t, root(t, Machine::VirtualFiles)) : 0; + unsigned oldLength = roots(t)->virtualFiles() + ? arrayLength(t, roots(t)->virtualFiles()) + : 0; for (unsigned i = 0; i < oldLength; ++i) { - if (arrayBody(t, root(t, Machine::VirtualFiles), i) == 0) { + if (arrayBody(t, roots(t)->virtualFiles(), i) == 0) { index = i; break; } } if (index == -1) { - object newArray = growArray(t, root(t, Machine::VirtualFiles)); + object newArray = growArray(t, roots(t)->virtualFiles()); setRoot(t, Machine::VirtualFiles, newArray); index = oldLength; } object region = makeRegion(t, r, 0); - set(t, root(t, Machine::VirtualFiles), ArrayBody + (index * BytesPerWord), + set(t, + roots(t)->virtualFiles(), + ArrayBody + (index * BytesPerWord), region); - fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField) - = index + VirtualFileBase; + fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField) = index + VirtualFileBase; } else { - t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_, path); + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_, + path); } } -int64_t JNICALL -readByteFromFile(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL readByteFromFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); MyClasspath* cp = static_cast(t->m->classpath); - int fd = fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField); + int fd = fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField); if (fd >= VirtualFileBase) { ACQUIRE(t, t->m->referenceLock); - - object region = arrayBody - (t, root(t, Machine::VirtualFiles), fd - VirtualFileBase); + + object region + = arrayBody(t, roots(t)->virtualFiles(), fd - VirtualFileBase); if (region) { - System::Region* r = static_cast - (regionRegion(t, region)); + System::Region* r = static_cast(regionRegion(t, region)); if (r->length() > regionPosition(t, region)) { return r->start()[regionPosition(t, region)++]; @@ -1217,19 +1205,21 @@ readByteFromFile(Thread* t, object method, uintptr_t* arguments) return -1; } } else { - throwNew(t, Machine::IoExceptionType); + throwNew(t, GcIoException::Type); } } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_)); } } int64_t JNICALL -readBytesFromFile(Thread* t, object method, uintptr_t* arguments) + readBytesFromFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); object dst = reinterpret_cast(arguments[1]); @@ -1238,21 +1228,20 @@ readBytesFromFile(Thread* t, object method, uintptr_t* arguments) MyClasspath* cp = static_cast(t->m->classpath); - int fd = fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField); + int fd = fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField); if (fd >= VirtualFileBase) { PROTECT(t, dst); ACQUIRE(t, t->m->referenceLock); - - object region = arrayBody - (t, root(t, Machine::VirtualFiles), fd - VirtualFileBase); + + object region + = arrayBody(t, roots(t)->virtualFiles(), fd - VirtualFileBase); if (region) { - System::Region* r = static_cast - (regionRegion(t, region)); + System::Region* r = static_cast(regionRegion(t, region)); int available = r->length() - regionPosition(t, region); if (available == 0) { @@ -1271,38 +1260,42 @@ readBytesFromFile(Thread* t, object method, uintptr_t* arguments) return length; } else { - throwNew(t, Machine::IoExceptionType); + throwNew(t, GcIoException::Type); } } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_, dst, offset, length)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_, + dst, + offset, + length)); } } -int64_t JNICALL -skipBytesInFile(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL skipBytesInFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); - int64_t count; memcpy(&count, arguments + 1, 8); + int64_t count; + memcpy(&count, arguments + 1, 8); MyClasspath* cp = static_cast(t->m->classpath); - int fd = fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField); + int fd = fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField); if (fd >= VirtualFileBase) { ACQUIRE(t, t->m->referenceLock); - - object region = arrayBody - (t, root(t, Machine::VirtualFiles), fd - VirtualFileBase); + + object region + = arrayBody(t, roots(t)->virtualFiles(), fd - VirtualFileBase); if (region) { - System::Region* r = static_cast - (regionRegion(t, region)); + System::Region* r = static_cast(regionRegion(t, region)); int available = r->length() - regionPosition(t, region); if (count > available) { @@ -1313,78 +1306,81 @@ skipBytesInFile(Thread* t, object method, uintptr_t* arguments) return count; } else { - throwNew(t, Machine::IoExceptionType); + throwNew(t, GcIoException::Type); } } else { - return longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_, count)); + return longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_, + count)); } } int64_t JNICALL -availableBytesInFile(Thread* t, object method, uintptr_t* arguments) + availableBytesInFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); MyClasspath* cp = static_cast(t->m->classpath); - int fd = fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField); + int fd = fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField); if (fd >= VirtualFileBase) { ACQUIRE(t, t->m->referenceLock); - - object region = arrayBody - (t, root(t, Machine::VirtualFiles), fd - VirtualFileBase); + + object region + = arrayBody(t, roots(t)->virtualFiles(), fd - VirtualFileBase); if (region) { return static_cast(regionRegion(t, region))->length() - - regionPosition(t, region); + - regionPosition(t, region); } else { - throwNew(t, Machine::IoExceptionType); + throwNew(t, GcIoException::Type); } } else { - object r = t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_); + object r = t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_); return r ? intValue(t, r) : 0; } } -void JNICALL -closeFile(Thread* t, object method, uintptr_t* arguments) +void JNICALL closeFile(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); MyClasspath* cp = static_cast(t->m->classpath); - int fd = fieldAtOffset - (fieldAtOffset - (this_, cp->fileInputStreamFdField), cp->fileDescriptorFdField); + int fd = fieldAtOffset( + fieldAtOffset(this_, cp->fileInputStreamFdField), + cp->fileDescriptorFdField); if (fd >= VirtualFileBase) { ACQUIRE(t, t->m->referenceLock); int index = fd - VirtualFileBase; - object region = arrayBody(t, root(t, Machine::VirtualFiles), index); + object region = arrayBody(t, roots(t)->virtualFiles(), index); if (region) { static_cast(regionRegion(t, region))->dispose(); } - set(t, root(t, Machine::VirtualFiles), ArrayBody + (index * BytesPerWord), - 0); + set(t, roots(t)->virtualFiles(), ArrayBody + (index * BytesPerWord), 0); } else { - t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - this_); + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + this_); } } @@ -1392,17 +1388,18 @@ class ZipFile { public: class Entry { public: - Entry(unsigned hash, const uint8_t* start, Entry* next): - hash(hash), start(start), next(next), entry(0) - { } + Entry(unsigned hash, const uint8_t* start, Entry* next) + : hash(hash), start(start), next(next), entry(0) + { + } - Entry(int64_t entry): - hash(0), start(0), next(0), entry(entry) - { } - - Entry(): - hash(0), start(0), next(0), entry(0) - { } + Entry(int64_t entry) : hash(0), start(0), next(0), entry(entry) + { + } + + Entry() : hash(0), start(0), next(0), entry(0) + { + } unsigned hash; const uint8_t* start; @@ -1410,20 +1407,21 @@ class ZipFile { int64_t entry; }; - ZipFile(Thread* t, System::Region* region, unsigned entryCount): - region(region), - entryCount(entryCount), - indexSize(nextPowerOfTwo(entryCount)), - index(reinterpret_cast - (t->m->heap->allocate(sizeof(ZipFile::Entry*) * indexSize))), - file(0) + ZipFile(Thread* t, System::Region* region, unsigned entryCount) + : region(region), + entryCount(entryCount), + indexSize(nextPowerOfTwo(entryCount)), + index(reinterpret_cast( + t->m->heap->allocate(sizeof(ZipFile::Entry*) * indexSize))), + file(0) { memset(index, 0, sizeof(ZipFile::Entry*) * indexSize); } - ZipFile(int64_t file): - region(0), entryCount(0), indexSize(0), index(0), file(file) - { } + ZipFile(int64_t file) + : region(0), entryCount(0), indexSize(0), index(0), file(file) + { + } System::Region* region; unsigned entryCount; @@ -1433,12 +1431,12 @@ class ZipFile { Entry entries[0]; }; -int64_t JNICALL -openZipFile(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL openZipFile(Thread* t, object method, uintptr_t* arguments) { object path = reinterpret_cast(arguments[0]); int mode = arguments[1]; - int64_t lastModified; memcpy(&lastModified, arguments + 2, 8); + int64_t lastModified; + memcpy(&lastModified, arguments + 2, 8); MyClasspath* cp = static_cast(t->m->classpath); @@ -1449,17 +1447,17 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) EmbeddedFile ef(cp, RUNTIME_ARRAY_BODY(p), stringLength(t, path)); if (ef.jar) { if (ef.jarLength == 0 or ef.pathLength == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } Finder* finder = getFinder(t, ef.jar, ef.jarLength); if (finder == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } System::Region* r = finder->find(ef.path); if (r == 0) { - throwNew(t, Machine::FileNotFoundExceptionType); + throwNew(t, GcFileNotFoundException::Type); } const uint8_t* start = r->start(); @@ -1471,7 +1469,7 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) while (p < end) { if (get4(p) == EntrySignature) { - ++ entryCount; + ++entryCount; p = endOfEntry(p); } else { @@ -1479,17 +1477,17 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) } } } else { - -- p; + --p; } } make: - ZipFile* file = new - (t->m->heap->allocate - (sizeof(ZipFile) + (sizeof(ZipFile::Entry) * entryCount))) - ZipFile(t, r, entryCount); + ZipFile* file = new (t->m->heap->allocate( + sizeof(ZipFile) + (sizeof(ZipFile::Entry) * entryCount))) + ZipFile(t, r, entryCount); - { unsigned position = 0; + { + unsigned position = 0; for (const uint8_t* p = end - CentralDirectorySearchStart; p > start;) { if (get4(p) == CentralDirectorySignature) { p = start + centralDirectoryOffset(p); @@ -1500,7 +1498,7 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) unsigned i = h & (file->indexSize - 1); file->index[i] = new (file->entries + (position++)) - ZipFile::Entry(h, p, file->index[i]); + ZipFile::Entry(h, p, file->index[i]); p = endOfEntry(p); } else { @@ -1508,7 +1506,7 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) } } } else { - -- p; + --p; } } } @@ -1516,35 +1514,44 @@ openZipFile(Thread* t, object method, uintptr_t* arguments) exit: return reinterpret_cast(file); } else { - return reinterpret_cast - (new (t->m->heap->allocate(sizeof(ZipFile))) ZipFile - (longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, path, mode, lastModified)))); + return reinterpret_cast( + new (t->m->heap->allocate(sizeof(ZipFile))) + ZipFile(longValue(t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, + methodRuntimeDataNative( + t, getMethodRuntimeData(t, method))), + 0, + path, + mode, + lastModified)))); } } int64_t JNICALL -getZipFileEntryCount(Thread* t, object method, uintptr_t* arguments) + getZipFileEntryCount(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile* file = reinterpret_cast(peer); if (file->region) { return file->entryCount; } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file)); } } -ZipFile::Entry* -find(ZipFile* file, const char* path, unsigned pathLength) +ZipFile::Entry* find(ZipFile* file, const char* path, unsigned pathLength) { unsigned i = hash(path) & (file->indexSize - 1); for (ZipFile::Entry* e = file->index[i]; e; e = e->next) { @@ -1556,17 +1563,18 @@ find(ZipFile* file, const char* path, unsigned pathLength) return 0; } -int64_t JNICALL -getZipFileEntry(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL getZipFileEntry(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); object path = reinterpret_cast(arguments[2]); bool addSlash = arguments[3]; ZipFile* file = reinterpret_cast(peer); if (file->region) { THREAD_RUNTIME_ARRAY(t, char, p, byteArrayLength(t, path) + 2); - memcpy(RUNTIME_ARRAY_BODY(p), &byteArrayBody(t, path, 0), + memcpy(RUNTIME_ARRAY_BODY(p), + &byteArrayBody(t, path, 0), byteArrayLength(t, path)); RUNTIME_ARRAY_BODY(p)[byteArrayLength(t, path)] = 0; replace('\\', '/', RUNTIME_ARRAY_BODY(p)); @@ -1575,31 +1583,37 @@ getZipFileEntry(Thread* t, object method, uintptr_t* arguments) RUNTIME_ARRAY_BODY(p)[byteArrayLength(t, path) + 1] = 0; } - return reinterpret_cast - (find(file, RUNTIME_ARRAY_BODY(p), byteArrayLength(t, path))); + return reinterpret_cast( + find(file, RUNTIME_ARRAY_BODY(p), byteArrayLength(t, path))); } else { - int64_t entry = longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file, path, addSlash)); + int64_t entry = longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file, + path, + addSlash)); - return entry ? reinterpret_cast - (new (t->m->heap->allocate(sizeof(ZipFile::Entry))) - ZipFile::Entry(entry)) : 0; + return entry ? reinterpret_cast(new (t->m->heap->allocate( + sizeof(ZipFile::Entry))) ZipFile::Entry(entry)) + : 0; } } int64_t JNICALL -getZipFileEntryBytes(Thread* t, object method, uintptr_t* arguments) + getZipFileEntryBytes(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); int type = arguments[2]; ZipFile::Entry* entry = reinterpret_cast(peer); if (entry->start) { switch (type) { - case 0: { // name + case 0: { // name unsigned nameLength = fileNameLength(entry->start); object array = makeByteArray(t, nameLength + 1); memcpy(&byteArrayBody(t, array, 0), fileName(entry->start), nameLength); @@ -1607,123 +1621,151 @@ getZipFileEntryBytes(Thread* t, object method, uintptr_t* arguments) return reinterpret_cast(array); } break; - case 1: { // extra + case 1: { // extra return 0; } break; - case 2: { // comment + case 2: { // comment return 0; } break; - default: abort(t); + default: + abort(t); } return compressedSize(entry->start); } else { - return reinterpret_cast - (t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, entry->entry, type)); + return reinterpret_cast(t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + entry->entry, + type)); } } int64_t JNICALL -getNextZipFileEntry(Thread* t, object method, uintptr_t* arguments) + getNextZipFileEntry(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); int index = arguments[2]; ZipFile* file = reinterpret_cast(peer); if (file->region) { return reinterpret_cast(file->entries + index); } else { - int64_t entry = longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file, index)); + int64_t entry = longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file, + index)); - return entry ? reinterpret_cast - (new (t->m->heap->allocate(sizeof(ZipFile::Entry))) - ZipFile::Entry(entry)) : 0; + return entry ? reinterpret_cast(new (t->m->heap->allocate( + sizeof(ZipFile::Entry))) ZipFile::Entry(entry)) + : 0; } } int64_t JNICALL -getZipFileEntryMethod(Thread* t, object method, uintptr_t* arguments) + getZipFileEntryMethod(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile::Entry* entry = reinterpret_cast(peer); if (entry->start) { return compressionMethod(entry->start); } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, entry->entry)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + entry->entry)); } } -int64_t JNICALL -getZipFileEntryCompressedSize(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL getZipFileEntryCompressedSize(Thread* t, + object method, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile::Entry* entry = reinterpret_cast(peer); if (entry->start) { return compressedSize(entry->start); } else { - return longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, entry->entry)); + return longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + entry->entry)); } } -int64_t JNICALL -getZipFileEntryUncompressedSize(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL getZipFileEntryUncompressedSize(Thread* t, + object method, + uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile::Entry* entry = reinterpret_cast(peer); if (entry->start) { return uncompressedSize(entry->start); } else { - return longValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, entry->entry)); + return longValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + entry->entry)); } } -void JNICALL -freeZipFileEntry(Thread* t, object method, uintptr_t* arguments) +void JNICALL freeZipFileEntry(Thread* t, object method, uintptr_t* arguments) { - int64_t filePeer; memcpy(&filePeer, arguments, 8); - int64_t entryPeer; memcpy(&entryPeer, arguments + 2, 8); + int64_t filePeer; + memcpy(&filePeer, arguments, 8); + int64_t entryPeer; + memcpy(&entryPeer, arguments + 2, 8); ZipFile* file = reinterpret_cast(filePeer); ZipFile::Entry* entry = reinterpret_cast(entryPeer); if (file->region == 0) { - t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file, entry->entry); + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file, + entry->entry); } t->m->heap->free(entry, sizeof(ZipFile::Entry)); } -int64_t JNICALL -readZipFileEntry(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL readZipFileEntry(Thread* t, object method, uintptr_t* arguments) { - int64_t filePeer; memcpy(&filePeer, arguments, 8); - int64_t entryPeer; memcpy(&entryPeer, arguments + 2, 8); - int64_t position; memcpy(&position, arguments + 4, 8); + int64_t filePeer; + memcpy(&filePeer, arguments, 8); + int64_t entryPeer; + memcpy(&entryPeer, arguments + 2, 8); + int64_t position; + memcpy(&position, arguments + 4, 8); object buffer = reinterpret_cast(arguments[6]); int offset = arguments[7]; int length = arguments[8]; @@ -1747,33 +1789,42 @@ readZipFileEntry(Thread* t, object method, uintptr_t* arguments) return length; } else { - return intValue - (t, t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file, entry->entry, position, buffer, offset, length)); + return intValue( + t, + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file, + entry->entry, + position, + buffer, + offset, + length)); } } -int64_t JNICALL -getZipMessage(Thread* t, object method, uintptr_t* arguments) +int64_t JNICALL getZipMessage(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile* file = reinterpret_cast(peer); if (file->region) { return 0; } else { - return reinterpret_cast - (t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file)); + return reinterpret_cast(t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file)); } } int64_t JNICALL -getJarFileMetaInfEntryNames(Thread* t, object method, uintptr_t* arguments) + getJarFileMetaInfEntryNames(Thread* t, object method, uintptr_t* arguments) { object this_ = reinterpret_cast(arguments[0]); @@ -1798,78 +1849,77 @@ getJarFileMetaInfEntryNames(Thread* t, object method, uintptr_t* arguments) // for any other fields in the object. object pseudoThis = makeLong(t, file->file); - return reinterpret_cast - (t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + return reinterpret_cast(t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), pseudoThis)); } } -void JNICALL -closeZipFile(Thread* t, object method, uintptr_t* arguments) +void JNICALL closeZipFile(Thread* t, object method, uintptr_t* arguments) { - int64_t peer; memcpy(&peer, arguments, 8); + int64_t peer; + memcpy(&peer, arguments, 8); ZipFile* file = reinterpret_cast(peer); if (file->region) { file->region->dispose(); - t->m->heap->free(file, sizeof(ZipFile) - + (sizeof(ZipFile::Entry) * file->entryCount)); + t->m->heap->free( + file, sizeof(ZipFile) + (sizeof(ZipFile::Entry) * file->entryCount)); } else { - t->m->processor->invoke - (t, nativeInterceptOriginal - (t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), - 0, file->file); + t->m->processor->invoke( + t, + nativeInterceptOriginal( + t, methodRuntimeDataNative(t, getMethodRuntimeData(t, method))), + 0, + file->file); t->m->heap->free(file, sizeof(ZipFile)); } } -int64_t JNICALL -getBootstrapResource(Thread* t, object, uintptr_t* arguments) +int64_t JNICALL getBootstrapResource(Thread* t, object, uintptr_t* arguments) { object name = reinterpret_cast(arguments[0]); PROTECT(t, name); - object m = findMethodOrNull - (t, type(t, Machine::SystemClassLoaderType), - "findResource", "(Ljava/lang/String;)Ljava/net/URL;"); - + GcMethod* m = findMethodOrNull(t, + type(t, GcSystemClassLoader::Type), + "findResource", + "(Ljava/lang/String;)Ljava/net/URL;"); + if (m) { - return reinterpret_cast - (t->m->processor->invoke(t, m, root(t, Machine::BootLoader), name)); + return reinterpret_cast( + t->m->processor->invoke(t, m, roots(t)->bootLoader(), name)); } else { return 0; } } -int64_t JNICALL -getBootstrapResources(Thread* t, object, uintptr_t* arguments) +int64_t JNICALL getBootstrapResources(Thread* t, object, uintptr_t* arguments) { object name = reinterpret_cast(arguments[0]); PROTECT(t, name); - object m = findMethodOrNull - (t, type(t, Machine::SystemClassLoaderType), - "findResources", "(Ljava/lang/String;)Ljava/util/Enumeration;"); - + GcMethod* m = findMethodOrNull(t, + type(t, GcSystemClassLoader::Type), + "findResources", + "(Ljava/lang/String;)Ljava/util/Enumeration;"); + if (m) { - return reinterpret_cast - (t->m->processor->invoke(t, m, root(t, Machine::BootLoader), name)); + return reinterpret_cast( + t->m->processor->invoke(t, m, roots(t)->bootLoader(), name)); } else { return 0; } } -extern "C" AVIAN_EXPORT jint JNICALL -net_JNI_OnLoad(JavaVM*, void*); +extern "C" AVIAN_EXPORT jint JNICALL net_JNI_OnLoad(JavaVM*, void*); -extern "C" AVIAN_EXPORT jint JNICALL -management_JNI_OnLoad(JavaVM*, void*); +extern "C" AVIAN_EXPORT jint JNICALL management_JNI_OnLoad(JavaVM*, void*); -void JNICALL -loadLibrary(Thread* t, object, uintptr_t* arguments) +void JNICALL loadLibrary(Thread* t, object, uintptr_t* arguments) { Thread::LibraryLoadStack stack( t, @@ -1885,10 +1935,11 @@ loadLibrary(Thread* t, object, uintptr_t* arguments) if (strcmp(RUNTIME_ARRAY_BODY(n), "net") == 0) { bool ran; - { ACQUIRE(t, t->m->classLock); + { + ACQUIRE(t, t->m->classLock); - local::MyClasspath* c = static_cast - (t->m->classpath); + local::MyClasspath* c + = static_cast(t->m->classpath); ran = c->ranNetOnLoad; c->ranNetOnLoad = true; @@ -1899,13 +1950,14 @@ loadLibrary(Thread* t, object, uintptr_t* arguments) } return; - } else if (strcmp(RUNTIME_ARRAY_BODY(n), "management") == 0) { + } else if (strcmp(RUNTIME_ARRAY_BODY(n), "management") == 0) { bool ran; - { ACQUIRE(t, t->m->classLock); + { + ACQUIRE(t, t->m->classLock); - local::MyClasspath* c = static_cast - (t->m->classpath); + local::MyClasspath* c + = static_cast(t->m->classpath); ran = c->ranManagementOnLoad; c->ranManagementOnLoad = true; @@ -1915,43 +1967,45 @@ loadLibrary(Thread* t, object, uintptr_t* arguments) management_JNI_OnLoad(t->m, 0); } - return; + return; } else if (strcmp(RUNTIME_ARRAY_BODY(n), "zip") == 0 - or strcmp(RUNTIME_ARRAY_BODY(n), "nio") == 0) - { + or strcmp(RUNTIME_ARRAY_BODY(n), "nio") == 0) { return; } } - - loadLibrary - (t, static_cast(t->m->classpath)->libraryPath, - RUNTIME_ARRAY_BODY(n), not absolute, true); + + loadLibrary(t, + static_cast(t->m->classpath)->libraryPath, + RUNTIME_ARRAY_BODY(n), + not absolute, + true); } -void -interceptFileOperations(Thread* t, bool updateRuntimeData) +void interceptFileOperations(Thread* t, bool updateRuntimeData) { MyClasspath* cp = static_cast(t->m->classpath); - { object fileClass = resolveClass - (t, root(t, Machine::BootLoader), "java/io/File", false); + { + object fileClass + = resolveClass(t, roots(t)->bootLoader(), "java/io/File", false); if (fileClass) { - object filePathField = findFieldInClass2 - (t, fileClass, "path", "Ljava/lang/String;"); - + object filePathField + = findFieldInClass2(t, fileClass, "path", "Ljava/lang/String;"); + if (filePathField) { cp->filePathField = fieldOffset(t, filePathField); } } } - { object fileDescriptorClass = resolveClass - (t, root(t, Machine::BootLoader), "java/io/FileDescriptor", false); + { + object fileDescriptorClass = resolveClass( + t, roots(t)->bootLoader(), "java/io/FileDescriptor", false); if (fileDescriptorClass) { - object fileDescriptorFdField = findFieldInClass2 - (t, fileDescriptorClass, "fd", "I"); + object fileDescriptorFdField + = findFieldInClass2(t, fileDescriptorClass, "fd", "I"); if (fileDescriptorFdField) { cp->fileDescriptorFdField = fieldOffset(t, fileDescriptorFdField); @@ -1959,104 +2013,184 @@ interceptFileOperations(Thread* t, bool updateRuntimeData) } } - { object fileInputStreamClass = resolveClass - (t, root(t, Machine::BootLoader), "java/io/FileInputStream", false); + { + object fileInputStreamClass = resolveClass( + t, roots(t)->bootLoader(), "java/io/FileInputStream", false); if (fileInputStreamClass) { PROTECT(t, fileInputStreamClass); - object fileInputStreamFdField = findFieldInClass2 - (t, fileInputStreamClass, "fd", "Ljava/io/FileDescriptor;"); + object fileInputStreamFdField = findFieldInClass2( + t, fileInputStreamClass, "fd", "Ljava/io/FileDescriptor;"); if (fileInputStreamFdField) { cp->fileInputStreamFdField = fieldOffset(t, fileInputStreamFdField); - intercept(t, fileInputStreamClass, "open", "(Ljava/lang/String;)V", - voidPointer(openFile), updateRuntimeData); - - if(findMethodOrNull(t, fileInputStreamClass, "read0", "()I") != 0) { - intercept(t, fileInputStreamClass, "read0", "()I", - voidPointer(readByteFromFile), updateRuntimeData); + intercept(t, + fileInputStreamClass, + "open", + "(Ljava/lang/String;)V", + voidPointer(openFile), + updateRuntimeData); + + if (findMethodOrNull(t, fileInputStreamClass, "read0", "()I") != 0) { + intercept(t, + fileInputStreamClass, + "read0", + "()I", + voidPointer(readByteFromFile), + updateRuntimeData); } else { - intercept(t, fileInputStreamClass, "read", "()I", - voidPointer(readByteFromFile), updateRuntimeData); + intercept(t, + fileInputStreamClass, + "read", + "()I", + voidPointer(readByteFromFile), + updateRuntimeData); } - - intercept(t, fileInputStreamClass, "readBytes", "([BII)I", - voidPointer(readBytesFromFile), updateRuntimeData); - - intercept(t, fileInputStreamClass, "skip", "(J)J", - voidPointer(skipBytesInFile), updateRuntimeData); - - intercept(t, fileInputStreamClass, "available", "()I", - voidPointer(availableBytesInFile), updateRuntimeData); - - intercept(t, fileInputStreamClass, "close0", "()V", - voidPointer(closeFile), updateRuntimeData); + + intercept(t, + fileInputStreamClass, + "readBytes", + "([BII)I", + voidPointer(readBytesFromFile), + updateRuntimeData); + + intercept(t, + fileInputStreamClass, + "skip", + "(J)J", + voidPointer(skipBytesInFile), + updateRuntimeData); + + intercept(t, + fileInputStreamClass, + "available", + "()I", + voidPointer(availableBytesInFile), + updateRuntimeData); + + intercept(t, + fileInputStreamClass, + "close0", + "()V", + voidPointer(closeFile), + updateRuntimeData); } } } - { object zipFileClass = resolveClass - (t, root(t, Machine::BootLoader), "java/util/zip/ZipFile", false); + { + object zipFileClass = resolveClass( + t, roots(t)->bootLoader(), "java/util/zip/ZipFile", false); if (zipFileClass) { PROTECT(t, zipFileClass); - object zipFileJzfileField = findFieldInClass2 - (t, zipFileClass, "jzfile", "J"); + object zipFileJzfileField + = findFieldInClass2(t, zipFileClass, "jzfile", "J"); if (zipFileJzfileField) { cp->zipFileJzfileField = fieldOffset(t, zipFileJzfileField); - intercept(t, zipFileClass, "open", "(Ljava/lang/String;IJZ)J", - voidPointer(openZipFile), updateRuntimeData); + intercept(t, + zipFileClass, + "open", + "(Ljava/lang/String;IJZ)J", + voidPointer(openZipFile), + updateRuntimeData); - intercept(t, zipFileClass, "getTotal", "(J)I", - voidPointer(getZipFileEntryCount), updateRuntimeData); + intercept(t, + zipFileClass, + "getTotal", + "(J)I", + voidPointer(getZipFileEntryCount), + updateRuntimeData); - intercept(t, zipFileClass, "getEntry", "(J[BZ)J", - voidPointer(getZipFileEntry), updateRuntimeData); + intercept(t, + zipFileClass, + "getEntry", + "(J[BZ)J", + voidPointer(getZipFileEntry), + updateRuntimeData); - intercept(t, zipFileClass, "getEntryBytes", "(JI)[B", - voidPointer(getZipFileEntryBytes), updateRuntimeData); + intercept(t, + zipFileClass, + "getEntryBytes", + "(JI)[B", + voidPointer(getZipFileEntryBytes), + updateRuntimeData); - intercept(t, zipFileClass, "getNextEntry", "(JI)J", - voidPointer(getNextZipFileEntry), updateRuntimeData); + intercept(t, + zipFileClass, + "getNextEntry", + "(JI)J", + voidPointer(getNextZipFileEntry), + updateRuntimeData); - intercept(t, zipFileClass, "getEntryMethod", "(J)I", - voidPointer(getZipFileEntryMethod), updateRuntimeData); + intercept(t, + zipFileClass, + "getEntryMethod", + "(J)I", + voidPointer(getZipFileEntryMethod), + updateRuntimeData); - intercept(t, zipFileClass, "freeEntry", "(JJ)V", - voidPointer(freeZipFileEntry), updateRuntimeData); + intercept(t, + zipFileClass, + "freeEntry", + "(JJ)V", + voidPointer(freeZipFileEntry), + updateRuntimeData); - intercept(t, zipFileClass, "read", "(JJJ[BII)I", - voidPointer(readZipFileEntry), updateRuntimeData); + intercept(t, + zipFileClass, + "read", + "(JJJ[BII)I", + voidPointer(readZipFileEntry), + updateRuntimeData); - intercept(t, zipFileClass, "getEntryCSize", "(J)J", + intercept(t, + zipFileClass, + "getEntryCSize", + "(J)J", voidPointer(getZipFileEntryCompressedSize), updateRuntimeData); - intercept(t, zipFileClass, "getEntrySize", "(J)J", + intercept(t, + zipFileClass, + "getEntrySize", + "(J)J", voidPointer(getZipFileEntryUncompressedSize), updateRuntimeData); - intercept(t, zipFileClass, "getZipMessage", "(J)Ljava/lang/String;", - voidPointer(getZipMessage), updateRuntimeData); + intercept(t, + zipFileClass, + "getZipMessage", + "(J)Ljava/lang/String;", + voidPointer(getZipMessage), + updateRuntimeData); - intercept(t, zipFileClass, "close", "(J)V", - voidPointer(closeZipFile), updateRuntimeData); + intercept(t, + zipFileClass, + "close", + "(J)V", + voidPointer(closeZipFile), + updateRuntimeData); } } } - { object jarFileClass = resolveClass - (t, root(t, Machine::BootLoader), "java/util/jar/JarFile", false); + { + object jarFileClass = resolveClass( + t, roots(t)->bootLoader(), "java/util/jar/JarFile", false); if (jarFileClass) { - intercept(t, jarFileClass, "getMetaInfEntryNames", + intercept(t, + jarFileClass, + "getMetaInfEntryNames", "()[Ljava/lang/String;", - voidPointer(getJarFileMetaInfEntryNames), updateRuntimeData); + voidPointer(getJarFileMetaInfEntryNames), + updateRuntimeData); } } @@ -2069,77 +2203,94 @@ interceptFileOperations(Thread* t, bool updateRuntimeData) const char* const gbaMethodName = "getBooleanAttributes0"; #endif - object fsClass = resolveClass - (t, root(t, Machine::BootLoader), fsClassName, false); + object fsClass + = resolveClass(t, roots(t)->bootLoader(), fsClassName, false); if (fsClass) { PROTECT(t, fsClass); - intercept(t, fsClass, gbaMethodName, "(Ljava/io/File;)I", - voidPointer(getFileAttributes), updateRuntimeData); + intercept(t, + fsClass, + gbaMethodName, + "(Ljava/io/File;)I", + voidPointer(getFileAttributes), + updateRuntimeData); - intercept(t, fsClass, "checkAccess", "(Ljava/io/File;I)Z", - voidPointer(checkFileAccess), updateRuntimeData); - - intercept(t, fsClass, "getLength", "(Ljava/io/File;)J", - voidPointer(getFileLength), updateRuntimeData); + intercept(t, + fsClass, + "checkAccess", + "(Ljava/io/File;I)Z", + voidPointer(checkFileAccess), + updateRuntimeData); + + intercept(t, + fsClass, + "getLength", + "(Ljava/io/File;)J", + voidPointer(getFileLength), + updateRuntimeData); } } - intercept(t, type(t, Machine::ClassLoaderType), "loadLibrary", + intercept(t, + type(t, GcClassLoader::Type), + "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V", - voidPointer(loadLibrary), updateRuntimeData); + voidPointer(loadLibrary), + updateRuntimeData); - intercept(t, type(t, Machine::ClassLoaderType), "getBootstrapResource", + intercept(t, + type(t, GcClassLoader::Type), + "getBootstrapResource", "(Ljava/lang/String;)Ljava/net/URL;", - voidPointer(getBootstrapResource), updateRuntimeData); + voidPointer(getBootstrapResource), + updateRuntimeData); - intercept(t, type(t, Machine::ClassLoaderType), "getBootstrapResources", + intercept(t, + type(t, GcClassLoader::Type), + "getBootstrapResources", "(Ljava/lang/String;)Ljava/util/Enumeration;", - voidPointer(getBootstrapResources), updateRuntimeData); + voidPointer(getBootstrapResources), + updateRuntimeData); } -#endif // AVIAN_OPENJDK_SRC +#endif // AVIAN_OPENJDK_SRC -unsigned -classDeclaredMethodCount(Thread* t, object c) +unsigned classDeclaredMethodCount(Thread* t, GcClass* c) { - object addendum = classAddendum(t, c); + GcClassAddendum* addendum = c->addendum(); if (addendum) { - int count = classAddendumDeclaredMethodCount(t, addendum); + int count = addendum->declaredMethodCount(); if (count >= 0) { return count; } } - object table = classMethodTable(t, c); - return table == 0 ? 0 : arrayLength(t, table); + GcArray* table = cast(t, c->methodTable()); + return table == 0 ? 0 : table->length(); } -unsigned -countMethods(Thread* t, object c, bool publicOnly) +unsigned countMethods(Thread* t, GcClass* c, bool publicOnly) { - object table = classMethodTable(t, c); + GcArray* table = cast(t, c->methodTable()); unsigned count = 0; for (unsigned i = 0, j = classDeclaredMethodCount(t, c); i < j; ++i) { - object vmMethod = arrayBody(t, table, i); - if (((not publicOnly) or (methodFlags(t, vmMethod) & ACC_PUBLIC)) - and byteArrayBody(t, methodName(t, vmMethod), 0) != '<') - { - ++ count; + GcMethod* vmMethod = cast(t, table->body()[i]); + if (((not publicOnly) or (vmMethod->flags() & ACC_PUBLIC)) + and vmMethod->name()->body()[0] != '<') { + ++count; } } return count; } -unsigned -countFields(Thread* t, object c, bool publicOnly) +unsigned countFields(Thread* t, GcClass* c, bool publicOnly) { - object table = classFieldTable(t, c); + GcArray* table = cast(t, c->fieldTable()); if (publicOnly) { unsigned count = 0; - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object vmField = arrayBody(t, table, i); - if (fieldFlags(t, vmField) & ACC_PUBLIC) { - ++ count; + for (unsigned i = 0; i < table->length(); ++i) { + GcField* vmField = cast(t, table->body()[i]); + if (vmField->flags() & ACC_PUBLIC) { + ++count; } } return count; @@ -2148,125 +2299,148 @@ countFields(Thread* t, object c, bool publicOnly) } } -unsigned -countConstructors(Thread* t, object c, bool publicOnly) +unsigned countConstructors(Thread* t, GcClass* c, bool publicOnly) { - object table = classMethodTable(t, c); + GcArray* table = cast(t, c->methodTable()); unsigned count = 0; for (unsigned i = 0, j = classDeclaredMethodCount(t, c); i < j; ++i) { - object vmMethod = arrayBody(t, table, i); - if (((not publicOnly) or (methodFlags(t, vmMethod) & ACC_PUBLIC)) - and strcmp(reinterpret_cast - (&byteArrayBody(t, methodName(t, vmMethod), 0)), - "") == 0) - { - ++ count; + GcMethod* vmMethod = cast(t, table->body()[i]); + if (((not publicOnly) or (vmMethod->flags() & ACC_PUBLIC)) + and strcmp(reinterpret_cast(vmMethod->name()->body().begin()), + "") == 0) { + ++count; } } return count; } #ifdef HAVE_JexecutableHasRealParameterData -object -makeJmethod(Thread* t, - uint8_t override, - object securityCheckCache, - object clazz, - uint32_t slot, - object name, - object returnType, - object parameterTypes, - object exceptionTypes, - uint32_t modifiers, - object signature, - object genericInfo, - object annotations, - object parameterAnnotations, - object annotationDefault, - object methodAccessor, - object root, - object declaredAnnotations) +object makeJmethod(Thread* t, + uint8_t override, + object securityCheckCache, + object clazz, + uint32_t slot, + object name, + object returnType, + object parameterTypes, + object exceptionTypes, + uint32_t modifiers, + object signature, + object genericInfo, + object annotations, + object parameterAnnotations, + object annotationDefault, + object methodAccessor, + object root, + object declaredAnnotations) { - return makeJmethod - (t, override, securityCheckCache, 0, 0, declaredAnnotations, clazz, slot, - name, returnType, parameterTypes, exceptionTypes, modifiers, signature, - genericInfo, annotations, parameterAnnotations, annotationDefault, - methodAccessor, root); + return makeJmethod(t, + override, + securityCheckCache, + 0, + 0, + declaredAnnotations, + clazz, + slot, + name, + returnType, + parameterTypes, + exceptionTypes, + modifiers, + signature, + genericInfo, + annotations, + parameterAnnotations, + annotationDefault, + methodAccessor, + root); } -object -makeJconstructor(Thread* t, - uint8_t override, - object securityCheckCache, - object clazz, - uint32_t slot, - object parameterTypes, - object exceptionTypes, - uint32_t modifiers, - object signature, - object genericInfo, - object annotations, - object parameterAnnotations, - object constructorAccessor, - object root, - object declaredAnnotations) +object makeJconstructor(Thread* t, + uint8_t override, + object securityCheckCache, + object clazz, + uint32_t slot, + object parameterTypes, + object exceptionTypes, + uint32_t modifiers, + object signature, + object genericInfo, + object annotations, + object parameterAnnotations, + object constructorAccessor, + object root, + object declaredAnnotations) { - return makeJconstructor - (t, override, securityCheckCache, 0, 0, declaredAnnotations, clazz, slot, - parameterTypes, exceptionTypes, modifiers, signature, genericInfo, - annotations, parameterAnnotations, constructorAccessor, root); + return makeJconstructor(t, + override, + securityCheckCache, + 0, + 0, + declaredAnnotations, + clazz, + slot, + parameterTypes, + exceptionTypes, + modifiers, + signature, + genericInfo, + annotations, + parameterAnnotations, + constructorAccessor, + root); } -#endif // HAVE_JexecutableHasRealParameterData +#endif // HAVE_JexecutableHasRealParameterData -object -makeJmethod(Thread* t, object vmMethod, int index) +object makeJmethod(Thread* t, GcMethod* vmMethod, int index) { PROTECT(t, vmMethod); - object name = intern - (t, t->m->classpath->makeString - (t, methodName(t, vmMethod), 0, byteArrayLength - (t, methodName(t, vmMethod)) - 1)); + object name + = intern(t, + t->m->classpath->makeString( + t, vmMethod->name(), 0, vmMethod->name()->length() - 1)); PROTECT(t, name); unsigned parameterCount; unsigned returnTypeSpec; - object parameterTypes = resolveParameterJTypes - (t, classLoader(t, methodClass(t, vmMethod)), methodSpec(t, vmMethod), - ¶meterCount, &returnTypeSpec); + object parameterTypes = resolveParameterJTypes(t, + vmMethod->class_()->loader(), + vmMethod->spec(), + ¶meterCount, + &returnTypeSpec); PROTECT(t, parameterTypes); - object returnType = resolveJType - (t, classLoader(t, methodClass(t, vmMethod)), reinterpret_cast - (&byteArrayBody(t, methodSpec(t, vmMethod), returnTypeSpec)), - byteArrayLength(t, methodSpec(t, vmMethod)) - 1 - returnTypeSpec); + GcJclass* returnType = resolveJType( + t, + vmMethod->class_()->loader(), + reinterpret_cast(&vmMethod->spec()->body()[returnTypeSpec]), + vmMethod->spec()->length() - 1 - returnTypeSpec); PROTECT(t, returnType); - object exceptionTypes = resolveExceptionJTypes - (t, classLoader(t, methodClass(t, vmMethod)), - methodAddendum(t, vmMethod)); + object exceptionTypes = resolveExceptionJTypes( + t, vmMethod->class_()->loader(), vmMethod->addendum()); PROTECT(t, exceptionTypes); object signature; object annotationTable; object parameterAnnotationTable; object annotationDefault; - object addendum = methodAddendum(t, vmMethod); + GcMethodAddendum* addendum = vmMethod->addendum(); if (addendum) { - signature = addendumSignature(t, addendum); + signature = addendum->signature(); if (signature) { PROTECT(t, addendum); - signature = t->m->classpath->makeString - (t, signature, 0, byteArrayLength(t, signature) - 1); + signature = t->m->classpath->makeString( + t, signature, 0, cast(t, signature)->length() - 1); } - annotationTable = addendumAnnotationTable(t, addendum); + annotationTable = addendum->annotationTable(); - parameterAnnotationTable = methodAddendumParameterAnnotationTable - (t, addendum); + parameterAnnotationTable = addendum->parameterAnnotationTable(); - annotationDefault = methodAddendumAnnotationDefault(t, addendum); + annotationDefault = addendum->annotationDefault(); } else { signature = 0; annotationTable = 0; @@ -2280,16 +2454,16 @@ makeJmethod(Thread* t, object vmMethod, int index) PROTECT(t, annotationDefault); if (annotationTable or parameterAnnotationTable or annotationDefault) { - object runtimeData = getClassRuntimeData(t, methodClass(t, vmMethod)); + GcClassRuntimeData* runtimeData + = getClassRuntimeData(t, vmMethod->class_()); - set(t, runtimeData, ClassRuntimeDataPool, - addendumPool(t, methodAddendum(t, vmMethod))); + runtimeData->setPool(t, vmMethod->addendum()->pool()); } if (index == -1) { - object table = classMethodTable(t, methodClass(t, vmMethod)); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - if (vmMethod == arrayBody(t, table, i)) { + GcArray* table = cast(t, vmMethod->class_()->methodTable()); + for (unsigned i = 0; i < table->length(); ++i) { + if (vmMethod == table->body()[i]) { index = i; break; } @@ -2298,47 +2472,60 @@ makeJmethod(Thread* t, object vmMethod, int index) expect(t, index != -1); - object jclass = getJClass(t, methodClass(t, vmMethod)); + GcJclass* jclass = getJClass(t, vmMethod->class_()); - return makeJmethod - (t, true, 0, jclass, index, name, returnType, parameterTypes, - exceptionTypes, methodFlags(t, vmMethod), signature, 0, annotationTable, - parameterAnnotationTable, annotationDefault, 0, 0, 0); + return makeJmethod(t, + true, + 0, + jclass, + index, + cast(t, name), + returnType, + parameterTypes, + exceptionTypes, + vmMethod->flags(), + cast(t, signature), + 0, + cast(t, annotationTable), + cast(t, parameterAnnotationTable), + cast(t, annotationDefault), + 0, + 0, + 0); } -object -makeJconstructor(Thread* t, object vmMethod, int index) +object makeJconstructor(Thread* t, GcMethod* vmMethod, int index) { PROTECT(t, vmMethod); unsigned parameterCount; unsigned returnTypeSpec; - object parameterTypes = resolveParameterJTypes - (t, classLoader(t, methodClass(t, vmMethod)), methodSpec(t, vmMethod), - ¶meterCount, &returnTypeSpec); + object parameterTypes = resolveParameterJTypes(t, + vmMethod->class_()->loader(), + vmMethod->spec(), + ¶meterCount, + &returnTypeSpec); PROTECT(t, parameterTypes); - object exceptionTypes = resolveExceptionJTypes - (t, classLoader(t, methodClass(t, vmMethod)), - methodAddendum(t, vmMethod)); + object exceptionTypes = resolveExceptionJTypes( + t, vmMethod->class_()->loader(), vmMethod->addendum()); PROTECT(t, exceptionTypes); object signature; object annotationTable; object parameterAnnotationTable; - object addendum = methodAddendum(t, vmMethod); + GcMethodAddendum* addendum = vmMethod->addendum(); if (addendum) { - signature = addendumSignature(t, addendum); + signature = addendum->signature(); if (signature) { PROTECT(t, addendum); - signature = t->m->classpath->makeString - (t, signature, 0, byteArrayLength(t, signature) - 1); + signature = t->m->classpath->makeString( + t, signature, 0, cast(t, signature)->length() - 1); } - annotationTable = addendumAnnotationTable(t, addendum); - parameterAnnotationTable = methodAddendumParameterAnnotationTable - (t, addendum); + annotationTable = addendum->annotationTable(); + parameterAnnotationTable = addendum->parameterAnnotationTable(); } else { signature = 0; annotationTable = 0; @@ -2350,16 +2537,16 @@ makeJconstructor(Thread* t, object vmMethod, int index) PROTECT(t, parameterAnnotationTable); if (annotationTable or parameterAnnotationTable) { - object runtimeData = getClassRuntimeData(t, methodClass(t, vmMethod)); + GcClassRuntimeData* runtimeData + = getClassRuntimeData(t, vmMethod->class_()); - set(t, runtimeData, ClassRuntimeDataPool, - addendumPool(t, methodAddendum(t, vmMethod))); + runtimeData->setPool(t, vmMethod->addendum()->pool()); } if (index == -1) { - object table = classMethodTable(t, methodClass(t, vmMethod)); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - if (vmMethod == arrayBody(t, table, i)) { + GcArray* table = cast(t, vmMethod->class_()->methodTable()); + for (unsigned i = 0; i < table->length(); ++i) { + if (vmMethod == table->body()[i]) { index = i; break; } @@ -2368,47 +2555,57 @@ makeJconstructor(Thread* t, object vmMethod, int index) expect(t, index != -1); - object jclass = getJClass(t, methodClass(t, vmMethod)); + GcJclass* jclass = getJClass(t, vmMethod->class_()); - return makeJconstructor - (t, true, 0, jclass, index, parameterTypes, exceptionTypes, methodFlags - (t, vmMethod), signature, 0, annotationTable, parameterAnnotationTable, - 0, 0, 0); + return makeJconstructor(t, + true, + 0, + jclass, + index, + parameterTypes, + exceptionTypes, + vmMethod->flags(), + cast(t, signature), + 0, + cast(t, annotationTable), + cast(t, parameterAnnotationTable), + 0, + 0, + 0); } -object -makeJfield(Thread* t, object vmField, int index) +object makeJfield(Thread* t, GcField* vmField, int index) { PROTECT(t, vmField); - object name = intern - (t, t->m->classpath->makeString - (t, fieldName(t, vmField), 0, byteArrayLength - (t, fieldName(t, vmField)) - 1)); + object name + = intern(t, + t->m->classpath->makeString( + t, vmField->name(), 0, vmField->name()->length() - 1)); PROTECT(t, name); - object type = resolveClassBySpec - (t, classLoader(t, fieldClass(t, vmField)), - reinterpret_cast - (&byteArrayBody(t, fieldSpec(t, vmField), 0)), - byteArrayLength(t, fieldSpec(t, vmField)) - 1); + GcClass* type = resolveClassBySpec( + t, + vmField->class_()->loader(), + reinterpret_cast(vmField->spec()->body().begin()), + vmField->spec()->length() - 1); PROTECT(t, type); - type = getJClass(t, type); + GcJclass* jtype = getJClass(t, type); object signature; object annotationTable; - object addendum = fieldAddendum(t, vmField); + GcFieldAddendum* addendum = vmField->addendum(); if (addendum) { - signature = addendumSignature(t, addendum); + signature = addendum->signature(); if (signature) { PROTECT(t, addendum); - signature = t->m->classpath->makeString - (t, signature, 0, byteArrayLength(t, signature) - 1); + signature = t->m->classpath->makeString( + t, signature, 0, cast(t, signature)->length() - 1); } - annotationTable = addendumAnnotationTable(t, addendum); + annotationTable = addendum->annotationTable(); } else { signature = 0; annotationTable = 0; @@ -2418,16 +2615,15 @@ makeJfield(Thread* t, object vmField, int index) PROTECT(t, annotationTable); if (annotationTable) { - object runtimeData = getClassRuntimeData(t, fieldClass(t, vmField)); + GcClassRuntimeData* runtimeData = getClassRuntimeData(t, vmField->class_()); - set(t, runtimeData, ClassRuntimeDataPool, - addendumPool(t, fieldAddendum(t, vmField))); + runtimeData->setPool(t, vmField->addendum()->pool()); } if (index == -1) { - object table = classFieldTable(t, fieldClass(t, vmField)); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - if (vmField == arrayBody(t, table, i)) { + GcArray* table = cast(t, vmField->class_()->fieldTable()); + for (unsigned i = 0; i < table->length(); ++i) { + if (vmField == table->body()[i]) { index = i; break; } @@ -2436,30 +2632,44 @@ makeJfield(Thread* t, object vmField, int index) expect(t, index != -1); - object jclass = getJClass(t, fieldClass(t, vmField)); + GcJclass* jclass = getJClass(t, vmField->class_()); - return makeJfield - (t, true, 0, jclass, index, name, type, fieldFlags - (t, vmField), signature, 0, annotationTable, 0, 0, 0, 0); + return makeJfield(t, + true, + 0, + jclass, + index, + cast(t, name), + jtype, + vmField->flags(), + cast(t, signature), + 0, + cast(t, annotationTable), + 0, + 0, + 0, + 0); } -void -setProperty(Thread* t, object method, object properties, - const char* name, const void* value, const char* format = "%s") +void setProperty(Thread* t, + GcMethod* method, + object properties, + const char* name, + const void* value, + const char* format = "%s") { PROTECT(t, method); PROTECT(t, properties); - - object n = makeString(t, "%s", name); + + GcString* n = makeString(t, "%s", name); PROTECT(t, n); - object v = makeString(t, format, value); + GcString* v = makeString(t, format, value); t->m->processor->invoke(t, method, properties, n, v); } -bool -pipeAvailable(int fd, int* available) +bool pipeAvailable(int fd, int* available) { #ifdef PLATFORM_WINDOWS HANDLE h = reinterpret_cast(_get_osfhandle(fd)); @@ -2468,7 +2678,7 @@ pipeAvailable(int fd, int* available) } DWORD n; - if (PeekNamedPipe(h, 0,0, 0, &n, 0)) { + if (PeekNamedPipe(h, 0, 0, 0, &n, 0)) { *available = n; } else { if (GetLastError() != ERROR_BROKEN_PIPE) { @@ -2483,94 +2693,103 @@ pipeAvailable(int fd, int* available) #endif } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -Classpath* -makeClasspath(System* s, Allocator* allocator, const char* javaHome, - const char* embedPrefix) +Classpath* makeClasspath(System* s, + Allocator* allocator, + const char* javaHome, + const char* embedPrefix) { return new (allocator->allocate(sizeof(local::MyClasspath))) - local::MyClasspath(s, allocator, javaHome, embedPrefix); + local::MyClasspath(s, allocator, javaHome, embedPrefix); } -} // namespace vm +} // namespace vm extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_lang_Class_getSuperclass -(Thread* t, object, uintptr_t* arguments) + Avian_java_lang_Class_getSuperclass(Thread* t, object, uintptr_t* arguments) { - object class_ = jclassVmClass(t, reinterpret_cast(arguments[0])); - if (classFlags(t, class_) & ACC_INTERFACE) { + GcClass* class_ + = cast(t, reinterpret_cast(arguments[0]))->vmClass(); + if (class_->flags() & ACC_INTERFACE) { return 0; } else { - object super = classSuper(t, class_); + GcClass* super = class_->super(); return super ? reinterpret_cast(getJClass(t, super)) : 0; } } -extern "C" AVIAN_EXPORT void -Avian_sun_misc_Unsafe_registerNatives -(Thread*, object, uintptr_t*) +extern "C" AVIAN_EXPORT void Avian_sun_misc_Unsafe_registerNatives(Thread*, + object, + uintptr_t*) { // ignore } -extern "C" AVIAN_EXPORT void -Avian_sun_misc_Perf_registerNatives -(Thread*, object, uintptr_t*) +extern "C" AVIAN_EXPORT void Avian_sun_misc_Perf_registerNatives(Thread*, + object, + uintptr_t*) { // ignore } extern "C" AVIAN_EXPORT int64_t -Avian_sun_misc_Perf_createLong -(Thread* t, object, uintptr_t*) + Avian_sun_misc_Perf_createLong(Thread* t, object, uintptr_t*) { - return reinterpret_cast - (t->m->processor->invoke - (t, resolveMethod - (t, root(t, Machine::BootLoader), "java/nio/ByteBuffer", "allocate", - "(I)Ljava/nio/ByteBuffer;"), 0, 8)); + return reinterpret_cast( + t->m->processor->invoke(t, + resolveMethod(t, + roots(t)->bootLoader(), + "java/nio/ByteBuffer", + "allocate", + "(I)Ljava/nio/ByteBuffer;"), + 0, + 8)); } extern "C" AVIAN_EXPORT int64_t -Avian_sun_misc_Unsafe_addressSize -(Thread*, object, uintptr_t*) + Avian_sun_misc_Unsafe_addressSize(Thread*, object, uintptr_t*) { return BytesPerWord; } extern "C" AVIAN_EXPORT int64_t -Avian_sun_misc_Unsafe_defineClass__Ljava_lang_String_2_3BIILjava_lang_ClassLoader_2Ljava_security_ProtectionDomain_2 -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_defineClass__Ljava_lang_String_2_3BIILjava_lang_ClassLoader_2Ljava_security_ProtectionDomain_2( + Thread* t, + object, + uintptr_t* arguments) { - //object name = reinterpret_cast(arguments[1]); - object data = reinterpret_cast(arguments[2]); + // object name = reinterpret_cast(arguments[1]); + GcByteArray* data + = cast(t, reinterpret_cast(arguments[2])); int32_t offset = arguments[3]; int32_t length = arguments[4]; - object loader = reinterpret_cast(arguments[5]); - //object domain = reinterpret_cast(arguments[6]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[5])); + // object domain = reinterpret_cast(arguments[6]); uint8_t* buffer = static_cast(t->m->heap->allocate(length)); - THREAD_RESOURCE2(t, uint8_t*, buffer, int, length, - t->m->heap->free(buffer, length)); + THREAD_RESOURCE2( + t, uint8_t*, buffer, int, length, t->m->heap->free(buffer, length)); - memcpy(buffer, &byteArrayBody(t, data, offset), length); + memcpy(buffer, &data->body()[offset], length); - return reinterpret_cast - (getJClass(t, defineClass(t, loader, buffer, length))); + return reinterpret_cast( + getJClass(t, cast(t, defineClass(t, loader, buffer, length)))); } extern "C" AVIAN_EXPORT int64_t -Avian_sun_misc_Unsafe_allocateInstance -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_allocateInstance(Thread* t, + object, + uintptr_t* arguments) { - object c = jclassVmClass(t, reinterpret_cast(arguments[1])); + GcClass* c + = cast(t, reinterpret_cast(arguments[1]))->vmClass(); PROTECT(t, c); initClass(t, c); @@ -2579,214 +2798,247 @@ Avian_sun_misc_Unsafe_allocateInstance } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_staticFieldOffset -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_staticFieldOffset(Thread* t, + object, + uintptr_t* arguments) { - object jfield = reinterpret_cast(arguments[1]); - return fieldOffset - (t, arrayBody - (t, classFieldTable - (t, jclassVmClass(t, jfieldClazz(t, jfield))), jfieldSlot(t, jfield))); + GcJfield* jfield = cast(t, reinterpret_cast(arguments[1])); + return cast( + t, + cast(t, jfield->clazz()->vmClass()->fieldTable()) + ->body()[jfield->slot()])->offset(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_staticFieldBase -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_staticFieldBase(Thread* t, + object, + uintptr_t* arguments) { - return reinterpret_cast - (classStaticTable - (t, jclassVmClass - (t, jfieldClazz(t, reinterpret_cast(arguments[1]))))); + return reinterpret_cast( + cast(t, reinterpret_cast(arguments[1])) + ->clazz() + ->vmClass() + ->staticTable()); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_objectFieldOffset -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_objectFieldOffset(Thread* t, + object, + uintptr_t* arguments) { - object jfield = reinterpret_cast(arguments[1]); - return fieldOffset - (t, arrayBody - (t, classFieldTable - (t, jclassVmClass(t, jfieldClazz(t, jfield))), jfieldSlot(t, jfield))); + GcJfield* jfield = cast(t, reinterpret_cast(arguments[1])); + return cast( + t, + cast(t, jfield->clazz()->vmClass()->fieldTable()) + ->body()[jfield->slot()])->offset(); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getShort__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getShort__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getChar__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getChar__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getInt__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getInt__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getFloat__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getFloat__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getLong__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getLong__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getDouble__Ljava_lang_Object_2J -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getDouble__Ljava_lang_Object_2J(Thread* t, + object method, + uintptr_t* arguments) { - return Avian_sun_misc_Unsafe_getLong__Ljava_lang_Object_2J - (t, method, arguments); + return Avian_sun_misc_Unsafe_getLong__Ljava_lang_Object_2J( + t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putByte__Ljava_lang_Object_2JB -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putByte__Ljava_lang_Object_2JB(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int8_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putShort__Ljava_lang_Object_2JS -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putShort__Ljava_lang_Object_2JS(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int16_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putChar__Ljava_lang_Object_2JC -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putChar__Ljava_lang_Object_2JC(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); uint16_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putInt__Ljava_lang_Object_2JI -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putInt__Ljava_lang_Object_2JI(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int32_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putFloat__Ljava_lang_Object_2JF -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putFloat__Ljava_lang_Object_2JF(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); int32_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getByte__Ljava_lang_Object_2J -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getByte__Ljava_lang_Object_2J(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); return fieldAtOffset(o, offset); } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_getBoolean__Ljava_lang_Object_2J -(Thread* t, object method, uintptr_t* arguments) + Avian_sun_misc_Unsafe_getBoolean__Ljava_lang_Object_2J(Thread* t, + object method, + uintptr_t* arguments) { - return Avian_sun_misc_Unsafe_getByte__Ljava_lang_Object_2J - (t, method, arguments); + return Avian_sun_misc_Unsafe_getByte__Ljava_lang_Object_2J( + t, method, arguments); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putBoolean__Ljava_lang_Object_2JZ -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putBoolean__Ljava_lang_Object_2JZ( + Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); uint8_t value = arguments[4]; fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_putLong__Ljava_lang_Object_2JJ -(Thread*, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_putLong__Ljava_lang_Object_2JJ(Thread*, + object, + uintptr_t* arguments) { object o = reinterpret_cast(arguments[1]); - int64_t offset; memcpy(&offset, arguments + 2, 8); - int64_t value; memcpy(&value, arguments + 4, 8); + int64_t offset; + memcpy(&offset, arguments + 2, 8); + int64_t value; + memcpy(&value, arguments + 4, 8); fieldAtOffset(o, offset) = value; } extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_sun_misc_Unsafe_pageSize -(Thread*, object, uintptr_t*) + Avian_sun_misc_Unsafe_pageSize(Thread*, object, uintptr_t*) { return local::PageSize; } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_ensureClassInitialized -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_ensureClassInitialized(Thread* t, + object, + uintptr_t* arguments) { - initClass(t, jclassVmClass(t, reinterpret_cast(arguments[1]))); + initClass( + t, cast(t, reinterpret_cast(arguments[1]))->vmClass()); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_monitorEnter -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_monitorEnter(Thread* t, object, uintptr_t* arguments) { acquire(t, reinterpret_cast(arguments[1])); } extern "C" AVIAN_EXPORT void JNICALL -Avian_sun_misc_Unsafe_monitorExit -(Thread* t, object, uintptr_t* arguments) + Avian_sun_misc_Unsafe_monitorExit(Thread* t, object, uintptr_t* arguments) { release(t, reinterpret_cast(arguments[1])); } @@ -2795,25 +3047,23 @@ namespace { namespace local { -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetInterfaceVersion)() +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_GetInterfaceVersion)() { return local::InterfaceVersion; } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_IHashCode)(Thread* t, jobject o) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_IHashCode)(Thread* t, jobject o) { ENTER(t, Thread::ActiveState); return o ? objectHash(t, *o) : 0; } -uint64_t -jvmWait(Thread* t, uintptr_t* arguments) +uint64_t jvmWait(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - jlong milliseconds; memcpy(&milliseconds, arguments + 1, sizeof(jlong)); + jlong milliseconds; + memcpy(&milliseconds, arguments + 1, sizeof(jlong)); vm::wait(t, *o, milliseconds); @@ -2821,7 +3071,7 @@ jvmWait(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_MonitorWait)(Thread* t, jobject o, jlong milliseconds) + EXPORT(JVM_MonitorWait)(Thread* t, jobject o, jlong milliseconds) { uintptr_t arguments[1 + (sizeof(jlong) / BytesPerWord)]; arguments[0] = reinterpret_cast(o); @@ -2830,8 +3080,7 @@ EXPORT(JVM_MonitorWait)(Thread* t, jobject o, jlong milliseconds) run(t, jvmWait, arguments); } -uint64_t -jvmNotify(Thread* t, uintptr_t* arguments) +uint64_t jvmNotify(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); @@ -2841,15 +3090,14 @@ jvmNotify(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_MonitorNotify)(Thread* t, jobject o) + EXPORT(JVM_MonitorNotify)(Thread* t, jobject o) { - uintptr_t arguments[] = { reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(o)}; run(t, jvmNotify, arguments); } -uint64_t -jvmNotifyAll(Thread* t, uintptr_t* arguments) +uint64_t jvmNotifyAll(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); @@ -2859,31 +3107,28 @@ jvmNotifyAll(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_MonitorNotifyAll)(Thread* t, jobject o) + EXPORT(JVM_MonitorNotifyAll)(Thread* t, jobject o) { - uintptr_t arguments[] = { reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(o)}; run(t, jvmNotifyAll, arguments); } -uint64_t -jvmClone(Thread* t, uintptr_t* arguments) +uint64_t jvmClone(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); return reinterpret_cast(makeLocalReference(t, clone(t, *o))); } -extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_Clone)(Thread* t, jobject o) +extern "C" AVIAN_EXPORT jobject JNICALL EXPORT(JVM_Clone)(Thread* t, jobject o) { - uintptr_t arguments[] = { reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(o)}; return reinterpret_cast(run(t, jvmClone, arguments)); } -uint64_t -jvmInternString(Thread* t, uintptr_t* arguments) +uint64_t jvmInternString(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); @@ -2891,27 +3136,25 @@ jvmInternString(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_InternString)(Thread* t, jstring s) + EXPORT(JVM_InternString)(Thread* t, jstring s) { - uintptr_t arguments[] = { reinterpret_cast(s) }; + uintptr_t arguments[] = {reinterpret_cast(s)}; - return reinterpret_cast(run(t, jvmInternString, arguments)); + return reinterpret_cast(run(t, jvmInternString, arguments)); } extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_CurrentTimeMillis)(Thread* t, jclass) + EXPORT(JVM_CurrentTimeMillis)(Thread* t, jclass) { return t->m->system->now(); } -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_NanoTime)(Thread* t, jclass) +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT(JVM_NanoTime)(Thread* t, jclass) { return t->m->system->now() * 1000 * 1000; } -uint64_t -jvmArrayCopy(Thread* t, uintptr_t* arguments) +uint64_t jvmArrayCopy(Thread* t, uintptr_t* arguments) { jobject src = reinterpret_cast(arguments[0]); jint srcOffset = arguments[1]; @@ -2924,27 +3167,33 @@ jvmArrayCopy(Thread* t, uintptr_t* arguments) return 1; } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_ArrayCopy)(Thread* t, jclass, jobject src, jint srcOffset, - jobject dst, jint dstOffset, jint length) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_ArrayCopy)(Thread* t, + jclass, + jobject src, + jint srcOffset, + jobject dst, + jint dstOffset, + jint length) { - uintptr_t arguments[] = { reinterpret_cast(src), - static_cast(srcOffset), - reinterpret_cast(dst), - static_cast(dstOffset), - static_cast(length) }; + uintptr_t arguments[] = {reinterpret_cast(src), + static_cast(srcOffset), + reinterpret_cast(dst), + static_cast(dstOffset), + static_cast(length)}; run(t, jvmArrayCopy, arguments); } -uint64_t -jvmInitProperties(Thread* t, uintptr_t* arguments) +uint64_t jvmInitProperties(Thread* t, uintptr_t* arguments) { jobject properties = reinterpret_cast(arguments[0]); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "java/util/Properties", "setProperty", - "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"); + GcMethod* method = resolveMethod( + t, + roots(t)->bootLoader(), + "java/util/Properties", + "setProperty", + "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"); PROTECT(t, method); @@ -2959,59 +3208,73 @@ jvmInitProperties(Thread* t, uintptr_t* arguments) local::setProperty(t, method, *properties, "java.io.tmpdir", buffer); local::setProperty(t, method, *properties, "java.home", buffer); - local::setProperty(t, method, *properties, "user.home", - _wgetenv(L"USERPROFILE"), "%ls"); + local::setProperty( + t, method, *properties, "user.home", _wgetenv(L"USERPROFILE"), "%ls"); GetCurrentDirectory(MAX_PATH, buffer); local::setProperty(t, method, *properties, "user.dir", buffer); -#else // not PLATFORM_WINDOWS +#else // not PLATFORM_WINDOWS local::setProperty(t, method, *properties, "line.separator", "\n"); local::setProperty(t, method, *properties, "file.separator", "/"); local::setProperty(t, method, *properties, "path.separator", ":"); -# ifdef __APPLE__ +#ifdef __APPLE__ local::setProperty(t, method, *properties, "os.name", "Mac OS X"); -# elif defined __FreeBSD__ +#elif defined __FreeBSD__ local::setProperty(t, method, *properties, "os.name", "FreeBSD"); -# else // not __APPLE__ +#else // not __APPLE__ local::setProperty(t, method, *properties, "os.name", "Linux"); -# endif // not __APPLE__ +#endif // not __APPLE__ local::setProperty(t, method, *properties, "java.io.tmpdir", "/tmp"); local::setProperty(t, method, *properties, "user.home", getenv("HOME")); char buffer[PATH_MAX]; - local::setProperty(t, method, *properties, "user.dir", - getcwd(buffer, PATH_MAX)); -#endif // not PLATFORM_WINDOWS + local::setProperty( + t, method, *properties, "user.dir", getcwd(buffer, PATH_MAX)); +#endif // not PLATFORM_WINDOWS - local::setProperty(t, method, *properties, "java.protocol.handler.pkgs", - "avian"); + local::setProperty( + t, method, *properties, "java.protocol.handler.pkgs", "avian"); - local::setProperty(t, method, *properties, "java.vm.vendor", - "Avian Contributors"); + local::setProperty( + t, method, *properties, "java.vm.vendor", "Avian Contributors"); - local::setProperty(t, method, *properties, "java.vm.name","Avian"); + local::setProperty(t, method, *properties, "java.vm.name", "Avian"); #ifdef AVIAN_VERSION - local::setProperty(t, method, *properties, "java.vm.version",AVIAN_VERSION); + local::setProperty(t, method, *properties, "java.vm.version", AVIAN_VERSION); #endif #ifdef AVIAN_INFO - local::setProperty(t, method, *properties, "java.vm.info",AVIAN_INFO); + local::setProperty(t, method, *properties, "java.vm.info", AVIAN_INFO); #endif - local::setProperty(t, method, *properties, "java.vm.specification.name", "Java Virtual Machine Specification"); + local::setProperty(t, + method, + *properties, + "java.vm.specification.name", + "Java Virtual Machine Specification"); - local::setProperty - (t, method, *properties, "java.home", - static_cast(t->m->classpath)->javaHome); + local::setProperty( + t, + method, + *properties, + "java.home", + static_cast(t->m->classpath)->javaHome); - local::setProperty - (t, method, *properties, "sun.boot.library.path", - static_cast(t->m->classpath)->libraryPath); + local::setProperty( + t, + method, + *properties, + "sun.boot.library.path", + static_cast(t->m->classpath)->libraryPath); - local::setProperty - (t, method, *properties, "sun.boot.class.path", - static_cast - (systemClassLoaderFinder(t, root(t, Machine::BootLoader)))->path()); + local::setProperty( + t, + method, + *properties, + "sun.boot.class.path", + static_cast( + roots(t)->bootLoader()->as(t)->finder()) + ->path()); local::setProperty(t, method, *properties, "file.encoding", "UTF-8"); #ifdef ARCH_x86_32 @@ -3027,91 +3290,89 @@ jvmInitProperties(Thread* t, uintptr_t* arguments) for (unsigned i = 0; i < t->m->propertyCount; ++i) { const char* start = t->m->properties[i]; const char* p = start; - while (*p and *p != '=') ++p; + while (*p and *p != '=') + ++p; if (*p == '=') { THREAD_RUNTIME_ARRAY(t, char, name, (p - start) + 1); memcpy(RUNTIME_ARRAY_BODY(name), start, p - start); RUNTIME_ARRAY_BODY(name)[p - start] = 0; - local::setProperty - (t, method, *properties, RUNTIME_ARRAY_BODY(name), p + 1); + local::setProperty( + t, method, *properties, RUNTIME_ARRAY_BODY(name), p + 1); } - } + } return reinterpret_cast(properties); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_InitProperties)(Thread* t, jobject properties) + EXPORT(JVM_InitProperties)(Thread* t, jobject properties) { - uintptr_t arguments[] = { reinterpret_cast(properties) }; + uintptr_t arguments[] = {reinterpret_cast(properties)}; return reinterpret_cast(run(t, jvmInitProperties, arguments)); } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_OnExit)(void (*)(void)) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_OnExit)(void (*)(void)) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_Exit)(jint code) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_Exit)(jint code) { exit(code); } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_Halt)(jint code) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_Halt)(jint code) { exit(code); } -uint64_t -jvmGC(Thread* t, uintptr_t*) +uint64_t jvmGC(Thread* t, uintptr_t*) { collect(t, Heap::MajorCollection); return 1; } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GC)() +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_GC)() { Thread* t = static_cast(local::globalMachine->localThread->get()); - + run(t, jvmGC, 0); } -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_MaxObjectInspectionAge)(void) +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT(JVM_MaxObjectInspectionAge)(void) { return 0; } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_TraceInstructions)(jboolean) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_TraceInstructions)(jboolean) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_TraceMethodCalls)(jboolean) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_TraceMethodCalls)(jboolean) +{ + abort(); +} -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_TotalMemory)() +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT(JVM_TotalMemory)() { return 0; } -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_FreeMemory)() +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT(JVM_FreeMemory)() { return 0; } -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_MaxMemory)() +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT(JVM_MaxMemory)() { return local::globalMachine->heap->limit(); } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_ActiveProcessorCount)() +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_ActiveProcessorCount)() { #ifdef PLATFORM_WINDOWS SYSTEM_INFO si; @@ -3122,41 +3383,40 @@ EXPORT(JVM_ActiveProcessorCount)() #endif } -uint64_t -jvmLoadLibrary(Thread* t, uintptr_t* arguments) +uint64_t jvmLoadLibrary(Thread* t, uintptr_t* arguments) { const char* path = reinterpret_cast(arguments[0]); THREAD_RUNTIME_ARRAY(t, char, p, strlen(path) + 1); replace('\\', '/', RUNTIME_ARRAY_BODY(p), path); - return reinterpret_cast - (loadLibrary - (t, static_cast(t->m->classpath)->libraryPath, - RUNTIME_ARRAY_BODY(p), false, false)); + return reinterpret_cast(loadLibrary( + t, + static_cast(t->m->classpath)->libraryPath, + RUNTIME_ARRAY_BODY(p), + false, + false)); } -extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_LoadLibrary)(const char* path) +extern "C" AVIAN_EXPORT void* JNICALL EXPORT(JVM_LoadLibrary)(const char* path) { Thread* t = static_cast(local::globalMachine->localThread->get()); - - uintptr_t arguments[] = { reinterpret_cast(path) }; - return reinterpret_cast(run(t, jvmLoadLibrary, arguments)); + uintptr_t arguments[] = {reinterpret_cast(path)}; + + return reinterpret_cast(run(t, jvmLoadLibrary, arguments)); } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_UnloadLibrary)(void*) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_UnloadLibrary)(void*) { // todo: implement this correctly for POSIX and Windows } extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_FindLibraryEntry)(void* library, const char* name) + EXPORT(JVM_FindLibraryEntry)(void* library, const char* name) { Thread* t = static_cast(local::globalMachine->localThread->get()); - + ENTER(t, Thread::ActiveState); if (library == RTLD_DEFAULT) { @@ -3173,167 +3433,188 @@ EXPORT(JVM_FindLibraryEntry)(void* library, const char* name) } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsSupportedJNIVersion)(jint version) + EXPORT(JVM_IsSupportedJNIVersion)(jint version) { return version <= JNI_VERSION_1_6; } -extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsNaN)(jdouble) { abort(); } - -uint64_t -jvmFillInStackTrace(Thread* t, uintptr_t* arguments) +extern "C" AVIAN_EXPORT jboolean JNICALL EXPORT(JVM_IsNaN)(jdouble) { - jobject throwable = reinterpret_cast(arguments[0]); + abort(); +} + +uint64_t jvmFillInStackTrace(Thread* t, uintptr_t* arguments) +{ + GcThrowable* throwable + = cast(t, *reinterpret_cast(arguments[0])); object trace = getTrace(t, 2); - set(t, *throwable, ThrowableTrace, trace); + throwable->setTrace(t, trace); return 1; } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_FillInStackTrace)(Thread* t, jobject throwable) + EXPORT(JVM_FillInStackTrace)(Thread* t, jobject throwable) { - uintptr_t arguments[] = { reinterpret_cast(throwable) }; + uintptr_t arguments[] = {reinterpret_cast(throwable)}; run(t, jvmFillInStackTrace, arguments); } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_PrintStackTrace)(Thread*, jobject, jobject) { abort(); } + EXPORT(JVM_PrintStackTrace)(Thread*, jobject, jobject) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetStackTraceDepth)(Thread* t, jobject throwable) + EXPORT(JVM_GetStackTraceDepth)(Thread* t, jobject throwable) { ENTER(t, Thread::ActiveState); - return objectArrayLength(t, throwableTrace(t, *throwable)); + return objectArrayLength(t, cast(t, *throwable)->trace()); } -uint64_t -jvmGetStackTraceElement(Thread* t, uintptr_t* arguments) +uint64_t jvmGetStackTraceElement(Thread* t, uintptr_t* arguments) { jobject throwable = reinterpret_cast(arguments[0]); jint index = arguments[1]; - return reinterpret_cast - (makeLocalReference - (t, makeStackTraceElement - (t, objectArrayBody(t, throwableTrace(t, *throwable), index)))); + return reinterpret_cast(makeLocalReference( + t, + makeStackTraceElement( + t, + cast( + t, + objectArrayBody( + t, cast(t, *throwable)->trace(), index))))); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetStackTraceElement)(Thread* t, jobject throwable, jint index) + EXPORT(JVM_GetStackTraceElement)(Thread* t, jobject throwable, jint index) { - uintptr_t arguments[] = { reinterpret_cast(throwable), - static_cast(index) }; + uintptr_t arguments[] + = {reinterpret_cast(throwable), static_cast(index)}; return reinterpret_cast(run(t, jvmGetStackTraceElement, arguments)); } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_InitializeCompiler) (Thread*, jclass) { abort(); } + EXPORT(JVM_InitializeCompiler)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsSilentCompiler)(Thread*, jclass) { abort(); } + EXPORT(JVM_IsSilentCompiler)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_CompileClass)(Thread*, jclass, jclass) + EXPORT(JVM_CompileClass)(Thread*, jclass, jclass) { return false; } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_CompileClasses)(Thread*, jclass, jstring) + EXPORT(JVM_CompileClasses)(Thread*, jclass, jstring) { return false; } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_CompilerCommand)(Thread*, jclass, jobject) { abort(); } + EXPORT(JVM_CompilerCommand)(Thread*, jclass, jobject) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_EnableCompiler)(Thread*, jclass) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_EnableCompiler)(Thread*, jclass) { // ignore } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_DisableCompiler)(Thread*, jclass) + EXPORT(JVM_DisableCompiler)(Thread*, jclass) { // ignore } -uint64_t -jvmStartThread(Thread* t, uintptr_t* arguments) +uint64_t jvmStartThread(Thread* t, uintptr_t* arguments) { jobject thread = reinterpret_cast(arguments[0]); - return startThread(t, *thread) != 0; + return startThread(t, cast(t, *thread)) != 0; } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_StartThread)(Thread* t, jobject thread) + EXPORT(JVM_StartThread)(Thread* t, jobject thread) { - uintptr_t arguments[] = { reinterpret_cast(thread) }; + uintptr_t arguments[] = {reinterpret_cast(thread)}; run(t, jvmStartThread, arguments); } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_StopThread)(Thread*, jobject, jobject) { abort(); } + EXPORT(JVM_StopThread)(Thread*, jobject, jobject) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsThreadAlive)(Thread* t, jobject thread) + EXPORT(JVM_IsThreadAlive)(Thread* t, jobject thread) { ENTER(t, Thread::ActiveState); - Thread* p = reinterpret_cast(threadPeer(t, *thread)); + Thread* p = reinterpret_cast(cast(t, *thread)->peer()); return p and (p->flags & Thread::ActiveFlag) != 0; } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SuspendThread)(Thread*, jobject) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_SuspendThread)(Thread*, jobject) +{ + abort(); +} + +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_ResumeThread)(Thread*, jobject) +{ + abort(); +} extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_ResumeThread)(Thread*, jobject) { abort(); } - -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetThreadPriority)(Thread*, jobject, jint) + EXPORT(JVM_SetThreadPriority)(Thread*, jobject, jint) { // ignore } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_Yield)(Thread* t, jclass) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_Yield)(Thread* t, jclass) { t->m->system->yield(); } -uint64_t -jvmSleep(Thread* t, uintptr_t* arguments) +uint64_t jvmSleep(Thread* t, uintptr_t* arguments) { - jlong milliseconds; memcpy(&milliseconds, arguments, sizeof(jlong)); + jlong milliseconds; + memcpy(&milliseconds, arguments, sizeof(jlong)); if (milliseconds <= 0) { milliseconds = 1; } - if (threadSleepLock(t, t->javaThread) == 0) { - object lock = makeJobject(t); - set(t, t->javaThread, ThreadSleepLock, lock); + if (t->javaThread->sleepLock() == 0) { + GcJobject* lock = makeJobject(t); + t->javaThread->setSleepLock(t, lock); } - acquire(t, threadSleepLock(t, t->javaThread)); - vm::wait(t, threadSleepLock(t, t->javaThread), milliseconds); - release(t, threadSleepLock(t, t->javaThread)); + acquire(t, t->javaThread->sleepLock()); + vm::wait(t, t->javaThread->sleepLock(), milliseconds); + release(t, t->javaThread->sleepLock()); return 1; } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_Sleep)(Thread* t, jclass, jlong milliseconds) + EXPORT(JVM_Sleep)(Thread* t, jclass, jlong milliseconds) { uintptr_t arguments[sizeof(jlong) / BytesPerWord]; memcpy(arguments, &milliseconds, sizeof(jlong)); @@ -3342,7 +3623,7 @@ EXPORT(JVM_Sleep)(Thread* t, jclass, jlong milliseconds) } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_CurrentThread)(Thread* t, jclass) + EXPORT(JVM_CurrentThread)(Thread* t, jclass) { ENTER(t, Thread::ActiveState); @@ -3350,97 +3631,107 @@ EXPORT(JVM_CurrentThread)(Thread* t, jclass) } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_CountStackFrames)(Thread*, jobject) { abort(); } - -uint64_t -jvmInterrupt(Thread* t, uintptr_t* arguments) + EXPORT(JVM_CountStackFrames)(Thread*, jobject) { - threadInterrupt(t, *reinterpret_cast(arguments[0])); + abort(); +} + +uint64_t jvmInterrupt(Thread* t, uintptr_t* arguments) +{ + threadInterrupt(t, + cast(t, *reinterpret_cast(arguments[0]))); return 1; } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_Interrupt)(Thread* t, jobject thread) + EXPORT(JVM_Interrupt)(Thread* t, jobject thread) { - uintptr_t arguments[] = { reinterpret_cast(thread) }; + uintptr_t arguments[] = {reinterpret_cast(thread)}; run(t, jvmInterrupt, arguments); } -uint64_t -jvmIsInterrupted(Thread* t, uintptr_t* arguments) +uint64_t jvmIsInterrupted(Thread* t, uintptr_t* arguments) { jobject thread = reinterpret_cast(arguments[0]); jboolean clear = arguments[1]; - return threadIsInterrupted(t, *thread, clear); + return threadIsInterrupted(t, cast(t, *thread), clear); } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsInterrupted)(Thread* t, jobject thread, jboolean clear) + EXPORT(JVM_IsInterrupted)(Thread* t, jobject thread, jboolean clear) { - uintptr_t arguments[] = { reinterpret_cast(thread), clear }; + uintptr_t arguments[] = {reinterpret_cast(thread), clear}; return run(t, jvmIsInterrupted, arguments); } -uint64_t -jvmHoldsLock(Thread* t, uintptr_t* arguments) +uint64_t jvmHoldsLock(Thread* t, uintptr_t* arguments) { - object m = objectMonitor(t, *reinterpret_cast(arguments[0]), false); + GcMonitor* m + = objectMonitor(t, *reinterpret_cast(arguments[0]), false); - return m and monitorOwner(t, m) == t; + return m and m->owner() == t; } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_HoldsLock)(Thread* t, jclass, jobject o) + EXPORT(JVM_HoldsLock)(Thread* t, jclass, jobject o) { - uintptr_t arguments[] = { reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(o)}; return run(t, jvmHoldsLock, arguments); } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_DumpAllStacks)(Thread*, jclass) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_DumpAllStacks)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetAllThreads)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetAllThreads)(Thread*, jclass) +{ + abort(); +} -uint64_t -jvmDumpThreads(Thread* t, uintptr_t* arguments) +uint64_t jvmDumpThreads(Thread* t, uintptr_t* arguments) { jobjectArray threads = reinterpret_cast(arguments[0]); - unsigned threadsLength = objectArrayLength(t, *threads); - object arrayClass = resolveObjectArrayClass - (t, classLoader(t, type(t, Machine::StackTraceElementType)), - type(t, Machine::StackTraceElementType)); + unsigned threadsLength + = objectArrayLength(t, reinterpret_cast(*threads)); + GcClass* arrayClass + = resolveObjectArrayClass(t, + type(t, GcStackTraceElement::Type)->loader(), + type(t, GcStackTraceElement::Type)); object result = makeObjectArray(t, arrayClass, threadsLength); PROTECT(t, result); for (unsigned threadsIndex = 0; threadsIndex < threadsLength; - ++ threadsIndex) - { - Thread* peer = reinterpret_cast - (threadPeer(t, objectArrayBody(t, *threads, threadsIndex))); + ++threadsIndex) { + Thread* peer = reinterpret_cast( + cast(t, + objectArrayBody( + t, reinterpret_cast(*threads), threadsIndex)) + ->peer()); if (peer) { object trace = t->m->processor->getStackTrace(t, peer); PROTECT(t, trace); unsigned traceLength = objectArrayLength(t, trace); - object array = makeObjectArray - (t, type(t, Machine::StackTraceElementType), traceLength); + object array + = makeObjectArray(t, type(t, GcStackTraceElement::Type), traceLength); PROTECT(t, array); - for (unsigned traceIndex = 0; traceIndex < traceLength; ++ traceIndex) { - object ste = makeStackTraceElement - (t, objectArrayBody(t, trace, traceIndex)); - set(t, array, ArrayBody + (traceIndex * BytesPerWord), ste); + for (unsigned traceIndex = 0; traceIndex < traceLength; ++traceIndex) { + object ste = makeStackTraceElement( + t, cast(t, objectArrayBody(t, trace, traceIndex))); + setField(t, array, ArrayBody + (traceIndex * BytesPerWord), ste); } - set(t, result, ArrayBody + (threadsIndex * BytesPerWord), array); + setField(t, result, ArrayBody + (threadsIndex * BytesPerWord), array); } } @@ -3448,18 +3739,19 @@ jvmDumpThreads(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_DumpThreads)(Thread* t, jclass, jobjectArray threads) + EXPORT(JVM_DumpThreads)(Thread* t, jclass, jobjectArray threads) { - uintptr_t arguments[] = { reinterpret_cast(threads) }; + uintptr_t arguments[] = {reinterpret_cast(threads)}; return reinterpret_cast(run(t, jvmDumpThreads, arguments)); } -extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_CurrentLoadedClass)(Thread*) { abort(); } +extern "C" AVIAN_EXPORT jclass JNICALL EXPORT(JVM_CurrentLoadedClass)(Thread*) +{ + abort(); +} -extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_CurrentClassLoader)(Thread*) +extern "C" AVIAN_EXPORT jobject JNICALL EXPORT(JVM_CurrentClassLoader)(Thread*) { // just return null, i.e. tell SecurityManager.currentClassLoader // all permissions are granted, since Avian doesn't do any internal @@ -3467,115 +3759,120 @@ EXPORT(JVM_CurrentClassLoader)(Thread*) return 0; } -uint64_t -jvmGetClassContext(Thread* t, uintptr_t*) +uint64_t jvmGetClassContext(Thread* t, uintptr_t*) { object trace = getTrace(t, 1); PROTECT(t, trace); - object context = makeObjectArray - (t, type(t, Machine::JclassType), objectArrayLength(t, trace)); + object context = makeObjectArray( + t, type(t, GcJclass::Type), objectArrayLength(t, trace)); PROTECT(t, context); for (unsigned i = 0; i < objectArrayLength(t, trace); ++i) { - object c = getJClass - (t, methodClass(t, traceElementMethod(t, objectArrayBody(t, trace, i)))); + object c = getJClass( + t, + cast( + t, cast(t, objectArrayBody(t, trace, i))->method()) + ->class_()); - set(t, context, ArrayBody + (i * BytesPerWord), c); + setField(t, context, ArrayBody + (i * BytesPerWord), c); } return reinterpret_cast(makeLocalReference(t, context)); } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassContext)(Thread* t) + EXPORT(JVM_GetClassContext)(Thread* t) { return reinterpret_cast(run(t, jvmGetClassContext, 0)); } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_ClassDepth)(Thread*, jstring) { abort(); } +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_ClassDepth)(Thread*, jstring) +{ + abort(); +} -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_ClassLoaderDepth)(Thread*) { abort(); } +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_ClassLoaderDepth)(Thread*) +{ + abort(); +} -uint64_t -jvmGetSystemPackage(Thread* t, uintptr_t* arguments) +uint64_t jvmGetSystemPackage(Thread* t, uintptr_t* arguments) { jstring s = reinterpret_cast(arguments[0]); ACQUIRE(t, t->m->classLock); - THREAD_RUNTIME_ARRAY(t, char, chars, stringLength(t, *s) + 1); + THREAD_RUNTIME_ARRAY(t, char, chars, (*s)->length(t) + 1); stringChars(t, *s, RUNTIME_ARRAY_BODY(chars)); object key = makeByteArray(t, RUNTIME_ARRAY_BODY(chars)); - object array = hashMapFind - (t, root(t, Machine::PackageMap), key, byteArrayHash, byteArrayEqual); + GcByteArray* array = cast( + t, + hashMapFind( + t, roots(t)->packageMap(), key, byteArrayHash, byteArrayEqual)); if (array) { - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeString - (t, array, 0, byteArrayLength(t, array)))); + return reinterpret_cast(makeLocalReference( + t, t->m->classpath->makeString(t, array, 0, array->length()))); } else { return 0; } } extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_GetSystemPackage)(Thread* t, jstring s) + EXPORT(JVM_GetSystemPackage)(Thread* t, jstring s) { - uintptr_t arguments[] = { reinterpret_cast(s) }; + uintptr_t arguments[] = {reinterpret_cast(s)}; return reinterpret_cast(run(t, jvmGetSystemPackage, arguments)); } -uint64_t -jvmGetSystemPackages(Thread* t, uintptr_t*) +uint64_t jvmGetSystemPackages(Thread* t, uintptr_t*) { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), "java/lang/Package"), 0))); + return reinterpret_cast(makeLocalReference( + t, + makeObjectArray( + t, resolveClass(t, roots(t)->bootLoader(), "java/lang/Package"), 0))); } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetSystemPackages)(Thread* t) + EXPORT(JVM_GetSystemPackages)(Thread* t) { return reinterpret_cast(run(t, jvmGetSystemPackages, 0)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_AllocateNewObject)(Thread*, jobject, jclass, - jclass) { abort(); } + EXPORT(JVM_AllocateNewObject)(Thread*, jobject, jclass, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_AllocateNewArray)(Thread*, jobject, jclass, - jint) { abort(); } + EXPORT(JVM_AllocateNewArray)(Thread*, jobject, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_LatestUserDefinedLoader)(Thread* t) + EXPORT(JVM_LatestUserDefinedLoader)(Thread* t) { ENTER(t, Thread::ActiveState); - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t): - t(t), loader(0) - { } + Visitor(Thread* t) : t(t), loader(0) + { + } - virtual bool visit(Processor::StackWalker* walker) { - object loader = classLoader(t, methodClass(t, walker->method())); - if (loader - and loader != root(t, Machine::BootLoader) - and strcmp - (&byteArrayBody(t, className(t, objectClass(t, loader)), 0), - reinterpret_cast - ("sun/reflect/DelegatingClassLoader"))) - { + virtual bool visit(Processor::StackWalker* walker) + { + GcClassLoader* loader = walker->method()->class_()->loader(); + if (loader and loader != roots(t)->bootLoader() + and strcmp(objectClass(t, loader)->name()->body().begin(), + reinterpret_cast( + "sun/reflect/DelegatingClassLoader"))) { this->loader = loader; return false; } else { @@ -3584,7 +3881,7 @@ EXPORT(JVM_LatestUserDefinedLoader)(Thread* t) } Thread* t; - object loader; + GcClassLoader* loader; } v(t); t->m->processor->walkStack(t, &v); @@ -3593,128 +3890,141 @@ EXPORT(JVM_LatestUserDefinedLoader)(Thread* t) } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_LoadClass0)(Thread*, jobject, jclass, - jstring) { abort(); } + EXPORT(JVM_LoadClass0)(Thread*, jobject, jclass, jstring) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetArrayLength)(Thread* t, jobject array) + EXPORT(JVM_GetArrayLength)(Thread* t, jobject array) { ENTER(t, Thread::ActiveState); return fieldAtOffset(*array, BytesPerWord); } -uint64_t -jvmGetArrayElement(Thread* t, uintptr_t* arguments) +uint64_t jvmGetArrayElement(Thread* t, uintptr_t* arguments) { jobject array = reinterpret_cast(arguments[0]); jint index = arguments[1]; - switch (byteArrayBody(t, className(t, objectClass(t, *array)), 1)) { + switch (objectClass(t, *array)->name()->body()[1]) { case 'Z': - return reinterpret_cast - (makeLocalReference - (t, makeBoolean(t, fieldAtOffset(*array, ArrayBody + index)))); + return reinterpret_cast(makeLocalReference( + t, makeBoolean(t, fieldAtOffset(*array, ArrayBody + index)))); case 'B': - return reinterpret_cast - (makeLocalReference - (t, makeByte(t, fieldAtOffset(*array, ArrayBody + index)))); + return reinterpret_cast(makeLocalReference( + t, makeByte(t, fieldAtOffset(*array, ArrayBody + index)))); case 'C': - return reinterpret_cast - (makeLocalReference - (t, makeChar(t, fieldAtOffset(*array, ArrayBody + (index * 2))))); + return reinterpret_cast(makeLocalReference( + t, + makeChar(t, fieldAtOffset(*array, ArrayBody + (index * 2))))); case 'S': - return reinterpret_cast - (makeLocalReference - (t, makeShort(t, fieldAtOffset(*array, ArrayBody + (index * 2))))); + return reinterpret_cast(makeLocalReference( + t, + makeShort(t, fieldAtOffset(*array, ArrayBody + (index * 2))))); case 'I': - return reinterpret_cast - (makeLocalReference - (t, makeInt(t, fieldAtOffset(*array, ArrayBody + (index * 4))))); + return reinterpret_cast(makeLocalReference( + t, + makeInt(t, fieldAtOffset(*array, ArrayBody + (index * 4))))); case 'F': - return reinterpret_cast - (makeLocalReference - (t, makeFloat(t, fieldAtOffset(*array, ArrayBody + (index * 4))))); + return reinterpret_cast(makeLocalReference( + t, + makeFloat(t, fieldAtOffset(*array, ArrayBody + (index * 4))))); case 'J': - return reinterpret_cast - (makeLocalReference - (t, makeLong(t, fieldAtOffset(*array, ArrayBody + (index * 8))))); + return reinterpret_cast(makeLocalReference( + t, + makeLong(t, fieldAtOffset(*array, ArrayBody + (index * 8))))); case 'D': - return reinterpret_cast - (makeLocalReference - (t, makeDouble(t, fieldAtOffset(*array, ArrayBody + (index * 8))))); + return reinterpret_cast(makeLocalReference( + t, + makeDouble(t, + fieldAtOffset(*array, ArrayBody + (index * 8))))); case 'L': case '[': - return reinterpret_cast - (makeLocalReference - (t, fieldAtOffset(*array, ArrayBody + (index * BytesPerWord)))); + return reinterpret_cast(makeLocalReference( + t, fieldAtOffset(*array, ArrayBody + (index * BytesPerWord)))); default: abort(t); } } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetArrayElement)(Thread* t, jobject array, jint index) + EXPORT(JVM_GetArrayElement)(Thread* t, jobject array, jint index) { - uintptr_t arguments[] = { reinterpret_cast(array), - static_cast(index) }; + uintptr_t arguments[] + = {reinterpret_cast(array), static_cast(index)}; return reinterpret_cast(run(t, jvmGetArrayElement, arguments)); } extern "C" AVIAN_EXPORT jvalue JNICALL -EXPORT(JVM_GetPrimitiveArrayElement)(Thread*, jobject, jint, jint) { abort(); } + EXPORT(JVM_GetPrimitiveArrayElement)(Thread*, jobject, jint, jint) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetArrayElement)(Thread* t, jobject array, jint index, - jobject value) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_SetArrayElement)(Thread* t, + jobject array, + jint index, + jobject value) { ENTER(t, Thread::ActiveState); - switch (byteArrayBody(t, className(t, objectClass(t, *array)), 1)) { + switch (objectClass(t, *array)->name()->body()[1]) { case 'Z': - fieldAtOffset(*array, ArrayBody + index) = booleanValue(t, *value); + fieldAtOffset(*array, ArrayBody + index) + = cast(t, *value)->value(); break; case 'B': - fieldAtOffset(*array, ArrayBody + index) = byteValue(t, *value); + fieldAtOffset(*array, ArrayBody + index) + = cast(t, *value)->value(); break; case 'C': - fieldAtOffset(*array, ArrayBody + (index * 2)) = charValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 2)) + = cast(t, *value)->value(); break; case 'S': - fieldAtOffset(*array, ArrayBody + (index * 2)) = shortValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 2)) + = cast(t, *value)->value(); break; case 'I': - fieldAtOffset(*array, ArrayBody + (index * 4)) = intValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 4)) + = cast(t, *value)->value(); break; case 'F': - fieldAtOffset(*array, ArrayBody + (index * 4)) = floatValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 4)) + = cast(t, *value)->value(); break; case 'J': - fieldAtOffset(*array, ArrayBody + (index * 8)) = longValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 8)) + = cast(t, *value)->value(); break; case 'D': - fieldAtOffset(*array, ArrayBody + (index * 8)) = doubleValue(t, *value); + fieldAtOffset(*array, ArrayBody + (index * 8)) + = cast(t, *value)->value(); break; case 'L': case '[': - set(t, *array, ArrayBody + (index * BytesPerWord), (value ? *value : 0)); + setField( + t, *array, ArrayBody + (index * BytesPerWord), (value ? *value : 0)); break; default: abort(t); } } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetPrimitiveArrayElement)(Thread*, jobject, jint, jvalue, - unsigned char) { abort(); } - -object -makeNewArray(Thread* t, object c, unsigned length) +extern "C" AVIAN_EXPORT void JNICALL EXPORT( + JVM_SetPrimitiveArrayElement)(Thread*, jobject, jint, jvalue, unsigned char) { - if (classVmFlags(t, c) & PrimitiveFlag) { - const char* name = reinterpret_cast - (&byteArrayBody(t, local::getClassName(t, c), 0)); + abort(); +} + +object makeNewArray(Thread* t, GcClass* c, unsigned length) +{ + if (c->vmFlags() & PrimitiveFlag) { + const char* name + = reinterpret_cast(local::getClassName(t, c)->body().begin()); switch (*name) { case 'b': @@ -3723,160 +4033,168 @@ makeNewArray(Thread* t, object c, unsigned length) } else { return makeByteArray(t, length); } - case 'c': return makeCharArray(t, length); - case 'd': return makeDoubleArray(t, length); - case 'f': return makeFloatArray(t, length); - case 'i': return makeIntArray(t, length); - case 'l': return makeLongArray(t, length); - case 's': return makeShortArray(t, length); - default: abort(t); + case 'c': + return makeCharArray(t, length); + case 'd': + return makeDoubleArray(t, length); + case 'f': + return makeFloatArray(t, length); + case 'i': + return makeIntArray(t, length); + case 'l': + return makeLongArray(t, length); + case 's': + return makeShortArray(t, length); + default: + abort(t); } } else { return makeObjectArray(t, c, length); } } -uint64_t -jvmNewArray(Thread* t, uintptr_t* arguments) +uint64_t jvmNewArray(Thread* t, uintptr_t* arguments) { jclass elementClass = reinterpret_cast(arguments[0]); jint length = arguments[1]; - return reinterpret_cast - (makeLocalReference - (t, makeNewArray(t, jclassVmClass(t, *elementClass), length))); + return reinterpret_cast(makeLocalReference( + t, makeNewArray(t, (*elementClass)->vmClass(), length))); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_NewArray)(Thread* t, jclass elementClass, jint length) + EXPORT(JVM_NewArray)(Thread* t, jclass elementClass, jint length) { - uintptr_t arguments[] = { reinterpret_cast(elementClass), - static_cast(length) }; + uintptr_t arguments[] = {reinterpret_cast(elementClass), + static_cast(length)}; return reinterpret_cast(run(t, jvmNewArray, arguments)); } -uint64_t -jvmNewMultiArray(Thread* t, uintptr_t* arguments) +uint64_t jvmNewMultiArray(Thread* t, uintptr_t* arguments) { jclass elementClass = reinterpret_cast(arguments[0]); jintArray dimensions = reinterpret_cast(arguments[1]); - THREAD_RUNTIME_ARRAY(t, int32_t, counts, intArrayLength(t, *dimensions)); - for (int i = intArrayLength(t, *dimensions) - 1; i >= 0; --i) { - RUNTIME_ARRAY_BODY(counts)[i] = intArrayBody(t, *dimensions, i); + THREAD_RUNTIME_ARRAY(t, int32_t, counts, (*dimensions)->length()); + for (int i = (*dimensions)->length() - 1; i >= 0; --i) { + RUNTIME_ARRAY_BODY(counts)[i] = (*dimensions)->body()[i]; if (UNLIKELY(RUNTIME_ARRAY_BODY(counts)[i] < 0)) { - throwNew(t, Machine::NegativeArraySizeExceptionType, "%d", + throwNew(t, + GcNegativeArraySizeException::Type, + "%d", RUNTIME_ARRAY_BODY(counts)[i]); return 0; } } - object array = makeNewArray - (t, jclassVmClass(t, *elementClass), RUNTIME_ARRAY_BODY(counts)[0]); + object array = makeNewArray( + t, (*elementClass)->vmClass(), RUNTIME_ARRAY_BODY(counts)[0]); PROTECT(t, array); - populateMultiArray(t, array, RUNTIME_ARRAY_BODY(counts), 0, - intArrayLength(t, *dimensions)); + populateMultiArray( + t, array, RUNTIME_ARRAY_BODY(counts), 0, (*dimensions)->length()); return reinterpret_cast(makeLocalReference(t, array)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_NewMultiArray)(Thread* t, jclass elementClass, - jintArray dimensions) + EXPORT(JVM_NewMultiArray)(Thread* t, + jclass elementClass, + jintArray dimensions) { - uintptr_t arguments[] = { reinterpret_cast(elementClass), - reinterpret_cast(dimensions) }; + uintptr_t arguments[] = {reinterpret_cast(elementClass), + reinterpret_cast(dimensions)}; return reinterpret_cast(run(t, jvmNewMultiArray, arguments)); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_GetCallerClass)(Thread* t, int target) + EXPORT(JVM_GetCallerClass)(Thread* t, int target) { ENTER(t, Thread::ActiveState); - object method = getCaller(t, target, true); + GcMethod* method = getCaller(t, target, true); - return method ? makeLocalReference - (t, getJClass(t, methodClass(t, method))) : 0; + return method ? reinterpret_cast( + makeLocalReference(t, getJClass(t, method->class_()))) + : 0; } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_FindPrimitiveClass)(Thread* t, const char* name) + EXPORT(JVM_FindPrimitiveClass)(Thread* t, const char* name) { ENTER(t, Thread::ActiveState); switch (*name) { case 'b': if (name[1] == 'o') { - return makeLocalReference - (t, getJClass(t, type(t, Machine::JbooleanType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJboolean::Type)))); } else { - return makeLocalReference - (t, getJClass(t, type(t, Machine::JbyteType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJbyte::Type)))); } case 'c': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JcharType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJchar::Type)))); case 'd': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JdoubleType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJdouble::Type)))); case 'f': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JfloatType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJfloat::Type)))); case 'i': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JintType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJint::Type)))); case 'l': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JlongType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJlong::Type)))); case 's': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JshortType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJshort::Type)))); case 'v': - return makeLocalReference - (t, getJClass(t, type(t, Machine::JvoidType))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, type(t, GcJvoid::Type)))); default: - throwNew(t, Machine::IllegalArgumentExceptionType); + throwNew(t, GcIllegalArgumentException::Type); } } -uint64_t -jvmResolveClass(Thread* t, uintptr_t* arguments) +uint64_t jvmResolveClass(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "link", - "(Lavian/VMClass;)V"); + GcMethod* method = resolveMethod( + t, roots(t)->bootLoader(), "avian/Classes", "link", "(Lavian/VMClass;)V"); - t->m->processor->invoke(t, method, 0, jclassVmClass(t, *c)); + t->m->processor->invoke(t, method, 0, (*c)->vmClass()); return 1; } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_ResolveClass)(Thread* t, jclass c) + EXPORT(JVM_ResolveClass)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; run(t, jvmResolveClass, arguments); } -uint64_t -jvmFindClassFromClassLoader(Thread* t, uintptr_t* arguments) +uint64_t jvmFindClassFromClassLoader(Thread* t, uintptr_t* arguments) { const char* name = reinterpret_cast(arguments[0]); jboolean init = arguments[1]; jobject loader = reinterpret_cast(arguments[2]); jboolean throwError = arguments[3]; - object c = resolveClass - (t, loader ? *loader : root(t, Machine::BootLoader), name, true, - throwError ? Machine::NoClassDefFoundErrorType - : Machine::ClassNotFoundExceptionType); + GcClass* c = resolveClass( + t, + loader ? cast(t, *loader) : roots(t)->bootLoader(), + name, + true, + throwError ? static_cast(GcNoClassDefFoundError::Type) + : static_cast(GcClassNotFoundException::Type)); if (init) { PROTECT(t, c); @@ -3888,161 +4206,179 @@ jvmFindClassFromClassLoader(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_FindClassFromClassLoader)(Thread* t, const char* name, - jboolean init, jobject loader, - jboolean throwError) + EXPORT(JVM_FindClassFromClassLoader)(Thread* t, + const char* name, + jboolean init, + jobject loader, + jboolean throwError) { - uintptr_t arguments[] = { reinterpret_cast(name), - init, - reinterpret_cast(loader), - throwError }; + uintptr_t arguments[] = {reinterpret_cast(name), + init, + reinterpret_cast(loader), + throwError}; - return reinterpret_cast - (run(t, jvmFindClassFromClassLoader, arguments)); + return reinterpret_cast( + run(t, jvmFindClassFromClassLoader, arguments)); } extern "C" AVIAN_EXPORT jclass JNICALL -JVM_FindClassFromBootLoader(Thread* t, const char* name) + JVM_FindClassFromBootLoader(Thread* t, const char* name) { return EXPORT(JVM_FindClassFromClassLoader)(t, name, false, 0, false); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_FindClassFromClass)(Thread*, const char*, jboolean, jclass) -{ abort(); } + EXPORT(JVM_FindClassFromClass)(Thread*, const char*, jboolean, jclass) +{ + abort(); +} -uint64_t -jvmFindLoadedClass(Thread* t, uintptr_t* arguments) +uint64_t jvmFindLoadedClass(Thread* t, uintptr_t* arguments) { jobject loader = reinterpret_cast(arguments[0]); jstring name = reinterpret_cast(arguments[1]); - object spec = makeByteArray(t, stringLength(t, *name) + 1); + GcByteArray* spec = makeByteArray(t, (*name)->length(t) + 1); - { char* s = reinterpret_cast(&byteArrayBody(t, spec, 0)); - stringChars(t, *name, s); + { + char* s = reinterpret_cast(spec->body().begin()); + stringChars(t, (*name), s); replace('.', '/', s); } - object c = findLoadedClass(t, *loader, spec); - - return reinterpret_cast - (c ? makeLocalReference(t, getJClass(t, c)) : 0); + GcClass* c = findLoadedClass(t, cast(t, *loader), spec); + + return reinterpret_cast(c ? makeLocalReference(t, getJClass(t, c)) + : 0); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_FindLoadedClass)(Thread* t, jobject loader, jstring name) + EXPORT(JVM_FindLoadedClass)(Thread* t, jobject loader, jstring name) { - uintptr_t arguments[] = { reinterpret_cast(loader), - reinterpret_cast(name) }; + uintptr_t arguments[] = {reinterpret_cast(loader), + reinterpret_cast(name)}; return reinterpret_cast(run(t, jvmFindLoadedClass, arguments)); } -uint64_t -jvmDefineClass(Thread* t, uintptr_t* arguments) +uint64_t jvmDefineClass(Thread* t, uintptr_t* arguments) { jobject loader = reinterpret_cast(arguments[0]); const uint8_t* data = reinterpret_cast(arguments[1]); jsize length = arguments[2]; - return reinterpret_cast - (makeLocalReference - (t, getJClass(t, defineClass(t, *loader, data, length)))); + return reinterpret_cast(makeLocalReference( + t, + getJClass( + t, + cast( + t, + defineClass(t, cast(t, *loader), data, length))))); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_DefineClass)(Thread* t, const char*, jobject loader, - const uint8_t* data, jsize length, jobject) + EXPORT(JVM_DefineClass)(Thread* t, + const char*, + jobject loader, + const uint8_t* data, + jsize length, + jobject) { - uintptr_t arguments[] = { reinterpret_cast(loader), - reinterpret_cast(data), - static_cast(length) }; + uintptr_t arguments[] = {reinterpret_cast(loader), + reinterpret_cast(data), + static_cast(length)}; return reinterpret_cast(run(t, jvmDefineClass, arguments)); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_DefineClassWithSource)(Thread* t, const char*, jobject loader, - const uint8_t* data, jsize length, jobject, - const char*) + EXPORT(JVM_DefineClassWithSource)(Thread* t, + const char*, + jobject loader, + const uint8_t* data, + jsize length, + jobject, + const char*) { return EXPORT(JVM_DefineClass)(t, 0, loader, data, length, 0); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_DefineClassWithSourceCond)(Thread* t, const char*, jobject loader, - const uint8_t* data, jsize length, - jobject, const char*, jboolean) + EXPORT(JVM_DefineClassWithSourceCond)(Thread* t, + const char*, + jobject loader, + const uint8_t* data, + jsize length, + jobject, + const char*, + jboolean) { return EXPORT(JVM_DefineClass)(t, 0, loader, data, length, 0); } extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_GetClassName)(Thread* t, jclass c) + EXPORT(JVM_GetClassName)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - return makeLocalReference(t, jclassName(t, *c)); + return reinterpret_cast(makeLocalReference(t, (*c)->name())); } -uint64_t -jvmGetClassInterfaces(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassInterfaces(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); - object addendum = classAddendum(t, jclassVmClass(t, *c)); + GcClassAddendum* addendum = (*c)->vmClass()->addendum(); if (addendum) { - object table = classAddendumInterfaceTable(t, addendum); + GcArray* table = cast(t, addendum->interfaceTable()); if (table) { PROTECT(t, table); - object array = makeObjectArray - (t, type(t, Machine::JclassType), arrayLength(t, table)); + object array + = makeObjectArray(t, type(t, GcJclass::Type), table->length()); PROTECT(t, array); - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object c = getJClass(t, arrayBody(t, table, i)); - set(t, array, ArrayBody + (i * BytesPerWord), c); + for (unsigned i = 0; i < table->length(); ++i) { + object c = getJClass(t, cast(t, table->body()[i])); + setField(t, array, ArrayBody + (i * BytesPerWord), c); } return reinterpret_cast(makeLocalReference(t, array)); } } - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray(t, type(t, Machine::JclassType), 0))); + return reinterpret_cast( + makeLocalReference(t, makeObjectArray(t, type(t, GcJclass::Type), 0))); } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassInterfaces)(Thread* t, jclass c) + EXPORT(JVM_GetClassInterfaces)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; - return reinterpret_cast(run(t, jvmGetClassInterfaces, arguments)); + return reinterpret_cast( + run(t, jvmGetClassInterfaces, arguments)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetClassLoader)(Thread* t, jclass c) + EXPORT(JVM_GetClassLoader)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - object loader = classLoader(t, jclassVmClass(t, *c)); + GcClassLoader* loader = (*c)->vmClass()->loader(); - if (loader == root(t, Machine::BootLoader)) { + if (loader == roots(t)->bootLoader()) { // sun.misc.Unsafe.getUnsafe expects a null result if the class // loader is the boot classloader and will throw a // SecurityException otherwise. - object caller = getCaller(t, 2); - if (caller and strcmp - (reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, caller)), 0)), - "sun/misc/Unsafe") == 0) - { + GcMethod* caller = getCaller(t, 2); + if (caller + and strcmp(reinterpret_cast( + caller->class_()->name()->body().begin()), + "sun/misc/Unsafe") == 0) { return 0; } else { - return makeLocalReference(t, root(t, Machine::BootLoader)); + return makeLocalReference(t, roots(t)->bootLoader()); } } else { return makeLocalReference(t, loader); @@ -4050,107 +4386,111 @@ EXPORT(JVM_GetClassLoader)(Thread* t, jclass c) } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsInterface)(Thread* t, jclass c) + EXPORT(JVM_IsInterface)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - return (classFlags(t, jclassVmClass(t, *c)) & ACC_INTERFACE) != 0; + return ((*c)->vmClass()->flags() & ACC_INTERFACE) != 0; } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassSigners)(Thread* t, jclass c) + EXPORT(JVM_GetClassSigners)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - object runtimeData = getClassRuntimeDataIfExists(t, jclassVmClass(t, *c)); + GcClassRuntimeData* runtimeData + = getClassRuntimeDataIfExists(t, (*c)->vmClass()); - return runtimeData ? makeLocalReference - (t, classRuntimeDataSigners(t, runtimeData)) : 0; + return runtimeData ? reinterpret_cast( + makeLocalReference(t, runtimeData->signers())) + : 0; } extern "C" AVIAN_EXPORT jbyteArray JNICALL -EXPORT(JVM_GetClassTypeAnnotations)(Thread*, jclass) + EXPORT(JVM_GetClassTypeAnnotations)(Thread*, jclass) { abort(); } extern "C" AVIAN_EXPORT jbyteArray JNICALL -EXPORT(JVM_GetFieldTypeAnnotations)(Thread*, jobject) + EXPORT(JVM_GetFieldTypeAnnotations)(Thread*, jobject) { abort(); } extern "C" AVIAN_EXPORT jbyteArray JNICALL -EXPORT(JVM_GetMethodTypeAnnotations)(Thread*, jobject) + EXPORT(JVM_GetMethodTypeAnnotations)(Thread*, jobject) { abort(); } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetClassSigners)(Thread* t, jclass c, jobjectArray signers) + EXPORT(JVM_SetClassSigners)(Thread* t, jclass c, jobjectArray signers) { ENTER(t, Thread::ActiveState); - object runtimeData = getClassRuntimeData(t, jclassVmClass(t, *c)); + GcClassRuntimeData* runtimeData = getClassRuntimeData(t, (*c)->vmClass()); - set(t, runtimeData, ClassRuntimeDataSigners, *signers); + runtimeData->setSigners(t, reinterpret_cast(*signers)); } -uint64_t -jvmGetProtectionDomain(Thread* t, uintptr_t* arguments) +uint64_t jvmGetProtectionDomain(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Classes", "getProtectionDomain", - "(Lavian/VMClass;)Ljava/security/ProtectionDomain;"); + GcMethod* method + = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Classes", + "getProtectionDomain", + "(Lavian/VMClass;)Ljava/security/ProtectionDomain;"); - return reinterpret_cast - (makeLocalReference - (t, t->m->processor->invoke(t, method, 0, jclassVmClass(t, *c)))); + return reinterpret_cast(makeLocalReference( + t, t->m->processor->invoke(t, method, 0, (*c)->vmClass()))); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetProtectionDomain)(Thread* t, jclass c) + EXPORT(JVM_GetProtectionDomain)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; return reinterpret_cast(run(t, jvmGetProtectionDomain, arguments)); } extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetProtectionDomain)(Thread*, jclass, jobject) { abort(); } - -extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsArrayClass)(Thread* t, jclass c) + EXPORT(JVM_SetProtectionDomain)(Thread*, jclass, jobject) { - ENTER(t, Thread::ActiveState); - - return classArrayDimensions(t, jclassVmClass(t, *c)) != 0; + abort(); } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsPrimitiveClass)(Thread* t, jclass c) + EXPORT(JVM_IsArrayClass)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - return (classVmFlags(t, jclassVmClass(t, *c)) & PrimitiveFlag) != 0; + return (*c)->vmClass()->arrayDimensions() != 0; } -uint64_t -jvmGetComponentType(Thread* t, uintptr_t* arguments) +extern "C" AVIAN_EXPORT jboolean JNICALL + EXPORT(JVM_IsPrimitiveClass)(Thread* t, jclass c) { - jclass c = reinterpret_cast(arguments[0]); + ENTER(t, Thread::ActiveState); - if (classArrayDimensions(t, jclassVmClass(t, *c))) { - uint8_t n = byteArrayBody(t, className(t, jclassVmClass(t, *c)), 1); + return ((*c)->vmClass()->vmFlags() & PrimitiveFlag) != 0; +} + +uint64_t jvmGetComponentType(Thread* t, uintptr_t* arguments) +{ + jclass c = reinterpret_cast(arguments[0]); + + if ((*c)->vmClass()->arrayDimensions()) { + uint8_t n = (*c)->vmClass()->name()->body()[1]; if (n != 'L' and n != '[') { - return reinterpret_cast - (makeLocalReference(t, getJClass(t, primitiveClass(t, n)))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, primitiveClass(t, n)))); } else { - return reinterpret_cast - (makeLocalReference - (t, getJClass(t, classStaticTable(t, jclassVmClass(t, *c))))); + return reinterpret_cast(makeLocalReference( + t, getJClass(t, (*c)->vmClass()->arrayElementClass()))); } } else { return 0; @@ -4158,484 +4498,504 @@ jvmGetComponentType(Thread* t, uintptr_t* arguments) } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_GetComponentType)(Thread* t, jclass c) + EXPORT(JVM_GetComponentType)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; return reinterpret_cast(run(t, jvmGetComponentType, arguments)); } -uint64_t -jvmGetClassModifiers(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassModifiers(Thread* t, uintptr_t* arguments) { - return classModifiers - (t, jclassVmClass(t, *reinterpret_cast(arguments[0]))); + return classModifiers( + t, + cast(t, *reinterpret_cast(arguments[0]))->vmClass()); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetClassModifiers)(Thread* t, jclass c) + EXPORT(JVM_GetClassModifiers)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; return run(t, jvmGetClassModifiers, arguments); } -uint64_t -jvmGetDeclaredClasses(Thread* t, uintptr_t* arguments) +uint64_t jvmGetDeclaredClasses(Thread* t, uintptr_t* arguments) { - return reinterpret_cast - (makeLocalReference - (t, getDeclaredClasses - (t, jclassVmClass(t, *reinterpret_cast(arguments[0])), false))); + return reinterpret_cast(makeLocalReference( + t, + getDeclaredClasses( + t, + cast(t, *reinterpret_cast(arguments[0])) + ->vmClass(), + false))); } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetDeclaredClasses)(Thread* t, jclass c) + EXPORT(JVM_GetDeclaredClasses)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; - return reinterpret_cast(run(t, jvmGetDeclaredClasses, arguments)); + return reinterpret_cast( + run(t, jvmGetDeclaredClasses, arguments)); } -uint64_t -jvmGetDeclaringClass(Thread* t, uintptr_t* arguments) +uint64_t jvmGetDeclaringClass(Thread* t, uintptr_t* arguments) { - return reinterpret_cast - (makeLocalReference - (t, getDeclaringClass - (t, jclassVmClass(t, *reinterpret_cast(arguments[0]))))); + return reinterpret_cast(makeLocalReference( + t, + getDeclaringClass( + t, + cast(t, *reinterpret_cast(arguments[0])) + ->vmClass()))); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_GetDeclaringClass)(Thread* t, jclass c) + EXPORT(JVM_GetDeclaringClass)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; return reinterpret_cast(run(t, jvmGetDeclaringClass, arguments)); } -uint64_t -jvmGetClassSignature(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassSignature(Thread* t, uintptr_t* arguments) { - jclass c = reinterpret_cast(arguments[0]); + jclass c = reinterpret_cast(arguments[0]); - object addendum = classAddendum(t, jclassVmClass(t, *c)); + GcClassAddendum* addendum = (*c)->vmClass()->addendum(); if (addendum) { - object signature = addendumSignature(t, addendum); + GcByteArray* signature = cast(t, addendum->signature()); if (signature) { - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeString - (t, signature, 0, byteArrayLength(t, signature) - 1))); + return reinterpret_cast( + makeLocalReference(t, + t->m->classpath->makeString( + t, signature, 0, signature->length() - 1))); } } return 0; } extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_GetClassSignature)(Thread* t, jclass c) + EXPORT(JVM_GetClassSignature)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; - return reinterpret_cast(run(t, jvmGetClassSignature, arguments)); + return reinterpret_cast(run(t, jvmGetClassSignature, arguments)); } extern "C" AVIAN_EXPORT jbyteArray JNICALL -EXPORT(JVM_GetClassAnnotations)(Thread* t, jclass c) + EXPORT(JVM_GetClassAnnotations)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - object addendum = classAddendum(t, jclassVmClass(t, *c)); - return addendum - ? makeLocalReference(t, addendumAnnotationTable(t, addendum)) : 0; + GcClassAddendum* addendum = (*c)->vmClass()->addendum(); + return addendum ? reinterpret_cast( + makeLocalReference(t, addendum->annotationTable())) + : 0; } -uint64_t -jvmGetClassDeclaredMethods(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassDeclaredMethods(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); jboolean publicOnly = arguments[1]; - object table = classMethodTable(t, jclassVmClass(t, *c)); + GcArray* table = cast(t, (*c)->vmClass()->methodTable()); if (table) { PROTECT(t, table); - object array = makeObjectArray - (t, type(t, Machine::JmethodType), - local::countMethods(t, jclassVmClass(t, *c), publicOnly)); + object array + = makeObjectArray(t, + type(t, GcJmethod::Type), + local::countMethods(t, (*c)->vmClass(), publicOnly)); PROTECT(t, array); unsigned ai = 0; - for (unsigned i = 0, j = classDeclaredMethodCount(t, jclassVmClass(t, *c)); - i < j; ++i) - { - object vmMethod = arrayBody(t, table, i); + for (unsigned i = 0, j = classDeclaredMethodCount(t, (*c)->vmClass()); + i < j; + ++i) { + GcMethod* vmMethod = cast(t, table->body()[i]); PROTECT(t, vmMethod); - if (((not publicOnly) or (methodFlags(t, vmMethod) & ACC_PUBLIC)) - and byteArrayBody(t, methodName(t, vmMethod), 0) != '<') - { + if (((not publicOnly) or (vmMethod->flags() & ACC_PUBLIC)) + and vmMethod->name()->body()[0] != '<') { object method = makeJmethod(t, vmMethod, i); - assert(t, ai < objectArrayLength(t, array)); + assertT(t, ai < objectArrayLength(t, array)); - set(t, array, ArrayBody + ((ai++) * BytesPerWord), method); + setField(t, array, ArrayBody + ((ai++) * BytesPerWord), method); } } return reinterpret_cast(makeLocalReference(t, array)); } else { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray(t, type(t, Machine::JmethodType), 0))); + return reinterpret_cast( + makeLocalReference(t, makeObjectArray(t, type(t, GcJmethod::Type), 0))); } } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassDeclaredMethods)(Thread* t, jclass c, jboolean publicOnly) + EXPORT(JVM_GetClassDeclaredMethods)(Thread* t, + jclass c, + jboolean publicOnly) { - uintptr_t arguments[] = { reinterpret_cast(c), publicOnly }; + uintptr_t arguments[] = {reinterpret_cast(c), publicOnly}; - return reinterpret_cast - (run(t, jvmGetClassDeclaredMethods, arguments)); + return reinterpret_cast( + run(t, jvmGetClassDeclaredMethods, arguments)); } -uint64_t -jvmGetClassDeclaredFields(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassDeclaredFields(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); jboolean publicOnly = arguments[1]; - object table = classFieldTable(t, jclassVmClass(t, *c)); + GcArray* table = cast(t, (*c)->vmClass()->fieldTable()); if (table) { PROTECT(t, table); - object array = makeObjectArray - (t, type(t, Machine::JfieldType), - local::countFields(t, jclassVmClass(t, *c), publicOnly)); + object array + = makeObjectArray(t, + type(t, GcJfield::Type), + local::countFields(t, (*c)->vmClass(), publicOnly)); PROTECT(t, array); unsigned ai = 0; - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object vmField = arrayBody(t, table, i); + for (unsigned i = 0; i < table->length(); ++i) { + GcField* vmField = cast(t, table->body()[i]); PROTECT(t, vmField); - if ((not publicOnly) or (fieldFlags(t, vmField) & ACC_PUBLIC)) { + if ((not publicOnly) or (vmField->flags() & ACC_PUBLIC)) { object field = makeJfield(t, vmField, i); - assert(t, ai < objectArrayLength(t, array)); + assertT(t, ai < objectArrayLength(t, array)); - set(t, array, ArrayBody + ((ai++) * BytesPerWord), field); + setField(t, array, ArrayBody + ((ai++) * BytesPerWord), field); } } - assert(t, ai == objectArrayLength(t, array)); + assertT(t, ai == objectArrayLength(t, array)); return reinterpret_cast(makeLocalReference(t, array)); } else { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray(t, type(t, Machine::JfieldType), 0))); + return reinterpret_cast( + makeLocalReference(t, makeObjectArray(t, type(t, GcJfield::Type), 0))); } } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassDeclaredFields)(Thread* t, jclass c, jboolean publicOnly) + EXPORT(JVM_GetClassDeclaredFields)(Thread* t, jclass c, jboolean publicOnly) { - uintptr_t arguments[] = { reinterpret_cast(c), publicOnly }; + uintptr_t arguments[] = {reinterpret_cast(c), publicOnly}; - return reinterpret_cast - (run(t, jvmGetClassDeclaredFields, arguments)); + return reinterpret_cast( + run(t, jvmGetClassDeclaredFields, arguments)); } -uint64_t -jvmGetClassDeclaredConstructors(Thread* t, uintptr_t* arguments) +uint64_t jvmGetClassDeclaredConstructors(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); jboolean publicOnly = arguments[1]; - object table = classMethodTable(t, jclassVmClass(t, *c)); + GcArray* table = cast(t, (*c)->vmClass()->methodTable()); if (table) { PROTECT(t, table); - object array = makeObjectArray - (t, type(t, Machine::JconstructorType), - local::countConstructors(t, jclassVmClass(t, *c), publicOnly)); + object array = makeObjectArray( + t, + type(t, GcJconstructor::Type), + local::countConstructors(t, (*c)->vmClass(), publicOnly)); PROTECT(t, array); unsigned ai = 0; - for (unsigned i = 0, j = classDeclaredMethodCount(t, jclassVmClass(t, *c)); - i < j; ++i) - { - object vmMethod = arrayBody(t, table, i); + for (unsigned i = 0, j = classDeclaredMethodCount(t, (*c)->vmClass()); + i < j; + ++i) { + GcMethod* vmMethod = cast(t, table->body()[i]); PROTECT(t, vmMethod); - if (((not publicOnly) or (methodFlags(t, vmMethod) & ACC_PUBLIC)) - and strcmp(reinterpret_cast - (&byteArrayBody(t, methodName(t, vmMethod), 0)), - "") == 0) - { + if (((not publicOnly) or (vmMethod->flags() & ACC_PUBLIC)) + and strcmp(reinterpret_cast(vmMethod->name()->body().begin()), + "") == 0) { object method = makeJconstructor(t, vmMethod, i); - assert(t, ai < objectArrayLength(t, array)); + assertT(t, ai < objectArrayLength(t, array)); - set(t, array, ArrayBody + ((ai++) * BytesPerWord), method); + setField(t, array, ArrayBody + ((ai++) * BytesPerWord), method); } } return reinterpret_cast(makeLocalReference(t, array)); } else { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray(t, type(t, Machine::JconstructorType), 0))); + return reinterpret_cast(makeLocalReference( + t, makeObjectArray(t, type(t, GcJconstructor::Type), 0))); } } extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetClassDeclaredConstructors)(Thread* t, jclass c, - jboolean publicOnly) + EXPORT(JVM_GetClassDeclaredConstructors)(Thread* t, + jclass c, + jboolean publicOnly) { - uintptr_t arguments[] = { reinterpret_cast(c), publicOnly }; + uintptr_t arguments[] = {reinterpret_cast(c), publicOnly}; - return reinterpret_cast - (run(t, jvmGetClassDeclaredConstructors, arguments)); + return reinterpret_cast( + run(t, jvmGetClassDeclaredConstructors, arguments)); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetClassAccessFlags)(Thread* t, jclass c) + EXPORT(JVM_GetClassAccessFlags)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - return classFlags(t, jclassVmClass(t, *c)); + return (*c)->vmClass()->flags(); } -uint64_t -jvmInvokeMethod(Thread* t, uintptr_t* arguments) +uint64_t jvmInvokeMethod(Thread* t, uintptr_t* arguments) { jobject method = reinterpret_cast(arguments[0]); jobject instance = reinterpret_cast(arguments[1]); jobjectArray args = reinterpret_cast(arguments[2]); - object vmMethod = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jmethodClazz(t, *method))), - jmethodSlot(t, *method)); + GcMethod* vmMethod = cast( + t, + cast( + t, cast(t, *method)->clazz()->vmClass()->methodTable()) + ->body()[cast(t, *method)->slot()]); - if (methodFlags(t, vmMethod) & ACC_STATIC) { + if (vmMethod->flags() & ACC_STATIC) { instance = 0; } - if (instance and not instanceOf(t, methodClass(t, vmMethod), *instance)) { - throwNew(t, Machine::IllegalArgumentExceptionType); + if (instance and not instanceOf(t, vmMethod->class_(), *instance)) { + throwNew(t, GcIllegalArgumentException::Type); } - return reinterpret_cast - (makeLocalReference - (t, invoke - (t, vmMethod, instance ? *instance : 0, args ? *args : 0))); + return reinterpret_cast( + makeLocalReference(t, + invoke(t, + vmMethod, + instance ? *instance : 0, + args ? reinterpret_cast(*args) : 0))); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_InvokeMethod)(Thread* t, jobject method, jobject instance, - jobjectArray args) + EXPORT(JVM_InvokeMethod)(Thread* t, + jobject method, + jobject instance, + jobjectArray args) { - uintptr_t arguments[] = { reinterpret_cast(method), - reinterpret_cast(instance), - reinterpret_cast(args) }; + uintptr_t arguments[] = {reinterpret_cast(method), + reinterpret_cast(instance), + reinterpret_cast(args)}; return reinterpret_cast(run(t, jvmInvokeMethod, arguments)); } -uint64_t -jvmNewInstanceFromConstructor(Thread* t, uintptr_t* arguments) +uint64_t jvmNewInstanceFromConstructor(Thread* t, uintptr_t* arguments) { jobject constructor = reinterpret_cast(arguments[0]); jobjectArray args = reinterpret_cast(arguments[1]); - object instance = make - (t, jclassVmClass(t, jconstructorClazz(t, *constructor))); + object instance + = make(t, cast(t, *constructor)->clazz()->vmClass()); PROTECT(t, instance); - object method = arrayBody - (t, classMethodTable - (t, jclassVmClass(t, jconstructorClazz(t, *constructor))), - jconstructorSlot(t, *constructor)); + GcMethod* method = cast( + t, + cast(t, + cast(t, *constructor) + ->clazz() + ->vmClass() + ->methodTable()) + ->body()[cast(t, *constructor)->slot()]); - invoke(t, method, instance, args ? *args : 0); + invoke(t, method, instance, args ? reinterpret_cast(*args) : 0); return reinterpret_cast(makeLocalReference(t, instance)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_NewInstanceFromConstructor)(Thread* t, jobject constructor, - jobjectArray args) + EXPORT(JVM_NewInstanceFromConstructor)(Thread* t, + jobject constructor, + jobjectArray args) { - uintptr_t arguments[] = { reinterpret_cast(constructor), - reinterpret_cast(args) }; + uintptr_t arguments[] = {reinterpret_cast(constructor), + reinterpret_cast(args)}; - return reinterpret_cast - (run(t, jvmNewInstanceFromConstructor, arguments)); + return reinterpret_cast( + run(t, jvmNewInstanceFromConstructor, arguments)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetClassConstantPool)(Thread* t, jclass c) + EXPORT(JVM_GetClassConstantPool)(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - object vmClass = jclassVmClass(t, *c); - object addendum = classAddendum(t, vmClass); + GcClass* vmClass = (*c)->vmClass(); + GcClassAddendum* addendum = vmClass->addendum(); object pool; if (addendum) { - pool = addendumPool(t, addendum); + pool = addendum->pool(); } else { pool = 0; } if (pool == 0) { - pool = classRuntimeDataPool(t, getClassRuntimeData(t, vmClass)); + pool = getClassRuntimeData(t, vmClass)->pool(); } return makeLocalReference(t, makeConstantPool(t, pool)); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_ConstantPoolGetSize)(Thread* t, jobject, jobject pool) + EXPORT(JVM_ConstantPoolGetSize)(Thread* t, jobject, jobject pool) { - if (pool == 0) return 0; + if (pool == 0) + return 0; ENTER(t, Thread::ActiveState); - return singletonCount(t, *pool); + return singletonCount(t, cast(t, *pool)); } extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_ConstantPoolGetClassAt)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetClassAt)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jclass JNICALL -EXPORT(JVM_ConstantPoolGetClassAtIfLoaded)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetClassAtIfLoaded)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_ConstantPoolGetMethodAt)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetMethodAt)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_ConstantPoolGetMethodAtIfLoaded)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetMethodAtIfLoaded)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_ConstantPoolGetFieldAt)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetFieldAt)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_ConstantPoolGetFieldAtIfLoaded)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetFieldAtIfLoaded)(Thread*, jobject, jobject, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_ConstantPoolGetMemberRefInfoAt)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetMemberRefInfoAt)(Thread*, jobject, jobject, jint) +{ + abort(); +} -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_ConstantPoolGetIntAt)(Thread* t, jobject, jobject pool, jint index) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT( + JVM_ConstantPoolGetIntAt)(Thread* t, jobject, jobject pool, jint index) { ENTER(t, Thread::ActiveState); - return singletonValue(t, *pool, index - 1); + return singletonValue(t, cast(t, *pool), index - 1); } -extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_ConstantPoolGetLongAt)(Thread* t, jobject, jobject pool, jint index) +extern "C" AVIAN_EXPORT jlong JNICALL EXPORT( + JVM_ConstantPoolGetLongAt)(Thread* t, jobject, jobject pool, jint index) { ENTER(t, Thread::ActiveState); uint64_t v; - memcpy(&v, &singletonValue(t, *pool, index - 1), 8); + memcpy(&v, &singletonValue(t, cast(t, *pool), index - 1), 8); return v; } -extern "C" AVIAN_EXPORT jfloat JNICALL -EXPORT(JVM_ConstantPoolGetFloatAt)(Thread* t, jobject, jobject pool, - jint index) +extern "C" AVIAN_EXPORT jfloat JNICALL EXPORT( + JVM_ConstantPoolGetFloatAt)(Thread* t, jobject, jobject pool, jint index) { ENTER(t, Thread::ActiveState); - return bitsToFloat(singletonValue(t, *pool, index - 1)); + return bitsToFloat(singletonValue(t, cast(t, *pool), index - 1)); } -extern "C" AVIAN_EXPORT jdouble JNICALL -EXPORT(JVM_ConstantPoolGetDoubleAt)(Thread* t, jobject, jobject pool, - jint index) +extern "C" AVIAN_EXPORT jdouble JNICALL EXPORT( + JVM_ConstantPoolGetDoubleAt)(Thread* t, jobject, jobject pool, jint index) { ENTER(t, Thread::ActiveState); double v; - memcpy(&v, &singletonValue(t, *pool, index - 1), 8); + memcpy(&v, &singletonValue(t, cast(t, *pool), index - 1), 8); return v; } extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_ConstantPoolGetStringAt)(Thread*, jobject, jobject, jint) -{ abort(); } + EXPORT(JVM_ConstantPoolGetStringAt)(Thread*, jobject, jobject, jint) +{ + abort(); +} -uint64_t -jvmConstantPoolGetUTF8At(Thread* t, uintptr_t* arguments) +uint64_t jvmConstantPoolGetUTF8At(Thread* t, uintptr_t* arguments) { jobject pool = reinterpret_cast(arguments[0]); jint index = arguments[1]; - object array = parseUtf8(t, singletonObject(t, *pool, index - 1)); + object array = parseUtf8( + t, + cast( + t, singletonObject(t, cast(t, *pool), index - 1))); - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeString - (t, array, 0, fieldAtOffset(array, BytesPerWord) - 1))); + return reinterpret_cast(makeLocalReference( + t, + t->m->classpath->makeString( + t, array, 0, fieldAtOffset(array, BytesPerWord) - 1))); } -extern "C" AVIAN_EXPORT jstring JNICALL -EXPORT(JVM_ConstantPoolGetUTF8At)(Thread* t, jobject, jobject pool, jint index) +extern "C" AVIAN_EXPORT jstring JNICALL EXPORT( + JVM_ConstantPoolGetUTF8At)(Thread* t, jobject, jobject pool, jint index) { - uintptr_t arguments[] = { reinterpret_cast(pool), - static_cast(index) }; + uintptr_t arguments[] + = {reinterpret_cast(pool), static_cast(index)}; - return reinterpret_cast - (run(t, jvmConstantPoolGetUTF8At, arguments)); + return reinterpret_cast(run(t, jvmConstantPoolGetUTF8At, arguments)); } -void -maybeWrap(Thread* t, bool wrapException) +void maybeWrap(Thread* t, bool wrapException) { - if (t->exception - and wrapException - and not (instanceOf(t, type(t, Machine::ErrorType), t->exception) - or instanceOf - (t, type(t, Machine::RuntimeExceptionType), t->exception))) - { - object exception = t->exception; + if (t->exception and wrapException + and not(instanceOf(t, type(t, GcError::Type), t->exception) + or instanceOf( + t, type(t, GcRuntimeException::Type), t->exception))) { + GcThrowable* exception = t->exception; t->exception = 0; PROTECT(t, exception); - object paeClass = resolveClass - (t, root(t, Machine::BootLoader), - "java/security/PrivilegedActionException"); + GcClass* paeClass = resolveClass( + t, roots(t)->bootLoader(), "java/security/PrivilegedActionException"); PROTECT(t, paeClass); - object paeConstructor = resolveMethod - (t, paeClass, "", "(Ljava/lang/Exception;)V"); + GcMethod* paeConstructor + = resolveMethod(t, paeClass, "", "(Ljava/lang/Exception;)V"); PROTECT(t, paeConstructor); - object result = make(t, paeClass); + GcThrowable* result = cast(t, make(t, paeClass)); PROTECT(t, result); - + t->m->processor->invoke(t, paeConstructor, result, exception); t->exception = result; } } -uint64_t -jvmDoPrivileged(Thread* t, uintptr_t* arguments) +uint64_t jvmDoPrivileged(Thread* t, uintptr_t* arguments) { jobject action = reinterpret_cast(arguments[0]); jboolean wrapException = arguments[1]; @@ -4643,187 +5003,285 @@ jvmDoPrivileged(Thread* t, uintptr_t* arguments) // todo: cache these class and method lookups in the t->m->classpath // object: - object privilegedAction = resolveClass - (t, root(t, Machine::BootLoader), "java/security/PrivilegedAction"); + GcClass* privilegedAction = resolveClass( + t, roots(t)->bootLoader(), "java/security/PrivilegedAction"); - object method; + GcMethod* method; if (instanceOf(t, privilegedAction, *action)) { - method = resolveMethod - (t, privilegedAction, "run", "()Ljava/lang/Object;"); + method = resolveMethod(t, privilegedAction, "run", "()Ljava/lang/Object;"); } else { - object privilegedExceptionAction = resolveClass - (t, root(t, Machine::BootLoader), - "java/security/PrivilegedExceptionAction"); + GcClass* privilegedExceptionAction = resolveClass( + t, roots(t)->bootLoader(), "java/security/PrivilegedExceptionAction"); - method = resolveMethod - (t, privilegedExceptionAction, "run", "()Ljava/lang/Object;"); + method = resolveMethod( + t, privilegedExceptionAction, "run", "()Ljava/lang/Object;"); } THREAD_RESOURCE(t, jboolean, wrapException, maybeWrap(t, wrapException)); - return reinterpret_cast - (makeLocalReference(t, t->m->processor->invoke(t, method, *action))); + return reinterpret_cast( + makeLocalReference(t, t->m->processor->invoke(t, method, *action))); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_DoPrivileged) -(Thread* t, jclass, jobject action, jobject, jboolean wrapException) + EXPORT(JVM_DoPrivileged)(Thread* t, + jclass, + jobject action, + jobject, + jboolean wrapException) { - uintptr_t arguments[] = { reinterpret_cast(action), - wrapException }; + uintptr_t arguments[] = {reinterpret_cast(action), wrapException}; return reinterpret_cast(run(t, jvmDoPrivileged, arguments)); } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetInheritedAccessControlContext)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetInheritedAccessControlContext)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_GetStackAccessControlContext)(Thread*, jclass) + EXPORT(JVM_GetStackAccessControlContext)(Thread*, jclass) { return 0; } -extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_RegisterSignal)(jint, void*) { abort(); } +extern "C" AVIAN_EXPORT void* JNICALL EXPORT(JVM_RegisterSignal)(jint, void*) +{ + abort(); +} -extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_RaiseSignal)(jint) { abort(); } +extern "C" AVIAN_EXPORT jboolean JNICALL EXPORT(JVM_RaiseSignal)(jint) +{ + abort(); +} -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_FindSignal)(const char*) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_FindSignal)(const char*) { return -1; } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_DesiredAssertionStatus)(Thread*, jclass, jclass) + EXPORT(JVM_DesiredAssertionStatus)(Thread*, jclass, jclass) { return false; } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_AssertionStatusDirectives)(Thread*, jclass) { abort(); } + EXPORT(JVM_AssertionStatusDirectives)(Thread*, jclass) +{ + abort(); +} -extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_SupportsCX8)() +extern "C" AVIAN_EXPORT jboolean JNICALL EXPORT(JVM_SupportsCX8)() { return true; } extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetClassNameUTF)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetClassNameUTF)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GetClassCPTypes)(Thread*, jclass, unsigned char*) { abort(); } + EXPORT(JVM_GetClassCPTypes)(Thread*, jclass, unsigned char*) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetClassCPEntriesCount)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetClassCPEntriesCount)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetClassFieldsCount)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetClassFieldsCount)(Thread*, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetClassMethodsCount)(Thread*, jclass) { abort(); } + EXPORT(JVM_GetClassMethodsCount)(Thread*, jclass) +{ + abort(); +} + +extern "C" AVIAN_EXPORT void JNICALL EXPORT( + JVM_GetMethodIxExceptionIndexes)(Thread*, jclass, jint, unsigned short*) +{ + abort(); +} + +extern "C" AVIAN_EXPORT jint JNICALL + EXPORT(JVM_GetMethodIxExceptionsCount)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GetMethodIxExceptionIndexes)(Thread*, jclass, jint, - unsigned short*) { abort(); } + EXPORT(JVM_GetMethodIxByteCode)(Thread*, jclass, jint, unsigned char*) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxExceptionsCount)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetMethodIxByteCodeLength)(Thread*, jclass, jint) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GetMethodIxByteCode)(Thread*, jclass, jint, - unsigned char*) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_GetMethodIxExceptionTableEntry)( + Thread*, + jclass, + jint, + jint, + local::JVM_ExceptionTableEntryType*) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxByteCodeLength)(Thread*, jclass, jint) { abort(); } - -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GetMethodIxExceptionTableEntry)(Thread*, jclass, jint, - jint, - local::JVM_ExceptionTableEntryType*) -{ abort(); } + EXPORT(JVM_GetMethodIxExceptionTableLength)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxExceptionTableLength)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_GetFieldIxModifiers)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetFieldIxModifiers)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_GetMethodIxModifiers)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxModifiers)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_GetMethodIxLocalsCount)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxLocalsCount)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_GetMethodIxArgsSize)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxArgsSize)(Thread*, jclass, int) { abort(); } - -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetMethodIxMaxStack)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_GetMethodIxMaxStack)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsConstructorIx)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_IsConstructorIx)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsVMGeneratedMethodIx)(Thread*, jclass, int) { abort(); } + EXPORT(JVM_IsVMGeneratedMethodIx)(Thread*, jclass, int) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetMethodIxNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetMethodIxNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetMethodIxSignatureUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetMethodIxSignatureUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPFieldNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPFieldNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPMethodNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPMethodNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPMethodSignatureUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPMethodSignatureUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPFieldSignatureUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPFieldSignatureUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPClassNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPClassNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPFieldClassNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPFieldClassNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT const char* JNICALL -EXPORT(JVM_GetCPMethodClassNameUTF)(Thread*, jclass, jint) { abort(); } + EXPORT(JVM_GetCPMethodClassNameUTF)(Thread*, jclass, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetCPFieldModifiers)(Thread*, jclass, int, jclass) { abort(); } + EXPORT(JVM_GetCPFieldModifiers)(Thread*, jclass, int, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetCPMethodModifiers)(Thread*, jclass, int, jclass) { abort(); } + EXPORT(JVM_GetCPMethodModifiers)(Thread*, jclass, int, jclass) +{ + abort(); +} -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_ReleaseUTF)(const char*) { abort(); } +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_ReleaseUTF)(const char*) +{ + abort(); +} extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_IsSameClassPackage)(Thread*, jclass, jclass) { abort(); } + EXPORT(JVM_IsSameClassPackage)(Thread*, jclass, jclass) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetLastErrorString)(char* dst, int length) + EXPORT(JVM_GetLastErrorString)(char* dst, int length) { strncpy(dst, strerror(errno), length); return strlen(dst); } -extern "C" AVIAN_EXPORT char* JNICALL -EXPORT(JVM_NativePath)(char* path) +extern "C" AVIAN_EXPORT char* JNICALL EXPORT(JVM_NativePath)(char* path) { return path; } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Open)(const char* path, jint flags, jint mode) + EXPORT(JVM_Open)(const char* path, jint flags, jint mode) { int r = OPEN(path, flags & 0xFFFF, mode); if (r == -1) { @@ -4833,59 +5291,58 @@ EXPORT(JVM_Open)(const char* path, jint flags, jint mode) } } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Close)(jint fd) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_Close)(jint fd) { return CLOSE(fd); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Read)(jint fd, char* dst, jint length) + EXPORT(JVM_Read)(jint fd, char* dst, jint length) { return READ(fd, dst, length); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Write)(jint fd, char* src, jint length) + EXPORT(JVM_Write)(jint fd, char* src, jint length) { return WRITE(fd, src, length); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Available)(jint fd, jlong* result) + EXPORT(JVM_Available)(jint fd, jlong* result) { struct STAT buffer; int n; if (FSTAT(fd, &buffer) >= 0 - and (S_ISCHR(buffer.st_mode) - or S_ISFIFO(buffer.st_mode) - or S_ISSOCK(buffer.st_mode)) - and local::pipeAvailable(fd, &n)) - { + and (S_ISCHR(buffer.st_mode) or S_ISFIFO(buffer.st_mode) + or S_ISSOCK(buffer.st_mode)) and local::pipeAvailable(fd, &n)) { *result = n; return 1; } int current = LSEEK(fd, 0, SEEK_CUR); - if (current == -1) return 0; + if (current == -1) + return 0; int end = LSEEK(fd, 0, SEEK_END); - if (end == -1) return 0; + if (end == -1) + return 0; - if (LSEEK(fd, current, SEEK_SET) == -1) return 0; + if (LSEEK(fd, current, SEEK_SET) == -1) + return 0; *result = end - current; return 1; } extern "C" AVIAN_EXPORT jlong JNICALL -EXPORT(JVM_Lseek)(jint fd, jlong offset, jint seek) + EXPORT(JVM_Lseek)(jint fd, jlong offset, jint seek) { return LSEEK(fd, offset, seek); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SetLength)(jint fd, jlong length) + EXPORT(JVM_SetLength)(jint fd, jlong length) { #ifdef PLATFORM_WINDOWS HANDLE h = reinterpret_cast(_get_osfhandle(fd)); @@ -4912,8 +5369,7 @@ EXPORT(JVM_SetLength)(jint fd, jlong length) #endif } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Sync)(jint fd) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_Sync)(jint fd) { #ifdef PLATFORM_WINDOWS HANDLE h = reinterpret_cast(_get_osfhandle(fd)); @@ -4933,8 +5389,7 @@ EXPORT(JVM_Sync)(jint fd) #endif } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_InitializeSocketLibrary)() +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_InitializeSocketLibrary)() { #ifdef PLATFORM_WINDOWS static bool wsaInitialized = false; @@ -4952,13 +5407,12 @@ EXPORT(JVM_InitializeSocketLibrary)() } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Socket)(jint domain, jint type, jint protocol) + EXPORT(JVM_Socket)(jint domain, jint type, jint protocol) { return socket(domain, type, protocol); } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SocketClose)(jint socket) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_SocketClose)(jint socket) { #ifdef PLATFORM_WINDOWS return closesocket(socket); @@ -4968,43 +5422,49 @@ EXPORT(JVM_SocketClose)(jint socket) } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SocketShutdown)(jint socket, jint how) + EXPORT(JVM_SocketShutdown)(jint socket, jint how) { return shutdown(socket, how); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Recv)(jint socket, char* dst, jint count, jint flags) + EXPORT(JVM_Recv)(jint socket, char* dst, jint count, jint flags) { return recv(socket, dst, count, flags); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Send)(jint socket, char* src, jint count, jint flags) + EXPORT(JVM_Send)(jint socket, char* src, jint count, jint flags) { return send(socket, src, count, flags); } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Timeout)(int, long) { abort(); } +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_Timeout)(int, long) +{ + abort(); +} -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Listen)(jint socket, jint count) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_Listen)(jint socket, jint count) { return listen(socket, count); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Connect)(jint socket, sockaddr* address, jint addressLength) + EXPORT(JVM_Connect)(jint socket, sockaddr* address, jint addressLength) { return connect(socket, address, addressLength); } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Bind)(jint, struct sockaddr*, jint) { abort(); } + EXPORT(JVM_Bind)(jint, struct sockaddr*, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_Accept)(jint socket, struct sockaddr* address, jint* addressLength) + EXPORT(JVM_Accept)(jint socket, + struct sockaddr* address, + jint* addressLength) { socklen_t length = *addressLength; int r = accept(socket, address, &length); @@ -5013,15 +5473,19 @@ EXPORT(JVM_Accept)(jint socket, struct sockaddr* address, jint* addressLength) } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_RecvFrom)(jint, char*, int, - int, struct sockaddr*, int*) { abort(); } + EXPORT(JVM_RecvFrom)(jint, char*, int, int, struct sockaddr*, int*) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SendTo)(jint, char*, int, - int, struct sockaddr*, int) { abort(); } + EXPORT(JVM_SendTo)(jint, char*, int, int, struct sockaddr*, int) +{ + abort(); +} extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SocketAvailable)(jint socket, jint* count) + EXPORT(JVM_SocketAvailable)(jint socket, jint* count) { #ifdef PLATFORM_WINDOWS unsigned long c = *count; @@ -5034,8 +5498,9 @@ EXPORT(JVM_SocketAvailable)(jint socket, jint* count) } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetSockName)(jint socket, struct sockaddr* address, - int* addressLength) + EXPORT(JVM_GetSockName)(jint socket, + struct sockaddr* address, + int* addressLength) { socklen_t length = *addressLength; int r = getsockname(socket, address, &length); @@ -5043,9 +5508,11 @@ EXPORT(JVM_GetSockName)(jint socket, struct sockaddr* address, return r; } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_GetSockOpt)(jint socket, int level, int optionName, - char* optionValue, int* optionLength) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_GetSockOpt)(jint socket, + int level, + int optionName, + char* optionValue, + int* optionLength) { socklen_t length = *optionLength; int rv = getsockopt(socket, level, optionName, optionValue, &length); @@ -5054,29 +5521,39 @@ EXPORT(JVM_GetSockOpt)(jint socket, int level, int optionName, } extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_SetSockOpt)(jint socket, int level, int optionName, - const char* optionValue, int optionLength) + EXPORT(JVM_SetSockOpt)(jint socket, + int level, + int optionName, + const char* optionValue, + int optionLength) { return setsockopt(socket, level, optionName, optionValue, optionLength); } extern "C" AVIAN_EXPORT struct protoent* JNICALL -EXPORT(JVM_GetProtoByName)(char*) { abort(); } + EXPORT(JVM_GetProtoByName)(char*) +{ + abort(); +} extern "C" AVIAN_EXPORT struct hostent* JNICALL -EXPORT(JVM_GetHostByAddr)(const char*, int, int) { abort(); } + EXPORT(JVM_GetHostByAddr)(const char*, int, int) +{ + abort(); +} -extern "C" AVIAN_EXPORT struct hostent* JNICALL -EXPORT(JVM_GetHostByName)(char*) { abort(); } +extern "C" AVIAN_EXPORT struct hostent* JNICALL EXPORT(JVM_GetHostByName)(char*) +{ + abort(); +} extern "C" AVIAN_EXPORT int JNICALL -EXPORT(JVM_GetHostName)(char* name, int length) + EXPORT(JVM_GetHostName)(char* name, int length) { return gethostname(name, length); } -extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_RawMonitorCreate)(void) +extern "C" AVIAN_EXPORT void* JNICALL EXPORT(JVM_RawMonitorCreate)(void) { System* s = local::globalMachine->system; System::Monitor* lock; @@ -5087,66 +5564,58 @@ EXPORT(JVM_RawMonitorCreate)(void) } } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_RawMonitorDestroy)(void* lock) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_RawMonitorDestroy)(void* lock) { static_cast(lock)->dispose(); } -extern "C" AVIAN_EXPORT jint JNICALL -EXPORT(JVM_RawMonitorEnter)(void* lock) +extern "C" AVIAN_EXPORT jint JNICALL EXPORT(JVM_RawMonitorEnter)(void* lock) { - static_cast(lock)->acquire - (static_cast - (local::globalMachine->localThread->get())->systemThread); + static_cast(lock) + ->acquire(static_cast(local::globalMachine->localThread->get()) + ->systemThread); return 0; } -extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_RawMonitorExit)(void* lock) +extern "C" AVIAN_EXPORT void JNICALL EXPORT(JVM_RawMonitorExit)(void* lock) { - static_cast(lock)->release - (static_cast - (local::globalMachine->localThread->get())->systemThread); + static_cast(lock) + ->release(static_cast(local::globalMachine->localThread->get()) + ->systemThread); } -int JNICALL -GetVersion(Thread*) +int JNICALL GetVersion(Thread*) { return JMM_VERSION_1_0; } -uint64_t -getInputArgumentArray(Thread* t, uintptr_t*) +uint64_t getInputArgumentArray(Thread* t, uintptr_t*) { - object array = makeObjectArray - (t, type(t, Machine::StringType), t->m->argumentCount); + object array + = makeObjectArray(t, type(t, GcString::Type), t->m->argumentCount); PROTECT(t, array); for (unsigned i = 0; i < t->m->argumentCount; ++i) { - object argument = makeString(t, t->m->arguments[i]); - set(t, array, ArrayBody + (i * BytesPerWord), argument); + GcString* argument = makeString(t, t->m->arguments[i]); + setField(t, array, ArrayBody + (i * BytesPerWord), argument); } return reinterpret_cast(makeLocalReference(t, array)); } -jobjectArray JNICALL -GetInputArgumentArray(Thread* t) +jobjectArray JNICALL GetInputArgumentArray(Thread* t) { return reinterpret_cast(run(t, getInputArgumentArray, 0)); } -jint JNICALL -GetOptionalSupport(Thread*, jmmOptionalSupport* support) +jint JNICALL GetOptionalSupport(Thread*, jmmOptionalSupport* support) { memset(support, 0, sizeof(jmmOptionalSupport)); return 0; } -jlong JNICALL -GetLongAttribute(Thread* t, jobject, jmmLongAttribute attribute) +jlong JNICALL GetLongAttribute(Thread* t, jobject, jmmLongAttribute attribute) { const unsigned JMM_JVM_INIT_DONE_TIME_MS = 7; @@ -5159,8 +5628,7 @@ GetLongAttribute(Thread* t, jobject, jmmLongAttribute attribute) } } -jboolean JNICALL -GetBoolAttribute(Thread* t, jmmBoolAttribute attribute) +jboolean JNICALL GetBoolAttribute(Thread* t, jmmBoolAttribute attribute) { const unsigned JMM_THREAD_CPU_TIME = 24; const unsigned JMM_THREAD_ALLOCATED_MEMORY = 25; @@ -5175,47 +5643,44 @@ GetBoolAttribute(Thread* t, jmmBoolAttribute attribute) } } -uint64_t -getMemoryManagers(Thread* t, uintptr_t*) +uint64_t getMemoryManagers(Thread* t, uintptr_t*) { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), - "java/lang/management/MemoryManagerMXBean"), 0))); + return reinterpret_cast(makeLocalReference( + t, + makeObjectArray(t, + resolveClass(t, + roots(t)->bootLoader(), + "java/lang/management/MemoryManagerMXBean"), + 0))); } -jobjectArray JNICALL -GetMemoryManagers(Thread* t, jobject) +jobjectArray JNICALL GetMemoryManagers(Thread* t, jobject) { return reinterpret_cast(run(t, getMemoryManagers, 0)); } -uint64_t -getMemoryPools(Thread* t, uintptr_t*) +uint64_t getMemoryPools(Thread* t, uintptr_t*) { - return reinterpret_cast - (makeLocalReference - (t, makeObjectArray - (t, resolveClass - (t, root(t, Machine::BootLoader), - "java/lang/management/MemoryPoolMXBean"), 0))); + return reinterpret_cast(makeLocalReference( + t, + makeObjectArray(t, + resolveClass(t, + roots(t)->bootLoader(), + "java/lang/management/MemoryPoolMXBean"), + 0))); } -jobjectArray JNICALL -GetMemoryPools(Thread* t, jobject) +jobjectArray JNICALL GetMemoryPools(Thread* t, jobject) { return reinterpret_cast(run(t, getMemoryPools, 0)); } -extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_GetManagement)(jint version) +extern "C" AVIAN_EXPORT void* JNICALL EXPORT(JVM_GetManagement)(jint version) { if (version == JMM_VERSION_1_0) { - JmmInterface* interface - = &(static_cast - (local::globalMachine->classpath)->jmmInterface); + JmmInterface* interface = &(static_cast( + local::globalMachine->classpath) + ->jmmInterface); memset(interface, 0, sizeof(JmmInterface)); @@ -5227,52 +5692,60 @@ EXPORT(JVM_GetManagement)(jint version) interface->GetMemoryPools = GetMemoryPools; interface->GetInputArgumentArray = GetInputArgumentArray; - return interface; + return interface; } else { return 0; } } extern "C" AVIAN_EXPORT jobject JNICALL -EXPORT(JVM_InitAgentProperties)(Thread*, jobject) { abort(); } + EXPORT(JVM_InitAgentProperties)(Thread*, jobject) +{ + abort(); +} -uint64_t -getEnclosingMethodInfo(Thread* t, uintptr_t* arguments) +uint64_t getEnclosingMethodInfo(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); - object class_ = jclassVmClass(t, *c); + GcClass* class_ = (*c)->vmClass(); PROTECT(t, class_); - object addendum = classAddendum(t, class_); + GcClassAddendum* addendum = class_->addendum(); if (addendum) { - object enclosingClass = classAddendumEnclosingClass(t, addendum); + object enclosingClass = addendum->enclosingClass(); if (enclosingClass) { PROTECT(t, enclosingClass); - object array = makeObjectArray(t, type(t, Machine::JobjectType), 3); + object array = makeObjectArray(t, type(t, GcJobject::Type), 3); PROTECT(t, array); - enclosingClass = getJClass - (t, resolveClass(t, classLoader(t, class_), enclosingClass)); - - set(t, array, ArrayBody, enclosingClass); + enclosingClass = getJClass( + t, + resolveClass( + t, class_->loader(), cast(t, enclosingClass))); - object enclosingMethod = classAddendumEnclosingMethod(t, addendum); + setField(t, array, ArrayBody, enclosingClass); + + GcPair* enclosingMethod = cast(t, addendum->enclosingMethod()); if (enclosingMethod) { PROTECT(t, enclosingMethod); - object name = t->m->classpath->makeString - (t, pairFirst(t, enclosingMethod), 0, - byteArrayLength(t, pairFirst(t, enclosingMethod)) - 1); + GcString* name = t->m->classpath->makeString( + t, + enclosingMethod->first(), + 0, + cast(t, enclosingMethod->first())->length() - 1); - set(t, array, ArrayBody + BytesPerWord, name); + setField(t, array, ArrayBody + BytesPerWord, name); - object spec = t->m->classpath->makeString - (t, pairSecond(t, enclosingMethod), 0, - byteArrayLength(t, pairSecond(t, enclosingMethod)) - 1); + GcString* spec = t->m->classpath->makeString( + t, + enclosingMethod->second(), + 0, + cast(t, enclosingMethod->second())->length() - 1); - set(t, array, ArrayBody + (2 * BytesPerWord), spec); + setField(t, array, ArrayBody + (2 * BytesPerWord), spec); } return reinterpret_cast(makeLocalReference(t, array)); @@ -5281,55 +5754,69 @@ getEnclosingMethodInfo(Thread* t, uintptr_t* arguments) return 0; } - extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetEnclosingMethodInfo)(Thread* t, jclass c) + EXPORT(JVM_GetEnclosingMethodInfo)(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; - return reinterpret_cast - (run(t, getEnclosingMethodInfo, arguments)); + return reinterpret_cast( + run(t, getEnclosingMethodInfo, arguments)); } extern "C" AVIAN_EXPORT jintArray JNICALL -EXPORT(JVM_GetThreadStateValues)(JNIEnv*, jint) { abort(); } + EXPORT(JVM_GetThreadStateValues)(JNIEnv*, jint) +{ + abort(); +} extern "C" AVIAN_EXPORT jobjectArray JNICALL -EXPORT(JVM_GetThreadStateNames)(JNIEnv*, jint, jintArray) { abort(); } + EXPORT(JVM_GetThreadStateNames)(JNIEnv*, jint, jintArray) +{ + abort(); +} extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_GetVersionInfo)(JNIEnv*, local::jvm_version_info* info, size_t size) + EXPORT(JVM_GetVersionInfo)(JNIEnv*, + local::jvm_version_info* info, + size_t size) { memset(info, 0, size); info->jvm_version = 0x01070000; } extern "C" AVIAN_EXPORT jboolean JNICALL -EXPORT(JVM_CX8Field)(JNIEnv*, jobject*, jfieldID*, jlong, jlong) -{ abort(); } + EXPORT(JVM_CX8Field)(JNIEnv*, jobject*, jfieldID*, jlong, jlong) +{ + abort(); +} extern "C" AVIAN_EXPORT void JNICALL -EXPORT(JVM_SetNativeThreadName)(JNIEnv*, jobject, jstring) { abort(); } + EXPORT(JVM_SetNativeThreadName)(JNIEnv*, jobject, jstring) +{ + abort(); +} -} // namespace local +} // namespace local -} // namespace +} // namespace -extern "C" AVIAN_EXPORT int -jio_vsnprintf(char* dst, size_t size, const char* format, va_list a) +extern "C" AVIAN_EXPORT int jio_vsnprintf(char* dst, + size_t size, + const char* format, + va_list a) { return vm::vsnprintf(dst, size, format, a); } -extern "C" AVIAN_EXPORT int -jio_vfprintf(FILE* stream, const char* format, va_list a) +extern "C" AVIAN_EXPORT int jio_vfprintf(FILE* stream, + const char* format, + va_list a) { return vfprintf(stream, format, a); } #ifdef PLATFORM_WINDOWS -extern "C" AVIAN_EXPORT void* JNICALL -EXPORT(JVM_GetThreadInterruptEvent)() +extern "C" AVIAN_EXPORT void* JNICALL EXPORT(JVM_GetThreadInterruptEvent)() { // hack: We don't want to expose thread interruption implementation // details, so we give the class library a fake event to play with. @@ -5342,26 +5829,29 @@ EXPORT(JVM_GetThreadInterruptEvent)() return fake; } -namespace { HMODULE jvmHandle = 0; } +namespace { +HMODULE jvmHandle = 0; +} extern "C" int JDK_InitJvmHandle() { jvmHandle = GetModuleHandle(0); return jvmHandle != 0; } - + extern "C" void* JDK_FindJvmEntry(const char* name) { return voidPointer(GetProcAddress(jvmHandle, name)); } -# ifdef AVIAN_OPENJDK_SRC +#ifdef AVIAN_OPENJDK_SRC extern "C" char* findJavaTZ_md(const char*, const char*); extern "C" AVIAN_EXPORT int64_t JNICALL -Avian_java_util_TimeZone_getSystemTimeZoneID -(Thread* t, object, uintptr_t* arguments) + Avian_java_util_TimeZone_getSystemTimeZoneID(Thread* t, + object, + uintptr_t* arguments) { // On Windows, findJavaTZ_md loads tzmappings from the filesystem // using fopen, so we have no opportunity to make it read straight @@ -5371,7 +5861,7 @@ Avian_java_util_TimeZone_getSystemTimeZoneID // implementing findJavaTZ_md ourselves from scratch, but that would // be a lot of code to implement and maintain. - object country = reinterpret_cast(arguments[1]); + object country = arguments[1]; THREAD_RUNTIME_ARRAY(t, char, countryChars, stringLength(t, country) + 1); stringChars(t, country, RUNTIME_ARRAY_BODY(countryChars)); @@ -5404,7 +5894,7 @@ Avian_java_util_TimeZone_getSystemTimeZoneID return 0; } - THREAD_RESOURCE(t, char*, tmpDir, rmdir(tmpDir)); + THREAD_RESOURCE(t, char*, tmpDir, rmdir(tmpDir)); char libDir[MAX_PATH + 1]; vm::snprintf(libDir, MAX_PATH, "%s/lib", tmpDir); @@ -5412,7 +5902,7 @@ Avian_java_util_TimeZone_getSystemTimeZoneID return 0; } - THREAD_RESOURCE(t, char*, libDir, rmdir(libDir)); + THREAD_RESOURCE(t, char*, libDir, rmdir(libDir)); char file[MAX_PATH + 1]; vm::snprintf(file, MAX_PATH, "%s/tzmappings", libDir); @@ -5420,13 +5910,12 @@ Avian_java_util_TimeZone_getSystemTimeZoneID if (out == 0) { return 0; } - - THREAD_RESOURCE(t, char*, file, unlink(file)); + + THREAD_RESOURCE(t, char*, file, unlink(file)); THREAD_RESOURCE(t, FILE*, out, fclose(out)); if (fwrite(r->start(), 1, r->length(), out) != r->length() - or fflush(out) != 0) - { + or fflush(out) != 0) { return 0; } @@ -5439,9 +5928,11 @@ Avian_java_util_TimeZone_getSystemTimeZoneID return 0; } } -# else // not AVIAN_OPENJDK_SRC -extern "C" AVIAN_EXPORT int -jio_snprintf(char* dst, size_t size, const char* format, ...) +#else // not AVIAN_OPENJDK_SRC +extern "C" AVIAN_EXPORT int jio_snprintf(char* dst, + size_t size, + const char* format, + ...) { va_list a; va_start(a, format); @@ -5453,8 +5944,7 @@ jio_snprintf(char* dst, size_t size, const char* format, ...) return r; } -extern "C" AVIAN_EXPORT int -jio_fprintf(FILE* stream, const char* format, ...) +extern "C" AVIAN_EXPORT int jio_fprintf(FILE* stream, const char* format, ...) { va_list a; va_start(a, format); @@ -5465,5 +5955,5 @@ jio_fprintf(FILE* stream, const char* format, ...) return r; } -# endif // not AVIAN_OPENJDK_SRC -#endif // PLATFORM_WINDOWS +#endif // not AVIAN_OPENJDK_SRC +#endif // PLATFORM_WINDOWS diff --git a/src/codegen/compiler.cpp b/src/codegen/compiler.cpp index 16972c61c7..3a72d36176 100644 --- a/src/codegen/compiler.cpp +++ b/src/codegen/compiler.cpp @@ -47,34 +47,46 @@ const unsigned StealRegisterReserveCount = 2; // compare instruction: const unsigned ResolveRegisterReserveCount = (TargetBytesPerWord == 8 ? 2 : 4); -void -apply(Context* c, lir::UnaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High); +void apply(Context* c, + lir::UnaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High); -void -apply(Context* c, lir::BinaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High); - -void -apply(Context* c, lir::TernaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High, - unsigned s3Size, Site* s3Low, Site* s3High); +void apply(Context* c, + lir::BinaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High); +void apply(Context* c, + lir::TernaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High, + unsigned s3Size, + Site* s3Low, + Site* s3High); class ConstantPoolNode { public: - ConstantPoolNode(Promise* promise): promise(promise), next(0) { } + ConstantPoolNode(Promise* promise) : promise(promise), next(0) + { + } Promise* promise; ConstantPoolNode* next; }; -Read* -live(Context* c UNUSED, Value* v) +Read* live(Context* c UNUSED, Value* v) { - assert(c, v->buddy->hasBuddy(c, v)); + assertT(c, v->buddy->hasBuddy(c, v)); Value* p = v; do { @@ -87,18 +99,16 @@ live(Context* c UNUSED, Value* v) return 0; } -unsigned -sitesToString(Context* c, Value* v, char* buffer, unsigned size); +unsigned sitesToString(Context* c, Value* v, char* buffer, unsigned size); -void -deadWord(Context* c, Value* v) +void deadWord(Context* c, Value* v) { Value* nextWord = v->nextWord; - assert(c, nextWord != v); + assertT(c, nextWord != v); for (SiteIterator it(c, v, true, false); it.hasMore();) { Site* s = it.next(); - + if (s->registerSize(c) > TargetBytesPerWord) { it.remove(c); nextWord->addSite(c, s); @@ -106,11 +116,10 @@ deadWord(Context* c, Value* v) } } -void -deadBuddy(Context* c, Value* v, Read* r UNUSED) +void deadBuddy(Context* c, Value* v, Read* r UNUSED) { - assert(c, v->buddy != v); - assert(c, r); + assertT(c, v->buddy != v); + assertT(c, r); if (DebugBuddies) { fprintf(stderr, "remove dead buddy %p from", v); @@ -120,32 +129,37 @@ deadBuddy(Context* c, Value* v, Read* r UNUSED) fprintf(stderr, "\n"); } - assert(c, v->buddy); + assertT(c, v->buddy); Value* next = v->buddy; v->buddy = v; Value* p = next; - while (p->buddy != v) p = p->buddy; + while (p->buddy != v) + p = p->buddy; p->buddy = next; - assert(c, p->buddy); + assertT(c, p->buddy); for (SiteIterator it(c, v, false, false); it.hasMore();) { Site* s = it.next(); it.remove(c); - + next->addSite(c, s); } } -void -popRead(Context* c, Event* e UNUSED, Value* v) +void popRead(Context* c, Event* e UNUSED, Value* v) { - assert(c, e == v->reads->event); + assertT(c, e == v->reads->event); if (DebugReads) { - fprintf(stderr, "pop read %p from %p next %p event %p (%s)\n", - v->reads, v, v->reads->next(c), e, (e ? e->name() : 0)); + fprintf(stderr, + "pop read %p from %p next %p event %p (%s)\n", + v->reads, + v, + v->reads->next(c), + e, + (e ? e->name() : 0)); } v->reads = v->reads->next(c); @@ -169,12 +183,12 @@ popRead(Context* c, Event* e UNUSED, Value* v) } } -void -addBuddy(Value* original, Value* buddy) +void addBuddy(Value* original, Value* buddy) { buddy->buddy = original; Value* p = original; - while (p->buddy != original) p = p->buddy; + while (p->buddy != original) + p = p->buddy; p->buddy = buddy; if (DebugBuddies) { @@ -186,37 +200,34 @@ addBuddy(Value* original, Value* buddy) } } -void -move(Context* c, Value* value, Site* src, Site* dst); +void move(Context* c, Value* value, Site* src, Site* dst); -unsigned -sitesToString(Context* c, Site* sites, char* buffer, unsigned size) +unsigned sitesToString(Context* c, Site* sites, char* buffer, unsigned size) { unsigned total = 0; for (Site* s = sites; s; s = s->next) { total += s->toString(c, buffer + total, size - total); if (s->next) { - assert(c, size > total + 2); + assertT(c, size > total + 2); memcpy(buffer + total, ", ", 2); total += 2; } } - assert(c, size > total); + assertT(c, size > total); buffer[total] = 0; return total; } -unsigned -sitesToString(Context* c, Value* v, char* buffer, unsigned size) +unsigned sitesToString(Context* c, Value* v, char* buffer, unsigned size) { unsigned total = 0; Value* p = v; do { if (total) { - assert(c, size > total + 2); + assertT(c, size > total + 2); memcpy(buffer + total, "; ", 2); total += 2; } @@ -234,14 +245,14 @@ sitesToString(Context* c, Value* v, char* buffer, unsigned size) return total; } -Site* -pickTargetSite(Context* c, Read* read, bool intersectRead = false, - unsigned registerReserveCount = 0, - CostCalculator* costCalculator = 0) +Site* pickTargetSite(Context* c, + Read* read, + bool intersectRead = false, + unsigned registerReserveCount = 0, + CostCalculator* costCalculator = 0) { - Target target - (pickTarget - (c, read, intersectRead, registerReserveCount, costCalculator)); + Target target( + pickTarget(c, read, intersectRead, registerReserveCount, costCalculator)); expect(c, target.cost < Target::Impossible); @@ -252,19 +263,21 @@ pickTargetSite(Context* c, Read* read, bool intersectRead = false, } } -bool -acceptMatch(Context* c, Site* s, Read*, const SiteMask& mask) +bool acceptMatch(Context* c, Site* s, Read*, const SiteMask& mask) { return s->match(c, mask); } -Site* -pickSourceSite(Context* c, Read* read, Site* target = 0, - unsigned* cost = 0, SiteMask* extraMask = 0, - bool intersectRead = true, bool includeBuddies = true, - bool includeNextWord = true, - bool (*accept)(Context*, Site*, Read*, const SiteMask&) - = acceptMatch) +Site* pickSourceSite(Context* c, + Read* read, + Site* target = 0, + unsigned* cost = 0, + SiteMask* extraMask = 0, + bool intersectRead = true, + bool includeBuddies = true, + bool includeNextWord = true, + bool (*accept)(Context*, Site*, Read*, const SiteMask&) + = acceptMatch) { SiteMask mask; @@ -279,8 +292,7 @@ pickSourceSite(Context* c, Read* read, Site* target = 0, Site* site = 0; unsigned copyCost = 0xFFFFFFFF; for (SiteIterator it(c, read->value, includeBuddies, includeNextWord); - it.hasMore();) - { + it.hasMore();) { Site* s = it.next(); if (accept(c, s, read, mask)) { unsigned v = s->copyCost(c, target); @@ -292,38 +304,45 @@ pickSourceSite(Context* c, Read* read, Site* target = 0, } if (DebugMoves and site and target) { - char srcb[256]; site->toString(c, srcb, 256); - char dstb[256]; target->toString(c, dstb, 256); - fprintf(stderr, "pick source %s to %s for %p cost %d\n", - srcb, dstb, read->value, copyCost); + char srcb[256]; + site->toString(c, srcb, 256); + char dstb[256]; + target->toString(c, dstb, 256); + fprintf(stderr, + "pick source %s to %s for %p cost %d\n", + srcb, + dstb, + read->value, + copyCost); } - if (cost) *cost = copyCost; + if (cost) + *cost = copyCost; return site; } -Site* -maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, - unsigned registerReserveCount = 0) +Site* maybeMove(Context* c, + Read* read, + bool intersectRead, + bool includeNextWord, + unsigned registerReserveCount = 0) { Value* value = read->value; unsigned size = value == value->nextWord ? TargetBytesPerWord : 8; - class MyCostCalculator: public CostCalculator { + class MyCostCalculator : public CostCalculator { public: - MyCostCalculator(Value* value, unsigned size, bool includeNextWord): - value(value), - size(size), - includeNextWord(includeNextWord) - { } + MyCostCalculator(Value* value, unsigned size, bool includeNextWord) + : value(value), size(size), includeNextWord(includeNextWord) + { + } virtual unsigned cost(Context* c, SiteMask dstMask) { OperandMask src; OperandMask tmp; - c->arch->planMove - (size, src, tmp, - OperandMask(dstMask.typeMask, dstMask.registerMask)); + c->arch->planMove( + size, src, tmp, OperandMask(dstMask.typeMask, dstMask.registerMask)); SiteMask srcMask = SiteMask::lowPart(src); for (SiteIterator it(c, value, true, includeNextWord); it.hasMore();) { @@ -341,14 +360,16 @@ maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, bool includeNextWord; } costCalculator(value, size, includeNextWord); - Site* dstSite = pickTargetSite - (c, read, intersectRead, registerReserveCount, &costCalculator); + Site* dstSite = pickTargetSite( + c, read, intersectRead, registerReserveCount, &costCalculator); OperandMask src; OperandMask tmp; - c->arch->planMove - (size, src, tmp, - OperandMask(1 << dstSite->type(c), dstSite->registerMask(c))); + c->arch->planMove( + size, + src, + tmp, + OperandMask(1 << dstSite->type(c), dstSite->registerMask(c))); SiteMask srcMask = SiteMask::lowPart(src); unsigned cost = 0xFFFFFFFF; @@ -369,20 +390,26 @@ maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, cost = v; } } - + if (cost) { if (DebugMoves) { - char srcb[256]; srcSite->toString(c, srcb, 256); - char dstb[256]; dstSite->toString(c, dstb, 256); - fprintf(stderr, "maybe move %s to %s for %p to %p\n", - srcb, dstb, value, value); + char srcb[256]; + srcSite->toString(c, srcb, 256); + char dstb[256]; + dstSite->toString(c, dstb, 256); + fprintf(stderr, + "maybe move %s to %s for %p to %p\n", + srcb, + dstb, + value, + value); } srcSite->freeze(c, value); value->addSite(c, dstSite); - - srcSite->thaw(c, value); + + srcSite->thaw(c, value); if (not srcSite->match(c, srcMask)) { srcSite->freeze(c, value); @@ -398,7 +425,7 @@ maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, value->addSite(c, tmpSite); move(c, value, srcSite, tmpSite); - + dstSite->thaw(c, value); srcSite->thaw(c, value); @@ -411,58 +438,70 @@ maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, return dstSite; } -Site* -maybeMove(Context* c, Value* v, const SiteMask& mask, bool intersectMask, - bool includeNextWord, unsigned registerReserveCount = 0) +Site* maybeMove(Context* c, + Value* v, + const SiteMask& mask, + bool intersectMask, + bool includeNextWord, + unsigned registerReserveCount = 0) { SingleRead read(mask, 0); read.value = v; read.successor_ = v; - return maybeMove - (c, &read, intersectMask, includeNextWord, registerReserveCount); + return maybeMove( + c, &read, intersectMask, includeNextWord, registerReserveCount); } -Site* -pickSiteOrMove(Context* c, Read* read, bool intersectRead, - bool includeNextWord, unsigned registerReserveCount = 0) +Site* pickSiteOrMove(Context* c, + Read* read, + bool intersectRead, + bool includeNextWord, + unsigned registerReserveCount = 0) { - Site* s = pickSourceSite - (c, read, 0, 0, 0, intersectRead, true, includeNextWord); - + Site* s + = pickSourceSite(c, read, 0, 0, 0, intersectRead, true, includeNextWord); + if (s) { return s; } else { - return maybeMove - (c, read, intersectRead, includeNextWord, registerReserveCount); + return maybeMove( + c, read, intersectRead, includeNextWord, registerReserveCount); } } -Site* -pickSiteOrMove(Context* c, Value* v, const SiteMask& mask, bool intersectMask, - bool includeNextWord, unsigned registerReserveCount = 0) +Site* pickSiteOrMove(Context* c, + Value* v, + const SiteMask& mask, + bool intersectMask, + bool includeNextWord, + unsigned registerReserveCount = 0) { SingleRead read(mask, 0); read.value = v; read.successor_ = v; - return pickSiteOrMove - (c, &read, intersectMask, includeNextWord, registerReserveCount); + return pickSiteOrMove( + c, &read, intersectMask, includeNextWord, registerReserveCount); } -void -steal(Context* c, Resource* r, Value* thief) +void steal(Context* c, Resource* r, Value* thief) { if (DebugResources) { - char resourceBuffer[256]; r->toString(c, resourceBuffer, 256); - char siteBuffer[1024]; sitesToString(c, r->value, siteBuffer, 1024); - fprintf(stderr, "%p steal %s from %p (%s)\n", - thief, resourceBuffer, r->value, siteBuffer); + char resourceBuffer[256]; + r->toString(c, resourceBuffer, 256); + char siteBuffer[1024]; + sitesToString(c, r->value, siteBuffer, 1024); + fprintf(stderr, + "%p steal %s from %p (%s)\n", + thief, + resourceBuffer, + r->value, + siteBuffer); } - if ((not (thief and thief->isBuddyOf(r->value)) - and r->value->uniqueSite(c, r->site))) - { + if ((not(thief and thief->isBuddyOf(r->value)) + and r->value->uniqueSite(c, r->site))) { r->site->freeze(c, r->value); maybeMove(c, live(c, r->value), false, true, StealRegisterReserveCount); @@ -473,35 +512,35 @@ steal(Context* c, Resource* r, Value* thief) r->value->removeSite(c, r->site); } -SiteMask -generalRegisterMask(Context* c) +SiteMask generalRegisterMask(Context* c) { - return SiteMask - (1 << lir::RegisterOperand, c->regFile->generalRegisters.mask, NoFrameIndex); + return SiteMask(1 << lir::RegisterOperand, + c->regFile->generalRegisters.mask, + NoFrameIndex); } -SiteMask -generalRegisterOrConstantMask(Context* c) +SiteMask generalRegisterOrConstantMask(Context* c) { - return SiteMask - ((1 << lir::RegisterOperand) | (1 << lir::ConstantOperand), - c->regFile->generalRegisters.mask, NoFrameIndex); + return SiteMask((1 << lir::RegisterOperand) | (1 << lir::ConstantOperand), + c->regFile->generalRegisters.mask, + NoFrameIndex); } -MultiRead* -multiRead(Context* c) +MultiRead* multiRead(Context* c) { - return new(c->zone) MultiRead; + return new (c->zone) MultiRead; } -StubRead* -stubRead(Context* c) +StubRead* stubRead(Context* c) { - return new(c->zone) StubRead; + return new (c->zone) StubRead; } -Site* -pickSite(Context* c, Value* v, Site* s, unsigned index, bool includeNextWord) +Site* pickSite(Context* c, + Value* v, + Site* s, + unsigned index, + bool includeNextWord) { for (SiteIterator it(c, v, true, includeNextWord); it.hasMore();) { Site* candidate = it.next(); @@ -513,8 +552,7 @@ pickSite(Context* c, Value* v, Site* s, unsigned index, bool includeNextWord) return 0; } -Site* -pickSiteOrMove(Context* c, Value* v, Site* s, unsigned index) +Site* pickSiteOrMove(Context* c, Value* v, Site* s, unsigned index) { Site* n = pickSite(c, v, s, index, false); if (n) { @@ -524,8 +562,7 @@ pickSiteOrMove(Context* c, Value* v, Site* s, unsigned index) return maybeMove(c, v, s->nextWordMask(c, index), true, false); } -Site* -pickSiteOrMove(Context* c, Value* v, Site* s, Site** low, Site** high) +Site* pickSiteOrMove(Context* c, Value* v, Site* s, Site** low, Site** high) { if (v->wordIndex == 0) { *low = s; @@ -538,8 +575,7 @@ pickSiteOrMove(Context* c, Value* v, Site* s, Site** low, Site** high) } } -Site* -pickSiteOrGrow(Context* c, Value* v, Site* s, unsigned index) +Site* pickSiteOrGrow(Context* c, Value* v, Site* s, unsigned index) { Site* n = pickSite(c, v, s, index, false); if (n) { @@ -551,8 +587,7 @@ pickSiteOrGrow(Context* c, Value* v, Site* s, unsigned index) return n; } -Site* -pickSiteOrGrow(Context* c, Value* v, Site* s, Site** low, Site** high) +Site* pickSiteOrGrow(Context* c, Value* v, Site* s, Site** low, Site** high) { if (v->wordIndex == 0) { *low = s; @@ -565,8 +600,7 @@ pickSiteOrGrow(Context* c, Value* v, Site* s, Site** low, Site** high) } } -bool -isHome(Value* v, int frameIndex) +bool isHome(Value* v, int frameIndex) { Value* p = v; do { @@ -579,38 +613,38 @@ isHome(Value* v, int frameIndex) return false; } -bool -acceptForResolve(Context* c, Site* s, Read* read, const SiteMask& mask) +bool acceptForResolve(Context* c, Site* s, Read* read, const SiteMask& mask) { if (acceptMatch(c, s, read, mask) and (not s->frozen(c))) { if (s->type(c) == lir::RegisterOperand) { return c->availableGeneralRegisterCount > ResolveRegisterReserveCount; } else { - assert(c, s->match(c, SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex))); + assertT(c, + s->match(c, SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex))); - return isHome(read->value, offsetToFrameIndex - (c, static_cast(s)->offset)); + return isHome(read->value, + offsetToFrameIndex(c, static_cast(s)->offset)); } } else { return false; } } -void -move(Context* c, Value* value, Site* src, Site* dst) +void move(Context* c, Value* value, Site* src, Site* dst) { if (DebugMoves) { - char srcb[256]; src->toString(c, srcb, 256); - char dstb[256]; dst->toString(c, dstb, 256); - fprintf(stderr, "move %s to %s for %p to %p\n", - srcb, dstb, value, value); + char srcb[256]; + src->toString(c, srcb, 256); + char dstb[256]; + dst->toString(c, dstb, 256); + fprintf(stderr, "move %s to %s for %p to %p\n", srcb, dstb, value, value); } - assert(c, value->findSite(dst)); + assertT(c, value->findSite(dst)); src->freeze(c, value); dst->freeze(c, value); - + unsigned srcSize; unsigned dstSize; if (value->nextWord == value) { @@ -643,14 +677,12 @@ move(Context* c, Value* value, Site* src, Site* dst) src->thaw(c, value); } -void -asAssemblerOperand(Context* c, Site* low, Site* high, - lir::Operand* result) +void asAssemblerOperand(Context* c, Site* low, Site* high, lir::Operand* result) { low->asAssemblerOperand(c, high, result); } -class OperandUnion: public lir::Operand { +class OperandUnion : public lir::Operand { public: // must be large enough and aligned properly to hold any operand // type (we'd use an actual union type here, except that classes @@ -658,79 +690,99 @@ class OperandUnion: public lir::Operand { uintptr_t padding[4]; }; -void -apply(Context* c, lir::UnaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High) +void apply(Context* c, + lir::UnaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High) { - assert(c, s1Low->type(c) == s1High->type(c)); + assertT(c, s1Low->type(c) == s1High->type(c)); lir::OperandType s1Type = s1Low->type(c); - OperandUnion s1Union; asAssemblerOperand(c, s1Low, s1High, &s1Union); + OperandUnion s1Union; + asAssemblerOperand(c, s1Low, s1High, &s1Union); - c->assembler->apply(op, - OperandInfo(s1Size, s1Type, &s1Union)); + c->assembler->apply(op, OperandInfo(s1Size, s1Type, &s1Union)); } -void -apply(Context* c, lir::BinaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High) +void apply(Context* c, + lir::BinaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High) { - assert(c, s1Low->type(c) == s1High->type(c)); - assert(c, s2Low->type(c) == s2High->type(c)); + assertT(c, s1Low->type(c) == s1High->type(c)); + assertT(c, s2Low->type(c) == s2High->type(c)); lir::OperandType s1Type = s1Low->type(c); - OperandUnion s1Union; asAssemblerOperand(c, s1Low, s1High, &s1Union); + OperandUnion s1Union; + asAssemblerOperand(c, s1Low, s1High, &s1Union); lir::OperandType s2Type = s2Low->type(c); - OperandUnion s2Union; asAssemblerOperand(c, s2Low, s2High, &s2Union); + OperandUnion s2Union; + asAssemblerOperand(c, s2Low, s2High, &s2Union); c->assembler->apply(op, - OperandInfo(s1Size, s1Type, &s1Union), - OperandInfo(s2Size, s2Type, &s2Union)); + OperandInfo(s1Size, s1Type, &s1Union), + OperandInfo(s2Size, s2Type, &s2Union)); } -void -apply(Context* c, lir::TernaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High, - unsigned s3Size, Site* s3Low, Site* s3High) +void apply(Context* c, + lir::TernaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High, + unsigned s3Size, + Site* s3Low, + Site* s3High) { - assert(c, s1Low->type(c) == s1High->type(c)); - assert(c, s2Low->type(c) == s2High->type(c)); - assert(c, s3Low->type(c) == s3High->type(c)); + assertT(c, s1Low->type(c) == s1High->type(c)); + assertT(c, s2Low->type(c) == s2High->type(c)); + assertT(c, s3Low->type(c) == s3High->type(c)); lir::OperandType s1Type = s1Low->type(c); - OperandUnion s1Union; asAssemblerOperand(c, s1Low, s1High, &s1Union); + OperandUnion s1Union; + asAssemblerOperand(c, s1Low, s1High, &s1Union); lir::OperandType s2Type = s2Low->type(c); - OperandUnion s2Union; asAssemblerOperand(c, s2Low, s2High, &s2Union); + OperandUnion s2Union; + asAssemblerOperand(c, s2Low, s2High, &s2Union); lir::OperandType s3Type = s3Low->type(c); - OperandUnion s3Union; asAssemblerOperand(c, s3Low, s3High, &s3Union); + OperandUnion s3Union; + asAssemblerOperand(c, s3Low, s3High, &s3Union); c->assembler->apply(op, - OperandInfo(s1Size, s1Type, &s1Union), - OperandInfo(s2Size, s2Type, &s2Union), - OperandInfo(s3Size, s3Type, &s3Union)); + OperandInfo(s1Size, s1Type, &s1Union), + OperandInfo(s2Size, s2Type, &s2Union), + OperandInfo(s3Size, s3Type, &s3Union)); } -void -append(Context* c, Event* e); +void append(Context* c, Event* e); -void -saveLocals(Context* c, Event* e) +void saveLocals(Context* c, Event* e) { for (unsigned li = 0; li < c->localFootprint; ++li) { Local* local = e->localsBefore + li; if (local->value) { if (DebugReads) { - fprintf(stderr, "local save read %p at %d of %d\n", - local->value, compiler::frameIndex(c, li), totalFrameSize(c)); + fprintf(stderr, + "local save read %p at %d of %d\n", + local->value, + compiler::frameIndex(c, li), + totalFrameSize(c)); } - e->addRead(c, local->value, SiteMask - (1 << lir::MemoryOperand, 0, compiler::frameIndex(c, li))); + e->addRead( + c, + local->value, + SiteMask(1 << lir::MemoryOperand, 0, compiler::frameIndex(c, li))); } } } @@ -758,7 +810,8 @@ void maybeMove(Context* c, unsigned cost = srcValue->source->copyCost(c, target); - if (srcSelectSize < dstSize) cost = 1; + if (srcSelectSize < dstSize) + cost = 1; if (cost) { // todo: let c->arch->planMove decide this: @@ -773,23 +826,28 @@ void maybeMove(Context* c, srcValue->source->thaw(c, srcValue); - bool addOffset = srcSize != srcSelectSize - and c->arch->bigEndian() - and srcValue->source->type(c) == lir::MemoryOperand; + bool addOffset = srcSize != srcSelectSize and c->arch->bigEndian() + and srcValue->source->type(c) == lir::MemoryOperand; if (addOffset) { static_cast(srcValue->source)->offset - += (srcSize - srcSelectSize); + += (srcSize - srcSelectSize); } target->freeze(c, dstValue); if (target->match(c, dstMask) and not useTemporary) { if (DebugMoves) { - char srcb[256]; srcValue->source->toString(c, srcb, 256); - char dstb[256]; target->toString(c, dstb, 256); - fprintf(stderr, "move %s to %s for %p to %p\n", - srcb, dstb, srcValue, dstValue); + char srcb[256]; + srcValue->source->toString(c, srcb, 256); + char dstb[256]; + target->toString(c, dstb, 256); + fprintf(stderr, + "move %s to %s for %p to %p\n", + srcb, + dstb, + srcValue, + dstValue); } srcValue->source->freeze(c, srcValue); @@ -807,7 +865,7 @@ void maybeMove(Context* c, } else { // pick a temporary register which is valid as both a // destination and a source for the moves we need to perform: - + dstValue->removeSite(c, target); bool thunk; @@ -819,11 +877,11 @@ void maybeMove(Context* c, src.registerMask &= c->regFile->generalRegisters.mask; } - assert(c, thunk == 0); - assert(c, dstMask.typeMask & src.typeMask & (1 << lir::RegisterOperand)); + assertT(c, thunk == 0); + assertT(c, dstMask.typeMask & src.typeMask & (1 << lir::RegisterOperand)); - Site* tmpTarget = freeRegisterSite - (c, dstMask.registerMask & src.registerMask); + Site* tmpTarget + = freeRegisterSite(c, dstMask.registerMask & src.registerMask); srcValue->source->freeze(c, srcValue); @@ -832,10 +890,16 @@ void maybeMove(Context* c, tmpTarget->freeze(c, dstValue); if (DebugMoves) { - char srcb[256]; srcValue->source->toString(c, srcb, 256); - char dstb[256]; tmpTarget->toString(c, dstb, 256); - fprintf(stderr, "move %s to %s for %p to %p\n", - srcb, dstb, srcValue, dstValue); + char srcb[256]; + srcValue->source->toString(c, srcb, 256); + char dstb[256]; + tmpTarget->toString(c, dstb, 256); + fprintf(stderr, + "move %s to %s for %p to %p\n", + srcb, + dstb, + srcValue, + dstValue); } apply(c, @@ -853,17 +917,30 @@ void maybeMove(Context* c, if (useTemporary or isStore) { if (DebugMoves) { - char srcb[256]; tmpTarget->toString(c, srcb, 256); - char dstb[256]; target->toString(c, dstb, 256); - fprintf(stderr, "move %s to %s for %p to %p\n", - srcb, dstb, srcValue, dstValue); + char srcb[256]; + tmpTarget->toString(c, srcb, 256); + char dstb[256]; + target->toString(c, dstb, 256); + fprintf(stderr, + "move %s to %s for %p to %p\n", + srcb, + dstb, + srcValue, + dstValue); } dstValue->addSite(c, target); tmpTarget->freeze(c, dstValue); - apply(c, lir::Move, dstSize, tmpTarget, tmpTarget, dstSize, target, target); + apply(c, + lir::Move, + dstSize, + tmpTarget, + tmpTarget, + dstSize, + target, + target); tmpTarget->thaw(c, dstValue); @@ -877,14 +954,16 @@ void maybeMove(Context* c, if (addOffset) { static_cast(srcValue->source)->offset - -= (srcSize - srcSelectSize); + -= (srcSize - srcSelectSize); } } else { target = srcValue->source; if (DebugMoves) { - char dstb[256]; target->toString(c, dstb, 256); - fprintf(stderr, "null move in %s for %p to %p\n", dstb, srcValue, dstValue); + char dstb[256]; + target->toString(c, dstb, 256); + fprintf( + stderr, "null move in %s for %p to %p\n", dstb, srcValue, dstValue); } } @@ -893,9 +972,11 @@ void maybeMove(Context* c, } } -Site* -pickMatchOrMove(Context* c, Read* r, Site* nextWord, unsigned index, - bool intersectRead) +Site* pickMatchOrMove(Context* c, + Read* r, + Site* nextWord, + unsigned index, + bool intersectRead) { Site* s = pickSite(c, r->value, nextWord, index, true); SiteMask mask; @@ -906,14 +987,18 @@ pickMatchOrMove(Context* c, Read* r, Site* nextWord, unsigned index, return s; } - return pickSiteOrMove - (c, r->value, mask.intersectionWith(nextWord->nextWordMask(c, index)), - true, true); + return pickSiteOrMove(c, + r->value, + mask.intersectionWith(nextWord->nextWordMask(c, index)), + true, + true); } -Site* -pickSiteOrMove(Context* c, Value* src, Value* dst, Site* nextWord, - unsigned index) +Site* pickSiteOrMove(Context* c, + Value* src, + Value* dst, + Site* nextWord, + unsigned index) { if (live(c, dst)) { Read* read = live(c, src); @@ -927,7 +1012,7 @@ pickSiteOrMove(Context* c, Value* src, Value* dst, Site* nextWord, s = maybeMove(c, read, false, true); } } - assert(c, s); + assertT(c, s); addBuddy(src, dst); @@ -941,20 +1026,18 @@ pickSiteOrMove(Context* c, Value* src, Value* dst, Site* nextWord, } } -ConstantSite* -findConstantSite(Context* c, Value* v); +ConstantSite* findConstantSite(Context* c, Value* v); -Site* -getTarget(Context* c, Value* value, Value* result, const SiteMask& resultMask); +Site* getTarget(Context* c, + Value* value, + Value* result, + const SiteMask& resultMask); -void -freezeSource(Context* c, unsigned size, Value* v); +void freezeSource(Context* c, unsigned size, Value* v); -void -thawSource(Context* c, unsigned size, Value* v); +void thawSource(Context* c, unsigned size, Value* v); -void -removeBuddy(Context* c, Value* v) +void removeBuddy(Context* c, Value* v) { if (v->buddy != v) { if (DebugBuddies) { @@ -965,15 +1048,16 @@ removeBuddy(Context* c, Value* v) fprintf(stderr, "\n"); } - assert(c, v->buddy); + assertT(c, v->buddy); Value* next = v->buddy; v->buddy = v; Value* p = next; - while (p->buddy != v) p = p->buddy; + while (p->buddy != v) + p = p->buddy; p->buddy = next; - assert(c, p->buddy); + assertT(c, p->buddy); if (not live(c, next)) { next->clearSites(c); @@ -985,8 +1069,7 @@ removeBuddy(Context* c, Value* v) } } -Site* -copy(Context* c, Site* s) +Site* copy(Context* c, Site* s) { Site* start = 0; Site* end = 0; @@ -1004,9 +1087,13 @@ copy(Context* c, Site* s) class Snapshot { public: - Snapshot(Context* c, Value* value, Snapshot* next): - value(value), buddy(value->buddy), sites(copy(c, value->sites)), next(next) - { } + Snapshot(Context* c, Value* value, Snapshot* next) + : value(value), + buddy(value->buddy), + sites(copy(c, value->sites)), + next(next) + { + } Value* value; Value* buddy; @@ -1014,20 +1101,19 @@ class Snapshot { Snapshot* next; }; -Snapshot* -snapshot(Context* c, Value* value, Snapshot* next) +Snapshot* snapshot(Context* c, Value* value, Snapshot* next) { if (DebugControl) { - char buffer[256]; sitesToString(c, value->sites, buffer, 256); - fprintf(stderr, "snapshot %p buddy %p sites %s\n", - value, value->buddy, buffer); + char buffer[256]; + sitesToString(c, value->sites, buffer, 256); + fprintf( + stderr, "snapshot %p buddy %p sites %s\n", value, value->buddy, buffer); } - return new(c->zone) Snapshot(c, value, next); + return new (c->zone) Snapshot(c, value, next); } -Snapshot* -makeSnapshots(Context* c, Value* value, Snapshot* next) +Snapshot* makeSnapshots(Context* c, Value* value, Snapshot* next) { next = snapshot(c, value, next); for (Value* p = value->buddy; p != value; p = p->buddy) { @@ -1036,16 +1122,14 @@ makeSnapshots(Context* c, Value* value, Snapshot* next) return next; } -Value* -maybeBuddy(Context* c, Value* v); +Value* maybeBuddy(Context* c, Value* v); -Value* -pushWord(Context* c, Value* v) +Value* pushWord(Context* c, Value* v) { if (v) { v = maybeBuddy(c, v); } - + Stack* s = stack(c, v, c->stack); if (DebugFrame) { @@ -1060,22 +1144,21 @@ pushWord(Context* c, Value* v) return v; } -void -push(Context* c, unsigned footprint, Value* v) +void push(Context* c, unsigned footprint, Value* v) { - assert(c, footprint); + assertT(c, footprint); bool bigEndian = c->arch->bigEndian(); - + Value* low = v; - + if (bigEndian) { v = pushWord(c, v); } Value* high; if (footprint > 1) { - assert(c, footprint == 2); + assertT(c, footprint == 2); if (TargetBytesPerWord == 4) { low->maybeSplit(c); @@ -1086,7 +1169,7 @@ push(Context* c, unsigned footprint, Value* v) } else { high = 0; } - + if (not bigEndian) { v = pushWord(c, v); } @@ -1098,23 +1181,21 @@ push(Context* c, unsigned footprint, Value* v) } } -void -popWord(Context* c) +void popWord(Context* c) { Stack* s = c->stack; - assert(c, s->value == 0 or s->value->home >= 0); + assertT(c, s->value == 0 or s->value->home >= 0); if (DebugFrame) { fprintf(stderr, "pop %p\n", s->value); } - - c->stack = s->next; + + c->stack = s->next; } -Value* -pop(Context* c, unsigned footprint) +Value* pop(Context* c, unsigned footprint) { - assert(c, footprint); + assertT(c, footprint); Stack* s = 0; @@ -1125,7 +1206,7 @@ pop(Context* c, unsigned footprint) } if (footprint > 1) { - assert(c, footprint == 2); + assertT(c, footprint == 2); #ifndef NDEBUG Stack* low; @@ -1138,10 +1219,12 @@ pop(Context* c, unsigned footprint) high = low->next; } - assert(c, (TargetBytesPerWord == 8 - and low->value->nextWord == low->value and high->value == 0) - or (TargetBytesPerWord == 4 and low->value->nextWord == high->value)); -#endif // not NDEBUG + assertT( + c, + (TargetBytesPerWord == 8 and low->value->nextWord == low->value + and high->value == 0) + or (TargetBytesPerWord == 4 and low->value->nextWord == high->value)); +#endif // not NDEBUG popWord(c); } @@ -1155,10 +1238,13 @@ pop(Context* c, unsigned footprint) return s->value; } -Value* -storeLocal(Context* c, unsigned footprint, Value* v, unsigned index, bool copy) +Value* storeLocal(Context* c, + unsigned footprint, + Value* v, + unsigned index, + bool copy) { - assert(c, index + footprint <= c->localFootprint); + assertT(c, index + footprint <= c->localFootprint); if (copy) { unsigned sizeInBytes = sizeof(Local) * c->localFootprint; @@ -1169,7 +1255,7 @@ storeLocal(Context* c, unsigned footprint, Value* v, unsigned index, bool copy) Value* high; if (footprint > 1) { - assert(c, footprint == 2); + assertT(c, footprint == 2); unsigned highIndex; unsigned lowIndex; @@ -1178,11 +1264,11 @@ storeLocal(Context* c, unsigned footprint, Value* v, unsigned index, bool copy) lowIndex = index; } else { lowIndex = index + 1; - highIndex = index; + highIndex = index; } if (TargetBytesPerWord == 4) { - assert(c, v->nextWord != v); + assertT(c, v->nextWord != v); high = storeLocal(c, 1, v->nextWord, highIndex, false); } else { @@ -1235,18 +1321,18 @@ unsigned typeFootprint(Context* c, ir::Type type) Value* loadLocal(Context* c, ir::Type type, unsigned index) { unsigned footprint = typeFootprint(c, type); - assert(c, index + footprint <= c->localFootprint); + assertT(c, index + footprint <= c->localFootprint); if (footprint > 1) { - assert(c, footprint == 2); + assertT(c, footprint == 2); if (not c->arch->bigEndian()) { - ++ index; + ++index; } } - assert(c, c->locals[index].value); - assert(c, c->locals[index].value->home >= 0); + assertT(c, c->locals[index].value); + assertT(c, c->locals[index].value->home >= 0); if (DebugFrame) { fprintf(stderr, "load local %p at %d\n", c->locals[index].value, index); @@ -1261,20 +1347,21 @@ Value* threadRegister(Context* c) return value(c, ir::Type::addr(), s, s); } -unsigned -frameFootprint(Context* c, Stack* s) +unsigned frameFootprint(Context* c, Stack* s) { return c->localFootprint + (s ? (s->index + 1) : 0); } -void -visit(Context* c, Link* link) +void visit(Context* c, Link* link) { - // fprintf(stderr, "visit link from %d to %d fork %p junction %p\n", - // link->predecessor->logicalInstruction->index, - // link->successor->logicalInstruction->index, - // link->forkState, - // link->junctionState); + if (false) { + fprintf(stderr, + "visit link from %d to %d fork %p junction %p\n", + link->predecessor->logicalInstruction->index, + link->successor->logicalInstruction->index, + link->forkState, + link->junctionState); + } ForkState* forkState = link->forkState; if (forkState) { @@ -1282,7 +1369,9 @@ visit(Context* c, Link* link) ForkElement* p = forkState->elements + i; Value* v = p->value; v->reads = p->read->nextTarget(); - // fprintf(stderr, "next read %p for %p from %p\n", v->reads, v, p->read); + if (false) { + fprintf(stderr, "next read %p for %p from %p\n", v->reads, v, p->read); + } if (not live(c, v)) { v->clearSites(c); } @@ -1293,36 +1382,38 @@ visit(Context* c, Link* link) if (junctionState) { for (unsigned i = 0; i < junctionState->frameFootprint; ++i) { StubReadPair* p = junctionState->reads + i; - + if (p->value and p->value->reads) { - assert(c, p->value->reads == p->read); + assertT(c, p->value->reads == p->read); popRead(c, 0, p->value); } } } } -class BuddyEvent: public Event { +class BuddyEvent : public Event { public: - BuddyEvent(Context* c, Value* original, Value* buddy): - Event(c), original(original), buddy(buddy) + BuddyEvent(Context* c, Value* original, Value* buddy) + : Event(c), original(original), buddy(buddy) { this->addRead(c, original, SiteMask(~0, ~0, AnyFrameIndex), buddy); } - virtual const char* name() { + virtual const char* name() + { return "BuddyEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { if (DebugBuddies) { fprintf(stderr, "original %p buddy %p\n", original, buddy); } - assert(c, original->hasSite(c)); + assertT(c, original->hasSite(c)); - assert(c, original); - assert(c, buddy); + assertT(c, original); + assertT(c, buddy); addBuddy(original, buddy); @@ -1333,14 +1424,12 @@ class BuddyEvent: public Event { Value* buddy; }; -void -appendBuddy(Context* c, Value* original, Value* buddy) +void appendBuddy(Context* c, Value* original, Value* buddy) { - append(c, new(c->zone) BuddyEvent(c, original, buddy)); + append(c, new (c->zone) BuddyEvent(c, original, buddy)); } -void -append(Context* c, Event* e) +void append(Context* c, Event* e) { LogicalInstruction* i = c->logicalCode[c->logicalIp]; if (c->stack != i->stack or c->locals != i->locals) { @@ -1348,9 +1437,11 @@ append(Context* c, Event* e) } if (DebugAppend) { - fprintf(stderr, " -- append %s at %d with %d stack before\n", - e->name(), e->logicalInstruction->index, c->stack ? - c->stack->index + 1 : 0); + fprintf(stderr, + " -- append %s at %d with %d stack before\n", + e->name(), + e->logicalInstruction->index, + c->stack ? c->stack->index + 1 : 0); } if (c->lastEvent) { @@ -1363,12 +1454,14 @@ append(Context* c, Event* e) Event* p = c->predecessor; if (p) { if (DebugAppend) { - fprintf(stderr, "%d precedes %d\n", p->logicalInstruction->index, + fprintf(stderr, + "%d precedes %d\n", + p->logicalInstruction->index, e->logicalInstruction->index); } - Link* link = compiler::link - (c, p, e->predecessors, e, p->successors, c->forkState); + Link* link + = compiler::link(c, p, e->predecessors, e, p->successors, c->forkState); e->predecessors = link; p->successors = link; } @@ -1382,13 +1475,13 @@ append(Context* c, Event* e) e->logicalInstruction->lastEvent = e; } -Site* -readSource(Context* c, Read* r) +Site* readSource(Context* c, Read* r) { Value* v = r->value; if (DebugReads) { - char buffer[1024]; sitesToString(c, v, buffer, 1024); + char buffer[1024]; + sitesToString(c, v, buffer, 1024); fprintf(stderr, "read source for %p from %s\n", v, buffer); } @@ -1407,8 +1500,7 @@ readSource(Context* c, Read* r) } } -void -propagateJunctionSites(Context* c, Event* e, Site** sites) +void propagateJunctionSites(Context* c, Event* e, Site** sites) { for (Link* pl = e->predecessors; pl; pl = pl->nextPredecessor) { Event* p = pl->predecessor; @@ -1422,15 +1514,13 @@ propagateJunctionSites(Context* c, Event* e, Site** sites) } } -void -propagateJunctionSites(Context* c, Event* e) +void propagateJunctionSites(Context* c, Event* e) { for (Link* sl = e->successors; sl; sl = sl->nextSuccessor) { Event* s = sl->successor; if (s->predecessors->nextPredecessor) { unsigned size = sizeof(Site*) * frameFootprint(c, e->stackAfter); - Site** junctionSites = static_cast - (c->zone->allocate(size)); + Site** junctionSites = static_cast(c->zone->allocate(size)); memset(junctionSites, 0, size); propagateJunctionSites(c, s, junctionSites); @@ -1445,8 +1535,7 @@ class SiteRecord { Value* value; }; -void -init(SiteRecord* r, Site* s, Value* v) +void init(SiteRecord* r, Site* s, Value* v) { r->site = s; r->value = v; @@ -1454,41 +1543,40 @@ init(SiteRecord* r, Site* s, Value* v) class SiteRecordList { public: - SiteRecordList(SiteRecord* records, unsigned capacity): - records(records), index(0), capacity(capacity) - { } + SiteRecordList(SiteRecord* records, unsigned capacity) + : records(records), index(0), capacity(capacity) + { + } SiteRecord* records; unsigned index; unsigned capacity; }; -void -freeze(Context* c, SiteRecordList* frozen, Site* s, Value* v) +void freeze(Context* c, SiteRecordList* frozen, Site* s, Value* v) { - assert(c, frozen->index < frozen->capacity); + assertT(c, frozen->index < frozen->capacity); s->freeze(c, v); - init(new (frozen->records + (frozen->index ++)) SiteRecord, s, v); + init(new (frozen->records + (frozen->index++)) SiteRecord, s, v); } -void -thaw(Context* c, SiteRecordList* frozen) +void thaw(Context* c, SiteRecordList* frozen) { while (frozen->index) { - SiteRecord* sr = frozen->records + (-- frozen->index); + SiteRecord* sr = frozen->records + (--frozen->index); sr->site->thaw(c, sr->value); } } -bool -resolveOriginalSites(Context* c, Event* e, SiteRecordList* frozen, - Site** sites) +bool resolveOriginalSites(Context* c, + Event* e, + SiteRecordList* frozen, + Site** sites) { bool complete = true; for (FrameIterator it(c, e->stackAfter, e->localsAfter, true); - it.hasMore();) - { + it.hasMore();) { FrameIterator::Element el = it.next(c); Value* v = el.value; Read* r = v ? live(c, v) : 0; @@ -1499,12 +1587,16 @@ resolveOriginalSites(Context* c, Event* e, SiteRecordList* frozen, if (DebugControl) { char buffer[256]; s->toString(c, buffer, 256); - fprintf(stderr, "resolve original %s for %p local %d frame %d\n", - buffer, v, el.localIndex, el.frameIndex(c)); + fprintf(stderr, + "resolve original %s for %p local %d frame %d\n", + buffer, + v, + el.localIndex, + el.frameIndex(c)); } - Site* target = pickSiteOrMove - (c, v, s->mask(c), true, true, ResolveRegisterReserveCount); + Site* target = pickSiteOrMove( + c, v, s->mask(c), true, true, ResolveRegisterReserveCount); freeze(c, frozen, target, v); } else { @@ -1514,8 +1606,12 @@ resolveOriginalSites(Context* c, Event* e, SiteRecordList* frozen, if (DebugControl) { char buffer[256]; s->toString(c, buffer, 256); - fprintf(stderr, "freeze original %s for %p local %d frame %d\n", - buffer, v, el.localIndex, el.frameIndex(c)); + fprintf(stderr, + "freeze original %s for %p local %d frame %d\n", + buffer, + v, + el.localIndex, + el.frameIndex(c)); } Value dummy(0, 0, ir::Type::addr()); @@ -1528,8 +1624,10 @@ resolveOriginalSites(Context* c, Event* e, SiteRecordList* frozen, return complete; } -bool -resolveSourceSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) +bool resolveSourceSites(Context* c, + Event* e, + SiteRecordList* frozen, + Site** sites) { bool complete = true; for (FrameIterator it(c, e->stackAfter, e->localsAfter); it.hasMore();) { @@ -1539,16 +1637,22 @@ resolveSourceSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) if (r and sites[el.localIndex] == 0) { SiteMask mask((1 << lir::RegisterOperand) | (1 << lir::MemoryOperand), - c->regFile->generalRegisters.mask, AnyFrameIndex); + c->regFile->generalRegisters.mask, + AnyFrameIndex); - Site* s = pickSourceSite - (c, r, 0, 0, &mask, true, false, true, acceptForResolve); + Site* s = pickSourceSite( + c, r, 0, 0, &mask, true, false, true, acceptForResolve); if (s) { if (DebugControl) { - char buffer[256]; s->toString(c, buffer, 256); - fprintf(stderr, "resolve source %s from %p local %d frame %d\n", - buffer, v, el.localIndex, el.frameIndex(c)); + char buffer[256]; + s->toString(c, buffer, 256); + fprintf(stderr, + "resolve source %s from %p local %d frame %d\n", + buffer, + v, + el.localIndex, + el.frameIndex(c)); } freeze(c, frozen, s, v); @@ -1563,8 +1667,10 @@ resolveSourceSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) return complete; } -void -resolveTargetSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) +void resolveTargetSites(Context* c, + Event* e, + SiteRecordList* frozen, + Site** sites) { for (FrameIterator it(c, e->stackAfter, e->localsAfter); it.hasMore();) { FrameIterator::Element el = it.next(c); @@ -1573,10 +1679,11 @@ resolveTargetSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) if (r and sites[el.localIndex] == 0) { SiteMask mask((1 << lir::RegisterOperand) | (1 << lir::MemoryOperand), - c->regFile->generalRegisters.mask, AnyFrameIndex); + c->regFile->generalRegisters.mask, + AnyFrameIndex); - Site* s = pickSourceSite - (c, r, 0, 0, &mask, false, true, true, acceptForResolve); + Site* s = pickSourceSite( + c, r, 0, 0, &mask, false, true, true, acceptForResolve); if (s == 0) { s = maybeMove(c, v, mask, false, true, ResolveRegisterReserveCount); @@ -1587,16 +1694,20 @@ resolveTargetSites(Context* c, Event* e, SiteRecordList* frozen, Site** sites) sites[el.localIndex] = s->copy(c); if (DebugControl) { - char buffer[256]; sites[el.localIndex]->toString(c, buffer, 256); - fprintf(stderr, "resolve target %s for %p local %d frame %d\n", - buffer, el.value, el.localIndex, el.frameIndex(c)); + char buffer[256]; + sites[el.localIndex]->toString(c, buffer, 256); + fprintf(stderr, + "resolve target %s for %p local %d frame %d\n", + buffer, + el.value, + el.localIndex, + el.frameIndex(c)); } } } } -void -resolveJunctionSites(Context* c, Event* e, SiteRecordList* frozen) +void resolveJunctionSites(Context* c, Event* e, SiteRecordList* frozen) { bool complete; if (e->junctionSites) { @@ -1615,29 +1726,28 @@ resolveJunctionSites(Context* c, Event* e, SiteRecordList* frozen) } if (DebugControl) { - fprintf(stderr, "resolved junction sites %p at %d\n", - e->junctionSites, e->logicalInstruction->index); + fprintf(stderr, + "resolved junction sites %p at %d\n", + e->junctionSites, + e->logicalInstruction->index); } } } -void -resolveBranchSites(Context* c, Event* e, SiteRecordList* frozen) +void resolveBranchSites(Context* c, Event* e, SiteRecordList* frozen) { if (e->successors->nextSuccessor and e->junctionSites == 0) { unsigned footprint = frameFootprint(c, e->stackAfter); RUNTIME_ARRAY(Site*, branchSites, footprint); memset(RUNTIME_ARRAY_BODY(branchSites), 0, sizeof(Site*) * footprint); - if (not resolveSourceSites(c, e, frozen, RUNTIME_ARRAY_BODY(branchSites))) - { + if (not resolveSourceSites(c, e, frozen, RUNTIME_ARRAY_BODY(branchSites))) { resolveTargetSites(c, e, frozen, RUNTIME_ARRAY_BODY(branchSites)); } } } -void -captureBranchSnapshots(Context* c, Event* e) +void captureBranchSnapshots(Context* c, Event* e) { if (e->successors->nextSuccessor) { for (FrameIterator it(c, e->stackAfter, e->localsAfter); it.hasMore();) { @@ -1645,42 +1755,43 @@ captureBranchSnapshots(Context* c, Event* e) e->snapshots = makeSnapshots(c, el.value, e->snapshots); } - for (List* sv = e->successors->forkState->saved; sv; sv = sv->next) { + for (List* sv = e->successors->forkState->saved; sv; + sv = sv->next) { e->snapshots = makeSnapshots(c, sv->item, e->snapshots); } if (DebugControl) { - fprintf(stderr, "captured snapshots %p at %d\n", - e->snapshots, e->logicalInstruction->index); + fprintf(stderr, + "captured snapshots %p at %d\n", + e->snapshots, + e->logicalInstruction->index); } } } -void -populateSiteTables(Context* c, Event* e, SiteRecordList* frozen) +void populateSiteTables(Context* c, Event* e, SiteRecordList* frozen) { resolveJunctionSites(c, e, frozen); resolveBranchSites(c, e, frozen); } -void -setSites(Context* c, Value* v, Site* s) +void setSites(Context* c, Value* v, Site* s) { - assert(c, live(c, v)); + assertT(c, live(c, v)); for (; s; s = s->next) { v->addSite(c, s->copy(c)); } if (DebugControl) { - char buffer[256]; sitesToString(c, v->sites, buffer, 256); + char buffer[256]; + sitesToString(c, v->sites, buffer, 256); fprintf(stderr, "set sites %s for %p\n", buffer, v); } } -void -resetFrame(Context* c, Event* e) +void resetFrame(Context* c, Event* e) { for (FrameIterator it(c, e->stackBefore, e->localsBefore); it.hasMore();) { FrameIterator::Element el = it.next(c); @@ -1692,8 +1803,7 @@ resetFrame(Context* c, Event* e) } } -void -setSites(Context* c, Event* e, Site** sites) +void setSites(Context* c, Event* e, Site** sites) { resetFrame(c, e); @@ -1703,19 +1813,26 @@ setSites(Context* c, Event* e, Site** sites) if (live(c, el.value)) { setSites(c, el.value, sites[el.localIndex]); } else if (DebugControl) { - char buffer[256]; sitesToString(c, sites[el.localIndex], buffer, 256); - fprintf(stderr, "skip sites %s for %p local %d frame %d\n", - buffer, el.value, el.localIndex, el.frameIndex(c)); + char buffer[256]; + sitesToString(c, sites[el.localIndex], buffer, 256); + fprintf(stderr, + "skip sites %s for %p local %d frame %d\n", + buffer, + el.value, + el.localIndex, + el.frameIndex(c)); } } else if (DebugControl) { - fprintf(stderr, "no sites for %p local %d frame %d\n", - el.value, el.localIndex, el.frameIndex(c)); + fprintf(stderr, + "no sites for %p local %d frame %d\n", + el.value, + el.localIndex, + el.frameIndex(c)); } } } -void -removeBuddies(Context* c) +void removeBuddies(Context* c) { for (FrameIterator it(c, c->stack, c->locals); it.hasMore();) { FrameIterator::Element el = it.next(c); @@ -1723,8 +1840,7 @@ removeBuddies(Context* c) } } -void -restore(Context* c, Event* e, Snapshot* snapshots) +void restore(Context* c, Event* e, Snapshot* snapshots) { for (Snapshot* s = snapshots; s; s = s->next) { Value* v = s->value; @@ -1732,13 +1848,14 @@ restore(Context* c, Event* e, Snapshot* snapshots) if (v != next) { v->buddy = v; Value* p = next; - while (p->buddy != v) p = p->buddy; + while (p->buddy != v) + p = p->buddy; p->buddy = next; } } for (Snapshot* s = snapshots; s; s = s->next) { - assert(c, s->buddy); + assertT(c, s->buddy); s->value->buddy = s->buddy; } @@ -1752,14 +1869,20 @@ restore(Context* c, Event* e, Snapshot* snapshots) } } - // char buffer[256]; sitesToString(c, s->sites, buffer, 256); - // fprintf(stderr, "restore %p buddy %p sites %s live %p\n", - // s->value, s->value->buddy, buffer, live(c, s->value)); + if (false) { + char buffer[256]; + sitesToString(c, s->sites, buffer, 256); + fprintf(stderr, + "restore %p buddy %p sites %s live %p\n", + s->value, + s->value->buddy, + buffer, + live(c, s->value)); + } } } -void -populateSources(Context* c, Event* e) +void populateSources(Context* c, Event* e) { RUNTIME_ARRAY(SiteRecord, frozenRecords, e->readCount); SiteRecordList frozen(RUNTIME_ARRAY_BODY(frozenRecords), e->readCount); @@ -1768,9 +1891,9 @@ populateSources(Context* c, Event* e) r->value->source = readSource(c, r); if (r->value->source) { if (DebugReads) { - char buffer[256]; r->value->source->toString(c, buffer, 256); - fprintf(stderr, "freeze source %s for %p\n", - buffer, r->value); + char buffer[256]; + r->value->source->toString(c, buffer, 256); + fprintf(stderr, "freeze source %s for %p\n", buffer, r->value); } freeze(c, &frozen, r->value->source, r->value); @@ -1780,15 +1903,15 @@ populateSources(Context* c, Event* e) thaw(c, &frozen); } -void -setStubRead(Context* c, StubReadPair* p, Value* v) +void setStubRead(Context* c, StubReadPair* p, Value* v) { if (v) { StubRead* r = stubRead(c); if (DebugReads) { fprintf(stderr, "add stub read %p to %p\n", r, v); } - // TODO: this is rather icky looking... but despite how it looks, it will not cause an NPE + // TODO: this is rather icky looking... but despite how it looks, it will + // not cause an NPE ((Event*)0)->addRead(c, v, r); p->value = v; @@ -1796,14 +1919,12 @@ setStubRead(Context* c, StubReadPair* p, Value* v) } } -void -populateJunctionReads(Context* c, Link* link) +void populateJunctionReads(Context* c, Link* link) { - JunctionState* state = new - (c->zone->allocate - (sizeof(JunctionState) - + (sizeof(StubReadPair) * frameFootprint(c, c->stack)))) - JunctionState(frameFootprint(c, c->stack)); + JunctionState* state = new ( + c->zone->allocate(sizeof(JunctionState) + + (sizeof(StubReadPair) * frameFootprint(c, c->stack)))) + JunctionState(frameFootprint(c, c->stack)); memset(state->reads, 0, sizeof(StubReadPair) * frameFootprint(c, c->stack)); @@ -1815,8 +1936,7 @@ populateJunctionReads(Context* c, Link* link) } } -void -updateJunctionReads(Context* c, JunctionState* state) +void updateJunctionReads(Context* c, JunctionState* state) { for (FrameIterator it(c, c->stack, c->locals); it.hasMore();) { FrameIterator::Element e = it.next(c); @@ -1825,8 +1945,8 @@ updateJunctionReads(Context* c, JunctionState* state) Read* r = live(c, e.value); if (r) { if (DebugReads) { - fprintf(stderr, "stub read %p for %p valid: %p\n", - p->read, p->value, r); + fprintf( + stderr, "stub read %p for %p valid: %p\n", p->read, p->value, r); } p->read->read = r; } @@ -1844,8 +1964,9 @@ updateJunctionReads(Context* c, JunctionState* state) } } -void -compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) +void compile(Context* c, + uintptr_t stackOverflowHandler, + unsigned stackLimitOffset) { if (c->logicalCode[c->logicalIp]->lastEvent == 0) { appendDummy(c); @@ -1866,7 +1987,8 @@ compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) if (DebugCompile) { fprintf(stderr, " -- compile %s at %d with %d preds %d succs %d stack\n", - e->name(), e->logicalInstruction->index, + e->name(), + e->logicalInstruction->index, e->predecessors->countPredecessors(), e->successors->countSuccessors(), e->stackBefore ? e->stackBefore->index + 1 : 0); @@ -1886,24 +2008,26 @@ compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) Event* first = e->predecessors->predecessor; if (e->predecessors->nextPredecessor) { - for (Link* pl = e->predecessors; - pl->nextPredecessor; - pl = pl->nextPredecessor) - { + for (Link* pl = e->predecessors; pl->nextPredecessor; + pl = pl->nextPredecessor) { updateJunctionReads(c, pl->junctionState); } if (DebugControl) { - fprintf(stderr, "set sites to junction sites %p at %d\n", - first->junctionSites, first->logicalInstruction->index); + fprintf(stderr, + "set sites to junction sites %p at %d\n", + first->junctionSites, + first->logicalInstruction->index); } setSites(c, e, first->junctionSites); removeBuddies(c); } else if (first->successors->nextSuccessor) { if (DebugControl) { - fprintf(stderr, "restore snapshots %p at %d\n", - first->snapshots, first->logicalInstruction->index); + fprintf(stderr, + "restore snapshots %p at %d\n", + first->snapshots, + first->logicalInstruction->index); } restore(c, e, first->snapshots); @@ -1936,7 +2060,8 @@ compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) } if (e->visitLinks) { - for (List* cell = reverseDestroy(e->visitLinks); cell; cell = cell->next) { + for (List* cell = reverseDestroy(e->visitLinks); cell; + cell = cell->next) { visit(c, cell->item); } e->visitLinks = 0; @@ -1945,15 +2070,13 @@ compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) for (CodePromise* p = e->promises; p; p = p->next) { p->offset = a->offset(); } - + a->endEvent(); LogicalInstruction* nextInstruction = e->logicalInstruction->next(c); - if (e->next == 0 - or (e->next->logicalInstruction != e->logicalInstruction - and (e->next->logicalInstruction != nextInstruction - or e != e->logicalInstruction->lastEvent))) - { + if (e->next == 0 or (e->next->logicalInstruction != e->logicalInstruction + and (e->next->logicalInstruction != nextInstruction + or e != e->logicalInstruction->lastEvent))) { Block* b = e->logicalInstruction->firstEvent->block; while (b->nextBlock) { @@ -1976,8 +2099,7 @@ compile(Context* c, uintptr_t stackOverflowHandler, unsigned stackLimitOffset) c->firstBlock = firstBlock; } -void -restore(Context* c, ForkState* state) +void restore(Context* c, ForkState* state) { for (unsigned i = 0; i < state->readCount; ++i) { ForkElement* p = state->elements + i; @@ -1986,14 +2108,14 @@ restore(Context* c, ForkState* state) } } -void -addForkElement(Context* c, Value* v, ForkState* state, unsigned index) +void addForkElement(Context* c, Value* v, ForkState* state, unsigned index) { MultiRead* r = multiRead(c); if (DebugReads) { fprintf(stderr, "add multi read %p to %p\n", r, v); } - // TODO: this is rather icky looking... but despite how it looks, it will not cause an NPE + // TODO: this is rather icky looking... but despite how it looks, it will not + // cause an NPE ((Event*)0)->addRead(c, v, r); ForkElement* p = state->elements + index; @@ -2001,8 +2123,7 @@ addForkElement(Context* c, Value* v, ForkState* state, unsigned index) p->read = r; } -ForkState* -saveState(Context* c) +ForkState* saveState(Context* c) { if (c->logicalCode[c->logicalIp]->lastEvent == 0) { appendDummy(c); @@ -2010,10 +2131,9 @@ saveState(Context* c) unsigned elementCount = frameFootprint(c, c->stack) + c->saved->count(); - ForkState* state = new - (c->zone->allocate - (sizeof(ForkState) + (sizeof(ForkElement) * elementCount))) - ForkState(c->stack, c->locals, c->saved, c->predecessor, c->logicalIp); + ForkState* state = new (c->zone->allocate( + sizeof(ForkState) + (sizeof(ForkElement) * elementCount))) + ForkState(c->stack, c->locals, c->saved, c->predecessor, c->logicalIp); if (c->predecessor) { c->forkState = state; @@ -2037,8 +2157,7 @@ saveState(Context* c) return state; } -void -restoreState(Context* c, ForkState* s) +void restoreState(Context* c, ForkState* s) { if (c->logicalCode[c->logicalIp]->lastEvent == 0) { appendDummy(c); @@ -2055,8 +2174,7 @@ restoreState(Context* c, ForkState* s) } } -Value* -maybeBuddy(Context* c, Value* v) +Value* maybeBuddy(Context* c, Value* v) { if (v->home >= 0) { Value* n = value(c, v->type); @@ -2067,8 +2185,7 @@ maybeBuddy(Context* c, Value* v) } } -void -linkLocals(Context* c, Local* oldLocals, Local* newLocals) +void linkLocals(Context* c, Local* oldLocals, Local* newLocals) { for (int i = 0; i < static_cast(c->localFootprint); ++i) { Local* local = oldLocals + i; @@ -2077,8 +2194,7 @@ linkLocals(Context* c, Local* oldLocals, Local* newLocals) if (i + highOffset >= 0 and i + highOffset < static_cast(c->localFootprint) - and local->value->nextWord == local[highOffset].value) - { + and local->value->nextWord == local[highOffset].value) { Value* v = newLocals[i].value; Value* next = newLocals[i + highOffset].value; v->nextWord = next; @@ -2089,11 +2205,14 @@ linkLocals(Context* c, Local* oldLocals, Local* newLocals) } } -class Client: public Assembler::Client { +class Client : public Assembler::Client { public: - Client(Context* c): c(c) { } + Client(Context* c) : c(c) + { + } - virtual int acquireTemporary(uint32_t mask) { + virtual int acquireTemporary(uint32_t mask) + { unsigned cost; int r = pickRegisterTarget(c, 0, mask, &cost); expect(c, cost < Target::Impossible); @@ -2102,16 +2221,18 @@ class Client: public Assembler::Client { return r; } - virtual void releaseTemporary(int r) { + virtual void releaseTemporary(int r) + { c->registerResources[r].decrement(c); } - virtual void save(int r) { + virtual void save(int r) + { RegisterResource* reg = c->registerResources + r; - assert(c, reg->referenceCount == 0); - assert(c, reg->freezeCount == 0); - assert(c, not reg->reserved); + assertT(c, reg->referenceCount == 0); + assertT(c, reg->freezeCount == 0); + assertT(c, not reg->reserved); if (reg->value) { steal(c, reg, 0); @@ -2121,27 +2242,33 @@ class Client: public Assembler::Client { Context* c; }; -class MyCompiler: public Compiler { +class MyCompiler : public Compiler { public: - MyCompiler(System* s, Assembler* assembler, Zone* zone, - Compiler::Client* compilerClient): - c(s, assembler, zone, compilerClient), client(&c) + MyCompiler(System* s, + Assembler* assembler, + Zone* zone, + Compiler::Client* compilerClient) + : c(s, assembler, zone, compilerClient), client(&c) { assembler->setClient(&client); } - virtual State* saveState() { + virtual State* saveState() + { State* s = compiler::saveState(&c); restoreState(s); return s; } - virtual void restoreState(State* state) { + virtual void restoreState(State* state) + { compiler::restoreState(&c, static_cast(state)); } - virtual void init(unsigned logicalCodeLength, unsigned parameterFootprint, - unsigned localFootprint, unsigned alignedFrameSize) + virtual void init(unsigned logicalCodeLength, + unsigned parameterFootprint, + unsigned localFootprint, + unsigned alignedFrameSize) { c.parameterFootprint = parameterFootprint; c.localFootprint = localFootprint; @@ -2149,9 +2276,9 @@ class MyCompiler: public Compiler { unsigned frameResourceCount = totalFrameSize(&c); - c.frameResources = static_cast - (c.zone->allocate(sizeof(FrameResource) * frameResourceCount)); - + c.frameResources = static_cast( + c.zone->allocate(sizeof(FrameResource) * frameResourceCount)); + for (unsigned i = 0; i < frameResourceCount; ++i) { new (c.frameResources + i) FrameResource; } @@ -2159,14 +2286,14 @@ class MyCompiler: public Compiler { unsigned base = frameBase(&c); c.frameResources[base + c.arch->returnAddressOffset()].reserved = true; c.frameResources[base + c.arch->framePointerOffset()].reserved - = UseFramePointer; + = UseFramePointer; c.logicalCode.init(c.zone, logicalCodeLength); c.logicalCode[-1] = new (c.zone) LogicalInstruction(-1, c.stack, c.locals); - c.locals = static_cast - (c.zone->allocate(sizeof(Local) * localFootprint)); + c.locals + = static_cast(c.zone->allocate(sizeof(Local) * localFootprint)); memset(c.locals, 0, sizeof(Local) * localFootprint); } @@ -2176,8 +2303,9 @@ class MyCompiler: public Compiler { c.logicalCode.extend(c.zone, more); } - virtual void visitLogicalIp(unsigned logicalIp) { - assert(&c, logicalIp < c.logicalCode.count()); + virtual void visitLogicalIp(unsigned logicalIp) + { + assertT(&c, logicalIp < c.logicalCode.count()); if (c.logicalCode[c.logicalIp]->lastEvent == 0) { appendDummy(&c); @@ -2188,22 +2316,26 @@ class MyCompiler: public Compiler { Event* p = c.predecessor; if (p) { if (DebugAppend) { - fprintf(stderr, "visit %d pred %d\n", logicalIp, + fprintf(stderr, + "visit %d pred %d\n", + logicalIp, p->logicalInstruction->index); } p->stackAfter = c.stack; p->localsAfter = c.locals; - Link* link = compiler::link - (&c, p, e->predecessors, e, p->successors, c.forkState); + Link* link = compiler::link( + &c, p, e->predecessors, e, p->successors, c.forkState); e->predecessors = link; p->successors = link; c.lastEvent->visitLinks = cons(&c, link, c.lastEvent->visitLinks); if (DebugAppend) { - fprintf(stderr, "populate junction reads for %d to %d\n", - p->logicalInstruction->index, logicalIp); + fprintf(stderr, + "populate junction reads for %d to %d\n", + p->logicalInstruction->index, + logicalIp); } populateJunctionReads(&c, link); @@ -2212,9 +2344,10 @@ class MyCompiler: public Compiler { c.forkState = 0; } - virtual void startLogicalIp(unsigned logicalIp) { - assert(&c, logicalIp < c.logicalCode.count()); - assert(&c, c.logicalCode[logicalIp] == 0); + virtual void startLogicalIp(unsigned logicalIp) + { + assertT(&c, logicalIp < c.logicalCode.count()); + assertT(&c, c.logicalCode[logicalIp] == 0); if (c.logicalCode[c.logicalIp]->lastEvent == 0) { appendDummy(&c); @@ -2226,20 +2359,24 @@ class MyCompiler: public Compiler { p->localsAfter = c.locals; } - c.logicalCode[logicalIp] = new(c.zone) LogicalInstruction(logicalIp, c.stack, c.locals); + c.logicalCode[logicalIp] = new (c.zone) + LogicalInstruction(logicalIp, c.stack, c.locals); c.logicalIp = logicalIp; } - virtual Promise* machineIp(unsigned logicalIp) { + virtual Promise* machineIp(unsigned logicalIp) + { return ipPromise(&c, logicalIp); } - virtual Promise* poolAppend(intptr_t value) { + virtual Promise* poolAppend(intptr_t value) + { return poolAppendPromise(resolvedPromise(&c, value)); } - virtual Promise* poolAppendPromise(Promise* value) { + virtual Promise* poolAppendPromise(Promise* value) + { Promise* p = poolPromise(&c, c.constantCount); ConstantPoolNode* constant = new (c.zone) ConstantPoolNode(value); @@ -2250,7 +2387,7 @@ class MyCompiler: public Compiler { c.firstConstant = constant; } c.lastConstant = constant; - ++ c.constantCount; + ++c.constantCount; return p; } @@ -2292,28 +2429,29 @@ class MyCompiler: public Compiler { return compiler::threadRegister(&c); } - Promise* machineIp() { + Promise* machineIp() + { return c.logicalCode[c.logicalIp]->lastEvent->makeCodePromise(&c); } virtual void push(ir::Type type, ir::Value* value) { - // TODO: once type information is flowed properly, enable this assert. + // TODO: once type information is flowed properly, enable this assertT. // Some time later, we can remove the parameter. - // assert(&c, value->type == type); + // assertT(&c, value->type == type); compiler::push(&c, typeFootprint(&c, type), static_cast(value)); } virtual void save(ir::Type type, ir::Value* value) { - // TODO: once type information is flowed properly, enable this assert. + // TODO: once type information is flowed properly, enable this assertT. // Some time later, we can remove the parameter. - // assert(&c, value->type == type); + // assertT(&c, value->type == type); unsigned footprint = typeFootprint(&c, type); c.saved = cons(&c, static_cast(value), c.saved); if (TargetBytesPerWord == 4 and footprint > 1) { - assert(&c, footprint == 2); - assert(&c, static_cast(value)->nextWord); + assertT(&c, footprint == 2); + assertT(&c, static_cast(value)->nextWord); save(ir::Type::i4(), static_cast(value)->nextWord); } @@ -2322,37 +2460,40 @@ class MyCompiler: public Compiler { virtual ir::Value* pop(ir::Type type) { ir::Value* value = compiler::pop(&c, typeFootprint(&c, type)); - // TODO: once type information is flowed properly, enable this assert. + // TODO: once type information is flowed properly, enable this assertT. // Some time later, we can remove the parameter. - // assert(&c, static_cast(value)->type == type); + // assertT(&c, static_cast(value)->type == type); return value; } virtual void pushed(ir::Type type) { Value* v = value(&c, type); - appendFrameSite - (&c, v, frameIndex - (&c, (c.stack ? c.stack->index : 0) + c.localFootprint)); + appendFrameSite( + &c, + v, + frameIndex(&c, (c.stack ? c.stack->index : 0) + c.localFootprint)); Stack* s = compiler::stack(&c, v, c.stack); v->home = frameIndex(&c, s->index + c.localFootprint); c.stack = s; } - virtual void popped(unsigned footprint) { - for (; footprint; -- footprint) { - assert(&c, c.stack->value == 0 or c.stack->value->home >= 0); + virtual void popped(unsigned footprint) + { + for (; footprint; --footprint) { + assertT(&c, c.stack->value == 0 or c.stack->value->home >= 0); if (DebugFrame) { fprintf(stderr, "popped %p\n", c.stack->value); } - + c.stack = c.stack->next; } } - virtual unsigned topOfStack() { + virtual unsigned topOfStack() + { return c.stack->index; } @@ -2364,7 +2505,7 @@ class MyCompiler: public Compiler { } if (footprint > 1) { - assert(&c, footprint == 2); + assertT(&c, footprint == 2); bool bigEndian = c.arch->bigEndian(); @@ -2379,11 +2520,12 @@ class MyCompiler: public Compiler { high = s->next; } - assert(&c, (TargetBytesPerWord == 8 - and low->value->nextWord == low->value and high->value == 0) - or (TargetBytesPerWord == 4 - and low->value->nextWord == high->value)); -#endif // not NDEBUG + assertT( + &c, + (TargetBytesPerWord == 8 and low->value->nextWord == low->value + and high->value == 0) + or (TargetBytesPerWord == 4 and low->value->nextWord == high->value)); +#endif // not NDEBUG if (bigEndian) { s = s->next; @@ -2400,7 +2542,8 @@ class MyCompiler: public Compiler { unsigned argumentCount, ...) { - va_list a; va_start(a, argumentCount); + va_list a; + va_start(a, argumentCount); bool bigEndian = c.arch->bigEndian(); @@ -2419,11 +2562,11 @@ class MyCompiler: public Compiler { RUNTIME_ARRAY_BODY(arguments)[++index] = o->nextWord; } size = TargetBytesPerWord; - ++ index; + ++index; } else { size = 8; } - ++ footprint; + ++footprint; } va_end(a); @@ -2455,13 +2598,13 @@ class MyCompiler: public Compiler { traceHandler, result, arguments); - assert(&c, c.stack == b); + assertT(&c, c.stack == b); return result; } virtual void return_(ir::Value* a) { - assert(&c, a); + assertT(&c, a); appendReturn(&c, static_cast(a)); } @@ -2493,12 +2636,12 @@ class MyCompiler: public Compiler { { unsigned footprint = typeFootprint(&c, type); - assert(&c, index + footprint <= c.localFootprint); + assertT(&c, index + footprint <= c.localFootprint); Value* v = value(&c, type); if (footprint > 1) { - assert(&c, footprint == 2); + assertT(&c, footprint == 2); unsigned highIndex; unsigned lowIndex; @@ -2522,8 +2665,11 @@ class MyCompiler: public Compiler { } if (DebugFrame) { - fprintf(stderr, "init local %p at %d (%d)\n", - v, index, frameIndex(&c, index)); + fprintf(stderr, + "init local %p at %d (%d)\n", + v, + index, + frameIndex(&c, index)); } appendFrameSite(&c, v, frameIndex(&c, index)); @@ -2533,8 +2679,9 @@ class MyCompiler: public Compiler { v->home = frameIndex(&c, index); } - virtual void initLocalsFromLogicalIp(unsigned logicalIp) { - assert(&c, logicalIp < c.logicalCode.count()); + virtual void initLocalsFromLogicalIp(unsigned logicalIp) + { + assertT(&c, logicalIp < c.logicalCode.count()); unsigned footprint = sizeof(Local) * c.localFootprint; Local* newLocals = static_cast(c.zone->allocate(footprint)); @@ -2554,7 +2701,11 @@ class MyCompiler: public Compiler { virtual void storeLocal(ir::Value* src, unsigned index) { - compiler::storeLocal(&c, typeFootprint(&c, src->type), static_cast(src), index, true); + compiler::storeLocal(&c, + typeFootprint(&c, src->type), + static_cast(src), + index, + true); } virtual ir::Value* loadLocal(ir::Type type, unsigned index) @@ -2562,10 +2713,11 @@ class MyCompiler: public Compiler { return compiler::loadLocal(&c, type, index); } - virtual void saveLocals() { + virtual void saveLocals() + { int oldIp UNUSED = c.logicalIp; appendSaveLocals(&c); - assert(&c, oldIp == c.logicalIp); + assertT(&c, oldIp == c.logicalIp); } virtual void checkBounds(ir::Value* object, @@ -2573,15 +2725,18 @@ class MyCompiler: public Compiler { ir::Value* index, intptr_t handler) { - appendBoundsCheck(&c, static_cast(object), lengthOffset, - static_cast(index), handler); + appendBoundsCheck(&c, + static_cast(object), + lengthOffset, + static_cast(index), + handler); } virtual ir::Value* truncate(ir::Type type, ir::Value* src) { - assert(&c, src->type.flavor() == type.flavor()); - assert(&c, type.flavor() != ir::Type::Float); - assert(&c, type.rawSize() < src->type.rawSize()); + assertT(&c, src->type.flavor() == type.flavor()); + assertT(&c, type.flavor() != ir::Type::Float); + assertT(&c, type.rawSize() < src->type.rawSize()); Value* dst = value(&c, type); appendMove(&c, lir::Move, @@ -2613,7 +2768,7 @@ class MyCompiler: public Compiler { virtual void store(ir::Value* src, ir::Value* dst) { - assert(&c, src->type.flavor() == dst->type.flavor()); + assertT(&c, src->type.flavor() == dst->type.flavor()); appendMove(&c, lir::Move, @@ -2628,7 +2783,7 @@ class MyCompiler: public Compiler { ir::Value* src, ir::Type dstType) { - assert(&c, src->type.flavor() == dstType.flavor()); + assertT(&c, src->type.flavor() == dstType.flavor()); Value* dst = value(&c, dstType); appendMove(&c, @@ -2648,12 +2803,12 @@ class MyCompiler: public Compiler { ir::Value* b, ir::Value* addr) { - assert(&c, - (isGeneralBranch(op) and isGeneralValue(a) and isGeneralValue(b))or( - isFloatBranch(op) and isFloatValue(a) and isFloatValue(b))); + assertT(&c, + (isGeneralBranch(op) and isGeneralValue(a) and isGeneralValue(b)) + or (isFloatBranch(op) and isFloatValue(a) and isFloatValue(b))); - assert(&c, a->type == b->type); - assert(&c, addr->type == ir::Type::iptr()); + assertT(&c, a->type == b->type); + assertT(&c, addr->type == ir::Type::iptr()); appendBranch(&c, op, @@ -2677,65 +2832,51 @@ class MyCompiler: public Compiler { ir::Value* a, ir::Value* b) { - assert(&c, - (isGeneralBinaryOp(op) and isGeneralValue(a) and isGeneralValue(b)) - or(isFloatBinaryOp(op) and isFloatValue(a) and isFloatValue(b))); + assertT(&c, + (isGeneralBinaryOp(op) and isGeneralValue(a) and isGeneralValue(b)) + or (isFloatBinaryOp(op) and isFloatValue(a) and isFloatValue(b))); Value* result = value(&c, type); - appendCombine(&c, - op, - static_cast(a), - static_cast(b), - result); + appendCombine( + &c, op, static_cast(a), static_cast(b), result); return result; } - virtual ir::Value* unaryOp(lir::BinaryOperation op, - ir::Value* a) + virtual ir::Value* unaryOp(lir::BinaryOperation op, ir::Value* a) { - assert(&c, - (isGeneralUnaryOp(op) and isGeneralValue(a))or(isFloatUnaryOp(op) - and isFloatValue(a))); + assertT(&c, + (isGeneralUnaryOp(op) and isGeneralValue(a)) + or (isFloatUnaryOp(op) and isFloatValue(a))); Value* result = value(&c, a->type); - appendTranslate( - &c, op, static_cast(a), result); + appendTranslate(&c, op, static_cast(a), result); return result; } virtual ir::Value* f2f(ir::Type resType, ir::Value* a) { - assert(&c, isFloatValue(a)); - assert(&c, resType.flavor() == ir::Type::Float); + assertT(&c, isFloatValue(a)); + assertT(&c, resType.flavor() == ir::Type::Float); Value* result = value(&c, resType); - appendTranslate(&c, - lir::Float2Float, - static_cast(a), - result); + appendTranslate(&c, lir::Float2Float, static_cast(a), result); return result; } virtual ir::Value* f2i(ir::Type resType, ir::Value* a) { - assert(&c, isFloatValue(a)); - assert(&c, resType.flavor() != ir::Type::Float); + assertT(&c, isFloatValue(a)); + assertT(&c, resType.flavor() != ir::Type::Float); Value* result = value(&c, resType); - appendTranslate(&c, - lir::Float2Int, - static_cast(a), - result); + appendTranslate(&c, lir::Float2Int, static_cast(a), result); return result; } virtual ir::Value* i2f(ir::Type resType, ir::Value* a) { - assert(&c, isGeneralValue(a)); - assert(&c, resType.flavor() == ir::Type::Float); + assertT(&c, isGeneralValue(a)); + assertT(&c, resType.flavor() == ir::Type::Float); Value* result = value(&c, resType); - appendTranslate(&c, - lir::Int2Float, - static_cast(a), - result); + appendTranslate(&c, lir::Int2Float, static_cast(a), result); return result; } @@ -2750,48 +2891,55 @@ class MyCompiler: public Compiler { compiler::compile(&c, stackOverflowHandler, stackLimitOffset); } - virtual unsigned resolve(uint8_t* dst) { + virtual unsigned resolve(uint8_t* dst) + { c.machineCode = dst; c.assembler->setDestination(dst); Block* block = c.firstBlock; while (block->nextBlock or block->nextInstruction) { Block* next = block->nextBlock - ? block->nextBlock - : block->nextInstruction->firstEvent->block; + ? block->nextBlock + : block->nextInstruction->firstEvent->block; - next->start = block->assemblerBlock->resolve - (block->start, next->assemblerBlock); + next->start + = block->assemblerBlock->resolve(block->start, next->assemblerBlock); block = next; } - return c.machineCodeSize = block->assemblerBlock->resolve - (block->start, 0) + c.assembler->footerSize(); + return c.machineCodeSize = block->assemblerBlock->resolve(block->start, 0) + + c.assembler->footerSize(); } - virtual unsigned poolSize() { + virtual unsigned poolSize() + { return c.constantCount * TargetBytesPerWord; } - virtual void write() { + virtual void write() + { c.assembler->write(); int i = 0; for (ConstantPoolNode* n = c.firstConstant; n; n = n->next) { - target_intptr_t* target = reinterpret_cast - (c.machineCode + pad(c.machineCodeSize, TargetBytesPerWord) + i); + target_intptr_t* target = reinterpret_cast( + c.machineCode + pad(c.machineCodeSize, TargetBytesPerWord) + i); if (n->promise->resolved()) { *target = targetVW(n->promise->value()); } else { - class Listener: public Promise::Listener { + class Listener : public Promise::Listener { public: - Listener(target_intptr_t* target): target(target){ } + Listener(target_intptr_t* target) : target(target) + { + } - virtual bool resolve(int64_t value, void** location) { + virtual bool resolve(int64_t value, void** location) + { *target = targetVW(value); - if (location) *location = target; + if (location) + *location = target; return true; } @@ -2804,7 +2952,8 @@ class MyCompiler: public Compiler { } } - virtual void dispose() { + virtual void dispose() + { // ignore } @@ -2812,14 +2961,15 @@ class MyCompiler: public Compiler { compiler::Client client; }; -} // namespace compiler +} // namespace compiler -Compiler* -makeCompiler(System* system, Assembler* assembler, Zone* zone, - Compiler::Client* client) +Compiler* makeCompiler(System* system, + Assembler* assembler, + Zone* zone, + Compiler::Client* client) { - return new(zone) compiler::MyCompiler(system, assembler, zone, client); + return new (zone) compiler::MyCompiler(system, assembler, zone, client); } -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/context.cpp b/src/codegen/compiler/context.cpp index 404b9aba28..c7b7a51741 100644 --- a/src/codegen/compiler/context.cpp +++ b/src/codegen/compiler/context.cpp @@ -53,18 +53,22 @@ Context::Context(vm::System* system, - regFile->generalRegisters.start), targetInfo(arch->targetInfo()) { - for (unsigned i = regFile->generalRegisters.start; i < regFile->generalRegisters.limit; ++i) { + for (unsigned i = regFile->generalRegisters.start; + i < regFile->generalRegisters.limit; + ++i) { new (registerResources + i) RegisterResource(arch->reserved(i)); if (registerResources[i].reserved) { - -- availableGeneralRegisterCount; + --availableGeneralRegisterCount; } } - for (unsigned i = regFile->floatRegisters.start; i < regFile->floatRegisters.limit; ++i) { + for (unsigned i = regFile->floatRegisters.start; + i < regFile->floatRegisters.limit; + ++i) { new (registerResources + i) RegisterResource(arch->reserved(i)); } } -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/context.h b/src/codegen/compiler/context.h index 03708f39c1..82488858a2 100644 --- a/src/codegen/compiler/context.h +++ b/src/codegen/compiler/context.h @@ -37,8 +37,9 @@ class ConstantPoolNode; class ForkState; class Block; -template -List* reverseDestroy(List* cell) { +template +List* reverseDestroy(List* cell) +{ List* previous = 0; while (cell) { List* next = cell->next; @@ -73,7 +74,7 @@ class LogicalCode { = logicalCode.cloneAndSet(zone, logicalCode.count + more, 0); for (size_t i = 0; i < logicalCode.count; i++) { - assert((vm::System*)0, logicalCode[i] == newCode[i]); + assertT((vm::System*)0, logicalCode[i] == newCode[i]); } logicalCode = newCode; @@ -93,7 +94,9 @@ class LogicalCode { class Context { public: - Context(vm::System* system, Assembler* assembler, vm::Zone* zone, + Context(vm::System* system, + Assembler* assembler, + vm::Zone* zone, Compiler::Client* client); vm::System* system; @@ -128,17 +131,19 @@ class Context { ir::TargetInfo targetInfo; }; -inline Aborter* getAborter(Context* c) { +inline Aborter* getAborter(Context* c) +{ return c->system; } -template -List* cons(Context* c, const T& value, List* next) { +template +List* cons(Context* c, const T& value, List* next) +{ return new (c->zone) List(value, next); } -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_CONTEXT_H +#endif // AVIAN_CODEGEN_COMPILER_CONTEXT_H diff --git a/src/codegen/compiler/event.cpp b/src/codegen/compiler/event.cpp index a1dc94d95a..5bd721815a 100644 --- a/src/codegen/compiler/event.cpp +++ b/src/codegen/compiler/event.cpp @@ -34,27 +34,41 @@ CodePromise* codePromise(Context* c, Promise* offset); void saveLocals(Context* c, Event* e); -void -apply(Context* c, lir::UnaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High); +void apply(Context* c, + lir::UnaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High); -void -apply(Context* c, lir::BinaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High); - -void -apply(Context* c, lir::TernaryOperation op, - unsigned s1Size, Site* s1Low, Site* s1High, - unsigned s2Size, Site* s2Low, Site* s2High, - unsigned s3Size, Site* s3Low, Site* s3High); +void apply(Context* c, + lir::BinaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High); +void apply(Context* c, + lir::TernaryOperation op, + unsigned s1Size, + Site* s1Low, + Site* s1High, + unsigned s2Size, + Site* s2Low, + Site* s2High, + unsigned s3Size, + Site* s3Low, + Site* s3High); void append(Context* c, Event* e); - -void clean(Context* c, Event* e, Stack* stack, Local* locals, Read* reads, - unsigned popIndex); +void clean(Context* c, + Event* e, + Stack* stack, + Local* locals, + Read* reads, + unsigned popIndex); Read* live(Context* c UNUSED, Value* v); @@ -69,35 +83,60 @@ void maybeMove(Context* c, Value* dst, const SiteMask& dstMask); -Site* -maybeMove(Context* c, Value* v, const SiteMask& mask, bool intersectMask, - bool includeNextWord, unsigned registerReserveCount = 0); +Site* maybeMove(Context* c, + Value* v, + const SiteMask& mask, + bool intersectMask, + bool includeNextWord, + unsigned registerReserveCount = 0); -Site* -maybeMove(Context* c, Read* read, bool intersectRead, bool includeNextWord, - unsigned registerReserveCount = 0); -Site* -pickSiteOrMove(Context* c, Value* src, Value* dst, Site* nextWord, - unsigned index); +Site* maybeMove(Context* c, + Read* read, + bool intersectRead, + bool includeNextWord, + unsigned registerReserveCount = 0); +Site* pickSiteOrMove(Context* c, + Value* src, + Value* dst, + Site* nextWord, + unsigned index); -Site* -pickTargetSite(Context* c, Read* read, bool intersectRead = false, - unsigned registerReserveCount = 0, - CostCalculator* costCalculator = 0); +Site* pickTargetSite(Context* c, + Read* read, + bool intersectRead = false, + unsigned registerReserveCount = 0, + CostCalculator* costCalculator = 0); Value* threadRegister(Context* c); -Event::Event(Context* c): - next(0), stackBefore(c->stack), localsBefore(c->locals), - stackAfter(0), localsAfter(0), promises(0), reads(0), - junctionSites(0), snapshots(0), predecessors(0), successors(0), - visitLinks(0), block(0), logicalInstruction(c->logicalCode[c->logicalIp]), - readCount(0) -{ } +Event::Event(Context* c) + : next(0), + stackBefore(c->stack), + localsBefore(c->locals), + stackAfter(0), + localsAfter(0), + promises(0), + reads(0), + junctionSites(0), + snapshots(0), + predecessors(0), + successors(0), + visitLinks(0), + block(0), + logicalInstruction(c->logicalCode[c->logicalIp]), + readCount(0) +{ +} -void Event::addRead(Context* c, Value* v, Read* r) { +void Event::addRead(Context* c, Value* v, Read* r) +{ if (DebugReads) { - fprintf(stderr, "add read %p to %p last %p event %p (%s)\n", - r, v, v->lastRead, this, (this ? this->name() : 0)); + fprintf(stderr, + "add read %p to %p last %p event %p (%s)\n", + r, + v, + v->lastRead, + this, + (this ? this->name() : 0)); } r->value = v; @@ -105,13 +144,13 @@ void Event::addRead(Context* c, Value* v, Read* r) { r->event = this; r->eventNext = this->reads; this->reads = r; - ++ this->readCount; + ++this->readCount; } if (v->lastRead) { - // if (DebugReads) { - // fprintf(stderr, "append %p to %p for %p\n", r, v->lastRead, v); - // } + if (DebugReads) { + fprintf(stderr, "append %p to %p for %p\n", r, v->lastRead, v); + } v->lastRead->append(c, r); } else { @@ -120,13 +159,21 @@ void Event::addRead(Context* c, Value* v, Read* r) { v->lastRead = r; } -void Event::addRead(Context* c, Value* v, const SiteMask& mask, Value* successor) { +void Event::addRead(Context* c, + Value* v, + const SiteMask& mask, + Value* successor) +{ this->addRead(c, v, read(c, mask, successor)); } -void Event::addReads(Context* c, Value* v, unsigned size, - const SiteMask& lowMask, Value* lowSuccessor, - const SiteMask& highMask, Value* highSuccessor) +void Event::addReads(Context* c, + Value* v, + unsigned size, + const SiteMask& lowMask, + Value* lowSuccessor, + const SiteMask& highMask, + Value* highSuccessor) { SingleRead* r = read(c, lowMask, lowSuccessor); this->addRead(c, v, r); @@ -136,33 +183,41 @@ void Event::addReads(Context* c, Value* v, unsigned size, } } -void Event::addReads(Context* c, Value* v, unsigned size, - const SiteMask& lowMask, const SiteMask& highMask) +void Event::addReads(Context* c, + Value* v, + unsigned size, + const SiteMask& lowMask, + const SiteMask& highMask) { this->addReads(c, v, size, lowMask, 0, highMask, 0); } -CodePromise* Event::makeCodePromise(Context* c) { - return this->promises = new(c->zone) CodePromise(c, this->promises); +CodePromise* Event::makeCodePromise(Context* c) +{ + return this->promises = new (c->zone) CodePromise(c, this->promises); } -bool Event::isUnreachable() { +bool Event::isUnreachable() +{ for (Link* p = this->predecessors; p; p = p->nextPredecessor) { - if (not p->predecessor->allExits()) return false; + if (not p->predecessor->allExits()) + return false; } return this->predecessors != 0; } -unsigned Link::countPredecessors() { +unsigned Link::countPredecessors() +{ Link* link = this; unsigned c = 0; for (; link; link = link->nextPredecessor) { - ++ c; + ++c; } return c; } -Link* Link::lastPredecessor() { +Link* Link::lastPredecessor() +{ Link* link = this; while (link->nextPredecessor) { link = link->nextPredecessor; @@ -170,20 +225,25 @@ Link* Link::lastPredecessor() { return link; } -unsigned Link::countSuccessors() { +unsigned Link::countSuccessors() +{ Link* link = this; unsigned c = 0; for (; link; link = link->nextSuccessor) { - ++ c; + ++c; } return c; } -Link* link(Context* c, Event* predecessor, Link* nextPredecessor, Event* successor, - Link* nextSuccessor, ForkState* forkState) +Link* link(Context* c, + Event* predecessor, + Link* nextPredecessor, + Event* successor, + Link* nextSuccessor, + ForkState* forkState) { - return new(c->zone) Link - (predecessor, nextPredecessor, successor, nextSuccessor, forkState); + return new (c->zone) + Link(predecessor, nextPredecessor, successor, nextSuccessor, forkState); } Value* maybeBuddySlice(Context* c, Value* v) @@ -235,12 +295,12 @@ Value* slicePushWord(Context* c, size_t index UNUSED = slice.count; - assert(c, slice.count < slice.capacity); + assertT(c, slice.count < slice.capacity); slice.push(v); - // if (DebugFrame) { - // fprintf(stderr, "push %p\n", v); - // } + if (false) { + fprintf(stderr, "push %p\n", v); + } if (v) { v->home = frameIndex(c, index + stackBase + c->localFootprint); @@ -255,7 +315,7 @@ void slicePush(Context* c, size_t stackBase, SliceStack& slice) { - assert(c, footprint); + assertT(c, footprint); bool bigEndian = c->arch->bigEndian(); @@ -267,7 +327,7 @@ void slicePush(Context* c, Value* high; if (footprint > 1) { - assert(c, footprint == 2); + assertT(c, footprint == 2); if (c->targetInfo.pointerSize == 4) { low->maybeSplit(c); @@ -290,7 +350,7 @@ void slicePush(Context* c, } } -class CallEvent: public Event { +class CallEvent : public Event { public: CallEvent(Context* c, Value* address, @@ -315,8 +375,8 @@ class CallEvent: public Event { uint32_t registerMask = c->regFile->generalRegisters.mask; if (callingConvention == ir::NativeCallingConvention) { - assert(c, (flags & Compiler::TailJump) == 0); - assert(c, stackArgumentFootprint == 0); + assertT(c, (flags & Compiler::TailJump) == 0); + assertT(c, stackArgumentFootprint == 0); unsigned index = 0; unsigned argumentIndex = 0; @@ -324,20 +384,18 @@ class CallEvent: public Event { while (true) { Value* v = static_cast(arguments[argumentIndex]); - unsigned footprint - = (argumentIndex + 1 < arguments.count and v->nextWord - == arguments[argumentIndex + 1]) - ? 2 - : 1; + unsigned footprint = (argumentIndex + 1 < arguments.count + and v->nextWord == arguments[argumentIndex + 1]) + ? 2 + : 1; if (index % (c->arch->argumentAlignment() ? footprint : 1)) { - ++ index; + ++index; } SiteMask targetMask; if (index + (c->arch->argumentRegisterAlignment() ? footprint : 1) - <= c->arch->argumentRegisterCount()) - { + <= c->arch->argumentRegisterCount()) { int number = c->arch->argumentRegister(index); if (DebugReads) { @@ -362,7 +420,7 @@ class CallEvent: public Event { this->addRead(c, v, targetMask); - ++ index; + ++index; if ((++argumentIndex) >= arguments.count) { break; @@ -374,17 +432,20 @@ class CallEvent: public Event { fprintf(stderr, "address read %p\n", address); } - { bool thunk; + { + bool thunk; OperandMask op; c->arch->plan((flags & Compiler::Aligned) ? lir::AlignedCall : lir::Call, c->targetInfo.pointerSize, op, &thunk); - assert(c, not thunk); + assertT(c, not thunk); - this->addRead(c, address, SiteMask - (op.typeMask, registerMask & op.registerMask, AnyFrameIndex)); + this->addRead( + c, + address, + SiteMask(op.typeMask, registerMask & op.registerMask, AnyFrameIndex)); } Stack* stack = stackBefore; @@ -399,9 +460,9 @@ class CallEvent: public Event { if ((c->targetInfo.pointerSize == 8 && (v == 0 || (i >= 1 && arguments[i - 1] == 0))) || (c->targetInfo.pointerSize == 4 && v->nextWord != v)) { - assert(c, - c->targetInfo.pointerSize == 8 - or v->nextWord == arguments[i - 1]); + assertT(c, + c->targetInfo.pointerSize == 8 + or v->nextWord == arguments[i - 1]); arguments[i] = arguments[i - 1]; --i; @@ -414,7 +475,7 @@ class CallEvent: public Event { int frameOffset; if (TailCalls and (flags & Compiler::TailJump)) { - assert(c, arguments.count == 0); + assertT(c, arguments.count == 0); int base = frameBase(c); returnAddressIndex = base + c->arch->returnAddressOffset(); @@ -425,7 +486,7 @@ class CallEvent: public Event { } frameOffset = totalFrameSize(c) - - c->arch->argumentFootprint(stackArgumentFootprint); + - c->arch->argumentFootprint(stackArgumentFootprint); } else { returnAddressIndex = -1; framePointerIndex = -1; @@ -438,8 +499,11 @@ class CallEvent: public Event { int frameIndex = i + frameOffset; if (DebugReads) { - fprintf(stderr, "stack arg read %p at %d of %d\n", - v, frameIndex, totalFrameSize(c)); + fprintf(stderr, + "stack arg read %p at %d of %d\n", + v, + frameIndex, + totalFrameSize(c)); } if (static_cast(frameIndex) == returnAddressIndex) { @@ -449,7 +513,8 @@ class CallEvent: public Event { framePointerSurrogate = v; this->addRead(c, v, generalRegisterMask(c)); } else { - this->addRead(c, v, SiteMask(1 << lir::MemoryOperand, 0, frameIndex)); + this->addRead( + c, v, SiteMask(1 << lir::MemoryOperand, 0, frameIndex)); } } } @@ -461,26 +526,27 @@ class CallEvent: public Event { stackArgumentIndex += stackBefore->index + 1 - stackArgumentFootprint; } - popIndex - = c->alignedFrameSize - + c->parameterFootprint - - c->arch->frameFooterSize() - - stackArgumentIndex; + popIndex = c->alignedFrameSize + c->parameterFootprint + - c->arch->frameFooterSize() - stackArgumentIndex; - assert(c, static_cast(popIndex) >= 0); + assertT(c, static_cast(popIndex) >= 0); while (stack) { if (stack->value) { - unsigned logicalIndex = compiler::frameIndex - (c, stack->index + c->localFootprint); + unsigned logicalIndex + = compiler::frameIndex(c, stack->index + c->localFootprint); if (DebugReads) { - fprintf(stderr, "stack save read %p at %d of %d\n", - stack->value, logicalIndex, totalFrameSize(c)); + fprintf(stderr, + "stack save read %p at %d of %d\n", + stack->value, + logicalIndex, + totalFrameSize(c)); } - this->addRead(c, stack->value, SiteMask - (1 << lir::MemoryOperand, 0, logicalIndex)); + this->addRead(c, + stack->value, + SiteMask(1 << lir::MemoryOperand, 0, logicalIndex)); } stack = stack->next; @@ -490,11 +556,13 @@ class CallEvent: public Event { } } - virtual const char* name() { + virtual const char* name() + { return "CallEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { lir::UnaryOperation op; unsigned footprint = c->arch->argumentFootprint(stackArgumentFootprint); @@ -512,17 +580,21 @@ class CallEvent: public Event { op = lir::Jump; } - assert(c, returnAddressSurrogate == 0 - or returnAddressSurrogate->source->type(c) == lir::RegisterOperand); - assert(c, framePointerSurrogate == 0 - or framePointerSurrogate->source->type(c) == lir::RegisterOperand); + assertT( + c, + returnAddressSurrogate == 0 + or returnAddressSurrogate->source->type(c) == lir::RegisterOperand); + assertT( + c, + framePointerSurrogate == 0 + or framePointerSurrogate->source->type(c) == lir::RegisterOperand); int ras; if (returnAddressSurrogate) { returnAddressSurrogate->source->freeze(c, returnAddressSurrogate); - ras = static_cast - (returnAddressSurrogate->source)->number; + ras = static_cast(returnAddressSurrogate->source) + ->number; } else { ras = lir::NoRegister; } @@ -531,8 +603,7 @@ class CallEvent: public Event { if (framePointerSurrogate) { framePointerSurrogate->source->freeze(c, framePointerSurrogate); - fps = static_cast - (framePointerSurrogate->source)->number; + fps = static_cast(framePointerSurrogate->source)->number; } else { fps = lir::NoRegister; } @@ -587,7 +658,8 @@ class CallEvent: public Event { } } - virtual bool allExits() { + virtual bool allExits() + { return (flags & Compiler::TailJump) != 0; } @@ -620,8 +692,7 @@ void appendCall(Context* c, arguments)); } - -class ReturnEvent: public Event { +class ReturnEvent : public Event { public: ReturnEvent(Context* c, Value* value) : Event(c), value(value) { @@ -634,19 +705,21 @@ class ReturnEvent: public Event { } } - virtual const char* name() { + virtual const char* name() + { return "ReturnEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { for (Read* r = reads; r; r = r->eventNext) { popRead(c, this, r->value); } - + if (not this->isUnreachable()) { - c->assembler->popFrameAndPopArgumentsAndReturn - (c->alignedFrameSize, - c->arch->argumentFootprint(c->parameterFootprint)); + c->assembler->popFrameAndPopArgumentsAndReturn( + c->alignedFrameSize, + c->arch->argumentFootprint(c->parameterFootprint)); } } @@ -658,7 +731,7 @@ void appendReturn(Context* c, Value* value) append(c, new (c->zone) ReturnEvent(c, value)); } -class MoveEvent: public Event { +class MoveEvent : public Event { public: MoveEvent(Context* c, lir::BinaryOperation op, @@ -677,7 +750,7 @@ class MoveEvent: public Event { dstSize(dstSize), dstValue(dstValue) { - assert(c, srcSelectSize <= srcSize); + assertT(c, srcSelectSize <= srcSize); bool noop = srcSelectSize >= dstSize; @@ -699,11 +772,13 @@ class MoveEvent: public Event { noop and dstSize > c->targetInfo.pointerSize ? dstValue->nextWord : 0); } - virtual const char* name() { + virtual const char* name() + { return "MoveEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { OperandMask dst; c->arch->planDestination( @@ -724,9 +799,15 @@ class MoveEvent: public Event { if (dstValue->target) { if (dstSize > c->targetInfo.pointerSize) { if (srcValue->source->registerSize(c) > c->targetInfo.pointerSize) { - apply(c, lir::Move, srcSelectSize, srcValue->source, srcValue->source, - dstSize, dstValue->target, dstValue->target); - + apply(c, + lir::Move, + srcSelectSize, + srcValue->source, + srcValue->source, + dstSize, + dstValue->target, + dstValue->target); + if (live(c, dstValue) == 0) { dstValue->removeSite(c, dstValue->target); if (dstSize > c->targetInfo.pointerSize) { @@ -783,11 +864,11 @@ class MoveEvent: public Event { dstValue, dstLowMask); } else { - assert(c, srcSize == c->targetInfo.pointerSize); - assert(c, srcSelectSize == c->targetInfo.pointerSize); + assertT(c, srcSize == c->targetInfo.pointerSize); + assertT(c, srcSelectSize == c->targetInfo.pointerSize); if (dstValue->nextWord->target or live(c, dstValue->nextWord)) { - assert(c, dstLowMask.typeMask & (1 << lir::RegisterOperand)); + assertT(c, dstLowMask.typeMask & (1 << lir::RegisterOperand)); Site* low = freeRegisterSite(c, dstLowMask.registerMask); @@ -796,12 +877,13 @@ class MoveEvent: public Event { dstValue->addSite(c, low); low->freeze(c, dstValue); - + if (DebugMoves) { - char srcb[256]; srcValue->source->toString(c, srcb, 256); - char dstb[256]; low->toString(c, dstb, 256); - fprintf(stderr, "move %s to %s for %p\n", - srcb, dstb, srcValue); + char srcb[256]; + srcValue->source->toString(c, srcb, 256); + char dstb[256]; + low->toString(c, dstb, 256); + fprintf(stderr, "move %s to %s for %p\n", srcb, dstb, srcValue); } apply(c, @@ -817,7 +899,7 @@ class MoveEvent: public Event { srcValue->source->thaw(c, srcValue); - assert(c, dstHighMask.typeMask & (1 << lir::RegisterOperand)); + assertT(c, dstHighMask.typeMask & (1 << lir::RegisterOperand)); Site* high = freeRegisterSite(c, dstHighMask.registerMask); @@ -826,12 +908,18 @@ class MoveEvent: public Event { dstValue->nextWord->addSite(c, high); high->freeze(c, dstValue->nextWord); - + if (DebugMoves) { - char srcb[256]; low->toString(c, srcb, 256); - char dstb[256]; high->toString(c, dstb, 256); - fprintf(stderr, "extend %s to %s for %p %p\n", - srcb, dstb, dstValue, dstValue->nextWord); + char srcb[256]; + low->toString(c, srcb, 256); + char dstb[256]; + high->toString(c, dstb, 256); + fprintf(stderr, + "extend %s to %s for %p %p\n", + srcb, + dstb, + dstValue, + dstValue->nextWord); } apply(c, @@ -877,7 +965,7 @@ void appendMove(Context* c, c->arch->planSource(op, srcSelectSize, src, dstSize, &thunk); - assert(c, not thunk); + assertT(c, not thunk); append(c, new (c->zone) MoveEvent(c, @@ -891,9 +979,7 @@ void appendMove(Context* c, SiteMask::highPart(src))); } - -void -freezeSource(Context* c, unsigned size, Value* v) +void freezeSource(Context* c, unsigned size, Value* v) { v->source->freeze(c, v); if (size > c->targetInfo.pointerSize) { @@ -901,8 +987,7 @@ freezeSource(Context* c, unsigned size, Value* v) } } -void -thawSource(Context* c, unsigned size, Value* v) +void thawSource(Context* c, unsigned size, Value* v) { v->source->thaw(c, v); if (size > c->targetInfo.pointerSize) { @@ -910,20 +995,24 @@ thawSource(Context* c, unsigned size, Value* v) } } -Read* liveNext(Context* c, Value* v) { - assert(c, v->buddy->hasBuddy(c, v)); +Read* liveNext(Context* c, Value* v) +{ + assertT(c, v->buddy->hasBuddy(c, v)); Read* r = v->reads->next(c); - if (valid(r)) return r; + if (valid(r)) + return r; for (Value* p = v->buddy; p != v; p = p->buddy) { - if (valid(p->reads)) return p->reads; + if (valid(p->reads)) + return p->reads; } return 0; } -void preserve(Context* c, Value* v, Read* r, Site* s) { +void preserve(Context* c, Value* v, Read* r, Site* s) +{ s->freeze(c, v); maybeMove(c, r, false, true, 0); @@ -931,15 +1020,18 @@ void preserve(Context* c, Value* v, Read* r, Site* s) { s->thaw(c, v); } -Site* getTarget(Context* c, Value* value, Value* result, const SiteMask& resultMask) { +Site* getTarget(Context* c, + Value* value, + Value* result, + const SiteMask& resultMask) +{ Site* s; Value* v; Read* r = liveNext(c, value); - if (value->source->match - (c, static_cast(resultMask)) - and (r == 0 or value->source->loneMatch - (c, static_cast(resultMask)))) - { + if (value->source->match(c, static_cast(resultMask)) + and (r == 0 + or value->source->loneMatch( + c, static_cast(resultMask)))) { s = value->source; v = value; if (r and v->uniqueSite(c, s)) { @@ -961,7 +1053,7 @@ Site* getTarget(Context* c, Value* value, Value* result, const SiteMask& resultM return s; } -class CombineEvent: public Event { +class CombineEvent : public Event { public: CombineEvent(Context* c, lir::TernaryOperation op, @@ -999,21 +1091,34 @@ class CombineEvent: public Event { condensed ? resultValue->nextWord : 0); } - virtual const char* name() { + virtual const char* name() + { return "CombineEvent"; } - virtual void compile(Context* c) { - assert(c, firstValue->source->type(c) == firstValue->nextWord->source->type(c)); + virtual void compile(Context* c) + { + assertT( + c, + firstValue->source->type(c) == firstValue->nextWord->source->type(c)); - // if (secondValue->source->type(c) != secondValue->nextWord->source->type(c)) { - // fprintf(stderr, "%p %p %d : %p %p %d\n", - // secondValue, secondValue->source, secondValue->source->type(c), - // secondValue->nextWord, secondValue->nextWord->source, - // secondValue->nextWord->source->type(c)); - // } + if (false) { + if (secondValue->source->type(c) + != secondValue->nextWord->source->type(c)) { + fprintf(stderr, + "%p %p %d : %p %p %d\n", + secondValue, + secondValue->source, + secondValue->source->type(c), + secondValue->nextWord, + secondValue->nextWord->source, + secondValue->nextWord->source->type(c)); + } + } - assert(c, secondValue->source->type(c) == secondValue->nextWord->source->type(c)); + assertT( + c, + secondValue->source->type(c) == secondValue->nextWord->source->type(c)); freezeSource(c, firstValue->type.size(c->targetInfo), firstValue); @@ -1050,10 +1155,16 @@ class CombineEvent: public Event { resultHighMask) : low); -// fprintf(stderr, "combine %p:%p and %p:%p into %p:%p\n", -// firstValue, firstValue->nextWord, -// secondValue, secondValue->nextWord, -// resultValue, resultValue->nextWord); + if (false) { + fprintf(stderr, + "combine %p:%p and %p:%p into %p:%p\n", + firstValue, + firstValue->nextWord, + secondValue, + secondValue->nextWord, + resultValue, + resultValue->nextWord); + } apply(c, op, @@ -1141,7 +1252,7 @@ void appendCombine(Context* c, slice); if (threadParameter) { - ++ stackSize; + ++stackSize; slicePush(c, 1, threadRegister(c), stackBase, slice); } @@ -1167,7 +1278,7 @@ void appendCombine(Context* c, } } -class TranslateEvent: public Event { +class TranslateEvent : public Event { public: TranslateEvent(Context* c, lir::BinaryOperation op, @@ -1192,12 +1303,16 @@ class TranslateEvent: public Event { condensed ? resultValue->nextWord : 0); } - virtual const char* name() { + virtual const char* name() + { return "TranslateEvent"; } - virtual void compile(Context* c) { - assert(c, firstValue->source->type(c) == firstValue->nextWord->source->type(c)); + virtual void compile(Context* c) + { + assertT( + c, + firstValue->source->type(c) == firstValue->nextWord->source->type(c)); OperandMask bMask; @@ -1215,7 +1330,7 @@ class TranslateEvent: public Event { SiteMask resultLowMask = SiteMask::lowPart(bMask); SiteMask resultHighMask = SiteMask::highPart(bMask); - + Site* low = getTarget(c, firstValue, resultValue, resultLowMask); unsigned lowSize = low->registerSize(c); Site* high = (resultValue->type.size(c->targetInfo) > lowSize @@ -1265,12 +1380,12 @@ void appendTranslate(Context* c, Value* firstValue, Value* resultValue) { - assert(c, - firstValue->type.size(c->targetInfo) - == firstValue->type.size(c->targetInfo)); - assert(c, - resultValue->type.size(c->targetInfo) - == resultValue->type.size(c->targetInfo)); + assertT(c, + firstValue->type.size(c->targetInfo) + == firstValue->type.size(c->targetInfo)); + assertT(c, + resultValue->type.size(c->targetInfo) + == resultValue->type.size(c->targetInfo)); bool thunk; OperandMask first; @@ -1316,30 +1431,32 @@ void appendTranslate(Context* c, } } -class OperationEvent: public Event { +class OperationEvent : public Event { public: - OperationEvent(Context* c, lir::Operation op): - Event(c), op(op) - { } + OperationEvent(Context* c, lir::Operation op) : Event(c), op(op) + { + } - virtual const char* name() { + virtual const char* name() + { return "OperationEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { c->assembler->apply(op); } lir::Operation op; }; -void -appendOperation(Context* c, lir::Operation op) +void appendOperation(Context* c, lir::Operation op) { - append(c, new(c->zone) OperationEvent(c, op)); + append(c, new (c->zone) OperationEvent(c, op)); } -ConstantSite* findConstantSite(Context* c, Value* v) { +ConstantSite* findConstantSite(Context* c, Value* v) +{ for (SiteIterator it(c, v); it.hasMore();) { Site* s = it.next(); if (s->type(c) == lir::ConstantOperand) { @@ -1349,8 +1466,7 @@ ConstantSite* findConstantSite(Context* c, Value* v) { return 0; } -void -moveIfConflict(Context* c, Value* v, MemorySite* s) +void moveIfConflict(Context* c, Value* v, MemorySite* s) { if (v->reads) { SiteMask mask(1 << lir::RegisterOperand, ~0, AnyFrameIndex); @@ -1362,12 +1478,20 @@ moveIfConflict(Context* c, Value* v, MemorySite* s) } } -class MemoryEvent: public Event { +class MemoryEvent : public Event { public: - MemoryEvent(Context* c, Value* base, int displacement, Value* index, - unsigned scale, Value* result): - Event(c), base(base), displacement(displacement), index(index), - scale(scale), result(result) + MemoryEvent(Context* c, + Value* base, + int displacement, + Value* index, + unsigned scale, + Value* result) + : Event(c), + base(base), + displacement(displacement), + index(index), + scale(scale), + result(result) { this->addRead(c, base, generalRegisterMask(c)); if (index) { @@ -1375,11 +1499,13 @@ class MemoryEvent: public Event { } } - virtual const char* name() { + virtual const char* name() + { return "MemoryEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { int indexRegister; int displacement = this->displacement; unsigned scale = this->scale; @@ -1391,27 +1517,33 @@ class MemoryEvent: public Event { displacement += (constant->value->value() * scale); scale = 1; } else { - assert(c, index->source->type(c) == lir::RegisterOperand); + assertT(c, index->source->type(c) == lir::RegisterOperand); indexRegister = static_cast(index->source)->number; } } else { indexRegister = lir::NoRegister; } - assert(c, base->source->type(c) == lir::RegisterOperand); + assertT(c, base->source->type(c) == lir::RegisterOperand); int baseRegister = static_cast(base->source)->number; popRead(c, this, base); if (index) { if (c->targetInfo.pointerSize == 8 and indexRegister != lir::NoRegister) { - apply(c, lir::Move, 4, index->source, index->source, - 8, index->source, index->source); + apply(c, + lir::Move, + 4, + index->source, + index->source, + 8, + index->source, + index->source); } popRead(c, this, index); } - MemorySite* site = memorySite - (c, baseRegister, displacement, indexRegister, scale); + MemorySite* site + = memorySite(c, baseRegister, displacement, indexRegister, scale); MemorySite* low; if (result->nextWord != result) { @@ -1437,15 +1569,20 @@ class MemoryEvent: public Event { Value* result; }; -void -appendMemory(Context* c, Value* base, int displacement, Value* index, - unsigned scale, Value* result) +void appendMemory(Context* c, + Value* base, + int displacement, + Value* index, + unsigned scale, + Value* result) { - append(c, new(c->zone) + append(c, + new (c->zone) MemoryEvent(c, base, displacement, index, scale, result)); } -double asFloat(unsigned size, int64_t v) { +double asFloat(unsigned size, int64_t v) +{ if (size == 4) { return vm::bitsToFloat(v); } else { @@ -1453,10 +1590,9 @@ double asFloat(unsigned size, int64_t v) { } } -bool -unordered(double a, double b) +bool unordered(double a, double b) { - return not (a >= b or a < b); + return not(a >= b or a < b); } bool shouldJump(Context* c, @@ -1504,19 +1640,19 @@ bool shouldJump(Context* c, case lir::JumpIfFloatLessOrUnordered: return asFloat(size, a) < asFloat(size, b) - or unordered(asFloat(size, a), asFloat(size, b)); + or unordered(asFloat(size, a), asFloat(size, b)); case lir::JumpIfFloatGreaterOrUnordered: return asFloat(size, a) > asFloat(size, b) - or unordered(asFloat(size, a), asFloat(size, b)); + or unordered(asFloat(size, a), asFloat(size, b)); case lir::JumpIfFloatLessOrEqualOrUnordered: return asFloat(size, a) <= asFloat(size, b) - or unordered(asFloat(size, a), asFloat(size, b)); + or unordered(asFloat(size, a), asFloat(size, b)); case lir::JumpIfFloatGreaterOrEqualOrUnordered: return asFloat(size, a) >= asFloat(size, b) - or unordered(asFloat(size, a), asFloat(size, b)); + or unordered(asFloat(size, a), asFloat(size, b)); default: abort(c); @@ -1553,7 +1689,7 @@ lir::TernaryOperation thunkBranch(Context* c, lir::TernaryOperation op) } } -class BranchEvent: public Event { +class BranchEvent : public Event { public: BranchEvent(Context* c, lir::TernaryOperation op, @@ -1593,28 +1729,29 @@ class BranchEvent: public Event { this->addRead(c, addressValue, SiteMask::lowPart(dstMask)); } - virtual const char* name() { + virtual const char* name() + { return "BranchEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { ConstantSite* firstConstant = findConstantSite(c, firstValue); ConstantSite* secondConstant = findConstantSite(c, secondValue); if (not this->isUnreachable()) { - if (firstConstant - and secondConstant - and firstConstant->value->resolved() - and secondConstant->value->resolved()) - { + if (firstConstant and secondConstant and firstConstant->value->resolved() + and secondConstant->value->resolved()) { int64_t firstConstVal = firstConstant->value->value(); int64_t secondConstVal = secondConstant->value->value(); if (firstValue->type.size(c->targetInfo) > c->targetInfo.pointerSize) { - firstConstVal |= findConstantSite - (c, firstValue->nextWord)->value->value() << 32; - secondConstVal |= findConstantSite - (c, secondValue->nextWord)->value->value() << 32; + firstConstVal + |= findConstantSite(c, firstValue->nextWord)->value->value() + << 32; + secondConstVal + |= findConstantSite(c, secondValue->nextWord)->value->value() + << 32; } if (shouldJump(c, @@ -1627,7 +1764,7 @@ class BranchEvent: public Event { c->targetInfo.pointerSize, addressValue->source, addressValue->source); - } + } } else { freezeSource(c, firstValue->type.size(c->targetInfo), firstValue); freezeSource(c, firstValue->type.size(c->targetInfo), secondValue); @@ -1656,7 +1793,10 @@ class BranchEvent: public Event { } } - virtual bool isBranch() { return true; } + virtual bool isBranch() + { + return true; + } lir::TernaryOperation op; Value* firstValue; @@ -1693,7 +1833,7 @@ void appendBranch(Context* c, firstValue->type.size(c->targetInfo), &threadParameter); - assert(c, not threadParameter); + assertT(c, not threadParameter); slicePush(c, ceilingDivide(firstValue->type.size(c->targetInfo), @@ -1737,21 +1877,23 @@ void appendBranch(Context* c, } } -void clean(Context* c, Value* v, unsigned popIndex) { +void clean(Context* c, Value* v, unsigned popIndex) +{ for (SiteIterator it(c, v); it.hasMore();) { Site* s = it.next(); - if (not (s->match(c, SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex)) - and offsetToFrameIndex - (c, static_cast(s)->offset) - >= popIndex)) - { - if (false and - s->match(c, SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex))) - { - char buffer[256]; s->toString(c, buffer, 256); - fprintf(stderr, "remove %s from %p at %d pop offset 0x%x\n", - buffer, v, offsetToFrameIndex - (c, static_cast(s)->offset), + if (not(s->match(c, SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex)) + and offsetToFrameIndex(c, static_cast(s)->offset) + >= popIndex)) { + if (false + and s->match(c, + SiteMask(1 << lir::MemoryOperand, 0, AnyFrameIndex))) { + char buffer[256]; + s->toString(c, buffer, 256); + fprintf(stderr, + "remove %s from %p at %d pop offset 0x%x\n", + buffer, + v, + offsetToFrameIndex(c, static_cast(s)->offset), frameIndexToOffset(c, popIndex)); } it.remove(c); @@ -1759,9 +1901,12 @@ void clean(Context* c, Value* v, unsigned popIndex) { } } -void -clean(Context* c, Event* e, Stack* stack, Local* locals, Read* reads, - unsigned popIndex) +void clean(Context* c, + Event* e, + Stack* stack, + Local* locals, + Read* reads, + unsigned popIndex) { for (FrameIterator it(c, stack, locals); it.hasMore();) { FrameIterator::Element e = it.next(c); @@ -1773,7 +1918,7 @@ clean(Context* c, Event* e, Stack* stack, Local* locals, Read* reads, } } -class JumpEvent: public Event { +class JumpEvent : public Event { public: JumpEvent(Context* c, lir::UnaryOperation op, @@ -1786,16 +1931,18 @@ class JumpEvent: public Event { OperandMask mask; c->arch->plan(op, c->targetInfo.pointerSize, mask, &thunk); - assert(c, not thunk); + assertT(c, not thunk); this->addRead(c, address, SiteMask::lowPart(mask)); } - virtual const char* name() { + virtual const char* name() + { return "JumpEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { if (not this->isUnreachable()) { apply(c, op, c->targetInfo.pointerSize, address->source, address->source); } @@ -1812,9 +1959,13 @@ class JumpEvent: public Event { } } - virtual bool isBranch() { return true; } + virtual bool isBranch() + { + return true; + } - virtual bool allExits() { + virtual bool allExits() + { return exit or this->isUnreachable(); } @@ -1833,22 +1984,30 @@ void appendJump(Context* c, append(c, new (c->zone) JumpEvent(c, op, address, exit, cleanLocals)); } -class BoundsCheckEvent: public Event { +class BoundsCheckEvent : public Event { public: - BoundsCheckEvent(Context* c, Value* object, unsigned lengthOffset, - Value* index, intptr_t handler): - Event(c), object(object), lengthOffset(lengthOffset), index(index), - handler(handler) + BoundsCheckEvent(Context* c, + Value* object, + unsigned lengthOffset, + Value* index, + intptr_t handler) + : Event(c), + object(object), + lengthOffset(lengthOffset), + index(index), + handler(handler) { this->addRead(c, object, generalRegisterMask(c)); this->addRead(c, index, generalRegisterOrConstantMask(c)); } - virtual const char* name() { + virtual const char* name() + { return "BoundsCheckEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { Assembler* a = c->assembler; ConstantSite* constant = findConstantSite(c, index); @@ -1881,12 +2040,15 @@ class BoundsCheckEvent: public Event { } if (constant == 0 or constant->value->value() >= 0) { - assert(c, object->source->type(c) == lir::RegisterOperand); + assertT(c, object->source->type(c) == lir::RegisterOperand); MemorySite length(static_cast(object->source)->number, - lengthOffset, lir::NoRegister, 1); + lengthOffset, + lir::NoRegister, + 1); length.acquired = true; - CodePromise* nextPromise = compiler::codePromise(c, static_cast(0)); + CodePromise* nextPromise + = compiler::codePromise(c, static_cast(0)); freezeSource(c, c->targetInfo.pointerSize, index); @@ -1928,25 +2090,31 @@ class BoundsCheckEvent: public Event { intptr_t handler; }; -void -appendBoundsCheck(Context* c, Value* object, unsigned lengthOffset, - Value* index, intptr_t handler) +void appendBoundsCheck(Context* c, + Value* object, + unsigned lengthOffset, + Value* index, + intptr_t handler) { - append(c, new(c->zone) BoundsCheckEvent(c, object, lengthOffset, index, handler)); + append(c, + new (c->zone) + BoundsCheckEvent(c, object, lengthOffset, index, handler)); } - -class FrameSiteEvent: public Event { +class FrameSiteEvent : public Event { public: - FrameSiteEvent(Context* c, Value* value, int index): - Event(c), value(value), index(index) - { } + FrameSiteEvent(Context* c, Value* value, int index) + : Event(c), value(value), index(index) + { + } - virtual const char* name() { + virtual const char* name() + { return "FrameSiteEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { if (live(c, value)) { value->addSite(c, frameSite(c, index)); } @@ -1956,59 +2124,60 @@ class FrameSiteEvent: public Event { int index; }; -void -appendFrameSite(Context* c, Value* value, int index) +void appendFrameSite(Context* c, Value* value, int index) { - append(c, new(c->zone) FrameSiteEvent(c, value, index)); + append(c, new (c->zone) FrameSiteEvent(c, value, index)); } -class SaveLocalsEvent: public Event { +class SaveLocalsEvent : public Event { public: - SaveLocalsEvent(Context* c): - Event(c) + SaveLocalsEvent(Context* c) : Event(c) { saveLocals(c, this); } - virtual const char* name() { + virtual const char* name() + { return "SaveLocalsEvent"; } - virtual void compile(Context* c) { + virtual void compile(Context* c) + { for (Read* r = reads; r; r = r->eventNext) { popRead(c, this, r->value); } } }; -void -appendSaveLocals(Context* c) +void appendSaveLocals(Context* c) { - append(c, new(c->zone) SaveLocalsEvent(c)); + append(c, new (c->zone) SaveLocalsEvent(c)); } -class DummyEvent: public Event { +class DummyEvent : public Event { public: - DummyEvent(Context* c, Local* locals): - Event(c), - locals_(locals) - { } + DummyEvent(Context* c, Local* locals) : Event(c), locals_(locals) + { + } - virtual const char* name() { + virtual const char* name() + { return "DummyEvent"; } - virtual void compile(Context*) { } + virtual void compile(Context*) + { + } - virtual Local* locals() { + virtual Local* locals() + { return locals_; } Local* locals_; }; -void -appendDummy(Context* c) +void appendDummy(Context* c) { Stack* stack = c->stack; Local* locals = c->locals; @@ -2017,12 +2186,12 @@ appendDummy(Context* c) c->stack = i->stack; c->locals = i->locals; - append(c, new(c->zone) DummyEvent(c, locals)); + append(c, new (c->zone) DummyEvent(c, locals)); c->stack = stack; - c->locals = locals; + c->locals = locals; } -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/event.h b/src/codegen/compiler/event.h index 03e21d2bc2..dbdb896edb 100644 --- a/src/codegen/compiler/event.h +++ b/src/codegen/compiler/event.h @@ -33,25 +33,41 @@ class Event { virtual void compile(Context* c) = 0; - virtual bool isBranch() { return false; } - - virtual bool allExits() { return false; } - - virtual Local* locals() { return localsBefore; } + virtual bool isBranch() + { + return false; + } + virtual bool allExits() + { + return false; + } + virtual Local* locals() + { + return localsBefore; + } void addRead(Context* c, Value* v, Read* r); - void addRead(Context* c, Value* v, const SiteMask& mask, - Value* successor = 0); + void addRead(Context* c, + Value* v, + const SiteMask& mask, + Value* successor = 0); - void addReads(Context* c, Value* v, unsigned size, - const SiteMask& lowMask, Value* lowSuccessor, - const SiteMask& highMask, Value* highSuccessor); + void addReads(Context* c, + Value* v, + unsigned size, + const SiteMask& lowMask, + Value* lowSuccessor, + const SiteMask& highMask, + Value* highSuccessor); - void addReads(Context* c, Value* v, unsigned size, - const SiteMask& lowMask, const SiteMask& highMask); + void addReads(Context* c, + Value* v, + unsigned size, + const SiteMask& lowMask, + const SiteMask& highMask); CodePromise* makeCodePromise(Context* c); @@ -82,7 +98,9 @@ class StubReadPair { class JunctionState { public: - JunctionState(unsigned frameFootprint): frameFootprint(frameFootprint) { } + JunctionState(unsigned frameFootprint) : frameFootprint(frameFootprint) + { + } unsigned frameFootprint; StubReadPair reads[0]; @@ -90,12 +108,19 @@ class JunctionState { class Link { public: - Link(Event* predecessor, Link* nextPredecessor, Event* successor, - Link* nextSuccessor, ForkState* forkState): - predecessor(predecessor), nextPredecessor(nextPredecessor), - successor(successor), nextSuccessor(nextSuccessor), forkState(forkState), - junctionState(0) - { } + Link(Event* predecessor, + Link* nextPredecessor, + Event* successor, + Link* nextSuccessor, + ForkState* forkState) + : predecessor(predecessor), + nextPredecessor(nextPredecessor), + successor(successor), + nextSuccessor(nextSuccessor), + forkState(forkState), + junctionState(0) + { + } unsigned countPredecessors(); Link* lastPredecessor(); @@ -109,9 +134,12 @@ class Link { JunctionState* junctionState; }; -Link* -link(Context* c, Event* predecessor, Link* nextPredecessor, Event* successor, - Link* nextSuccessor, ForkState* forkState); +Link* link(Context* c, + Event* predecessor, + Link* nextPredecessor, + Event* successor, + Link* nextSuccessor, + ForkState* forkState); void appendCall(Context* c, Value* address, @@ -142,12 +170,14 @@ void appendTranslate(Context* c, Value* first, Value* result); -void -appendOperation(Context* c, lir::Operation op); +void appendOperation(Context* c, lir::Operation op); -void -appendMemory(Context* c, Value* base, int displacement, Value* index, - unsigned scale, Value* result); +void appendMemory(Context* c, + Value* base, + int displacement, + Value* index, + unsigned scale, + Value* result); void appendBranch(Context* c, lir::TernaryOperation op, @@ -161,23 +191,22 @@ void appendJump(Context* c, bool exit = false, bool cleanLocals = false); -void -appendBoundsCheck(Context* c, Value* object, unsigned lengthOffset, - Value* index, intptr_t handler); +void appendBoundsCheck(Context* c, + Value* object, + unsigned lengthOffset, + Value* index, + intptr_t handler); -void -appendFrameSite(Context* c, Value* value, int index); +void appendFrameSite(Context* c, Value* value, int index); -void -appendSaveLocals(Context* c); +void appendSaveLocals(Context* c); -void -appendDummy(Context* c); +void appendDummy(Context* c); void appendBuddy(Context* c, Value* original, Value* buddy); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_EVENT_H +#endif // AVIAN_CODEGEN_COMPILER_EVENT_H diff --git a/src/codegen/compiler/frame.cpp b/src/codegen/compiler/frame.cpp index 223d036e9d..389c0b06f3 100644 --- a/src/codegen/compiler/frame.cpp +++ b/src/codegen/compiler/frame.cpp @@ -19,14 +19,15 @@ namespace avian { namespace codegen { namespace compiler { -unsigned totalFrameSize(Context* c) { - return c->alignedFrameSize - + c->arch->frameHeaderSize() - + c->arch->argumentFootprint(c->parameterFootprint); +unsigned totalFrameSize(Context* c) +{ + return c->alignedFrameSize + c->arch->frameHeaderSize() + + c->arch->argumentFootprint(c->parameterFootprint); } -int frameIndex(Context* c, int localIndex) { - assert(c, localIndex >= 0); +int frameIndex(Context* c, int localIndex) +{ + assertT(c, localIndex >= 0); int index = c->alignedFrameSize + c->parameterFootprint - localIndex - 1; @@ -36,66 +37,75 @@ int frameIndex(Context* c, int localIndex) { index -= c->arch->frameFooterSize(); } - assert(c, index >= 0); - assert(c, static_cast(index) < totalFrameSize(c)); + assertT(c, index >= 0); + assertT(c, static_cast(index) < totalFrameSize(c)); return index; } -unsigned frameIndexToOffset(Context* c, unsigned frameIndex) { - assert(c, frameIndex < totalFrameSize(c)); +unsigned frameIndexToOffset(Context* c, unsigned frameIndex) +{ + assertT(c, frameIndex < totalFrameSize(c)); return (frameIndex + c->arch->frameFooterSize()) * c->targetInfo.pointerSize; } -unsigned offsetToFrameIndex(Context* c, unsigned offset) { - assert(c, - static_cast((offset / c->targetInfo.pointerSize) - - c->arch->frameFooterSize()) >= 0); - assert(c, - ((offset / c->targetInfo.pointerSize) - c->arch->frameFooterSize()) - < totalFrameSize(c)); +unsigned offsetToFrameIndex(Context* c, unsigned offset) +{ + assertT(c, + static_cast((offset / c->targetInfo.pointerSize) + - c->arch->frameFooterSize()) >= 0); + assertT(c, + ((offset / c->targetInfo.pointerSize) - c->arch->frameFooterSize()) + < totalFrameSize(c)); return (offset / c->targetInfo.pointerSize) - c->arch->frameFooterSize(); } -unsigned frameBase(Context* c) { - return c->alignedFrameSize - - c->arch->frameReturnAddressSize() - - c->arch->frameFooterSize() - + c->arch->frameHeaderSize(); -} +unsigned frameBase(Context* c) +{ + return c->alignedFrameSize - c->arch->frameReturnAddressSize() + - c->arch->frameFooterSize() + c->arch->frameHeaderSize(); +} -FrameIterator::Element::Element(Value* value, unsigned localIndex): - value(value), localIndex(localIndex) -{ } +FrameIterator::Element::Element(Value* value, unsigned localIndex) + : value(value), localIndex(localIndex) +{ +} - -int FrameIterator::Element::frameIndex(Context* c) { +int FrameIterator::Element::frameIndex(Context* c) +{ return compiler::frameIndex(c, this->localIndex); } -FrameIterator::FrameIterator(Context* c, Stack* stack, Local* locals, - bool includeEmpty): - stack(stack), locals(locals), localIndex(c->localFootprint - 1), - includeEmpty(includeEmpty) -{ } +FrameIterator::FrameIterator(Context* c, + Stack* stack, + Local* locals, + bool includeEmpty) + : stack(stack), + locals(locals), + localIndex(c->localFootprint - 1), + includeEmpty(includeEmpty) +{ +} -bool FrameIterator::hasMore() { +bool FrameIterator::hasMore() +{ if (not includeEmpty) { while (stack and stack->value == 0) { stack = stack->next; } while (localIndex >= 0 and locals[localIndex].value == 0) { - -- localIndex; + --localIndex; } } return stack != 0 or localIndex >= 0; } -FrameIterator::Element FrameIterator::next(Context* c) { +FrameIterator::Element FrameIterator::next(Context* c) +{ Value* v; unsigned li; if (stack) { @@ -107,17 +117,16 @@ FrameIterator::Element FrameIterator::next(Context* c) { Local* l = locals + localIndex; v = l->value; li = localIndex; - -- localIndex; + --localIndex; } return Element(v, li); } -Stack* stack(Context* c, Value* value, Stack* next) { - return new(c->zone) Stack(next ? next->index + 1 : 0, value, next); +Stack* stack(Context* c, Value* value, Stack* next) +{ + return new (c->zone) Stack(next ? next->index + 1 : 0, value, next); } - - -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/frame.h b/src/codegen/compiler/frame.h index de361765fe..e0cf976d0b 100644 --- a/src/codegen/compiler/frame.h +++ b/src/codegen/compiler/frame.h @@ -37,7 +37,9 @@ class FrameIterator { const unsigned localIndex; }; - FrameIterator(Context* c, Stack* stack, Local* locals, + FrameIterator(Context* c, + Stack* stack, + Local* locals, bool includeEmpty = false); bool hasMore(); @@ -57,9 +59,10 @@ class Local { class Stack { public: - Stack(unsigned index, Value* value, Stack* next): - index(index), value(value), next(next) - { } + Stack(unsigned index, Value* value, Stack* next) + : index(index), value(value), next(next) + { + } unsigned index; Value* value; @@ -68,8 +71,8 @@ class Stack { Stack* stack(Context* c, Value* value, Stack* next); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_FRAME_H +#endif // AVIAN_CODEGEN_COMPILER_FRAME_H diff --git a/src/codegen/compiler/ir.cpp b/src/codegen/compiler/ir.cpp index abd6cc608f..aa9534adda 100644 --- a/src/codegen/compiler/ir.cpp +++ b/src/codegen/compiler/ir.cpp @@ -23,31 +23,35 @@ LogicalInstruction::LogicalInstruction(int index, Stack* stack, Local* locals) locals(locals), machineOffset(0), /*subroutine(0), */ index(index) -{ } +{ +} -LogicalInstruction* LogicalInstruction::next(Context* c) { +LogicalInstruction* LogicalInstruction::next(Context* c) +{ LogicalInstruction* i = this; for (size_t n = i->index + 1; n < c->logicalCode.count(); ++n) { i = c->logicalCode[n]; - if (i) return i; + if (i) + return i; } return 0; } -unsigned -machineOffset(Context* c, int logicalIp) +unsigned machineOffset(Context* c, int logicalIp) { return c->logicalCode[logicalIp]->machineOffset->value(); } -Block::Block(Event* head): - head(head), nextBlock(0), nextInstruction(0), assemblerBlock(0), start(0) -{ } - -Block* block(Context* c, Event* head) { - return new(c->zone) Block(head); +Block::Block(Event* head) + : head(head), nextBlock(0), nextInstruction(0), assemblerBlock(0), start(0) +{ } -} // namespace compiler -} // namespace codegen -} // namespace avian +Block* block(Context* c, Event* head) +{ + return new (c->zone) Block(head); +} + +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/ir.h b/src/codegen/compiler/ir.h index 8b919c44a4..64e34bfc4e 100644 --- a/src/codegen/compiler/ir.h +++ b/src/codegen/compiler/ir.h @@ -24,17 +24,21 @@ class ForkElement { bool local; }; -class ForkState: public Compiler::State { +class ForkState : public Compiler::State { public: - ForkState(Stack* stack, Local* locals, List* saved, Event* predecessor, - unsigned logicalIp): - stack(stack), - locals(locals), - saved(saved), - predecessor(predecessor), - logicalIp(logicalIp), - readCount(0) - { } + ForkState(Stack* stack, + Local* locals, + List* saved, + Event* predecessor, + unsigned logicalIp) + : stack(stack), + locals(locals), + saved(saved), + predecessor(predecessor), + logicalIp(logicalIp), + readCount(0) + { + } Stack* stack; Local* locals; @@ -75,8 +79,8 @@ Block* block(Context* c, Event* head); unsigned machineOffset(Context* c, int logicalIp); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_IR_H +#endif // AVIAN_CODEGEN_COMPILER_IR_H diff --git a/src/codegen/compiler/promise.cpp b/src/codegen/compiler/promise.cpp index 1567140cca..ef370be200 100644 --- a/src/codegen/compiler/promise.cpp +++ b/src/codegen/compiler/promise.cpp @@ -18,88 +18,104 @@ namespace avian { namespace codegen { namespace compiler { -CodePromise::CodePromise(Context* c, CodePromise* next): - c(c), offset(0), next(next) -{ } +CodePromise::CodePromise(Context* c, CodePromise* next) + : c(c), offset(0), next(next) +{ +} -CodePromise::CodePromise(Context* c, Promise* offset): - c(c), offset(offset), next(0) -{ } +CodePromise::CodePromise(Context* c, Promise* offset) + : c(c), offset(offset), next(0) +{ +} -int64_t CodePromise::value() { +int64_t CodePromise::value() +{ if (resolved()) { return reinterpret_cast(c->machineCode + offset->value()); } - + abort(c); } -bool CodePromise::resolved() { +bool CodePromise::resolved() +{ return c->machineCode != 0 and offset and offset->resolved(); } -CodePromise* codePromise(Context* c, Promise* offset) { +CodePromise* codePromise(Context* c, Promise* offset) +{ return new (c->zone) CodePromise(c, offset); } -Promise* shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask) { +Promise* shiftMaskPromise(Context* c, + Promise* base, + unsigned shift, + int64_t mask) +{ return new (c->zone) ShiftMaskPromise(base, shift, mask); } -Promise* combinedPromise(Context* c, Promise* low, Promise* high) { +Promise* combinedPromise(Context* c, Promise* low, Promise* high) +{ return new (c->zone) CombinedPromise(low, high); } -Promise* resolvedPromise(Context* c, int64_t value) { +Promise* resolvedPromise(Context* c, int64_t value) +{ return new (c->zone) ResolvedPromise(value); } -class IpPromise: public Promise { +class IpPromise : public Promise { public: - IpPromise(Context* c, int logicalIp): - c(c), - logicalIp(logicalIp) - { } + IpPromise(Context* c, int logicalIp) : c(c), logicalIp(logicalIp) + { + } - virtual int64_t value() { + virtual int64_t value() + { if (resolved()) { - return reinterpret_cast - (c->machineCode + machineOffset(c, logicalIp)); + return reinterpret_cast(c->machineCode + + machineOffset(c, logicalIp)); } abort(c); } - virtual bool resolved() { + virtual bool resolved() + { return c->machineCode != 0 - and c->logicalCode[logicalIp]->machineOffset->resolved(); + and c->logicalCode[logicalIp]->machineOffset->resolved(); } Context* c; int logicalIp; }; -Promise* ipPromise(Context* c, int logicalIp) { +Promise* ipPromise(Context* c, int logicalIp) +{ return new (c->zone) IpPromise(c, logicalIp); } - -class PoolPromise: public Promise { +class PoolPromise : public Promise { public: - PoolPromise(Context* c, int key): c(c), key(key) { } + PoolPromise(Context* c, int key) : c(c), key(key) + { + } - virtual int64_t value() { + virtual int64_t value() + { if (resolved()) { return reinterpret_cast( c->machineCode + vm::pad(c->machineCodeSize, c->targetInfo.pointerSize) + (key * c->targetInfo.pointerSize)); } - + abort(c); } - virtual bool resolved() { + virtual bool resolved() + { return c->machineCode != 0; } @@ -107,11 +123,11 @@ class PoolPromise: public Promise { int key; }; -Promise* poolPromise(Context* c, int key) { - return new(c->zone) PoolPromise(c, key); +Promise* poolPromise(Context* c, int key) +{ + return new (c->zone) PoolPromise(c, key); } - -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/promise.h b/src/codegen/compiler/promise.h index e575df3185..d8a74be27b 100644 --- a/src/codegen/compiler/promise.h +++ b/src/codegen/compiler/promise.h @@ -15,8 +15,7 @@ namespace avian { namespace codegen { namespace compiler { - -class CodePromise: public Promise { +class CodePromise : public Promise { public: CodePromise(Context* c, CodePromise* next); @@ -33,7 +32,10 @@ class CodePromise: public Promise { CodePromise* codePromise(Context* c, Promise* offset); -Promise* shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask); +Promise* shiftMaskPromise(Context* c, + Promise* base, + unsigned shift, + int64_t mask); Promise* combinedPromise(Context* c, Promise* low, Promise* high); @@ -43,8 +45,8 @@ Promise* ipPromise(Context* c, int logicalIp); Promise* poolPromise(Context* c, int key); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_PROMISE_H +#endif // AVIAN_CODEGEN_COMPILER_PROMISE_H diff --git a/src/codegen/compiler/read.cpp b/src/codegen/compiler/read.cpp index 7e3e972f96..0c7d09fd76 100644 --- a/src/codegen/compiler/read.cpp +++ b/src/codegen/compiler/read.cpp @@ -20,43 +20,51 @@ namespace avian { namespace codegen { namespace compiler { +SingleRead::SingleRead(const SiteMask& mask, Value* successor) + : next_(0), mask(mask), high_(0), successor_(successor) +{ +} -SingleRead::SingleRead(const SiteMask& mask, Value* successor): - next_(0), mask(mask), high_(0), successor_(successor) -{ } - -bool SingleRead::intersect(SiteMask* mask, unsigned) { +bool SingleRead::intersect(SiteMask* mask, unsigned) +{ *mask = mask->intersectionWith(this->mask); return true; } -Value* SingleRead::high(Context*) { +Value* SingleRead::high(Context*) +{ return high_; } -Value* SingleRead::successor() { +Value* SingleRead::successor() +{ return successor_; } -bool SingleRead::valid() { +bool SingleRead::valid() +{ return true; } -void SingleRead::append(Context* c UNUSED, Read* r) { - assert(c, next_ == 0); +void SingleRead::append(Context* c UNUSED, Read* r) +{ + assertT(c, next_ == 0); next_ = r; } -Read* SingleRead::next(Context*) { +Read* SingleRead::next(Context*) +{ return next_; } -MultiRead::MultiRead(): - reads(0), lastRead(0), firstTarget(0), lastTarget(0), visited(false) -{ } +MultiRead::MultiRead() + : reads(0), lastRead(0), firstTarget(0), lastTarget(0), visited(false) +{ +} -bool MultiRead::intersect(SiteMask* mask, unsigned depth) { +bool MultiRead::intersect(SiteMask* mask, unsigned depth) +{ if (depth > 0) { // short-circuit recursion to avoid poor performance in // deeply-nested branches @@ -81,11 +89,13 @@ bool MultiRead::intersect(SiteMask* mask, unsigned depth) { return result; } -Value* MultiRead::successor() { +Value* MultiRead::successor() +{ return 0; } -bool MultiRead::valid() { +bool MultiRead::valid() +{ bool result = false; if (not visited) { visited = true; @@ -103,7 +113,8 @@ bool MultiRead::valid() { return result; } -void MultiRead::append(Context* c, Read* r) { +void MultiRead::append(Context* c, Read* r) +{ List* cell = cons(c, r, 0); if (lastRead == 0) { reads = cell; @@ -112,19 +123,25 @@ void MultiRead::append(Context* c, Read* r) { } lastRead = cell; -// fprintf(stderr, "append %p to %p for %p\n", r, lastTarget, this); + if (false) { + fprintf(stderr, "append %p to %p for %p\n", r, lastTarget, this); + } lastTarget->item = r; } -Read* MultiRead::next(Context* c) { +Read* MultiRead::next(Context* c) +{ abort(c); } -void MultiRead::allocateTarget(Context* c) { +void MultiRead::allocateTarget(Context* c) +{ List* cell = cons(c, 0, 0); -// fprintf(stderr, "allocate target for %p: %p\n", this, cell); + if (false) { + fprintf(stderr, "allocate target for %p: %p\n", this, cell); + } if (lastTarget) { lastTarget->next = cell; @@ -134,20 +151,23 @@ void MultiRead::allocateTarget(Context* c) { lastTarget = cell; } -Read* MultiRead::nextTarget() { - // fprintf(stderr, "next target for %p: %p\n", this, firstTarget); +Read* MultiRead::nextTarget() +{ + if (false) { + fprintf(stderr, "next target for %p: %p\n", this, firstTarget); + } Read* r = firstTarget->item; firstTarget = firstTarget->next; return r; } +StubRead::StubRead() : next_(0), read(0), visited(false), valid_(true) +{ +} -StubRead::StubRead(): - next_(0), read(0), visited(false), valid_(true) -{ } - -bool StubRead::intersect(SiteMask* mask, unsigned depth) { +bool StubRead::intersect(SiteMask* mask, unsigned depth) +{ if (not visited) { visited = true; if (read) { @@ -161,31 +181,35 @@ bool StubRead::intersect(SiteMask* mask, unsigned depth) { return valid_; } -Value* StubRead::successor() { +Value* StubRead::successor() +{ return 0; } -bool StubRead::valid() { +bool StubRead::valid() +{ return valid_; } -void StubRead::append(Context* c UNUSED, Read* r) { - assert(c, next_ == 0); +void StubRead::append(Context* c UNUSED, Read* r) +{ + assertT(c, next_ == 0); next_ = r; } -Read* StubRead::next(Context*) { +Read* StubRead::next(Context*) +{ return next_; } +SingleRead* read(Context* c, const SiteMask& mask, Value* successor) +{ + assertT(c, + (mask.typeMask != 1 << lir::MemoryOperand) or mask.frameIndex >= 0); - -SingleRead* read(Context* c, const SiteMask& mask, Value* successor) { - assert(c, (mask.typeMask != 1 << lir::MemoryOperand) or mask.frameIndex >= 0); - - return new(c->zone) SingleRead(mask, successor); + return new (c->zone) SingleRead(mask, successor); } -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/read.h b/src/codegen/compiler/read.h index 0e6f42a4e5..7941bbeb3f 100644 --- a/src/codegen/compiler/read.h +++ b/src/codegen/compiler/read.h @@ -22,16 +22,19 @@ class Event; class Read { public: - Read(): - value(0), event(0), eventNext(0) - { } + Read() : value(0), event(0), eventNext(0) + { + } virtual bool intersect(SiteMask* mask, unsigned depth = 0) = 0; - virtual Value* high(Context* c) { abort(c); } + virtual Value* high(Context* c) + { + abort(c); + } virtual Value* successor() = 0; - + virtual bool valid() = 0; virtual void append(Context* c, Read* r) = 0; @@ -43,11 +46,12 @@ class Read { Read* eventNext; }; -inline bool valid(Read* r) { +inline bool valid(Read* r) +{ return r and r->valid(); } -class SingleRead: public Read { +class SingleRead : public Read { public: SingleRead(const SiteMask& mask, Value* successor); @@ -56,7 +60,7 @@ class SingleRead: public Read { virtual Value* high(Context*); virtual Value* successor(); - + virtual bool valid(); virtual void append(Context* c UNUSED, Read* r); @@ -69,8 +73,7 @@ class SingleRead: public Read { Value* successor_; }; - -class MultiRead: public Read { +class MultiRead : public Read { public: MultiRead(); @@ -95,7 +98,7 @@ class MultiRead: public Read { bool visited; }; -class StubRead: public Read { +class StubRead : public Read { public: StubRead(); @@ -117,9 +120,8 @@ class StubRead: public Read { SingleRead* read(Context* c, const SiteMask& mask, Value* successor = 0); +} // namespace compiler +} // namespace codegen +} // namespace avian -} // namespace compiler -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_COMPILER_READ_H +#endif // AVIAN_CODEGEN_COMPILER_READ_H diff --git a/src/codegen/compiler/regalloc.cpp b/src/codegen/compiler/regalloc.cpp index 8699838900..6f716df770 100644 --- a/src/codegen/compiler/regalloc.cpp +++ b/src/codegen/compiler/regalloc.cpp @@ -20,28 +20,29 @@ namespace avian { namespace codegen { namespace compiler { -RegisterAllocator::RegisterAllocator(Aborter* a, const RegisterFile* registerFile): - a(a), - registerFile(registerFile) -{ } - +RegisterAllocator::RegisterAllocator(Aborter* a, + const RegisterFile* registerFile) + : a(a), registerFile(registerFile) +{ +} unsigned totalFrameSize(Context* c); Read* live(Context* c UNUSED, Value* v); -unsigned -resourceCost(Context* c, Value* v, Resource* r, SiteMask mask, - CostCalculator* costCalculator) +unsigned resourceCost(Context* c, + Value* v, + Resource* r, + SiteMask mask, + CostCalculator* costCalculator) { if (r->reserved or r->freezeCount or r->referenceCount) { return Target::Impossible; - } else { - unsigned baseCost = - costCalculator ? costCalculator->cost(c, mask) : 0; + } else { + unsigned baseCost = costCalculator ? costCalculator->cost(c, mask) : 0; if (r->value) { - assert(c, r->value->findSite(r->site)); - + assertT(c, r->value->findSite(r->site)); + if (v and r->value->isBuddyOf(v)) { return baseCost; } else if (r->value->uniqueSite(c, r->site)) { @@ -55,15 +56,23 @@ resourceCost(Context* c, Value* v, Resource* r, SiteMask mask, } } -bool -pickRegisterTarget(Context* c, int i, Value* v, uint32_t mask, int* target, - unsigned* cost, CostCalculator* costCalculator) +bool pickRegisterTarget(Context* c, + int i, + Value* v, + uint32_t mask, + int* target, + unsigned* cost, + CostCalculator* costCalculator) { if ((1 << i) & mask) { RegisterResource* r = c->registerResources + i; - unsigned myCost = resourceCost - (c, v, r, SiteMask(1 << lir::RegisterOperand, 1 << i, NoFrameIndex), costCalculator) - + Target::MinimumRegisterCost; + unsigned myCost + = resourceCost( + c, + v, + r, + SiteMask(1 << lir::RegisterOperand, 1 << i, NoFrameIndex), + costCalculator) + Target::MinimumRegisterCost; if ((static_cast(1) << i) == mask) { *cost = myCost; @@ -76,17 +85,19 @@ pickRegisterTarget(Context* c, int i, Value* v, uint32_t mask, int* target, return false; } -int -pickRegisterTarget(Context* c, Value* v, uint32_t mask, unsigned* cost, - CostCalculator* costCalculator) +int pickRegisterTarget(Context* c, + Value* v, + uint32_t mask, + unsigned* cost, + CostCalculator* costCalculator) { int target = lir::NoRegister; *cost = Target::Impossible; if (mask & c->regFile->generalRegisters.mask) { for (int i = c->regFile->generalRegisters.limit - 1; - i >= c->regFile->generalRegisters.start; --i) - { + i >= c->regFile->generalRegisters.start; + --i) { if (pickRegisterTarget(c, i, v, mask, &target, cost, costCalculator)) { return i; } @@ -95,8 +106,8 @@ pickRegisterTarget(Context* c, Value* v, uint32_t mask, unsigned* cost, if (mask & c->regFile->floatRegisters.mask) { for (int i = c->regFile->floatRegisters.start; - i < static_cast(c->regFile->floatRegisters.limit); ++i) - { + i < static_cast(c->regFile->floatRegisters.limit); + ++i) { if (pickRegisterTarget(c, i, v, mask, &target, cost, costCalculator)) { return i; } @@ -106,34 +117,38 @@ pickRegisterTarget(Context* c, Value* v, uint32_t mask, unsigned* cost, return target; } -Target -pickRegisterTarget(Context* c, Value* v, uint32_t mask, - CostCalculator* costCalculator) +Target pickRegisterTarget(Context* c, + Value* v, + uint32_t mask, + CostCalculator* costCalculator) { unsigned cost; int number = pickRegisterTarget(c, v, mask, &cost, costCalculator); return Target(number, lir::RegisterOperand, cost); } -unsigned -frameCost(Context* c, Value* v, int frameIndex, CostCalculator* costCalculator) +unsigned frameCost(Context* c, + Value* v, + int frameIndex, + CostCalculator* costCalculator) { - return resourceCost - (c, v, c->frameResources + frameIndex, SiteMask(1 << lir::MemoryOperand, 0, frameIndex), - costCalculator) - + Target::MinimumFrameCost; + return resourceCost(c, + v, + c->frameResources + frameIndex, + SiteMask(1 << lir::MemoryOperand, 0, frameIndex), + costCalculator) + Target::MinimumFrameCost; } -Target -pickFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) +Target pickFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) { Target best; Value* p = v; do { if (p->home >= 0) { - Target mine - (p->home, lir::MemoryOperand, frameCost(c, v, p->home, costCalculator)); + Target mine(p->home, + lir::MemoryOperand, + frameCost(c, v, p->home, costCalculator)); if (mine.cost == Target::MinimumFrameCost) { return mine; @@ -147,8 +162,7 @@ pickFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) return best; } -Target -pickAnyFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) +Target pickAnyFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) { Target best; @@ -159,20 +173,22 @@ pickAnyFrameTarget(Context* c, Value* v, CostCalculator* costCalculator) return mine; } else if (mine.cost < best.cost) { best = mine; - } + } } return best; } -Target -pickTarget(Context* c, Value* value, const SiteMask& mask, - unsigned registerPenalty, Target best, - CostCalculator* costCalculator) +Target pickTarget(Context* c, + Value* value, + const SiteMask& mask, + unsigned registerPenalty, + Target best, + CostCalculator* costCalculator) { if (mask.typeMask & (1 << lir::RegisterOperand)) { - Target mine = pickRegisterTarget - (c, value, mask.registerMask, costCalculator); + Target mine + = pickRegisterTarget(c, value, mask.registerMask, costCalculator); mine.cost += registerPenalty; if (mine.cost == Target::MinimumRegisterCost) { @@ -184,7 +200,8 @@ pickTarget(Context* c, Value* value, const SiteMask& mask, if (mask.typeMask & (1 << lir::MemoryOperand)) { if (mask.frameIndex >= 0) { - Target mine(mask.frameIndex, lir::MemoryOperand, + Target mine(mask.frameIndex, + lir::MemoryOperand, frameCost(c, value, mask.frameIndex, costCalculator)); if (mine.cost == Target::MinimumFrameCost) { return mine; @@ -204,13 +221,16 @@ pickTarget(Context* c, Value* value, const SiteMask& mask, return best; } -Target -pickTarget(Context* c, Read* read, bool intersectRead, - unsigned registerReserveCount, CostCalculator* costCalculator) +Target pickTarget(Context* c, + Read* read, + bool intersectRead, + unsigned registerReserveCount, + CostCalculator* costCalculator) { unsigned registerPenalty - = (c->availableGeneralRegisterCount > registerReserveCount - ? 0 : Target::LowRegisterPenalty); + = (c->availableGeneralRegisterCount > registerReserveCount + ? 0 + : Target::LowRegisterPenalty); Value* value = read->value; @@ -235,8 +255,8 @@ pickTarget(Context* c, Read* read, bool intersectRead, if (r) { SiteMask intersection = mask; if (r->intersect(&intersection)) { - best = pickTarget - (c, value, intersection, registerPenalty, best, costCalculator); + best = pickTarget( + c, value, intersection, registerPenalty, best, costCalculator); if (best.cost <= Target::MinimumFrameCost) { return best; @@ -252,14 +272,18 @@ pickTarget(Context* c, Read* read, bool intersectRead, if (intersectRead) { if (best.cost == Target::Impossible) { - fprintf(stderr, "mask type %d reg %d frame %d\n", - mask.typeMask, mask.registerMask, mask.frameIndex); + fprintf(stderr, + "mask type %d reg %d frame %d\n", + mask.typeMask, + mask.registerMask, + mask.frameIndex); abort(c); } return best; } - { Target mine = pickRegisterTarget(c, value, registerMask, costCalculator); + { + Target mine = pickRegisterTarget(c, value, registerMask, costCalculator); mine.cost += registerPenalty; @@ -270,7 +294,8 @@ pickTarget(Context* c, Read* read, bool intersectRead, } } - { Target mine = pickFrameTarget(c, value, costCalculator); + { + Target mine = pickFrameTarget(c, value, costCalculator); if (mine.cost == Target::MinimumFrameCost) { return mine; } else if (mine.cost < best.cost) { @@ -279,13 +304,12 @@ pickTarget(Context* c, Read* read, bool intersectRead, } if (best.cost >= Target::StealUniquePenalty - and c->availableGeneralRegisterCount == 0) - { + and c->availableGeneralRegisterCount == 0) { // there are no free registers left, so moving from memory to // memory isn't an option - try harder to find an available frame // site: best = pickAnyFrameTarget(c, value, costCalculator); - assert(c, best.cost <= 3); + assertT(c, best.cost <= 3); } if (best.cost == Target::Impossible) { @@ -295,6 +319,6 @@ pickTarget(Context* c, Read* read, bool intersectRead, return best; } -} // namespace regalloc -} // namespace codegen -} // namespace avian +} // namespace regalloc +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/regalloc.h b/src/codegen/compiler/regalloc.h index e7d4a3d7d2..3c87b20c00 100644 --- a/src/codegen/compiler/regalloc.h +++ b/src/codegen/compiler/regalloc.h @@ -20,7 +20,7 @@ namespace avian { namespace util { class Aborter; -} // namespace util +} // namespace util namespace codegen { namespace compiler { @@ -33,14 +33,12 @@ class SiteMask; class Resource; class Read; - class RegisterAllocator { -public: + public: Aborter* a; const RegisterFile* registerFile; RegisterAllocator(Aborter* a, const RegisterFile* registerFile); - }; class Target { @@ -53,11 +51,14 @@ class Target { static const unsigned LowRegisterPenalty = 10; static const unsigned Impossible = 20; - Target(): cost(Impossible) { } + Target() : cost(Impossible) + { + } - Target(int index, lir::OperandType type, unsigned cost): - index(index), type(type), cost(cost) - { } + Target(int index, lir::OperandType type, unsigned cost) + : index(index), type(type), cost(cost) + { + } int16_t index; lir::OperandType type; @@ -69,43 +70,55 @@ class CostCalculator { virtual unsigned cost(Context* c, SiteMask mask) = 0; }; -unsigned -resourceCost(Context* c, Value* v, Resource* r, SiteMask mask, - CostCalculator* costCalculator); +unsigned resourceCost(Context* c, + Value* v, + Resource* r, + SiteMask mask, + CostCalculator* costCalculator); +bool pickRegisterTarget(Context* c, + int i, + Value* v, + uint32_t mask, + int* target, + unsigned* cost, + CostCalculator* costCalculator = 0); -bool -pickRegisterTarget(Context* c, int i, Value* v, uint32_t mask, int* target, - unsigned* cost, CostCalculator* costCalculator = 0); +int pickRegisterTarget(Context* c, + Value* v, + uint32_t mask, + unsigned* cost, + CostCalculator* costCalculator = 0); -int -pickRegisterTarget(Context* c, Value* v, uint32_t mask, unsigned* cost, - CostCalculator* costCalculator = 0); +Target pickRegisterTarget(Context* c, + Value* v, + uint32_t mask, + CostCalculator* costCalculator = 0); -Target -pickRegisterTarget(Context* c, Value* v, uint32_t mask, - CostCalculator* costCalculator = 0); +unsigned frameCost(Context* c, + Value* v, + int frameIndex, + CostCalculator* costCalculator); -unsigned -frameCost(Context* c, Value* v, int frameIndex, CostCalculator* costCalculator); +Target pickFrameTarget(Context* c, Value* v, CostCalculator* costCalculator); -Target -pickFrameTarget(Context* c, Value* v, CostCalculator* costCalculator); +Target pickAnyFrameTarget(Context* c, Value* v, CostCalculator* costCalculator); -Target -pickAnyFrameTarget(Context* c, Value* v, CostCalculator* costCalculator); +Target pickTarget(Context* c, + Value* value, + const SiteMask& mask, + unsigned registerPenalty, + Target best, + CostCalculator* costCalculator); -Target -pickTarget(Context* c, Value* value, const SiteMask& mask, - unsigned registerPenalty, Target best, - CostCalculator* costCalculator); +Target pickTarget(Context* c, + Read* read, + bool intersectRead, + unsigned registerReserveCount, + CostCalculator* costCalculator); -Target -pickTarget(Context* c, Read* read, bool intersectRead, - unsigned registerReserveCount, CostCalculator* costCalculator); +} // namespace regalloc +} // namespace codegen +} // namespace avian -} // namespace regalloc -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_COMPILER_REGALLOC_H +#endif // AVIAN_CODEGEN_COMPILER_REGALLOC_H diff --git a/src/codegen/compiler/resource.cpp b/src/codegen/compiler/resource.cpp index d47ad1ff11..f9a307c1dc 100644 --- a/src/codegen/compiler/resource.cpp +++ b/src/codegen/compiler/resource.cpp @@ -18,167 +18,186 @@ namespace compiler { const bool DebugResources = false; - void steal(Context* c, Resource* r, Value* thief); -void decrementAvailableGeneralRegisterCount(Context* c) { - assert(c, c->availableGeneralRegisterCount); - -- c->availableGeneralRegisterCount; - +void decrementAvailableGeneralRegisterCount(Context* c) +{ + assertT(c, c->availableGeneralRegisterCount); + --c->availableGeneralRegisterCount; + if (DebugResources) { - fprintf(stderr, "%d registers available\n", - c->availableGeneralRegisterCount); + fprintf( + stderr, "%d registers available\n", c->availableGeneralRegisterCount); } } -void incrementAvailableGeneralRegisterCount(Context* c) { - ++ c->availableGeneralRegisterCount; +void incrementAvailableGeneralRegisterCount(Context* c) +{ + ++c->availableGeneralRegisterCount; if (DebugResources) { - fprintf(stderr, "%d registers available\n", - c->availableGeneralRegisterCount); + fprintf( + stderr, "%d registers available\n", c->availableGeneralRegisterCount); } } -void freezeResource(Context* c, Resource* r, Value* v) { +void freezeResource(Context* c, Resource* r, Value* v) +{ if (DebugResources) { - char buffer[256]; r->toString(c, buffer, 256); + char buffer[256]; + r->toString(c, buffer, 256); fprintf(stderr, "%p freeze %s to %d\n", v, buffer, r->freezeCount + 1); } - - ++ r->freezeCount; + + ++r->freezeCount; } -void thawResource(Context* c, Resource* r, Value* v) { +void thawResource(Context* c, Resource* r, Value* v) +{ if (not r->reserved) { if (DebugResources) { - char buffer[256]; r->toString(c, buffer, 256); + char buffer[256]; + r->toString(c, buffer, 256); fprintf(stderr, "%p thaw %s to %d\n", v, buffer, r->freezeCount - 1); } - assert(c, r->freezeCount); + assertT(c, r->freezeCount); - -- r->freezeCount; + --r->freezeCount; } } +Resource::Resource(bool reserved) + : value(0), + site(0), + previousAcquired(0), + nextAcquired(0), + freezeCount(0), + referenceCount(0), + reserved(reserved) +{ +} -Resource::Resource(bool reserved): - value(0), site(0), previousAcquired(0), nextAcquired(0), freezeCount(0), - referenceCount(0), reserved(reserved) -{ } +RegisterResource::RegisterResource(bool reserved) : Resource(reserved) +{ +} -RegisterResource::RegisterResource(bool reserved): - Resource(reserved) -{ } - -void RegisterResource::freeze(Context* c, Value* v) { +void RegisterResource::freeze(Context* c, Value* v) +{ if (not reserved) { freezeResource(c, this, v); if (freezeCount == 1 - and ((1 << index(c)) & c->regFile->generalRegisters.mask)) - { + and ((1 << index(c)) & c->regFile->generalRegisters.mask)) { decrementAvailableGeneralRegisterCount(c); } } } -void RegisterResource::thaw(Context* c, Value* v) { +void RegisterResource::thaw(Context* c, Value* v) +{ if (not reserved) { thawResource(c, this, v); if (freezeCount == 0 - and ((1 << index(c)) & c->regFile->generalRegisters.mask)) - { + and ((1 << index(c)) & c->regFile->generalRegisters.mask)) { incrementAvailableGeneralRegisterCount(c); } } } -unsigned RegisterResource::toString(Context* c, char* buffer, unsigned bufferSize) { +unsigned RegisterResource::toString(Context* c, + char* buffer, + unsigned bufferSize) +{ return vm::snprintf(buffer, bufferSize, "register %d", index(c)); } -unsigned RegisterResource::index(Context* c) { +unsigned RegisterResource::index(Context* c) +{ return this - c->registerResources; } -void RegisterResource::increment(Context* c) { +void RegisterResource::increment(Context* c) +{ if (not this->reserved) { if (DebugResources) { - char buffer[256]; this->toString(c, buffer, 256); + char buffer[256]; + this->toString(c, buffer, 256); fprintf(stderr, "increment %s to %d\n", buffer, this->referenceCount + 1); } - ++ this->referenceCount; + ++this->referenceCount; if (this->referenceCount == 1 - and ((1 << this->index(c)) & c->regFile->generalRegisters.mask)) - { + and ((1 << this->index(c)) & c->regFile->generalRegisters.mask)) { decrementAvailableGeneralRegisterCount(c); } } } -void RegisterResource::decrement(Context* c) { +void RegisterResource::decrement(Context* c) +{ if (not this->reserved) { if (DebugResources) { - char buffer[256]; this->toString(c, buffer, 256); + char buffer[256]; + this->toString(c, buffer, 256); fprintf(stderr, "decrement %s to %d\n", buffer, this->referenceCount - 1); } - assert(c, this->referenceCount > 0); + assertT(c, this->referenceCount > 0); - -- this->referenceCount; + --this->referenceCount; if (this->referenceCount == 0 - and ((1 << this->index(c)) & c->regFile->generalRegisters.mask)) - { + and ((1 << this->index(c)) & c->regFile->generalRegisters.mask)) { incrementAvailableGeneralRegisterCount(c); } } } - - -void FrameResource::freeze(Context* c, Value* v) { +void FrameResource::freeze(Context* c, Value* v) +{ freezeResource(c, this, v); } -void FrameResource::thaw(Context* c, Value* v) { +void FrameResource::thaw(Context* c, Value* v) +{ thawResource(c, this, v); } -unsigned FrameResource::toString(Context* c, char* buffer, unsigned bufferSize) { +unsigned FrameResource::toString(Context* c, char* buffer, unsigned bufferSize) +{ return vm::snprintf(buffer, bufferSize, "frame %d", index(c)); } -unsigned FrameResource::index(Context* c) { +unsigned FrameResource::index(Context* c) +{ return this - c->frameResources; } - -void acquire(Context* c, Resource* resource, Value* value, Site* site) { - assert(c, value); - assert(c, site); +void acquire(Context* c, Resource* resource, Value* value, Site* site) +{ + assertT(c, value); + assertT(c, site); if (not resource->reserved) { if (DebugResources) { - char buffer[256]; resource->toString(c, buffer, 256); + char buffer[256]; + resource->toString(c, buffer, 256); fprintf(stderr, "%p acquire %s\n", value, buffer); } if (resource->value) { - assert(c, resource->value->findSite(resource->site)); - assert(c, not value->findSite(resource->site)); + assertT(c, resource->value->findSite(resource->site)); + assertT(c, not value->findSite(resource->site)); steal(c, resource, value); } if (c->acquiredResources) { c->acquiredResources->previousAcquired = resource; - resource->nextAcquired = c->acquiredResources; + resource->nextAcquired = c->acquiredResources; } c->acquiredResources = resource; @@ -187,18 +206,23 @@ void acquire(Context* c, Resource* resource, Value* value, Site* site) { } } -void release(Context* c, Resource* resource, Value* value UNUSED, Site* site UNUSED) { +void release(Context* c, + Resource* resource, + Value* value UNUSED, + Site* site UNUSED) +{ if (not resource->reserved) { if (DebugResources) { - char buffer[256]; resource->toString(c, buffer, 256); + char buffer[256]; + resource->toString(c, buffer, 256); fprintf(stderr, "%p release %s\n", resource->value, buffer); } - assert(c, resource->value); - assert(c, resource->site); + assertT(c, resource->value); + assertT(c, resource->site); - assert(c, resource->value->isBuddyOf(value)); - assert(c, site == resource->site); + assertT(c, resource->value->isBuddyOf(value)); + assertT(c, site == resource->site); Resource* next = resource->nextAcquired; if (next) { @@ -211,16 +235,15 @@ void release(Context* c, Resource* resource, Value* value UNUSED, Site* site UNU previous->nextAcquired = next; resource->previousAcquired = 0; } else { - assert(c, c->acquiredResources == resource); + assertT(c, c->acquiredResources == resource); c->acquiredResources = next; } - + resource->value = 0; resource->site = 0; } } - -} // namespace compiler -} // namespace codegen -} // namespace avian \ No newline at end of file +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/resource.h b/src/codegen/compiler/resource.h index 8c2c7f7b25..1712871079 100644 --- a/src/codegen/compiler/resource.h +++ b/src/codegen/compiler/resource.h @@ -38,7 +38,7 @@ class Resource { bool reserved; }; -class RegisterResource: public Resource { +class RegisterResource : public Resource { public: RegisterResource(bool reserved); @@ -55,7 +55,7 @@ class RegisterResource: public Resource { void decrement(Context*); }; -class FrameResource: public Resource { +class FrameResource : public Resource { public: virtual void freeze(Context*, Value*); @@ -70,8 +70,8 @@ void acquire(Context* c, Resource* resource, Value* value, Site* site); void release(Context* c, Resource* resource, Value* value, Site* site); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_RESOURCE_H +#endif // AVIAN_CODEGEN_COMPILER_RESOURCE_H diff --git a/src/codegen/compiler/site.cpp b/src/codegen/compiler/site.cpp index b1ddcee1d7..ea762a851f 100644 --- a/src/codegen/compiler/site.cpp +++ b/src/codegen/compiler/site.cpp @@ -21,35 +21,43 @@ namespace avian { namespace codegen { namespace compiler { - - -int intersectFrameIndexes(int a, int b) { - if (a == NoFrameIndex or b == NoFrameIndex) return NoFrameIndex; - if (a == AnyFrameIndex) return b; - if (b == AnyFrameIndex) return a; - if (a == b) return a; +int intersectFrameIndexes(int a, int b) +{ + if (a == NoFrameIndex or b == NoFrameIndex) + return NoFrameIndex; + if (a == AnyFrameIndex) + return b; + if (b == AnyFrameIndex) + return a; + if (a == b) + return a; return NoFrameIndex; } - -SiteMask SiteMask::intersectionWith(const SiteMask& b) { - return SiteMask(typeMask & b.typeMask, registerMask & b.registerMask, +SiteMask SiteMask::intersectionWith(const SiteMask& b) +{ + return SiteMask(typeMask & b.typeMask, + registerMask & b.registerMask, intersectFrameIndexes(frameIndex, b.frameIndex)); } -SiteIterator::SiteIterator(Context* c, Value* v, bool includeBuddies, - bool includeNextWord): - c(c), - originalValue(v), - currentValue(v), - includeBuddies(includeBuddies), - includeNextWord(includeNextWord), - pass(0), - next_(findNext(&(v->sites))), - previous(0) -{ } +SiteIterator::SiteIterator(Context* c, + Value* v, + bool includeBuddies, + bool includeNextWord) + : c(c), + originalValue(v), + currentValue(v), + includeBuddies(includeBuddies), + includeNextWord(includeNextWord), + pass(0), + next_(findNext(&(v->sites))), + previous(0) +{ +} -Site** SiteIterator::findNext(Site** p) { +Site** SiteIterator::findNext(Site** p) +{ while (true) { if (*p) { if (pass == 0 or (*p)->registerSize(c) > c->targetInfo.pointerSize) { @@ -83,7 +91,8 @@ Site** SiteIterator::findNext(Site** p) { } } -bool SiteIterator::hasMore() { +bool SiteIterator::hasMore() +{ if (previous) { next_ = findNext(&((*previous)->next)); previous = 0; @@ -91,12 +100,14 @@ bool SiteIterator::hasMore() { return next_ != 0; } -Site* SiteIterator::next() { +Site* SiteIterator::next() +{ previous = next_; return *previous; } -void SiteIterator::remove(Context* c) { +void SiteIterator::remove(Context* c) +{ (*previous)->release(c, originalValue); *previous = (*previous)->next; next_ = findNext(previous); @@ -108,118 +119,135 @@ unsigned Site::registerSize(Context* c) return c->targetInfo.pointerSize; } -Site* constantSite(Context* c, Promise* value) { - return new(c->zone) ConstantSite(value); +Site* constantSite(Context* c, Promise* value) +{ + return new (c->zone) ConstantSite(value); } -Site* constantSite(Context* c, int64_t value) { +Site* constantSite(Context* c, int64_t value) +{ return constantSite(c, resolvedPromise(c, value)); } - - -class AddressSite: public Site { +class AddressSite : public Site { public: - AddressSite(Promise* address): address(address) { } + AddressSite(Promise* address) : address(address) + { + } - virtual unsigned toString(Context*, char* buffer, unsigned bufferSize) { + virtual unsigned toString(Context*, char* buffer, unsigned bufferSize) + { if (address->resolved()) { - return vm::snprintf - (buffer, bufferSize, "address %" LLD, address->value()); + return vm::snprintf( + buffer, bufferSize, "address %" LLD, address->value()); } else { return vm::snprintf(buffer, bufferSize, "address unresolved"); } } - virtual unsigned copyCost(Context*, Site* s) { + virtual unsigned copyCost(Context*, Site* s) + { return (s == this ? 0 : AddressCopyCost); } - virtual bool match(Context*, const SiteMask& mask) { + virtual bool match(Context*, const SiteMask& mask) + { return mask.typeMask & (1 << lir::AddressOperand); } - virtual bool loneMatch(Context*, const SiteMask&) { + virtual bool loneMatch(Context*, const SiteMask&) + { return false; } - virtual bool matchNextWord(Context* c, Site*, unsigned) { + virtual bool matchNextWord(Context* c, Site*, unsigned) + { abort(c); } - virtual lir::OperandType type(Context*) { + virtual lir::OperandType type(Context*) + { return lir::AddressOperand; } - virtual void asAssemblerOperand(Context* c UNUSED, Site* high UNUSED, + virtual void asAssemblerOperand(Context* c UNUSED, + Site* high UNUSED, lir::Operand* result) { - assert(c, high == this); + assertT(c, high == this); new (result) lir::Address(address); } - virtual Site* copy(Context* c) { + virtual Site* copy(Context* c) + { return addressSite(c, address); } - virtual Site* copyLow(Context* c) { + virtual Site* copyLow(Context* c) + { abort(c); } - virtual Site* copyHigh(Context* c) { + virtual Site* copyHigh(Context* c) + { abort(c); } - virtual Site* makeNextWord(Context* c, unsigned) { + virtual Site* makeNextWord(Context* c, unsigned) + { abort(c); } - virtual SiteMask mask(Context*) { + virtual SiteMask mask(Context*) + { return SiteMask(1 << lir::AddressOperand, 0, NoFrameIndex); } - virtual SiteMask nextWordMask(Context* c, unsigned) { + virtual SiteMask nextWordMask(Context* c, unsigned) + { abort(c); } Promise* address; }; -Site* addressSite(Context* c, Promise* address) { - return new(c->zone) AddressSite(address); +Site* addressSite(Context* c, Promise* address) +{ + return new (c->zone) AddressSite(address); } +RegisterSite::RegisterSite(uint32_t mask, int number) + : mask_(mask), number(number) +{ +} -RegisterSite::RegisterSite(uint32_t mask, int number): - mask_(mask), number(number) -{ } - -unsigned RegisterSite::toString(Context*, char* buffer, unsigned bufferSize) { +unsigned RegisterSite::toString(Context*, char* buffer, unsigned bufferSize) +{ if (number != lir::NoRegister) { return vm::snprintf(buffer, bufferSize, "%p register %d", this, number); } else { - return vm::snprintf(buffer, bufferSize, - "%p register unacquired (mask %d)", this, mask_); + return vm::snprintf( + buffer, bufferSize, "%p register unacquired (mask %d)", this, mask_); } } -unsigned RegisterSite::copyCost(Context* c, Site* s) { - assert(c, number != lir::NoRegister); +unsigned RegisterSite::copyCost(Context* c, Site* s) +{ + assertT(c, number != lir::NoRegister); - if (s and - (this == s or - (s->type(c) == lir::RegisterOperand - and (static_cast(s)->mask_ & (1 << number))))) - { + if (s and (this == s + or (s->type(c) == lir::RegisterOperand + and (static_cast(s)->mask_ & (1 << number))))) { return 0; } else { return RegisterCopyCost; } } -bool RegisterSite::match(Context* c UNUSED, const SiteMask& mask) { - assert(c, number != lir::NoRegister); +bool RegisterSite::match(Context* c UNUSED, const SiteMask& mask) +{ + assertT(c, number != lir::NoRegister); if ((mask.typeMask & (1 << lir::RegisterOperand))) { return ((static_cast(1) << number) & mask.registerMask); @@ -228,8 +256,9 @@ bool RegisterSite::match(Context* c UNUSED, const SiteMask& mask) { } } -bool RegisterSite::loneMatch(Context* c UNUSED, const SiteMask& mask) { - assert(c, number != lir::NoRegister); +bool RegisterSite::loneMatch(Context* c UNUSED, const SiteMask& mask) +{ + assertT(c, number != lir::NoRegister); if ((mask.typeMask & (1 << lir::RegisterOperand))) { return ((static_cast(1) << number) == mask.registerMask); @@ -238,8 +267,9 @@ bool RegisterSite::loneMatch(Context* c UNUSED, const SiteMask& mask) { } } -bool RegisterSite::matchNextWord(Context* c, Site* s, unsigned) { - assert(c, number != lir::NoRegister); +bool RegisterSite::matchNextWord(Context* c, Site* s, unsigned) +{ + assertT(c, number != lir::NoRegister); if (s->type(c) != lir::RegisterOperand) { return false; @@ -248,7 +278,7 @@ bool RegisterSite::matchNextWord(Context* c, Site* s, unsigned) { RegisterSite* rs = static_cast(s); unsigned size = rs->registerSize(c); if (size > c->targetInfo.pointerSize) { - assert(c, number != lir::NoRegister); + assertT(c, number != lir::NoRegister); return number == rs->number; } else { uint32_t mask = c->regFile->generalRegisters.mask; @@ -256,7 +286,8 @@ bool RegisterSite::matchNextWord(Context* c, Site* s, unsigned) { } } -void RegisterSite::acquire(Context* c, Value* v) { +void RegisterSite::acquire(Context* c, Value* v) +{ Target target; if (number != lir::NoRegister) { target = Target(number, lir::RegisterOperand, 0); @@ -271,43 +302,49 @@ void RegisterSite::acquire(Context* c, Value* v) { number = target.index; } -void RegisterSite::release(Context* c, Value* v) { - assert(c, number != lir::NoRegister); +void RegisterSite::release(Context* c, Value* v) +{ + assertT(c, number != lir::NoRegister); compiler::release(c, c->registerResources + number, v, this); } -void RegisterSite::freeze(Context* c, Value* v) { - assert(c, number != lir::NoRegister); +void RegisterSite::freeze(Context* c, Value* v) +{ + assertT(c, number != lir::NoRegister); c->registerResources[number].freeze(c, v); } -void RegisterSite::thaw(Context* c, Value* v) { - assert(c, number != lir::NoRegister); +void RegisterSite::thaw(Context* c, Value* v) +{ + assertT(c, number != lir::NoRegister); c->registerResources[number].thaw(c, v); } -bool RegisterSite::frozen(Context* c UNUSED) { - assert(c, number != lir::NoRegister); +bool RegisterSite::frozen(Context* c UNUSED) +{ + assertT(c, number != lir::NoRegister); return c->registerResources[number].freezeCount != 0; } -lir::OperandType RegisterSite::type(Context*) { +lir::OperandType RegisterSite::type(Context*) +{ return lir::RegisterOperand; } -void RegisterSite::asAssemblerOperand(Context* c UNUSED, Site* high, - lir::Operand* result) +void RegisterSite::asAssemblerOperand(Context* c UNUSED, + Site* high, + lir::Operand* result) { - assert(c, number != lir::NoRegister); + assertT(c, number != lir::NoRegister); int highNumber; if (high != this) { highNumber = static_cast(high)->number; - assert(c, highNumber != lir::NoRegister); + assertT(c, highNumber != lir::NoRegister); } else { highNumber = lir::NoRegister; } @@ -315,9 +352,10 @@ void RegisterSite::asAssemblerOperand(Context* c UNUSED, Site* high, new (result) lir::Register(number, highNumber); } -Site* RegisterSite::copy(Context* c) { +Site* RegisterSite::copy(Context* c) +{ uint32_t mask; - + if (number != lir::NoRegister) { mask = 1 << number; } else { @@ -327,39 +365,45 @@ Site* RegisterSite::copy(Context* c) { return freeRegisterSite(c, mask); } -Site* RegisterSite::copyLow(Context* c) { +Site* RegisterSite::copyLow(Context* c) +{ abort(c); } -Site* RegisterSite::copyHigh(Context* c) { +Site* RegisterSite::copyHigh(Context* c) +{ abort(c); } -Site* RegisterSite::makeNextWord(Context* c, unsigned) { - assert(c, number != lir::NoRegister); - assert(c, ((1 << number) & c->regFile->generalRegisters.mask)); +Site* RegisterSite::makeNextWord(Context* c, unsigned) +{ + assertT(c, number != lir::NoRegister); + assertT(c, ((1 << number) & c->regFile->generalRegisters.mask)); - return freeRegisterSite(c, c->regFile->generalRegisters.mask); + return freeRegisterSite(c, c->regFile->generalRegisters.mask); } -SiteMask RegisterSite::mask(Context* c UNUSED) { +SiteMask RegisterSite::mask(Context* c UNUSED) +{ return SiteMask(1 << lir::RegisterOperand, mask_, NoFrameIndex); } -SiteMask RegisterSite::nextWordMask(Context* c, unsigned) { - assert(c, number != lir::NoRegister); +SiteMask RegisterSite::nextWordMask(Context* c, unsigned) +{ + assertT(c, number != lir::NoRegister); if (registerSize(c) > c->targetInfo.pointerSize) { - return SiteMask - (1 << lir::RegisterOperand, number, NoFrameIndex); + return SiteMask(1 << lir::RegisterOperand, number, NoFrameIndex); } else { - return SiteMask - (1 << lir::RegisterOperand, c->regFile->generalRegisters.mask, NoFrameIndex); + return SiteMask(1 << lir::RegisterOperand, + c->regFile->generalRegisters.mask, + NoFrameIndex); } } -unsigned RegisterSite::registerSize(Context* c) { - assert(c, number != lir::NoRegister); +unsigned RegisterSite::registerSize(Context* c) +{ + assertT(c, number != lir::NoRegister); if ((1 << number) & c->regFile->floatRegisters.mask) { return c->arch->floatRegisterSize(); @@ -368,72 +412,76 @@ unsigned RegisterSite::registerSize(Context* c) { } } -unsigned RegisterSite::registerMask(Context* c UNUSED) { - assert(c, number != lir::NoRegister); +unsigned RegisterSite::registerMask(Context* c UNUSED) +{ + assertT(c, number != lir::NoRegister); return 1 << number; } +Site* registerSite(Context* c, int number) +{ + assertT(c, number >= 0); + assertT(c, + (1 << number) & (c->regFile->generalRegisters.mask + | c->regFile->floatRegisters.mask)); - -Site* registerSite(Context* c, int number) { - assert(c, number >= 0); - assert(c, (1 << number) & (c->regFile->generalRegisters.mask - | c->regFile->floatRegisters.mask)); - - return new(c->zone) RegisterSite(1 << number, number); + return new (c->zone) RegisterSite(1 << number, number); } -Site* freeRegisterSite(Context* c, uint32_t mask) { - return new(c->zone) RegisterSite(mask, lir::NoRegister); +Site* freeRegisterSite(Context* c, uint32_t mask) +{ + return new (c->zone) RegisterSite(mask, lir::NoRegister); } -MemorySite::MemorySite(int base, int offset, int index, unsigned scale): - acquired(false), base(base), offset(offset), index(index), scale(scale) -{ } +MemorySite::MemorySite(int base, int offset, int index, unsigned scale) + : acquired(false), base(base), offset(offset), index(index), scale(scale) +{ +} -unsigned MemorySite::toString(Context*, char* buffer, unsigned bufferSize) { +unsigned MemorySite::toString(Context*, char* buffer, unsigned bufferSize) +{ if (acquired) { - return vm::snprintf(buffer, bufferSize, "memory %d 0x%x %d %d", - base, offset, index, scale); + return vm::snprintf( + buffer, bufferSize, "memory %d 0x%x %d %d", base, offset, index, scale); } else { return vm::snprintf(buffer, bufferSize, "memory unacquired"); } } -unsigned MemorySite::copyCost(Context* c, Site* s) { - assert(c, acquired); +unsigned MemorySite::copyCost(Context* c, Site* s) +{ + assertT(c, acquired); - if (s and - (this == s or - (s->type(c) == lir::MemoryOperand - and static_cast(s)->base == base - and static_cast(s)->offset == offset - and static_cast(s)->index == index - and static_cast(s)->scale == scale))) - { + if (s and (this == s or (s->type(c) == lir::MemoryOperand + and static_cast(s)->base == base + and static_cast(s)->offset == offset + and static_cast(s)->index == index + and static_cast(s)->scale == scale))) { return 0; } else { return MemoryCopyCost; } } -bool MemorySite::conflicts(const SiteMask& mask) { +bool MemorySite::conflicts(const SiteMask& mask) +{ return (mask.typeMask & (1 << lir::RegisterOperand)) != 0 - and (((1 << base) & mask.registerMask) == 0 - or (index != lir::NoRegister - and ((1 << index) & mask.registerMask) == 0)); + and (((1 << base) & mask.registerMask) == 0 + or (index != lir::NoRegister + and ((1 << index) & mask.registerMask) == 0)); } -bool MemorySite::match(Context* c, const SiteMask& mask) { - assert(c, acquired); +bool MemorySite::match(Context* c, const SiteMask& mask) +{ + assertT(c, acquired); if (mask.typeMask & (1 << lir::MemoryOperand)) { if (mask.frameIndex >= 0) { if (base == c->arch->stack()) { - assert(c, index == lir::NoRegister); + assertT(c, index == lir::NoRegister); return static_cast(frameIndexToOffset(c, mask.frameIndex)) - == offset; + == offset; } else { return false; } @@ -445,12 +493,13 @@ bool MemorySite::match(Context* c, const SiteMask& mask) { } } -bool MemorySite::loneMatch(Context* c, const SiteMask& mask) { - assert(c, acquired); +bool MemorySite::loneMatch(Context* c, const SiteMask& mask) +{ + assertT(c, acquired); if (mask.typeMask & (1 << lir::MemoryOperand)) { if (base == c->arch->stack()) { - assert(c, index == lir::NoRegister); + assertT(c, index == lir::NoRegister); if (mask.frameIndex == AnyFrameIndex) { return false; @@ -462,7 +511,8 @@ bool MemorySite::loneMatch(Context* c, const SiteMask& mask) { return false; } -bool MemorySite::matchNextWord(Context* c, Site* s, unsigned index) { +bool MemorySite::matchNextWord(Context* c, Site* s, unsigned index) +{ if (s->type(c) == lir::MemoryOperand) { MemorySite* ms = static_cast(s); return ms->base == this->base @@ -480,32 +530,32 @@ bool MemorySite::matchNextWord(Context* c, Site* s, unsigned index) { } } -void MemorySite::acquire(Context* c, Value* v) { +void MemorySite::acquire(Context* c, Value* v) +{ c->registerResources[base].increment(c); if (index != lir::NoRegister) { c->registerResources[index].increment(c); } if (base == c->arch->stack()) { - assert(c, index == lir::NoRegister); - assert - (c, not c->frameResources[offsetToFrameIndex(c, offset)].reserved); + assertT(c, index == lir::NoRegister); + assertT(c, not c->frameResources[offsetToFrameIndex(c, offset)].reserved); - compiler::acquire - (c, c->frameResources + offsetToFrameIndex(c, offset), v, this); + compiler::acquire( + c, c->frameResources + offsetToFrameIndex(c, offset), v, this); } acquired = true; } -void MemorySite::release(Context* c, Value* v) { +void MemorySite::release(Context* c, Value* v) +{ if (base == c->arch->stack()) { - assert(c, index == lir::NoRegister); - assert - (c, not c->frameResources[offsetToFrameIndex(c, offset)].reserved); + assertT(c, index == lir::NoRegister); + assertT(c, not c->frameResources[offsetToFrameIndex(c, offset)].reserved); - compiler::release - (c, c->frameResources + offsetToFrameIndex(c, offset), v, this); + compiler::release( + c, c->frameResources + offsetToFrameIndex(c, offset), v, this); } c->registerResources[base].decrement(c); @@ -516,7 +566,8 @@ void MemorySite::release(Context* c, Value* v) { acquired = false; } -void MemorySite::freeze(Context* c, Value* v) { +void MemorySite::freeze(Context* c, Value* v) +{ if (base == c->arch->stack()) { c->frameResources[offsetToFrameIndex(c, offset)].freeze(c, v); } else { @@ -527,7 +578,8 @@ void MemorySite::freeze(Context* c, Value* v) { } } -void MemorySite::thaw(Context* c, Value* v) { +void MemorySite::thaw(Context* c, Value* v) +{ if (base == c->arch->stack()) { c->frameResources[offsetToFrameIndex(c, offset)].thaw(c, v); } else { @@ -538,37 +590,42 @@ void MemorySite::thaw(Context* c, Value* v) { } } -bool MemorySite::frozen(Context* c) { +bool MemorySite::frozen(Context* c) +{ return base == c->arch->stack() - and c->frameResources[offsetToFrameIndex(c, offset)].freezeCount != 0; + and c->frameResources[offsetToFrameIndex(c, offset)].freezeCount != 0; } -lir::OperandType MemorySite::type(Context*) { +lir::OperandType MemorySite::type(Context*) +{ return lir::MemoryOperand; } -void MemorySite::asAssemblerOperand(Context* c UNUSED, Site* high UNUSED, - lir::Operand* result) +void MemorySite::asAssemblerOperand(Context* c UNUSED, + Site* high UNUSED, + lir::Operand* result) { // todo: endianness? - assert(c, - high == this - or (static_cast(high)->base == base - and static_cast(high)->offset - == static_cast(offset + c->targetInfo.pointerSize) - and static_cast(high)->index == index - and static_cast(high)->scale == scale)); + assertT(c, + high == this + or (static_cast(high)->base == base + and static_cast(high)->offset + == static_cast(offset + c->targetInfo.pointerSize) + and static_cast(high)->index == index + and static_cast(high)->scale == scale)); - assert(c, acquired); + assertT(c, acquired); new (result) lir::Memory(base, offset, index, scale); } -Site* MemorySite::copy(Context* c) { +Site* MemorySite::copy(Context* c) +{ return memorySite(c, base, offset, index, scale); } -Site* MemorySite::copyHalf(Context* c, bool add) { +Site* MemorySite::copyHalf(Context* c, bool add) +{ if (add) { return memorySite( c, base, offset + c->targetInfo.pointerSize, index, scale); @@ -577,15 +634,18 @@ Site* MemorySite::copyHalf(Context* c, bool add) { } } -Site* MemorySite::copyLow(Context* c) { +Site* MemorySite::copyLow(Context* c) +{ return copyHalf(c, c->arch->bigEndian()); } -Site* MemorySite::copyHigh(Context* c) { +Site* MemorySite::copyHigh(Context* c) +{ return copyHalf(c, not c->arch->bigEndian()); } -Site* MemorySite::makeNextWord(Context* c, unsigned index) { +Site* MemorySite::makeNextWord(Context* c, unsigned index) +{ return memorySite(c, base, offset + ((index == 1) xor c->arch->bigEndian() @@ -595,39 +655,52 @@ Site* MemorySite::makeNextWord(Context* c, unsigned index) { scale); } -SiteMask MemorySite::mask(Context* c) { - return SiteMask(1 << lir::MemoryOperand, 0, (base == c->arch->stack()) - ? static_cast(offsetToFrameIndex(c, offset)) - : NoFrameIndex); +SiteMask MemorySite::mask(Context* c) +{ + return SiteMask(1 << lir::MemoryOperand, + 0, + (base == c->arch->stack()) + ? static_cast(offsetToFrameIndex(c, offset)) + : NoFrameIndex); } -SiteMask MemorySite::nextWordMask(Context* c, unsigned index) { +SiteMask MemorySite::nextWordMask(Context* c, unsigned index) +{ int frameIndex; if (base == c->arch->stack()) { - assert(c, this->index == lir::NoRegister); + assertT(c, this->index == lir::NoRegister); frameIndex = static_cast(offsetToFrameIndex(c, offset)) - + ((index == 1) xor c->arch->bigEndian() ? 1 : -1); + + ((index == 1) xor c->arch->bigEndian() ? 1 : -1); } else { frameIndex = NoFrameIndex; } return SiteMask(1 << lir::MemoryOperand, 0, frameIndex); } -bool MemorySite::isVolatile(Context* c) { +bool MemorySite::isVolatile(Context* c) +{ return base != c->arch->stack(); } - -MemorySite* memorySite(Context* c, int base, int offset, int index, unsigned scale) { - return new(c->zone) MemorySite(base, offset, index, scale); +MemorySite* memorySite(Context* c, + int base, + int offset, + int index, + unsigned scale) +{ + return new (c->zone) MemorySite(base, offset, index, scale); } -MemorySite* frameSite(Context* c, int frameIndex) { - assert(c, frameIndex >= 0); - return memorySite - (c, c->arch->stack(), frameIndexToOffset(c, frameIndex), lir::NoRegister, 0); +MemorySite* frameSite(Context* c, int frameIndex) +{ + assertT(c, frameIndex >= 0); + return memorySite(c, + c->arch->stack(), + frameIndexToOffset(c, frameIndex), + lir::NoRegister, + 0); } -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/site.h b/src/codegen/compiler/site.h index 3f762eefed..3f93d1f5dd 100644 --- a/src/codegen/compiler/site.h +++ b/src/codegen/compiler/site.h @@ -30,23 +30,29 @@ const unsigned CopyPenalty = 10; class SiteMask { public: - SiteMask(): typeMask(~0), registerMask(~0), frameIndex(AnyFrameIndex) { } + SiteMask() : typeMask(~0), registerMask(~0), frameIndex(AnyFrameIndex) + { + } - SiteMask(uint8_t typeMask, uint32_t registerMask, int frameIndex): - typeMask(typeMask), registerMask(registerMask), frameIndex(frameIndex) - { } + SiteMask(uint8_t typeMask, uint32_t registerMask, int frameIndex) + : typeMask(typeMask), registerMask(registerMask), frameIndex(frameIndex) + { + } SiteMask intersectionWith(const SiteMask& b); - static SiteMask fixedRegisterMask(int number) { + static SiteMask fixedRegisterMask(int number) + { return SiteMask(1 << lir::RegisterOperand, 1 << number, NoFrameIndex); } - static SiteMask lowPart(const OperandMask& mask) { + static SiteMask lowPart(const OperandMask& mask) + { return SiteMask(mask.typeMask, mask.registerMask, AnyFrameIndex); } - static SiteMask highPart(const OperandMask& mask) { + static SiteMask highPart(const OperandMask& mask) + { return SiteMask(mask.typeMask, mask.registerMask >> 32, AnyFrameIndex); } @@ -57,9 +63,14 @@ class SiteMask { class Site { public: - Site(): next(0) { } - - virtual Site* readTarget(Context*, Read*) { return this; } + Site() : next(0) + { + } + + virtual Site* readTarget(Context*, Read*) + { + return this; + } virtual unsigned toString(Context*, char*, unsigned) = 0; @@ -70,16 +81,27 @@ class Site { virtual bool loneMatch(Context*, const SiteMask&) = 0; virtual bool matchNextWord(Context*, Site*, unsigned) = 0; - - virtual void acquire(Context*, Value*) { } - virtual void release(Context*, Value*) { } + virtual void acquire(Context*, Value*) + { + } - virtual void freeze(Context*, Value*) { } + virtual void release(Context*, Value*) + { + } - virtual void thaw(Context*, Value*) { } + virtual void freeze(Context*, Value*) + { + } - virtual bool frozen(Context*) { return false; } + virtual void thaw(Context*, Value*) + { + } + + virtual bool frozen(Context*) + { + return false; + } virtual lir::OperandType type(Context*) = 0; @@ -99,16 +121,24 @@ class Site { virtual unsigned registerSize(Context*); - virtual unsigned registerMask(Context*) { return 0; } + virtual unsigned registerMask(Context*) + { + return 0; + } - virtual bool isVolatile(Context*) { return false; } + virtual bool isVolatile(Context*) + { + return false; + } Site* next; }; class SiteIterator { public: - SiteIterator(Context* c, Value* v, bool includeBuddies = true, + SiteIterator(Context* c, + Value* v, + bool includeBuddies = true, bool includeNextWord = true); Site** findNext(Site** p); @@ -130,43 +160,52 @@ Site* constantSite(Context* c, Promise* value); Site* constantSite(Context* c, int64_t value); Promise* combinedPromise(Context* c, Promise* low, Promise* high); -Promise* shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask); +Promise* shiftMaskPromise(Context* c, + Promise* base, + unsigned shift, + int64_t mask); -class ConstantSite: public Site { +class ConstantSite : public Site { public: - ConstantSite(Promise* value): value(value) { } + ConstantSite(Promise* value) : value(value) + { + } - virtual unsigned toString(Context*, char* buffer, unsigned bufferSize) { + virtual unsigned toString(Context*, char* buffer, unsigned bufferSize) + { if (value->resolved()) { - return vm::snprintf - (buffer, bufferSize, "constant %" LLD, value->value()); + return vm::snprintf(buffer, bufferSize, "constant %" LLD, value->value()); } else { return vm::snprintf(buffer, bufferSize, "constant unresolved"); } } - virtual unsigned copyCost(Context*, Site* s) { + virtual unsigned copyCost(Context*, Site* s) + { return (s == this ? 0 : ConstantCopyCost); } - virtual bool match(Context*, const SiteMask& mask) { + virtual bool match(Context*, const SiteMask& mask) + { return mask.typeMask & (1 << lir::ConstantOperand); } - virtual bool loneMatch(Context*, const SiteMask&) { + virtual bool loneMatch(Context*, const SiteMask&) + { return true; } - virtual bool matchNextWord(Context* c, Site* s, unsigned) { + virtual bool matchNextWord(Context* c, Site* s, unsigned) + { return s->type(c) == lir::ConstantOperand; } - virtual lir::OperandType type(Context*) { + virtual lir::OperandType type(Context*) + { return lir::ConstantOperand; } - virtual void asAssemblerOperand(Context* c, Site* high, - lir::Operand* result) + virtual void asAssemblerOperand(Context* c, Site* high, lir::Operand* result) { Promise* v = value; if (high != this) { @@ -175,27 +214,33 @@ class ConstantSite: public Site { new (result) lir::Constant(v); } - virtual Site* copy(Context* c) { + virtual Site* copy(Context* c) + { return constantSite(c, value); } - virtual Site* copyLow(Context* c) { + virtual Site* copyLow(Context* c) + { return constantSite(c, shiftMaskPromise(c, value, 0, 0xFFFFFFFF)); } - virtual Site* copyHigh(Context* c) { + virtual Site* copyHigh(Context* c) + { return constantSite(c, shiftMaskPromise(c, value, 32, 0xFFFFFFFF)); } - virtual Site* makeNextWord(Context* c, unsigned) { + virtual Site* makeNextWord(Context* c, unsigned) + { abort(c); } - virtual SiteMask mask(Context*) { + virtual SiteMask mask(Context*) + { return SiteMask(1 << lir::ConstantOperand, 0, NoFrameIndex); } - virtual SiteMask nextWordMask(Context*, unsigned) { + virtual SiteMask nextWordMask(Context*, unsigned) + { return SiteMask(1 << lir::ConstantOperand, 0, NoFrameIndex); } @@ -204,7 +249,7 @@ class ConstantSite: public Site { Site* addressSite(Context* c, Promise* address); -class RegisterSite: public Site { +class RegisterSite : public Site { public: RegisterSite(uint32_t mask, int number); @@ -230,7 +275,8 @@ class RegisterSite: public Site { virtual lir::OperandType type(Context*); - virtual void asAssemblerOperand(Context* c UNUSED, Site* high, + virtual void asAssemblerOperand(Context* c UNUSED, + Site* high, lir::Operand* result); virtual Site* copy(Context* c); @@ -256,8 +302,7 @@ class RegisterSite: public Site { Site* registerSite(Context* c, int number); Site* freeRegisterSite(Context* c, uint32_t mask); - -class MemorySite: public Site { +class MemorySite : public Site { public: MemorySite(int base, int offset, int index, unsigned scale); @@ -285,7 +330,8 @@ class MemorySite: public Site { virtual lir::OperandType type(Context*); - virtual void asAssemblerOperand(Context* c UNUSED, Site* high UNUSED, + virtual void asAssemblerOperand(Context* c UNUSED, + Site* high UNUSED, lir::Operand* result); virtual Site* copy(Context* c); @@ -311,11 +357,15 @@ class MemorySite: public Site { unsigned scale; }; -MemorySite* memorySite(Context* c, int base, int offset = 0, int index = lir::NoRegister, unsigned scale = 1); +MemorySite* memorySite(Context* c, + int base, + int offset = 0, + int index = lir::NoRegister, + unsigned scale = 1); MemorySite* frameSite(Context* c, int frameIndex); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_SITE_H +#endif // AVIAN_CODEGEN_COMPILER_SITE_H diff --git a/src/codegen/compiler/value.cpp b/src/codegen/compiler/value.cpp index 411cbe37ee..5e90b48ae3 100644 --- a/src/codegen/compiler/value.cpp +++ b/src/codegen/compiler/value.cpp @@ -31,26 +31,33 @@ Value::Value(Site* site, Site* target, ir::Type type) { } -bool Value::findSite(Site* site) { +bool Value::findSite(Site* site) +{ for (Site* s = this->sites; s; s = s->next) { - if (s == site) return true; + if (s == site) + return true; } return false; } -bool Value::isBuddyOf(Value* b) { +bool Value::isBuddyOf(Value* b) +{ Value* a = this; - if (a == b) return true; + if (a == b) + return true; for (Value* p = a->buddy; p != a; p = p->buddy) { - if (p == b) return true; + if (p == b) + return true; } return false; } -void Value::addSite(Context* c, Site* s) { +void Value::addSite(Context* c, Site* s) +{ if (not this->findSite(s)) { if (DebugSites) { - char buffer[256]; s->toString(c, buffer, 256); + char buffer[256]; + s->toString(c, buffer, 256); fprintf(stderr, "add site %s to %p\n", buffer, this); } s->acquire(c, this); @@ -59,9 +66,9 @@ void Value::addSite(Context* c, Site* s) { } } - -void Value::grow(Context* c) { - assert(c, this->nextWord == this); +void Value::grow(Context* c) +{ + assertT(c, this->nextWord == this); Value* next = value(c, this->type); this->nextWord = next; @@ -69,29 +76,32 @@ void Value::grow(Context* c) { next->wordIndex = 1; } - -void Value::maybeSplit(Context* c) { +void Value::maybeSplit(Context* c) +{ if (this->nextWord == this) { this->split(c); } } -void Value::split(Context* c) { +void Value::split(Context* c) +{ this->grow(c); for (SiteIterator it(c, this); it.hasMore();) { Site* s = it.next(); this->removeSite(c, s); - + this->addSite(c, s->copyLow(c)); this->nextWord->addSite(c, s->copyHigh(c)); } } -void Value::removeSite(Context* c, Site* s) { +void Value::removeSite(Context* c, Site* s) +{ for (SiteIterator it(c, this); it.hasMore();) { if (s == it.next()) { if (DebugSites) { - char buffer[256]; s->toString(c, buffer, 256); + char buffer[256]; + s->toString(c, buffer, 256); fprintf(stderr, "remove site %s from %p\n", buffer, this); } it.remove(c); @@ -101,15 +111,17 @@ void Value::removeSite(Context* c, Site* s) { if (DebugSites) { fprintf(stderr, "%p has more: %d\n", this, this->hasSite(c)); } - assert(c, not this->findSite(s)); + assertT(c, not this->findSite(s)); } -bool Value::hasSite(Context* c) { +bool Value::hasSite(Context* c) +{ SiteIterator it(c, this); return it.hasMore(); } -bool Value::uniqueSite(Context* c, Site* s) { +bool Value::uniqueSite(Context* c, Site* s) +{ SiteIterator it(c, this); Site* p UNUSED = it.next(); if (it.hasMore()) { @@ -126,14 +138,15 @@ bool Value::uniqueSite(Context* c, Site* s) { } } else { return false; - } + } } else { - assert(c, p == s); + assertT(c, p == s); return true; } } -void Value::clearSites(Context* c) { +void Value::clearSites(Context* c) +{ if (DebugSites) { fprintf(stderr, "clear sites for %p\n", this); } @@ -143,9 +156,9 @@ void Value::clearSites(Context* c) { } } - #ifndef NDEBUG -bool Value::hasBuddy(Context* c, Value* b) { +bool Value::hasBuddy(Context* c, Value* b) +{ Value* a = this; if (a == b) { return true; @@ -162,13 +175,13 @@ bool Value::hasBuddy(Context* c, Value* b) { } return false; } -#endif // not NDEBUG +#endif // not NDEBUG Value* value(Context* c, ir::Type type, Site* site, Site* target) { - return new(c->zone) Value(site, target, type); + return new (c->zone) Value(site, target, type); } -} // namespace regalloc -} // namespace codegen -} // namespace avian +} // namespace regalloc +} // namespace codegen +} // namespace avian diff --git a/src/codegen/compiler/value.h b/src/codegen/compiler/value.h index 3eaed04fa7..9143a93a2b 100644 --- a/src/codegen/compiler/value.h +++ b/src/codegen/compiler/value.h @@ -62,8 +62,7 @@ class Value : public ir::Value { #ifndef NDEBUG bool hasBuddy(Context* c, Value* b); -#endif // not NDEBUG - +#endif // not NDEBUG }; inline bool isFloatValue(ir::Value* a) @@ -78,8 +77,8 @@ inline bool isGeneralValue(ir::Value* a) Value* value(Context* c, ir::Type type, Site* site = 0, Site* target = 0); -} // namespace compiler -} // namespace codegen -} // namespace avian +} // namespace compiler +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_COMPILER_VALUE_H +#endif // AVIAN_CODEGEN_COMPILER_VALUE_H diff --git a/src/codegen/registers.cpp b/src/codegen/registers.cpp index 3bde6eb412..0f13f56244 100644 --- a/src/codegen/registers.cpp +++ b/src/codegen/registers.cpp @@ -13,23 +13,23 @@ namespace avian { namespace codegen { -unsigned -RegisterMask::maskStart(uint32_t mask) +unsigned RegisterMask::maskStart(uint32_t mask) { for (int i = 0; i <= 31; ++i) { - if (mask & (1 << i)) return i; + if (mask & (1 << i)) + return i; } return 32; } -unsigned -RegisterMask::maskLimit(uint32_t mask) +unsigned RegisterMask::maskLimit(uint32_t mask) { for (int i = 31; i >= 0; --i) { - if (mask & (1 << i)) return i + 1; + if (mask & (1 << i)) + return i + 1; } return 0; } -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian diff --git a/src/codegen/runtime.cpp b/src/codegen/runtime.cpp index 6ae3a887a3..2c8ff51c15 100644 --- a/src/codegen/runtime.cpp +++ b/src/codegen/runtime.cpp @@ -277,6 +277,6 @@ uint64_t longToFloat(int64_t a) return vm::floatToBits(static_cast(a)); } -} // namespace runtime -} // namespace codegen -} // namespace avian +} // namespace runtime +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/assembler.cpp b/src/codegen/target/arm/assembler.cpp index b817ef1ae2..9f9b0dcfce 100644 --- a/src/codegen/target/arm/assembler.cpp +++ b/src/codegen/target/arm/assembler.cpp @@ -36,8 +36,9 @@ namespace arm { namespace isa { // HARDWARE FLAGS -bool vfpSupported() { - // TODO: Use at runtime detection +bool vfpSupported() +{ +// TODO: Use at runtime detection #if defined(__ARM_PCS_VFP) // armhf return true; @@ -49,9 +50,12 @@ bool vfpSupported() { return false; #endif } -} // namespace isa +} // namespace isa -inline unsigned lo8(int64_t i) { return (unsigned)(i&MASK_LO8); } +inline unsigned lo8(int64_t i) +{ + return (unsigned)(i & MASK_LO8); +} const RegisterFile MyRegisterFileWithoutFloats(GPR_MASK, 0); const RegisterFile MyRegisterFileWithFloats(GPR_MASK, FPR_MASK); @@ -59,8 +63,8 @@ const RegisterFile MyRegisterFileWithFloats(GPR_MASK, FPR_MASK); const unsigned FrameHeaderSize = 1; const unsigned StackAlignmentInBytes = 8; -const unsigned StackAlignmentInWords -= StackAlignmentInBytes / TargetBytesPerWord; +const unsigned StackAlignmentInWords = StackAlignmentInBytes + / TargetBytesPerWord; void resolve(MyBlock*); @@ -74,19 +78,23 @@ using namespace isa; // END OPERATION COMPILERS -unsigned -argumentFootprint(unsigned footprint) +unsigned argumentFootprint(unsigned footprint) { return max(pad(footprint, StackAlignmentInWords), StackAlignmentInWords); } -void -nextFrame(ArchitectureContext* con, uint32_t* start, unsigned size UNUSED, - unsigned footprint, void* link, bool, - int targetParameterFootprint UNUSED, void** ip, void** stack) +void nextFrame(ArchitectureContext* con, + uint32_t* start, + unsigned size UNUSED, + unsigned footprint, + void* link, + bool, + int targetParameterFootprint UNUSED, + void** ip, + void** stack) { - assert(con, *ip >= start); - assert(con, *ip <= start + (size / TargetBytesPerWord)); + assertT(con, *ip >= start); + assertT(con, *ip <= start + (size / TargetBytesPerWord)); uint32_t* instruction = static_cast(*ip); @@ -108,7 +116,7 @@ nextFrame(ArchitectureContext* con, uint32_t* start, unsigned size UNUSED, return; } - if (*instruction == 0xe12fff1e) { // return + if (*instruction == 0xe12fff1e) { // return *ip = link; return; } @@ -116,7 +124,7 @@ nextFrame(ArchitectureContext* con, uint32_t* start, unsigned size UNUSED, if (TailCalls and targetParameterFootprint >= 0) { if (argumentFootprint(targetParameterFootprint) > StackAlignmentInWords) { offset += argumentFootprint(targetParameterFootprint) - - StackAlignmentInWords; + - StackAlignmentInWords; } // check for post-non-tail-call stack adjustment of the form "sub @@ -125,9 +133,14 @@ nextFrame(ArchitectureContext* con, uint32_t* start, unsigned size UNUSED, unsigned value = *instruction & 0xff; unsigned rotation = (*instruction >> 8) & 0xf; switch (rotation) { - case 0: offset -= value / TargetBytesPerWord; break; - case 15: offset -= value; break; - default: abort(con); + case 0: + offset -= value / TargetBytesPerWord; + break; + case 15: + offset -= value; + break; + default: + abort(con); } } @@ -138,45 +151,56 @@ nextFrame(ArchitectureContext* con, uint32_t* start, unsigned size UNUSED, *stack = static_cast(*stack) + offset; } -class MyArchitecture: public Architecture { +class MyArchitecture : public Architecture { public: - MyArchitecture(System* system): con(system), referenceCount(0) { + MyArchitecture(System* system) : con(system), referenceCount(0) + { populateTables(&con); } - virtual unsigned floatRegisterSize() { + virtual unsigned floatRegisterSize() + { return vfpSupported() ? 8 : 0; } - virtual const RegisterFile* registerFile() { - return vfpSupported() ? &MyRegisterFileWithFloats : &MyRegisterFileWithoutFloats; + virtual const RegisterFile* registerFile() + { + return vfpSupported() ? &MyRegisterFileWithFloats + : &MyRegisterFileWithoutFloats; } - virtual int scratch() { + virtual int scratch() + { return 5; } - virtual int stack() { + virtual int stack() + { return StackRegister; } - virtual int thread() { + virtual int thread() + { return ThreadRegister; } - virtual int returnLow() { + virtual int returnLow() + { return 0; } - virtual int returnHigh() { + virtual int returnHigh() + { return 1; } - virtual int virtualCallTarget() { + virtual int virtualCallTarget() + { return 4; } - virtual int virtualCallIndex() { + virtual int virtualCallIndex() + { return 3; } @@ -185,15 +209,18 @@ class MyArchitecture: public Architecture { return ir::TargetInfo(TargetBytesPerWord); } - virtual bool bigEndian() { + virtual bool bigEndian() + { return false; } - virtual uintptr_t maximumImmediateJump() { + virtual uintptr_t maximumImmediateJump() + { return 0x1FFFFFF; } - virtual bool reserved(int register_) { + virtual bool reserved(int register_) + { switch (register_) { case LinkRegister: case StackRegister: @@ -206,15 +233,18 @@ class MyArchitecture: public Architecture { } } - virtual unsigned frameFootprint(unsigned footprint) { + virtual unsigned frameFootprint(unsigned footprint) + { return max(footprint, StackAlignmentInWords); } - virtual unsigned argumentFootprint(unsigned footprint) { + virtual unsigned argumentFootprint(unsigned footprint) + { return arm::argumentFootprint(footprint); } - virtual bool argumentAlignment() { + virtual bool argumentAlignment() + { #ifdef __APPLE__ return false; #else @@ -222,7 +252,8 @@ class MyArchitecture: public Architecture { #endif } - virtual bool argumentRegisterAlignment() { + virtual bool argumentRegisterAlignment() + { #ifdef __APPLE__ return false; #else @@ -230,30 +261,35 @@ class MyArchitecture: public Architecture { #endif } - virtual unsigned argumentRegisterCount() { + virtual unsigned argumentRegisterCount() + { return 4; } - virtual int argumentRegister(unsigned index) { - assert(&con, index < argumentRegisterCount()); + virtual int argumentRegister(unsigned index) + { + assertT(&con, index < argumentRegisterCount()); return index; } - virtual bool hasLinkRegister() { + virtual bool hasLinkRegister() + { return true; } - virtual unsigned stackAlignmentInWords() { + virtual unsigned stackAlignmentInWords() + { return StackAlignmentInWords; } - virtual bool matchCall(void* returnAddress, void* target) { + virtual bool matchCall(void* returnAddress, void* target) + { uint32_t* instruction = static_cast(returnAddress) - 1; - return *instruction == static_cast - (bl(static_cast(target) - - reinterpret_cast(instruction))); + return *instruction == static_cast( + bl(static_cast(target) + - reinterpret_cast(instruction))); } virtual void updateCall(lir::UnaryOperation op UNUSED, @@ -265,7 +301,8 @@ class MyArchitecture: public Architecture { case lir::Jump: case lir::AlignedCall: case lir::AlignedJump: { - updateOffset(con.s, static_cast(returnAddress) - 4, + updateOffset(con.s, + static_cast(returnAddress) - 4, reinterpret_cast(newTarget)); } break; @@ -275,81 +312,105 @@ class MyArchitecture: public Architecture { case lir::AlignedLongJump: { uint32_t* p = static_cast(returnAddress) - 2; *reinterpret_cast(p + (((*p & PoolOffsetMask) + 8) / 4)) - = newTarget; + = newTarget; } break; - default: abort(&con); + default: + abort(&con); } } - virtual unsigned constantCallSize() { + virtual unsigned constantCallSize() + { return 4; } - virtual void setConstant(void* dst, uint64_t constant) { + virtual void setConstant(void* dst, uint64_t constant) + { *static_cast(dst) = constant; } - virtual unsigned alignFrameSize(unsigned sizeInWords) { + virtual unsigned alignFrameSize(unsigned sizeInWords) + { return pad(sizeInWords + FrameHeaderSize, StackAlignmentInWords) - - FrameHeaderSize; + - FrameHeaderSize; } - virtual void nextFrame(void* start, unsigned size, unsigned footprint, - void* link, bool mostRecent, - int targetParameterFootprint, void** ip, + virtual void nextFrame(void* start, + unsigned size, + unsigned footprint, + void* link, + bool mostRecent, + int targetParameterFootprint, + void** ip, void** stack) { - arm::nextFrame(&con, static_cast(start), size, footprint, link, - mostRecent, targetParameterFootprint, ip, stack); + arm::nextFrame(&con, + static_cast(start), + size, + footprint, + link, + mostRecent, + targetParameterFootprint, + ip, + stack); } - virtual void* frameIp(void* stack) { + virtual void* frameIp(void* stack) + { return stack ? static_cast(stack)[returnAddressOffset()] : 0; } - virtual unsigned frameHeaderSize() { + virtual unsigned frameHeaderSize() + { return FrameHeaderSize; } - virtual unsigned frameReturnAddressSize() { + virtual unsigned frameReturnAddressSize() + { return 0; } - virtual unsigned frameFooterSize() { + virtual unsigned frameFooterSize() + { return 0; } - virtual int returnAddressOffset() { + virtual int returnAddressOffset() + { return -1; } - virtual int framePointerOffset() { + virtual int framePointerOffset() + { return 0; } - - virtual bool alwaysCondensed(lir::BinaryOperation) { + + virtual bool alwaysCondensed(lir::BinaryOperation) + { return false; } - - virtual bool alwaysCondensed(lir::TernaryOperation) { + + virtual bool alwaysCondensed(lir::TernaryOperation) + { return false; } - - virtual void plan - (lir::UnaryOperation, - unsigned, OperandMask& aMask, - bool* thunk) + + virtual void plan(lir::UnaryOperation, + unsigned, + OperandMask& aMask, + bool* thunk) { aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::ConstantOperand); aMask.registerMask = ~static_cast(0); *thunk = false; } - virtual void planSource - (lir::BinaryOperation op, - unsigned aSize, OperandMask& aMask, - unsigned bSize, bool* thunk) + virtual void planSource(lir::BinaryOperation op, + unsigned aSize, + OperandMask& aMask, + unsigned bSize, + bool* thunk) { *thunk = false; aMask.typeMask = ~0; @@ -403,11 +464,12 @@ class MyArchitecture: public Architecture { break; } } - - virtual void planDestination - (lir::BinaryOperation op, - unsigned, const OperandMask& aMask, - unsigned, OperandMask& bMask) + + virtual void planDestination(lir::BinaryOperation op, + unsigned, + const OperandMask& aMask, + unsigned, + OperandMask& bMask) { bMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); bMask.registerMask = GPR_MASK64; @@ -443,10 +505,10 @@ class MyArchitecture: public Architecture { } } - virtual void planMove - (unsigned, OperandMask& srcMask, - OperandMask& tmpMask, - const OperandMask& dstMask) + virtual void planMove(unsigned, + OperandMask& srcMask, + OperandMask& tmpMask, + const OperandMask& dstMask) { srcMask.typeMask = ~0; srcMask.registerMask = ~static_cast(0); @@ -459,20 +521,21 @@ class MyArchitecture: public Architecture { srcMask.typeMask = 1 << lir::RegisterOperand; tmpMask.typeMask = 1 << lir::RegisterOperand; tmpMask.registerMask = GPR_MASK64; - } else if (vfpSupported() && - dstMask.typeMask & 1 << lir::RegisterOperand && - dstMask.registerMask & FPR_MASK) { - srcMask.typeMask = tmpMask.typeMask = 1 << lir::RegisterOperand | - 1 << lir::MemoryOperand; + } else if (vfpSupported() && dstMask.typeMask & 1 << lir::RegisterOperand + && dstMask.registerMask & FPR_MASK) { + srcMask.typeMask = tmpMask.typeMask = 1 << lir::RegisterOperand + | 1 << lir::MemoryOperand; tmpMask.registerMask = ~static_cast(0); } } - virtual void planSource - (lir::TernaryOperation op, - unsigned, OperandMask& aMask, - unsigned bSize, OperandMask& bMask, - unsigned, bool* thunk) + virtual void planSource(lir::TernaryOperation op, + unsigned, + OperandMask& aMask, + unsigned bSize, + OperandMask& bMask, + unsigned, + bool* thunk) { aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::ConstantOperand); aMask.registerMask = GPR_MASK64; @@ -486,7 +549,8 @@ class MyArchitecture: public Architecture { case lir::ShiftLeft: case lir::ShiftRight: case lir::UnsignedShiftRight: - if (bSize == 8) aMask.typeMask = bMask.typeMask = (1 << lir::RegisterOperand); + if (bSize == 8) + aMask.typeMask = bMask.typeMask = (1 << lir::RegisterOperand); break; case lir::Add: @@ -512,7 +576,7 @@ class MyArchitecture: public Architecture { aMask.registerMask = bMask.registerMask = FPR_MASK64; } else { *thunk = true; - } + } break; case lir::JumpIfFloatEqual: @@ -538,11 +602,13 @@ class MyArchitecture: public Architecture { } } - virtual void planDestination - (lir::TernaryOperation op, - unsigned, const OperandMask& aMask UNUSED, - unsigned, const OperandMask& bMask, - unsigned, OperandMask& cMask) + virtual void planDestination(lir::TernaryOperation op, + unsigned, + const OperandMask& aMask UNUSED, + unsigned, + const OperandMask& bMask, + unsigned, + OperandMask& cMask) { if (isBranch(op)) { cMask.typeMask = (1 << lir::ConstantOperand); @@ -555,12 +621,14 @@ class MyArchitecture: public Architecture { virtual Assembler* makeAssembler(Allocator* allocator, Zone* zone); - virtual void acquire() { - ++ referenceCount; + virtual void acquire() + { + ++referenceCount; } - virtual void release() { - if (-- referenceCount == 0) { + virtual void release() + { + if (--referenceCount == 0) { con.s->free(this); } } @@ -569,18 +637,21 @@ class MyArchitecture: public Architecture { unsigned referenceCount; }; -class MyAssembler: public Assembler { +class MyAssembler : public Assembler { public: - MyAssembler(System* s, Allocator* a, Zone* zone, MyArchitecture* arch): - con(s, a, zone), arch_(arch) - { } + MyAssembler(System* s, Allocator* a, Zone* zone, MyArchitecture* arch) + : con(s, a, zone), arch_(arch) + { + } - virtual void setClient(Client* client) { - assert(&con, con.client == 0); + virtual void setClient(Client* client) + { + assertT(&con, con.client == 0); con.client = client; } - virtual Architecture* arch() { + virtual Architecture* arch() + { return arch_; } @@ -589,12 +660,17 @@ class MyAssembler: public Assembler { { lir::Register stack(StackRegister); lir::Memory stackLimit(ThreadRegister, stackLimitOffsetFromThread); - lir::Constant handlerConstant(new(con.zone) ResolvedPromise(handler)); - branchRM(&con, lir::JumpIfGreaterOrEqual, TargetBytesPerWord, &stack, &stackLimit, + lir::Constant handlerConstant(new (con.zone) ResolvedPromise(handler)); + branchRM(&con, + lir::JumpIfGreaterOrEqual, + TargetBytesPerWord, + &stack, + &stackLimit, &handlerConstant); } - virtual void saveFrame(unsigned stackOffset, unsigned ipOffset) { + virtual void saveFrame(unsigned stackOffset, unsigned ipOffset) + { lir::Register link(LinkRegister); lir::Memory linkDst(ThreadRegister, ipOffset); moveRM(&con, TargetBytesPerWord, &link, TargetBytesPerWord, &linkDst); @@ -604,7 +680,8 @@ class MyAssembler: public Assembler { moveRM(&con, TargetBytesPerWord, &stack, TargetBytesPerWord, &stackDst); } - virtual void pushFrame(unsigned argumentCount, ...) { + virtual void pushFrame(unsigned argumentCount, ...) + { struct Argument { unsigned size; lir::OperandType type; @@ -612,55 +689,63 @@ class MyAssembler: public Assembler { }; RUNTIME_ARRAY(Argument, arguments, argumentCount); - va_list a; va_start(a, argumentCount); + va_list a; + va_start(a, argumentCount); unsigned footprint = 0; for (unsigned i = 0; i < argumentCount; ++i) { RUNTIME_ARRAY_BODY(arguments)[i].size = va_arg(a, unsigned); - RUNTIME_ARRAY_BODY(arguments)[i].type = static_cast(va_arg(a, int)); + RUNTIME_ARRAY_BODY(arguments)[i].type + = static_cast(va_arg(a, int)); RUNTIME_ARRAY_BODY(arguments)[i].operand = va_arg(a, lir::Operand*); - footprint += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord); + footprint += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord); } va_end(a); allocateFrame(arch_->alignFrameSize(footprint)); - + unsigned offset = 0; for (unsigned i = 0; i < argumentCount; ++i) { if (i < arch_->argumentRegisterCount()) { lir::Register dst(arch_->argumentRegister(i)); apply(lir::Move, - OperandInfo( - RUNTIME_ARRAY_BODY(arguments)[i].size, - RUNTIME_ARRAY_BODY(arguments)[i].type, - RUNTIME_ARRAY_BODY(arguments)[i].operand), - OperandInfo( - pad(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord), lir::RegisterOperand, &dst)); + OperandInfo(RUNTIME_ARRAY_BODY(arguments)[i].size, + RUNTIME_ARRAY_BODY(arguments)[i].type, + RUNTIME_ARRAY_BODY(arguments)[i].operand), + OperandInfo(pad(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord), + lir::RegisterOperand, + &dst)); - offset += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord); + offset += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord); } else { lir::Memory dst(StackRegister, offset * TargetBytesPerWord); apply(lir::Move, - OperandInfo( - RUNTIME_ARRAY_BODY(arguments)[i].size, - RUNTIME_ARRAY_BODY(arguments)[i].type, - RUNTIME_ARRAY_BODY(arguments)[i].operand), - OperandInfo( - pad(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord), lir::MemoryOperand, &dst)); + OperandInfo(RUNTIME_ARRAY_BODY(arguments)[i].size, + RUNTIME_ARRAY_BODY(arguments)[i].type, + RUNTIME_ARRAY_BODY(arguments)[i].operand), + OperandInfo(pad(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord), + lir::MemoryOperand, + &dst)); - offset += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord); + offset += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord); } } } - virtual void allocateFrame(unsigned footprint) { + virtual void allocateFrame(unsigned footprint) + { footprint += FrameHeaderSize; // larger frames may require multiple subtract/add instructions // to allocate/deallocate, and nextFrame will need to be taught // how to handle them: - assert(&con, footprint < 256); + assertT(&con, footprint < 256); lir::Register stack(StackRegister); ResolvedPromise footprintPromise(footprint * TargetBytesPerWord); @@ -668,28 +753,36 @@ class MyAssembler: public Assembler { subC(&con, TargetBytesPerWord, &footprintConstant, &stack, &stack); lir::Register returnAddress(LinkRegister); - lir::Memory returnAddressDst - (StackRegister, (footprint - 1) * TargetBytesPerWord); - moveRM(&con, TargetBytesPerWord, &returnAddress, TargetBytesPerWord, + lir::Memory returnAddressDst(StackRegister, + (footprint - 1) * TargetBytesPerWord); + moveRM(&con, + TargetBytesPerWord, + &returnAddress, + TargetBytesPerWord, &returnAddressDst); } - virtual void adjustFrame(unsigned difference) { + virtual void adjustFrame(unsigned difference) + { lir::Register stack(StackRegister); ResolvedPromise differencePromise(difference * TargetBytesPerWord); lir::Constant differenceConstant(&differencePromise); subC(&con, TargetBytesPerWord, &differenceConstant, &stack, &stack); } - virtual void popFrame(unsigned footprint) { + virtual void popFrame(unsigned footprint) + { footprint += FrameHeaderSize; lir::Register returnAddress(LinkRegister); - lir::Memory returnAddressSrc - (StackRegister, (footprint - 1) * TargetBytesPerWord); - moveMR(&con, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord, + lir::Memory returnAddressSrc(StackRegister, + (footprint - 1) * TargetBytesPerWord); + moveMR(&con, + TargetBytesPerWord, + &returnAddressSrc, + TargetBytesPerWord, &returnAddress); - + lir::Register stack(StackRegister); ResolvedPromise footprintPromise(footprint * TargetBytesPerWord); lir::Constant footprintConstant(&footprintPromise); @@ -701,26 +794,29 @@ class MyAssembler: public Assembler { int returnAddressSurrogate, int framePointerSurrogate UNUSED) { - assert(&con, framePointerSurrogate == lir::NoRegister); + assertT(&con, framePointerSurrogate == lir::NoRegister); if (TailCalls) { if (offset) { footprint += FrameHeaderSize; lir::Register link(LinkRegister); - lir::Memory returnAddressSrc - (StackRegister, (footprint - 1) * TargetBytesPerWord); - moveMR(&con, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord, + lir::Memory returnAddressSrc(StackRegister, + (footprint - 1) * TargetBytesPerWord); + moveMR(&con, + TargetBytesPerWord, + &returnAddressSrc, + TargetBytesPerWord, &link); - + lir::Register stack(StackRegister); - ResolvedPromise footprintPromise - ((footprint - offset) * TargetBytesPerWord); + ResolvedPromise footprintPromise((footprint - offset) + * TargetBytesPerWord); lir::Constant footprintConstant(&footprintPromise); addC(&con, TargetBytesPerWord, &footprintConstant, &stack, &stack); if (returnAddressSurrogate != lir::NoRegister) { - assert(&con, offset > 0); + assertT(&con, offset > 0); lir::Register ras(returnAddressSurrogate); lir::Memory dst(StackRegister, (offset - 1) * TargetBytesPerWord); @@ -739,8 +835,8 @@ class MyAssembler: public Assembler { { popFrame(frameFootprint); - assert(&con, argumentFootprint >= StackAlignmentInWords); - assert(&con, (argumentFootprint % StackAlignmentInWords) == 0); + assertT(&con, argumentFootprint >= StackAlignmentInWords); + assertT(&con, (argumentFootprint % StackAlignmentInWords) == 0); unsigned offset; if (TailCalls and argumentFootprint > StackAlignmentInWords) { @@ -769,46 +865,52 @@ class MyAssembler: public Assembler { return_(&con); } - virtual void apply(lir::Operation op) { + virtual void apply(lir::Operation op) + { arch_->con.operations[op](&con); } virtual void apply(lir::UnaryOperation op, OperandInfo a) { - arch_->con.unaryOperations[Multimethod::index(op, a.type)] - (&con, a.size, a.operand); + arch_->con.unaryOperations[Multimethod::index(op, a.type)]( + &con, a.size, a.operand); } virtual void apply(lir::BinaryOperation op, OperandInfo a, OperandInfo b) { - arch_->con.binaryOperations[index(&(arch_->con), op, a.type, b.type)] - (&con, a.size, a.operand, b.size, b.operand); + arch_->con.binaryOperations[index(&(arch_->con), op, a.type, b.type)]( + &con, a.size, a.operand, b.size, b.operand); } - virtual void apply(lir::TernaryOperation op, OperandInfo a, OperandInfo b, OperandInfo c) + virtual void apply(lir::TernaryOperation op, + OperandInfo a, + OperandInfo b, + OperandInfo c) { if (isBranch(op)) { - assert(&con, a.size == b.size); - assert(&con, c.size == TargetBytesPerWord); - assert(&con, c.type == lir::ConstantOperand); + assertT(&con, a.size == b.size); + assertT(&con, c.size == TargetBytesPerWord); + assertT(&con, c.type == lir::ConstantOperand); - arch_->con.branchOperations[branchIndex(&(arch_->con), a.type, b.type)] - (&con, op, a.size, a.operand, b.operand, c.operand); + arch_->con.branchOperations[branchIndex(&(arch_->con), a.type, b.type)]( + &con, op, a.size, a.operand, b.operand, c.operand); } else { - assert(&con, b.size == c.size); - assert(&con, b.type == lir::RegisterOperand); - assert(&con, c.type == lir::RegisterOperand); + assertT(&con, b.size == c.size); + assertT(&con, b.type == lir::RegisterOperand); + assertT(&con, c.type == lir::RegisterOperand); - arch_->con.ternaryOperations[index(&(arch_->con), op, a.type)] - (&con, b.size, a.operand, b.operand, c.operand); + arch_->con.ternaryOperations[index(&(arch_->con), op, a.type)]( + &con, b.size, a.operand, b.operand, c.operand); } } - virtual void setDestination(uint8_t* dst) { + virtual void setDestination(uint8_t* dst) + { con.result = dst; } - virtual void write() { + virtual void write() + { uint8_t* dst = con.result; unsigned dstOffset = 0; for (MyBlock* b = con.firstBlock; b; b = b->next) { @@ -828,8 +930,11 @@ class MyAssembler: public Assembler { unsigned poolSize = 0; for (PoolOffset* o = e->poolOffsetHead; o; o = o->next) { if (DebugPool) { - fprintf(stderr, "visit pool offset %p %d in block %p\n", - o, o->offset, b); + fprintf(stderr, + "visit pool offset %p %d in block %p\n", + o, + o->offset, + b); } unsigned entry = dstOffset + poolSize; @@ -840,8 +945,8 @@ class MyAssembler: public Assembler { o->entry->address = dst + entry; - unsigned instruction = o->block->start - + padding(o->block, o->offset) + o->offset; + unsigned instruction = o->block->start + padding(o->block, o->offset) + + o->offset; int32_t v = (entry - 8) - instruction; expect(&con, v == (v & PoolOffsetMask)); @@ -854,8 +959,8 @@ class MyAssembler: public Assembler { bool jump = needJump(b); if (jump) { - write4 - (dst + dstOffset, isa::b((poolSize + TargetBytesPerWord - 8) >> 2)); + write4(dst + dstOffset, + isa::b((poolSize + TargetBytesPerWord - 8) >> 2)); } dstOffset += poolSize + (jump ? TargetBytesPerWord : 0); @@ -879,20 +984,27 @@ class MyAssembler: public Assembler { *static_cast(e->address) = e->constant->value(); } else { new (e->constant->listen(sizeof(ConstantPoolListener))) - ConstantPoolListener(con.s, static_cast(e->address), - e->callOffset - ? dst + e->callOffset->value() + 8 - : 0); + ConstantPoolListener( + con.s, + static_cast(e->address), + e->callOffset ? dst + e->callOffset->value() + 8 : 0); + } + if (false) { + fprintf(stderr, + "constant %p at %p\n", + reinterpret_cast(e->constant->value()), + e->address); } -// fprintf(stderr, "constant %p at %p\n", reinterpret_cast(e->constant->value()), e->address); } } - virtual Promise* offset(bool forTrace) { + virtual Promise* offset(bool forTrace) + { return arm::offsetPromise(&con, forTrace); } - virtual Block* endBlock(bool startNew) { + virtual Block* endBlock(bool startNew) + { MyBlock* b = con.lastBlock; b->size = con.code.length() - b->offset; if (startNew) { @@ -903,26 +1015,33 @@ class MyAssembler: public Assembler { return b; } - virtual void endEvent() { + virtual void endEvent() + { MyBlock* b = con.lastBlock; unsigned thisEventOffset = con.code.length() - b->offset; if (b->poolOffsetHead) { int32_t v = (thisEventOffset + TargetBytesPerWord - 8) - - b->poolOffsetHead->offset; + - b->poolOffsetHead->offset; if (v > 0 and v != (v & PoolOffsetMask)) { - appendPoolEvent - (&con, b, b->lastEventOffset, b->poolOffsetHead, - b->lastPoolOffsetTail); + appendPoolEvent(&con, + b, + b->lastEventOffset, + b->poolOffsetHead, + b->lastPoolOffsetTail); if (DebugPool) { for (PoolOffset* o = b->poolOffsetHead; - o != b->lastPoolOffsetTail->next; o = o->next) - { + o != b->lastPoolOffsetTail->next; + o = o->next) { fprintf(stderr, "in endEvent, include %p %d in pool event %p at offset %d " "in block %p\n", - o, o->offset, b->poolEventTail, b->lastEventOffset, b); + o, + o->offset, + b->poolEventTail, + b->lastEventOffset, + b); } } @@ -937,15 +1056,18 @@ class MyAssembler: public Assembler { b->lastPoolOffsetTail = b->poolOffsetTail; } - virtual unsigned length() { + virtual unsigned length() + { return con.code.length(); } - virtual unsigned footerSize() { + virtual unsigned footerSize() + { return 0; } - virtual void dispose() { + virtual void dispose() + { con.code.dispose(); } @@ -953,17 +1075,18 @@ class MyAssembler: public Assembler { MyArchitecture* arch_; }; -Assembler* MyArchitecture::makeAssembler(Allocator* allocator, Zone* zone) { - return new(zone) MyAssembler(this->con.s, allocator, zone, this); -} - -} // namespace arm - -Architecture* -makeArchitectureArm(System* system, bool) +Assembler* MyArchitecture::makeAssembler(Allocator* allocator, Zone* zone) { - return new (allocate(system, sizeof(arm::MyArchitecture))) arm::MyArchitecture(system); + return new (zone) MyAssembler(this->con.s, allocator, zone, this); } -} // namespace codegen -} // namespace avian +} // namespace arm + +Architecture* makeArchitectureArm(System* system, bool) +{ + return new (allocate(system, sizeof(arm::MyArchitecture))) + arm::MyArchitecture(system); +} + +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/block.cpp b/src/codegen/target/arm/block.cpp index f6383965ea..d0995e329b 100644 --- a/src/codegen/target/arm/block.cpp +++ b/src/codegen/target/arm/block.cpp @@ -19,13 +19,23 @@ void resolve(MyBlock*); unsigned padding(MyBlock*, unsigned); -MyBlock::MyBlock(Context* context, unsigned offset): - context(context), next(0), poolOffsetHead(0), poolOffsetTail(0), - lastPoolOffsetTail(0), poolEventHead(0), poolEventTail(0), - lastEventOffset(0), offset(offset), start(~0), size(0) -{ } +MyBlock::MyBlock(Context* context, unsigned offset) + : context(context), + next(0), + poolOffsetHead(0), + poolOffsetTail(0), + lastPoolOffsetTail(0), + poolEventHead(0), + poolEventTail(0), + lastEventOffset(0), + offset(offset), + start(~0), + size(0) +{ +} -unsigned MyBlock::resolve(unsigned start, Assembler::Block* next) { +unsigned MyBlock::resolve(unsigned start, Assembler::Block* next) +{ this->start = start; this->next = static_cast(next); @@ -34,6 +44,6 @@ unsigned MyBlock::resolve(unsigned start, Assembler::Block* next) { return start + size + padding(this, size); } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/block.h b/src/codegen/target/arm/block.h index b926924969..d40cc45d3d 100644 --- a/src/codegen/target/arm/block.h +++ b/src/codegen/target/arm/block.h @@ -20,7 +20,7 @@ namespace arm { class PoolEvent; -class MyBlock: public Assembler::Block { +class MyBlock : public Assembler::Block { public: MyBlock(Context* context, unsigned offset); @@ -39,8 +39,8 @@ class MyBlock: public Assembler::Block { unsigned size; }; -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_BLOCK_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_BLOCK_H diff --git a/src/codegen/target/arm/context.cpp b/src/codegen/target/arm/context.cpp index d1f64e7916..1c2757abbc 100644 --- a/src/codegen/target/arm/context.cpp +++ b/src/codegen/target/arm/context.cpp @@ -31,6 +31,6 @@ Context::Context(vm::System* s, util::Allocator* a, vm::Zone* zone) { } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/context.h b/src/codegen/target/arm/context.h index 4bf8c5adb2..15d3c2e0f0 100644 --- a/src/codegen/target/arm/context.h +++ b/src/codegen/target/arm/context.h @@ -18,14 +18,14 @@ namespace vm { class System; class Zone; -} // namespace vm +} // namespace vm namespace avian { namespace util { class Aborter; class Allocator; -} // namespace util +} // namespace util namespace codegen { namespace arm { @@ -57,43 +57,57 @@ typedef void (*OperationType)(Context*); typedef void (*UnaryOperationType)(Context*, unsigned, lir::Operand*); -typedef void (*BinaryOperationType) -(Context*, unsigned, lir::Operand*, unsigned, lir::Operand*); +typedef void (*BinaryOperationType)(Context*, + unsigned, + lir::Operand*, + unsigned, + lir::Operand*); -typedef void (*TernaryOperationType) -(Context*, unsigned, lir::Operand*, lir::Operand*, - lir::Operand*); +typedef void (*TernaryOperationType)(Context*, + unsigned, + lir::Operand*, + lir::Operand*, + lir::Operand*); -typedef void (*BranchOperationType) -(Context*, lir::TernaryOperation, unsigned, lir::Operand*, - lir::Operand*, lir::Operand*); +typedef void (*BranchOperationType)(Context*, + lir::TernaryOperation, + unsigned, + lir::Operand*, + lir::Operand*, + lir::Operand*); class ArchitectureContext { public: - ArchitectureContext(vm::System* s): s(s) { } + ArchitectureContext(vm::System* s) : s(s) + { + } vm::System* s; OperationType operations[lir::OperationCount]; - UnaryOperationType unaryOperations[lir::UnaryOperationCount - * lir::OperandTypeCount]; - BinaryOperationType binaryOperations - [lir::BinaryOperationCount * lir::OperandTypeCount * lir::OperandTypeCount]; - TernaryOperationType ternaryOperations - [lir::NonBranchTernaryOperationCount * lir::OperandTypeCount]; - BranchOperationType branchOperations - [lir::BranchOperationCount * lir::OperandTypeCount * lir::OperandTypeCount]; + UnaryOperationType + unaryOperations[lir::UnaryOperationCount * lir::OperandTypeCount]; + BinaryOperationType binaryOperations[lir::BinaryOperationCount + * lir::OperandTypeCount + * lir::OperandTypeCount]; + TernaryOperationType ternaryOperations[lir::NonBranchTernaryOperationCount + * lir::OperandTypeCount]; + BranchOperationType branchOperations[lir::BranchOperationCount + * lir::OperandTypeCount + * lir::OperandTypeCount]; }; -inline avian::util::Aborter* getAborter(Context* c) { +inline avian::util::Aborter* getAborter(Context* c) +{ return c->s; } -inline avian::util::Aborter* getAborter(ArchitectureContext* c) { +inline avian::util::Aborter* getAborter(ArchitectureContext* c) +{ return c->s; } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_CONTEXT_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_CONTEXT_H diff --git a/src/codegen/target/arm/encode.h b/src/codegen/target/arm/encode.h index aef77ca50e..edbeb3d071 100644 --- a/src/codegen/target/arm/encode.h +++ b/src/codegen/target/arm/encode.h @@ -25,162 +25,668 @@ const int FPSID = 0x0; const int FPSCR = 0x1; const int FPEXC = 0x8; // INSTRUCTION OPTIONS -enum CONDITION { EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE, AL, NV }; +enum CONDITION { + EQ, + NE, + CS, + CC, + MI, + PL, + VS, + VC, + HI, + LS, + GE, + LT, + GT, + LE, + AL, + NV +}; enum SHIFTOP { LSL, LSR, ASR, ROR }; // INSTRUCTION FORMATS -inline int DATA(int cond, int opcode, int S, int Rn, int Rd, int shift, int Sh, int Rm) -{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; } -inline int DATAS(int cond, int opcode, int S, int Rn, int Rd, int Rs, int Sh, int Rm) -{ return cond<<28 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | Rs<<8 | Sh<<5 | 1<<4 | Rm; } +inline int + DATA(int cond, int opcode, int S, int Rn, int Rd, int shift, int Sh, int Rm) +{ + return cond << 28 | opcode << 21 | S << 20 | Rn << 16 | Rd << 12 | shift << 7 + | Sh << 5 | Rm; +} +inline int + DATAS(int cond, int opcode, int S, int Rn, int Rd, int Rs, int Sh, int Rm) +{ + return cond << 28 | opcode << 21 | S << 20 | Rn << 16 | Rd << 12 | Rs << 8 + | Sh << 5 | 1 << 4 | Rm; +} inline int DATAI(int cond, int opcode, int S, int Rn, int Rd, int rot, int imm) -{ return cond<<28 | 1<<25 | opcode<<21 | S<<20 | Rn<<16 | Rd<<12 | rot<<8 | (imm&0xff); } +{ + return cond << 28 | 1 << 25 | opcode << 21 | S << 20 | Rn << 16 | Rd << 12 + | rot << 8 | (imm & 0xff); +} inline int BRANCH(int cond, int L, int offset) -{ return cond<<28 | 5<<25 | L<<24 | (offset&0xffffff); } +{ + return cond << 28 | 5 << 25 | L << 24 | (offset & 0xffffff); +} inline int BRANCHX(int cond, int L, int Rm) -{ return cond<<28 | 0x4bffc<<6 | L<<5 | 1<<4 | Rm; } +{ + return cond << 28 | 0x4bffc << 6 | L << 5 | 1 << 4 | Rm; +} inline int MULTIPLY(int cond, int mul, int S, int Rd, int Rn, int Rs, int Rm) -{ return cond<<28 | mul<<21 | S<<20 | Rd<<16 | Rn<<12 | Rs<<8 | 9<<4 | Rm; } -inline int XFER(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int shift, int Sh, int Rm) -{ return cond<<28 | 3<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | shift<<7 | Sh<<5 | Rm; } -inline int XFERI(int cond, int P, int U, int B, int W, int L, int Rn, int Rd, int offset) -{ return cond<<28 | 2<<25 | P<<24 | U<<23 | B<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | (offset&0xfff); } -inline int XFER2(int cond, int P, int U, int W, int L, int Rn, int Rd, int S, int H, int Rm) -{ return cond<<28 | P<<24 | U<<23 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | 1<<7 | S<<6 | H<<5 | 1<<4 | Rm; } -inline int XFER2I(int cond, int P, int U, int W, int L, int Rn, int Rd, int offsetH, int S, int H, int offsetL) -{ return cond<<28 | P<<24 | U<<23 | 1<<22 | W<<21 | L<<20 | Rn<<16 | Rd<<12 | offsetH<<8 | 1<<7 | S<<6 | H<<5 | 1<<4 | (offsetL&0xf); } -inline int COOP(int cond, int opcode_1, int CRn, int CRd, int cp_num, int opcode_2, int CRm) -{ return cond<<28 | 0xe<<24 | opcode_1<<20 | CRn<<16 | CRd<<12 | cp_num<<8 | opcode_2<<5 | CRm; } -inline int COXFER(int cond, int P, int U, int N, int W, int L, int Rn, int CRd, int cp_num, int offset) // offset is in words, not bytes -{ return cond<<28 | 0x6<<25 | P<<24 | U<<23 | N<<22 | W<<21 | L<<20 | Rn<<16 | CRd<<12 | cp_num<<8 | (offset&0xff)>>2; } -inline int COREG(int cond, int opcode_1, int L, int CRn, int Rd, int cp_num, int opcode_2, int CRm) -{ return cond<<28 | 0xe<<24 | opcode_1<<21 | L<<20 | CRn<<16 | Rd<<12 | cp_num<<8 | opcode_2<<5 | 1<<4 | CRm; } -inline int COREG2(int cond, int L, int Rn, int Rd, int cp_num, int opcode, int CRm) -{ return cond<<28 | 0xc4<<20 | L<<20 | Rn<<16 | Rd<<12 | cp_num<<8 | opcode<<4 | CRm;} +{ + return cond << 28 | mul << 21 | S << 20 | Rd << 16 | Rn << 12 | Rs << 8 + | 9 << 4 | Rm; +} +inline int XFER(int cond, + int P, + int U, + int B, + int W, + int L, + int Rn, + int Rd, + int shift, + int Sh, + int Rm) +{ + return cond << 28 | 3 << 25 | P << 24 | U << 23 | B << 22 | W << 21 | L << 20 + | Rn << 16 | Rd << 12 | shift << 7 | Sh << 5 | Rm; +} +inline int XFERI(int cond, + int P, + int U, + int B, + int W, + int L, + int Rn, + int Rd, + int offset) +{ + return cond << 28 | 2 << 25 | P << 24 | U << 23 | B << 22 | W << 21 | L << 20 + | Rn << 16 | Rd << 12 | (offset & 0xfff); +} +inline int XFER2(int cond, + int P, + int U, + int W, + int L, + int Rn, + int Rd, + int S, + int H, + int Rm) +{ + return cond << 28 | P << 24 | U << 23 | W << 21 | L << 20 | Rn << 16 + | Rd << 12 | 1 << 7 | S << 6 | H << 5 | 1 << 4 | Rm; +} +inline int XFER2I(int cond, + int P, + int U, + int W, + int L, + int Rn, + int Rd, + int offsetH, + int S, + int H, + int offsetL) +{ + return cond << 28 | P << 24 | U << 23 | 1 << 22 | W << 21 | L << 20 | Rn << 16 + | Rd << 12 | offsetH << 8 | 1 << 7 | S << 6 | H << 5 | 1 << 4 + | (offsetL & 0xf); +} +inline int COOP(int cond, + int opcode_1, + int CRn, + int CRd, + int cp_num, + int opcode_2, + int CRm) +{ + return cond << 28 | 0xe << 24 | opcode_1 << 20 | CRn << 16 | CRd << 12 + | cp_num << 8 | opcode_2 << 5 | CRm; +} +inline int COXFER(int cond, + int P, + int U, + int N, + int W, + int L, + int Rn, + int CRd, + int cp_num, + int offset) // offset is in words, not bytes +{ + return cond << 28 | 0x6 << 25 | P << 24 | U << 23 | N << 22 | W << 21 + | L << 20 | Rn << 16 | CRd << 12 | cp_num << 8 | (offset & 0xff) >> 2; +} +inline int COREG(int cond, + int opcode_1, + int L, + int CRn, + int Rd, + int cp_num, + int opcode_2, + int CRm) +{ + return cond << 28 | 0xe << 24 | opcode_1 << 21 | L << 20 | CRn << 16 + | Rd << 12 | cp_num << 8 | opcode_2 << 5 | 1 << 4 | CRm; +} +inline int + COREG2(int cond, int L, int Rn, int Rd, int cp_num, int opcode, int CRm) +{ + return cond << 28 | 0xc4 << 20 | L << 20 | Rn << 16 | Rd << 12 | cp_num << 8 + | opcode << 4 | CRm; +} // FIELD CALCULATORS -inline int calcU(int imm) { return imm >= 0 ? 1 : 0; } +inline int calcU(int imm) +{ + return imm >= 0 ? 1 : 0; +} // INSTRUCTIONS // The "cond" and "S" fields are set using the SETCOND() and SETS() functions -inline int b(int offset) { return BRANCH(AL, 0, offset); } -inline int bl(int offset) { return BRANCH(AL, 1, offset); } -inline int bx(int Rm) { return BRANCHX(AL, 0, Rm); } -inline int blx(int Rm) { return BRANCHX(AL, 1, Rm); } -inline int and_(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x0, 0, Rn, Rd, shift, Sh, Rm); } -inline int eor(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x1, 0, Rn, Rd, shift, Sh, Rm); } -inline int rsb(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x3, 0, Rn, Rd, shift, Sh, Rm); } -inline int add(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x4, 0, Rn, Rd, shift, Sh, Rm); } -inline int adc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x5, 0, Rn, Rd, shift, Sh, Rm); } -inline int rsc(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0x7, 0, Rn, Rd, shift, Sh, Rm); } -inline int cmp(int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xa, 1, Rn, 0, shift, Sh, Rm); } -inline int orr(int Rd, int Rn, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xc, 0, Rn, Rd, shift, Sh, Rm); } -inline int mov(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xd, 0, 0, Rd, shift, Sh, Rm); } -inline int mvn(int Rd, int Rm, int Sh=0, int shift=0) { return DATA(AL, 0xf, 0, 0, Rd, shift, Sh, Rm); } -inline int andi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x0, 0, Rn, Rd, rot, imm); } -inline int subi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x2, 0, Rn, Rd, rot, imm); } -inline int rsbi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x3, 0, Rn, Rd, rot, imm); } -inline int addi(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x4, 0, Rn, Rd, rot, imm); } -inline int adci(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0x5, 0, Rn, Rd, rot, imm); } -inline int bici(int Rd, int Rn, int imm, int rot=0) { return DATAI(AL, 0xe, 0, Rn, Rd, rot, imm); } -inline int cmpi(int Rn, int imm, int rot=0) { return DATAI(AL, 0xa, 1, Rn, 0, rot, imm); } -inline int movi(int Rd, int imm, int rot=0) { return DATAI(AL, 0xd, 0, 0, Rd, rot, imm); } -inline int orrsh(int Rd, int Rn, int Rm, int Rs, int Sh) { return DATAS(AL, 0xc, 0, Rn, Rd, Rs, Sh, Rm); } -inline int movsh(int Rd, int Rm, int Rs, int Sh) { return DATAS(AL, 0xd, 0, 0, Rd, Rs, Sh, Rm); } -inline int mul(int Rd, int Rm, int Rs) { return MULTIPLY(AL, 0, 0, Rd, 0, Rs, Rm); } -inline int mla(int Rd, int Rm, int Rs, int Rn) { return MULTIPLY(AL, 1, 0, Rd, Rn, Rs, Rm); } -inline int umull(int RdLo, int RdHi, int Rm, int Rs) { return MULTIPLY(AL, 4, 0, RdHi, RdLo, Rs, Rm); } -inline int ldr(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 1, Rn, Rd, 0, 0, Rm); } -inline int ldri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 1, Rn, Rd, abs(imm)); } -inline int ldrb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 1, Rn, Rd, 0, 0, Rm); } -inline int ldrbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 1, Rn, Rd, abs(imm)); } -inline int str(int Rd, int Rn, int Rm, int W=0) { return XFER(AL, 1, 1, 0, W, 0, Rn, Rd, 0, 0, Rm); } -inline int stri(int Rd, int Rn, int imm, int W=0) { return XFERI(AL, 1, calcU(imm), 0, W, 0, Rn, Rd, abs(imm)); } -inline int strb(int Rd, int Rn, int Rm) { return XFER(AL, 1, 1, 1, 0, 0, Rn, Rd, 0, 0, Rm); } -inline int strbi(int Rd, int Rn, int imm) { return XFERI(AL, 1, calcU(imm), 1, 0, 0, Rn, Rd, abs(imm)); } -inline int ldrh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 0, 1, Rm); } -inline int ldrhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); } -inline int strh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 0, Rn, Rd, 0, 1, Rm); } -inline int strhi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 0, Rn, Rd, abs(imm)>>4 & 0xf, 0, 1, abs(imm)&0xf); } -inline int ldrsh(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 1, Rm); } -inline int ldrshi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 1, abs(imm)&0xf); } -inline int ldrsb(int Rd, int Rn, int Rm) { return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 0, Rm); } -inline int ldrsbi(int Rd, int Rn, int imm) { return XFER2I(AL, 1, calcU(imm), 0, 1, Rn, Rd, abs(imm)>>4 & 0xf, 1, 0, abs(imm)&0xf); } +inline int b(int offset) +{ + return BRANCH(AL, 0, offset); +} +inline int bl(int offset) +{ + return BRANCH(AL, 1, offset); +} +inline int bx(int Rm) +{ + return BRANCHX(AL, 0, Rm); +} +inline int blx(int Rm) +{ + return BRANCHX(AL, 1, Rm); +} +inline int and_(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x0, 0, Rn, Rd, shift, Sh, Rm); +} +inline int eor(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x1, 0, Rn, Rd, shift, Sh, Rm); +} +inline int rsb(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x3, 0, Rn, Rd, shift, Sh, Rm); +} +inline int add(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x4, 0, Rn, Rd, shift, Sh, Rm); +} +inline int adc(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x5, 0, Rn, Rd, shift, Sh, Rm); +} +inline int rsc(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0x7, 0, Rn, Rd, shift, Sh, Rm); +} +inline int cmp(int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0xa, 1, Rn, 0, shift, Sh, Rm); +} +inline int orr(int Rd, int Rn, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0xc, 0, Rn, Rd, shift, Sh, Rm); +} +inline int mov(int Rd, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0xd, 0, 0, Rd, shift, Sh, Rm); +} +inline int mvn(int Rd, int Rm, int Sh = 0, int shift = 0) +{ + return DATA(AL, 0xf, 0, 0, Rd, shift, Sh, Rm); +} +inline int andi(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0x0, 0, Rn, Rd, rot, imm); +} +inline int subi(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0x2, 0, Rn, Rd, rot, imm); +} +inline int rsbi(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0x3, 0, Rn, Rd, rot, imm); +} +inline int addi(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0x4, 0, Rn, Rd, rot, imm); +} +inline int adci(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0x5, 0, Rn, Rd, rot, imm); +} +inline int bici(int Rd, int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0xe, 0, Rn, Rd, rot, imm); +} +inline int cmpi(int Rn, int imm, int rot = 0) +{ + return DATAI(AL, 0xa, 1, Rn, 0, rot, imm); +} +inline int movi(int Rd, int imm, int rot = 0) +{ + return DATAI(AL, 0xd, 0, 0, Rd, rot, imm); +} +inline int orrsh(int Rd, int Rn, int Rm, int Rs, int Sh) +{ + return DATAS(AL, 0xc, 0, Rn, Rd, Rs, Sh, Rm); +} +inline int movsh(int Rd, int Rm, int Rs, int Sh) +{ + return DATAS(AL, 0xd, 0, 0, Rd, Rs, Sh, Rm); +} +inline int mul(int Rd, int Rm, int Rs) +{ + return MULTIPLY(AL, 0, 0, Rd, 0, Rs, Rm); +} +inline int mla(int Rd, int Rm, int Rs, int Rn) +{ + return MULTIPLY(AL, 1, 0, Rd, Rn, Rs, Rm); +} +inline int umull(int RdLo, int RdHi, int Rm, int Rs) +{ + return MULTIPLY(AL, 4, 0, RdHi, RdLo, Rs, Rm); +} +inline int ldr(int Rd, int Rn, int Rm, int W = 0) +{ + return XFER(AL, 1, 1, 0, W, 1, Rn, Rd, 0, 0, Rm); +} +inline int ldri(int Rd, int Rn, int imm, int W = 0) +{ + return XFERI(AL, 1, calcU(imm), 0, W, 1, Rn, Rd, abs(imm)); +} +inline int ldrb(int Rd, int Rn, int Rm) +{ + return XFER(AL, 1, 1, 1, 0, 1, Rn, Rd, 0, 0, Rm); +} +inline int ldrbi(int Rd, int Rn, int imm) +{ + return XFERI(AL, 1, calcU(imm), 1, 0, 1, Rn, Rd, abs(imm)); +} +inline int str(int Rd, int Rn, int Rm, int W = 0) +{ + return XFER(AL, 1, 1, 0, W, 0, Rn, Rd, 0, 0, Rm); +} +inline int stri(int Rd, int Rn, int imm, int W = 0) +{ + return XFERI(AL, 1, calcU(imm), 0, W, 0, Rn, Rd, abs(imm)); +} +inline int strb(int Rd, int Rn, int Rm) +{ + return XFER(AL, 1, 1, 1, 0, 0, Rn, Rd, 0, 0, Rm); +} +inline int strbi(int Rd, int Rn, int imm) +{ + return XFERI(AL, 1, calcU(imm), 1, 0, 0, Rn, Rd, abs(imm)); +} +inline int ldrh(int Rd, int Rn, int Rm) +{ + return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 0, 1, Rm); +} +inline int ldrhi(int Rd, int Rn, int imm) +{ + return XFER2I(AL, + 1, + calcU(imm), + 0, + 1, + Rn, + Rd, + abs(imm) >> 4 & 0xf, + 0, + 1, + abs(imm) & 0xf); +} +inline int strh(int Rd, int Rn, int Rm) +{ + return XFER2(AL, 1, 1, 0, 0, Rn, Rd, 0, 1, Rm); +} +inline int strhi(int Rd, int Rn, int imm) +{ + return XFER2I(AL, + 1, + calcU(imm), + 0, + 0, + Rn, + Rd, + abs(imm) >> 4 & 0xf, + 0, + 1, + abs(imm) & 0xf); +} +inline int ldrsh(int Rd, int Rn, int Rm) +{ + return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 1, Rm); +} +inline int ldrshi(int Rd, int Rn, int imm) +{ + return XFER2I(AL, + 1, + calcU(imm), + 0, + 1, + Rn, + Rd, + abs(imm) >> 4 & 0xf, + 1, + 1, + abs(imm) & 0xf); +} +inline int ldrsb(int Rd, int Rn, int Rm) +{ + return XFER2(AL, 1, 1, 0, 1, Rn, Rd, 1, 0, Rm); +} +inline int ldrsbi(int Rd, int Rn, int imm) +{ + return XFER2I(AL, + 1, + calcU(imm), + 0, + 1, + Rn, + Rd, + abs(imm) >> 4 & 0xf, + 1, + 0, + abs(imm) & 0xf); +} // breakpoint instruction, this really has its own instruction format -inline int bkpt(int16_t immed) { return 0xe1200070 | (((unsigned)immed & 0xffff) >> 4 << 8) | (immed & 0xf); } +inline int bkpt(int16_t immed) +{ + return 0xe1200070 | (((unsigned)immed & 0xffff) >> 4 << 8) | (immed & 0xf); +} // COPROCESSOR INSTRUCTIONS -inline int mcr(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 0, CRn, Rd, coproc, opcode_2, CRm); } -inline int mcrr(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 0, Rn, Rd, coproc, opcode, CRm); } -inline int mrc(int coproc, int opcode_1, int Rd, int CRn, int CRm, int opcode_2=0) { return COREG(AL, opcode_1, 1, CRn, Rd, coproc, opcode_2, CRm); } -inline int mrrc(int coproc, int opcode, int Rd, int Rn, int CRm) { return COREG2(AL, 1, Rn, Rd, coproc, opcode, CRm); } +inline int mcr(int coproc, + int opcode_1, + int Rd, + int CRn, + int CRm, + int opcode_2 = 0) +{ + return COREG(AL, opcode_1, 0, CRn, Rd, coproc, opcode_2, CRm); +} +inline int mcrr(int coproc, int opcode, int Rd, int Rn, int CRm) +{ + return COREG2(AL, 0, Rn, Rd, coproc, opcode, CRm); +} +inline int mrc(int coproc, + int opcode_1, + int Rd, + int CRn, + int CRm, + int opcode_2 = 0) +{ + return COREG(AL, opcode_1, 1, CRn, Rd, coproc, opcode_2, CRm); +} +inline int mrrc(int coproc, int opcode, int Rd, int Rn, int CRm) +{ + return COREG2(AL, 1, Rn, Rd, coproc, opcode, CRm); +} // VFP FLOATING-POINT INSTRUCTIONS -inline int fmuls(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|2, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); } -inline int fadds(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); } -inline int fsubs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|3, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1)|2, Sm>>1); } -inline int fdivs(int Sd, int Sn, int Sm) { return COOP(AL, (Sd&1)<<2|8, Sn>>1, Sd>>1, 10, (Sn&1)<<2|(Sm&1), Sm>>1); } -inline int fmuld(int Dd, int Dn, int Dm) { return COOP(AL, 2, Dn, Dd, 11, 0, Dm); } -inline int faddd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 0, Dm); } -inline int fsubd(int Dd, int Dn, int Dm) { return COOP(AL, 3, Dn, Dd, 11, 2, Dm); } -inline int fdivd(int Dd, int Dn, int Dm) { return COOP(AL, 8, Dn, Dd, 11, 0, Dm); } -inline int fcpys(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 2|(Sm&1), Sm>>1); } -inline int fabss(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0, Sd>>1, 10, 6|(Sm&1), Sm>>1); } -inline int fnegs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 2|(Sm&1), Sm>>1); } -inline int fsqrts(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 1, Sd>>1, 10, 6|(Sm&1), Sm>>1); } -inline int fcmps(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 4, Sd>>1, 10, 2|(Sm&1), Sm>>1); } -inline int fcvtds(int Dd, int Sm) { return COOP(AL, 0xb, 7, Dd, 10, 6|(Sm&1), Sm>>1); } -inline int fsitos(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 8, Sd>>1, 10, 6|(Sm&1), Sm>>1); } -inline int ftosizs(int Sd, int Sm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 10, 6|(Sm&1), Sm>>1); } -inline int fcpyd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 2, Dm); } -inline int fabsd(int Dd, int Dm) { return COOP(AL, 0xb, 0, Dd, 11, 6, Dm); } -inline int fnegd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 2, Dm); } -inline int fsqrtd(int Dd, int Dm) { return COOP(AL, 0xb, 1, Dd, 11, 6, Dm); } +inline int fmuls(int Sd, int Sn, int Sm) +{ + return COOP(AL, + (Sd & 1) << 2 | 2, + Sn >> 1, + Sd >> 1, + 10, + (Sn & 1) << 2 | (Sm & 1), + Sm >> 1); +} +inline int fadds(int Sd, int Sn, int Sm) +{ + return COOP(AL, + (Sd & 1) << 2 | 3, + Sn >> 1, + Sd >> 1, + 10, + (Sn & 1) << 2 | (Sm & 1), + Sm >> 1); +} +inline int fsubs(int Sd, int Sn, int Sm) +{ + return COOP(AL, + (Sd & 1) << 2 | 3, + Sn >> 1, + Sd >> 1, + 10, + (Sn & 1) << 2 | (Sm & 1) | 2, + Sm >> 1); +} +inline int fdivs(int Sd, int Sn, int Sm) +{ + return COOP(AL, + (Sd & 1) << 2 | 8, + Sn >> 1, + Sd >> 1, + 10, + (Sn & 1) << 2 | (Sm & 1), + Sm >> 1); +} +inline int fmuld(int Dd, int Dn, int Dm) +{ + return COOP(AL, 2, Dn, Dd, 11, 0, Dm); +} +inline int faddd(int Dd, int Dn, int Dm) +{ + return COOP(AL, 3, Dn, Dd, 11, 0, Dm); +} +inline int fsubd(int Dd, int Dn, int Dm) +{ + return COOP(AL, 3, Dn, Dd, 11, 2, Dm); +} +inline int fdivd(int Dd, int Dn, int Dm) +{ + return COOP(AL, 8, Dn, Dd, 11, 0, Dm); +} +inline int fcpys(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 0, Sd >> 1, 10, 2 | (Sm & 1), Sm >> 1); +} +inline int fabss(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 0, Sd >> 1, 10, 6 | (Sm & 1), Sm >> 1); +} +inline int fnegs(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 1, Sd >> 1, 10, 2 | (Sm & 1), Sm >> 1); +} +inline int fsqrts(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 1, Sd >> 1, 10, 6 | (Sm & 1), Sm >> 1); +} +inline int fcmps(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 4, Sd >> 1, 10, 2 | (Sm & 1), Sm >> 1); +} +inline int fcvtds(int Dd, int Sm) +{ + return COOP(AL, 0xb, 7, Dd, 10, 6 | (Sm & 1), Sm >> 1); +} +inline int fsitos(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 8, Sd >> 1, 10, 6 | (Sm & 1), Sm >> 1); +} +inline int ftosizs(int Sd, int Sm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 0xd, Sd >> 1, 10, 6 | (Sm & 1), Sm >> 1); +} +inline int fcpyd(int Dd, int Dm) +{ + return COOP(AL, 0xb, 0, Dd, 11, 2, Dm); +} +inline int fabsd(int Dd, int Dm) +{ + return COOP(AL, 0xb, 0, Dd, 11, 6, Dm); +} +inline int fnegd(int Dd, int Dm) +{ + return COOP(AL, 0xb, 1, Dd, 11, 2, Dm); +} +inline int fsqrtd(int Dd, int Dm) +{ + return COOP(AL, 0xb, 1, Dd, 11, 6, Dm); +} // double-precision comparison instructions -inline int fcmpd(int Dd, int Dm) { return COOP(AL, 0xb, 4, Dd, 11, 2, Dm); } +inline int fcmpd(int Dd, int Dm) +{ + return COOP(AL, 0xb, 4, Dd, 11, 2, Dm); +} // double-precision conversion instructions -inline int fcvtsd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 7, Sd>>1, 11, 6, Dm); } -inline int fsitod(int Dd, int Sm) { return COOP(AL, 0xb, 8, Dd, 11, 6|(Sm&1), Sm>>1); } -inline int ftosizd(int Sd, int Dm) { return COOP(AL, 0xb|(Sd&1)<<2, 0xd, Sd>>1, 11, 6, Dm); } +inline int fcvtsd(int Sd, int Dm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 7, Sd >> 1, 11, 6, Dm); +} +inline int fsitod(int Dd, int Sm) +{ + return COOP(AL, 0xb, 8, Dd, 11, 6 | (Sm & 1), Sm >> 1); +} +inline int ftosizd(int Sd, int Dm) +{ + return COOP(AL, 0xb | (Sd & 1) << 2, 0xd, Sd >> 1, 11, 6, Dm); +} // single load/store instructions for both precision types -inline int flds(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 1, Rn, Sd>>1, 10, offset); }; -inline int fldd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 1, Rn, Dd, 11, offset); }; -inline int fsts(int Sd, int Rn, int offset=0) { return COXFER(AL, 1, 1, Sd&1, 0, 0, Rn, Sd>>1, 10, offset); }; -inline int fstd(int Dd, int Rn, int offset=0) { return COXFER(AL, 1, 1, 0, 0, 0, Rn, Dd, 11, offset); }; +inline int flds(int Sd, int Rn, int offset = 0) +{ + return COXFER(AL, 1, 1, Sd & 1, 0, 1, Rn, Sd >> 1, 10, offset); +}; +inline int fldd(int Dd, int Rn, int offset = 0) +{ + return COXFER(AL, 1, 1, 0, 0, 1, Rn, Dd, 11, offset); +}; +inline int fsts(int Sd, int Rn, int offset = 0) +{ + return COXFER(AL, 1, 1, Sd & 1, 0, 0, Rn, Sd >> 1, 10, offset); +}; +inline int fstd(int Dd, int Rn, int offset = 0) +{ + return COXFER(AL, 1, 1, 0, 0, 0, Rn, Dd, 11, offset); +}; // move between GPRs and FPRs -inline int fmsr(int Sn, int Rd) { return mcr(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); } -inline int fmrs(int Rd, int Sn) { return mrc(10, 0, Rd, Sn>>1, 0, (Sn&1)<<2); } +inline int fmsr(int Sn, int Rd) +{ + return mcr(10, 0, Rd, Sn >> 1, 0, (Sn & 1) << 2); +} +inline int fmrs(int Rd, int Sn) +{ + return mrc(10, 0, Rd, Sn >> 1, 0, (Sn & 1) << 2); +} // move to/from VFP system registers -inline int fmrx(int Rd, int reg) { return mrc(10, 7, Rd, reg, 0); } +inline int fmrx(int Rd, int reg) +{ + return mrc(10, 7, Rd, reg, 0); +} // these move around pairs of single-precision registers -inline int fmdrr(int Dm, int Rd, int Rn) { return mcrr(11, 1, Rd, Rn, Dm); } -inline int fmrrd(int Rd, int Rn, int Dm) { return mrrc(11, 1, Rd, Rn, Dm); } +inline int fmdrr(int Dm, int Rd, int Rn) +{ + return mcrr(11, 1, Rd, Rn, Dm); +} +inline int fmrrd(int Rd, int Rn, int Dm) +{ + return mrrc(11, 1, Rd, Rn, Dm); +} // FLAG SETTERS -inline int SETCOND(int ins, int cond) { return ((ins&0x0fffffff) | (cond<<28)); } -inline int SETS(int ins) { return ins | 1<<20; } +inline int SETCOND(int ins, int cond) +{ + return ((ins & 0x0fffffff) | (cond << 28)); +} +inline int SETS(int ins) +{ + return ins | 1 << 20; +} // PSEUDO-INSTRUCTIONS -inline int lsl(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSL); } -inline int lsli(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSL, imm); } -inline int lsr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, LSR); } -inline int lsri(int Rd, int Rm, int imm) { return mov(Rd, Rm, LSR, imm); } -inline int asr(int Rd, int Rm, int Rs) { return movsh(Rd, Rm, Rs, ASR); } -inline int asri(int Rd, int Rm, int imm) { return mov(Rd, Rm, ASR, imm); } -inline int beq(int offset) { return SETCOND(b(offset), EQ); } -inline int bne(int offset) { return SETCOND(b(offset), NE); } -inline int bls(int offset) { return SETCOND(b(offset), LS); } -inline int bhi(int offset) { return SETCOND(b(offset), HI); } -inline int blt(int offset) { return SETCOND(b(offset), LT); } -inline int bgt(int offset) { return SETCOND(b(offset), GT); } -inline int ble(int offset) { return SETCOND(b(offset), LE); } -inline int bge(int offset) { return SETCOND(b(offset), GE); } -inline int blo(int offset) { return SETCOND(b(offset), CC); } -inline int bhs(int offset) { return SETCOND(b(offset), CS); } -inline int bpl(int offset) { return SETCOND(b(offset), PL); } -inline int fmstat() { return fmrx(15, FPSCR); } +inline int lsl(int Rd, int Rm, int Rs) +{ + return movsh(Rd, Rm, Rs, LSL); +} +inline int lsli(int Rd, int Rm, int imm) +{ + return mov(Rd, Rm, LSL, imm); +} +inline int lsr(int Rd, int Rm, int Rs) +{ + return movsh(Rd, Rm, Rs, LSR); +} +inline int lsri(int Rd, int Rm, int imm) +{ + return mov(Rd, Rm, LSR, imm); +} +inline int asr(int Rd, int Rm, int Rs) +{ + return movsh(Rd, Rm, Rs, ASR); +} +inline int asri(int Rd, int Rm, int imm) +{ + return mov(Rd, Rm, ASR, imm); +} +inline int beq(int offset) +{ + return SETCOND(b(offset), EQ); +} +inline int bne(int offset) +{ + return SETCOND(b(offset), NE); +} +inline int bls(int offset) +{ + return SETCOND(b(offset), LS); +} +inline int bhi(int offset) +{ + return SETCOND(b(offset), HI); +} +inline int blt(int offset) +{ + return SETCOND(b(offset), LT); +} +inline int bgt(int offset) +{ + return SETCOND(b(offset), GT); +} +inline int ble(int offset) +{ + return SETCOND(b(offset), LE); +} +inline int bge(int offset) +{ + return SETCOND(b(offset), GE); +} +inline int blo(int offset) +{ + return SETCOND(b(offset), CC); +} +inline int bhs(int offset) +{ + return SETCOND(b(offset), CS); +} +inline int bpl(int offset) +{ + return SETCOND(b(offset), PL); +} +inline int fmstat() +{ + return fmrx(15, FPSCR); +} // todo: make this pretty: -inline int dmb() { return 0xf57ff05f; } +inline int dmb() +{ + return 0xf57ff05f; +} -} // namespace isa +} // namespace isa -inline void emit(Context* con, int code) { con->code.append4(code); } +inline void emit(Context* con, int code) +{ + con->code.append4(code); +} -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_ENCODE_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_ENCODE_H diff --git a/src/codegen/target/arm/fixup.cpp b/src/codegen/target/arm/fixup.cpp index 011cb62988..e1d41b6eb4 100644 --- a/src/codegen/target/arm/fixup.cpp +++ b/src/codegen/target/arm/fixup.cpp @@ -20,65 +20,78 @@ using namespace util; unsigned padding(MyBlock*, unsigned); -OffsetPromise::OffsetPromise(Context* con, MyBlock* block, unsigned offset, bool forTrace): - con(con), block(block), offset(offset), forTrace(forTrace) -{ } +OffsetPromise::OffsetPromise(Context* con, + MyBlock* block, + unsigned offset, + bool forTrace) + : con(con), block(block), offset(offset), forTrace(forTrace) +{ +} -bool OffsetPromise::resolved() { +bool OffsetPromise::resolved() +{ return block->start != static_cast(~0); } -int64_t OffsetPromise::value() { - assert(con, resolved()); +int64_t OffsetPromise::value() +{ + assertT(con, resolved()); unsigned o = offset - block->offset; - return block->start + padding - (block, forTrace ? o - vm::TargetBytesPerWord : o) + o; + return block->start + + padding(block, forTrace ? o - vm::TargetBytesPerWord : o) + o; } - -Promise* offsetPromise(Context* con, bool forTrace) { - return new(con->zone) OffsetPromise(con, con->lastBlock, con->code.length(), forTrace); +Promise* offsetPromise(Context* con, bool forTrace) +{ + return new (con->zone) + OffsetPromise(con, con->lastBlock, con->code.length(), forTrace); } +OffsetListener::OffsetListener(vm::System* s, uint8_t* instruction) + : s(s), instruction(instruction) +{ +} -OffsetListener::OffsetListener(vm::System* s, uint8_t* instruction): - s(s), - instruction(instruction) -{ } - -bool OffsetListener::resolve(int64_t value, void** location) { +bool OffsetListener::resolve(int64_t value, void** location) +{ void* p = updateOffset(s, instruction, value); - if (location) *location = p; + if (location) + *location = p; return false; } +OffsetTask::OffsetTask(Task* next, Promise* promise, Promise* instructionOffset) + : Task(next), promise(promise), instructionOffset(instructionOffset) +{ +} -OffsetTask::OffsetTask(Task* next, Promise* promise, Promise* instructionOffset): - Task(next), - promise(promise), - instructionOffset(instructionOffset) -{ } - -void OffsetTask::run(Context* con) { +void OffsetTask::run(Context* con) +{ if (promise->resolved()) { - updateOffset - (con->s, con->result + instructionOffset->value(), promise->value()); + updateOffset( + con->s, con->result + instructionOffset->value(), promise->value()); } else { new (promise->listen(sizeof(OffsetListener))) - OffsetListener(con->s, con->result + instructionOffset->value()); + OffsetListener(con->s, con->result + instructionOffset->value()); } } -void appendOffsetTask(Context* con, Promise* promise, Promise* instructionOffset) { - con->tasks = new(con->zone) OffsetTask(con->tasks, promise, instructionOffset); +void appendOffsetTask(Context* con, + Promise* promise, + Promise* instructionOffset) +{ + con->tasks = new (con->zone) + OffsetTask(con->tasks, promise, instructionOffset); } -bool bounded(int right, int left, int32_t v) { +bool bounded(int right, int left, int32_t v) +{ return ((v << left) >> left) == v and ((v >> right) << right) == v; } -void* updateOffset(vm::System* s, uint8_t* instruction, int64_t value) { +void* updateOffset(vm::System* s, uint8_t* instruction, int64_t value) +{ // ARM's PC is two words ahead, and branches drop the bottom 2 bits. int32_t v = (reinterpret_cast(value) - (instruction + 8)) >> 2; @@ -92,30 +105,39 @@ void* updateOffset(vm::System* s, uint8_t* instruction, int64_t value) { return instruction + 4; } -ConstantPoolEntry::ConstantPoolEntry(Context* con, Promise* constant, ConstantPoolEntry* next, - Promise* callOffset): - con(con), constant(constant), next(next), callOffset(callOffset), - address(0) -{ } +ConstantPoolEntry::ConstantPoolEntry(Context* con, + Promise* constant, + ConstantPoolEntry* next, + Promise* callOffset) + : con(con), + constant(constant), + next(next), + callOffset(callOffset), + address(0) +{ +} -int64_t ConstantPoolEntry::value() { - assert(con, resolved()); +int64_t ConstantPoolEntry::value() +{ + assertT(con, resolved()); return reinterpret_cast(address); } -bool ConstantPoolEntry::resolved() { +bool ConstantPoolEntry::resolved() +{ return address != 0; } -ConstantPoolListener::ConstantPoolListener(vm::System* s, vm::target_uintptr_t* address, - uint8_t* returnAddress): - s(s), - address(address), - returnAddress(returnAddress) -{ } +ConstantPoolListener::ConstantPoolListener(vm::System* s, + vm::target_uintptr_t* address, + uint8_t* returnAddress) + : s(s), address(address), returnAddress(returnAddress) +{ +} -bool ConstantPoolListener::resolve(int64_t value, void** location) { +bool ConstantPoolListener::resolve(int64_t value, void** location) +{ *address = value; if (location) { *location = returnAddress ? static_cast(returnAddress) : address; @@ -123,32 +145,49 @@ bool ConstantPoolListener::resolve(int64_t value, void** location) { return true; } -PoolOffset::PoolOffset(MyBlock* block, ConstantPoolEntry* entry, unsigned offset): - block(block), entry(entry), next(0), offset(offset) -{ } +PoolOffset::PoolOffset(MyBlock* block, + ConstantPoolEntry* entry, + unsigned offset) + : block(block), entry(entry), next(0), offset(offset) +{ +} -PoolEvent::PoolEvent(PoolOffset* poolOffsetHead, PoolOffset* poolOffsetTail, - unsigned offset): - poolOffsetHead(poolOffsetHead), poolOffsetTail(poolOffsetTail), next(0), - offset(offset) -{ } +PoolEvent::PoolEvent(PoolOffset* poolOffsetHead, + PoolOffset* poolOffsetTail, + unsigned offset) + : poolOffsetHead(poolOffsetHead), + poolOffsetTail(poolOffsetTail), + next(0), + offset(offset) +{ +} -void appendConstantPoolEntry(Context* con, Promise* constant, Promise* callOffset) { +void appendConstantPoolEntry(Context* con, + Promise* constant, + Promise* callOffset) +{ if (constant->resolved()) { // make a copy, since the original might be allocated on the // stack, and we need our copy to live until assembly is complete - constant = new(con->zone) ResolvedPromise(constant->value()); + constant = new (con->zone) ResolvedPromise(constant->value()); } - con->constantPool = new(con->zone) ConstantPoolEntry(con, constant, con->constantPool, callOffset); + con->constantPool = new (con->zone) + ConstantPoolEntry(con, constant, con->constantPool, callOffset); - ++ con->constantPoolCount; + ++con->constantPoolCount; - PoolOffset* o = new(con->zone) PoolOffset(con->lastBlock, con->constantPool, con->code.length() - con->lastBlock->offset); + PoolOffset* o = new (con->zone) + PoolOffset(con->lastBlock, + con->constantPool, + con->code.length() - con->lastBlock->offset); if (DebugPool) { - fprintf(stderr, "add pool offset %p %d to block %p\n", - o, o->offset, con->lastBlock); + fprintf(stderr, + "add pool offset %p %d to block %p\n", + o, + o->offset, + con->lastBlock); } if (con->lastBlock->poolOffsetTail) { @@ -159,10 +198,13 @@ void appendConstantPoolEntry(Context* con, Promise* constant, Promise* callOffse con->lastBlock->poolOffsetTail = o; } -void appendPoolEvent(Context* con, MyBlock* b, unsigned offset, PoolOffset* head, - PoolOffset* tail) +void appendPoolEvent(Context* con, + MyBlock* b, + unsigned offset, + PoolOffset* head, + PoolOffset* tail) { - PoolEvent* e = new(con->zone) PoolEvent(head, tail, offset); + PoolEvent* e = new (con->zone) PoolEvent(head, tail, offset); if (b->poolEventTail) { b->poolEventTail->next = e; @@ -172,6 +214,6 @@ void appendPoolEvent(Context* con, MyBlock* b, unsigned offset, PoolOffset* head b->poolEventTail = e; } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/fixup.h b/src/codegen/target/arm/fixup.h index 43c32c821f..5460295d95 100644 --- a/src/codegen/target/arm/fixup.h +++ b/src/codegen/target/arm/fixup.h @@ -31,19 +31,21 @@ const int32_t PoolOffsetMask = 0xFFF; class Task { public: - Task(Task* next): next(next) { } + Task(Task* next) : next(next) + { + } virtual void run(Context* con) = 0; Task* next; }; -class OffsetPromise: public Promise { +class OffsetPromise : public Promise { public: OffsetPromise(Context* con, MyBlock* block, unsigned offset, bool forTrace); virtual bool resolved(); - + virtual int64_t value(); Context* con; @@ -54,7 +56,7 @@ class OffsetPromise: public Promise { Promise* offsetPromise(Context* con, bool forTrace = false); -class OffsetListener: public Promise::Listener { +class OffsetListener : public Promise::Listener { public: OffsetListener(vm::System* s, uint8_t* instruction); @@ -64,7 +66,7 @@ class OffsetListener: public Promise::Listener { uint8_t* instruction; }; -class OffsetTask: public Task { +class OffsetTask : public Task { public: OffsetTask(Task* next, Promise* promise, Promise* instructionOffset); @@ -74,13 +76,17 @@ class OffsetTask: public Task { Promise* instructionOffset; }; -void appendOffsetTask(Context* con, Promise* promise, Promise* instructionOffset); +void appendOffsetTask(Context* con, + Promise* promise, + Promise* instructionOffset); void* updateOffset(vm::System* s, uint8_t* instruction, int64_t value); -class ConstantPoolEntry: public Promise { +class ConstantPoolEntry : public Promise { public: - ConstantPoolEntry(Context* con, Promise* constant, ConstantPoolEntry* next, + ConstantPoolEntry(Context* con, + Promise* constant, + ConstantPoolEntry* next, Promise* callOffset); virtual int64_t value(); @@ -95,9 +101,10 @@ class ConstantPoolEntry: public Promise { unsigned constantPoolCount; }; -class ConstantPoolListener: public Promise::Listener { +class ConstantPoolListener : public Promise::Listener { public: - ConstantPoolListener(vm::System* s, vm::target_uintptr_t* address, + ConstantPoolListener(vm::System* s, + vm::target_uintptr_t* address, uint8_t* returnAddress); virtual bool resolve(int64_t value, void** location); @@ -119,7 +126,8 @@ class PoolOffset { class PoolEvent { public: - PoolEvent(PoolOffset* poolOffsetHead, PoolOffset* poolOffsetTail, + PoolEvent(PoolOffset* poolOffsetHead, + PoolOffset* poolOffsetTail, unsigned offset); PoolOffset* poolOffsetHead; @@ -128,13 +136,18 @@ class PoolEvent { unsigned offset; }; -void appendConstantPoolEntry(Context* con, Promise* constant, Promise* callOffset); +void appendConstantPoolEntry(Context* con, + Promise* constant, + Promise* callOffset); -void appendPoolEvent(Context* con, MyBlock* b, unsigned offset, PoolOffset* head, - PoolOffset* tail); +void appendPoolEvent(Context* con, + MyBlock* b, + unsigned offset, + PoolOffset* head, + PoolOffset* tail); -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_PROMISE_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_PROMISE_H diff --git a/src/codegen/target/arm/multimethod.cpp b/src/codegen/target/arm/multimethod.cpp index 65c84438f1..0ee2a642bc 100644 --- a/src/codegen/target/arm/multimethod.cpp +++ b/src/codegen/target/arm/multimethod.cpp @@ -21,31 +21,32 @@ namespace arm { using namespace util; unsigned index(ArchitectureContext*, - lir::BinaryOperation operation, - lir::OperandType operand1, - lir::OperandType operand2) + lir::BinaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2) { - return operation - + (lir::BinaryOperationCount * operand1) - + (lir::BinaryOperationCount * lir::OperandTypeCount * operand2); + return operation + (lir::BinaryOperationCount * operand1) + + (lir::BinaryOperationCount * lir::OperandTypeCount * operand2); } unsigned index(ArchitectureContext* con UNUSED, - lir::TernaryOperation operation, - lir::OperandType operand1) + lir::TernaryOperation operation, + lir::OperandType operand1) { - assert(con, not isBranch(operation)); + assertT(con, not isBranch(operation)); return operation + (lir::NonBranchTernaryOperationCount * operand1); } -unsigned branchIndex(ArchitectureContext* con UNUSED, lir::OperandType operand1, - lir::OperandType operand2) +unsigned branchIndex(ArchitectureContext* con UNUSED, + lir::OperandType operand1, + lir::OperandType operand2) { return operand1 + (lir::OperandTypeCount * operand2); } -void populateTables(ArchitectureContext* con) { +void populateTables(ArchitectureContext* con) +{ const lir::OperandType C = lir::ConstantOperand; const lir::OperandType A = lir::AddressOperand; const lir::OperandType R = lir::RegisterOperand; @@ -136,6 +137,6 @@ void populateTables(ArchitectureContext* con) { bro[branchIndex(con, R, M)] = CAST_BRANCH(branchRM); } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/multimethod.h b/src/codegen/target/arm/multimethod.h index 80ce2da6f0..1949bf5486 100644 --- a/src/codegen/target/arm/multimethod.h +++ b/src/codegen/target/arm/multimethod.h @@ -24,21 +24,22 @@ namespace codegen { namespace arm { unsigned index(ArchitectureContext*, - lir::BinaryOperation operation, - lir::OperandType operand1, - lir::OperandType operand2); + lir::BinaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2); unsigned index(ArchitectureContext* con UNUSED, - lir::TernaryOperation operation, - lir::OperandType operand1); + lir::TernaryOperation operation, + lir::OperandType operand1); -unsigned branchIndex(ArchitectureContext* con UNUSED, lir::OperandType operand1, - lir::OperandType operand2); +unsigned branchIndex(ArchitectureContext* con UNUSED, + lir::OperandType operand1, + lir::OperandType operand2); void populateTables(ArchitectureContext* con); -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_MULTIMETHOD_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_MULTIMETHOD_H diff --git a/src/codegen/target/arm/operations.cpp b/src/codegen/target/arm/operations.cpp index 3d23082373..8afe088729 100644 --- a/src/codegen/target/arm/operations.cpp +++ b/src/codegen/target/arm/operations.cpp @@ -22,14 +22,27 @@ namespace arm { using namespace isa; using namespace avian::util; -inline bool isOfWidth(int64_t i, int size) { return static_cast(i) >> size == 0; } +inline bool isOfWidth(int64_t i, int size) +{ + return static_cast(i) >> size == 0; +} -inline unsigned lo8(int64_t i) { return (unsigned)(i&MASK_LO8); } +inline unsigned lo8(int64_t i) +{ + return (unsigned)(i & MASK_LO8); +} -void andC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst); +void andC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst); -void shiftLeftR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) +void shiftLeftR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) { if (size == 8) { int tmp1 = newTemp(con), tmp2 = newTemp(con), tmp3 = newTemp(con); @@ -44,7 +57,9 @@ void shiftLeftR(Context* con, unsigned size, lir::Register* a, lir::Register* b, emit(con, SETCOND(mov(t->high, tmp1), MI)); emit(con, SETCOND(lsl(t->high, b->low, t->high), PL)); emit(con, lsl(t->low, b->low, tmp3)); - freeTemp(con, tmp1); freeTemp(con, tmp2); freeTemp(con, tmp3); + freeTemp(con, tmp1); + freeTemp(con, tmp2); + freeTemp(con, tmp3); } else { int tmp = newTemp(con); ResolvedPromise maskPromise(0x1F); @@ -56,12 +71,19 @@ void shiftLeftR(Context* con, unsigned size, lir::Register* a, lir::Register* b, } } -void moveRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize, lir::Register* dst); +void moveRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize, + lir::Register* dst); -void shiftLeftC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t) +void shiftLeftC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); if (getValue(a) & 0x1F) { emit(con, lsli(t->low, b->low, getValue(a) & 0x1F)); } else { @@ -69,7 +91,11 @@ void shiftLeftC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Regis } } -void shiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) +void shiftRightR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) { if (size == 8) { int tmp1 = newTemp(con), tmp2 = newTemp(con), tmp3 = newTemp(con); @@ -84,7 +110,9 @@ void shiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b emit(con, SETCOND(mov(t->low, tmp1), MI)); emit(con, SETCOND(asr(t->low, b->high, t->low), PL)); emit(con, asr(t->high, b->high, tmp3)); - freeTemp(con, tmp1); freeTemp(con, tmp2); freeTemp(con, tmp3); + freeTemp(con, tmp1); + freeTemp(con, tmp2); + freeTemp(con, tmp3); } else { int tmp = newTemp(con); ResolvedPromise maskPromise(0x1F); @@ -96,9 +124,13 @@ void shiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b } } -void shiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t) +void shiftRightC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); if (getValue(a) & 0x1F) { emit(con, asri(t->low, b->low, getValue(a) & 0x1F)); } else { @@ -106,7 +138,11 @@ void shiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Regi } } -void unsignedShiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) +void unsignedShiftRightR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) { int tmpShift = newTemp(con); ResolvedPromise maskPromise(size == 8 ? 0x3F : 0x1F); @@ -123,14 +159,19 @@ void unsignedShiftRightR(Context* con, unsigned size, lir::Register* a, lir::Reg emit(con, lsr(tmpLo, b->high, tmpHi)); emit(con, orr(t->low, t->low, tmpLo)); emit(con, lsr(t->high, b->high, tmpShift)); - freeTemp(con, tmpHi); freeTemp(con, tmpLo); + freeTemp(con, tmpHi); + freeTemp(con, tmpLo); } freeTemp(con, tmpShift); } -void unsignedShiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t) +void unsignedShiftRightC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); if (getValue(a) & 0x1F) { emit(con, lsri(t->low, b->low, getValue(a) & 0x1F)); } else { @@ -138,14 +179,12 @@ void unsignedShiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, l } } -bool -needJump(MyBlock* b) +bool needJump(MyBlock* b) { return b->next or b->size != (b->size & PoolOffsetMask); } -unsigned -padding(MyBlock* b, unsigned offset) +unsigned padding(MyBlock* b, unsigned offset) { unsigned total = 0; for (PoolEvent* e = b->poolEventHead; e; e = e->next) { @@ -181,37 +220,51 @@ void resolve(MyBlock* b) if (b->next == 0 or b->next->poolEventHead) { append = true; } else { - int32_t v = (b->start + b->size + b->next->size + vm::TargetBytesPerWord - 8) - - (con->poolOffsetHead->offset + con->poolOffsetHead->block->start); + int32_t v + = (b->start + b->size + b->next->size + vm::TargetBytesPerWord - 8) + - (con->poolOffsetHead->offset + con->poolOffsetHead->block->start); append = (v != (v & PoolOffsetMask)); if (DebugPool) { fprintf(stderr, "current %p %d %d next %p %d %d\n", - b, b->start, b->size, b->next, b->start + b->size, + b, + b->start, + b->size, + b->next, + b->start + b->size, b->next->size); fprintf(stderr, "offset %p %d is of distance %d to next block; append? %d\n", - con->poolOffsetHead, con->poolOffsetHead->offset, v, append); + con->poolOffsetHead, + con->poolOffsetHead->offset, + v, + append); } } if (append) { #ifndef NDEBUG - int32_t v = (b->start + b->size - 8) - - (con->poolOffsetHead->offset + con->poolOffsetHead->block->start); - - expect(con, v == (v & PoolOffsetMask)); -#endif // not NDEBUG + int32_t v + = (b->start + b->size - 8) + - (con->poolOffsetHead->offset + con->poolOffsetHead->block->start); - appendPoolEvent(con, b, b->size, con->poolOffsetHead, con->poolOffsetTail); + expect(con, v == (v & PoolOffsetMask)); +#endif // not NDEBUG + + appendPoolEvent( + con, b, b->size, con->poolOffsetHead, con->poolOffsetTail); if (DebugPool) { for (PoolOffset* o = con->poolOffsetHead; o; o = o->next) { fprintf(stderr, "include %p %d in pool event %p at offset %d in block %p\n", - o, o->offset, b->poolEventTail, b->size, b); + o, + o->offset, + b->poolEventTail, + b->size, + b); } } @@ -223,15 +276,18 @@ void resolve(MyBlock* b) void jumpR(Context* con, unsigned size UNUSED, lir::Register* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); emit(con, bx(target->low)); } -void swapRR(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void swapRR(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { - assert(con, aSize == vm::TargetBytesPerWord); - assert(con, bSize == vm::TargetBytesPerWord); + assertT(con, aSize == vm::TargetBytesPerWord); + assertT(con, bSize == vm::TargetBytesPerWord); lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); moveRR(con, aSize, a, bSize, &tmp); @@ -240,23 +296,32 @@ void swapRR(Context* con, unsigned aSize, lir::Register* a, con->client->releaseTemporary(tmp.low); } -void moveRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize, lir::Register* dst) +void moveRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize, + lir::Register* dst) { bool srcIsFpr = isFpr(src); bool dstIsFpr = isFpr(dst); - if (srcIsFpr || dstIsFpr) { // FPR(s) involved - assert(con, srcSize == dstSize); + if (srcIsFpr || dstIsFpr) { // FPR(s) involved + assertT(con, srcSize == dstSize); const bool dprec = srcSize == 8; - if (srcIsFpr && dstIsFpr) { // FPR to FPR - if (dprec) emit(con, fcpyd(fpr64(dst), fpr64(src))); // double - else emit(con, fcpys(fpr32(dst), fpr32(src))); // single - } else if (srcIsFpr) { // FPR to GPR - if (dprec) emit(con, fmrrd(dst->low, dst->high, fpr64(src))); - else emit(con, fmrs(dst->low, fpr32(src))); - } else { // GPR to FPR - if (dprec) emit(con, fmdrr(fpr64(dst->low), src->low, src->high)); - else emit(con, fmsr(fpr32(dst), src->low)); + if (srcIsFpr && dstIsFpr) { // FPR to FPR + if (dprec) + emit(con, fcpyd(fpr64(dst), fpr64(src))); // double + else + emit(con, fcpys(fpr32(dst), fpr32(src))); // single + } else if (srcIsFpr) { // FPR to GPR + if (dprec) + emit(con, fmrrd(dst->low, dst->high, fpr64(src))); + else + emit(con, fmrs(dst->low, fpr32(src))); + } else { // GPR to FPR + if (dprec) + emit(con, fmdrr(fpr64(dst->low), src->low, src->high)); + else + emit(con, fmsr(fpr32(dst), src->low)); } return; } @@ -297,12 +362,16 @@ void moveRR(Context* con, unsigned srcSize, lir::Register* src, } break; - default: abort(con); + default: + abort(con); } } -void moveZRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned, lir::Register* dst) +void moveZRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned, + lir::Register* dst) { switch (srcSize) { case 2: @@ -310,46 +379,60 @@ void moveZRR(Context* con, unsigned srcSize, lir::Register* src, emit(con, lsri(dst->low, dst->low, 16)); break; - default: abort(con); + default: + abort(con); } } -void moveCR(Context* con, unsigned size, lir::Constant* src, - unsigned, lir::Register* dst); +void moveCR(Context* con, + unsigned size, + lir::Constant* src, + unsigned, + lir::Register* dst); -void moveCR2(Context* con, unsigned size, lir::Constant* src, - lir::Register* dst, Promise* callOffset) +void moveCR2(Context* con, + unsigned size, + lir::Constant* src, + lir::Register* dst, + Promise* callOffset) { - if (isFpr(dst)) { // floating-point - lir::Register tmp = size > 4 ? makeTemp64(con) : - makeTemp(con); + if (isFpr(dst)) { // floating-point + lir::Register tmp = size > 4 ? makeTemp64(con) : makeTemp(con); moveCR(con, size, src, size, &tmp); moveRR(con, size, &tmp, size, dst); freeTemp(con, tmp); - } else if (size > 4) { + } else if (size > 4) { uint64_t value = (uint64_t)src->value->value(); ResolvedPromise loBits(value & MASK_LO32); lir::Constant srcLo(&loBits); - ResolvedPromise hiBits(value >> 32); + ResolvedPromise hiBits(value >> 32); lir::Constant srcHi(&hiBits); lir::Register dstHi(dst->high); moveCR(con, 4, &srcLo, 4, dst); moveCR(con, 4, &srcHi, 4, &dstHi); } else if (src->value->resolved() and isOfWidth(getValue(src), 8)) { - emit(con, movi(dst->low, lo8(getValue(src)))); // fits in immediate + emit(con, movi(dst->low, lo8(getValue(src)))); // fits in immediate } else { appendConstantPoolEntry(con, src->value, callOffset); - emit(con, ldri(dst->low, ProgramCounter, 0)); // load 32 bits + emit(con, ldri(dst->low, ProgramCounter, 0)); // load 32 bits } } -void moveCR(Context* con, unsigned size, lir::Constant* src, - unsigned, lir::Register* dst) +void moveCR(Context* con, + unsigned size, + lir::Constant* src, + unsigned, + lir::Register* dst) { moveCR2(con, size, src, dst, 0); } -void addR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void addR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { emit(con, SETS(add(t->low, a->low, b->low))); emit(con, adc(t->high, a->high, b->high)); @@ -358,7 +441,12 @@ void addR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir:: } } -void subR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void subR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { emit(con, SETS(rsb(t->low, a->low, b->low))); emit(con, rsc(t->high, a->high, b->high)); @@ -367,10 +455,13 @@ void subR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir:: } } -void addC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst) +void addC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); int32_t v = a->value->value(); if (v) { @@ -387,10 +478,13 @@ void addC(Context* con, unsigned size, lir::Constant* a, } } -void subC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst) +void subC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); int32_t v = a->value->value(); if (v) { @@ -407,11 +501,18 @@ void subC(Context* con, unsigned size, lir::Constant* a, } } -void multiplyR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void multiplyR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { bool useTemporaries = b->low == t->low; - int tmpLow = useTemporaries ? con->client->acquireTemporary(GPR_MASK) : t->low; - int tmpHigh = useTemporaries ? con->client->acquireTemporary(GPR_MASK) : t->high; + int tmpLow = useTemporaries ? con->client->acquireTemporary(GPR_MASK) + : t->low; + int tmpHigh = useTemporaries ? con->client->acquireTemporary(GPR_MASK) + : t->high; emit(con, umull(tmpLow, tmpHigh, a->low, b->low)); emit(con, mla(tmpHigh, a->low, b->high, tmpHigh)); @@ -428,7 +529,12 @@ void multiplyR(Context* con, unsigned size, lir::Register* a, lir::Register* b, } } -void floatAbsoluteRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b) { +void floatAbsoluteRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b) +{ if (size == 8) { emit(con, fabsd(fpr64(b), fpr64(a))); } else { @@ -436,7 +542,12 @@ void floatAbsoluteRR(Context* con, unsigned size, lir::Register* a, unsigned, li } } -void floatNegateRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b) { +void floatNegateRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b) +{ if (size == 8) { emit(con, fnegd(fpr64(b), fpr64(a))); } else { @@ -444,7 +555,12 @@ void floatNegateRR(Context* con, unsigned size, lir::Register* a, unsigned, lir: } } -void float2FloatRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b) { +void float2FloatRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b) +{ if (size == 8) { emit(con, fcvtsd(fpr32(b), fpr64(a))); } else { @@ -452,28 +568,43 @@ void float2FloatRR(Context* con, unsigned size, lir::Register* a, unsigned, lir: } } -void float2IntRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b) { +void float2IntRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b) +{ int tmp = newTemp(con, FPR_MASK); int ftmp = fpr32(tmp); - if (size == 8) { // double to int + if (size == 8) { // double to int emit(con, ftosizd(ftmp, fpr64(a))); - } else { // float to int + } else { // float to int emit(con, ftosizs(ftmp, fpr32(a))); - } // else thunked + } // else thunked emit(con, fmrs(b->low, ftmp)); freeTemp(con, tmp); } -void int2FloatRR(Context* con, unsigned, lir::Register* a, unsigned size, lir::Register* b) { +void int2FloatRR(Context* con, + unsigned, + lir::Register* a, + unsigned size, + lir::Register* b) +{ emit(con, fmsr(fpr32(b), a->low)); - if (size == 8) { // int to double + if (size == 8) { // int to double emit(con, fsitod(fpr64(b), fpr32(b))); - } else { // int to float + } else { // int to float emit(con, fsitos(fpr32(b), fpr32(b))); - } // else thunked + } // else thunked } -void floatSqrtRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b) { +void floatSqrtRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b) +{ if (size == 8) { emit(con, fsqrtd(fpr64(b), fpr64(a))); } else { @@ -481,7 +612,12 @@ void floatSqrtRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::R } } -void floatAddR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void floatAddR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { emit(con, faddd(fpr64(t), fpr64(a), fpr64(b))); } else { @@ -489,7 +625,12 @@ void floatAddR(Context* con, unsigned size, lir::Register* a, lir::Register* b, } } -void floatSubtractR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void floatSubtractR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { emit(con, fsubd(fpr64(t), fpr64(b), fpr64(a))); } else { @@ -497,7 +638,12 @@ void floatSubtractR(Context* con, unsigned size, lir::Register* a, lir::Register } } -void floatMultiplyR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { +void floatMultiplyR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ if (size == 8) { emit(con, fmuld(fpr64(t), fpr64(a), fpr64(b))); } else { @@ -505,21 +651,30 @@ void floatMultiplyR(Context* con, unsigned size, lir::Register* a, lir::Register } } -void floatDivideR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t) { - if (size == 8) { +void floatDivideR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t) +{ + if (size == 8) { emit(con, fdivd(fpr64(t), fpr64(b), fpr64(a))); } else { emit(con, fdivs(fpr32(t), fpr32(b), fpr32(a))); } } -int normalize(Context* con, int offset, int index, unsigned scale, - bool* preserveIndex, bool* release) +int normalize(Context* con, + int offset, + int index, + unsigned scale, + bool* preserveIndex, + bool* release) { if (offset != 0 or scale != 1) { - lir::Register normalizedIndex - (*preserveIndex ? con->client->acquireTemporary(GPR_MASK) : index); - + lir::Register normalizedIndex( + *preserveIndex ? con->client->acquireTemporary(GPR_MASK) : index); + if (*preserveIndex) { *release = true; *preserveIndex = false; @@ -534,9 +689,12 @@ int normalize(Context* con, int offset, int index, unsigned scale, ResolvedPromise scalePromise(log(scale)); lir::Constant scaleConstant(&scalePromise); - - shiftLeftC(con, vm::TargetBytesPerWord, &scaleConstant, - &unscaledIndex, &normalizedIndex); + + shiftLeftC(con, + vm::TargetBytesPerWord, + &scaleConstant, + &unscaledIndex, + &normalizedIndex); scaled = normalizedIndex.low; } else { @@ -550,8 +708,16 @@ int normalize(Context* con, int offset, int index, unsigned scale, lir::Constant offsetConstant(&offsetPromise); lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); - moveCR(con, vm::TargetBytesPerWord, &offsetConstant, vm::TargetBytesPerWord, &tmp); - addR(con, vm::TargetBytesPerWord, &tmp, &untranslatedIndex, &normalizedIndex); + moveCR(con, + vm::TargetBytesPerWord, + &offsetConstant, + vm::TargetBytesPerWord, + &tmp); + addR(con, + vm::TargetBytesPerWord, + &tmp, + &untranslatedIndex, + &normalizedIndex); con->client->releaseTemporary(tmp.low); } @@ -562,15 +728,21 @@ int normalize(Context* con, int offset, int index, unsigned scale, } } -void store(Context* con, unsigned size, lir::Register* src, - int base, int offset, int index, unsigned scale, bool preserveIndex) +void store(Context* con, + unsigned size, + lir::Register* src, + int base, + int offset, + int index, + unsigned scale, + bool preserveIndex) { if (index != lir::NoRegister) { bool release; - int normalized = normalize - (con, offset, index, scale, &preserveIndex, &release); + int normalized + = normalize(con, offset, index, scale, &preserveIndex, &release); - if (!isFpr(src)) { // GPR store + if (!isFpr(src)) { // GPR store switch (size) { case 1: emit(con, strb(src->low, base, normalized)); @@ -584,33 +756,34 @@ void store(Context* con, unsigned size, lir::Register* src, emit(con, str(src->low, base, normalized)); break; - case 8: { // split into 2 32-bit stores + case 8: { // split into 2 32-bit stores lir::Register srcHigh(src->high); store(con, 4, &srcHigh, base, 0, normalized, 1, preserveIndex); store(con, 4, src, base, 4, normalized, 1, preserveIndex); } break; - default: abort(con); + default: + abort(con); } - } else { // FPR store - lir::Register base_(base), - normalized_(normalized), - absAddr = makeTemp(con); + } else { // FPR store + lir::Register base_(base), normalized_(normalized), + absAddr = makeTemp(con); // FPR stores have only bases, so we must add the index addR(con, vm::TargetBytesPerWord, &base_, &normalized_, &absAddr); // double-precision - if (size == 8) emit(con, fstd(fpr64(src), absAddr.low)); + if (size == 8) + emit(con, fstd(fpr64(src), absAddr.low)); // single-precision - else emit(con, fsts(fpr32(src), absAddr.low)); + else + emit(con, fsts(fpr32(src), absAddr.low)); freeTemp(con, absAddr); } - if (release) con->client->releaseTemporary(normalized); - } else if (size == 8 - or abs(offset) == (abs(offset) & 0xFF) - or (size != 2 and abs(offset) == (abs(offset) & 0xFFF))) - { - if (!isFpr(src)) { // GPR store + if (release) + con->client->releaseTemporary(normalized); + } else if (size == 8 or abs(offset) == (abs(offset) & 0xFF) + or (size != 2 and abs(offset) == (abs(offset) & 0xFFF))) { + if (!isFpr(src)) { // GPR store switch (size) { case 1: emit(con, strbi(src->low, base, offset)); @@ -624,51 +797,68 @@ void store(Context* con, unsigned size, lir::Register* src, emit(con, stri(src->low, base, offset)); break; - case 8: { // split into 2 32-bit stores + case 8: { // split into 2 32-bit stores lir::Register srcHigh(src->high); store(con, 4, &srcHigh, base, offset, lir::NoRegister, 1, false); store(con, 4, src, base, offset + 4, lir::NoRegister, 1, false); } break; - default: abort(con); + default: + abort(con); } - } else { // FPR store + } else { // FPR store // double-precision - if (size == 8) emit(con, fstd(fpr64(src), base, offset)); + if (size == 8) + emit(con, fstd(fpr64(src), base, offset)); // single-precision - else emit(con, fsts(fpr32(src), base, offset)); + else + emit(con, fsts(fpr32(src), base, offset)); } } else { lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); ResolvedPromise offsetPromise(offset); lir::Constant offsetConstant(&offsetPromise); - moveCR(con, vm::TargetBytesPerWord, &offsetConstant, - vm::TargetBytesPerWord, &tmp); - + moveCR(con, + vm::TargetBytesPerWord, + &offsetConstant, + vm::TargetBytesPerWord, + &tmp); + store(con, size, src, base, 0, tmp.low, 1, false); con->client->releaseTemporary(tmp.low); } } -void moveRM(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize UNUSED, lir::Memory* dst) +void moveRM(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize UNUSED, + lir::Memory* dst) { - assert(con, srcSize == dstSize); + assertT(con, srcSize == dstSize); - store(con, srcSize, src, dst->base, dst->offset, dst->index, dst->scale, true); + store( + con, srcSize, src, dst->base, dst->offset, dst->index, dst->scale, true); } -void load(Context* con, unsigned srcSize, int base, int offset, int index, - unsigned scale, unsigned dstSize, lir::Register* dst, - bool preserveIndex, bool signExtend) +void load(Context* con, + unsigned srcSize, + int base, + int offset, + int index, + unsigned scale, + unsigned dstSize, + lir::Register* dst, + bool preserveIndex, + bool signExtend) { if (index != lir::NoRegister) { bool release; - int normalized = normalize - (con, offset, index, scale, &preserveIndex, &release); + int normalized + = normalize(con, offset, index, scale, &preserveIndex, &release); - if (!isFpr(dst)) { // GPR load + if (!isFpr(dst)) { // GPR load switch (srcSize) { case 1: if (signExtend) { @@ -689,43 +879,50 @@ void load(Context* con, unsigned srcSize, int base, int offset, int index, case 4: case 8: { if (srcSize == 4 and dstSize == 8) { - load(con, 4, base, 0, normalized, 1, 4, dst, preserveIndex, - false); + load(con, 4, base, 0, normalized, 1, 4, dst, preserveIndex, false); moveRR(con, 4, dst, 8, dst); } else if (srcSize == 8 and dstSize == 8) { lir::Register dstHigh(dst->high); - load(con, 4, base, 0, normalized, 1, 4, &dstHigh, - preserveIndex, false); - load(con, 4, base, 4, normalized, 1, 4, dst, preserveIndex, + load(con, + 4, + base, + 0, + normalized, + 1, + 4, + &dstHigh, + preserveIndex, false); + load(con, 4, base, 4, normalized, 1, 4, dst, preserveIndex, false); } else { emit(con, ldr(dst->low, base, normalized)); } } break; - default: abort(con); + default: + abort(con); } - } else { // FPR load - lir::Register base_(base), - normalized_(normalized), - absAddr = makeTemp(con); + } else { // FPR load + lir::Register base_(base), normalized_(normalized), + absAddr = makeTemp(con); // VFP loads only have bases, so we must add the index addR(con, vm::TargetBytesPerWord, &base_, &normalized_, &absAddr); // double-precision - if (srcSize == 8) emit(con, fldd(fpr64(dst), absAddr.low)); + if (srcSize == 8) + emit(con, fldd(fpr64(dst), absAddr.low)); // single-precision - else emit(con, flds(fpr32(dst), absAddr.low)); + else + emit(con, flds(fpr32(dst), absAddr.low)); freeTemp(con, absAddr); } - if (release) con->client->releaseTemporary(normalized); + if (release) + con->client->releaseTemporary(normalized); } else if ((srcSize == 8 and dstSize == 8) or abs(offset) == (abs(offset) & 0xFF) - or (srcSize != 2 - and (srcSize != 1 or not signExtend) - and abs(offset) == (abs(offset) & 0xFFF))) - { - if (!isFpr(dst)) { // GPR load + or (srcSize != 2 and (srcSize != 1 or not signExtend) + and abs(offset) == (abs(offset) & 0xFFF))) { + if (!isFpr(dst)) { // GPR load switch (srcSize) { case 1: if (signExtend) { @@ -750,60 +947,110 @@ void load(Context* con, unsigned srcSize, int base, int offset, int index, case 8: { if (dstSize == 8) { lir::Register dstHigh(dst->high); - load(con, 4, base, offset, lir::NoRegister, 1, 4, &dstHigh, false, + load(con, + 4, + base, + offset, + lir::NoRegister, + 1, + 4, + &dstHigh, + false, false); - load(con, 4, base, offset + 4, lir::NoRegister, 1, 4, dst, false, + load(con, + 4, + base, + offset + 4, + lir::NoRegister, + 1, + 4, + dst, + false, false); } else { emit(con, ldri(dst->low, base, offset)); } } break; - default: abort(con); + default: + abort(con); } - } else { // FPR load + } else { // FPR load // double-precision - if (srcSize == 8) emit(con, fldd(fpr64(dst), base, offset)); + if (srcSize == 8) + emit(con, fldd(fpr64(dst), base, offset)); // single-precision - else emit(con, flds(fpr32(dst), base, offset)); + else + emit(con, flds(fpr32(dst), base, offset)); } } else { lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); ResolvedPromise offsetPromise(offset); lir::Constant offsetConstant(&offsetPromise); - moveCR(con, vm::TargetBytesPerWord, &offsetConstant, vm::TargetBytesPerWord, + moveCR(con, + vm::TargetBytesPerWord, + &offsetConstant, + vm::TargetBytesPerWord, &tmp); - - load(con, srcSize, base, 0, tmp.low, 1, dstSize, dst, false, - signExtend); + + load(con, srcSize, base, 0, tmp.low, 1, dstSize, dst, false, signExtend); con->client->releaseTemporary(tmp.low); } } -void moveMR(Context* con, unsigned srcSize, lir::Memory* src, - unsigned dstSize, lir::Register* dst) +void moveMR(Context* con, + unsigned srcSize, + lir::Memory* src, + unsigned dstSize, + lir::Register* dst) { - load(con, srcSize, src->base, src->offset, src->index, src->scale, - dstSize, dst, true, true); + load(con, + srcSize, + src->base, + src->offset, + src->index, + src->scale, + dstSize, + dst, + true, + true); } -void moveZMR(Context* con, unsigned srcSize, lir::Memory* src, - unsigned dstSize, lir::Register* dst) +void moveZMR(Context* con, + unsigned srcSize, + lir::Memory* src, + unsigned dstSize, + lir::Register* dst) { - load(con, srcSize, src->base, src->offset, src->index, src->scale, - dstSize, dst, true, false); + load(con, + srcSize, + src->base, + src->offset, + src->index, + src->scale, + dstSize, + dst, + true, + false); } -void andR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst) +void andR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst) { - if (size == 8) emit(con, and_(dst->high, a->high, b->high)); + if (size == 8) + emit(con, and_(dst->high, a->high, b->high)); emit(con, and_(dst->low, a->low, b->low)); } -void andC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst) +void andC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst) { int64_t v = a->value->value(); @@ -838,7 +1085,7 @@ void andC(Context* con, unsigned size, lir::Constant* a, moveCR(con, 4, a, 4, &tmp); andR(con, 4, b, &tmp, dst); - + if (useTemporary) { con->client->releaseTemporary(tmp.low); } @@ -849,24 +1096,35 @@ void andC(Context* con, unsigned size, lir::Constant* a, } } -void orR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst) +void orR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst) { - if (size == 8) emit(con, orr(dst->high, a->high, b->high)); + if (size == 8) + emit(con, orr(dst->high, a->high, b->high)); emit(con, orr(dst->low, a->low, b->low)); } -void xorR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst) +void xorR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst) { - if (size == 8) emit(con, eor(dst->high, a->high, b->high)); + if (size == 8) + emit(con, eor(dst->high, a->high, b->high)); emit(con, eor(dst->low, a->low, b->low)); } -void moveAR2(Context* con, unsigned srcSize, lir::Address* src, - unsigned dstSize, lir::Register* dst) +void moveAR2(Context* con, + unsigned srcSize, + lir::Address* src, + unsigned dstSize, + lir::Register* dst) { - assert(con, srcSize == 4 and dstSize == 4); + assertT(con, srcSize == 4 and dstSize == 4); lir::Constant constant(src->address); moveCR(con, srcSize, &constant, dstSize, dst); @@ -875,36 +1133,46 @@ void moveAR2(Context* con, unsigned srcSize, lir::Address* src, moveMR(con, dstSize, &memory, dstSize, dst); } -void moveAR(Context* con, unsigned srcSize, lir::Address* src, - unsigned dstSize, lir::Register* dst) +void moveAR(Context* con, + unsigned srcSize, + lir::Address* src, + unsigned dstSize, + lir::Register* dst) { moveAR2(con, srcSize, src, dstSize, dst); } -void compareRR(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void compareRR(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(con, !(isFpr(a) ^ isFpr(b))); // regs must be of the same type + assertT(con, !(isFpr(a) ^ isFpr(b))); // regs must be of the same type - if (!isFpr(a)) { // GPR compare - assert(con, aSize == 4 && bSize == 4); - /**///assert(con, b->low != a->low); + if (!isFpr(a)) { // GPR compare + assertT(con, aSize == 4 && bSize == 4); + /**/ // assertT(con, b->low != a->low); emit(con, cmp(b->low, a->low)); - } else { // FPR compare - assert(con, aSize == bSize); - if (aSize == 8) emit(con, fcmpd(fpr64(b), fpr64(a))); // double - else emit(con, fcmps(fpr32(b), fpr32(a))); // single + } else { // FPR compare + assertT(con, aSize == bSize); + if (aSize == 8) + emit(con, fcmpd(fpr64(b), fpr64(a))); // double + else + emit(con, fcmps(fpr32(b), fpr32(a))); // single emit(con, fmstat()); } } -void compareCR(Context* con, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void compareCR(Context* con, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(con, aSize == 4 and bSize == 4); + assertT(con, aSize == 4 and bSize == 4); - if (!isFpr(b) && a->value->resolved() && - isOfWidth(a->value->value(), 8)) { + if (!isFpr(b) && a->value->resolved() && isOfWidth(a->value->value(), 8)) { emit(con, cmpi(b->low, a->value->value())); } else { lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); @@ -914,10 +1182,13 @@ void compareCR(Context* con, unsigned aSize, lir::Constant* a, } } -void compareCM(Context* con, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Memory* b) +void compareCM(Context* con, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Memory* b) { - assert(con, aSize == 4 and bSize == 4); + assertT(con, aSize == 4 and bSize == 4); lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); moveMR(con, bSize, b, bSize, &tmp); @@ -925,10 +1196,13 @@ void compareCM(Context* con, unsigned aSize, lir::Constant* a, con->client->releaseTemporary(tmp.low); } -void compareRM(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Memory* b) +void compareRM(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Memory* b) { - assert(con, aSize == 4 and bSize == 4); + assertT(con, aSize == 4 and bSize == 4); lir::Register tmp(con->client->acquireTemporary(GPR_MASK)); moveMR(con, bSize, b, bSize, &tmp); @@ -936,8 +1210,7 @@ void compareRM(Context* con, unsigned aSize, lir::Register* a, con->client->releaseTemporary(tmp.low); } -int32_t -branch(Context* con, lir::TernaryOperation op) +int32_t branch(Context* con, lir::TernaryOperation op) { switch (op) { case lir::JumpIfEqual: @@ -971,7 +1244,7 @@ branch(Context* con, lir::TernaryOperation op) case lir::JumpIfFloatGreaterOrEqualOrUnordered: return bpl(0); - + default: abort(con); } @@ -988,16 +1261,20 @@ void branch(Context* con, lir::TernaryOperation op, lir::Constant* target) conditional(con, branch(con, op), target); } -void branchLong(Context* con, lir::TernaryOperation op, lir::Operand* al, - lir::Operand* ah, lir::Operand* bl, - lir::Operand* bh, lir::Constant* target, - BinaryOperationType compareSigned, - BinaryOperationType compareUnsigned) +void branchLong(Context* con, + lir::TernaryOperation op, + lir::Operand* al, + lir::Operand* ah, + lir::Operand* bl, + lir::Operand* bh, + lir::Constant* target, + BinaryOperationType compareSigned, + BinaryOperationType compareUnsigned) { compareSigned(con, 4, ah, 4, bh); unsigned next = 0; - + switch (op) { case lir::JumpIfEqual: case lir::JumpIfFloatEqual: @@ -1072,27 +1349,33 @@ void branchLong(Context* con, lir::TernaryOperation op, lir::Operand* al, } } -void branchRR(Context* con, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Register* b, - lir::Constant* target) +void branchRR(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Constant* target) { if (!isFpr(a) && size > vm::TargetBytesPerWord) { lir::Register ah(a->high); lir::Register bh(b->high); - branchLong(con, op, a, &ah, b, &bh, target, CAST2(compareRR), - CAST2(compareRR)); + branchLong( + con, op, a, &ah, b, &bh, target, CAST2(compareRR), CAST2(compareRR)); } else { compareRR(con, size, a, size, b); branch(con, op, target); } } -void branchCR(Context* con, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Register* b, - lir::Constant* target) +void branchCR(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Constant* target) { - assert(con, !isFloatBranch(op)); + assertT(con, !isFloatBranch(op)); if (size > vm::TargetBytesPerWord) { int64_t v = a->value->value(); @@ -1105,55 +1388,63 @@ void branchCR(Context* con, lir::TernaryOperation op, unsigned size, lir::Register bh(b->high); - branchLong(con, op, &al, &ah, b, &bh, target, CAST2(compareCR), - CAST2(compareCR)); + branchLong( + con, op, &al, &ah, b, &bh, target, CAST2(compareCR), CAST2(compareCR)); } else { compareCR(con, size, a, size, b); branch(con, op, target); } } -void branchRM(Context* con, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Memory* b, - lir::Constant* target) +void branchRM(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Memory* b, + lir::Constant* target) { - assert(con, !isFloatBranch(op)); - assert(con, size <= vm::TargetBytesPerWord); + assertT(con, !isFloatBranch(op)); + assertT(con, size <= vm::TargetBytesPerWord); compareRM(con, size, a, size, b); branch(con, op, target); } -void branchCM(Context* con, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Memory* b, - lir::Constant* target) +void branchCM(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Memory* b, + lir::Constant* target) { - assert(con, !isFloatBranch(op)); - assert(con, size <= vm::TargetBytesPerWord); + assertT(con, !isFloatBranch(op)); + assertT(con, size <= vm::TargetBytesPerWord); compareCM(con, size, a, size, b); branch(con, op, target); } -ShiftMaskPromise* -shiftMaskPromise(Context* con, Promise* base, unsigned shift, int64_t mask) +ShiftMaskPromise* shiftMaskPromise(Context* con, + Promise* base, + unsigned shift, + int64_t mask) { - return new(con->zone) ShiftMaskPromise(base, shift, mask); + return new (con->zone) ShiftMaskPromise(base, shift, mask); } -void moveCM(Context* con, unsigned srcSize, lir::Constant* src, - unsigned dstSize, lir::Memory* dst) +void moveCM(Context* con, + unsigned srcSize, + lir::Constant* src, + unsigned dstSize, + lir::Memory* dst) { switch (dstSize) { case 8: { - lir::Constant srcHigh - (shiftMaskPromise(con, src->value, 32, 0xFFFFFFFF)); - lir::Constant srcLow - (shiftMaskPromise(con, src->value, 0, 0xFFFFFFFF)); - - lir::Memory dstLow - (dst->base, dst->offset + 4, dst->index, dst->scale); - + lir::Constant srcHigh(shiftMaskPromise(con, src->value, 32, 0xFFFFFFFF)); + lir::Constant srcLow(shiftMaskPromise(con, src->value, 0, 0xFFFFFFFF)); + + lir::Memory dstLow(dst->base, dst->offset + 4, dst->index, dst->scale); + moveCM(con, 4, &srcLow, 4, &dstLow); moveCM(con, 4, &srcHigh, 4, dst); } break; @@ -1166,10 +1457,13 @@ void moveCM(Context* con, unsigned srcSize, lir::Constant* src, } } -void negateRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize UNUSED, lir::Register* dst) +void negateRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize UNUSED, + lir::Register* dst) { - assert(con, srcSize == dstSize); + assertT(con, srcSize == dstSize); emit(con, mvn(dst->low, src->low)); emit(con, SETS(addi(dst->low, dst->low, 1))); @@ -1181,13 +1475,13 @@ void negateRR(Context* con, unsigned srcSize, lir::Register* src, void callR(Context* con, unsigned size UNUSED, lir::Register* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); emit(con, blx(target->low)); } void callC(Context* con, unsigned size UNUSED, lir::Constant* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); appendOffsetTask(con, target->value, offsetPromise(con)); emit(con, bl(0)); @@ -1195,7 +1489,7 @@ void callC(Context* con, unsigned size UNUSED, lir::Constant* target) void longCallC(Context* con, unsigned size UNUSED, lir::Constant* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); lir::Register tmp(4); moveCR2(con, vm::TargetBytesPerWord, target, &tmp, offsetPromise(con)); @@ -1204,16 +1498,16 @@ void longCallC(Context* con, unsigned size UNUSED, lir::Constant* target) void longJumpC(Context* con, unsigned size UNUSED, lir::Constant* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); - lir::Register tmp(4); // a non-arg reg that we don't mind clobbering + lir::Register tmp(4); // a non-arg reg that we don't mind clobbering moveCR2(con, vm::TargetBytesPerWord, target, &tmp, offsetPromise(con)); jumpR(con, vm::TargetBytesPerWord, &tmp); } void jumpC(Context* con, unsigned size UNUSED, lir::Constant* target) { - assert(con, size == vm::TargetBytesPerWord); + assertT(con, size == vm::TargetBytesPerWord); appendOffsetTask(con, target->value, offsetPromise(con)); emit(con, b(0)); @@ -1257,6 +1551,6 @@ void storeLoadBarrier(Context* con) memoryBarrier(con); } -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/arm/operations.h b/src/codegen/target/arm/operations.h index 3a2d10f705..4c3f53cb56 100644 --- a/src/codegen/target/arm/operations.h +++ b/src/codegen/target/arm/operations.h @@ -25,51 +25,87 @@ class Context; // shortcut functions -inline int newTemp(Context* con) { +inline int newTemp(Context* con) +{ return con->client->acquireTemporary(GPR_MASK); } -inline int newTemp(Context* con, unsigned mask) { +inline int newTemp(Context* con, unsigned mask) +{ return con->client->acquireTemporary(mask); } -inline void freeTemp(Context* con, int r) { +inline void freeTemp(Context* con, int r) +{ con->client->releaseTemporary(r); } -inline int64_t getValue(lir::Constant* con) { +inline int64_t getValue(lir::Constant* con) +{ return con->value->value(); } -inline lir::Register makeTemp(Context* con) { +inline lir::Register makeTemp(Context* con) +{ lir::Register tmp(newTemp(con)); return tmp; } -inline lir::Register makeTemp64(Context* con) { +inline lir::Register makeTemp64(Context* con) +{ lir::Register tmp(newTemp(con), newTemp(con)); return tmp; } -inline void freeTemp(Context* con, const lir::Register& tmp) { - if (tmp.low != lir::NoRegister) freeTemp(con, tmp.low); - if (tmp.high != lir::NoRegister) freeTemp(con, tmp.high); +inline void freeTemp(Context* con, const lir::Register& tmp) +{ + if (tmp.low != lir::NoRegister) + freeTemp(con, tmp.low); + if (tmp.high != lir::NoRegister) + freeTemp(con, tmp.high); } -void shiftLeftR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void shiftLeftR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void moveRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize, lir::Register* dst); +void moveRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize, + lir::Register* dst); -void shiftLeftC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t); +void shiftLeftC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t); -void shiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void shiftRightR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void shiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t); +void shiftRightC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t); -void unsignedShiftRightR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void unsignedShiftRightR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void unsignedShiftRightC(Context* con, unsigned size UNUSED, lir::Constant* a, lir::Register* b, lir::Register* t); +void unsignedShiftRightC(Context* con, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b, + lir::Register* t); bool needJump(MyBlock* b); @@ -79,142 +115,297 @@ void resolve(MyBlock* b); void jumpR(Context* con, unsigned size UNUSED, lir::Register* target); -void swapRR(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); +void swapRR(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b); -void moveRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize, lir::Register* dst); +void moveRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize, + lir::Register* dst); -void moveZRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned, lir::Register* dst); +void moveZRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned, + lir::Register* dst); -void moveCR(Context* con, unsigned size, lir::Constant* src, - unsigned, lir::Register* dst); +void moveCR(Context* con, + unsigned size, + lir::Constant* src, + unsigned, + lir::Register* dst); -void moveCR2(Context* con, unsigned size, lir::Constant* src, - lir::Register* dst, Promise* callOffset); +void moveCR2(Context* con, + unsigned size, + lir::Constant* src, + lir::Register* dst, + Promise* callOffset); -void moveCR(Context* con, unsigned size, lir::Constant* src, - unsigned, lir::Register* dst); +void moveCR(Context* con, + unsigned size, + lir::Constant* src, + unsigned, + lir::Register* dst); -void addR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void addR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void subR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void subR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void addC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst); +void addC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst); -void subC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst); +void subC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst); -void multiplyR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void multiplyR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void floatAbsoluteRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b); +void floatAbsoluteRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b); -void floatNegateRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b); +void floatNegateRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b); -void float2FloatRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b); +void float2FloatRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b); -void float2IntRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b); +void float2IntRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b); -void int2FloatRR(Context* con, unsigned, lir::Register* a, unsigned size, lir::Register* b); +void int2FloatRR(Context* con, + unsigned, + lir::Register* a, + unsigned size, + lir::Register* b); -void floatSqrtRR(Context* con, unsigned size, lir::Register* a, unsigned, lir::Register* b); +void floatSqrtRR(Context* con, + unsigned size, + lir::Register* a, + unsigned, + lir::Register* b); -void floatAddR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void floatAddR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void floatSubtractR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void floatSubtractR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void floatMultiplyR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void floatMultiplyR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -void floatDivideR(Context* con, unsigned size, lir::Register* a, lir::Register* b, lir::Register* t); +void floatDivideR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* t); -int normalize(Context* con, int offset, int index, unsigned scale, - bool* preserveIndex, bool* release); +int normalize(Context* con, + int offset, + int index, + unsigned scale, + bool* preserveIndex, + bool* release); -void store(Context* con, unsigned size, lir::Register* src, - int base, int offset, int index, unsigned scale, bool preserveIndex); +void store(Context* con, + unsigned size, + lir::Register* src, + int base, + int offset, + int index, + unsigned scale, + bool preserveIndex); -void moveRM(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize UNUSED, lir::Memory* dst); +void moveRM(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize UNUSED, + lir::Memory* dst); -void load(Context* con, unsigned srcSize, int base, int offset, int index, - unsigned scale, unsigned dstSize, lir::Register* dst, - bool preserveIndex, bool signExtend); +void load(Context* con, + unsigned srcSize, + int base, + int offset, + int index, + unsigned scale, + unsigned dstSize, + lir::Register* dst, + bool preserveIndex, + bool signExtend); -void moveMR(Context* con, unsigned srcSize, lir::Memory* src, - unsigned dstSize, lir::Register* dst); +void moveMR(Context* con, + unsigned srcSize, + lir::Memory* src, + unsigned dstSize, + lir::Register* dst); -void moveZMR(Context* con, unsigned srcSize, lir::Memory* src, - unsigned dstSize, lir::Register* dst); +void moveZMR(Context* con, + unsigned srcSize, + lir::Memory* src, + unsigned dstSize, + lir::Register* dst); -void andR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst); +void andR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst); -void andC(Context* con, unsigned size, lir::Constant* a, - lir::Register* b, lir::Register* dst); +void andC(Context* con, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Register* dst); -void orR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst); +void orR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst); -void xorR(Context* con, unsigned size, lir::Register* a, - lir::Register* b, lir::Register* dst); +void xorR(Context* con, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Register* dst); -void moveAR2(Context* con, unsigned srcSize, lir::Address* src, - unsigned dstSize, lir::Register* dst); +void moveAR2(Context* con, + unsigned srcSize, + lir::Address* src, + unsigned dstSize, + lir::Register* dst); -void moveAR(Context* con, unsigned srcSize, lir::Address* src, - unsigned dstSize, lir::Register* dst); +void moveAR(Context* con, + unsigned srcSize, + lir::Address* src, + unsigned dstSize, + lir::Register* dst); -void compareRR(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void compareRR(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareCR(Context* con, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void compareCR(Context* con, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void compareCM(Context* con, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Memory* b); +void compareCM(Context* con, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Memory* b); -void compareRM(Context* con, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Memory* b); +void compareRM(Context* con, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Memory* b); -int32_t -branch(Context* con, lir::TernaryOperation op); +int32_t branch(Context* con, lir::TernaryOperation op); void conditional(Context* con, int32_t branch, lir::Constant* target); void branch(Context* con, lir::TernaryOperation op, lir::Constant* target); -void branchLong(Context* con, lir::TernaryOperation op, lir::Operand* al, - lir::Operand* ah, lir::Operand* bl, - lir::Operand* bh, lir::Constant* target, - BinaryOperationType compareSigned, - BinaryOperationType compareUnsigned); +void branchLong(Context* con, + lir::TernaryOperation op, + lir::Operand* al, + lir::Operand* ah, + lir::Operand* bl, + lir::Operand* bh, + lir::Constant* target, + BinaryOperationType compareSigned, + BinaryOperationType compareUnsigned); -void branchRR(Context* con, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Register* b, - lir::Constant* target); +void branchRR(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Constant* target); -void branchCR(Context* con, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Register* b, - lir::Constant* target); +void branchCR(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Constant* target); -void branchRM(Context* con, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Memory* b, - lir::Constant* target); +void branchRM(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Memory* b, + lir::Constant* target); -void branchCM(Context* con, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Memory* b, - lir::Constant* target); +void branchCM(Context* con, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Memory* b, + lir::Constant* target); -ShiftMaskPromise* -shiftMaskPromise(Context* con, Promise* base, unsigned shift, int64_t mask); +ShiftMaskPromise* shiftMaskPromise(Context* con, + Promise* base, + unsigned shift, + int64_t mask); -void moveCM(Context* con, unsigned srcSize, lir::Constant* src, - unsigned dstSize, lir::Memory* dst); +void moveCM(Context* con, + unsigned srcSize, + lir::Constant* src, + unsigned dstSize, + lir::Memory* dst); -void negateRR(Context* con, unsigned srcSize, lir::Register* src, - unsigned dstSize UNUSED, lir::Register* dst); +void negateRR(Context* con, + unsigned srcSize, + lir::Register* src, + unsigned dstSize UNUSED, + lir::Register* dst); void callR(Context* con, unsigned size UNUSED, lir::Register* target); @@ -236,9 +427,8 @@ void storeStoreBarrier(Context*); void storeLoadBarrier(Context*); -} // namespace arm -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_OPERATIONS_H +} // namespace arm +} // namespace codegen +} // namespace avian +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_OPERATIONS_H diff --git a/src/codegen/target/arm/registers.h b/src/codegen/target/arm/registers.h index fdb6cf0891..f6d0a9d7fa 100644 --- a/src/codegen/target/arm/registers.h +++ b/src/codegen/target/arm/registers.h @@ -18,10 +18,9 @@ namespace avian { namespace codegen { namespace arm { - const uint64_t MASK_LO32 = 0xffffffff; const unsigned MASK_LO16 = 0xffff; -const unsigned MASK_LO8 = 0xff; +const unsigned MASK_LO8 = 0xff; const int N_GPRS = 16; const int N_FPRS = 16; @@ -31,22 +30,35 @@ const uint32_t FPR_MASK = 0xffff0000; const uint64_t GPR_MASK64 = GPR_MASK | (uint64_t)GPR_MASK << 32; const uint64_t FPR_MASK64 = FPR_MASK | (uint64_t)FPR_MASK << 32; -inline bool isFpr(lir::Register* reg) { +inline bool isFpr(lir::Register* reg) +{ return reg->low >= N_GPRS; } -inline int fpr64(int reg) { return reg - N_GPRS; } -inline int fpr64(lir::Register* reg) { return fpr64(reg->low); } -inline int fpr32(int reg) { return fpr64(reg) << 1; } -inline int fpr32(lir::Register* reg) { return fpr64(reg) << 1; } +inline int fpr64(int reg) +{ + return reg - N_GPRS; +} +inline int fpr64(lir::Register* reg) +{ + return fpr64(reg->low); +} +inline int fpr32(int reg) +{ + return fpr64(reg) << 1; +} +inline int fpr32(lir::Register* reg) +{ + return fpr64(reg) << 1; +} const int ThreadRegister = 8; const int StackRegister = 13; const int LinkRegister = 14; const int ProgramCounter = 15; -} // namespace arm -} // namespace codegen -} // namespace avian +} // namespace arm +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_REGISTERS_H +#endif // AVIAN_CODEGEN_ASSEMBLER_ARM_REGISTERS_H diff --git a/src/codegen/target/multimethod.h b/src/codegen/target/multimethod.h index 1a0890d851..e5de2ca23c 100644 --- a/src/codegen/target/multimethod.h +++ b/src/codegen/target/multimethod.h @@ -11,19 +11,19 @@ #ifndef AVIAN_CODEGEN_TARGET_MULTIMETHOD_H #define AVIAN_CODEGEN_TARGET_MULTIMETHOD_H - namespace avian { namespace codegen { class Multimethod { -public: - inline static unsigned index(lir::UnaryOperation operation, lir::OperandType operand) { + public: + inline static unsigned index(lir::UnaryOperation operation, + lir::OperandType operand) + { return operation + (lir::UnaryOperationCount * operand); } }; -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_TARGET_MULTIMETHOD_H +} // namespace codegen +} // namespace avian +#endif // AVIAN_CODEGEN_TARGET_MULTIMETHOD_H diff --git a/src/codegen/target/x86/assembler.cpp b/src/codegen/target/x86/assembler.cpp index 4791f65681..e124a97a85 100644 --- a/src/codegen/target/x86/assembler.cpp +++ b/src/codegen/target/x86/assembler.cpp @@ -54,28 +54,33 @@ namespace x86 { const unsigned FrameHeaderSize = (UseFramePointer ? 2 : 1); const unsigned StackAlignmentInBytes = 16; -const unsigned StackAlignmentInWords = StackAlignmentInBytes / TargetBytesPerWord; +const unsigned StackAlignmentInWords = StackAlignmentInBytes + / TargetBytesPerWord; -unsigned -argumentFootprint(unsigned footprint) +unsigned argumentFootprint(unsigned footprint) { return max(pad(footprint, StackAlignmentInWords), StackAlignmentInWords); } -uint32_t -read4(uint8_t* p) +uint32_t read4(uint8_t* p) { - uint32_t v; memcpy(&v, p, 4); + uint32_t v; + memcpy(&v, p, 4); return v; } -void -nextFrame(ArchitectureContext* c UNUSED, uint8_t* start, unsigned size UNUSED, - unsigned footprint, void*, bool mostRecent, - int targetParameterFootprint, void** ip, void** stack) +void nextFrame(ArchitectureContext* c UNUSED, + uint8_t* start, + unsigned size UNUSED, + unsigned footprint, + void*, + bool mostRecent, + int targetParameterFootprint, + void** ip, + void** stack) { - assert(c, *ip >= start); - assert(c, *ip <= start + size); + assertT(c, *ip >= start); + assertT(c, *ip <= start + size); uint8_t* instruction = static_cast(*ip); @@ -89,7 +94,7 @@ nextFrame(ArchitectureContext* c UNUSED, uint8_t* start, unsigned size UNUSED, } if (instruction <= start) { - assert(c, mostRecent); + assertT(c, mostRecent); *ip = static_cast(*stack)[0]; return; } @@ -99,7 +104,7 @@ nextFrame(ArchitectureContext* c UNUSED, uint8_t* start, unsigned size UNUSED, start += (TargetBytesPerWord == 4 ? 3 : 4); if (instruction <= start or *instruction == 0x5d) { - assert(c, mostRecent); + assertT(c, mostRecent); *ip = static_cast(*stack)[1]; *stack = static_cast(*stack) + 1; @@ -107,7 +112,7 @@ nextFrame(ArchitectureContext* c UNUSED, uint8_t* start, unsigned size UNUSED, } } - if (*instruction == 0xc3) { // return + if (*instruction == 0xc3) { // return *ip = static_cast(*stack)[0]; return; } @@ -117,54 +122,55 @@ nextFrame(ArchitectureContext* c UNUSED, uint8_t* start, unsigned size UNUSED, if (TailCalls and targetParameterFootprint >= 0) { if (argumentFootprint(targetParameterFootprint) > StackAlignmentInWords) { offset += argumentFootprint(targetParameterFootprint) - - StackAlignmentInWords; + - StackAlignmentInWords; } // check for post-non-tail-call stack adjustment of the form "sub // $offset,%rsp": if (TargetBytesPerWord == 4) { if ((*instruction == 0x83 or *instruction == 0x81) - and instruction[1] == 0xec) - { + and instruction[1] == 0xec) { offset - -= (*instruction == 0x83 ? instruction[2] : read4(instruction + 2)) - / TargetBytesPerWord; + -= (*instruction == 0x83 ? instruction[2] : read4(instruction + 2)) + / TargetBytesPerWord; } } else if (*instruction == 0x48 and (instruction[1] == 0x83 or instruction[1] == 0x81) - and instruction[2] == 0xec) - { + and instruction[2] == 0xec) { offset - -= (instruction[1] == 0x83 ? instruction[3] : read4(instruction + 3)) - / TargetBytesPerWord; + -= (instruction[1] == 0x83 ? instruction[3] : read4(instruction + 3)) + / TargetBytesPerWord; } // todo: check for and handle tail calls } - - if (UseFramePointer and not mostRecent) { - assert(c, static_cast(*stack)[-1] + 1 - == static_cast(*stack) + offset); - assert(c, static_cast(*stack)[-1][1] - == static_cast(*stack)[offset]); + if (UseFramePointer and not mostRecent) { + assertT(c, + static_cast(*stack)[-1] + 1 + == static_cast(*stack) + offset); + + assertT(c, + static_cast(*stack)[-1][1] + == static_cast(*stack)[offset]); } *ip = static_cast(*stack)[offset]; *stack = static_cast(*stack) + offset; } -class MyArchitecture: public Architecture { +class MyArchitecture : public Architecture { public: - MyArchitecture(System* system, bool useNativeFeatures): - c(system, useNativeFeatures), - referenceCount(0), - myRegisterFile(GeneralRegisterMask, useSSE(&c) ? FloatRegisterMask : 0) + MyArchitecture(System* system, bool useNativeFeatures) + : c(system, useNativeFeatures), + referenceCount(0), + myRegisterFile(GeneralRegisterMask, useSSE(&c) ? FloatRegisterMask : 0) { populateTables(&c); } - virtual unsigned floatRegisterSize() { + virtual unsigned floatRegisterSize() + { if (useSSE(&c)) { return 8; } else { @@ -172,35 +178,43 @@ class MyArchitecture: public Architecture { } } - virtual const RegisterFile* registerFile() { + virtual const RegisterFile* registerFile() + { return &myRegisterFile; } - virtual int scratch() { + virtual int scratch() + { return rax; } - virtual int stack() { + virtual int stack() + { return rsp; } - virtual int thread() { + virtual int thread() + { return rbx; } - virtual int returnLow() { + virtual int returnLow() + { return rax; } - virtual int returnHigh() { + virtual int returnHigh() + { return (TargetBytesPerWord == 4 ? rdx : lir::NoRegister); } - virtual int virtualCallTarget() { + virtual int virtualCallTarget() + { return rax; } - virtual int virtualCallIndex() { + virtual int virtualCallIndex() + { return rdx; } @@ -209,15 +223,18 @@ class MyArchitecture: public Architecture { return ir::TargetInfo(TargetBytesPerWord); } - virtual bool bigEndian() { + virtual bool bigEndian() + { return false; } - virtual uintptr_t maximumImmediateJump() { + virtual uintptr_t maximumImmediateJump() + { return 0x7FFFFFFF; } - virtual bool reserved(int register_) { + virtual bool reserved(int register_) + { switch (register_) { case rbp: return UseFramePointer; @@ -225,45 +242,56 @@ class MyArchitecture: public Architecture { case rsp: case rbx: return true; - + default: return false; } } - virtual unsigned frameFootprint(unsigned footprint) { + virtual unsigned frameFootprint(unsigned footprint) + { #if AVIAN_TARGET_FORMAT == AVIAN_FORMAT_PE return max(footprint, StackAlignmentInWords); #else - return max(footprint > argumentRegisterCount() ? - footprint - argumentRegisterCount() : 0, + return max(footprint > argumentRegisterCount() + ? footprint - argumentRegisterCount() + : 0, StackAlignmentInWords); #endif } - virtual unsigned argumentFootprint(unsigned footprint) { + virtual unsigned argumentFootprint(unsigned footprint) + { return x86::argumentFootprint(footprint); } - virtual bool argumentAlignment() { + virtual bool argumentAlignment() + { return false; } - virtual bool argumentRegisterAlignment() { + virtual bool argumentRegisterAlignment() + { return false; } - virtual unsigned argumentRegisterCount() { + virtual unsigned argumentRegisterCount() + { #if AVIAN_TARGET_FORMAT == AVIAN_FORMAT_PE - if (TargetBytesPerWord == 8) return 4; else + if (TargetBytesPerWord == 8) + return 4; + else #else - if (TargetBytesPerWord == 8) return 6; else + if (TargetBytesPerWord == 8) + return 6; + else #endif - return 0; + return 0; } - virtual int argumentRegister(unsigned index) { - assert(&c, TargetBytesPerWord == 8); + virtual int argumentRegister(unsigned index) + { + assertT(&c, TargetBytesPerWord == 8); switch (index) { #if AVIAN_TARGET_FORMAT == AVIAN_FORMAT_PE case 0: @@ -293,64 +321,73 @@ class MyArchitecture: public Architecture { } } - virtual bool hasLinkRegister() { + virtual bool hasLinkRegister() + { return false; } - virtual unsigned stackAlignmentInWords() { + virtual unsigned stackAlignmentInWords() + { return StackAlignmentInWords; } - virtual bool matchCall(void* returnAddress, void* target) { + virtual bool matchCall(void* returnAddress, void* target) + { uint8_t* instruction = static_cast(returnAddress) - 5; - int32_t actualOffset; memcpy(&actualOffset, instruction + 1, 4); + int32_t actualOffset; + memcpy(&actualOffset, instruction + 1, 4); void* actualTarget = static_cast(returnAddress) + actualOffset; return *instruction == 0xE8 and actualTarget == target; } - virtual void updateCall(lir::UnaryOperation op, void* returnAddress, + virtual void updateCall(lir::UnaryOperation op, + void* returnAddress, void* newTarget) { - bool assertAlignment UNUSED; + bool assertTAlignment UNUSED; switch (op) { case lir::AlignedCall: op = lir::Call; - assertAlignment = true; + assertTAlignment = true; break; case lir::AlignedJump: op = lir::Jump; - assertAlignment = true; + assertTAlignment = true; break; case lir::AlignedLongCall: op = lir::LongCall; - assertAlignment = true; + assertTAlignment = true; break; case lir::AlignedLongJump: op = lir::LongJump; - assertAlignment = true; + assertTAlignment = true; break; default: - assertAlignment = false; + assertTAlignment = false; } if (TargetBytesPerWord == 4 or op == lir::Call or op == lir::Jump) { uint8_t* instruction = static_cast(returnAddress) - 5; - - assert(&c, ((op == lir::Call or op == lir::LongCall) and *instruction == 0xE8) - or ((op == lir::Jump or op == lir::LongJump) and *instruction == 0xE9)); - assert(&c, (not assertAlignment) - or reinterpret_cast(instruction + 1) % 4 == 0); - + assertT( + &c, + ((op == lir::Call or op == lir::LongCall) and *instruction == 0xE8) + or ((op == lir::Jump or op == lir::LongJump) + and *instruction == 0xE9)); + + assertT(&c, + (not assertTAlignment) + or reinterpret_cast(instruction + 1) % 4 == 0); + intptr_t v = static_cast(newTarget) - - static_cast(returnAddress); + - static_cast(returnAddress); - assert(&c, vm::fitsInInt32(v)); + assertT(&c, vm::fitsInInt32(v)); int32_t v32 = v; @@ -358,55 +395,75 @@ class MyArchitecture: public Architecture { } else { uint8_t* instruction = static_cast(returnAddress) - 13; - assert(&c, instruction[0] == 0x49 and instruction[1] == 0xBA); - assert(&c, instruction[10] == 0x41 and instruction[11] == 0xFF); - assert(&c, (op == lir::LongCall and instruction[12] == 0xD2) - or (op == lir::LongJump and instruction[12] == 0xE2)); + assertT(&c, instruction[0] == 0x49 and instruction[1] == 0xBA); + assertT(&c, instruction[10] == 0x41 and instruction[11] == 0xFF); + assertT(&c, + (op == lir::LongCall and instruction[12] == 0xD2) + or (op == lir::LongJump and instruction[12] == 0xE2)); + + assertT(&c, + (not assertTAlignment) + or reinterpret_cast(instruction + 2) % 8 == 0); - assert(&c, (not assertAlignment) - or reinterpret_cast(instruction + 2) % 8 == 0); - memcpy(instruction + 2, &newTarget, 8); } } - virtual void setConstant(void* dst, uint64_t constant) { + virtual void setConstant(void* dst, uint64_t constant) + { target_uintptr_t v = targetVW(constant); memcpy(dst, &v, TargetBytesPerWord); } - virtual unsigned alignFrameSize(unsigned sizeInWords) { + virtual unsigned alignFrameSize(unsigned sizeInWords) + { return pad(sizeInWords + FrameHeaderSize, StackAlignmentInWords) - - FrameHeaderSize; + - FrameHeaderSize; } - virtual void nextFrame(void* start, unsigned size, unsigned footprint, - void* link, bool mostRecent, - int targetParameterFootprint, void** ip, + virtual void nextFrame(void* start, + unsigned size, + unsigned footprint, + void* link, + bool mostRecent, + int targetParameterFootprint, + void** ip, void** stack) { - x86::nextFrame(&c, static_cast(start), size, footprint, - link, mostRecent, targetParameterFootprint, ip, stack); + x86::nextFrame(&c, + static_cast(start), + size, + footprint, + link, + mostRecent, + targetParameterFootprint, + ip, + stack); } - virtual void* frameIp(void* stack) { + virtual void* frameIp(void* stack) + { return stack ? *static_cast(stack) : 0; } - virtual unsigned frameHeaderSize() { + virtual unsigned frameHeaderSize() + { return FrameHeaderSize; } - virtual unsigned frameReturnAddressSize() { + virtual unsigned frameReturnAddressSize() + { return 1; } - virtual unsigned frameFooterSize() { + virtual unsigned frameFooterSize() + { return 0; } - virtual bool alwaysCondensed(lir::BinaryOperation op) { - switch(op) { + virtual bool alwaysCondensed(lir::BinaryOperation op) + { + switch (op) { case lir::Float2Float: case lir::Float2Int: case lir::Int2Float: @@ -423,35 +480,40 @@ class MyArchitecture: public Architecture { abort(&c); } } - - virtual bool alwaysCondensed(lir::TernaryOperation) { + + virtual bool alwaysCondensed(lir::TernaryOperation) + { return true; } - virtual int returnAddressOffset() { + virtual int returnAddressOffset() + { return 0; } - virtual int framePointerOffset() { + virtual int framePointerOffset() + { return UseFramePointer ? -1 : 0; } - virtual void plan - (lir::UnaryOperation, - unsigned, OperandMask& aMask, - bool* thunk) + virtual void plan(lir::UnaryOperation, + unsigned, + OperandMask& aMask, + bool* thunk) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand) | (1 << lir::ConstantOperand); + aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand) + | (1 << lir::ConstantOperand); *thunk = false; } - virtual void planSource - (lir::BinaryOperation op, - unsigned aSize, OperandMask& aMask, - unsigned bSize, bool* thunk) + virtual void planSource(lir::BinaryOperation op, + unsigned aSize, + OperandMask& aMask, + unsigned bSize, + bool* thunk) { - aMask.registerMask = GeneralRegisterMask | - (static_cast(GeneralRegisterMask) << 32); + aMask.registerMask = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); *thunk = false; @@ -459,7 +521,7 @@ class MyArchitecture: public Architecture { case lir::Negate: aMask.typeMask = (1 << lir::RegisterOperand); aMask.registerMask = (static_cast(1) << (rdx + 32)) - | (static_cast(1) << rax); + | (static_cast(1) << rax); break; case lir::Absolute: @@ -475,12 +537,12 @@ class MyArchitecture: public Architecture { if (useSSE(&c)) { aMask.typeMask = (1 << lir::RegisterOperand); aMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; } else { *thunk = true; } - break; - + break; + case lir::FloatNegate: // floatNegateRR does not support doubles if (useSSE(&c) and aSize == 4 and bSize == 4) { @@ -493,9 +555,10 @@ class MyArchitecture: public Architecture { case lir::FloatSquareRoot: if (useSSE(&c)) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); aMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; } else { *thunk = true; } @@ -503,9 +566,10 @@ class MyArchitecture: public Architecture { case lir::Float2Float: if (useSSE(&c)) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); aMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; } else { *thunk = true; } @@ -517,9 +581,10 @@ class MyArchitecture: public Architecture { // thunks or produce inline machine code which handles edge // cases properly. if (false and useSSE(&c) and bSize <= TargetBytesPerWord) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); aMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; } else { *thunk = true; } @@ -527,9 +592,11 @@ class MyArchitecture: public Architecture { case lir::Int2Float: if (useSSE(&c) and aSize <= TargetBytesPerWord) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); - aMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); + aMask.registerMask + = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); } else { *thunk = true; } @@ -541,15 +608,17 @@ class MyArchitecture: public Architecture { if (TargetBytesPerWord == 4) { if (aSize == 4 and bSize == 8) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); - const uint32_t mask - = GeneralRegisterMask & ~((1 << rax) | (1 << rdx)); - aMask.registerMask = (static_cast(mask) << 32) | mask; + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); + const uint32_t mask = GeneralRegisterMask + & ~((1 << rax) | (1 << rdx)); + aMask.registerMask = (static_cast(mask) << 32) | mask; } else if (aSize == 1 or bSize == 1) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); - const uint32_t mask - = (1 << rax) | (1 << rcx) | (1 << rdx) | (1 << rbx); - aMask.registerMask = (static_cast(mask) << 32) | mask; + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); + const uint32_t mask = (1 << rax) | (1 << rcx) | (1 << rdx) + | (1 << rbx); + aMask.registerMask = (static_cast(mask) << 32) | mask; } } break; @@ -559,14 +628,15 @@ class MyArchitecture: public Architecture { } } - virtual void planDestination - (lir::BinaryOperation op, - unsigned aSize, const OperandMask& aMask, - unsigned bSize, OperandMask& bMask) + virtual void planDestination(lir::BinaryOperation op, + unsigned aSize, + const OperandMask& aMask, + unsigned bSize, + OperandMask& bMask) { bMask.typeMask = ~0; bMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + | (static_cast(GeneralRegisterMask) << 32); switch (op) { case lir::Absolute: @@ -590,7 +660,7 @@ class MyArchitecture: public Architecture { case lir::Int2Float: bMask.typeMask = (1 << lir::RegisterOperand); bMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; break; case lir::Float2Int: @@ -598,30 +668,34 @@ class MyArchitecture: public Architecture { break; case lir::Move: - if (aMask.typeMask & ((1 << lir::MemoryOperand) | 1 << lir::AddressOperand)) { + if (aMask.typeMask + & ((1 << lir::MemoryOperand) | 1 << lir::AddressOperand)) { bMask.typeMask = (1 << lir::RegisterOperand); bMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32) - | FloatRegisterMask; + | (static_cast(GeneralRegisterMask) + << 32) | FloatRegisterMask; } else if (aMask.typeMask & (1 << lir::RegisterOperand)) { - bMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + bMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); if (aMask.registerMask & FloatRegisterMask) { - bMask.registerMask = FloatRegisterMask; + bMask.registerMask = FloatRegisterMask; } else { - bMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + bMask.registerMask + = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); } } else { - bMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + bMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); } if (TargetBytesPerWord == 4) { if (aSize == 4 and bSize == 8) { bMask.registerMask = (static_cast(1) << (rdx + 32)) - | (static_cast(1) << rax); + | (static_cast(1) << rax); } else if (aSize == 1 or bSize == 1) { - const uint32_t mask - = (1 << rax) | (1 << rcx) | (1 << rdx) | (1 << rbx); + const uint32_t mask = (1 << rax) | (1 << rcx) | (1 << rdx) + | (1 << rbx); bMask.registerMask = (static_cast(mask) << 32) | mask; } } @@ -632,10 +706,10 @@ class MyArchitecture: public Architecture { } } - virtual void planMove - (unsigned size, OperandMask& srcMask, - OperandMask& tmpMask, - const OperandMask& dstMask) + virtual void planMove(unsigned size, + OperandMask& srcMask, + OperandMask& tmpMask, + const OperandMask& dstMask) { srcMask.typeMask = ~0; srcMask.registerMask = ~static_cast(0); @@ -645,21 +719,25 @@ class MyArchitecture: public Architecture { if (dstMask.typeMask & (1 << lir::MemoryOperand)) { // can't move directly from memory to memory - srcMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::ConstantOperand); + srcMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::ConstantOperand); tmpMask.typeMask = 1 << lir::RegisterOperand; - tmpMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + tmpMask.registerMask + = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); } else if (dstMask.typeMask & (1 << lir::RegisterOperand)) { if (size > TargetBytesPerWord) { // can't move directly from FPR to GPR or vice-versa for // values larger than the GPR size if (dstMask.registerMask & FloatRegisterMask) { - srcMask.registerMask = FloatRegisterMask - | (static_cast(FloatRegisterMask) << 32); - tmpMask.typeMask = 1 << lir::MemoryOperand; + srcMask.registerMask + = FloatRegisterMask + | (static_cast(FloatRegisterMask) << 32); + tmpMask.typeMask = 1 << lir::MemoryOperand; } else if (dstMask.registerMask & GeneralRegisterMask) { - srcMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + srcMask.registerMask + = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); tmpMask.typeMask = 1 << lir::MemoryOperand; } } @@ -669,27 +747,31 @@ class MyArchitecture: public Architecture { if (size > TargetBytesPerWord) { tmpMask.typeMask = 1 << lir::MemoryOperand; } else { - tmpMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); - tmpMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + tmpMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); + tmpMask.registerMask + = GeneralRegisterMask + | (static_cast(GeneralRegisterMask) << 32); } } } } - virtual void planSource - (lir::TernaryOperation op, - unsigned aSize, OperandMask& aMask, - unsigned bSize, OperandMask& bMask, - unsigned, bool* thunk) + virtual void planSource(lir::TernaryOperation op, + unsigned aSize, + OperandMask& aMask, + unsigned bSize, + OperandMask& bMask, + unsigned, + bool* thunk) { aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::ConstantOperand); aMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + | (static_cast(GeneralRegisterMask) << 32); bMask.typeMask = (1 << lir::RegisterOperand); bMask.registerMask = GeneralRegisterMask - | (static_cast(GeneralRegisterMask) << 32); + | (static_cast(GeneralRegisterMask) << 32); *thunk = false; @@ -699,12 +781,12 @@ class MyArchitecture: public Architecture { case lir::FloatMultiply: case lir::FloatDivide: if (useSSE(&c)) { - aMask.typeMask = (1 << lir::RegisterOperand) | (1 << lir::MemoryOperand); + aMask.typeMask = (1 << lir::RegisterOperand) + | (1 << lir::MemoryOperand); bMask.typeMask = (1 << lir::RegisterOperand); - const uint64_t mask - = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + const uint64_t mask = (static_cast(FloatRegisterMask) << 32) + | FloatRegisterMask; aMask.registerMask = mask; bMask.registerMask = mask; } else { @@ -715,9 +797,9 @@ class MyArchitecture: public Architecture { case lir::FloatRemainder: *thunk = true; break; - + case lir::Multiply: - if (TargetBytesPerWord == 4 and aSize == 8) { + if (TargetBytesPerWord == 4 and aSize == 8) { const uint32_t mask = GeneralRegisterMask & ~((1 << rax) | (1 << rdx)); aMask.registerMask = (static_cast(mask) << 32) | mask; bMask.registerMask = (static_cast(1) << (rdx + 32)) | mask; @@ -729,11 +811,11 @@ class MyArchitecture: public Architecture { case lir::Divide: if (TargetBytesPerWord == 4 and aSize == 8) { - *thunk = true; + *thunk = true; } else { aMask.typeMask = (1 << lir::RegisterOperand); aMask.registerMask = GeneralRegisterMask & ~((1 << rax) | (1 << rdx)); - bMask.registerMask = 1 << rax; + bMask.registerMask = 1 << rax; } break; @@ -756,7 +838,7 @@ class MyArchitecture: public Architecture { bMask.registerMask = (static_cast(mask) << 32) | mask; } else { aMask.registerMask = (static_cast(GeneralRegisterMask) << 32) - | (static_cast(1) << rcx); + | (static_cast(1) << rcx); const uint32_t mask = GeneralRegisterMask & ~(1 << rcx); bMask.registerMask = (static_cast(mask) << 32) | mask; } @@ -775,7 +857,7 @@ class MyArchitecture: public Architecture { if (useSSE(&c)) { aMask.typeMask = (1 << lir::RegisterOperand); aMask.registerMask = (static_cast(FloatRegisterMask) << 32) - | FloatRegisterMask; + | FloatRegisterMask; bMask.typeMask = aMask.typeMask; bMask.registerMask = aMask.registerMask; } else { @@ -788,11 +870,13 @@ class MyArchitecture: public Architecture { } } - virtual void planDestination - (lir::TernaryOperation op, - unsigned, const OperandMask&, - unsigned, const OperandMask& bMask, - unsigned, OperandMask& cMask) + virtual void planDestination(lir::TernaryOperation op, + unsigned, + const OperandMask&, + unsigned, + const OperandMask& bMask, + unsigned, + OperandMask& cMask) { if (isBranch(op)) { cMask.typeMask = (1 << lir::ConstantOperand); @@ -805,12 +889,14 @@ class MyArchitecture: public Architecture { virtual Assembler* makeAssembler(util::Allocator* allocator, Zone* zone); - virtual void acquire() { - ++ referenceCount; + virtual void acquire() + { + ++referenceCount; } - virtual void release() { - if (-- referenceCount == 0) { + virtual void release() + { + if (--referenceCount == 0) { c.s->free(this); } } @@ -820,18 +906,21 @@ class MyArchitecture: public Architecture { const RegisterFile myRegisterFile; }; -class MyAssembler: public Assembler { +class MyAssembler : public Assembler { public: MyAssembler(System* s, util::Allocator* a, Zone* zone, MyArchitecture* arch) : c(s, a, zone, &(arch->c)), arch_(arch) - { } + { + } - virtual void setClient(Client* client) { - assert(&c, c.client == 0); + virtual void setClient(Client* client) + { + assertT(&c, c.client == 0); c.client = client; } - virtual Architecture* arch() { + virtual Architecture* arch() + { return arch_; } @@ -841,19 +930,25 @@ class MyAssembler: public Assembler { lir::Register stack(rsp); lir::Memory stackLimit(rbx, stackLimitOffsetFromThread); lir::Constant handlerConstant(resolvedPromise(&c, handler)); - branchRM(&c, lir::JumpIfGreaterOrEqual, TargetBytesPerWord, &stack, &stackLimit, + branchRM(&c, + lir::JumpIfGreaterOrEqual, + TargetBytesPerWord, + &stack, + &stackLimit, &handlerConstant); } - virtual void saveFrame(unsigned stackOffset, unsigned) { + virtual void saveFrame(unsigned stackOffset, unsigned) + { lir::Register stack(rsp); lir::Memory stackDst(rbx, stackOffset); apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), - OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &stackDst)); + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), + OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &stackDst)); } - virtual void pushFrame(unsigned argumentCount, ...) { + virtual void pushFrame(unsigned argumentCount, ...) + { // TODO: Argument should be replaced by OperandInfo... struct Argument { unsigned size; @@ -861,51 +956,51 @@ class MyAssembler: public Assembler { lir::Operand* operand; }; RUNTIME_ARRAY(Argument, arguments, argumentCount); - va_list a; va_start(a, argumentCount); + va_list a; + va_start(a, argumentCount); unsigned footprint = 0; for (unsigned i = 0; i < argumentCount; ++i) { RUNTIME_ARRAY_BODY(arguments)[i].size = va_arg(a, unsigned); RUNTIME_ARRAY_BODY(arguments)[i].type - = static_cast(va_arg(a, int)); + = static_cast(va_arg(a, int)); RUNTIME_ARRAY_BODY(arguments)[i].operand = va_arg(a, lir::Operand*); - footprint += ceilingDivide - (RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord); + footprint += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord); } va_end(a); allocateFrame(arch_->alignFrameSize(footprint)); - + unsigned offset = 0; for (unsigned i = 0; i < argumentCount; ++i) { if (i < arch_->argumentRegisterCount()) { lir::Register dst(arch_->argumentRegister(i)); apply(lir::Move, - OperandInfo( - RUNTIME_ARRAY_BODY(arguments)[i].size, - RUNTIME_ARRAY_BODY(arguments)[i].type, - RUNTIME_ARRAY_BODY(arguments)[i].operand), - OperandInfo( - pad(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord), - lir::RegisterOperand, - &dst)); + OperandInfo(RUNTIME_ARRAY_BODY(arguments)[i].size, + RUNTIME_ARRAY_BODY(arguments)[i].type, + RUNTIME_ARRAY_BODY(arguments)[i].operand), + OperandInfo(pad(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord), + lir::RegisterOperand, + &dst)); } else { lir::Memory dst(rsp, offset * TargetBytesPerWord); apply(lir::Move, - OperandInfo( - RUNTIME_ARRAY_BODY(arguments)[i].size, - RUNTIME_ARRAY_BODY(arguments)[i].type, - RUNTIME_ARRAY_BODY(arguments)[i].operand), - OperandInfo( - pad(RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord), - lir::MemoryOperand, - &dst)); - offset += ceilingDivide - (RUNTIME_ARRAY_BODY(arguments)[i].size, TargetBytesPerWord); + OperandInfo(RUNTIME_ARRAY_BODY(arguments)[i].size, + RUNTIME_ARRAY_BODY(arguments)[i].type, + RUNTIME_ARRAY_BODY(arguments)[i].operand), + OperandInfo(pad(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord), + lir::MemoryOperand, + &dst)); + offset += ceilingDivide(RUNTIME_ARRAY_BODY(arguments)[i].size, + TargetBytesPerWord); } } } - virtual void allocateFrame(unsigned footprint) { + virtual void allocateFrame(unsigned footprint) + { lir::Register stack(rsp); if (UseFramePointer) { @@ -913,42 +1008,49 @@ class MyAssembler: public Assembler { pushR(&c, TargetBytesPerWord, &base); apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &base)); + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &base)); } - lir::Constant footprintConstant(resolvedPromise(&c, footprint * TargetBytesPerWord)); + lir::Constant footprintConstant( + resolvedPromise(&c, footprint * TargetBytesPerWord)); apply(lir::Subtract, - OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &footprintConstant), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); + OperandInfo( + TargetBytesPerWord, lir::ConstantOperand, &footprintConstant), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); } - virtual void adjustFrame(unsigned difference) { + virtual void adjustFrame(unsigned difference) + { lir::Register stack(rsp); - lir::Constant differenceConstant(resolvedPromise(&c, difference * TargetBytesPerWord)); - apply(lir::Subtract, - OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &differenceConstant), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); + lir::Constant differenceConstant( + resolvedPromise(&c, difference * TargetBytesPerWord)); + apply(lir::Subtract, + OperandInfo( + TargetBytesPerWord, lir::ConstantOperand, &differenceConstant), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); } - virtual void popFrame(unsigned frameFootprint) { + virtual void popFrame(unsigned frameFootprint) + { if (UseFramePointer) { lir::Register base(rbp); lir::Register stack(rsp); apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &base), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &base), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); popR(&c, TargetBytesPerWord, &base); } else { lir::Register stack(rsp); - lir::Constant footprint(resolvedPromise(&c, frameFootprint * TargetBytesPerWord)); + lir::Constant footprint( + resolvedPromise(&c, frameFootprint * TargetBytesPerWord)); apply(lir::Add, - OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &footprint), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); + OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &footprint), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &stack)); } } @@ -960,17 +1062,23 @@ class MyAssembler: public Assembler { if (TailCalls) { if (offset) { lir::Register tmp(c.client->acquireTemporary()); - + unsigned baseSize = UseFramePointer ? 1 : 0; - lir::Memory returnAddressSrc - (rsp, (frameFootprint + baseSize) * TargetBytesPerWord); - moveMR(&c, TargetBytesPerWord, &returnAddressSrc, TargetBytesPerWord, + lir::Memory returnAddressSrc( + rsp, (frameFootprint + baseSize) * TargetBytesPerWord); + moveMR(&c, + TargetBytesPerWord, + &returnAddressSrc, + TargetBytesPerWord, &tmp); - - lir::Memory returnAddressDst - (rsp, (frameFootprint - offset + baseSize) * TargetBytesPerWord); - moveRM(&c, TargetBytesPerWord, &tmp, TargetBytesPerWord, + + lir::Memory returnAddressDst( + rsp, (frameFootprint - offset + baseSize) * TargetBytesPerWord); + moveRM(&c, + TargetBytesPerWord, + &tmp, + TargetBytesPerWord, &returnAddressDst); c.client->releaseTemporary(tmp.low); @@ -982,14 +1090,13 @@ class MyAssembler: public Assembler { } lir::Register stack(rsp); - lir::Constant footprint - (resolvedPromise - (&c, (frameFootprint - offset + baseSize) * TargetBytesPerWord)); + lir::Constant footprint(resolvedPromise( + &c, (frameFootprint - offset + baseSize) * TargetBytesPerWord)); addCR(&c, TargetBytesPerWord, &footprint, TargetBytesPerWord, &stack); if (returnAddressSurrogate != lir::NoRegister) { - assert(&c, offset > 0); + assertT(&c, offset > 0); lir::Register ras(returnAddressSurrogate); lir::Memory dst(rsp, offset * TargetBytesPerWord); @@ -997,7 +1104,7 @@ class MyAssembler: public Assembler { } if (framePointerSurrogate != lir::NoRegister) { - assert(&c, offset > 0); + assertT(&c, offset > 0); lir::Register fps(framePointerSurrogate); lir::Memory dst(rsp, (offset - 1) * TargetBytesPerWord); @@ -1016,17 +1123,17 @@ class MyAssembler: public Assembler { { popFrame(frameFootprint); - assert(&c, argumentFootprint >= StackAlignmentInWords); - assert(&c, (argumentFootprint % StackAlignmentInWords) == 0); + assertT(&c, argumentFootprint >= StackAlignmentInWords); + assertT(&c, (argumentFootprint % StackAlignmentInWords) == 0); if (TailCalls and argumentFootprint > StackAlignmentInWords) { lir::Register returnAddress(rcx); popR(&c, TargetBytesPerWord, &returnAddress); lir::Register stack(rsp); - lir::Constant adjustment - (resolvedPromise(&c, (argumentFootprint - StackAlignmentInWords) - * TargetBytesPerWord)); + lir::Constant adjustment(resolvedPromise( + &c, + (argumentFootprint - StackAlignmentInWords) * TargetBytesPerWord)); addCR(&c, TargetBytesPerWord, &adjustment, TargetBytesPerWord, &stack); jumpR(&c, TargetBytesPerWord, &returnAddress); @@ -1050,45 +1157,51 @@ class MyAssembler: public Assembler { jumpR(&c, TargetBytesPerWord, &returnAddress); } - virtual void apply(lir::Operation op) { + virtual void apply(lir::Operation op) + { arch_->c.operations[op](&c); } virtual void apply(lir::UnaryOperation op, OperandInfo a) { - arch_->c.unaryOperations[Multimethod::index(op, a.type)] - (&c, a.size, a.operand); + arch_->c.unaryOperations[Multimethod::index(op, a.type)]( + &c, a.size, a.operand); } virtual void apply(lir::BinaryOperation op, OperandInfo a, OperandInfo b) { - arch_->c.binaryOperations[index(&(arch_->c), op, a.type, b.type)] - (&c, a.size, a.operand, b.size, b.operand); + arch_->c.binaryOperations[index(&(arch_->c), op, a.type, b.type)]( + &c, a.size, a.operand, b.size, b.operand); } - virtual void apply(lir::TernaryOperation op, OperandInfo a, OperandInfo b, OperandInfo c) + virtual void apply(lir::TernaryOperation op, + OperandInfo a, + OperandInfo b, + OperandInfo c) { if (isBranch(op)) { - assert(&this->c, a.size == b.size); - assert(&this->c, c.size == TargetBytesPerWord); - assert(&this->c, c.type == lir::ConstantOperand); + assertT(&this->c, a.size == b.size); + assertT(&this->c, c.size == TargetBytesPerWord); + assertT(&this->c, c.type == lir::ConstantOperand); - arch_->c.branchOperations[branchIndex(&(arch_->c), a.type, b.type)] - (&this->c, op, a.size, a.operand, b.operand, c.operand); + arch_->c.branchOperations[branchIndex(&(arch_->c), a.type, b.type)]( + &this->c, op, a.size, a.operand, b.operand, c.operand); } else { - assert(&this->c, b.size == c.size); - assert(&this->c, b.type == c.type); + assertT(&this->c, b.size == c.size); + assertT(&this->c, b.type == c.type); - arch_->c.binaryOperations[index(&(arch_->c), op, a.type, b.type)] - (&this->c, a.size, a.operand, b.size, b.operand); + arch_->c.binaryOperations[index(&(arch_->c), op, a.type, b.type)]( + &this->c, a.size, a.operand, b.size, b.operand); } } - virtual void setDestination(uint8_t* dst) { + virtual void setDestination(uint8_t* dst) + { c.result = dst; } - virtual void write() { + virtual void write() + { uint8_t* dst = c.result; for (MyBlock* b = c.firstBlock; b; b = b->next) { unsigned index = 0; @@ -1103,10 +1216,9 @@ class MyAssembler: public Assembler { index += size; while ((b->start + index + padding + p->instructionOffset) - % p->alignment) - { + % p->alignment) { *(dst + b->start + index + padding) = 0x90; - ++ padding; + ++padding; } } @@ -1114,40 +1226,46 @@ class MyAssembler: public Assembler { c.code.data.begin() + b->offset + index, b->size - index); } - + for (Task* t = c.tasks; t; t = t->next) { t->run(&c); } } - virtual Promise* offset(bool) { + virtual Promise* offset(bool) + { return x86::offsetPromise(&c); } - virtual Block* endBlock(bool startNew) { + virtual Block* endBlock(bool startNew) + { MyBlock* b = c.lastBlock; b->size = c.code.length() - b->offset; if (startNew) { - c.lastBlock = new(c.zone) MyBlock(c.code.length()); + c.lastBlock = new (c.zone) MyBlock(c.code.length()); } else { c.lastBlock = 0; } return b; } - virtual void endEvent() { + virtual void endEvent() + { // ignore } - virtual unsigned length() { + virtual unsigned length() + { return c.code.length(); } - virtual unsigned footerSize() { + virtual unsigned footerSize() + { return 0; } - virtual void dispose() { + virtual void dispose() + { c.code.dispose(); } @@ -1157,17 +1275,16 @@ class MyAssembler: public Assembler { Assembler* MyArchitecture::makeAssembler(util::Allocator* allocator, Zone* zone) { - return - new(zone) MyAssembler(c.s, allocator, zone, this); + return new (zone) MyAssembler(c.s, allocator, zone, this); } -} // namespace x86 +} // namespace x86 Architecture* makeArchitectureX86(System* system, bool useNativeFeatures) { return new (allocate(system, sizeof(x86::MyArchitecture))) - x86::MyArchitecture(system, useNativeFeatures); + x86::MyArchitecture(system, useNativeFeatures); } -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/block.cpp b/src/codegen/target/x86/block.cpp index a506aac932..39169ee9e9 100644 --- a/src/codegen/target/x86/block.cpp +++ b/src/codegen/target/x86/block.cpp @@ -16,21 +16,29 @@ namespace avian { namespace codegen { namespace x86 { -unsigned -padding(AlignmentPadding* p, unsigned index, unsigned offset, AlignmentPadding* limit); +unsigned padding(AlignmentPadding* p, + unsigned index, + unsigned offset, + AlignmentPadding* limit); -MyBlock::MyBlock(unsigned offset): - next(0), firstPadding(0), lastPadding(0), offset(offset), start(~0), - size(0) -{ } +MyBlock::MyBlock(unsigned offset) + : next(0), + firstPadding(0), + lastPadding(0), + offset(offset), + start(~0), + size(0) +{ +} -unsigned MyBlock::resolve(unsigned start, Assembler::Block* next) { +unsigned MyBlock::resolve(unsigned start, Assembler::Block* next) +{ this->start = start; this->next = static_cast(next); return start + size + padding(firstPadding, start, offset, lastPadding); } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/block.h b/src/codegen/target/x86/block.h index 4099ee8122..36e00f68bf 100644 --- a/src/codegen/target/x86/block.h +++ b/src/codegen/target/x86/block.h @@ -19,7 +19,7 @@ namespace x86 { class AlignmentPadding; -class MyBlock: public Assembler::Block { +class MyBlock : public Assembler::Block { public: MyBlock(unsigned offset); @@ -33,8 +33,8 @@ class MyBlock: public Assembler::Block { unsigned size; }; -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_BLOCK_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_BLOCK_H diff --git a/src/codegen/target/x86/context.cpp b/src/codegen/target/x86/context.cpp index 5bd467a74a..93cdef29cd 100644 --- a/src/codegen/target/x86/context.cpp +++ b/src/codegen/target/x86/context.cpp @@ -18,9 +18,10 @@ namespace avian { namespace codegen { namespace x86 { -ArchitectureContext::ArchitectureContext(vm::System* s, bool useNativeFeatures): - s(s), useNativeFeatures(useNativeFeatures) -{ } +ArchitectureContext::ArchitectureContext(vm::System* s, bool useNativeFeatures) + : s(s), useNativeFeatures(useNativeFeatures) +{ +} Context::Context(vm::System* s, util::Allocator* a, @@ -38,6 +39,6 @@ Context::Context(vm::System* s, { } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/context.h b/src/codegen/target/x86/context.h index ddadf7187f..9a1eb912b8 100644 --- a/src/codegen/target/x86/context.h +++ b/src/codegen/target/x86/context.h @@ -28,13 +28,13 @@ namespace vm { class System; class Allocator; class Zone; -} // namespace vm +} // namespace vm namespace avian { namespace util { class Aborter; -} // namespace util +} // namespace util namespace codegen { namespace x86 { @@ -47,12 +47,18 @@ typedef void (*OperationType)(Context*); typedef void (*UnaryOperationType)(Context*, unsigned, lir::Operand*); -typedef void (*BinaryOperationType) -(Context*, unsigned, lir::Operand*, unsigned, lir::Operand*); +typedef void (*BinaryOperationType)(Context*, + unsigned, + lir::Operand*, + unsigned, + lir::Operand*); -typedef void (*BranchOperationType) -(Context*, lir::TernaryOperation, unsigned, lir::Operand*, - lir::Operand*, lir::Operand*); +typedef void (*BranchOperationType)(Context*, + lir::TernaryOperation, + unsigned, + lir::Operand*, + lir::Operand*, + lir::Operand*); class ArchitectureContext { public: @@ -61,16 +67,14 @@ class ArchitectureContext { vm::System* s; bool useNativeFeatures; OperationType operations[lir::OperationCount]; - UnaryOperationType unaryOperations[lir::UnaryOperationCount - * lir::OperandTypeCount]; + UnaryOperationType + unaryOperations[lir::UnaryOperationCount * lir::OperandTypeCount]; BinaryOperationType binaryOperations - [(lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) - * lir::OperandTypeCount - * lir::OperandTypeCount]; - BranchOperationType branchOperations - [lir::BranchOperationCount - * lir::OperandTypeCount - * lir::OperandTypeCount]; + [(lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) + * lir::OperandTypeCount * lir::OperandTypeCount]; + BranchOperationType branchOperations[lir::BranchOperationCount + * lir::OperandTypeCount + * lir::OperandTypeCount]; }; class Context { @@ -91,16 +95,18 @@ class Context { ArchitectureContext* ac; }; -inline avian::util::Aborter* getAborter(Context* c) { +inline avian::util::Aborter* getAborter(Context* c) +{ return c->s; } -inline avian::util::Aborter* getAborter(ArchitectureContext* c) { +inline avian::util::Aborter* getAborter(ArchitectureContext* c) +{ return c->s; } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_CONTEXT_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_CONTEXT_H diff --git a/src/codegen/target/x86/detect.cpp b/src/codegen/target/x86/detect.cpp index 69ae9f02d2..cfa09cc243 100644 --- a/src/codegen/target/x86/detect.cpp +++ b/src/codegen/target/x86/detect.cpp @@ -17,18 +17,18 @@ namespace avian { namespace codegen { namespace x86 { -extern "C" bool -detectFeature(unsigned ecx, unsigned edx); +extern "C" bool detectFeature(unsigned ecx, unsigned edx); -bool useSSE(ArchitectureContext* c) { +bool useSSE(ArchitectureContext* c) +{ if (vm::TargetBytesPerWord == 8) { // amd64 implies SSE2 support return true; } else if (c->useNativeFeatures) { static int supported = -1; if (supported == -1) { - supported = detectFeature(0, 0x2000000) // SSE 1 - and detectFeature(0, 0x4000000); // SSE 2 + supported = detectFeature(0, 0x2000000) // SSE 1 + and detectFeature(0, 0x4000000); // SSE 2 } return supported; } else { @@ -36,6 +36,6 @@ bool useSSE(ArchitectureContext* c) { } } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/detect.h b/src/codegen/target/x86/detect.h index 2a8a46bbbd..1cccb2fd5a 100644 --- a/src/codegen/target/x86/detect.h +++ b/src/codegen/target/x86/detect.h @@ -21,8 +21,8 @@ class ArchitectureContext; bool useSSE(ArchitectureContext* c); -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_DETECT_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_DETECT_H diff --git a/src/codegen/target/x86/encode.cpp b/src/codegen/target/x86/encode.cpp index 190810d463..f64d91a2c9 100644 --- a/src/codegen/target/x86/encode.cpp +++ b/src/codegen/target/x86/encode.cpp @@ -26,9 +26,8 @@ using namespace avian::util; namespace { -int64_t -signExtend(unsigned size, int64_t v) -{ +int64_t signExtend(unsigned size, int64_t v) +{ if (size == 4) { return static_cast(v); } else if (size == 2) { @@ -40,20 +39,25 @@ signExtend(unsigned size, int64_t v) } } -} // namespace +} // namespace namespace avian { namespace codegen { namespace x86 { - #define REX_W 0x48 #define REX_R 0x44 #define REX_X 0x42 #define REX_B 0x41 #define REX_NONE 0x40 -void maybeRex(Context* c, unsigned size, int a, int index, int base, bool always) { +void maybeRex(Context* c, + unsigned size, + int a, + int index, + int base, + bool always) +{ if (vm::TargetBytesPerWord == 8) { uint8_t byte; if (size == 8) { @@ -61,46 +65,60 @@ void maybeRex(Context* c, unsigned size, int a, int index, int base, bool always } else { byte = REX_NONE; } - if (a != lir::NoRegister and (a & 8)) byte |= REX_R; - if (index != lir::NoRegister and (index & 8)) byte |= REX_X; - if (base != lir::NoRegister and (base & 8)) byte |= REX_B; - if (always or byte != REX_NONE) c->code.append(byte); + if (a != lir::NoRegister and (a & 8)) + byte |= REX_R; + if (index != lir::NoRegister and (index & 8)) + byte |= REX_X; + if (base != lir::NoRegister and (base & 8)) + byte |= REX_B; + if (always or byte != REX_NONE) + c->code.append(byte); } } -void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Register* b) { +void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Register* b) +{ maybeRex(c, size, a->low, lir::NoRegister, b->low, false); } -void alwaysRex(Context* c, unsigned size, lir::Register* a, lir::Register* b) { +void alwaysRex(Context* c, unsigned size, lir::Register* a, lir::Register* b) +{ maybeRex(c, size, a->low, lir::NoRegister, b->low, true); } -void maybeRex(Context* c, unsigned size, lir::Register* a) { +void maybeRex(Context* c, unsigned size, lir::Register* a) +{ maybeRex(c, size, lir::NoRegister, lir::NoRegister, a->low, false); } -void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Memory* b) { +void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Memory* b) +{ maybeRex(c, size, a->low, b->index, b->base, size == 1 and (a->low & 4)); } -void maybeRex(Context* c, unsigned size, lir::Memory* a) { +void maybeRex(Context* c, unsigned size, lir::Memory* a) +{ maybeRex(c, size, lir::NoRegister, a->index, a->base, false); } -void modrm(Context* c, uint8_t mod, int a, int b) { +void modrm(Context* c, uint8_t mod, int a, int b) +{ c->code.append(mod | (regCode(b) << 3) | regCode(a)); } -void modrm(Context* c, uint8_t mod, lir::Register* a, lir::Register* b) { +void modrm(Context* c, uint8_t mod, lir::Register* a, lir::Register* b) +{ modrm(c, mod, a->low, b->low); } -void sib(Context* c, unsigned scale, int index, int base) { - c->code.append((util::log(scale) << 6) | (regCode(index) << 3) | regCode(base)); +void sib(Context* c, unsigned scale, int index, int base) +{ + c->code.append((util::log(scale) << 6) | (regCode(index) << 3) + | regCode(base)); } -void modrmSib(Context* c, int width, int a, int scale, int index, int base) { +void modrmSib(Context* c, int width, int a, int scale, int index, int base) +{ if (index == lir::NoRegister) { modrm(c, width, base, a); if (regCode(base) == rsp) { @@ -112,7 +130,8 @@ void modrmSib(Context* c, int width, int a, int scale, int index, int base) { } } -void modrmSibImm(Context* c, int a, int scale, int index, int base, int offset) { +void modrmSibImm(Context* c, int a, int scale, int index, int base, int offset) +{ if (offset == 0 and regCode(base) != rbp) { modrmSib(c, 0x00, a, scale, index, base); } else if (vm::fitsInInt8(offset)) { @@ -124,38 +143,46 @@ void modrmSibImm(Context* c, int a, int scale, int index, int base, int offset) } } -void modrmSibImm(Context* c, lir::Register* a, lir::Memory* b) { +void modrmSibImm(Context* c, lir::Register* a, lir::Memory* b) +{ modrmSibImm(c, a->low, b->scale, b->index, b->base, b->offset); } -void opcode(Context* c, uint8_t op) { +void opcode(Context* c, uint8_t op) +{ c->code.append(op); } -void opcode(Context* c, uint8_t op1, uint8_t op2) { +void opcode(Context* c, uint8_t op1, uint8_t op2) +{ c->code.append(op1); c->code.append(op2); } -void unconditional(Context* c, unsigned jump, lir::Constant* a) { +void unconditional(Context* c, unsigned jump, lir::Constant* a) +{ appendOffsetTask(c, a->value, offsetPromise(c), 5); opcode(c, jump); c->code.append4(0); } -void conditional(Context* c, unsigned condition, lir::Constant* a) { +void conditional(Context* c, unsigned condition, lir::Constant* a) +{ appendOffsetTask(c, a->value, offsetPromise(c), 6); - + opcode(c, 0x0f, condition); c->code.append4(0); } -void sseMoveRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void sseMoveRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize >= 4); - assert(c, aSize == bSize); + assertT(c, aSize >= 4); + assertT(c, aSize == bSize); if (isFloatReg(a) and isFloatReg(b)) { if (aSize == 4) { @@ -168,34 +195,40 @@ void sseMoveRR(Context* c, unsigned aSize, lir::Register* a, maybeRex(c, 4, b, a); opcode(c, 0x0f, 0x10); modrm(c, 0xc0, a, b); - } + } } else if (isFloatReg(a)) { opcode(c, 0x66); maybeRex(c, aSize, a, b); opcode(c, 0x0f, 0x7e); - modrm(c, 0xc0, b, a); + modrm(c, 0xc0, b, a); } else { opcode(c, 0x66); maybeRex(c, aSize, b, a); opcode(c, 0x0f, 0x6e); - modrm(c, 0xc0, a, b); + modrm(c, 0xc0, a, b); } } -void sseMoveCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void sseMoveCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize <= vm::TargetBytesPerWord); + assertT(c, aSize <= vm::TargetBytesPerWord); lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR2(c, aSize, a, aSize, &tmp, 0); sseMoveRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); } -void sseMoveMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void sseMoveMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize >= 4); + assertT(c, aSize >= 4); if (vm::TargetBytesPerWord == 4 and aSize == 8) { opcode(c, 0xf3); @@ -209,11 +242,14 @@ void sseMoveMR(Context* c, unsigned aSize, lir::Memory* a, } } -void sseMoveRM(Context* c, unsigned aSize, lir::Register* a, - UNUSED unsigned bSize, lir::Memory* b) +void sseMoveRM(Context* c, + unsigned aSize, + lir::Register* a, + UNUSED unsigned bSize, + lir::Memory* b) { - assert(c, aSize >= 4); - assert(c, aSize == bSize); + assertT(c, aSize >= 4); + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { opcode(c, 0x66); @@ -227,7 +263,8 @@ void sseMoveRM(Context* c, unsigned aSize, lir::Register* a, } } -void branch(Context* c, lir::TernaryOperation op, lir::Constant* target) { +void branch(Context* c, lir::TernaryOperation op, lir::Constant* target) +{ switch (op) { case lir::JumpIfEqual: conditional(c, 0x84, target); @@ -258,7 +295,8 @@ void branch(Context* c, lir::TernaryOperation op, lir::Constant* target) { } } -void branchFloat(Context* c, lir::TernaryOperation op, lir::Constant* target) { +void branchFloat(Context* c, lir::TernaryOperation op, lir::Constant* target) +{ switch (op) { case lir::JumpIfFloatEqual: // jp past the je so we don't jump to the target if unordered: @@ -313,8 +351,13 @@ void branchFloat(Context* c, lir::TernaryOperation op, lir::Constant* target) { } } -void floatRegOp(Context* c, unsigned aSize, lir::Register* a, unsigned bSize, - lir::Register* b, uint8_t op, uint8_t mod) +void floatRegOp(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b, + uint8_t op, + uint8_t mod) { if (aSize == 4) { opcode(c, 0xf3); @@ -326,8 +369,12 @@ void floatRegOp(Context* c, unsigned aSize, lir::Register* a, unsigned bSize, modrm(c, mod, a, b); } -void floatMemOp(Context* c, unsigned aSize, lir::Memory* a, unsigned bSize, - lir::Register* b, uint8_t op) +void floatMemOp(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b, + uint8_t op) { if (aSize == 4) { opcode(c, 0xf3); @@ -339,11 +386,18 @@ void floatMemOp(Context* c, unsigned aSize, lir::Memory* a, unsigned bSize, modrmSibImm(c, b, a); } -void moveCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void moveCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void moveCR2(Context* c, UNUSED unsigned aSize, lir::Constant* a, - UNUSED unsigned bSize, lir::Register* b, unsigned promiseOffset) +void moveCR2(Context* c, + UNUSED unsigned aSize, + lir::Constant* a, + UNUSED unsigned bSize, + lir::Register* b, + unsigned promiseOffset) { if (vm::TargetBytesPerWord == 4 and bSize == 8) { int64_t v = signExtend(aSize, a->value->value()); @@ -366,13 +420,13 @@ void moveCR2(Context* c, UNUSED unsigned aSize, lir::Constant* a, } else { expect(c, aSize == vm::TargetBytesPerWord); - appendImmediateTask - (c, a->value, offsetPromise(c), vm::TargetBytesPerWord, promiseOffset); + appendImmediateTask( + c, a->value, offsetPromise(c), vm::TargetBytesPerWord, promiseOffset); c->code.appendTargetAddress(static_cast(0)); } } } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/encode.h b/src/codegen/target/x86/encode.h index 2b067ae2da..564b84f6e9 100644 --- a/src/codegen/target/x86/encode.h +++ b/src/codegen/target/x86/encode.h @@ -25,7 +25,12 @@ namespace x86 { class Context; -void maybeRex(Context* c, unsigned size, int a, int index, int base, bool always); +void maybeRex(Context* c, + unsigned size, + int a, + int index, + int base, + bool always); void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Register* b); @@ -37,15 +42,18 @@ void maybeRex(Context* c, unsigned size, lir::Register* a, lir::Memory* b); void maybeRex(Context* c, unsigned size, lir::Memory* a); -inline int regCode(int a) { +inline int regCode(int a) +{ return a & 7; } -inline int regCode(lir::Register* a) { +inline int regCode(lir::Register* a) +{ return regCode(a->low); } -inline bool isFloatReg(lir::Register* a) { +inline bool isFloatReg(lir::Register* a) +{ return a->low >= xmm0; } @@ -58,7 +66,7 @@ void sib(Context* c, unsigned scale, int index, int base); void modrmSib(Context* c, int width, int a, int scale, int index, int base); void modrmSibImm(Context* c, int a, int scale, int index, int base, int offset); - + void modrmSibImm(Context* c, lir::Register* a, lir::Memory* b); void opcode(Context* c, uint8_t op); @@ -69,33 +77,58 @@ void unconditional(Context* c, unsigned jump, lir::Constant* a); void conditional(Context* c, unsigned condition, lir::Constant* a); -void sseMoveRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void sseMoveRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void sseMoveCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void sseMoveCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void sseMoveMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); +void sseMoveMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void sseMoveRM(Context* c, unsigned aSize, lir::Register* a, - UNUSED unsigned bSize, lir::Memory* b); +void sseMoveRM(Context* c, + unsigned aSize, + lir::Register* a, + UNUSED unsigned bSize, + lir::Memory* b); void branch(Context* c, lir::TernaryOperation op, lir::Constant* target); void branchFloat(Context* c, lir::TernaryOperation op, lir::Constant* target); -void floatRegOp(Context* c, unsigned aSize, lir::Register* a, unsigned bSize, - lir::Register* b, uint8_t op, uint8_t mod = 0xc0); +void floatRegOp(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b, + uint8_t op, + uint8_t mod = 0xc0); -void floatMemOp(Context* c, unsigned aSize, lir::Memory* a, unsigned bSize, - lir::Register* b, uint8_t op); +void floatMemOp(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b, + uint8_t op); -void moveCR2(Context* c, UNUSED unsigned aSize, lir::Constant* a, - UNUSED unsigned bSize, lir::Register* b, unsigned promiseOffset); +void moveCR2(Context* c, + UNUSED unsigned aSize, + lir::Constant* a, + UNUSED unsigned bSize, + lir::Register* b, + unsigned promiseOffset); -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_ENCODE_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_ENCODE_H diff --git a/src/codegen/target/x86/fixup.cpp b/src/codegen/target/x86/fixup.cpp index 7bf1b78a9d..dbf53628e3 100644 --- a/src/codegen/target/x86/fixup.cpp +++ b/src/codegen/target/x86/fixup.cpp @@ -29,39 +29,49 @@ namespace x86 { using namespace util; -ResolvedPromise* resolvedPromise(Context* c, int64_t value) { - return new(c->zone) ResolvedPromise(value); +ResolvedPromise* resolvedPromise(Context* c, int64_t value) +{ + return new (c->zone) ResolvedPromise(value); } -OffsetPromise::OffsetPromise(Context* c, MyBlock* block, unsigned offset, AlignmentPadding* limit): - c(c), block(block), offset(offset), limit(limit), value_(-1) -{ } +OffsetPromise::OffsetPromise(Context* c, + MyBlock* block, + unsigned offset, + AlignmentPadding* limit) + : c(c), block(block), offset(offset), limit(limit), value_(-1) +{ +} -bool OffsetPromise::resolved() { +bool OffsetPromise::resolved() +{ return block->start != static_cast(~0); } -int64_t OffsetPromise::value() { - assert(c, resolved()); +int64_t OffsetPromise::value() +{ + assertT(c, resolved()); if (value_ == -1) { value_ = block->start + (offset - block->offset) - + padding(block->firstPadding, block->start, block->offset, limit); + + padding(block->firstPadding, block->start, block->offset, limit); } return value_; } -Promise* offsetPromise(Context* c) { - return new(c->zone) OffsetPromise(c, c->lastBlock, c->code.length(), c->lastBlock->lastPadding); +Promise* offsetPromise(Context* c) +{ + return new (c->zone) OffsetPromise( + c, c->lastBlock, c->code.length(), c->lastBlock->lastPadding); } -void* -resolveOffset(vm::System* s, uint8_t* instruction, unsigned instructionSize, - int64_t value) +void* resolveOffset(vm::System* s, + uint8_t* instruction, + unsigned instructionSize, + int64_t value) { - intptr_t v = reinterpret_cast(value) - - instruction - instructionSize; - + intptr_t v = reinterpret_cast(value) - instruction + - instructionSize; + expect(s, vm::fitsInInt32(v)); int32_t v4 = v; @@ -69,54 +79,66 @@ resolveOffset(vm::System* s, uint8_t* instruction, unsigned instructionSize, return instruction + instructionSize; } -OffsetListener::OffsetListener(vm::System* s, uint8_t* instruction, - unsigned instructionSize): - s(s), - instruction(instruction), - instructionSize(instructionSize) -{ } +OffsetListener::OffsetListener(vm::System* s, + uint8_t* instruction, + unsigned instructionSize) + : s(s), instruction(instruction), instructionSize(instructionSize) +{ +} -bool OffsetListener::resolve(int64_t value, void** location) { +bool OffsetListener::resolve(int64_t value, void** location) +{ void* p = resolveOffset(s, instruction, instructionSize, value); - if (location) *location = p; + if (location) + *location = p; return false; } -OffsetTask::OffsetTask(Task* next, Promise* promise, Promise* instructionOffset, - unsigned instructionSize): - Task(next), - promise(promise), - instructionOffset(instructionOffset), - instructionSize(instructionSize) -{ } +OffsetTask::OffsetTask(Task* next, + Promise* promise, + Promise* instructionOffset, + unsigned instructionSize) + : Task(next), + promise(promise), + instructionOffset(instructionOffset), + instructionSize(instructionSize) +{ +} -void OffsetTask::run(Context* c) { +void OffsetTask::run(Context* c) +{ if (promise->resolved()) { - resolveOffset - (c->s, c->result + instructionOffset->value(), instructionSize, - promise->value()); + resolveOffset(c->s, + c->result + instructionOffset->value(), + instructionSize, + promise->value()); } else { - new (promise->listen(sizeof(OffsetListener))) - OffsetListener(c->s, c->result + instructionOffset->value(), - instructionSize); + new (promise->listen(sizeof(OffsetListener))) OffsetListener( + c->s, c->result + instructionOffset->value(), instructionSize); } } -void -appendOffsetTask(Context* c, Promise* promise, Promise* instructionOffset, - unsigned instructionSize) +void appendOffsetTask(Context* c, + Promise* promise, + Promise* instructionOffset, + unsigned instructionSize) { - OffsetTask* task = - new(c->zone) OffsetTask(c->tasks, promise, instructionOffset, instructionSize); + OffsetTask* task = new (c->zone) + OffsetTask(c->tasks, promise, instructionOffset, instructionSize); c->tasks = task; } -ImmediateListener::ImmediateListener(vm::System* s, void* dst, unsigned size, unsigned offset): - s(s), dst(dst), size(size), offset(offset) -{ } +ImmediateListener::ImmediateListener(vm::System* s, + void* dst, + unsigned size, + unsigned offset) + : s(s), dst(dst), size(size), offset(offset) +{ +} -void copy(vm::System* s, void* dst, int64_t src, unsigned size) { +void copy(vm::System* s, void* dst, int64_t src, unsigned size) +{ switch (size) { case 4: { int32_t v = src; @@ -128,46 +150,60 @@ void copy(vm::System* s, void* dst, int64_t src, unsigned size) { memcpy(dst, &v, 8); } break; - default: abort(s); + default: + abort(s); } } -bool ImmediateListener::resolve(int64_t value, void** location) { +bool ImmediateListener::resolve(int64_t value, void** location) +{ copy(s, dst, value, size); - if (location) *location = static_cast(dst) + offset; + if (location) + *location = static_cast(dst) + offset; return offset == 0; } -ImmediateTask::ImmediateTask(Task* next, Promise* promise, Promise* offset, unsigned size, - unsigned promiseOffset): - Task(next), - promise(promise), - offset(offset), - size(size), - promiseOffset(promiseOffset) -{ } +ImmediateTask::ImmediateTask(Task* next, + Promise* promise, + Promise* offset, + unsigned size, + unsigned promiseOffset) + : Task(next), + promise(promise), + offset(offset), + size(size), + promiseOffset(promiseOffset) +{ +} -void ImmediateTask::run(Context* c) { +void ImmediateTask::run(Context* c) +{ if (promise->resolved()) { copy(c->s, c->result + offset->value(), promise->value(), size); } else { - new (promise->listen(sizeof(ImmediateListener))) ImmediateListener - (c->s, c->result + offset->value(), size, promiseOffset); + new (promise->listen(sizeof(ImmediateListener))) ImmediateListener( + c->s, c->result + offset->value(), size, promiseOffset); } } -void -appendImmediateTask(Context* c, Promise* promise, Promise* offset, - unsigned size, unsigned promiseOffset) +void appendImmediateTask(Context* c, + Promise* promise, + Promise* offset, + unsigned size, + unsigned promiseOffset) { - c->tasks = new(c->zone) ImmediateTask - (c->tasks, promise, offset, size, promiseOffset); + c->tasks = new (c->zone) + ImmediateTask(c->tasks, promise, offset, size, promiseOffset); } -ShiftMaskPromise* shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask) { - return new(c->zone) ShiftMaskPromise(base, shift, mask); +ShiftMaskPromise* shiftMaskPromise(Context* c, + Promise* base, + unsigned shift, + int64_t mask) +{ + return new (c->zone) ShiftMaskPromise(base, shift, mask); } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/fixup.h b/src/codegen/target/x86/fixup.h index 13d0ac7103..1796ab44e9 100644 --- a/src/codegen/target/x86/fixup.h +++ b/src/codegen/target/x86/fixup.h @@ -31,19 +31,24 @@ ResolvedPromise* resolvedPromise(Context* c, int64_t value); class Task { public: - Task(Task* next): next(next) { } + Task(Task* next) : next(next) + { + } virtual void run(Context* c) = 0; Task* next; }; -class OffsetPromise: public Promise { +class OffsetPromise : public Promise { public: - OffsetPromise(Context* c, MyBlock* block, unsigned offset, AlignmentPadding* limit); + OffsetPromise(Context* c, + MyBlock* block, + unsigned offset, + AlignmentPadding* limit); virtual bool resolved(); - + virtual int64_t value(); Context* c; @@ -55,9 +60,12 @@ class OffsetPromise: public Promise { Promise* offsetPromise(Context* c); -void* resolveOffset(vm::System* s, uint8_t* instruction, unsigned instructionSize, int64_t value); +void* resolveOffset(vm::System* s, + uint8_t* instruction, + unsigned instructionSize, + int64_t value); -class OffsetListener: public Promise::Listener { +class OffsetListener : public Promise::Listener { public: OffsetListener(vm::System* s, uint8_t* instruction, unsigned instructionSize); @@ -68,9 +76,12 @@ class OffsetListener: public Promise::Listener { unsigned instructionSize; }; -class OffsetTask: public Task { +class OffsetTask : public Task { public: - OffsetTask(Task* next, Promise* promise, Promise* instructionOffset, unsigned instructionSize); + OffsetTask(Task* next, + Promise* promise, + Promise* instructionOffset, + unsigned instructionSize); virtual void run(Context* c); @@ -79,9 +90,12 @@ class OffsetTask: public Task { unsigned instructionSize; }; -void appendOffsetTask(Context* c, Promise* promise, Promise* instructionOffset, unsigned instructionSize); +void appendOffsetTask(Context* c, + Promise* promise, + Promise* instructionOffset, + unsigned instructionSize); -class ImmediateListener: public Promise::Listener { +class ImmediateListener : public Promise::Listener { public: ImmediateListener(vm::System* s, void* dst, unsigned size, unsigned offset); @@ -93,9 +107,12 @@ class ImmediateListener: public Promise::Listener { unsigned offset; }; -class ImmediateTask: public Task { +class ImmediateTask : public Task { public: - ImmediateTask(Task* next, Promise* promise, Promise* offset, unsigned size, + ImmediateTask(Task* next, + Promise* promise, + Promise* offset, + unsigned size, unsigned promiseOffset); virtual void run(Context* c); @@ -106,14 +123,19 @@ class ImmediateTask: public Task { unsigned promiseOffset; }; -void -appendImmediateTask(Context* c, Promise* promise, Promise* offset, - unsigned size, unsigned promiseOffset = 0); +void appendImmediateTask(Context* c, + Promise* promise, + Promise* offset, + unsigned size, + unsigned promiseOffset = 0); -ShiftMaskPromise* shiftMaskPromise(Context* c, Promise* base, unsigned shift, int64_t mask); +ShiftMaskPromise* shiftMaskPromise(Context* c, + Promise* base, + unsigned shift, + int64_t mask); -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_FIXUP_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_FIXUP_H diff --git a/src/codegen/target/x86/multimethod.cpp b/src/codegen/target/x86/multimethod.cpp index a71f02c04a..19e6135e1a 100644 --- a/src/codegen/target/x86/multimethod.cpp +++ b/src/codegen/target/x86/multimethod.cpp @@ -26,35 +26,40 @@ namespace x86 { using namespace util; -unsigned index(ArchitectureContext*, lir::BinaryOperation operation, - lir::OperandType operand1, - lir::OperandType operand2) +unsigned index(ArchitectureContext*, + lir::BinaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2) { - return operation - + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) * operand1) - + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) - * lir::OperandTypeCount * operand2); + return operation + ((lir::BinaryOperationCount + + lir::NonBranchTernaryOperationCount) * operand1) + + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) + * lir::OperandTypeCount * operand2); } -unsigned index(ArchitectureContext* c UNUSED, lir::TernaryOperation operation, - lir::OperandType operand1, lir::OperandType operand2) +unsigned index(ArchitectureContext* c UNUSED, + lir::TernaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2) { - assert(c, not isBranch(operation)); + assertT(c, not isBranch(operation)); return lir::BinaryOperationCount + operation - + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) * operand1) - + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) - * lir::OperandTypeCount * operand2); + + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) + * operand1) + + ((lir::BinaryOperationCount + lir::NonBranchTernaryOperationCount) + * lir::OperandTypeCount * operand2); } -unsigned branchIndex(ArchitectureContext* c UNUSED, lir::OperandType operand1, - lir::OperandType operand2) +unsigned branchIndex(ArchitectureContext* c UNUSED, + lir::OperandType operand1, + lir::OperandType operand2) { return operand1 + (lir::OperandTypeCount * operand2); } - -void populateTables(ArchitectureContext* c) { +void populateTables(ArchitectureContext* c) +{ const lir::OperandType C = lir::ConstantOperand; const lir::OperandType A = lir::AddressOperand; const lir::OperandType R = lir::RegisterOperand; @@ -170,6 +175,6 @@ void populateTables(ArchitectureContext* c) { bro[branchIndex(c, R, M)] = CAST_BRANCH(branchRM); } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/multimethod.h b/src/codegen/target/x86/multimethod.h index 58056926b9..e9a4b36de6 100644 --- a/src/codegen/target/x86/multimethod.h +++ b/src/codegen/target/x86/multimethod.h @@ -21,20 +21,24 @@ namespace x86 { class ArchitectureContext; -unsigned index(ArchitectureContext*, lir::BinaryOperation operation, - lir::OperandType operand1, - lir::OperandType operand2); +unsigned index(ArchitectureContext*, + lir::BinaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2); -unsigned index(ArchitectureContext* c UNUSED, lir::TernaryOperation operation, - lir::OperandType operand1, lir::OperandType operand2); +unsigned index(ArchitectureContext* c UNUSED, + lir::TernaryOperation operation, + lir::OperandType operand1, + lir::OperandType operand2); -unsigned branchIndex(ArchitectureContext* c UNUSED, lir::OperandType operand1, - lir::OperandType operand2); +unsigned branchIndex(ArchitectureContext* c UNUSED, + lir::OperandType operand1, + lir::OperandType operand2); void populateTables(ArchitectureContext* c); -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_MULTIMETHOD_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_MULTIMETHOD_H diff --git a/src/codegen/target/x86/operations.cpp b/src/codegen/target/x86/operations.cpp index 8523bdb032..0301cda1eb 100644 --- a/src/codegen/target/x86/operations.cpp +++ b/src/codegen/target/x86/operations.cpp @@ -32,17 +32,22 @@ namespace avian { namespace codegen { namespace x86 { -void return_(Context* c) { +void return_(Context* c) +{ opcode(c, 0xc3); } -void trap(Context* c) { +void trap(Context* c) +{ opcode(c, 0xcc); } -void ignore(Context*) { } +void ignore(Context*) +{ +} -void storeLoadBarrier(Context* c) { +void storeLoadBarrier(Context* c) +{ if (useSSE(c->ac)) { // mfence: c->code.append(0x0f); @@ -57,18 +62,20 @@ void storeLoadBarrier(Context* c) { c->code.append(0x83); c->code.append(0x04); c->code.append(0x24); - c->code.append(0x00); + c->code.append(0x00); } } -void callC(Context* c, unsigned size UNUSED, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void callC(Context* c, unsigned size UNUSED, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); unconditional(c, 0xe8, a); } -void longCallC(Context* c, unsigned size, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void longCallC(Context* c, unsigned size, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); if (vm::TargetBytesPerWord == 8) { lir::Register r(LongJumpRegister); @@ -79,29 +86,33 @@ void longCallC(Context* c, unsigned size, lir::Constant* a) { } } -void jumpR(Context* c, unsigned size UNUSED, lir::Register* a) { - assert(c, size == vm::TargetBytesPerWord); +void jumpR(Context* c, unsigned size UNUSED, lir::Register* a) +{ + assertT(c, size == vm::TargetBytesPerWord); maybeRex(c, 4, a); opcode(c, 0xff, 0xe0 + regCode(a)); } -void jumpC(Context* c, unsigned size UNUSED, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void jumpC(Context* c, unsigned size UNUSED, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); unconditional(c, 0xe9, a); } -void jumpM(Context* c, unsigned size UNUSED, lir::Memory* a) { - assert(c, size == vm::TargetBytesPerWord); - +void jumpM(Context* c, unsigned size UNUSED, lir::Memory* a) +{ + assertT(c, size == vm::TargetBytesPerWord); + maybeRex(c, 4, a); opcode(c, 0xff); modrmSibImm(c, rsp, a->scale, a->index, a->base, a->offset); } -void longJumpC(Context* c, unsigned size, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void longJumpC(Context* c, unsigned size, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); if (vm::TargetBytesPerWord == 8) { lir::Register r(LongJumpRegister); @@ -112,29 +123,33 @@ void longJumpC(Context* c, unsigned size, lir::Constant* a) { } } -void callR(Context* c, unsigned size UNUSED, lir::Register* a) { - assert(c, size == vm::TargetBytesPerWord); +void callR(Context* c, unsigned size UNUSED, lir::Register* a) +{ + assertT(c, size == vm::TargetBytesPerWord); // maybeRex.W has no meaning here so we disable it maybeRex(c, 4, a); opcode(c, 0xff, 0xd0 + regCode(a)); } -void callM(Context* c, unsigned size UNUSED, lir::Memory* a) { - assert(c, size == vm::TargetBytesPerWord); - +void callM(Context* c, unsigned size UNUSED, lir::Memory* a) +{ + assertT(c, size == vm::TargetBytesPerWord); + maybeRex(c, 4, a); opcode(c, 0xff); modrmSibImm(c, rdx, a->scale, a->index, a->base, a->offset); } -void alignedCallC(Context* c, unsigned size, lir::Constant* a) { - new(c->zone) AlignmentPadding(c, 1, 4); +void alignedCallC(Context* c, unsigned size, lir::Constant* a) +{ + new (c->zone) AlignmentPadding(c, 1, 4); callC(c, size, a); } -void alignedLongCallC(Context* c, unsigned size, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void alignedLongCallC(Context* c, unsigned size, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); if (vm::TargetBytesPerWord == 8) { new (c->zone) AlignmentPadding(c, 2, 8); @@ -144,13 +159,15 @@ void alignedLongCallC(Context* c, unsigned size, lir::Constant* a) { } } -void alignedJumpC(Context* c, unsigned size, lir::Constant* a) { +void alignedJumpC(Context* c, unsigned size, lir::Constant* a) +{ new (c->zone) AlignmentPadding(c, 1, 4); jumpC(c, size, a); } -void alignedLongJumpC(Context* c, unsigned size, lir::Constant* a) { - assert(c, size == vm::TargetBytesPerWord); +void alignedLongJumpC(Context* c, unsigned size, lir::Constant* a) +{ + assertT(c, size == vm::TargetBytesPerWord); if (vm::TargetBytesPerWord == 8) { new (c->zone) AlignmentPadding(c, 2, 8); @@ -192,7 +209,7 @@ void popR(Context* c, unsigned size, lir::Register* a) void negateR(Context* c, unsigned size, lir::Register* a) { if (vm::TargetBytesPerWord == 4 and size == 8) { - assert(c, a->low == rax and a->high == rdx); + assertT(c, a->low == rax and a->high == rdx); ResolvedPromise zeroPromise(0); lir::Constant zero(&zeroPromise); @@ -208,16 +225,22 @@ void negateR(Context* c, unsigned size, lir::Register* a) } } -void negateRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED) +void negateRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); negateR(c, aSize, a); } -void moveCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void moveCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { if (isFloatReg(b)) { sseMoveCR(c, aSize, a, bSize, b); @@ -226,38 +249,47 @@ void moveCR(Context* c, unsigned aSize, lir::Constant* a, } } -void moveZCR(Context* c, unsigned aSize UNUSED, lir::Constant* a, - unsigned bSize UNUSED, lir::Register* b) +void moveZCR(Context* c, + unsigned aSize UNUSED, + lir::Constant* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, not isFloatReg(b)); - assert(c, aSize == 2); - assert(c, bSize == vm::TargetBytesPerWord); - assert(c, a->value->resolved()); + assertT(c, not isFloatReg(b)); + assertT(c, aSize == 2); + assertT(c, bSize == vm::TargetBytesPerWord); + assertT(c, a->value->resolved()); maybeRex(c, vm::TargetBytesPerWord, b); opcode(c, 0xb8 + regCode(b)); c->code.appendTargetAddress(static_cast(a->value->value())); } -void swapRR(Context* c, unsigned aSize UNUSED, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void swapRR(Context* c, + unsigned aSize UNUSED, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); - assert(c, aSize == vm::TargetBytesPerWord); - + assertT(c, aSize == bSize); + assertT(c, aSize == vm::TargetBytesPerWord); + alwaysRex(c, aSize, a, b); opcode(c, 0x87); modrm(c, 0xc0, b, a); } -void moveRR(Context* c, unsigned aSize, lir::Register* a, - UNUSED unsigned bSize, lir::Register* b) +void moveRR(Context* c, + unsigned aSize, + lir::Register* a, + UNUSED unsigned bSize, + lir::Register* b) { if (isFloatReg(a) or isFloatReg(b)) { sseMoveRR(c, aSize, a, bSize, b); return; } - + if (vm::TargetBytesPerWord == 4 and aSize == 8 and bSize == 8) { lir::Register ah(a->high); lir::Register bh(b->high); @@ -277,7 +309,7 @@ void moveRR(Context* c, unsigned aSize, lir::Register* a, switch (aSize) { case 1: if (vm::TargetBytesPerWord == 4 and a->low > rbx) { - assert(c, b->low <= rbx); + assertT(c, b->low <= rbx); moveRR(c, vm::TargetBytesPerWord, a, vm::TargetBytesPerWord, b); moveRR(c, 1, b, vm::TargetBytesPerWord, b); @@ -302,9 +334,9 @@ void moveRR(Context* c, unsigned aSize, lir::Register* a, modrm(c, 0xc0, a, b); } else { if (a->low == rax and b->low == rax and b->high == rdx) { - opcode(c, 0x99); //cdq + opcode(c, 0x99); // cdq } else { - assert(c, b->low == rax and b->high == rdx); + assertT(c, b->low == rax and b->high == rdx); moveRR(c, 4, a, 4, b); moveRR(c, 4, b, 8, b); @@ -317,10 +349,10 @@ void moveRR(Context* c, unsigned aSize, lir::Register* a, modrm(c, 0xc0, b, a); } } - break; - + break; + case 8: - if (a->low != b->low){ + if (a->low != b->low) { maybeRex(c, aSize, a, b); opcode(c, 0x89); modrm(c, 0xc0, b, a); @@ -330,14 +362,17 @@ void moveRR(Context* c, unsigned aSize, lir::Register* a, } } -void moveMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b) +void moveMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b) { if (isFloatReg(b)) { sseMoveMR(c, aSize, a, bSize, b); return; } - + switch (aSize) { case 1: maybeRex(c, bSize, b, a); @@ -358,8 +393,8 @@ void moveMR(Context* c, unsigned aSize, lir::Memory* a, modrmSibImm(c, b, a); } else { if (bSize == 8) { - assert(c, b->low == rax and b->high == rdx); - + assertT(c, b->low == rax and b->high == rdx); + moveMR(c, 4, a, 4, b); moveRR(c, 4, b, 8, b); } else { @@ -369,13 +404,13 @@ void moveMR(Context* c, unsigned aSize, lir::Memory* a, } } break; - + case 8: if (vm::TargetBytesPerWord == 4 and bSize == 8) { lir::Memory ah(a->base, a->offset + 4, a->index, a->scale); lir::Register bh(b->high); - moveMR(c, 4, a, 4, b); + moveMR(c, 4, a, 4, b); moveMR(c, 4, &ah, 4, &bh); } else { maybeRex(c, bSize, b, a); @@ -384,20 +419,24 @@ void moveMR(Context* c, unsigned aSize, lir::Memory* a, } break; - default: abort(c); + default: + abort(c); } } -void moveRM(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Memory* b) +void moveRM(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Memory* b) { - assert(c, aSize == bSize); - + assertT(c, aSize == bSize); + if (isFloatReg(a)) { sseMoveRM(c, aSize, a, bSize, b); return; } - + switch (aSize) { case 1: maybeRex(c, bSize, a, b); @@ -423,7 +462,7 @@ void moveRM(Context* c, unsigned aSize, lir::Register* a, modrmSibImm(c, a, b); } break; - + case 8: if (vm::TargetBytesPerWord == 8) { maybeRex(c, bSize, a, b); @@ -433,19 +472,23 @@ void moveRM(Context* c, unsigned aSize, lir::Register* a, lir::Register ah(a->high); lir::Memory bh(b->base, b->offset + 4, b->index, b->scale); - moveRM(c, 4, a, 4, b); + moveRM(c, 4, a, 4, b); moveRM(c, 4, &ah, 4, &bh); } break; - default: abort(c); + default: + abort(c); } } -void moveAR(Context* c, unsigned aSize, lir::Address* a, - unsigned bSize, lir::Register* b) +void moveAR(Context* c, + unsigned aSize, + lir::Address* a, + unsigned bSize, + lir::Register* b) { - assert(c, vm::TargetBytesPerWord == 8 or (aSize == 4 and bSize == 4)); + assertT(c, vm::TargetBytesPerWord == 8 or (aSize == 4 and bSize == 4)); lir::Constant constant(a->address); lir::Memory memory(b->low, 0, -1, 0); @@ -454,8 +497,11 @@ void moveAR(Context* c, unsigned aSize, lir::Address* a, moveMR(c, bSize, &memory, bSize, b); } -void moveCM(Context* c, unsigned aSize UNUSED, lir::Constant* a, - unsigned bSize, lir::Memory* b) +void moveCM(Context* c, + unsigned aSize UNUSED, + lir::Constant* a, + unsigned bSize, + lir::Memory* b) { switch (bSize) { case 1: @@ -493,8 +539,7 @@ void moveCM(Context* c, unsigned aSize UNUSED, lir::Constant* a, modrmSibImm(c, 0, b->scale, b->index, b->base, b->offset); c->code.append4(a->value->value()); } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, 8, a, 8, &tmp); moveRM(c, 8, &tmp, 8, b); c->client->releaseTemporary(tmp.low); @@ -510,12 +555,16 @@ void moveCM(Context* c, unsigned aSize UNUSED, lir::Constant* a, } } break; - default: abort(c); + default: + abort(c); } } -void moveZRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void moveZRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { switch (aSize) { case 2: @@ -524,35 +573,41 @@ void moveZRR(Context* c, unsigned aSize, lir::Register* a, modrm(c, 0xc0, a, b); break; - default: abort(c); + default: + abort(c); } } -void moveZMR(Context* c, unsigned aSize UNUSED, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void moveZMR(Context* c, + unsigned aSize UNUSED, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, bSize == vm::TargetBytesPerWord); - assert(c, aSize == 2); - + assertT(c, bSize == vm::TargetBytesPerWord); + assertT(c, aSize == 2); + maybeRex(c, bSize, b, a); opcode(c, 0x0f, 0xb7); modrmSibImm(c, b->low, a->scale, a->index, a->base, a->offset); } -void addCarryRR(Context* c, unsigned size, lir::Register* a, - lir::Register* b) +void addCarryRR(Context* c, unsigned size, lir::Register* a, lir::Register* b) { - assert(c, vm::TargetBytesPerWord == 8 or size == 4); - + assertT(c, vm::TargetBytesPerWord == 8 or size == 4); + maybeRex(c, size, a, b); opcode(c, 0x11); modrm(c, 0xc0, b, a); } -void addRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void addRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { lir::Register ah(a->high); @@ -567,10 +622,8 @@ void addRR(Context* c, unsigned aSize, lir::Register* a, } } -void addCarryCR(Context* c, unsigned size, lir::Constant* a, - lir::Register* b) +void addCarryCR(Context* c, unsigned size, lir::Constant* a, lir::Register* b) { - int64_t v = a->value->value(); maybeRex(c, size, b); if (vm::fitsInInt8(v)) { @@ -582,10 +635,13 @@ void addCarryCR(Context* c, unsigned size, lir::Constant* a, } } -void addCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void addCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); int64_t v = a->value->value(); if (v) { @@ -611,8 +667,7 @@ void addCR(Context* c, unsigned aSize, lir::Constant* a, c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); addRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); @@ -621,11 +676,13 @@ void addCR(Context* c, unsigned aSize, lir::Constant* a, } } -void subtractBorrowCR(Context* c, unsigned size UNUSED, lir::Constant* a, - lir::Register* b) +void subtractBorrowCR(Context* c, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b) { - assert(c, vm::TargetBytesPerWord == 8 or size == 4); - + assertT(c, vm::TargetBytesPerWord == 8 or size == 4); + int64_t v = a->value->value(); if (vm::fitsInInt8(v)) { opcode(c, 0x83, 0xd8 + regCode(b)); @@ -636,10 +693,13 @@ void subtractBorrowCR(Context* c, unsigned size UNUSED, lir::Constant* a, } } -void subtractCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void subtractCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); int64_t v = a->value->value(); if (v) { @@ -665,8 +725,7 @@ void subtractCR(Context* c, unsigned aSize, lir::Constant* a, c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); subtractRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); @@ -675,21 +734,26 @@ void subtractCR(Context* c, unsigned aSize, lir::Constant* a, } } -void subtractBorrowRR(Context* c, unsigned size, lir::Register* a, - lir::Register* b) +void subtractBorrowRR(Context* c, + unsigned size, + lir::Register* a, + lir::Register* b) { - assert(c, vm::TargetBytesPerWord == 8 or size == 4); - + assertT(c, vm::TargetBytesPerWord == 8 or size == 4); + maybeRex(c, size, a, b); opcode(c, 0x19); modrm(c, 0xc0, b, a); } -void subtractRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void subtractRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); - + assertT(c, aSize == bSize); + if (vm::TargetBytesPerWord == 4 and aSize == 8) { lir::Register ah(a->high); lir::Register bh(b->high); @@ -703,11 +767,13 @@ void subtractRR(Context* c, unsigned aSize, lir::Register* a, } } -void andRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void andRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); - + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { lir::Register ah(a->high); @@ -722,10 +788,13 @@ void andRR(Context* c, unsigned aSize, lir::Register* a, } } -void andCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void andCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); int64_t v = a->value->value(); @@ -751,8 +820,7 @@ void andCR(Context* c, unsigned aSize, lir::Constant* a, c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); andRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); @@ -760,10 +828,13 @@ void andCR(Context* c, unsigned aSize, lir::Constant* a, } } -void orRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void orRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { lir::Register ah(a->high); @@ -778,10 +849,13 @@ void orRR(Context* c, unsigned aSize, lir::Register* a, } } -void orCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void orCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); int64_t v = a->value->value(); if (v) { @@ -804,11 +878,10 @@ void orCR(Context* c, unsigned aSize, lir::Constant* a, c->code.append(v); } else { opcode(c, 0x81, 0xc8 + regCode(b)); - c->code.append4(v); + c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); orRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); @@ -817,8 +890,11 @@ void orCR(Context* c, unsigned aSize, lir::Constant* a, } } -void xorRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void xorRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { if (vm::TargetBytesPerWord == 4 and aSize == 8) { lir::Register ah(a->high); @@ -833,10 +909,13 @@ void xorRR(Context* c, unsigned aSize, lir::Register* a, } } -void xorCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void xorCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); int64_t v = a->value->value(); if (v) { @@ -859,11 +938,10 @@ void xorCR(Context* c, unsigned aSize, lir::Constant* a, c->code.append(v); } else { opcode(c, 0x81, 0xf0 + regCode(b)); - c->code.append4(v); + c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); xorRR(c, aSize, &tmp, bSize, b); c->client->releaseTemporary(tmp.low); @@ -872,17 +950,19 @@ void xorCR(Context* c, unsigned aSize, lir::Constant* a, } } -void multiplyRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void multiplyRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); - + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { - assert(c, b->high == rdx); - assert(c, b->low != rax); - assert(c, a->low != rax); - assert(c, a->high != rax); + assertT(c, b->high == rdx); + assertT(c, b->low != rax); + assertT(c, a->low != rax); + assertT(c, a->high != rax); c->client->save(rax); @@ -893,8 +973,7 @@ void multiplyRR(Context* c, unsigned aSize, lir::Register* a, lir::Register tmp(-1); lir::Register* scratch; if (a->low == b->low) { - tmp.low = c->client->acquireTemporary - (GeneralRegisterMask & ~(1 << rax)); + tmp.low = c->client->acquireTemporary(GeneralRegisterMask & ~(1 << rax)); scratch = &tmp; moveRR(c, 4, b, 4, scratch); } else { @@ -905,10 +984,10 @@ void multiplyRR(Context* c, unsigned aSize, lir::Register* a, multiplyRR(c, 4, &ah, 4, scratch); multiplyRR(c, 4, a, 4, &bh); addRR(c, 4, &bh, 4, scratch); - + // mul a->low,%eax%edx opcode(c, 0xf7, 0xe0 + a->low); - + addRR(c, 4, scratch, 4, &bh); moveRR(c, 4, &axdx, 4, b); @@ -922,23 +1001,29 @@ void multiplyRR(Context* c, unsigned aSize, lir::Register* a, } } -void compareRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void compareRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); - assert(c, aSize <= vm::TargetBytesPerWord); + assertT(c, aSize == bSize); + assertT(c, aSize <= vm::TargetBytesPerWord); maybeRex(c, aSize, a, b); opcode(c, 0x39); - modrm(c, 0xc0, b, a); + modrm(c, 0xc0, b, a); } -void compareCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void compareCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); - assert(c, vm::TargetBytesPerWord == 8 or aSize == 4); - + assertT(c, aSize == bSize); + assertT(c, vm::TargetBytesPerWord == 8 or aSize == 4); + if (a->value->resolved() and vm::fitsInInt32(a->value->value())) { int64_t v = a->value->value(); maybeRex(c, aSize, b); @@ -957,12 +1042,15 @@ void compareCR(Context* c, unsigned aSize, lir::Constant* a, } } -void compareRM(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Memory* b) +void compareRM(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Memory* b) { - assert(c, aSize == bSize); - assert(c, vm::TargetBytesPerWord == 8 or aSize == 4); - + assertT(c, aSize == bSize); + assertT(c, vm::TargetBytesPerWord == 8 or aSize == 4); + if (vm::TargetBytesPerWord == 8 and aSize == 4) { moveRR(c, 4, a, 8, a); } @@ -971,18 +1059,21 @@ void compareRM(Context* c, unsigned aSize, lir::Register* a, modrmSibImm(c, a, b); } -void compareCM(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Memory* b) +void compareCM(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Memory* b) { - assert(c, aSize == bSize); - assert(c, vm::TargetBytesPerWord == 8 or aSize == 4); - - if (a->value->resolved()) { - int64_t v = a->value->value(); + assertT(c, aSize == bSize); + assertT(c, vm::TargetBytesPerWord == 8 or aSize == 4); + + if (a->value->resolved()) { + int64_t v = a->value->value(); maybeRex(c, aSize, b); opcode(c, vm::fitsInInt8(v) ? 0x83 : 0x81); modrmSibImm(c, rdi, b->scale, b->index, b->base, b->offset); - + if (vm::fitsInInt8(v)) { c->code.append(v); } else if (vm::fitsInInt32(v)) { @@ -998,10 +1089,13 @@ void compareCM(Context* c, unsigned aSize, lir::Constant* a, } } -void compareFloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void compareFloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); if (aSize == 8) { opcode(c, 0x66); @@ -1011,79 +1105,83 @@ void compareFloatRR(Context* c, unsigned aSize, lir::Register* a, modrm(c, 0xc0, a, b); } -void branchLong(Context* c, lir::TernaryOperation op, lir::Operand* al, - lir::Operand* ah, lir::Operand* bl, - lir::Operand* bh, lir::Constant* target, - BinaryOperationType compare) +void branchLong(Context* c, + lir::TernaryOperation op, + lir::Operand* al, + lir::Operand* ah, + lir::Operand* bl, + lir::Operand* bh, + lir::Constant* target, + BinaryOperationType compare) { compare(c, 4, ah, 4, bh); - + unsigned next = 0; switch (op) { case lir::JumpIfEqual: - opcode(c, 0x75); // jne + opcode(c, 0x75); // jne next = c->code.length(); c->code.append(0); compare(c, 4, al, 4, bl); - conditional(c, 0x84, target); // je + conditional(c, 0x84, target); // je break; case lir::JumpIfNotEqual: - conditional(c, 0x85, target); // jne + conditional(c, 0x85, target); // jne compare(c, 4, al, 4, bl); - conditional(c, 0x85, target); // jne + conditional(c, 0x85, target); // jne break; case lir::JumpIfLess: - conditional(c, 0x8c, target); // jl + conditional(c, 0x8c, target); // jl - opcode(c, 0x7f); // jg + opcode(c, 0x7f); // jg next = c->code.length(); c->code.append(0); compare(c, 4, al, 4, bl); - conditional(c, 0x82, target); // jb + conditional(c, 0x82, target); // jb break; case lir::JumpIfGreater: - conditional(c, 0x8f, target); // jg + conditional(c, 0x8f, target); // jg - opcode(c, 0x7c); // jl + opcode(c, 0x7c); // jl next = c->code.length(); c->code.append(0); compare(c, 4, al, 4, bl); - conditional(c, 0x87, target); // ja + conditional(c, 0x87, target); // ja break; case lir::JumpIfLessOrEqual: - conditional(c, 0x8c, target); // jl + conditional(c, 0x8c, target); // jl - opcode(c, 0x7f); // jg + opcode(c, 0x7f); // jg next = c->code.length(); c->code.append(0); compare(c, 4, al, 4, bl); - conditional(c, 0x86, target); // jbe + conditional(c, 0x86, target); // jbe break; case lir::JumpIfGreaterOrEqual: - conditional(c, 0x8f, target); // jg + conditional(c, 0x8f, target); // jg - opcode(c, 0x7c); // jl + opcode(c, 0x7c); // jl next = c->code.length(); c->code.append(0); compare(c, 4, al, 4, bl); - conditional(c, 0x83, target); // jae + conditional(c, 0x83, target); // jae break; default: abort(c); - } + } if (next) { int8_t nextOffset = c->code.length() - next - 1; @@ -1091,9 +1189,12 @@ void branchLong(Context* c, lir::TernaryOperation op, lir::Operand* al, } } -void branchRR(Context* c, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Register* b, - lir::Constant* target) +void branchRR(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Constant* target) { if (isFloatBranch(op)) { compareFloatRR(c, size, a, size, b); @@ -1109,21 +1210,24 @@ void branchRR(Context* c, lir::TernaryOperation op, unsigned size, } } -void branchCR(Context* c, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Register* b, - lir::Constant* target) +void branchCR(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Constant* target) { - assert(c, not isFloatBranch(op)); + assertT(c, not isFloatBranch(op)); if (size > vm::TargetBytesPerWord) { int64_t v = a->value->value(); ResolvedPromise low(v & ~static_cast(0)); lir::Constant al(&low); - + ResolvedPromise high((v >> 32) & ~static_cast(0)); lir::Constant ah(&high); - + lir::Register bh(b->high); branchLong(c, op, &al, &ah, b, &bh, target, CAST2(compareCR)); @@ -1133,37 +1237,46 @@ void branchCR(Context* c, lir::TernaryOperation op, unsigned size, } } -void branchRM(Context* c, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Memory* b, - lir::Constant* target) +void branchRM(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Memory* b, + lir::Constant* target) { - assert(c, not isFloatBranch(op)); - assert(c, size <= vm::TargetBytesPerWord); + assertT(c, not isFloatBranch(op)); + assertT(c, size <= vm::TargetBytesPerWord); compareRM(c, size, a, size, b); branch(c, op, target); } -void branchCM(Context* c, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Memory* b, - lir::Constant* target) +void branchCM(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Memory* b, + lir::Constant* target) { - assert(c, not isFloatBranch(op)); - assert(c, size <= vm::TargetBytesPerWord); + assertT(c, not isFloatBranch(op)); + assertT(c, size <= vm::TargetBytesPerWord); compareCM(c, size, a, size, b); branch(c, op, target); } -void multiplyCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void multiplyCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); if (vm::TargetBytesPerWord == 4 and aSize == 8) { const uint32_t mask = GeneralRegisterMask & ~((1 << rax) | (1 << rdx)); lir::Register tmp(c->client->acquireTemporary(mask), - c->client->acquireTemporary(mask)); + c->client->acquireTemporary(mask)); moveCR(c, aSize, a, aSize, &tmp); multiplyRR(c, aSize, &tmp, bSize, b); @@ -1181,47 +1294,52 @@ void multiplyCR(Context* c, unsigned aSize, lir::Constant* a, } else { opcode(c, 0x69); modrm(c, 0xc0, b, b); - c->code.append4(v); + c->code.append4(v); } } else { - lir::Register tmp - (c->client->acquireTemporary(GeneralRegisterMask)); + lir::Register tmp(c->client->acquireTemporary(GeneralRegisterMask)); moveCR(c, aSize, a, aSize, &tmp); multiplyRR(c, aSize, &tmp, bSize, b); - c->client->releaseTemporary(tmp.low); + c->client->releaseTemporary(tmp.low); } } } } -void divideRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED) +void divideRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); - assert(c, b->low == rax); - assert(c, a->low != rdx); + assertT(c, b->low == rax); + assertT(c, a->low != rdx); c->client->save(rdx); - maybeRex(c, aSize, a, b); - opcode(c, 0x99); // cdq + maybeRex(c, aSize, a, b); + opcode(c, 0x99); // cdq maybeRex(c, aSize, b, a); opcode(c, 0xf7, 0xf8 + regCode(a)); } -void remainderRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void remainderRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, aSize == bSize); + assertT(c, aSize == bSize); - assert(c, b->low == rax); - assert(c, a->low != rdx); + assertT(c, b->low == rax); + assertT(c, a->low != rdx); c->client->save(rdx); - maybeRex(c, aSize, a, b); - opcode(c, 0x99); // cdq + maybeRex(c, aSize, a, b); + opcode(c, 0x99); // cdq maybeRex(c, aSize, b, a); opcode(c, 0xf7, 0xf8 + regCode(a)); @@ -1229,11 +1347,17 @@ void remainderRR(Context* c, unsigned aSize, lir::Register* a, moveRR(c, vm::TargetBytesPerWord, &dx, vm::TargetBytesPerWord, b); } -void doShift(Context* c, UNUSED void (*shift) - (Context*, unsigned, lir::Register*, unsigned, - lir::Register*), - int type, UNUSED unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void doShift(Context* c, + UNUSED void (*shift)(Context*, + unsigned, + lir::Register*, + unsigned, + lir::Register*), + int type, + UNUSED unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { int64_t v = a->value->value(); @@ -1258,8 +1382,11 @@ void doShift(Context* c, UNUSED void (*shift) } } -void shiftLeftRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void shiftLeftRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { if (vm::TargetBytesPerWord == 4 and bSize == 8) { lir::Register cx(rcx); @@ -1280,31 +1407,37 @@ void shiftLeftRR(Context* c, UNUSED unsigned aSize, lir::Register* a, ResolvedPromise promise(32); lir::Constant constant(&promise); - compareCR(c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, - &cx); + compareCR( + c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, &cx); - opcode(c, 0x7c); //jl + opcode(c, 0x7c); // jl c->code.append(2 + 2); lir::Register bh(b->high); - moveRR(c, 4, b, 4, &bh); // 2 bytes - xorRR(c, 4, b, 4, b); // 2 bytes + moveRR(c, 4, b, 4, &bh); // 2 bytes + xorRR(c, 4, b, 4, b); // 2 bytes } else { - assert(c, a->low == rcx); + assertT(c, a->low == rcx); maybeRex(c, bSize, a, b); opcode(c, 0xd3, 0xe0 + regCode(b)); } } -void shiftLeftCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void shiftLeftCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { doShift(c, shiftLeftRR, 0xe0, aSize, a, bSize, b); } -void shiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void shiftRightRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { if (vm::TargetBytesPerWord == 4 and bSize == 8) { lir::Register cx(rcx); @@ -1325,34 +1458,40 @@ void shiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, ResolvedPromise promise(32); lir::Constant constant(&promise); - compareCR(c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, - &cx); + compareCR( + c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, &cx); - opcode(c, 0x7c); //jl + opcode(c, 0x7c); // jl c->code.append(2 + 3); lir::Register bh(b->high); - moveRR(c, 4, &bh, 4, b); // 2 bytes + moveRR(c, 4, &bh, 4, b); // 2 bytes // sar 31,high opcode(c, 0xc1, 0xf8 + b->high); c->code.append(31); } else { - assert(c, a->low == rcx); + assertT(c, a->low == rcx); maybeRex(c, bSize, a, b); opcode(c, 0xd3, 0xf8 + regCode(b)); } } -void shiftRightCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b) +void shiftRightCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { doShift(c, shiftRightRR, 0xf8, aSize, a, bSize, b); } -void unsignedShiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void unsignedShiftRightRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { if (vm::TargetBytesPerWord == 4 and bSize == 8) { lir::Register cx(rcx); @@ -1373,133 +1512,187 @@ void unsignedShiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, ResolvedPromise promise(32); lir::Constant constant(&promise); - compareCR(c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, - &cx); + compareCR( + c, vm::TargetBytesPerWord, &constant, vm::TargetBytesPerWord, &cx); - opcode(c, 0x7c); //jl + opcode(c, 0x7c); // jl c->code.append(2 + 2); lir::Register bh(b->high); - moveRR(c, 4, &bh, 4, b); // 2 bytes - xorRR(c, 4, &bh, 4, &bh); // 2 bytes + moveRR(c, 4, &bh, 4, b); // 2 bytes + xorRR(c, 4, &bh, 4, &bh); // 2 bytes } else { - assert(c, a->low == rcx); + assertT(c, a->low == rcx); maybeRex(c, bSize, a, b); opcode(c, 0xd3, 0xe8 + regCode(b)); } } -void unsignedShiftRightCR(Context* c, unsigned aSize UNUSED, lir::Constant* a, - unsigned bSize, lir::Register* b) +void unsignedShiftRightCR(Context* c, + unsigned aSize UNUSED, + lir::Constant* a, + unsigned bSize, + lir::Register* b) { doShift(c, unsignedShiftRightRR, 0xe8, aSize, a, bSize, b); } -void floatSqrtRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatSqrtRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x51); } -void floatSqrtMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void floatSqrtMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x51); } -void floatAddRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatAddRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x58); } -void floatAddMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void floatAddMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x58); } -void floatSubtractRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatSubtractRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x5c); } -void floatSubtractMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void floatSubtractMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x5c); } -void floatMultiplyRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatMultiplyRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x59); } -void floatMultiplyMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void floatMultiplyMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x59); } -void floatDivideRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatDivideRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x5e); } -void floatDivideMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void floatDivideMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x5e); } -void float2FloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void float2FloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { floatRegOp(c, aSize, a, 4, b, 0x5a); } -void float2FloatMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b) +void float2FloatMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b) { floatMemOp(c, aSize, a, 4, b, 0x5a); } -void float2IntRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void float2IntRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { - assert(c, not isFloatReg(b)); + assertT(c, not isFloatReg(b)); floatRegOp(c, aSize, a, bSize, b, 0x2c); } -void float2IntMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b) +void float2IntMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b) { floatMemOp(c, aSize, a, bSize, b, 0x2c); } -void int2FloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b) +void int2FloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b) { floatRegOp(c, bSize, a, aSize, b, 0x2a); } -void int2FloatMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b) +void int2FloatMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b) { floatMemOp(c, bSize, a, aSize, b, 0x2a); } -void floatNegateRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatNegateRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, isFloatReg(a) and isFloatReg(b)); + assertT(c, isFloatReg(a) and isFloatReg(b)); // unlike most of the other floating point code, this does NOT // support doubles: - assert(c, aSize == 4); + assertT(c, aSize == 4); ResolvedPromise pcon(0x80000000); lir::Constant con(&pcon); if (a->low == b->low) { @@ -1511,20 +1704,24 @@ void floatNegateRR(Context* c, unsigned aSize, lir::Register* a, c->client->releaseTemporary(tmp.low); } else { moveCR(c, 4, &con, 4, b); - if (aSize == 8) opcode(c, 0x66); + if (aSize == 8) + opcode(c, 0x66); maybeRex(c, 4, a, b); opcode(c, 0x0f, 0x57); modrm(c, 0xc0, a, b); } } -void floatAbsoluteRR(Context* c, unsigned aSize UNUSED, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b) +void floatAbsoluteRR(Context* c, + unsigned aSize UNUSED, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b) { - assert(c, isFloatReg(a) and isFloatReg(b)); + assertT(c, isFloatReg(a) and isFloatReg(b)); // unlike most of the other floating point code, this does NOT // support doubles: - assert(c, aSize == 4); + assertT(c, aSize == 4); ResolvedPromise pcon(0x7fffffff); lir::Constant con(&pcon); if (a->low == b->low) { @@ -1542,12 +1739,14 @@ void floatAbsoluteRR(Context* c, unsigned aSize UNUSED, lir::Register* a, } } -void absoluteRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED) +void absoluteRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED) { - assert(c, aSize == bSize and a->low == rax and b->low == rax); - lir::Register d - (c->client->acquireTemporary(static_cast(1) << rdx)); + assertT(c, aSize == bSize and a->low == rax and b->low == rax); + lir::Register d(c->client->acquireTemporary(static_cast(1) << rdx)); maybeRex(c, aSize, a, b); opcode(c, 0x99); xorRR(c, aSize, &d, aSize, a); @@ -1555,6 +1754,6 @@ void absoluteRR(Context* c, unsigned aSize, lir::Register* a, c->client->releaseTemporary(rdx); } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/operations.h b/src/codegen/target/x86/operations.h index 770c8cea7f..80f985f042 100644 --- a/src/codegen/target/x86/operations.h +++ b/src/codegen/target/x86/operations.h @@ -59,212 +59,401 @@ void popR(Context* c, unsigned size, lir::Register* a); void negateR(Context* c, unsigned size, lir::Register* a); -void negateRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED); +void negateRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED); -void moveCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void moveCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void moveZCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void moveZCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void swapRR(Context* c, unsigned aSize UNUSED, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void swapRR(Context* c, + unsigned aSize UNUSED, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void moveRR(Context* c, unsigned aSize, lir::Register* a, - UNUSED unsigned bSize, lir::Register* b); +void moveRR(Context* c, + unsigned aSize, + lir::Register* a, + UNUSED unsigned bSize, + lir::Register* b); -void moveMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b); +void moveMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b); -void moveRM(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Memory* b); +void moveRM(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Memory* b); -void moveAR(Context* c, unsigned aSize, lir::Address* a, - unsigned bSize, lir::Register* b); +void moveAR(Context* c, + unsigned aSize, + lir::Address* a, + unsigned bSize, + lir::Register* b); -void moveCM(Context* c, unsigned aSize UNUSED, lir::Constant* a, - unsigned bSize, lir::Memory* b); +void moveCM(Context* c, + unsigned aSize UNUSED, + lir::Constant* a, + unsigned bSize, + lir::Memory* b); -void moveZRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void moveZRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void moveZMR(Context* c, unsigned aSize UNUSED, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); +void moveZMR(Context* c, + unsigned aSize UNUSED, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void addCarryRR(Context* c, unsigned size, lir::Register* a, +void addCarryRR(Context* c, unsigned size, lir::Register* a, lir::Register* b); + +void addRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, lir::Register* b); -void addRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void addCarryCR(Context* c, unsigned size, lir::Constant* a, lir::Register* b); -void addCarryCR(Context* c, unsigned size, lir::Constant* a, +void addCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, lir::Register* b); -void addCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void subtractBorrowCR(Context* c, + unsigned size UNUSED, + lir::Constant* a, + lir::Register* b); -void subtractBorrowCR(Context* c, unsigned size UNUSED, lir::Constant* a, +void subtractCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void subtractBorrowRR(Context* c, + unsigned size, + lir::Register* a, + lir::Register* b); + +void subtractRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void andRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void andCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void orRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void orCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void xorRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void xorCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void multiplyRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void compareRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void compareCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void compareRM(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Memory* b); + +void compareCM(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Memory* b); + +void compareFloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); + +void branchLong(Context* c, + lir::TernaryOperation op, + lir::Operand* al, + lir::Operand* ah, + lir::Operand* bl, + lir::Operand* bh, + lir::Constant* target, + BinaryOperationType compare); + +void branchRR(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Register* b, + lir::Constant* target); + +void branchCR(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Register* b, + lir::Constant* target); + +void branchRM(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Register* a, + lir::Memory* b, + lir::Constant* target); + +void branchCM(Context* c, + lir::TernaryOperation op, + unsigned size, + lir::Constant* a, + lir::Memory* b, + lir::Constant* target); + +void multiplyCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); + +void divideRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED); + +void remainderRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, lir::Register* b); -void subtractCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void doShift(Context* c, + UNUSED void (*shift)(Context*, + unsigned, + lir::Register*, + unsigned, + lir::Register*), + int type, + UNUSED unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void subtractBorrowRR(Context* c, unsigned size, lir::Register* a, +void shiftLeftRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, lir::Register* b); -void subtractRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void shiftLeftCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void andRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void shiftRightRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b); -void andCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void shiftRightCR(Context* c, + unsigned aSize, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void orRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void unsignedShiftRightRR(Context* c, + UNUSED unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b); -void orCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void unsignedShiftRightCR(Context* c, + unsigned aSize UNUSED, + lir::Constant* a, + unsigned bSize, + lir::Register* b); -void xorRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void floatSqrtRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void xorCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void floatSqrtMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void multiplyRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void floatAddRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void floatAddMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void floatSubtractRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareRM(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Memory* b); +void floatSubtractMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareCM(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Memory* b); +void floatMultiplyRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void compareFloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void floatMultiplyMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void branchLong(Context* c, lir::TernaryOperation op, lir::Operand* al, - lir::Operand* ah, lir::Operand* bl, - lir::Operand* bh, lir::Constant* target, - BinaryOperationType compare); +void floatDivideRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void branchRR(Context* c, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Register* b, - lir::Constant* target); +void floatDivideMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void branchCR(Context* c, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Register* b, - lir::Constant* target); +void float2FloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void branchRM(Context* c, lir::TernaryOperation op, unsigned size, - lir::Register* a, lir::Memory* b, - lir::Constant* target); +void float2FloatMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize UNUSED, + lir::Register* b); -void branchCM(Context* c, lir::TernaryOperation op, unsigned size, - lir::Constant* a, lir::Memory* b, - lir::Constant* target); +void float2IntRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b); -void multiplyCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void float2IntMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b); -void divideRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED); +void int2FloatRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize, + lir::Register* b); -void remainderRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); +void int2FloatMR(Context* c, + unsigned aSize, + lir::Memory* a, + unsigned bSize, + lir::Register* b); -void doShift(Context* c, UNUSED void (*shift) - (Context*, unsigned, lir::Register*, unsigned, - lir::Register*), - int type, UNUSED unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void floatNegateRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void shiftLeftRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); +void floatAbsoluteRR(Context* c, + unsigned aSize UNUSED, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b); -void shiftLeftCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); +void absoluteRR(Context* c, + unsigned aSize, + lir::Register* a, + unsigned bSize UNUSED, + lir::Register* b UNUSED); -void shiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); +} // namespace x86 +} // namespace codegen +} // namespace avian -void shiftRightCR(Context* c, unsigned aSize, lir::Constant* a, - unsigned bSize, lir::Register* b); - -void unsignedShiftRightRR(Context* c, UNUSED unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); - -void unsignedShiftRightCR(Context* c, unsigned aSize UNUSED, lir::Constant* a, - unsigned bSize, lir::Register* b); - -void floatSqrtRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatSqrtMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatAddRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatAddMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatSubtractRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatSubtractMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatMultiplyRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatMultiplyMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatDivideRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatDivideMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void float2FloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void float2FloatMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize UNUSED, lir::Register* b); - -void float2IntRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); - -void float2IntMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b); - -void int2FloatRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize, lir::Register* b); - -void int2FloatMR(Context* c, unsigned aSize, lir::Memory* a, - unsigned bSize, lir::Register* b); - -void floatNegateRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void floatAbsoluteRR(Context* c, unsigned aSize UNUSED, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b); - -void absoluteRR(Context* c, unsigned aSize, lir::Register* a, - unsigned bSize UNUSED, lir::Register* b UNUSED); - -} // namespace x86 -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_OPERATIONS_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_OPERATIONS_H diff --git a/src/codegen/target/x86/padding.cpp b/src/codegen/target/x86/padding.cpp index 330a1debc1..dcd0c83df4 100644 --- a/src/codegen/target/x86/padding.cpp +++ b/src/codegen/target/x86/padding.cpp @@ -18,12 +18,14 @@ namespace avian { namespace codegen { namespace x86 { -AlignmentPadding::AlignmentPadding(Context* c, unsigned instructionOffset, unsigned alignment): - offset(c->code.length()), - instructionOffset(instructionOffset), - alignment(alignment), - next(0), - padding(-1) +AlignmentPadding::AlignmentPadding(Context* c, + unsigned instructionOffset, + unsigned alignment) + : offset(c->code.length()), + instructionOffset(instructionOffset), + alignment(alignment), + next(0), + padding(-1) { if (c->lastBlock->firstPadding) { c->lastBlock->lastPadding->next = this; @@ -33,9 +35,10 @@ AlignmentPadding::AlignmentPadding(Context* c, unsigned instructionOffset, unsig c->lastBlock->lastPadding = this; } -unsigned -padding(AlignmentPadding* p, unsigned start, unsigned offset, - AlignmentPadding* limit) +unsigned padding(AlignmentPadding* p, + unsigned start, + unsigned offset, + AlignmentPadding* limit) { unsigned padding = 0; if (limit) { @@ -44,14 +47,14 @@ padding(AlignmentPadding* p, unsigned start, unsigned offset, if (p->padding == -1) { unsigned index = p->offset - offset; while ((start + index + padding + p->instructionOffset) - % p->alignment) - { - ++ padding; + % p->alignment) { + ++padding; } - + p->padding = padding; - if (p == limit) break; + if (p == limit) + break; } else { padding = p->padding; } @@ -63,6 +66,6 @@ padding(AlignmentPadding* p, unsigned start, unsigned offset, return padding; } -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian diff --git a/src/codegen/target/x86/padding.h b/src/codegen/target/x86/padding.h index f7bef3ccf8..625b3008e0 100644 --- a/src/codegen/target/x86/padding.h +++ b/src/codegen/target/x86/padding.h @@ -28,12 +28,13 @@ class AlignmentPadding { int padding; }; -unsigned -padding(AlignmentPadding* p, unsigned start, unsigned offset, - AlignmentPadding* limit); +unsigned padding(AlignmentPadding* p, + unsigned start, + unsigned offset, + AlignmentPadding* limit); -} // namespace x86 -} // namespace codegen -} // namespace avian +} // namespace x86 +} // namespace codegen +} // namespace avian -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_PADDING_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_PADDING_H diff --git a/src/codegen/target/x86/registers.h b/src/codegen/target/x86/registers.h index 54af5a18ec..b61e521b7c 100644 --- a/src/codegen/target/x86/registers.h +++ b/src/codegen/target/x86/registers.h @@ -55,13 +55,14 @@ enum { const int LongJumpRegister = r10; -const unsigned GeneralRegisterMask = vm::TargetBytesPerWord == 4 ? 0x000000ff : 0x0000ffff; +const unsigned GeneralRegisterMask = vm::TargetBytesPerWord == 4 ? 0x000000ff + : 0x0000ffff; -const unsigned FloatRegisterMask = vm::TargetBytesPerWord == 4 ? 0x00ff0000 : 0xffff0000; +const unsigned FloatRegisterMask = vm::TargetBytesPerWord == 4 ? 0x00ff0000 + : 0xffff0000; +} // namespace x86 +} // namespace codegen +} // namespace avian -} // namespace x86 -} // namespace codegen -} // namespace avian - -#endif // AVIAN_CODEGEN_ASSEMBLER_X86_REGISTERS_H +#endif // AVIAN_CODEGEN_ASSEMBLER_X86_REGISTERS_H diff --git a/src/codegen/targets.cpp b/src/codegen/targets.cpp index b4aaa99a51..e981e8a497 100644 --- a/src/codegen/targets.cpp +++ b/src/codegen/targets.cpp @@ -17,22 +17,25 @@ namespace avian { namespace codegen { -Architecture* makeArchitectureNative(vm::System* system, bool useNativeFeatures UNUSED) { +Architecture* makeArchitectureNative(vm::System* system, + bool useNativeFeatures UNUSED) +{ #ifndef AVIAN_TARGET_ARCH - #error "Must specify native target!" +#error "Must specify native target!" #endif #if AVIAN_TARGET_ARCH == AVIAN_ARCH_UNKNOWN system->abort(); return 0; -#elif (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86) || (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86_64) +#elif(AVIAN_TARGET_ARCH == AVIAN_ARCH_X86) \ + || (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86_64) return makeArchitectureX86(system, useNativeFeatures); #elif AVIAN_TARGET_ARCH == AVIAN_ARCH_ARM return makeArchitectureArm(system, useNativeFeatures); #else - #error "Unsupported codegen target" +#error "Unsupported codegen target" #endif } -} // namespace codegen -} // namespace avian +} // namespace codegen +} // namespace avian diff --git a/src/compile.cpp b/src/compile.cpp index e81323a2b0..7a546feb3a 100644 --- a/src/compile.cpp +++ b/src/compile.cpp @@ -31,20 +31,23 @@ using namespace vm; -extern "C" uint64_t -vmInvoke(void* thread, void* function, void* arguments, - unsigned argumentFootprint, unsigned frameSize, unsigned returnType); +extern "C" uint64_t vmInvoke(void* thread, + void* function, + void* arguments, + unsigned argumentFootprint, + unsigned frameSize, + unsigned returnType); -extern "C" void -vmInvoke_returnAddress(); +extern "C" void vmInvoke_returnAddress(); -extern "C" void -vmInvoke_safeStack(); +extern "C" void vmInvoke_safeStack(); -extern "C" void -vmJumpAndInvoke(void* thread, void* function, void* stack, - unsigned argumentFootprint, uintptr_t* arguments, - unsigned frameSize); +extern "C" void vmJumpAndInvoke(void* thread, + void* function, + void* stack, + unsigned argumentFootprint, + uintptr_t* arguments, + unsigned frameSize); using namespace avian::codegen; using namespace avian::system; @@ -74,18 +77,6 @@ const unsigned InitialZoneCapacityInBytes = 64 * 1024; const unsigned ExecutableAreaSizeInBytes = 30 * 1024 * 1024; -enum Root { - CallTable, - MethodTree, - MethodTreeSentinal, - ObjectPools, - StaticTableArray, - VirtualThunks, - ReceiveMethod, - WindMethod, - RewindMethod -}; - enum ThunkIndex { compileMethodIndex, compileVirtualMethodIndex, @@ -96,46 +87,42 @@ enum ThunkIndex { #define THUNK(s) s##Index, #include "thunks.cpp" #undef THUNK - dummyIndex }; -const unsigned RootCount = RewindMethod + 1; - -inline bool -isVmInvokeUnsafeStack(void* ip) +inline bool isVmInvokeUnsafeStack(void* ip) { return reinterpret_cast(ip) - >= reinterpret_cast(voidPointer(vmInvoke_returnAddress)) - and reinterpret_cast(ip) - < reinterpret_cast (voidPointer(vmInvoke_safeStack)); + >= reinterpret_cast(voidPointer(vmInvoke_returnAddress)) + and reinterpret_cast(ip) + < reinterpret_cast(voidPointer(vmInvoke_safeStack)); } class MyThread; -void* -getIp(MyThread*); +void* getIp(MyThread*); -class MyThread: public Thread { +class MyThread : public Thread { public: class CallTrace { public: - CallTrace(MyThread* t, object method): - t(t), - ip(getIp(t)), - stack(t->stack), - scratch(t->scratch), - continuation(t->continuation), - nativeMethod((methodFlags(t, method) & ACC_NATIVE) ? method : 0), - targetMethod(0), - originalMethod(method), - next(t->trace) + CallTrace(MyThread* t, GcMethod* method) + : t(t), + ip(getIp(t)), + stack(t->stack), + scratch(t->scratch), + continuation(t->continuation), + nativeMethod((method->flags() & ACC_NATIVE) ? method : 0), + targetMethod(0), + originalMethod(method), + next(t->trace) { doTransition(t, 0, 0, 0, this); } - ~CallTrace() { - assert(t, t->stack == 0); + ~CallTrace() + { + assertT(t, t->stack == 0); t->scratch = scratch; @@ -146,68 +133,78 @@ class MyThread: public Thread { void* ip; void* stack; void* scratch; - object continuation; - object nativeMethod; - object targetMethod; - object originalMethod; + GcContinuation* continuation; + GcMethod* nativeMethod; + GcMethod* targetMethod; + GcMethod* originalMethod; CallTrace* next; }; class Context { public: - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(MyThread* t, Context* context): - Protector(t), context(context) - { } + MyProtector(MyThread* t, Context* context) + : Protector(t), context(context) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(context->continuation)); } Context* context; }; - Context(MyThread* t, void* ip, void* stack, object continuation, - CallTrace* trace): - ip(ip), - stack(stack), - continuation(continuation), - trace(trace), - protector(t, this) - { } + Context(MyThread* t, + void* ip, + void* stack, + GcContinuation* continuation, + CallTrace* trace) + : ip(ip), + stack(stack), + continuation(continuation), + trace(trace), + protector(t, this) + { + } void* ip; void* stack; - object continuation; + GcContinuation* continuation; CallTrace* trace; MyProtector protector; }; - class TraceContext: public Context { + class TraceContext : public Context { public: - TraceContext(MyThread* t, void* ip, void* stack, object continuation, - CallTrace* trace): - Context(t, ip, stack, continuation, trace), - t(t), - link(0), - next(t->traceContext), - methodIsMostRecent(false) + TraceContext(MyThread* t, + void* ip, + void* stack, + GcContinuation* continuation, + CallTrace* trace) + : Context(t, ip, stack, continuation, trace), + t(t), + link(0), + next(t->traceContext), + methodIsMostRecent(false) { t->traceContext = this; } - TraceContext(MyThread* t, void* link): - Context(t, t->ip, t->stack, t->continuation, t->trace), - t(t), - link(link), - next(t->traceContext), - methodIsMostRecent(false) + TraceContext(MyThread* t, void* link) + : Context(t, t->ip, t->stack, t->continuation, t->trace), + t(t), + link(link), + next(t->traceContext), + methodIsMostRecent(false) { t->traceContext = this; } - ~TraceContext() { + ~TraceContext() + { t->traceContext = next; } @@ -217,15 +214,18 @@ class MyThread: public Thread { bool methodIsMostRecent; }; - static void doTransition(MyThread* t, void* ip, void* stack, - object continuation, MyThread::CallTrace* trace) + static void doTransition(MyThread* t, + void* ip, + void* stack, + GcContinuation* continuation, + MyThread::CallTrace* trace) { // in this function, we "atomically" update the thread context // fields in such a way to ensure that another thread may // interrupt us at any time and still get a consistent, accurate // stack trace. See MyProcessor::getStackTrace for details. - assert(t, t->transition == 0); + assertT(t, t->transition == 0); Context c(t, ip, stack, continuation, trace); @@ -245,33 +245,35 @@ class MyThread: public Thread { t->transition = 0; } - MyThread(Machine* m, object javaThread, MyThread* parent, - bool useNativeFeatures): - Thread(m, javaThread, parent), - ip(0), - stack(0), - newStack(0), - scratch(0), - continuation(0), - exceptionStackAdjustment(0), - exceptionOffset(0), - exceptionHandler(0), - tailAddress(0), - virtualCallTarget(0), - virtualCallIndex(0), - heapImage(0), - codeImage(0), - thunkTable(0), - trace(0), - reference(0), - arch(parent - ? parent->arch - : avian::codegen::makeArchitectureNative(m->system, useNativeFeatures)), - transition(0), - traceContext(0), - stackLimit(0), - referenceFrame(0), - methodLockIsClean(true) + MyThread(Machine* m, + GcThread* javaThread, + MyThread* parent, + bool useNativeFeatures) + : Thread(m, javaThread, parent), + ip(0), + stack(0), + newStack(0), + scratch(0), + continuation(0), + exceptionStackAdjustment(0), + exceptionOffset(0), + exceptionHandler(0), + tailAddress(0), + virtualCallTarget(0), + virtualCallIndex(0), + heapImage(0), + codeImage(0), + thunkTable(0), + trace(0), + reference(0), + arch(parent ? parent->arch : avian::codegen::makeArchitectureNative( + m->system, + useNativeFeatures)), + transition(0), + traceContext(0), + stackLimit(0), + referenceFrame(0), + methodLockIsClean(true) { arch->acquire(); } @@ -280,7 +282,7 @@ class MyThread: public Thread { void* stack; void* newStack; void* scratch; - object continuation; + GcContinuation* continuation; uintptr_t exceptionStackAdjustment; uintptr_t exceptionOffset; void* exceptionHandler; @@ -300,89 +302,83 @@ class MyThread: public Thread { bool methodLockIsClean; }; -void -transition(MyThread* t, void* ip, void* stack, object continuation, - MyThread::CallTrace* trace) +void transition(MyThread* t, + void* ip, + void* stack, + GcContinuation* continuation, + MyThread::CallTrace* trace) { MyThread::doTransition(t, ip, stack, continuation, trace); } -object -resolveThisPointer(MyThread* t, void* stack) +object resolveThisPointer(MyThread* t, void* stack) { - return reinterpret_cast(stack) - [t->arch->frameFooterSize() + t->arch->frameReturnAddressSize()]; + return reinterpret_cast( + stack)[t->arch->frameFooterSize() + t->arch->frameReturnAddressSize()]; } -object -findMethod(Thread* t, object method, object instance) +GcMethod* findMethod(Thread* t, GcMethod* method, object instance) { - if ((methodFlags(t, method) & ACC_STATIC) == 0) { - if (classFlags(t, methodClass(t, method)) & ACC_INTERFACE) { + if ((method->flags() & ACC_STATIC) == 0) { + if (method->class_()->flags() & ACC_INTERFACE) { return findInterfaceMethod(t, method, objectClass(t, instance)); } else if (methodVirtual(t, method)) { - return findVirtualMethod(t, method, objectClass(t, instance)); + return findVirtualMethod(t, method, objectClass(t, instance)); } } return method; } -object -resolveTarget(MyThread* t, void* stack, object method) +GcMethod* resolveTarget(MyThread* t, void* stack, GcMethod* method) { - object class_ = objectClass(t, resolveThisPointer(t, stack)); + GcClass* class_ = objectClass(t, resolveThisPointer(t, stack)); - if (classVmFlags(t, class_) & BootstrapFlag) { + if (class_->vmFlags() & BootstrapFlag) { PROTECT(t, method); PROTECT(t, class_); - resolveSystemClass(t, root(t, Machine::BootLoader), className(t, class_)); + resolveSystemClass(t, roots(t)->bootLoader(), class_->name()); } - if (classFlags(t, methodClass(t, method)) & ACC_INTERFACE) { + if (method->class_()->flags() & ACC_INTERFACE) { return findInterfaceMethod(t, method, class_); } else { return findVirtualMethod(t, method, class_); } } -object -resolveTarget(MyThread* t, object class_, unsigned index) +GcMethod* resolveTarget(MyThread* t, GcClass* class_, unsigned index) { - if (classVmFlags(t, class_) & BootstrapFlag) { + if (class_->vmFlags() & BootstrapFlag) { PROTECT(t, class_); - resolveSystemClass(t, root(t, Machine::BootLoader), className(t, class_)); + resolveSystemClass(t, roots(t)->bootLoader(), class_->name()); } - return arrayBody(t, classVirtualTable(t, class_), index); + return cast( + t, cast(t, class_->virtualTable())->body()[index]); } -object& -root(Thread* t, Root root); +GcCompileRoots* compileRoots(Thread* t); -void -setRoot(Thread* t, Root root, object value); - -intptr_t -methodCompiled(Thread* t, object method) +intptr_t methodCompiled(Thread* t UNUSED, GcMethod* method) { - return codeCompiled(t, methodCode(t, method)); + return method->code()->compiled(); } -unsigned -methodCompiledSize(Thread* t, object method) +unsigned methodCompiledSize(Thread* t UNUSED, GcMethod* method) { - return codeCompiledSize(t, methodCode(t, method)); + return method->code()->compiledSize(); } -intptr_t -compareIpToMethodBounds(Thread* t, intptr_t ip, object method) +intptr_t compareIpToMethodBounds(Thread* t, intptr_t ip, object om) { + GcMethod* method = cast(t, om); intptr_t start = methodCompiled(t, method); if (DebugMethodTree) { - fprintf(stderr, "find %p in (%p,%p)\n", + fprintf(stderr, + "find %p in (%p,%p)\n", reinterpret_cast(ip), reinterpret_cast(start), reinterpret_cast(start + methodCompiledSize(t, method))); @@ -390,17 +386,15 @@ compareIpToMethodBounds(Thread* t, intptr_t ip, object method) if (ip < start) { return -1; - } else if (ip < start + static_cast - (methodCompiledSize(t, method))) - { + } else if (ip < start + + static_cast(methodCompiledSize(t, method))) { return 0; } else { return 1; } } -object -methodForIp(MyThread* t, void* ip) +GcMethod* methodForIp(MyThread* t, void* ip) { if (DebugMethodTree) { fprintf(stderr, "query for method containing %p\n", ip); @@ -411,38 +405,40 @@ methodForIp(MyThread* t, void* ip) // compile(MyThread*, FixedAllocator*, BootContext*, object)): loadMemoryBarrier(); - return treeQuery(t, root(t, MethodTree), reinterpret_cast(ip), - root(t, MethodTreeSentinal), compareIpToMethodBounds); + return cast(t, + treeQuery(t, + compileRoots(t)->methodTree(), + reinterpret_cast(ip), + compileRoots(t)->methodTreeSentinal(), + compareIpToMethodBounds)); } -unsigned -localSize(MyThread* t, object method) +unsigned localSize(MyThread* t UNUSED, GcMethod* method) { - unsigned size = codeMaxLocals(t, methodCode(t, method)); - if ((methodFlags(t, method) & (ACC_SYNCHRONIZED | ACC_STATIC)) - == ACC_SYNCHRONIZED) - { - ++ size; + unsigned size = method->code()->maxLocals(); + if ((method->flags() & (ACC_SYNCHRONIZED | ACC_STATIC)) == ACC_SYNCHRONIZED) { + ++size; } return size; } -unsigned -alignedFrameSize(MyThread* t, object method) +unsigned alignedFrameSize(MyThread* t, GcMethod* method) { - return t->arch->alignFrameSize - (localSize(t, method) - - methodParameterFootprint(t, method) - + codeMaxStack(t, methodCode(t, method)) - + t->arch->frameFootprint(MaxNativeCallFootprint)); + return t->arch->alignFrameSize( + localSize(t, method) - method->parameterFootprint() + + method->code()->maxStack() + + t->arch->frameFootprint(MaxNativeCallFootprint)); } -void -nextFrame(MyThread* t, void** ip, void** sp, object method, object target, - bool mostRecent) +void nextFrame(MyThread* t, + void** ip, + void** sp, + GcMethod* method, + GcMethod* target, + bool mostRecent) { - object code = methodCode(t, method); - intptr_t start = codeCompiled(t, code); + GcCode* code = method->code(); + intptr_t start = code->compiled(); void* link; bool methodIsMostRecent; @@ -454,31 +450,34 @@ nextFrame(MyThread* t, void** ip, void** sp, object method, object target, methodIsMostRecent = false; } - // fprintf(stderr, "nextFrame %s.%s%s target %s.%s%s ip %p sp %p\n", - // &byteArrayBody(t, className(t, methodClass(t, method)), 0), - // &byteArrayBody(t, methodName(t, method), 0), - // &byteArrayBody(t, methodSpec(t, method), 0), - // target - // ? &byteArrayBody(t, className(t, methodClass(t, target)), 0) - // : 0, - // target - // ? &byteArrayBody(t, methodName(t, target), 0) - // : 0, - // target - // ? &byteArrayBody(t, methodSpec(t, target), 0) - // : 0, - // *ip, *sp); + if (false) { + fprintf(stderr, + "nextFrame %s.%s%s target %s.%s%s ip %p sp %p\n", + method->class_()->name()->body().begin(), + method->name()->body().begin(), + method->spec()->body().begin(), + target ? target->class_()->name()->body().begin() : 0, + target ? target->name()->body().begin() : 0, + target ? target->spec()->body().begin() : 0, + *ip, + *sp); + } - t->arch->nextFrame - (reinterpret_cast(start), codeCompiledSize(t, code), - alignedFrameSize(t, method), link, methodIsMostRecent, - target ? methodParameterFootprint(t, target) : -1, ip, sp); + t->arch->nextFrame(reinterpret_cast(start), + code->compiledSize(), + alignedFrameSize(t, method), + link, + methodIsMostRecent, + target ? target->parameterFootprint() : -1, + ip, + sp); - // fprintf(stderr, "next frame ip %p sp %p\n", *ip, *sp); + if (false) { + fprintf(stderr, "next frame ip %p sp %p\n", *ip, *sp); + } } -void* -getIp(MyThread* t, void* ip, void* stack) +void* getIp(MyThread* t, void* ip, void* stack) { // Here we use the convention that, if the return address is neither // pushed on to the stack automatically as part of the call nor @@ -488,31 +487,23 @@ getIp(MyThread* t, void* ip, void* stack) return t->arch->returnAddressOffset() < 0 ? ip : t->arch->frameIp(stack); } -void* -getIp(MyThread* t) +void* getIp(MyThread* t) { return getIp(t, t->ip, t->stack); } -class MyStackWalker: public Processor::StackWalker { +class MyStackWalker : public Processor::StackWalker { public: - enum State { - Start, - Next, - Trace, - Continuation, - Method, - NativeMethod, - Finish - }; + enum State { Start, Next, Trace, Continuation, Method, NativeMethod, Finish }; - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(MyStackWalker* walker): - Protector(walker->t), walker(walker) - { } + MyProtector(MyStackWalker* walker) : Protector(walker->t), walker(walker) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(walker->method_)); v->visit(&(walker->target)); v->visit(&(walker->continuation)); @@ -521,13 +512,8 @@ class MyStackWalker: public Processor::StackWalker { MyStackWalker* walker; }; - MyStackWalker(MyThread* t): - t(t), - state(Start), - method_(0), - target(0), - count_(0), - protector(this) + MyStackWalker(MyThread* t) + : t(t), state(Start), method_(0), target(0), count_(0), protector(this) { if (t->traceContext) { ip_ = t->traceContext->ip; @@ -538,24 +524,26 @@ class MyStackWalker: public Processor::StackWalker { ip_ = getIp(t); stack = t->stack; trace = t->trace; - continuation = t->continuation; + continuation = t->continuation; } } - MyStackWalker(MyStackWalker* w): - t(w->t), - state(w->state), - ip_(w->ip_), - stack(w->stack), - trace(w->trace), - method_(w->method_), - target(w->target), - continuation(w->continuation), - count_(w->count_), - protector(this) - { } + MyStackWalker(MyStackWalker* w) + : t(w->t), + state(w->state), + ip_(w->ip_), + stack(w->stack), + trace(w->trace), + method_(w->method_), + target(w->target), + continuation(w->continuation), + count_(w->count_), + protector(this) + { + } - virtual void walk(Processor::StackVisitor* v) { + virtual void walk(Processor::StackVisitor* v) + { for (MyStackWalker it(this); it.valid();) { MyStackWalker walker(&it); if (not v->visit(&walker)) { @@ -564,10 +552,13 @@ class MyStackWalker: public Processor::StackWalker { it.next(); } } - - bool valid() { + + bool valid() + { while (true) { -// fprintf(stderr, "state: %d\n", state); + if (false) { + fprintf(stderr, "state: %d\n", state); + } switch (state) { case Start: if (trace and trace->nativeMethod) { @@ -585,7 +576,7 @@ class MyStackWalker: public Processor::StackWalker { if (method_) { state = Method; } else if (continuation) { - method_ = continuationMethod(t, continuation); + method_ = continuation->method(); state = Continuation; } else { state = Trace; @@ -615,19 +606,20 @@ class MyStackWalker: public Processor::StackWalker { case Finish: return false; - + default: abort(t); } } } - - void next() { + + void next() + { expect(t, count_ <= stackSizeInWords(t)); switch (state) { case Continuation: - continuation = continuationNext(t, continuation); + continuation = continuation->next(); break; case Method: @@ -636,32 +628,37 @@ class MyStackWalker: public Processor::StackWalker { case NativeMethod: break; - + default: abort(t); } - ++ count_; + ++count_; state = Next; } - virtual object method() { -// fprintf(stderr, "method %s.%s\n", &byteArrayBody -// (t, className(t, methodClass(t, method_)), 0), -// &byteArrayBody(t, methodName(t, method_), 0)); + virtual GcMethod* method() + { + if (false) { + fprintf(stderr, + "method %s.%s\n", + method_->class_()->name()->body().begin(), + method_->name()->body().begin()); + } return method_; } - virtual int ip() { + virtual int ip() + { switch (state) { case Continuation: - return reinterpret_cast(continuationAddress(t, continuation)) - - methodCompiled(t, continuationMethod(t, continuation)); + return reinterpret_cast(continuation->address()) + - methodCompiled(t, continuation->method()); case Method: return reinterpret_cast(ip_) - methodCompiled(t, method_); - + case NativeMethod: return 0; @@ -670,14 +667,15 @@ class MyStackWalker: public Processor::StackWalker { } } - virtual unsigned count() { + virtual unsigned count() + { unsigned count = 0; for (MyStackWalker walker(this); walker.valid();) { walker.next(); - ++ count; + ++count; } - + return count; } @@ -686,70 +684,63 @@ class MyStackWalker: public Processor::StackWalker { void* ip_; void* stack; MyThread::CallTrace* trace; - object method_; - object target; - object continuation; + GcMethod* method_; + GcMethod* target; + GcContinuation* continuation; unsigned count_; MyProtector protector; }; -int -localOffset(MyThread* t, int v, object method) +int localOffset(MyThread* t, int v, GcMethod* method) { - int parameterFootprint = methodParameterFootprint(t, method); + int parameterFootprint = method->parameterFootprint(); int frameSize = alignedFrameSize(t, method); - int offset = ((v < parameterFootprint) ? - (frameSize - + parameterFootprint - + t->arch->frameFooterSize() - + t->arch->frameHeaderSize() - - v - 1) : - (frameSize - + parameterFootprint - - v - 1)); + int offset + = ((v < parameterFootprint) + ? (frameSize + parameterFootprint + t->arch->frameFooterSize() + + t->arch->frameHeaderSize() - v - 1) + : (frameSize + parameterFootprint - v - 1)); - assert(t, offset >= 0); + assertT(t, offset >= 0); return offset; } -int -localOffsetFromStack(MyThread* t, int index, object method) +int localOffsetFromStack(MyThread* t, int index, GcMethod* method) { - return localOffset(t, index, method) - + t->arch->frameReturnAddressSize(); + return localOffset(t, index, method) + t->arch->frameReturnAddressSize(); } -object* -localObject(MyThread* t, void* stack, object method, unsigned index) +object* localObject(MyThread* t, void* stack, GcMethod* method, unsigned index) { return static_cast(stack) + localOffsetFromStack(t, index, method); } -int -stackOffsetFromFrame(MyThread* t, object method) +int stackOffsetFromFrame(MyThread* t, GcMethod* method) { return alignedFrameSize(t, method) + t->arch->frameHeaderSize(); } -void* -stackForFrame(MyThread* t, void* frame, object method) +void* stackForFrame(MyThread* t, void* frame, GcMethod* method) { return static_cast(frame) - stackOffsetFromFrame(t, method); } -class PoolElement: public avian::codegen::Promise { +class PoolElement : public avian::codegen::Promise { public: - PoolElement(Thread* t, object target, PoolElement* next): - t(t), target(target), address(0), next(next) - { } + PoolElement(Thread* t, object target, PoolElement* next) + : t(t), target(target), address(0), next(next) + { + } - virtual int64_t value() { - assert(t, resolved()); + virtual int64_t value() + { + assertT(t, resolved()); return address; } - virtual bool resolved() { + virtual bool resolved() + { return address != 0; } @@ -770,7 +761,8 @@ class Subroutine { returnAddress(returnAddress), duplicatedBaseIp(methodSize * index), visited(false) - { } + { + } // Index of this subroutine, in the (unmaterialized) list of subroutines in // this method. @@ -793,27 +785,33 @@ class Subroutine { class Context; -class TraceElement: public avian::codegen::TraceHandler { +class TraceElement : public avian::codegen::TraceHandler { public: static const unsigned VirtualCall = 1 << 0; - static const unsigned TailCall = 1 << 1; - static const unsigned LongCall = 1 << 2; + static const unsigned TailCall = 1 << 1; + static const unsigned LongCall = 1 << 2; - TraceElement(Context* context, unsigned ip, object target, unsigned flags, - TraceElement* next, unsigned mapSize): - context(context), - address(0), - next(next), - target(target), - ip(ip), - argumentIndex(0), - flags(flags), - watch(false) + TraceElement(Context* context, + unsigned ip, + GcMethod* target, + unsigned flags, + TraceElement* next, + unsigned mapSize) + : context(context), + address(0), + next(next), + target(target), + ip(ip), + argumentIndex(0), + flags(flags), + watch(false) { memset(map, 0xFF, mapSize * BytesPerWord); } - virtual void handleTrace(avian::codegen::Promise* address, unsigned argumentIndex) { + virtual void handleTrace(avian::codegen::Promise* address, + unsigned argumentIndex) + { if (this->address == 0) { this->address = address; this->argumentIndex = argumentIndex; @@ -823,7 +821,7 @@ class TraceElement: public avian::codegen::TraceHandler { Context* context; avian::codegen::Promise* address; TraceElement* next; - object target; + GcMethod* target; unsigned ip; unsigned argumentIndex; unsigned flags; @@ -831,16 +829,20 @@ class TraceElement: public avian::codegen::TraceHandler { uintptr_t map[0]; }; -class TraceElementPromise: public avian::codegen::Promise { +class TraceElementPromise : public avian::codegen::Promise { public: - TraceElementPromise(System* s, TraceElement* trace): s(s), trace(trace) { } + TraceElementPromise(System* s, TraceElement* trace) : s(s), trace(trace) + { + } - virtual int64_t value() { - assert(s, resolved()); + virtual int64_t value() + { + assertT(s, resolved()); return trace->address->value(); } - virtual bool resolved() { + virtual bool resolved() + { return trace->address != 0 and trace->address->resolved(); } @@ -858,14 +860,12 @@ enum Event { TraceEvent, }; -unsigned -frameMapSizeInBits(MyThread* t, object method) +unsigned frameMapSizeInBits(MyThread* t, GcMethod* method) { - return localSize(t, method) + codeMaxStack(t, methodCode(t, method)); + return localSize(t, method) + method->code()->maxStack(); } -unsigned -frameMapSizeInWords(MyThread* t, object method) +unsigned frameMapSizeInWords(MyThread* t, GcMethod* method) { return ceilingDivide(frameMapSizeInBits(t, method), BitsPerWord); } @@ -880,16 +880,18 @@ enum Thunk { const unsigned ThunkCount = idleIfNecessaryThunk + 1; -intptr_t -getThunk(MyThread* t, Thunk thunk); +intptr_t getThunk(MyThread* t, Thunk thunk); class BootContext { public: - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(Thread* t, BootContext* c): Protector(t), c(c) { } + MyProtector(Thread* t, BootContext* c) : Protector(t), c(c) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(c->constants)); v->visit(&(c->calls)); } @@ -897,16 +899,25 @@ class BootContext { BootContext* c; }; - BootContext(Thread* t, object constants, object calls, - avian::codegen::DelayedPromise* addresses, Zone* zone, OffsetResolver* resolver): - protector(t, this), constants(constants), calls(calls), - addresses(addresses), addressSentinal(addresses), zone(zone), - resolver(resolver) - { } + BootContext(Thread* t, + GcTriple* constants, + GcTriple* calls, + avian::codegen::DelayedPromise* addresses, + Zone* zone, + OffsetResolver* resolver) + : protector(t, this), + constants(constants), + calls(calls), + addresses(addresses), + addressSentinal(addresses), + zone(zone), + resolver(resolver) + { + } MyProtector protector; - object constants; - object calls; + GcTriple* constants; + GcTriple* calls; avian::codegen::DelayedPromise* addresses; avian::codegen::DelayedPromise* addressSentinal; Zone* zone; @@ -915,22 +926,28 @@ class BootContext { class Context { public: - class MyResource: public Thread::AutoResource { + class MyResource : public Thread::AutoResource { public: - MyResource(Context* c): AutoResource(c->thread), c(c) { } + MyResource(Context* c) : AutoResource(c->thread), c(c) + { + } - virtual void release() { + virtual void release() + { c->dispose(); } Context* c; }; - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(Context* c): Protector(c->thread), c(c) { } + MyProtector(Context* c) : Protector(c->thread), c(c) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(c->method)); for (PoolElement* p = c->objectPool; p; p = p->next) { @@ -945,40 +962,44 @@ class Context { Context* c; }; - class MyClient: public Compiler::Client { + class MyClient : public Compiler::Client { public: - MyClient(MyThread* t): t(t) { } + MyClient(MyThread* t) : t(t) + { + } - virtual intptr_t getThunk(avian::codegen::lir::UnaryOperation, unsigned) { + virtual intptr_t getThunk(avian::codegen::lir::UnaryOperation, unsigned) + { abort(t); } - - virtual intptr_t getThunk(avian::codegen::lir::BinaryOperation op, unsigned size, + + virtual intptr_t getThunk(avian::codegen::lir::BinaryOperation op, + unsigned size, unsigned resultSize) { if (size == 8) { - switch(op) { + switch (op) { case avian::codegen::lir::Absolute: - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, absoluteLongThunk); case avian::codegen::lir::FloatNegate: - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, negateDoubleThunk); case avian::codegen::lir::FloatSquareRoot: - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, squareRootDoubleThunk); case avian::codegen::lir::Float2Float: - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, doubleToFloatThunk); case avian::codegen::lir::Float2Int: if (resultSize == 8) { return local::getThunk(t, doubleToLongThunk); } else { - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, doubleToIntThunk); } @@ -986,37 +1007,38 @@ class Context { if (resultSize == 8) { return local::getThunk(t, longToDoubleThunk); } else { - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, longToFloatThunk); } - - default: abort(t); + + default: + abort(t); } } else { - assert(t, size == 4); + assertT(t, size == 4); - switch(op) { + switch (op) { case avian::codegen::lir::Absolute: - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, absoluteIntThunk); case avian::codegen::lir::FloatNegate: - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, negateFloatThunk); case avian::codegen::lir::FloatAbsolute: - assert(t, resultSize == 4); + assertT(t, resultSize == 4); return local::getThunk(t, absoluteFloatThunk); case avian::codegen::lir::Float2Float: - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, floatToDoubleThunk); case avian::codegen::lir::Float2Int: if (resultSize == 4) { return local::getThunk(t, floatToIntThunk); } else { - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, floatToLongThunk); } @@ -1024,16 +1046,19 @@ class Context { if (resultSize == 4) { return local::getThunk(t, intToFloatThunk); } else { - assert(t, resultSize == 8); + assertT(t, resultSize == 8); return local::getThunk(t, intToDoubleThunk); } - default: abort(t); + default: + abort(t); } } } - virtual intptr_t getThunk(avian::codegen::lir::TernaryOperation op, unsigned size, unsigned, + virtual intptr_t getThunk(avian::codegen::lir::TernaryOperation op, + unsigned size, + unsigned, bool* threadParameter) { *threadParameter = false; @@ -1077,10 +1102,11 @@ class Context { case avian::codegen::lir::JumpIfFloatLessOrEqualOrUnordered: return local::getThunk(t, compareDoublesLThunk); - default: abort(t); + default: + abort(t); } } else { - assert(t, size == 4); + assertT(t, size == 4); switch (op) { case avian::codegen::lir::Divide: *threadParameter = true; @@ -1119,7 +1145,8 @@ class Context { case avian::codegen::lir::JumpIfFloatLessOrEqualOrUnordered: return local::getThunk(t, compareFloatsLThunk); - default: abort(t); + default: + abort(t); } } } @@ -1127,7 +1154,7 @@ class Context { MyThread* t; }; - Context(MyThread* t, BootContext* bootContext, object method) + Context(MyThread* t, BootContext* bootContext, GcMethod* method) : thread(t), zone(t->m->system, t->m->heap, InitialZoneCapacityInBytes), assembler(t->arch->makeAssembler(t->m->heap, &zone)), @@ -1139,14 +1166,11 @@ class Context { subroutineCount(0), traceLog(0), visitTable( - Slice::allocAndSet(&zone, - codeLength(t, methodCode(t, method)), - 0)), - rootTable( - Slice::allocAndSet(&zone, - codeLength(t, methodCode(t, method)) - * frameMapSizeInWords(t, method), - ~(uintptr_t)0)), + Slice::allocAndSet(&zone, method->code()->length(), 0)), + rootTable(Slice::allocAndSet( + &zone, + method->code()->length() * frameMapSizeInWords(t, method), + ~(uintptr_t)0)), executableAllocator(0), executableStart(0), executableSize(0), @@ -1160,7 +1184,8 @@ class Context { argumentBuffer( (ir::Value**)t->m->heap->allocate(256 * sizeof(ir::Value*)), 256) // below the maximal allowed parameter count for Java - { } + { + } Context(MyThread* t) : thread(t), @@ -1186,13 +1211,16 @@ class Context { protector(this), resource(this), argumentBuffer(0, 0) - { } + { + } - ~Context() { + ~Context() + { dispose(); } - void dispose() { + void dispose() + { if (compiler) { compiler->dispose(); } @@ -1227,7 +1255,7 @@ class Context { avian::codegen::Assembler* assembler; MyClient client; avian::codegen::Compiler* compiler; - object method; + GcMethod* method; BootContext* bootContext; PoolElement* objectPool; unsigned subroutineCount; @@ -1247,11 +1275,11 @@ class Context { Slice argumentBuffer; }; -unsigned -translateLocalIndex(Context* context, unsigned footprint, unsigned index) +unsigned translateLocalIndex(Context* context, + unsigned footprint, + unsigned index) { - unsigned parameterFootprint = methodParameterFootprint - (context->thread, context->method); + unsigned parameterFootprint = context->method->parameterFootprint(); if (index < parameterFootprint) { return parameterFootprint - index - footprint; @@ -1268,7 +1296,7 @@ ir::Value* loadLocal(Context* context, ir::Value* result = context->compiler->loadLocal( type, translateLocalIndex(context, footprint, index)); - assert(context->thread, type == result->type); + assertT(context->thread, type == result->type); return result; } @@ -1278,7 +1306,7 @@ void storeLocal(Context* context, ir::Value* value, unsigned index) { - assert(context->thread, type == value->type); + assertT(context->thread, type == value->type); context->compiler->storeLocal(value, translateLocalIndex(context, footprint, index)); } @@ -1287,7 +1315,6 @@ avian::util::FixedAllocator* codeAllocator(MyThread* t); ir::Type operandTypeForFieldCode(Thread* t, unsigned code) { - switch (code) { case ByteField: case BooleanField: @@ -1315,28 +1342,27 @@ ir::Type operandTypeForFieldCode(Thread* t, unsigned code) } unsigned methodReferenceParameterFootprint(Thread* t, - object reference, + GcReference* reference, bool isStatic) { return parameterFootprint( t, - reinterpret_cast( - &byteArrayBody(t, referenceSpec(t, reference), 0)), + reinterpret_cast(reference->spec()->body().begin()), isStatic); } -int methodReferenceReturnCode(Thread* t, object reference) +int methodReferenceReturnCode(Thread* t, GcReference* reference) { unsigned parameterCount; unsigned parameterFootprint; unsigned returnCode; - scanMethodSpec(t, - reinterpret_cast( - &byteArrayBody(t, referenceSpec(t, reference), 0)), - true, - ¶meterCount, - ¶meterFootprint, - &returnCode); + scanMethodSpec( + t, + reinterpret_cast(reference->spec()->body().begin()), + true, + ¶meterCount, + ¶meterFootprint, + &returnCode); return returnCode; } @@ -1353,9 +1379,7 @@ class Frame { sp(localSize()), level(0) { - memset(stackMap, - 0, - codeMaxStack(t, methodCode(t, context->method)) * sizeof(ir::Type)); + memset(stackMap, 0, context->method->code()->maxStack() * sizeof(ir::Type)); } Frame(Frame* f, ir::Type* stackMap) @@ -1370,18 +1394,20 @@ class Frame { { memcpy(stackMap, f->stackMap, - codeMaxStack(t, methodCode(t, context->method)) * sizeof(ir::Type)); + context->method->code()->maxStack() * sizeof(ir::Type)); if (level > 1) { context->eventLog.append(PushContextEvent); } } - ~Frame() { + ~Frame() + { dispose(); } - void dispose() { + void dispose() + { if (level > 1) { context->eventLog.append(PopContextEvent); } @@ -1391,7 +1417,8 @@ class Frame { { BootContext* bc = context->bootContext; if (bc) { - avian::codegen::Promise* p = new (bc->zone) avian::codegen::ListenPromise(t->m->system, bc->zone); + avian::codegen::Promise* p = new (bc->zone) + avian::codegen::ListenPromise(t->m->system, bc->zone); PROTECT(t, o); object pointer = makePointer(t, p); @@ -1410,29 +1437,33 @@ class Frame { } } - context->objectPool = new(&context->zone) PoolElement(t, o, context->objectPool); + context->objectPool = new (&context->zone) + PoolElement(t, o, context->objectPool); - ++ context->objectPoolCount; + ++context->objectPoolCount; return c->address(ir::Type::object(), context->objectPool); } } - unsigned localSize() { + unsigned localSize() + { return local::localSize(t, context->method); } - unsigned stackSize() { - return codeMaxStack(t, methodCode(t, context->method)); + unsigned stackSize() + { + return context->method->code()->maxStack(); } - unsigned frameSize() { + unsigned frameSize() + { return localSize() + stackSize(); } void set(unsigned index, ir::Type type) { - assert(t, index < frameSize()); + assertT(t, index < frameSize()); if (type == ir::Type::object()) { context->eventLog.append(MarkEvent); @@ -1450,25 +1481,28 @@ class Frame { ir::Type get(unsigned index) { - assert(t, index < frameSize()); + assertT(t, index < frameSize()); int si = index - localSize(); - assert(t, si >= 0); + assertT(t, si >= 0); return stackMap[si]; } - void popped(unsigned count) { - assert(t, sp >= count); - assert(t, sp - count >= localSize()); + void popped(unsigned count) + { + assertT(t, sp >= count); + assertT(t, sp - count >= localSize()); while (count) { set(--sp, ir::Type::i4()); - -- count; + --count; } } - avian::codegen::Promise* addressPromise(avian::codegen::Promise* p) { + avian::codegen::Promise* addressPromise(avian::codegen::Promise* p) + { BootContext* bc = context->bootContext; if (bc) { - bc->addresses = new(bc->zone) avian::codegen::DelayedPromise(t->m->system, bc->zone, p, bc->addresses); + bc->addresses = new (bc->zone) avian::codegen::DelayedPromise( + t->m->system, bc->zone, p, bc->addresses); return bc->addresses; } else { return p; @@ -1539,24 +1573,25 @@ class Frame { void push(ir::Type type, ir::Value* o) { - assert(t, type == o->type); + assertT(t, type == o->type); c->push(o->type, o); - assert(t, sp + 1 <= frameSize()); + assertT(t, sp + 1 <= frameSize()); set(sp++, type); } - void pushObject() { + void pushObject() + { c->pushed(ir::Type::object()); - assert(t, sp + 1 <= frameSize()); + assertT(t, sp + 1 <= frameSize()); set(sp++, ir::Type::object()); } void pushLarge(ir::Type type, ir::Value* o) { - assert(t, o->type == type); + assertT(t, o->type == type); c->push(type, o); - assert(t, sp + 2 <= frameSize()); + assertT(t, sp + 2 <= frameSize()); set(sp++, type); set(sp++, type); } @@ -1569,63 +1604,67 @@ class Frame { ir::Value* pop(ir::Type type) { - assert(t, sp >= 1); - assert(t, sp - 1 >= localSize()); - assert(t, get(sp - 1) == type); + assertT(t, sp >= 1); + assertT(t, sp - 1 >= localSize()); + assertT(t, get(sp - 1) == type); set(--sp, ir::Type::i4()); return c->pop(type); } ir::Value* popLarge(ir::Type type) { - assert(t, sp >= 1); - assert(t, sp - 2 >= localSize()); - assert(t, get(sp - 1) == type); - assert(t, get(sp - 2) == type); + assertT(t, sp >= 1); + assertT(t, sp - 2 >= localSize()); + assertT(t, get(sp - 1) == type); + assertT(t, get(sp - 2) == type); sp -= 2; return c->pop(type); } void load(ir::Type type, unsigned index) { - assert(t, index < localSize()); + assertT(t, index < localSize()); push(type, loadLocal(context, 1, type, index)); } - void loadLarge(ir::Type type, unsigned index) { - assert(t, index < static_cast(localSize() - 1)); + void loadLarge(ir::Type type, unsigned index) + { + assertT(t, index < static_cast(localSize() - 1)); pushLarge(type, loadLocal(context, 2, type, index)); } void store(ir::Type type, unsigned index) { - assert(t, - type == ir::Type::i4() || type == ir::Type::f4() - || type == ir::Type::object()); + assertT(t, + type == ir::Type::i4() || type == ir::Type::f4() + || type == ir::Type::object()); storeLocal(context, 1, type, pop(type), index); unsigned ti = translateLocalIndex(context, 1, index); - assert(t, ti < localSize()); + assertT(t, ti < localSize()); set(ti, type); } - void storeLarge(ir::Type type, unsigned index) { + void storeLarge(ir::Type type, unsigned index) + { storeLocal(context, 2, type, popLarge(type), index); unsigned ti = translateLocalIndex(context, 2, index); - assert(t, ti + 1 < localSize()); + assertT(t, ti + 1 < localSize()); set(ti, type); set(ti + 1, type); } - void dup() { + void dup() + { c->push(ir::Type::i4(), c->peek(1, 0)); - assert(t, sp + 1 <= frameSize()); - assert(t, sp - 1 >= localSize()); + assertT(t, sp + 1 <= frameSize()); + assertT(t, sp - 1 >= localSize()); set(sp, get(sp - 1)); - ++ sp; + ++sp; } - void dupX1() { + void dupX1() + { ir::Value* s0 = c->pop(ir::Type::i4()); ir::Value* s1 = c->pop(ir::Type::i4()); @@ -1633,20 +1672,21 @@ class Frame { c->push(ir::Type::i4(), s1); c->push(ir::Type::i4(), s0); - assert(t, sp + 1 <= frameSize()); - assert(t, sp - 2 >= localSize()); + assertT(t, sp + 1 <= frameSize()); + assertT(t, sp - 2 >= localSize()); ir::Type b2 = get(sp - 2); ir::Type b1 = get(sp - 1); set(sp - 1, b2); set(sp - 2, b1); - set(sp , b1); + set(sp, b1); - ++ sp; + ++sp; } - void dupX2() { + void dupX2() + { ir::Value* s0 = c->pop(ir::Type::i4()); if (get(sp - 2) == ir::Type::i8()) { @@ -1665,8 +1705,8 @@ class Frame { c->push(ir::Type::i4(), s0); } - assert(t, sp + 1 <= frameSize()); - assert(t, sp - 3 >= localSize()); + assertT(t, sp + 1 <= frameSize()); + assertT(t, sp - 3 >= localSize()); ir::Type b3 = get(sp - 3); ir::Type b2 = get(sp - 2); @@ -1675,12 +1715,13 @@ class Frame { set(sp - 2, b3); set(sp - 1, b2); set(sp - 3, b1); - set(sp , b1); + set(sp, b1); - ++ sp; + ++sp; } - void dup2() { + void dup2() + { if (get(sp - 1) == ir::Type::i8()) { c->push(ir::Type::i8(), c->peek(2, 0)); } else { @@ -1693,8 +1734,8 @@ class Frame { c->push(ir::Type::i4(), s0); } - assert(t, sp + 2 <= frameSize()); - assert(t, sp - 2 >= localSize()); + assertT(t, sp + 2 <= frameSize()); + assertT(t, sp - 2 >= localSize()); ir::Type b2 = get(sp - 2); ir::Type b1 = get(sp - 1); @@ -1705,7 +1746,8 @@ class Frame { sp += 2; } - void dup2X1() { + void dup2X1() + { if (get(sp - 1) == ir::Type::i8()) { ir::Value* s0 = c->pop(ir::Type::i8()); ir::Value* s1 = c->pop(ir::Type::i4()); @@ -1725,8 +1767,8 @@ class Frame { c->push(ir::Type::i4(), s0); } - assert(t, sp + 2 <= frameSize()); - assert(t, sp - 3 >= localSize()); + assertT(t, sp + 2 <= frameSize()); + assertT(t, sp - 3 >= localSize()); ir::Type b3 = get(sp - 3); ir::Type b2 = get(sp - 2); @@ -1734,14 +1776,15 @@ class Frame { set(sp - 1, b3); set(sp - 3, b2); - set(sp , b2); + set(sp, b2); set(sp - 2, b1); set(sp + 1, b1); sp += 2; } - void dup2X2() { + void dup2X2() + { if (get(sp - 1) == ir::Type::i8()) { ir::Value* s0 = c->pop(ir::Type::i8()); @@ -1774,8 +1817,8 @@ class Frame { c->push(ir::Type::i4(), s0); } - assert(t, sp + 2 <= frameSize()); - assert(t, sp - 4 >= localSize()); + assertT(t, sp + 2 <= frameSize()); + assertT(t, sp - 4 >= localSize()); ir::Type b4 = get(sp - 4); ir::Type b3 = get(sp - 3); @@ -1785,21 +1828,22 @@ class Frame { set(sp - 2, b4); set(sp - 1, b3); set(sp - 4, b2); - set(sp , b2); + set(sp, b2); set(sp - 3, b1); set(sp + 1, b1); sp += 2; } - void swap() { + void swap() + { ir::Value* s0 = c->pop(ir::Type::i4()); ir::Value* s1 = c->pop(ir::Type::i4()); c->push(ir::Type::i4(), s0); c->push(ir::Type::i4(), s1); - assert(t, sp - 2 >= localSize()); + assertT(t, sp - 2 >= localSize()); ir::Type saved = get(sp - 1); @@ -1807,7 +1851,8 @@ class Frame { set(sp - 2, saved); } - TraceElement* trace(object target, unsigned flags) { + TraceElement* trace(GcMethod* target, unsigned flags) + { unsigned mapSize = frameMapSizeInWords(t, context->method); TraceElement* e = context->traceLog = new ( @@ -1819,7 +1864,7 @@ class Frame { context->traceLog, mapSize); - ++ context->traceLogCount; + ++context->traceLogCount; context->eventLog.append(TraceEvent); context->eventLog.appendAddress(e); @@ -1864,12 +1909,12 @@ class Frame { } void stackCall(ir::Value* methodValue, - object methodObject, + GcMethod* methodObject, unsigned flags, TraceElement* trace) { - unsigned footprint = methodParameterFootprint(t, methodObject); - unsigned returnCode = methodReturnCode(t, methodObject); + unsigned footprint = methodObject->parameterFootprint(); + unsigned returnCode = methodObject->returnCode(); ir::Value* result = c->stackCall(methodValue, flags, trace, @@ -1885,7 +1930,7 @@ class Frame { void referenceStackCall(bool isStatic, ir::Value* methodValue, - object methodReference, + GcReference* methodReference, unsigned flags, TraceElement* trace) { @@ -1919,10 +1964,10 @@ class Frame { Subroutine* subroutine = new (&context->zone) Subroutine(context->subroutineCount++, returnAddress, - codeLength(t, methodCode(t, context->method)), + context->method->code()->length(), this->subroutine); - context->extendLogicalCode(codeLength(t, methodCode(t, context->method))); + context->extendLogicalCode(context->method->code()->length()); this->subroutine = subroutine; } @@ -1957,39 +2002,34 @@ class Frame { unsigned level; }; -unsigned -savedTargetIndex(MyThread* t, object method) +unsigned savedTargetIndex(MyThread* t UNUSED, GcMethod* method) { - return codeMaxLocals(t, methodCode(t, method)); + return method->code()->maxLocals(); } -object -findCallNode(MyThread* t, void* address); +GcCallNode* findCallNode(MyThread* t, void* address); -void -insertCallNode(MyThread* t, object node); +void insertCallNode(MyThread* t, GcCallNode* node); -void* -findExceptionHandler(Thread* t, object method, void* ip) +void* findExceptionHandler(Thread* t, GcMethod* method, void* ip) { if (t->exception) { - object table = codeExceptionHandlerTable(t, methodCode(t, method)); + GcArray* table = cast(t, method->code()->exceptionHandlerTable()); if (table) { - object index = arrayBody(t, table, 0); - - uint8_t* compiled = reinterpret_cast - (methodCompiled(t, method)); + GcIntArray* index = cast(t, table->body()[0]); - for (unsigned i = 0; i < arrayLength(t, table) - 1; ++i) { - unsigned start = intArrayBody(t, index, i * 3); - unsigned end = intArrayBody(t, index, (i * 3) + 1); + uint8_t* compiled = reinterpret_cast(methodCompiled(t, method)); + + for (unsigned i = 0; i < table->length() - 1; ++i) { + unsigned start = index->body()[i * 3]; + unsigned end = index->body()[(i * 3) + 1]; unsigned key = difference(ip, compiled) - 1; if (key >= start and key < end) { - object catchType = arrayBody(t, table, i + 1); + GcClass* catchType = cast(t, table->body()[i + 1]); if (exceptionMatch(t, catchType, t->exception)) { - return compiled + intArrayBody(t, index, (i * 3) + 2); + return compiled + index->body()[(i * 3) + 2]; } } } @@ -1999,20 +2039,20 @@ findExceptionHandler(Thread* t, object method, void* ip) return 0; } -void -releaseLock(MyThread* t, object method, void* stack) +void releaseLock(MyThread* t, GcMethod* method, void* stack) { - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_SYNCHRONIZED) { if (t->methodLockIsClean) { object lock; - if (methodFlags(t, method) & ACC_STATIC) { - lock = methodClass(t, method); + if (method->flags() & ACC_STATIC) { + lock = method->class_(); } else { - lock = *localObject - (t, stackForFrame(t, stack, method), method, - savedTargetIndex(t, method)); + lock = *localObject(t, + stackForFrame(t, stack, method), + method, + savedTargetIndex(t, method)); } - + release(t, lock); } else { // got an exception while trying to acquire the lock for a @@ -2023,13 +2063,15 @@ releaseLock(MyThread* t, object method, void* stack) } } -void -findUnwindTarget(MyThread* t, void** targetIp, void** targetFrame, - void** targetStack, object* targetContinuation) +void findUnwindTarget(MyThread* t, + void** targetIp, + void** targetFrame, + void** targetStack, + GcContinuation** targetContinuation) { void* ip; void* stack; - object continuation; + GcContinuation* continuation; if (t->traceContext) { ip = t->traceContext->ip; @@ -2038,15 +2080,15 @@ findUnwindTarget(MyThread* t, void** targetIp, void** targetFrame, } else { ip = getIp(t); stack = t->stack; - continuation = t->continuation; + continuation = t->continuation; } - object target = t->trace->targetMethod; + GcMethod* target = t->trace->targetMethod; bool mostRecent = true; *targetIp = 0; while (*targetIp == 0) { - object method = methodForIp(t, ip); + GcMethod* method = methodForIp(t, ip); if (method) { void* handler = findExceptionHandler(t, method, ip); @@ -2056,10 +2098,10 @@ findUnwindTarget(MyThread* t, void** targetIp, void** targetFrame, nextFrame(t, &ip, &stack, method, target, mostRecent); void** sp = static_cast(stackForFrame(t, stack, method)) - + t->arch->frameReturnAddressSize(); + + t->arch->frameReturnAddressSize(); - *targetFrame = static_cast - (stack) + t->arch->framePointerOffset(); + *targetFrame = static_cast(stack) + + t->arch->framePointerOffset(); *targetStack = sp; *targetContinuation = continuation; @@ -2080,39 +2122,38 @@ findUnwindTarget(MyThread* t, void** targetIp, void** targetFrame, *targetIp = ip; *targetFrame = 0; *targetStack = static_cast(stack) - + t->arch->frameReturnAddressSize(); + + t->arch->frameReturnAddressSize(); *targetContinuation = continuation; while (Continuations and *targetContinuation) { - object c = *targetContinuation; + GcContinuation* c = *targetContinuation; - object method = continuationMethod(t, c); + GcMethod* method = c->method(); - void* handler = findExceptionHandler - (t, method, continuationAddress(t, c)); + void* handler = findExceptionHandler(t, method, c->address()); if (handler) { t->exceptionHandler = handler; - t->exceptionStackAdjustment - = (stackOffsetFromFrame(t, method) - - ((continuationFramePointerOffset(t, c) / BytesPerWord) - - t->arch->framePointerOffset() - + t->arch->frameReturnAddressSize())) * BytesPerWord; + t->exceptionStackAdjustment + = (stackOffsetFromFrame(t, method) + - ((c->framePointerOffset() / BytesPerWord) + - t->arch->framePointerOffset() + + t->arch->frameReturnAddressSize())) * BytesPerWord; - t->exceptionOffset - = localOffset(t, localSize(t, method), method) * BytesPerWord; + t->exceptionOffset = localOffset(t, localSize(t, method), method) + * BytesPerWord; break; } else if (t->exception) { - releaseLock(t, method, - reinterpret_cast(c) - + ContinuationBody - + continuationReturnAddressOffset(t, c) + releaseLock(t, + method, + reinterpret_cast(c) + ContinuationBody + + c->returnAddressOffset() - t->arch->returnAddressOffset()); } - *targetContinuation = continuationNext(t, c); + *targetContinuation = c->next(); } } @@ -2120,39 +2161,41 @@ findUnwindTarget(MyThread* t, void** targetIp, void** targetFrame, } } -object -makeCurrentContinuation(MyThread* t, void** targetIp, void** targetStack) +GcContinuation* makeCurrentContinuation(MyThread* t, + void** targetIp, + void** targetStack) { void* ip = getIp(t); void* stack = t->stack; - object context = t->continuation - ? continuationContext(t, t->continuation) - : makeContinuationContext(t, 0, 0, 0, 0, t->trace->originalMethod); + GcContinuationContext* context + = t->continuation + ? t->continuation->context() + : makeContinuationContext(t, 0, 0, 0, 0, t->trace->originalMethod); PROTECT(t, context); - object target = t->trace->targetMethod; + GcMethod* target = t->trace->targetMethod; PROTECT(t, target); - object first = 0; + GcContinuation* first = 0; PROTECT(t, first); - object last = 0; + GcContinuation* last = 0; PROTECT(t, last); bool mostRecent = true; *targetIp = 0; while (*targetIp == 0) { - object method = methodForIp(t, ip); + GcMethod* method = methodForIp(t, ip); if (method) { PROTECT(t, method); void** top = static_cast(stack) - + t->arch->frameReturnAddressSize() - + t->arch->frameFooterSize(); + + t->arch->frameReturnAddressSize() + + t->arch->frameFooterSize(); unsigned argumentFootprint - = t->arch->argumentFootprint(methodParameterFootprint(t, target)); + = t->arch->argumentFootprint(target->parameterFootprint()); unsigned alignment = t->arch->stackAlignmentInWords(); if (avian::codegen::TailCalls and argumentFootprint > alignment) { top += argumentFootprint - alignment; @@ -2162,28 +2205,30 @@ makeCurrentContinuation(MyThread* t, void** targetIp, void** targetStack) nextFrame(t, &nextIp, &stack, method, target, mostRecent); void** bottom = static_cast(stack) - + t->arch->frameReturnAddressSize(); + + t->arch->frameReturnAddressSize(); unsigned frameSize = bottom - top; - unsigned totalSize = frameSize - + t->arch->frameFooterSize() - + t->arch->argumentFootprint(methodParameterFootprint(t, method)); + unsigned totalSize + = frameSize + t->arch->frameFooterSize() + + t->arch->argumentFootprint(method->parameterFootprint()); - object c = makeContinuation - (t, 0, context, method, ip, - (frameSize - + t->arch->frameFooterSize() - + t->arch->returnAddressOffset() - - t->arch->frameReturnAddressSize()) * BytesPerWord, - (frameSize - + t->arch->frameFooterSize() - + t->arch->framePointerOffset() - - t->arch->frameReturnAddressSize()) * BytesPerWord, - totalSize); + GcContinuation* c = makeContinuation( + t, + 0, + context, + method, + ip, + (frameSize + t->arch->frameFooterSize() + + t->arch->returnAddressOffset() - t->arch->frameReturnAddressSize()) + * BytesPerWord, + (frameSize + t->arch->frameFooterSize() + + t->arch->framePointerOffset() - t->arch->frameReturnAddressSize()) + * BytesPerWord, + totalSize); - memcpy(&continuationBody(t, c, 0), top, totalSize * BytesPerWord); + memcpy(c->body().begin(), top, totalSize * BytesPerWord); if (last) { - set(t, last, ContinuationNext, c); + last->setNext(t, c); } else { first = c; } @@ -2195,25 +2240,24 @@ makeCurrentContinuation(MyThread* t, void** targetIp, void** targetStack) } else { *targetIp = ip; *targetStack = static_cast(stack) - + t->arch->frameReturnAddressSize(); + + t->arch->frameReturnAddressSize(); } mostRecent = false; } expect(t, last); - set(t, last, ContinuationNext, t->continuation); + last->setNext(t, t->continuation); return first; } -void NO_RETURN -unwind(MyThread* t) +void NO_RETURN unwind(MyThread* t) { void* ip; void* frame; void* stack; - object continuation; + GcContinuation* continuation; findUnwindTarget(t, &ip, &frame, &stack, &continuation); t->trace->targetMethod = 0; @@ -2224,94 +2268,93 @@ unwind(MyThread* t) vmJump(ip, frame, stack, t, 0, 0); } -class MyCheckpoint: public Thread::Checkpoint { +class MyCheckpoint : public Thread::Checkpoint { public: - MyCheckpoint(MyThread* t): Checkpoint(t) { } + MyCheckpoint(MyThread* t) : Checkpoint(t) + { + } - virtual void unwind() { + virtual void unwind() + { local::unwind(static_cast(t)); } }; -uintptr_t -defaultThunk(MyThread* t); +uintptr_t defaultThunk(MyThread* t); -uintptr_t -nativeThunk(MyThread* t); +uintptr_t nativeThunk(MyThread* t); -uintptr_t -bootNativeThunk(MyThread* t); +uintptr_t bootNativeThunk(MyThread* t); -uintptr_t -aioobThunk(MyThread* t); +uintptr_t aioobThunk(MyThread* t); -uintptr_t -stackOverflowThunk(MyThread* t); +uintptr_t stackOverflowThunk(MyThread* t); -uintptr_t -virtualThunk(MyThread* t, unsigned index); +uintptr_t virtualThunk(MyThread* t, unsigned index); -bool -unresolved(MyThread* t, uintptr_t methodAddress); +bool unresolved(MyThread* t, uintptr_t methodAddress); -uintptr_t -methodAddress(Thread* t, object method) +uintptr_t methodAddress(Thread* t, GcMethod* method) { - if (methodFlags(t, method) & ACC_NATIVE) { + if (method->flags() & ACC_NATIVE) { return bootNativeThunk(static_cast(t)); } else { return methodCompiled(t, method); } } -void -tryInitClass(MyThread* t, object class_) +void tryInitClass(MyThread* t, GcClass* class_) { initClass(t, class_); } -void -compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, - object method); +void compile(MyThread* t, + FixedAllocator* allocator, + BootContext* bootContext, + GcMethod* method); -object -resolveMethod(Thread* t, object pair) +GcMethod* resolveMethod(Thread* t, GcPair* pair) { - object reference = pairSecond(t, pair); + GcReference* reference = cast(t, pair->second()); PROTECT(t, reference); - object class_ = resolveClassInObject - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), reference, - ReferenceClass); + GcClass* class_ = resolveClassInObject( + t, + cast(t, pair->first())->class_()->loader(), + reference, + ReferenceClass); - return findInHierarchy - (t, class_, referenceName(t, reference), referenceSpec(t, reference), - findMethodInClass, Machine::NoSuchMethodErrorType); + return cast(t, + findInHierarchy(t, + class_, + reference->name(), + reference->spec(), + findMethodInClass, + GcNoSuchMethodError::Type)); } -bool -methodAbstract(Thread* t, object method) +bool methodAbstract(Thread* t UNUSED, GcMethod* method) { - return methodCode(t, method) == 0 - and (methodFlags(t, method) & ACC_NATIVE) == 0; + return method->code() == 0 and (method->flags() & ACC_NATIVE) == 0; } -int64_t -prepareMethodForCall(MyThread* t, object target) +int64_t prepareMethodForCall(MyThread* t, GcMethod* target) { if (methodAbstract(t, target)) { - throwNew(t, Machine::AbstractMethodErrorType, "%s.%s%s", - &byteArrayBody(t, className(t, methodClass(t, target)), 0), - &byteArrayBody(t, methodName(t, target), 0), - &byteArrayBody(t, methodSpec(t, target), 0)); - } else { + throwNew(t, + GcAbstractMethodError::Type, + "%s.%s%s", + target->class_()->name()->body().begin(), + target->name()->body().begin(), + target->spec()->body().begin()); + } else { if (unresolved(t, methodAddress(t, target))) { PROTECT(t, target); - + compile(t, codeAllocator(t), 0, target); } - if (methodFlags(t, target) & ACC_NATIVE) { + if (target->flags() & ACC_NATIVE) { t->trace->nativeMethod = target; } @@ -2319,63 +2362,63 @@ prepareMethodForCall(MyThread* t, object target) } } -int64_t -findInterfaceMethodFromInstance(MyThread* t, object method, object instance) +int64_t findInterfaceMethodFromInstance(MyThread* t, + GcMethod* method, + object instance) { if (instance) { - return prepareMethodForCall - (t, findInterfaceMethod(t, method, objectClass(t, instance))); + return prepareMethodForCall( + t, findInterfaceMethod(t, method, objectClass(t, instance))); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -int64_t -findInterfaceMethodFromInstanceAndReference -(MyThread* t, object pair, object instance) +int64_t findInterfaceMethodFromInstanceAndReference(MyThread* t, + GcPair* pair, + object instance) { PROTECT(t, instance); - object method = resolveMethod(t, pair); + GcMethod* method = resolveMethod(t, pair); return findInterfaceMethodFromInstance(t, method, instance); } -void -checkMethod(Thread* t, object method, bool shouldBeStatic) +void checkMethod(Thread* t, GcMethod* method, bool shouldBeStatic) { - if (((methodFlags(t, method) & ACC_STATIC) == 0) == shouldBeStatic) { - throwNew(t, Machine::IncompatibleClassChangeErrorType, + if (((method->flags() & ACC_STATIC) == 0) == shouldBeStatic) { + throwNew(t, + GcIncompatibleClassChangeError::Type, "expected %s.%s%s to be %s", - &byteArrayBody(t, className(t, methodClass(t, method)), 0), - &byteArrayBody(t, methodName(t, method), 0), - &byteArrayBody(t, methodSpec(t, method), 0), + method->class_()->name()->body().begin(), + method->name()->body().begin(), + method->spec()->body().begin(), shouldBeStatic ? "static" : "non-static"); } } -void -checkField(Thread* t, object field, bool shouldBeStatic) +void checkField(Thread* t, GcField* field, bool shouldBeStatic) { - if (((fieldFlags(t, field) & ACC_STATIC) == 0) == shouldBeStatic) { - throwNew(t, Machine::IncompatibleClassChangeErrorType, + if (((field->flags() & ACC_STATIC) == 0) == shouldBeStatic) { + throwNew(t, + GcIncompatibleClassChangeError::Type, "expected %s.%s to be %s", - &byteArrayBody(t, className(t, fieldClass(t, field)), 0), - &byteArrayBody(t, fieldName(t, field), 0), + field->class_()->name()->body().begin(), + field->name()->body().begin(), shouldBeStatic ? "static" : "non-static"); } } -int64_t -findSpecialMethodFromReference(MyThread* t, object pair) +int64_t findSpecialMethodFromReference(MyThread* t, GcPair* pair) { PROTECT(t, pair); - object target = resolveMethod(t, pair); + GcMethod* target = resolveMethod(t, pair); - object class_ = methodClass(t, pairFirst(t, pair)); + GcClass* class_ = cast(t, pair->first())->class_(); if (isSpecialMethod(t, target, class_)) { - target = findVirtualMethod(t, target, classSuper(t, class_)); + target = findVirtualMethod(t, target, class_->super()); } checkMethod(t, target, false); @@ -2383,22 +2426,22 @@ findSpecialMethodFromReference(MyThread* t, object pair) return prepareMethodForCall(t, target); } -int64_t -findStaticMethodFromReference(MyThread* t, object pair) +int64_t findStaticMethodFromReference(MyThread* t, GcPair* pair) { - object target = resolveMethod(t, pair); + GcMethod* target = resolveMethod(t, pair); checkMethod(t, target, true); return prepareMethodForCall(t, target); } -int64_t -findVirtualMethodFromReference(MyThread* t, object pair, object instance) +int64_t findVirtualMethodFromReference(MyThread* t, + GcPair* pair, + object instance) { PROTECT(t, instance); - object target = resolveMethod(t, pair); + GcMethod* target = resolveMethod(t, pair); target = findVirtualMethod(t, target, objectClass(t, instance)); @@ -2407,31 +2450,31 @@ findVirtualMethodFromReference(MyThread* t, object pair, object instance) return prepareMethodForCall(t, target); } -int64_t -getMethodAddress(MyThread* t, object target) +int64_t getMethodAddress(MyThread* t, GcMethod* target) { return prepareMethodForCall(t, target); } -int64_t -getJClassFromReference(MyThread* t, object pair) +int64_t getJClassFromReference(MyThread* t, GcPair* pair) { - return reinterpret_cast - (getJClass - (t, resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))))); + return reinterpret_cast(getJClass( + t, + resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()))); } -unsigned -traceSize(Thread* t) +unsigned traceSize(Thread* t) { - class Counter: public Processor::StackVisitor { + class Counter : public Processor::StackVisitor { public: - Counter(): count(0) { } + Counter() : count(0) + { + } - virtual bool visit(Processor::StackWalker*) { - ++ count; + virtual bool visit(Processor::StackWalker*) + { + ++count; return true; } @@ -2440,22 +2483,22 @@ traceSize(Thread* t) t->m->processor->walkStack(t, &counter); - return FixedSizeOfArray + (counter.count * ArrayElementSizeOfArray) - + (counter.count * FixedSizeOfTraceElement); + return pad(GcArray::FixedSize) + + (counter.count * pad(ArrayElementSizeOfArray)) + + (counter.count * pad(GcTraceElement::FixedSize)); } -void NO_RETURN -throwArithmetic(MyThread* t) +void NO_RETURN throwArithmetic(MyThread* t) { - if (ensure(t, FixedSizeOfArithmeticException + traceSize(t))) { + if (ensure(t, GcArithmeticException::FixedSize + traceSize(t))) { atomicOr(&(t->flags), Thread::TracingFlag); THREAD_RESOURCE0(t, atomicAnd(&(t->flags), ~Thread::TracingFlag)); - throwNew(t, Machine::ArithmeticExceptionType); + throwNew(t, GcArithmeticException::Type); } else { // not enough memory available for a new exception and stack trace // -- use a preallocated instance instead - throw_(t, root(t, Machine::ArithmeticException)); + throw_(t, roots(t)->arithmeticException()); } } @@ -2495,76 +2538,59 @@ int64_t moduloInt(MyThread* t, int32_t b, int32_t a) } } -uint64_t -makeBlankObjectArray(MyThread* t, object class_, int32_t length) +uint64_t makeBlankObjectArray(MyThread* t, GcClass* class_, int32_t length) { if (length >= 0) { return reinterpret_cast(makeObjectArray(t, class_, length)); } else { - throwNew(t, Machine::NegativeArraySizeExceptionType, "%d", length); + throwNew(t, GcNegativeArraySizeException::Type, "%d", length); } } -uint64_t -makeBlankObjectArrayFromReference(MyThread* t, object pair, - int32_t length) +uint64_t makeBlankObjectArrayFromReference(MyThread* t, + GcPair* pair, + int32_t length) { - return makeBlankObjectArray - (t, resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))), length); + return makeBlankObjectArray( + t, + resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()), + length); } -uint64_t -makeBlankArray(MyThread* t, unsigned type, int32_t length) +uint64_t makeBlankArray(MyThread* t, unsigned type, int32_t length) { if (length >= 0) { - object (*constructor)(Thread*, uintptr_t); switch (type) { case T_BOOLEAN: - constructor = makeBooleanArray; - break; - + return reinterpret_cast(makeBooleanArray(t, length)); case T_CHAR: - constructor = makeCharArray; - break; - + return reinterpret_cast(makeCharArray(t, length)); case T_FLOAT: - constructor = makeFloatArray; - break; - + return reinterpret_cast(makeFloatArray(t, length)); case T_DOUBLE: - constructor = makeDoubleArray; - break; - + return reinterpret_cast(makeDoubleArray(t, length)); case T_BYTE: - constructor = makeByteArray; - break; - + return reinterpret_cast(makeByteArray(t, length)); case T_SHORT: - constructor = makeShortArray; - break; - + return reinterpret_cast(makeShortArray(t, length)); case T_INT: - constructor = makeIntArray; - break; - + return reinterpret_cast(makeIntArray(t, length)); case T_LONG: - constructor = makeLongArray; - break; - - default: abort(t); + return reinterpret_cast(makeLongArray(t, length)); + default: + abort(t); } - - return reinterpret_cast(constructor(t, length)); } else { - throwNew(t, Machine::NegativeArraySizeExceptionType, "%d", length); + throwNew(t, GcNegativeArraySizeException::Type, "%d", length); } } -uint64_t -lookUpAddress(int32_t key, uintptr_t* start, int32_t count, - uintptr_t default_) +uint64_t lookUpAddress(int32_t key, + uintptr_t* start, + int32_t count, + uintptr_t default_) { int32_t bottom = 0; int32_t top = count; @@ -2585,51 +2611,48 @@ lookUpAddress(int32_t key, uintptr_t* start, int32_t count, return default_; } -void -setMaybeNull(MyThread* t, object o, unsigned offset, object value) +void setMaybeNull(MyThread* t, object o, unsigned offset, object value) { if (LIKELY(o)) { - set(t, o, offset, value); + setField(t, o, offset, value); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -void -acquireMonitorForObject(MyThread* t, object o) +void acquireMonitorForObject(MyThread* t, object o) { if (LIKELY(o)) { acquire(t, o); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -void -acquireMonitorForObjectOnEntrance(MyThread* t, object o) +void acquireMonitorForObjectOnEntrance(MyThread* t, object o) { if (LIKELY(o)) { t->methodLockIsClean = false; acquire(t, o); t->methodLockIsClean = true; } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -void -releaseMonitorForObject(MyThread* t, object o) +void releaseMonitorForObject(MyThread* t, object o) { if (LIKELY(o)) { release(t, o); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -object -makeMultidimensionalArray2(MyThread* t, object class_, uintptr_t* countStack, - int32_t dimensions) +object makeMultidimensionalArray2(MyThread* t, + GcClass* class_, + uintptr_t* countStack, + int32_t dimensions) { PROTECT(t, class_); @@ -2637,7 +2660,9 @@ makeMultidimensionalArray2(MyThread* t, object class_, uintptr_t* countStack, for (int i = dimensions - 1; i >= 0; --i) { RUNTIME_ARRAY_BODY(counts)[i] = countStack[dimensions - i - 1]; if (UNLIKELY(RUNTIME_ARRAY_BODY(counts)[i] < 0)) { - throwNew(t, Machine::NegativeArraySizeExceptionType, "%d", + throwNew(t, + GcNegativeArraySizeException::Type, + "%d", RUNTIME_ARRAY_BODY(counts)[i]); return 0; } @@ -2652,149 +2677,156 @@ makeMultidimensionalArray2(MyThread* t, object class_, uintptr_t* countStack, return array; } -uint64_t -makeMultidimensionalArray(MyThread* t, object class_, int32_t dimensions, - int32_t offset) +uint64_t makeMultidimensionalArray(MyThread* t, + GcClass* class_, + int32_t dimensions, + int32_t offset) { - return reinterpret_cast - (makeMultidimensionalArray2 - (t, class_, static_cast(t->stack) + offset, dimensions)); + return reinterpret_cast(makeMultidimensionalArray2( + t, class_, static_cast(t->stack) + offset, dimensions)); } -uint64_t -makeMultidimensionalArrayFromReference(MyThread* t, object pair, - int32_t dimensions, - int32_t offset) +uint64_t makeMultidimensionalArrayFromReference(MyThread* t, + GcPair* pair, + int32_t dimensions, + int32_t offset) { - return makeMultidimensionalArray - (t, resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))), dimensions, offset); + return makeMultidimensionalArray( + t, + resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()), + dimensions, + offset); } -void NO_RETURN -throwArrayIndexOutOfBounds(MyThread* t) +void NO_RETURN throwArrayIndexOutOfBounds(MyThread* t) { - if (ensure(t, FixedSizeOfArrayIndexOutOfBoundsException + traceSize(t))) { + if (ensure(t, GcArrayIndexOutOfBoundsException::FixedSize + traceSize(t))) { atomicOr(&(t->flags), Thread::TracingFlag); THREAD_RESOURCE0(t, atomicAnd(&(t->flags), ~Thread::TracingFlag)); - throwNew(t, Machine::ArrayIndexOutOfBoundsExceptionType); + throwNew(t, GcArrayIndexOutOfBoundsException::Type); } else { // not enough memory available for a new exception and stack trace // -- use a preallocated instance instead - throw_(t, root(t, Machine::ArrayIndexOutOfBoundsException)); + throw_(t, roots(t)->arrayIndexOutOfBoundsException()); } } -void NO_RETURN -throwStackOverflow(MyThread* t) +void NO_RETURN throwStackOverflow(MyThread* t) { - throwNew(t, Machine::StackOverflowErrorType); + throwNew(t, GcStackOverflowError::Type); } -void NO_RETURN -throw_(MyThread* t, object o) +void NO_RETURN throw_(MyThread* t, GcThrowable* o) { if (LIKELY(o)) { vm::throw_(t, o); } else { - throwNew(t, Machine::NullPointerExceptionType); + throwNew(t, GcNullPointerException::Type); } } -void -checkCast(MyThread* t, object class_, object o) +void checkCast(MyThread* t, GcClass* class_, object o) { if (UNLIKELY(o and not isAssignableFrom(t, class_, objectClass(t, o)))) { - object classNameFrom = className(t, objectClass(t, o)); - object classNameTo = className(t, class_); - THREAD_RUNTIME_ARRAY(t, char, classFrom, byteArrayLength(t, classNameFrom)); - THREAD_RUNTIME_ARRAY(t, char, classTo, byteArrayLength(t, classNameTo)); - replace('/', '.', RUNTIME_ARRAY_BODY(classFrom), - reinterpret_cast(&byteArrayBody(t, classNameFrom, 0))); - replace('/', '.', RUNTIME_ARRAY_BODY(classTo), - reinterpret_cast(&byteArrayBody(t, classNameTo, 0))); - throwNew - (t, Machine::ClassCastExceptionType, "%s cannot be cast to %s", - RUNTIME_ARRAY_BODY(classFrom), RUNTIME_ARRAY_BODY(classTo)); + GcByteArray* classNameFrom = objectClass(t, o)->name(); + GcByteArray* classNameTo = class_->name(); + THREAD_RUNTIME_ARRAY(t, char, classFrom, classNameFrom->length()); + THREAD_RUNTIME_ARRAY(t, char, classTo, classNameTo->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(classFrom), + reinterpret_cast(classNameFrom->body().begin())); + replace('/', + '.', + RUNTIME_ARRAY_BODY(classTo), + reinterpret_cast(classNameTo->body().begin())); + throwNew(t, + GcClassCastException::Type, + "%s cannot be cast to %s", + RUNTIME_ARRAY_BODY(classFrom), + RUNTIME_ARRAY_BODY(classTo)); } } -void -checkCastFromReference(MyThread* t, object pair, object o) +void checkCastFromReference(MyThread* t, GcPair* pair, object o) { PROTECT(t, o); - object c = resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))); + GcClass* c + = resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()); checkCast(t, c, o); } -object -resolveField(Thread* t, object pair) +GcField* resolveField(Thread* t, GcPair* pair) { - object reference = pairSecond(t, pair); + GcReference* reference = cast(t, pair->second()); PROTECT(t, reference); - object class_ = resolveClassInObject - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), reference, - ReferenceClass); + GcClass* class_ = resolveClassInObject( + t, + cast(t, pair->first())->class_()->loader(), + reference, + ReferenceClass); - return findInHierarchy - (t, class_, referenceName(t, reference), referenceSpec(t, reference), - findFieldInClass, Machine::NoSuchFieldErrorType); + return cast(t, + findInHierarchy(t, + class_, + reference->name(), + reference->spec(), + findFieldInClass, + GcNoSuchFieldError::Type)); } -uint64_t -getFieldValue(Thread* t, object target, object field) +uint64_t getFieldValue(Thread* t, object target, GcField* field) { - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: - return fieldAtOffset(target, fieldOffset(t, field)); + return fieldAtOffset(target, field->offset()); case CharField: case ShortField: - return fieldAtOffset(target, fieldOffset(t, field)); + return fieldAtOffset(target, field->offset()); case FloatField: case IntField: - return fieldAtOffset(target, fieldOffset(t, field)); + return fieldAtOffset(target, field->offset()); case DoubleField: case LongField: - return fieldAtOffset(target, fieldOffset(t, field)); + return fieldAtOffset(target, field->offset()); case ObjectField: - return fieldAtOffset(target, fieldOffset(t, field)); + return fieldAtOffset(target, field->offset()); default: abort(t); } } -uint64_t -getStaticFieldValueFromReference(MyThread* t, object pair) +uint64_t getStaticFieldValueFromReference(MyThread* t, GcPair* pair) { - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); ACQUIRE_FIELD_FOR_READ(t, field); - return getFieldValue(t, classStaticTable(t, fieldClass(t, field)), field); + return getFieldValue(t, field->class_()->staticTable(), field); } -uint64_t -getFieldValueFromReference(MyThread* t, object pair, object instance) +uint64_t getFieldValueFromReference(MyThread* t, GcPair* pair, object instance) { PROTECT(t, instance); - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); @@ -2802,82 +2834,84 @@ getFieldValueFromReference(MyThread* t, object pair, object instance) return getFieldValue(t, instance, field); } -void -setStaticLongFieldValueFromReference(MyThread* t, object pair, uint64_t value) +void setStaticLongFieldValueFromReference(MyThread* t, + GcPair* pair, + uint64_t value) { - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); ACQUIRE_FIELD_FOR_WRITE(t, field); - fieldAtOffset - (classStaticTable(t, fieldClass(t, field)), fieldOffset(t, field)) = value; + fieldAtOffset(field->class_()->staticTable(), field->offset()) + = value; } -void -setLongFieldValueFromReference(MyThread* t, object pair, object instance, - uint64_t value) +void setLongFieldValueFromReference(MyThread* t, + GcPair* pair, + object instance, + uint64_t value) { PROTECT(t, instance); - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - fieldAtOffset(instance, fieldOffset(t, field)) = value; + fieldAtOffset(instance, field->offset()) = value; } -void -setStaticObjectFieldValueFromReference(MyThread* t, object pair, object value) +void setStaticObjectFieldValueFromReference(MyThread* t, + GcPair* pair, + object value) { PROTECT(t, value); - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); ACQUIRE_FIELD_FOR_WRITE(t, field); - set(t, classStaticTable(t, fieldClass(t, field)), fieldOffset(t, field), - value); + setField(t, field->class_()->staticTable(), field->offset(), value); } -void -setObjectFieldValueFromReference(MyThread* t, object pair, object instance, - object value) +void setObjectFieldValueFromReference(MyThread* t, + GcPair* pair, + object instance, + object value) { PROTECT(t, instance); PROTECT(t, value); - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - set(t, instance, fieldOffset(t, field), value); + setField(t, instance, field->offset(), value); } -void -setFieldValue(MyThread* t, object target, object field, uint32_t value) +void setFieldValue(MyThread* t, object target, GcField* field, uint32_t value) { - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: - fieldAtOffset(target, fieldOffset(t, field)) = value; + fieldAtOffset(target, field->offset()) = value; break; case CharField: case ShortField: - fieldAtOffset(target, fieldOffset(t, field)) = value; + fieldAtOffset(target, field->offset()) = value; break; case FloatField: case IntField: - fieldAtOffset(target, fieldOffset(t, field)) = value; + fieldAtOffset(target, field->offset()) = value; break; default: @@ -2885,25 +2919,25 @@ setFieldValue(MyThread* t, object target, object field, uint32_t value) } } -void -setStaticFieldValueFromReference(MyThread* t, object pair, uint32_t value) +void setStaticFieldValueFromReference(MyThread* t, GcPair* pair, uint32_t value) { - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); ACQUIRE_FIELD_FOR_WRITE(t, field); - setFieldValue(t, classStaticTable(t, fieldClass(t, field)), field, value); + setFieldValue(t, field->class_()->staticTable(), field, value); } -void -setFieldValueFromReference(MyThread* t, object pair, object instance, - uint32_t value) +void setFieldValueFromReference(MyThread* t, + GcPair* pair, + object instance, + uint32_t value) { PROTECT(t, instance); - object field = resolveField(t, pair); + GcField* field = resolveField(t, pair); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); @@ -2911,26 +2945,24 @@ setFieldValueFromReference(MyThread* t, object pair, object instance, setFieldValue(t, instance, field, value); } -uint64_t -instanceOf64(Thread* t, object class_, object o) +uint64_t instanceOf64(Thread* t, GcClass* class_, object o) { return instanceOf(t, class_, o); } -uint64_t -instanceOfFromReference(Thread* t, object pair, object o) +uint64_t instanceOfFromReference(Thread* t, GcPair* pair, object o) { PROTECT(t, o); - object c = resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))); + GcClass* c + = resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()); return instanceOf64(t, c, o); } -uint64_t -makeNewGeneral64(Thread* t, object class_) +uint64_t makeNewGeneral64(Thread* t, GcClass* class_) { PROTECT(t, class_); @@ -2939,8 +2971,7 @@ makeNewGeneral64(Thread* t, object class_) return reinterpret_cast(makeNewGeneral(t, class_)); } -uint64_t -makeNew64(Thread* t, object class_) +uint64_t makeNew64(Thread* t, GcClass* class_) { PROTECT(t, class_); @@ -2949,12 +2980,12 @@ makeNew64(Thread* t, object class_) return reinterpret_cast(makeNew(t, class_)); } -uint64_t -makeNewFromReference(Thread* t, object pair) +uint64_t makeNewFromReference(Thread* t, GcPair* pair) { - object class_ = resolveClass - (t, classLoader(t, methodClass(t, pairFirst(t, pair))), - referenceName(t, pairSecond(t, pair))); + GcClass* class_ + = resolveClass(t, + cast(t, pair->first())->class_()->loader(), + cast(t, pair->second())->name()); PROTECT(t, class_); @@ -2963,14 +2994,12 @@ makeNewFromReference(Thread* t, object pair) return makeNewGeneral64(t, class_); } -uint64_t -getJClass64(Thread* t, object class_) +uint64_t getJClass64(Thread* t, GcClass* class_) { return reinterpret_cast(getJClass(t, class_)); } -void -gcIfNecessary(MyThread* t) +void gcIfNecessary(MyThread* t) { stress(t); @@ -2986,8 +3015,7 @@ void idleIfNecessary(MyThread* t) } } -unsigned -resultSize(MyThread* t, unsigned code) +unsigned resultSize(MyThread* t, unsigned code) { switch (code) { case ByteField: @@ -3033,25 +3061,26 @@ ir::Value* popField(MyThread* t, Frame* frame, int code) case ObjectField: return frame->pop(ir::Type::object()); - default: abort(t); + default: + abort(t); } } -bool -useLongJump(MyThread* t, uintptr_t target) +bool useLongJump(MyThread* t, uintptr_t target) { uintptr_t reach = t->arch->maximumImmediateJump(); FixedAllocator* a = codeAllocator(t); uintptr_t start = reinterpret_cast(a->memory.begin()); uintptr_t end = reinterpret_cast(a->memory.begin()) + a->memory.count; - assert(t, end - start < reach); + assertT(t, end - start < reach); return (target > end && (target - start) > reach) - or (target < start && (end - target) > reach); + or (target < start && (end - target) > reach); } -void compileSafePoint(MyThread* t, Compiler* c, Frame* frame) { +void compileSafePoint(MyThread* t, Compiler* c, Frame* frame) +{ c->call(c->constant(getThunk(t, idleIfNecessaryThunk), ir::Type::iptr()), 0, frame->trace(0, 0), @@ -3062,14 +3091,15 @@ void compileSafePoint(MyThread* t, Compiler* c, Frame* frame) { void compileDirectInvoke(MyThread* t, Frame* frame, - object target, + GcMethod* target, bool tailCall, bool useThunk, avian::codegen::Promise* addressPromise) { avian::codegen::Compiler* c = frame->c; - unsigned flags = (avian::codegen::TailCalls and tailCall ? Compiler::TailJump : 0); + unsigned flags + = (avian::codegen::TailCalls and tailCall ? Compiler::TailJump : 0); unsigned traceFlags; if (addressPromise == 0 and useLongJump(t, methodAddress(t, target))) { @@ -3079,9 +3109,8 @@ void compileDirectInvoke(MyThread* t, traceFlags = 0; } - if (useThunk - or (avian::codegen::TailCalls and tailCall and (methodFlags(t, target) & ACC_NATIVE))) - { + if (useThunk or (avian::codegen::TailCalls and tailCall + and (target->flags() & ACC_NATIVE))) { if (frame->context->bootContext == 0) { flags |= Compiler::Aligned; } @@ -3091,9 +3120,9 @@ void compileDirectInvoke(MyThread* t, TraceElement* trace = frame->trace(target, traceFlags); - avian::codegen::Promise* returnAddressPromise = new - (frame->context->zone.allocate(sizeof(TraceElementPromise))) - TraceElementPromise(t->m->system, trace); + avian::codegen::Promise* returnAddressPromise + = new (frame->context->zone.allocate(sizeof(TraceElementPromise))) + TraceElementPromise(t->m->system, trace); frame->stackCall( c->promiseConstant(returnAddressPromise, ir::Type::iptr()), @@ -3106,10 +3135,9 @@ void compileDirectInvoke(MyThread* t, ir::Type::iptr(), TARGET_THREAD_TAILADDRESS)); - c->exit(c->constant((methodFlags(t, target) & ACC_NATIVE) - ? nativeThunk(t) - : defaultThunk(t), - ir::Type::iptr())); + c->exit(c->constant( + (target->flags() & ACC_NATIVE) ? nativeThunk(t) : defaultThunk(t), + ir::Type::iptr())); } else { return frame->stackCall(c->constant(defaultThunk(t), ir::Type::iptr()), target, @@ -3126,31 +3154,30 @@ void compileDirectInvoke(MyThread* t, address, target, flags, - tailCall ? 0 - : frame->trace( - (methodFlags(t, target) & ACC_NATIVE) ? target : 0, 0)); + tailCall ? 0 : frame->trace((target->flags() & ACC_NATIVE) ? target : 0, + 0)); } } -bool -compileDirectInvoke(MyThread* t, Frame* frame, object target, bool tailCall) +bool compileDirectInvoke(MyThread* t, + Frame* frame, + GcMethod* target, + bool tailCall) { // don't bother calling an empty method unless calling it might // cause the class to be initialized, which may have side effects - if (emptyMethod(t, target) - and (not classNeedsInit(t, methodClass(t, target)))) - { - frame->popFootprint(methodParameterFootprint(t, target)); + if (emptyMethod(t, target) and (not classNeedsInit(t, target->class_()))) { + frame->popFootprint(target->parameterFootprint()); tailCall = false; } else { BootContext* bc = frame->context->bootContext; if (bc) { - if ((methodClass(t, target) == methodClass(t, frame->context->method) - or (not classNeedsInit(t, methodClass(t, target)))) - and (not (avian::codegen::TailCalls and tailCall - and (methodFlags(t, target) & ACC_NATIVE)))) - { - avian::codegen::Promise* p = new(bc->zone) avian::codegen::ListenPromise(t->m->system, bc->zone); + if ((target->class_() == frame->context->method->class_() + or (not classNeedsInit(t, target->class_()))) + and (not(avian::codegen::TailCalls and tailCall + and (target->flags() & ACC_NATIVE)))) { + avian::codegen::Promise* p = new (bc->zone) + avian::codegen::ListenPromise(t->m->system, bc->zone); PROTECT(t, target); object pointer = makePointer(t, p); @@ -3161,8 +3188,7 @@ compileDirectInvoke(MyThread* t, Frame* frame, object target, bool tailCall) compileDirectInvoke(t, frame, target, tailCall, true, 0); } } else if (unresolved(t, methodAddress(t, target)) - or classNeedsInit(t, methodClass(t, target))) - { + or classNeedsInit(t, target->class_())) { compileDirectInvoke(t, frame, target, tailCall, true, 0); } else { compileDirectInvoke(t, frame, target, tailCall, false, 0); @@ -3174,7 +3200,7 @@ compileDirectInvoke(MyThread* t, Frame* frame, object target, bool tailCall) void compileReferenceInvoke(Frame* frame, ir::Value* method, - object reference, + GcReference* reference, bool isStatic, bool tailCall) { @@ -3185,15 +3211,18 @@ void compileReferenceInvoke(Frame* frame, frame->trace(0, 0)); } -void -compileDirectReferenceInvoke(MyThread* t, Frame* frame, Thunk thunk, - object reference, bool isStatic, bool tailCall) +void compileDirectReferenceInvoke(MyThread* t, + Frame* frame, + Thunk thunk, + GcReference* reference, + bool isStatic, + bool tailCall) { avian::codegen::Compiler* c = frame->c; PROTECT(t, reference); - object pair = makePair(t, frame->context->method, reference); + GcPair* pair = makePair(t, frame->context->method, reference); compileReferenceInvoke( frame, @@ -3211,16 +3240,18 @@ compileDirectReferenceInvoke(MyThread* t, Frame* frame, Thunk thunk, void compileAbstractInvoke(Frame* frame, ir::Value* method, - object target, + GcMethod* target, bool tailCall) { frame->stackCall( method, target, tailCall ? Compiler::TailJump : 0, frame->trace(0, 0)); } -void -compileDirectAbstractInvoke(MyThread* t, Frame* frame, Thunk thunk, - object target, bool tailCall) +void compileDirectAbstractInvoke(MyThread* t, + Frame* frame, + Thunk thunk, + GcMethod* target, + bool tailCall) { avian::codegen::Compiler* c = frame->c; @@ -3237,18 +3268,17 @@ compileDirectAbstractInvoke(MyThread* t, Frame* frame, Thunk thunk, tailCall); } -void -handleMonitorEvent(MyThread* t, Frame* frame, intptr_t function) +void handleMonitorEvent(MyThread* t, Frame* frame, intptr_t function) { avian::codegen::Compiler* c = frame->c; - object method = frame->context->method; + GcMethod* method = frame->context->method; - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_SYNCHRONIZED) { ir::Value* lock; - if (methodFlags(t, method) & ACC_STATIC) { + if (method->flags() & ACC_STATIC) { PROTECT(t, method); - lock = frame->append(methodClass(t, method)); + lock = frame->append(method->class_()); } else { lock = loadLocal( frame->context, 1, ir::Type::object(), savedTargetIndex(t, method)); @@ -3264,14 +3294,11 @@ handleMonitorEvent(MyThread* t, Frame* frame, intptr_t function) } } -void -handleEntrance(MyThread* t, Frame* frame) +void handleEntrance(MyThread* t, Frame* frame) { - object method = frame->context->method; + GcMethod* method = frame->context->method; - if ((methodFlags(t, method) & (ACC_SYNCHRONIZED | ACC_STATIC)) - == ACC_SYNCHRONIZED) - { + if ((method->flags() & (ACC_SYNCHRONIZED | ACC_STATIC)) == ACC_SYNCHRONIZED) { // save 'this' pointer in case it is overwritten. unsigned index = savedTargetIndex(t, method); storeLocal(frame->context, @@ -3282,28 +3309,24 @@ handleEntrance(MyThread* t, Frame* frame) frame->set(index, ir::Type::object()); } - handleMonitorEvent - (t, frame, getThunk(t, acquireMonitorForObjectOnEntranceThunk)); + handleMonitorEvent( + t, frame, getThunk(t, acquireMonitorForObjectOnEntranceThunk)); } -void -handleExit(MyThread* t, Frame* frame) +void handleExit(MyThread* t, Frame* frame) { - handleMonitorEvent - (t, frame, getThunk(t, releaseMonitorForObjectThunk)); + handleMonitorEvent(t, frame, getThunk(t, releaseMonitorForObjectThunk)); } -bool -inTryBlock(MyThread* t, object code, unsigned ip) +bool inTryBlock(MyThread* t UNUSED, GcCode* code, unsigned ip) { - object table = codeExceptionHandlerTable(t, code); + GcExceptionHandlerTable* table + = cast(t, code->exceptionHandlerTable()); if (table) { - unsigned length = exceptionHandlerTableLength(t, table); + unsigned length = table->length(); for (unsigned i = 0; i < length; ++i) { - uint64_t eh = exceptionHandlerTableBody(t, table, i); - if (ip >= exceptionHandlerStart(eh) - and ip < exceptionHandlerEnd(eh)) - { + uint64_t eh = table->body()[i]; + if (ip >= exceptionHandlerStart(eh) and ip < exceptionHandlerEnd(eh)) { return true; } } @@ -3311,17 +3334,15 @@ inTryBlock(MyThread* t, object code, unsigned ip) return false; } -bool -needsReturnBarrier(MyThread* t, object method) +bool needsReturnBarrier(MyThread* t UNUSED, GcMethod* method) { - return (methodFlags(t, method) & ConstructorFlag) - and (classVmFlags(t, methodClass(t, method)) & HasFinalMemberFlag); + return (method->flags() & ConstructorFlag) + and (method->class_()->vmFlags() & HasFinalMemberFlag); } -bool -returnsNext(MyThread* t, object code, unsigned ip) +bool returnsNext(MyThread* t, GcCode* code, unsigned ip) { - switch (codeBody(t, code, ip)) { + switch (code->body()[ip]) { case return_: case areturn: case ireturn: @@ -3333,7 +3354,7 @@ returnsNext(MyThread* t, object code, unsigned ip) case goto_: { uint32_t offset = codeReadInt16(t, code, ++ip); uint32_t newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); return returnsNext(t, code, newIp); } @@ -3341,8 +3362,8 @@ returnsNext(MyThread* t, object code, unsigned ip) case goto_w: { uint32_t offset = codeReadInt32(t, code, ++ip); uint32_t newIp = (ip - 5) + offset; - assert(t, newIp < codeLength(t, code)); - + assertT(t, newIp < code->length()); + return returnsNext(t, code, newIp); } @@ -3351,47 +3372,64 @@ returnsNext(MyThread* t, object code, unsigned ip) } } -bool -isTailCall(MyThread* t, object code, unsigned ip, object caller, - int calleeReturnCode, object calleeClassName, - object calleeMethodName, object calleeMethodSpec) +bool isTailCall(MyThread* t, + GcCode* code, + unsigned ip, + GcMethod* caller, + int calleeReturnCode, + GcByteArray* calleeClassName, + GcByteArray* calleeMethodName, + GcByteArray* calleeMethodSpec) { return avian::codegen::TailCalls - and ((methodFlags(t, caller) & ACC_SYNCHRONIZED) == 0) - and (not inTryBlock(t, code, ip - 1)) - and (not needsReturnBarrier(t, caller)) - and (methodReturnCode(t, caller) == VoidField - or methodReturnCode(t, caller) == calleeReturnCode) - and returnsNext(t, code, ip) - and t->m->classpath->canTailCall - (t, caller, calleeClassName, calleeMethodName, calleeMethodSpec); + and ((caller->flags() & ACC_SYNCHRONIZED) == 0) + and (not inTryBlock(t, code, ip - 1)) + and (not needsReturnBarrier(t, caller)) + and (caller->returnCode() == VoidField + or caller->returnCode() == calleeReturnCode) + and returnsNext(t, code, ip) + and t->m->classpath->canTailCall(t, + caller, + calleeClassName, + calleeMethodName, + calleeMethodSpec); } -bool -isTailCall(MyThread* t, object code, unsigned ip, object caller, object callee) +bool isTailCall(MyThread* t, + GcCode* code, + unsigned ip, + GcMethod* caller, + GcMethod* callee) { - return isTailCall - (t, code, ip, caller, methodReturnCode(t, callee), - className(t, methodClass(t, callee)), methodName(t, callee), - methodSpec(t, callee)); + return isTailCall(t, + code, + ip, + caller, + callee->returnCode(), + callee->class_()->name(), + callee->name(), + callee->spec()); } -bool -isReferenceTailCall(MyThread* t, object code, unsigned ip, object caller, - object calleeReference) +bool isReferenceTailCall(MyThread* t, + GcCode* code, + unsigned ip, + GcMethod* caller, + GcReference* calleeReference) { - object c = referenceClass(t, calleeReference); - if (objectClass(t, c) == type(t, Machine::ClassType)) { - c = className(t, c); - } - - return isTailCall - (t, code, ip, caller, methodReferenceReturnCode(t, calleeReference), - c, referenceName(t, calleeReference), referenceSpec(t, calleeReference)); + return isTailCall(t, + code, + ip, + caller, + methodReferenceReturnCode(t, calleeReference), + calleeReference->class_(), + calleeReference->name(), + calleeReference->spec()); } -lir::TernaryOperation toCompilerJumpOp(MyThread* t, unsigned instruction) { - switch(instruction) { +lir::TernaryOperation toCompilerJumpOp(MyThread* t, unsigned instruction) +{ + switch (instruction) { case ifeq: case if_icmpeq: case if_acmpeq: @@ -3421,21 +3459,21 @@ lir::TernaryOperation toCompilerJumpOp(MyThread* t, unsigned instruction) { bool integerBranch(MyThread* t, Frame* frame, - object code, + GcCode* code, unsigned& ip, ir::Value* a, ir::Value* b, unsigned* newIpp) { - if (ip + 3 > codeLength(t, code)) { + if (ip + 3 > code->length()) { return false; } avian::codegen::Compiler* c = frame->c; - unsigned instruction = codeBody(t, code, ip++); + unsigned instruction = code->body()[ip++]; uint32_t offset = codeReadInt16(t, code, ip); uint32_t newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); ir::Value* target = frame->machineIpValue(newIp); @@ -3462,7 +3500,7 @@ lir::TernaryOperation toCompilerFloatJumpOp(MyThread* t, unsigned instruction, bool lessIfUnordered) { - switch(instruction) { + switch (instruction) { case ifeq: return lir::JumpIfFloatEqual; case ifne: @@ -3498,22 +3536,22 @@ lir::TernaryOperation toCompilerFloatJumpOp(MyThread* t, bool floatBranch(MyThread* t, Frame* frame, - object code, + GcCode* code, unsigned& ip, bool lessIfUnordered, ir::Value* a, ir::Value* b, unsigned* newIpp) { - if (ip + 3 > codeLength(t, code)) { + if (ip + 3 > code->length()) { return false; } avian::codegen::Compiler* c = frame->c; - unsigned instruction = codeBody(t, code, ip++); + unsigned instruction = code->body()[ip++]; uint32_t offset = codeReadInt16(t, code, ip); uint32_t newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); ir::Value* target = frame->machineIpValue(newIp); @@ -3524,10 +3562,8 @@ bool floatBranch(MyThread* t, case ifge: case iflt: case ifle: - c->condJump(toCompilerFloatJumpOp(t, instruction, lessIfUnordered), - a, - b, - target); + c->condJump( + toCompilerFloatJumpOp(t, instruction, lessIfUnordered), a, b, target); break; default: @@ -3548,35 +3584,31 @@ ir::Value* popLongAddress(Frame* frame) ir::Type::iptr()); } -bool -intrinsic(MyThread* t, Frame* frame, object target) +bool intrinsic(MyThread* t UNUSED, Frame* frame, GcMethod* target) { -#define MATCH(name, constant) \ - (byteArrayLength(t, name) == sizeof(constant) \ - and ::strcmp(reinterpret_cast(&byteArrayBody(t, name, 0)), \ - constant) == 0) +#define MATCH(name, constant) \ + (name->length() == sizeof(constant) \ + and ::strcmp(reinterpret_cast(name->body().begin()), constant) == 0) - object className = vm::className(t, methodClass(t, target)); + GcByteArray* className = target->class_()->name(); if (UNLIKELY(MATCH(className, "java/lang/Math"))) { avian::codegen::Compiler* c = frame->c; - if (MATCH(methodName(t, target), "sqrt") - and MATCH(methodSpec(t, target), "(D)D")) - { + if (MATCH(target->name(), "sqrt") and MATCH(target->spec(), "(D)D")) { frame->pushLarge( ir::Type::f8(), c->unaryOp(lir::FloatSquareRoot, frame->popLarge(ir::Type::f8()))); return true; - } else if (MATCH(methodName(t, target), "abs")) { - if (MATCH(methodSpec(t, target), "(I)I")) { + } else if (MATCH(target->name(), "abs")) { + if (MATCH(target->spec(), "(I)I")) { frame->push(ir::Type::i4(), c->unaryOp(lir::Absolute, frame->pop(ir::Type::i4()))); return true; - } else if (MATCH(methodSpec(t, target), "(J)J")) { + } else if (MATCH(target->spec(), "(J)J")) { frame->pushLarge( ir::Type::i8(), c->unaryOp(lir::Absolute, frame->popLarge(ir::Type::i8()))); return true; - } else if (MATCH(methodSpec(t, target), "(F)F")) { + } else if (MATCH(target->spec(), "(F)F")) { frame->push(ir::Type::f4(), c->unaryOp(lir::FloatAbsolute, frame->pop(ir::Type::f4()))); return true; @@ -3584,9 +3616,7 @@ intrinsic(MyThread* t, Frame* frame, object target) } } else if (UNLIKELY(MATCH(className, "sun/misc/Unsafe"))) { avian::codegen::Compiler* c = frame->c; - if (MATCH(methodName(t, target), "getByte") - and MATCH(methodSpec(t, target), "(J)B")) - { + if (MATCH(target->name(), "getByte") and MATCH(target->spec(), "(J)B")) { ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); frame->push(ir::Type::i4(), @@ -3594,19 +3624,17 @@ intrinsic(MyThread* t, Frame* frame, object target) c->memory(address, ir::Type::i1()), ir::Type::i4())); return true; - } else if (MATCH(methodName(t, target), "putByte") - and MATCH(methodSpec(t, target), "(JB)V")) - { + } else if (MATCH(target->name(), "putByte") + and MATCH(target->spec(), "(JB)V")) { ir::Value* value = frame->pop(ir::Type::i4()); ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); c->store(value, c->memory(address, ir::Type::i1())); return true; - } else if ((MATCH(methodName(t, target), "getShort") - and MATCH(methodSpec(t, target), "(J)S")) - or (MATCH(methodName(t, target), "getChar") - and MATCH(methodSpec(t, target), "(J)C"))) - { + } else if ((MATCH(target->name(), "getShort") + and MATCH(target->spec(), "(J)S")) + or (MATCH(target->name(), "getChar") + and MATCH(target->spec(), "(J)C"))) { ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); frame->push(ir::Type::i4(), @@ -3614,67 +3642,61 @@ intrinsic(MyThread* t, Frame* frame, object target) c->memory(address, ir::Type::i2()), ir::Type::i4())); return true; - } else if ((MATCH(methodName(t, target), "putShort") - and MATCH(methodSpec(t, target), "(JS)V")) - or (MATCH(methodName(t, target), "putChar") - and MATCH(methodSpec(t, target), "(JC)V"))) - { + } else if ((MATCH(target->name(), "putShort") + and MATCH(target->spec(), "(JS)V")) + or (MATCH(target->name(), "putChar") + and MATCH(target->spec(), "(JC)V"))) { ir::Value* value = frame->pop(ir::Type::i4()); ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); c->store(value, c->memory(address, ir::Type::i2())); return true; - } else if ((MATCH(methodName(t, target), "getInt") - and MATCH(methodSpec(t, target), "(J)I")) - or (MATCH(methodName(t, target), "getFloat") - and MATCH(methodSpec(t, target), "(J)F"))) - { + } else if ((MATCH(target->name(), "getInt") + and MATCH(target->spec(), "(J)I")) + or (MATCH(target->name(), "getFloat") + and MATCH(target->spec(), "(J)F"))) { ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); - ir::Type type = MATCH(methodName(t, target), "getInt") ? ir::Type::i4() - : ir::Type::f4(); + ir::Type type = MATCH(target->name(), "getInt") ? ir::Type::i4() + : ir::Type::f4(); frame->push(type, c->load(ir::SignExtend, c->memory(address, type), type)); return true; - } else if ((MATCH(methodName(t, target), "putInt") - and MATCH(methodSpec(t, target), "(JI)V")) - or (MATCH(methodName(t, target), "putFloat") - and MATCH(methodSpec(t, target), "(JF)V"))) - { - ir::Type type = MATCH(methodName(t, target), "putInt") ? ir::Type::i4() - : ir::Type::f4(); + } else if ((MATCH(target->name(), "putInt") + and MATCH(target->spec(), "(JI)V")) + or (MATCH(target->name(), "putFloat") + and MATCH(target->spec(), "(JF)V"))) { + ir::Type type = MATCH(target->name(), "putInt") ? ir::Type::i4() + : ir::Type::f4(); ir::Value* value = frame->pop(type); ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); c->store(value, c->memory(address, type)); return true; - } else if ((MATCH(methodName(t, target), "getLong") - and MATCH(methodSpec(t, target), "(J)J")) - or (MATCH(methodName(t, target), "getDouble") - and MATCH(methodSpec(t, target), "(J)D"))) - { + } else if ((MATCH(target->name(), "getLong") + and MATCH(target->spec(), "(J)J")) + or (MATCH(target->name(), "getDouble") + and MATCH(target->spec(), "(J)D"))) { ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); - ir::Type type = MATCH(methodName(t, target), "getLong") ? ir::Type::i8() - : ir::Type::f8(); + ir::Type type = MATCH(target->name(), "getLong") ? ir::Type::i8() + : ir::Type::f8(); frame->pushLarge(type, c->load(ir::SignExtend, c->memory(address, type), type)); return true; - } else if ((MATCH(methodName(t, target), "putLong") - and MATCH(methodSpec(t, target), "(JJ)V")) - or (MATCH(methodName(t, target), "putDouble") - and MATCH(methodSpec(t, target), "(JD)V"))) - { - ir::Type type = MATCH(methodName(t, target), "putLong") ? ir::Type::i8() - : ir::Type::f8(); + } else if ((MATCH(target->name(), "putLong") + and MATCH(target->spec(), "(JJ)V")) + or (MATCH(target->name(), "putDouble") + and MATCH(target->spec(), "(JD)V"))) { + ir::Type type = MATCH(target->name(), "putLong") ? ir::Type::i8() + : ir::Type::f8(); ir::Value* value = frame->popLarge(type); ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); c->store(value, c->memory(address, type)); return true; - } else if (MATCH(methodName(t, target), "getAddress") - and MATCH(methodSpec(t, target), "(J)J")) - { + } else if (MATCH(target->name(), "getAddress") + and MATCH(target->spec(), "(J)J")) { ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); frame->pushLarge(ir::Type::i8(), @@ -3682,9 +3704,8 @@ intrinsic(MyThread* t, Frame* frame, object target) c->memory(address, ir::Type::iptr()), ir::Type::i8())); return true; - } else if (MATCH(methodName(t, target), "putAddress") - and MATCH(methodSpec(t, target), "(JJ)V")) - { + } else if (MATCH(target->name(), "putAddress") + and MATCH(target->spec(), "(JJ)V")) { ir::Value* value = frame->popLarge(ir::Type::i8()); ir::Value* address = popLongAddress(frame); frame->pop(ir::Type::object()); @@ -3695,62 +3716,70 @@ intrinsic(MyThread* t, Frame* frame, object target) return false; } -unsigned -targetFieldOffset(Context* context, object field) +unsigned targetFieldOffset(Context* context, GcField* field) { if (context->bootContext) { return context->bootContext->resolver->fieldOffset(context->thread, field); } else { - return fieldOffset(context->thread, field); + return field->offset(); } } class Stack { public: - class MyResource: public Thread::AutoResource { + class MyResource : public Thread::AutoResource { public: - MyResource(Stack* s): AutoResource(s->thread), s(s) { } + MyResource(Stack* s) : AutoResource(s->thread), s(s) + { + } - virtual void release() { + virtual void release() + { s->zone.dispose(); } Stack* s; }; - Stack(MyThread* t): - thread(t), - zone(t->m->system, t->m->heap, 0), - resource(this) - { } + Stack(MyThread* t) + : thread(t), zone(t->m->system, t->m->heap, 0), resource(this) + { + } - ~Stack() { + ~Stack() + { zone.dispose(); } - void pushValue(uintptr_t v) { + void pushValue(uintptr_t v) + { *static_cast(push(BytesPerWord)) = v; } - uintptr_t peekValue(unsigned offset) { + uintptr_t peekValue(unsigned offset) + { return *static_cast(peek((offset + 1) * BytesPerWord)); } - uintptr_t popValue() { + uintptr_t popValue() + { uintptr_t v = peekValue(0); pop(BytesPerWord); return v; } - void* push(unsigned size) { + void* push(unsigned size) + { return zone.allocate(size); } - void* peek(unsigned size) { + void* peek(unsigned size) + { return zone.peek(size); } - void pop(unsigned size) { + void pop(unsigned size) + { zone.pop(size); } @@ -3776,16 +3805,19 @@ class SwitchState { bottom(bottom), top(top), index(0) - { } - - Frame* frame() { - return reinterpret_cast - (reinterpret_cast(this) - pad(count * 4) - pad(sizeof(Frame))); + { } - uint32_t* ipTable() { - return reinterpret_cast - (reinterpret_cast(this) - pad(count * 4)); + Frame* frame() + { + return reinterpret_cast(reinterpret_cast(this) + - pad(count * 4) - pad(sizeof(Frame))); + } + + uint32_t* ipTable() + { + return reinterpret_cast(reinterpret_cast(this) + - pad(count * 4)); } Compiler::State* state; @@ -3848,39 +3880,32 @@ lir::TernaryOperation toCompilerBinaryOp(MyThread* t, unsigned instruction) } } -void -compile(MyThread* t, Frame* initialFrame, unsigned initialIp, - int exceptionHandlerStart = -1) +void compile(MyThread* t, + Frame* initialFrame, + unsigned initialIp, + int exceptionHandlerStart = -1) { - enum { - Return, - Unbranch, - Unsubroutine, - Untable0, - Untable1, - Unswitch - }; + enum { Return, Unbranch, Unsubroutine, Untable0, Untable1, Unswitch }; Frame* frame = initialFrame; avian::codegen::Compiler* c = frame->c; Context* context = frame->context; - unsigned stackSize = codeMaxStack(t, methodCode(t, context->method)); + unsigned stackSize = context->method->code()->maxStack(); Stack stack(t); unsigned ip = initialIp; unsigned newIp; stack.pushValue(Return); - - start: - ir::Type* stackMap - = static_cast(stack.push(stackSize * sizeof(ir::Type))); +start: + ir::Type* stackMap + = static_cast(stack.push(stackSize * sizeof(ir::Type))); frame = new (stack.push(sizeof(Frame))) Frame(frame, stackMap); - loop: - object code = methodCode(t, context->method); +loop: + GcCode* code = context->method->code(); PROTECT(t, code); - - while (ip < codeLength(t, code)) { + + while (ip < code->length()) { if (context->visitTable[frame->duplicatedIp(ip)]++) { // we've already visited this part of the code frame->visitLogicalIp(ip); @@ -3904,8 +3929,6 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, c->threadRegister()); } -// fprintf(stderr, "ip: %d map: %ld\n", ip, *(frame->map)); - if (DebugInstructions) { unsigned startingIp = ip; fprintf(stderr, " stack: ["); @@ -3927,11 +3950,11 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } fprintf(stderr, "]\n"); fprintf(stderr, "% 5d: ", startingIp); - avian::jvm::debug::printInstruction(&codeBody(t, code, 0), startingIp); + avian::jvm::debug::printInstruction(code->body().begin(), startingIp); fprintf(stderr, "\n"); } - unsigned instruction = codeBody(t, code, ip++); + unsigned instruction = code->body()[ip++]; switch (instruction) { case aaload: @@ -4113,7 +4136,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, break; case aload: - frame->load(ir::Type::object(), codeBody(t, code, ip++)); + frame->load(ir::Type::object(), code->body()[ip++]); break; case aload_0: @@ -4134,13 +4157,14 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case anewarray: { uint16_t index = codeReadInt16(t, code, ip); - - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object class_ = resolveClassInPool(t, context->method, index - 1, false); + GcClass* class_ + = resolveClassInPool(t, context->method, index - 1, false); ir::Value* length = frame->pop(ir::Type::i4()); @@ -4168,7 +4192,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case areturn: { handleExit(t, frame); c->return_(frame->pop(ir::Type::object())); - } goto next; + } + goto next; case arraylength: { frame->push(ir::Type::i4(), @@ -4180,7 +4205,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; case astore: - frame->store(ir::Type::object(), codeBody(t, code, ip++)); + frame->store(ir::Type::object(), code->body()[ip++]); break; case astore_0: @@ -4210,23 +4235,25 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, target); c->nullaryOp(lir::Trap); - } goto next; + } + goto next; case bipush: - frame->push(ir::Type::i4(), - c->constant(static_cast(codeBody(t, code, ip++)), - ir::Type::i4())); + frame->push( + ir::Type::i4(), + c->constant(static_cast(code->body()[ip++]), ir::Type::i4())); break; case checkcast: { uint16_t index = codeReadInt16(t, code, ip); - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object class_ = resolveClassInPool(t, context->method, index - 1, false); + GcClass* class_ + = resolveClassInPool(t, context->method, index - 1, false); object argument; Thunk thunk; @@ -4337,7 +4364,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, c->unaryOp(lir::FloatNegate, frame->popLarge(ir::Type::f8()))); } break; - case dup: + case vm::dup: frame->dup(); break; @@ -4349,7 +4376,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, frame->dupX2(); break; - case dup2: + case vm::dup2: frame->dup2(); break; @@ -4432,12 +4459,12 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, frame->push(ir::Type::f4(), c->constant(floatToBits(0.0), ir::Type::f4())); break; - + case fconst_1: frame->push(ir::Type::f4(), c->constant(floatToBits(1.0), ir::Type::f4())); break; - + case fconst_2: frame->push(ir::Type::f4(), c->constant(floatToBits(2.0), ir::Type::f4())); @@ -4451,20 +4478,17 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case getfield: case getstatic: { uint16_t index = codeReadInt16(t, code, ip); - - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object field = resolveField(t, context->method, index - 1, false); + GcField* field = resolveField(t, context->method, index - 1, false); if (LIKELY(field)) { - if ((fieldFlags(t, field) & ACC_VOLATILE) - and TargetBytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField)) - { + if ((field->flags() & ACC_VOLATILE) and TargetBytesPerWord == 4 + and (field->code() == DoubleField or field->code() == LongField)) { PROTECT(t, field); c->call(c->constant(getThunk(t, acquireMonitorForObjectThunk), @@ -4484,7 +4508,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, PROTECT(t, field); - if (classNeedsInit(t, fieldClass(t, field))) { + if (classNeedsInit(t, field->class_())) { c->call( c->constant(getThunk(t, tryInitClassThunk), ir::Type::iptr()), 0, @@ -4492,10 +4516,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Type::void_(), 2, c->threadRegister(), - frame->append(fieldClass(t, field))); + frame->append(field->class_())); } - table = frame->append(classStaticTable(t, fieldClass(t, field))); + table = frame->append(field->class_()->staticTable()); } else { checkField(t, field, false); @@ -4507,7 +4531,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: frame->push(ir::Type::i4(), @@ -4585,11 +4609,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, abort(t); } - if (fieldFlags(t, field) & ACC_VOLATILE) { - if (TargetBytesPerWord == 4 - and (fieldCode(t, field) == DoubleField - or fieldCode(t, field) == LongField)) - { + if (field->flags() & ACC_VOLATILE) { + if (TargetBytesPerWord == 4 and (field->code() == DoubleField + or field->code() == LongField)) { c->call(c->constant(getThunk(t, releaseMonitorForObjectThunk), ir::Type::iptr()), 0, @@ -4603,10 +4625,11 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } } else { - int fieldCode = vm::fieldCode - (t, byteArrayBody(t, referenceSpec(t, reference), 0)); + GcReference* ref = cast(t, reference); + PROTECT(t, ref); + int fieldCode = vm::fieldCode(t, ref->spec()->body()[0]); - object pair = makePair(t, context->method, reference); + GcPair* pair = makePair(t, context->method, reference); ir::Type rType = operandTypeForFieldCode(t, fieldCode); @@ -4643,9 +4666,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case goto_: { uint32_t offset = codeReadInt16(t, code, ip); uint32_t newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4656,9 +4679,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case goto_w: { uint32_t offset = codeReadInt32(t, code, ip); uint32_t newIp = (ip - 5) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4707,7 +4730,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Type::i2(), frame->pop(ir::Type::i4()))); } break; - + case iadd: case iand: case ior: @@ -4770,9 +4793,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case if_acmpne: { uint32_t offset = codeReadInt16(t, code, ip); newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4781,7 +4804,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Value* target = frame->machineIpValue(newIp); c->condJump(toCompilerJumpOp(t, instruction), a, b, target); - } goto branch; + } + goto branch; case if_icmpeq: case if_icmpne: @@ -4791,9 +4815,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case if_icmple: { uint32_t offset = codeReadInt16(t, code, ip); newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4802,7 +4826,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Value* target = frame->machineIpValue(newIp); c->condJump(toCompilerJumpOp(t, instruction), a, b, target); - } goto branch; + } + goto branch; case ifeq: case ifne: @@ -4812,11 +4837,11 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case ifle: { uint32_t offset = codeReadInt16(t, code, ip); newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); ir::Value* target = frame->machineIpValue(newIp); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4824,15 +4849,16 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Value* b = frame->pop(ir::Type::i4()); c->condJump(toCompilerJumpOp(t, instruction), a, b, target); - } goto branch; + } + goto branch; case ifnull: case ifnonnull: { uint32_t offset = codeReadInt16(t, code, ip); newIp = (ip - 3) + offset; - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); - if(newIp <= ip) { + if (newIp <= ip) { compileSafePoint(t, c, frame); } @@ -4841,11 +4867,12 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Value* target = frame->machineIpValue(newIp); c->condJump(toCompilerJumpOp(t, instruction), a, b, target); - } goto branch; + } + goto branch; case iinc: { - uint8_t index = codeBody(t, code, ip++); - int8_t count = codeBody(t, code, ip++); + uint8_t index = code->body()[ip++]; + int8_t count = code->body()[ip++]; storeLocal(context, 1, @@ -4858,10 +4885,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; case iload: - frame->load(ir::Type::i4(), codeBody(t, code, ip++)); + frame->load(ir::Type::i4(), code->body()[ip++]); break; case fload: - frame->load(ir::Type::f4(), codeBody(t, code, ip++)); + frame->load(ir::Type::f4(), code->body()[ip++]); break; case iload_0: @@ -4900,12 +4927,13 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case instanceof: { uint16_t index = codeReadInt16(t, code, ip); - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object class_ = resolveClassInPool(t, context->method, index - 1, false); + GcClass* class_ + = resolveClassInPool(t, context->method, index - 1, false); ir::Value* instance = frame->pop(ir::Type::object()); @@ -4936,12 +4964,12 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, uint16_t index = codeReadInt16(t, code, ip); ip += 2; - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object target = resolveMethod(t, context->method, index - 1, false); + GcMethod* target = resolveMethod(t, context->method, index - 1, false); object argument; Thunk thunk; @@ -4953,17 +4981,17 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, argument = target; thunk = findInterfaceMethodFromInstanceThunk; - parameterFootprint = methodParameterFootprint(t, target); - returnCode = methodReturnCode(t, target); + parameterFootprint = target->parameterFootprint(); + returnCode = target->returnCode(); tailCall = isTailCall(t, code, ip, context->method, target); } else { + GcReference* ref = cast(t, reference); + PROTECT(t, ref); argument = makePair(t, context->method, reference); thunk = findInterfaceMethodFromInstanceAndReferenceThunk; - parameterFootprint = methodReferenceParameterFootprint - (t, reference, false); - returnCode = methodReferenceReturnCode(t, reference); - tailCall = isReferenceTailCall - (t, code, ip, context->method, reference); + parameterFootprint = methodReferenceParameterFootprint(t, ref, false); + returnCode = methodReferenceReturnCode(t, ref); + tailCall = isReferenceTailCall(t, code, ip, context->method, ref); } unsigned rSize = resultSize(t, returnCode); @@ -4994,17 +5022,17 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, uint16_t index = codeReadInt16(t, code, ip); - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object target = resolveMethod(t, context->method, index - 1, false); + GcMethod* target = resolveMethod(t, context->method, index - 1, false); if (LIKELY(target)) { - object class_ = methodClass(t, context->method); + GcClass* class_ = context->method->class_(); if (isSpecialMethod(t, target, class_)) { - target = findVirtualMethod(t, target, classSuper(t, class_)); + target = findVirtualMethod(t, target, class_->super()); } checkMethod(t, target, false); @@ -5012,15 +5040,21 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, bool tailCall = isTailCall(t, code, ip, context->method, target); if (UNLIKELY(methodAbstract(t, target))) { - compileDirectAbstractInvoke - (t, frame, getMethodAddressThunk, target, tailCall); + compileDirectAbstractInvoke( + t, frame, getMethodAddressThunk, target, tailCall); } else { compileDirectInvoke(t, frame, target, tailCall); } } else { - compileDirectReferenceInvoke - (t, frame, findSpecialMethodFromReferenceThunk, reference, false, - isReferenceTailCall(t, code, ip, context->method, reference)); + GcReference* ref = cast(t, reference); + PROTECT(t, ref); + compileDirectReferenceInvoke( + t, + frame, + findSpecialMethodFromReferenceThunk, + ref, + false, + isReferenceTailCall(t, code, ip, context->method, ref)); } } break; @@ -5029,12 +5063,12 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, uint16_t index = codeReadInt16(t, code, ip); - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object target = resolveMethod(t, context->method, index - 1, false); + GcMethod* target = resolveMethod(t, context->method, index - 1, false); if (LIKELY(target)) { checkMethod(t, target, true); @@ -5044,9 +5078,15 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, compileDirectInvoke(t, frame, target, tailCall); } } else { - compileDirectReferenceInvoke - (t, frame, findStaticMethodFromReferenceThunk, reference, true, - isReferenceTailCall(t, code, ip, context->method, reference)); + GcReference* ref = cast(t, reference); + PROTECT(t, ref); + compileDirectReferenceInvoke( + t, + frame, + findStaticMethodFromReferenceThunk, + ref, + true, + isReferenceTailCall(t, code, ip, context->method, ref)); } } break; @@ -5055,24 +5095,24 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, uint16_t index = codeReadInt16(t, code, ip); - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object target = resolveMethod(t, context->method, index - 1, false); + GcMethod* target = resolveMethod(t, context->method, index - 1, false); if (LIKELY(target)) { checkMethod(t, target, false); - + if (not intrinsic(t, frame, target)) { bool tailCall = isTailCall(t, code, ip, context->method, target); if (LIKELY(methodVirtual(t, target))) { - unsigned parameterFootprint = methodParameterFootprint(t, target); + unsigned parameterFootprint = target->parameterFootprint(); unsigned offset = TargetClassVtable - + (methodOffset(t, target) * TargetBytesPerWord); + + (target->offset() * TargetBytesPerWord); ir::Value* instance = c->peek(1, parameterFootprint - 1); @@ -5096,9 +5136,11 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } } else { + GcReference* ref = cast(t, reference); PROTECT(t, reference); + PROTECT(t, ref); - object pair = makePair(t, context->method, reference); + GcPair* pair = makePair(t, context->method, reference); compileReferenceInvoke( frame, @@ -5112,11 +5154,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, c->threadRegister(), frame->append(pair), c->peek(1, - methodReferenceParameterFootprint(t, reference, false) - - 1)), - reference, + methodReferenceParameterFootprint(t, ref, false) - 1)), + ref, false, - isReferenceTailCall(t, code, ip, context->method, reference)); + isReferenceTailCall(t, code, ip, context->method, ref)); } } break; @@ -5142,13 +5183,14 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case freturn: { handleExit(t, frame); c->return_(frame->pop(ir::Type::f4())); - } goto next; + } + goto next; case istore: - frame->store(ir::Type::i4(), codeBody(t, code, ip++)); + frame->store(ir::Type::i4(), code->body()[ip++]); break; case fstore: - frame->store(ir::Type::f4(), codeBody(t, code, ip++)); + frame->store(ir::Type::f4(), code->body()[ip++]); break; case istore_0: @@ -5193,7 +5235,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, newIp = thisIp + offset; } - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); frame->startSubroutine(newIp, ip); @@ -5265,20 +5307,20 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, uint16_t index; if (instruction == ldc) { - index = codeBody(t, code, ip++); + index = code->body()[ip++]; } else { index = codeReadInt16(t, code, ip); } - object pool = codePool(t, code); + GcSingleton* pool = code->pool(); if (singletonIsObject(t, pool, index - 1)) { object v = singletonObject(t, pool, index - 1); loadMemoryBarrier(); - if (objectClass(t, v) == type(t, Machine::ReferenceType)) { - object reference = v; + if (objectClass(t, v) == type(t, GcReference::Type)) { + GcReference* reference = cast(t, v); PROTECT(t, reference); v = resolveClassInPool(t, context->method, index - 1, false); @@ -5299,7 +5341,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } if (v) { - if (objectClass(t, v) == type(t, Machine::ClassType)) { + if (objectClass(t, v) == type(t, GcClass::Type)) { frame->push(ir::Type::object(), c->call(c->constant(getThunk(t, getJClass64Thunk), ir::Type::iptr()), @@ -5325,7 +5367,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case ldc2_w: { uint16_t index = codeReadInt16(t, code, ip); - object pool = codePool(t, code); + GcSingleton* pool = code->pool(); uint64_t v; memcpy(&v, &singletonValue(t, pool, index - 1), 8); @@ -5349,10 +5391,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; case lload: - frame->loadLarge(ir::Type::i8(), codeBody(t, code, ip++)); + frame->loadLarge(ir::Type::i8(), code->body()[ip++]); break; case dload: - frame->loadLarge(ir::Type::f8(), codeBody(t, code, ip++)); + frame->loadLarge(ir::Type::f8(), code->body()[ip++]); break; case lload_0: @@ -5392,12 +5434,12 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case lookupswitch: { int32_t base = ip - 1; - ip = (ip + 3) & ~3; // pad to four byte boundary + ip = (ip + 3) & ~3; // pad to four byte boundary ir::Value* key = frame->pop(ir::Type::i4()); uint32_t defaultIp = base + codeReadInt32(t, code, ip); - assert(t, defaultIp < codeLength(t, code)); + assertT(t, defaultIp < code->length()); int32_t pairCount = codeReadInt32(t, code, ip); @@ -5406,13 +5448,13 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, frame->addressPromise(frame->machineIp(defaultIp))); avian::codegen::Promise* start = 0; - uint32_t* ipTable = static_cast - (stack.push(sizeof(uint32_t) * pairCount)); + uint32_t* ipTable + = static_cast(stack.push(sizeof(uint32_t) * pairCount)); for (int32_t i = 0; i < pairCount; ++i) { unsigned index = ip + (i * 8); int32_t key = codeReadInt32(t, code, index); uint32_t newIp = base + codeReadInt32(t, code, index); - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); ipTable[i] = newIp; @@ -5422,7 +5464,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } c->poolAppendPromise(frame->addressPromise(frame->machineIp(newIp))); } - assert(t, start); + assertT(t, start); ir::Value* address = c->call( c->constant(getThunk(t, lookUpAddressThunk), ir::Type::iptr()), @@ -5444,8 +5486,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, address) : address); - new (stack.push(sizeof(SwitchState))) SwitchState - (c->saveState(), pairCount, defaultIp, 0, 0, 0, 0); + new (stack.push(sizeof(SwitchState))) + SwitchState(c->saveState(), pairCount, defaultIp, 0, 0, 0, 0); goto switchloop; } else { @@ -5477,7 +5519,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case dreturn: { handleExit(t, frame); c->return_(frame->popLarge(ir::Type::f8())); - } goto next; + } + goto next; case lshl: case lshr: @@ -5491,10 +5534,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; case lstore: - frame->storeLarge(ir::Type::i8(), codeBody(t, code, ip++)); + frame->storeLarge(ir::Type::i8(), code->body()[ip++]); break; case dstore: - frame->storeLarge(ir::Type::f8(), codeBody(t, code, ip++)); + frame->storeLarge(ir::Type::f8(), code->body()[ip++]); break; case lstore_0: @@ -5551,14 +5594,15 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case multianewarray: { uint16_t index = codeReadInt16(t, code, ip); - uint8_t dimensions = codeBody(t, code, ip++); + uint8_t dimensions = code->body()[ip++]; - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object class_ = resolveClassInPool(t, context->method, index - 1, false); + GcClass* class_ + = resolveClassInPool(t, context->method, index - 1, false); object argument; Thunk thunk; @@ -5571,9 +5615,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } unsigned offset - = localOffset - (t, localSize(t, context->method) + c->topOfStack(), context->method) - + t->arch->frameReturnAddressSize(); + = localOffset(t, + localSize(t, context->method) + c->topOfStack(), + context->method) + t->arch->frameReturnAddressSize(); ir::Value* result = c->call(c->constant(getThunk(t, thunk), ir::Type::iptr()), @@ -5592,19 +5636,20 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case new_: { uint16_t index = codeReadInt16(t, code, ip); - - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object class_ = resolveClassInPool(t, context->method, index - 1, false); + GcClass* class_ + = resolveClassInPool(t, context->method, index - 1, false); object argument; Thunk thunk; if (LIKELY(class_)) { argument = class_; - if (classVmFlags(t, class_) & (WeakReferenceFlag | HasFinalizerFlag)) { + if (class_->vmFlags() & (WeakReferenceFlag | HasFinalizerFlag)) { thunk = makeNewGeneral64Thunk; } else { thunk = makeNew64Thunk; @@ -5625,7 +5670,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; case newarray: { - uint8_t type = codeBody(t, code, ip++); + uint8_t type = code->body()[ip++]; ir::Value* length = frame->pop(ir::Type::i4()); @@ -5641,7 +5686,8 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, length)); } break; - case nop: break; + case nop: + break; case pop_: frame->popFootprint(1); @@ -5654,23 +5700,23 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case putfield: case putstatic: { uint16_t index = codeReadInt16(t, code, ip); - - object reference = singletonObject - (t, codePool(t, methodCode(t, context->method)), index - 1); + + object reference + = singletonObject(t, context->method->code()->pool(), index - 1); PROTECT(t, reference); - object field = resolveField(t, context->method, index - 1, false); + GcField* field = resolveField(t, context->method, index - 1, false); if (LIKELY(field)) { - int fieldCode = vm::fieldCode(t, field); + int fieldCode = field->code(); object staticTable = 0; if (instruction == putstatic) { checkField(t, field, true); - if (classNeedsInit(t, fieldClass(t, field))) { + if (classNeedsInit(t, field->class_())) { PROTECT(t, field); c->call( @@ -5680,10 +5726,10 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Type::void_(), 2, c->threadRegister(), - frame->append(fieldClass(t, field))); + frame->append(field->class_())); } - staticTable = classStaticTable(t, fieldClass(t, field)); + staticTable = field->class_()->staticTable(); } else { checkField(t, field, false); @@ -5693,10 +5739,9 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } - if (fieldFlags(t, field) & ACC_VOLATILE) { + if (field->flags() & ACC_VOLATILE) { if (TargetBytesPerWord == 4 - and (fieldCode == DoubleField or fieldCode == LongField)) - { + and (fieldCode == DoubleField or fieldCode == LongField)) { PROTECT(t, field); c->call(c->constant(getThunk(t, acquireMonitorForObjectThunk), @@ -5783,7 +5828,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, value); } else { c->call( - c->constant(getThunk(t, setThunk), ir::Type::iptr()), + c->constant(getThunk(t, setObjectThunk), ir::Type::iptr()), 0, 0, ir::Type::void_(), @@ -5795,13 +5840,13 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } break; - default: abort(t); + default: + abort(t); } - if (fieldFlags(t, field) & ACC_VOLATILE) { + if (field->flags() & ACC_VOLATILE) { if (TargetBytesPerWord == 4 - and (fieldCode == DoubleField or fieldCode == LongField)) - { + and (fieldCode == DoubleField or fieldCode == LongField)) { c->call(c->constant(getThunk(t, releaseMonitorForObjectThunk), ir::Type::iptr()), 0, @@ -5815,13 +5860,14 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } } else { - int fieldCode = vm::fieldCode - (t, byteArrayBody(t, referenceSpec(t, reference), 0)); + GcReference* ref = cast(t, reference); + PROTECT(t, ref); + int fieldCode = vm::fieldCode(t, ref->spec()->body()[0]); ir::Value* value = popField(t, frame, fieldCode); ir::Type rType = operandTypeForFieldCode(t, fieldCode); - object pair = makePair(t, context->method, reference); + GcPair* pair = makePair(t, context->method, reference); switch (fieldCode) { case ByteField: @@ -5919,13 +5965,14 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, } } break; - default: abort(t); + default: + abort(t); } } } break; case ret: { - unsigned index = codeBody(t, code, ip); + unsigned index = code->body()[ip]; unsigned returnAddress = frame->endSubroutine(index); c->jmp(frame->machineIpValue(returnAddress)); @@ -5954,22 +6001,22 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, case tableswitch: { int32_t base = ip - 1; - ip = (ip + 3) & ~3; // pad to four byte boundary + ip = (ip + 3) & ~3; // pad to four byte boundary uint32_t defaultIp = base + codeReadInt32(t, code, ip); - assert(t, defaultIp < codeLength(t, code)); - + assertT(t, defaultIp < code->length()); + int32_t bottom = codeReadInt32(t, code, ip); int32_t top = codeReadInt32(t, code, ip); - + avian::codegen::Promise* start = 0; unsigned count = top - bottom + 1; - uint32_t* ipTable = static_cast - (stack.push(sizeof(uint32_t) * count)); + uint32_t* ipTable + = static_cast(stack.push(sizeof(uint32_t) * count)); for (int32_t i = 0; i < top - bottom + 1; ++i) { unsigned index = ip + (i * 4); uint32_t newIp = base + codeReadInt32(t, code, index); - assert(t, newIp < codeLength(t, code)); + assertT(t, newIp < code->length()); ipTable[i] = newIp; @@ -5979,7 +6026,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, start = p; } } - assert(t, start); + assertT(t, start); ir::Value* key = frame->pop(ir::Type::i4()); @@ -5990,15 +6037,16 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, c->save(ir::Type::i4(), key); - new (stack.push(sizeof(SwitchState))) SwitchState - (c->saveState(), count, defaultIp, key, start, bottom, top); + new (stack.push(sizeof(SwitchState))) SwitchState( + c->saveState(), count, defaultIp, key, start, bottom, top); stack.pushValue(Untable0); ip = defaultIp; - } goto start; + } + goto start; case wide: { - switch (codeBody(t, code, ip++)) { + switch (code->body()[ip++]) { case aload: { frame->load(ir::Type::object(), codeReadInt16(t, code, ip)); } break; @@ -6045,15 +6093,17 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ip = returnAddress; } break; - default: abort(t); + default: + abort(t); } } break; - default: abort(t); + default: + abort(t); } } - next: +next: frame->dispose(); frame = 0; stack.pop(sizeof(Frame)); @@ -6075,8 +6125,7 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, if (DebugInstructions) { fprintf(stderr, "Untable0\n"); } - SwitchState* s = static_cast - (stack.peek(sizeof(SwitchState))); + SwitchState* s = static_cast(stack.peek(sizeof(SwitchState))); frame = s->frame(); @@ -6090,14 +6139,14 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, c->save(ir::Type::i4(), s->key); ip = s->defaultIp; stack.pushValue(Untable1); - } goto start; + } + goto start; case Untable1: { if (DebugInstructions) { fprintf(stderr, "Untable1\n"); } - SwitchState* s = static_cast - (stack.peek(sizeof(SwitchState))); + SwitchState* s = static_cast(stack.peek(sizeof(SwitchState))); frame = s->frame(); @@ -6128,20 +6177,21 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, ir::Type::iptr())); s->state = c->saveState(); - } goto switchloop; + } + goto switchloop; case Unswitch: { if (DebugInstructions) { fprintf(stderr, "Unswitch\n"); } - SwitchState* s = static_cast - (stack.peek(sizeof(SwitchState))); + SwitchState* s = static_cast(stack.peek(sizeof(SwitchState))); frame = s->frame(); - c->restoreState - (static_cast(stack.peek(sizeof(SwitchState)))->state); - } goto switchloop; + c->restoreState( + static_cast(stack.peek(sizeof(SwitchState)))->state); + } + goto switchloop; case Unsubroutine: { if (DebugInstructions) { @@ -6151,31 +6201,31 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, unsigned start = stack.popValue(); frame = reinterpret_cast(stack.peek(sizeof(Frame))); frame->endSubroutine(start); - } goto loop; + } + goto loop; default: abort(t); } - switchloop: { - SwitchState* s = static_cast - (stack.peek(sizeof(SwitchState))); +switchloop : { + SwitchState* s = static_cast(stack.peek(sizeof(SwitchState))); - if (s->index < s->count) { - ip = s->ipTable()[s->index++]; - stack.pushValue(Unswitch); - goto start; - } else { - ip = s->defaultIp; - unsigned count = s->count * 4; - stack.pop(sizeof(SwitchState)); - stack.pop(count); - frame = reinterpret_cast(stack.peek(sizeof(Frame))); - goto loop; - } + if (s->index < s->count) { + ip = s->ipTable()[s->index++]; + stack.pushValue(Unswitch); + goto start; + } else { + ip = s->defaultIp; + unsigned count = s->count * 4; + stack.pop(sizeof(SwitchState)); + stack.pop(count); + frame = reinterpret_cast(stack.peek(sizeof(Frame))); + goto loop; } +} - branch: +branch: stack.pushValue(reinterpret_cast(c->saveState())); stack.pushValue(ip); stack.pushValue(Unbranch); @@ -6185,21 +6235,23 @@ compile(MyThread* t, Frame* initialFrame, unsigned initialIp, FILE* compileLog = 0; -void -logCompile(MyThread* t, const void* code, unsigned size, const char* class_, - const char* name, const char* spec); +void logCompile(MyThread* t, + const void* code, + unsigned size, + const char* class_, + const char* name, + const char* spec); -int -resolveIpForwards(Context* context, int start, int end) +int resolveIpForwards(Context* context, int start, int end) { if (start < 0) { start = 0; } while (start < end and context->visitTable[start] == 0) { - ++ start; + ++start; } - + if (start >= end) { return -1; } else { @@ -6207,19 +6259,17 @@ resolveIpForwards(Context* context, int start, int end) } } -int -resolveIpBackwards(Context* context, int start, int end) +int resolveIpBackwards(Context* context, int start, int end) { - Thread* t = context->thread; - if (start >= static_cast(codeLength(t, methodCode(t, context->method)) + if (start >= static_cast(context->method->code()->length() * (context->subroutineCount + 1))) { - start = codeLength(t, methodCode(t, context->method)); + start = context->method->code()->length(); } else { while (start >= end and context->visitTable[start] == 0) { - -- start; + --start; } } - + if (start < end) { return -1; } else { @@ -6227,84 +6277,83 @@ resolveIpBackwards(Context* context, int start, int end) } } -object -truncateIntArray(Thread* t, object array, unsigned length) +GcIntArray* truncateIntArray(Thread* t, GcIntArray* array, unsigned length) { - expect(t, intArrayLength(t, array) > length); + expect(t, array->length() > length); PROTECT(t, array); - object newArray = makeIntArray(t, length); + GcIntArray* newArray = makeIntArray(t, length); if (length) { - memcpy(&intArrayBody(t, newArray, 0), &intArrayBody(t, array, 0), - length * 4); + memcpy(newArray->body().begin(), array->body().begin(), length * 4); } return newArray; } -object -truncateArray(Thread* t, object array, unsigned length) +GcArray* truncateArray(Thread* t, GcArray* array, unsigned length) { - expect(t, arrayLength(t, array) > length); + expect(t, array->length() > length); PROTECT(t, array); - object newArray = makeArray(t, length); + GcArray* newArray = makeArray(t, length); if (length) { - memcpy(&arrayBody(t, newArray, 0), &arrayBody(t, array, 0), - length * BytesPerWord); + for (size_t i = 0; i < length; i++) { + newArray->setBodyElement(t, i, array->body()[i]); + } } return newArray; } -object -truncateLineNumberTable(Thread* t, object table, unsigned length) +GcLineNumberTable* truncateLineNumberTable(Thread* t, + GcLineNumberTable* table, + unsigned length) { - expect(t, lineNumberTableLength(t, table) > length); + expect(t, table->length() > length); PROTECT(t, table); - object newTable = makeLineNumberTable(t, length); + GcLineNumberTable* newTable = makeLineNumberTable(t, length); if (length) { - memcpy(&lineNumberTableBody(t, newTable, 0), - &lineNumberTableBody(t, table, 0), + memcpy(newTable->body().begin(), + table->body().begin(), length * sizeof(uint64_t)); } return newTable; } -object translateExceptionHandlerTable(MyThread* t, - Context* context, - intptr_t start, - intptr_t end) +GcArray* translateExceptionHandlerTable(MyThread* t, + Context* context, + intptr_t start, + intptr_t end) { avian::codegen::Compiler* c = context->compiler; - object oldTable = codeExceptionHandlerTable - (t, methodCode(t, context->method)); + GcExceptionHandlerTable* oldTable = cast( + t, context->method->code()->exceptionHandlerTable()); if (oldTable) { PROTECT(t, oldTable); - unsigned length = exceptionHandlerTableLength(t, oldTable); + unsigned length = oldTable->length(); - object newIndex + GcIntArray* newIndex = makeIntArray(t, length * (context->subroutineCount + 1) * 3); PROTECT(t, newIndex); - object newTable = makeArray(t, length * (context->subroutineCount + 1) + 1); + GcArray* newTable + = makeArray(t, length * (context->subroutineCount + 1) + 1); PROTECT(t, newTable); unsigned ni = 0; for (unsigned subI = 0; subI <= context->subroutineCount; ++subI) { - unsigned duplicatedBaseIp - = subI * codeLength(t, methodCode(t, context->method)); + unsigned duplicatedBaseIp = subI * context->method->code()->length(); for (unsigned oi = 0; oi < length; ++oi) { - uint64_t oldHandler = exceptionHandlerTableBody(t, oldTable, oi); + uint64_t oldHandler = oldTable->body()[oi]; int handlerStart = resolveIpForwards( context, @@ -6312,33 +6361,32 @@ object translateExceptionHandlerTable(MyThread* t, duplicatedBaseIp + exceptionHandlerEnd(oldHandler)); if (LIKELY(handlerStart >= 0)) { - assert( - t, - handlerStart - < static_cast(codeLength(t, methodCode(t, context->method)) - * (context->subroutineCount + 1))); + assertT(t, + handlerStart + < static_cast(context->method->code()->length() + * (context->subroutineCount + 1))); int handlerEnd = resolveIpBackwards( context, duplicatedBaseIp + exceptionHandlerEnd(oldHandler), duplicatedBaseIp + exceptionHandlerStart(oldHandler)); - assert(t, handlerEnd >= 0); - assert(t, - handlerEnd <= static_cast( - codeLength(t, methodCode(t, context->method)) - * (context->subroutineCount + 1))); + assertT(t, handlerEnd >= 0); + assertT( + t, + handlerEnd <= static_cast(context->method->code()->length() + * (context->subroutineCount + 1))); - intArrayBody(t, newIndex, ni* 3) = c->machineIp(handlerStart)->value() - - start; + newIndex->body()[ni * 3] = c->machineIp(handlerStart)->value() + - start; - intArrayBody(t, newIndex, (ni* 3) + 1) - = (handlerEnd == static_cast(codeLength( - t, methodCode(t, context->method))) + newIndex->body()[(ni * 3) + 1] + = (handlerEnd + == static_cast(context->method->code()->length()) ? end : c->machineIp(handlerEnd)->value()) - start; - intArrayBody(t, newIndex, (ni* 3) + 2) + newIndex->body()[(ni * 3) + 2] = c->machineIp(exceptionHandlerIp(oldHandler))->value() - start; object type; @@ -6349,7 +6397,7 @@ object translateExceptionHandlerTable(MyThread* t, type = 0; } - set(t, newTable, ArrayBody + ((ni + 1) * BytesPerWord), type); + newTable->setBodyElement(t, ni + 1, type); ++ni; } @@ -6361,7 +6409,7 @@ object translateExceptionHandlerTable(MyThread* t, newTable = truncateArray(t, newTable, ni + 1); } - set(t, newTable, ArrayBody, newIndex); + newTable->setBodyElement(t, 0, newIndex); return newTable; } else { @@ -6369,28 +6417,30 @@ object translateExceptionHandlerTable(MyThread* t, } } -object -translateLineNumberTable(MyThread* t, Context* context, intptr_t start) +GcLineNumberTable* translateLineNumberTable(MyThread* t, + Context* context, + intptr_t start) { - object oldTable = codeLineNumberTable(t, methodCode(t, context->method)); + GcLineNumberTable* oldTable = context->method->code()->lineNumberTable(); if (oldTable) { PROTECT(t, oldTable); - unsigned length = lineNumberTableLength(t, oldTable); - object newTable = makeLineNumberTable(t, length); + unsigned length = oldTable->length(); + GcLineNumberTable* newTable = makeLineNumberTable(t, length); unsigned ni = 0; for (unsigned oi = 0; oi < length; ++oi) { - uint64_t oldLine = lineNumberTableBody(t, oldTable, oi); + uint64_t oldLine = oldTable->body()[oi]; - int ip = resolveIpForwards - (context, lineNumberIp(oldLine), oi + 1 < length - ? lineNumberIp(lineNumberTableBody(t, oldTable, oi + 1)) - 1 - : lineNumberIp(oldLine) + 1); + int ip = resolveIpForwards( + context, + lineNumberIp(oldLine), + oi + 1 < length ? lineNumberIp(oldTable->body()[oi + 1]) - 1 + : lineNumberIp(oldLine) + 1); if (LIKELY(ip >= 0)) { - lineNumberTableBody(t, newTable, ni++) = lineNumber - (context->compiler->machineIp(ip)->value() - start, - lineNumberLine(oldLine)); + newTable->body()[ni++] + = lineNumber(context->compiler->machineIp(ip)->value() - start, + lineNumberLine(oldLine)); } } @@ -6404,8 +6454,7 @@ translateLineNumberTable(MyThread* t, Context* context, intptr_t start) } } -void -printSet(uintptr_t* m, unsigned limit) +void printSet(uintptr_t* m, unsigned limit) { if (limit) { for (unsigned i = 0; i < 32; ++i) { @@ -6418,12 +6467,11 @@ printSet(uintptr_t* m, unsigned limit) } } -void calculateTryCatchRoots( - Context* context, - uintptr_t* roots, - unsigned mapSize, - unsigned start, - unsigned end) +void calculateTryCatchRoots(Context* context, + uintptr_t* roots, + unsigned mapSize, + unsigned start, + unsigned end) { memset(roots, 0xFF, mapSize * BytesPerWord); @@ -6518,7 +6566,7 @@ unsigned calculateFrameMaps(MyThread* t, fprintf(stderr, "\n"); } - assert(context->thread, ip * mapSize <= context->rootTable.count); + assertT(context->thread, ip * mapSize <= context->rootTable.count); uintptr_t* tableRoots = context->rootTable.begin() + (ip * mapSize); if (context->visitTable[ip] > 1) { @@ -6527,8 +6575,7 @@ unsigned calculateFrameMaps(MyThread* t, if ((eventIndex == length or context->eventLog.get(eventIndex) == PopContextEvent) - and newRoots != tableRoots[wi]) - { + and newRoots != tableRoots[wi]) { if (DebugFrameMaps) { fprintf(stderr, "dirty roots!\n"); } @@ -6578,13 +6625,14 @@ unsigned calculateFrameMaps(MyThread* t, } break; case TraceEvent: { - TraceElement* te; context->eventLog.get(eventIndex, &te, BytesPerWord); + TraceElement* te; + context->eventLog.get(eventIndex, &te, BytesPerWord); if (DebugFrameMaps) { fprintf(stderr, " trace roots at ip %3d: ", ip); printSet(RUNTIME_ARRAY_BODY(roots), mapSize); fprintf(stderr, "\n"); } - + uintptr_t* map; bool watch; map = te->map; @@ -6607,11 +6655,12 @@ unsigned calculateFrameMaps(MyThread* t, eventIndex += BytesPerWord; } break; - default: abort(t); + default: + abort(t); } } - exit: +exit: if (resultRoots and ip != -1) { if (DebugFrameMaps) { fprintf(stderr, "result roots at ip %3d: ", ip); @@ -6625,8 +6674,7 @@ unsigned calculateFrameMaps(MyThread* t, return eventIndex; } -int -compareTraceElementPointers(const void* va, const void* vb) +int compareTraceElementPointers(const void* va, const void* vb) { TraceElement* a = *static_cast(va); TraceElement* b = *static_cast(vb); @@ -6639,19 +6687,20 @@ compareTraceElementPointers(const void* va, const void* vb) } } -unsigned -simpleFrameMapTableSize(MyThread* t, object method, object map) +unsigned simpleFrameMapTableSize(MyThread* t, GcMethod* method, GcIntArray* map) { int size = frameMapSizeInBits(t, method); - return ceilingDivide(intArrayLength(t, map) * size, 32 + size); + return ceilingDivide(map->length() * size, 32 + size); } -uint8_t* -finish(MyThread* t, FixedAllocator* allocator, avian::codegen::Assembler* a, const char* name, - unsigned length) +uint8_t* finish(MyThread* t, + FixedAllocator* allocator, + avian::codegen::Assembler* a, + const char* name, + unsigned length) { - uint8_t* start = static_cast - (allocator->allocate(length, TargetBytesPerWord)); + uint8_t* start + = static_cast(allocator->allocate(length, TargetBytesPerWord)); a->setDestination(start); a->write(); @@ -6661,14 +6710,12 @@ finish(MyThread* t, FixedAllocator* allocator, avian::codegen::Assembler* a, con return start; } -void -setBit(int32_t* dst, unsigned index) +void setBit(int32_t* dst, unsigned index) { dst[index / 32] |= static_cast(1) << (index % 32); } -void -clearBit(int32_t* dst, unsigned index) +void clearBit(int32_t* dst, unsigned index) { dst[index / 32] &= ~(static_cast(1) << (index % 32)); } @@ -6708,20 +6755,19 @@ void copyFrameMap(int32_t* dst, class FrameMapTableHeader { public: - FrameMapTableHeader(unsigned indexCount): - indexCount(indexCount) - { } + FrameMapTableHeader(unsigned indexCount) : indexCount(indexCount) + { + } unsigned indexCount; }; class FrameMapTableIndexElement { public: - FrameMapTableIndexElement(int offset, unsigned base, unsigned path): - offset(offset), - base(base), - path(path) - { } + FrameMapTableIndexElement(int offset, unsigned base, unsigned path) + : offset(offset), base(base), path(path) + { + } int offset; unsigned base; @@ -6730,11 +6776,10 @@ class FrameMapTableIndexElement { class FrameMapTablePath { public: - FrameMapTablePath(unsigned stackIndex, unsigned elementCount, unsigned next): - stackIndex(stackIndex), - elementCount(elementCount), - next(next) - { } + FrameMapTablePath(unsigned stackIndex, unsigned elementCount, unsigned next) + : stackIndex(stackIndex), elementCount(elementCount), next(next) + { + } unsigned stackIndex; unsigned elementCount; @@ -6742,65 +6787,62 @@ class FrameMapTablePath { int32_t elements[0]; }; -object -makeSimpleFrameMapTable(MyThread* t, Context* context, uint8_t* start, - TraceElement** elements, unsigned elementCount) +GcIntArray* makeSimpleFrameMapTable(MyThread* t, + Context* context, + uint8_t* start, + TraceElement** elements, + unsigned elementCount) { unsigned mapSize = frameMapSizeInBits(t, context->method); - object table = makeIntArray - (t, elementCount + ceilingDivide(elementCount * mapSize, 32)); + GcIntArray* table = makeIntArray( + t, elementCount + ceilingDivide(elementCount * mapSize, 32)); - assert(t, intArrayLength(t, table) == elementCount - + simpleFrameMapTableSize(t, context->method, table)); + assertT(t, + table->length() + == elementCount + simpleFrameMapTableSize(t, context->method, table)); for (unsigned i = 0; i < elementCount; ++i) { TraceElement* p = elements[i]; - intArrayBody(t, table, i) = static_cast(p->address->value()) - - reinterpret_cast(start); + table->body()[i] = static_cast(p->address->value()) + - reinterpret_cast(start); - assert(t, elementCount + ceilingDivide((i + 1) * mapSize, 32) - <= intArrayLength(t, table)); + assertT( + t, + elementCount + ceilingDivide((i + 1) * mapSize, 32) <= table->length()); if (mapSize) { - copyFrameMap(&intArrayBody(t, table, elementCount), - p->map, - mapSize, - i * mapSize, - p); + copyFrameMap( + &table->body()[elementCount], p->map, mapSize, i * mapSize, p); } } return table; } -void -finish(MyThread* t, FixedAllocator* allocator, Context* context) +void finish(MyThread* t, FixedAllocator* allocator, Context* context) { avian::codegen::Compiler* c = context->compiler; if (false) { - logCompile - (t, 0, 0, - reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, context->method)), 0)), - reinterpret_cast - (&byteArrayBody(t, methodName(t, context->method), 0)), - reinterpret_cast - (&byteArrayBody(t, methodSpec(t, context->method), 0))); + logCompile( + t, + 0, + 0, + reinterpret_cast( + context->method->class_()->name()->body().begin()), + reinterpret_cast(context->method->name()->body().begin()), + reinterpret_cast(context->method->spec()->body().begin())); } // for debugging: - if (false and - ::strcmp - (reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, context->method)), 0)), - "java/lang/System") == 0 and - ::strcmp - (reinterpret_cast - (&byteArrayBody(t, methodName(t, context->method), 0)), - "") == 0) - { + if (false + and ::strcmp(reinterpret_cast( + context->method->class_()->name()->body().begin()), + "java/lang/System") == 0 + and ::strcmp(reinterpret_cast( + context->method->name()->body().begin()), + "") == 0) { trap(); } @@ -6817,10 +6859,10 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) unsigned codeSize = c->resolve(allocator->memory.begin() + allocator->offset); unsigned total = pad(codeSize, TargetBytesPerWord) - + pad(c->poolSize(), TargetBytesPerWord); + + pad(c->poolSize(), TargetBytesPerWord); - target_uintptr_t* code = static_cast - (allocator->allocate(total, TargetBytesPerWord)); + target_uintptr_t* code = static_cast( + allocator->allocate(total, TargetBytesPerWord)); uint8_t* start = reinterpret_cast(code); context->executableAllocator = allocator; @@ -6828,19 +6870,22 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) context->executableSize = total; if (context->objectPool) { - object pool = allocate3 - (t, allocator, Machine::ImmortalAllocation, - FixedSizeOfArray + ((context->objectPoolCount + 1) * BytesPerWord), - true); + object pool = allocate3( + t, + allocator, + Machine::ImmortalAllocation, + GcArray::FixedSize + ((context->objectPoolCount + 1) * BytesPerWord), + true); context->executableSize = (allocator->memory.begin() + allocator->offset) - static_cast(context->executableStart); - initArray(t, pool, context->objectPoolCount + 1); + initArray( + t, reinterpret_cast(pool), context->objectPoolCount + 1); mark(t, pool, 0); - set(t, pool, ArrayBody, root(t, ObjectPools)); - setRoot(t, ObjectPools, pool); + setField(t, pool, ArrayBody, compileRoots(t)->objectPools()); + compileRoots(t)->setObjectPools(t, pool); unsigned i = 1; for (PoolElement* p = context->objectPool; p; p = p->next) { @@ -6848,7 +6893,7 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) p->address = reinterpret_cast(pool) + offset; - set(t, pool, offset, p->target); + setField(t, pool, offset, p->target); } } @@ -6858,29 +6903,38 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) if (bc) { for (avian::codegen::DelayedPromise* p = bc->addresses; p != bc->addressSentinal; - p = p->next) - { - p->basis = new(bc->zone) avian::codegen::ResolvedPromise(p->basis->value()); + p = p->next) { + p->basis = new (bc->zone) + avian::codegen::ResolvedPromise(p->basis->value()); } } - { object newExceptionHandlerTable = translateExceptionHandlerTable - (t, context, reinterpret_cast(start), - reinterpret_cast(start) + codeSize); + { + GcArray* newExceptionHandlerTable = translateExceptionHandlerTable( + t, + context, + reinterpret_cast(start), + reinterpret_cast(start) + codeSize); PROTECT(t, newExceptionHandlerTable); - object newLineNumberTable = translateLineNumberTable - (t, context, reinterpret_cast(start)); + GcLineNumberTable* newLineNumberTable = translateLineNumberTable( + t, context, reinterpret_cast(start)); - object code = methodCode(t, context->method); + GcCode* code = context->method->code(); - code = makeCode - (t, 0, newExceptionHandlerTable, newLineNumberTable, - reinterpret_cast(start), codeSize, codeMaxStack(t, code), - codeMaxLocals(t, code), 0); + code = makeCode(t, + 0, + 0, + newExceptionHandlerTable, + newLineNumberTable, + reinterpret_cast(start), + codeSize, + code->maxStack(), + code->maxLocals(), + 0); - set(t, context->method, MethodCode, code); + context->method->setCode(t, code); } if (context->traceLogCount) { @@ -6889,49 +6943,46 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) // unsigned pathFootprint = 0; // unsigned mapCount = 0; for (TraceElement* p = context->traceLog; p; p = p->next) { - assert(t, index < context->traceLogCount); + assertT(t, index < context->traceLogCount); if (p->address) { - RUNTIME_ARRAY_BODY(elements)[index++] = p; if (p->target) { - insertCallNode - (t, makeCallNode - (t, p->address->value(), p->target, p->flags, 0)); + insertCallNode( + t, makeCallNode(t, p->address->value(), p->target, p->flags, 0)); } } } - qsort(RUNTIME_ARRAY_BODY(elements), index, - sizeof(TraceElement*), compareTraceElementPointers); + qsort(RUNTIME_ARRAY_BODY(elements), + index, + sizeof(TraceElement*), + compareTraceElementPointers); - object map = makeSimpleFrameMapTable( + GcIntArray* map = makeSimpleFrameMapTable( t, context, start, RUNTIME_ARRAY_BODY(elements), index); - set(t, methodCode(t, context->method), CodePool, map); + context->method->code()->setStackMap(t, map); } - logCompile - (t, start, codeSize, - reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, context->method)), 0)), - reinterpret_cast - (&byteArrayBody(t, methodName(t, context->method), 0)), - reinterpret_cast - (&byteArrayBody(t, methodSpec(t, context->method), 0))); + logCompile( + t, + start, + codeSize, + reinterpret_cast( + context->method->class_()->name()->body().begin()), + reinterpret_cast(context->method->name()->body().begin()), + reinterpret_cast(context->method->spec()->body().begin())); // for debugging: - if (false and - ::strcmp - (reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, context->method)), 0)), - "java/lang/System") == 0 and - ::strcmp - (reinterpret_cast - (&byteArrayBody(t, methodName(t, context->method), 0)), - "") == 0) - { + if (false + and ::strcmp(reinterpret_cast( + context->method->class_()->name()->body().begin()), + "java/lang/System") == 0 + and ::strcmp(reinterpret_cast( + context->method->name()->body().begin()), + "") == 0) { trap(); } #if !defined(AVIAN_AOT_ONLY) @@ -6939,36 +6990,39 @@ finish(MyThread* t, FixedAllocator* allocator, Context* context) #endif } -void -compile(MyThread* t, Context* context) +void compile(MyThread* t, Context* context) { avian::codegen::Compiler* c = context->compiler; -// fprintf(stderr, "compiling %s.%s%s\n", -// &byteArrayBody(t, className(t, methodClass(t, context->method)), 0), -// &byteArrayBody(t, methodName(t, context->method), 0), -// &byteArrayBody(t, methodSpec(t, context->method), 0)); + if (false) { + fprintf(stderr, + "compiling %s.%s%s\n", + context->method->class_()->name()->body().begin(), + context->method->name()->body().begin(), + context->method->spec()->body().begin()); + } - unsigned footprint = methodParameterFootprint(t, context->method); + unsigned footprint = context->method->parameterFootprint(); unsigned locals = localSize(t, context->method); - c->init(codeLength(t, methodCode(t, context->method)), footprint, locals, + c->init(context->method->code()->length(), + footprint, + locals, alignedFrameSize(t, context->method)); - ir::Type* stackMap = (ir::Type*)malloc( - sizeof(ir::Type) * codeMaxStack(t, methodCode(t, context->method))); + ir::Type* stackMap = (ir::Type*)malloc(sizeof(ir::Type) + * context->method->code()->maxStack()); Frame frame(context, stackMap); - unsigned index = methodParameterFootprint(t, context->method); - if ((methodFlags(t, context->method) & ACC_STATIC) == 0) { + unsigned index = context->method->parameterFootprint(); + if ((context->method->flags() & ACC_STATIC) == 0) { frame.set(--index, ir::Type::object()); c->initLocal(index, ir::Type::object()); } - for (MethodSpecIterator it - (t, reinterpret_cast - (&byteArrayBody(t, methodSpec(t, context->method), 0))); - it.hasNext();) - { + for (MethodSpecIterator it(t, + reinterpret_cast( + context->method->spec()->body().begin())); + it.hasNext();) { switch (*it.next()) { case 'L': case '[': @@ -7009,11 +7063,12 @@ compile(MyThread* t, Context* context) context->dirtyRoots = false; unsigned eventIndex = calculateFrameMaps(t, context, 0, 0, 0); - object eht = codeExceptionHandlerTable(t, methodCode(t, context->method)); + GcExceptionHandlerTable* eht = cast( + t, context->method->code()->exceptionHandlerTable()); if (eht) { PROTECT(t, eht); - unsigned visitCount = exceptionHandlerTableLength(t, eht); + unsigned visitCount = eht->length(); THREAD_RUNTIME_ARRAY(t, bool, visited, visitCount); memset(RUNTIME_ARRAY_BODY(visited), 0, visitCount * sizeof(bool)); @@ -7023,26 +7078,24 @@ compile(MyThread* t, Context* context) progress = false; for (unsigned subI = 0; subI <= context->subroutineCount; ++subI) { - unsigned duplicatedBaseIp - = subI * codeLength(t, methodCode(t, context->method)); + unsigned duplicatedBaseIp = subI * context->method->code()->length(); - for (unsigned i = 0; i < exceptionHandlerTableLength(t, eht); ++i) { - uint64_t eh = exceptionHandlerTableBody(t, eht, i); + for (unsigned i = 0; i < eht->length(); ++i) { + uint64_t eh = eht->body()[i]; int start = resolveIpForwards(context, duplicatedBaseIp + exceptionHandlerStart(eh), duplicatedBaseIp + exceptionHandlerEnd(eh)); - if ((not RUNTIME_ARRAY_BODY(visited)[i])and start - >= 0 and context->visitTable[start]) { + if ((not RUNTIME_ARRAY_BODY(visited)[i]) and start >= 0 + and context->visitTable[start]) { RUNTIME_ARRAY_BODY(visited)[i] = true; progress = true; c->restoreState(state); ir::Type* stackMap = (ir::Type*)malloc( - sizeof(ir::Type) - * codeMaxStack(t, methodCode(t, context->method))); + sizeof(ir::Type) * context->method->code()->maxStack()); Frame frame2(&frame, stackMap); unsigned end = duplicatedBaseIp + exceptionHandlerEnd(eh); @@ -7055,9 +7108,7 @@ compile(MyThread* t, Context* context) context->eventLog.append2(start); context->eventLog.append2(end); - for (unsigned i = 1; - i < codeMaxStack(t, methodCode(t, context->method)); - ++i) { + for (unsigned i = 1; i < context->method->code()->maxStack(); ++i) { frame2.set(localSize(t, context->method) + i, ir::Type::i4()); } @@ -7079,17 +7130,17 @@ compile(MyThread* t, Context* context) free(stackMap); } -void -updateCall(MyThread* t, avian::codegen::lir::UnaryOperation op, void* returnAddress, void* target) +void updateCall(MyThread* t, + avian::codegen::lir::UnaryOperation op, + void* returnAddress, + void* target) { t->arch->updateCall(op, returnAddress, target); } -void* -compileMethod2(MyThread* t, void* ip); +void* compileMethod2(MyThread* t, void* ip); -uint64_t -compileMethod(MyThread* t) +uint64_t compileMethod(MyThread* t) { void* ip; if (t->tailAddress) { @@ -7102,8 +7153,7 @@ compileMethod(MyThread* t) return reinterpret_cast(compileMethod2(t, ip)); } -void* -compileVirtualMethod2(MyThread* t, object class_, unsigned index) +void* compileVirtualMethod2(MyThread* t, GcClass* class_, unsigned index) { // If class_ has BootstrapFlag set, that means its vtable is not yet // available. However, we must set t->trace->targetMethod to an @@ -7111,34 +7161,34 @@ compileVirtualMethod2(MyThread* t, object class_, unsigned index) // GC roots. We find such a method by looking for a superclass with // a vtable and using it instead: - object c = class_; - while (classVmFlags(t, c) & BootstrapFlag) { - c = classSuper(t, c); + GcClass* c = class_; + while (c->vmFlags() & BootstrapFlag) { + c = c->super(); } - t->trace->targetMethod = arrayBody(t, classVirtualTable(t, c), index); + t->trace->targetMethod + = cast(t, cast(t, c->virtualTable())->body()[index]); THREAD_RESOURCE0(t, static_cast(t)->trace->targetMethod = 0;); PROTECT(t, class_); - object target = resolveTarget(t, class_, index); + GcMethod* target = resolveTarget(t, class_, index); PROTECT(t, target); compile(t, codeAllocator(t), 0, target); void* address = reinterpret_cast(methodAddress(t, target)); - if (methodFlags(t, target) & ACC_NATIVE) { + if (target->flags() & ACC_NATIVE) { t->trace->nativeMethod = target; } else { - classVtable(t, class_, methodOffset(t, target)) = address; + class_->vtable()[target->offset()] = address; } return address; } -uint64_t -compileVirtualMethod(MyThread* t) +uint64_t compileVirtualMethod(MyThread* t) { - object class_ = objectClass(t, static_cast(t->virtualCallTarget)); + GcClass* class_ = objectClass(t, static_cast(t->virtualCallTarget)); t->virtualCallTarget = 0; unsigned index = t->virtualCallIndex; @@ -7147,26 +7197,25 @@ compileVirtualMethod(MyThread* t) return reinterpret_cast(compileVirtualMethod2(t, class_, index)); } -uint64_t -invokeNativeFast(MyThread* t, object method, void* function) +uint64_t invokeNativeFast(MyThread* t, GcMethod* method, void* function) { - FastNativeFunction f; memcpy(&f, &function, sizeof(void*)); - return f(t, method, - static_cast(t->stack) - + t->arch->frameFooterSize() + FastNativeFunction f; + memcpy(&f, &function, sizeof(void*)); + return f(t, + method, + static_cast(t->stack) + t->arch->frameFooterSize() + t->arch->frameReturnAddressSize()); } -uint64_t -invokeNativeSlow(MyThread* t, object method, void* function) +uint64_t invokeNativeSlow(MyThread* t, GcMethod* method, void* function) { PROTECT(t, method); - unsigned footprint = methodParameterFootprint(t, method) + 1; - if (methodFlags(t, method) & ACC_STATIC) { - ++ footprint; + unsigned footprint = method->parameterFootprint() + 1; + if (method->flags() & ACC_STATIC) { + ++footprint; } - unsigned count = methodParameterCount(t, method) + 2; + unsigned count = method->parameterCount() + 2; THREAD_RUNTIME_ARRAY(t, uintptr_t, args, footprint); unsigned argOffset = 0; @@ -7176,30 +7225,27 @@ invokeNativeSlow(MyThread* t, object method, void* function) RUNTIME_ARRAY_BODY(args)[argOffset++] = reinterpret_cast(t); RUNTIME_ARRAY_BODY(types)[typeOffset++] = POINTER_TYPE; - uintptr_t* sp = static_cast(t->stack) - + t->arch->frameFooterSize() - + t->arch->frameReturnAddressSize(); + uintptr_t* sp = static_cast(t->stack) + t->arch->frameFooterSize() + + t->arch->frameReturnAddressSize(); - object jclass = 0; + GcJclass* jclass = 0; PROTECT(t, jclass); - if (methodFlags(t, method) & ACC_STATIC) { - jclass = getJClass(t, methodClass(t, method)); + if (method->flags() & ACC_STATIC) { + jclass = getJClass(t, method->class_()); RUNTIME_ARRAY_BODY(args)[argOffset++] - = reinterpret_cast(&jclass); + = reinterpret_cast(&jclass); } else { - RUNTIME_ARRAY_BODY(args)[argOffset++] - = reinterpret_cast(sp++); + RUNTIME_ARRAY_BODY(args)[argOffset++] = reinterpret_cast(sp++); } RUNTIME_ARRAY_BODY(types)[typeOffset++] = POINTER_TYPE; - MethodSpecIterator it - (t, reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0))); - + MethodSpecIterator it( + t, reinterpret_cast(method->spec()->body().begin())); + while (it.hasNext()) { unsigned type = RUNTIME_ARRAY_BODY(types)[typeOffset++] - = fieldType(t, fieldCode(t, *it.next())); + = fieldType(t, fieldCode(t, *it.next())); switch (type) { case INT8_TYPE: @@ -7218,31 +7264,32 @@ invokeNativeSlow(MyThread* t, object method, void* function) case POINTER_TYPE: { if (*sp) { - RUNTIME_ARRAY_BODY(args)[argOffset++] - = reinterpret_cast(sp); + RUNTIME_ARRAY_BODY(args)[argOffset++] = reinterpret_cast(sp); } else { RUNTIME_ARRAY_BODY(args)[argOffset++] = 0; } - ++ sp; + ++sp; } break; - default: abort(t); + default: + abort(t); } } - unsigned returnCode = methodReturnCode(t, method); + unsigned returnCode = method->returnCode(); unsigned returnType = fieldType(t, returnCode); uint64_t result; if (DebugNatives) { - fprintf(stderr, "invoke native method %s.%s\n", - &byteArrayBody(t, className(t, methodClass(t, method)), 0), - &byteArrayBody(t, methodName(t, method), 0)); + fprintf(stderr, + "invoke native method %s.%s\n", + method->class_()->name()->body().begin(), + method->name()->body().begin()); } - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { - if (methodFlags(t, method) & ACC_STATIC) { - acquire(t, methodClass(t, method)); + if (method->flags() & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_STATIC) { + acquire(t, method->class_()); } else { acquire(t, *reinterpret_cast(RUNTIME_ARRAY_BODY(args)[1])); } @@ -7250,7 +7297,8 @@ invokeNativeSlow(MyThread* t, object method, void* function) Reference* reference = t->reference; - { ENTER(t, Thread::IdleState); + { + ENTER(t, Thread::IdleState); bool noThrow = t->checkpoint->noThrow; t->checkpoint->noThrow = true; @@ -7264,22 +7312,23 @@ invokeNativeSlow(MyThread* t, object method, void* function) returnType); } - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { - if (methodFlags(t, method) & ACC_STATIC) { - release(t, methodClass(t, method)); + if (method->flags() & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_STATIC) { + release(t, method->class_()); } else { release(t, *reinterpret_cast(RUNTIME_ARRAY_BODY(args)[1])); } } if (DebugNatives) { - fprintf(stderr, "return from native method %s.%s\n", - &byteArrayBody(t, className(t, methodClass(t, method)), 0), - &byteArrayBody(t, methodName(t, method), 0)); + fprintf(stderr, + "return from native method %s.%s\n", + method->class_()->name()->body().begin(), + method->name()->body().begin()); } if (UNLIKELY(t->exception)) { - object exception = t->exception; + GcThrowable* exception = t->exception; t->exception = 0; vm::throw_(t, exception); } @@ -7308,15 +7357,17 @@ invokeNativeSlow(MyThread* t, object method, void* function) break; case ObjectField: - result = static_cast(result) ? *reinterpret_cast - (static_cast(result)) : 0; + result = static_cast(result) + ? *reinterpret_cast(static_cast(result)) + : 0; break; case VoidField: result = 0; break; - default: abort(t); + default: + abort(t); } while (t->reference != reference) { @@ -7325,20 +7376,18 @@ invokeNativeSlow(MyThread* t, object method, void* function) return result; } - -uint64_t -invokeNative2(MyThread* t, object method) + +uint64_t invokeNative2(MyThread* t, GcMethod* method) { - object native = methodRuntimeDataNative(t, getMethodRuntimeData(t, method)); - if (nativeFast(t, native)) { - return invokeNativeFast(t, method, nativeFunction(t, native)); + GcNative* native = getMethodRuntimeData(t, method)->native(); + if (native->fast()) { + return invokeNativeFast(t, method, native->function()); } else { - return invokeNativeSlow(t, method, nativeFunction(t, native)); + return invokeNativeSlow(t, method, native->function()); } } -uint64_t -invokeNative(MyThread* t) +uint64_t invokeNative(MyThread* t) { if (t->trace->nativeMethod == 0) { void* ip; @@ -7349,15 +7398,15 @@ invokeNative(MyThread* t) ip = getIp(t); } - object node = findCallNode(t, ip); - object target = callNodeTarget(t, node); - if (callNodeFlags(t, node) & TraceElement::VirtualCall) { + GcCallNode* node = findCallNode(t, ip); + GcMethod* target = node->target(); + if (node->flags() & TraceElement::VirtualCall) { target = resolveTarget(t, t->stack, target); } t->trace->nativeMethod = target; } - assert(t, t->tailAddress == 0); + assertT(t, t->tailAddress == 0); uint64_t result = 0; @@ -7367,17 +7416,15 @@ invokeNative(MyThread* t) result = invokeNative2(t, t->trace->nativeMethod); - unsigned parameterFootprint = methodParameterFootprint - (t, t->trace->targetMethod); + unsigned parameterFootprint = t->trace->targetMethod->parameterFootprint(); uintptr_t* stack = static_cast(t->stack); if (avian::codegen::TailCalls and t->arch->argumentFootprint(parameterFootprint) - > t->arch->stackAlignmentInWords()) - { + > t->arch->stackAlignmentInWords()) { stack += t->arch->argumentFootprint(parameterFootprint) - - t->arch->stackAlignmentInWords(); + - t->arch->stackAlignmentInWords(); } stack += t->arch->frameReturnAddressSize(); @@ -7390,21 +7437,24 @@ invokeNative(MyThread* t) return result; } -void -findFrameMapInSimpleTable(MyThread* t, object method, object table, - int32_t offset, int32_t** map, unsigned* start) +void findFrameMapInSimpleTable(MyThread* t, + GcMethod* method, + GcIntArray* table, + int32_t offset, + int32_t** map, + unsigned* start) { unsigned tableSize = simpleFrameMapTableSize(t, method, table); - unsigned indexSize = intArrayLength(t, table) - tableSize; + unsigned indexSize = table->length() - tableSize; + + *map = &table->body()[indexSize]; - *map = &intArrayBody(t, table, indexSize); - unsigned bottom = 0; unsigned top = indexSize; for (unsigned span = top - bottom; span; span = top - bottom) { unsigned middle = bottom + (span / 2); - int32_t v = intArrayBody(t, table, middle); - + int32_t v = table->body()[middle]; + if (offset == v) { *start = frameMapSizeInBits(t, method) * middle; return; @@ -7418,78 +7468,22 @@ findFrameMapInSimpleTable(MyThread* t, object method, object table, abort(t); } -unsigned -findFrameMap(MyThread* t, void* stack, object method, object table, - unsigned pathIndex) +void findFrameMap(MyThread* t, + void* stack UNUSED, + GcMethod* method, + int32_t offset, + int32_t** map, + unsigned* start) { - if (pathIndex) { - FrameMapTablePath* path = reinterpret_cast - (&byteArrayBody(t, table, pathIndex)); - - void* address = static_cast(stack)[path->stackIndex]; - uint8_t* base = reinterpret_cast(methodAddress(t, method)); - for (unsigned i = 0; i < path->elementCount; ++i) { - if (address == base + path->elements[i]) { - return i + (path->elementCount * findFrameMap - (t, stack, method, table, path->next)); - } - } - - abort(t); - } else { - return 0; - } + findFrameMapInSimpleTable( + t, method, method->code()->stackMap(), offset, map, start); } -void -findFrameMapInGeneralTable(MyThread* t, void* stack, object method, - object table, int32_t offset, int32_t** map, - unsigned* start) -{ - FrameMapTableHeader* header = reinterpret_cast - (&byteArrayBody(t, table, 0)); - - FrameMapTableIndexElement* index - = reinterpret_cast - (&byteArrayBody(t, table, sizeof(FrameMapTableHeader))); - - *map = reinterpret_cast(index + header->indexCount); - - unsigned bottom = 0; - unsigned top = header->indexCount; - for (unsigned span = top - bottom; span; span = top - bottom) { - unsigned middle = bottom + (span / 2); - FrameMapTableIndexElement* v = index + middle; - - if (offset == v->offset) { - *start = v->base + (findFrameMap(t, stack, method, table, v->path) - * frameMapSizeInBits(t, method)); - return; - } else if (offset < v->offset) { - top = middle; - } else { - bottom = middle + 1; - } - } - - abort(t); -} - -void -findFrameMap(MyThread* t, void* stack, object method, int32_t offset, - int32_t** map, unsigned* start) -{ - object table = codePool(t, methodCode(t, method)); - if (objectClass(t, table) == type(t, Machine::IntArrayType)) { - findFrameMapInSimpleTable(t, method, table, offset, map, start); - } else { - findFrameMapInGeneralTable(t, stack, method, table, offset, map, start); - } -} - -void -visitStackAndLocals(MyThread* t, Heap::Visitor* v, void* frame, object method, - void* ip) +void visitStackAndLocals(MyThread* t, + Heap::Visitor* v, + void* frame, + GcMethod* method, + void* ip) { unsigned count = frameMapSizeInBits(t, method); @@ -7498,69 +7492,69 @@ visitStackAndLocals(MyThread* t, Heap::Visitor* v, void* frame, object method, int32_t* map; unsigned offset; - findFrameMap - (t, stack, method, difference - (ip, reinterpret_cast(methodAddress(t, method))), &map, &offset); + findFrameMap( + t, + stack, + method, + difference(ip, reinterpret_cast(methodAddress(t, method))), + &map, + &offset); for (unsigned i = 0; i < count; ++i) { int j = offset + i; if (map[j / 32] & (static_cast(1) << (j % 32))) { - v->visit(localObject(t, stack, method, i)); + v->visit(localObject(t, stack, method, i)); } } } } -void -visitArgument(MyThread* t, Heap::Visitor* v, void* stack, unsigned index) +void visitArgument(MyThread* t, Heap::Visitor* v, void* stack, unsigned index) { - v->visit(static_cast(stack) - + index - + t->arch->frameReturnAddressSize() - + t->arch->frameFooterSize()); + v->visit(static_cast(stack) + index + + t->arch->frameReturnAddressSize() + t->arch->frameFooterSize()); } -void -visitArguments(MyThread* t, Heap::Visitor* v, void* stack, object method) +void visitArguments(MyThread* t, + Heap::Visitor* v, + void* stack, + GcMethod* method) { unsigned index = 0; - if ((methodFlags(t, method) & ACC_STATIC) == 0) { + if ((method->flags() & ACC_STATIC) == 0) { visitArgument(t, v, stack, index++); } - for (MethodSpecIterator it - (t, reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0))); - it.hasNext();) - { + for (MethodSpecIterator it( + t, reinterpret_cast(method->spec()->body().begin())); + it.hasNext();) { switch (*it.next()) { case 'L': case '[': visitArgument(t, v, stack, index++); break; - + case 'J': case 'D': index += 2; break; default: - ++ index; + ++index; break; } } } -void -visitStack(MyThread* t, Heap::Visitor* v) +void visitStack(MyThread* t, Heap::Visitor* v) { void* ip = getIp(t); void* stack = t->stack; MyThread::CallTrace* trace = t->trace; - object targetMethod = (trace ? trace->targetMethod : 0); - object target = targetMethod; + GcMethod* targetMethod = (trace ? trace->targetMethod : 0); + GcMethod* target = targetMethod; bool mostRecent = true; while (stack) { @@ -7569,7 +7563,7 @@ visitStack(MyThread* t, Heap::Visitor* v) targetMethod = 0; } - object method = methodForIp(t, ip); + GcMethod* method = methodForIp(t, ip); if (method) { PROTECT(t, method); @@ -7600,20 +7594,20 @@ visitStack(MyThread* t, Heap::Visitor* v) } } -void -walkContinuationBody(MyThread* t, Heap::Walker* w, object c, int start) +void walkContinuationBody(MyThread* t, + Heap::Walker* w, + GcContinuation* c, + int start) { const int BodyOffset = ContinuationBody / BytesPerWord; - object method = static_cast - (t->m->heap->follow(continuationMethod(t, c))); + GcMethod* method = t->m->heap->follow(c->method()); int count = frameMapSizeInBits(t, method); if (count) { - int stack = BodyOffset - + (continuationFramePointerOffset(t, c) / BytesPerWord) - - t->arch->framePointerOffset() - - stackOffsetFromFrame(t, method); + int stack = BodyOffset + (c->framePointerOffset() / BytesPerWord) + - t->arch->framePointerOffset() + - stackOffsetFromFrame(t, method); int first = stack + localOffsetFromStack(t, count - 1, method); if (start > first) { @@ -7622,10 +7616,13 @@ walkContinuationBody(MyThread* t, Heap::Walker* w, object c, int start) int32_t* map; unsigned offset; - findFrameMap - (t, reinterpret_cast(c) + stack, method, difference - (continuationAddress(t, c), - reinterpret_cast(methodAddress(t, method))), &map, &offset); + findFrameMap(t, + reinterpret_cast(c) + stack, + method, + difference(c->address(), + reinterpret_cast(methodAddress(t, method))), + &map, + &offset); for (int i = count - 1; i >= 0; --i) { int j = offset + i; @@ -7638,11 +7635,14 @@ walkContinuationBody(MyThread* t, Heap::Walker* w, object c, int start) } } -void -callContinuation(MyThread* t, object continuation, object result, - object exception, void* ip, void* stack) +void callContinuation(MyThread* t, + GcContinuation* continuation, + object result, + GcThrowable* exception, + void* ip, + void* stack) { - assert(t, t->exception == 0); + assertT(t, t->exception == 0); if (exception) { t->exception = exception; @@ -7663,133 +7663,123 @@ callContinuation(MyThread* t, object continuation, object result, vmJump(ip, 0, stack, t, reinterpret_cast(result), 0); } -int8_t* -returnSpec(MyThread* t, object method) +int8_t* returnSpec(MyThread* t, GcMethod* method) { - int8_t* s = &byteArrayBody(t, methodSpec(t, method), 0); - while (*s and *s != ')') ++ s; + int8_t* s = method->spec()->body().begin(); + while (*s and *s != ')') + ++s; expect(t, *s == ')'); return s + 1; } -object -returnClass(MyThread* t, object method) +GcClass* returnClass(MyThread* t, GcMethod* method) { PROTECT(t, method); int8_t* spec = returnSpec(t, method); unsigned length = strlen(reinterpret_cast(spec)); - object name; + GcByteArray* name; if (*spec == '[') { name = makeByteArray(t, length + 1); - memcpy(&byteArrayBody(t, name, 0), spec, length); + memcpy(name->body().begin(), spec, length); } else { - assert(t, *spec == 'L'); - assert(t, spec[length - 1] == ';'); + assertT(t, *spec == 'L'); + assertT(t, spec[length - 1] == ';'); name = makeByteArray(t, length - 1); - memcpy(&byteArrayBody(t, name, 0), spec + 1, length - 2); + memcpy(name->body().begin(), spec + 1, length - 2); } - return resolveClass(t, classLoader(t, methodClass(t, method)), name); + return resolveClass(t, method->class_()->loader(), name); } -bool -compatibleReturnType(MyThread* t, object oldMethod, object newMethod) +bool compatibleReturnType(MyThread* t, GcMethod* oldMethod, GcMethod* newMethod) { if (oldMethod == newMethod) { return true; - } else if (methodReturnCode(t, oldMethod) == methodReturnCode(t, newMethod)) - { - if (methodReturnCode(t, oldMethod) == ObjectField) { + } else if (oldMethod->returnCode() == newMethod->returnCode()) { + if (oldMethod->returnCode() == ObjectField) { PROTECT(t, newMethod); - object oldClass = returnClass(t, oldMethod); + GcClass* oldClass = returnClass(t, oldMethod); PROTECT(t, oldClass); - object newClass = returnClass(t, newMethod); + GcClass* newClass = returnClass(t, newMethod); return isAssignableFrom(t, oldClass, newClass); } else { return true; } } else { - return methodReturnCode(t, oldMethod) == VoidField; + return oldMethod->returnCode() == VoidField; } } -void -jumpAndInvoke(MyThread* t, object method, void* stack, ...) +void jumpAndInvoke(MyThread* t, GcMethod* method, void* stack, ...) { t->trace->targetMethod = 0; - if (methodFlags(t, method) & ACC_NATIVE) { + if (method->flags() & ACC_NATIVE) { t->trace->nativeMethod = method; } else { t->trace->nativeMethod = 0; } - unsigned argumentCount = methodParameterFootprint(t, method); + unsigned argumentCount = method->parameterFootprint(); THREAD_RUNTIME_ARRAY(t, uintptr_t, arguments, argumentCount); - va_list a; va_start(a, stack); + va_list a; + va_start(a, stack); for (unsigned i = 0; i < argumentCount; ++i) { RUNTIME_ARRAY_BODY(arguments)[i] = va_arg(a, uintptr_t); } va_end(a); - assert(t, t->exception == 0); + assertT(t, t->exception == 0); popResources(t); - - vmJumpAndInvoke - (t, reinterpret_cast(methodAddress(t, method)), - stack, - argumentCount * BytesPerWord, - RUNTIME_ARRAY_BODY(arguments), - (t->arch->alignFrameSize(t->arch->argumentFootprint(argumentCount)) - + t->arch->frameReturnAddressSize()) - * BytesPerWord); + + vmJumpAndInvoke( + t, + reinterpret_cast(methodAddress(t, method)), + stack, + argumentCount * BytesPerWord, + RUNTIME_ARRAY_BODY(arguments), + (t->arch->alignFrameSize(t->arch->argumentFootprint(argumentCount)) + + t->arch->frameReturnAddressSize()) * BytesPerWord); } -void -callContinuation(MyThread* t, object continuation, object result, - object exception) +void callContinuation(MyThread* t, + GcContinuation* continuation, + object result, + GcThrowable* exception) { - enum { - Call, - Unwind, - Rewind - } action; + enum { Call, Unwind, Rewind } action; - object nextContinuation = 0; + GcContinuation* nextContinuation = 0; if (t->continuation == 0 - or continuationContext(t, t->continuation) - != continuationContext(t, continuation)) - { + or t->continuation->context() != continuation->context()) { PROTECT(t, continuation); PROTECT(t, result); PROTECT(t, exception); - if (compatibleReturnType - (t, t->trace->originalMethod, continuationContextMethod - (t, continuationContext(t, continuation)))) - { - object oldContext; - object unwindContext; + if (compatibleReturnType( + t, t->trace->originalMethod, continuation->context()->method())) { + GcContinuationContext* oldContext; + GcContinuationContext* unwindContext; if (t->continuation) { - oldContext = continuationContext(t, t->continuation); + oldContext = t->continuation->context(); unwindContext = oldContext; } else { oldContext = 0; unwindContext = 0; } - object rewindContext = 0; + GcContinuationContext* rewindContext = 0; - for (object newContext = continuationContext(t, continuation); - newContext; newContext = continuationContextNext(t, newContext)) - { + for (GcContinuationContext* newContext = continuation->context(); + newContext; + newContext = newContext->next()) { if (newContext == oldContext) { unwindContext = 0; break; @@ -7798,37 +7788,38 @@ callContinuation(MyThread* t, object continuation, object result, } } - if (unwindContext - and continuationContextContinuation(t, unwindContext)) - { - nextContinuation = continuationContextContinuation(t, unwindContext); + if (unwindContext and unwindContext->continuation()) { + nextContinuation + = cast(t, unwindContext->continuation()); result = makeUnwindResult(t, continuation, result, exception); action = Unwind; - } else if (rewindContext - and continuationContextContinuation(t, rewindContext)) - { - nextContinuation = continuationContextContinuation(t, rewindContext); + } else if (rewindContext and rewindContext->continuation()) { + nextContinuation + = cast(t, rewindContext->continuation()); action = Rewind; - if (root(t, RewindMethod) == 0) { + if (compileRoots(t)->rewindMethod() == 0) { PROTECT(t, nextContinuation); - - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Continuations", "rewind", - "(Ljava/lang/Runnable;Lavian/Callback;Ljava/lang/Object;" - "Ljava/lang/Throwable;)V"); + + GcMethod* method = resolveMethod( + t, + roots(t)->bootLoader(), + "avian/Continuations", + "rewind", + "(Ljava/lang/Runnable;Lavian/Callback;Ljava/lang/Object;" + "Ljava/lang/Throwable;)V"); PROTECT(t, method); - + compile(t, local::codeAllocator(t), 0, method); - - setRoot(t, RewindMethod, method); + + compileRoots(t)->setRewindMethod(t, method); } } else { action = Call; } } else { - throwNew(t, Machine::IncompatibleContinuationExceptionType); + throwNew(t, GcIncompatibleContinuationException::Type); } } else { action = Call; @@ -7837,7 +7828,7 @@ callContinuation(MyThread* t, object continuation, object result, void* ip; void* frame; void* stack; - object threadContinuation; + GcContinuation* threadContinuation; findUnwindTarget(t, &ip, &frame, &stack, &threadContinuation); switch (action) { @@ -7852,10 +7843,13 @@ callContinuation(MyThread* t, object continuation, object result, case Rewind: { transition(t, 0, 0, nextContinuation, t->trace); - jumpAndInvoke - (t, root(t, RewindMethod), stack, - continuationContextBefore(t, continuationContext(t, nextContinuation)), - continuation, result, exception); + jumpAndInvoke(t, + compileRoots(t)->rewindMethod(), + stack, + nextContinuation->context()->before(), + continuation, + result, + exception); } break; default: @@ -7863,37 +7857,38 @@ callContinuation(MyThread* t, object continuation, object result, } } -void -callWithCurrentContinuation(MyThread* t, object receiver) +void callWithCurrentContinuation(MyThread* t, object receiver) { - object method = 0; + GcMethod* method = 0; void* ip = 0; void* stack = 0; - { PROTECT(t, receiver); + { + PROTECT(t, receiver); - if (root(t, ReceiveMethod) == 0) { - object m = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Function", "call", - "(Ljava/lang/Object;)Ljava/lang/Object;"); + if (compileRoots(t)->receiveMethod() == 0) { + GcMethod* m = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Function", + "call", + "(Ljava/lang/Object;)Ljava/lang/Object;"); if (m) { - setRoot(t, ReceiveMethod, m); + compileRoots(t)->setReceiveMethod(t, m); - object continuationClass = type(t, Machine::ContinuationType); - - if (classVmFlags(t, continuationClass) & BootstrapFlag) { - resolveSystemClass - (t, root(t, Machine::BootLoader), - vm::className(t, continuationClass)); + GcClass* continuationClass = type(t, GcContinuation::Type); + + if (continuationClass->vmFlags() & BootstrapFlag) { + resolveSystemClass( + t, roots(t)->bootLoader(), continuationClass->name()); } } } - method = findInterfaceMethod - (t, root(t, ReceiveMethod), objectClass(t, receiver)); + method = findInterfaceMethod( + t, compileRoots(t)->receiveMethod(), objectClass(t, receiver)); PROTECT(t, method); - + compile(t, local::codeAllocator(t), 0, method); t->continuation = makeCurrentContinuation(t, &ip, &stack); @@ -7902,51 +7897,63 @@ callWithCurrentContinuation(MyThread* t, object receiver) jumpAndInvoke(t, method, stack, receiver, t->continuation); } -void -dynamicWind(MyThread* t, object before, object thunk, object after) +void dynamicWind(MyThread* t, object before, object thunk, object after) { void* ip = 0; void* stack = 0; - { PROTECT(t, before); + { + PROTECT(t, before); PROTECT(t, thunk); PROTECT(t, after); - if (root(t, WindMethod) == 0) { - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Continuations", "wind", - "(Ljava/lang/Runnable;Ljava/util/concurrent/Callable;" - "Ljava/lang/Runnable;)Lavian/Continuations$UnwindResult;"); + if (compileRoots(t)->windMethod() == 0) { + GcMethod* method = resolveMethod( + t, + roots(t)->bootLoader(), + "avian/Continuations", + "wind", + "(Ljava/lang/Runnable;Ljava/util/concurrent/Callable;" + "Ljava/lang/Runnable;)Lavian/Continuations$UnwindResult;"); if (method) { - setRoot(t, WindMethod, method); + compileRoots(t)->setWindMethod(t, method); compile(t, local::codeAllocator(t), 0, method); } } t->continuation = makeCurrentContinuation(t, &ip, &stack); - object newContext = makeContinuationContext - (t, continuationContext(t, t->continuation), before, after, - t->continuation, t->trace->originalMethod); + GcContinuationContext* newContext + = makeContinuationContext(t, + t->continuation->context(), + before, + after, + t->continuation, + t->trace->originalMethod); - set(t, t->continuation, ContinuationContext, newContext); + t->continuation->setContext(t, newContext); } - jumpAndInvoke(t, root(t, WindMethod), stack, before, thunk, after); + jumpAndInvoke(t, compileRoots(t)->windMethod(), stack, before, thunk, after); } class ArgumentList { public: - ArgumentList(Thread* t, uintptr_t* array, unsigned size, bool* objectMask, - object this_, const char* spec, bool indirectObjects, - va_list arguments): - t(static_cast(t)), - array(array), - objectMask(objectMask), - size(size), - position(0), - protector(this) + ArgumentList(Thread* t, + uintptr_t* array, + unsigned size, + bool* objectMask, + object this_, + const char* spec, + bool indirectObjects, + va_list arguments) + : t(static_cast(t)), + array(array), + objectMask(objectMask), + size(size), + position(0), + protector(this) { if (this_) { addObject(this_); @@ -7963,7 +7970,7 @@ class ArgumentList { addObject(va_arg(arguments, object)); } break; - + case 'J': addLong(va_arg(arguments, uint64_t)); break; @@ -7978,19 +7985,24 @@ class ArgumentList { default: addInt(va_arg(arguments, uint32_t)); - break; + break; } } } - ArgumentList(Thread* t, uintptr_t* array, unsigned size, bool* objectMask, - object this_, const char* spec, const jvalue* arguments): - t(static_cast(t)), - array(array), - objectMask(objectMask), - size(size), - position(0), - protector(this) + ArgumentList(Thread* t, + uintptr_t* array, + unsigned size, + bool* objectMask, + object this_, + const char* spec, + const jvalue* arguments) + : t(static_cast(t)), + array(array), + objectMask(objectMask), + size(size), + position(0), + protector(this) { if (this_) { addObject(this_); @@ -8004,7 +8016,7 @@ class ArgumentList { object* v = arguments[index++].l; addObject(v ? *v : 0); } break; - + case 'J': addLong(arguments[index++].j); break; @@ -8019,19 +8031,24 @@ class ArgumentList { default: addInt(arguments[index++].i); - break; + break; } } } - ArgumentList(Thread* t, uintptr_t* array, unsigned size, bool* objectMask, - object this_, const char* spec, object arguments): - t(static_cast(t)), - array(array), - objectMask(objectMask), - size(size), - position(0), - protector(this) + ArgumentList(Thread* t, + uintptr_t* array, + unsigned size, + bool* objectMask, + object this_, + const char* spec, + object arguments) + : t(static_cast(t)), + array(array), + objectMask(objectMask), + size(size), + position(0), + protector(this) { if (this_) { addObject(this_); @@ -8044,38 +8061,42 @@ class ArgumentList { case '[': addObject(objectArrayBody(t, arguments, index++)); break; - + case 'J': case 'D': - addLong(fieldAtOffset(objectArrayBody(t, arguments, index++), 8)); + addLong( + fieldAtOffset(objectArrayBody(t, arguments, index++), 8)); break; default: addInt(fieldAtOffset(objectArrayBody(t, arguments, index++), - BytesPerWord)); + BytesPerWord)); break; } } } - void addObject(object v) { - assert(t, position < size); + void addObject(object v) + { + assertT(t, position < size); array[position] = reinterpret_cast(v); objectMask[position] = true; - ++ position; + ++position; } - void addInt(uintptr_t v) { - assert(t, position < size); + void addInt(uintptr_t v) + { + assertT(t, position < size); array[position] = v; objectMask[position] = false; - ++ position; + ++position; } - void addLong(uint64_t v) { - assert(t, position < size - 1); + void addLong(uint64_t v) + { + assertT(t, position < size - 1); memcpy(array + position, &v, 8); @@ -8091,11 +8112,14 @@ class ArgumentList { unsigned size; unsigned position; - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(ArgumentList* list): Protector(list->t), list(list) { } + MyProtector(ArgumentList* list) : Protector(list->t), list(list) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { for (unsigned i = 0; i < list->position; ++i) { if (list->objectMask[i]) { v->visit(reinterpret_cast(list->array + i)); @@ -8107,20 +8131,19 @@ class ArgumentList { } protector; }; -object -invoke(Thread* thread, object method, ArgumentList* arguments) +object invoke(Thread* thread, GcMethod* method, ArgumentList* arguments) { MyThread* t = static_cast(thread); if (false) { PROTECT(t, method); - compile(t, local::codeAllocator(static_cast(t)), 0, - resolveMethod - (t, root(t, Machine::AppLoader), - "foo/ClassName", - "methodName", - "()V")); + compile( + t, + local::codeAllocator(static_cast(t)), + 0, + resolveMethod( + t, roots(t)->appLoader(), "foo/ClassName", "methodName", "()V")); } uintptr_t stackLimit = t->stackLimit; @@ -8128,39 +8151,42 @@ invoke(Thread* thread, object method, ArgumentList* arguments) if (stackLimit == 0) { t->stackLimit = stackPosition - t->m->stackSizeInBytes; } else if (stackPosition < stackLimit) { - throwNew(t, Machine::StackOverflowErrorType); + throwNew(t, GcStackOverflowError::Type); } - THREAD_RESOURCE(t, uintptr_t, stackLimit, + THREAD_RESOURCE(t, + uintptr_t, + stackLimit, static_cast(t)->stackLimit = stackLimit); - unsigned returnCode = methodReturnCode(t, method); + unsigned returnCode = method->returnCode(); unsigned returnType = fieldType(t, returnCode); uint64_t result; - { MyThread::CallTrace trace(t, method); + { + MyThread::CallTrace trace(t, method); MyCheckpoint checkpoint(t); - assert(t, arguments->position == arguments->size); + assertT(t, arguments->position == arguments->size); - result = vmInvoke - (t, reinterpret_cast(methodAddress(t, method)), - arguments->array, - arguments->position * BytesPerWord, - t->arch->alignFrameSize - (t->arch->argumentFootprint(arguments->position)) - * BytesPerWord, - returnType); + result = vmInvoke( + t, + reinterpret_cast(methodAddress(t, method)), + arguments->array, + arguments->position * BytesPerWord, + t->arch->alignFrameSize(t->arch->argumentFootprint(arguments->position)) + * BytesPerWord, + returnType); } - if (t->exception) { + if (t->exception) { if (UNLIKELY(t->flags & Thread::UseBackupHeapFlag)) { collect(t, Heap::MinorCollection); } - - object exception = t->exception; + + GcThrowable* exception = t->exception; t->exception = 0; vm::throw_(t, exception); } @@ -8196,38 +8222,45 @@ invoke(Thread* thread, object method, ArgumentList* arguments) return r; } -class SignalHandler: public SignalRegistrar::Handler { +class SignalHandler : public SignalRegistrar::Handler { public: - SignalHandler(Machine::Type type, Machine::Root root, unsigned fixedSize): - m(0), type(type), root(root), fixedSize(fixedSize) { } + typedef GcThrowable* (GcRoots::*ExceptionGetter)(); + SignalHandler(Gc::Type type, ExceptionGetter exc, unsigned fixedSize) + : m(0), type(type), exc(exc), fixedSize(fixedSize) + { + } - virtual bool handleSignal(void** ip, void** frame, void** stack, + virtual bool handleSignal(void** ip, + void** frame, + void** stack, void** thread) { MyThread* t = static_cast(m->localThread->get()); if (t and t->state == Thread::ActiveState) { - object node = methodForIp(t, *ip); + GcMethod* node = methodForIp(t, *ip); if (node) { // add one to the IP since findLineNumber will subtract one // when we make the trace: - MyThread::TraceContext context - (t, static_cast(*ip) + 1, - static_cast(*stack) - t->arch->frameReturnAddressSize(), - t->continuation, t->trace); + MyThread::TraceContext context( + t, + static_cast(*ip) + 1, + static_cast(*stack) - t->arch->frameReturnAddressSize(), + t->continuation, + t->trace); - if (ensure(t, fixedSize + traceSize(t))) { + if (ensure(t, pad(fixedSize) + traceSize(t))) { atomicOr(&(t->flags), Thread::TracingFlag); t->exception = makeThrowable(t, type); atomicAnd(&(t->flags), ~Thread::TracingFlag); } else { // not enough memory available for a new exception and stack // trace -- use a preallocated instance instead - t->exception = vm::root(t, root); + t->exception = (vm::roots(t)->*exc)(); } // printTrace(t, t->exception); - object continuation; + GcContinuation* continuation; findUnwindTarget(t, ip, frame, stack, &continuation); transition(t, ip, stack, continuation, t->trace); @@ -8246,39 +8279,36 @@ class SignalHandler: public SignalRegistrar::Handler { } Machine* m; - Machine::Type type; - Machine::Root root; + Gc::Type type; + ExceptionGetter exc; unsigned fixedSize; }; -bool -isThunk(MyThread* t, void* ip); +bool isThunk(MyThread* t, void* ip); -bool -isVirtualThunk(MyThread* t, void* ip); +bool isVirtualThunk(MyThread* t, void* ip); -bool -isThunkUnsafeStack(MyThread* t, void* ip); +bool isThunkUnsafeStack(MyThread* t, void* ip); -void -boot(MyThread* t, BootImage* image, uint8_t* code); +void boot(MyThread* t, BootImage* image, uint8_t* code); class MyProcessor; -MyProcessor* -processor(MyThread* t); +MyProcessor* processor(MyThread* t); -void -compileThunks(MyThread* t, FixedAllocator* allocator); +void compileThunks(MyThread* t, FixedAllocator* allocator); class CompilationHandlerList { -public: - CompilationHandlerList(CompilationHandlerList* next, Processor::CompilationHandler* handler): - next(next), - handler(handler) {} + public: + CompilationHandlerList(CompilationHandlerList* next, + Processor::CompilationHandler* handler) + : next(next), handler(handler) + { + } - void dispose(Allocator* allocator) { - if(this) { + void dispose(Allocator* allocator) + { + if (this) { next->dispose(allocator); handler->dispose(); allocator->free(this, sizeof(*this)); @@ -8289,10 +8319,12 @@ public: Processor::CompilationHandler* handler; }; -template -int checkConstant(MyThread* t, size_t expected, T C::* field, const char* name) { - size_t actual = reinterpret_cast(&(t->*field)) - reinterpret_cast(t); - if(expected != actual) { +template +int checkConstant(MyThread* t, size_t expected, T C::*field, const char* name) +{ + size_t actual = reinterpret_cast(&(t->*field)) + - reinterpret_cast(t); + if (expected != actual) { fprintf(stderr, "constant mismatch (%s): \n\tconstant says: %d\n\tc++ compiler " "says: %d\n", @@ -8304,17 +8336,18 @@ int checkConstant(MyThread* t, size_t expected, T C::* field, const char* name) return 0; } -class MyProcessor: public Processor { +class MyProcessor : public Processor { public: class Thunk { public: - Thunk(): - start(0), frameSavedOffset(0), length(0) - { } + Thunk() : start(0), frameSavedOffset(0), length(0) + { + } - Thunk(uint8_t* start, unsigned frameSavedOffset, unsigned length): - start(start), frameSavedOffset(frameSavedOffset), length(length) - { } + Thunk(uint8_t* start, unsigned frameSavedOffset, unsigned length) + : start(start), frameSavedOffset(frameSavedOffset), length(length) + { + } uint8_t* start; unsigned frameSavedOffset; @@ -8342,12 +8375,12 @@ class MyProcessor: public Processor { heapImage(0), codeImage(0), codeImageSize(0), - segFaultHandler(Machine::NullPointerExceptionType, - Machine::NullPointerException, - FixedSizeOfNullPointerException), - divideByZeroHandler(Machine::ArithmeticExceptionType, - Machine::ArithmeticException, - FixedSizeOfArithmeticException), + segFaultHandler(GcNullPointerException::Type, + &GcRoots::nullPointerException, + GcNullPointerException::FixedSize), + divideByZeroHandler(GcArithmeticException::Type, + &GcRoots::arithmeticException, + GcArithmeticException::FixedSize), codeAllocator(s, Slice(0, 0)), callTableSize(0), useNativeFeatures(useNativeFeatures), @@ -8356,8 +8389,8 @@ class MyProcessor: public Processor { thunkTable[compileMethodIndex] = voidPointer(local::compileMethod); thunkTable[compileVirtualMethodIndex] = voidPointer(compileVirtualMethod); thunkTable[invokeNativeIndex] = voidPointer(invokeNative); - thunkTable[throwArrayIndexOutOfBoundsIndex] = voidPointer - (throwArrayIndexOutOfBounds); + thunkTable[throwArrayIndexOutOfBoundsIndex] + = voidPointer(throwArrayIndexOutOfBounds); thunkTable[throwStackOverflowIndex] = voidPointer(throwStackOverflow); using namespace avian::codegen::runtime; @@ -8371,18 +8404,16 @@ class MyProcessor: public Processor { // implicitly sign- or zero-extended). We'll use this property // later to determine the maximum size of a thunk in the thunk // table. - thunkTable[dummyIndex] = reinterpret_cast - (static_cast(UINT64_C(0x5555555555555555))); + thunkTable[dummyIndex] = reinterpret_cast( + static_cast(UINT64_C(0x5555555555555555))); signals.setCrashDumpDirectory(crashDumpDirectory); } - virtual Thread* - makeThread(Machine* m, object javaThread, Thread* parent) + virtual Thread* makeThread(Machine* m, GcThread* javaThread, Thread* parent) { - MyThread* t = new (m->heap->allocate(sizeof(MyThread))) - MyThread(m, javaThread, static_cast(parent), - useNativeFeatures); + MyThread* t = new (m->heap->allocate(sizeof(MyThread))) MyThread( + m, javaThread, static_cast(parent), useNativeFeatures); t->heapImage = heapImage; t->codeImage = codeImage; @@ -8444,11 +8475,15 @@ class MyProcessor: public Processor { &MyThread::stackLimit, "TARGET_THREAD_STACKLIMIT"); - if(mismatches > 0) { + if (mismatches > 0) { fprintf(stderr, "%d constant mismatches\n", mismatches); abort(t); } + expect(t, TargetClassArrayElementSize == ClassArrayElementSize); + expect(t, TargetClassFixedSize == ClassFixedSize); + expect(t, TargetClassVtable == ClassVtable); + #endif t->init(); @@ -8456,69 +8491,93 @@ class MyProcessor: public Processor { return t; } - virtual object - makeMethod(vm::Thread* t, - uint8_t vmFlags, - uint8_t returnCode, - uint8_t parameterCount, - uint8_t parameterFootprint, - uint16_t flags, - uint16_t offset, - object name, - object spec, - object addendum, - object class_, - object code) + virtual GcMethod* makeMethod(vm::Thread* t, + uint8_t vmFlags, + uint8_t returnCode, + uint8_t parameterCount, + uint8_t parameterFootprint, + uint16_t flags, + uint16_t offset, + GcByteArray* name, + GcByteArray* spec, + GcMethodAddendum* addendum, + GcClass* class_, + GcCode* code) { if (code) { - codeCompiled(t, code) = local::defaultThunk(static_cast(t)); + code->compiled() = local::defaultThunk(static_cast(t)); } - return vm::makeMethod - (t, vmFlags, returnCode, parameterCount, parameterFootprint, flags, - offset, 0, 0, name, spec, addendum, class_, code); + return vm::makeMethod(t, + vmFlags, + returnCode, + parameterCount, + parameterFootprint, + flags, + offset, + 0, + 0, + name, + spec, + addendum, + class_, + code); } - virtual object - makeClass(vm::Thread* t, - uint16_t flags, - uint16_t vmFlags, - uint16_t fixedSize, - uint8_t arrayElementSize, - uint8_t arrayDimensions, - object objectMask, - object name, - object sourceFile, - object super, - object interfaceTable, - object virtualTable, - object fieldTable, - object methodTable, - object staticTable, - object addendum, - object loader, - unsigned vtableLength) + virtual GcClass* makeClass(vm::Thread* t, + uint16_t flags, + uint16_t vmFlags, + uint16_t fixedSize, + uint8_t arrayElementSize, + uint8_t arrayDimensions, + GcClass* arrayElementClass, + GcIntArray* objectMask, + GcByteArray* name, + GcByteArray* sourceFile, + GcClass* super, + object interfaceTable, + object virtualTable, + object fieldTable, + object methodTable, + GcClassAddendum* addendum, + GcSingleton* staticTable, + GcClassLoader* loader, + unsigned vtableLength) { - return vm::makeClass - (t, flags, vmFlags, fixedSize, arrayElementSize, arrayDimensions, - 0, objectMask, name, sourceFile, super, interfaceTable, virtualTable, - fieldTable, methodTable, staticTable, addendum, loader, 0, - vtableLength); + return vm::makeClass(t, + flags, + vmFlags, + fixedSize, + arrayElementSize, + arrayDimensions, + arrayElementClass, + 0, + objectMask, + name, + sourceFile, + super, + interfaceTable, + virtualTable, + fieldTable, + methodTable, + addendum, + staticTable, + loader, + 0, + vtableLength); } - virtual void - initVtable(Thread* t, object c) + virtual void initVtable(Thread* t, GcClass* c) { PROTECT(t, c); - for (int i = classLength(t, c) - 1; i >= 0; --i) { - void* thunk = reinterpret_cast - (virtualThunk(static_cast(t), i)); - classVtable(t, c, i) = thunk; + for (int i = c->length() - 1; i >= 0; --i) { + void* thunk + = reinterpret_cast(virtualThunk(static_cast(t), i)); + c->vtable()[i] = thunk; } } - virtual void - visitObjects(Thread* vmt, Heap::Visitor* v) + virtual void visitObjects(Thread* vmt, Heap::Visitor* v) { MyThread* t = static_cast(vmt); @@ -8542,8 +8601,7 @@ class MyProcessor: public Processor { visitStack(t, v); } - virtual void - walkStack(Thread* vmt, StackVisitor* v) + virtual void walkStack(Thread* vmt, StackVisitor* v) { MyThread* t = static_cast(vmt); @@ -8551,14 +8609,12 @@ class MyProcessor: public Processor { walker.walk(v); } - virtual int - lineNumber(Thread* vmt, object method, int ip) + virtual int lineNumber(Thread* vmt, GcMethod* method, int ip) { return findLineNumber(static_cast(vmt), method, ip); } - virtual object* - makeLocalReference(Thread* vmt, object o) + virtual object* makeLocalReference(Thread* vmt, object o) { if (o) { MyThread* t = static_cast(vmt); @@ -8572,7 +8628,7 @@ class MyProcessor: public Processor { } Reference* r = new (t->m->heap->allocate(sizeof(Reference))) - Reference(o, &(t->reference), false); + Reference(o, &(t->reference), false); acquire(t, r); @@ -8582,28 +8638,24 @@ class MyProcessor: public Processor { } } - virtual void - disposeLocalReference(Thread* t, object* r) + virtual void disposeLocalReference(Thread* t, object* r) { if (r) { release(t, reinterpret_cast(r)); } } - virtual bool - pushLocalFrame(Thread* vmt, unsigned) + virtual bool pushLocalFrame(Thread* vmt, unsigned) { MyThread* t = static_cast(vmt); - t->referenceFrame = new - (t->m->heap->allocate(sizeof(List))) - List(t->reference, t->referenceFrame); - + t->referenceFrame = new (t->m->heap->allocate(sizeof(List))) + List(t->reference, t->referenceFrame); + return true; } - virtual void - popLocalFrame(Thread* vmt) + virtual void popLocalFrame(Thread* vmt) { MyThread* t = static_cast(vmt); @@ -8616,128 +8668,165 @@ class MyProcessor: public Processor { t->m->heap->free(f, sizeof(List)); } - virtual object - invokeArray(Thread* t, object method, object this_, object arguments) + virtual object invokeArray(Thread* t, + GcMethod* method, + object this_, + object arguments) { - assert(t, t->exception == 0); + assertT(t, t->exception == 0); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); method = findMethod(t, method, this_); - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); + const char* spec = reinterpret_cast(method->spec()->body().begin()); - unsigned size = methodParameterFootprint(t, method); + unsigned size = method->parameterFootprint(); THREAD_RUNTIME_ARRAY(t, uintptr_t, array, size); THREAD_RUNTIME_ARRAY(t, bool, objectMask, size); - ArgumentList list - (t, RUNTIME_ARRAY_BODY(array), size, RUNTIME_ARRAY_BODY(objectMask), - this_, spec, arguments); - - PROTECT(t, method); - - compile(static_cast(t), - local::codeAllocator(static_cast(t)), 0, method); - - return local::invoke(t, method, &list); - } - - virtual object - invokeArray(Thread* t, object method, object this_, const jvalue* arguments) - { - assert(t, t->exception == 0); - - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); - - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); - - method = findMethod(t, method, this_); - - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); - - unsigned size = methodParameterFootprint(t, method); - THREAD_RUNTIME_ARRAY(t, uintptr_t, array, size); - THREAD_RUNTIME_ARRAY(t, bool, objectMask, size); - ArgumentList list - (t, RUNTIME_ARRAY_BODY(array), size, RUNTIME_ARRAY_BODY(objectMask), - this_, spec, arguments); + ArgumentList list(t, + RUNTIME_ARRAY_BODY(array), + size, + RUNTIME_ARRAY_BODY(objectMask), + this_, + spec, + arguments); PROTECT(t, method); compile(static_cast(t), - local::codeAllocator(static_cast(t)), 0, method); + local::codeAllocator(static_cast(t)), + 0, + method); return local::invoke(t, method, &list); } - virtual object - invokeList(Thread* t, object method, object this_, bool indirectObjects, - va_list arguments) + virtual object invokeArray(Thread* t, + GcMethod* method, + object this_, + const jvalue* arguments) { - assert(t, t->exception == 0); + assertT(t, t->exception == 0); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); + + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); - method = findMethod(t, method, this_); - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); + const char* spec = reinterpret_cast(method->spec()->body().begin()); - unsigned size = methodParameterFootprint(t, method); + unsigned size = method->parameterFootprint(); THREAD_RUNTIME_ARRAY(t, uintptr_t, array, size); THREAD_RUNTIME_ARRAY(t, bool, objectMask, size); - ArgumentList list - (t, RUNTIME_ARRAY_BODY(array), size, RUNTIME_ARRAY_BODY(objectMask), - this_, spec, indirectObjects, arguments); + ArgumentList list(t, + RUNTIME_ARRAY_BODY(array), + size, + RUNTIME_ARRAY_BODY(objectMask), + this_, + spec, + arguments); PROTECT(t, method); compile(static_cast(t), - local::codeAllocator(static_cast(t)), 0, method); + local::codeAllocator(static_cast(t)), + 0, + method); return local::invoke(t, method, &list); } - virtual object - invokeList(Thread* t, object loader, const char* className, - const char* methodName, const char* methodSpec, - object this_, va_list arguments) + virtual object invokeList(Thread* t, + GcMethod* method, + object this_, + bool indirectObjects, + va_list arguments) { - assert(t, t->exception == 0); + assertT(t, t->exception == 0); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); + + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); + + method = findMethod(t, method, this_); + + const char* spec = reinterpret_cast(method->spec()->body().begin()); + + unsigned size = method->parameterFootprint(); + THREAD_RUNTIME_ARRAY(t, uintptr_t, array, size); + THREAD_RUNTIME_ARRAY(t, bool, objectMask, size); + ArgumentList list(t, + RUNTIME_ARRAY_BODY(array), + size, + RUNTIME_ARRAY_BODY(objectMask), + this_, + spec, + indirectObjects, + arguments); + + PROTECT(t, method); + + compile(static_cast(t), + local::codeAllocator(static_cast(t)), + 0, + method); + + return local::invoke(t, method, &list); + } + + virtual object invokeList(Thread* t, + GcClassLoader* loader, + const char* className, + const char* methodName, + const char* methodSpec, + object this_, + va_list arguments) + { + assertT(t, t->exception == 0); + + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); unsigned size = parameterFootprint(t, methodSpec, this_ == 0); THREAD_RUNTIME_ARRAY(t, uintptr_t, array, size); THREAD_RUNTIME_ARRAY(t, bool, objectMask, size); - ArgumentList list - (t, RUNTIME_ARRAY_BODY(array), size, RUNTIME_ARRAY_BODY(objectMask), - this_, methodSpec, false, arguments); + ArgumentList list(t, + RUNTIME_ARRAY_BODY(array), + size, + RUNTIME_ARRAY_BODY(objectMask), + this_, + methodSpec, + false, + arguments); - object method = resolveMethod - (t, loader, className, methodName, methodSpec); + GcMethod* method + = resolveMethod(t, loader, className, methodName, methodSpec); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); PROTECT(t, method); - - compile(static_cast(t), - local::codeAllocator(static_cast(t)), 0, method); + + compile(static_cast(t), + local::codeAllocator(static_cast(t)), + 0, + method); return local::invoke(t, method, &list); } - virtual void dispose(Thread* vmt) { + virtual void dispose(Thread* vmt) + { MyThread* t = static_cast(vmt); while (t->reference) { @@ -8747,10 +8836,10 @@ class MyProcessor: public Processor { t->arch->release(); t->m->heap->free(t, sizeof(*t)); - } - virtual void dispose() { + virtual void dispose() + { if (codeAllocator.memory.begin()) { #if !defined(AVIAN_AOT_ONLY) s->freeExecutable(codeAllocator.memory.begin(), @@ -8769,18 +8858,21 @@ class MyProcessor: public Processor { allocator->free(this, sizeof(*this)); } - virtual object getStackTrace(Thread* vmt, Thread* vmTarget) { + virtual object getStackTrace(Thread* vmt, Thread* vmTarget) + { MyThread* t = static_cast(vmt); MyThread* target = static_cast(vmTarget); MyProcessor* p = this; - class Visitor: public System::ThreadVisitor { + class Visitor : public System::ThreadVisitor { public: - Visitor(MyThread* t, MyProcessor* p, MyThread* target): - t(t), p(p), target(target), trace(0) - { } + Visitor(MyThread* t, MyProcessor* p, MyThread* target) + : t(t), p(p), target(target), trace(0) + { + } - virtual void visit(void* ip, void* stack, void* link) { + virtual void visit(void* ip, void* stack, void* link) + { MyThread::TraceContext c(target, link); if (methodForIp(t, ip)) { @@ -8800,10 +8892,8 @@ class MyProcessor: public Processor { // MyThread::continuation or MyThread::trace c.ip = 0; c.stack = 0; - } else if (target->stack - and (not isThunkUnsafeStack(t, ip)) - and (not isVirtualThunk(t, ip))) - { + } else if (target->stack and (not isThunkUnsafeStack(t, ip)) + and (not isVirtualThunk(t, ip))) { // we caught the thread in a thunk or native code, and the // saved stack pointer indicates the most recent Java frame // on the stack @@ -8860,15 +8950,20 @@ class MyProcessor: public Processor { codeAllocator.memory = code; } - virtual void addCompilationHandler(CompilationHandler* handler) { + virtual void addCompilationHandler(CompilationHandler* handler) + { compilationHandlers = new (allocator->allocate(sizeof(CompilationHandlerList))) CompilationHandlerList(compilationHandlers, handler); } - virtual void compileMethod(Thread* vmt, Zone* zone, object* constants, - object* calls, avian::codegen::DelayedPromise** addresses, - object method, OffsetResolver* resolver) + virtual void compileMethod(Thread* vmt, + Zone* zone, + GcTriple** constants, + GcTriple** calls, + avian::codegen::DelayedPromise** addresses, + GcMethod* method, + OffsetResolver* resolver) { MyThread* t = static_cast(vmt); BootContext bootContext(t, *constants, *calls, *addresses, zone, resolver); @@ -8880,41 +8975,44 @@ class MyProcessor: public Processor { *addresses = bootContext.addresses; } - virtual void visitRoots(Thread* t, HeapWalker* w) { - bootImage->methodTree = w->visitRoot(root(t, MethodTree)); - bootImage->methodTreeSentinal = w->visitRoot(root(t, MethodTreeSentinal)); - bootImage->virtualThunks = w->visitRoot(root(t, VirtualThunks)); + virtual void visitRoots(Thread* t, HeapWalker* w) + { + bootImage->methodTree = w->visitRoot(compileRoots(t)->methodTree()); + bootImage->methodTreeSentinal + = w->visitRoot(compileRoots(t)->methodTreeSentinal()); + bootImage->virtualThunks = w->visitRoot(compileRoots(t)->virtualThunks()); } - virtual void normalizeVirtualThunks(Thread* t) { - for (unsigned i = 0; i < wordArrayLength(t, root(t, VirtualThunks)); - i += 2) - { - if (wordArrayBody(t, root(t, VirtualThunks), i)) { - wordArrayBody(t, root(t, VirtualThunks), i) + virtual void normalizeVirtualThunks(Thread* t) + { + GcWordArray* a = compileRoots(t)->virtualThunks(); + for (unsigned i = 0; i < a->length(); i += 2) { + if (a->body()[i]) { + a->body()[i] -= reinterpret_cast(codeAllocator.memory.begin()); } } } - virtual unsigned* makeCallTable(Thread* t, HeapWalker* w) { + virtual unsigned* makeCallTable(Thread* t, HeapWalker* w) + { bootImage->codeSize = codeAllocator.offset; bootImage->callCount = callTableSize; - unsigned* table = static_cast - (t->m->heap->allocate(callTableSize * sizeof(unsigned) * 2)); + unsigned* table = static_cast( + t->m->heap->allocate(callTableSize * sizeof(unsigned) * 2)); unsigned index = 0; - for (unsigned i = 0; i < arrayLength(t, root(t, CallTable)); ++i) { - for (object p = arrayBody(t, root(t, CallTable), i); - p; p = callNodeNext(t, p)) - { + GcArray* callTable = compileRoots(t)->callTable(); + for (unsigned i = 0; i < callTable->length(); ++i) { + for (GcCallNode* p = cast(t, callTable->body()[i]); p; + p = p->next()) { + table[index++] + = targetVW(p->address() - reinterpret_cast( + codeAllocator.memory.begin())); table[index++] = targetVW( - callNodeAddress(t, p) - - reinterpret_cast(codeAllocator.memory.begin())); - table[index++] = targetVW( - w->map()->find(callNodeTarget(t, p)) - | (static_cast(callNodeFlags(t, p)) << TargetBootShift)); + w->map()->find(p->target()) + | (static_cast(p->flags()) << TargetBootShift)); } } @@ -8937,16 +9035,19 @@ class MyProcessor: public Processor { if (image and code) { local::boot(static_cast(t), image, code); } else { - roots = makeArray(t, RootCount); + roots = makeCompileRoots(t, 0, 0, 0, 0, 0, 0, 0, 0, 0); - setRoot(t, CallTable, makeArray(t, 128)); + { + GcArray* ct = makeArray(t, 128); + // sequence point, for gc (don't recombine statements) + compileRoots(t)->setCallTable(t, ct); + } - setRoot(t, MethodTreeSentinal, makeTreeNode(t, 0, 0, 0)); - setRoot(t, MethodTree, root(t, MethodTreeSentinal)); - set(t, root(t, MethodTree), TreeNodeLeft, - root(t, MethodTreeSentinal)); - set(t, root(t, MethodTree), TreeNodeRight, - root(t, MethodTreeSentinal)); + GcTreeNode* tree = makeTreeNode(t, 0, 0, 0); + compileRoots(t)->setMethodTreeSentinal(t, tree); + compileRoots(t)->setMethodTree(t, tree); + tree->setLeft(t, tree); + tree->setRight(t, tree); } #ifdef AVIAN_AOT_ONLY @@ -8954,19 +9055,24 @@ class MyProcessor: public Processor { #else local::compileThunks(static_cast(t), &codeAllocator); - if (not (image and code)) { + if (not(image and code)) { bootThunks = thunks; } #endif segFaultHandler.m = t->m; - expect(t, signals.registerHandler(SignalRegistrar::SegFault, &segFaultHandler)); + expect( + t, + signals.registerHandler(SignalRegistrar::SegFault, &segFaultHandler)); divideByZeroHandler.m = t->m; - expect(t, signals.registerHandler(SignalRegistrar::DivideByZero, ÷ByZeroHandler)); + expect(t, + signals.registerHandler(SignalRegistrar::DivideByZero, + ÷ByZeroHandler)); } - virtual void callWithCurrentContinuation(Thread* t, object receiver) { + virtual void callWithCurrentContinuation(Thread* t, object receiver) + { if (Continuations) { local::callWithCurrentContinuation(static_cast(t), receiver); } else { @@ -8974,8 +9080,7 @@ class MyProcessor: public Processor { } } - virtual void dynamicWind(Thread* t, object before, object thunk, - object after) + virtual void dynamicWind(Thread* t, object before, object thunk, object after) { if (Continuations) { local::dynamicWind(static_cast(t), before, thunk, after); @@ -8984,7 +9089,8 @@ class MyProcessor: public Processor { } } - virtual void feedResultToContinuation(Thread* t, object continuation, + virtual void feedResultToContinuation(Thread* t, + GcContinuation* continuation, object result) { if (Continuations) { @@ -8994,8 +9100,9 @@ class MyProcessor: public Processor { } } - virtual void feedExceptionToContinuation(Thread* t, object continuation, - object exception) + virtual void feedExceptionToContinuation(Thread* t, + GcContinuation* continuation, + GcThrowable* exception) { if (Continuations) { callContinuation(static_cast(t), continuation, 0, exception); @@ -9004,20 +9111,23 @@ class MyProcessor: public Processor { } } - virtual void walkContinuationBody(Thread* t, Heap::Walker* w, object o, + virtual void walkContinuationBody(Thread* t, + Heap::Walker* w, + object o, unsigned start) { if (Continuations) { - local::walkContinuationBody(static_cast(t), w, o, start); + local::walkContinuationBody( + static_cast(t), w, cast(t, o), start); } else { abort(t); } } - + System* s; SignalRegistrar signals; Allocator* allocator; - object roots; + GcCompileRoots* roots; BootImage* bootImage; uintptr_t* heapImage; uint8_t* codeImage; @@ -9033,23 +9143,26 @@ class MyProcessor: public Processor { CompilationHandlerList* compilationHandlers; }; -const char* -stringOrNull(const char* str) { - if(str) { +const char* stringOrNull(const char* str) +{ + if (str) { return str; } else { return "(null)"; } } -size_t -stringOrNullSize(const char* str) { +size_t stringOrNullSize(const char* str) +{ return strlen(stringOrNull(str)); } -void -logCompile(MyThread* t, const void* code, unsigned size, const char* class_, - const char* name, const char* spec) +void logCompile(MyThread* t, + const void* code, + unsigned size, + const char* class_, + const char* name, + const char* spec) { static bool open = false; if (not open) { @@ -9063,9 +9176,13 @@ logCompile(MyThread* t, const void* code, unsigned size, const char* class_, } if (compileLog) { - fprintf(compileLog, "%p,%p %s.%s%s\n", - code, static_cast(code) + size, - class_, name, spec); + fprintf(compileLog, + "%p,%p %s.%s%s\n", + code, + static_cast(code) + size, + class_, + name, + spec); } size_t nameLength = stringOrNullSize(class_) + stringOrNullSize(name) @@ -9080,16 +9197,15 @@ logCompile(MyThread* t, const void* code, unsigned size, const char* class_, stringOrNull(spec)); MyProcessor* p = static_cast(t->m->processor); - for(CompilationHandlerList* h = p->compilationHandlers; h; h = h->next) { + for (CompilationHandlerList* h = p->compilationHandlers; h; h = h->next) { h->handler->compiled(code, 0, 0, RUNTIME_ARRAY_BODY(completeName)); } } -void* -compileMethod2(MyThread* t, void* ip) +void* compileMethod2(MyThread* t, void* ip) { - object node = findCallNode(t, ip); - object target = callNodeTarget(t, node); + GcCallNode* node = findCallNode(t, ip); + GcMethod* target = node->target(); PROTECT(t, node); PROTECT(t, target); @@ -9105,25 +9221,27 @@ compileMethod2(MyThread* t, void* ip) MyProcessor* p = processor(t); bool updateCaller = updateIp < p->codeImage - or updateIp >= p->codeImage + p->codeImageSize; + or updateIp >= p->codeImage + p->codeImageSize; uintptr_t address; - if (methodFlags(t, target) & ACC_NATIVE) { + if (target->flags() & ACC_NATIVE) { address = useLongJump(t, reinterpret_cast(ip)) - or (not updateCaller) ? bootNativeThunk(t) : nativeThunk(t); + or (not updateCaller) + ? bootNativeThunk(t) + : nativeThunk(t); } else { address = methodAddress(t, target); } if (updateCaller) { avian::codegen::lir::UnaryOperation op; - if (callNodeFlags(t, node) & TraceElement::LongCall) { - if (callNodeFlags(t, node) & TraceElement::TailCall) { + if (node->flags() & TraceElement::LongCall) { + if (node->flags() & TraceElement::TailCall) { op = avian::codegen::lir::AlignedLongJump; } else { op = avian::codegen::lir::AlignedLongCall; } - } else if (callNodeFlags(t, node) & TraceElement::TailCall) { + } else if (node->flags() & TraceElement::TailCall) { op = avian::codegen::lir::AlignedJump; } else { op = avian::codegen::lir::AlignedCall; @@ -9135,38 +9253,34 @@ compileMethod2(MyThread* t, void* ip) return reinterpret_cast(address); } -bool -isThunk(MyProcessor::ThunkCollection* thunks, void* ip) +bool isThunk(MyProcessor::ThunkCollection* thunks, void* ip) { uint8_t* thunkStart = thunks->default_.start; - uint8_t* thunkEnd = thunks->table.start - + (thunks->table.length * ThunkCount); + uint8_t* thunkEnd = thunks->table.start + (thunks->table.length * ThunkCount); return (reinterpret_cast(ip) >= reinterpret_cast(thunkStart) and reinterpret_cast(ip) - < reinterpret_cast(thunkEnd)); + < reinterpret_cast(thunkEnd)); } -bool -isThunk(MyThread* t, void* ip) +bool isThunk(MyThread* t, void* ip) { MyProcessor* p = processor(t); return isThunk(&(p->thunks), ip) or isThunk(&(p->bootThunks), ip); } -bool -isThunkUnsafeStack(MyProcessor::Thunk* thunk, void* ip) +bool isThunkUnsafeStack(MyProcessor::Thunk* thunk, void* ip) { return reinterpret_cast(ip) - >= reinterpret_cast(thunk->start) - and reinterpret_cast(ip) - < reinterpret_cast(thunk->start + thunk->frameSavedOffset); + >= reinterpret_cast(thunk->start) + and reinterpret_cast(ip) + < reinterpret_cast(thunk->start + + thunk->frameSavedOffset); } -bool -isThunkUnsafeStack(MyProcessor::ThunkCollection* thunks, void* ip) +bool isThunkUnsafeStack(MyProcessor::ThunkCollection* thunks, void* ip) { const unsigned NamedThunkCount = 5; @@ -9177,12 +9291,12 @@ isThunkUnsafeStack(MyProcessor::ThunkCollection* thunks, void* ip) table[2] = thunks->native; table[3] = thunks->aioob; table[4] = thunks->stackOverflow; - + for (unsigned i = 0; i < ThunkCount; ++i) { - new (table + NamedThunkCount + i) MyProcessor::Thunk - (thunks->table.start + (i * thunks->table.length), - thunks->table.frameSavedOffset, - thunks->table.length); + new (table + NamedThunkCount + i) + MyProcessor::Thunk(thunks->table.start + (i * thunks->table.length), + thunks->table.frameSavedOffset, + thunks->table.length); } for (unsigned i = 0; i < NamedThunkCount + ThunkCount; ++i) { @@ -9194,17 +9308,15 @@ isThunkUnsafeStack(MyProcessor::ThunkCollection* thunks, void* ip) return false; } -bool -isVirtualThunk(MyThread* t, void* ip) +bool isVirtualThunk(MyThread* t, void* ip) { - for (unsigned i = 0; i < wordArrayLength(t, root(t, VirtualThunks)); i += 2) - { - uintptr_t start = wordArrayBody(t, root(t, VirtualThunks), i); - uintptr_t end = start + wordArrayBody(t, root(t, VirtualThunks), i + 1); + GcWordArray* a = compileRoots(t)->virtualThunks(); + for (unsigned i = 0; i < a->length(); i += 2) { + uintptr_t start = a->body()[i]; + uintptr_t end = start + a->body()[i + 1]; if (reinterpret_cast(ip) >= start - and reinterpret_cast(ip) < end) - { + and reinterpret_cast(ip) < end) { return true; } } @@ -9212,18 +9324,15 @@ isVirtualThunk(MyThread* t, void* ip) return false; } -bool -isThunkUnsafeStack(MyThread* t, void* ip) +bool isThunkUnsafeStack(MyThread* t, void* ip) { MyProcessor* p = processor(t); - return isThunk(t, ip) - and (isThunkUnsafeStack(&(p->thunks), ip) - or isThunkUnsafeStack(&(p->bootThunks), ip)); + return isThunk(t, ip) and (isThunkUnsafeStack(&(p->thunks), ip) + or isThunkUnsafeStack(&(p->bootThunks), ip)); } -object -findCallNode(MyThread* t, void* address) +GcCallNode* findCallNode(MyThread* t, void* address) { if (DebugCallTable) { fprintf(stderr, "find call node %p\n", address); @@ -9234,15 +9343,14 @@ findCallNode(MyThread* t, void* address) // compile(MyThread*, Allocator*, BootContext*, object)): loadMemoryBarrier(); - object table = root(t, CallTable); + GcArray* table = compileRoots(t)->callTable(); intptr_t key = reinterpret_cast(address); - unsigned index = static_cast(key) & (arrayLength(t, table) - 1); + unsigned index = static_cast(key) & (table->length() - 1); - for (object n = arrayBody(t, table, index); - n; n = callNodeNext(t, n)) - { - intptr_t k = callNodeAddress(t, n); + for (GcCallNode* n = cast(t, table->body()[index]); n; + n = n->next()) { + intptr_t k = n->address(); if (k == key) { return n; @@ -9252,114 +9360,124 @@ findCallNode(MyThread* t, void* address) return 0; } -object -resizeTable(MyThread* t, object oldTable, unsigned newLength) +GcArray* resizeTable(MyThread* t, GcArray* oldTable, unsigned newLength) { PROTECT(t, oldTable); - object oldNode = 0; + GcCallNode* oldNode = 0; PROTECT(t, oldNode); - object newTable = makeArray(t, newLength); + GcArray* newTable = makeArray(t, newLength); PROTECT(t, newTable); - for (unsigned i = 0; i < arrayLength(t, oldTable); ++i) { - for (oldNode = arrayBody(t, oldTable, i); - oldNode; - oldNode = callNodeNext(t, oldNode)) - { - intptr_t k = callNodeAddress(t, oldNode); + for (unsigned i = 0; i < oldTable->length(); ++i) { + for (oldNode = cast(t, oldTable->body()[i]); oldNode; + oldNode = oldNode->next()) { + intptr_t k = oldNode->address(); unsigned index = k & (newLength - 1); - object newNode = makeCallNode - (t, callNodeAddress(t, oldNode), - callNodeTarget(t, oldNode), - callNodeFlags(t, oldNode), - arrayBody(t, newTable, index)); + GcCallNode* newNode + = makeCallNode(t, + oldNode->address(), + oldNode->target(), + oldNode->flags(), + cast(t, newTable->body()[index])); - set(t, newTable, ArrayBody + (index * BytesPerWord), newNode); + newTable->setBodyElement(t, index, newNode); } } return newTable; } -object -insertCallNode(MyThread* t, object table, unsigned* size, object node) +GcArray* insertCallNode(MyThread* t, + GcArray* table, + unsigned* size, + GcCallNode* node) { if (DebugCallTable) { - fprintf(stderr, "insert call node %p\n", - reinterpret_cast(callNodeAddress(t, node))); + fprintf(stderr, + "insert call node %p\n", + reinterpret_cast(node->address())); } PROTECT(t, table); PROTECT(t, node); - ++ (*size); + ++(*size); - if (*size >= arrayLength(t, table) * 2) { - table = resizeTable(t, table, arrayLength(t, table) * 2); + if (*size >= table->length() * 2) { + table = resizeTable(t, table, table->length() * 2); } - intptr_t key = callNodeAddress(t, node); - unsigned index = static_cast(key) & (arrayLength(t, table) - 1); + intptr_t key = node->address(); + unsigned index = static_cast(key) & (table->length() - 1); - set(t, node, CallNodeNext, arrayBody(t, table, index)); - set(t, table, ArrayBody + (index * BytesPerWord), node); + node->setNext(t, cast(t, table->body()[index])); + table->setBodyElement(t, index, node); return table; } -void -insertCallNode(MyThread* t, object node) +void insertCallNode(MyThread* t, GcCallNode* node) { - setRoot(t, CallTable, insertCallNode - (t, root(t, CallTable), &(processor(t)->callTableSize), node)); + GcArray* newArray = insertCallNode( + t, compileRoots(t)->callTable(), &(processor(t)->callTableSize), node); + // sequence point, for gc (don't recombine statements) + compileRoots(t)->setCallTable(t, newArray); } -object -makeClassMap(Thread* t, unsigned* table, unsigned count, - uintptr_t* heap) +GcHashMap* makeClassMap(Thread* t, + unsigned* table, + unsigned count, + uintptr_t* heap) { - object array = makeArray(t, nextPowerOfTwo(count)); - object map = makeHashMap(t, 0, array); + GcArray* array = makeArray(t, nextPowerOfTwo(count)); + GcHashMap* map = makeHashMap(t, 0, array); PROTECT(t, map); - + for (unsigned i = 0; i < count; ++i) { - object c = bootObject(heap, table[i]); - hashMapInsert(t, map, className(t, c), c, byteArrayHash); + GcClass* c = cast(t, bootObject(heap, table[i])); + hashMapInsert(t, map, c->name(), c, byteArrayHash); } return map; } -object -makeStaticTableArray(Thread* t, unsigned* bootTable, unsigned bootCount, - unsigned* appTable, unsigned appCount, uintptr_t* heap) +GcArray* makeStaticTableArray(Thread* t, + unsigned* bootTable, + unsigned bootCount, + unsigned* appTable, + unsigned appCount, + uintptr_t* heap) { - object array = makeArray(t, bootCount + appCount); - + GcArray* array = makeArray(t, bootCount + appCount); + for (unsigned i = 0; i < bootCount; ++i) { - set(t, array, ArrayBody + (i * BytesPerWord), - classStaticTable(t, bootObject(heap, bootTable[i]))); + array->setBodyElement( + t, i, cast(t, bootObject(heap, bootTable[i]))->staticTable()); } for (unsigned i = 0; i < appCount; ++i) { - set(t, array, ArrayBody + ((bootCount + i) * BytesPerWord), - classStaticTable(t, bootObject(heap, appTable[i]))); + array->setBodyElement( + t, + (bootCount + i), + cast(t, bootObject(heap, appTable[i]))->staticTable()); } return array; } -object -makeStringMap(Thread* t, unsigned* table, unsigned count, uintptr_t* heap) +GcHashMap* makeStringMap(Thread* t, + unsigned* table, + unsigned count, + uintptr_t* heap) { - object array = makeArray(t, nextPowerOfTwo(count)); - object map = makeWeakHashMap(t, 0, array); + GcArray* array = makeArray(t, nextPowerOfTwo(count)); + GcHashMap* map = makeWeakHashMap(t, 0, array)->as(t); PROTECT(t, map); - + for (unsigned i = 0; i < count; ++i) { object s = bootObject(heap, table[i]); hashMapInsert(t, map, s, 0, stringHash); @@ -9368,11 +9486,13 @@ makeStringMap(Thread* t, unsigned* table, unsigned count, uintptr_t* heap) return map; } -object -makeCallTable(MyThread* t, uintptr_t* heap, unsigned* calls, unsigned count, - uintptr_t base) +GcArray* makeCallTable(MyThread* t, + uintptr_t* heap, + unsigned* calls, + unsigned count, + uintptr_t base) { - object table = makeArray(t, nextPowerOfTwo(count)); + GcArray* table = makeArray(t, nextPowerOfTwo(count)); PROTECT(t, table); unsigned size = 0; @@ -9380,9 +9500,12 @@ makeCallTable(MyThread* t, uintptr_t* heap, unsigned* calls, unsigned count, unsigned address = calls[i * 2]; unsigned target = calls[(i * 2) + 1]; - object node = makeCallNode - (t, base + address, bootObject(heap, target & BootMask), - target >> BootShift, 0); + GcCallNode* node + = makeCallNode(t, + base + address, + cast(t, bootObject(heap, target & BootMask)), + target >> BootShift, + 0); table = insertCallNode(t, table, &size, node); } @@ -9390,8 +9513,10 @@ makeCallTable(MyThread* t, uintptr_t* heap, unsigned* calls, unsigned count, return table; } -void -fixupHeap(MyThread* t UNUSED, uintptr_t* map, unsigned size, uintptr_t* heap) +void fixupHeap(MyThread* t UNUSED, + uintptr_t* map, + unsigned size, + uintptr_t* heap) { for (unsigned word = 0; word < size; ++word) { uintptr_t w = map[word]; @@ -9401,15 +9526,20 @@ fixupHeap(MyThread* t UNUSED, uintptr_t* map, unsigned size, uintptr_t* heap) unsigned index = indexOf(word, bit); uintptr_t* p = heap + index; - assert(t, *p); - + assertT(t, *p); + uintptr_t number = *p & BootMask; uintptr_t mark = *p >> BootShift; if (number) { *p = reinterpret_cast(heap + (number - 1)) | mark; - // fprintf(stderr, "fixup %d: %d 0x%x\n", index, - // static_cast(number), static_cast(*p)); + if (false) { + fprintf(stderr, + "fixup %d: %d 0x%x\n", + index, + static_cast(number), + static_cast(*p)); + } } else { *p = mark; } @@ -9419,37 +9549,39 @@ fixupHeap(MyThread* t UNUSED, uintptr_t* map, unsigned size, uintptr_t* heap) } } -void -resetClassRuntimeState(Thread* t, object c, uintptr_t* heap, unsigned heapSize) +void resetClassRuntimeState(Thread* t, + GcClass* c, + uintptr_t* heap, + unsigned heapSize) { - classRuntimeDataIndex(t, c) = 0; + c->runtimeDataIndex() = 0; - if (classArrayElementSize(t, c) == 0) { - object staticTable = classStaticTable(t, c); + if (c->arrayElementSize() == 0) { + GcSingleton* staticTable = c->staticTable()->as(t); if (staticTable) { for (unsigned i = 0; i < singletonCount(t, staticTable); ++i) { if (singletonIsObject(t, staticTable, i) - and (reinterpret_cast - (singletonObject(t, staticTable, i)) < heap or - reinterpret_cast - (singletonObject(t, staticTable, i)) > heap + heapSize)) - { + and (reinterpret_cast( + singletonObject(t, staticTable, i)) < heap + or reinterpret_cast(singletonObject( + t, staticTable, i)) > heap + heapSize)) { singletonObject(t, staticTable, i) = 0; } } } } - if (classMethodTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) { - object m = arrayBody(t, classMethodTable(t, c), i); + if (GcArray* mtable = cast(t, c->methodTable())) { + PROTECT(t, mtable); + for (unsigned i = 0; i < mtable->length(); ++i) { + GcMethod* m = cast(t, mtable->body()[i]); - methodNativeID(t, m) = 0; - methodRuntimeDataIndex(t, m) = 0; + m->nativeID() = 0; + m->runtimeDataIndex() = 0; - if (methodVmFlags(t, m) & ClassInitFlag) { - classVmFlags(t, c) |= NeedInitFlag; - classVmFlags(t, c) &= ~InitErrorFlag; + if (m->vmFlags() & ClassInitFlag) { + c->vmFlags() |= NeedInitFlag; + c->vmFlags() &= ~InitErrorFlag; } } } @@ -9457,41 +9589,45 @@ resetClassRuntimeState(Thread* t, object c, uintptr_t* heap, unsigned heapSize) t->m->processor->initVtable(t, c); } -void -resetRuntimeState(Thread* t, object map, uintptr_t* heap, unsigned heapSize) +void resetRuntimeState(Thread* t, + GcHashMap* map, + uintptr_t* heap, + unsigned heapSize) { for (HashMapIterator it(t, map); it.hasMore();) { - resetClassRuntimeState(t, tripleSecond(t, it.next()), heap, heapSize); + resetClassRuntimeState( + t, cast(t, it.next()->second()), heap, heapSize); } } -void -fixupMethods(Thread* t, object map, BootImage* image UNUSED, uint8_t* code) +void fixupMethods(Thread* t, + GcHashMap* map, + BootImage* image UNUSED, + uint8_t* code) { for (HashMapIterator it(t, map); it.hasMore();) { - object c = tripleSecond(t, it.next()); + GcClass* c = cast(t, it.next()->second()); - if (classMethodTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) { - object method = arrayBody(t, classMethodTable(t, c), i); - if (methodCode(t, method)) { - assert(t, methodCompiled(t, method) - <= static_cast(image->codeSize)); + if (GcArray* mtable = cast(t, c->methodTable())) { + PROTECT(t, mtable); + for (unsigned i = 0; i < mtable->length(); ++i) { + GcMethod* method = cast(t, mtable->body()[i]); + if (method->code()) { + assertT(t, + methodCompiled(t, method) + <= static_cast(image->codeSize)); - codeCompiled(t, methodCode(t, method)) - = methodCompiled(t, method) + reinterpret_cast(code); + method->code()->compiled() = methodCompiled(t, method) + + reinterpret_cast(code); if (DebugCompile) { - logCompile - (static_cast(t), - reinterpret_cast(methodCompiled(t, method)), - methodCompiledSize(t, method), - reinterpret_cast - (&byteArrayBody(t, className(t, methodClass(t, method)), 0)), - reinterpret_cast - (&byteArrayBody(t, methodName(t, method), 0)), - reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0))); + logCompile(static_cast(t), + reinterpret_cast(methodCompiled(t, method)), + methodCompiledSize(t, method), + reinterpret_cast( + method->class_()->name()->body().begin()), + reinterpret_cast(method->name()->body().begin()), + reinterpret_cast(method->spec()->body().begin())); } } } @@ -9501,167 +9637,193 @@ fixupMethods(Thread* t, object map, BootImage* image UNUSED, uint8_t* code) } } -MyProcessor::Thunk -thunkToThunk(const BootImage::Thunk& thunk, uint8_t* base) +MyProcessor::Thunk thunkToThunk(const BootImage::Thunk& thunk, uint8_t* base) { - return MyProcessor::Thunk - (base + thunk.start, thunk.frameSavedOffset, thunk.length); + return MyProcessor::Thunk( + base + thunk.start, thunk.frameSavedOffset, thunk.length); } -void -findThunks(MyThread* t, BootImage* image, uint8_t* code) +void findThunks(MyThread* t, BootImage* image, uint8_t* code) { MyProcessor* p = processor(t); - + p->bootThunks.default_ = thunkToThunk(image->thunks.default_, code); p->bootThunks.defaultVirtual - = thunkToThunk(image->thunks.defaultVirtual, code); + = thunkToThunk(image->thunks.defaultVirtual, code); p->bootThunks.native = thunkToThunk(image->thunks.native, code); p->bootThunks.aioob = thunkToThunk(image->thunks.aioob, code); - p->bootThunks.stackOverflow - = thunkToThunk(image->thunks.stackOverflow, code); + p->bootThunks.stackOverflow = thunkToThunk(image->thunks.stackOverflow, code); p->bootThunks.table = thunkToThunk(image->thunks.table, code); } -void -fixupVirtualThunks(MyThread* t, uint8_t* code) +void fixupVirtualThunks(MyThread* t, uint8_t* code) { - for (unsigned i = 0; i < wordArrayLength(t, root(t, VirtualThunks)); i += 2) - { - if (wordArrayBody(t, root(t, VirtualThunks), i)) { - wordArrayBody(t, root(t, VirtualThunks), i) - = wordArrayBody(t, root(t, VirtualThunks), i) - + reinterpret_cast(code); + GcWordArray* a = compileRoots(t)->virtualThunks(); + for (unsigned i = 0; i < a->length(); i += 2) { + if (a->body()[i]) { + a->body()[i] += reinterpret_cast(code); } } } -void -boot(MyThread* t, BootImage* image, uint8_t* code) +void boot(MyThread* t, BootImage* image, uint8_t* code) { - assert(t, image->magic == BootImage::Magic); + assertT(t, image->magic == BootImage::Magic); unsigned* bootClassTable = reinterpret_cast(image + 1); unsigned* appClassTable = bootClassTable + image->bootClassCount; unsigned* stringTable = appClassTable + image->appClassCount; unsigned* callTable = stringTable + image->stringCount; - uintptr_t* heapMap = reinterpret_cast - (padWord(reinterpret_cast(callTable + (image->callCount * 2)))); + uintptr_t* heapMap = reinterpret_cast( + padWord(reinterpret_cast(callTable + (image->callCount * 2)))); - unsigned heapMapSizeInWords = ceilingDivide - (heapMapSize(image->heapSize), BytesPerWord); + unsigned heapMapSizeInWords + = ceilingDivide(heapMapSize(image->heapSize), BytesPerWord); uintptr_t* heap = heapMap + heapMapSizeInWords; MyProcessor* p = static_cast(t->m->processor); t->heapImage = p->heapImage = heap; - // fprintf(stderr, "heap from %p to %p\n", - // heap, heap + ceilingDivide(image->heapSize, BytesPerWord)); + if (false) { + fprintf(stderr, + "heap from %p to %p\n", + heap, + heap + ceilingDivide(image->heapSize, BytesPerWord)); + } t->codeImage = p->codeImage = code; p->codeImageSize = image->codeSize; - // fprintf(stderr, "code from %p to %p\n", - // code, code + image->codeSize); - + if (false) { + fprintf(stderr, "code from %p to %p\n", code, code + image->codeSize); + } + if (not image->initialized) { fixupHeap(t, heapMap, heapMapSizeInWords, heap); } - + t->m->heap->setImmortalHeap(heap, image->heapSize / BytesPerWord); - t->m->types = bootObject(heap, image->types); + t->m->types = reinterpret_cast(bootObject(heap, image->types)); - t->m->roots = makeArray(t, Machine::RootCount); + t->m->roots = GcRoots::makeZeroed(t); - setRoot(t, Machine::BootLoader, bootObject(heap, image->bootLoader)); - setRoot(t, Machine::AppLoader, bootObject(heap, image->appLoader)); + roots(t)->setBootLoader( + t, cast(t, bootObject(heap, image->bootLoader))); + roots(t)->setAppLoader( + t, cast(t, bootObject(heap, image->appLoader))); - p->roots = makeArray(t, RootCount); - - setRoot(t, MethodTree, bootObject(heap, image->methodTree)); - setRoot(t, MethodTreeSentinal, bootObject(heap, image->methodTreeSentinal)); + p->roots = GcCompileRoots::makeZeroed(t); - setRoot(t, VirtualThunks, bootObject(heap, image->virtualThunks)); + compileRoots(t)->setMethodTree( + t, cast(t, bootObject(heap, image->methodTree))); + compileRoots(t)->setMethodTreeSentinal( + t, cast(t, bootObject(heap, image->methodTreeSentinal))); - { object map = makeClassMap(t, bootClassTable, image->bootClassCount, heap); - set(t, root(t, Machine::BootLoader), ClassLoaderMap, map); + compileRoots(t)->setVirtualThunks( + t, cast(t, bootObject(heap, image->virtualThunks))); + + { + GcHashMap* map + = makeClassMap(t, bootClassTable, image->bootClassCount, heap); + // sequence point, for gc (don't recombine statements) + roots(t)->bootLoader()->setMap(t, map); } - systemClassLoaderFinder(t, root(t, Machine::BootLoader)) = t->m->bootFinder; + roots(t)->bootLoader()->as(t)->finder() + = t->m->bootFinder; - { object map = makeClassMap(t, appClassTable, image->appClassCount, heap); - set(t, root(t, Machine::AppLoader), ClassLoaderMap, map); + { + GcHashMap* map = makeClassMap(t, appClassTable, image->appClassCount, heap); + // sequence point, for gc (don't recombine statements) + roots(t)->appLoader()->setMap(t, map); } - systemClassLoaderFinder(t, root(t, Machine::AppLoader)) = t->m->appFinder; + roots(t)->appLoader()->as(t)->finder() = t->m->appFinder; - setRoot(t, Machine::StringMap, makeStringMap - (t, stringTable, image->stringCount, heap)); + { + GcHashMap* map = makeStringMap(t, stringTable, image->stringCount, heap); + // sequence point, for gc (don't recombine statements) + roots(t)->setStringMap(t, map); + } p->callTableSize = image->callCount; - setRoot(t, CallTable, makeCallTable - (t, heap, callTable, image->callCount, - reinterpret_cast(code))); + { + GcArray* ct = makeCallTable(t, + heap, + callTable, + image->callCount, + reinterpret_cast(code)); + // sequence point, for gc (don't recombine statements) + compileRoots(t)->setCallTable(t, ct); + } + + { + GcArray* staticTableArray = makeStaticTableArray(t, + bootClassTable, + image->bootClassCount, + appClassTable, + image->appClassCount, + heap); + // sequence point, for gc (don't recombine statements) + compileRoots(t)->setStaticTableArray(t, staticTableArray); + } - setRoot(t, StaticTableArray, makeStaticTableArray - (t, bootClassTable, image->bootClassCount, - appClassTable, image->appClassCount, heap)); - findThunks(t, image, code); if (image->initialized) { - resetRuntimeState - (t, classLoaderMap(t, root(t, Machine::BootLoader)), heap, - image->heapSize); + resetRuntimeState(t, + cast(t, roots(t)->bootLoader()->map()), + heap, + image->heapSize); - resetRuntimeState - (t, classLoaderMap(t, root(t, Machine::AppLoader)), heap, - image->heapSize); + resetRuntimeState(t, + cast(t, roots(t)->appLoader()->map()), + heap, + image->heapSize); - for (unsigned i = 0; i < arrayLength(t, t->m->types); ++i) { - resetClassRuntimeState - (t, type(t, static_cast(i)), heap, image->heapSize); + for (unsigned i = 0; i < t->m->types->length(); ++i) { + resetClassRuntimeState( + t, type(t, static_cast(i)), heap, image->heapSize); } } else { fixupVirtualThunks(t, code); - fixupMethods - (t, classLoaderMap(t, root(t, Machine::BootLoader)), image, code); + fixupMethods( + t, cast(t, roots(t)->bootLoader()->map()), image, code); - fixupMethods - (t, classLoaderMap(t, root(t, Machine::AppLoader)), image, code); + fixupMethods( + t, cast(t, roots(t)->appLoader()->map()), image, code); } image->initialized = true; - setRoot(t, Machine::BootstrapClassMap, makeHashMap(t, 0, 0)); + GcHashMap* map = makeHashMap(t, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(t)->setBootstrapClassMap(t, map); } -intptr_t -getThunk(MyThread* t, Thunk thunk) +intptr_t getThunk(MyThread* t, Thunk thunk) { MyProcessor* p = processor(t); - - return reinterpret_cast - (p->thunks.table.start + (thunk * p->thunks.table.length)); + + return reinterpret_cast(p->thunks.table.start + + (thunk * p->thunks.table.length)); } -BootImage::Thunk -thunkToThunk(const MyProcessor::Thunk& thunk, uint8_t* base) +BootImage::Thunk thunkToThunk(const MyProcessor::Thunk& thunk, uint8_t* base) { - return BootImage::Thunk - (thunk.start - base, thunk.frameSavedOffset, thunk.length); + return BootImage::Thunk( + thunk.start - base, thunk.frameSavedOffset, thunk.length); } using avian::codegen::OperandInfo; namespace lir = avian::codegen::lir; -void -compileCall(MyThread* t, Context* c, ThunkIndex index, bool call = true) +void compileCall(MyThread* t, Context* c, ThunkIndex index, bool call = true) { avian::codegen::Assembler* a = c->assembler; @@ -9675,34 +9837,32 @@ compileCall(MyThread* t, Context* c, ThunkIndex index, bool call = true) a->apply(lir::Move, OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &proc), OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &scratch)); - a->apply - (call ? lir::Call : lir::Jump, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &scratch)); + a->apply(call ? lir::Call : lir::Jump, + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &scratch)); } else { - lir::Constant proc - (new(&c->zone) avian::codegen::ResolvedPromise(reinterpret_cast(t->thunkTable[index]))); + lir::Constant proc(new (&c->zone) avian::codegen::ResolvedPromise( + reinterpret_cast(t->thunkTable[index]))); - a->apply - (call ? lir::LongCall : lir::LongJump, - OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &proc)); + a->apply(call ? lir::LongCall : lir::LongJump, + OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &proc)); } } -void -compileThunks(MyThread* t, FixedAllocator* allocator) +void compileThunks(MyThread* t, FixedAllocator* allocator) { MyProcessor* p = processor(t); - { Context context(t); + { + Context context(t); avian::codegen::Assembler* a = context.assembler; - + a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); p->thunks.default_.frameSavedOffset = a->length(); lir::Register thread(t->arch->thread()); a->pushFrame(1, TargetBytesPerWord, lir::RegisterOperand, &thread); - + compileCall(t, &context, compileMethodIndex); a->popFrame(t->arch->alignFrameSize(1)); @@ -9713,38 +9873,43 @@ compileThunks(MyThread* t, FixedAllocator* allocator) p->thunks.default_.length = a->endBlock(false)->resolve(0, 0); - p->thunks.default_.start = finish - (t, allocator, a, "default", p->thunks.default_.length); + p->thunks.default_.start + = finish(t, allocator, a, "default", p->thunks.default_.length); } - { Context context(t); + { + Context context(t); avian::codegen::Assembler* a = context.assembler; - + lir::Register class_(t->arch->virtualCallTarget()); - lir::Memory virtualCallTargetSrc - (t->arch->stack(), - (t->arch->frameFooterSize() + t->arch->frameReturnAddressSize()) - * TargetBytesPerWord); + lir::Memory virtualCallTargetSrc( + t->arch->stack(), + (t->arch->frameFooterSize() + t->arch->frameReturnAddressSize()) + * TargetBytesPerWord); a->apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &virtualCallTargetSrc), + OperandInfo( + TargetBytesPerWord, lir::MemoryOperand, &virtualCallTargetSrc), OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &class_)); - lir::Memory virtualCallTargetDst - (t->arch->thread(), TARGET_THREAD_VIRTUALCALLTARGET); + lir::Memory virtualCallTargetDst(t->arch->thread(), + TARGET_THREAD_VIRTUALCALLTARGET); - a->apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &class_), - OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &virtualCallTargetDst)); + a->apply( + lir::Move, + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &class_), + OperandInfo( + TargetBytesPerWord, lir::MemoryOperand, &virtualCallTargetDst)); lir::Register index(t->arch->virtualCallIndex()); - lir::Memory virtualCallIndex - (t->arch->thread(), TARGET_THREAD_VIRTUALCALLINDEX); + lir::Memory virtualCallIndex(t->arch->thread(), + TARGET_THREAD_VIRTUALCALLINDEX); + + a->apply( + lir::Move, + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &index), + OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &virtualCallIndex)); - a->apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &index), - OperandInfo(TargetBytesPerWord, lir::MemoryOperand, &virtualCallIndex)); - a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); p->thunks.defaultVirtual.frameSavedOffset = a->length(); @@ -9753,7 +9918,7 @@ compileThunks(MyThread* t, FixedAllocator* allocator) a->pushFrame(1, TargetBytesPerWord, lir::RegisterOperand, &thread); compileCall(t, &context, compileVirtualMethodIndex); - + a->popFrame(t->arch->alignFrameSize(1)); lir::Register result(t->arch->returnLow()); @@ -9762,11 +9927,12 @@ compileThunks(MyThread* t, FixedAllocator* allocator) p->thunks.defaultVirtual.length = a->endBlock(false)->resolve(0, 0); - p->thunks.defaultVirtual.start = finish - (t, allocator, a, "defaultVirtual", p->thunks.defaultVirtual.length); + p->thunks.defaultVirtual.start = finish( + t, allocator, a, "defaultVirtual", p->thunks.defaultVirtual.length); } - { Context context(t); + { + Context context(t); avian::codegen::Assembler* a = context.assembler; a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); @@ -9777,17 +9943,18 @@ compileThunks(MyThread* t, FixedAllocator* allocator) a->pushFrame(1, TargetBytesPerWord, lir::RegisterOperand, &thread); compileCall(t, &context, invokeNativeIndex); - - a->popFrameAndUpdateStackAndReturn - (t->arch->alignFrameSize(1), TARGET_THREAD_NEWSTACK); + + a->popFrameAndUpdateStackAndReturn(t->arch->alignFrameSize(1), + TARGET_THREAD_NEWSTACK); p->thunks.native.length = a->endBlock(false)->resolve(0, 0); - p->thunks.native.start = finish - (t, allocator, a, "native", p->thunks.native.length); + p->thunks.native.start + = finish(t, allocator, a, "native", p->thunks.native.length); } - { Context context(t); + { + Context context(t); avian::codegen::Assembler* a = context.assembler; a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); @@ -9801,13 +9968,14 @@ compileThunks(MyThread* t, FixedAllocator* allocator) p->thunks.aioob.length = a->endBlock(false)->resolve(0, 0); - p->thunks.aioob.start = finish - (t, allocator, a, "aioob", p->thunks.aioob.length); + p->thunks.aioob.start + = finish(t, allocator, a, "aioob", p->thunks.aioob.length); } - { Context context(t); + { + Context context(t); avian::codegen::Assembler* a = context.assembler; - + a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); p->thunks.stackOverflow.frameSavedOffset = a->length(); @@ -9819,11 +9987,13 @@ compileThunks(MyThread* t, FixedAllocator* allocator) p->thunks.stackOverflow.length = a->endBlock(false)->resolve(0, 0); - p->thunks.stackOverflow.start = finish - (t, allocator, a, "stackOverflow", p->thunks.stackOverflow.length); + p->thunks.stackOverflow.start = finish( + t, allocator, a, "stackOverflow", p->thunks.stackOverflow.length); } - { { Context context(t); + { + { + Context context(t); avian::codegen::Assembler* a = context.assembler; a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); @@ -9834,33 +10004,32 @@ compileThunks(MyThread* t, FixedAllocator* allocator) p->thunks.table.length = a->endBlock(false)->resolve(0, 0); - p->thunks.table.start = static_cast - (allocator->allocate - (p->thunks.table.length * ThunkCount, TargetBytesPerWord)); + p->thunks.table.start = static_cast(allocator->allocate( + p->thunks.table.length * ThunkCount, TargetBytesPerWord)); } uint8_t* start = p->thunks.table.start; -#define THUNK(s) { \ - Context context(t); \ - avian::codegen::Assembler* a = context.assembler; \ - \ - a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); \ - \ - p->thunks.table.frameSavedOffset = a->length(); \ - \ - compileCall(t, &context, s##Index, false); \ - \ - expect(t, a->endBlock(false)->resolve(0, 0) \ - <= p->thunks.table.length); \ - \ - a->setDestination(start); \ - a->write(); \ - \ - logCompile(t, start, p->thunks.table.length, 0, #s, 0); \ - \ - start += p->thunks.table.length; \ - } +#define THUNK(s) \ + { \ + Context context(t); \ + avian::codegen::Assembler* a = context.assembler; \ + \ + a->saveFrame(TARGET_THREAD_STACK, TARGET_THREAD_IP); \ + \ + p->thunks.table.frameSavedOffset = a->length(); \ + \ + compileCall(t, &context, s##Index, false); \ + \ + expect(t, a->endBlock(false)->resolve(0, 0) <= p->thunks.table.length); \ + \ + a->setDestination(start); \ + a->write(); \ + \ + logCompile(t, start, p->thunks.table.length, 0, #s, 0); \ + \ + start += p->thunks.table.length; \ + } #include "thunks.cpp" #undef THUNK } @@ -9871,74 +10040,63 @@ compileThunks(MyThread* t, FixedAllocator* allocator) uint8_t* imageBase = p->codeAllocator.memory.begin(); image->thunks.default_ = thunkToThunk(p->thunks.default_, imageBase); - image->thunks.defaultVirtual = thunkToThunk - (p->thunks.defaultVirtual, imageBase); + image->thunks.defaultVirtual + = thunkToThunk(p->thunks.defaultVirtual, imageBase); image->thunks.native = thunkToThunk(p->thunks.native, imageBase); image->thunks.aioob = thunkToThunk(p->thunks.aioob, imageBase); - image->thunks.stackOverflow = thunkToThunk - (p->thunks.stackOverflow, imageBase); + image->thunks.stackOverflow + = thunkToThunk(p->thunks.stackOverflow, imageBase); image->thunks.table = thunkToThunk(p->thunks.table, imageBase); } } -MyProcessor* -processor(MyThread* t) +MyProcessor* processor(MyThread* t) { return static_cast(t->m->processor); } -uintptr_t -defaultThunk(MyThread* t) +uintptr_t defaultThunk(MyThread* t) { return reinterpret_cast(processor(t)->thunks.default_.start); } -uintptr_t -bootDefaultThunk(MyThread* t) +uintptr_t bootDefaultThunk(MyThread* t) { return reinterpret_cast(processor(t)->bootThunks.default_.start); } -uintptr_t -defaultVirtualThunk(MyThread* t) +uintptr_t defaultVirtualThunk(MyThread* t) { - return reinterpret_cast - (processor(t)->thunks.defaultVirtual.start); + return reinterpret_cast(processor(t)->thunks.defaultVirtual.start); } -uintptr_t -nativeThunk(MyThread* t) +uintptr_t nativeThunk(MyThread* t) { return reinterpret_cast(processor(t)->thunks.native.start); } -uintptr_t -bootNativeThunk(MyThread* t) +uintptr_t bootNativeThunk(MyThread* t) { return reinterpret_cast(processor(t)->bootThunks.native.start); } -uintptr_t -aioobThunk(MyThread* t) +uintptr_t aioobThunk(MyThread* t) { return reinterpret_cast(processor(t)->thunks.aioob.start); } -uintptr_t -stackOverflowThunk(MyThread* t) +uintptr_t stackOverflowThunk(MyThread* t) { return reinterpret_cast(processor(t)->thunks.stackOverflow.start); } -bool -unresolved(MyThread* t, uintptr_t methodAddress) +bool unresolved(MyThread* t, uintptr_t methodAddress) { return methodAddress == defaultThunk(t) - or methodAddress == bootDefaultThunk(t); + or methodAddress == bootDefaultThunk(t); } -uintptr_t -compileVirtualThunk(MyThread* t, unsigned index, unsigned* size) +uintptr_t compileVirtualThunk(MyThread* t, unsigned index, unsigned* size) { Context context(t); avian::codegen::Assembler* a = context.assembler; @@ -9946,19 +10104,21 @@ compileVirtualThunk(MyThread* t, unsigned index, unsigned* size) avian::codegen::ResolvedPromise indexPromise(index); lir::Constant indexConstant(&indexPromise); lir::Register indexRegister(t->arch->virtualCallIndex()); - a->apply(lir::Move, - OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &indexConstant), - OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &indexRegister)); - - avian::codegen::ResolvedPromise defaultVirtualThunkPromise(defaultVirtualThunk(t)); + a->apply( + lir::Move, + OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &indexConstant), + OperandInfo(TargetBytesPerWord, lir::RegisterOperand, &indexRegister)); + + avian::codegen::ResolvedPromise defaultVirtualThunkPromise( + defaultVirtualThunk(t)); lir::Constant thunk(&defaultVirtualThunkPromise); a->apply(lir::Jump, OperandInfo(TargetBytesPerWord, lir::ConstantOperand, &thunk)); *size = a->endBlock(false)->resolve(0, 0); - uint8_t* start = static_cast - (codeAllocator(t)->allocate(*size, TargetBytesPerWord)); + uint8_t* start = static_cast( + codeAllocator(t)->allocate(*size, TargetBytesPerWord)); a->setDestination(start); a->write(); @@ -9967,57 +10127,63 @@ compileVirtualThunk(MyThread* t, unsigned index, unsigned* size) const size_t virtualThunkBaseNameLength = strlen(virtualThunkBaseName); const size_t maxIntStringLength = 10; - THREAD_RUNTIME_ARRAY(t, char, virtualThunkName, virtualThunkBaseNameLength + maxIntStringLength); + THREAD_RUNTIME_ARRAY(t, + char, + virtualThunkName, + virtualThunkBaseNameLength + maxIntStringLength); - sprintf(RUNTIME_ARRAY_BODY(virtualThunkName), "%s%d", virtualThunkBaseName, index); + sprintf(RUNTIME_ARRAY_BODY(virtualThunkName), + "%s%d", + virtualThunkBaseName, + index); logCompile(t, start, *size, 0, RUNTIME_ARRAY_BODY(virtualThunkName), 0); return reinterpret_cast(start); } -uintptr_t -virtualThunk(MyThread* t, unsigned index) +uintptr_t virtualThunk(MyThread* t, unsigned index) { ACQUIRE(t, t->m->classLock); - if (root(t, VirtualThunks) == 0 - or wordArrayLength(t, root(t, VirtualThunks)) <= index * 2) - { - object newArray = makeWordArray(t, nextPowerOfTwo((index + 1) * 2)); - if (root(t, VirtualThunks)) { - memcpy(&wordArrayBody(t, newArray, 0), - &wordArrayBody(t, root(t, VirtualThunks), 0), - wordArrayLength(t, root(t, VirtualThunks)) * BytesPerWord); + GcWordArray* oldArray = compileRoots(t)->virtualThunks(); + if (oldArray == 0 or oldArray->length() <= index * 2) { + GcWordArray* newArray = makeWordArray(t, nextPowerOfTwo((index + 1) * 2)); + if (compileRoots(t)->virtualThunks()) { + memcpy(newArray->body().begin(), + oldArray->body().begin(), + oldArray->length() * BytesPerWord); } - setRoot(t, VirtualThunks, newArray); + compileRoots(t)->setVirtualThunks(t, newArray); + oldArray = newArray; } - if (wordArrayBody(t, root(t, VirtualThunks), index * 2) == 0) { + if (oldArray->body()[index * 2] == 0) { unsigned size; uintptr_t thunk = compileVirtualThunk(t, index, &size); - wordArrayBody(t, root(t, VirtualThunks), index * 2) = thunk; - wordArrayBody(t, root(t, VirtualThunks), (index * 2) + 1) = size; + oldArray->body()[index * 2] = thunk; + oldArray->body()[(index * 2) + 1] = size; } - return wordArrayBody(t, root(t, VirtualThunks), index * 2); + return oldArray->body()[index * 2]; } -void -compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, - object method) +void compile(MyThread* t, + FixedAllocator* allocator, + BootContext* bootContext, + GcMethod* method) { PROTECT(t, method); - if (bootContext == 0 and methodFlags(t, method) & ACC_STATIC) { - initClass(t, methodClass(t, method)); + if (bootContext == 0 and method->flags() & ACC_STATIC) { + initClass(t, method->class_()); } if (methodAddress(t, method) != defaultThunk(t)) { return; } - assert(t, (methodFlags(t, method) & ACC_NATIVE) == 0); + assertT(t, (method->flags() & ACC_NATIVE) == 0); // We must avoid acquiring any locks until after the first pass of // compilation, since this pass may trigger classloading operations @@ -10026,7 +10192,7 @@ compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, // method so that we won't be confused if another thread updates the // original while we're working. - object clone = methodClone(t, method); + GcMethod* clone = methodClone(t, method); loadMemoryBarrier(); @@ -10039,18 +10205,19 @@ compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, Context context(t, bootContext, clone); compile(t, &context); - { object ehTable = codeExceptionHandlerTable(t, methodCode(t, clone)); + { + GcExceptionHandlerTable* ehTable = cast( + t, clone->code()->exceptionHandlerTable()); if (ehTable) { PROTECT(t, ehTable); // resolve all exception handler catch types before we acquire // the class lock: - for (unsigned i = 0; i < exceptionHandlerTableLength(t, ehTable); ++i) { - uint64_t handler = exceptionHandlerTableBody(t, ehTable, i); + for (unsigned i = 0; i < ehTable->length(); ++i) { + uint64_t handler = ehTable->body()[i]; if (exceptionHandlerCatchType(handler)) { - resolveClassInPool - (t, clone, exceptionHandlerCatchType(handler) - 1); + resolveClassInPool(t, clone, exceptionHandlerCatchType(handler) - 1); } } } @@ -10063,9 +10230,10 @@ compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, } finish(t, allocator, &context); - + if (DebugMethodTree) { - fprintf(stderr, "insert method at %p\n", + fprintf(stderr, + "insert method at %p\n", reinterpret_cast(methodCompiled(t, clone))); } @@ -10079,19 +10247,23 @@ compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, // clone in its place. Later, we'll replace the clone with the // original to save memory. - setRoot - (t, MethodTree, treeInsert - (t, &(context.zone), root(t, MethodTree), - methodCompiled(t, clone), clone, root(t, MethodTreeSentinal), - compareIpToMethodBounds)); + GcTreeNode* newTree = treeInsert(t, + &(context.zone), + compileRoots(t)->methodTree(), + methodCompiled(t, clone), + clone, + compileRoots(t)->methodTreeSentinal(), + compareIpToMethodBounds); + // sequence point, for gc (don't recombine statements) + compileRoots(t)->setMethodTree(t, newTree); storeStoreMemoryBarrier(); - set(t, method, MethodCode, methodCode(t, clone)); + method->setCode(t, clone->code()); if (methodVirtual(t, method)) { - classVtable(t, methodClass(t, method), methodOffset(t, method)) - = reinterpret_cast(methodCompiled(t, clone)); + method->class_()->vtable()[method->offset()] + = reinterpret_cast(methodCompiled(t, clone)); } // we've compiled the method and inserted it into the tree without @@ -10099,21 +10271,17 @@ compile(MyThread* t, FixedAllocator* allocator, BootContext* bootContext, // when we dispose of the context: context.executableAllocator = 0; - treeUpdate(t, root(t, MethodTree), methodCompiled(t, clone), - method, root(t, MethodTreeSentinal), compareIpToMethodBounds); + treeUpdate(t, + compileRoots(t)->methodTree(), + methodCompiled(t, clone), + method, + compileRoots(t)->methodTreeSentinal(), + compareIpToMethodBounds); } -object& -root(Thread* t, Root root) +GcCompileRoots* compileRoots(Thread* t) { - return arrayBody(t, processor(static_cast(t))->roots, root); -} - -void -setRoot(Thread* t, Root root, object value) -{ - set(t, processor(static_cast(t))->roots, - ArrayBody + (root * BytesPerWord), value); + return processor(static_cast(t))->roots; } avian::util::FixedAllocator* codeAllocator(MyThread* t) @@ -10121,9 +10289,9 @@ avian::util::FixedAllocator* codeAllocator(MyThread* t) return &(processor(t)->codeAllocator); } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { @@ -10133,7 +10301,8 @@ Processor* makeProcessor(System* system, bool useNativeFeatures) { return new (allocator->allocate(sizeof(local::MyProcessor))) - local::MyProcessor(system, allocator, crashDumpDirectory, useNativeFeatures); + local::MyProcessor( + system, allocator, crashDumpDirectory, useNativeFeatures); } -} // namespace vm +} // namespace vm diff --git a/src/debug-util.cpp b/src/debug-util.cpp index c0275aae97..0cab3e58e8 100644 --- a/src/debug-util.cpp +++ b/src/debug-util.cpp @@ -122,13 +122,13 @@ int printInstruction(uint8_t* code, unsigned& ip, const char* prefix) return fprintf(stderr, "drem"); case dsub: return fprintf(stderr, "dsub"); - case dup: + case vm::dup: return fprintf(stderr, "dup"); case dup_x1: return fprintf(stderr, "dup_x1"); case dup_x2: return fprintf(stderr, "dup_x2"); - case dup2: + case vm::dup2: return fprintf(stderr, "dup2"); case dup2_x1: return fprintf(stderr, "dup2_x1"); diff --git a/src/embed.cpp b/src/embed.cpp index 804f505766..05ea91a844 100644 --- a/src/embed.cpp +++ b/src/embed.cpp @@ -18,105 +18,118 @@ #include "avian/embed.h" #ifdef __x86_64__ -# define BINARY_LOADER(x) _binary_loader_##x +#define BINARY_LOADER(x) _binary_loader_##x #else -# define BINARY_LOADER(x) binary_loader_##x +#define BINARY_LOADER(x) binary_loader_##x #endif extern "C" const uint8_t BINARY_LOADER(start)[]; extern "C" const uint8_t BINARY_LOADER(end)[]; -__declspec(noreturn) -void printUsage(const wchar_t* executableName) +__declspec(noreturn) void printUsage(const wchar_t* executableName) { - wprintf(L"Usage: %s destination.exe classes.jar package.Main\n", executableName); - exit(0); + wprintf(L"Usage: %s destination.exe classes.jar package.Main\n", + executableName); + exit(0); } void writeDestinationFile(const wchar_t* filename) { - if(FILE* file = _wfopen(filename, L"wb")) - { - size_t count = BINARY_LOADER(end) - BINARY_LOADER(start); - if(count == fwrite(BINARY_LOADER(start), sizeof(BINARY_LOADER(start)[0]), count, file)) - { - fclose(file); - return; - } - } - - fprintf(stderr, "Unable to write to destination file\n"); - exit(EXIT_FAILURE); + if (FILE* file = _wfopen(filename, L"wb")) { + size_t count = BINARY_LOADER(end) - BINARY_LOADER(start); + if (count == fwrite(BINARY_LOADER(start), + sizeof(BINARY_LOADER(start)[0]), + count, + file)) { + fclose(file); + return; + } + } + + fprintf(stderr, "Unable to write to destination file\n"); + exit(EXIT_FAILURE); } void readFile(std::vector* jarFile, const wchar_t* fileName) { - if(FILE* file = _wfopen(fileName, L"rb")) - { - fseek(file, 0, SEEK_END); - jarFile->resize(ftell(file)); - fseek(file, 0, SEEK_SET); - fread(&jarFile->at(0), 1, jarFile->size(), file); - fclose(file); - } + if (FILE* file = _wfopen(fileName, L"rb")) { + fseek(file, 0, SEEK_END); + jarFile->resize(ftell(file)); + fseek(file, 0, SEEK_SET); + fread(&jarFile->at(0), 1, jarFile->size(), file); + fclose(file); + } } -bool mkStringSection(std::vector* stringSection, const std::vector& strings, int first, int last) +bool mkStringSection(std::vector* stringSection, + const std::vector& strings, + int first, + int last) { - stringSection->clear(); - for(int i = first; i <= last; ++i) - { - const std::wstring& s = strings.at(i); - stringSection->push_back(s.size()); - stringSection->insert(stringSection->end(), s.begin(), s.end()); - } + stringSection->clear(); + for (int i = first; i <= last; ++i) { + const std::wstring& s = strings.at(i); + stringSection->push_back(s.size()); + stringSection->insert(stringSection->end(), s.begin(), s.end()); + } - // pad to 16 entries - for(int i = last - first; i < 15; ++i) - stringSection->push_back(0); + // pad to 16 entries + for (int i = last - first; i < 15; ++i) + stringSection->push_back(0); - return stringSection->size() > 16; + return stringSection->size() > 16; } -void writeStringResources(HANDLE hDest, const std::vector& strings) +void writeStringResources(HANDLE hDest, + const std::vector& strings) { - for(unsigned i = 0; i < strings.size(); i += 16) - { - std::vector stringSection; + for (unsigned i = 0; i < strings.size(); i += 16) { + std::vector stringSection; - if(mkStringSection(&stringSection, strings, i, std::min(i + 15, strings.size() - 1))) - UpdateResourceW(hDest, reinterpret_cast(RT_STRING), reinterpret_cast(MAKEINTRESOURCE((i >> 4) + 1)), LANG_NEUTRAL, &stringSection.at(0), sizeof(wchar_t) * stringSection.size()); - } + if (mkStringSection(&stringSection, + strings, + i, + std::min(i + 15, strings.size() - 1))) + UpdateResourceW(hDest, + reinterpret_cast(RT_STRING), + reinterpret_cast(MAKEINTRESOURCE((i >> 4) + 1)), + LANG_NEUTRAL, + &stringSection.at(0), + sizeof(wchar_t) * stringSection.size()); + } } int wmain(int argc, wchar_t* argv[]) { - if(argc != 4) - printUsage(argv[0]); + if (argc != 4) + printUsage(argv[0]); - const wchar_t* destinationName = argv[1]; - const wchar_t* classesName = argv[2]; - const wchar_t* mainClassName = argv[3]; - - writeDestinationFile(destinationName); - - if(HANDLE hDest = BeginUpdateResourceW(destinationName, TRUE)) - { - std::vector strings; - strings.resize(RESID_MAIN_CLASS + 1); - strings.at(RESID_MAIN_CLASS) = mainClassName; - - writeStringResources(hDest, strings); - - std::vector jarFile; - readFile(&jarFile, classesName); - UpdateResourceW(hDest, reinterpret_cast(RT_RCDATA), RESID_BOOT_JAR, LANG_NEUTRAL, &jarFile.at(0), jarFile.size()); - - EndUpdateResource(hDest, FALSE); - } - + const wchar_t* destinationName = argv[1]; + const wchar_t* classesName = argv[2]; + const wchar_t* mainClassName = argv[3]; - return 0; + writeDestinationFile(destinationName); + + if (HANDLE hDest = BeginUpdateResourceW(destinationName, TRUE)) { + std::vector strings; + strings.resize(RESID_MAIN_CLASS + 1); + strings.at(RESID_MAIN_CLASS) = mainClassName; + + writeStringResources(hDest, strings); + + std::vector jarFile; + readFile(&jarFile, classesName); + UpdateResourceW(hDest, + reinterpret_cast(RT_RCDATA), + RESID_BOOT_JAR, + LANG_NEUTRAL, + &jarFile.at(0), + jarFile.size()); + + EndUpdateResource(hDest, FALSE); + } + + return 0; } #ifndef _MSC_VER @@ -125,9 +138,9 @@ extern "C" void __wgetmainargs(int*, wchar_t***, wchar_t***, int, int*); int main() { - wchar_t **enpv, **argv; - int argc, si = 0; - __wgetmainargs(&argc, &argv, &enpv, _CRT_glob, &si); - return wmain(argc, argv); + wchar_t** enpv, **argv; + int argc, si = 0; + __wgetmainargs(&argc, &argv, &enpv, _CRT_glob, &si); + return wmain(argc, argv); } #endif diff --git a/src/embedded-loader.cpp b/src/embedded-loader.cpp index 6c6bf59b4a..59fd529b66 100644 --- a/src/embedded-loader.cpp +++ b/src/embedded-loader.cpp @@ -17,40 +17,39 @@ #include "jni.h" extern "C" { - // since we aren't linking against libstdc++, we must implement this - // ourselves: - void __cxa_pure_virtual(void) { abort(); } +// since we aren't linking against libstdc++, we must implement this +// ourselves: +void __cxa_pure_virtual(void) +{ + abort(); +} - AVIAN_EXPORT const uint8_t* - bootJar(unsigned* size) - { - if(HRSRC hResInfo = FindResourceW(NULL, RESID_BOOT_JAR, reinterpret_cast(RT_RCDATA))) - { - if(HGLOBAL hRes = LoadResource(NULL, hResInfo)) - { - *size = SizeofResource(NULL, hResInfo); - return (const uint8_t*)LockResource(hRes); - } +AVIAN_EXPORT const uint8_t* bootJar(unsigned* size) +{ + if (HRSRC hResInfo = FindResourceW( + NULL, RESID_BOOT_JAR, reinterpret_cast(RT_RCDATA))) { + if (HGLOBAL hRes = LoadResource(NULL, hResInfo)) { + *size = SizeofResource(NULL, hResInfo); + return (const uint8_t*)LockResource(hRes); } - - fprintf(stderr, "boot.jar resource not found\n"); - - *size = 0; - return NULL; } -} // extern "C" + + fprintf(stderr, "boot.jar resource not found\n"); + + *size = 0; + return NULL; +} +} // extern "C" static void getMainClass(char* pName, int maxLen) { - if(0 == LoadString(NULL, RESID_MAIN_CLASS, pName, maxLen)) - { + if (0 == LoadString(NULL, RESID_MAIN_CLASS, pName, maxLen)) { fprintf(stderr, "Main class not specified\n"); strcpy(pName, "Main"); } } -int -main(int ac, const char** av) +int main(int ac, const char** av) { JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_2; @@ -72,24 +71,28 @@ main(int ac, const char** av) jclass c = e->FindClass(mainClass); if (not e->ExceptionCheck()) { - jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); - if (not e->ExceptionCheck()) { - jclass stringClass = e->FindClass("java/lang/String"); - if (not e->ExceptionCheck()) { - jobjectArray a = e->NewObjectArray(ac-1, stringClass, 0); - if (not e->ExceptionCheck()) { - for (int i = 1; i < ac; ++i) { - e->SetObjectArrayElement(a, i-1, e->NewStringUTF(av[i])); - } - - e->CallStaticVoidMethod(c, m, a); - } else fprintf(stderr, "Couldn't create array\n"); - } else fprintf(stderr, "java.lang.String not found\n"); - } else fprintf(stderr, "main method not found\n"); - } else fprintf(stderr, "Main class not found\n"); + jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); + if (not e->ExceptionCheck()) { + jclass stringClass = e->FindClass("java/lang/String"); + if (not e->ExceptionCheck()) { + jobjectArray a = e->NewObjectArray(ac - 1, stringClass, 0); + if (not e->ExceptionCheck()) { + for (int i = 1; i < ac; ++i) { + e->SetObjectArrayElement(a, i - 1, e->NewStringUTF(av[i])); + } + + e->CallStaticVoidMethod(c, m, a); + } else + fprintf(stderr, "Couldn't create array\n"); + } else + fprintf(stderr, "java.lang.String not found\n"); + } else + fprintf(stderr, "main method not found\n"); + } else + fprintf(stderr, "Main class not found\n"); int exitCode = 0; - if(e->ExceptionCheck()) { + if (e->ExceptionCheck()) { exitCode = -1; e->ExceptionDescribe(); e->ExceptionClear(); diff --git a/src/finder.cpp b/src/finder.cpp index dd99c898b7..f211928663 100644 --- a/src/finder.cpp +++ b/src/finder.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include "avian/zlib-custom.h" #include "avian/finder.h" @@ -34,11 +35,14 @@ class Element { virtual void dispose() = 0; }; - Element(): next(0) { } + Element() : next(0) + { + } virtual Iterator* iterator() = 0; virtual System::Region* find(const char* name) = 0; - virtual System::FileType stat(const char* name, unsigned* length, + virtual System::FileType stat(const char* name, + unsigned* length, bool tryDirectory) = 0; virtual const char* urlPrefix() = 0; virtual const char* sourceUrl() = 0; @@ -47,20 +51,26 @@ class Element { Element* next; }; -class DirectoryElement: public Element { +class DirectoryElement : public Element { public: - class Iterator: public Element::Iterator { + class Iterator : public Element::Iterator { public: - Iterator(System* s, Allocator* allocator, const char* name, unsigned skip): - s(s), allocator(allocator), name(name), skip(skip), directory(0), - last(0), it(0) + Iterator(System* s, Allocator* allocator, const char* name, unsigned skip) + : s(s), + allocator(allocator), + name(name), + skip(skip), + directory(0), + last(0), + it(0) { if (not s->success(s->open(&directory, name))) { directory = 0; } } - virtual const char* next(unsigned* size) { + virtual const char* next(unsigned* size) + { if (it) { const char* v = it->next(size); if (v) { @@ -82,7 +92,7 @@ class DirectoryElement: public Element { unsigned length; if (s->stat(last, &length) == System::TypeDirectory) { it = new (allocator->allocate(sizeof(Iterator))) - Iterator(s, allocator, last, skip); + Iterator(s, allocator, last, skip); it->name = last; } const char* result = last + skip; @@ -95,7 +105,8 @@ class DirectoryElement: public Element { return 0; } - virtual void dispose() { + virtual void dispose() + { directory->dispose(); allocator->free(this, sizeof(*this)); } @@ -109,21 +120,24 @@ class DirectoryElement: public Element { Iterator* it; }; - DirectoryElement(System* s, Allocator* allocator, const char* name): - s(s), - allocator(allocator), - originalName(name), - name(s->toAbsolutePath(allocator, name)), - urlPrefix_(append(allocator, "file:", this->name, "/")), - sourceUrl_(append(allocator, "file:", this->name)) - { } - - virtual Element::Iterator* iterator() { - return new (allocator->allocate(sizeof(Iterator))) - Iterator(s, allocator, name, strlen(name) + 1); + DirectoryElement(System* s, Allocator* allocator, const char* name) + : s(s), + allocator(allocator), + originalName(name), + name(s->toAbsolutePath(allocator, name)), + urlPrefix_(append(allocator, "file:", this->name, "/")), + sourceUrl_(append(allocator, "file:", this->name)) + { } - virtual System::Region* find(const char* name) { + virtual Element::Iterator* iterator() + { + return new (allocator->allocate(sizeof(Iterator))) + Iterator(s, allocator, name, strlen(name) + 1); + } + + virtual System::Region* find(const char* name) + { const char* file = append(allocator, this->name, "/", name); System::Region* region; System::Status status = s->map(®ion, file); @@ -142,7 +156,8 @@ class DirectoryElement: public Element { } } - virtual System::FileType stat(const char* name, unsigned* length, bool) { + virtual System::FileType stat(const char* name, unsigned* length, bool) + { const char* file = append(allocator, this->name, "/", name); System::FileType type = s->stat(file, length); if (DebugStat) { @@ -152,15 +167,18 @@ class DirectoryElement: public Element { return type; } - virtual const char* urlPrefix() { + virtual const char* urlPrefix() + { return urlPrefix_; } - virtual const char* sourceUrl() { + virtual const char* sourceUrl() + { return sourceUrl_; } - virtual void dispose() { + virtual void dispose() + { allocator->free(originalName, strlen(originalName) + 1); allocator->free(name, strlen(name) + 1); allocator->free(urlPrefix_, strlen(urlPrefix_) + 1); @@ -176,26 +194,33 @@ class DirectoryElement: public Element { const char* sourceUrl_; }; -class PointerRegion: public System::Region { +class PointerRegion : public System::Region { public: - PointerRegion(System* s, Allocator* allocator, const uint8_t* start, - size_t length, bool freePointer = false): - s(s), - allocator(allocator), - start_(start), - length_(length), - freePointer(freePointer) - { } + PointerRegion(System* s, + Allocator* allocator, + const uint8_t* start, + size_t length, + bool freePointer = false) + : s(s), + allocator(allocator), + start_(start), + length_(length), + freePointer(freePointer) + { + } - virtual const uint8_t* start() { + virtual const uint8_t* start() + { return start_; } - virtual size_t length() { + virtual size_t length() + { return length_; } - virtual void dispose() { + virtual void dispose() + { if (freePointer) { allocator->free(start_, length_); } @@ -209,23 +234,25 @@ class PointerRegion: public System::Region { bool freePointer; }; -class DataRegion: public System::Region { +class DataRegion : public System::Region { public: - DataRegion(System* s, Allocator* allocator, size_t length): - s(s), - allocator(allocator), - length_(length) - { } + DataRegion(System* s, Allocator* allocator, size_t length) + : s(s), allocator(allocator), length_(length) + { + } - virtual const uint8_t* start() { + virtual const uint8_t* start() + { return data; } - virtual size_t length() { + virtual size_t length() + { return length_; } - virtual void dispose() { + virtual void dispose() + { allocator->free(this, sizeof(*this) + length_); } @@ -237,39 +264,37 @@ class DataRegion: public System::Region { class JarIndex { public: - enum CompressionMethod { - Stored = 0, - Deflated = 8 - }; + enum CompressionMethod { Stored = 0, Deflated = 8 }; class Entry { - public: - Entry(uint32_t hash, const uint8_t* entry): - hash(hash), - entry(entry) {} + public: + Entry(uint32_t hash, const uint8_t* entry) : hash(hash), entry(entry) + { + } uint32_t hash; const uint8_t* entry; }; - JarIndex(System* s, Allocator* allocator, unsigned capacity): - s(s), - allocator(allocator), - capacity(capacity), - position(0), - nodes(static_cast*>(allocator->allocate(sizeof(List) * capacity))) + JarIndex(System* s, Allocator* allocator, unsigned capacity) + : s(s), + allocator(allocator), + capacity(capacity), + position(0), + nodes(static_cast*>( + allocator->allocate(sizeof(List) * capacity))) { memset(table, 0, sizeof(List*) * capacity); } - static JarIndex* make(System* s, Allocator* allocator, unsigned capacity) { - return new - (allocator->allocate(sizeof(JarIndex) + (sizeof(List*) * capacity))) - JarIndex(s, allocator, capacity); + static JarIndex* make(System* s, Allocator* allocator, unsigned capacity) + { + return new (allocator->allocate(sizeof(JarIndex) + + (sizeof(List*) * capacity))) + JarIndex(s, allocator, capacity); } - - static JarIndex* open(System* s, Allocator* allocator, - System::Region* region) + + static JarIndex* open(System* s, Allocator* allocator, System::Region* region) { JarIndex* index = make(s, allocator, 32); @@ -283,7 +308,8 @@ class JarIndex { while (p < end) { if (signature(p) == EntrySignature) { - index = index->add(Entry(hash(fileName(p), fileNameLength(p)), p)); + index = index->add(Entry( + hash(Slice(fileName(p), fileNameLength(p))), p)); p = endOfEntry(p); } else { @@ -298,7 +324,8 @@ class JarIndex { return index; } - JarIndex* add(const Entry& entry) { + JarIndex* add(const Entry& entry) + { if (position < capacity) { unsigned i = entry.hash & (capacity - 1); table[i] = new (nodes + (position++)) List(entry, table[i]); @@ -314,7 +341,8 @@ class JarIndex { } } - List* findNode(const char* name) { + List* findNode(const char* name) + { unsigned length = strlen(name); unsigned i = hash(name) & (capacity - 1); for (List* n = table[i]; n; n = n->next) { @@ -326,26 +354,30 @@ class JarIndex { return 0; } - System::Region* find(const char* name, const uint8_t* start) { + System::Region* find(const char* name, const uint8_t* start) + { List* n = findNode(name); if (n) { const uint8_t* p = n->item.entry; switch (compressionMethod(p)) { case Stored: { return new (allocator->allocate(sizeof(PointerRegion))) - PointerRegion(s, allocator, fileData(start + localHeaderOffset(p)), - compressedSize(p)); + PointerRegion(s, + allocator, + fileData(start + localHeaderOffset(p)), + compressedSize(p)); } break; case Deflated: { - DataRegion* region = new - (allocator->allocate(sizeof(DataRegion) + uncompressedSize(p))) - DataRegion(s, allocator, uncompressedSize(p)); - - z_stream zStream; memset(&zStream, 0, sizeof(z_stream)); + DataRegion* region = new ( + allocator->allocate(sizeof(DataRegion) + uncompressedSize(p))) + DataRegion(s, allocator, uncompressedSize(p)); - zStream.next_in = const_cast(fileData(start + - localHeaderOffset(p))); + z_stream zStream; + memset(&zStream, 0, sizeof(z_stream)); + + zStream.next_in + = const_cast(fileData(start + localHeaderOffset(p))); zStream.avail_in = compressedSize(p); zStream.next_out = region->data; zStream.avail_out = region->length(); @@ -398,7 +430,8 @@ class JarIndex { } } - void dispose() { + void dispose() + { allocator->free(nodes, sizeof(List) * capacity); allocator->free(this, sizeof(*this) + (sizeof(List*) * capacity)); } @@ -407,20 +440,22 @@ class JarIndex { Allocator* allocator; unsigned capacity; unsigned position; - + List* nodes; List* table[0]; }; -class JarElement: public Element { +class JarElement : public Element { public: - class Iterator: public Element::Iterator { + class Iterator : public Element::Iterator { public: - Iterator(System* s, Allocator* allocator, JarIndex* index): - s(s), allocator(allocator), index(index), position(0) - { } + Iterator(System* s, Allocator* allocator, JarIndex* index) + : s(s), allocator(allocator), index(index), position(0) + { + } - virtual const char* next(unsigned* size) { + virtual const char* next(unsigned* size) + { if (position < index->position) { List* n = index->nodes + (position++); *size = fileNameLength(n->item.entry); @@ -430,7 +465,8 @@ class JarElement: public Element { } } - virtual void dispose() { + virtual void dispose() + { allocator->free(this, sizeof(*this)); } @@ -440,41 +476,49 @@ class JarElement: public Element { unsigned position; }; - JarElement(System* s, Allocator* allocator, const char* name, - bool canonicalizePath = true): - s(s), - allocator(allocator), - originalName(name), - name(name and canonicalizePath - ? s->toAbsolutePath(allocator, name) : name), - urlPrefix_(this->name - ? append(allocator, "jar:file:", this->name, "!/") : 0), - sourceUrl_(this->name - ? append(allocator, "file:", this->name) : 0), - region(0), index(0) - { } + JarElement(System* s, + Allocator* allocator, + const char* name, + bool canonicalizePath = true) + : s(s), + allocator(allocator), + originalName(name), + name(name and canonicalizePath ? s->toAbsolutePath(allocator, name) + : name), + urlPrefix_(this->name ? append(allocator, "jar:file:", this->name, "!/") + : 0), + sourceUrl_(this->name ? append(allocator, "file:", this->name) : 0), + region(0), + index(0) + { + } - JarElement(System* s, Allocator* allocator, const uint8_t* jarData, - unsigned jarLength): - s(s), - allocator(allocator), - originalName(0), - name(0), - urlPrefix_(name ? append(allocator, "jar:file:", name, "!/") : 0), - sourceUrl_(name ? append(allocator, "file:", name) : 0), - region(new (allocator->allocate(sizeof(PointerRegion))) - PointerRegion(s, allocator, jarData, jarLength)), - index(JarIndex::open(s, allocator, region)) - { } + JarElement(System* s, + Allocator* allocator, + const uint8_t* jarData, + unsigned jarLength) + : s(s), + allocator(allocator), + originalName(0), + name(0), + urlPrefix_(name ? append(allocator, "jar:file:", name, "!/") : 0), + sourceUrl_(name ? append(allocator, "file:", name) : 0), + region(new (allocator->allocate(sizeof(PointerRegion))) + PointerRegion(s, allocator, jarData, jarLength)), + index(JarIndex::open(s, allocator, region)) + { + } - virtual Element::Iterator* iterator() { + virtual Element::Iterator* iterator() + { init(); return new (allocator->allocate(sizeof(Iterator))) - Iterator(s, allocator, index); + Iterator(s, allocator, index); } - virtual void init() { + virtual void init() + { if (index == 0) { System::Region* r; if (s->success(s->map(&r, name))) { @@ -484,10 +528,12 @@ class JarElement: public Element { } } - virtual System::Region* find(const char* name) { + virtual System::Region* find(const char* name) + { init(); - while (*name == '/') name++; + while (*name == '/') + name++; System::Region* r = (index ? index->find(name, region->start()) : 0); if (DebugFind) { @@ -500,34 +546,40 @@ class JarElement: public Element { return r; } - virtual System::FileType stat(const char* name, unsigned* length, + virtual System::FileType stat(const char* name, + unsigned* length, bool tryDirectory) { init(); - while (*name == '/') name++; + while (*name == '/') + name++; System::FileType type = (index ? index->stat(name, length, tryDirectory) - : System::TypeDoesNotExist); + : System::TypeDoesNotExist); if (DebugStat) { fprintf(stderr, "stat %s in %s: %d\n", name, this->name, type); } return type; } - virtual const char* urlPrefix() { + virtual const char* urlPrefix() + { return urlPrefix_; } - virtual const char* sourceUrl() { + virtual const char* sourceUrl() + { return sourceUrl_; } - virtual void dispose() { + virtual void dispose() + { dispose(sizeof(*this)); } - virtual void dispose(unsigned size) { + virtual void dispose(unsigned size) + { if (name) { if (originalName != name) { allocator->free(originalName, strlen(originalName) + 1); @@ -555,15 +607,19 @@ class JarElement: public Element { JarIndex* index; }; -class BuiltinElement: public JarElement { +class BuiltinElement : public JarElement { public: - BuiltinElement(System* s, Allocator* allocator, const char* name, - const char* libraryName): - JarElement(s, allocator, name, false), - libraryName(libraryName ? copy(allocator, libraryName) : 0) - { } + BuiltinElement(System* s, + Allocator* allocator, + const char* name, + const char* libraryName) + : JarElement(s, allocator, name, false), + libraryName(libraryName ? copy(allocator, libraryName) : 0) + { + } - virtual void init() { + virtual void init() + { if (index == 0) { if (s->success(s->load(&library, libraryName))) { bool lzma = strncmp("lzma.", name, 5) == 0; @@ -591,29 +647,31 @@ class BuiltinElement: public JarElement { freePointer = false; } region = new (allocator->allocate(sizeof(PointerRegion))) - PointerRegion(s, allocator, data, size, freePointer); + PointerRegion(s, allocator, data, size, freePointer); index = JarIndex::open(s, allocator, region); } else if (DebugFind) { - fprintf(stderr, "%s in %s returned null\n", symbolName, - libraryName); + fprintf( + stderr, "%s in %s returned null\n", symbolName, libraryName); } } else if (DebugFind) { - fprintf(stderr, "unable to find %s in %s\n", symbolName, - libraryName); + fprintf(stderr, "unable to find %s in %s\n", symbolName, libraryName); } } } } - virtual const char* urlPrefix() { + virtual const char* urlPrefix() + { return "avianvmresource:"; } - virtual const char* sourceUrl() { + virtual const char* sourceUrl() + { return 0; } - virtual void dispose() { + virtual void dispose() + { library->disposeAll(); if (libraryName) { allocator->free(libraryName, strlen(libraryName) + 1); @@ -625,8 +683,7 @@ class BuiltinElement: public JarElement { const char* libraryName; }; -void -add(Element** first, Element** last, Element* e) +void add(Element** first, Element** last, Element* e) { if (*last) { (*last)->next = e; @@ -636,8 +693,7 @@ add(Element** first, Element** last, Element* e) *last = e; } -unsigned -baseName(const char* name, char fileSeparator) +unsigned baseName(const char* name, char fileSeparator) { const char* p = name; const char* last = 0; @@ -651,14 +707,23 @@ baseName(const char* name, char fileSeparator) return last ? (last + 1) - name : 0; } -void -add(System* s, Element** first, Element** last, Allocator* allocator, - const char* name, unsigned nameLength, const char* bootLibrary); +void add(System* s, + Element** first, + Element** last, + Allocator* allocator, + const char* name, + unsigned nameLength, + const char* bootLibrary); -void -addTokens(System* s, Element** first, Element** last, Allocator* allocator, - const char* jarName, unsigned jarNameBase, const char* tokens, - unsigned tokensLength, const char* bootLibrary) +void addTokens(System* s, + Element** first, + Element** last, + Allocator* allocator, + const char* jarName, + unsigned jarNameBase, + const char* tokens, + unsigned tokensLength, + const char* bootLibrary) { for (Tokenizer t(String(tokens, tokensLength), ' '); t.hasMore();) { String token(t.next()); @@ -667,31 +732,39 @@ addTokens(System* s, Element** first, Element** last, Allocator* allocator, memcpy(RUNTIME_ARRAY_BODY(n), jarName, jarNameBase); memcpy(RUNTIME_ARRAY_BODY(n) + jarNameBase, token.text, token.length); RUNTIME_ARRAY_BODY(n)[jarNameBase + token.length] = 0; - - add(s, first, last, allocator, RUNTIME_ARRAY_BODY(n), - jarNameBase + token.length, bootLibrary); + + add(s, + first, + last, + allocator, + RUNTIME_ARRAY_BODY(n), + jarNameBase + token.length, + bootLibrary); } } -bool -continuationLine(const uint8_t* base, unsigned total, unsigned* start, - unsigned* length) +bool continuationLine(const uint8_t* base, + unsigned total, + unsigned* start, + unsigned* length) { - return readLine(base, total, start, length) - and *length > 0 - and base[*start] == ' '; + return readLine(base, total, start, length) and *length > 0 + and base[*start] == ' '; } -void -addJar(System* s, Element** first, Element** last, Allocator* allocator, - const char* name, const char* bootLibrary) +void addJar(System* s, + Element** first, + Element** last, + Allocator* allocator, + const char* name, + const char* bootLibrary) { if (DebugFind) { fprintf(stderr, "add jar %s\n", name); } JarElement* e = new (allocator->allocate(sizeof(JarElement))) - JarElement(s, allocator, name); + JarElement(s, allocator, name); unsigned nameBase = baseName(name, s->fileSeparator()); @@ -706,52 +779,65 @@ addJar(System* s, Element** first, Element** last, Allocator* allocator, const unsigned PrefixLength = 12; if (length > PrefixLength - and strncmp("Class-Path: ", reinterpret_cast - (region->start() + start), PrefixLength) == 0) - { - { unsigned nextStart = start + length; + and strncmp("Class-Path: ", + reinterpret_cast(region->start() + start), + PrefixLength) == 0) { + { + unsigned nextStart = start + length; unsigned nextLength; - while (continuationLine - (region->start(), region->length(), &nextStart, &nextLength)) - { + while (continuationLine( + region->start(), region->length(), &nextStart, &nextLength)) { multilineTotal += nextLength; nextStart += nextLength; } } - const char* line = reinterpret_cast - (region->start() + start + PrefixLength); + const char* line = reinterpret_cast(region->start() + start + + PrefixLength); unsigned lineLength = length - PrefixLength; if (multilineTotal) { - RUNTIME_ARRAY - (char, n, (length - PrefixLength) + multilineTotal + 1); + RUNTIME_ARRAY(char, n, (length - PrefixLength) + multilineTotal + 1); memcpy(RUNTIME_ARRAY_BODY(n), line, lineLength); unsigned offset = lineLength; - { unsigned nextStart = start + length; + { + unsigned nextStart = start + length; unsigned nextLength; - while (continuationLine - (region->start(), region->length(), &nextStart, - &nextLength)) - { + while (continuationLine( + region->start(), region->length(), &nextStart, &nextLength)) { unsigned continuationLength = nextLength - 1; memcpy(RUNTIME_ARRAY_BODY(n) + offset, - region->start() + nextStart + 1, continuationLength); - + region->start() + nextStart + 1, + continuationLength); + offset += continuationLength; nextStart += nextLength; } } - addTokens(s, first, last, allocator, name, nameBase, - RUNTIME_ARRAY_BODY(n), offset, bootLibrary); + addTokens(s, + first, + last, + allocator, + name, + nameBase, + RUNTIME_ARRAY_BODY(n), + offset, + bootLibrary); } else { - addTokens(s, first, last, allocator, name, nameBase, line, - lineLength, bootLibrary); + addTokens(s, + first, + last, + allocator, + name, + nameBase, + line, + lineLength, + bootLibrary); } } @@ -762,20 +848,26 @@ addJar(System* s, Element** first, Element** last, Allocator* allocator, } } -void -add(System* s, Element** first, Element** last, Allocator* allocator, - const char* token, unsigned tokenLength, const char* bootLibrary) +void add(System* s, + Element** first, + Element** last, + Allocator* allocator, + const char* token, + unsigned tokenLength, + const char* bootLibrary) { if (*token == '[' and token[tokenLength - 1] == ']') { char* name = static_cast(allocator->allocate(tokenLength - 1)); memcpy(name, token + 1, tokenLength - 1); - name[tokenLength - 2] = 0; + name[tokenLength - 2] = 0; if (DebugFind) { fprintf(stderr, "add builtin %s\n", name); } - - add(first, last, new (allocator->allocate(sizeof(BuiltinElement))) + + add(first, + last, + new (allocator->allocate(sizeof(BuiltinElement))) BuiltinElement(s, allocator, name, bootLibrary)); } else { char* name = static_cast(allocator->allocate(tokenLength + 1)); @@ -793,7 +885,9 @@ add(System* s, Element** first, Element** last, Allocator* allocator, fprintf(stderr, "add directory %s\n", name); } - add(first, last, new (allocator->allocate(sizeof(DirectoryElement))) + add(first, + last, + new (allocator->allocate(sizeof(DirectoryElement))) DirectoryElement(s, allocator, name)); } break; @@ -808,9 +902,10 @@ add(System* s, Element** first, Element** last, Allocator* allocator, } } -Element* -parsePath(System* s, Allocator* allocator, const char* path, - const char* bootLibrary) +Element* parsePath(System* s, + Allocator* allocator, + const char* path, + const char* bootLibrary) { Element* first = 0; Element* last = 0; @@ -823,14 +918,18 @@ parsePath(System* s, Allocator* allocator, const char* path, return first; } -class MyIterator: public Finder::IteratorImp { +class MyIterator : public Finder::IteratorImp { public: - MyIterator(System* s, Allocator* allocator, Element* path): - s(s), allocator(allocator), e(path ? path->next : 0), - it(path ? path->iterator() : 0) - { } + MyIterator(System* s, Allocator* allocator, Element* path) + : s(s), + allocator(allocator), + e(path ? path->next : 0), + it(path ? path->iterator() : 0) + { + } - virtual const char* next(unsigned* size) { + virtual const char* next(unsigned* size) + { while (it) { const char* v = it->next(size); if (v) { @@ -848,8 +947,10 @@ class MyIterator: public Finder::IteratorImp { return 0; } - virtual void dispose() { - if (it) it->dispose(); + virtual void dispose() + { + if (it) + it->dispose(); allocator->free(this, sizeof(*this)); } @@ -859,42 +960,51 @@ class MyIterator: public Finder::IteratorImp { Element::Iterator* it; }; -class MyFinder: public Finder { +class MyFinder : public Finder { public: - MyFinder(System* system, Allocator* allocator, const char* path, - const char* bootLibrary): - system(system), - allocator(allocator), - path_(parsePath(system, allocator, path, bootLibrary)), - pathString(copy(allocator, path)) - { } - - MyFinder(System* system, Allocator* allocator, const uint8_t* jarData, - unsigned jarLength): - system(system), - allocator(allocator), - path_(new (allocator->allocate(sizeof(JarElement))) - JarElement(system, allocator, jarData, jarLength)), - pathString(0) - { } - - virtual IteratorImp* iterator() { - return new (allocator->allocate(sizeof(MyIterator))) - MyIterator(system, allocator, path_); + MyFinder(System* system, + Allocator* allocator, + const char* path, + const char* bootLibrary) + : system(system), + allocator(allocator), + path_(parsePath(system, allocator, path, bootLibrary)), + pathString(copy(allocator, path)) + { } - virtual System::Region* find(const char* name) { + MyFinder(System* system, + Allocator* allocator, + const uint8_t* jarData, + unsigned jarLength) + : system(system), + allocator(allocator), + path_(new (allocator->allocate(sizeof(JarElement))) + JarElement(system, allocator, jarData, jarLength)), + pathString(0) + { + } + + virtual IteratorImp* iterator() + { + return new (allocator->allocate(sizeof(MyIterator))) + MyIterator(system, allocator, path_); + } + + virtual System::Region* find(const char* name) + { for (Element* e = path_; e; e = e->next) { System::Region* r = e->find(name); if (r) { return r; } } - + return 0; } - virtual System::FileType stat(const char* name, unsigned* length, + virtual System::FileType stat(const char* name, + unsigned* length, bool tryDirectory) { for (Element* e = path_; e; e = e->next) { @@ -903,19 +1013,19 @@ class MyFinder: public Finder { return type; } } - + return System::TypeDoesNotExist; } - virtual const char* urlPrefix(const char* name) { - void *finderElementPtr = NULL; + virtual const char* urlPrefix(const char* name) + { + void* finderElementPtr = NULL; return nextUrlPrefix(name, finderElementPtr); } - virtual const char* nextUrlPrefix(const char* name, - void *&finderElementPtr) + virtual const char* nextUrlPrefix(const char* name, void*& finderElementPtr) { - Element *&e = reinterpret_cast(finderElementPtr); + Element*& e = reinterpret_cast(finderElementPtr); e = e ? e->next : path_; for (; e; e = e->next) { unsigned length; @@ -928,7 +1038,8 @@ class MyFinder: public Finder { return 0; } - virtual const char* sourceUrl(const char* name) { + virtual const char* sourceUrl(const char* name) + { for (Element* e = path_; e; e = e->next) { unsigned length; System::FileType type = e->stat(name, &length, true); @@ -940,11 +1051,13 @@ class MyFinder: public Finder { return 0; } - virtual const char* path() { + virtual const char* path() + { return pathString; } - virtual void dispose() { + virtual void dispose() + { for (Element* e = path_; e;) { Element* t = e; e = e->next; @@ -962,21 +1075,24 @@ class MyFinder: public Finder { const char* pathString; }; -} // namespace +} // namespace namespace vm { -AVIAN_EXPORT Finder* -makeFinder(System* s, Allocator* a, const char* path, const char* bootLibrary) +AVIAN_EXPORT Finder* makeFinder(System* s, + Allocator* a, + const char* path, + const char* bootLibrary) { return new (a->allocate(sizeof(MyFinder))) MyFinder(s, a, path, bootLibrary); } -Finder* -makeFinder(System* s, Allocator* a, const uint8_t* jarData, unsigned jarLength) +Finder* makeFinder(System* s, + Allocator* a, + const uint8_t* jarData, + unsigned jarLength) { - return new (a->allocate(sizeof(MyFinder))) - MyFinder(s, a, jarData, jarLength); + return new (a->allocate(sizeof(MyFinder))) MyFinder(s, a, jarData, jarLength); } -} // namespace vm +} // namespace vm diff --git a/src/heap/heap.cpp b/src/heap/heap.cpp index fa11086b65..54ce4a4209 100644 --- a/src/heap/heap.cpp +++ b/src/heap/heap.cpp @@ -38,15 +38,17 @@ const bool DebugAllocation = false; const bool DebugAllocation = true; #endif -#define ACQUIRE(x) MutexLock MAKE_NAME(monitorLock_) (x) +#define ACQUIRE(x) MutexLock MAKE_NAME(monitorLock_)(x) class MutexLock { public: - MutexLock(System::Mutex* m): m(m) { + MutexLock(System::Mutex* m) : m(m) + { m->acquire(); } - ~MutexLock() { + ~MutexLock() + { m->release(); } @@ -64,40 +66,35 @@ void* allocate(Context* c, unsigned size, bool limit); void free(Context* c, const void* p, unsigned size); #ifdef USE_ATOMIC_OPERATIONS -inline void -markBitAtomic(uintptr_t* map, unsigned i) +inline void markBitAtomic(uintptr_t* map, unsigned i) { uintptr_t* p = map + wordOf(i); uintptr_t v = static_cast(1) << bitOf(i); - for (uintptr_t old = *p; - not atomicCompareAndSwap(p, old, old | v); - old = *p) - { } + for (uintptr_t old = *p; not atomicCompareAndSwap(p, old, old | v); + old = *p) { + } } -#endif // USE_ATOMIC_OPERATIONS +#endif // USE_ATOMIC_OPERATIONS -inline void* -get(void* o, unsigned offsetInWords) +inline void* get(void* o, unsigned offsetInWords) { - return maskAlignedPointer(fieldAtOffset(o, offsetInWords * BytesPerWord)); + return maskAlignedPointer( + fieldAtOffset(o, offsetInWords * BytesPerWord)); } -inline void** -getp(void* o, unsigned offsetInWords) +inline void** getp(void* o, unsigned offsetInWords) { return &fieldAtOffset(o, offsetInWords * BytesPerWord); } -inline void -set(void** o, void* value) +inline void set(void** o, void* value) { - *o = reinterpret_cast - (reinterpret_cast(value) - | (reinterpret_cast(*o) & (~PointerMask))); + *o = reinterpret_cast( + reinterpret_cast(value) + | (reinterpret_cast(*o) & (~PointerMask))); } -inline void -set(void* o, unsigned offsetInWords, void* value) +inline void set(void* o, unsigned offsetInWords, void* value) { set(getp(o, offsetInWords), value); } @@ -111,42 +108,43 @@ class Segment { Map* map; unsigned index; unsigned limit; - - Iterator(Map* map, unsigned start, unsigned end): - map(map) - { - assert(map->segment->context, map->bitsPerRecord == 1); - assert(map->segment->context, map->segment); - assert(map->segment->context, start <= map->segment->position()); - if (end > map->segment->position()) end = map->segment->position(); + Iterator(Map* map, unsigned start, unsigned end) : map(map) + { + assertT(map->segment->context, map->bitsPerRecord == 1); + assertT(map->segment->context, map->segment); + assertT(map->segment->context, start <= map->segment->position()); + + if (end > map->segment->position()) + end = map->segment->position(); index = map->indexOf(start); limit = map->indexOf(end); - if ((end - start) % map->scale) ++ limit; + if ((end - start) % map->scale) + ++limit; } - bool hasMore() { + bool hasMore() + { unsigned word = wordOf(index); unsigned bit = bitOf(index); unsigned wordLimit = wordOf(limit); unsigned bitLimit = bitOf(limit); for (; word <= wordLimit and (word < wordLimit or bit < bitLimit); - ++word) - { + ++word) { uintptr_t w = map->data[word]; if (2) { for (; bit < BitsPerWord and (word < wordLimit or bit < bitLimit); - ++bit) - { + ++bit) { if (w & (static_cast(1) << bit)) { index = ::indexOf(word, bit); // printf("hit at index %d\n", index); return true; } else { - // printf("miss at index %d\n", indexOf(word, bit)); + // printf("miss at index %d\n", indexOf(word, + // bit)); } } } @@ -157,10 +155,11 @@ class Segment { return false; } - - unsigned next() { - assert(map->segment->context, hasMore()); - assert(map->segment->context, map->segment); + + unsigned next() + { + assertT(map->segment->context, hasMore()); + assertT(map->segment->context, map->segment); return (index++) * map->scale; } @@ -173,34 +172,44 @@ class Segment { unsigned scale; bool clearNewData; - Map(Segment* segment, uintptr_t* data, unsigned bitsPerRecord, - unsigned scale, Map* child, bool clearNewData): - segment(segment), - child(child), - data(data), - bitsPerRecord(bitsPerRecord), - scale(scale), - clearNewData(clearNewData) - { } + Map(Segment* segment, + uintptr_t* data, + unsigned bitsPerRecord, + unsigned scale, + Map* child, + bool clearNewData) + : segment(segment), + child(child), + data(data), + bitsPerRecord(bitsPerRecord), + scale(scale), + clearNewData(clearNewData) + { + } - Map(Segment* segment, unsigned bitsPerRecord, unsigned scale, Map* child, - bool clearNewData): - segment(segment), - child(child), - data(0), - bitsPerRecord(bitsPerRecord), - scale(scale), - clearNewData(clearNewData) - { } + Map(Segment* segment, + unsigned bitsPerRecord, + unsigned scale, + Map* child, + bool clearNewData) + : segment(segment), + child(child), + data(0), + bitsPerRecord(bitsPerRecord), + scale(scale), + clearNewData(clearNewData) + { + } - void init() { - assert(segment->context, bitsPerRecord); - assert(segment->context, scale); - assert(segment->context, powerOfTwo(scale)); + void init() + { + assertT(segment->context, bitsPerRecord); + assertT(segment->context, scale); + assertT(segment->context, powerOfTwo(scale)); if (data == 0) { data = segment->data + segment->capacity() - + calculateOffset(segment->capacity()); + + calculateOffset(segment->capacity()); } if (clearNewData) { @@ -212,114 +221,141 @@ class Segment { } } - unsigned calculateOffset(unsigned capacity) { + unsigned calculateOffset(unsigned capacity) + { unsigned n = 0; - if (child) n += child->calculateFootprint(capacity); + if (child) + n += child->calculateFootprint(capacity); return n; } - static unsigned calculateSize(Context* c UNUSED, unsigned capacity, - unsigned scale, unsigned bitsPerRecord) + static unsigned calculateSize(Context* c UNUSED, + unsigned capacity, + unsigned scale, + unsigned bitsPerRecord) { - unsigned result - = ceilingDivide(ceilingDivide(capacity, scale) * bitsPerRecord, BitsPerWord); - assert(c, result); + unsigned result = ceilingDivide( + ceilingDivide(capacity, scale) * bitsPerRecord, BitsPerWord); + assertT(c, result); return result; } - unsigned calculateSize(unsigned capacity) { + unsigned calculateSize(unsigned capacity) + { return calculateSize(segment->context, capacity, scale, bitsPerRecord); } - unsigned size() { + unsigned size() + { return calculateSize(segment->capacity()); } - unsigned calculateFootprint(unsigned capacity) { + unsigned calculateFootprint(unsigned capacity) + { unsigned n = calculateSize(capacity); - if (child) n += child->calculateFootprint(capacity); + if (child) + n += child->calculateFootprint(capacity); return n; } - void replaceWith(Map* m) { - assert(segment->context, bitsPerRecord == m->bitsPerRecord); - assert(segment->context, scale == m->scale); + void replaceWith(Map* m) + { + assertT(segment->context, bitsPerRecord == m->bitsPerRecord); + assertT(segment->context, scale == m->scale); data = m->data; m->segment = 0; m->data = 0; - - if (child) child->replaceWith(m->child); + + if (child) + child->replaceWith(m->child); } - unsigned indexOf(unsigned segmentIndex) { + unsigned indexOf(unsigned segmentIndex) + { return (segmentIndex / scale) * bitsPerRecord; } - unsigned indexOf(void* p) { - assert(segment->context, segment->almostContains(p)); - assert(segment->context, segment->capacity()); + unsigned indexOf(void* p) + { + assertT(segment->context, segment->almostContains(p)); + assertT(segment->context, segment->capacity()); return indexOf(segment->indexOf(p)); } - void clearBit(unsigned i) { - assert(segment->context, wordOf(i) < size()); + void clearBit(unsigned i) + { + assertT(segment->context, wordOf(i) < size()); vm::clearBit(data, i); } - void setBit(unsigned i) { - assert(segment->context, wordOf(i) < size()); + void setBit(unsigned i) + { + assertT(segment->context, wordOf(i) < size()); vm::markBit(data, i); } - void clearOnlyIndex(unsigned index) { + void clearOnlyIndex(unsigned index) + { clearBits(data, bitsPerRecord, index); } - void clearOnly(unsigned segmentIndex) { + void clearOnly(unsigned segmentIndex) + { clearOnlyIndex(indexOf(segmentIndex)); } - void clearOnly(void* p) { + void clearOnly(void* p) + { clearOnlyIndex(indexOf(p)); } - void clear(void* p) { + void clear(void* p) + { clearOnly(p); - if (child) child->clear(p); + if (child) + child->clear(p); } - void setOnlyIndex(unsigned index, unsigned v = 1) { + void setOnlyIndex(unsigned index, unsigned v = 1) + { setBits(data, bitsPerRecord, index, v); } - void setOnly(unsigned segmentIndex, unsigned v = 1) { + void setOnly(unsigned segmentIndex, unsigned v = 1) + { setOnlyIndex(indexOf(segmentIndex), v); } - void setOnly(void* p, unsigned v = 1) { + void setOnly(void* p, unsigned v = 1) + { setOnlyIndex(indexOf(p), v); } - void set(void* p, unsigned v = 1) { + void set(void* p, unsigned v = 1) + { setOnly(p, v); - assert(segment->context, get(p) == v); - if (child) child->set(p, v); + assertT(segment->context, get(p) == v); + if (child) + child->set(p, v); } #ifdef USE_ATOMIC_OPERATIONS - void markAtomic(void* p) { - assert(segment->context, bitsPerRecord == 1); + void markAtomic(void* p) + { + assertT(segment->context, bitsPerRecord == 1); markBitAtomic(data, indexOf(p)); - assert(segment->context, getBit(data, indexOf(p))); - if (child) child->markAtomic(p); + assertT(segment->context, getBit(data, indexOf(p))); + if (child) + child->markAtomic(p); } #endif - unsigned get(void* p) { + unsigned get(void* p) + { return getBits(data, bitsPerRecord, indexOf(p)); } }; @@ -330,20 +366,19 @@ class Segment { unsigned capacity_; Map* map; - Segment(Context* context, Map* map, unsigned desired, unsigned minimum, - int64_t available = INT64_MAX): - context(context), - data(0), - position_(0), - capacity_(0), - map(map) + Segment(Context* context, + Map* map, + unsigned desired, + unsigned minimum, + int64_t available = INT64_MAX) + : context(context), data(0), position_(0), capacity_(0), map(map) { if (desired) { if (minimum == 0) { minimum = 1; } - - assert(context, desired >= minimum); + + assertT(context, desired >= minimum); capacity_ = desired; @@ -356,17 +391,15 @@ class Segment { if (bottom == capacity_) { break; } else if (static_cast(footprint(capacity_ - 1)) - <= target) - { - -- capacity_; + <= target) { + --capacity_; break; } top = capacity_; capacity_ = avg(bottom, capacity_); } else if (static_cast(footprint(capacity_)) < target) { if (top == capacity_ - or static_cast(footprint(capacity_ + 1)) >= target) - { + or static_cast(footprint(capacity_ + 1)) >= target) { break; } bottom = capacity_; @@ -378,9 +411,8 @@ class Segment { } while (data == 0) { - data = static_cast - (local::allocate - (context, (footprint(capacity_)) * BytesPerWord, false)); + data = static_cast(local::allocate( + context, (footprint(capacity_)) * BytesPerWord, false)); if (data == 0) { if (capacity_ > minimum) { @@ -389,9 +421,8 @@ class Segment { break; } } else { - data = static_cast - (local::allocate - (context, (footprint(capacity_)) * BytesPerWord)); + data = static_cast(local::allocate( + context, (footprint(capacity_)) * BytesPerWord)); } } } @@ -402,37 +433,45 @@ class Segment { } } - Segment(Context* context, Map* map, uintptr_t* data, unsigned position, - unsigned capacity): - context(context), - data(data), - position_(position), - capacity_(capacity), - map(map) + Segment(Context* context, + Map* map, + uintptr_t* data, + unsigned position, + unsigned capacity) + : context(context), + data(data), + position_(position), + capacity_(capacity), + map(map) { if (map) { map->init(); } } - unsigned footprint(unsigned capacity) { + unsigned footprint(unsigned capacity) + { return capacity - + (map and capacity ? map->calculateFootprint(capacity) : 0); + + (map and capacity ? map->calculateFootprint(capacity) : 0); } - unsigned capacity() { + unsigned capacity() + { return capacity_; } - unsigned position() { + unsigned position() + { return position_; } - unsigned remaining() { + unsigned remaining() + { return capacity() - position(); } - void replaceWith(Segment* s) { + void replaceWith(Segment* s) + { if (data) { free(context, data, (footprint(capacity())) * BytesPerWord); } @@ -453,38 +492,44 @@ class Segment { abort(context); } } else { - assert(context, map == 0); - } + assertT(context, map == 0); + } } - bool contains(void* p) { + bool contains(void* p) + { return position() and p >= data and p < data + position(); } - bool almostContains(void* p) { + bool almostContains(void* p) + { return contains(p) or p == data + position(); } - void* get(unsigned offset) { - assert(context, offset <= position()); + void* get(unsigned offset) + { + assertT(context, offset <= position()); return data + offset; } - unsigned indexOf(void* p) { - assert(context, almostContains(p)); + unsigned indexOf(void* p) + { + assertT(context, almostContains(p)); return static_cast(p) - data; } - void* allocate(unsigned size) { - assert(context, size); - assert(context, position() + size <= capacity()); + void* allocate(unsigned size) + { + assertT(context, size); + assertT(context, position() + size <= capacity()); void* p = data + position(); position_ += size; return p; } - void dispose() { + void dispose() + { if (data) { free(context, data, (footprint(capacity())) * BytesPerWord); } @@ -500,13 +545,12 @@ class Fixie { static const unsigned Dirty = 1 << 2; static const unsigned Dead = 1 << 3; - Fixie(Context* c, unsigned size, bool hasMask, Fixie** handle, - bool immortal): - age(immortal ? FixieTenureThreshold + 1 : 0), - flags(hasMask ? HasMask : 0), - size(size), - next(0), - handle(0) + Fixie(Context* c, unsigned size, bool hasMask, Fixie** handle, bool immortal) + : age(immortal ? FixieTenureThreshold + 1 : 0), + flags(hasMask ? HasMask : 0), + size(size), + next(0), + handle(0) { memset(mask(), 0, maskSize(size, hasMask)); add(c, handle); @@ -515,27 +559,31 @@ class Fixie { } } - bool immortal() { + bool immortal() + { return age == FixieTenureThreshold + 1; } - void add(Context* c UNUSED, Fixie** handle) { - assert(c, this->handle == 0); - assert(c, next == 0); + void add(Context* c UNUSED, Fixie** handle) + { + assertT(c, this->handle == 0); + assertT(c, next == 0); this->handle = handle; if (handle) { next = *handle; - if (next) next->handle = &next; + if (next) + next->handle = &next; *handle = this; } else { next = 0; } } - void remove(Context* c UNUSED) { + void remove(Context* c UNUSED) + { if (handle) { - assert(c, *handle == this); + assertT(c, *handle == this); *handle = next; } if (next) { @@ -545,7 +593,8 @@ class Fixie { handle = 0; } - void move(Context* c, Fixie** handle) { + void move(Context* c, Fixie** handle) + { if (DebugFixies) { fprintf(stderr, "move fixie %p\n", this); } @@ -554,35 +603,43 @@ class Fixie { add(c, handle); } - void** body() { + void** body() + { return static_cast(static_cast(body_)); } - uintptr_t* mask() { + uintptr_t* mask() + { return body_ + size; } - static unsigned maskSize(unsigned size, bool hasMask) { + static unsigned maskSize(unsigned size, bool hasMask) + { return hasMask * ceilingDivide(size, BitsPerWord) * BytesPerWord; } - static unsigned totalSize(unsigned size, bool hasMask) { + static unsigned totalSize(unsigned size, bool hasMask) + { return sizeof(Fixie) + (size * BytesPerWord) + maskSize(size, hasMask); } - unsigned totalSize() { + unsigned totalSize() + { return totalSize(size, hasMask()); } - bool hasMask() { + bool hasMask() + { return (flags & HasMask) != 0; } - bool marked() { + bool marked() + { return (flags & Marked) != 0; } - void marked(bool v) { + void marked(bool v) + { if (v) { flags |= Marked; } else { @@ -590,11 +647,13 @@ class Fixie { } } - bool dirty() { + bool dirty() + { return (flags & Dirty) != 0; } - void dirty(bool v) { + void dirty(bool v) + { if (v) { flags |= Dirty; } else { @@ -602,11 +661,13 @@ class Fixie { } } - bool dead() { + bool dead() + { return (flags & Dead) != 0; } - void dead(bool v) { + void dead(bool v) + { if (v) { flags |= Dead; } else { @@ -625,77 +686,72 @@ class Fixie { uintptr_t body_[0]; }; -Fixie* -fixie(void* body) +Fixie* fixie(void* body) { return static_cast(body) - 1; } -void -free(Context* c, Fixie** fixies, bool resetImmortal = false); +void free(Context* c, Fixie** fixies, bool resetImmortal = false); class Context { public: - Context(System* system, unsigned limit): - system(system), - client(0), - count(0), - limit(limit), - lock(0), - - immortalHeapStart(0), - immortalHeapEnd(0), - - ageMap(&gen1, max(1, log(TenureThreshold)), 1, 0, false), - gen1(this, &ageMap, 0, 0), - - nextAgeMap(&nextGen1, max(1, log(TenureThreshold)), 1, 0, false), - nextGen1(this, &nextAgeMap, 0, 0), - - pointerMap(&gen2, 1, 1, 0, true), - pageMap(&gen2, 1, LikelyPageSizeInBytes / BytesPerWord, &pointerMap, true), - heapMap(&gen2, 1, pageMap.scale * 1024, &pageMap, true), - gen2(this, &heapMap, 0, 0), - - nextPointerMap(&nextGen2, 1, 1, 0, true), - nextPageMap(&nextGen2, 1, LikelyPageSizeInBytes / BytesPerWord, - &nextPointerMap, true), - nextHeapMap(&nextGen2, 1, nextPageMap.scale * 1024, &nextPageMap, true), - nextGen2(this, &nextHeapMap, 0, 0), - - gen2Base(0), - incomingFootprint(0), - pendingAllocation(0), - tenureFootprint(0), - gen1Padding(0), - tenurePadding(0), - gen2Padding(0), - - fixieTenureFootprint(0), - untenuredFixieFootprint(0), - tenuredFixieFootprint(0), - tenuredFixieCeiling(InitialTenuredFixieCeilingInBytes), - - mode(Heap::MinorCollection), - - fixies(0), - tenuredFixies(0), - dirtyTenuredFixies(0), - markedFixies(0), - visitedFixies(0), - - lastCollectionTime(system->now()), - totalCollectionTime(0), - totalTime(0), - - limitWasExceeded(false) + Context(System* system, unsigned limit) + : system(system), + client(0), + count(0), + limit(limit), + lock(0), + immortalHeapStart(0), + immortalHeapEnd(0), + ageMap(&gen1, max(1, log(TenureThreshold)), 1, 0, false), + gen1(this, &ageMap, 0, 0), + nextAgeMap(&nextGen1, max(1, log(TenureThreshold)), 1, 0, false), + nextGen1(this, &nextAgeMap, 0, 0), + pointerMap(&gen2, 1, 1, 0, true), + pageMap(&gen2, + 1, + LikelyPageSizeInBytes / BytesPerWord, + &pointerMap, + true), + heapMap(&gen2, 1, pageMap.scale * 1024, &pageMap, true), + gen2(this, &heapMap, 0, 0), + nextPointerMap(&nextGen2, 1, 1, 0, true), + nextPageMap(&nextGen2, + 1, + LikelyPageSizeInBytes / BytesPerWord, + &nextPointerMap, + true), + nextHeapMap(&nextGen2, 1, nextPageMap.scale * 1024, &nextPageMap, true), + nextGen2(this, &nextHeapMap, 0, 0), + gen2Base(0), + incomingFootprint(0), + pendingAllocation(0), + tenureFootprint(0), + gen1Padding(0), + tenurePadding(0), + gen2Padding(0), + fixieTenureFootprint(0), + untenuredFixieFootprint(0), + tenuredFixieFootprint(0), + tenuredFixieCeiling(InitialTenuredFixieCeilingInBytes), + mode(Heap::MinorCollection), + fixies(0), + tenuredFixies(0), + dirtyTenuredFixies(0), + markedFixies(0), + visitedFixies(0), + lastCollectionTime(system->now()), + totalCollectionTime(0), + totalTime(0), + limitWasExceeded(false) { if (not system->success(system->make(&lock))) { system->abort(); } } - void dispose() { + void dispose() + { gen1.dispose(); nextGen1.dispose(); gen2.dispose(); @@ -703,7 +759,8 @@ class Context { lock->dispose(); } - void disposeFixies() { + void disposeFixies() + { free(this, &tenuredFixies, true); free(this, &dirtyTenuredFixies, true); free(this, &fixies, true); @@ -737,7 +794,7 @@ class Context { Segment nextGen2; unsigned gen2Base; - + unsigned incomingFootprint; int pendingAllocation; unsigned tenureFootprint; @@ -765,8 +822,7 @@ class Context { bool limitWasExceeded; }; -const char* -segment(Context* c, void* p) +const char* segment(Context* c, void* p) { if (c->gen1.contains(p)) { return "gen1"; @@ -781,36 +837,33 @@ segment(Context* c, void* p) } } -inline Aborter* getAborter(Context* c) { +inline Aborter* getAborter(Context* c) +{ return c->system; } -inline unsigned -minimumNextGen1Capacity(Context* c) +inline unsigned minimumNextGen1Capacity(Context* c) { return c->gen1.position() - c->tenureFootprint + c->incomingFootprint - + c->gen1Padding; + + c->gen1Padding; } -inline unsigned -minimumNextGen2Capacity(Context* c) +inline unsigned minimumNextGen2Capacity(Context* c) { return c->gen2.position() + c->tenureFootprint + c->tenurePadding - + c->gen2Padding; + + c->gen2Padding; } -inline bool -oversizedGen2(Context* c) +inline bool oversizedGen2(Context* c) { return c->gen2.capacity() > (InitialGen2CapacityInBytes / BytesPerWord) - and c->gen2.position() < (c->gen2.capacity() / 4); + and c->gen2.position() < (c->gen2.capacity() / 4); } -inline void -initNextGen1(Context* c) +inline void initNextGen1(Context* c) { - new (&(c->nextAgeMap)) Segment::Map - (&(c->nextGen1), max(1, log(TenureThreshold)), 1, 0, false); + new (&(c->nextAgeMap)) + Segment::Map(&(c->nextGen1), max(1, log(TenureThreshold)), 1, 0, false); unsigned minimum = minimumNextGen1Capacity(c); unsigned desired = minimum; @@ -818,23 +871,24 @@ initNextGen1(Context* c) new (&(c->nextGen1)) Segment(c, &(c->nextAgeMap), desired, minimum); if (Verbose2) { - fprintf(stderr, "init nextGen1 to %d bytes\n", + fprintf(stderr, + "init nextGen1 to %d bytes\n", c->nextGen1.capacity() * BytesPerWord); } } -inline void -initNextGen2(Context* c) +inline void initNextGen2(Context* c) { - new (&(c->nextPointerMap)) Segment::Map - (&(c->nextGen2), 1, 1, 0, true); + new (&(c->nextPointerMap)) Segment::Map(&(c->nextGen2), 1, 1, 0, true); - new (&(c->nextPageMap)) Segment::Map - (&(c->nextGen2), 1, LikelyPageSizeInBytes / BytesPerWord, - &(c->nextPointerMap), true); + new (&(c->nextPageMap)) Segment::Map(&(c->nextGen2), + 1, + LikelyPageSizeInBytes / BytesPerWord, + &(c->nextPointerMap), + true); - new (&(c->nextHeapMap)) Segment::Map - (&(c->nextGen2), 1, c->pageMap.scale * 1024, &(c->nextPageMap), true); + new (&(c->nextHeapMap)) Segment::Map( + &(c->nextGen2), 1, c->pageMap.scale * 1024, &(c->nextPageMap), true); unsigned minimum = minimumNextGen2Capacity(c); unsigned desired = minimum; @@ -847,57 +901,53 @@ initNextGen2(Context* c) desired = InitialGen2CapacityInBytes / BytesPerWord; } - new (&(c->nextGen2)) Segment - (c, &(c->nextHeapMap), desired, minimum, - static_cast(c->limit / BytesPerWord) - - (static_cast(c->count / BytesPerWord) - - c->gen2.footprint(c->gen2.capacity()) - - c->gen1.footprint(c->gen1.capacity()) - + c->pendingAllocation)); + new (&(c->nextGen2)) Segment( + c, + &(c->nextHeapMap), + desired, + minimum, + static_cast(c->limit / BytesPerWord) + - (static_cast(c->count / BytesPerWord) + - c->gen2.footprint(c->gen2.capacity()) + - c->gen1.footprint(c->gen1.capacity()) + c->pendingAllocation)); if (Verbose2) { - fprintf(stderr, "init nextGen2 to %d bytes\n", + fprintf(stderr, + "init nextGen2 to %d bytes\n", c->nextGen2.capacity() * BytesPerWord); } } -inline bool -fresh(Context* c, void* o) +inline bool fresh(Context* c, void* o) { - return c->nextGen1.contains(o) - or c->nextGen2.contains(o) - or (c->gen2.contains(o) and c->gen2.indexOf(o) >= c->gen2Base); + return c->nextGen1.contains(o) or c->nextGen2.contains(o) + or (c->gen2.contains(o) and c->gen2.indexOf(o) >= c->gen2Base); } -inline bool -wasCollected(Context* c, void* o) +inline bool wasCollected(Context* c, void* o) { return o and (not fresh(c, o)) and fresh(c, get(o, 0)); } -inline void* -follow(Context* c UNUSED, void* o) +inline void* follow(Context* c UNUSED, void* o) { - assert(c, wasCollected(c, o)); + assertT(c, wasCollected(c, o)); return fieldAtOffset(o, 0); } -inline void*& -parent(Context* c UNUSED, void* o) +inline void*& parent(Context* c UNUSED, void* o) { - assert(c, wasCollected(c, o)); + assertT(c, wasCollected(c, o)); return fieldAtOffset(o, BytesPerWord); } -inline uintptr_t* -bitset(Context* c UNUSED, void* o) +inline uintptr_t* bitset(Context* c UNUSED, void* o) { - assert(c, wasCollected(c, o)); + assertT(c, wasCollected(c, o)); return &fieldAtOffset(o, BytesPerWord * 2); } -void -free(Context* c, Fixie** fixies, bool resetImmortal) +void free(Context* c, Fixie** fixies, bool resetImmortal) { for (Fixie** p = fixies; *p;) { Fixie* f = *p; @@ -913,7 +963,7 @@ free(Context* c, Fixie** fixies, bool resetImmortal) f->handle = 0; f->marked(false); f->dirty(false); - } else { + } else { p = &(f->next); } } else { @@ -926,20 +976,18 @@ free(Context* c, Fixie** fixies, bool resetImmortal) } } -void -kill(Fixie* fixies) +void kill(Fixie* fixies) { for (Fixie* f = fixies; f; f = f->next) { - if (! f->immortal()) { + if (!f->immortal()) { f->dead(true); } } } -void -killFixies(Context* c) +void killFixies(Context* c) { - assert(c, c->markedFixies == 0); + assertT(c, c->markedFixies == 0); if (c->mode == Heap::MajorCollection) { kill(c->tenuredFixies); @@ -948,10 +996,9 @@ killFixies(Context* c) kill(c->fixies); } -void -sweepFixies(Context* c) +void sweepFixies(Context* c) { - assert(c, c->markedFixies == 0); + assertT(c, c->markedFixies == 0); if (c->mode == Heap::MajorCollection) { free(c, &(c->tenuredFixies)); @@ -968,7 +1015,7 @@ sweepFixies(Context* c) f->remove(c); if (not f->immortal()) { - ++ f->age; + ++f->age; if (f->age > FixieTenureThreshold) { f->age = FixieTenureThreshold; } else if (static_cast(f->age + 1) == FixieTenureThreshold) { @@ -999,40 +1046,36 @@ sweepFixies(Context* c) f->marked(false); } - c->tenuredFixieCeiling = max - (c->tenuredFixieFootprint * 2, - InitialTenuredFixieCeilingInBytes); + c->tenuredFixieCeiling + = max(c->tenuredFixieFootprint * 2, InitialTenuredFixieCeilingInBytes); } -inline void* -copyTo(Context* c, Segment* s, void* o, unsigned size) +inline void* copyTo(Context* c, Segment* s, void* o, unsigned size) { - assert(c, s->remaining() >= size); + assertT(c, s->remaining() >= size); void* dst = s->allocate(size); c->client->copy(o, dst); return dst; } -bool -immortalHeapContains(Context* c, void* p) +bool immortalHeapContains(Context* c, void* p) { return p < c->immortalHeapEnd and p >= c->immortalHeapStart; } -void* -copy2(Context* c, void* o) +void* copy2(Context* c, void* o) { unsigned size = c->client->copiedSizeInWords(o); if (c->gen2.contains(o)) { - assert(c, c->mode == Heap::MajorCollection); + assertT(c, c->mode == Heap::MajorCollection); return copyTo(c, &(c->nextGen2), o, size); } else if (c->gen1.contains(o)) { unsigned age = c->ageMap.get(o); if (age == TenureThreshold) { if (c->mode == Heap::MinorCollection) { - assert(c, c->gen2.remaining() >= size); + assertT(c, c->gen2.remaining() >= size); if (c->gen2Base == Top) { c->gen2Base = c->gen2.position(); @@ -1053,9 +1096,9 @@ copy2(Context* c, void* o) return o; } } else { - assert(c, not c->nextGen1.contains(o)); - assert(c, not c->nextGen2.contains(o)); - assert(c, not immortalHeapContains(c, o)); + assertT(c, not c->nextGen1.contains(o)); + assertT(c, not c->nextGen2.contains(o)); + assertT(c, not immortalHeapContains(c, o)); o = copyTo(c, &(c->nextGen1), o, size); @@ -1065,14 +1108,17 @@ copy2(Context* c, void* o) } } -void* -copy(Context* c, void* o) +void* copy(Context* c, void* o) { void* r = copy2(c, o); if (Debug) { - fprintf(stderr, "copy %p (%s) to %p (%s)\n", - o, segment(c, o), r, segment(c, r)); + fprintf(stderr, + "copy %p (%s) to %p (%s)\n", + o, + segment(c, o), + r, + segment(c, r)); } // leave a pointer to the copy in the original @@ -1081,15 +1127,12 @@ copy(Context* c, void* o) return r; } -void* -update3(Context* c, void* o, bool* needsVisit) +void* update3(Context* c, void* o, bool* needsVisit) { if (c->client->isFixed(o)) { Fixie* f = fixie(o); - if ((not f->marked()) - and (c->mode == Heap::MajorCollection - or f->age < FixieTenureThreshold)) - { + if ((not f->marked()) and (c->mode == Heap::MajorCollection + or f->age < FixieTenureThreshold)) { if (DebugFixies) { fprintf(stderr, "mark fixie %p\n", f); } @@ -1101,7 +1144,7 @@ update3(Context* c, void* o, bool* needsVisit) return o; } else if (immortalHeapContains(c, o)) { *needsVisit = false; - return o; + return o; } else if (wasCollected(c, o)) { *needsVisit = false; return follow(c, o); @@ -1111,8 +1154,7 @@ update3(Context* c, void* o, bool* needsVisit) } } -void* -update2(Context* c, void* o, bool* needsVisit) +void* update2(Context* c, void* o, bool* needsVisit) { if (c->mode == Heap::MinorCollection and c->gen2.contains(o)) { *needsVisit = false; @@ -1122,8 +1164,7 @@ update2(Context* c, void* o, bool* needsVisit) return update3(c, o, needsVisit); } -void -markDirty(Context* c, Fixie* f) +void markDirty(Context* c, Fixie* f) { if (not f->dirty()) { #ifdef USE_ATOMIC_OPERATIONS @@ -1137,8 +1178,7 @@ markDirty(Context* c, Fixie* f) } } -void -markClean(Context* c, Fixie* f) +void markClean(Context* c, Fixie* f) { if (f->dirty()) { f->dirty(false); @@ -1150,8 +1190,11 @@ markClean(Context* c, Fixie* f) } } -void -updateHeapMap(Context* c, void* p, void* target, unsigned offset, void* result) +void updateHeapMap(Context* c, + void* p, + void* target, + unsigned offset, + void* result) { Segment* seg; Segment::Map* map; @@ -1164,28 +1207,35 @@ updateHeapMap(Context* c, void* p, void* target, unsigned offset, void* result) map = &(c->nextHeapMap); } - if (not (immortalHeapContains(c, result) - or (c->client->isFixed(result) - and fixie(result)->age >= FixieTenureThreshold) - or seg->contains(result))) - { + if (not(immortalHeapContains(c, result) + or (c->client->isFixed(result) + and fixie(result)->age >= FixieTenureThreshold) + or seg->contains(result))) { if (target and c->client->isFixed(target)) { Fixie* f = fixie(target); - assert(c, offset == 0 or f->hasMask()); + assertT(c, offset == 0 or f->hasMask()); if (static_cast(f->age + 1) >= FixieTenureThreshold) { if (DebugFixies) { - fprintf(stderr, "dirty fixie %p at %d (%p): %p\n", - f, offset, f->body() + offset, result); + fprintf(stderr, + "dirty fixie %p at %d (%p): %p\n", + f, + offset, + f->body() + offset, + result); } f->dirty(true); markBit(f->mask(), offset); } } else if (seg->contains(p)) { - if (Debug) { - fprintf(stderr, "mark %p (%s) at %p (%s)\n", - result, segment(c, result), p, segment(c, p)); + if (Debug) { + fprintf(stderr, + "mark %p (%s) at %p (%s)\n", + result, + segment(c, result), + p, + segment(c, p)); } map->set(p); @@ -1193,8 +1243,11 @@ updateHeapMap(Context* c, void* p, void* target, unsigned offset, void* result) } } -void* -update(Context* c, void** p, void* target, unsigned offset, bool* needsVisit) +void* update(Context* c, + void** p, + void* target, + unsigned offset, + bool* needsVisit) { if (maskAlignedPointer(*p) == 0) { *needsVisit = false; @@ -1211,16 +1264,14 @@ update(Context* c, void** p, void* target, unsigned offset, bool* needsVisit) } const uintptr_t BitsetExtensionBit -= (static_cast(1) << (BitsPerWord - 1)); + = (static_cast(1) << (BitsPerWord - 1)); -void -bitsetInit(uintptr_t* p) +void bitsetInit(uintptr_t* p) { memset(p, 0, BytesPerWord); } -void -bitsetClear(uintptr_t* p, unsigned start, unsigned end) +void bitsetClear(uintptr_t* p, unsigned start, unsigned end) { if (end < BitsPerWord - 1) { // do nothing @@ -1235,14 +1286,14 @@ bitsetClear(uintptr_t* p, unsigned start, unsigned end) } } -void -bitsetSet(uintptr_t* p, unsigned i, bool v) +void bitsetSet(uintptr_t* p, unsigned i, bool v) { if (i >= BitsPerWord - 1) { i += (BitsPerWord * 2) + 1; if (v) { p[0] |= BitsetExtensionBit; - if (p[2] <= wordOf(i) - 3) p[2] = wordOf(i) - 2; + if (p[2] <= wordOf(i) - 3) + p[2] = wordOf(i) - 2; } } @@ -1253,11 +1304,11 @@ bitsetSet(uintptr_t* p, unsigned i, bool v) } } -bool -bitsetHasMore(uintptr_t* p) +bool bitsetHasMore(uintptr_t* p) { switch (*p) { - case 0: return false; + case 0: + return false; case BitsetExtensionBit: { uintptr_t length = p[2]; @@ -1272,23 +1323,24 @@ bitsetHasMore(uintptr_t* p) return false; } - default: return true; + default: + return true; } } -unsigned -bitsetNext(Context* c, uintptr_t* p) +unsigned bitsetNext(Context* c, uintptr_t* p) { bool more UNUSED = bitsetHasMore(p); - assert(c, more); + assertT(c, more); switch (*p) { - case 0: abort(c); + case 0: + abort(c); case BitsetExtensionBit: { uintptr_t i = p[1]; uintptr_t word = wordOf(i); - assert(c, word < p[2]); + assertT(c, word < p[2]); for (uintptr_t bit = bitOf(i); bit < BitsPerWord; ++bit) { if (p[word + 3] & (static_cast(1) << bit)) { p[1] = indexOf(word, bit) + 1; @@ -1311,151 +1363,163 @@ bitsetNext(Context* c, uintptr_t* p) } } -void -collect(Context* c, void** p, void* target, unsigned offset) +void collect(Context* c, void** p, void* target, unsigned offset) { void* original = maskAlignedPointer(*p); void* parent_ = 0; - + if (Debug) { - fprintf(stderr, "update %p (%s) at %p (%s)\n", - maskAlignedPointer(*p), segment(c, *p), p, segment(c, p)); + fprintf(stderr, + "update %p (%s) at %p (%s)\n", + maskAlignedPointer(*p), + segment(c, *p), + p, + segment(c, p)); } bool needsVisit; local::set(p, update(c, maskAlignedPointer(p), target, offset, &needsVisit)); if (Debug) { - fprintf(stderr, " result: %p (%s) (visit? %d)\n", - maskAlignedPointer(*p), segment(c, *p), needsVisit); + fprintf(stderr, + " result: %p (%s) (visit? %d)\n", + maskAlignedPointer(*p), + segment(c, *p), + needsVisit); } - if (not needsVisit) return; + if (not needsVisit) + return; - visit: { - void* copy = follow(c, original); +visit : { + void* copy = follow(c, original); - class Walker : public Heap::Walker { - public: - Walker(Context* c, void* copy, uintptr_t* bitset): - c(c), - copy(copy), - bitset(bitset), - first(0), - second(0), - last(0), - visits(0), - total(0) - { } + class Walker : public Heap::Walker { + public: + Walker(Context* c, void* copy, uintptr_t* bitset) + : c(c), + copy(copy), + bitset(bitset), + first(0), + second(0), + last(0), + visits(0), + total(0) + { + } - virtual bool visit(unsigned offset) { - if (Debug) { - fprintf(stderr, " update %p (%s) at %p - offset %d from %p (%s)\n", - get(copy, offset), - segment(c, get(copy, offset)), - getp(copy, offset), - offset, - copy, - segment(c, copy)); + virtual bool visit(unsigned offset) + { + if (Debug) { + fprintf(stderr, + " update %p (%s) at %p - offset %d from %p (%s)\n", + get(copy, offset), + segment(c, get(copy, offset)), + getp(copy, offset), + offset, + copy, + segment(c, copy)); + } + + bool needsVisit; + void* childCopy + = update(c, getp(copy, offset), copy, offset, &needsVisit); + + if (Debug) { + fprintf(stderr, + " result: %p (%s) (visit? %d)\n", + childCopy, + segment(c, childCopy), + needsVisit); + } + + ++total; + + if (total == 3) { + bitsetInit(bitset); + } + + if (needsVisit) { + ++visits; + + if (visits == 1) { + first = offset; + } else if (visits == 2) { + second = offset; } + } else { + local::set(copy, offset, childCopy); + } - bool needsVisit; - void* childCopy = update - (c, getp(copy, offset), copy, offset, &needsVisit); - - if (Debug) { - fprintf(stderr, " result: %p (%s) (visit? %d)\n", - childCopy, segment(c, childCopy), needsVisit); - } + if (visits > 1 and total > 2 and (second or needsVisit)) { + bitsetClear(bitset, last, offset); + last = offset; - ++ total; - - if (total == 3) { - bitsetInit(bitset); + if (second) { + bitsetSet(bitset, second, true); + second = 0; } if (needsVisit) { - ++ visits; - - if (visits == 1) { - first = offset; - } else if (visits == 2) { - second = offset; - } - } else { - local::set(copy, offset, childCopy); + bitsetSet(bitset, offset, true); } - - if (visits > 1 and total > 2 and (second or needsVisit)) { - bitsetClear(bitset, last, offset); - last = offset; - - if (second) { - bitsetSet(bitset, second, true); - second = 0; - } - - if (needsVisit) { - bitsetSet(bitset, offset, true); - } - } - - return true; } - Context* c; - void* copy; - uintptr_t* bitset; - unsigned first; - unsigned second; - unsigned last; - unsigned visits; - unsigned total; - } walker(c, copy, bitset(c, original)); - - if (Debug) { - fprintf(stderr, "walk %p (%s)\n", copy, segment(c, copy)); + return true; } - c->client->walk(copy, &walker); + Context* c; + void* copy; + uintptr_t* bitset; + unsigned first; + unsigned second; + unsigned last; + unsigned visits; + unsigned total; + } walker(c, copy, bitset(c, original)); - if (walker.visits) { - // descend - if (walker.visits > 1) { - parent(c, original) = parent_; - parent_ = original; - } - - original = get(copy, walker.first); - local::set(copy, walker.first, follow(c, original)); - goto visit; - } else { - // ascend - original = parent_; - } + if (Debug) { + fprintf(stderr, "walk %p (%s)\n", copy, segment(c, copy)); } + c->client->walk(copy, &walker); + + if (walker.visits) { + // descend + if (walker.visits > 1) { + parent(c, original) = parent_; + parent_ = original; + } + + original = get(copy, walker.first); + local::set(copy, walker.first, follow(c, original)); + goto visit; + } else { + // ascend + original = parent_; + } +} + if (original) { void* copy = follow(c, original); class Walker : public Heap::Walker { public: - Walker(Context* c, uintptr_t* bitset): - c(c), - bitset(bitset), - next(0), - total(0) - { } + Walker(Context* c, uintptr_t* bitset) + : c(c), bitset(bitset), next(0), total(0) + { + } - virtual bool visit(unsigned offset) { - switch (++ total) { + virtual bool visit(unsigned offset) + { + switch (++total) { case 1: return true; case 2: next = offset; return true; - + case 3: next = bitsetNext(c, bitset); return false; @@ -1477,7 +1541,7 @@ collect(Context* c, void** p, void* target, unsigned offset) c->client->walk(copy, &walker); - assert(c, walker.total > 1); + assertT(c, walker.total > 1); if (walker.total == 3 and bitsetHasMore(bitset(c, original))) { parent_ = original; @@ -1486,7 +1550,8 @@ collect(Context* c, void** p, void* target, unsigned offset) } if (Debug) { - fprintf(stderr, " next is %p (%s) at %p - offset %d from %p (%s)\n", + fprintf(stderr, + " next is %p (%s) at %p - offset %d from %p (%s)\n", get(copy, walker.next), segment(c, get(copy, walker.next)), getp(copy, walker.next), @@ -1503,20 +1568,17 @@ collect(Context* c, void** p, void* target, unsigned offset) } } -void -collect(Context* c, void** p) +void collect(Context* c, void** p) { collect(c, p, 0, 0); } -void -collect(Context* c, void* target, unsigned offset) +void collect(Context* c, void* target, unsigned offset) { collect(c, getp(target, offset), target, offset); } -void -visitDirtyFixies(Context* c, Fixie** p) +void visitDirtyFixies(Context* c, Fixie** p) { while (*p) { Fixie* f = *p; @@ -1534,13 +1596,10 @@ visitDirtyFixies(Context* c, Fixie** p) fprintf(stderr, "clean fixie %p\n", f); } - for (; word <= wordLimit and (word < wordLimit or bit < bitLimit); - ++ word) - { + for (; word <= wordLimit and (word < wordLimit or bit < bitLimit); ++word) { if (mask[word]) { for (; bit < BitsPerWord and (word < wordLimit or bit < bitLimit); - ++ bit) - { + ++bit) { unsigned index = indexOf(word, bit); if (getBit(mask, index)) { @@ -1549,8 +1608,11 @@ visitDirtyFixies(Context* c, Fixie** p) clearBit(mask, index); if (DebugFixies) { - fprintf(stderr, "clean fixie %p at %d (%p)\n", - f, index, f->body() + index); + fprintf(stderr, + "clean fixie %p at %d (%p)\n", + f, + index, + f->body() + index); } collect(c, f->body(), index); @@ -1568,7 +1630,7 @@ visitDirtyFixies(Context* c, Fixie** p) fprintf(stderr, "done cleaning fixie %p\n", f); } - assert(c, wasDirty); + assertT(c, wasDirty); if (clean) { markClean(c, f); @@ -1578,8 +1640,7 @@ visitDirtyFixies(Context* c, Fixie** p) } } -void -visitMarkedFixies(Context* c) +void visitMarkedFixies(Context* c) { while (c->markedFixies) { Fixie* f = c->markedFixies; @@ -1589,13 +1650,14 @@ visitMarkedFixies(Context* c) fprintf(stderr, "visit fixie %p\n", f); } - class Walker: public Heap::Walker { + class Walker : public Heap::Walker { public: - Walker(Context* c, void** p): - c(c), p(p) - { } + Walker(Context* c, void** p) : c(c), p(p) + { + } - virtual bool visit(unsigned offset) { + virtual bool visit(unsigned offset) + { local::collect(c, p, offset); return true; } @@ -1607,18 +1669,21 @@ visitMarkedFixies(Context* c) c->client->walk(f->body(), &w); f->move(c, &(c->visitedFixies)); - } + } } -void -collect(Context* c, Segment::Map* map, unsigned start, unsigned end, - bool* dirty, bool expectDirty UNUSED) +void collect(Context* c, + Segment::Map* map, + unsigned start, + unsigned end, + bool* dirty, + bool expectDirty UNUSED) { bool wasDirty UNUSED = false; for (Segment::Map::Iterator it(map, start, end); it.hasMore();) { wasDirty = true; if (map->child) { - assert(c, map->scale > 1); + assertT(c, map->scale > 1); unsigned s = it.next(); unsigned e = s + map->scale; @@ -1630,7 +1695,7 @@ collect(Context* c, Segment::Map* map, unsigned start, unsigned end, *dirty = true; } } else { - assert(c, map->scale == 1); + assertT(c, map->scale == 1); void** p = reinterpret_cast(map->segment->get(it.next())); map->clearOnly(p); @@ -1648,11 +1713,10 @@ collect(Context* c, Segment::Map* map, unsigned start, unsigned end, } } - assert(c, wasDirty or not expectDirty); + assertT(c, wasDirty or not expectDirty); } -void -collect2(Context* c) +void collect2(Context* c) { c->gen2Base = Top; c->tenureFootprint = 0; @@ -1677,9 +1741,12 @@ collect2(Context* c) class Visitor : public Heap::Visitor { public: - Visitor(Context* c): c(c) { } + Visitor(Context* c) : c(c) + { + } - virtual void visit(void* p) { + virtual void visit(void* p) + { local::collect(c, static_cast(p)); visitMarkedFixies(c); } @@ -1690,11 +1757,10 @@ collect2(Context* c) c->client->visitRoots(&v); } -bool -limitExceeded(Context* c, int pendingAllocation) +bool limitExceeded(Context* c, int pendingAllocation) { unsigned count = c->count + pendingAllocation - - (c->gen2.remaining() * BytesPerWord); + - (c->gen2.remaining() * BytesPerWord); if (Verbose) { if (count > c->limit) { @@ -1704,30 +1770,26 @@ limitExceeded(Context* c, int pendingAllocation) } } else if (c->limitWasExceeded) { c->limitWasExceeded = false; - fprintf(stderr, "heap limit %d no longer exceeded: %d\n", - c->limit, count); + fprintf( + stderr, "heap limit %d no longer exceeded: %d\n", c->limit, count); } } return count > c->limit; } -void -collect(Context* c) +void collect(Context* c) { - if (limitExceeded(c, c->pendingAllocation) - or oversizedGen2(c) + if (limitExceeded(c, c->pendingAllocation) or oversizedGen2(c) or c->tenureFootprint + c->tenurePadding > c->gen2.remaining() or c->fixieTenureFootprint + c->tenuredFixieFootprint - > c->tenuredFixieCeiling) - { + > c->tenuredFixieCeiling) { if (Verbose) { if (limitExceeded(c, c->pendingAllocation)) { fprintf(stderr, "low memory causes "); } else if (oversizedGen2(c)) { fprintf(stderr, "oversized gen2 causes "); - } else if (c->tenureFootprint + c->tenurePadding > c->gen2.remaining()) - { + } else if (c->tenureFootprint + c->tenurePadding > c->gen2.remaining()) { fprintf(stderr, "undersized gen2 causes "); } else { fprintf(stderr, "fixie ceiling causes "); @@ -1801,8 +1863,7 @@ collect(Context* c) } } -void* -allocate(Context* c, unsigned size, bool limit) +void* allocate(Context* c, unsigned size, bool limit) { ACQUIRE(c->lock); @@ -1814,7 +1875,7 @@ allocate(Context* c, unsigned size, bool limit) void* p = c->system->tryAllocate(size); if (p) { c->count += size; - + if (DebugAllocation) { static_cast(p)[0] = 0x22377322; static_cast(p)[(size / BytesPerWord) - 1] = 0x22377322; @@ -1827,14 +1888,12 @@ allocate(Context* c, unsigned size, bool limit) return 0; } -void* -tryAllocate(Context* c, unsigned size) +void* tryAllocate(Context* c, unsigned size) { return allocate(c, size, true); } -void* -allocate(Context* c, unsigned size) +void* allocate(Context* c, unsigned size) { void* p = allocate(c, size, false); expect(c->system, p); @@ -1842,8 +1901,7 @@ allocate(Context* c, unsigned size) return p; } -void -free(Context* c, const void* p, unsigned size) +void free(Context* c, const void* p, unsigned size) { ACQUIRE(c->lock); @@ -1856,8 +1914,9 @@ free(Context* c, const void* p, unsigned size) expect(c->system, static_cast(p)[0] == 0x22377322); - expect(c->system, static_cast(p) - [(size / BytesPerWord) - 1] == 0x22377322); + expect(c->system, + static_cast(p)[(size / BytesPerWord) - 1] + == 0x22377322); } expect(c->system, c->count >= size); @@ -1866,53 +1925,61 @@ free(Context* c, const void* p, unsigned size) c->count -= size; } -void -free_(Context* c, const void* p, unsigned size) +void free_(Context* c, const void* p, unsigned size) { free(c, p, size); } -class MyHeap: public Heap { +class MyHeap : public Heap { public: - MyHeap(System* system, unsigned limit): - c(system, limit) - { } + MyHeap(System* system, unsigned limit) : c(system, limit) + { + } - virtual void setClient(Heap::Client* client) { - assert(&c, c.client == 0); + virtual void setClient(Heap::Client* client) + { + assertT(&c, c.client == 0); c.client = client; } - virtual void setImmortalHeap(uintptr_t* start, unsigned sizeInWords) { + virtual void setImmortalHeap(uintptr_t* start, unsigned sizeInWords) + { c.immortalHeapStart = start; c.immortalHeapEnd = start + sizeInWords; } - virtual unsigned remaining() { + virtual unsigned remaining() + { return c.limit - c.count; } - virtual unsigned limit() { + virtual unsigned limit() + { return c.limit; } - virtual bool limitExceeded(int pendingAllocation = 0) { + virtual bool limitExceeded(int pendingAllocation = 0) + { return local::limitExceeded(&c, pendingAllocation); } - virtual void* tryAllocate(unsigned size) { + virtual void* tryAllocate(unsigned size) + { return local::tryAllocate(&c, size); } - virtual void* allocate(unsigned size) { + virtual void* allocate(unsigned size) + { return local::allocate(&c, size); } - virtual void free(const void* p, unsigned size) { + virtual void free(const void* p, unsigned size) + { free_(&c, p, size); } - virtual void collect(CollectionType type, unsigned incomingFootprint, + virtual void collect(CollectionType type, + unsigned incomingFootprint, int pendingAllocation) { c.mode = type; @@ -1922,12 +1989,16 @@ class MyHeap: public Heap { local::collect(&c); } - virtual unsigned fixedFootprint(unsigned sizeInWords, bool objectMask) { + virtual unsigned fixedFootprint(unsigned sizeInWords, bool objectMask) + { return Fixie::totalSize(sizeInWords, objectMask); } - void* allocateFixed(Allocator* allocator, unsigned sizeInWords, - bool objectMask, Fixie** handle, bool immortal) + void* allocateFixed(Allocator* allocator, + unsigned sizeInWords, + bool objectMask, + Fixie** handle, + bool immortal) { expect(&c, not limitExceeded()); @@ -1937,24 +2008,27 @@ class MyHeap: public Heap { expect(&c, not limitExceeded()); return (new (p) Fixie(&c, sizeInWords, objectMask, handle, immortal)) - ->body(); + ->body(); } - virtual void* allocateFixed(Allocator* allocator, unsigned sizeInWords, + virtual void* allocateFixed(Allocator* allocator, + unsigned sizeInWords, bool objectMask) { - return allocateFixed - (allocator, sizeInWords, objectMask, &(c.fixies), false); + return allocateFixed( + allocator, sizeInWords, objectMask, &(c.fixies), false); } virtual void* allocateImmortalFixed(Allocator* allocator, - unsigned sizeInWords, bool objectMask) + unsigned sizeInWords, + bool objectMask) { return allocateFixed(allocator, sizeInWords, objectMask, 0, true); } - bool needsMark(void* p) { - assert(&c, c.client->isFixed(p) or (not immortalHeapContains(&c, p))); + bool needsMark(void* p) + { + assertT(&c, c.client->isFixed(p) or (not immortalHeapContains(&c, p))); if (c.client->isFixed(p)) { return fixie(p)->age >= FixieTenureThreshold; @@ -1963,16 +2037,17 @@ class MyHeap: public Heap { } } - bool targetNeedsMark(void* target) { - return target - and not c.gen2.contains(target) - and not c.nextGen2.contains(target) - and not immortalHeapContains(&c, target) - and not (c.client->isFixed(target) - and fixie(target)->age >= FixieTenureThreshold); + bool targetNeedsMark(void* target) + { + return target and not c.gen2.contains(target) + and not c.nextGen2.contains(target) + and not immortalHeapContains(&c, target) + and not(c.client->isFixed(target) + and fixie(target)->age >= FixieTenureThreshold); } - virtual void mark(void* p, unsigned offset, unsigned count) { + virtual void mark(void* p, unsigned offset, unsigned count) + { if (needsMark(p)) { #ifndef USE_ATOMIC_OPERATIONS ACQUIRE(c.lock); @@ -1980,15 +2055,19 @@ class MyHeap: public Heap { if (c.client->isFixed(p)) { Fixie* f = fixie(p); - assert(&c, offset == 0 or f->hasMask()); + assertT(&c, offset == 0 or f->hasMask()); bool dirty = false; for (unsigned i = 0; i < count; ++i) { void** target = static_cast(p) + offset + i; if (targetNeedsMark(maskAlignedPointer(*target))) { if (DebugFixies) { - fprintf(stderr, "dirty fixie %p at %d (%p): %p\n", - f, offset, f->body() + offset, maskAlignedPointer(*target)); + fprintf(stderr, + "dirty fixie %p at %d (%p): %p\n", + f, + offset, + f->body() + offset, + maskAlignedPointer(*target)); } dirty = true; @@ -1997,17 +2076,18 @@ class MyHeap: public Heap { #else markBit(f->mask(), offset + i); #endif - assert(&c, getBit(f->mask(), offset + i)); + assertT(&c, getBit(f->mask(), offset + i)); } } - if (dirty) markDirty(&c, f); + if (dirty) + markDirty(&c, f); } else { Segment::Map* map; if (c.gen2.contains(p)) { map = &(c.heapMap); } else { - assert(&c, c.nextGen2.contains(p)); + assertT(&c, c.nextGen2.contains(p)); map = &(c.nextHeapMap); } @@ -2025,28 +2105,33 @@ class MyHeap: public Heap { } } - virtual void pad(void* p) { + virtual void pad(void* p) + { if (c.gen1.contains(p)) { if (c.ageMap.get(p) == TenureThreshold) { - ++ c.tenurePadding; + ++c.tenurePadding; } else { - ++ c.gen1Padding; + ++c.gen1Padding; } } else if (c.gen2.contains(p)) { - ++ c.gen2Padding; + ++c.gen2Padding; } else { - ++ c.gen1Padding; + ++c.gen1Padding; } } - virtual void* follow(void* p) { + virtual void* follow(void* p) + { if (p == 0 or c.client->isFixed(p)) { return p; } else if (wasCollected(&c, p)) { if (Debug) { - fprintf(stderr, "follow %p (%s) to %p (%s)\n", - p, segment(&c, p), - local::follow(&c, p), segment(&c, local::follow(&c, p))); + fprintf(stderr, + "follow %p (%s) to %p (%s)\n", + p, + segment(&c, p), + local::follow(&c, p), + segment(&c, local::follow(&c, p))); } return local::follow(&c, p); @@ -2055,30 +2140,29 @@ class MyHeap: public Heap { } } - virtual void postVisit() { + virtual void postVisit() + { killFixies(&c); } - virtual Status status(void* p) { + virtual Status status(void* p) + { p = maskAlignedPointer(p); if (p == 0) { return Null; } else if (c.client->isFixed(p)) { Fixie* f = fixie(p); - return f->dead() - ? Unreachable - : (static_cast(f->age + 1) < FixieTenureThreshold - ? Reachable - : Tenured); + return f->dead() ? Unreachable : (static_cast(f->age + 1) + < FixieTenureThreshold + ? Reachable + : Tenured); } else if (c.nextGen1.contains(p)) { return Reachable; - } else if (c.nextGen2.contains(p) - or immortalHeapContains(&c, p) + } else if (c.nextGen2.contains(p) or immortalHeapContains(&c, p) or (c.gen2.contains(p) and (c.mode == Heap::MinorCollection - or c.gen2.indexOf(p) >= c.gen2Base))) - { + or c.gen2.indexOf(p) >= c.gen2Base))) { return Tenured; } else if (wasCollected(&c, p)) { return Reachable; @@ -2087,34 +2171,36 @@ class MyHeap: public Heap { } } - virtual CollectionType collectionType() { + virtual CollectionType collectionType() + { return c.mode; } - virtual void disposeFixies() { + virtual void disposeFixies() + { c.disposeFixies(); } - virtual void dispose() { + virtual void dispose() + { c.dispose(); - assert(&c, c.count == 0); + assertT(&c, c.count == 0); c.system->free(this); } Context c; }; -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -Heap* -makeHeap(System* system, unsigned limit) -{ +Heap* makeHeap(System* system, unsigned limit) +{ return new (system->tryAllocate(sizeof(local::MyHeap))) - local::MyHeap(system, limit); + local::MyHeap(system, limit); } -} // namespace vm +} // namespace vm diff --git a/src/heapdump.cpp b/src/heapdump.cpp index 22a34f67c2..f729c10ef5 100644 --- a/src/heapdump.cpp +++ b/src/heapdump.cpp @@ -17,62 +17,55 @@ namespace { namespace local { -enum { - Root, - Size, - ClassName, - Push, - Pop -}; +enum { Root, Size, ClassName, Push, Pop }; -void -write1(FILE* out, uint8_t v) +void write1(FILE* out, uint8_t v) { size_t n UNUSED = fwrite(&v, 1, 1, out); } -void -write4(FILE* out, uint32_t v) +void write4(FILE* out, uint32_t v) { - uint8_t b[] = { static_cast( v >> 24 ), - static_cast((v >> 16) & 0xFF), - static_cast((v >> 8) & 0xFF), - static_cast( v & 0xFF) }; + uint8_t b[] = {static_cast(v >> 24), + static_cast((v >> 16) & 0xFF), + static_cast((v >> 8) & 0xFF), + static_cast(v & 0xFF)}; size_t n UNUSED = fwrite(b, 4, 1, out); } -void -writeString(FILE* out, int8_t* p, unsigned size) +void writeString(FILE* out, int8_t* p, unsigned size) { write4(out, size); size_t n UNUSED = fwrite(p, size, 1, out); } -unsigned -objectSize(Thread* t, object o) +unsigned objectSize(Thread* t, object o) { return extendedSize(t, o, baseSize(t, o, objectClass(t, o))); } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -void -dumpHeap(Thread* t, FILE* out) +void dumpHeap(Thread* t, FILE* out) { - class Visitor: public HeapVisitor { + class Visitor : public HeapVisitor { public: - Visitor(Thread* t, FILE* out): t(t), out(out), nextNumber(1) { } - - virtual void root() { - write1(out, local::Root); + Visitor(Thread* t, FILE* out) : t(t), out(out), nextNumber(1) + { } - virtual unsigned visitNew(object p) { + virtual void root() + { + write1(out, local::Root); + } + + virtual unsigned visitNew(object p) + { if (p) { unsigned number = nextNumber++; local::write4(out, number); @@ -80,12 +73,12 @@ dumpHeap(Thread* t, FILE* out) local::write1(out, local::Size); local::write4(out, local::objectSize(t, p)); - if (objectClass(t, p) == type(t, Machine::ClassType)) { + if (objectClass(t, p) == type(t, GcClass::Type)) { object name = className(t, p); if (name) { local::write1(out, local::ClassName); - local::writeString(out, &byteArrayBody(t, name, 0), - byteArrayLength(t, name) - 1); + local::writeString( + out, &byteArrayBody(t, name, 0), byteArrayLength(t, name) - 1); } } @@ -95,15 +88,18 @@ dumpHeap(Thread* t, FILE* out) } } - virtual void visitOld(object, unsigned number) { - local::write4(out, number); + virtual void visitOld(object, unsigned number) + { + local::write4(out, number); } - virtual void push(object, unsigned, unsigned) { + virtual void push(object, unsigned, unsigned) + { local::write1(out, local::Push); } - virtual void pop() { + virtual void pop() + { local::write1(out, local::Pop); } @@ -117,4 +113,4 @@ dumpHeap(Thread* t, FILE* out) w->dispose(); } -} // namespace vm +} // namespace vm diff --git a/src/heapwalk.cpp b/src/heapwalk.cpp index d40f568104..4aca3259d5 100644 --- a/src/heapwalk.cpp +++ b/src/heapwalk.cpp @@ -21,7 +21,7 @@ const uintptr_t PointerShift = log(BytesPerWord); class Context; -class Set: public HeapMap { +class Set : public HeapMap { public: class Entry { public: @@ -30,23 +30,22 @@ class Set: public HeapMap { int next; }; - static unsigned footprint(unsigned capacity) { - return sizeof(Set) - + pad(sizeof(int) * capacity) - + pad(sizeof(Set::Entry) * capacity); + static unsigned footprint(unsigned capacity) + { + return sizeof(Set) + pad(sizeof(int) * capacity) + + pad(sizeof(Set::Entry) * capacity); } - Set(Context* context, unsigned capacity): - context(context), - index(reinterpret_cast - (reinterpret_cast(this) - + sizeof(Set))), - entries(reinterpret_cast - (reinterpret_cast(index) - + pad(sizeof(int) * capacity))), - size(0), - capacity(capacity) - { } + Set(Context* context, unsigned capacity) + : context(context), + index(reinterpret_cast(reinterpret_cast(this) + + sizeof(Set))), + entries(reinterpret_cast(reinterpret_cast(index) + + pad(sizeof(int) * capacity))), + size(0), + capacity(capacity) + { + } virtual int find(object value); @@ -69,7 +68,9 @@ class Stack { static const unsigned Capacity = 4096; - Stack(Stack* next): next(next), entryCount(0) { } + Stack(Stack* next) : next(next), entryCount(0) + { + } Stack* next; unsigned entryCount; @@ -78,11 +79,12 @@ class Stack { class Context { public: - Context(Thread* thread): - thread(thread), objects(0), stack(0) - { } + Context(Thread* thread) : thread(thread), objects(0), stack(0) + { + } - void dispose() { + void dispose() + { if (objects) { objects->dispose(); } @@ -99,20 +101,18 @@ class Context { Stack* stack; }; -void -push(Context* c, object p, int offset) +void push(Context* c, object p, int offset) { if (c->stack == 0 or c->stack->entryCount == Stack::Capacity) { c->stack = new (c->thread->m->heap->allocate(sizeof(Stack))) - Stack(c->stack); + Stack(c->stack); } Stack::Entry* e = c->stack->entries + (c->stack->entryCount++); e->value = p; e->offset = offset; } -bool -pop(Context* c, object* p, int* offset) +bool pop(Context* c, object* p, int* offset) { if (c->stack) { if (c->stack->entryCount == 0) { @@ -133,17 +133,15 @@ pop(Context* c, object* p, int* offset) } } -unsigned -hash(object p, unsigned capacity) +unsigned hash(object p, unsigned capacity) { - return (reinterpret_cast(p) >> PointerShift) - & (capacity - 1); + return (reinterpret_cast(p) >> PointerShift) & (capacity - 1); } -Set::Entry* -find(Context* c, object p) +Set::Entry* find(Context* c, object p) { - if (c->objects == 0) return 0; + if (c->objects == 0) + return 0; for (int i = c->objects->index[hash(p, c->objects->capacity)]; i >= 0;) { Set::Entry* e = c->objects->entries + i; @@ -156,8 +154,7 @@ find(Context* c, object p) return 0; } -int -Set::find(object value) +int Set::find(object value) { Set::Entry* e = local::find(context, value); if (e) { @@ -167,16 +164,14 @@ Set::find(object value) } } -void -Set::dispose() +void Set::dispose() { context->thread->m->heap->free(this, footprint(capacity)); } -Set::Entry* -add(Context* c UNUSED, Set* set, object p, uint32_t number) +Set::Entry* add(Context* c UNUSED, Set* set, object p, uint32_t number) { - assert(c->thread, set->size < set->capacity); + assertT(c->thread, set->size < set->capacity); unsigned index = hash(p, set->capacity); @@ -189,19 +184,18 @@ add(Context* c UNUSED, Set* set, object p, uint32_t number) return e; } -Set::Entry* -add(Context* c, object p) +Set::Entry* add(Context* c, object p) { if (c->objects == 0 or c->objects->size == c->objects->capacity) { unsigned capacity; if (c->objects) { capacity = c->objects->capacity * 2; } else { - capacity = 4096; // must be power of two + capacity = 4096; // must be power of two } Set* set = new (c->thread->m->heap->allocate(Set::footprint(capacity))) - Set(c, capacity); + Set(c, capacity); memset(set->index, 0xFF, sizeof(int) * capacity); @@ -214,8 +208,8 @@ add(Context* c, object p) } } - c->thread->m->heap->free - (c->objects, Set::footprint(c->objects->capacity)); + c->thread->m->heap->free(c->objects, + Set::footprint(c->objects->capacity)); } c->objects = set; @@ -224,16 +218,13 @@ add(Context* c, object p) return add(c, c->objects, p, 0); } -inline object -get(object o, unsigned offsetInWords) +inline object get(object o, unsigned offsetInWords) { - return static_cast - (maskAlignedPointer - (fieldAtOffset(o, offsetInWords * BytesPerWord))); + return static_cast(maskAlignedPointer( + fieldAtOffset(o, offsetInWords * BytesPerWord))); } -unsigned -walk(Context* c, HeapVisitor* v, object p) +unsigned walk(Context* c, HeapVisitor* v, object p) { Thread* t = c->thread; object root = p; @@ -241,65 +232,70 @@ walk(Context* c, HeapVisitor* v, object p) v->root(); - visit: { - Set::Entry* e = find(c, p); - if (e) { - v->visitOld(p, e->number); - } else { - e = add(c, p); - e->number = v->visitNew(p); +visit : { + Set::Entry* e = find(c, p); + if (e) { + v->visitOld(p, e->number); + } else { + e = add(c, p); + e->number = v->visitNew(p); - nextChildOffset = walkNext(t, p, -1); - if (nextChildOffset != -1) { - goto children; - } + nextChildOffset = walkNext(t, p, -1); + if (nextChildOffset != -1) { + goto children; } } +} goto pop; - children: { - v->push(p, find(c, p)->number, nextChildOffset); - push(c, p, nextChildOffset); - p = get(p, nextChildOffset); - goto visit; - } +children : { + v->push(p, find(c, p)->number, nextChildOffset); + push(c, p, nextChildOffset); + p = get(p, nextChildOffset); + goto visit; +} - pop: { - if (pop(c, &p, &nextChildOffset)) { - v->pop(); - nextChildOffset = walkNext(t, p, nextChildOffset); - if (nextChildOffset >= 0) { - goto children; - } else { - goto pop; - } +pop : { + if (pop(c, &p, &nextChildOffset)) { + v->pop(); + nextChildOffset = walkNext(t, p, nextChildOffset); + if (nextChildOffset >= 0) { + goto children; + } else { + goto pop; } } +} return find(c, root)->number; } -class MyHeapWalker: public HeapWalker { +class MyHeapWalker : public HeapWalker { public: - MyHeapWalker(Thread* t, HeapVisitor* v): - context(t), visitor(v) + MyHeapWalker(Thread* t, HeapVisitor* v) : context(t), visitor(v) { add(&context, 0)->number = v->visitNew(0); } - virtual unsigned visitRoot(object root) { + virtual unsigned visitRoot(object root) + { return walk(&context, visitor, root); } - virtual void visitAllRoots() { - class Visitor: public Heap::Visitor { + virtual void visitAllRoots() + { + class Visitor : public Heap::Visitor { public: - Visitor(Context* c, HeapVisitor* v): c(c), v(v) { } + Visitor(Context* c, HeapVisitor* v) : c(c), v(v) + { + } - virtual void visit(void* p) { - walk(c, v, static_cast - (maskAlignedPointer(*static_cast(p)))); + virtual void visit(void* p) + { + walk(c, + v, + static_cast(maskAlignedPointer(*static_cast(p)))); } Context* c; @@ -309,11 +305,13 @@ class MyHeapWalker: public HeapWalker { visitRoots(context.thread->m, &v); } - virtual HeapMap* map() { + virtual HeapMap* map() + { return context.objects; } - virtual void dispose() { + virtual void dispose() + { context.dispose(); context.thread->m->heap->free(this, sizeof(MyHeapWalker)); } @@ -322,17 +320,16 @@ class MyHeapWalker: public HeapWalker { HeapVisitor* visitor; }; -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -HeapWalker* -makeHeapWalker(Thread* t, HeapVisitor* v) +HeapWalker* makeHeapWalker(Thread* t, HeapVisitor* v) { return new (t->m->heap->allocate(sizeof(local::MyHeapWalker))) - local::MyHeapWalker(t, v); + local::MyHeapWalker(t, v); } -} // namespace vm +} // namespace vm diff --git a/src/interpret.cpp b/src/interpret.cpp index 46c3fcfaed..b1f5a648fe 100644 --- a/src/interpret.cpp +++ b/src/interpret.cpp @@ -32,60 +32,56 @@ const unsigned FrameMethodOffset = 2; const unsigned FrameIpOffset = 3; const unsigned FrameFootprint = 4; -class Thread: public vm::Thread { +class Thread : public vm::Thread { public: - - Thread(Machine* m, object javaThread, vm::Thread* parent): - vm::Thread(m, javaThread, parent), - ip(0), - sp(0), - frame(-1), - code(0), - stackPointers(0) - { } + Thread(Machine* m, GcThread* javaThread, vm::Thread* parent) + : vm::Thread(m, javaThread, parent), + ip(0), + sp(0), + frame(-1), + code(0), + stackPointers(0) + { + } unsigned ip; unsigned sp; int frame; - object code; + GcCode* code; List* stackPointers; uintptr_t stack[0]; }; -inline void -pushObject(Thread* t, object o) +inline void pushObject(Thread* t, object o) { if (DebugStack) { fprintf(stderr, "push object %p at %d\n", o, t->sp); } - assert(t, t->sp + 1 < stackSizeInWords(t) / 2); - t->stack[(t->sp * 2) ] = ObjectTag; + assertT(t, t->sp + 1 < stackSizeInWords(t) / 2); + t->stack[(t->sp * 2)] = ObjectTag; t->stack[(t->sp * 2) + 1] = reinterpret_cast(o); - ++ t->sp; + ++t->sp; } -inline void -pushInt(Thread* t, uint32_t v) +inline void pushInt(Thread* t, uint32_t v) { if (DebugStack) { fprintf(stderr, "push int %d at %d\n", v, t->sp); } - assert(t, t->sp + 1 < stackSizeInWords(t) / 2); - t->stack[(t->sp * 2) ] = IntTag; + assertT(t, t->sp + 1 < stackSizeInWords(t) / 2); + t->stack[(t->sp * 2)] = IntTag; t->stack[(t->sp * 2) + 1] = v; - ++ t->sp; + ++t->sp; } -inline void -pushFloat(Thread* t, float v) +inline void pushFloat(Thread* t, float v) { pushInt(t, floatToBits(v)); } -inline void -pushLong(Thread* t, uint64_t v) +inline void pushLong(Thread* t, uint64_t v) { if (DebugStack) { fprintf(stderr, "push long %" LLD " at %d\n", v, t->sp); @@ -95,50 +91,48 @@ pushLong(Thread* t, uint64_t v) pushInt(t, v & 0xFFFFFFFF); } -inline void -pushDouble(Thread* t, double v) +inline void pushDouble(Thread* t, double v) { uint64_t w = doubleToBits(v); pushLong(t, w); } -inline object -popObject(Thread* t) +inline object popObject(Thread* t) { if (DebugStack) { - fprintf(stderr, "pop object %p at %d\n", + fprintf(stderr, + "pop object %p at %d\n", reinterpret_cast(t->stack[((t->sp - 1) * 2) + 1]), t->sp - 1); } - assert(t, t->stack[(t->sp - 1) * 2] == ObjectTag); - return reinterpret_cast(t->stack[((-- t->sp) * 2) + 1]); + assertT(t, t->stack[(t->sp - 1) * 2] == ObjectTag); + return reinterpret_cast(t->stack[((--t->sp) * 2) + 1]); } -inline uint32_t -popInt(Thread* t) +inline uint32_t popInt(Thread* t) { if (DebugStack) { - fprintf(stderr, "pop int %" ULD " at %d\n", + fprintf(stderr, + "pop int %" ULD " at %d\n", t->stack[((t->sp - 1) * 2) + 1], t->sp - 1); } - assert(t, t->stack[(t->sp - 1) * 2] == IntTag); - return t->stack[((-- t->sp) * 2) + 1]; + assertT(t, t->stack[(t->sp - 1) * 2] == IntTag); + return t->stack[((--t->sp) * 2) + 1]; } -inline float -popFloat(Thread* t) +inline float popFloat(Thread* t) { return bitsToFloat(popInt(t)); } -inline uint64_t -popLong(Thread* t) +inline uint64_t popLong(Thread* t) { if (DebugStack) { - fprintf(stderr, "pop long %" LLD " at %d\n", + fprintf(stderr, + "pop long %" LLD " at %d\n", (static_cast(t->stack[((t->sp - 2) * 2) + 1]) << 32) | static_cast(t->stack[((t->sp - 1) * 2) + 1]), t->sp - 2); @@ -149,57 +143,53 @@ popLong(Thread* t) return (b << 32) | a; } -inline double -popDouble(Thread* t) +inline double popDouble(Thread* t) { uint64_t v = popLong(t); return bitsToDouble(v); } -inline object -peekObject(Thread* t, unsigned index) +inline object peekObject(Thread* t, unsigned index) { if (DebugStack) { - fprintf(stderr, "peek object %p at %d\n", + fprintf(stderr, + "peek object %p at %d\n", reinterpret_cast(t->stack[(index * 2) + 1]), index); } - assert(t, index < stackSizeInWords(t) / 2); - assert(t, t->stack[index * 2] == ObjectTag); + assertT(t, index < stackSizeInWords(t) / 2); + assertT(t, t->stack[index * 2] == ObjectTag); return reinterpret_cast(t->stack[(index * 2) + 1]); } -inline uint32_t -peekInt(Thread* t, unsigned index) +inline uint32_t peekInt(Thread* t, unsigned index) { if (DebugStack) { - fprintf(stderr, "peek int %" ULD " at %d\n", - t->stack[(index * 2) + 1], - index); + fprintf( + stderr, "peek int %" ULD " at %d\n", t->stack[(index * 2) + 1], index); } - assert(t, index < stackSizeInWords(t) / 2); - assert(t, t->stack[index * 2] == IntTag); + assertT(t, index < stackSizeInWords(t) / 2); + assertT(t, t->stack[index * 2] == IntTag); return t->stack[(index * 2) + 1]; } -inline uint64_t -peekLong(Thread* t, unsigned index) +inline uint64_t peekLong(Thread* t, unsigned index) { if (DebugStack) { - fprintf(stderr, "peek long %" LLD " at %d\n", + fprintf(stderr, + "peek long %" LLD " at %d\n", (static_cast(t->stack[(index * 2) + 1]) << 32) | static_cast(t->stack[((index + 1) * 2) + 1]), index); } return (static_cast(peekInt(t, index)) << 32) - | static_cast(peekInt(t, index + 1)); + | static_cast(peekInt(t, index + 1)); } -inline void -pokeObject(Thread* t, unsigned index, object value) +inline void pokeObject(Thread* t, unsigned index, object value) { if (DebugStack) { fprintf(stderr, "poke object %p at %d\n", value, index); @@ -209,8 +199,7 @@ pokeObject(Thread* t, unsigned index, object value) t->stack[(index * 2) + 1] = reinterpret_cast(value); } -inline void -pokeInt(Thread* t, unsigned index, uint32_t value) +inline void pokeInt(Thread* t, unsigned index, uint32_t value) { if (DebugStack) { fprintf(stderr, "poke int %d at %d\n", value, index); @@ -220,8 +209,7 @@ pokeInt(Thread* t, unsigned index, uint32_t value) t->stack[(index * 2) + 1] = value; } -inline void -pokeLong(Thread* t, unsigned index, uint64_t value) +inline void pokeLong(Thread* t, unsigned index, uint64_t value) { if (DebugStack) { fprintf(stderr, "poke long %" LLD " at %d\n", value, index); @@ -231,8 +219,7 @@ pokeLong(Thread* t, unsigned index, uint64_t value) pokeInt(t, index + 1, value & 0xFFFFFFFF); } -inline object* -pushReference(Thread* t, object o) +inline object* pushReference(Thread* t, object o) { if (o) { expect(t, t->sp + 1 < stackSizeInWords(t) / 2); @@ -243,85 +230,74 @@ pushReference(Thread* t, object o) } } -inline int -frameNext(Thread* t, int frame) +inline int frameNext(Thread* t, int frame) { return peekInt(t, frame + FrameNextOffset); } -inline object -frameMethod(Thread* t, int frame) +inline GcMethod* frameMethod(Thread* t, int frame) { - return peekObject(t, frame + FrameMethodOffset); + return cast(t, peekObject(t, frame + FrameMethodOffset)); } -inline unsigned -frameIp(Thread* t, int frame) +inline unsigned frameIp(Thread* t, int frame) { return peekInt(t, frame + FrameIpOffset); } -inline unsigned -frameBase(Thread* t, int frame) +inline unsigned frameBase(Thread* t, int frame) { return peekInt(t, frame + FrameBaseOffset); } -inline object -localObject(Thread* t, unsigned index) +inline object localObject(Thread* t, unsigned index) { return peekObject(t, frameBase(t, t->frame) + index); } -inline uint32_t -localInt(Thread* t, unsigned index) +inline uint32_t localInt(Thread* t, unsigned index) { return peekInt(t, frameBase(t, t->frame) + index); } -inline uint64_t -localLong(Thread* t, unsigned index) +inline uint64_t localLong(Thread* t, unsigned index) { return peekLong(t, frameBase(t, t->frame) + index); } -inline void -setLocalObject(Thread* t, unsigned index, object value) +inline void setLocalObject(Thread* t, unsigned index, object value) { pokeObject(t, frameBase(t, t->frame) + index, value); } -inline void -setLocalInt(Thread* t, unsigned index, uint32_t value) +inline void setLocalInt(Thread* t, unsigned index, uint32_t value) { pokeInt(t, frameBase(t, t->frame) + index, value); } -inline void -setLocalLong(Thread* t, unsigned index, uint64_t value) +inline void setLocalLong(Thread* t, unsigned index, uint64_t value) { pokeLong(t, frameBase(t, t->frame) + index, value); } -void -pushFrame(Thread* t, object method) +void pushFrame(Thread* t, GcMethod* method) { PROTECT(t, method); - unsigned parameterFootprint = methodParameterFootprint(t, method); + unsigned parameterFootprint = method->parameterFootprint(); unsigned base = t->sp - parameterFootprint; unsigned locals = parameterFootprint; - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_SYNCHRONIZED) { // Try to acquire the monitor before doing anything else. // Otherwise, if we were to push the frame first, we risk trying // to release a monitor we never successfully acquired when we try // to pop the frame back off. - if (methodFlags(t, method) & ACC_STATIC) { - acquire(t, methodClass(t, method)); + if (method->flags() & ACC_STATIC) { + acquire(t, method->class_()); } else { acquire(t, peekObject(t, base)); - } + } } if (t->frame >= 0) { @@ -329,12 +305,13 @@ pushFrame(Thread* t, object method) } t->ip = 0; - if ((methodFlags(t, method) & ACC_NATIVE) == 0) { - t->code = methodCode(t, method); + if ((method->flags() & ACC_NATIVE) == 0) { + t->code = method->code(); - locals = codeMaxLocals(t, t->code); + locals = t->code->maxLocals(); - memset(t->stack + ((base + parameterFootprint) * 2), 0, + memset(t->stack + ((base + parameterFootprint) * 2), + 0, (locals - parameterFootprint) * BytesPerWord * 2); } @@ -349,23 +326,22 @@ pushFrame(Thread* t, object method) pokeInt(t, t->frame + FrameIpOffset, 0); } -void -popFrame(Thread* t) +void popFrame(Thread* t) { - object method = frameMethod(t, t->frame); + GcMethod* method = frameMethod(t, t->frame); - if (methodFlags(t, method) & ACC_SYNCHRONIZED) { - if (methodFlags(t, method) & ACC_STATIC) { - release(t, methodClass(t, method)); + if (method->flags() & ACC_SYNCHRONIZED) { + if (method->flags() & ACC_STATIC) { + release(t, method->class_()); } else { release(t, peekObject(t, frameBase(t, t->frame))); - } + } } t->sp = frameBase(t, t->frame); t->frame = frameNext(t, t->frame); if (t->frame >= 0) { - t->code = methodCode(t, frameMethod(t, t->frame)); + t->code = frameMethod(t, t->frame)->code(); t->ip = frameIp(t, t->frame); } else { t->code = 0; @@ -373,11 +349,14 @@ popFrame(Thread* t) } } -class MyStackWalker: public Processor::StackWalker { +class MyStackWalker : public Processor::StackWalker { public: - MyStackWalker(Thread* t, int frame): t(t), frame(frame) { } + MyStackWalker(Thread* t, int frame) : t(t), frame(frame) + { + } - virtual void walk(Processor::StackVisitor* v) { + virtual void walk(Processor::StackVisitor* v) + { for (int frame = this->frame; frame >= 0; frame = frameNext(t, frame)) { MyStackWalker walker(t, frame); if (not v->visit(&walker)) { @@ -386,18 +365,21 @@ class MyStackWalker: public Processor::StackWalker { } } - virtual object method() { + virtual GcMethod* method() + { return frameMethod(t, frame); } - virtual int ip() { + virtual int ip() + { return frameIp(t, frame); } - virtual unsigned count() { + virtual unsigned count() + { unsigned count = 0; for (int frame = this->frame; frame >= 0; frame = frameNext(t, frame)) { - ++ count; + ++count; } return count; } @@ -406,22 +388,16 @@ class MyStackWalker: public Processor::StackWalker { int frame; }; -inline void -checkStack(Thread* t, object method) +inline void checkStack(Thread* t, GcMethod* method) { - if (UNLIKELY(t->sp - + methodParameterFootprint(t, method) - + codeMaxLocals(t, methodCode(t, method)) - + FrameFootprint - + codeMaxStack(t, methodCode(t, method)) - > stackSizeInWords(t) / 2)) - { - throwNew(t, Machine::StackOverflowErrorType); + if (UNLIKELY(t->sp + method->parameterFootprint() + + method->code()->maxLocals() + FrameFootprint + + method->code()->maxStack() > stackSizeInWords(t) / 2)) { + throwNew(t, GcStackOverflowError::Type); } } -void -pushResult(Thread* t, unsigned returnCode, uint64_t result, bool indirect) +void pushResult(Thread* t, unsigned returnCode, uint64_t result, bool indirect) { switch (returnCode) { case ByteField: @@ -465,13 +441,19 @@ pushResult(Thread* t, unsigned returnCode, uint64_t result, bool indirect) case ObjectField: if (indirect) { if (DebugRun) { - fprintf(stderr, "result: %p at %p\n", - static_cast(result) == 0 ? 0 : - *reinterpret_cast(static_cast(result)), - reinterpret_cast(static_cast(result))); + fprintf( + stderr, + "result: %p at %p\n", + static_cast(result) == 0 + ? 0 + : *reinterpret_cast(static_cast(result)), + reinterpret_cast(static_cast(result))); } - pushObject(t, static_cast(result) == 0 ? 0 : - *reinterpret_cast(static_cast(result))); + pushObject( + t, + static_cast(result) == 0 + ? 0 + : *reinterpret_cast(static_cast(result))); } else { if (DebugRun) { fprintf(stderr, "result: %p\n", reinterpret_cast(result)); @@ -488,14 +470,16 @@ pushResult(Thread* t, unsigned returnCode, uint64_t result, bool indirect) } } -void -marshalArguments(Thread* t, uintptr_t* args, uint8_t* types, unsigned sp, - object method, bool fastCallingConvention) +void marshalArguments(Thread* t, + uintptr_t* args, + uint8_t* types, + unsigned sp, + GcMethod* method, + bool fastCallingConvention) { - MethodSpecIterator it - (t, reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0))); - + MethodSpecIterator it( + t, reinterpret_cast(method->spec()->body().begin())); + unsigned argOffset = 0; unsigned typeOffset = 0; @@ -533,23 +517,23 @@ marshalArguments(Thread* t, uintptr_t* args, uint8_t* types, unsigned sp, } } break; - default: abort(t); + default: + abort(t); } } } -unsigned -invokeNativeSlow(Thread* t, object method, void* function) +unsigned invokeNativeSlow(Thread* t, GcMethod* method, void* function) { PROTECT(t, method); pushFrame(t, method); - unsigned footprint = methodParameterFootprint(t, method) + 1; - if (methodFlags(t, method) & ACC_STATIC) { - ++ footprint; + unsigned footprint = method->parameterFootprint() + 1; + if (method->flags() & ACC_STATIC) { + ++footprint; } - unsigned count = methodParameterCount(t, method) + 2; + unsigned count = method->parameterCount() + 2; THREAD_RUNTIME_ARRAY(t, uintptr_t, args, footprint); unsigned argOffset = 0; @@ -559,15 +543,15 @@ invokeNativeSlow(Thread* t, object method, void* function) RUNTIME_ARRAY_BODY(args)[argOffset++] = reinterpret_cast(t); RUNTIME_ARRAY_BODY(types)[typeOffset++] = POINTER_TYPE; - object jclass = 0; + GcJclass* jclass = 0; PROTECT(t, jclass); unsigned sp; - if (methodFlags(t, method) & ACC_STATIC) { + if (method->flags() & ACC_STATIC) { sp = frameBase(t, t->frame); - jclass = getJClass(t, methodClass(t, method)); + jclass = getJClass(t, method->class_()); RUNTIME_ARRAY_BODY(args)[argOffset++] - = reinterpret_cast(&jclass); + = reinterpret_cast(&jclass); } else { sp = frameBase(t, t->frame); object* v = reinterpret_cast(t->stack + ((sp++) * 2) + 1); @@ -578,21 +562,26 @@ invokeNativeSlow(Thread* t, object method, void* function) } RUNTIME_ARRAY_BODY(types)[typeOffset++] = POINTER_TYPE; - marshalArguments - (t, RUNTIME_ARRAY_BODY(args) + argOffset, - RUNTIME_ARRAY_BODY(types) + typeOffset, sp, method, false); + marshalArguments(t, + RUNTIME_ARRAY_BODY(args) + argOffset, + RUNTIME_ARRAY_BODY(types) + typeOffset, + sp, + method, + false); - unsigned returnCode = methodReturnCode(t, method); + unsigned returnCode = method->returnCode(); unsigned returnType = fieldType(t, returnCode); uint64_t result; if (DebugRun) { - fprintf(stderr, "invoke native method %s.%s\n", - &byteArrayBody(t, className(t, methodClass(t, method)), 0), - &byteArrayBody(t, methodName(t, method), 0)); + fprintf(stderr, + "invoke native method %s.%s\n", + method->class_()->name()->body().begin(), + method->name()->body().begin()); } - - { ENTER(t, Thread::IdleState); + + { + ENTER(t, Thread::IdleState); bool noThrow = t->checkpoint->noThrow; t->checkpoint->noThrow = true; @@ -607,17 +596,16 @@ invokeNativeSlow(Thread* t, object method, void* function) } if (DebugRun) { - fprintf(stderr, "return from native method %s.%s\n", - &byteArrayBody - (t, className(t, methodClass(t, frameMethod(t, t->frame))), 0), - &byteArrayBody - (t, methodName(t, frameMethod(t, t->frame)), 0)); + fprintf(stderr, + "return from native method %s.%s\n", + frameMethod(t, t->frame)->class_()->name()->body().begin(), + frameMethod(t, t->frame)->name()->body().begin()); } popFrame(t); if (UNLIKELY(t->exception)) { - object exception = t->exception; + GcThrowable* exception = t->exception; t->exception = 0; throw_(t, exception); } @@ -627,90 +615,86 @@ invokeNativeSlow(Thread* t, object method, void* function) return returnCode; } -unsigned -invokeNative(Thread* t, object method) +unsigned invokeNative(Thread* t, GcMethod* method) { PROTECT(t, method); resolveNative(t, method); - object native = methodRuntimeDataNative(t, getMethodRuntimeData(t, method)); - if (nativeFast(t, native)) { + GcNative* native = getMethodRuntimeData(t, method)->native(); + if (native->fast()) { pushFrame(t, method); uint64_t result; - { THREAD_RESOURCE0(t, popFrame(static_cast(t))); + { + THREAD_RESOURCE0(t, popFrame(static_cast(t))); - unsigned footprint = methodParameterFootprint(t, method); + unsigned footprint = method->parameterFootprint(); THREAD_RUNTIME_ARRAY(t, uintptr_t, args, footprint); unsigned sp = frameBase(t, t->frame); unsigned argOffset = 0; - if ((methodFlags(t, method) & ACC_STATIC) == 0) { + if ((method->flags() & ACC_STATIC) == 0) { RUNTIME_ARRAY_BODY(args)[argOffset++] - = reinterpret_cast(peekObject(t, sp++)); + = reinterpret_cast(peekObject(t, sp++)); } - marshalArguments - (t, RUNTIME_ARRAY_BODY(args) + argOffset, 0, sp, method, true); + marshalArguments( + t, RUNTIME_ARRAY_BODY(args) + argOffset, 0, sp, method, true); - result = reinterpret_cast - (nativeFunction(t, native))(t, method, RUNTIME_ARRAY_BODY(args)); + result = reinterpret_cast(native->function())( + t, method, RUNTIME_ARRAY_BODY(args)); } - pushResult(t, methodReturnCode(t, method), result, false); + pushResult(t, method->returnCode(), result, false); - return methodReturnCode(t, method); + return method->returnCode(); } else { - return invokeNativeSlow(t, method, nativeFunction(t, native)); + return invokeNativeSlow(t, method, native->function()); } } -inline void -store(Thread* t, unsigned index) +inline void store(Thread* t, unsigned index) { memcpy(t->stack + ((frameBase(t, t->frame) + index) * 2), - t->stack + ((-- t->sp) * 2), + t->stack + ((--t->sp) * 2), BytesPerWord * 2); } -bool -isNaN(double v) +bool isNaN(double v) { return fpclassify(v) == FP_NAN; } -bool -isNaN(float v) +bool isNaN(float v) { return fpclassify(v) == FP_NAN; } -uint64_t -findExceptionHandler(Thread* t, object method, unsigned ip) +uint64_t findExceptionHandler(Thread* t, GcMethod* method, unsigned ip) { PROTECT(t, method); - object eht = codeExceptionHandlerTable(t, methodCode(t, method)); - + GcExceptionHandlerTable* eht = cast( + t, method->code()->exceptionHandlerTable()); + if (eht) { - for (unsigned i = 0; i < exceptionHandlerTableLength(t, eht); ++i) { - uint64_t eh = exceptionHandlerTableBody(t, eht, i); + for (unsigned i = 0; i < eht->length(); ++i) { + uint64_t eh = eht->body()[i]; if (ip - 1 >= exceptionHandlerStart(eh) - and ip - 1 < exceptionHandlerEnd(eh)) - { - object catchType = 0; + and ip - 1 < exceptionHandlerEnd(eh)) { + GcClass* catchType = 0; if (exceptionHandlerCatchType(eh)) { - object e = t->exception; + GcThrowable* e = t->exception; t->exception = 0; PROTECT(t, e); PROTECT(t, eht); - catchType = resolveClassInPool - (t, method, exceptionHandlerCatchType(eh) - 1); + catchType = resolveClassInPool( + t, method, exceptionHandlerCatchType(eh) - 1); if (catchType) { - eh = exceptionHandlerTableBody(t, eht, i); + eh = eht->body()[i]; t->exception = e; } else { // can't find what we're supposed to catch - move on. @@ -728,38 +712,36 @@ findExceptionHandler(Thread* t, object method, unsigned ip) return 0; } -uint64_t -findExceptionHandler(Thread* t, int frame) +uint64_t findExceptionHandler(Thread* t, int frame) { return findExceptionHandler(t, frameMethod(t, frame), frameIp(t, frame)); } -void -pushField(Thread* t, object target, object field) +void pushField(Thread* t, object target, GcField* field) { - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: - pushInt(t, fieldAtOffset(target, fieldOffset(t, field))); + pushInt(t, fieldAtOffset(target, field->offset())); break; case CharField: case ShortField: - pushInt(t, fieldAtOffset(target, fieldOffset(t, field))); + pushInt(t, fieldAtOffset(target, field->offset())); break; case FloatField: case IntField: - pushInt(t, fieldAtOffset(target, fieldOffset(t, field))); + pushInt(t, fieldAtOffset(target, field->offset())); break; case DoubleField: case LongField: - pushLong(t, fieldAtOffset(target, fieldOffset(t, field))); + pushLong(t, fieldAtOffset(target, field->offset())); break; case ObjectField: - pushObject(t, fieldAtOffset(target, fieldOffset(t, field))); + pushObject(t, fieldAtOffset(target, field->offset())); break; default: @@ -767,40 +749,41 @@ pushField(Thread* t, object target, object field) } } -void safePoint(Thread* t) { +void safePoint(Thread* t) +{ if (UNLIKELY(t->m->exclusive)) { ENTER(t, Thread::IdleState); } } -object -interpret3(Thread* t, const int base) +object interpret3(Thread* t, const int base) { unsigned instruction = nop; unsigned& ip = t->ip; unsigned& sp = t->sp; int& frame = t->frame; - object& code = t->code; - object& exception = t->exception; + GcCode*& code = t->code; + GcMethod* method = 0; + PROTECT(t, method); + GcThrowable*& exception = t->exception; uintptr_t* stack = t->stack; - code = methodCode(t, frameMethod(t, frame)); + code = frameMethod(t, frame)->code(); if (UNLIKELY(exception)) { goto throw_; } - loop: - instruction = codeBody(t, code, ip++); +loop: + instruction = code->body()[ip++]; if (DebugRun) { - fprintf(stderr, "ip: %d; instruction: 0x%x in %s.%s ", + fprintf(stderr, + "ip: %d; instruction: 0x%x in %s.%s ", ip - 1, instruction, - &byteArrayBody - (t, className(t, methodClass(t, frameMethod(t, frame))), 0), - &byteArrayBody - (t, methodName(t, frameMethod(t, frame)), 0)); + frameMethod(t, frame)->class_()->name()->body().begin(), + frameMethod(t, frame)->name()->body().begin()); int line = findLineNumber(t, frameMethod(t, frame), ip); switch (line) { @@ -821,21 +804,24 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < objectArrayLength(t, array))) - { + if (LIKELY(index >= 0 + and static_cast(index) + < objectArrayLength(t, array))) { pushObject(t, objectArrayBody(t, array, index)); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, objectArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + objectArrayLength(t, array)); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case aastore: { object value = popObject(t); @@ -843,61 +829,71 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < objectArrayLength(t, array))) - { - set(t, array, ArrayBody + (index * BytesPerWord), value); + if (LIKELY(index >= 0 + and static_cast(index) + < objectArrayLength(t, array))) { + setField(t, array, ArrayBody + (index * BytesPerWord), value); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, objectArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + objectArrayLength(t, array)); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case aconst_null: { pushObject(t, 0); - } goto loop; + } + goto loop; case aload: { - pushObject(t, localObject(t, codeBody(t, code, ip++))); - } goto loop; + pushObject(t, localObject(t, code->body()[ip++])); + } + goto loop; case aload_0: { pushObject(t, localObject(t, 0)); - } goto loop; + } + goto loop; case aload_1: { pushObject(t, localObject(t, 1)); - } goto loop; + } + goto loop; case aload_2: { pushObject(t, localObject(t, 2)); - } goto loop; + } + goto loop; case aload_3: { pushObject(t, localObject(t, 3)); - } goto loop; + } + goto loop; case anewarray: { int32_t count = popInt(t); if (LIKELY(count >= 0)) { uint16_t index = codeReadInt16(t, code, ip); - - object class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); - + + GcClass* class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); + pushObject(t, makeObjectArray(t, class_, count)); } else { - exception = makeThrowable - (t, Machine::NegativeArraySizeExceptionType, "%d", count); + exception + = makeThrowable(t, GcNegativeArraySizeException::Type, "%d", count); goto throw_; } - } goto loop; + } + goto loop; case areturn: { object result = popObject(t); @@ -908,80 +904,91 @@ interpret3(Thread* t, const int base) } else { return result; } - } goto loop; + } + goto loop; case arraylength: { object array = popObject(t); if (LIKELY(array)) { pushInt(t, fieldAtOffset(array, BytesPerWord)); } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case astore: { - store(t, codeBody(t, code, ip++)); - } goto loop; + store(t, code->body()[ip++]); + } + goto loop; case astore_0: { store(t, 0); - } goto loop; + } + goto loop; case astore_1: { store(t, 1); - } goto loop; + } + goto loop; case astore_2: { store(t, 2); - } goto loop; + } + goto loop; case astore_3: { store(t, 3); - } goto loop; + } + goto loop; case athrow: { - exception = popObject(t); + exception = cast(t, popObject(t)); if (UNLIKELY(exception == 0)) { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); } - } goto throw_; + } + goto throw_; case baload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (objectClass(t, array) == type(t, Machine::BooleanArrayType)) { - if (LIKELY(index >= 0 and - static_cast(index) - < booleanArrayLength(t, array))) - { - pushInt(t, booleanArrayBody(t, array, index)); + if (objectClass(t, array) == type(t, GcBooleanArray::Type)) { + GcBooleanArray* a = cast(t, array); + if (LIKELY(index >= 0 + and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, - "%d not in [0,%d)", index, booleanArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - if (LIKELY(index >= 0 and - static_cast(index) - < byteArrayLength(t, array))) - { - pushInt(t, byteArrayBody(t, array, index)); + GcByteArray* a = cast(t, array); + if (LIKELY(index >= 0 + and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, - "%d not in [0,%d)", index, byteArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case bastore: { int8_t value = popInt(t); @@ -989,60 +996,67 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (objectClass(t, array) == type(t, Machine::BooleanArrayType)) { - if (LIKELY(index >= 0 and - static_cast(index) - < booleanArrayLength(t, array))) - { - booleanArrayBody(t, array, index) = value; + if (objectClass(t, array) == type(t, GcBooleanArray::Type)) { + GcBooleanArray* a = cast(t, array); + if (LIKELY(index >= 0 + and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, - "%d not in [0,%d)", index, booleanArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - if (LIKELY(index >= 0 and - static_cast(index) < byteArrayLength(t, array))) - { - byteArrayBody(t, array, index) = value; + GcByteArray* a = cast(t, array); + if (LIKELY(index >= 0 + and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, - "%d not in [0,%d)", index, byteArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case bipush: { - pushInt(t, static_cast(codeBody(t, code, ip++))); - } goto loop; + pushInt(t, static_cast(code->body()[ip++])); + } + goto loop; case caload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < charArrayLength(t, array))) - { - pushInt(t, charArrayBody(t, array, index)); + GcCharArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, charArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case castore: { uint16_t value = popInt(t); @@ -1050,95 +1064,118 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < charArrayLength(t, array))) - { - charArrayBody(t, array, index) = value; + GcCharArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, charArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case checkcast: { uint16_t index = codeReadInt16(t, code, ip); if (peekObject(t, sp - 1)) { - object class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); - if (UNLIKELY(exception)) goto throw_; + GcClass* class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); + if (UNLIKELY(exception)) + goto throw_; if (not instanceOf(t, class_, peekObject(t, sp - 1))) { - exception = makeThrowable - (t, Machine::ClassCastExceptionType, "%s as %s", - &byteArrayBody - (t, className(t, objectClass(t, peekObject(t, sp - 1))), 0), - &byteArrayBody(t, className(t, class_), 0)); + exception = makeThrowable( + t, + GcClassCastException::Type, + "%s as %s", + objectClass(t, peekObject(t, sp - 1))->name()->body().begin(), + class_->name()->body().begin()); goto throw_; } } - } goto loop; + } + goto loop; case d2f: { pushFloat(t, static_cast(popDouble(t))); - } goto loop; + } + goto loop; case d2i: { double f = popDouble(t); switch (fpclassify(f)) { - case FP_NAN: pushInt(t, 0); break; - case FP_INFINITE: pushInt(t, signbit(f) ? INT32_MIN : INT32_MAX); break; - default: pushInt - (t, f >= INT32_MAX ? INT32_MAX - : (f <= INT32_MIN ? INT32_MIN : static_cast(f))); + case FP_NAN: + pushInt(t, 0); + break; + case FP_INFINITE: + pushInt(t, signbit(f) ? INT32_MIN : INT32_MAX); + break; + default: + pushInt(t, + f >= INT32_MAX + ? INT32_MAX + : (f <= INT32_MIN ? INT32_MIN : static_cast(f))); break; } - } goto loop; + } + goto loop; case d2l: { double f = popDouble(t); switch (fpclassify(f)) { - case FP_NAN: pushLong(t, 0); break; - case FP_INFINITE: pushLong(t, signbit(f) ? INT64_MIN : INT64_MAX); break; - default: pushLong - (t, f >= INT64_MAX ? INT64_MAX - : (f <= INT64_MIN ? INT64_MIN : static_cast(f))); + case FP_NAN: + pushLong(t, 0); + break; + case FP_INFINITE: + pushLong(t, signbit(f) ? INT64_MIN : INT64_MAX); + break; + default: + pushLong(t, + f >= INT64_MAX + ? INT64_MAX + : (f <= INT64_MIN ? INT64_MIN : static_cast(f))); break; } - } goto loop; + } + goto loop; case dadd: { double b = popDouble(t); double a = popDouble(t); - + pushDouble(t, a + b); - } goto loop; + } + goto loop; case daload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < doubleArrayLength(t, array))) - { - pushLong(t, doubleArrayBody(t, array, index)); + GcDoubleArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushLong(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, doubleArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case dastore: { double value = popDouble(t); @@ -1146,29 +1183,32 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < doubleArrayLength(t, array))) - { - memcpy(&doubleArrayBody(t, array, index), &value, sizeof(uint64_t)); + GcDoubleArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + memcpy(&a->body()[index], &value, sizeof(uint64_t)); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, doubleArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case dcmpg: { double b = popDouble(t); double a = popDouble(t); - + if (isNaN(a) or isNaN(b)) { pushInt(t, 1); - } if (a < b) { + } + if (a < b) { pushInt(t, static_cast(-1)); } else if (a > b) { pushInt(t, 1); @@ -1177,15 +1217,17 @@ interpret3(Thread* t, const int base) } else { pushInt(t, 1); } - } goto loop; + } + goto loop; case dcmpl: { double b = popDouble(t); double a = popDouble(t); - + if (isNaN(a) or isNaN(b)) { pushInt(t, static_cast(-1)); - } if (a < b) { + } + if (a < b) { pushInt(t, static_cast(-1)); } else if (a > b) { pushInt(t, 1); @@ -1194,90 +1236,102 @@ interpret3(Thread* t, const int base) } else { pushInt(t, static_cast(-1)); } - } goto loop; + } + goto loop; case dconst_0: { pushDouble(t, 0); - } goto loop; + } + goto loop; case dconst_1: { pushDouble(t, 1); - } goto loop; + } + goto loop; case ddiv: { double b = popDouble(t); double a = popDouble(t); - + pushDouble(t, a / b); - } goto loop; + } + goto loop; case dmul: { double b = popDouble(t); double a = popDouble(t); - + pushDouble(t, a * b); - } goto loop; + } + goto loop; case dneg: { double a = popDouble(t); - - pushDouble(t, - a); - } goto loop; + + pushDouble(t, -a); + } + goto loop; case vm::drem: { double b = popDouble(t); double a = popDouble(t); - + pushDouble(t, fmod(a, b)); - } goto loop; + } + goto loop; case dsub: { double b = popDouble(t); double a = popDouble(t); - + pushDouble(t, a - b); - } goto loop; + } + goto loop; case dup: { if (DebugStack) { fprintf(stderr, "dup\n"); } - memcpy(stack + ((sp ) * 2), stack + ((sp - 1) * 2), BytesPerWord * 2); - ++ sp; - } goto loop; + memcpy(stack + ((sp)*2), stack + ((sp - 1) * 2), BytesPerWord * 2); + ++sp; + } + goto loop; case dup_x1: { if (DebugStack) { fprintf(stderr, "dup_x1\n"); } - memcpy(stack + ((sp ) * 2), stack + ((sp - 1) * 2), BytesPerWord * 2); + memcpy(stack + ((sp)*2), stack + ((sp - 1) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 1) * 2), stack + ((sp - 2) * 2), BytesPerWord * 2); - memcpy(stack + ((sp - 2) * 2), stack + ((sp ) * 2), BytesPerWord * 2); - ++ sp; - } goto loop; + memcpy(stack + ((sp - 2) * 2), stack + ((sp)*2), BytesPerWord * 2); + ++sp; + } + goto loop; case dup_x2: { if (DebugStack) { fprintf(stderr, "dup_x2\n"); } - memcpy(stack + ((sp ) * 2), stack + ((sp - 1) * 2), BytesPerWord * 2); + memcpy(stack + ((sp)*2), stack + ((sp - 1) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 1) * 2), stack + ((sp - 2) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 2) * 2), stack + ((sp - 3) * 2), BytesPerWord * 2); - memcpy(stack + ((sp - 3) * 2), stack + ((sp ) * 2), BytesPerWord * 2); - ++ sp; - } goto loop; + memcpy(stack + ((sp - 3) * 2), stack + ((sp)*2), BytesPerWord * 2); + ++sp; + } + goto loop; case dup2: { if (DebugStack) { fprintf(stderr, "dup2\n"); } - memcpy(stack + ((sp ) * 2), stack + ((sp - 2) * 2), BytesPerWord * 4); + memcpy(stack + ((sp)*2), stack + ((sp - 2) * 2), BytesPerWord * 4); sp += 2; - } goto loop; + } + goto loop; case dup2_x1: { if (DebugStack) { @@ -1285,11 +1339,12 @@ interpret3(Thread* t, const int base) } memcpy(stack + ((sp + 1) * 2), stack + ((sp - 1) * 2), BytesPerWord * 2); - memcpy(stack + ((sp ) * 2), stack + ((sp - 2) * 2), BytesPerWord * 2); + memcpy(stack + ((sp)*2), stack + ((sp - 2) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 1) * 2), stack + ((sp - 3) * 2), BytesPerWord * 2); - memcpy(stack + ((sp - 3) * 2), stack + ((sp ) * 2), BytesPerWord * 4); + memcpy(stack + ((sp - 3) * 2), stack + ((sp)*2), BytesPerWord * 4); sp += 2; - } goto loop; + } + goto loop; case dup2_x2: { if (DebugStack) { @@ -1297,65 +1352,84 @@ interpret3(Thread* t, const int base) } memcpy(stack + ((sp + 1) * 2), stack + ((sp - 1) * 2), BytesPerWord * 2); - memcpy(stack + ((sp ) * 2), stack + ((sp - 2) * 2), BytesPerWord * 2); + memcpy(stack + ((sp)*2), stack + ((sp - 2) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 1) * 2), stack + ((sp - 3) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 2) * 2), stack + ((sp - 4) * 2), BytesPerWord * 2); - memcpy(stack + ((sp - 4) * 2), stack + ((sp ) * 2), BytesPerWord * 4); + memcpy(stack + ((sp - 4) * 2), stack + ((sp)*2), BytesPerWord * 4); sp += 2; - } goto loop; + } + goto loop; case f2d: { pushDouble(t, popFloat(t)); - } goto loop; + } + goto loop; case f2i: { float f = popFloat(t); switch (fpclassify(f)) { - case FP_NAN: pushInt(t, 0); break; - case FP_INFINITE: pushInt(t, signbit(f) ? INT32_MIN : INT32_MAX); break; - default: pushInt(t, f >= INT32_MAX ? INT32_MAX - : (f <= INT32_MIN ? INT32_MIN : static_cast(f))); + case FP_NAN: + pushInt(t, 0); + break; + case FP_INFINITE: + pushInt(t, signbit(f) ? INT32_MIN : INT32_MAX); + break; + default: + pushInt(t, + f >= INT32_MAX + ? INT32_MAX + : (f <= INT32_MIN ? INT32_MIN : static_cast(f))); break; } - } goto loop; + } + goto loop; case f2l: { float f = popFloat(t); switch (fpclassify(f)) { - case FP_NAN: pushLong(t, 0); break; - case FP_INFINITE: pushLong(t, signbit(f) ? INT64_MIN : INT64_MAX); + case FP_NAN: + pushLong(t, 0); + break; + case FP_INFINITE: + pushLong(t, signbit(f) ? INT64_MIN : INT64_MAX); + break; + default: + pushLong(t, static_cast(f)); break; - default: pushLong(t, static_cast(f)); break; } - } goto loop; + } + goto loop; case fadd: { float b = popFloat(t); float a = popFloat(t); - + pushFloat(t, a + b); - } goto loop; + } + goto loop; case faload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < floatArrayLength(t, array))) - { - pushInt(t, floatArrayBody(t, array, index)); + GcFloatArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, floatArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case fastore: { float value = popFloat(t); @@ -1363,29 +1437,32 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < floatArrayLength(t, array))) - { - memcpy(&floatArrayBody(t, array, index), &value, sizeof(uint32_t)); + GcFloatArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + memcpy(&a->body()[index], &value, sizeof(uint32_t)); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, floatArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case fcmpg: { float b = popFloat(t); float a = popFloat(t); - + if (isNaN(a) or isNaN(b)) { pushInt(t, 1); - } if (a < b) { + } + if (a < b) { pushInt(t, static_cast(-1)); } else if (a > b) { pushInt(t, 1); @@ -1394,15 +1471,17 @@ interpret3(Thread* t, const int base) } else { pushInt(t, 1); } - } goto loop; + } + goto loop; case fcmpl: { float b = popFloat(t); float a = popFloat(t); - + if (isNaN(a) or isNaN(b)) { pushInt(t, static_cast(-1)); - } if (a < b) { + } + if (a < b) { pushInt(t, static_cast(-1)); } else if (a > b) { pushInt(t, 1); @@ -1411,61 +1490,70 @@ interpret3(Thread* t, const int base) } else { pushInt(t, static_cast(-1)); } - } goto loop; + } + goto loop; case fconst_0: { pushFloat(t, 0); - } goto loop; + } + goto loop; case fconst_1: { pushFloat(t, 1); - } goto loop; + } + goto loop; case fconst_2: { pushFloat(t, 2); - } goto loop; + } + goto loop; case fdiv: { float b = popFloat(t); float a = popFloat(t); - + pushFloat(t, a / b); - } goto loop; + } + goto loop; case fmul: { float b = popFloat(t); float a = popFloat(t); - + pushFloat(t, a * b); - } goto loop; + } + goto loop; case fneg: { float a = popFloat(t); - - pushFloat(t, - a); - } goto loop; + + pushFloat(t, -a); + } + goto loop; case frem: { float b = popFloat(t); float a = popFloat(t); - + pushFloat(t, fmodf(a, b)); - } goto loop; + } + goto loop; case fsub: { float b = popFloat(t); float a = popFloat(t); - + pushFloat(t, a - b); - } goto loop; + } + goto loop; case getfield: { if (LIKELY(peekObject(t, sp - 1))) { uint16_t index = codeReadInt16(t, code, ip); - - object field = resolveField(t, frameMethod(t, frame), index - 1); - assert(t, (fieldFlags(t, field) & ACC_STATIC) == 0); + GcField* field = resolveField(t, frameMethod(t, frame), index - 1); + + assertT(t, (field->flags() & ACC_STATIC) == 0); PROTECT(t, field); @@ -1473,95 +1561,109 @@ interpret3(Thread* t, const int base) pushField(t, popObject(t), field); } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case getstatic: { uint16_t index = codeReadInt16(t, code, ip); - object field = resolveField(t, frameMethod(t, frame), index - 1); + GcField* field = resolveField(t, frameMethod(t, frame), index - 1); - assert(t, fieldFlags(t, field) & ACC_STATIC); + assertT(t, field->flags() & ACC_STATIC); PROTECT(t, field); - initClass(t, fieldClass(t, field)); + initClass(t, field->class_()); ACQUIRE_FIELD_FOR_READ(t, field); - pushField(t, classStaticTable(t, fieldClass(t, field)), field); - } goto loop; + pushField(t, field->class_()->staticTable(), field); + } + goto loop; case goto_: { int16_t offset = codeReadInt16(t, code, ip); ip = (ip - 3) + offset; - } goto back_branch; - + } + goto back_branch; + case goto_w: { int32_t offset = codeReadInt32(t, code, ip); ip = (ip - 5) + offset; - } goto back_branch; + } + goto back_branch; case i2b: { pushInt(t, static_cast(popInt(t))); - } goto loop; + } + goto loop; case i2c: { pushInt(t, static_cast(popInt(t))); - } goto loop; + } + goto loop; case i2d: { pushDouble(t, static_cast(static_cast(popInt(t)))); - } goto loop; + } + goto loop; case i2f: { pushFloat(t, static_cast(static_cast(popInt(t)))); - } goto loop; + } + goto loop; case i2l: { pushLong(t, static_cast(popInt(t))); - } goto loop; + } + goto loop; case i2s: { pushInt(t, static_cast(popInt(t))); - } goto loop; + } + goto loop; case iadd: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a + b); - } goto loop; + } + goto loop; case iaload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < intArrayLength(t, array))) - { - pushInt(t, intArrayBody(t, array, index)); + GcIntArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, intArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case iand: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a & b); - } goto loop; + } + goto loop; case iastore: { int32_t value = popInt(t); @@ -1569,149 +1671,167 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < intArrayLength(t, array))) - { - intArrayBody(t, array, index) = value; + GcIntArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, intArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case iconst_m1: { pushInt(t, static_cast(-1)); - } goto loop; + } + goto loop; case iconst_0: { pushInt(t, 0); - } goto loop; + } + goto loop; case iconst_1: { pushInt(t, 1); - } goto loop; + } + goto loop; case iconst_2: { pushInt(t, 2); - } goto loop; + } + goto loop; case iconst_3: { pushInt(t, 3); - } goto loop; + } + goto loop; case iconst_4: { pushInt(t, 4); - } goto loop; + } + goto loop; case iconst_5: { pushInt(t, 5); - } goto loop; + } + goto loop; case idiv: { int32_t b = popInt(t); int32_t a = popInt(t); if (UNLIKELY(b == 0)) { - exception = makeThrowable(t, Machine::ArithmeticExceptionType); + exception = makeThrowable(t, GcArithmeticException::Type); goto throw_; } - + pushInt(t, a / b); - } goto loop; + } + goto loop; case if_acmpeq: { int16_t offset = codeReadInt16(t, code, ip); object b = popObject(t); object a = popObject(t); - + if (a == b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_acmpne: { int16_t offset = codeReadInt16(t, code, ip); object b = popObject(t); object a = popObject(t); - + if (a != b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmpeq: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a == b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmpne: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a != b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmpgt: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a > b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmpge: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a >= b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmplt: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a < b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case if_icmple: { int16_t offset = codeReadInt16(t, code, ip); int32_t b = popInt(t); int32_t a = popInt(t); - + if (a <= b) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifeq: { int16_t offset = codeReadInt16(t, code, ip); @@ -1719,7 +1839,8 @@ interpret3(Thread* t, const int base) if (popInt(t) == 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifne: { int16_t offset = codeReadInt16(t, code, ip); @@ -1727,7 +1848,8 @@ interpret3(Thread* t, const int base) if (popInt(t)) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifgt: { int16_t offset = codeReadInt16(t, code, ip); @@ -1735,7 +1857,8 @@ interpret3(Thread* t, const int base) if (static_cast(popInt(t)) > 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifge: { int16_t offset = codeReadInt16(t, code, ip); @@ -1743,7 +1866,8 @@ interpret3(Thread* t, const int base) if (static_cast(popInt(t)) >= 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case iflt: { int16_t offset = codeReadInt16(t, code, ip); @@ -1751,7 +1875,8 @@ interpret3(Thread* t, const int base) if (static_cast(popInt(t)) < 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifle: { int16_t offset = codeReadInt16(t, code, ip); @@ -1759,7 +1884,8 @@ interpret3(Thread* t, const int base) if (static_cast(popInt(t)) <= 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifnonnull: { int16_t offset = codeReadInt16(t, code, ip); @@ -1767,7 +1893,8 @@ interpret3(Thread* t, const int base) if (popObject(t)) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case ifnull: { int16_t offset = codeReadInt16(t, code, ip); @@ -1775,56 +1902,65 @@ interpret3(Thread* t, const int base) if (popObject(t) == 0) { ip = (ip - 3) + offset; } - } goto back_branch; + } + goto back_branch; case iinc: { - uint8_t index = codeBody(t, code, ip++); - int8_t c = codeBody(t, code, ip++); - + uint8_t index = code->body()[ip++]; + int8_t c = code->body()[ip++]; + setLocalInt(t, index, localInt(t, index) + c); - } goto loop; + } + goto loop; case iload: case fload: { - pushInt(t, localInt(t, codeBody(t, code, ip++))); - } goto loop; + pushInt(t, localInt(t, code->body()[ip++])); + } + goto loop; case iload_0: case fload_0: { pushInt(t, localInt(t, 0)); - } goto loop; + } + goto loop; case iload_1: case fload_1: { pushInt(t, localInt(t, 1)); - } goto loop; + } + goto loop; case iload_2: case fload_2: { pushInt(t, localInt(t, 2)); - } goto loop; + } + goto loop; case iload_3: case fload_3: { pushInt(t, localInt(t, 3)); - } goto loop; + } + goto loop; case imul: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a * b); - } goto loop; + } + goto loop; case ineg: { - pushInt(t, - popInt(t)); - } goto loop; + pushInt(t, -popInt(t)); + } + goto loop; case instanceof: { uint16_t index = codeReadInt16(t, code, ip); if (peekObject(t, sp - 1)) { - object class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); + GcClass* class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); if (instanceOf(t, class_, popObject(t))) { pushInt(t, 1); @@ -1835,101 +1971,108 @@ interpret3(Thread* t, const int base) popObject(t); pushInt(t, 0); } - } goto loop; + } + goto loop; case invokeinterface: { uint16_t index = codeReadInt16(t, code, ip); - + ip += 2; - object method = resolveMethod(t, frameMethod(t, frame), index - 1); - - unsigned parameterFootprint = methodParameterFootprint(t, method); + GcMethod* m = resolveMethod(t, frameMethod(t, frame), index - 1); + + unsigned parameterFootprint = m->parameterFootprint(); if (LIKELY(peekObject(t, sp - parameterFootprint))) { - code = findInterfaceMethod - (t, method, objectClass(t, peekObject(t, sp - parameterFootprint))); + method = findInterfaceMethod( + t, m, objectClass(t, peekObject(t, sp - parameterFootprint))); goto invoke; } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case invokespecial: { uint16_t index = codeReadInt16(t, code, ip); - object method = resolveMethod(t, frameMethod(t, frame), index - 1); - - unsigned parameterFootprint = methodParameterFootprint(t, method); + GcMethod* m = resolveMethod(t, frameMethod(t, frame), index - 1); + + unsigned parameterFootprint = m->parameterFootprint(); if (LIKELY(peekObject(t, sp - parameterFootprint))) { - object class_ = methodClass(t, frameMethod(t, frame)); - if (isSpecialMethod(t, method, class_)) { - class_ = classSuper(t, class_); - PROTECT(t, method); + GcClass* class_ = frameMethod(t, frame)->class_(); + if (isSpecialMethod(t, m, class_)) { + class_ = class_->super(); + PROTECT(t, m); PROTECT(t, class_); initClass(t, class_); - code = findVirtualMethod(t, method, class_); + method = findVirtualMethod(t, m, class_); } else { - code = method; + method = m; } - + goto invoke; } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case invokestatic: { uint16_t index = codeReadInt16(t, code, ip); - object method = resolveMethod(t, frameMethod(t, frame), index - 1); - PROTECT(t, method); - - initClass(t, methodClass(t, method)); + GcMethod* m = resolveMethod(t, frameMethod(t, frame), index - 1); + PROTECT(t, m); - code = method; - } goto invoke; + initClass(t, m->class_()); + + method = m; + } + goto invoke; case invokevirtual: { uint16_t index = codeReadInt16(t, code, ip); - object method = resolveMethod(t, frameMethod(t, frame), index - 1); - - unsigned parameterFootprint = methodParameterFootprint(t, method); + GcMethod* m = resolveMethod(t, frameMethod(t, frame), index - 1); + + unsigned parameterFootprint = m->parameterFootprint(); if (LIKELY(peekObject(t, sp - parameterFootprint))) { - object class_ = objectClass(t, peekObject(t, sp - parameterFootprint)); - PROTECT(t, method); + GcClass* class_ = objectClass(t, peekObject(t, sp - parameterFootprint)); + PROTECT(t, m); PROTECT(t, class_); - code = findVirtualMethod(t, method, class_); + method = findVirtualMethod(t, m, class_); goto invoke; } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case ior: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a | b); - } goto loop; + } + goto loop; case irem: { int32_t b = popInt(t); int32_t a = popInt(t); - + if (UNLIKELY(b == 0)) { - exception = makeThrowable(t, Machine::ArithmeticExceptionType); + exception = makeThrowable(t, GcArithmeticException::Type); goto throw_; } - + pushInt(t, a % b); - } goto loop; + } + goto loop; case ireturn: case freturn: { @@ -1941,128 +2084,148 @@ interpret3(Thread* t, const int base) } else { return makeInt(t, result); } - } goto loop; + } + goto loop; case ishl: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a << (b & 0x1F)); - } goto loop; + } + goto loop; case ishr: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a >> (b & 0x1F)); - } goto loop; + } + goto loop; case istore: case fstore: { - setLocalInt(t, codeBody(t, code, ip++), popInt(t)); - } goto loop; + setLocalInt(t, code->body()[ip++], popInt(t)); + } + goto loop; case istore_0: case fstore_0: { setLocalInt(t, 0, popInt(t)); - } goto loop; + } + goto loop; case istore_1: case fstore_1: { setLocalInt(t, 1, popInt(t)); - } goto loop; + } + goto loop; case istore_2: case fstore_2: { setLocalInt(t, 2, popInt(t)); - } goto loop; + } + goto loop; case istore_3: case fstore_3: { setLocalInt(t, 3, popInt(t)); - } goto loop; + } + goto loop; case isub: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a - b); - } goto loop; + } + goto loop; case iushr: { int32_t b = popInt(t); uint32_t a = popInt(t); - + pushInt(t, a >> (b & 0x1F)); - } goto loop; + } + goto loop; case ixor: { int32_t b = popInt(t); int32_t a = popInt(t); - + pushInt(t, a ^ b); - } goto loop; + } + goto loop; case jsr: { uint16_t offset = codeReadInt16(t, code, ip); pushInt(t, ip); ip = (ip - 3) + static_cast(offset); - } goto loop; + } + goto loop; case jsr_w: { uint32_t offset = codeReadInt32(t, code, ip); pushInt(t, ip); ip = (ip - 5) + static_cast(offset); - } goto loop; + } + goto loop; case l2d: { pushDouble(t, static_cast(static_cast(popLong(t)))); - } goto loop; + } + goto loop; case l2f: { pushFloat(t, static_cast(static_cast(popLong(t)))); - } goto loop; + } + goto loop; case l2i: { pushInt(t, static_cast(popLong(t))); - } goto loop; + } + goto loop; case ladd: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a + b); - } goto loop; + } + goto loop; case laload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < longArrayLength(t, array))) - { - pushLong(t, longArrayBody(t, array, index)); + GcLongArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushLong(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, longArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case land: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a & b); - } goto loop; + } + goto loop; case lastore: { int64_t value = popLong(t); @@ -2070,133 +2233,149 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < longArrayLength(t, array))) - { - longArrayBody(t, array, index) = value; + GcLongArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, longArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case lcmp: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushInt(t, a > b ? 1 : a == b ? 0 : -1); - } goto loop; + } + goto loop; case lconst_0: { pushLong(t, 0); - } goto loop; + } + goto loop; case lconst_1: { pushLong(t, 1); - } goto loop; + } + goto loop; case ldc: case ldc_w: { uint16_t index; if (instruction == ldc) { - index = codeBody(t, code, ip++); + index = code->body()[ip++]; } else { index = codeReadInt16(t, code, ip); } - object pool = codePool(t, code); + GcSingleton* pool = code->pool(); if (singletonIsObject(t, pool, index - 1)) { object v = singletonObject(t, pool, index - 1); - if (objectClass(t, v) == type(t, Machine::ReferenceType)) { - object class_ = resolveClassInPool - (t, frameMethod(t, frame), index - 1); + if (objectClass(t, v) == type(t, GcReference::Type)) { + GcClass* class_ + = resolveClassInPool(t, frameMethod(t, frame), index - 1); - pushObject(t, getJClass(t, class_)); - } else if (objectClass(t, v) == type(t, Machine::ClassType)) { - pushObject(t, getJClass(t, v)); - } else { + pushObject(t, reinterpret_cast(getJClass(t, class_))); + } else if (objectClass(t, v) == type(t, GcClass::Type)) { + pushObject(t, + reinterpret_cast(getJClass(t, cast(t, v)))); + } else { pushObject(t, v); } } else { pushInt(t, singletonValue(t, pool, index - 1)); } - } goto loop; + } + goto loop; case ldc2_w: { uint16_t index = codeReadInt16(t, code, ip); - object pool = codePool(t, code); + GcSingleton* pool = code->pool(); uint64_t v; memcpy(&v, &singletonValue(t, pool, index - 1), 8); pushLong(t, v); - } goto loop; + } + goto loop; case ldiv_: { int64_t b = popLong(t); int64_t a = popLong(t); - + if (UNLIKELY(b == 0)) { - exception = makeThrowable(t, Machine::ArithmeticExceptionType); + exception = makeThrowable(t, GcArithmeticException::Type); goto throw_; } - + pushLong(t, a / b); - } goto loop; + } + goto loop; case lload: case dload: { - pushLong(t, localLong(t, codeBody(t, code, ip++))); - } goto loop; + pushLong(t, localLong(t, code->body()[ip++])); + } + goto loop; case lload_0: case dload_0: { pushLong(t, localLong(t, 0)); - } goto loop; + } + goto loop; case lload_1: case dload_1: { pushLong(t, localLong(t, 1)); - } goto loop; + } + goto loop; case lload_2: case dload_2: { pushLong(t, localLong(t, 2)); - } goto loop; + } + goto loop; case lload_3: case dload_3: { pushLong(t, localLong(t, 3)); - } goto loop; + } + goto loop; case lmul: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a * b); - } goto loop; + } + goto loop; case lneg: { - pushLong(t, - popLong(t)); - } goto loop; + pushLong(t, -popLong(t)); + } + goto loop; case lookupswitch: { int32_t base = ip - 1; ip += 3; ip -= (ip % 4); - + int32_t default_ = codeReadInt32(t, code, ip); int32_t pairCount = codeReadInt32(t, code, ip); - + int32_t key = popInt(t); int32_t bottom = 0; @@ -2218,26 +2397,29 @@ interpret3(Thread* t, const int base) } ip = base + default_; - } goto loop; + } + goto loop; case lor: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a | b); - } goto loop; + } + goto loop; case lrem: { int64_t b = popLong(t); int64_t a = popLong(t); - + if (UNLIKELY(b == 0)) { - exception = makeThrowable(t, Machine::ArithmeticExceptionType); + exception = makeThrowable(t, GcArithmeticException::Type); goto throw_; } - + pushLong(t, a % b); - } goto loop; + } + goto loop; case lreturn: case dreturn: { @@ -2249,102 +2431,116 @@ interpret3(Thread* t, const int base) } else { return makeLong(t, result); } - } goto loop; + } + goto loop; case lshl: { int32_t b = popInt(t); int64_t a = popLong(t); - + pushLong(t, a << (b & 0x3F)); - } goto loop; + } + goto loop; case lshr: { int32_t b = popInt(t); int64_t a = popLong(t); - + pushLong(t, a >> (b & 0x3F)); - } goto loop; + } + goto loop; case lstore: case dstore: { - setLocalLong(t, codeBody(t, code, ip++), popLong(t)); - } goto loop; + setLocalLong(t, code->body()[ip++], popLong(t)); + } + goto loop; - case lstore_0: - case dstore_0:{ + case lstore_0: + case dstore_0: { setLocalLong(t, 0, popLong(t)); - } goto loop; + } + goto loop; - case lstore_1: + case lstore_1: case dstore_1: { setLocalLong(t, 1, popLong(t)); - } goto loop; + } + goto loop; - case lstore_2: + case lstore_2: case dstore_2: { setLocalLong(t, 2, popLong(t)); - } goto loop; + } + goto loop; - case lstore_3: + case lstore_3: case dstore_3: { setLocalLong(t, 3, popLong(t)); - } goto loop; + } + goto loop; case lsub: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a - b); - } goto loop; + } + goto loop; case lushr: { int64_t b = popInt(t); uint64_t a = popLong(t); - + pushLong(t, a >> (b & 0x3F)); - } goto loop; + } + goto loop; case lxor: { int64_t b = popLong(t); int64_t a = popLong(t); - + pushLong(t, a ^ b); - } goto loop; + } + goto loop; case monitorenter: { object o = popObject(t); if (LIKELY(o)) { acquire(t, o); } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case monitorexit: { object o = popObject(t); if (LIKELY(o)) { release(t, o); } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case multianewarray: { uint16_t index = codeReadInt16(t, code, ip); - uint8_t dimensions = codeBody(t, code, ip++); + uint8_t dimensions = code->body()[ip++]; - object class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); + GcClass* class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); PROTECT(t, class_); THREAD_RUNTIME_ARRAY(t, int32_t, counts, dimensions); for (int i = dimensions - 1; i >= 0; --i) { RUNTIME_ARRAY_BODY(counts)[i] = popInt(t); if (UNLIKELY(RUNTIME_ARRAY_BODY(counts)[i] < 0)) { - exception = makeThrowable - (t, Machine::NegativeArraySizeExceptionType, "%d", - RUNTIME_ARRAY_BODY(counts)[i]); + exception = makeThrowable(t, + GcNegativeArraySizeException::Type, + "%d", + RUNTIME_ARRAY_BODY(counts)[i]); goto throw_; } } @@ -2356,24 +2552,26 @@ interpret3(Thread* t, const int base) populateMultiArray(t, array, RUNTIME_ARRAY_BODY(counts), 0, dimensions); pushObject(t, array); - } goto loop; + } + goto loop; case new_: { uint16_t index = codeReadInt16(t, code, ip); - - object class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); + + GcClass* class_ = resolveClassInPool(t, frameMethod(t, frame), index - 1); PROTECT(t, class_); initClass(t, class_); pushObject(t, make(t, class_)); - } goto loop; + } + goto loop; case newarray: { int32_t count = popInt(t); if (LIKELY(count >= 0)) { - uint8_t type = codeBody(t, code, ip++); + uint8_t type = code->body()[ip++]; object array; @@ -2410,38 +2608,44 @@ interpret3(Thread* t, const int base) array = makeLongArray(t, count); break; - default: abort(t); + default: + abort(t); } - + pushObject(t, array); } else { - exception = makeThrowable - (t, Machine::NegativeArraySizeExceptionType, "%d", count); + exception + = makeThrowable(t, GcNegativeArraySizeException::Type, "%d", count); goto throw_; } - } goto loop; + } + goto loop; - case nop: goto loop; + case nop: + goto loop; case pop_: { - -- sp; - } goto loop; + --sp; + } + goto loop; case pop2: { sp -= 2; - } goto loop; + } + goto loop; case putfield: { uint16_t index = codeReadInt16(t, code, ip); - - object field = resolveField(t, frameMethod(t, frame), index - 1); - assert(t, (fieldFlags(t, field) & ACC_STATIC) == 0); + GcField* field = resolveField(t, frameMethod(t, frame), index - 1); + + assertT(t, (field->flags() & ACC_STATIC) == 0); PROTECT(t, field); - { ACQUIRE_FIELD_FOR_WRITE(t, field); + { + ACQUIRE_FIELD_FOR_WRITE(t, field); - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: case CharField: @@ -2451,24 +2655,24 @@ interpret3(Thread* t, const int base) int32_t value = popInt(t); object o = popObject(t); if (LIKELY(o)) { - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: - fieldAtOffset(o, fieldOffset(t, field)) = value; + fieldAtOffset(o, field->offset()) = value; break; - + case CharField: case ShortField: - fieldAtOffset(o, fieldOffset(t, field)) = value; + fieldAtOffset(o, field->offset()) = value; break; - + case FloatField: case IntField: - fieldAtOffset(o, fieldOffset(t, field)) = value; + fieldAtOffset(o, field->offset()) = value; break; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); } } break; @@ -2477,9 +2681,9 @@ interpret3(Thread* t, const int base) int64_t value = popLong(t); object o = popObject(t); if (LIKELY(o)) { - fieldAtOffset(o, fieldOffset(t, field)) = value; + fieldAtOffset(o, field->offset()) = value; } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); } } break; @@ -2487,37 +2691,39 @@ interpret3(Thread* t, const int base) object value = popObject(t); object o = popObject(t); if (LIKELY(o)) { - set(t, o, fieldOffset(t, field), value); + setField(t, o, field->offset(), value); } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); } } break; - default: abort(t); + default: + abort(t); } } if (UNLIKELY(exception)) { goto throw_; } - } goto loop; + } + goto loop; case putstatic: { uint16_t index = codeReadInt16(t, code, ip); - object field = resolveField(t, frameMethod(t, frame), index - 1); + GcField* field = resolveField(t, frameMethod(t, frame), index - 1); - assert(t, fieldFlags(t, field) & ACC_STATIC); + assertT(t, field->flags() & ACC_STATIC); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - initClass(t, fieldClass(t, field)); - - object table = classStaticTable(t, fieldClass(t, field)); + initClass(t, field->class_()); - switch (fieldCode(t, field)) { + GcSingleton* table = field->class_()->staticTable(); + + switch (field->code()) { case ByteField: case BooleanField: case CharField: @@ -2525,46 +2731,48 @@ interpret3(Thread* t, const int base) case FloatField: case IntField: { int32_t value = popInt(t); - switch (fieldCode(t, field)) { + switch (field->code()) { case ByteField: case BooleanField: - fieldAtOffset(table, fieldOffset(t, field)) = value; + fieldAtOffset(table, field->offset()) = value; break; - + case CharField: case ShortField: - fieldAtOffset(table, fieldOffset(t, field)) = value; + fieldAtOffset(table, field->offset()) = value; break; - + case FloatField: case IntField: - fieldAtOffset(table, fieldOffset(t, field)) = value; + fieldAtOffset(table, field->offset()) = value; break; } } break; case DoubleField: case LongField: { - fieldAtOffset(table, fieldOffset(t, field)) = popLong(t); + fieldAtOffset(table, field->offset()) = popLong(t); } break; case ObjectField: { - set(t, table, fieldOffset(t, field), popObject(t)); + setField(t, table, field->offset(), popObject(t)); } break; - default: abort(t); + default: + abort(t); } - } goto loop; + } + goto loop; case ret: { - ip = localInt(t, codeBody(t, code, ip)); - } goto loop; + ip = localInt(t, code->body()[ip]); + } + goto loop; case return_: { - object method = frameMethod(t, frame); - if ((methodFlags(t, method) & ConstructorFlag) - and (classVmFlags(t, methodClass(t, method)) & HasFinalMemberFlag)) - { + GcMethod* method = frameMethod(t, frame); + if ((method->flags() & ConstructorFlag) + and (method->class_()->vmFlags() & HasFinalMemberFlag)) { storeStoreMemoryBarrier(); } @@ -2574,28 +2782,31 @@ interpret3(Thread* t, const int base) } else { return 0; } - } goto loop; + } + goto loop; case saload: { int32_t index = popInt(t); object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < shortArrayLength(t, array))) - { - pushInt(t, shortArrayBody(t, array, index)); + GcShortArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + pushInt(t, a->body()[index]); } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, shortArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case sastore: { int16_t value = popInt(t); @@ -2603,136 +2814,153 @@ interpret3(Thread* t, const int base) object array = popObject(t); if (LIKELY(array)) { - if (LIKELY(index >= 0 and - static_cast(index) < shortArrayLength(t, array))) - { - shortArrayBody(t, array, index) = value; + GcShortArray* a = cast(t, array); + if (LIKELY(index >= 0 and static_cast(index) < a->length())) { + a->body()[index] = value; } else { - exception = makeThrowable - (t, Machine::ArrayIndexOutOfBoundsExceptionType, "%d not in [0,%d)", - index, shortArrayLength(t, array)); + exception = makeThrowable(t, + GcArrayIndexOutOfBoundsException::Type, + "%d not in [0,%d)", + index, + a->length()); goto throw_; } } else { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); goto throw_; } - } goto loop; + } + goto loop; case sipush: { pushInt(t, static_cast(codeReadInt16(t, code, ip))); - } goto loop; + } + goto loop; case swap: { uintptr_t tmp[2]; - memcpy(tmp , stack + ((sp - 1) * 2), BytesPerWord * 2); + memcpy(tmp, stack + ((sp - 1) * 2), BytesPerWord * 2); memcpy(stack + ((sp - 1) * 2), stack + ((sp - 2) * 2), BytesPerWord * 2); - memcpy(stack + ((sp - 2) * 2), tmp , BytesPerWord * 2); - } goto loop; + memcpy(stack + ((sp - 2) * 2), tmp, BytesPerWord * 2); + } + goto loop; case tableswitch: { int32_t base = ip - 1; ip += 3; ip -= (ip % 4); - + int32_t default_ = codeReadInt32(t, code, ip); int32_t bottom = codeReadInt32(t, code, ip); int32_t top = codeReadInt32(t, code, ip); - + int32_t key = popInt(t); - + if (key >= bottom and key <= top) { unsigned index = ip + ((key - bottom) * 4); ip = base + codeReadInt32(t, code, index); } else { ip = base + default_; } - } goto loop; + } + goto loop; - case wide: goto wide; + case wide: + goto wide; case impdep1: { // this means we're invoking a virtual method on an instance of a // bootstrap class, so we need to load the real class to get the // real method and call it. - assert(t, frameNext(t, frame) >= base); + assertT(t, frameNext(t, frame) >= base); popFrame(t); - assert(t, codeBody(t, code, ip - 3) == invokevirtual); + assertT(t, code->body()[ip - 3] == invokevirtual); ip -= 2; uint16_t index = codeReadInt16(t, code, ip); - object method = resolveMethod(t, frameMethod(t, frame), index - 1); + GcMethod* method = resolveMethod(t, frameMethod(t, frame), index - 1); - unsigned parameterFootprint = methodParameterFootprint(t, method); - object class_ = objectClass(t, peekObject(t, sp - parameterFootprint)); - assert(t, classVmFlags(t, class_) & BootstrapFlag); - - resolveClass(t, classLoader(t, methodClass(t, frameMethod(t, frame))), - className(t, class_)); + unsigned parameterFootprint = method->parameterFootprint(); + GcClass* class_ = objectClass(t, peekObject(t, sp - parameterFootprint)); + assertT(t, class_->vmFlags() & BootstrapFlag); + + resolveClass(t, frameMethod(t, frame)->class_()->loader(), class_->name()); ip -= 3; - } goto loop; + } + goto loop; - default: abort(t); + default: + abort(t); } - wide: - switch (codeBody(t, code, ip++)) { +wide: + switch (code->body()[ip++]) { case aload: { pushObject(t, localObject(t, codeReadInt16(t, code, ip))); - } goto loop; + } + goto loop; case astore: { setLocalObject(t, codeReadInt16(t, code, ip), popObject(t)); - } goto loop; + } + goto loop; case iinc: { uint16_t index = codeReadInt16(t, code, ip); int16_t count = codeReadInt16(t, code, ip); - + setLocalInt(t, index, localInt(t, index) + count); - } goto loop; + } + goto loop; case iload: { pushInt(t, localInt(t, codeReadInt16(t, code, ip))); - } goto loop; + } + goto loop; case istore: { setLocalInt(t, codeReadInt16(t, code, ip), popInt(t)); - } goto loop; + } + goto loop; case lload: { pushLong(t, localLong(t, codeReadInt16(t, code, ip))); - } goto loop; + } + goto loop; case lstore: { - setLocalLong(t, codeReadInt16(t, code, ip), popLong(t)); - } goto loop; + setLocalLong(t, codeReadInt16(t, code, ip), popLong(t)); + } + goto loop; case ret: { ip = localInt(t, codeReadInt16(t, code, ip)); - } goto loop; + } + goto loop; - default: abort(t); + default: + abort(t); } - back_branch: +back_branch: safePoint(t); goto loop; - invoke: { - if (methodFlags(t, code) & ACC_NATIVE) { - invokeNative(t, code); - } else { - checkStack(t, code); - pushFrame(t, code); - } - } goto loop; +invoke : { + if (method->flags() & ACC_NATIVE) { + invokeNative(t, method); + } else { + checkStack(t, method); + pushFrame(t, method); + } +} + goto loop; - throw_: +throw_: if (DebugRun) { fprintf(stderr, "throw\n"); } @@ -2752,8 +2980,7 @@ interpret3(Thread* t, const int base) return 0; } -uint64_t -interpret2(vm::Thread* t, uintptr_t* arguments) +uint64_t interpret2(vm::Thread* t, uintptr_t* arguments) { int base = arguments[0]; bool* success = reinterpret_cast(arguments[1]); @@ -2763,20 +2990,19 @@ interpret2(vm::Thread* t, uintptr_t* arguments) return reinterpret_cast(r); } -object -interpret(Thread* t) +object interpret(Thread* t) { const int base = t->frame; while (true) { bool success = false; - uintptr_t arguments[] = { static_cast(base), - reinterpret_cast(&success) }; + uintptr_t arguments[] + = {static_cast(base), reinterpret_cast(&success)}; uint64_t r = run(t, interpret2, arguments); if (success) { if (t->exception) { - object exception = t->exception; + GcThrowable* exception = t->exception; t->exception = 0; throw_(t, exception); } else { @@ -2786,9 +3012,11 @@ interpret(Thread* t) } } -void -pushArguments(Thread* t, object this_, const char* spec, bool indirectObjects, - va_list a) +void pushArguments(Thread* t, + object this_, + const char* spec, + bool indirectObjects, + va_list a) { if (this_) { pushObject(t, this_); @@ -2805,7 +3033,7 @@ pushArguments(Thread* t, object this_, const char* spec, bool indirectObjects, pushObject(t, va_arg(a, object)); } break; - + case 'J': case 'D': pushLong(t, va_arg(a, uint64_t)); @@ -2817,14 +3045,15 @@ pushArguments(Thread* t, object this_, const char* spec, bool indirectObjects, default: pushInt(t, va_arg(a, uint32_t)); - break; + break; } } } -void -pushArguments(Thread* t, object this_, const char* spec, - const jvalue* arguments) +void pushArguments(Thread* t, + object this_, + const char* spec, + const jvalue* arguments) { if (this_) { pushObject(t, this_); @@ -2838,7 +3067,7 @@ pushArguments(Thread* t, object this_, const char* spec, jobject v = arguments[index++].l; pushObject(t, v ? *v : 0); } break; - + case 'J': case 'D': pushLong(t, arguments[index++].j); @@ -2850,13 +3079,12 @@ pushArguments(Thread* t, object this_, const char* spec, default: pushInt(t, arguments[index++].i); - break; + break; } } } -void -pushArguments(Thread* t, object this_, const char* spec, object a) +void pushArguments(Thread* t, object this_, const char* spec, object a) { if (this_) { pushObject(t, this_); @@ -2869,52 +3097,52 @@ pushArguments(Thread* t, object this_, const char* spec, object a) case '[': pushObject(t, objectArrayBody(t, a, index++)); break; - + case 'J': case 'D': pushLong(t, fieldAtOffset(objectArrayBody(t, a, index++), 8)); break; default: - pushInt(t, fieldAtOffset(objectArrayBody(t, a, index++), - BytesPerWord)); - break; + pushInt( + t, + fieldAtOffset(objectArrayBody(t, a, index++), BytesPerWord)); + break; } } } -object -invoke(Thread* t, object method) +object invoke(Thread* t, GcMethod* method) { PROTECT(t, method); - object class_; + GcClass* class_; PROTECT(t, class_); if (methodVirtual(t, method)) { - unsigned parameterFootprint = methodParameterFootprint(t, method); + unsigned parameterFootprint = method->parameterFootprint(); class_ = objectClass(t, peekObject(t, t->sp - parameterFootprint)); - if (classVmFlags(t, class_) & BootstrapFlag) { - resolveClass(t, root(t, Machine::BootLoader), className(t, class_)); + if (class_->vmFlags() & BootstrapFlag) { + resolveClass(t, roots(t)->bootLoader(), class_->name()); } - if (classFlags(t, methodClass(t, method)) & ACC_INTERFACE) { + if (method->class_()->flags() & ACC_INTERFACE) { method = findInterfaceMethod(t, method, class_); } else { method = findVirtualMethod(t, method, class_); } } else { - class_ = methodClass(t, method); + class_ = method->class_(); } - if (methodFlags(t, method) & ACC_STATIC) { + if (method->flags() & ACC_STATIC) { initClass(t, class_); } object result = 0; - if (methodFlags(t, method) & ACC_NATIVE) { + if (method->flags() & ACC_NATIVE) { unsigned returnCode = invokeNative(t, method); switch (returnCode) { @@ -2931,7 +3159,7 @@ invoke(Thread* t, object method) case DoubleField: result = makeLong(t, popLong(t)); break; - + case ObjectField: result = popObject(t); break; @@ -2952,7 +3180,7 @@ invoke(Thread* t, object method) if (LIKELY(t->exception == 0)) { popFrame(t); } else { - object exception = t->exception; + GcThrowable* exception = t->exception; t->exception = 0; throw_(t, exception); } @@ -2961,7 +3189,7 @@ invoke(Thread* t, object method) return result; } -class MyProcessor: public Processor { +class MyProcessor : public Processor { public: MyProcessor(System* s, Allocator* allocator, const char* crashDumpDirectory) : s(s), allocator(allocator) @@ -2969,68 +3197,94 @@ class MyProcessor: public Processor { signals.setCrashDumpDirectory(crashDumpDirectory); } - virtual vm::Thread* - makeThread(Machine* m, object javaThread, vm::Thread* parent) + virtual vm::Thread* makeThread(Machine* m, + GcThread* javaThread, + vm::Thread* parent) { Thread* t = new (m->heap->allocate(sizeof(Thread) + m->stackSizeInBytes)) - Thread(m, javaThread, parent); + Thread(m, javaThread, parent); t->init(); return t; } - virtual object - makeMethod(vm::Thread* t, - uint8_t vmFlags, - uint8_t returnCode, - uint8_t parameterCount, - uint8_t parameterFootprint, - uint16_t flags, - uint16_t offset, - object name, - object spec, - object addendum, - object class_, - object code) + virtual GcMethod* makeMethod(vm::Thread* t, + uint8_t vmFlags, + uint8_t returnCode, + uint8_t parameterCount, + uint8_t parameterFootprint, + uint16_t flags, + uint16_t offset, + GcByteArray* name, + GcByteArray* spec, + GcMethodAddendum* addendum, + GcClass* class_, + GcCode* code) { - return vm::makeMethod - (t, vmFlags, returnCode, parameterCount, parameterFootprint, flags, - offset, 0, 0, name, spec, addendum, class_, code); + return vm::makeMethod(t, + vmFlags, + returnCode, + parameterCount, + parameterFootprint, + flags, + offset, + 0, + 0, + name, + spec, + addendum, + class_, + code); } - virtual object - makeClass(vm::Thread* t, - uint16_t flags, - uint16_t vmFlags, - uint16_t fixedSize, - uint8_t arrayElementSize, - uint8_t arrayDimensions, - object objectMask, - object name, - object sourceFile, - object super, - object interfaceTable, - object virtualTable, - object fieldTable, - object methodTable, - object addendum, - object staticTable, - object loader, - unsigned vtableLength UNUSED) + virtual GcClass* makeClass(vm::Thread* t, + uint16_t flags, + uint16_t vmFlags, + uint16_t fixedSize, + uint8_t arrayElementSize, + uint8_t arrayDimensions, + GcClass* arrayElementClass, + GcIntArray* objectMask, + GcByteArray* name, + GcByteArray* sourceFile, + GcClass* super, + object interfaceTable, + object virtualTable, + object fieldTable, + object methodTable, + GcClassAddendum* addendum, + GcSingleton* staticTable, + GcClassLoader* loader, + unsigned vtableLength UNUSED) { - return vm::makeClass - (t, flags, vmFlags, fixedSize, arrayElementSize, arrayDimensions, 0, - objectMask, name, sourceFile, super, interfaceTable, virtualTable, - fieldTable, methodTable, addendum, staticTable, loader, 0, 0); + return vm::makeClass(t, + flags, + vmFlags, + fixedSize, + arrayElementSize, + arrayDimensions, + arrayElementClass, + 0, + objectMask, + name, + sourceFile, + super, + interfaceTable, + virtualTable, + fieldTable, + methodTable, + addendum, + staticTable, + loader, + 0, + 0); } - virtual void - initVtable(vm::Thread*, object) + virtual void initVtable(vm::Thread*, GcClass*) { // ignore } - virtual void - visitObjects(vm::Thread* vmt, Heap::Visitor* v) + virtual void visitObjects(vm::Thread* vmt, Heap::Visitor* v) { Thread* t = static_cast(vmt); @@ -3043,8 +3297,7 @@ class MyProcessor: public Processor { } } - virtual void - walkStack(vm::Thread* vmt, StackVisitor* v) + virtual void walkStack(vm::Thread* vmt, StackVisitor* v) { Thread* t = static_cast(vmt); @@ -3056,45 +3309,40 @@ class MyProcessor: public Processor { walker.walk(v); } - virtual int - lineNumber(vm::Thread* t, object method, int ip) + virtual int lineNumber(vm::Thread* t, GcMethod* method, int ip) { return findLineNumber(static_cast(t), method, ip); } - virtual object* - makeLocalReference(vm::Thread* vmt, object o) + virtual object* makeLocalReference(vm::Thread* vmt, object o) { Thread* t = static_cast(vmt); return pushReference(t, o); } - virtual void - disposeLocalReference(vm::Thread*, object* r) + virtual void disposeLocalReference(vm::Thread*, object* r) { if (r) { *r = 0; } } - virtual bool - pushLocalFrame(vm::Thread* vmt, unsigned capacity) + virtual bool pushLocalFrame(vm::Thread* vmt, unsigned capacity) { Thread* t = static_cast(vmt); if (t->sp + capacity < stackSizeInWords(t) / 2) { - t->stackPointers = new(t->m->heap) - List(t->sp, t->stackPointers); - + t->stackPointers = new (t->m->heap) + List(t->sp, t->stackPointers); + return true; } else { return false; } } - virtual void - popLocalFrame(vm::Thread* vmt) + virtual void popLocalFrame(vm::Thread* vmt) { Thread* t = static_cast(vmt); @@ -3105,104 +3353,110 @@ class MyProcessor: public Processor { t->m->heap->free(f, sizeof(List)); } - virtual object - invokeArray(vm::Thread* vmt, object method, object this_, object arguments) + virtual object invokeArray(vm::Thread* vmt, + GcMethod* method, + object this_, + object arguments) { Thread* t = static_cast(vmt); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); - if (UNLIKELY(t->sp + methodParameterFootprint(t, method) + 1 - > stackSizeInWords(t) / 2)) - { - throwNew(t, Machine::StackOverflowErrorType); + if (UNLIKELY(t->sp + method->parameterFootprint() + 1 > stackSizeInWords(t) + / 2)) { + throwNew(t, GcStackOverflowError::Type); } - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); + const char* spec = reinterpret_cast(method->spec()->body().begin()); pushArguments(t, this_, spec, arguments); return local::invoke(t, method); } - virtual object - invokeArray(vm::Thread* vmt, object method, object this_, - const jvalue* arguments) + virtual object invokeArray(vm::Thread* vmt, + GcMethod* method, + object this_, + const jvalue* arguments) { Thread* t = static_cast(vmt); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); - if (UNLIKELY(t->sp + methodParameterFootprint(t, method) + 1 - > stackSizeInWords(t) / 2)) - { - throwNew(t, Machine::StackOverflowErrorType); + if (UNLIKELY(t->sp + method->parameterFootprint() + 1 > stackSizeInWords(t) + / 2)) { + throwNew(t, GcStackOverflowError::Type); } - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); + const char* spec = reinterpret_cast(method->spec()->body().begin()); pushArguments(t, this_, spec, arguments); return local::invoke(t, method); } - virtual object - invokeList(vm::Thread* vmt, object method, object this_, - bool indirectObjects, va_list arguments) + virtual object invokeList(vm::Thread* vmt, + GcMethod* method, + object this_, + bool indirectObjects, + va_list arguments) { Thread* t = static_cast(vmt); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); - if (UNLIKELY(t->sp + methodParameterFootprint(t, method) + 1 - > stackSizeInWords(t) / 2)) - { - throwNew(t, Machine::StackOverflowErrorType); + if (UNLIKELY(t->sp + method->parameterFootprint() + 1 > stackSizeInWords(t) + / 2)) { + throwNew(t, GcStackOverflowError::Type); } - const char* spec = reinterpret_cast - (&byteArrayBody(t, methodSpec(t, method), 0)); + const char* spec = reinterpret_cast(method->spec()->body().begin()); pushArguments(t, this_, spec, indirectObjects, arguments); return local::invoke(t, method); } - virtual object - invokeList(vm::Thread* vmt, object loader, const char* className, - const char* methodName, const char* methodSpec, object this_, - va_list arguments) + virtual object invokeList(vm::Thread* vmt, + GcClassLoader* loader, + const char* className, + const char* methodName, + const char* methodSpec, + object this_, + va_list arguments) { Thread* t = static_cast(vmt); - assert(t, t->state == Thread::ActiveState - or t->state == Thread::ExclusiveState); + assertT( + t, + t->state == Thread::ActiveState or t->state == Thread::ExclusiveState); if (UNLIKELY(t->sp + parameterFootprint(vmt, methodSpec, false) - > stackSizeInWords(t) / 2)) - { - throwNew(t, Machine::StackOverflowErrorType); + > stackSizeInWords(t) / 2)) { + throwNew(t, GcStackOverflowError::Type); } pushArguments(t, this_, methodSpec, false, arguments); - object method = resolveMethod - (t, loader, className, methodName, methodSpec); + GcMethod* method + = resolveMethod(t, loader, className, methodName, methodSpec); - assert(t, ((methodFlags(t, method) & ACC_STATIC) == 0) xor (this_ == 0)); + assertT(t, ((method->flags() & ACC_STATIC) == 0) xor (this_ == 0)); return local::invoke(t, method); } - virtual object getStackTrace(vm::Thread* t, vm::Thread*) { + virtual object getStackTrace(vm::Thread* t, vm::Thread*) + { // not implemented return makeObjectArray(t, 0); } @@ -3212,70 +3466,90 @@ class MyProcessor: public Processor { abort(s); } - virtual void addCompilationHandler(CompilationHandler*) { - abort(s); - } - - virtual void compileMethod(vm::Thread*, Zone*, object*, object*, - avian::codegen::DelayedPromise**, object, OffsetResolver*) + virtual void addCompilationHandler(CompilationHandler*) { abort(s); } - virtual void visitRoots(vm::Thread*, HeapWalker*) { + virtual void compileMethod(vm::Thread*, + Zone*, + GcTriple**, + GcTriple**, + avian::codegen::DelayedPromise**, + GcMethod*, + OffsetResolver*) + { abort(s); } - virtual void normalizeVirtualThunks(vm::Thread*) { + virtual void visitRoots(vm::Thread*, HeapWalker*) + { abort(s); } - virtual unsigned* makeCallTable(vm::Thread*, HeapWalker*) { + virtual void normalizeVirtualThunks(vm::Thread*) + { abort(s); } - virtual void boot(vm::Thread*, BootImage* image, uint8_t* code) { + virtual unsigned* makeCallTable(vm::Thread*, HeapWalker*) + { + abort(s); + } + + virtual void boot(vm::Thread*, BootImage* image, uint8_t* code) + { expect(s, image == 0 and code == 0); } - virtual void callWithCurrentContinuation(vm::Thread*, object) { + virtual void callWithCurrentContinuation(vm::Thread*, object) + { abort(s); } - virtual void dynamicWind(vm::Thread*, object, object, object) { + virtual void dynamicWind(vm::Thread*, object, object, object) + { abort(s); } - virtual void feedResultToContinuation(vm::Thread*, object, object){ + virtual void feedResultToContinuation(vm::Thread*, GcContinuation*, object) + { abort(s); } - virtual void feedExceptionToContinuation(vm::Thread*, object, object) { + virtual void feedExceptionToContinuation(vm::Thread*, + GcContinuation*, + GcThrowable*) + { abort(s); } - virtual void walkContinuationBody(vm::Thread*, Heap::Walker*, object, + virtual void walkContinuationBody(vm::Thread*, + Heap::Walker*, + object, unsigned) { abort(s); } - virtual void dispose(vm::Thread* t) { + virtual void dispose(vm::Thread* t) + { t->m->heap->free(t, sizeof(Thread) + t->m->stackSizeInBytes); } - virtual void dispose() { + virtual void dispose() + { signals.setCrashDumpDirectory(0); this->~MyProcessor(); allocator->free(this, sizeof(*this)); } - + System* s; Allocator* allocator; SignalRegistrar signals; }; -} // namespace +} // namespace namespace vm { @@ -3285,7 +3559,7 @@ Processor* makeProcessor(System* system, bool) { return new (allocator->allocate(sizeof(local::MyProcessor))) - local::MyProcessor(system, allocator, crashDumpDirectory); + local::MyProcessor(system, allocator, crashDumpDirectory); } -} // namespace vm +} // namespace vm diff --git a/src/jnienv.cpp b/src/jnienv.cpp index dda50462c1..1f067b0268 100644 --- a/src/jnienv.cpp +++ b/src/jnienv.cpp @@ -22,8 +22,7 @@ namespace { namespace local { -jint JNICALL -AttachCurrentThread(Machine* m, Thread** t, void*) +jint JNICALL AttachCurrentThread(Machine* m, Thread** t, void*) { *t = static_cast(m->localThread->get()); if (*t == 0) { @@ -32,8 +31,7 @@ AttachCurrentThread(Machine* m, Thread** t, void*) return 0; } -jint JNICALL -AttachCurrentThreadAsDaemon(Machine* m, Thread** t, void*) +jint JNICALL AttachCurrentThreadAsDaemon(Machine* m, Thread** t, void*) { *t = static_cast(m->localThread->get()); if (*t == 0) { @@ -42,8 +40,7 @@ AttachCurrentThreadAsDaemon(Machine* m, Thread** t, void*) return 0; } -jint JNICALL -DetachCurrentThread(Machine* m) +jint JNICALL DetachCurrentThread(Machine* m) { Thread* t = static_cast(m->localThread->get()); if (t) { @@ -58,7 +55,7 @@ DetachCurrentThread(Machine* m) enter(t, Thread::ActiveState); - threadPeer(t, t->javaThread) = 0; + t->javaThread->peer() = 0; enter(t, Thread::ZombieState); @@ -71,24 +68,26 @@ DetachCurrentThread(Machine* m) } } -uint64_t -destroyJavaVM(Thread* t, uintptr_t*) +uint64_t destroyJavaVM(Thread* t, uintptr_t*) { // wait for other non-daemon threads to exit - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); while (t->m->liveCount - t->m->daemonCount > 1) { t->m->stateLock->wait(t->systemThread, 0); } } - { ENTER(t, Thread::ActiveState); + { + ENTER(t, Thread::ActiveState); t->m->classpath->shutDown(t); } // wait again in case the Classpath::shutDown process started new // threads: - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); while (t->m->liveCount - t->m->daemonCount > 1) { t->m->stateLock->wait(t->systemThread, 0); } @@ -101,10 +100,10 @@ destroyJavaVM(Thread* t, uintptr_t*) return 1; } -jint JNICALL -DestroyJavaVM(Machine* m) +jint JNICALL DestroyJavaVM(Machine* m) { - Thread* t; AttachCurrentThread(m, &t, 0); + Thread* t; + AttachCurrentThread(m, &t, 0); if (runRaw(t, destroyJavaVM, 0)) { t->exit(); @@ -114,8 +113,7 @@ DestroyJavaVM(Machine* m) } } -jint JNICALL -GetEnv(Machine* m, Thread** t, jint version) +jint JNICALL GetEnv(Machine* m, Thread** t, jint version) { *t = static_cast(m->localThread->get()); if (*t) { @@ -129,230 +127,226 @@ GetEnv(Machine* m, Thread** t, jint version) } } -jint JNICALL -GetVersion(Thread* t) +jint JNICALL GetVersion(Thread* t) { ENTER(t, Thread::ActiveState); return JNI_VERSION_1_6; } -jsize JNICALL -GetStringLength(Thread* t, jstring s) +jsize JNICALL GetStringLength(Thread* t, jstring s) { ENTER(t, Thread::ActiveState); - return stringLength(t, *s); + return (*s)->length(t); } -const jchar* JNICALL -GetStringChars(Thread* t, jstring s, jboolean* isCopy) +const jchar* JNICALL GetStringChars(Thread* t, jstring s, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - jchar* chars = static_cast - (t->m->heap->allocate((stringLength(t, *s) + 1) * sizeof(jchar))); + jchar* chars = static_cast( + t->m->heap->allocate(((*s)->length(t) + 1) * sizeof(jchar))); stringChars(t, *s, chars); - if (isCopy) *isCopy = true; + if (isCopy) + *isCopy = true; return chars; } -void JNICALL -ReleaseStringChars(Thread* t, jstring s, const jchar* chars) +void JNICALL ReleaseStringChars(Thread* t, jstring s, const jchar* chars) { ENTER(t, Thread::ActiveState); - t->m->heap->free(chars, (stringLength(t, *s) + 1) * sizeof(jchar)); + t->m->heap->free(chars, ((*s)->length(t) + 1) * sizeof(jchar)); } void JNICALL -GetStringRegion(Thread* t, jstring s, jsize start, jsize length, jchar* dst) + GetStringRegion(Thread* t, jstring s, jsize start, jsize length, jchar* dst) { ENTER(t, Thread::ActiveState); stringChars(t, *s, start, length, dst); } -const jchar* JNICALL -GetStringCritical(Thread* t, jstring s, jboolean* isCopy) +const jchar* JNICALL GetStringCritical(Thread* t, jstring s, jboolean* isCopy) { if (t->criticalLevel == 0) { enter(t, Thread::ActiveState); } - ++ t->criticalLevel; + ++t->criticalLevel; if (isCopy) { *isCopy = true; } - - object data = stringData(t, *s); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { + + object data = (*s)->data(); + if (objectClass(t, data) == type(t, GcByteArray::Type)) { return GetStringChars(t, s, isCopy); } else { - return &charArrayBody(t, data, stringOffset(t, *s)); + return &cast(t, data)->body()[(*s)->offset(t)]; } } -void JNICALL -ReleaseStringCritical(Thread* t, jstring s, const jchar* chars) +void JNICALL ReleaseStringCritical(Thread* t, jstring s, const jchar* chars) { - if (objectClass(t, stringData(t, *s)) == type(t, Machine::ByteArrayType)) { + if (objectClass(t, (*s)->data()) == type(t, GcByteArray::Type)) { ReleaseStringChars(t, s, chars); } - if ((-- t->criticalLevel) == 0) { + if ((--t->criticalLevel) == 0) { enter(t, Thread::IdleState); } } -jsize JNICALL -GetStringUTFLength(Thread* t, jstring s) +jsize JNICALL GetStringUTFLength(Thread* t, jstring s) { ENTER(t, Thread::ActiveState); return stringUTFLength(t, *s); } -const char* JNICALL -GetStringUTFChars(Thread* t, jstring s, jboolean* isCopy) +const char* JNICALL GetStringUTFChars(Thread* t, jstring s, jboolean* isCopy) { ENTER(t, Thread::ActiveState); int length = stringUTFLength(t, *s); - char* chars = static_cast - (t->m->heap->allocate(length + 1)); + char* chars = static_cast(t->m->heap->allocate(length + 1)); stringUTFChars(t, *s, chars, length); - if (isCopy) *isCopy = true; + if (isCopy) + *isCopy = true; return chars; } -void JNICALL -ReleaseStringUTFChars(Thread* t, jstring s, const char* chars) +void JNICALL ReleaseStringUTFChars(Thread* t, jstring s, const char* chars) { ENTER(t, Thread::ActiveState); t->m->heap->free(chars, stringUTFLength(t, *s) + 1); } -void JNICALL -GetStringUTFRegion(Thread* t, jstring s, jsize start, jsize length, char* dst) +void JNICALL GetStringUTFRegion(Thread* t, + jstring s, + jsize start, + jsize length, + char* dst) { ENTER(t, Thread::ActiveState); - stringUTFChars - (t, *s, start, length, dst, stringUTFLength(t, *s, start, length)); + stringUTFChars( + t, *s, start, length, dst, stringUTFLength(t, *s, start, length)); } -jsize JNICALL -GetArrayLength(Thread* t, jarray array) +jsize JNICALL GetArrayLength(Thread* t, jarray array) { ENTER(t, Thread::ActiveState); return fieldAtOffset(*array, BytesPerWord); } -uint64_t -newString(Thread* t, uintptr_t* arguments) +uint64_t newString(Thread* t, uintptr_t* arguments) { const jchar* chars = reinterpret_cast(arguments[0]); jsize size = arguments[1]; - object a = makeCharArray(t, size); + GcCharArray* a = makeCharArray(t, size); if (size) { - memcpy(&charArrayBody(t, a, 0), chars, size * sizeof(jchar)); + memcpy(a->body().begin(), chars, size * sizeof(jchar)); } - return reinterpret_cast - (makeLocalReference(t, t->m->classpath->makeString(t, a, 0, size))); + return reinterpret_cast( + makeLocalReference(t, t->m->classpath->makeString(t, a, 0, size))); } -jstring JNICALL -NewString(Thread* t, const jchar* chars, jsize size) +jstring JNICALL NewString(Thread* t, const jchar* chars, jsize size) { - if (chars == 0) return 0; + if (chars == 0) + return 0; - uintptr_t arguments[] = { reinterpret_cast(chars), - static_cast(size) }; + uintptr_t arguments[] + = {reinterpret_cast(chars), static_cast(size)}; return reinterpret_cast(run(t, newString, arguments)); } -uint64_t -newStringUTF(Thread* t, uintptr_t* arguments) +uint64_t newStringUTF(Thread* t, uintptr_t* arguments) { const char* chars = reinterpret_cast(arguments[0]); object array = parseUtf8(t, chars, strlen(chars)); - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeString - (t, array, 0, fieldAtOffset(array, BytesPerWord) - 1))); + return reinterpret_cast(makeLocalReference( + t, + t->m->classpath->makeString( + t, array, 0, fieldAtOffset(array, BytesPerWord) - 1))); } -jstring JNICALL -NewStringUTF(Thread* t, const char* chars) +jstring JNICALL NewStringUTF(Thread* t, const char* chars) { - if (chars == 0) return 0; + if (chars == 0) + return 0; - uintptr_t arguments[] = { reinterpret_cast(chars) }; + uintptr_t arguments[] = {reinterpret_cast(chars)}; return reinterpret_cast(run(t, newStringUTF, arguments)); } -void -replace(int a, int b, const char* in, int8_t* out) +void replace(int a, int b, const char* in, int8_t* out) { while (*in) { *out = (*in == a ? b : *in); - ++ in; - ++ out; + ++in; + ++out; } *out = 0; } -uint64_t -defineClass(Thread* t, uintptr_t* arguments) +uint64_t defineClass(Thread* t, uintptr_t* arguments) { jobject loader = reinterpret_cast(arguments[0]); const uint8_t* buffer = reinterpret_cast(arguments[1]); jsize length = arguments[2]; - return reinterpret_cast - (makeLocalReference - (t, getJClass - (t, defineClass - (t, loader ? *loader : root(t, Machine::BootLoader), buffer, length)))); + return reinterpret_cast(makeLocalReference( + t, + getJClass( + t, + cast(t, + defineClass(t, + loader ? cast(t, *loader) + : roots(t)->bootLoader(), + buffer, + length))))); } -jclass JNICALL -DefineClass(Thread* t, const char*, jobject loader, const jbyte* buffer, - jsize length) +jclass JNICALL DefineClass(Thread* t, + const char*, + jobject loader, + const jbyte* buffer, + jsize length) { - uintptr_t arguments[] = { reinterpret_cast(loader), - reinterpret_cast(buffer), - static_cast(length) }; + uintptr_t arguments[] = {reinterpret_cast(loader), + reinterpret_cast(buffer), + static_cast(length)}; return reinterpret_cast(run(t, defineClass, arguments)); } -uint64_t -findClass(Thread* t, uintptr_t* arguments) +uint64_t findClass(Thread* t, uintptr_t* arguments) { const char* name = reinterpret_cast(arguments[0]); - object n = makeByteArray(t, strlen(name) + 1); - replace('.', '/', name, &byteArrayBody(t, n, 0)); + GcByteArray* n = makeByteArray(t, strlen(name) + 1); + replace('.', '/', name, n->body().begin()); - object caller = getCaller(t, 0); + GcMethod* caller = getCaller(t, 0); - object c + GcClass* c = resolveClass(t, caller ? t->m->classpath->libraryClassLoader(t, caller) - : root(t, Machine::AppLoader), + : roots(t)->appLoader(), n); if (t->m->classpath->mayInitClasses()) { @@ -364,21 +358,19 @@ findClass(Thread* t, uintptr_t* arguments) return reinterpret_cast(makeLocalReference(t, getJClass(t, c))); } -jclass JNICALL -FindClass(Thread* t, const char* name) +jclass JNICALL FindClass(Thread* t, const char* name) { - uintptr_t arguments[] = { reinterpret_cast(name) }; + uintptr_t arguments[] = {reinterpret_cast(name)}; return reinterpret_cast(run(t, findClass, arguments)); } -uint64_t -throwNew(Thread* t, uintptr_t* arguments) +uint64_t throwNew(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); const char* message = reinterpret_cast(arguments[1]); - object m = 0; + GcString* m = 0; PROTECT(t, m); if (message) { @@ -388,150 +380,136 @@ throwNew(Thread* t, uintptr_t* arguments) object trace = makeTrace(t); PROTECT(t, trace); - t->exception = make(t, jclassVmClass(t, *c)); - set(t, t->exception, ThrowableMessage, m); - set(t, t->exception, ThrowableTrace, trace); + t->exception = cast(t, make(t, (*c)->vmClass())); + t->exception->setMessage(t, m); + t->exception->setTrace(t, trace); return 1; } -jint JNICALL -ThrowNew(Thread* t, jclass c, const char* message) +jint JNICALL ThrowNew(Thread* t, jclass c, const char* message) { if (t->exception) { return -1; } - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(message) }; + uintptr_t arguments[] + = {reinterpret_cast(c), reinterpret_cast(message)}; return run(t, throwNew, arguments) ? 0 : -1; } -jint JNICALL -Throw(Thread* t, jthrowable throwable) +jint JNICALL Throw(Thread* t, jthrowable throwable) { if (t->exception) { return -1; } ENTER(t, Thread::ActiveState); - + t->exception = *throwable; return 0; } -jobject JNICALL -NewLocalRef(Thread* t, jobject o) -{ +jobject JNICALL NewLocalRef(Thread* t, jobject o) +{ ENTER(t, Thread::ActiveState); return makeLocalReference(t, *o); } -void JNICALL -DeleteLocalRef(Thread* t, jobject r) +void JNICALL DeleteLocalRef(Thread* t, jobject r) { ENTER(t, Thread::ActiveState); disposeLocalReference(t, r); } -jboolean JNICALL -ExceptionCheck(Thread* t) +jboolean JNICALL ExceptionCheck(Thread* t) { return t->exception != 0; } -uint64_t -getObjectClass(Thread* t, uintptr_t* arguments) +uint64_t getObjectClass(Thread* t, uintptr_t* arguments) { - jobject o = reinterpret_cast(arguments[0]); + jobject o = reinterpret_cast(arguments[0]); - return reinterpret_cast - (makeLocalReference(t, getJClass(t, objectClass(t, *o)))); + return reinterpret_cast( + makeLocalReference(t, getJClass(t, objectClass(t, *o)))); } -jclass JNICALL -GetObjectClass(Thread* t, jobject o) +jclass JNICALL GetObjectClass(Thread* t, jobject o) { - uintptr_t arguments[] = { reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(o)}; return reinterpret_cast(run(t, getObjectClass, arguments)); } -uint64_t -getSuperclass(Thread* t, uintptr_t* arguments) +uint64_t getSuperclass(Thread* t, uintptr_t* arguments) { - object class_ = jclassVmClass(t, *reinterpret_cast(arguments[0])); - if (classFlags(t, class_) & ACC_INTERFACE) { + GcClass* class_ = (*reinterpret_cast(arguments[0]))->vmClass(); + if (class_->flags() & ACC_INTERFACE) { return 0; } else { - object super = classSuper(t, class_); - return super ? reinterpret_cast - (makeLocalReference(t, getJClass(t, super))) : 0; + GcClass* super = class_->super(); + return super ? reinterpret_cast( + makeLocalReference(t, getJClass(t, super))) + : 0; } } -jclass JNICALL -GetSuperclass(Thread* t, jclass c) +jclass JNICALL GetSuperclass(Thread* t, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(c) }; + uintptr_t arguments[] = {reinterpret_cast(c)}; return reinterpret_cast(run(t, getSuperclass, arguments)); } -uint64_t -isInstanceOf(Thread* t, uintptr_t* arguments) +uint64_t isInstanceOf(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jclass c = reinterpret_cast(arguments[1]); - return instanceOf(t, jclassVmClass(t, *c), *o); + return instanceOf(t, (*c)->vmClass(), *o); } -jboolean JNICALL -IsInstanceOf(Thread* t, jobject o, jclass c) +jboolean JNICALL IsInstanceOf(Thread* t, jobject o, jclass c) { - uintptr_t arguments[] = { reinterpret_cast(o), - reinterpret_cast(c) }; + uintptr_t arguments[] + = {reinterpret_cast(o), reinterpret_cast(c)}; return run(t, isInstanceOf, arguments); } -uint64_t -isAssignableFrom(Thread* t, uintptr_t* arguments) +uint64_t isAssignableFrom(Thread* t, uintptr_t* arguments) { jclass b = reinterpret_cast(arguments[0]); jclass a = reinterpret_cast(arguments[1]); - return isAssignableFrom(t, jclassVmClass(t, *a), jclassVmClass(t, *b)); + return isAssignableFrom(t, (*a)->vmClass(), (*b)->vmClass()); } -jboolean JNICALL -IsAssignableFrom(Thread* t, jclass b, jclass a) +jboolean JNICALL IsAssignableFrom(Thread* t, jclass b, jclass a) { - uintptr_t arguments[] = { reinterpret_cast(b), - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(b), reinterpret_cast(a)}; return run(t, isAssignableFrom, arguments); } -object -findMethod(Thread* t, jclass c, const char* name, const char* spec) +GcMethod* findMethod(Thread* t, jclass c, const char* name, const char* spec) { - object n = makeByteArray(t, "%s", name); + GcByteArray* n = makeByteArray(t, "%s", name); PROTECT(t, n); - object s = makeByteArray(t, "%s", spec); - return vm::findMethod(t, jclassVmClass(t, *c), n, s); + GcByteArray* s = makeByteArray(t, "%s", spec); + return vm::findMethod(t, (*c)->vmClass(), n, s); } -jint -methodID(Thread* t, object method) +jint methodID(Thread* t, GcMethod* method) { - int id = methodNativeID(t, method); + int id = method->nativeID(); loadMemoryBarrier(); @@ -539,89 +517,86 @@ methodID(Thread* t, object method) PROTECT(t, method); ACQUIRE(t, t->m->referenceLock); - - if (methodNativeID(t, method) == 0) { - setRoot(t, Machine::JNIMethodTable, vectorAppend - (t, root(t, Machine::JNIMethodTable), method)); + + if (method->nativeID() == 0) { + GcVector* v = vectorAppend(t, roots(t)->jNIMethodTable(), method); + // sequence point, for gc (don't recombine statements) + roots(t)->setJNIMethodTable(t, v); storeStoreMemoryBarrier(); - methodNativeID(t, method) = vectorSize - (t, root(t, Machine::JNIMethodTable)); + method->nativeID() = roots(t)->jNIMethodTable()->size(); } } - return methodNativeID(t, method); + return method->nativeID(); } -uint64_t -getMethodID(Thread* t, uintptr_t* arguments) +uint64_t getMethodID(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); const char* name = reinterpret_cast(arguments[1]); const char* spec = reinterpret_cast(arguments[2]); - object method = findMethod(t, c, name, spec); + GcMethod* method = findMethod(t, c, name, spec); - assert(t, (methodFlags(t, method) & ACC_STATIC) == 0); - - return methodID(t, method); -} - -jmethodID JNICALL -GetMethodID(Thread* t, jclass c, const char* name, const char* spec) -{ - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(name), - reinterpret_cast(spec) }; - - return run(t, getMethodID, arguments); -} - -uint64_t -getStaticMethodID(Thread* t, uintptr_t* arguments) -{ - jclass c = reinterpret_cast(arguments[0]); - const char* name = reinterpret_cast(arguments[1]); - const char* spec = reinterpret_cast(arguments[2]); - - object method = findMethod(t, c, name, spec); - - assert(t, methodFlags(t, method) & ACC_STATIC); + assertT(t, (method->flags() & ACC_STATIC) == 0); return methodID(t, method); } jmethodID JNICALL -GetStaticMethodID(Thread* t, jclass c, const char* name, const char* spec) + GetMethodID(Thread* t, jclass c, const char* name, const char* spec) { - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(name), - reinterpret_cast(spec) }; + uintptr_t arguments[] = {reinterpret_cast(c), + reinterpret_cast(name), + reinterpret_cast(spec)}; + + return run(t, getMethodID, arguments); +} + +uint64_t getStaticMethodID(Thread* t, uintptr_t* arguments) +{ + jclass c = reinterpret_cast(arguments[0]); + const char* name = reinterpret_cast(arguments[1]); + const char* spec = reinterpret_cast(arguments[2]); + + GcMethod* method = findMethod(t, c, name, spec); + + assertT(t, method->flags() & ACC_STATIC); + + return methodID(t, method); +} + +jmethodID JNICALL + GetStaticMethodID(Thread* t, jclass c, const char* name, const char* spec) +{ + uintptr_t arguments[] = {reinterpret_cast(c), + reinterpret_cast(name), + reinterpret_cast(spec)}; return run(t, getStaticMethodID, arguments); } -object -getMethod(Thread* t, jmethodID m) +GcMethod* getMethod(Thread* t, jmethodID m) { - assert(t, m); + assertT(t, m); - object method = vectorBody(t, root(t, Machine::JNIMethodTable), m - 1); + GcMethod* method + = cast(t, roots(t)->jNIMethodTable()->body()[m - 1]); - assert(t, (methodFlags(t, method) & ACC_STATIC) == 0); + assertT(t, (method->flags() & ACC_STATIC) == 0); return method; } -uint64_t -newObjectV(Thread* t, uintptr_t* arguments) +uint64_t newObjectV(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; va_list* a = reinterpret_cast(arguments[2]); - object o = make(t, jclassVmClass(t, *c)); + object o = make(t, (*c)->vmClass()); PROTECT(t, o); t->m->processor->invokeList(t, getMethod(t, m), o, true, *a); @@ -629,18 +604,16 @@ newObjectV(Thread* t, uintptr_t* arguments) return reinterpret_cast(makeLocalReference(t, o)); } -jobject JNICALL -NewObjectV(Thread* t, jclass c, jmethodID m, va_list a) +jobject JNICALL NewObjectV(Thread* t, jclass c, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(c), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(c), + m, + reinterpret_cast(VA_LIST(a))}; return reinterpret_cast(run(t, newObjectV, arguments)); } -jobject JNICALL -NewObject(Thread* t, jclass c, jmethodID m, ...) +jobject JNICALL NewObject(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -652,14 +625,13 @@ NewObject(Thread* t, jclass c, jmethodID m, ...) return r; } -uint64_t -newObjectA(Thread* t, uintptr_t* arguments) +uint64_t newObjectA(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; const jvalue* a = reinterpret_cast(arguments[2]); - object o = make(t, jclassVmClass(t, *c)); + object o = make(t, (*c)->vmClass()); PROTECT(t, o); t->m->processor->invokeArray(t, getMethod(t, m), o, a); @@ -667,40 +639,34 @@ newObjectA(Thread* t, uintptr_t* arguments) return reinterpret_cast(makeLocalReference(t, o)); } -jobject JNICALL -NewObjectA(Thread* t, jobject o, jmethodID m, const jvalue* a) +jobject JNICALL NewObjectA(Thread* t, jclass c, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(c), m, reinterpret_cast(a)}; return reinterpret_cast(run(t, newObjectA, arguments)); } -uint64_t -callObjectMethodV(Thread* t, uintptr_t* arguments) +uint64_t callObjectMethodV(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; va_list* a = reinterpret_cast(arguments[2]); - return reinterpret_cast - (makeLocalReference - (t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a))); + return reinterpret_cast(makeLocalReference( + t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a))); } -jobject JNICALL -CallObjectMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jobject JNICALL CallObjectMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return reinterpret_cast(run(t, callObjectMethodV, arguments)); } -jobject JNICALL -CallObjectMethod(Thread* t, jobject o, jmethodID m, ...) +jobject JNICALL CallObjectMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -712,51 +678,47 @@ CallObjectMethod(Thread* t, jobject o, jmethodID m, ...) return r; } -uint64_t -callObjectMethodA(Thread* t, uintptr_t* arguments) +uint64_t callObjectMethodA(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; const jvalue* a = reinterpret_cast(arguments[2]); - return reinterpret_cast - (makeLocalReference - (t, t->m->processor->invokeArray(t, getMethod(t, m), *o, a))); + return reinterpret_cast(makeLocalReference( + t, t->m->processor->invokeArray(t, getMethod(t, m), *o, a))); } jobject JNICALL -CallObjectMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallObjectMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return reinterpret_cast(run(t, callObjectMethodA, arguments)); } -uint64_t -callIntMethodV(Thread* t, uintptr_t* arguments) +uint64_t callIntMethodV(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; va_list* a = reinterpret_cast(arguments[2]); - return intValue - (t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a)); + return cast( + t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a)) + ->value(); } jboolean JNICALL -CallBooleanMethodV(Thread* t, jobject o, jmethodID m, va_list a) + CallBooleanMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callIntMethodV, arguments) != 0; } -jboolean JNICALL -CallBooleanMethod(Thread* t, jobject o, jmethodID m, ...) +jboolean JNICALL CallBooleanMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -768,39 +730,35 @@ CallBooleanMethod(Thread* t, jobject o, jmethodID m, ...) return r; } -uint64_t -callIntMethodA(Thread* t, uintptr_t* arguments) +uint64_t callIntMethodA(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; const jvalue* a = reinterpret_cast(arguments[2]); - return intValue - (t, t->m->processor->invokeArray(t, getMethod(t, m), *o, a)); + return cast(t, t->m->processor->invokeArray(t, getMethod(t, m), *o, a)) + ->value(); } jboolean JNICALL -CallBooleanMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallBooleanMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callIntMethodA, arguments) != 0; } -jbyte JNICALL -CallByteMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jbyte JNICALL CallByteMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callIntMethodV, arguments); } -jbyte JNICALL -CallByteMethod(Thread* t, jobject o, jmethodID m, ...) +jbyte JNICALL CallByteMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -813,27 +771,24 @@ CallByteMethod(Thread* t, jobject o, jmethodID m, ...) } jbyte JNICALL -CallByteMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallByteMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callIntMethodA, arguments); } -jchar JNICALL -CallCharMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jchar JNICALL CallCharMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callIntMethodV, arguments); } -jchar JNICALL -CallCharMethod(Thread* t, jobject o, jmethodID m, ...) +jchar JNICALL CallCharMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -846,27 +801,24 @@ CallCharMethod(Thread* t, jobject o, jmethodID m, ...) } jchar JNICALL -CallCharMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallCharMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callIntMethodA, arguments); } -jshort JNICALL -CallShortMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jshort JNICALL CallShortMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callIntMethodV, arguments); } -jshort JNICALL -CallShortMethod(Thread* t, jobject o, jmethodID m, ...) +jshort JNICALL CallShortMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -879,27 +831,24 @@ CallShortMethod(Thread* t, jobject o, jmethodID m, ...) } jshort JNICALL -CallShortMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallShortMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callIntMethodA, arguments); } -jint JNICALL -CallIntMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jint JNICALL CallIntMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callIntMethodV, arguments); } -jint JNICALL -CallIntMethod(Thread* t, jobject o, jmethodID m, ...) +jint JNICALL CallIntMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -911,39 +860,35 @@ CallIntMethod(Thread* t, jobject o, jmethodID m, ...) return r; } -jint JNICALL -CallIntMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) +jint JNICALL CallIntMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callIntMethodA, arguments); } -uint64_t -callLongMethodV(Thread* t, uintptr_t* arguments) +uint64_t callLongMethodV(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; va_list* a = reinterpret_cast(arguments[2]); - return longValue - (t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a)); + return cast( + t, t->m->processor->invokeList(t, getMethod(t, m), *o, true, *a)) + ->value(); } -jlong JNICALL -CallLongMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jlong JNICALL CallLongMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return run(t, callLongMethodV, arguments); } -jlong JNICALL -CallLongMethod(Thread* t, jobject o, jmethodID m, ...) +jlong JNICALL CallLongMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -955,39 +900,36 @@ CallLongMethod(Thread* t, jobject o, jmethodID m, ...) return r; } -uint64_t -callLongMethodA(Thread* t, uintptr_t* arguments) +uint64_t callLongMethodA(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; const jvalue* a = reinterpret_cast(arguments[2]); - return longValue - (t, t->m->processor->invokeArray(t, getMethod(t, m), *o, a)); + return cast(t, + t->m->processor->invokeArray(t, getMethod(t, m), *o, a)) + ->value(); } jlong JNICALL -CallLongMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallLongMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return run(t, callLongMethodA, arguments); } -jfloat JNICALL -CallFloatMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jfloat JNICALL CallFloatMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return bitsToFloat(run(t, callIntMethodV, arguments)); } -jfloat JNICALL -CallFloatMethod(Thread* t, jobject o, jmethodID m, ...) +jfloat JNICALL CallFloatMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1000,27 +942,24 @@ CallFloatMethod(Thread* t, jobject o, jmethodID m, ...) } jfloat JNICALL -CallFloatMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallFloatMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return bitsToFloat(run(t, callIntMethodA, arguments)); } -jdouble JNICALL -CallDoubleMethodV(Thread* t, jobject o, jmethodID m, va_list a) +jdouble JNICALL CallDoubleMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; return bitsToDouble(run(t, callLongMethodV, arguments)); } -jdouble JNICALL -CallDoubleMethod(Thread* t, jobject o, jmethodID m, ...) +jdouble JNICALL CallDoubleMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1033,17 +972,15 @@ CallDoubleMethod(Thread* t, jobject o, jmethodID m, ...) } jdouble JNICALL -CallDoubleMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) + CallDoubleMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; return bitsToDouble(run(t, callLongMethodA, arguments)); } -uint64_t -callVoidMethodV(Thread* t, uintptr_t* arguments) +uint64_t callVoidMethodV(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; @@ -1054,18 +991,16 @@ callVoidMethodV(Thread* t, uintptr_t* arguments) return 0; } -void JNICALL -CallVoidMethodV(Thread* t, jobject o, jmethodID m, va_list a) +void JNICALL CallVoidMethodV(Thread* t, jobject o, jmethodID m, va_list a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {reinterpret_cast(o), + m, + reinterpret_cast(VA_LIST(a))}; run(t, callVoidMethodV, arguments); } -void JNICALL -CallVoidMethod(Thread* t, jobject o, jmethodID m, ...) +void JNICALL CallVoidMethod(Thread* t, jobject o, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1075,8 +1010,7 @@ CallVoidMethod(Thread* t, jobject o, jmethodID m, ...) va_end(a); } -uint64_t -callVoidMethodA(Thread* t, uintptr_t* arguments) +uint64_t callVoidMethodA(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); jmethodID m = arguments[1]; @@ -1087,49 +1021,44 @@ callVoidMethodA(Thread* t, uintptr_t* arguments) return 0; } -void JNICALL -CallVoidMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) +void JNICALL CallVoidMethodA(Thread* t, jobject o, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { reinterpret_cast(o), - m, - reinterpret_cast(a) }; + uintptr_t arguments[] + = {reinterpret_cast(o), m, reinterpret_cast(a)}; run(t, callVoidMethodA, arguments); } -object -getStaticMethod(Thread* t, jmethodID m) +GcMethod* getStaticMethod(Thread* t, jmethodID m) { - assert(t, m); + assertT(t, m); - object method = vectorBody(t, root(t, Machine::JNIMethodTable), m - 1); + GcMethod* method + = cast(t, roots(t)->jNIMethodTable()->body()[m - 1]); - assert(t, methodFlags(t, method) & ACC_STATIC); + assertT(t, method->flags() & ACC_STATIC); return method; } -uint64_t -callStaticObjectMethodV(Thread* t, uintptr_t* arguments) +uint64_t callStaticObjectMethodV(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; va_list* a = reinterpret_cast(arguments[1]); - return reinterpret_cast - (makeLocalReference - (t, t->m->processor->invokeList(t, getStaticMethod(t, m), 0, true, *a))); + return reinterpret_cast(makeLocalReference( + t, t->m->processor->invokeList(t, getStaticMethod(t, m), 0, true, *a))); } jobject JNICALL -CallStaticObjectMethodV(Thread* t, jclass, jmethodID m, va_list a) + CallStaticObjectMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return reinterpret_cast(run(t, callStaticObjectMethodV, arguments)); } -jobject JNICALL -CallStaticObjectMethod(Thread* t, jclass c, jmethodID m, ...) +jobject JNICALL CallStaticObjectMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1141,45 +1070,42 @@ CallStaticObjectMethod(Thread* t, jclass c, jmethodID m, ...) return r; } -uint64_t -callStaticObjectMethodA(Thread* t, uintptr_t* arguments) +uint64_t callStaticObjectMethodA(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; const jvalue* a = reinterpret_cast(arguments[1]); - return reinterpret_cast - (makeLocalReference - (t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a))); + return reinterpret_cast(makeLocalReference( + t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a))); } jobject JNICALL -CallStaticObjectMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticObjectMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return reinterpret_cast(run(t, callStaticObjectMethodA, arguments)); } -uint64_t -callStaticIntMethodV(Thread* t, uintptr_t* arguments) +uint64_t callStaticIntMethodV(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; va_list* a = reinterpret_cast(arguments[1]); - return intValue - (t, t->m->processor->invokeList(t, getStaticMethod(t, m), 0, true, *a)); + return cast(t, + t->m->processor->invokeList( + t, getStaticMethod(t, m), 0, true, *a))->value(); } jboolean JNICALL -CallStaticBooleanMethodV(Thread* t, jclass, jmethodID m, va_list a) + CallStaticBooleanMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticIntMethodV, arguments) != 0; } -jboolean JNICALL -CallStaticBooleanMethod(Thread* t, jclass c, jmethodID m, ...) +jboolean JNICALL CallStaticBooleanMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1191,34 +1117,32 @@ CallStaticBooleanMethod(Thread* t, jclass c, jmethodID m, ...) return r; } -uint64_t -callStaticIntMethodA(Thread* t, uintptr_t* arguments) +uint64_t callStaticIntMethodA(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; const jvalue* a = reinterpret_cast(arguments[1]); - return intValue - (t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a)); + return cast( + t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a)) + ->value(); } jboolean JNICALL -CallStaticBooleanMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticBooleanMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticIntMethodA, arguments) != 0; } -jbyte JNICALL -CallStaticByteMethodV(Thread* t, jclass, jmethodID m, va_list a) +jbyte JNICALL CallStaticByteMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticIntMethodV, arguments); } -jbyte JNICALL -CallStaticByteMethod(Thread* t, jclass c, jmethodID m, ...) +jbyte JNICALL CallStaticByteMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1231,23 +1155,21 @@ CallStaticByteMethod(Thread* t, jclass c, jmethodID m, ...) } jbyte JNICALL -CallStaticByteMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticByteMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticIntMethodA, arguments); } -jchar JNICALL -CallStaticCharMethodV(Thread* t, jclass, jmethodID m, va_list a) +jchar JNICALL CallStaticCharMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticIntMethodV, arguments); } -jchar JNICALL -CallStaticCharMethod(Thread* t, jclass c, jmethodID m, ...) +jchar JNICALL CallStaticCharMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1260,23 +1182,21 @@ CallStaticCharMethod(Thread* t, jclass c, jmethodID m, ...) } jchar JNICALL -CallStaticCharMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticCharMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticIntMethodA, arguments); } -jshort JNICALL -CallStaticShortMethodV(Thread* t, jclass, jmethodID m, va_list a) +jshort JNICALL CallStaticShortMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticIntMethodV, arguments); } -jshort JNICALL -CallStaticShortMethod(Thread* t, jclass c, jmethodID m, ...) +jshort JNICALL CallStaticShortMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1289,23 +1209,21 @@ CallStaticShortMethod(Thread* t, jclass c, jmethodID m, ...) } jshort JNICALL -CallStaticShortMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticShortMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticIntMethodA, arguments); } -jint JNICALL -CallStaticIntMethodV(Thread* t, jclass, jmethodID m, va_list a) +jint JNICALL CallStaticIntMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticIntMethodV, arguments); } -jint JNICALL -CallStaticIntMethod(Thread* t, jclass c, jmethodID m, ...) +jint JNICALL CallStaticIntMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1318,33 +1236,31 @@ CallStaticIntMethod(Thread* t, jclass c, jmethodID m, ...) } jint JNICALL -CallStaticIntMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticIntMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticIntMethodA, arguments); } -uint64_t -callStaticLongMethodV(Thread* t, uintptr_t* arguments) +uint64_t callStaticLongMethodV(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; va_list* a = reinterpret_cast(arguments[1]); - return longValue - (t, t->m->processor->invokeList(t, getStaticMethod(t, m), 0, true, *a)); + return cast(t, + t->m->processor->invokeList( + t, getStaticMethod(t, m), 0, true, *a))->value(); } -jlong JNICALL -CallStaticLongMethodV(Thread* t, jclass, jmethodID m, va_list a) +jlong JNICALL CallStaticLongMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return run(t, callStaticLongMethodV, arguments); } -jlong JNICALL -CallStaticLongMethod(Thread* t, jclass c, jmethodID m, ...) +jlong JNICALL CallStaticLongMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1356,34 +1272,32 @@ CallStaticLongMethod(Thread* t, jclass c, jmethodID m, ...) return r; } -uint64_t -callStaticLongMethodA(Thread* t, uintptr_t* arguments) +uint64_t callStaticLongMethodA(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; const jvalue* a = reinterpret_cast(arguments[1]); - return longValue - (t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a)); + return cast( + t, t->m->processor->invokeArray(t, getStaticMethod(t, m), 0, a)) + ->value(); } jlong JNICALL -CallStaticLongMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticLongMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return run(t, callStaticLongMethodA, arguments); } -jfloat JNICALL -CallStaticFloatMethodV(Thread* t, jclass, jmethodID m, va_list a) +jfloat JNICALL CallStaticFloatMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return bitsToFloat(run(t, callStaticIntMethodV, arguments)); } -jfloat JNICALL -CallStaticFloatMethod(Thread* t, jclass c, jmethodID m, ...) +jfloat JNICALL CallStaticFloatMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1396,23 +1310,22 @@ CallStaticFloatMethod(Thread* t, jclass c, jmethodID m, ...) } jfloat JNICALL -CallStaticFloatMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticFloatMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return bitsToFloat(run(t, callStaticIntMethodA, arguments)); } jdouble JNICALL -CallStaticDoubleMethodV(Thread* t, jclass, jmethodID m, va_list a) + CallStaticDoubleMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; return bitsToDouble(run(t, callStaticLongMethodV, arguments)); } -jdouble JNICALL -CallStaticDoubleMethod(Thread* t, jclass c, jmethodID m, ...) +jdouble JNICALL CallStaticDoubleMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1425,15 +1338,14 @@ CallStaticDoubleMethod(Thread* t, jclass c, jmethodID m, ...) } jdouble JNICALL -CallStaticDoubleMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticDoubleMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; return bitsToDouble(run(t, callStaticLongMethodA, arguments)); } -uint64_t -callStaticVoidMethodV(Thread* t, uintptr_t* arguments) +uint64_t callStaticVoidMethodV(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; va_list* a = reinterpret_cast(arguments[1]); @@ -1443,16 +1355,14 @@ callStaticVoidMethodV(Thread* t, uintptr_t* arguments) return 0; } -void JNICALL -CallStaticVoidMethodV(Thread* t, jclass, jmethodID m, va_list a) +void JNICALL CallStaticVoidMethodV(Thread* t, jclass, jmethodID m, va_list a) { - uintptr_t arguments[] = { m, reinterpret_cast(VA_LIST(a)) }; + uintptr_t arguments[] = {m, reinterpret_cast(VA_LIST(a))}; run(t, callStaticVoidMethodV, arguments); } -void JNICALL -CallStaticVoidMethod(Thread* t, jclass c, jmethodID m, ...) +void JNICALL CallStaticVoidMethod(Thread* t, jclass c, jmethodID m, ...) { va_list a; va_start(a, m); @@ -1462,8 +1372,7 @@ CallStaticVoidMethod(Thread* t, jclass c, jmethodID m, ...) va_end(a); } -uint64_t -callStaticVoidMethodA(Thread* t, uintptr_t* arguments) +uint64_t callStaticVoidMethodA(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[0]; const jvalue* a = reinterpret_cast(arguments[1]); @@ -1474,17 +1383,16 @@ callStaticVoidMethodA(Thread* t, uintptr_t* arguments) } void JNICALL -CallStaticVoidMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) + CallStaticVoidMethodA(Thread* t, jclass, jmethodID m, const jvalue* a) { - uintptr_t arguments[] = { m, reinterpret_cast(a) }; + uintptr_t arguments[] = {m, reinterpret_cast(a)}; run(t, callStaticVoidMethodA, arguments); } -jint -fieldID(Thread* t, object field) +jint fieldID(Thread* t, GcField* field) { - int id = fieldNativeID(t, field); + int id = field->nativeID(); loadMemoryBarrier(); @@ -1492,419 +1400,370 @@ fieldID(Thread* t, object field) PROTECT(t, field); ACQUIRE(t, t->m->referenceLock); - - if (fieldNativeID(t, field) == 0) { - setRoot(t, Machine::JNIFieldTable, vectorAppend - (t, root(t, Machine::JNIFieldTable), field)); + + if (field->nativeID() == 0) { + GcVector* v = vectorAppend(t, roots(t)->jNIFieldTable(), field); + // sequence point, for gc (don't recombine statements) + roots(t)->setJNIFieldTable(t, v); storeStoreMemoryBarrier(); - fieldNativeID(t, field) = vectorSize(t, root(t, Machine::JNIFieldTable)); + field->nativeID() = roots(t)->jNIFieldTable()->size(); } } - return fieldNativeID(t, field); + return field->nativeID(); } -uint64_t -getFieldID(Thread* t, uintptr_t* arguments) +uint64_t getFieldID(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); const char* name = reinterpret_cast(arguments[1]); const char* spec = reinterpret_cast(arguments[2]); - return fieldID(t, resolveField(t, jclassVmClass(t, *c), name, spec)); + return fieldID(t, resolveField(t, (*c)->vmClass(), name, spec)); } jfieldID JNICALL -GetFieldID(Thread* t, jclass c, const char* name, const char* spec) + GetFieldID(Thread* t, jclass c, const char* name, const char* spec) { - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(name), - reinterpret_cast(spec) }; + uintptr_t arguments[] = {reinterpret_cast(c), + reinterpret_cast(name), + reinterpret_cast(spec)}; return run(t, getFieldID, arguments); } jfieldID JNICALL -GetStaticFieldID(Thread* t, jclass c, const char* name, const char* spec) + GetStaticFieldID(Thread* t, jclass c, const char* name, const char* spec) { - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(name), - reinterpret_cast(spec) }; + uintptr_t arguments[] = {reinterpret_cast(c), + reinterpret_cast(name), + reinterpret_cast(spec)}; return run(t, getFieldID, arguments); } -object -getField(Thread* t, jfieldID f) +GcField* getField(Thread* t, jfieldID f) { - assert(t, f); + assertT(t, f); - object field = vectorBody(t, root(t, Machine::JNIFieldTable), f - 1); + GcField* field = cast(t, roots(t)->jNIFieldTable()->body()[f - 1]); - assert(t, (fieldFlags(t, field) & ACC_STATIC) == 0); + assertT(t, (field->flags() & ACC_STATIC) == 0); return field; } -uint64_t -getObjectField(Thread* t, uintptr_t* arguments) +uint64_t getObjectField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return reinterpret_cast - (makeLocalReference(t, fieldAtOffset(*o, fieldOffset(t, field)))); + return reinterpret_cast( + makeLocalReference(t, fieldAtOffset(*o, field->offset()))); } -jobject JNICALL -GetObjectField(Thread* t, jobject o, jfieldID field) +jobject JNICALL GetObjectField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return reinterpret_cast(run(t, getObjectField, arguments)); } -uint64_t -getBooleanField(Thread* t, uintptr_t* arguments) +uint64_t getBooleanField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jboolean JNICALL -GetBooleanField(Thread* t, jobject o, jfieldID field) +jboolean JNICALL GetBooleanField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getBooleanField, arguments); } -uint64_t -getByteField(Thread* t, uintptr_t* arguments) +uint64_t getByteField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jbyte JNICALL -GetByteField(Thread* t, jobject o, jfieldID field) +jbyte JNICALL GetByteField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getByteField, arguments); } -uint64_t -getCharField(Thread* t, uintptr_t* arguments) +uint64_t getCharField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jchar JNICALL -GetCharField(Thread* t, jobject o, jfieldID field) +jchar JNICALL GetCharField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getCharField, arguments); } -uint64_t -getShortField(Thread* t, uintptr_t* arguments) +uint64_t getShortField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jshort JNICALL -GetShortField(Thread* t, jobject o, jfieldID field) +jshort JNICALL GetShortField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getShortField, arguments); } -uint64_t -getIntField(Thread* t, uintptr_t* arguments) +uint64_t getIntField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jint JNICALL -GetIntField(Thread* t, jobject o, jfieldID field) +jint JNICALL GetIntField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getIntField, arguments); } -uint64_t -getLongField(Thread* t, uintptr_t* arguments) +uint64_t getLongField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset(*o, fieldOffset(t, field)); + return fieldAtOffset(*o, field->offset()); } -jlong JNICALL -GetLongField(Thread* t, jobject o, jfieldID field) +jlong JNICALL GetLongField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return run(t, getLongField, arguments); } -uint64_t -getFloatField(Thread* t, uintptr_t* arguments) +uint64_t getFloatField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return floatToBits(fieldAtOffset(*o, fieldOffset(t, field))); + return floatToBits(fieldAtOffset(*o, field->offset())); } -jfloat JNICALL -GetFloatField(Thread* t, jobject o, jfieldID field) +jfloat JNICALL GetFloatField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return bitsToFloat(run(t, getFloatField, arguments)); } -uint64_t -getDoubleField(Thread* t, uintptr_t* arguments) +uint64_t getDoubleField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return doubleToBits(fieldAtOffset(*o, fieldOffset(t, field))); + return doubleToBits(fieldAtOffset(*o, field->offset())); } -jdouble JNICALL -GetDoubleField(Thread* t, jobject o, jfieldID field) +jdouble JNICALL GetDoubleField(Thread* t, jobject o, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(o), - field }; + uintptr_t arguments[] = {reinterpret_cast(o), field}; return bitsToDouble(run(t, getDoubleField, arguments)); } -uint64_t -setObjectField(Thread* t, uintptr_t* arguments) +uint64_t setObjectField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jobject v = reinterpret_cast(arguments[2]); - + PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - set(t, *o, fieldOffset(t, field), (v ? *v : 0)); - + setField(t, *o, field->offset(), (v ? *v : 0)); + return 1; } -void JNICALL -SetObjectField(Thread* t, jobject o, jfieldID field, jobject v) +void JNICALL SetObjectField(Thread* t, jobject o, jfieldID field, jobject v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - reinterpret_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(o), field, reinterpret_cast(v)}; run(t, setObjectField, arguments); } -uint64_t -setBooleanField(Thread* t, uintptr_t* arguments) +uint64_t setBooleanField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jboolean v = arguments[2]; - + PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetBooleanField(Thread* t, jobject o, jfieldID field, jboolean v) +void JNICALL SetBooleanField(Thread* t, jobject o, jfieldID field, jboolean v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - v }; + uintptr_t arguments[] = {reinterpret_cast(o), field, v}; run(t, setBooleanField, arguments); } -uint64_t -setByteField(Thread* t, uintptr_t* arguments) +uint64_t setByteField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jbyte v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetByteField(Thread* t, jobject o, jfieldID field, jbyte v) +void JNICALL SetByteField(Thread* t, jobject o, jfieldID field, jbyte v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(o), field, static_cast(v)}; run(t, setByteField, arguments); } -uint64_t -setCharField(Thread* t, uintptr_t* arguments) +uint64_t setCharField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jchar v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetCharField(Thread* t, jobject o, jfieldID field, jchar v) +void JNICALL SetCharField(Thread* t, jobject o, jfieldID field, jchar v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - v }; + uintptr_t arguments[] = {reinterpret_cast(o), field, v}; run(t, setCharField, arguments); } -uint64_t -setShortField(Thread* t, uintptr_t* arguments) +uint64_t setShortField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jshort v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetShortField(Thread* t, jobject o, jfieldID field, jshort v) +void JNICALL SetShortField(Thread* t, jobject o, jfieldID field, jshort v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(o), field, static_cast(v)}; run(t, setShortField, arguments); } -uint64_t -setIntField(Thread* t, uintptr_t* arguments) +uint64_t setIntField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jint v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetIntField(Thread* t, jobject o, jfieldID field, jint v) +void JNICALL SetIntField(Thread* t, jobject o, jfieldID field, jint v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(o), field, static_cast(v)}; run(t, setIntField, arguments); } -uint64_t -setLongField(Thread* t, uintptr_t* arguments) +uint64_t setLongField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); - jlong v; memcpy(&v, arguments + 2, sizeof(jlong)); + GcField* field = getField(t, arguments[1]); + jlong v; + memcpy(&v, arguments + 2, sizeof(jlong)); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetLongField(Thread* t, jobject o, jfieldID field, jlong v) +void JNICALL SetLongField(Thread* t, jobject o, jfieldID field, jlong v) { uintptr_t arguments[2 + (sizeof(jlong) / BytesPerWord)]; arguments[0] = reinterpret_cast(o); @@ -1914,48 +1773,44 @@ SetLongField(Thread* t, jobject o, jfieldID field, jlong v) run(t, setLongField, arguments); } -uint64_t -setFloatField(Thread* t, uintptr_t* arguments) +uint64_t setFloatField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); + GcField* field = getField(t, arguments[1]); jfloat v = bitsToFloat(arguments[2]); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetFloatField(Thread* t, jobject o, jfieldID field, jfloat v) +void JNICALL SetFloatField(Thread* t, jobject o, jfieldID field, jfloat v) { - uintptr_t arguments[] = { reinterpret_cast(o), - field, - floatToBits(v) }; + uintptr_t arguments[] + = {reinterpret_cast(o), field, floatToBits(v)}; run(t, setFloatField, arguments); } -uint64_t -setDoubleField(Thread* t, uintptr_t* arguments) +uint64_t setDoubleField(Thread* t, uintptr_t* arguments) { jobject o = reinterpret_cast(arguments[0]); - object field = getField(t, arguments[1]); - jdouble v; memcpy(&v, arguments + 2, sizeof(jdouble)); + GcField* field = getField(t, arguments[1]); + jdouble v; + memcpy(&v, arguments + 2, sizeof(jdouble)); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset(*o, fieldOffset(t, field)) = v; - + + fieldAtOffset(*o, field->offset()) = v; + return 1; } -void JNICALL -SetDoubleField(Thread* t, jobject o, jfieldID field, jdouble v) +void JNICALL SetDoubleField(Thread* t, jobject o, jfieldID field, jdouble v) { uintptr_t arguments[2 + (sizeof(jdouble) / BytesPerWord)]; arguments[0] = reinterpret_cast(o); @@ -1965,442 +1820,378 @@ SetDoubleField(Thread* t, jobject o, jfieldID field, jdouble v) run(t, setDoubleField, arguments); } -object -getStaticField(Thread* t, jfieldID f) +GcField* getStaticField(Thread* t, jfieldID f) { - assert(t, f); + assertT(t, f); - object field = vectorBody(t, root(t, Machine::JNIFieldTable), f - 1); + GcField* field = cast(t, roots(t)->jNIFieldTable()->body()[f - 1]); - assert(t, fieldFlags(t, field) & ACC_STATIC); + assertT(t, field->flags() & ACC_STATIC); return field; } -uint64_t -getStaticObjectField(Thread* t, uintptr_t* arguments) +uint64_t getStaticObjectField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return reinterpret_cast - (makeLocalReference - (t, fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)))); + return reinterpret_cast(makeLocalReference( + t, fieldAtOffset(c->vmClass()->staticTable(), field->offset()))); } -jobject JNICALL -GetStaticObjectField(Thread* t, jobject c, jfieldID field) +jobject JNICALL GetStaticObjectField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return reinterpret_cast(run(t, getStaticObjectField, arguments)); } -uint64_t -getStaticBooleanField(Thread* t, uintptr_t* arguments) +uint64_t getStaticBooleanField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jboolean JNICALL -GetStaticBooleanField(Thread* t, jobject c, jfieldID field) +jboolean JNICALL GetStaticBooleanField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticBooleanField, arguments); } -uint64_t -getStaticByteField(Thread* t, uintptr_t* arguments) +uint64_t getStaticByteField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jbyte JNICALL -GetStaticByteField(Thread* t, jobject c, jfieldID field) +jbyte JNICALL GetStaticByteField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticByteField, arguments); } -uint64_t -getStaticCharField(Thread* t, uintptr_t* arguments) +uint64_t getStaticCharField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jchar JNICALL -GetStaticCharField(Thread* t, jobject c, jfieldID field) +jchar JNICALL GetStaticCharField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticCharField, arguments); } -uint64_t -getStaticShortField(Thread* t, uintptr_t* arguments) +uint64_t getStaticShortField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jshort JNICALL -GetStaticShortField(Thread* t, jobject c, jfieldID field) +jshort JNICALL GetStaticShortField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticShortField, arguments); } -uint64_t -getStaticIntField(Thread* t, uintptr_t* arguments) +uint64_t getStaticIntField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jint JNICALL -GetStaticIntField(Thread* t, jobject c, jfieldID field) +jint JNICALL GetStaticIntField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticIntField, arguments); } -uint64_t -getStaticLongField(Thread* t, uintptr_t* arguments) +uint64_t getStaticLongField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)); + return fieldAtOffset(c->vmClass()->staticTable(), field->offset()); } -jlong JNICALL -GetStaticLongField(Thread* t, jobject c, jfieldID field) +jlong JNICALL GetStaticLongField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return run(t, getStaticLongField, arguments); } -uint64_t -getStaticFloatField(Thread* t, uintptr_t* arguments) +uint64_t getStaticFloatField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return floatToBits - (fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field))); + return floatToBits( + fieldAtOffset(c->vmClass()->staticTable(), field->offset())); } -jfloat JNICALL -GetStaticFloatField(Thread* t, jobject c, jfieldID field) +jfloat JNICALL GetStaticFloatField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return bitsToFloat(run(t, getStaticFloatField, arguments)); } -uint64_t -getStaticDoubleField(Thread* t, uintptr_t* arguments) +uint64_t getStaticDoubleField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); PROTECT(t, field); ACQUIRE_FIELD_FOR_READ(t, field); - return doubleToBits - (fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field))); + return doubleToBits( + fieldAtOffset(c->vmClass()->staticTable(), field->offset())); } -jdouble JNICALL -GetStaticDoubleField(Thread* t, jobject c, jfieldID field) +jdouble JNICALL GetStaticDoubleField(Thread* t, jclass c, jfieldID field) { - uintptr_t arguments[] = { reinterpret_cast(c), - field }; + uintptr_t arguments[] = {reinterpret_cast(c), field}; return bitsToDouble(run(t, getStaticDoubleField, arguments)); } -uint64_t -setStaticObjectField(Thread* t, uintptr_t* arguments) +uint64_t setStaticObjectField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jobject v = reinterpret_cast(arguments[2]); - + PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - set(t, classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field), - (v ? *v : 0)); - + setField(t, c->vmClass()->staticTable(), field->offset(), (v ? *v : 0)); + return 1; } void JNICALL -SetStaticObjectField(Thread* t, jobject c, jfieldID field, jobject v) + SetStaticObjectField(Thread* t, jclass c, jfieldID field, jobject v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - reinterpret_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(c), field, reinterpret_cast(v)}; run(t, setStaticObjectField, arguments); } -uint64_t -setStaticBooleanField(Thread* t, uintptr_t* arguments) +uint64_t setStaticBooleanField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jboolean v = arguments[2]; - + PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } void JNICALL -SetStaticBooleanField(Thread* t, jobject c, jfieldID field, jboolean v) + SetStaticBooleanField(Thread* t, jclass c, jfieldID field, jboolean v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - v }; + uintptr_t arguments[] = {reinterpret_cast(c), field, v}; run(t, setStaticBooleanField, arguments); } -uint64_t -setStaticByteField(Thread* t, uintptr_t* arguments) +uint64_t setStaticByteField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jbyte v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticByteField(Thread* t, jobject c, jfieldID field, jbyte v) +void JNICALL SetStaticByteField(Thread* t, jclass c, jfieldID field, jbyte v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(c), field, static_cast(v)}; run(t, setStaticByteField, arguments); } -uint64_t -setStaticCharField(Thread* t, uintptr_t* arguments) +uint64_t setStaticCharField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jchar v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticCharField(Thread* t, jobject c, jfieldID field, jchar v) +void JNICALL SetStaticCharField(Thread* t, jclass c, jfieldID field, jchar v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - v }; + uintptr_t arguments[] = {reinterpret_cast(c), field, v}; run(t, setStaticCharField, arguments); } -uint64_t -setStaticShortField(Thread* t, uintptr_t* arguments) +uint64_t setStaticShortField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jshort v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticShortField(Thread* t, jobject c, jfieldID field, jshort v) +void JNICALL SetStaticShortField(Thread* t, jclass c, jfieldID field, jshort v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(c), field, static_cast(v)}; run(t, setStaticShortField, arguments); } -uint64_t -setStaticIntField(Thread* t, uintptr_t* arguments) +uint64_t setStaticIntField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jint v = arguments[2]; PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticIntField(Thread* t, jobject c, jfieldID field, jint v) +void JNICALL SetStaticIntField(Thread* t, jclass c, jfieldID field, jint v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - static_cast(v) }; + uintptr_t arguments[] + = {reinterpret_cast(c), field, static_cast(v)}; run(t, setStaticIntField, arguments); } -uint64_t -setStaticLongField(Thread* t, uintptr_t* arguments) +uint64_t setStaticLongField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); - jlong v; memcpy(&v, arguments + 2, sizeof(jlong)); + GcField* field = getStaticField(t, arguments[1]); + jlong v; + memcpy(&v, arguments + 2, sizeof(jlong)); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticLongField(Thread* t, jobject c, jfieldID field, jlong v) +void JNICALL SetStaticLongField(Thread* t, jclass c, jfieldID field, jlong v) { uintptr_t arguments[2 + (sizeof(jlong) / BytesPerWord)]; arguments[0] = reinterpret_cast(c); @@ -2410,56 +2201,51 @@ SetStaticLongField(Thread* t, jobject c, jfieldID field, jlong v) run(t, setStaticLongField, arguments); } -uint64_t -setStaticFloatField(Thread* t, uintptr_t* arguments) +uint64_t setStaticFloatField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); + GcField* field = getStaticField(t, arguments[1]); jfloat v = bitsToFloat(arguments[2]); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } -void JNICALL -SetStaticFloatField(Thread* t, jobject c, jfieldID field, jfloat v) +void JNICALL SetStaticFloatField(Thread* t, jclass c, jfieldID field, jfloat v) { - uintptr_t arguments[] = { reinterpret_cast(c), - field, - floatToBits(v) }; + uintptr_t arguments[] + = {reinterpret_cast(c), field, floatToBits(v)}; run(t, setStaticFloatField, arguments); } -uint64_t -setStaticDoubleField(Thread* t, uintptr_t* arguments) +uint64_t setStaticDoubleField(Thread* t, uintptr_t* arguments) { - jobject c = reinterpret_cast(arguments[0]); + GcJclass* c = cast(t, *reinterpret_cast(arguments[0])); - initClass(t, jclassVmClass(t, *c)); + initClass(t, c->vmClass()); - object field = getStaticField(t, arguments[1]); - jdouble v; memcpy(&v, arguments + 2, sizeof(jdouble)); + GcField* field = getStaticField(t, arguments[1]); + jdouble v; + memcpy(&v, arguments + 2, sizeof(jdouble)); PROTECT(t, field); ACQUIRE_FIELD_FOR_WRITE(t, field); - - fieldAtOffset - (classStaticTable(t, jclassVmClass(t, *c)), fieldOffset(t, field)) = v; - + + fieldAtOffset(c->vmClass()->staticTable(), field->offset()) = v; + return 1; } void JNICALL -SetStaticDoubleField(Thread* t, jobject c, jfieldID field, jdouble v) + SetStaticDoubleField(Thread* t, jclass c, jfieldID field, jdouble v) { uintptr_t arguments[2 + (sizeof(jdouble) / BytesPerWord)]; arguments[0] = reinterpret_cast(c); @@ -2469,13 +2255,12 @@ SetStaticDoubleField(Thread* t, jobject c, jfieldID field, jdouble v) run(t, setStaticDoubleField, arguments); } -jobject JNICALL -newGlobalRef(Thread* t, jobject o, bool weak) +jobject JNICALL newGlobalRef(Thread* t, jobject o, bool weak) { ENTER(t, Thread::ActiveState); ACQUIRE(t, t->m->referenceLock); - + if (o) { for (Reference* r = t->m->jniReferences; r; r = r->next) { if (r->target == *o and r->weak == weak) { @@ -2486,7 +2271,7 @@ newGlobalRef(Thread* t, jobject o, bool weak) } Reference* r = new (t->m->heap->allocate(sizeof(Reference))) - Reference(*o, &(t->m->jniReferences), weak); + Reference(*o, &(t->m->jniReferences), weak); acquire(t, r); @@ -2496,215 +2281,201 @@ newGlobalRef(Thread* t, jobject o, bool weak) } } -jobject JNICALL -NewGlobalRef(Thread* t, jobject o) +jobject JNICALL NewGlobalRef(Thread* t, jobject o) { return newGlobalRef(t, o, false); } -void JNICALL -DeleteGlobalRef(Thread* t, jobject r) +void JNICALL DeleteGlobalRef(Thread* t, jobject r) { ENTER(t, Thread::ActiveState); ACQUIRE(t, t->m->referenceLock); - + if (r) { release(t, reinterpret_cast(r)); } } -jobject JNICALL -NewWeakGlobalRef(Thread* t, jobject o) +jobject JNICALL NewWeakGlobalRef(Thread* t, jobject o) { return newGlobalRef(t, o, true); } -void JNICALL -DeleteWeakGlobalRef(Thread* t, jobject r) +void JNICALL DeleteWeakGlobalRef(Thread* t, jobject r) { DeleteGlobalRef(t, r); } -jint JNICALL -EnsureLocalCapacity(Thread*, jint) +jint JNICALL EnsureLocalCapacity(Thread*, jint) { return 0; } -jthrowable JNICALL -ExceptionOccurred(Thread* t) +jthrowable JNICALL ExceptionOccurred(Thread* t) { ENTER(t, Thread::ActiveState); - return makeLocalReference(t, t->exception); + return reinterpret_cast(makeLocalReference(t, t->exception)); } -void JNICALL -ExceptionDescribe(Thread* t) +void JNICALL ExceptionDescribe(Thread* t) { ENTER(t, Thread::ActiveState); return printTrace(t, t->exception); } -void JNICALL -ExceptionClear(Thread* t) +void JNICALL ExceptionClear(Thread* t) { ENTER(t, Thread::ActiveState); t->exception = 0; } -uint64_t -newObjectArray(Thread* t, uintptr_t* arguments) +uint64_t newObjectArray(Thread* t, uintptr_t* arguments) { jsize length = arguments[0]; jclass class_ = reinterpret_cast(arguments[1]); jobject init = reinterpret_cast(arguments[2]); - object a = makeObjectArray(t, jclassVmClass(t, *class_), length); + object a = makeObjectArray(t, (*class_)->vmClass(), length); object value = (init ? *init : 0); for (jsize i = 0; i < length; ++i) { - set(t, a, ArrayBody + (i * BytesPerWord), value); + reinterpret_cast(a)->setBodyElement(t, i, value); } return reinterpret_cast(makeLocalReference(t, a)); } jobjectArray JNICALL -NewObjectArray(Thread* t, jsize length, jclass class_, jobject init) + NewObjectArray(Thread* t, jsize length, jclass class_, jobject init) { - uintptr_t arguments[] = { static_cast(length), - reinterpret_cast(class_), - reinterpret_cast(init) }; + uintptr_t arguments[] = {static_cast(length), + reinterpret_cast(class_), + reinterpret_cast(init)}; return reinterpret_cast(run(t, newObjectArray, arguments)); } jobject JNICALL -GetObjectArrayElement(Thread* t, jobjectArray array, jsize index) + GetObjectArrayElement(Thread* t, jobjectArray array, jsize index) { ENTER(t, Thread::ActiveState); - return makeLocalReference(t, objectArrayBody(t, *array, index)); + return makeLocalReference( + t, objectArrayBody(t, reinterpret_cast(*array), index)); } -void JNICALL -SetObjectArrayElement(Thread* t, jobjectArray array, jsize index, - jobject value) +void JNICALL SetObjectArrayElement(Thread* t, + jobjectArray array, + jsize index, + jobject value) { ENTER(t, Thread::ActiveState); - set(t, *array, ArrayBody + (index * BytesPerWord), (value ? *value : 0)); + setField(t, + reinterpret_cast(*array), + ArrayBody + (index * BytesPerWord), + (value ? *value : 0)); } -uint64_t -newArray(Thread* t, uintptr_t* arguments) +uint64_t newArray(Thread* t, uintptr_t* arguments) { object (*constructor)(Thread*, unsigned) - = reinterpret_cast(arguments[0]); + = reinterpret_cast(arguments[0]); jsize length = arguments[1]; - return reinterpret_cast - (makeLocalReference(t, constructor(t, length))); + return reinterpret_cast( + makeLocalReference(t, constructor(t, length))); } -jbooleanArray JNICALL -NewBooleanArray(Thread* t, jsize length) +jbooleanArray JNICALL NewBooleanArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeBooleanArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeBooleanArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -object -makeByteArray0(Thread* t, unsigned length) +object makeByteArray0(Thread* t, unsigned length) { return makeByteArray(t, length); } -jbyteArray JNICALL -NewByteArray(Thread* t, jsize length) +jbyteArray JNICALL NewByteArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeByteArray0)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeByteArray0)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jcharArray JNICALL -NewCharArray(Thread* t, jsize length) +jcharArray JNICALL NewCharArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeCharArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeCharArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jshortArray JNICALL -NewShortArray(Thread* t, jsize length) +jshortArray JNICALL NewShortArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeShortArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeShortArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jintArray JNICALL -NewIntArray(Thread* t, jsize length) +jintArray JNICALL NewIntArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeIntArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeIntArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jlongArray JNICALL -NewLongArray(Thread* t, jsize length) +jlongArray JNICALL NewLongArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeLongArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeLongArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jfloatArray JNICALL -NewFloatArray(Thread* t, jsize length) +jfloatArray JNICALL NewFloatArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeFloatArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeFloatArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } -jdoubleArray JNICALL -NewDoubleArray(Thread* t, jsize length) +jdoubleArray JNICALL NewDoubleArray(Thread* t, jsize length) { uintptr_t arguments[] - = { reinterpret_cast(voidPointer(makeDoubleArray)), - static_cast(length) }; + = {reinterpret_cast(voidPointer(makeDoubleArray)), + static_cast(length)}; return reinterpret_cast(run(t, newArray, arguments)); } jboolean* JNICALL -GetBooleanArrayElements(Thread* t, jbooleanArray array, jboolean* isCopy) + GetBooleanArrayElements(Thread* t, jbooleanArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = booleanArrayLength(t, *array) * sizeof(jboolean); + unsigned size = (*array)->length() * sizeof(jboolean); jboolean* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &booleanArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2715,14 +2486,14 @@ GetBooleanArrayElements(Thread* t, jbooleanArray array, jboolean* isCopy) } jbyte* JNICALL -GetByteArrayElements(Thread* t, jbyteArray array, jboolean* isCopy) + GetByteArrayElements(Thread* t, jbyteArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = byteArrayLength(t, *array) * sizeof(jbyte); + unsigned size = (*array)->length() * sizeof(jbyte); jbyte* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &byteArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2733,14 +2504,14 @@ GetByteArrayElements(Thread* t, jbyteArray array, jboolean* isCopy) } jchar* JNICALL -GetCharArrayElements(Thread* t, jcharArray array, jboolean* isCopy) + GetCharArrayElements(Thread* t, jcharArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = charArrayLength(t, *array) * sizeof(jchar); + unsigned size = (*array)->length() * sizeof(jchar); jchar* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &charArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2751,14 +2522,14 @@ GetCharArrayElements(Thread* t, jcharArray array, jboolean* isCopy) } jshort* JNICALL -GetShortArrayElements(Thread* t, jshortArray array, jboolean* isCopy) + GetShortArrayElements(Thread* t, jshortArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = shortArrayLength(t, *array) * sizeof(jshort); + unsigned size = (*array)->length() * sizeof(jshort); jshort* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &shortArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2768,15 +2539,14 @@ GetShortArrayElements(Thread* t, jshortArray array, jboolean* isCopy) return p; } -jint* JNICALL -GetIntArrayElements(Thread* t, jintArray array, jboolean* isCopy) +jint* JNICALL GetIntArrayElements(Thread* t, jintArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = intArrayLength(t, *array) * sizeof(jint); + unsigned size = (*array)->length() * sizeof(jint); jint* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &intArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2787,14 +2557,14 @@ GetIntArrayElements(Thread* t, jintArray array, jboolean* isCopy) } jlong* JNICALL -GetLongArrayElements(Thread* t, jlongArray array, jboolean* isCopy) + GetLongArrayElements(Thread* t, jlongArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = longArrayLength(t, *array) * sizeof(jlong); + unsigned size = (*array)->length() * sizeof(jlong); jlong* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &longArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2805,14 +2575,14 @@ GetLongArrayElements(Thread* t, jlongArray array, jboolean* isCopy) } jfloat* JNICALL -GetFloatArrayElements(Thread* t, jfloatArray array, jboolean* isCopy) + GetFloatArrayElements(Thread* t, jfloatArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = floatArrayLength(t, *array) * sizeof(jfloat); + unsigned size = (*array)->length() * sizeof(jfloat); jfloat* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &floatArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2823,14 +2593,14 @@ GetFloatArrayElements(Thread* t, jfloatArray array, jboolean* isCopy) } jdouble* JNICALL -GetDoubleArrayElements(Thread* t, jdoubleArray array, jboolean* isCopy) + GetDoubleArrayElements(Thread* t, jdoubleArray array, jboolean* isCopy) { ENTER(t, Thread::ActiveState); - unsigned size = doubleArrayLength(t, *array) * sizeof(jdouble); + unsigned size = (*array)->length() * sizeof(jdouble); jdouble* p = static_cast(t->m->heap->allocate(size)); if (size) { - memcpy(p, &doubleArrayBody(t, *array, 0), size); + memcpy(p, (*array)->body().begin(), size); } if (isCopy) { @@ -2840,17 +2610,18 @@ GetDoubleArrayElements(Thread* t, jdoubleArray array, jboolean* isCopy) return p; } -void JNICALL -ReleaseBooleanArrayElements(Thread* t, jbooleanArray array, jboolean* p, - jint mode) +void JNICALL ReleaseBooleanArrayElements(Thread* t, + jbooleanArray array, + jboolean* p, + jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = booleanArrayLength(t, *array) * sizeof(jboolean); + + unsigned size = (*array)->length() * sizeof(jboolean); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&booleanArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2860,15 +2631,15 @@ ReleaseBooleanArrayElements(Thread* t, jbooleanArray array, jboolean* p, } void JNICALL -ReleaseByteArrayElements(Thread* t, jbyteArray array, jbyte* p, jint mode) + ReleaseByteArrayElements(Thread* t, jbyteArray array, jbyte* p, jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = byteArrayLength(t, *array) * sizeof(jbyte); + + unsigned size = (*array)->length() * sizeof(jbyte); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&byteArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2878,33 +2649,15 @@ ReleaseByteArrayElements(Thread* t, jbyteArray array, jbyte* p, jint mode) } void JNICALL -ReleaseCharArrayElements(Thread* t, jcharArray array, jchar* p, jint mode) + ReleaseCharArrayElements(Thread* t, jcharArray array, jchar* p, jint mode) { ENTER(t, Thread::ActiveState); - unsigned size = charArrayLength(t, *array) * sizeof(jchar); - - if (mode == 0 or mode == AVIAN_JNI_COMMIT) { - if (size) { - memcpy(&charArrayBody(t, *array, 0), p, size); - } - } - - if (mode == 0 or mode == AVIAN_JNI_ABORT) { - t->m->heap->free(p, size); - } -} - -void JNICALL -ReleaseShortArrayElements(Thread* t, jshortArray array, jshort* p, jint mode) -{ - ENTER(t, Thread::ActiveState); - - unsigned size = shortArrayLength(t, *array) * sizeof(jshort); + unsigned size = (*array)->length() * sizeof(jchar); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&shortArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2913,16 +2666,18 @@ ReleaseShortArrayElements(Thread* t, jshortArray array, jshort* p, jint mode) } } -void JNICALL -ReleaseIntArrayElements(Thread* t, jintArray array, jint* p, jint mode) +void JNICALL ReleaseShortArrayElements(Thread* t, + jshortArray array, + jshort* p, + jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = intArrayLength(t, *array) * sizeof(jint); + + unsigned size = (*array)->length() * sizeof(jshort); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&intArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2932,15 +2687,15 @@ ReleaseIntArrayElements(Thread* t, jintArray array, jint* p, jint mode) } void JNICALL -ReleaseLongArrayElements(Thread* t, jlongArray array, jlong* p, jint mode) + ReleaseIntArrayElements(Thread* t, jintArray array, jint* p, jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = longArrayLength(t, *array) * sizeof(jlong); + + unsigned size = (*array)->length() * sizeof(jint); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&longArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2950,15 +2705,15 @@ ReleaseLongArrayElements(Thread* t, jlongArray array, jlong* p, jint mode) } void JNICALL -ReleaseFloatArrayElements(Thread* t, jfloatArray array, jfloat* p, jint mode) + ReleaseLongArrayElements(Thread* t, jlongArray array, jlong* p, jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = floatArrayLength(t, *array) * sizeof(jfloat); + + unsigned size = (*array)->length() * sizeof(jlong); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&floatArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2967,17 +2722,18 @@ ReleaseFloatArrayElements(Thread* t, jfloatArray array, jfloat* p, jint mode) } } -void JNICALL -ReleaseDoubleArrayElements(Thread* t, jdoubleArray array, jdouble* p, - jint mode) +void JNICALL ReleaseFloatArrayElements(Thread* t, + jfloatArray array, + jfloat* p, + jint mode) { ENTER(t, Thread::ActiveState); - - unsigned size = doubleArrayLength(t, *array) * sizeof(jdouble); + + unsigned size = (*array)->length() * sizeof(jfloat); if (mode == 0 or mode == AVIAN_JNI_COMMIT) { if (size) { - memcpy(&doubleArrayBody(t, *array, 0), p, size); + memcpy((*array)->body().begin(), p, size); } } @@ -2986,193 +2742,243 @@ ReleaseDoubleArrayElements(Thread* t, jdoubleArray array, jdouble* p, } } -void JNICALL -GetBooleanArrayRegion(Thread* t, jbooleanArray array, jint offset, jint length, - jboolean* dst) +void JNICALL ReleaseDoubleArrayElements(Thread* t, + jdoubleArray array, + jdouble* p, + jint mode) { ENTER(t, Thread::ActiveState); - if (length) { - memcpy(dst, &booleanArrayBody(t, *array, offset), - length * sizeof(jboolean)); + unsigned size = (*array)->length() * sizeof(jdouble); + + if (mode == 0 or mode == AVIAN_JNI_COMMIT) { + if (size) { + memcpy((*array)->body().begin(), p, size); + } + } + + if (mode == 0 or mode == AVIAN_JNI_ABORT) { + t->m->heap->free(p, size); } } -void JNICALL -GetByteArrayRegion(Thread* t, jbyteArray array, jint offset, jint length, - jbyte* dst) +void JNICALL GetBooleanArrayRegion(Thread* t, + jbooleanArray array, + jint offset, + jint length, + jboolean* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &byteArrayBody(t, *array, offset), length * sizeof(jbyte)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jboolean)); } } -void JNICALL -GetCharArrayRegion(Thread* t, jcharArray array, jint offset, jint length, - jchar* dst) +void JNICALL GetByteArrayRegion(Thread* t, + jbyteArray array, + jint offset, + jint length, + jbyte* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &charArrayBody(t, *array, offset), length * sizeof(jchar)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jbyte)); } } -void JNICALL -GetShortArrayRegion(Thread* t, jshortArray array, jint offset, jint length, - jshort* dst) +void JNICALL GetCharArrayRegion(Thread* t, + jcharArray array, + jint offset, + jint length, + jchar* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &shortArrayBody(t, *array, offset), length * sizeof(jshort)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jchar)); } } -void JNICALL -GetIntArrayRegion(Thread* t, jintArray array, jint offset, jint length, - jint* dst) +void JNICALL GetShortArrayRegion(Thread* t, + jshortArray array, + jint offset, + jint length, + jshort* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &intArrayBody(t, *array, offset), length * sizeof(jint)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jshort)); } } -void JNICALL -GetLongArrayRegion(Thread* t, jlongArray array, jint offset, jint length, - jlong* dst) +void JNICALL GetIntArrayRegion(Thread* t, + jintArray array, + jint offset, + jint length, + jint* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &longArrayBody(t, *array, offset), length * sizeof(jlong)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jint)); } } -void JNICALL -GetFloatArrayRegion(Thread* t, jfloatArray array, jint offset, jint length, - jfloat* dst) +void JNICALL GetLongArrayRegion(Thread* t, + jlongArray array, + jint offset, + jint length, + jlong* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &floatArrayBody(t, *array, offset), length * sizeof(jfloat)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jlong)); } } -void JNICALL -GetDoubleArrayRegion(Thread* t, jdoubleArray array, jint offset, jint length, - jdouble* dst) +void JNICALL GetFloatArrayRegion(Thread* t, + jfloatArray array, + jint offset, + jint length, + jfloat* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(dst, &doubleArrayBody(t, *array, offset), length * sizeof(jdouble)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jfloat)); } } -void JNICALL -SetBooleanArrayRegion(Thread* t, jbooleanArray array, jint offset, jint length, - const jboolean* src) +void JNICALL GetDoubleArrayRegion(Thread* t, + jdoubleArray array, + jint offset, + jint length, + jdouble* dst) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&booleanArrayBody(t, *array, offset), src, - length * sizeof(jboolean)); + memcpy(dst, &(*array)->body()[offset], length * sizeof(jdouble)); } } -void JNICALL -SetByteArrayRegion(Thread* t, jbyteArray array, jint offset, jint length, - const jbyte* src) +void JNICALL SetBooleanArrayRegion(Thread* t, + jbooleanArray array, + jint offset, + jint length, + const jboolean* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&byteArrayBody(t, *array, offset), src, length * sizeof(jbyte)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jboolean)); } } -void JNICALL -SetCharArrayRegion(Thread* t, jcharArray array, jint offset, jint length, - const jchar* src) +void JNICALL SetByteArrayRegion(Thread* t, + jbyteArray array, + jint offset, + jint length, + const jbyte* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&charArrayBody(t, *array, offset), src, length * sizeof(jchar)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jbyte)); } } -void JNICALL -SetShortArrayRegion(Thread* t, jshortArray array, jint offset, jint length, - const jshort* src) +void JNICALL SetCharArrayRegion(Thread* t, + jcharArray array, + jint offset, + jint length, + const jchar* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&shortArrayBody(t, *array, offset), src, length * sizeof(jshort)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jchar)); } } -void JNICALL -SetIntArrayRegion(Thread* t, jintArray array, jint offset, jint length, - const jint* src) +void JNICALL SetShortArrayRegion(Thread* t, + jshortArray array, + jint offset, + jint length, + const jshort* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&intArrayBody(t, *array, offset), src, length * sizeof(jint)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jshort)); } } -void JNICALL -SetLongArrayRegion(Thread* t, jlongArray array, jint offset, jint length, - const jlong* src) +void JNICALL SetIntArrayRegion(Thread* t, + jintArray array, + jint offset, + jint length, + const jint* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&longArrayBody(t, *array, offset), src, length * sizeof(jlong)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jint)); } } -void JNICALL -SetFloatArrayRegion(Thread* t, jfloatArray array, jint offset, jint length, - const jfloat* src) +void JNICALL SetLongArrayRegion(Thread* t, + jlongArray array, + jint offset, + jint length, + const jlong* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&floatArrayBody(t, *array, offset), src, length * sizeof(jfloat)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jlong)); } } -void JNICALL -SetDoubleArrayRegion(Thread* t, jdoubleArray array, jint offset, jint length, - const jdouble* src) +void JNICALL SetFloatArrayRegion(Thread* t, + jfloatArray array, + jint offset, + jint length, + const jfloat* src) { ENTER(t, Thread::ActiveState); if (length) { - memcpy(&doubleArrayBody(t, *array, offset), src, length * sizeof(jdouble)); + memcpy(&(*array)->body()[offset], src, length * sizeof(jfloat)); + } +} + +void JNICALL SetDoubleArrayRegion(Thread* t, + jdoubleArray array, + jint offset, + jint length, + const jdouble* src) +{ + ENTER(t, Thread::ActiveState); + + if (length) { + memcpy(&(*array)->body()[offset], src, length * sizeof(jdouble)); } } void* JNICALL -GetPrimitiveArrayCritical(Thread* t, jarray array, jboolean* isCopy) + GetPrimitiveArrayCritical(Thread* t, jarray array, jboolean* isCopy) { if (t->criticalLevel == 0) { enter(t, Thread::ActiveState); } - ++ t->criticalLevel; - + ++t->criticalLevel; + if (isCopy) { *isCopy = true; } @@ -3182,96 +2988,88 @@ GetPrimitiveArrayCritical(Thread* t, jarray array, jboolean* isCopy) return reinterpret_cast(*array) + 2; } -void JNICALL -ReleasePrimitiveArrayCritical(Thread* t, jarray, void*, jint) +void JNICALL ReleasePrimitiveArrayCritical(Thread* t, jarray, void*, jint) { - if ((-- t->criticalLevel) == 0) { + if ((--t->criticalLevel) == 0) { enter(t, Thread::IdleState); } } -uint64_t -fromReflectedMethod(Thread* t, uintptr_t* arguments) +uint64_t fromReflectedMethod(Thread* t, uintptr_t* arguments) { jobject m = reinterpret_cast(arguments[0]); return methodID(t, t->m->classpath->getVMMethod(t, *m)); } -jmethodID JNICALL -FromReflectedMethod(Thread* t, jobject method) +jmethodID JNICALL FromReflectedMethod(Thread* t, jobject method) { - uintptr_t arguments[] = { reinterpret_cast(method) }; + uintptr_t arguments[] = {reinterpret_cast(method)}; return static_cast(run(t, fromReflectedMethod, arguments)); } -uint64_t -toReflectedMethod(Thread* t, uintptr_t* arguments) +uint64_t toReflectedMethod(Thread* t, uintptr_t* arguments) { jmethodID m = arguments[1]; jboolean isStatic = arguments[2]; - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeJMethod - (t, isStatic ? getStaticMethod(t, m) : getMethod(t, m)))); + return reinterpret_cast(makeLocalReference( + t, + t->m->classpath->makeJMethod( + t, isStatic ? getStaticMethod(t, m) : getMethod(t, m)))); } jobject JNICALL -ToReflectedMethod(Thread* t, jclass c, jmethodID method, jboolean isStatic) + ToReflectedMethod(Thread* t, jclass c, jmethodID method, jboolean isStatic) { - uintptr_t arguments[] = { reinterpret_cast(c), - static_cast(method), - static_cast(isStatic) }; + uintptr_t arguments[] = {reinterpret_cast(c), + static_cast(method), + static_cast(isStatic)}; return reinterpret_cast(run(t, toReflectedMethod, arguments)); } -uint64_t -fromReflectedField(Thread* t, uintptr_t* arguments) +uint64_t fromReflectedField(Thread* t, uintptr_t* arguments) { jobject f = reinterpret_cast(arguments[0]); - return fieldID(t, t->m->classpath->getVMField(t, *f)); + return fieldID(t, t->m->classpath->getVMField(t, cast(t, *f))); } -jfieldID JNICALL -FromReflectedField(Thread* t, jobject field) +jfieldID JNICALL FromReflectedField(Thread* t, jobject field) { - uintptr_t arguments[] = { reinterpret_cast(field) }; + uintptr_t arguments[] = {reinterpret_cast(field)}; return static_cast(run(t, fromReflectedField, arguments)); } -uint64_t -toReflectedField(Thread* t, uintptr_t* arguments) +uint64_t toReflectedField(Thread* t, uintptr_t* arguments) { jfieldID f = arguments[1]; jboolean isStatic = arguments[2]; - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeJField - (t, isStatic ? getStaticField(t, f) : getField(t, f)))); + return reinterpret_cast(makeLocalReference( + t, + t->m->classpath->makeJField( + t, isStatic ? getStaticField(t, f) : getField(t, f)))); } jobject JNICALL -ToReflectedField(Thread* t, jclass c, jfieldID field, jboolean isStatic) + ToReflectedField(Thread* t, jclass c, jfieldID field, jboolean isStatic) { - uintptr_t arguments[] = { reinterpret_cast(c), - static_cast(field), - static_cast(isStatic) }; + uintptr_t arguments[] = {reinterpret_cast(c), + static_cast(field), + static_cast(isStatic)}; return reinterpret_cast(run(t, toReflectedField, arguments)); } -uint64_t -registerNatives(Thread* t, uintptr_t* arguments) +uint64_t registerNatives(Thread* t, uintptr_t* arguments) { jclass c = reinterpret_cast(arguments[0]); const JNINativeMethod* methods - = reinterpret_cast(arguments[1]); + = reinterpret_cast(arguments[1]); jint methodCount = arguments[2]; for (int i = 0; i < methodCount; ++i) { @@ -3279,102 +3077,100 @@ registerNatives(Thread* t, uintptr_t* arguments) // Android's class library sometimes prepends a mysterious "!" // to the method signature, which we happily ignore: const char* sig = methods[i].signature; - if (*sig == '!') ++ sig; + if (*sig == '!') + ++sig; - object method = findMethodOrNull - (t, jclassVmClass(t, *c), methods[i].name, sig); + GcMethod* method + = findMethodOrNull(t, (*c)->vmClass(), methods[i].name, sig); - if (method == 0 or (methodFlags(t, method) & ACC_NATIVE) == 0) { + if (method == 0 or (method->flags() & ACC_NATIVE) == 0) { // The JNI spec says we must throw a NoSuchMethodError in this // case, but that would prevent using a code shrinker like // ProGuard effectively. Instead, we just ignore it. - // fprintf(stderr, "not found: %s.%s%s\n", &byteArrayBody(t, className(t, jclassVmClass(t, *c)), 0), methods[i].name, sig); - // abort(t); + if (false) { + fprintf(stderr, + "not found: %s.%s%s\n", + (*c)->vmClass()->name()->body().begin(), + methods[i].name, + sig); + abort(t); + } } else { registerNative(t, method, methods[i].function); } } } - return 1; + return 1; } -jint JNICALL -RegisterNatives(Thread* t, jclass c, const JNINativeMethod* methods, - jint methodCount) +jint JNICALL RegisterNatives(Thread* t, + jclass c, + const JNINativeMethod* methods, + jint methodCount) { - uintptr_t arguments[] = { reinterpret_cast(c), - reinterpret_cast(methods), - static_cast(methodCount) }; + uintptr_t arguments[] = {reinterpret_cast(c), + reinterpret_cast(methods), + static_cast(methodCount)}; return run(t, registerNatives, arguments) ? 0 : -1; } -jint JNICALL -UnregisterNatives(Thread* t, jclass c) +jint JNICALL UnregisterNatives(Thread* t, jclass c) { ENTER(t, Thread::ActiveState); - unregisterNatives(t, *c); + unregisterNatives(t, (*c)->vmClass()); return 0; } -uint64_t -monitorOp(Thread* t, uintptr_t* arguments) +uint64_t monitorOp(Thread* t, uintptr_t* arguments) { void (*op)(Thread*, object) - = reinterpret_cast(arguments[0]); + = reinterpret_cast(arguments[0]); jobject o = reinterpret_cast(arguments[1]); - + op(t, *o); return 1; } -void -acquire0(Thread* t, object o) +void acquire0(Thread* t, object o) { return acquire(t, o); } -jint JNICALL -MonitorEnter(Thread* t, jobject o) +jint JNICALL MonitorEnter(Thread* t, jobject o) { - uintptr_t arguments[] - = { reinterpret_cast(voidPointer(acquire0)), - reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(voidPointer(acquire0)), + reinterpret_cast(o)}; return run(t, monitorOp, arguments) ? 0 : -1; } -void -release0(Thread* t, object o) +void release0(Thread* t, object o) { return release(t, o); } -jint JNICALL -MonitorExit(Thread* t, jobject o) +jint JNICALL MonitorExit(Thread* t, jobject o) { - uintptr_t arguments[] - = { reinterpret_cast(voidPointer(release0)), - reinterpret_cast(o) }; + uintptr_t arguments[] = {reinterpret_cast(voidPointer(release0)), + reinterpret_cast(o)}; return run(t, monitorOp, arguments) ? 0 : -1; } -jint JNICALL -GetJavaVM(Thread* t, Machine** m) +jint JNICALL GetJavaVM(Thread* t, Machine** m) { *m = t->m; return 0; } -jboolean JNICALL -IsSameObject(Thread* t, jobject a, jobject b) +jboolean JNICALL IsSameObject(Thread* t, jobject a, jobject b) { if (a and b) { ENTER(t, Thread::ActiveState); @@ -3385,30 +3181,27 @@ IsSameObject(Thread* t, jobject a, jobject b) } } -uint64_t -pushLocalFrame(Thread* t, uintptr_t* arguments) +uint64_t pushLocalFrame(Thread* t, uintptr_t* arguments) { if (t->m->processor->pushLocalFrame(t, arguments[0])) { return 1; } else { - throw_(t, root(t, Machine::OutOfMemoryError)); + throw_(t, roots(t)->outOfMemoryError()); } } -jint JNICALL -PushLocalFrame(Thread* t, jint capacity) +jint JNICALL PushLocalFrame(Thread* t, jint capacity) { - uintptr_t arguments[] = { static_cast(capacity) }; + uintptr_t arguments[] = {static_cast(capacity)}; return run(t, pushLocalFrame, arguments) ? 0 : -1; } -uint64_t -popLocalFrame(Thread* t, uintptr_t* arguments) +uint64_t popLocalFrame(Thread* t, uintptr_t* arguments) { uint64_t r; jobject presult = reinterpret_cast(arguments[0]); - if(presult != NULL) { + if (presult != NULL) { object result = *presult; PROTECT(t, result); @@ -3423,27 +3216,25 @@ popLocalFrame(Thread* t, uintptr_t* arguments) return r; } -jobject JNICALL -PopLocalFrame(Thread* t, jobject result) +jobject JNICALL PopLocalFrame(Thread* t, jobject result) { - uintptr_t arguments[] = { reinterpret_cast(result) }; + uintptr_t arguments[] = {reinterpret_cast(result)}; return reinterpret_cast(run(t, popLocalFrame, arguments)); } -uint64_t -newDirectByteBuffer(Thread* t, uintptr_t* arguments) +uint64_t newDirectByteBuffer(Thread* t, uintptr_t* arguments) { - jlong capacity; memcpy(&capacity, arguments + 1, sizeof(jlong)); + jlong capacity; + memcpy(&capacity, arguments + 1, sizeof(jlong)); - return reinterpret_cast - (makeLocalReference - (t, t->m->classpath->makeDirectByteBuffer - (t, reinterpret_cast(arguments[0]), capacity))); + return reinterpret_cast(makeLocalReference( + t, + t->m->classpath->makeDirectByteBuffer( + t, reinterpret_cast(arguments[0]), capacity))); } -jobject JNICALL -NewDirectByteBuffer(Thread* t, void* p, jlong capacity) +jobject JNICALL NewDirectByteBuffer(Thread* t, void* p, jlong capacity) { uintptr_t arguments[1 + (sizeof(jlong) / BytesPerWord)]; arguments[0] = reinterpret_cast(p); @@ -3452,33 +3243,28 @@ NewDirectByteBuffer(Thread* t, void* p, jlong capacity) return reinterpret_cast(run(t, newDirectByteBuffer, arguments)); } -uint64_t -getDirectBufferAddress(Thread* t, uintptr_t* arguments) +uint64_t getDirectBufferAddress(Thread* t, uintptr_t* arguments) { - return reinterpret_cast - (t->m->classpath->getDirectBufferAddress - (t, *reinterpret_cast(arguments[0]))); + return reinterpret_cast(t->m->classpath->getDirectBufferAddress( + t, *reinterpret_cast(arguments[0]))); } -void* JNICALL -GetDirectBufferAddress(Thread* t, jobject b) +void* JNICALL GetDirectBufferAddress(Thread* t, jobject b) { - uintptr_t arguments[] = { reinterpret_cast(b) }; + uintptr_t arguments[] = {reinterpret_cast(b)}; return reinterpret_cast(run(t, getDirectBufferAddress, arguments)); } -uint64_t -getDirectBufferCapacity(Thread* t, uintptr_t* arguments) +uint64_t getDirectBufferCapacity(Thread* t, uintptr_t* arguments) { - return t->m->classpath->getDirectBufferCapacity - (t, *reinterpret_cast(arguments[0])); + return t->m->classpath->getDirectBufferCapacity( + t, *reinterpret_cast(arguments[0])); } -jlong JNICALL -GetDirectBufferCapacity(Thread* t, jobject b) +jlong JNICALL GetDirectBufferCapacity(Thread* t, jobject b) { - uintptr_t arguments[] = { reinterpret_cast(b) }; + uintptr_t arguments[] = {reinterpret_cast(b)}; return run(t, getDirectBufferCapacity, arguments); } @@ -3496,8 +3282,7 @@ struct JavaVMInitArgs { jboolean ignoreUnrecognized; }; -int -parseSize(const char* s) +int parseSize(const char* s) { unsigned length = strlen(s); RUNTIME_ARRAY(char, buffer, length + 1); @@ -3516,8 +3301,7 @@ parseSize(const char* s) } } -void -append(char** p, const char* value, unsigned length, char tail) +void append(char** p, const char* value, unsigned length, char tail) { if (length) { memcpy(*p, value, length); @@ -3526,43 +3310,52 @@ append(char** p, const char* value, unsigned length, char tail) } } -uint64_t -boot(Thread* t, uintptr_t*) +uint64_t boot(Thread* t, uintptr_t*) { - setRoot(t, Machine::NullPointerException, makeThrowable - (t, Machine::NullPointerExceptionType)); - - setRoot(t, Machine::ArithmeticException, - makeThrowable(t, Machine::ArithmeticExceptionType)); + GcThrowable* throwable = makeThrowable(t, GcNullPointerException::Type); + // sequence point, for gc (don't recombine statements) + roots(t)->setNullPointerException(t, throwable); - setRoot(t, Machine::ArrayIndexOutOfBoundsException, - makeThrowable(t, Machine::ArrayIndexOutOfBoundsExceptionType)); + throwable = makeThrowable(t, GcArithmeticException::Type); + // sequence point, for gc (don't recombine statements) + roots(t)->setArithmeticException(t, throwable); - setRoot(t, Machine::OutOfMemoryError, - makeThrowable(t, Machine::OutOfMemoryErrorType)); + throwable = makeThrowable(t, GcArrayIndexOutOfBoundsException::Type); + // sequence point, for gc (don't recombine statements) + roots(t)->setArrayIndexOutOfBoundsException(t, throwable); - setRoot(t, Machine::Shutdown, makeThrowable(t, Machine::ThrowableType)); + throwable = makeThrowable(t, GcOutOfMemoryError::Type); + // sequence point, for gc (don't recombine statements) + roots(t)->setOutOfMemoryError(t, throwable); + + throwable = makeThrowable(t, GcThrowable::Type); + // sequence point, for gc (don't recombine statements) + roots(t)->setShutdownInProgress(t, throwable); t->m->classpath->preBoot(t); t->javaThread = t->m->classpath->makeThread(t, 0); - threadPeer(t, t->javaThread) = reinterpret_cast(t); + t->javaThread->peer() = reinterpret_cast(t); - setRoot(t, Machine::FinalizerThread, t->m->classpath->makeThread(t, t)); + GcThread* jthread = t->m->classpath->makeThread(t, t); + // sequence point, for gc (don't recombine statements) + roots(t)->setFinalizerThread(t, jthread); - threadDaemon(t, root(t, Machine::FinalizerThread)) = true; + roots(t)->finalizerThread()->daemon() = true; t->m->classpath->boot(t); const char* port = findProperty(t, "avian.trace.port"); if (port) { - object host = makeString(t, "0.0.0.0"); + GcString* host = makeString(t, "0.0.0.0"); PROTECT(t, host); - object method = resolveMethod - (t, root(t, Machine::BootLoader), "avian/Traces", "startTraceListener", - "(Ljava/lang/String;I)V"); + GcMethod* method = resolveMethod(t, + roots(t)->bootLoader(), + "avian/Traces", + "startTraceListener", + "(Ljava/lang/String;I)V"); t->m->processor->invoke(t, method, 0, host, atoi(port)); } @@ -3572,14 +3365,13 @@ boot(Thread* t, uintptr_t*) return 1; } -} // namespace local +} // namespace local -} // namespace +} // namespace namespace vm { -void -populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable) +void populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable) { memset(vmTable, 0, sizeof(JavaVMVTable)); @@ -3775,7 +3567,7 @@ populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable) envTable->SetDoubleArrayRegion = local::SetDoubleArrayRegion; envTable->GetPrimitiveArrayCritical = local::GetPrimitiveArrayCritical; envTable->ReleasePrimitiveArrayCritical - = local::ReleasePrimitiveArrayCritical; + = local::ReleasePrimitiveArrayCritical; envTable->RegisterNatives = local::RegisterNatives; envTable->UnregisterNatives = local::UnregisterNatives; envTable->MonitorEnter = local::MonitorEnter; @@ -3790,23 +3582,22 @@ populateJNITables(JavaVMVTable* vmTable, JNIEnvVTable* envTable) envTable->ToReflectedField = local::ToReflectedField; } -} // namespace vm +} // namespace vm -extern "C" AVIAN_EXPORT jint JNICALL -JNI_GetDefaultJavaVMInitArgs(void*) +extern "C" AVIAN_EXPORT jint JNICALL JNI_GetDefaultJavaVMInitArgs(void*) { return 0; } extern "C" AVIAN_EXPORT jint JNICALL -JNI_GetCreatedJavaVMs(Machine**, jsize, jsize*) + JNI_GetCreatedJavaVMs(Machine**, jsize, jsize*) { // todo return -1; } extern "C" AVIAN_EXPORT jint JNICALL -JNI_CreateJavaVM(Machine** m, Thread** t, void* args) + JNI_CreateJavaVM(Machine** m, Thread** t, void* args) { local::JavaVMInitArgs* a = static_cast(args); @@ -3830,58 +3621,56 @@ JNI_CreateJavaVM(Machine** m, Thread** t, void* args) heapLimit = local::parseSize(p + 2); } else if (strncmp(p, "ss", 2) == 0) { stackLimit = local::parseSize(p + 2); - } else if (strncmp(p, BOOTCLASSPATH_PREPEND_OPTION ":", - sizeof(BOOTCLASSPATH_PREPEND_OPTION)) == 0) - { + } else if (strncmp(p, + BOOTCLASSPATH_PREPEND_OPTION ":", + sizeof(BOOTCLASSPATH_PREPEND_OPTION)) == 0) { bootClasspathPrepend = p + sizeof(BOOTCLASSPATH_PREPEND_OPTION); - } else if (strncmp(p, BOOTCLASSPATH_OPTION ":", - sizeof(BOOTCLASSPATH_OPTION)) == 0) - { + } else if (strncmp( + p, BOOTCLASSPATH_OPTION ":", sizeof(BOOTCLASSPATH_OPTION)) + == 0) { bootClasspath = p + sizeof(BOOTCLASSPATH_OPTION); - } else if (strncmp(p, BOOTCLASSPATH_APPEND_OPTION ":", - sizeof(BOOTCLASSPATH_APPEND_OPTION)) == 0) - { + } else if (strncmp(p, + BOOTCLASSPATH_APPEND_OPTION ":", + sizeof(BOOTCLASSPATH_APPEND_OPTION)) == 0) { bootClasspathAppend = p + sizeof(BOOTCLASSPATH_APPEND_OPTION); } } else if (strncmp(a->options[i].optionString, "-D", 2) == 0) { const char* p = a->options[i].optionString + 2; - if (strncmp(p, BOOTSTRAP_PROPERTY "=", - sizeof(BOOTSTRAP_PROPERTY)) == 0) - { + if (strncmp(p, BOOTSTRAP_PROPERTY "=", sizeof(BOOTSTRAP_PROPERTY)) == 0) { bootLibraries = p + sizeof(BOOTSTRAP_PROPERTY); - } else if (strncmp(p, JAVA_COMMAND_PROPERTY "=", + } else if (strncmp(p, + JAVA_COMMAND_PROPERTY "=", sizeof(JAVA_COMMAND_PROPERTY)) == 0 - or strncmp(p, JAVA_LAUNCHER_PROPERTY "=", - sizeof(JAVA_LAUNCHER_PROPERTY)) == 0) - { + or strncmp(p, + JAVA_LAUNCHER_PROPERTY "=", + sizeof(JAVA_LAUNCHER_PROPERTY)) == 0) { // this means we're being invoked via the javac or java // command, so the bootstrap library should be e.g. libjvm.so bootLibraries = SO_PREFIX "jvm" SO_SUFFIX; - } else if (strncmp(p, CRASHDIR_PROPERTY "=", - sizeof(CRASHDIR_PROPERTY)) == 0) - { + } else if (strncmp(p, CRASHDIR_PROPERTY "=", sizeof(CRASHDIR_PROPERTY)) + == 0) { crashDumpDirectory = p + sizeof(CRASHDIR_PROPERTY); - } else if (strncmp(p, CLASSPATH_PROPERTY "=", - sizeof(CLASSPATH_PROPERTY)) == 0) - { + } else if (strncmp(p, CLASSPATH_PROPERTY "=", sizeof(CLASSPATH_PROPERTY)) + == 0) { classpath = p + sizeof(CLASSPATH_PROPERTY); - } else if (strncmp(p, JAVA_HOME_PROPERTY "=", - sizeof(JAVA_HOME_PROPERTY)) == 0) - { + } else if (strncmp(p, JAVA_HOME_PROPERTY "=", sizeof(JAVA_HOME_PROPERTY)) + == 0) { javaHome = p + sizeof(JAVA_HOME_PROPERTY); - } else if (strncmp(p, EMBED_PREFIX_PROPERTY "=", - sizeof(EMBED_PREFIX_PROPERTY)) == 0) - { + } else if (strncmp(p, + EMBED_PREFIX_PROPERTY "=", + sizeof(EMBED_PREFIX_PROPERTY)) == 0) { embedPrefix = p + sizeof(EMBED_PREFIX_PROPERTY); } - ++ propertyCount; + ++propertyCount; } } - if (heapLimit == 0) heapLimit = 128 * 1024 * 1024; + if (heapLimit == 0) + heapLimit = 128 * 1024 * 1024; - if (stackLimit == 0) stackLimit = 128 * 1024; + if (stackLimit == 0) + stackLimit = 128 * 1024; bool addClasspathProperty = classpath == 0; if (addClasspathProperty) { @@ -3905,10 +3694,12 @@ JNI_CreateJavaVM(Machine** m, Thread** t, void* args) RUNTIME_ARRAY(char, bootClasspathBuffer, bootClasspathBufferSize); char* bootClasspathPointer = RUNTIME_ARRAY_BODY(bootClasspathBuffer); if (bootClasspathBufferSize > 3) { - local::append(&bootClasspathPointer, bootClasspathPrepend, bcppl, + local::append(&bootClasspathPointer, + bootClasspathPrepend, + bcppl, bcpl + bcpal ? PATH_SEPARATOR : 0); - local::append(&bootClasspathPointer, bootClasspath, bcpl, - bcpal ? PATH_SEPARATOR : 0); + local::append( + &bootClasspathPointer, bootClasspath, bcpl, bcpal ? PATH_SEPARATOR : 0); local::append(&bootClasspathPointer, bootClasspathAppend, bcpal, 0); } else { *RUNTIME_ARRAY_BODY(bootClasspathBuffer) = 0; @@ -3916,26 +3707,26 @@ JNI_CreateJavaVM(Machine** m, Thread** t, void* args) char* bootLibrary = bootLibraries ? strdup(bootLibraries) : 0; char* bootLibraryEnd = bootLibrary ? strchr(bootLibrary, PATH_SEPARATOR) : 0; - if(bootLibraryEnd) + if (bootLibraryEnd) *bootLibraryEnd = 0; - Finder* bf = makeFinder - (s, h, RUNTIME_ARRAY_BODY(bootClasspathBuffer), bootLibrary); + Finder* bf + = makeFinder(s, h, RUNTIME_ARRAY_BODY(bootClasspathBuffer), bootLibrary); Finder* af = makeFinder(s, h, classpath, bootLibrary); - if(bootLibrary) + if (bootLibrary) free(bootLibrary); Processor* p = makeProcessor(s, h, crashDumpDirectory, true); // reserve space for avian.version and file.encoding: propertyCount += 2; - const char** properties = static_cast - (h->allocate(sizeof(const char*) * propertyCount)); + const char** properties = static_cast( + h->allocate(sizeof(const char*) * propertyCount)); const char** propertyPointer = properties; - const char** arguments = static_cast - (h->allocate(sizeof(const char*) * a->nOptions)); + const char** arguments = static_cast( + h->allocate(sizeof(const char*) * a->nOptions)); const char** argumentPointer = arguments; @@ -3961,9 +3752,17 @@ JNI_CreateJavaVM(Machine** m, Thread** t, void* args) // overrideable via JavaVMInitArgs? *(propertyPointer++) = "file.encoding=UTF-8"; - *m = new (h->allocate(sizeof(Machine))) Machine - (s, h, bf, af, p, c, properties, propertyCount, arguments, a->nOptions, - stackLimit); + *m = new (h->allocate(sizeof(Machine))) Machine(s, + h, + bf, + af, + p, + c, + properties, + propertyCount, + arguments, + a->nOptions, + stackLimit); h->free(properties, sizeof(const char*) * propertyCount); diff --git a/src/lzma-decode.cpp b/src/lzma-decode.cpp index e5fb4e7ec0..a1af7ae9fc 100644 --- a/src/lzma-decode.cpp +++ b/src/lzma-decode.cpp @@ -15,22 +15,22 @@ using namespace vm; namespace { -int32_t -read4(const uint8_t* in) +int32_t read4(const uint8_t* in) { return (static_cast(in[3]) << 24) - | (static_cast(in[2]) << 16) - | (static_cast(in[1]) << 8) - | (static_cast(in[0]) ); + | (static_cast(in[2]) << 16) + | (static_cast(in[1]) << 8) | (static_cast(in[0])); } -} // namespace +} // namespace namespace vm { -uint8_t* -decodeLZMA(System* s, avian::util::Allocator* a, uint8_t* in, unsigned inSize, - unsigned* outSize) +uint8_t* decodeLZMA(System* s, + avian::util::Allocator* a, + uint8_t* in, + unsigned inSize, + unsigned* outSize) { const unsigned PropHeaderSize = 5; const unsigned HeaderSize = 13; @@ -45,9 +45,15 @@ decodeLZMA(System* s, avian::util::Allocator* a, uint8_t* in, unsigned inSize, LzmaAllocator allocator(a); ELzmaStatus status; - int result = LzmaDecode - (out, &outSizeT, in + HeaderSize, &inSizeT, in, PropHeaderSize, - LZMA_FINISH_END, &status, &(allocator.allocator)); + int result = LzmaDecode(out, + &outSizeT, + in + HeaderSize, + &inSizeT, + in, + PropHeaderSize, + LZMA_FINISH_END, + &status, + &(allocator.allocator)); expect(s, result == SZ_OK); expect(s, status == LZMA_STATUS_FINISHED_WITH_MARK); @@ -57,5 +63,4 @@ decodeLZMA(System* s, avian::util::Allocator* a, uint8_t* in, unsigned inSize, return out; } -} // namespace vm - +} // namespace vm diff --git a/src/lzma-encode.cpp b/src/lzma-encode.cpp index 015086c194..8dc26586a3 100644 --- a/src/lzma-encode.cpp +++ b/src/lzma-encode.cpp @@ -15,19 +15,20 @@ using namespace vm; namespace { -SRes -myProgress(void*, UInt64, UInt64) +SRes myProgress(void*, UInt64, UInt64) { return SZ_OK; } -} // namespace +} // namespace namespace vm { -uint8_t* -encodeLZMA(System* s, Allocator* a, uint8_t* in, unsigned inSize, - unsigned* outSize) +uint8_t* encodeLZMA(System* s, + Allocator* a, + uint8_t* in, + unsigned inSize, + unsigned* outSize) { const unsigned PropHeaderSize = 5; const unsigned HeaderSize = 13; @@ -43,17 +44,25 @@ encodeLZMA(System* s, Allocator* a, uint8_t* in, unsigned inSize, props.level = 9; props.writeEndMark = 1; - ICompressProgress progress = { myProgress }; + ICompressProgress progress = {myProgress}; SizeT propsSize = PropHeaderSize; int32_t inSize32 = inSize; memcpy(buffer + PropHeaderSize, &inSize32, 4); - + SizeT outSizeT = bufferSize; - int result = LzmaEncode - (buffer + HeaderSize, &outSizeT, in, inSize, &props, buffer, - &propsSize, 1, &progress, &(allocator.allocator), &(allocator.allocator)); + int result = LzmaEncode(buffer + HeaderSize, + &outSizeT, + in, + inSize, + &props, + buffer, + &propsSize, + 1, + &progress, + &(allocator.allocator), + &(allocator.allocator)); expect(s, result == SZ_OK); @@ -67,5 +76,4 @@ encodeLZMA(System* s, Allocator* a, uint8_t* in, unsigned inSize, return out; } -} // namespace vm - +} // namespace vm diff --git a/src/lzma/load.cpp b/src/lzma/load.cpp index 4a68466772..3f177e6b39 100644 --- a/src/lzma/load.cpp +++ b/src/lzma/load.cpp @@ -9,69 +9,62 @@ #include "C/LzmaDec.h" #if (defined __MINGW32__) || (defined _MSC_VER) -# define EXPORT __declspec(dllexport) -# include -# define open _open -# define write _write -# define close _close -# ifdef _MSC_VER -# define S_IRWXU (_S_IREAD | _S_IWRITE) -# define and && -# endif +#define EXPORT __declspec(dllexport) +#include +#define open _open +#define write _write +#define close _close +#ifdef _MSC_VER +#define S_IRWXU (_S_IREAD | _S_IWRITE) +#define and && +#endif #else -# define EXPORT __attribute__ ((visibility("default"))) -# include -# include -# include -# define O_BINARY 0 +#define EXPORT __attribute__((visibility("default"))) +#include +#include +#include +#define O_BINARY 0 #endif -#if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) -# define SYMBOL(x) binary_exe_##x +#if (!defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) +#define SYMBOL(x) binary_exe_##x #else -# define SYMBOL(x) _binary_exe_##x +#define SYMBOL(x) _binary_exe_##x #endif extern "C" { +extern const uint8_t SYMBOL(start)[]; +extern const uint8_t SYMBOL(end)[]; - extern const uint8_t SYMBOL(start)[]; - extern const uint8_t SYMBOL(end)[]; - -} // extern "C" +} // extern "C" namespace { -int32_t -read4(const uint8_t* in) +int32_t read4(const uint8_t* in) { return (static_cast(in[3]) << 24) - | (static_cast(in[2]) << 16) - | (static_cast(in[1]) << 8) - | (static_cast(in[0]) ); + | (static_cast(in[2]) << 16) + | (static_cast(in[1]) << 8) | (static_cast(in[0])); } -void* -myAllocate(void*, size_t size) +void* myAllocate(void*, size_t size) { return malloc(size); } -void -myFree(void*, void* address) +void myFree(void*, void* address) { free(address); } #if (defined __MINGW32__) || (defined _MSC_VER) -void* -openLibrary(const char* name) +void* openLibrary(const char* name) { return LoadLibrary(name); } -void* -librarySymbol(void* library, const char* name) +void* librarySymbol(void* library, const char* name) { void* address; FARPROC p = GetProcAddress(static_cast(library), name); @@ -79,14 +72,12 @@ librarySymbol(void* library, const char* name) return address; } -const char* -libraryError(void*) +const char* libraryError(void*) { return "unknown error"; } -const char* -temporaryFileName(char* buffer, unsigned size) +const char* temporaryFileName(char* buffer, unsigned size) { unsigned c = GetTempPathA(size, buffer); if (c) { @@ -100,36 +91,31 @@ temporaryFileName(char* buffer, unsigned size) #else -void* -openLibrary(const char* name) +void* openLibrary(const char* name) { return dlopen(name, RTLD_LAZY | RTLD_LOCAL); } -void* -librarySymbol(void* library, const char* name) +void* librarySymbol(void* library, const char* name) { return dlsym(library, name); } -const char* -libraryError(void*) +const char* libraryError(void*) { return dlerror(); } -const char* -temporaryFileName(char* buffer, unsigned) +const char* temporaryFileName(char* buffer, unsigned) { return tmpnam(buffer); } #endif -} // namespace +} // namespace -int -main(int ac, const char** av) +int main(int ac, const char** av) { const unsigned PropHeaderSize = 5; const unsigned HeaderSize = 13; @@ -141,13 +127,18 @@ main(int ac, const char** av) uint8_t* out = static_cast(malloc(outSize)); if (out) { - ISzAlloc allocator = { myAllocate, myFree }; + ISzAlloc allocator = {myAllocate, myFree}; ELzmaStatus status = LZMA_STATUS_NOT_SPECIFIED; - if (SZ_OK == LzmaDecode - (out, &outSize, SYMBOL(start) + HeaderSize, &inSize, SYMBOL(start), - PropHeaderSize, LZMA_FINISH_END, &status, &allocator)) - { + if (SZ_OK == LzmaDecode(out, + &outSize, + SYMBOL(start) + HeaderSize, + &inSize, + SYMBOL(start), + PropHeaderSize, + LZMA_FINISH_END, + &status, + &allocator)) { const unsigned BufferSize = 1024; char buffer[BufferSize]; const char* name = temporaryFileName(buffer, BufferSize); @@ -171,14 +162,18 @@ main(int ac, const char** av) fprintf(stderr, "unable to find main in %s", name); } } else { - fprintf(stderr, "unable to load %s: %s\n", name, + fprintf(stderr, + "unable to load %s: %s\n", + name, libraryError(library)); } } else { unlink(name); - fprintf(stderr, "close or write failed; tried %d, got %d; %s\n", - static_cast(outSize), static_cast(result), + fprintf(stderr, + "close or write failed; tried %d, got %d; %s\n", + static_cast(outSize), + static_cast(result), strerror(errno)); } } else { @@ -191,7 +186,8 @@ main(int ac, const char** av) fprintf(stderr, "unable to decode LZMA data\n"); } } else { - fprintf(stderr, "unable to allocate buffer of size %d\n", + fprintf(stderr, + "unable to allocate buffer of size %d\n", static_cast(outSize)); } diff --git a/src/lzma/main.cpp b/src/lzma/main.cpp index f6baa39bb9..daf75c9cde 100644 --- a/src/lzma/main.cpp +++ b/src/lzma/main.cpp @@ -17,46 +17,40 @@ namespace { -int32_t -read4(const uint8_t* in) +int32_t read4(const uint8_t* in) { return (static_cast(in[3]) << 24) - | (static_cast(in[2]) << 16) - | (static_cast(in[1]) << 8) - | (static_cast(in[0]) ); + | (static_cast(in[2]) << 16) + | (static_cast(in[1]) << 8) | (static_cast(in[0])); } -void* -myAllocate(void*, size_t size) +void* myAllocate(void*, size_t size) { return malloc(size); } -void -myFree(void*, void* address) +void myFree(void*, void* address) { free(address); } -SRes -myProgress(void*, UInt64, UInt64) +SRes myProgress(void*, UInt64, UInt64) { return SZ_OK; } -void -usageAndExit(const char* program) +void usageAndExit(const char* program) { fprintf(stderr, "usage: %s {encode|decode} " - "[]", program); + "[]", + program); exit(-1); } -} // namespace +} // namespace -int -main(int argc, const char** argv) +int main(int argc, const char** argv) { if (argc < 4 or argc > 5) { usageAndExit(argv[0]); @@ -73,26 +67,16 @@ main(int argc, const char** argv) if (r != -1) { #ifdef WIN32 HANDLE fm; - HANDLE h = (HANDLE) _get_osfhandle (fd); + HANDLE h = (HANDLE)_get_osfhandle(fd); - fm = CreateFileMapping( - h, - NULL, - PAGE_READONLY, - 0, - 0, - NULL); - data = static_cast(MapViewOfFile( - fm, - FILE_MAP_READ, - 0, - 0, - s.st_size)); + fm = CreateFileMapping(h, NULL, PAGE_READONLY, 0, 0, NULL); + data = static_cast( + MapViewOfFile(fm, FILE_MAP_READ, 0, 0, s.st_size)); CloseHandle(fm); #else - data = static_cast - (mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0)); + data = static_cast( + mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0)); #endif size = s.st_size; } @@ -123,7 +107,7 @@ main(int argc, const char** argv) uint8_t* out = static_cast(malloc(outSize)); if (out) { SizeT inSize = size; - ISzAlloc allocator = { myAllocate, myFree }; + ISzAlloc allocator = {myAllocate, myFree}; ELzmaStatus status = LZMA_STATUS_NOT_SPECIFIED; int result; if (encode) { @@ -132,22 +116,36 @@ main(int argc, const char** argv) props.level = 9; props.writeEndMark = 1; - ICompressProgress progress = { myProgress }; + ICompressProgress progress = {myProgress}; SizeT propsSize = PropHeaderSize; int32_t inSize32 = inSize; memcpy(out + PropHeaderSize, &inSize32, 4); - - result = LzmaEncode - (out + HeaderSize, &outSize, data, inSize, &props, out, - &propsSize, 1, &progress, &allocator, &allocator); + + result = LzmaEncode(out + HeaderSize, + &outSize, + data, + inSize, + &props, + out, + &propsSize, + 1, + &progress, + &allocator, + &allocator); outSize += HeaderSize; } else { - result = LzmaDecode - (out, &outSize, data + HeaderSize, &inSize, data, PropHeaderSize, - LZMA_FINISH_END, &status, &allocator); + result = LzmaDecode(out, + &outSize, + data + HeaderSize, + &inSize, + data, + PropHeaderSize, + LZMA_FINISH_END, + &status, + &allocator); } if (result == SZ_OK) { @@ -165,8 +163,11 @@ main(int argc, const char** argv) fprintf(stderr, "unable to open %s\n", argv[3]); } } else { - fprintf(stderr, "unable to %s data: result %d status %d\n", - encode ? "encode" : "decode", result, status); + fprintf(stderr, + "unable to %s data: result %d status %d\n", + encode ? "encode" : "decode", + result, + status); } free(out); diff --git a/src/machine.cpp b/src/machine.cpp index 2f28cbf86f..a9af32e917 100644 --- a/src/machine.cpp +++ b/src/machine.cpp @@ -21,8 +21,8 @@ #include #if defined(PLATFORM_WINDOWS) -# define WIN32_LEAN_AND_MEAN -# include +#define WIN32_LEAN_AND_MEAN +#include #endif using namespace vm; @@ -35,22 +35,19 @@ const bool DebugClassReader = false; const unsigned NoByte = 0xFFFF; #ifdef USE_ATOMIC_OPERATIONS -void -atomicIncrement(uint32_t* p, int v) +void atomicIncrement(uint32_t* p, int v) { - for (uint32_t old = *p; - not atomicCompareAndSwap32(p, old, old + v); - old = *p) - { } + for (uint32_t old = *p; not atomicCompareAndSwap32(p, old, old + v); + old = *p) { + } } #endif -void -join(Thread* t, Thread* o) +void join(Thread* t, Thread* o) { if (t != o) { - assert(t, o->state != Thread::JoinedState); - assert(t, (o->flags & Thread::SystemFlag) == 0); + assertT(t, o->state != Thread::JoinedState); + assertT(t, (o->flags & Thread::SystemFlag) == 0); if (o->flags & Thread::JoinFlag) { o->systemThread->join(); } @@ -60,40 +57,41 @@ join(Thread* t, Thread* o) #ifndef NDEBUG -bool -find(Thread* t, Thread* o) +bool find(Thread* t, Thread* o) { - return (t == o) - or (t->peer and find(t->peer, o)) - or (t->child and find(t->child, o)); + return (t == o) or (t->peer and find(t->peer, o)) + or (t->child and find(t->child, o)); } -unsigned -count(Thread* t, Thread* o) +unsigned count(Thread* t, Thread* o) { unsigned c = 0; - if (t != o) ++ c; - if (t->peer) c += count(t->peer, o); - if (t->child) c += count(t->child, o); + if (t != o) + ++c; + if (t->peer) + c += count(t->peer, o); + if (t->child) + c += count(t->child, o); return c; } -Thread** -fill(Thread* t, Thread* o, Thread** array) +Thread** fill(Thread* t, Thread* o, Thread** array) { - if (t != o) *(array++) = t; - if (t->peer) array = fill(t->peer, o, array); - if (t->child) array = fill(t->child, o, array); + if (t != o) + *(array++) = t; + if (t->peer) + array = fill(t->peer, o, array); + if (t->child) + array = fill(t->child, o, array); return array; } -#endif // not NDEBUG +#endif // not NDEBUG -void -dispose(Thread* t, Thread* o, bool remove) +void dispose(Thread* t, Thread* o, bool remove) { if (remove) { #ifndef NDEBUG @@ -118,7 +116,7 @@ dispose(Thread* t, Thread* o, bool remove) previous = p; p = p->peer; } - } + } for (Thread* p = o->child; p;) { Thread* next = p->peer; @@ -154,8 +152,7 @@ dispose(Thread* t, Thread* o, bool remove) o->dispose(); } -void -visitAll(Thread* m, Thread* o, void (*visit)(Thread*, Thread*)) +void visitAll(Thread* m, Thread* o, void (*visit)(Thread*, Thread*)) { for (Thread* p = o->child; p;) { Thread* child = p; @@ -166,22 +163,19 @@ visitAll(Thread* m, Thread* o, void (*visit)(Thread*, Thread*)) visit(m, o); } -void -disposeNoRemove(Thread* m, Thread* o) +void disposeNoRemove(Thread* m, Thread* o) { dispose(m, o, false); } -void -interruptDaemon(Thread* m, Thread* o) +void interruptDaemon(Thread* m, Thread* o) { if (o->flags & Thread::DaemonFlag) { interrupt(m, o); } } -void -turnOffTheLights(Thread* t) +void turnOffTheLights(Thread* t) { expect(t, t->m->liveCount == 1); @@ -189,47 +183,46 @@ turnOffTheLights(Thread* t) enter(t, Thread::ExitState); - { object p = 0; + { + GcFinalizer* p = 0; PROTECT(t, p); for (p = t->m->finalizers; p;) { - object f = p; - p = finalizerNext(t, p); + GcFinalizer* f = p; + p = cast(t, p->next()); void (*function)(Thread*, object); - memcpy(&function, &finalizerFinalize(t, f), BytesPerWord); + memcpy(&function, &f->finalize(), BytesPerWord); if (function) { - function(t, finalizerTarget(t, f)); + function(t, f->target()); } } for (p = t->m->tenuredFinalizers; p;) { - object f = p; - p = finalizerNext(t, p); + GcFinalizer* f = p; + p = cast(t, p->next()); void (*function)(Thread*, object); - memcpy(&function, &finalizerFinalize(t, f), BytesPerWord); + memcpy(&function, &f->finalize(), BytesPerWord); if (function) { - function(t, finalizerTarget(t, f)); + function(t, f->target()); } } } - if (root(t, Machine::VirtualFiles)) { - for (unsigned i = 0; i < arrayLength(t, root(t, Machine::VirtualFiles)); - ++i) - { - object region = arrayBody(t, root(t, Machine::VirtualFiles), i); + if (GcArray* files = roots(t)->virtualFiles()) { + PROTECT(t, files); + for (unsigned i = 0; i < files->length(); ++i) { + object region = files->body()[i]; if (region) { - static_cast(regionRegion(t, region))->dispose(); + static_cast(cast(t, region)->region()) + ->dispose(); } } } - for (object p = root(t, Machine::VirtualFileFinders); - p; p = finderNext(t, p)) - { - static_cast(finderFinder(t, p))->dispose(); + for (GcFinder* p = roots(t)->virtualFileFinders(); p; p = p->next()) { + static_cast(p->finder())->dispose(); } Machine* m = t->m; @@ -256,8 +249,7 @@ turnOffTheLights(Thread* t) s->dispose(); } -void -killZombies(Thread* t, Thread* o) +void killZombies(Thread* t, Thread* o) { for (Thread* p = o->child; p;) { Thread* child = p; @@ -269,18 +261,18 @@ killZombies(Thread* t, Thread* o) switch (o->state) { case Thread::ZombieState: join(t, o); - // fall through - + // fall through + case Thread::JoinedState: dispose(t, o, true); - - default: break; + + default: + break; } } } -unsigned -footprint(Thread* t) +unsigned footprint(Thread* t) { expect(t, t->criticalLevel == 0); @@ -293,8 +285,7 @@ footprint(Thread* t) return n; } -void -visitRoots(Thread* t, Heap::Visitor* v) +void visitRoots(Thread* t, Heap::Visitor* v) { if (t->state != Thread::ZombieState) { v->visit(&(t->javaThread)); @@ -312,13 +303,17 @@ visitRoots(Thread* t, Heap::Visitor* v) } } -bool -walk(Thread*, Heap::Walker* w, uint32_t* mask, unsigned fixedSize, - unsigned arrayElementSize, unsigned arrayLength, unsigned start) +bool walk(Thread*, + Heap::Walker* w, + uint32_t* mask, + unsigned fixedSize, + unsigned arrayElementSize, + unsigned arrayLength, + unsigned start) { unsigned fixedSizeInWords = ceilingDivide(fixedSize, BytesPerWord); unsigned arrayElementSizeInWords - = ceilingDivide(arrayElementSize, BytesPerWord); + = ceilingDivide(arrayElementSize, BytesPerWord); for (unsigned i = start; i < fixedSizeInWords; ++i) { if (mask[i / 32] & (static_cast(1) << (i % 32))) { @@ -353,9 +348,8 @@ walk(Thread*, Heap::Walker* w, uint32_t* mask, unsigned fixedSize, for (unsigned j = elementStart; j < arrayElementSizeInWords; ++j) { unsigned k = fixedSizeInWords + j; if (mask[k / 32] & (static_cast(1) << (k % 32))) { - if (not w->visit - (fixedSizeInWords + (i * arrayElementSizeInWords) + j)) - { + if (not w->visit(fixedSizeInWords + (i * arrayElementSizeInWords) + + j)) { return false; } } @@ -366,195 +360,185 @@ walk(Thread*, Heap::Walker* w, uint32_t* mask, unsigned fixedSize, return true; } -object -findInInterfaces(Thread* t, object class_, object name, object spec, - object (*find)(Thread*, object, object, object)) +object findInInterfaces( + Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec, + object (*find)(Thread*, GcClass*, GcByteArray*, GcByteArray*)) { object result = 0; - if (classInterfaceTable(t, class_)) { - for (unsigned i = 0; - i < arrayLength(t, classInterfaceTable(t, class_)) and result == 0; - i += 2) - { - result = find - (t, arrayBody(t, classInterfaceTable(t, class_), i), name, spec); + if (GcArray* itable = cast(t, class_->interfaceTable())) { + PROTECT(t, itable); + for (unsigned i = 0; i < itable->length() and result == 0; i += 2) { + result = find(t, cast(t, itable->body()[i]), name, spec); } } return result; } -void -finalizerTargetUnreachable(Thread* t, Heap::Visitor* v, object* p) +void finalizerTargetUnreachable(Thread* t, Heap::Visitor* v, GcFinalizer** p) { - v->visit(&finalizerTarget(t, *p)); + v->visit(&(*p)->target()); - object finalizer = *p; - *p = finalizerNext(t, finalizer); + GcFinalizer* finalizer = *p; + *p = cast(t, finalizer->next()); void (*function)(Thread*, object); - memcpy(&function, &finalizerFinalize(t, finalizer), BytesPerWord); + memcpy(&function, &finalizer->finalize(), BytesPerWord); if (function) { - finalizerNext(t, finalizer) = t->m->finalizeQueue; + // TODO: use set() here? + finalizer->next() = t->m->finalizeQueue; t->m->finalizeQueue = finalizer; } else { - set(t, finalizer, FinalizerQueueTarget, finalizerTarget(t, finalizer)); - set(t, finalizer, FinalizerQueueNext, root(t, Machine::ObjectsToFinalize)); - setRoot(t, Machine::ObjectsToFinalize, finalizer); + finalizer->setQueueTarget(t, finalizer->target()); + finalizer->setQueueNext(t, roots(t)->objectsToFinalize()); + roots(t)->setObjectsToFinalize(t, finalizer); } } -void -referenceTargetUnreachable(Thread* t, Heap::Visitor* v, object* p) +void referenceTargetUnreachable(Thread* t, Heap::Visitor* v, GcJreference** p) { if (DebugReferences) { - fprintf(stderr, "target %p unreachable for reference %p\n", - jreferenceTarget(t, *p), *p); + fprintf( + stderr, "target %p unreachable for reference %p\n", (*p)->target(), *p); } v->visit(p); - jreferenceTarget(t, *p) = 0; + (*p)->target() = 0; - if (objectClass(t, *p) == type(t, Machine::CleanerType)) { - object reference = *p; - *p = jreferenceVmNext(t, reference); + if (objectClass(t, *p) == type(t, GcCleaner::Type)) { + *p = cast(t, (*p)->vmNext()); - set(t, reference, CleanerQueueNext, root(t, Machine::ObjectsToClean)); - setRoot(t, Machine::ObjectsToClean, reference); + // In openjdk, sun/misc/Cleaner extends PhantomReference + GcCleaner* cleaner = (*p)->as(t); + + cleaner->setQueueNext(t, roots(t)->objectsToClean()); + roots(t)->setObjectsToClean(t, cleaner); } else { - if (jreferenceQueue(t, *p) - and t->m->heap->status(jreferenceQueue(t, *p)) != Heap::Unreachable) - { + if ((*p)->queue() + and t->m->heap->status((*p)->queue()) != Heap::Unreachable) { // queue is reachable - add the reference - v->visit(&jreferenceQueue(t, *p)); + v->visit(&(*p)->queue()); - object q = jreferenceQueue(t, *p); + GcReferenceQueue* q = (*p)->queue(); - if (referenceQueueFront(t, q)) { - set(t, *p, JreferenceJNext, referenceQueueFront(t, q)); + if (q->front()) { + (*p)->setJNext(t, q->front()); } else { - set(t, *p, JreferenceJNext, *p); + (*p)->setJNext(t, *p); } - set(t, q, ReferenceQueueFront, *p); + q->setFront(t, *p); - jreferenceQueue(t, *p) = 0; + (*p)->queue() = 0; } - *p = jreferenceVmNext(t, *p); + *p = cast(t, (*p)->vmNext()); } } -void -referenceUnreachable(Thread* t, Heap::Visitor* v, object* p) +void referenceUnreachable(Thread* t, Heap::Visitor* v, GcJreference** p) { - object r = static_cast(t->m->heap->follow(*p)); + GcJreference* r = t->m->heap->follow(*p); if (DebugReferences) { - fprintf(stderr, "reference %p unreachable (target %p)\n", - *p, jreferenceTarget(t, r)); + fprintf(stderr, "reference %p unreachable (target %p)\n", *p, r->target()); } - if (jreferenceQueue(t, r) - and t->m->heap->status(jreferenceQueue(t, r)) != Heap::Unreachable) - { + if (r->queue() and t->m->heap->status(r->queue()) != Heap::Unreachable) { // queue is reachable - add the reference - referenceTargetUnreachable(t, v, p); + referenceTargetUnreachable(t, v, p); } else { - *p = jreferenceVmNext(t, *p); + *p = cast(t, (*p)->vmNext()); } } -void -referenceTargetReachable(Thread* t, Heap::Visitor* v, object* p) +void referenceTargetReachable(Thread* t, Heap::Visitor* v, GcJreference** p) { if (DebugReferences) { - fprintf(stderr, "target %p reachable for reference %p\n", - jreferenceTarget(t, *p), *p); + fprintf( + stderr, "target %p reachable for reference %p\n", (*p)->target(), *p); } v->visit(p); - v->visit(&jreferenceTarget(t, *p)); + v->visit(&(*p)->target()); - if (t->m->heap->status(jreferenceQueue(t, *p)) == Heap::Unreachable) { - jreferenceQueue(t, *p) = 0; + if (t->m->heap->status((*p)->queue()) == Heap::Unreachable) { + (*p)->queue() = 0; } else { - v->visit(&jreferenceQueue(t, *p)); + v->visit(&(*p)->queue()); } } -bool -isFinalizable(Thread* t, object o) +bool isFinalizable(Thread* t, object o) { return t->m->heap->status(o) == Heap::Unreachable - and (classVmFlags - (t, static_cast(t->m->heap->follow(objectClass(t, o)))) - & HasFinalizerFlag); + and (t->m->heap->follow(objectClass(t, o))->vmFlags() + & HasFinalizerFlag); } -void -clearTargetIfFinalizable(Thread* t, object r) +void clearTargetIfFinalizable(Thread* t, GcJreference* r) { - if (isFinalizable - (t, static_cast(t->m->heap->follow(jreferenceTarget(t, r))))) - { - jreferenceTarget(t, r) = 0; + if (isFinalizable(t, t->m->heap->follow(r->target()))) { + r->target() = 0; } } -void -postVisit(Thread* t, Heap::Visitor* v) +void postVisit(Thread* t, Heap::Visitor* v) { Machine* m = t->m; bool major = m->heap->collectionType() == Heap::MajorCollection; - assert(t, m->finalizeQueue == 0); + assertT(t, m->finalizeQueue == 0); m->heap->postVisit(); - for (object p = m->weakReferences; p;) { - object r = static_cast(m->heap->follow(p)); - p = jreferenceVmNext(t, r); + for (GcJreference* p = m->weakReferences; p;) { + GcJreference* r = m->heap->follow(p); + p = cast(t, r->vmNext()); clearTargetIfFinalizable(t, r); } if (major) { - for (object p = m->tenuredWeakReferences; p;) { - object r = static_cast(m->heap->follow(p)); - p = jreferenceVmNext(t, r); + for (GcJreference* p = m->tenuredWeakReferences; p;) { + GcJreference* r = m->heap->follow(p); + p = cast(t, r->vmNext()); clearTargetIfFinalizable(t, r); } } for (Reference* r = m->jniReferences; r; r = r->next) { - if (r->weak and isFinalizable - (t, static_cast(t->m->heap->follow(r->target)))) - { + if (r->weak + and isFinalizable(t, + static_cast(t->m->heap->follow(r->target)))) { r->target = 0; } } - object firstNewTenuredFinalizer = 0; - object lastNewTenuredFinalizer = 0; + GcFinalizer* firstNewTenuredFinalizer = 0; + GcFinalizer* lastNewTenuredFinalizer = 0; - { object unreachable = 0; - for (object* p = &(m->finalizers); *p;) { + { + object unreachable = 0; + for (GcFinalizer** p = &(m->finalizers); *p;) { v->visit(p); - if (m->heap->status(finalizerTarget(t, *p)) == Heap::Unreachable) { - object finalizer = *p; - *p = finalizerNext(t, finalizer); + if (m->heap->status((*p)->target()) == Heap::Unreachable) { + GcFinalizer* finalizer = *p; + *p = cast(t, finalizer->next()); - finalizerNext(t, finalizer) = unreachable; + finalizer->next() = unreachable; unreachable = finalizer; } else { - p = &finalizerNext(t, *p); + p = reinterpret_cast(&(*p)->next()); } } - for (object* p = &(m->finalizers); *p;) { + for (GcFinalizer** p = &(m->finalizers); *p;) { // target is reachable - v->visit(&finalizerTarget(t, *p)); + v->visit(&(*p)->target()); if (m->heap->status(*p) == Heap::Tenured) { // the finalizer is tenured, so we remove it from @@ -564,33 +548,30 @@ postVisit(Thread* t, Heap::Visitor* v) lastNewTenuredFinalizer = *p; } - object finalizer = *p; - *p = finalizerNext(t, finalizer); - finalizerNext(t, finalizer) = firstNewTenuredFinalizer; + GcFinalizer* finalizer = *p; + *p = cast(t, finalizer->next()); + finalizer->next() = firstNewTenuredFinalizer; firstNewTenuredFinalizer = finalizer; } else { - p = &finalizerNext(t, *p); + p = reinterpret_cast(&(*p)->next()); } } for (object* p = &unreachable; *p;) { // target is unreachable - queue it up for finalization - finalizerTargetUnreachable(t, v, p); + finalizerTargetUnreachable(t, v, reinterpret_cast(p)); } } - object firstNewTenuredWeakReference = 0; - object lastNewTenuredWeakReference = 0; + GcJreference* firstNewTenuredWeakReference = 0; + GcJreference* lastNewTenuredWeakReference = 0; - for (object* p = &(m->weakReferences); *p;) { + for (GcJreference** p = &(m->weakReferences); *p;) { if (m->heap->status(*p) == Heap::Unreachable) { // reference is unreachable referenceUnreachable(t, v, p); - } else if (m->heap->status - (jreferenceTarget - (t, static_cast(m->heap->follow(*p)))) - == Heap::Unreachable) - { + } else if (m->heap->status(m->heap->follow(*p)->target()) + == Heap::Unreachable) { // target is unreachable referenceTargetUnreachable(t, v, p); } else { @@ -606,71 +587,68 @@ postVisit(Thread* t, Heap::Visitor* v) lastNewTenuredWeakReference = *p; } - object reference = *p; - *p = jreferenceVmNext(t, reference); - jreferenceVmNext(t, reference) = firstNewTenuredWeakReference; + GcJreference* reference = (*p); + *p = cast(t, reference->vmNext()); + reference->vmNext() = firstNewTenuredWeakReference; firstNewTenuredWeakReference = reference; } else { - p = &jreferenceVmNext(t, *p); + p = reinterpret_cast(&(*p)->vmNext()); } } } if (major) { - { object unreachable = 0; - for (object* p = &(m->tenuredFinalizers); *p;) { + { + object unreachable = 0; + for (GcFinalizer** p = &(m->tenuredFinalizers); *p;) { v->visit(p); - if (m->heap->status(finalizerTarget(t, *p)) == Heap::Unreachable) { - object finalizer = *p; - *p = finalizerNext(t, finalizer); + if (m->heap->status((*p)->target()) == Heap::Unreachable) { + GcFinalizer* finalizer = *p; + *p = cast(t, finalizer->next()); - finalizerNext(t, finalizer) = unreachable; + finalizer->next() = unreachable; unreachable = finalizer; } else { - p = &finalizerNext(t, *p); + p = reinterpret_cast(&(*p)->next()); } } - for (object* p = &(m->tenuredFinalizers); *p;) { + for (GcFinalizer** p = &(m->tenuredFinalizers); *p;) { // target is reachable - v->visit(&finalizerTarget(t, *p)); - p = &finalizerNext(t, *p); + v->visit(&(*p)->target()); + p = reinterpret_cast(&(*p)->next()); } for (object* p = &unreachable; *p;) { // target is unreachable - queue it up for finalization - finalizerTargetUnreachable(t, v, p); + finalizerTargetUnreachable(t, v, reinterpret_cast(p)); } } - for (object* p = &(m->tenuredWeakReferences); *p;) { + for (GcJreference** p = &(m->tenuredWeakReferences); *p;) { if (m->heap->status(*p) == Heap::Unreachable) { // reference is unreachable - referenceUnreachable(t, v, p); - } else if (m->heap->status - (jreferenceTarget - (t, static_cast(m->heap->follow(*p)))) - == Heap::Unreachable) - { + referenceUnreachable(t, v, reinterpret_cast(p)); + } else if (m->heap->status(m->heap->follow(*p)->target()) + == Heap::Unreachable) { // target is unreachable - referenceTargetUnreachable(t, v, p); + referenceTargetUnreachable(t, v, reinterpret_cast(p)); } else { // both reference and target are reachable - referenceTargetReachable(t, v, p); - p = &jreferenceVmNext(t, *p); + referenceTargetReachable(t, v, reinterpret_cast(p)); + p = reinterpret_cast(&(*p)->vmNext()); } } } if (lastNewTenuredFinalizer) { - finalizerNext(t, lastNewTenuredFinalizer) = m->tenuredFinalizers; + lastNewTenuredFinalizer->next() = m->tenuredFinalizers; m->tenuredFinalizers = firstNewTenuredFinalizer; } if (lastNewTenuredWeakReference) { - jreferenceVmNext(t, lastNewTenuredWeakReference) - = m->tenuredWeakReferences; + lastNewTenuredWeakReference->vmNext() = m->tenuredWeakReferences; m->tenuredWeakReferences = firstNewTenuredWeakReference; } @@ -685,13 +663,12 @@ postVisit(Thread* t, Heap::Visitor* v) } } -void -postCollect(Thread* t) +void postCollect(Thread* t) { #ifdef VM_STRESS t->m->heap->free(t->defaultHeap, ThreadHeapSizeInBytes); - t->defaultHeap = static_cast - (t->m->heap->allocate(ThreadHeapSizeInBytes)); + t->defaultHeap + = static_cast(t->m->heap->allocate(ThreadHeapSizeInBytes)); memset(t->defaultHeap, 0, ThreadHeapSizeInBytes); #endif @@ -724,10 +701,9 @@ postCollect(Thread* t) } } -uint64_t -invoke(Thread* t, uintptr_t* arguments) +uint64_t invoke(Thread* t, uintptr_t* arguments) { - object m = *reinterpret_cast(arguments[0]); + GcMethod* m = cast(t, *reinterpret_cast(arguments[0])); object o = *reinterpret_cast(arguments[1]); t->m->processor->invoke(t, m, o); @@ -735,36 +711,34 @@ invoke(Thread* t, uintptr_t* arguments) return 1; } -void -finalizeObject(Thread* t, object o, const char* name) +void finalizeObject(Thread* t, object o, const char* name) { - for (object c = objectClass(t, o); c; c = classSuper(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) { - object m = arrayBody(t, classMethodTable(t, c), i); + for (GcClass* c = objectClass(t, o); c; c = c->super()) { + GcArray* mtable = cast(t, c->methodTable()); + for (unsigned i = 0; i < mtable->length(); ++i) { + GcMethod* m = cast(t, mtable->body()[i]); if (vm::strcmp(reinterpret_cast(name), - &byteArrayBody(t, methodName(t, m), 0)) == 0 + m->name()->body().begin()) == 0 and vm::strcmp(reinterpret_cast("()V"), - &byteArrayBody(t, methodSpec(t, m), 0)) == 0) - { + m->spec()->body().begin()) == 0) { PROTECT(t, m); PROTECT(t, o); - uintptr_t arguments[] = { reinterpret_cast(&m), - reinterpret_cast(&o) }; + uintptr_t arguments[] = {reinterpret_cast(&m), + reinterpret_cast(&o)}; run(t, invoke, arguments); t->exception = 0; return; - } + } } } abort(t); } -unsigned -readByte(AbstractStream& s, unsigned* value) +unsigned readByte(AbstractStream& s, unsigned* value) { if (*value == NoByte) { return s.read1(); @@ -775,134 +749,135 @@ readByte(AbstractStream& s, unsigned* value) } } -object -parseUtf8NonAscii(Thread* t, AbstractStream& s, object bytesSoFar, - unsigned byteCount, unsigned sourceIndex, unsigned byteA, - unsigned byteB) +GcCharArray* parseUtf8NonAscii(Thread* t, + AbstractStream& s, + GcByteArray* bytesSoFar, + unsigned byteCount, + unsigned sourceIndex, + unsigned byteA, + unsigned byteB) { PROTECT(t, bytesSoFar); - - unsigned length = byteArrayLength(t, bytesSoFar) - 1; - object value = makeCharArray(t, length + 1); + + unsigned length = bytesSoFar->length() - 1; + GcCharArray* value = makeCharArray(t, length + 1); unsigned vi = 0; for (; vi < byteCount; ++vi) { - charArrayBody(t, value, vi) = byteArrayBody(t, bytesSoFar, vi); + value->body()[vi] = bytesSoFar->body()[vi]; } for (unsigned si = sourceIndex; si < length; ++si) { unsigned a = readByte(s, &byteA); if (a & 0x80) { if (a & 0x20) { - // 3 bytes - si += 2; - assert(t, si < length); + // 3 bytes + si += 2; + assertT(t, si < length); unsigned b = readByte(s, &byteB); - unsigned c = s.read1(); - charArrayBody(t, value, vi++) - = ((a & 0xf) << 12) | ((b & 0x3f) << 6) | (c & 0x3f); + unsigned c = s.read1(); + value->body()[vi++] = ((a & 0xf) << 12) | ((b & 0x3f) << 6) + | (c & 0x3f); } else { - // 2 bytes - ++ si; - assert(t, si < length); + // 2 bytes + ++si; + assertT(t, si < length); unsigned b = readByte(s, &byteB); - if (a == 0xC0 and b == 0x80) { - charArrayBody(t, value, vi++) = 0; - } else { - charArrayBody(t, value, vi++) = ((a & 0x1f) << 6) | (b & 0x3f); - } + if (a == 0xC0 and b == 0x80) { + value->body()[vi++] = 0; + } else { + value->body()[vi++] = ((a & 0x1f) << 6) | (b & 0x3f); + } } } else { - charArrayBody(t, value, vi++) = a; + value->body()[vi++] = a; } } if (vi < length) { PROTECT(t, value); - - object v = makeCharArray(t, vi + 1); - memcpy(&charArrayBody(t, v, 0), &charArrayBody(t, value, 0), vi * 2); + + GcCharArray* v = makeCharArray(t, vi + 1); + memcpy(v->body().begin(), value->body().begin(), vi * 2); value = v; } - + return value; } -object -parseUtf8(Thread* t, AbstractStream& s, unsigned length) +object parseUtf8(Thread* t, AbstractStream& s, unsigned length) { - object value = makeByteArray(t, length + 1); + GcByteArray* value = makeByteArray(t, length + 1); unsigned vi = 0; for (unsigned si = 0; si < length; ++si) { unsigned a = s.read1(); if (a & 0x80) { if (a & 0x20) { - // 3 bytes + // 3 bytes return parseUtf8NonAscii(t, s, value, vi, si, a, NoByte); } else { - // 2 bytes - unsigned b = s.read1(); + // 2 bytes + unsigned b = s.read1(); - if (a == 0xC0 and b == 0x80) { - ++ si; - assert(t, si < length); - byteArrayBody(t, value, vi++) = 0; - } else { + if (a == 0xC0 and b == 0x80) { + ++si; + assertT(t, si < length); + value->body()[vi++] = 0; + } else { return parseUtf8NonAscii(t, s, value, vi, si, a, b); - } + } } } else { - byteArrayBody(t, value, vi++) = a; + value->body()[vi++] = a; } } if (vi < length) { PROTECT(t, value); - - object v = makeByteArray(t, vi + 1); - memcpy(&byteArrayBody(t, v, 0), &byteArrayBody(t, value, 0), vi); + + GcByteArray* v = makeByteArray(t, vi + 1); + memcpy(v->body().begin(), value->body().begin(), vi); value = v; } - + return value; } -object -makeByteArray(Thread* t, Stream& s, unsigned length) +GcByteArray* makeByteArray(Thread* t, Stream& s, unsigned length) { - object value = makeByteArray(t, length + 1); - s.read(reinterpret_cast(&byteArrayBody(t, value, 0)), length); + GcByteArray* value = makeByteArray(t, length + 1); + s.read(reinterpret_cast(value->body().begin()), length); return value; } -void -removeByteArray(Thread* t, object o) +void removeByteArray(Thread* t, object o) { - hashMapRemove - (t, root(t, Machine::ByteArrayMap), o, byteArrayHash, objectEqual); + hashMapRemove(t, roots(t)->byteArrayMap(), o, byteArrayHash, objectEqual); } -object -internByteArray(Thread* t, object array) +GcByteArray* internByteArray(Thread* t, GcByteArray* array) { PROTECT(t, array); ACQUIRE(t, t->m->referenceLock); - object n = hashMapFindNode - (t, root(t, Machine::ByteArrayMap), array, byteArrayHash, byteArrayEqual); + GcTriple* n = hashMapFindNode( + t, roots(t)->byteArrayMap(), array, byteArrayHash, byteArrayEqual); if (n) { - return jreferenceTarget(t, tripleFirst(t, n)); + return cast(t, cast(t, n->first())->target()); } else { - hashMapInsert(t, root(t, Machine::ByteArrayMap), array, 0, byteArrayHash); + hashMapInsert(t, roots(t)->byteArrayMap(), array, 0, byteArrayHash); addFinalizer(t, array, removeByteArray); return array; } } -unsigned -parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) +unsigned parsePoolEntry(Thread* t, + Stream& s, + uint32_t* index, + GcSingleton* pool, + unsigned i) { PROTECT(t, pool); @@ -914,62 +889,69 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) uint32_t v = s.read4(); singletonValue(t, pool, i) = v; - if(DebugClassReader) { + if (DebugClassReader) { fprintf(stderr, " consts[%d] = int/float 0x%x\n", i, v); } - } return 1; - + } + return 1; + case CONSTANT_Long: case CONSTANT_Double: { uint64_t v = s.read8(); memcpy(&singletonValue(t, pool, i), &v, 8); - if(DebugClassReader) { + if (DebugClassReader) { fprintf(stderr, " consts[%d] = long/double \n", i); } - } return 2; + } + return 2; case CONSTANT_Utf8: { if (singletonObject(t, pool, i) == 0) { - object value = internByteArray(t, makeByteArray(t, s, s.read2())); - set(t, pool, SingletonBody + (i * BytesPerWord), value); + GcByteArray* value = internByteArray(t, makeByteArray(t, s, s.read2())); + pool->setBodyElement(t, i, reinterpret_cast(value)); - if(DebugClassReader) { - fprintf(stderr, " consts[%d] = utf8 %s\n", i, &byteArrayBody(t, value, 0)); + if (DebugClassReader) { + fprintf(stderr, " consts[%d] = utf8 %s\n", i, value->body().begin()); } } - } return 1; + } + return 1; case CONSTANT_Class: { if (singletonObject(t, pool, i) == 0) { unsigned si = s.read2() - 1; parsePoolEntry(t, s, index, pool, si); - - object value = makeReference(t, 0, 0, singletonObject(t, pool, si), 0); - set(t, pool, SingletonBody + (i * BytesPerWord), value); - if(DebugClassReader) { + GcReference* value = makeReference( + t, 0, 0, cast(t, singletonObject(t, pool, si)), 0); + pool->setBodyElement(t, i, reinterpret_cast(value)); + + if (DebugClassReader) { fprintf(stderr, " consts[%d] = class \n", i); } } - } return 1; + } + return 1; case CONSTANT_String: { if (singletonObject(t, pool, i) == 0) { unsigned si = s.read2() - 1; parsePoolEntry(t, s, index, pool, si); - - object value = parseUtf8(t, singletonObject(t, pool, si)); - value = t->m->classpath->makeString - (t, value, 0, fieldAtOffset(value, BytesPerWord) - 1); - value = intern(t, value); - set(t, pool, SingletonBody + (i * BytesPerWord), value); - if(DebugClassReader) { + object value + = parseUtf8(t, cast(t, singletonObject(t, pool, si))); + value = t->m->classpath->makeString( + t, value, 0, fieldAtOffset(value, BytesPerWord) - 1); + value = intern(t, value); + pool->setBodyElement(t, i, reinterpret_cast(value)); + + if (DebugClassReader) { fprintf(stderr, " consts[%d] = string \n", i); } } - } return 1; + } + return 1; case CONSTANT_NameAndType: { if (singletonObject(t, pool, i) == 0) { @@ -978,17 +960,22 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) parsePoolEntry(t, s, index, pool, ni); parsePoolEntry(t, s, index, pool, ti); - - object name = singletonObject(t, pool, ni); - object type = singletonObject(t, pool, ti); - object value = makePair(t, name, type); - set(t, pool, SingletonBody + (i * BytesPerWord), value); - if(DebugClassReader) { - fprintf(stderr, " consts[%d] = nameAndType %s%s\n", i, &byteArrayBody(t, name, 0), &byteArrayBody(t, type, 0)); + GcByteArray* name = cast(t, singletonObject(t, pool, ni)); + GcByteArray* type = cast(t, singletonObject(t, pool, ti)); + GcPair* value = makePair(t, name, type); + pool->setBodyElement(t, i, reinterpret_cast(value)); + + if (DebugClassReader) { + fprintf(stderr, + " consts[%d] = nameAndType %s%s\n", + i, + name->body().begin(), + type->body().begin()); } } - } return 1; + } + return 1; case CONSTANT_Fieldref: case CONSTANT_Methodref: @@ -1000,18 +987,28 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) parsePoolEntry(t, s, index, pool, ci); parsePoolEntry(t, s, index, pool, nti); - object class_ = referenceName(t, singletonObject(t, pool, ci)); - object nameAndType = singletonObject(t, pool, nti); + GcByteArray* className + = cast(t, singletonObject(t, pool, ci))->name(); + GcPair* nameAndType = cast(t, singletonObject(t, pool, nti)); - object value = makeReference - (t, 0, class_, pairFirst(t, nameAndType), pairSecond(t, nameAndType)); - set(t, pool, SingletonBody + (i * BytesPerWord), value); + object value = makeReference(t, + 0, + className, + cast(t, nameAndType->first()), + cast(t, nameAndType->second())); + pool->setBodyElement(t, i, reinterpret_cast(value)); - if(DebugClassReader) { - fprintf(stderr, " consts[%d] = method %s.%s%s\n", i, &byteArrayBody(t, class_, 0), &byteArrayBody(t, pairFirst(t, nameAndType), 0), &byteArrayBody(t, pairSecond(t, nameAndType), 0)); + if (DebugClassReader) { + fprintf(stderr, + " consts[%d] = method %s.%s%s\n", + i, + className->body().begin(), + cast(t, nameAndType->first())->body().begin(), + cast(t, nameAndType->second())->body().begin()); } } - } return 1; + } + return 1; case CONSTANT_MethodHandle: if (singletonObject(t, pool, i) == 0) { @@ -1020,21 +1017,24 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) parsePoolEntry(t, s, index, pool, ri); - object value = singletonObject(t, pool, ri); + GcReference* value = cast(t, singletonObject(t, pool, ri)); if (DebugClassReader) { - fprintf(stderr, " consts[%d] = method handle %d %s.%s%s\n", i, kind, - &byteArrayBody(t, referenceClass(t, value), 0), - &byteArrayBody(t, referenceName(t, value), 0), - &byteArrayBody(t, referenceSpec(t, value), 0)); + fprintf(stderr, + " consts[%d] = method handle %d %s.%s%s\n", + i, + kind, + value->class_()->body().begin(), + value->name()->body().begin(), + value->spec()->body().begin()); } - value = makeReference - (t, kind, referenceClass(t, value), referenceName(t, value), - referenceSpec(t, value)); + value = makeReference( + t, kind, value->class_(), value->name(), value->spec()); - set(t, pool, SingletonBody + (i * BytesPerWord), value); - } return 1; + pool->setBodyElement(t, i, reinterpret_cast(value)); + } + return 1; case CONSTANT_MethodType: if (singletonObject(t, pool, i) == 0) { @@ -1042,9 +1042,10 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) parsePoolEntry(t, s, index, pool, ni); - set(t, pool, SingletonBody + (i * BytesPerWord), - singletonObject(t, pool, ni)); - } return 1; + pool->setBodyElement( + t, i, reinterpret_cast(singletonObject(t, pool, ni))); + } + return 1; case CONSTANT_InvokeDynamic: if (singletonObject(t, pool, i) == 0) { @@ -1053,47 +1054,67 @@ parsePoolEntry(Thread* t, Stream& s, uint32_t* index, object pool, unsigned i) parsePoolEntry(t, s, index, pool, nti); - object nameAndType = singletonObject(t, pool, nti); + GcPair* nameAndType = cast(t, singletonObject(t, pool, nti)); - const char* specString = reinterpret_cast - (&byteArrayBody(t, pairSecond(t, nameAndType), 0)); + const char* specString = reinterpret_cast( + cast(t, nameAndType->second())->body().begin()); unsigned parameterCount; unsigned parameterFootprint; unsigned returnCode; - scanMethodSpec - (t, specString, true, ¶meterCount, ¶meterFootprint, - &returnCode); + scanMethodSpec(t, + specString, + true, + ¶meterCount, + ¶meterFootprint, + &returnCode); - object template_ = makeMethod - (t, 0, returnCode, parameterCount, parameterFootprint, 0, 0, 0, 0, - pairFirst(t, nameAndType), pairSecond(t, nameAndType), 0, 0, 0); + GcMethod* template_ + = makeMethod(t, + 0, + returnCode, + parameterCount, + parameterFootprint, + 0, + 0, + 0, + 0, + cast(t, nameAndType->first()), + cast(t, nameAndType->second()), + 0, + 0, + 0); - object value = makeInvocation - (t, bootstrap, -1, 0, pool, template_, 0); + object value = reinterpret_cast( + makeInvocation(t, bootstrap, -1, 0, pool, template_, 0)); - set(t, pool, SingletonBody + (i * BytesPerWord), value); - } return 1; + pool->setBodyElement(t, i, reinterpret_cast(value)); + } + return 1; - default: abort(t); + default: + abort(t); } } -object -parsePool(Thread* t, Stream& s) +GcSingleton* parsePool(Thread* t, Stream& s) { unsigned count = s.read2() - 1; - object pool = makeSingletonOfSize(t, count + poolMaskSize(count)); + GcSingleton* pool = makeSingletonOfSize(t, count + poolMaskSize(count)); PROTECT(t, pool); - if(DebugClassReader) { + if (DebugClassReader) { fprintf(stderr, " const pool entries %d\n", count); } if (count) { uint32_t* index = static_cast(t->m->heap->allocate(count * 4)); - THREAD_RESOURCE2(t, uint32_t*, index, unsigned, count, + THREAD_RESOURCE2(t, + uint32_t*, + index, + unsigned, + count, t->m->heap->free(index, count * 4)); for (unsigned i = 0; i < count; ++i) { @@ -1125,14 +1146,14 @@ parsePool(Thread* t, Stream& s) case CONSTANT_Long: s.skip(8); - ++ i; + ++i; break; case CONSTANT_Double: singletonSetBit(t, pool, count, i); singletonSetBit(t, pool, count, i + 1); s.skip(8); - ++ i; + ++i; break; case CONSTANT_Utf8: @@ -1155,7 +1176,8 @@ parsePool(Thread* t, Stream& s) s.skip(4); break; - default: abort(t); + default: + abort(t); } } @@ -1171,86 +1193,87 @@ parsePool(Thread* t, Stream& s) return pool; } -void -addInterfaces(Thread* t, object class_, object map) +void addInterfaces(Thread* t, GcClass* class_, GcHashMap* map) { - object table = classInterfaceTable(t, class_); + GcArray* table = cast(t, class_->interfaceTable()); if (table) { unsigned increment = 2; - if (classFlags(t, class_) & ACC_INTERFACE) { + if (class_->flags() & ACC_INTERFACE) { increment = 1; } PROTECT(t, map); PROTECT(t, table); - for (unsigned i = 0; i < arrayLength(t, table); i += increment) { - object interface = arrayBody(t, table, i); - object name = className(t, interface); - hashMapInsertMaybe(t, map, name, interface, byteArrayHash, - byteArrayEqual); + for (unsigned i = 0; i < table->length(); i += increment) { + GcClass* interface = cast(t, table->body()[i]); + GcByteArray* name = interface->name(); + hashMapInsertMaybe( + t, map, name, interface, byteArrayHash, byteArrayEqual); } } } -object -getClassAddendum(Thread* t, object class_, object pool) +GcClassAddendum* getClassAddendum(Thread* t, GcClass* class_, GcSingleton* pool) { - object addendum = classAddendum(t, class_); + GcClassAddendum* addendum = class_->addendum(); if (addendum == 0) { PROTECT(t, class_); addendum = makeClassAddendum(t, pool, 0, 0, 0, 0, -1, 0, 0); - set(t, class_, ClassAddendum, addendum); + setField(t, class_, ClassAddendum, addendum); } return addendum; } -void -parseInterfaceTable(Thread* t, Stream& s, object class_, object pool, - Machine::Type throwType) +void parseInterfaceTable(Thread* t, + Stream& s, + GcClass* class_, + GcSingleton* pool, + Gc::Type throwType) { PROTECT(t, class_); PROTECT(t, pool); - - object map = makeHashMap(t, 0, 0); + + GcHashMap* map = makeHashMap(t, 0, 0); PROTECT(t, map); - if (classSuper(t, class_)) { - addInterfaces(t, classSuper(t, class_), map); + if (class_->super()) { + addInterfaces(t, class_->super(), map); } unsigned count = s.read2(); - object table = 0; + GcArray* table = 0; PROTECT(t, table); if (count) { table = makeArray(t, count); - object addendum = getClassAddendum(t, class_, pool); - set(t, addendum, ClassAddendumInterfaceTable, table); + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); + addendum->setInterfaceTable(t, table); } for (unsigned i = 0; i < count; ++i) { - object name = referenceName(t, singletonObject(t, pool, s.read2() - 1)); + GcByteArray* name + = cast(t, singletonObject(t, pool, s.read2() - 1))->name(); PROTECT(t, name); - object interface = resolveClass - (t, classLoader(t, class_), name, true, throwType); + GcClass* interface = resolveClass( + t, class_->loader(), name, true, throwType); PROTECT(t, interface); - set(t, table, ArrayBody + (i * BytesPerWord), interface); + table->setBodyElement(t, i, interface); hashMapInsertMaybe(t, map, name, interface, byteArrayHash, byteArrayEqual); addInterfaces(t, interface, map); } - object interfaceTable = 0; - if (hashMapSize(t, map)) { - unsigned length = hashMapSize(t, map); - if ((classFlags(t, class_) & ACC_INTERFACE) == 0) { + GcArray* interfaceTable = 0; + if (map->size()) { + unsigned length = map->size(); + if ((class_->flags() & ACC_INTERFACE) == 0) { length *= 2; } interfaceTable = makeArray(t, length); @@ -1258,18 +1281,18 @@ parseInterfaceTable(Thread* t, Stream& s, object class_, object pool, unsigned i = 0; for (HashMapIterator it(t, map); it.hasMore();) { - object interface = tripleSecond(t, it.next()); + GcClass* interface = cast(t, it.next()->second()); - set(t, interfaceTable, ArrayBody + (i * BytesPerWord), interface); - ++ i; + interfaceTable->setBodyElement(t, i, interface); + ++i; - if ((classFlags(t, class_) & ACC_INTERFACE) == 0) { - if (classVirtualTable(t, interface)) { + if ((class_->flags() & ACC_INTERFACE) == 0) { + if (GcArray* vt = cast(t, interface->virtualTable())) { + PROTECT(t, vt); // we'll fill in this table in parseMethodTable(): - object vtable = makeArray - (t, arrayLength(t, classVirtualTable(t, interface))); - - set(t, interfaceTable, ArrayBody + (i * BytesPerWord), vtable); + GcArray* vtable = makeArray(t, vt->length()); + + interfaceTable->setBodyElement(t, i, vtable); } ++i; @@ -1277,32 +1300,31 @@ parseInterfaceTable(Thread* t, Stream& s, object class_, object pool, } } - set(t, class_, ClassInterfaceTable, interfaceTable); + class_->setInterfaceTable(t, interfaceTable); } -void -parseFieldTable(Thread* t, Stream& s, object class_, object pool) +void parseFieldTable(Thread* t, Stream& s, GcClass* class_, GcSingleton* pool) { PROTECT(t, class_); PROTECT(t, pool); unsigned memberOffset = BytesPerWord; - if (classSuper(t, class_)) { - memberOffset = classFixedSize(t, classSuper(t, class_)); + if (class_->super()) { + memberOffset = class_->super()->fixedSize(); } unsigned count = s.read2(); if (count) { unsigned staticOffset = BytesPerWord * 3; unsigned staticCount = 0; - - object fieldTable = makeArray(t, count); + + GcArray* fieldTable = makeArray(t, count); PROTECT(t, fieldTable); - object staticValueTable = makeIntArray(t, count); + GcIntArray* staticValueTable = makeIntArray(t, count); PROTECT(t, staticValueTable); - object addendum = 0; + GcFieldAddendum* addendum = 0; PROTECT(t, addendum); THREAD_RUNTIME_ARRAY(t, uint8_t, staticTypes, count); @@ -1316,92 +1338,88 @@ parseFieldTable(Thread* t, Stream& s, object class_, object pool) addendum = 0; - unsigned code = fieldCode - (t, byteArrayBody(t, singletonObject(t, pool, spec - 1), 0)); + unsigned code = fieldCode( + t, + cast(t, singletonObject(t, pool, spec - 1))->body()[0]); unsigned attributeCount = s.read2(); for (unsigned j = 0; j < attributeCount; ++j) { - object name = singletonObject(t, pool, s.read2() - 1); + GcByteArray* name + = cast(t, singletonObject(t, pool, s.read2() - 1)); unsigned length = s.read4(); if (vm::strcmp(reinterpret_cast("ConstantValue"), - &byteArrayBody(t, name, 0)) == 0) - { + name->body().begin()) == 0) { value = s.read2(); } else if (vm::strcmp(reinterpret_cast("Signature"), - &byteArrayBody(t, name, 0)) == 0) - { - if (addendum == 0) { - addendum = makeFieldAddendum(t, pool, 0, 0); - } - - set(t, addendum, AddendumSignature, - singletonObject(t, pool, s.read2() - 1)); - } else if (vm::strcmp(reinterpret_cast - ("RuntimeVisibleAnnotations"), - &byteArrayBody(t, name, 0)) == 0) - { + name->body().begin()) == 0) { if (addendum == 0) { addendum = makeFieldAddendum(t, pool, 0, 0); } - object body = makeByteArray(t, length); - s.read(reinterpret_cast(&byteArrayBody(t, body, 0)), - length); + addendum->setSignature(t, singletonObject(t, pool, s.read2() - 1)); + } else if (vm::strcmp(reinterpret_cast( + "RuntimeVisibleAnnotations"), + name->body().begin()) == 0) { + if (addendum == 0) { + addendum = makeFieldAddendum(t, pool, 0, 0); + } - set(t, addendum, AddendumAnnotationTable, body); + GcByteArray* body = makeByteArray(t, length); + s.read(reinterpret_cast(body->body().begin()), length); + + addendum->setAnnotationTable(t, body); } else { s.skip(length); } } - object field = makeField - (t, - 0, // vm flags - code, - flags, - 0, // offset - 0, // native ID - singletonObject(t, pool, name - 1), - singletonObject(t, pool, spec - 1), - addendum, - class_); + GcField* field + = makeField(t, + 0, // vm flags + code, + flags, + 0, // offset + 0, // native ID + cast(t, singletonObject(t, pool, name - 1)), + cast(t, singletonObject(t, pool, spec - 1)), + addendum, + class_); unsigned size = fieldSize(t, code); if (flags & ACC_STATIC) { staticOffset = pad(staticOffset, size); - fieldOffset(t, field) = staticOffset; + field->offset() = staticOffset; staticOffset += size; - intArrayBody(t, staticValueTable, staticCount) = value; + staticValueTable->body()[staticCount] = value; RUNTIME_ARRAY_BODY(staticTypes)[staticCount++] = code; } else { if (flags & ACC_FINAL) { - classVmFlags(t, class_) |= HasFinalMemberFlag; + class_->vmFlags() |= HasFinalMemberFlag; } memberOffset = pad(memberOffset, size); - fieldOffset(t, field) = memberOffset; + field->offset() = memberOffset; memberOffset += size; } - set(t, fieldTable, ArrayBody + (i * BytesPerWord), field); + fieldTable->setBodyElement(t, i, field); } - set(t, class_, ClassFieldTable, fieldTable); + class_->setFieldTable(t, fieldTable); if (staticCount) { - unsigned footprint = ceilingDivide(staticOffset - (BytesPerWord * 2), - BytesPerWord); - object staticTable = makeSingletonOfSize(t, footprint); + unsigned footprint + = ceilingDivide(staticOffset - (BytesPerWord * 2), BytesPerWord); + GcSingleton* staticTable = makeSingletonOfSize(t, footprint); - uint8_t* body = reinterpret_cast - (&singletonBody(t, staticTable, 0)); + uint8_t* body = reinterpret_cast(staticTable->body().begin()); memcpy(body, &class_, BytesPerWord); singletonMarkObject(t, staticTable, 0); @@ -1410,7 +1428,7 @@ parseFieldTable(Thread* t, Stream& s, object class_, object pool) unsigned size = fieldSize(t, RUNTIME_ARRAY_BODY(staticTypes)[i]); offset = pad(offset, size); - unsigned value = intArrayBody(t, staticValueTable, i); + unsigned value = staticValueTable->body()[i]; if (value) { switch (RUNTIME_ARRAY_BODY(staticTypes)[i]) { case ByteField: @@ -1421,13 +1439,13 @@ parseFieldTable(Thread* t, Stream& s, object class_, object pool) case CharField: case ShortField: *reinterpret_cast(body + offset) - = singletonValue(t, pool, value - 1); + = singletonValue(t, pool, value - 1); break; case IntField: case FloatField: *reinterpret_cast(body + offset) - = singletonValue(t, pool, value - 1); + = singletonValue(t, pool, value - 1); break; case LongField: @@ -1441,7 +1459,8 @@ parseFieldTable(Thread* t, Stream& s, object class_, object pool) BytesPerWord); break; - default: abort(t); + default: + abort(t); } } @@ -1452,62 +1471,59 @@ parseFieldTable(Thread* t, Stream& s, object class_, object pool) offset += size; } - set(t, class_, ClassStaticTable, staticTable); + class_->setStaticTable(t, staticTable); } } - classFixedSize(t, class_) = pad(memberOffset); - - if (classSuper(t, class_) - and memberOffset == classFixedSize(t, classSuper(t, class_))) - { - set(t, class_, ClassObjectMask, - classObjectMask(t, classSuper(t, class_))); - } else { - object mask = makeIntArray - (t, ceilingDivide(classFixedSize(t, class_), 32 * BytesPerWord)); - intArrayBody(t, mask, 0) = 1; + class_->fixedSize() = memberOffset; - object superMask = 0; - if (classSuper(t, class_)) { - superMask = classObjectMask(t, classSuper(t, class_)); + if (class_->super() and memberOffset == class_->super()->fixedSize()) { + class_->setObjectMask(t, class_->super()->objectMask()); + } else { + GcIntArray* mask = makeIntArray( + t, ceilingDivide(class_->fixedSize(), 32 * BytesPerWord)); + mask->body()[0] = 1; + + GcIntArray* superMask = 0; + if (class_->super()) { + superMask = class_->super()->objectMask(); if (superMask) { - memcpy(&intArrayBody(t, mask, 0), - &intArrayBody(t, superMask, 0), - ceilingDivide(classFixedSize(t, classSuper(t, class_)), - 32 * BytesPerWord) - * 4); + memcpy( + mask->body().begin(), + superMask->body().begin(), + ceilingDivide(class_->super()->fixedSize(), 32 * BytesPerWord) * 4); } } bool sawReferenceField = false; - object fieldTable = classFieldTable(t, class_); + GcArray* fieldTable = cast(t, class_->fieldTable()); if (fieldTable) { - for (int i = arrayLength(t, fieldTable) - 1; i >= 0; --i) { - object field = arrayBody(t, fieldTable, i); - if ((fieldFlags(t, field) & ACC_STATIC) == 0 - and fieldCode(t, field) == ObjectField) - { - unsigned index = fieldOffset(t, field) / BytesPerWord; - intArrayBody(t, mask, (index / 32)) |= 1 << (index % 32); + for (int i = fieldTable->length() - 1; i >= 0; --i) { + GcField* field = cast(t, fieldTable->body()[i]); + if ((field->flags() & ACC_STATIC) == 0 + and field->code() == ObjectField) { + unsigned index = field->offset() / BytesPerWord; + mask->body()[index / 32] |= 1 << (index % 32); sawReferenceField = true; } } } if (superMask or sawReferenceField) { - set(t, class_, ClassObjectMask, mask); + class_->setObjectMask(t, mask); } } } -uint16_t read16(uint8_t* code, unsigned& ip) { +uint16_t read16(uint8_t* code, unsigned& ip) +{ uint16_t a = code[ip++]; uint16_t b = code[ip++]; return (a << 8) | b; } -uint32_t read32(uint8_t* code, unsigned& ip) { +uint32_t read32(uint8_t* code, unsigned& ip) +{ uint32_t b = code[ip++]; uint32_t a = code[ip++]; uint32_t c = code[ip++]; @@ -1515,372 +1531,754 @@ uint32_t read32(uint8_t* code, unsigned& ip) { return (a << 24) | (b << 16) | (c << 8) | d; } -void -disassembleCode(const char* prefix, uint8_t* code, unsigned length) +void disassembleCode(const char* prefix, uint8_t* code, unsigned length) { unsigned ip = 0; - while(ip < length) { + while (ip < length) { unsigned instr; fprintf(stderr, "%s%x:\t", prefix, ip); switch (instr = code[ip++]) { - case aaload: fprintf(stderr, "aaload\n"); break; - case aastore: fprintf(stderr, "aastore\n"); break; + case aaload: + fprintf(stderr, "aaload\n"); + break; + case aastore: + fprintf(stderr, "aastore\n"); + break; - case aconst_null: fprintf(stderr, "aconst_null\n"); break; + case aconst_null: + fprintf(stderr, "aconst_null\n"); + break; - case aload: fprintf(stderr, "aload %02x\n", code[ip++]); break; - case aload_0: fprintf(stderr, "aload_0\n"); break; - case aload_1: fprintf(stderr, "aload_1\n"); break; - case aload_2: fprintf(stderr, "aload_2\n"); break; - case aload_3: fprintf(stderr, "aload_3\n"); break; + case aload: + fprintf(stderr, "aload %02x\n", code[ip++]); + break; + case aload_0: + fprintf(stderr, "aload_0\n"); + break; + case aload_1: + fprintf(stderr, "aload_1\n"); + break; + case aload_2: + fprintf(stderr, "aload_2\n"); + break; + case aload_3: + fprintf(stderr, "aload_3\n"); + break; - case anewarray: fprintf(stderr, "anewarray %04x\n", read16(code, ip)); break; - case areturn: fprintf(stderr, "areturn\n"); break; - case arraylength: fprintf(stderr, "arraylength\n"); break; + case anewarray: + fprintf(stderr, "anewarray %04x\n", read16(code, ip)); + break; + case areturn: + fprintf(stderr, "areturn\n"); + break; + case arraylength: + fprintf(stderr, "arraylength\n"); + break; - case astore: fprintf(stderr, "astore %02x\n", code[ip++]); break; - case astore_0: fprintf(stderr, "astore_0\n"); break; - case astore_1: fprintf(stderr, "astore_1\n"); break; - case astore_2: fprintf(stderr, "astore_2\n"); break; - case astore_3: fprintf(stderr, "astore_3\n"); break; + case astore: + fprintf(stderr, "astore %02x\n", code[ip++]); + break; + case astore_0: + fprintf(stderr, "astore_0\n"); + break; + case astore_1: + fprintf(stderr, "astore_1\n"); + break; + case astore_2: + fprintf(stderr, "astore_2\n"); + break; + case astore_3: + fprintf(stderr, "astore_3\n"); + break; + case athrow: + fprintf(stderr, "athrow\n"); + break; + case baload: + fprintf(stderr, "baload\n"); + break; + case bastore: + fprintf(stderr, "bastore\n"); + break; - case athrow: fprintf(stderr, "athrow\n"); break; - case baload: fprintf(stderr, "baload\n"); break; - case bastore: fprintf(stderr, "bastore\n"); break; + case bipush: + fprintf(stderr, "bipush %02x\n", code[ip++]); + break; + case caload: + fprintf(stderr, "caload\n"); + break; + case castore: + fprintf(stderr, "castore\n"); + break; + case checkcast: + fprintf(stderr, "checkcast %04x\n", read16(code, ip)); + break; + case d2f: + fprintf(stderr, "d2f\n"); + break; + case d2i: + fprintf(stderr, "d2i\n"); + break; + case d2l: + fprintf(stderr, "d2l\n"); + break; + case dadd: + fprintf(stderr, "dadd\n"); + break; + case daload: + fprintf(stderr, "daload\n"); + break; + case dastore: + fprintf(stderr, "dastore\n"); + break; + case dcmpg: + fprintf(stderr, "dcmpg\n"); + break; + case dcmpl: + fprintf(stderr, "dcmpl\n"); + break; + case dconst_0: + fprintf(stderr, "dconst_0\n"); + break; + case dconst_1: + fprintf(stderr, "dconst_1\n"); + break; + case ddiv: + fprintf(stderr, "ddiv\n"); + break; + case dmul: + fprintf(stderr, "dmul\n"); + break; + case dneg: + fprintf(stderr, "dneg\n"); + break; + case vm::drem: + fprintf(stderr, "drem\n"); + break; + case dsub: + fprintf(stderr, "dsub\n"); + break; + case vm::dup: + fprintf(stderr, "dup\n"); + break; + case dup_x1: + fprintf(stderr, "dup_x1\n"); + break; + case dup_x2: + fprintf(stderr, "dup_x2\n"); + break; + case vm::dup2: + fprintf(stderr, "dup2\n"); + break; + case dup2_x1: + fprintf(stderr, "dup2_x1\n"); + break; + case dup2_x2: + fprintf(stderr, "dup2_x2\n"); + break; + case f2d: + fprintf(stderr, "f2d\n"); + break; + case f2i: + fprintf(stderr, "f2i\n"); + break; + case f2l: + fprintf(stderr, "f2l\n"); + break; + case fadd: + fprintf(stderr, "fadd\n"); + break; + case faload: + fprintf(stderr, "faload\n"); + break; + case fastore: + fprintf(stderr, "fastore\n"); + break; + case fcmpg: + fprintf(stderr, "fcmpg\n"); + break; + case fcmpl: + fprintf(stderr, "fcmpl\n"); + break; + case fconst_0: + fprintf(stderr, "fconst_0\n"); + break; + case fconst_1: + fprintf(stderr, "fconst_1\n"); + break; + case fconst_2: + fprintf(stderr, "fconst_2\n"); + break; + case fdiv: + fprintf(stderr, "fdiv\n"); + break; + case fmul: + fprintf(stderr, "fmul\n"); + break; + case fneg: + fprintf(stderr, "fneg\n"); + break; + case frem: + fprintf(stderr, "frem\n"); + break; + case fsub: + fprintf(stderr, "fsub\n"); + break; - case bipush: fprintf(stderr, "bipush %02x\n", code[ip++]); break; - case caload: fprintf(stderr, "caload\n"); break; - case castore: fprintf(stderr, "castore\n"); break; - case checkcast: fprintf(stderr, "checkcast %04x\n", read16(code, ip)); break; - case d2f: fprintf(stderr, "d2f\n"); break; - case d2i: fprintf(stderr, "d2i\n"); break; - case d2l: fprintf(stderr, "d2l\n"); break; - case dadd: fprintf(stderr, "dadd\n"); break; - case daload: fprintf(stderr, "daload\n"); break; - case dastore: fprintf(stderr, "dastore\n"); break; - case dcmpg: fprintf(stderr, "dcmpg\n"); break; - case dcmpl: fprintf(stderr, "dcmpl\n"); break; - case dconst_0: fprintf(stderr, "dconst_0\n"); break; - case dconst_1: fprintf(stderr, "dconst_1\n"); break; - case ddiv: fprintf(stderr, "ddiv\n"); break; - case dmul: fprintf(stderr, "dmul\n"); break; - case dneg: fprintf(stderr, "dneg\n"); break; - case vm::drem: fprintf(stderr, "drem\n"); break; - case dsub: fprintf(stderr, "dsub\n"); break; - case dup: fprintf(stderr, "dup\n"); break; - case dup_x1: fprintf(stderr, "dup_x1\n"); break; - case dup_x2: fprintf(stderr, "dup_x2\n"); break; - case dup2: fprintf(stderr, "dup2\n"); break; - case dup2_x1: fprintf(stderr, "dup2_x1\n"); break; - case dup2_x2: fprintf(stderr, "dup2_x2\n"); break; - case f2d: fprintf(stderr, "f2d\n"); break; - case f2i: fprintf(stderr, "f2i\n"); break; - case f2l: fprintf(stderr, "f2l\n"); break; - case fadd: fprintf(stderr, "fadd\n"); break; - case faload: fprintf(stderr, "faload\n"); break; - case fastore: fprintf(stderr, "fastore\n"); break; - case fcmpg: fprintf(stderr, "fcmpg\n"); break; - case fcmpl: fprintf(stderr, "fcmpl\n"); break; - case fconst_0: fprintf(stderr, "fconst_0\n"); break; - case fconst_1: fprintf(stderr, "fconst_1\n"); break; - case fconst_2: fprintf(stderr, "fconst_2\n"); break; - case fdiv: fprintf(stderr, "fdiv\n"); break; - case fmul: fprintf(stderr, "fmul\n"); break; - case fneg: fprintf(stderr, "fneg\n"); break; - case frem: fprintf(stderr, "frem\n"); break; - case fsub: fprintf(stderr, "fsub\n"); break; + case getfield: + fprintf(stderr, "getfield %04x\n", read16(code, ip)); + break; + case getstatic: + fprintf(stderr, "getstatic %04x\n", read16(code, ip)); + break; + case goto_: { + int16_t offset = read16(code, ip); + fprintf(stderr, "goto %04x\n", offset + ip - 3); + } break; + case goto_w: { + int32_t offset = read32(code, ip); + fprintf(stderr, "goto_w %08x\n", offset + ip - 5); + } break; - case getfield: fprintf(stderr, "getfield %04x\n", read16(code, ip)); break; - case getstatic: fprintf(stderr, "getstatic %04x\n", read16(code, ip)); break; - case goto_: { - int16_t offset = read16(code, ip); - fprintf(stderr, "goto %04x\n", offset + ip - 3); - } break; - case goto_w: { - int32_t offset = read32(code, ip); - fprintf(stderr, "goto_w %08x\n", offset + ip - 5); - } break; + case i2b: + fprintf(stderr, "i2b\n"); + break; + case i2c: + fprintf(stderr, "i2c\n"); + break; + case i2d: + fprintf(stderr, "i2d\n"); + break; + case i2f: + fprintf(stderr, "i2f\n"); + break; + case i2l: + fprintf(stderr, "i2l\n"); + break; + case i2s: + fprintf(stderr, "i2s\n"); + break; + case iadd: + fprintf(stderr, "iadd\n"); + break; + case iaload: + fprintf(stderr, "iaload\n"); + break; + case iand: + fprintf(stderr, "iand\n"); + break; + case iastore: + fprintf(stderr, "iastore\n"); + break; + case iconst_m1: + fprintf(stderr, "iconst_m1\n"); + break; + case iconst_0: + fprintf(stderr, "iconst_0\n"); + break; + case iconst_1: + fprintf(stderr, "iconst_1\n"); + break; + case iconst_2: + fprintf(stderr, "iconst_2\n"); + break; + case iconst_3: + fprintf(stderr, "iconst_3\n"); + break; + case iconst_4: + fprintf(stderr, "iconst_4\n"); + break; + case iconst_5: + fprintf(stderr, "iconst_5\n"); + break; + case idiv: + fprintf(stderr, "idiv\n"); + break; - case i2b: fprintf(stderr, "i2b\n"); break; - case i2c: fprintf(stderr, "i2c\n"); break; - case i2d: fprintf(stderr, "i2d\n"); break; - case i2f: fprintf(stderr, "i2f\n"); break; - case i2l: fprintf(stderr, "i2l\n"); break; - case i2s: fprintf(stderr, "i2s\n"); break; - case iadd: fprintf(stderr, "iadd\n"); break; - case iaload: fprintf(stderr, "iaload\n"); break; - case iand: fprintf(stderr, "iand\n"); break; - case iastore: fprintf(stderr, "iastore\n"); break; - case iconst_m1: fprintf(stderr, "iconst_m1\n"); break; - case iconst_0: fprintf(stderr, "iconst_0\n"); break; - case iconst_1: fprintf(stderr, "iconst_1\n"); break; - case iconst_2: fprintf(stderr, "iconst_2\n"); break; - case iconst_3: fprintf(stderr, "iconst_3\n"); break; - case iconst_4: fprintf(stderr, "iconst_4\n"); break; - case iconst_5: fprintf(stderr, "iconst_5\n"); break; - case idiv: fprintf(stderr, "idiv\n"); break; + case if_acmpeq: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_acmpeq %04x\n", offset + ip - 3); + } break; + case if_acmpne: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_acmpne %04x\n", offset + ip - 3); + } break; + case if_icmpeq: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmpeq %04x\n", offset + ip - 3); + } break; + case if_icmpne: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmpne %04x\n", offset + ip - 3); + } break; - case if_acmpeq: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_acmpeq %04x\n", offset + ip - 3); - } break; - case if_acmpne: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_acmpne %04x\n", offset + ip - 3); - } break; - case if_icmpeq: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmpeq %04x\n", offset + ip - 3); - } break; - case if_icmpne: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmpne %04x\n", offset + ip - 3); - } break; + case if_icmpgt: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmpgt %04x\n", offset + ip - 3); + } break; + case if_icmpge: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmpge %04x\n", offset + ip - 3); + } break; + case if_icmplt: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmplt %04x\n", offset + ip - 3); + } break; + case if_icmple: { + int16_t offset = read16(code, ip); + fprintf(stderr, "if_icmple %04x\n", offset + ip - 3); + } break; - case if_icmpgt: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmpgt %04x\n", offset + ip - 3); - } break; - case if_icmpge: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmpge %04x\n", offset + ip - 3); - } break; - case if_icmplt: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmplt %04x\n", offset + ip - 3); - } break; - case if_icmple: { - int16_t offset = read16(code, ip); - fprintf(stderr, "if_icmple %04x\n", offset + ip - 3); - } break; + case ifeq: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifeq %04x\n", offset + ip - 3); + } break; + case ifne: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifne %04x\n", offset + ip - 3); + } break; + case ifgt: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifgt %04x\n", offset + ip - 3); + } break; + case ifge: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifge %04x\n", offset + ip - 3); + } break; + case iflt: { + int16_t offset = read16(code, ip); + fprintf(stderr, "iflt %04x\n", offset + ip - 3); + } break; + case ifle: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifle %04x\n", offset + ip - 3); + } break; - case ifeq: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifeq %04x\n", offset + ip - 3); - } break; - case ifne: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifne %04x\n", offset + ip - 3); - } break; - case ifgt: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifgt %04x\n", offset + ip - 3); - } break; - case ifge: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifge %04x\n", offset + ip - 3); - } break; - case iflt: { - int16_t offset = read16(code, ip); - fprintf(stderr, "iflt %04x\n", offset + ip - 3); - } break; - case ifle: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifle %04x\n", offset + ip - 3); - } break; + case ifnonnull: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifnonnull %04x\n", offset + ip - 3); + } break; + case ifnull: { + int16_t offset = read16(code, ip); + fprintf(stderr, "ifnull %04x\n", offset + ip - 3); + } break; - case ifnonnull: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifnonnull %04x\n", offset + ip - 3); - } break; - case ifnull: { - int16_t offset = read16(code, ip); - fprintf(stderr, "ifnull %04x\n", offset + ip - 3); - } break; + case iinc: { + uint8_t a = code[ip++]; + uint8_t b = code[ip++]; + fprintf(stderr, "iinc %02x %02x\n", a, b); + } break; - case iinc: { - uint8_t a = code[ip++]; - uint8_t b = code[ip++]; - fprintf(stderr, "iinc %02x %02x\n", a, b); - } break; + case iload: + fprintf(stderr, "iload %02x\n", code[ip++]); + break; + case fload: + fprintf(stderr, "fload %02x\n", code[ip++]); + break; - case iload: fprintf(stderr, "iload %02x\n", code[ip++]); break; - case fload: fprintf(stderr, "fload %02x\n", code[ip++]); break; + case iload_0: + fprintf(stderr, "iload_0\n"); + break; + case fload_0: + fprintf(stderr, "fload_0\n"); + break; + case iload_1: + fprintf(stderr, "iload_1\n"); + break; + case fload_1: + fprintf(stderr, "fload_1\n"); + break; - case iload_0: fprintf(stderr, "iload_0\n"); break; - case fload_0: fprintf(stderr, "fload_0\n"); break; - case iload_1: fprintf(stderr, "iload_1\n"); break; - case fload_1: fprintf(stderr, "fload_1\n"); break; + case iload_2: + fprintf(stderr, "iload_2\n"); + break; + case fload_2: + fprintf(stderr, "fload_2\n"); + break; + case iload_3: + fprintf(stderr, "iload_3\n"); + break; + case fload_3: + fprintf(stderr, "fload_3\n"); + break; - case iload_2: fprintf(stderr, "iload_2\n"); break; - case fload_2: fprintf(stderr, "fload_2\n"); break; - case iload_3: fprintf(stderr, "iload_3\n"); break; - case fload_3: fprintf(stderr, "fload_3\n"); break; + case imul: + fprintf(stderr, "imul\n"); + break; + case ineg: + fprintf(stderr, "ineg\n"); + break; - case imul: fprintf(stderr, "imul\n"); break; - case ineg: fprintf(stderr, "ineg\n"); break; + case instanceof: + fprintf(stderr, "instanceof %04x\n", read16(code, ip)); + break; + case invokeinterface: + fprintf(stderr, "invokeinterface %04x\n", read16(code, ip)); + break; + case invokespecial: + fprintf(stderr, "invokespecial %04x\n", read16(code, ip)); + break; + case invokestatic: + fprintf(stderr, "invokestatic %04x\n", read16(code, ip)); + break; + case invokevirtual: + fprintf(stderr, "invokevirtual %04x\n", read16(code, ip)); + break; - case instanceof: fprintf(stderr, "instanceof %04x\n", read16(code, ip)); break; - case invokeinterface: fprintf(stderr, "invokeinterface %04x\n", read16(code, ip)); break; - case invokespecial: fprintf(stderr, "invokespecial %04x\n", read16(code, ip)); break; - case invokestatic: fprintf(stderr, "invokestatic %04x\n", read16(code, ip)); break; - case invokevirtual: fprintf(stderr, "invokevirtual %04x\n", read16(code, ip)); break; + case ior: + fprintf(stderr, "ior\n"); + break; + case irem: + fprintf(stderr, "irem\n"); + break; + case ireturn: + fprintf(stderr, "ireturn\n"); + break; + case freturn: + fprintf(stderr, "freturn\n"); + break; + case ishl: + fprintf(stderr, "ishl\n"); + break; + case ishr: + fprintf(stderr, "ishr\n"); + break; - case ior: fprintf(stderr, "ior\n"); break; - case irem: fprintf(stderr, "irem\n"); break; - case ireturn: fprintf(stderr, "ireturn\n"); break; - case freturn: fprintf(stderr, "freturn\n"); break; - case ishl: fprintf(stderr, "ishl\n"); break; - case ishr: fprintf(stderr, "ishr\n"); break; + case istore: + fprintf(stderr, "istore %02x\n", code[ip++]); + break; + case fstore: + fprintf(stderr, "fstore %02x\n", code[ip++]); + break; - case istore: fprintf(stderr, "istore %02x\n", code[ip++]); break; - case fstore: fprintf(stderr, "fstore %02x\n", code[ip++]); break; + case istore_0: + fprintf(stderr, "istore_0\n"); + break; + case fstore_0: + fprintf(stderr, "fstore_0\n"); + break; + case istore_1: + fprintf(stderr, "istore_1\n"); + break; + case fstore_1: + fprintf(stderr, "fstore_1\n"); + break; + case istore_2: + fprintf(stderr, "istore_2\n"); + break; + case fstore_2: + fprintf(stderr, "fstore_2\n"); + break; + case istore_3: + fprintf(stderr, "istore_3\n"); + break; + case fstore_3: + fprintf(stderr, "fstore_3\n"); + break; - case istore_0: fprintf(stderr, "istore_0\n"); break; - case fstore_0: fprintf(stderr, "fstore_0\n"); break; - case istore_1: fprintf(stderr, "istore_1\n"); break; - case fstore_1: fprintf(stderr, "fstore_1\n"); break; - case istore_2: fprintf(stderr, "istore_2\n"); break; - case fstore_2: fprintf(stderr, "fstore_2\n"); break; - case istore_3: fprintf(stderr, "istore_3\n"); break; - case fstore_3: fprintf(stderr, "fstore_3\n"); break; + case isub: + fprintf(stderr, "isub\n"); + break; + case iushr: + fprintf(stderr, "iushr\n"); + break; + case ixor: + fprintf(stderr, "ixor\n"); + break; - case isub: fprintf(stderr, "isub\n"); break; - case iushr: fprintf(stderr, "iushr\n"); break; - case ixor: fprintf(stderr, "ixor\n"); break; + case jsr: + fprintf(stderr, "jsr %04x\n", read16(code, ip)); + break; + case jsr_w: + fprintf(stderr, "jsr_w %08x\n", read32(code, ip)); + break; - case jsr: fprintf(stderr, "jsr %04x\n", read16(code, ip)); break; - case jsr_w: fprintf(stderr, "jsr_w %08x\n", read32(code, ip)); break; + case l2d: + fprintf(stderr, "l2d\n"); + break; + case l2f: + fprintf(stderr, "l2f\n"); + break; + case l2i: + fprintf(stderr, "l2i\n"); + break; + case ladd: + fprintf(stderr, "ladd\n"); + break; + case laload: + fprintf(stderr, "laload\n"); + break; - case l2d: fprintf(stderr, "l2d\n"); break; - case l2f: fprintf(stderr, "l2f\n"); break; - case l2i: fprintf(stderr, "l2i\n"); break; - case ladd: fprintf(stderr, "ladd\n"); break; - case laload: fprintf(stderr, "laload\n"); break; + case land: + fprintf(stderr, "land\n"); + break; + case lastore: + fprintf(stderr, "lastore\n"); + break; - case land: fprintf(stderr, "land\n"); break; - case lastore: fprintf(stderr, "lastore\n"); break; + case lcmp: + fprintf(stderr, "lcmp\n"); + break; + case lconst_0: + fprintf(stderr, "lconst_0\n"); + break; + case lconst_1: + fprintf(stderr, "lconst_1\n"); + break; - case lcmp: fprintf(stderr, "lcmp\n"); break; - case lconst_0: fprintf(stderr, "lconst_0\n"); break; - case lconst_1: fprintf(stderr, "lconst_1\n"); break; + case ldc: + fprintf(stderr, "ldc %04x\n", read16(code, ip)); + break; + case ldc_w: + fprintf(stderr, "ldc_w %08x\n", read32(code, ip)); + break; + case ldc2_w: + fprintf(stderr, "ldc2_w %04x\n", read16(code, ip)); + break; - case ldc: fprintf(stderr, "ldc %04x\n", read16(code, ip)); break; - case ldc_w: fprintf(stderr, "ldc_w %08x\n", read32(code, ip)); break; - case ldc2_w: fprintf(stderr, "ldc2_w %04x\n", read16(code, ip)); break; + case ldiv_: + fprintf(stderr, "ldiv_\n"); + break; - case ldiv_: fprintf(stderr, "ldiv_\n"); break; + case lload: + fprintf(stderr, "lload %02x\n", code[ip++]); + break; + case dload: + fprintf(stderr, "dload %02x\n", code[ip++]); + break; - case lload: fprintf(stderr, "lload %02x\n", code[ip++]); break; - case dload: fprintf(stderr, "dload %02x\n", code[ip++]); break; + case lload_0: + fprintf(stderr, "lload_0\n"); + break; + case dload_0: + fprintf(stderr, "dload_0\n"); + break; + case lload_1: + fprintf(stderr, "lload_1\n"); + break; + case dload_1: + fprintf(stderr, "dload_1\n"); + break; + case lload_2: + fprintf(stderr, "lload_2\n"); + break; + case dload_2: + fprintf(stderr, "dload_2\n"); + break; + case lload_3: + fprintf(stderr, "lload_3\n"); + break; + case dload_3: + fprintf(stderr, "dload_3\n"); + break; - case lload_0: fprintf(stderr, "lload_0\n"); break; - case dload_0: fprintf(stderr, "dload_0\n"); break; - case lload_1: fprintf(stderr, "lload_1\n"); break; - case dload_1: fprintf(stderr, "dload_1\n"); break; - case lload_2: fprintf(stderr, "lload_2\n"); break; - case dload_2: fprintf(stderr, "dload_2\n"); break; - case lload_3: fprintf(stderr, "lload_3\n"); break; - case dload_3: fprintf(stderr, "dload_3\n"); break; + case lmul: + fprintf(stderr, "lmul\n"); + break; + case lneg: + fprintf(stderr, "lneg\n"); + break; - case lmul: fprintf(stderr, "lmul\n"); break; - case lneg: fprintf(stderr, "lneg\n"); break; + case lookupswitch: { + int32_t default_ = read32(code, ip); + int32_t pairCount = read32(code, ip); + fprintf(stderr, + "lookupswitch default: %d pairCount: %d\n", + default_, + pairCount); - case lookupswitch: { - int32_t default_ = read32(code, ip); - int32_t pairCount = read32(code, ip); - fprintf(stderr, "lookupswitch default: %d pairCount: %d\n", default_, pairCount); + for (int i = 0; i < pairCount; i++) { + int32_t k = read32(code, ip); + int32_t d = read32(code, ip); + fprintf(stderr, "%s key: %02x dest: %2x\n", prefix, k, d); + } + } break; - for (int i = 0; i < pairCount; i++) { - int32_t k = read32(code, ip); - int32_t d = read32(code, ip); - fprintf(stderr, "%s key: %02x dest: %2x\n", prefix, k, d); - } - } break; + case lor: + fprintf(stderr, "lor\n"); + break; + case lrem: + fprintf(stderr, "lrem\n"); + break; + case lreturn: + fprintf(stderr, "lreturn\n"); + break; + case dreturn: + fprintf(stderr, "dreturn\n"); + break; + case lshl: + fprintf(stderr, "lshl\n"); + break; + case lshr: + fprintf(stderr, "lshr\n"); + break; - case lor: fprintf(stderr, "lor\n"); break; - case lrem: fprintf(stderr, "lrem\n"); break; - case lreturn: fprintf(stderr, "lreturn\n"); break; - case dreturn: fprintf(stderr, "dreturn\n"); break; - case lshl: fprintf(stderr, "lshl\n"); break; - case lshr: fprintf(stderr, "lshr\n"); break; + case lstore: + fprintf(stderr, "lstore %02x\n", code[ip++]); + break; + case dstore: + fprintf(stderr, "dstore %02x\n", code[ip++]); + break; - case lstore: fprintf(stderr, "lstore %02x\n", code[ip++]); break; - case dstore: fprintf(stderr, "dstore %02x\n", code[ip++]); break; + case lstore_0: + fprintf(stderr, "lstore_0\n"); + break; + case dstore_0: + fprintf(stderr, "dstore_0\n"); + break; + case lstore_1: + fprintf(stderr, "lstore_1\n"); + break; + case dstore_1: + fprintf(stderr, "dstore_1\n"); + break; + case lstore_2: + fprintf(stderr, "lstore_2\n"); + break; + case dstore_2: + fprintf(stderr, "dstore_2\n"); + break; + case lstore_3: + fprintf(stderr, "lstore_3\n"); + break; + case dstore_3: + fprintf(stderr, "dstore_3\n"); + break; - case lstore_0: fprintf(stderr, "lstore_0\n"); break; - case dstore_0: fprintf(stderr, "dstore_0\n"); break; - case lstore_1: fprintf(stderr, "lstore_1\n"); break; - case dstore_1: fprintf(stderr, "dstore_1\n"); break; - case lstore_2: fprintf(stderr, "lstore_2\n"); break; - case dstore_2: fprintf(stderr, "dstore_2\n"); break; - case lstore_3: fprintf(stderr, "lstore_3\n"); break; - case dstore_3: fprintf(stderr, "dstore_3\n"); break; + case lsub: + fprintf(stderr, "lsub\n"); + break; + case lushr: + fprintf(stderr, "lushr\n"); + break; + case lxor: + fprintf(stderr, "lxor\n"); + break; - case lsub: fprintf(stderr, "lsub\n"); break; - case lushr: fprintf(stderr, "lushr\n"); break; - case lxor: fprintf(stderr, "lxor\n"); break; + case monitorenter: + fprintf(stderr, "monitorenter\n"); + break; + case monitorexit: + fprintf(stderr, "monitorexit\n"); + break; - case monitorenter: fprintf(stderr, "monitorenter\n"); break; - case monitorexit: fprintf(stderr, "monitorexit\n"); break; + case multianewarray: { + unsigned type = read16(code, ip); + fprintf(stderr, "multianewarray %04x %02x\n", type, code[ip++]); + } break; - case multianewarray: { - unsigned type = read16(code, ip); - fprintf(stderr, "multianewarray %04x %02x\n", type, code[ip++]); - } break; + case new_: + fprintf(stderr, "new %04x\n", read16(code, ip)); + break; - case new_: fprintf(stderr, "new %04x\n", read16(code, ip)); break; + case newarray: + fprintf(stderr, "newarray %02x\n", code[ip++]); + break; - case newarray: fprintf(stderr, "newarray %02x\n", code[ip++]); break; + case nop: + fprintf(stderr, "nop\n"); + break; + case pop_: + fprintf(stderr, "pop\n"); + break; + case pop2: + fprintf(stderr, "pop2\n"); + break; - case nop: fprintf(stderr, "nop\n"); break; - case pop_: fprintf(stderr, "pop\n"); break; - case pop2: fprintf(stderr, "pop2\n"); break; + case putfield: + fprintf(stderr, "putfield %04x\n", read16(code, ip)); + break; + case putstatic: + fprintf(stderr, "putstatic %04x\n", read16(code, ip)); + break; - case putfield: fprintf(stderr, "putfield %04x\n", read16(code, ip)); break; - case putstatic: fprintf(stderr, "putstatic %04x\n", read16(code, ip)); break; + case ret: + fprintf(stderr, "ret %02x\n", code[ip++]); + break; - case ret: fprintf(stderr, "ret %02x\n", code[ip++]); break; + case return_: + fprintf(stderr, "return_\n"); + break; + case saload: + fprintf(stderr, "saload\n"); + break; + case sastore: + fprintf(stderr, "sastore\n"); + break; - case return_: fprintf(stderr, "return_\n"); break; - case saload: fprintf(stderr, "saload\n"); break; - case sastore: fprintf(stderr, "sastore\n"); break; + case sipush: + fprintf(stderr, "sipush %04x\n", read16(code, ip)); + break; - case sipush: fprintf(stderr, "sipush %04x\n", read16(code, ip)); break; + case swap: + fprintf(stderr, "swap\n"); + break; - case swap: fprintf(stderr, "swap\n"); break; + case tableswitch: { + int32_t default_ = read32(code, ip); + int32_t bottom = read32(code, ip); + int32_t top = read32(code, ip); + fprintf(stderr, + "tableswitch default: %d bottom: %d top: %d\n", + default_, + bottom, + top); - case tableswitch: { - int32_t default_ = read32(code, ip); - int32_t bottom = read32(code, ip); - int32_t top = read32(code, ip); - fprintf(stderr, "tableswitch default: %d bottom: %d top: %d\n", default_, bottom, top); + for (int i = 0; i < top - bottom + 1; i++) { + int32_t d = read32(code, ip); + fprintf(stderr, "%s key: %d dest: %2x\n", prefix, i + bottom, d); + } + } break; - for (int i = 0; i < top - bottom + 1; i++) { - int32_t d = read32(code, ip); - fprintf(stderr, "%s key: %d dest: %2x\n", prefix, i + bottom, d); - } - } break; + case wide: { + switch (code[ip++]) { + case aload: + fprintf(stderr, "wide aload %04x\n", read16(code, ip)); + break; - case wide: { - switch (code[ip++]) { - case aload: fprintf(stderr, "wide aload %04x\n", read16(code, ip)); break; - - case astore: fprintf(stderr, "wide astore %04x\n", read16(code, ip)); break; - case iinc: fprintf(stderr, "wide iinc %04x %04x\n", read16(code, ip), read16(code, ip)); break; - case iload: fprintf(stderr, "wide iload %04x\n", read16(code, ip)); break; - case istore: fprintf(stderr, "wide istore %04x\n", read16(code, ip)); break; - case lload: fprintf(stderr, "wide lload %04x\n", read16(code, ip)); break; - case lstore: fprintf(stderr, "wide lstore %04x\n", read16(code, ip)); break; - case ret: fprintf(stderr, "wide ret %04x\n", read16(code, ip)); break; - - default: { - fprintf(stderr, "unknown wide instruction %02x %04x\n", instr, read16(code, ip)); - } - } - } break; + case astore: + fprintf(stderr, "wide astore %04x\n", read16(code, ip)); + break; + case iinc: + fprintf(stderr, + "wide iinc %04x %04x\n", + read16(code, ip), + read16(code, ip)); + break; + case iload: + fprintf(stderr, "wide iload %04x\n", read16(code, ip)); + break; + case istore: + fprintf(stderr, "wide istore %04x\n", read16(code, ip)); + break; + case lload: + fprintf(stderr, "wide lload %04x\n", read16(code, ip)); + break; + case lstore: + fprintf(stderr, "wide lstore %04x\n", read16(code, ip)); + break; + case ret: + fprintf(stderr, "wide ret %04x\n", read16(code, ip)); + break; default: { - fprintf(stderr, "unknown instruction %02x\n", instr); + fprintf(stderr, + "unknown wide instruction %02x %04x\n", + instr, + read16(code, ip)); } + } + } break; + + default: { + fprintf(stderr, "unknown instruction %02x\n", instr); + } } } } -object -parseCode(Thread* t, Stream& s, object pool) +GcCode* parseCode(Thread* t, Stream& s, GcSingleton* pool) { PROTECT(t, pool); @@ -1888,50 +2286,53 @@ parseCode(Thread* t, Stream& s, object pool) unsigned maxLocals = s.read2(); unsigned length = s.read4(); - if(DebugClassReader) { - fprintf(stderr, " code: maxStack %d maxLocals %d length %d\n", maxStack, maxLocals, length); + if (DebugClassReader) { + fprintf(stderr, + " code: maxStack %d maxLocals %d length %d\n", + maxStack, + maxLocals, + length); } - object code = makeCode(t, pool, 0, 0, 0, 0, maxStack, maxLocals, length); - s.read(&codeBody(t, code, 0), length); + GcCode* code = makeCode(t, pool, 0, 0, 0, 0, 0, maxStack, maxLocals, length); + s.read(code->body().begin(), length); PROTECT(t, code); - if(DebugClassReader) { - disassembleCode(" ", &codeBody(t, code, 0), length); + if (DebugClassReader) { + disassembleCode(" ", code->body().begin(), length); } unsigned ehtLength = s.read2(); if (ehtLength) { - object eht = makeExceptionHandlerTable(t, ehtLength); + GcExceptionHandlerTable* eht = makeExceptionHandlerTable(t, ehtLength); for (unsigned i = 0; i < ehtLength; ++i) { unsigned start = s.read2(); unsigned end = s.read2(); unsigned ip = s.read2(); unsigned catchType = s.read2(); - exceptionHandlerTableBody(t, eht, i) = exceptionHandler - (start, end, ip, catchType); + eht->body()[i] = exceptionHandler(start, end, ip, catchType); } - set(t, code, CodeExceptionHandlerTable, eht); + code->setExceptionHandlerTable(t, eht); } unsigned attributeCount = s.read2(); for (unsigned j = 0; j < attributeCount; ++j) { - object name = singletonObject(t, pool, s.read2() - 1); + GcByteArray* name + = cast(t, singletonObject(t, pool, s.read2() - 1)); unsigned length = s.read4(); if (vm::strcmp(reinterpret_cast("LineNumberTable"), - &byteArrayBody(t, name, 0)) == 0) - { + name->body().begin()) == 0) { unsigned lntLength = s.read2(); - object lnt = makeLineNumberTable(t, lntLength); + GcLineNumberTable* lnt = makeLineNumberTable(t, lntLength); for (unsigned i = 0; i < lntLength; ++i) { unsigned ip = s.read2(); unsigned line = s.read2(); - lineNumberTableBody(t, lnt, i) = lineNumber(ip, line); + lnt->body()[i] = lineNumber(ip, line); } - set(t, code, CodeLineNumberTable, lnt); + code->setLineNumberTable(t, lnt); } else { s.skip(length); } @@ -1940,49 +2341,51 @@ parseCode(Thread* t, Stream& s, object pool) return code; } -object -addInterfaceMethods(Thread* t, object class_, object virtualMap, - unsigned* virtualCount, bool makeList) +GcList* addInterfaceMethods(Thread* t, + GcClass* class_, + GcHashMap* virtualMap, + unsigned* virtualCount, + bool makeList) { - object itable = classInterfaceTable(t, class_); + GcArray* itable = cast(t, class_->interfaceTable()); if (itable) { PROTECT(t, class_); - PROTECT(t, virtualMap); + PROTECT(t, virtualMap); PROTECT(t, itable); - - object list = 0; + + GcList* list = 0; PROTECT(t, list); - object method = 0; + GcMethod* method = 0; PROTECT(t, method); - object vtable = 0; + GcArray* vtable = 0; PROTECT(t, vtable); - unsigned stride = (classFlags(t, class_) & ACC_INTERFACE) ? 1 : 2; - for (unsigned i = 0; i < arrayLength(t, itable); i += stride) { - vtable = classVirtualTable(t, arrayBody(t, itable, i)); + unsigned stride = (class_->flags() & ACC_INTERFACE) ? 1 : 2; + for (unsigned i = 0; i < itable->length(); i += stride) { + vtable = cast( + t, cast(t, itable->body()[i])->virtualTable()); if (vtable) { - for (unsigned j = 0; j < arrayLength(t, vtable); ++j) { - method = arrayBody(t, vtable, j); - object n = hashMapFindNode - (t, virtualMap, method, methodHash, methodEqual); + for (unsigned j = 0; j < vtable->length(); ++j) { + method = cast(t, vtable->body()[j]); + GcTriple* n + = hashMapFindNode(t, virtualMap, method, methodHash, methodEqual); if (n == 0) { - method = makeMethod - (t, - methodVmFlags(t, method), - methodReturnCode(t, method), - methodParameterCount(t, method), - methodParameterFootprint(t, method), - methodFlags(t, method), - (*virtualCount)++, - 0, - 0, - methodName(t, method), - methodSpec(t, method), - 0, - class_, - 0); + method = makeMethod(t, + method->vmFlags(), + method->returnCode(), + method->parameterCount(), + method->parameterFootprint(), + method->flags(), + (*virtualCount)++, + 0, + 0, + method->name(), + method->spec(), + 0, + class_, + 0); hashMapInsert(t, virtualMap, method, method, methodHash); @@ -2003,52 +2406,51 @@ addInterfaceMethods(Thread* t, object class_, object virtualMap, return 0; } -void -parseMethodTable(Thread* t, Stream& s, object class_, object pool) +void parseMethodTable(Thread* t, Stream& s, GcClass* class_, GcSingleton* pool) { PROTECT(t, class_); PROTECT(t, pool); - object virtualMap = makeHashMap(t, 0, 0); + GcHashMap* virtualMap = makeHashMap(t, 0, 0); PROTECT(t, virtualMap); unsigned virtualCount = 0; unsigned declaredVirtualCount = 0; - object superVirtualTable = 0; + GcArray* superVirtualTable = 0; PROTECT(t, superVirtualTable); - if ((classFlags(t, class_) & ACC_INTERFACE) == 0) { - if (classSuper(t, class_)) { - superVirtualTable = classVirtualTable(t, classSuper(t, class_)); + if ((class_->flags() & ACC_INTERFACE) == 0) { + if (class_->super()) { + superVirtualTable = cast(t, class_->super()->virtualTable()); } if (superVirtualTable) { - virtualCount = arrayLength(t, superVirtualTable); + virtualCount = superVirtualTable->length(); for (unsigned i = 0; i < virtualCount; ++i) { - object method = arrayBody(t, superVirtualTable, i); + object method = superVirtualTable->body()[i]; hashMapInsert(t, virtualMap, method, method, methodHash); } } } - object newVirtuals = makeList(t, 0, 0, 0); + GcList* newVirtuals = makeList(t, 0, 0, 0); PROTECT(t, newVirtuals); - + unsigned count = s.read2(); - if(DebugClassReader) { + if (DebugClassReader) { fprintf(stderr, " method count %d\n", count); } if (count) { - object methodTable = makeArray(t, count); + GcArray* methodTable = makeArray(t, count); PROTECT(t, methodTable); - object addendum = 0; + GcMethodAddendum* addendum = 0; PROTECT(t, addendum); - object code = 0; + GcCode* code = 0; PROTECT(t, code); for (unsigned i = 0; i < count; ++i) { @@ -2056,10 +2458,18 @@ parseMethodTable(Thread* t, Stream& s, object class_, object pool) unsigned name = s.read2(); unsigned spec = s.read2(); - if(DebugClassReader) { - fprintf(stderr, " method flags %d name %d spec %d '%s%s'\n", flags, name, spec, - &byteArrayBody(t, singletonObject(t, pool, name - 1), 0), - &byteArrayBody(t, singletonObject(t, pool, spec - 1), 0)); + if (DebugClassReader) { + fprintf(stderr, + " method flags %d name %d spec %d '%s%s'\n", + flags, + name, + spec, + cast(t, singletonObject(t, pool, name - 1)) + ->body() + .begin(), + cast(t, singletonObject(t, pool, spec - 1)) + ->body() + .begin()); } addendum = 0; @@ -2067,285 +2477,272 @@ parseMethodTable(Thread* t, Stream& s, object class_, object pool) unsigned attributeCount = s.read2(); for (unsigned j = 0; j < attributeCount; ++j) { - object attributeName = singletonObject(t, pool, s.read2() - 1); + GcByteArray* attributeName + = cast(t, singletonObject(t, pool, s.read2() - 1)); unsigned length = s.read4(); if (vm::strcmp(reinterpret_cast("Code"), - &byteArrayBody(t, attributeName, 0)) == 0) - { + attributeName->body().begin()) == 0) { code = parseCode(t, s, pool); } else if (vm::strcmp(reinterpret_cast("Exceptions"), - &byteArrayBody(t, attributeName, 0)) == 0) - { + attributeName->body().begin()) == 0) { if (addendum == 0) { addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); } unsigned exceptionCount = s.read2(); - object body = makeShortArray(t, exceptionCount); + GcShortArray* body = makeShortArray(t, exceptionCount); for (unsigned i = 0; i < exceptionCount; ++i) { - shortArrayBody(t, body, i) = s.read2(); + body->body()[i] = s.read2(); } - set(t, addendum, MethodAddendumExceptionTable, body); - } else if (vm::strcmp(reinterpret_cast - ("AnnotationDefault"), - &byteArrayBody(t, attributeName, 0)) == 0) - { + addendum->setExceptionTable(t, body); + } else if (vm::strcmp( + reinterpret_cast("AnnotationDefault"), + attributeName->body().begin()) == 0) { if (addendum == 0) { addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); } - object body = makeByteArray(t, length); - s.read(reinterpret_cast(&byteArrayBody(t, body, 0)), - length); + GcByteArray* body = makeByteArray(t, length); + s.read(reinterpret_cast(body->body().begin()), length); - set(t, addendum, MethodAddendumAnnotationDefault, body); + addendum->setAnnotationDefault(t, body); } else if (vm::strcmp(reinterpret_cast("Signature"), - &byteArrayBody(t, attributeName, 0)) == 0) - { - if (addendum == 0) { - addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); - } - - set(t, addendum, AddendumSignature, - singletonObject(t, pool, s.read2() - 1)); - } else if (vm::strcmp(reinterpret_cast - ("RuntimeVisibleAnnotations"), - &byteArrayBody(t, attributeName, 0)) == 0) - { + attributeName->body().begin()) == 0) { if (addendum == 0) { addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); } - object body = makeByteArray(t, length); - s.read(reinterpret_cast(&byteArrayBody(t, body, 0)), - length); - - set(t, addendum, AddendumAnnotationTable, body); - } else if (vm::strcmp(reinterpret_cast - ("RuntimeVisibleParameterAnnotations"), - &byteArrayBody(t, attributeName, 0)) == 0) - { + addendum->setSignature(t, singletonObject(t, pool, s.read2() - 1)); + } else if (vm::strcmp(reinterpret_cast( + "RuntimeVisibleAnnotations"), + attributeName->body().begin()) == 0) { if (addendum == 0) { addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); } - object body = makeByteArray(t, length); - s.read(reinterpret_cast(&byteArrayBody(t, body, 0)), - length); + GcByteArray* body = makeByteArray(t, length); + s.read(reinterpret_cast(body->body().begin()), length); - set(t, addendum, MethodAddendumParameterAnnotationTable, body); + addendum->setAnnotationTable(t, body); + } else if (vm::strcmp(reinterpret_cast( + "RuntimeVisibleParameterAnnotations"), + attributeName->body().begin()) == 0) { + if (addendum == 0) { + addendum = makeMethodAddendum(t, pool, 0, 0, 0, 0, 0); + } + + GcByteArray* body = makeByteArray(t, length); + s.read(reinterpret_cast(body->body().begin()), length); + + addendum->setParameterAnnotationTable(t, body); } else { s.skip(length); } } - const char* specString = reinterpret_cast - (&byteArrayBody(t, singletonObject(t, pool, spec - 1), 0)); + const char* specString = reinterpret_cast( + cast(t, singletonObject(t, pool, spec - 1)) + ->body() + .begin()); unsigned parameterCount; unsigned parameterFootprint; unsigned returnCode; - scanMethodSpec(t, specString, flags & ACC_STATIC, ¶meterCount, - ¶meterFootprint, &returnCode); + scanMethodSpec(t, + specString, + flags & ACC_STATIC, + ¶meterCount, + ¶meterFootprint, + &returnCode); - object method = t->m->processor->makeMethod - (t, - 0, // vm flags - returnCode, - parameterCount, - parameterFootprint, - flags, - 0, // offset - singletonObject(t, pool, name - 1), - singletonObject(t, pool, spec - 1), - addendum, - class_, - code); + GcMethod* method = t->m->processor->makeMethod( + t, + 0, // vm flags + returnCode, + parameterCount, + parameterFootprint, + flags, + 0, // offset + cast(t, singletonObject(t, pool, name - 1)), + cast(t, singletonObject(t, pool, spec - 1)), + addendum, + class_, + code); PROTECT(t, method); if (methodVirtual(t, method)) { - ++ declaredVirtualCount; + ++declaredVirtualCount; - object p = hashMapFindNode - (t, virtualMap, method, methodHash, methodEqual); + GcTriple* p + = hashMapFindNode(t, virtualMap, method, methodHash, methodEqual); if (p) { - methodOffset(t, method) = methodOffset(t, tripleFirst(t, p)); + method->offset() = cast(t, p->first())->offset(); - set(t, p, TripleSecond, method); + p->setSecond(t, method); } else { - methodOffset(t, method) = virtualCount++; + method->offset() = virtualCount++; listAppend(t, newVirtuals, method); hashMapInsert(t, virtualMap, method, method, methodHash); } - if (UNLIKELY((classFlags(t, class_) & ACC_INTERFACE) == 0 - and vm::strcmp - (reinterpret_cast("finalize"), - &byteArrayBody(t, methodName(t, method), 0)) == 0 - and vm::strcmp - (reinterpret_cast("()V"), - &byteArrayBody(t, methodSpec(t, method), 0)) == 0 - and (not emptyMethod(t, method)))) - { - classVmFlags(t, class_) |= HasFinalizerFlag; + if (UNLIKELY((class_->flags() & ACC_INTERFACE) == 0 + and vm::strcmp(reinterpret_cast("finalize"), + method->name()->body().begin()) == 0 + and vm::strcmp(reinterpret_cast("()V"), + method->spec()->body().begin()) == 0 + and (not emptyMethod(t, method)))) { + class_->vmFlags() |= HasFinalizerFlag; } } else { - methodOffset(t, method) = i; + method->offset() = i; - if (vm::strcmp(reinterpret_cast(""), - &byteArrayBody(t, methodName(t, method), 0)) == 0) - { - methodVmFlags(t, method) |= ClassInitFlag; - classVmFlags(t, class_) |= NeedInitFlag; - } else if (vm::strcmp - (reinterpret_cast(""), - &byteArrayBody(t, methodName(t, method), 0)) == 0) - { - methodVmFlags(t, method) |= ConstructorFlag; + if (vm::strcmp(reinterpret_cast(""), + method->name()->body().begin()) == 0) { + method->vmFlags() |= ClassInitFlag; + class_->vmFlags() |= NeedInitFlag; + } else if (vm::strcmp(reinterpret_cast(""), + method->name()->body().begin()) == 0) { + method->vmFlags() |= ConstructorFlag; } } - set(t, methodTable, ArrayBody + (i * BytesPerWord), method); + methodTable->setBodyElement(t, i, method); } - set(t, class_, ClassMethodTable, methodTable); + class_->setMethodTable(t, methodTable); } - - object abstractVirtuals = addInterfaceMethods - (t, class_, virtualMap, &virtualCount, true); + GcList* abstractVirtuals + = addInterfaceMethods(t, class_, virtualMap, &virtualCount, true); PROTECT(t, abstractVirtuals); bool populateInterfaceVtables = false; - if (declaredVirtualCount == 0 - and abstractVirtuals == 0 - and (classFlags(t, class_) & ACC_INTERFACE) == 0) - { - if (classSuper(t, class_)) { + if (declaredVirtualCount == 0 and abstractVirtuals == 0 + and (class_->flags() & ACC_INTERFACE) == 0) { + if (class_->super()) { // inherit virtual table from superclass - set(t, class_, ClassVirtualTable, superVirtualTable); - - if (classInterfaceTable(t, classSuper(t, class_)) - and arrayLength(t, classInterfaceTable(t, class_)) - == arrayLength - (t, classInterfaceTable(t, classSuper(t, class_)))) - { + class_->setVirtualTable(t, superVirtualTable); + + if (class_->super()->interfaceTable() + and cast(t, class_->interfaceTable())->length() + == cast(t, class_->super()->interfaceTable()) + ->length()) { // inherit interface table from superclass - set(t, class_, ClassInterfaceTable, - classInterfaceTable(t, classSuper(t, class_))); + class_->setInterfaceTable(t, class_->super()->interfaceTable()); } else { populateInterfaceVtables = true; } } else { // apparently, Object does not have any virtual methods. We // give it a vtable anyway so code doesn't break elsewhere. - object vtable = makeArray(t, 0); - set(t, class_, ClassVirtualTable, vtable); + GcArray* vtable = makeArray(t, 0); + class_->setVirtualTable(t, vtable); } } else if (virtualCount) { // generate class vtable - object vtable = makeArray(t, virtualCount); + GcArray* vtable = makeArray(t, virtualCount); unsigned i = 0; - if (classFlags(t, class_) & ACC_INTERFACE) { + if (class_->flags() & ACC_INTERFACE) { PROTECT(t, vtable); for (HashMapIterator it(t, virtualMap); it.hasMore();) { - object method = tripleFirst(t, it.next()); - assert(t, arrayBody(t, vtable, methodOffset(t, method)) == 0); - set(t, vtable, ArrayBody + (methodOffset(t, method) * BytesPerWord), - method); - ++ i; + GcMethod* method = cast(t, it.next()->first()); + assertT(t, vtable->body()[method->offset()] == 0); + vtable->setBodyElement(t, method->offset(), method); + ++i; } } else { populateInterfaceVtables = true; if (superVirtualTable) { - for (; i < arrayLength(t, superVirtualTable); ++i) { - object method = arrayBody(t, superVirtualTable, i); + for (; i < superVirtualTable->length(); ++i) { + object method = superVirtualTable->body()[i]; method = hashMapFind(t, virtualMap, method, methodHash, methodEqual); - set(t, vtable, ArrayBody + (i * BytesPerWord), method); + vtable->setBodyElement(t, i, method); } } - for (object p = listFront(t, newVirtuals); p; p = pairSecond(t, p)) { - set(t, vtable, ArrayBody + (i * BytesPerWord), pairFirst(t, p)); - ++ i; + for (GcPair* p = cast(t, newVirtuals->front()); p; + p = cast(t, p->second())) { + vtable->setBodyElement(t, i, p->first()); + ++i; } } if (abstractVirtuals) { PROTECT(t, vtable); - object originalMethodTable = classMethodTable(t, class_); + object originalMethodTable = class_->methodTable(); PROTECT(t, originalMethodTable); - unsigned oldLength = classMethodTable(t, class_) ? - arrayLength(t, classMethodTable(t, class_)) : 0; + unsigned oldLength + = class_->methodTable() + ? cast(t, class_->methodTable())->length() + : 0; - object addendum = getClassAddendum(t, class_, pool); - classAddendumDeclaredMethodCount(t, addendum) = oldLength; + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); + addendum->declaredMethodCount() = oldLength; - object newMethodTable = makeArray - (t, oldLength + listSize(t, abstractVirtuals)); + GcArray* newMethodTable + = makeArray(t, oldLength + abstractVirtuals->size()); if (oldLength) { - memcpy(&arrayBody(t, newMethodTable, 0), - &arrayBody(t, classMethodTable(t, class_), 0), - oldLength * sizeof(object)); + GcArray* mtable = cast(t, class_->methodTable()); + for (size_t i = 0; i < oldLength; i++) { + newMethodTable->setBodyElement(t, i, mtable->body()[i]); + } } mark(t, newMethodTable, ArrayBody, oldLength); unsigned mti = oldLength; - for (object p = listFront(t, abstractVirtuals); - p; p = pairSecond(t, p)) - { - set(t, newMethodTable, - ArrayBody + ((mti++) * BytesPerWord), pairFirst(t, p)); + for (GcPair* p = cast(t, abstractVirtuals->front()); p; + p = cast(t, p->second())) { + newMethodTable->setBodyElement(t, mti++, p->first()); - if ((classFlags(t, class_) & ACC_INTERFACE) == 0) { - set(t, vtable, - ArrayBody + ((i++) * BytesPerWord), pairFirst(t, p)); + if ((class_->flags() & ACC_INTERFACE) == 0) { + vtable->setBodyElement(t, i++, p->first()); } } - assert(t, arrayLength(t, newMethodTable) == mti); + assertT(t, newMethodTable->length() == mti); - set(t, class_, ClassMethodTable, newMethodTable); + class_->setMethodTable(t, newMethodTable); } - assert(t, arrayLength(t, vtable) == i); + assertT(t, vtable->length() == i); - set(t, class_, ClassVirtualTable, vtable); + class_->setVirtualTable(t, vtable); } if (populateInterfaceVtables) { // generate interface vtables - object itable = classInterfaceTable(t, class_); + GcArray* itable = cast(t, class_->interfaceTable()); if (itable) { PROTECT(t, itable); - for (unsigned i = 0; i < arrayLength(t, itable); i += 2) { - object ivtable = classVirtualTable(t, arrayBody(t, itable, i)); + for (unsigned i = 0; i < itable->length(); i += 2) { + GcArray* ivtable = cast( + t, cast(t, itable->body()[i])->virtualTable()); if (ivtable) { - object vtable = arrayBody(t, itable, i + 1); - - for (unsigned j = 0; j < arrayLength(t, ivtable); ++j) { - object method = arrayBody(t, ivtable, j); - method = hashMapFind - (t, virtualMap, method, methodHash, methodEqual); - assert(t, method); - - set(t, vtable, ArrayBody + (j * BytesPerWord), method); + GcArray* vtable = cast(t, itable->body()[i + 1]); + + for (unsigned j = 0; j < ivtable->length(); ++j) { + object method = ivtable->body()[j]; + method + = hashMapFind(t, virtualMap, method, methodHash, methodEqual); + assertT(t, method); + + vtable->setBodyElement(t, j, method); } } } @@ -2353,32 +2750,32 @@ parseMethodTable(Thread* t, Stream& s, object class_, object pool) } } -void -parseAttributeTable(Thread* t, Stream& s, object class_, object pool) +void parseAttributeTable(Thread* t, + Stream& s, + GcClass* class_, + GcSingleton* pool) { PROTECT(t, class_); PROTECT(t, pool); unsigned attributeCount = s.read2(); for (unsigned j = 0; j < attributeCount; ++j) { - object name = singletonObject(t, pool, s.read2() - 1); + GcByteArray* name + = cast(t, singletonObject(t, pool, s.read2() - 1)); unsigned length = s.read4(); if (vm::strcmp(reinterpret_cast("SourceFile"), - &byteArrayBody(t, name, 0)) == 0) - { - set(t, class_, ClassSourceFile, singletonObject(t, pool, s.read2() - 1)); + name->body().begin()) == 0) { + class_->setSourceFile( + t, cast(t, singletonObject(t, pool, s.read2() - 1))); } else if (vm::strcmp(reinterpret_cast("Signature"), - &byteArrayBody(t, name, 0)) == 0) - { - object addendum = getClassAddendum(t, class_, pool); - set(t, addendum, AddendumSignature, - singletonObject(t, pool, s.read2() - 1)); + name->body().begin()) == 0) { + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); + addendum->setSignature(t, singletonObject(t, pool, s.read2() - 1)); } else if (vm::strcmp(reinterpret_cast("InnerClasses"), - &byteArrayBody(t, name, 0)) == 0) - { + name->body().begin()) == 0) { unsigned innerClassCount = s.read2(); - object table = makeArray(t, innerClassCount); + GcArray* table = makeArray(t, innerClassCount); PROTECT(t, table); for (unsigned i = 0; i < innerClassCount; ++i) { @@ -2387,119 +2784,128 @@ parseAttributeTable(Thread* t, Stream& s, object class_, object pool) int16_t name = s.read2(); int16_t flags = s.read2(); - object reference = makeInnerClassReference - (t, - inner ? referenceName(t, singletonObject(t, pool, inner - 1)) : 0, - outer ? referenceName(t, singletonObject(t, pool, outer - 1)) : 0, - name ? singletonObject(t, pool, name - 1) : 0, - flags); + GcInnerClassReference* reference = makeInnerClassReference( + t, + inner + ? cast(t, singletonObject(t, pool, inner - 1)) + ->name() + : 0, + outer + ? cast(t, singletonObject(t, pool, outer - 1)) + ->name() + : 0, + name ? cast(t, singletonObject(t, pool, name - 1)) : 0, + flags); - set(t, table, ArrayBody + (i * BytesPerWord), reference); + table->setBodyElement(t, i, reference); } - object addendum = getClassAddendum(t, class_, pool); - set(t, addendum, ClassAddendumInnerClassTable, table); - } else if (vm::strcmp(reinterpret_cast - ("RuntimeVisibleAnnotations"), - &byteArrayBody(t, name, 0)) == 0) - { - object body = makeByteArray(t, length); + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); + addendum->setInnerClassTable(t, table); + } else if (vm::strcmp( + reinterpret_cast("RuntimeVisibleAnnotations"), + name->body().begin()) == 0) { + GcByteArray* body = makeByteArray(t, length); PROTECT(t, body); - s.read(reinterpret_cast(&byteArrayBody(t, body, 0)), length); + s.read(reinterpret_cast(body->body().begin()), length); - object addendum = getClassAddendum(t, class_, pool); - set(t, addendum, AddendumAnnotationTable, body); - } else if (vm::strcmp(reinterpret_cast - ("EnclosingMethod"), - &byteArrayBody(t, name, 0)) == 0) - { + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); + addendum->setAnnotationTable(t, body); + } else if (vm::strcmp(reinterpret_cast("EnclosingMethod"), + name->body().begin()) == 0) { int16_t enclosingClass = s.read2(); int16_t enclosingMethod = s.read2(); - object addendum = getClassAddendum(t, class_, pool); + GcClassAddendum* addendum = getClassAddendum(t, class_, pool); - set(t, addendum, ClassAddendumEnclosingClass, - referenceName(t, singletonObject(t, pool, enclosingClass - 1))); + addendum->setEnclosingClass( + t, + reinterpret_cast( + cast(t, singletonObject(t, pool, enclosingClass - 1)) + ->name())); - set(t, addendum, ClassAddendumEnclosingMethod, enclosingMethod - ? singletonObject(t, pool, enclosingMethod - 1) : 0); + addendum->setEnclosingMethod( + t, + enclosingMethod ? singletonObject(t, pool, enclosingMethod - 1) : 0); } else { s.skip(length); } } } -void -updateClassTables(Thread* t, object newClass, object oldClass) +void updateClassTables(Thread* t, GcClass* newClass, GcClass* oldClass) { - object fieldTable = classFieldTable(t, newClass); + GcArray* fieldTable = cast(t, newClass->fieldTable()); if (fieldTable) { - for (unsigned i = 0; i < arrayLength(t, fieldTable); ++i) { - set(t, arrayBody(t, fieldTable, i), FieldClass, newClass); + for (unsigned i = 0; i < fieldTable->length(); ++i) { + cast(t, fieldTable->body()[i])->setClass(t, newClass); } } - object staticTable = classStaticTable(t, newClass); + GcSingleton* staticTable = newClass->staticTable(); if (staticTable) { - set(t, staticTable, SingletonBody, newClass); + staticTable->setBodyElement(t, 0, reinterpret_cast(newClass)); } - if (classFlags(t, newClass) & ACC_INTERFACE) { - object virtualTable = classVirtualTable(t, newClass); + if (newClass->flags() & ACC_INTERFACE) { + GcArray* virtualTable = cast(t, newClass->virtualTable()); if (virtualTable) { - for (unsigned i = 0; i < arrayLength(t, virtualTable); ++i) { - if (methodClass(t, arrayBody(t, virtualTable, i)) == oldClass) { - set(t, arrayBody(t, virtualTable, i), MethodClass, newClass); + for (unsigned i = 0; i < virtualTable->length(); ++i) { + GcMethod* m = cast(t, virtualTable->body()[i]); + if (m->class_() == oldClass) { + m->setClass(t, newClass); } } } } - object methodTable = classMethodTable(t, newClass); + GcArray* methodTable = cast(t, newClass->methodTable()); if (methodTable) { - for (unsigned i = 0; i < arrayLength(t, methodTable); ++i) { - set(t, arrayBody(t, methodTable, i), MethodClass, newClass); + for (unsigned i = 0; i < methodTable->length(); ++i) { + cast(t, methodTable->body()[i])->setClass(t, newClass); } } } -void -updateBootstrapClass(Thread* t, object bootstrapClass, object class_) +void updateBootstrapClass(Thread* t, GcClass* bootstrapClass, GcClass* class_) { expect(t, bootstrapClass != class_); // verify that the classes have the same layout - expect(t, classSuper(t, bootstrapClass) == classSuper(t, class_)); + expect(t, bootstrapClass->super() == class_->super()); - expect(t, classFixedSize(t, bootstrapClass) >= classFixedSize(t, class_)); + expect(t, bootstrapClass->fixedSize() >= class_->fixedSize()); - expect(t, (classVmFlags(t, class_) & HasFinalizerFlag) == 0); + expect(t, (class_->vmFlags() & HasFinalizerFlag) == 0); PROTECT(t, bootstrapClass); PROTECT(t, class_); ENTER(t, Thread::ExclusiveState); - classVmFlags(t, bootstrapClass) &= ~BootstrapFlag; - classVmFlags(t, bootstrapClass) |= classVmFlags(t, class_); - classFlags(t, bootstrapClass) |= classFlags(t, class_); + bootstrapClass->vmFlags() &= ~BootstrapFlag; + bootstrapClass->vmFlags() |= class_->vmFlags(); + bootstrapClass->flags() |= class_->flags(); - set(t, bootstrapClass, ClassSuper, classSuper(t, class_)); - set(t, bootstrapClass, ClassInterfaceTable, classInterfaceTable(t, class_)); - set(t, bootstrapClass, ClassVirtualTable, classVirtualTable(t, class_)); - set(t, bootstrapClass, ClassFieldTable, classFieldTable(t, class_)); - set(t, bootstrapClass, ClassMethodTable, classMethodTable(t, class_)); - set(t, bootstrapClass, ClassStaticTable, classStaticTable(t, class_)); - set(t, bootstrapClass, ClassAddendum, classAddendum(t, class_)); + bootstrapClass->setArrayElementClass(t, class_->arrayElementClass()); + bootstrapClass->setSuper(t, class_->super()); + bootstrapClass->setInterfaceTable(t, class_->interfaceTable()); + bootstrapClass->setVirtualTable(t, class_->virtualTable()); + bootstrapClass->setFieldTable(t, class_->fieldTable()); + bootstrapClass->setMethodTable(t, class_->methodTable()); + bootstrapClass->setStaticTable(t, class_->staticTable()); + bootstrapClass->setAddendum(t, class_->addendum()); updateClassTables(t, bootstrapClass, class_); } -object -makeArrayClass(Thread* t, object loader, unsigned dimensions, object spec, - object elementClass) +GcClass* makeArrayClass(Thread* t, + GcClassLoader* loader, + unsigned dimensions, + GcByteArray* spec, + GcClass* elementClass) { - if (classVmFlags(t, type(t, Machine::JobjectType)) & BootstrapFlag) { + if (type(t, GcJobject::Type)->vmFlags() & BootstrapFlag) { PROTECT(t, loader); PROTECT(t, spec); PROTECT(t, elementClass); @@ -2508,32 +2914,31 @@ makeArrayClass(Thread* t, object loader, unsigned dimensions, object spec, // don't throw an exception if we can't find it. This way, we // avoid infinite recursion due to trying to create an array to // make a stack trace for a ClassNotFoundException. - resolveSystemClass - (t, root(t, Machine::BootLoader), - className(t, type(t, Machine::JobjectType)), false); + resolveSystemClass( + t, roots(t)->bootLoader(), type(t, GcJobject::Type)->name(), false); } - object vtable = classVirtualTable(t, type(t, Machine::JobjectType)); + GcArray* vtable = cast(t, type(t, GcJobject::Type)->virtualTable()); - object c = t->m->processor->makeClass - (t, - 0, - 0, - 2 * BytesPerWord, - BytesPerWord, - dimensions, - classObjectMask(t, type(t, Machine::ArrayType)), - spec, - 0, - type(t, Machine::JobjectType), - root(t, Machine::ArrayInterfaceTable), - vtable, - 0, - 0, - 0, - elementClass, - loader, - arrayLength(t, vtable)); + GcClass* c = t->m->processor->makeClass(t, + 0, + 0, + 2 * BytesPerWord, + BytesPerWord, + dimensions, + elementClass, + type(t, GcArray::Type)->objectMask(), + spec, + 0, + type(t, GcJobject::Type), + roots(t)->arrayInterfaceTable(), + vtable, + 0, + 0, + 0, + 0, + loader, + vtable->length()); PROTECT(t, c); @@ -2542,51 +2947,54 @@ makeArrayClass(Thread* t, object loader, unsigned dimensions, object spec, return c; } -void -saveLoadedClass(Thread* t, object loader, object c) +void saveLoadedClass(Thread* t, GcClassLoader* loader, GcClass* c) { PROTECT(t, loader); PROTECT(t, c); ACQUIRE(t, t->m->classLock); - if (classLoaderMap(t, loader) == 0) { - object map = makeHashMap(t, 0, 0); - set(t, loader, ClassLoaderMap, map); + if (loader->map() == 0) { + GcHashMap* map = makeHashMap(t, 0, 0); + loader->setMap(t, map); } - hashMapInsert - (t, classLoaderMap(t, loader), className(t, c), c, byteArrayHash); + hashMapInsert( + t, cast(t, loader->map()), c->name(), c, byteArrayHash); } -object -makeArrayClass(Thread* t, object loader, object spec, bool throw_, - Machine::Type throwType) +GcClass* makeArrayClass(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + bool throw_, + Gc::Type throwType) { PROTECT(t, loader); PROTECT(t, spec); - const char* s = reinterpret_cast(&byteArrayBody(t, spec, 0)); + const char* s = reinterpret_cast(spec->body().begin()); const char* start = s; unsigned dimensions = 0; - for (; *s == '['; ++s) ++ dimensions; + for (; *s == '['; ++s) + ++dimensions; - object elementSpec; + GcByteArray* elementSpec; switch (*s) { case 'L': { - ++ s; + ++s; const char* elementSpecStart = s; - while (*s and *s != ';') ++ s; + while (*s and *s != ';') + ++s; if (dimensions > 1) { elementSpecStart -= dimensions; - ++ s; + ++s; } elementSpec = makeByteArray(t, s - elementSpecStart + 1); - memcpy(&byteArrayBody(t, elementSpec, 0), - &byteArrayBody(t, spec, elementSpecStart - start), + memcpy(elementSpec->body().begin(), + &spec->body()[elementSpecStart - start], s - elementSpecStart); - byteArrayBody(t, elementSpec, s - elementSpecStart) = 0; + elementSpec->body()[s - elementSpecStart] = 0; } break; default: @@ -2595,62 +3003,71 @@ makeArrayClass(Thread* t, object loader, object spec, bool throw_, elementSpec = makeByteArray(t, dimensions + 1); unsigned i; for (i = 0; i < dimensions - 1; ++i) { - byteArrayBody(t, elementSpec, i) = '['; + elementSpec->body()[i] = '['; } - byteArrayBody(t, elementSpec, i++) = c; - byteArrayBody(t, elementSpec, i) = 0; - -- dimensions; + elementSpec->body()[i++] = c; + elementSpec->body()[i] = 0; + --dimensions; } else { abort(t); } } - object elementClass = hashMapFind - (t, root(t, Machine::BootstrapClassMap), elementSpec, byteArrayHash, - byteArrayEqual); - + GcClass* elementClass + = cast(t, + hashMapFind(t, + roots(t)->bootstrapClassMap(), + elementSpec, + byteArrayHash, + byteArrayEqual)); + if (elementClass == 0) { elementClass = resolveClass(t, loader, elementSpec, throw_, throwType); - if (elementClass == 0) return 0; + if (elementClass == 0) + return 0; } PROTECT(t, elementClass); ACQUIRE(t, t->m->classLock); - object class_ = findLoadedClass(t, classLoader(t, elementClass), spec); + GcClass* class_ = findLoadedClass(t, elementClass->loader(), spec); if (class_) { return class_; } - class_ = makeArrayClass - (t, classLoader(t, elementClass), dimensions, spec, elementClass); + class_ = makeArrayClass( + t, elementClass->loader(), dimensions, spec, elementClass); PROTECT(t, class_); - saveLoadedClass(t, classLoader(t, elementClass), class_); + saveLoadedClass(t, elementClass->loader(), class_); return class_; } -object -resolveArrayClass(Thread* t, object loader, object spec, bool throw_, - Machine::Type throwType) +GcClass* resolveArrayClass(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + bool throw_, + Gc::Type throwType) { - object c = hashMapFind - (t, root(t, Machine::BootstrapClassMap), spec, byteArrayHash, - byteArrayEqual); + GcClass* c = cast(t, + hashMapFind(t, + roots(t)->bootstrapClassMap(), + spec, + byteArrayHash, + byteArrayEqual)); if (c) { - set(t, c, ClassVirtualTable, - classVirtualTable(t, type(t, Machine::JobjectType))); + c->setVirtualTable(t, type(t, GcJobject::Type)->virtualTable()); return c; } else { PROTECT(t, loader); PROTECT(t, spec); - c = findLoadedClass(t, root(t, Machine::BootLoader), spec); + c = findLoadedClass(t, roots(t)->bootLoader(), spec); if (c) { return c; @@ -2660,320 +3077,331 @@ resolveArrayClass(Thread* t, object loader, object spec, bool throw_, } } -void -removeMonitor(Thread* t, object o) +void removeMonitor(Thread* t, object o) { unsigned hash; if (DebugMonitors) { hash = objectHash(t, o); } - object m = hashMapRemove - (t, root(t, Machine::MonitorMap), o, objectHash, objectEqual); + object m + = hashMapRemove(t, roots(t)->monitorMap(), o, objectHash, objectEqual); if (DebugMonitors) { fprintf(stderr, "dispose monitor %p for object %x\n", m, hash); } } -void -removeString(Thread* t, object o) +void removeString(Thread* t, object o) { - hashMapRemove(t, root(t, Machine::StringMap), o, stringHash, objectEqual); + hashMapRemove(t, roots(t)->stringMap(), o, stringHash, objectEqual); } -void -bootClass(Thread* t, Machine::Type type, int superType, uint32_t objectMask, - unsigned fixedSize, unsigned arrayElementSize, unsigned vtableLength) +void bootClass(Thread* t, + Gc::Type type, + int superType, + uint32_t objectMask, + unsigned fixedSize, + unsigned arrayElementSize, + unsigned vtableLength) { - object super = (superType >= 0 - ? vm::type(t, static_cast(superType)) : 0); + GcClass* super + = (superType >= 0 ? vm::type(t, static_cast(superType)) : 0); - object mask; + GcIntArray* mask; if (objectMask) { - if (super - and classObjectMask(t, super) - and intArrayBody(t, classObjectMask(t, super), 0) - == static_cast(objectMask)) - { - mask = classObjectMask - (t, vm::type(t, static_cast(superType))); + if (super and super->objectMask() + and super->objectMask()->body()[0] + == static_cast(objectMask)) { + mask = vm::type(t, static_cast(superType))->objectMask(); } else { mask = makeIntArray(t, 1); - intArrayBody(t, mask, 0) = objectMask; + mask->body()[0] = objectMask; } } else { mask = 0; } - super = (superType >= 0 - ? vm::type(t, static_cast(superType)) : 0); + super = (superType >= 0 ? vm::type(t, static_cast(superType)) : 0); - object class_ = t->m->processor->makeClass - (t, 0, BootstrapFlag, fixedSize, arrayElementSize, - arrayElementSize ? 1 : 0, mask, 0, 0, super, 0, 0, 0, 0, 0, 0, - root(t, Machine::BootLoader), vtableLength); + GcClass* class_ = t->m->processor->makeClass(t, + 0, + BootstrapFlag, + fixedSize, + arrayElementSize, + arrayElementSize ? 1 : 0, + 0, + mask, + 0, + 0, + super, + 0, + 0, + 0, + 0, + 0, + 0, + roots(t)->bootLoader(), + vtableLength); setType(t, type, class_); } -void -bootJavaClass(Thread* t, Machine::Type type, int superType, const char* name, - int vtableLength, object bootMethod) +void bootJavaClass(Thread* t, + Gc::Type type, + int superType, + const char* name, + int vtableLength, + object bootMethod) { PROTECT(t, bootMethod); - object n = makeByteArray(t, name); + GcByteArray* n = makeByteArray(t, name); PROTECT(t, n); - object class_ = vm::type(t, type); + GcClass* class_ = vm::type(t, type); PROTECT(t, class_); - set(t, class_, ClassName, n); + class_->setName(t, n); - object vtable; + GcArray* vtable; if (vtableLength >= 0) { vtable = makeArray(t, vtableLength); - for (int i = 0; i < vtableLength; ++ i) { - arrayBody(t, vtable, i) = bootMethod; + for (int i = 0; i < vtableLength; ++i) { + vtable->setBodyElement(t, i, bootMethod); } } else { - vtable = classVirtualTable - (t, vm::type(t, static_cast(superType))); + vtable = cast( + t, vm::type(t, static_cast(superType))->virtualTable()); } - set(t, class_, ClassVirtualTable, vtable); + class_->setVirtualTable(t, vtable); t->m->processor->initVtable(t, class_); - hashMapInsert - (t, root(t, Machine::BootstrapClassMap), n, class_, byteArrayHash); + hashMapInsert(t, roots(t)->bootstrapClassMap(), n, class_, byteArrayHash); } -void -nameClass(Thread* t, Machine::Type type, const char* name) +void nameClass(Thread* t, Gc::Type type, const char* name) { - object n = makeByteArray(t, name); - set(t, arrayBody(t, t->m->types, type), ClassName, n); + GcByteArray* n = makeByteArray(t, name); + cast(t, t->m->types->body()[type])->setName(t, n); } -void -makeArrayInterfaceTable(Thread* t) +void makeArrayInterfaceTable(Thread* t) { - object interfaceTable = makeArray(t, 4); - - set(t, interfaceTable, ArrayBody, type - (t, Machine::SerializableType)); - - set(t, interfaceTable, ArrayBody + (2 * BytesPerWord), - type(t, Machine::CloneableType)); - - setRoot(t, Machine::ArrayInterfaceTable, interfaceTable); + GcArray* interfaceTable = makeArray(t, 4); + + interfaceTable->setBodyElement(t, 0, type(t, GcSerializable::Type)); + + interfaceTable->setBodyElement(t, 2, type(t, GcCloneable::Type)); + + roots(t)->setArrayInterfaceTable(t, interfaceTable); } -void -boot(Thread* t) +void boot(Thread* t) { Machine* m = t->m; m->unsafe = true; - m->roots = allocate(t, pad((Machine::RootCount + 2) * BytesPerWord), true); - arrayLength(t, m->roots) = Machine::RootCount; + m->roots = reinterpret_cast(allocate(t, GcRoots::FixedSize, true)); - setRoot(t, Machine::BootLoader, - allocate(t, FixedSizeOfSystemClassLoader, true)); + object classLoader = allocate(t, GcSystemClassLoader::FixedSize, true); + // sequence point, for gc (don't recombine statements) + roots(t)->setBootLoader(t, reinterpret_cast(classLoader)); - setRoot(t, Machine::AppLoader, - allocate(t, FixedSizeOfSystemClassLoader, true)); + classLoader = allocate(t, GcSystemClassLoader::FixedSize, true); + // sequence point, for gc (don't recombine statements) + roots(t)->setAppLoader(t, reinterpret_cast(classLoader)); - m->types = allocate(t, pad((TypeCount + 2) * BytesPerWord), true); - arrayLength(t, m->types) = TypeCount; + m->types = reinterpret_cast( + allocate(t, pad((TypeCount + 2) * BytesPerWord), true)); + m->types->length() = TypeCount; #include "type-initializations.cpp" - object arrayClass = type(t, Machine::ArrayType); - set(t, m->types, 0, arrayClass); - set(t, m->roots, 0, arrayClass); + GcClass* arrayClass = type(t, GcArray::Type); + setField(t, m->types, 0, arrayClass); - object loaderClass = type(t, Machine::SystemClassLoaderType); - set(t, root(t, Machine::BootLoader), 0, loaderClass); - set(t, root(t, Machine::AppLoader), 0, loaderClass); + GcClass* rootsClass = type(t, GcRoots::Type); + setField(t, m->roots, 0, rootsClass); - object objectClass = type(t, Machine::JobjectType); + GcClass* loaderClass = type(t, GcSystemClassLoader::Type); + setField(t, roots(t)->bootLoader(), 0, loaderClass); + setField(t, roots(t)->appLoader(), 0, loaderClass); - object classClass = type(t, Machine::ClassType); - set(t, classClass, 0, classClass); - set(t, classClass, ClassSuper, objectClass); + GcClass* objectClass = type(t, GcJobject::Type); - object intArrayClass = type(t, Machine::IntArrayType); - set(t, intArrayClass, 0, classClass); - set(t, intArrayClass, ClassSuper, objectClass); + GcClass* classClass = type(t, GcClass::Type); + setField(t, classClass, 0, classClass); + classClass->setSuper(t, objectClass); + + GcClass* intArrayClass = type(t, GcIntArray::Type); + setField(t, intArrayClass, 0, classClass); + intArrayClass->setSuper(t, objectClass); m->unsafe = false; - classVmFlags(t, type(t, Machine::SingletonType)) - |= SingletonFlag; + type(t, GcSingleton::Type)->vmFlags() |= SingletonFlag; - classVmFlags(t, type(t, Machine::ContinuationType)) - |= ContinuationFlag; + type(t, GcContinuation::Type)->vmFlags() |= ContinuationFlag; - classVmFlags(t, type(t, Machine::JreferenceType)) - |= ReferenceFlag; - classVmFlags(t, type(t, Machine::WeakReferenceType)) - |= ReferenceFlag | WeakReferenceFlag; - classVmFlags(t, type(t, Machine::SoftReferenceType)) - |= ReferenceFlag | WeakReferenceFlag; - classVmFlags(t, type(t, Machine::PhantomReferenceType)) - |= ReferenceFlag | WeakReferenceFlag; + type(t, GcJreference::Type)->vmFlags() |= ReferenceFlag; + type(t, GcWeakReference::Type)->vmFlags() |= ReferenceFlag + | WeakReferenceFlag; + type(t, GcSoftReference::Type)->vmFlags() |= ReferenceFlag + | WeakReferenceFlag; + type(t, GcPhantomReference::Type)->vmFlags() |= ReferenceFlag + | WeakReferenceFlag; - classVmFlags(t, type(t, Machine::JbooleanType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JbyteType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JcharType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JshortType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JintType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JlongType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JfloatType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JdoubleType)) - |= PrimitiveFlag; - classVmFlags(t, type(t, Machine::JvoidType)) - |= PrimitiveFlag; + type(t, GcJboolean::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJbyte::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJchar::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJshort::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJint::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJlong::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJfloat::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJdouble::Type)->vmFlags() |= PrimitiveFlag; + type(t, GcJvoid::Type)->vmFlags() |= PrimitiveFlag; - set(t, type(t, Machine::BooleanArrayType), ClassStaticTable, - type(t, Machine::JbooleanType)); - set(t, type(t, Machine::ByteArrayType), ClassStaticTable, - type(t, Machine::JbyteType)); - set(t, type(t, Machine::CharArrayType), ClassStaticTable, - type(t, Machine::JcharType)); - set(t, type(t, Machine::ShortArrayType), ClassStaticTable, - type(t, Machine::JshortType)); - set(t, type(t, Machine::IntArrayType), ClassStaticTable, - type(t, Machine::JintType)); - set(t, type(t, Machine::LongArrayType), ClassStaticTable, - type(t, Machine::JlongType)); - set(t, type(t, Machine::FloatArrayType), ClassStaticTable, - type(t, Machine::JfloatType)); - set(t, type(t, Machine::DoubleArrayType), ClassStaticTable, - type(t, Machine::JdoubleType)); + type(t, GcBooleanArray::Type) + ->setArrayElementClass(t, type(t, GcJboolean::Type)); + type(t, GcByteArray::Type)->setArrayElementClass(t, type(t, GcJbyte::Type)); + type(t, GcCharArray::Type)->setArrayElementClass(t, type(t, GcJchar::Type)); + type(t, GcShortArray::Type)->setArrayElementClass(t, type(t, GcJshort::Type)); + type(t, GcIntArray::Type)->setArrayElementClass(t, type(t, GcJint::Type)); + type(t, GcLongArray::Type)->setArrayElementClass(t, type(t, GcJlong::Type)); + type(t, GcFloatArray::Type)->setArrayElementClass(t, type(t, GcJfloat::Type)); + type(t, GcDoubleArray::Type) + ->setArrayElementClass(t, type(t, GcJdouble::Type)); - { object map = makeHashMap(t, 0, 0); - set(t, root(t, Machine::BootLoader), ClassLoaderMap, map); + { + GcHashMap* map = makeHashMap(t, 0, 0); + roots(t)->bootLoader()->setMap(t, map); } - systemClassLoaderFinder(t, root(t, Machine::BootLoader)) = m->bootFinder; + roots(t)->bootLoader()->as(t)->finder() = m->bootFinder; - { object map = makeHashMap(t, 0, 0); - set(t, root(t, Machine::AppLoader), ClassLoaderMap, map); + { + GcHashMap* map = makeHashMap(t, 0, 0); + roots(t)->appLoader()->setMap(t, map); } - systemClassLoaderFinder(t, root(t, Machine::AppLoader)) = m->appFinder; + roots(t)->appLoader()->as(t)->finder() = m->appFinder; - set(t, root(t, Machine::AppLoader), ClassLoaderParent, - root(t, Machine::BootLoader)); + roots(t)->appLoader()->setParent(t, roots(t)->bootLoader()); - setRoot(t, Machine::BootstrapClassMap, makeHashMap(t, 0, 0)); + { + GcHashMap* map = makeHashMap(t, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(t)->setBootstrapClassMap(t, map); + } - setRoot(t, Machine::StringMap, makeWeakHashMap(t, 0, 0)); + { + GcWeakHashMap* map = makeWeakHashMap(t, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(t)->setStringMap(t, map->as(t)); + } makeArrayInterfaceTable(t); - set(t, type(t, Machine::BooleanArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::ByteArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::CharArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::ShortArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::IntArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::LongArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::FloatArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); - set(t, type(t, Machine::DoubleArrayType), ClassInterfaceTable, - root(t, Machine::ArrayInterfaceTable)); + type(t, GcBooleanArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcByteArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcCharArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcShortArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcIntArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcLongArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcFloatArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); + type(t, GcDoubleArray::Type) + ->setInterfaceTable(t, roots(t)->arrayInterfaceTable()); m->processor->boot(t, 0, 0); - { object bootCode = makeCode(t, 0, 0, 0, 0, 0, 0, 0, 1); - codeBody(t, bootCode, 0) = impdep1; - object bootMethod = makeMethod - (t, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, bootCode); + { + GcCode* bootCode = makeCode(t, 0, 0, 0, 0, 0, 0, 0, 0, 1); + bootCode->body()[0] = impdep1; + object bootMethod + = makeMethod(t, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, bootCode); PROTECT(t, bootMethod); #include "type-java-initializations.cpp" - //#ifdef AVIAN_HEAPDUMP -# include "type-name-initializations.cpp" - //#endif +//#ifdef AVIAN_HEAPDUMP +#include "type-name-initializations.cpp" + //#endif } } -class HeapClient: public Heap::Client { +class HeapClient : public Heap::Client { public: - HeapClient(Machine* m): m(m) { } + HeapClient(Machine* m) : m(m) + { + } - virtual void visitRoots(Heap::Visitor* v) { + virtual void visitRoots(Heap::Visitor* v) + { ::visitRoots(m, v); postVisit(m->rootThread, v); } - virtual void collect(void* context, Heap::CollectionType type) { + virtual void collect(void* context, Heap::CollectionType type) + { collect(static_cast(context), type); } - virtual bool isFixed(void* p) { + virtual bool isFixed(void* p) + { return objectFixed(m->rootThread, static_cast(p)); } - virtual unsigned sizeInWords(void* p) { + virtual unsigned sizeInWords(void* p) + { Thread* t = m->rootThread; object o = static_cast(m->heap->follow(maskAlignedPointer(p))); - unsigned n = baseSize(t, o, static_cast - (m->heap->follow(objectClass(t, o)))); + unsigned n = baseSize(t, o, m->heap->follow(objectClass(t, o))); if (objectExtended(t, o)) { - ++ n; + ++n; } return n; } - virtual unsigned copiedSizeInWords(void* p) { + virtual unsigned copiedSizeInWords(void* p) + { Thread* t = m->rootThread; object o = static_cast(m->heap->follow(maskAlignedPointer(p))); - assert(t, not objectFixed(t, o)); + assertT(t, not objectFixed(t, o)); - unsigned n = baseSize(t, o, static_cast - (m->heap->follow(objectClass(t, o)))); + unsigned n = baseSize(t, o, m->heap->follow(objectClass(t, o))); if (objectExtended(t, o) or hashTaken(t, o)) { - ++ n; + ++n; } return n; } - virtual void copy(void* srcp, void* dstp) { + virtual void copy(void* srcp, void* dstp) + { Thread* t = m->rootThread; object src = static_cast(m->heap->follow(maskAlignedPointer(srcp))); - assert(t, not objectFixed(t, src)); + assertT(t, not objectFixed(t, src)); - object class_ = static_cast - (m->heap->follow(objectClass(t, src))); + GcClass* class_ = m->heap->follow(objectClass(t, src)); unsigned base = baseSize(t, src, class_); unsigned n = extendedSize(t, src, base); @@ -2989,21 +3417,22 @@ class HeapClient: public Heap::Client { } } - virtual void walk(void* p, Heap::Walker* w) { + virtual void walk(void* p, Heap::Walker* w) + { object o = static_cast(m->heap->follow(maskAlignedPointer(p))); ::walk(m->rootThread, w, o, 0); } - void dispose() { + void dispose() + { m->heap->free(this, sizeof(*this)); } - + private: Machine* m; }; -void -doCollect(Thread* t, Heap::CollectionType type, int pendingAllocation) +void doCollect(Thread* t, Heap::CollectionType type, int pendingAllocation) { expect(t, not t->m->collecting); @@ -3012,14 +3441,17 @@ doCollect(Thread* t, Heap::CollectionType type, int pendingAllocation) #ifdef VM_STRESS bool stress = (t->flags & Thread::StressFlag) != 0; - if (not stress) atomicOr(&(t->flags), Thread::StressFlag); + if (not stress) + atomicOr(&(t->flags), Thread::StressFlag); #endif Machine* m = t->m; m->unsafe = true; - m->heap->collect(type, footprint(m->rootThread), pendingAllocation - - (t->m->heapPoolIndex * ThreadHeapSizeInWords)); + m->heap->collect( + type, + footprint(m->rootThread), + pendingAllocation - (t->m->heapPoolIndex * ThreadHeapSizeInWords)); m->unsafe = false; postCollect(m->rootThread); @@ -3040,24 +3472,24 @@ doCollect(Thread* t, Heap::CollectionType type, int pendingAllocation) } #ifdef VM_STRESS - if (not stress) atomicAnd(&(t->flags), ~Thread::StressFlag); + if (not stress) + atomicAnd(&(t->flags), ~Thread::StressFlag); #endif - object finalizeQueue = t->m->finalizeQueue; + GcFinalizer* finalizeQueue = t->m->finalizeQueue; t->m->finalizeQueue = 0; - for (; finalizeQueue; finalizeQueue = finalizerNext(t, finalizeQueue)) { + for (; finalizeQueue; + finalizeQueue = cast(t, finalizeQueue->next())) { void (*function)(Thread*, object); - memcpy(&function, &finalizerFinalize(t, finalizeQueue), BytesPerWord); - function(t, finalizerTarget(t, finalizeQueue)); + memcpy(&function, &finalizeQueue->finalize(), BytesPerWord); + function(t, finalizeQueue->target()); } - if ((root(t, Machine::ObjectsToFinalize) or root(t, Machine::ObjectsToClean)) - and m->finalizeThread == 0 - and t->state != Thread::ExitState) - { - m->finalizeThread = m->processor->makeThread - (m, root(t, Machine::FinalizerThread), m->rootThread); - + if ((roots(t)->objectsToFinalize() or roots(t)->objectsToClean()) + and m->finalizeThread == 0 and t->state != Thread::ExitState) { + m->finalizeThread = m->processor->makeThread( + m, roots(t)->finalizerThread(), m->rootThread); + addThread(t, m->finalizeThread); if (not startThread(t, m->finalizeThread)) { @@ -3067,19 +3499,17 @@ doCollect(Thread* t, Heap::CollectionType type, int pendingAllocation) } } -uint64_t -invokeLoadClass(Thread* t, uintptr_t* arguments) +uint64_t invokeLoadClass(Thread* t, uintptr_t* arguments) { - object method = reinterpret_cast(arguments[0]); + GcMethod* method = cast(t, reinterpret_cast(arguments[0])); object loader = reinterpret_cast(arguments[1]); object specString = reinterpret_cast(arguments[2]); - return reinterpret_cast - (t->m->processor->invoke(t, method, loader, specString)); + return reinterpret_cast( + t->m->processor->invoke(t, method, loader, specString)); } -bool -isInitializing(Thread* t, object c) +bool isInitializing(Thread* t, GcClass* c) { for (Thread::ClassInitStack* s = t->classInitStack; s; s = s->next) { if (s->class_ == c) { @@ -3089,80 +3519,79 @@ isInitializing(Thread* t, object c) return false; } -object -findInTable(Thread* t, object table, object name, object spec, - object& (*getName)(Thread*, object), - object& (*getSpec)(Thread*, object)) +object findInTable(Thread* t, + GcArray* table, + GcByteArray* name, + GcByteArray* spec, + GcByteArray* (*getName)(Thread*, object), + GcByteArray* (*getSpec)(Thread*, object)) { if (table) { - for (unsigned i = 0; i < arrayLength(t, table); ++i) { - object o = arrayBody(t, table, i); - if (vm::strcmp(&byteArrayBody(t, getName(t, o), 0), - &byteArrayBody(t, name, 0)) == 0 and - vm::strcmp(&byteArrayBody(t, getSpec(t, o), 0), - &byteArrayBody(t, spec, 0)) == 0) - { + for (unsigned i = 0; i < table->length(); ++i) { + object o = table->body()[i]; + if (vm::strcmp(getName(t, o)->body().begin(), name->body().begin()) == 0 + and vm::strcmp(getSpec(t, o)->body().begin(), spec->body().begin()) + == 0) { return o; } } -// fprintf(stderr, "%s %s not in\n", -// &byteArrayBody(t, name, 0), -// &byteArrayBody(t, spec, 0)); + if (false) { + fprintf( + stderr, "%s %s not in\n", name->body().begin(), spec->body().begin()); -// for (unsigned i = 0; i < arrayLength(t, table); ++i) { -// object o = arrayBody(t, table, i); -// fprintf(stderr, "\t%s %s\n", -// &byteArrayBody(t, getName(t, o), 0), -// &byteArrayBody(t, getSpec(t, o), 0)); -// } + for (unsigned i = 0; i < table->length(); ++i) { + object o = table->body()[i]; + fprintf(stderr, + "\t%s %s\n", + getName(t, o)->body().begin(), + getSpec(t, o)->body().begin()); + } + } } return 0; } -void -updatePackageMap(Thread* t, object class_) +void updatePackageMap(Thread* t, GcClass* class_) { PROTECT(t, class_); - if (root(t, Machine::PackageMap) == 0) { - setRoot(t, Machine::PackageMap, makeHashMap(t, 0, 0)); + if (roots(t)->packageMap() == 0) { + GcHashMap* map = makeHashMap(t, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(t)->setPackageMap(t, map); } - object className = vm::className(t, class_); - if ('[' != byteArrayBody(t, className, 0)) { - THREAD_RUNTIME_ARRAY - (t, char, packageName, byteArrayLength(t, className)); + GcByteArray* className = class_->name(); + if ('[' != className->body()[0]) { + THREAD_RUNTIME_ARRAY(t, char, packageName, className->length()); - char* s = reinterpret_cast(&byteArrayBody(t, className, 0)); + char* s = reinterpret_cast(className->body().begin()); char* p = strrchr(s, '/'); if (p) { int length = (p - s) + 1; - memcpy(RUNTIME_ARRAY_BODY(packageName), - &byteArrayBody(t, className, 0), - length); + memcpy( + RUNTIME_ARRAY_BODY(packageName), className->body().begin(), length); RUNTIME_ARRAY_BODY(packageName)[length] = 0; - object key = vm::makeByteArray - (t, "%s", RUNTIME_ARRAY_BODY(packageName)); + GcByteArray* key + = vm::makeByteArray(t, "%s", RUNTIME_ARRAY_BODY(packageName)); PROTECT(t, key); - hashMapRemove - (t, root(t, Machine::PackageMap), key, byteArrayHash, - byteArrayEqual); + hashMapRemove( + t, roots(t)->packageMap(), key, byteArrayHash, byteArrayEqual); - object source = classSource(t, class_); + GcByteArray* source = class_->source(); if (source) { // note that we strip the "file:" prefix, since OpenJDK's // Package.defineSystemPackage expects an unadorned filename: const unsigned PrefixLength = 5; - unsigned sourceNameLength = byteArrayLength(t, source) - - PrefixLength; + unsigned sourceNameLength = source->length() - PrefixLength; THREAD_RUNTIME_ARRAY(t, char, sourceName, sourceNameLength); memcpy(RUNTIME_ARRAY_BODY(sourceName), - &byteArrayBody(t, source, PrefixLength), + &source->body()[PrefixLength], sourceNameLength); source = vm::makeByteArray(t, "%s", RUNTIME_ARRAY_BODY(sourceName)); @@ -3170,65 +3599,69 @@ updatePackageMap(Thread* t, object class_) source = vm::makeByteArray(t, "avian-dummy-package-source"); } - hashMapInsert - (t, root(t, Machine::PackageMap), key, source, byteArrayHash); + hashMapInsert(t, roots(t)->packageMap(), key, source, byteArrayHash); } } } -} // namespace +} // namespace namespace vm { -Machine::Machine(System* system, Heap* heap, Finder* bootFinder, - Finder* appFinder, Processor* processor, Classpath* classpath, - const char** properties, unsigned propertyCount, - const char** arguments, unsigned argumentCount, - unsigned stackSizeInBytes): - vtable(&javaVMVTable), - system(system), - heapClient(new (heap->allocate(sizeof(HeapClient))) - HeapClient(this)), - heap(heap), - bootFinder(bootFinder), - appFinder(appFinder), - processor(processor), - classpath(classpath), - rootThread(0), - exclusive(0), - finalizeThread(0), - jniReferences(0), - propertyCount(propertyCount), - arguments(arguments), - argumentCount(argumentCount), - threadCount(0), - activeCount(0), - liveCount(0), - daemonCount(0), - fixedFootprint(0), - stackSizeInBytes(stackSizeInBytes), - localThread(0), - stateLock(0), - heapLock(0), - classLock(0), - referenceLock(0), - shutdownLock(0), - libraries(0), - errorLog(0), - bootimage(0), - types(0), - roots(0), - finalizers(0), - tenuredFinalizers(0), - finalizeQueue(0), - weakReferences(0), - tenuredWeakReferences(0), - unsafe(false), - collecting(false), - triedBuiltinOnLoad(false), - dumpedHeapOnOOM(false), - alive(true), - heapPoolIndex(0) +Machine::Machine(System* system, + Heap* heap, + Finder* bootFinder, + Finder* appFinder, + Processor* processor, + Classpath* classpath, + const char** properties, + unsigned propertyCount, + const char** arguments, + unsigned argumentCount, + unsigned stackSizeInBytes) + : vtable(&javaVMVTable), + system(system), + heapClient(new (heap->allocate(sizeof(HeapClient))) HeapClient(this)), + heap(heap), + bootFinder(bootFinder), + appFinder(appFinder), + processor(processor), + classpath(classpath), + rootThread(0), + exclusive(0), + finalizeThread(0), + jniReferences(0), + propertyCount(propertyCount), + arguments(arguments), + argumentCount(argumentCount), + threadCount(0), + activeCount(0), + liveCount(0), + daemonCount(0), + fixedFootprint(0), + stackSizeInBytes(stackSizeInBytes), + localThread(0), + stateLock(0), + heapLock(0), + classLock(0), + referenceLock(0), + shutdownLock(0), + libraries(0), + errorLog(0), + bootimage(0), + types(0), + roots(0), + finalizers(0), + tenuredFinalizers(0), + finalizeQueue(0), + weakReferences(0), + tenuredWeakReferences(0), + unsafe(false), + collecting(false), + triedBuiltinOnLoad(false), + dumpedHeapOnOOM(false), + alive(true), + heapPoolIndex(0) { heap->setClient(heapClient); @@ -3236,30 +3669,31 @@ Machine::Machine(System* system, Heap* heap, Finder* bootFinder, // Copying the properties memory (to avoid memory crashes) this->properties = (char**)heap->allocate(sizeof(char*) * propertyCount); - for (unsigned int i = 0; i < propertyCount; i++) - { - size_t length = strlen(properties[i]) + 1; // +1 for null-terminating char + for (unsigned int i = 0; i < propertyCount; i++) { + size_t length = strlen(properties[i]) + 1; // +1 for null-terminating char this->properties[i] = (char*)heap->allocate(sizeof(char) * length); memcpy(this->properties[i], properties[i], length); } const char* bootstrapProperty = findProperty(this, BOOTSTRAP_PROPERTY); - const char* bootstrapPropertyDup = bootstrapProperty ? strdup(bootstrapProperty) : 0; - const char* bootstrapPropertyEnd = bootstrapPropertyDup + (bootstrapPropertyDup ? strlen(bootstrapPropertyDup) : 0); + const char* bootstrapPropertyDup + = bootstrapProperty ? strdup(bootstrapProperty) : 0; + const char* bootstrapPropertyEnd + = bootstrapPropertyDup + + (bootstrapPropertyDup ? strlen(bootstrapPropertyDup) : 0); char* codeLibraryName = (char*)bootstrapPropertyDup; char* codeLibraryNameEnd = 0; - if (codeLibraryName && (codeLibraryNameEnd = strchr(codeLibraryName, system->pathSeparator()))) + if (codeLibraryName && (codeLibraryNameEnd + = strchr(codeLibraryName, system->pathSeparator()))) *codeLibraryNameEnd = 0; - if (not system->success(system->make(&localThread)) or - not system->success(system->make(&stateLock)) or - not system->success(system->make(&heapLock)) or - not system->success(system->make(&classLock)) or - not system->success(system->make(&referenceLock)) or - not system->success(system->make(&shutdownLock)) or - not system->success - (system->load(&libraries, bootstrapPropertyDup))) - { + if (not system->success(system->make(&localThread)) + or not system->success(system->make(&stateLock)) + or not system->success(system->make(&heapLock)) + or not system->success(system->make(&classLock)) + or not system->success(system->make(&referenceLock)) + or not system->success(system->make(&shutdownLock)) + or not system->success(system->load(&libraries, bootstrapPropertyDup))) { system->abort(); } @@ -3275,12 +3709,11 @@ Machine::Machine(System* system, Heap* heap, Finder* bootFinder, libraries->setNext(additionalLibrary); } - if(bootstrapPropertyDup) + if (bootstrapPropertyDup) free((void*)bootstrapPropertyDup); } -void -Machine::dispose() +void Machine::dispose() { localThread->dispose(); stateLock->dispose(); @@ -3309,8 +3742,7 @@ Machine::dispose() heap->free(arguments, sizeof(const char*) * argumentCount); - for (unsigned int i = 0; i < propertyCount; i++) - { + for (unsigned int i = 0; i < propertyCount; i++) { heap->free(properties[i], sizeof(char) * (strlen(properties[i]) + 1)); } heap->free(properties, sizeof(const char*) * propertyCount); @@ -3320,41 +3752,41 @@ Machine::dispose() heap->free(this, sizeof(*this)); } -Thread::Thread(Machine* m, object javaThread, Thread* parent): - vtable(&(m->jniEnvVTable)), - m(m), - parent(parent), - peer(0), - child(0), - waitNext(0), - state(NoState), - criticalLevel(0), - systemThread(0), - lock(0), - javaThread(javaThread), - exception(0), - heapIndex(0), - heapOffset(0), - protector(0), - classInitStack(0), - libraryLoadStack(0), - runnable(this), - defaultHeap(static_cast - (m->heap->allocate(ThreadHeapSizeInBytes))), - heap(defaultHeap), - backupHeapIndex(0), - flags(ActiveFlag) -{ } +Thread::Thread(Machine* m, GcThread* javaThread, Thread* parent) + : vtable(&(m->jniEnvVTable)), + m(m), + parent(parent), + peer(0), + child(0), + waitNext(0), + state(NoState), + criticalLevel(0), + systemThread(0), + lock(0), + javaThread(javaThread), + exception(0), + heapIndex(0), + heapOffset(0), + protector(0), + classInitStack(0), + libraryLoadStack(0), + runnable(this), + defaultHeap( + static_cast(m->heap->allocate(ThreadHeapSizeInBytes))), + heap(defaultHeap), + backupHeapIndex(0), + flags(ActiveFlag) +{ +} -void -Thread::init() +void Thread::init() { memset(defaultHeap, 0, ThreadHeapSizeInBytes); memset(backupHeap, 0, ThreadBackupHeapSizeInBytes); if (parent == 0) { - assert(this, m->rootThread == 0); - assert(this, javaThread == 0); + assertT(this, m->rootThread == 0); + assertT(this, javaThread == 0); m->rootThread = this; m->unsafe = true; @@ -3368,8 +3800,7 @@ Thread::init() const char* imageFunctionName = findProperty(m, "avian.bootimage"); if (imageFunctionName) { bool lzma = strncmp("lzma:", imageFunctionName, 5) == 0; - const char* symbolName - = lzma ? imageFunctionName + 5 : imageFunctionName; + const char* symbolName = lzma ? imageFunctionName + 5 : imageFunctionName; void* imagep = m->libraries->resolve(symbolName); if (imagep) { @@ -3380,9 +3811,8 @@ Thread::init() uint8_t* imageBytes = imageFunction(&size); if (lzma) { #ifdef AVIAN_USE_LZMA - m->bootimage = image = reinterpret_cast - (decodeLZMA - (m->system, m->heap, imageBytes, size, &(m->bootimageSize))); + m->bootimage = image = reinterpret_cast(decodeLZMA( + m->system, m->heap, imageBytes, size, &(m->bootimageSize))); #else abort(this); #endif @@ -3414,13 +3844,29 @@ Thread::init() boot(this); } - setRoot(this, Machine::ByteArrayMap, makeWeakHashMap(this, 0, 0)); - setRoot(this, Machine::MonitorMap, makeWeakHashMap(this, 0, 0)); + GcWeakHashMap* map = makeWeakHashMap(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setByteArrayMap(this, map->as(this)); - setRoot(this, Machine::ClassRuntimeDataTable, makeVector(this, 0, 0)); - setRoot(this, Machine::MethodRuntimeDataTable, makeVector(this, 0, 0)); - setRoot(this, Machine::JNIMethodTable, makeVector(this, 0, 0)); - setRoot(this, Machine::JNIFieldTable, makeVector(this, 0, 0)); + map = makeWeakHashMap(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setMonitorMap(this, map->as(this)); + + GcVector* v = makeVector(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setClassRuntimeDataTable(this, v); + + v = makeVector(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setMethodRuntimeDataTable(this, v); + + v = makeVector(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setJNIMethodTable(this, v); + + v = makeVector(this, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(this)->setJNIFieldTable(this, v); m->localThread->set(this); } @@ -3428,70 +3874,65 @@ Thread::init() expect(this, m->system->success(m->system->make(&lock))); } -void -Thread::exit() +void Thread::exit() { - if (state != Thread::ExitState and - state != Thread::ZombieState) - { + if (state != Thread::ExitState and state != Thread::ZombieState) { enter(this, Thread::ExclusiveState); if (m->liveCount == 1) { turnOffTheLights(this); } else { - threadPeer(this, javaThread) = 0; + javaThread->peer() = 0; enter(this, Thread::ZombieState); } } } -void -Thread::dispose() +void Thread::dispose() { if (lock) { lock->dispose(); } - + if (systemThread) { systemThread->dispose(); } - -- m->threadCount; + --m->threadCount; m->heap->free(defaultHeap, ThreadHeapSizeInBytes); m->processor->dispose(this); } -void -shutDown(Thread* t) +void shutDown(Thread* t) { ACQUIRE(t, t->m->shutdownLock); - object hooks = root(t, Machine::ShutdownHooks); + GcPair* hooks = roots(t)->shutdownHooks(); PROTECT(t, hooks); - setRoot(t, Machine::ShutdownHooks, 0); + roots(t)->setShutdownHooks(t, 0); - object h = hooks; + GcPair* h = hooks; PROTECT(t, h); - for (; h; h = pairSecond(t, h)) { - startThread(t, pairFirst(t, h)); + for (; h; h = cast(t, h->second())) { + startThread(t, cast(t, h->first())); } // wait for hooks to exit h = hooks; - for (; h; h = pairSecond(t, h)) { + for (; h; h = cast(t, h->second())) { while (true) { - Thread* ht = reinterpret_cast(threadPeer(t, pairFirst(t, h))); + Thread* ht + = reinterpret_cast(cast(t, h->first())->peer()); - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); - if (ht == 0 - or ht->state == Thread::ZombieState - or ht->state == Thread::JoinedState) - { + if (ht == 0 or ht->state == Thread::ZombieState + or ht->state == Thread::JoinedState) { break; } else { ENTER(t, Thread::IdleState); @@ -3502,17 +3943,17 @@ shutDown(Thread* t) } // tell finalize thread to exit and wait for it to do so - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); Thread* finalizeThread = t->m->finalizeThread; if (finalizeThread) { t->m->finalizeThread = 0; t->m->stateLock->notifyAll(t->systemThread); while (finalizeThread->state != Thread::ZombieState - and finalizeThread->state != Thread::JoinedState) - { + and finalizeThread->state != Thread::JoinedState) { ENTER(t, Thread::IdleState); - t->m->stateLock->wait(t->systemThread, 0); + t->m->stateLock->wait(t->systemThread, 0); } } } @@ -3521,7 +3962,8 @@ shutDown(Thread* t) // todo: be more aggressive about killing daemon threads, e.g. at // any GC point, not just at waits/sleeps - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); t->m->alive = false; @@ -3529,12 +3971,12 @@ shutDown(Thread* t) } } -void -enter(Thread* t, Thread::State s) +void enter(Thread* t, Thread::State s) { stress(t); - if (s == t->state) return; + if (s == t->state) + return; if (t->state == Thread::ExitState) { // once in exit state, we stay that way @@ -3542,16 +3984,16 @@ enter(Thread* t, Thread::State s) } #ifdef USE_ATOMIC_OPERATIONS -# define INCREMENT atomicIncrement -# define ACQUIRE_LOCK ACQUIRE_RAW(t, t->m->stateLock) -# define STORE_LOAD_MEMORY_BARRIER storeLoadMemoryBarrier() +#define INCREMENT atomicIncrement +#define ACQUIRE_LOCK ACQUIRE_RAW(t, t->m->stateLock) +#define STORE_LOAD_MEMORY_BARRIER storeLoadMemoryBarrier() #else -# define INCREMENT(pointer, value) *(pointer) += value; -# define ACQUIRE_LOCK -# define STORE_LOAD_MEMORY_BARRIER +#define INCREMENT(pointer, value) *(pointer) += value; +#define ACQUIRE_LOCK +#define STORE_LOAD_MEMORY_BARRIER ACQUIRE_RAW(t, t->m->stateLock); -#endif // not USE_ATOMIC_OPERATIONS +#endif // not USE_ATOMIC_OPERATIONS switch (s) { case Thread::ExclusiveState: { @@ -3564,18 +4006,20 @@ enter(Thread* t, Thread::State s) } switch (t->state) { - case Thread::ActiveState: break; + case Thread::ActiveState: + break; case Thread::IdleState: { INCREMENT(&(t->m->activeCount), 1); } break; - default: abort(t); + default: + abort(t); } t->state = Thread::ExclusiveState; t->m->exclusive = t; - + STORE_LOAD_MEMORY_BARRIER; while (t->m->activeCount > 1) { @@ -3586,7 +4030,7 @@ enter(Thread* t, Thread::State s) case Thread::IdleState: if (LIKELY(t->state == Thread::ActiveState)) { // fast path - assert(t, t->m->activeCount > 0); + assertT(t, t->m->activeCount > 0); INCREMENT(&(t->m->activeCount), -1); t->state = s; @@ -3607,24 +4051,26 @@ enter(Thread* t, Thread::State s) switch (t->state) { case Thread::ExclusiveState: { - assert(t, t->m->exclusive == t); + assertT(t, t->m->exclusive == t); t->m->exclusive = 0; } break; - case Thread::ActiveState: break; + case Thread::ActiveState: + break; - default: abort(t); + default: + abort(t); } - assert(t, t->m->activeCount > 0); + assertT(t, t->m->activeCount > 0); INCREMENT(&(t->m->activeCount), -1); if (s == Thread::ZombieState) { - assert(t, t->m->liveCount > 0); - -- t->m->liveCount; + assertT(t, t->m->liveCount > 0); + --t->m->liveCount; if (t->flags & Thread::DaemonFlag) { - -- t->m->daemonCount; + --t->m->daemonCount; } } @@ -3649,11 +4095,12 @@ enter(Thread* t, Thread::State s) } } - { ACQUIRE_LOCK; + { + ACQUIRE_LOCK; switch (t->state) { case Thread::ExclusiveState: { - assert(t, t->m->exclusive == t); + assertT(t, t->m->exclusive == t); t->state = s; t->m->exclusive = 0; @@ -3669,33 +4116,37 @@ enter(Thread* t, Thread::State s) INCREMENT(&(t->m->activeCount), 1); if (t->state == Thread::NoState) { - ++ t->m->liveCount; - ++ t->m->threadCount; + ++t->m->liveCount; + ++t->m->threadCount; } t->state = s; } break; - default: abort(t); + default: + abort(t); } - } break; + } + break; case Thread::ExitState: { ACQUIRE_LOCK; switch (t->state) { case Thread::ExclusiveState: { - assert(t, t->m->exclusive == t); + assertT(t, t->m->exclusive == t); // exit state should also be exclusive, so don't set exclusive = 0 t->m->stateLock->notifyAll(t->systemThread); } break; - case Thread::ActiveState: break; + case Thread::ActiveState: + break; - default: abort(t); + default: + abort(t); } - assert(t, t->m->activeCount > 0); + assertT(t, t->m->activeCount > 0); INCREMENT(&(t->m->activeCount), -1); t->state = s; @@ -3705,36 +4156,43 @@ enter(Thread* t, Thread::State s) } } break; - default: abort(t); + default: + abort(t); } } -object -allocate2(Thread* t, unsigned sizeInBytes, bool objectMask) +object allocate2(Thread* t, unsigned sizeInBytes, bool objectMask) { - return allocate3 - (t, t->m->heap, - ceilingDivide(sizeInBytes, BytesPerWord) > ThreadHeapSizeInWords ? - Machine::FixedAllocation : Machine::MovableAllocation, - sizeInBytes, objectMask); + return allocate3( + t, + t->m->heap, + ceilingDivide(sizeInBytes, BytesPerWord) > ThreadHeapSizeInWords + ? Machine::FixedAllocation + : Machine::MovableAllocation, + sizeInBytes, + objectMask); } -object -allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, - unsigned sizeInBytes, bool objectMask) +object allocate3(Thread* t, + Allocator* allocator, + Machine::AllocationType type, + unsigned sizeInBytes, + bool objectMask) { expect(t, t->criticalLevel == 0); if (UNLIKELY(t->flags & Thread::UseBackupHeapFlag)) { - expect(t, t->backupHeapIndex + ceilingDivide(sizeInBytes, BytesPerWord) + expect(t, + t->backupHeapIndex + ceilingDivide(sizeInBytes, BytesPerWord) <= ThreadBackupHeapSizeInWords); - + object o = reinterpret_cast(t->backupHeap + t->backupHeapIndex); t->backupHeapIndex += ceilingDivide(sizeInBytes, BytesPerWord); fieldAtOffset(o, 0) = 0; return o; } else if (UNLIKELY(t->flags & Thread::TracingFlag)) { - expect(t, t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) + expect(t, + t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) <= ThreadHeapSizeInWords); return allocateSmall(t, sizeInBytes); } @@ -3750,19 +4208,17 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, t->m->stateLock->wait(t->systemThread, 0); } } - + do { switch (type) { case Machine::MovableAllocation: if (t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) - > ThreadHeapSizeInWords) - { + > ThreadHeapSizeInWords) { t->heap = 0; if ((not t->m->heap->limitExceeded()) - and t->m->heapPoolIndex < ThreadHeapPoolSize) - { - t->heap = static_cast - (t->m->heap->tryAllocate(ThreadHeapSizeInBytes)); + and t->m->heapPoolIndex < ThreadHeapPoolSize) { + t->heap = static_cast( + t->m->heap->tryAllocate(ThreadHeapSizeInBytes)); if (t->heap) { memset(t->heap, 0, ThreadHeapSizeInBytes); @@ -3776,8 +4232,7 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, break; case Machine::FixedAllocation: - if (t->m->fixedFootprint + sizeInBytes > FixedFootprintThresholdInBytes) - { + if (t->m->fixedFootprint + sizeInBytes > FixedFootprintThresholdInBytes) { t->heap = 0; } break; @@ -3786,8 +4241,8 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, break; } - int pendingAllocation = t->m->heap->fixedFootprint - (ceilingDivide(sizeInBytes, BytesPerWord), objectMask); + int pendingAllocation = t->m->heap->fixedFootprint( + ceilingDivide(sizeInBytes, BytesPerWord), objectMask); if (t->heap == 0 or t->m->heap->limitExceeded(pendingAllocation)) { // fprintf(stderr, "gc"); @@ -3796,11 +4251,11 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, } if (t->m->heap->limitExceeded(pendingAllocation)) { - throw_(t, root(t, Machine::OutOfMemoryError)); + throw_(t, roots(t)->outOfMemoryError()); } } while (type == Machine::MovableAllocation and t->heapIndex + ceilingDivide(sizeInBytes, BytesPerWord) - > ThreadHeapSizeInWords); + > ThreadHeapSizeInWords); switch (type) { case Machine::MovableAllocation: { @@ -3808,24 +4263,22 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, } case Machine::FixedAllocation: { - object o = static_cast - (t->m->heap->allocateFixed - (allocator, ceilingDivide(sizeInBytes, BytesPerWord), objectMask)); + object o = static_cast(t->m->heap->allocateFixed( + allocator, ceilingDivide(sizeInBytes, BytesPerWord), objectMask)); memset(o, 0, sizeInBytes); alias(o, 0) = FixedMark; - - t->m->fixedFootprint += t->m->heap->fixedFootprint - (ceilingDivide(sizeInBytes, BytesPerWord), objectMask); - + + t->m->fixedFootprint += t->m->heap->fixedFootprint( + ceilingDivide(sizeInBytes, BytesPerWord), objectMask); + return o; } case Machine::ImmortalAllocation: { - object o = static_cast - (t->m->heap->allocateImmortalFixed - (allocator, ceilingDivide(sizeInBytes, BytesPerWord), objectMask)); + object o = static_cast(t->m->heap->allocateImmortalFixed( + allocator, ceilingDivide(sizeInBytes, BytesPerWord), objectMask)); memset(o, 0, sizeInBytes); @@ -3834,17 +4287,17 @@ allocate3(Thread* t, Allocator* allocator, Machine::AllocationType type, return o; } - default: abort(t); + default: + abort(t); } } -void -collect(Thread* t, Heap::CollectionType type, int pendingAllocation) +void collect(Thread* t, Heap::CollectionType type, int pendingAllocation) { ENTER(t, Thread::ExclusiveState); unsigned pending = pendingAllocation - - (t->m->heapPoolIndex * ThreadHeapSizeInWords); + - (t->m->heapPoolIndex * ThreadHeapSizeInWords); if (t->m->heap->limitExceeded(pending)) { type = Heap::MajorCollection; @@ -3859,32 +4312,30 @@ collect(Thread* t, Heap::CollectionType type, int pendingAllocation) } } -object -makeNewGeneral(Thread* t, object class_) +object makeNewGeneral(Thread* t, GcClass* class_) { - assert(t, t->state == Thread::ActiveState); + assertT(t, t->state == Thread::ActiveState); PROTECT(t, class_); object instance = makeNew(t, class_); PROTECT(t, instance); - if (classVmFlags(t, class_) & WeakReferenceFlag) { + if (class_->vmFlags() & WeakReferenceFlag) { ACQUIRE(t, t->m->referenceLock); - - jreferenceVmNext(t, instance) = t->m->weakReferences; - t->m->weakReferences = instance; + + cast(t, instance)->vmNext() = t->m->weakReferences; + t->m->weakReferences = cast(t, instance); } - if (classVmFlags(t, class_) & HasFinalizerFlag) { + if (class_->vmFlags() & HasFinalizerFlag) { addFinalizer(t, instance, 0); } return instance; } -void -popResources(Thread* t) +void popResources(Thread* t) { while (t->resource != t->checkpoint->resource) { Thread::Resource* r = t->resource; @@ -3895,30 +4346,27 @@ popResources(Thread* t) t->protector = t->checkpoint->protector; } -object -makeByteArrayV(Thread* t, const char* format, va_list a, int size) +GcByteArray* makeByteArrayV(Thread* t, const char* format, va_list a, int size) { THREAD_RUNTIME_ARRAY(t, char, buffer, size); - + int r = vm::vsnprintf(RUNTIME_ARRAY_BODY(buffer), size - 1, format, a); if (r >= 0 and r < size - 1) { - object s = makeByteArray(t, strlen(RUNTIME_ARRAY_BODY(buffer)) + 1); - memcpy(&byteArrayBody(t, s, 0), RUNTIME_ARRAY_BODY(buffer), - byteArrayLength(t, s)); + GcByteArray* s = makeByteArray(t, strlen(RUNTIME_ARRAY_BODY(buffer)) + 1); + memcpy(s->body().begin(), RUNTIME_ARRAY_BODY(buffer), s->length()); return s; } else { return 0; } } -object -makeByteArray(Thread* t, const char* format, ...) +GcByteArray* makeByteArray(Thread* t, const char* format, ...) { int size = 256; while (true) { va_list a; va_start(a, format); - object s = makeByteArrayV(t, format, a, size); + GcByteArray* s = makeByteArrayV(t, format, a, size); va_end(a); if (s) { @@ -3929,41 +4377,46 @@ makeByteArray(Thread* t, const char* format, ...) } } -object -makeString(Thread* t, const char* format, ...) +GcString* makeString(Thread* t, const char* format, ...) { int size = 256; while (true) { va_list a; va_start(a, format); - object s = makeByteArrayV(t, format, a, size); + GcByteArray* s = makeByteArrayV(t, format, a, size); va_end(a); if (s) { - return t->m->classpath->makeString(t, s, 0, byteArrayLength(t, s) - 1); + return t->m->classpath->makeString(t, s, 0, s->length() - 1); } else { size *= 2; } } } -int -stringUTFLength(Thread* t, object string, unsigned start, unsigned length) +int stringUTFLength(Thread* t, + GcString* string, + unsigned start, + unsigned length) { unsigned result = 0; if (length) { - object data = stringData(t, string); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { + object data = string->data(); + if (objectClass(t, data) == type(t, GcByteArray::Type)) { result = length; } else { + GcCharArray* a = cast(t, data); for (unsigned i = 0; i < length; ++i) { - uint16_t c = charArrayBody - (t, data, stringOffset(t, string) + start + i); - if (c == 0) result += 1; // null char (was 2 bytes in Java) - else if (c < 0x80) result += 1; // ASCII char - else if (c < 0x800) result += 2; // two-byte char - else result += 3; // three-byte char + uint16_t c = a->body()[string->offset(t) + start + i]; + if (c == 0) + result += 1; // null char (was 2 bytes in Java) + else if (c < 0x80) + result += 1; // ASCII char + else if (c < 0x800) + result += 2; // two-byte char + else + result += 3; // three-byte char } } } @@ -3971,100 +4424,109 @@ stringUTFLength(Thread* t, object string, unsigned start, unsigned length) return result; } -void -stringChars(Thread* t, object string, unsigned start, unsigned length, - char* chars) +void stringChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + char* chars) { if (length) { - object data = stringData(t, string); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { - memcpy(chars, - &byteArrayBody(t, data, stringOffset(t, string) + start), - length); + object data = string->data(); + if (objectClass(t, data) == type(t, GcByteArray::Type)) { + GcByteArray* b = cast(t, data); + memcpy(chars, &b->body()[string->offset(t) + start], length); } else { + GcCharArray* c = cast(t, data); for (unsigned i = 0; i < length; ++i) { - chars[i] = charArrayBody(t, data, stringOffset(t, string) + start + i); + chars[i] = c->body()[string->offset(t) + start + i]; } } } chars[length] = 0; } -void -stringChars(Thread* t, object string, unsigned start, unsigned length, - uint16_t* chars) +void stringChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + uint16_t* chars) { if (length) { - object data = stringData(t, string); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { + object data = string->data(); + if (objectClass(t, data) == type(t, GcByteArray::Type)) { + GcByteArray* b = cast(t, data); for (unsigned i = 0; i < length; ++i) { - chars[i] = byteArrayBody(t, data, stringOffset(t, string) + start + i); + chars[i] = b->body()[string->offset(t) + start + i]; } } else { + GcCharArray* c = cast(t, data); memcpy(chars, - &charArrayBody(t, data, stringOffset(t, string) + start), + &c->body()[string->offset(t) + start], length * sizeof(uint16_t)); } } chars[length] = 0; } -void -stringUTFChars(Thread* t, object string, unsigned start, unsigned length, - char* chars, unsigned charsLength UNUSED) +void stringUTFChars(Thread* t, + GcString* string, + unsigned start, + unsigned length, + char* chars, + unsigned charsLength UNUSED) { - assert(t, static_cast - (stringUTFLength(t, string, start, length)) == charsLength); + assertT(t, + static_cast(stringUTFLength(t, string, start, length)) + == charsLength); - object data = stringData(t, string); - if (objectClass(t, data) == type(t, Machine::ByteArrayType)) { - memcpy(chars, - &byteArrayBody(t, data, stringOffset(t, string) + start), - length); - chars[length] = 0; + object data = string->data(); + if (objectClass(t, data) == type(t, GcByteArray::Type)) { + GcByteArray* b = cast(t, data); + memcpy(chars, &b->body()[string->offset(t) + start], length); + chars[length] = 0; } else { + GcCharArray* cs = cast(t, data); int j = 0; for (unsigned i = 0; i < length; ++i) { - uint16_t c = charArrayBody - (t, data, stringOffset(t, string) + start + i); - if(!c) { // null char + uint16_t c = cs->body()[string->offset(t) + start + i]; + if (!c) { // null char chars[j++] = 0; } else if (c < 0x80) { // ASCII char chars[j++] = static_cast(c); - } else if (c < 0x800) { // two-byte char + } else if (c < 0x800) { // two-byte char chars[j++] = static_cast(0x0c0 | (c >> 6)); chars[j++] = static_cast(0x080 | (c & 0x03f)); - } else { // three-byte char + } else { // three-byte char chars[j++] = static_cast(0x0e0 | ((c >> 12) & 0x0f)); chars[j++] = static_cast(0x080 | ((c >> 6) & 0x03f)); chars[j++] = static_cast(0x080 | (c & 0x03f)); } } chars[j] = 0; - } + } } -uint64_t -resolveBootstrap(Thread* t, uintptr_t* arguments) +uint64_t resolveBootstrap(Thread* t, uintptr_t* arguments) { - object name = reinterpret_cast(arguments[0]); + GcByteArray* name + = cast(t, reinterpret_cast(arguments[0])); - resolveSystemClass(t, root(t, Machine::BootLoader), name); + resolveSystemClass(t, roots(t)->bootLoader(), name); return 1; } -bool -isAssignableFrom(Thread* t, object a, object b) +bool isAssignableFrom(Thread* t, GcClass* a, GcClass* b) { - assert(t, a); - assert(t, b); + assertT(t, a); + assertT(t, b); - if (a == b) return true; + if (a == b) + return true; - if (classFlags(t, a) & ACC_INTERFACE) { - if (classVmFlags(t, b) & BootstrapFlag) { - uintptr_t arguments[] = { reinterpret_cast(className(t, b)) }; + if (a->flags() & ACC_INTERFACE) { + if (b->vmFlags() & BootstrapFlag) { + uintptr_t arguments[] = {reinterpret_cast(b->name())}; if (run(t, resolveBootstrap, arguments) == 0) { t->exception = 0; @@ -4072,24 +4534,22 @@ isAssignableFrom(Thread* t, object a, object b) } } - object itable = classInterfaceTable(t, b); + GcArray* itable = cast(t, b->interfaceTable()); if (itable) { - unsigned stride = (classFlags(t, b) & ACC_INTERFACE) ? 1 : 2; - for (unsigned i = 0; i < arrayLength(t, itable); i += stride) { - if (arrayBody(t, itable, i) == a) { + unsigned stride = (b->flags() & ACC_INTERFACE) ? 1 : 2; + for (unsigned i = 0; i < itable->length(); i += stride) { + if (itable->body()[i] == a) { return true; } } } - } else if (classArrayDimensions(t, a)) { - if (classArrayDimensions(t, b)) { - return isAssignableFrom - (t, classStaticTable(t, a), classStaticTable(t, b)); + } else if (a->arrayDimensions()) { + if (b->arrayDimensions()) { + return isAssignableFrom( + t, a->arrayElementClass(), b->arrayElementClass()); } - } else if ((classVmFlags(t, a) & PrimitiveFlag) - == (classVmFlags(t, b) & PrimitiveFlag)) - { - for (; b; b = classSuper(t, b)) { + } else if ((a->vmFlags() & PrimitiveFlag) == (b->vmFlags() & PrimitiveFlag)) { + for (; b; b = b->super()) { if (b == a) { return true; } @@ -4099,8 +4559,7 @@ isAssignableFrom(Thread* t, object a, object b) return false; } -bool -instanceOf(Thread* t, object class_, object o) +bool instanceOf(Thread* t, GcClass* class_, object o) { if (o == 0) { return false; @@ -4109,24 +4568,22 @@ instanceOf(Thread* t, object class_, object o) } } -object -classInitializer(Thread* t, object class_) +GcMethod* classInitializer(Thread* t, GcClass* class_) { - if (classMethodTable(t, class_)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, class_)); ++i) - { - object o = arrayBody(t, classMethodTable(t, class_), i); + if (GcArray* mtable = cast(t, class_->methodTable())) { + PROTECT(t, mtable); + for (unsigned i = 0; i < mtable->length(); ++i) { + GcMethod* o = cast(t, mtable->body()[i]); - if (methodVmFlags(t, o) & ClassInitFlag) { + if (o->vmFlags() & ClassInitFlag) { return o; - } + } } } return 0; } -unsigned -fieldCode(Thread* t, unsigned javaCode) +unsigned fieldCode(Thread* t, unsigned javaCode) { switch (javaCode) { case 'B': @@ -4151,12 +4608,12 @@ fieldCode(Thread* t, unsigned javaCode) case '[': return ObjectField; - default: abort(t); + default: + abort(t); } } -unsigned -fieldType(Thread* t, unsigned code) +unsigned fieldType(Thread* t, unsigned code) { switch (code) { case VoidField: @@ -4178,12 +4635,12 @@ fieldType(Thread* t, unsigned code) case ObjectField: return POINTER_TYPE; - default: abort(t); + default: + abort(t); } } -unsigned -primitiveSize(Thread* t, unsigned code) +unsigned primitiveSize(Thread* t, unsigned code) { switch (code) { case VoidField: @@ -4201,21 +4658,27 @@ primitiveSize(Thread* t, unsigned code) case LongField: return 8; - default: abort(t); + default: + abort(t); } } -object -parseClass(Thread* t, object loader, const uint8_t* data, unsigned size, - Machine::Type throwType) +GcClass* parseClass(Thread* t, + GcClassLoader* loader, + const uint8_t* data, + unsigned size, + Gc::Type throwType) { PROTECT(t, loader); - class Client: public Stream::Client { + class Client : public Stream::Client { public: - Client(Thread* t): t(t) { } + Client(Thread* t) : t(t) + { + } - virtual void NO_RETURN handleError() { + virtual void NO_RETURN handleError() + { abort(t); } @@ -4227,59 +4690,61 @@ parseClass(Thread* t, object loader, const uint8_t* data, unsigned size, uint32_t magic = s.read4(); expect(t, magic == 0xCAFEBABE); - unsigned minorVer = s.read2(); // minor version - unsigned majorVer = s.read2(); // major version - if(DebugClassReader) { + unsigned minorVer = s.read2(); // minor version + unsigned majorVer = s.read2(); // major version + if (DebugClassReader) { fprintf(stderr, "read class (minor %d major %d)\n", minorVer, majorVer); } - object pool = parsePool(t, s); + GcSingleton* pool = parsePool(t, s); PROTECT(t, pool); unsigned flags = s.read2(); unsigned name = s.read2(); - object class_ = makeClass(t, - flags, - 0, // VM flags - 0, // fixed size - 0, // array size - 0, // array dimensions - 0, // runtime data index - 0, // object mask - referenceName - (t, singletonObject(t, pool, name - 1)), - 0, // source file - 0, // super - 0, // interfaces - 0, // vtable - 0, // fields - 0, // methods - 0, // addendum - 0, // static table - loader, - 0, // source - 0);// vtable length + GcClass* class_ = (GcClass*)makeClass( + t, + flags, + 0, // VM flags + 0, // fixed size + 0, // array size + 0, // array dimensions + 0, // array element class + 0, // runtime data index + 0, // object mask + cast(t, singletonObject(t, pool, name - 1))->name(), + 0, // source file + 0, // super + 0, // interfaces + 0, // vtable + 0, // fields + 0, // methods + 0, // addendum + 0, // static table + loader, + 0, // source + 0); // vtable length PROTECT(t, class_); - + unsigned super = s.read2(); if (super) { - object sc = resolveClass - (t, loader, referenceName(t, singletonObject(t, pool, super - 1)), - true, throwType); + GcClass* sc = resolveClass( + t, + loader, + cast(t, singletonObject(t, pool, super - 1))->name(), + true, + throwType); - set(t, class_, ClassSuper, sc); + class_->setSuper(t, sc); - classVmFlags(t, class_) - |= (classVmFlags(t, sc) - & (ReferenceFlag | WeakReferenceFlag | HasFinalizerFlag - | NeedInitFlag)); + class_->vmFlags() |= (sc->vmFlags() & (ReferenceFlag | WeakReferenceFlag + | HasFinalizerFlag | NeedInitFlag)); } - if(DebugClassReader) { + if (DebugClassReader) { fprintf(stderr, " flags %d name %d super %d\n", flags, name, super); } - + parseInterfaceTable(t, s, class_, pool, throwType); parseFieldTable(t, s, class_, pool); @@ -4288,28 +4753,28 @@ parseClass(Thread* t, object loader, const uint8_t* data, unsigned size, parseAttributeTable(t, s, class_, pool); - object vtable = classVirtualTable(t, class_); - unsigned vtableLength = (vtable ? arrayLength(t, vtable) : 0); + GcArray* vtable = cast(t, class_->virtualTable()); + unsigned vtableLength = (vtable ? vtable->length() : 0); - object real = t->m->processor->makeClass - (t, - classFlags(t, class_), - classVmFlags(t, class_), - classFixedSize(t, class_), - classArrayElementSize(t, class_), - classArrayDimensions(t, class_), - classObjectMask(t, class_), - className(t, class_), - classSourceFile(t, class_), - classSuper(t, class_), - classInterfaceTable(t, class_), - classVirtualTable(t, class_), - classFieldTable(t, class_), - classMethodTable(t, class_), - classAddendum(t, class_), - classStaticTable(t, class_), - classLoader(t, class_), - vtableLength); + GcClass* real = t->m->processor->makeClass(t, + class_->flags(), + class_->vmFlags(), + class_->fixedSize(), + class_->arrayElementSize(), + class_->arrayDimensions(), + class_->arrayElementClass(), + class_->objectMask(), + class_->name(), + class_->sourceFile(), + class_->super(), + class_->interfaceTable(), + class_->virtualTable(), + class_->fieldTable(), + class_->methodTable(), + class_->addendum(), + class_->staticTable(), + class_->loader(), + vtableLength); PROTECT(t, real); @@ -4317,86 +4782,95 @@ parseClass(Thread* t, object loader, const uint8_t* data, unsigned size, updateClassTables(t, real, class_); - if (root(t, Machine::PoolMap)) { - object bootstrapClass = hashMapFind - (t, root(t, Machine::BootstrapClassMap), className(t, class_), - byteArrayHash, byteArrayEqual); + if (roots(t)->poolMap()) { + object bootstrapClass = hashMapFind(t, + roots(t)->bootstrapClassMap(), + class_->name(), + byteArrayHash, + byteArrayEqual); - hashMapInsert - (t, root(t, Machine::PoolMap), bootstrapClass ? bootstrapClass : real, - pool, objectHash); + hashMapInsert(t, + roots(t)->poolMap(), + bootstrapClass ? bootstrapClass : real, + pool, + objectHash); } return real; } -uint64_t -runParseClass(Thread* t, uintptr_t* arguments) +uint64_t runParseClass(Thread* t, uintptr_t* arguments) { - object loader = reinterpret_cast(arguments[0]); + GcClassLoader* loader + = cast(t, reinterpret_cast(arguments[0])); System::Region* region = reinterpret_cast(arguments[1]); - Machine::Type throwType = static_cast(arguments[2]); + Gc::Type throwType = static_cast(arguments[2]); - return reinterpret_cast - (parseClass(t, loader, region->start(), region->length(), throwType)); + return reinterpret_cast( + parseClass(t, loader, region->start(), region->length(), throwType)); } -object -resolveSystemClass(Thread* t, object loader, object spec, bool throw_, - Machine::Type throwType) +GcClass* resolveSystemClass(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + bool throw_, + Gc::Type throwType) { PROTECT(t, loader); PROTECT(t, spec); ACQUIRE(t, t->m->classLock); - object class_ = hashMapFind - (t, classLoaderMap(t, loader), spec, byteArrayHash, byteArrayEqual); + GcClass* class_ = cast(t, + hashMapFind(t, + cast(t, loader->map()), + spec, + byteArrayHash, + byteArrayEqual)); if (class_ == 0) { PROTECT(t, class_); - if (classLoaderParent(t, loader)) { - class_ = resolveSystemClass - (t, classLoaderParent(t, loader), spec, false); + if (loader->parent()) { + class_ = resolveSystemClass(t, loader->parent(), spec, false); if (class_) { return class_; } } - if (byteArrayBody(t, spec, 0) == '[') { + if (spec->body()[0] == '[') { class_ = resolveArrayClass(t, loader, spec, throw_, throwType); } else { - THREAD_RUNTIME_ARRAY(t, char, file, byteArrayLength(t, spec) + 6); - memcpy(RUNTIME_ARRAY_BODY(file), - &byteArrayBody(t, spec, 0), - byteArrayLength(t, spec) - 1); - memcpy(RUNTIME_ARRAY_BODY(file) + byteArrayLength(t, spec) - 1, - ".class", - 7); + GcSystemClassLoader* sysLoader = loader->as(t); + PROTECT(t, sysLoader); - System::Region* region = static_cast - (systemClassLoaderFinder(t, loader))->find - (RUNTIME_ARRAY_BODY(file)); + THREAD_RUNTIME_ARRAY(t, char, file, spec->length() + 6); + memcpy( + RUNTIME_ARRAY_BODY(file), spec->body().begin(), spec->length() - 1); + memcpy(RUNTIME_ARRAY_BODY(file) + spec->length() - 1, ".class", 7); + + System::Region* region = static_cast(sysLoader->finder()) + ->find(RUNTIME_ARRAY_BODY(file)); if (region) { if (Verbose) { - fprintf(stderr, "parsing %s\n", &byteArrayBody(t, spec, 0)); + fprintf(stderr, "parsing %s\n", spec->body().begin()); } - { THREAD_RESOURCE(t, System::Region*, region, region->dispose()); + { + THREAD_RESOURCE(t, System::Region*, region, region->dispose()); - uintptr_t arguments[] = { reinterpret_cast(loader), - reinterpret_cast(region), - static_cast(throwType) }; + uintptr_t arguments[] = {reinterpret_cast(loader), + reinterpret_cast(region), + static_cast(throwType)}; // parse class file - class_ = reinterpret_cast - (runRaw(t, runParseClass, arguments)); + class_ = cast( + t, reinterpret_cast(runRaw(t, runParseClass, arguments))); if (UNLIKELY(t->exception)) { if (throw_) { - object e = t->exception; + GcThrowable* e = t->exception; t->exception = 0; vm::throw_(t, e); } else { @@ -4407,32 +4881,35 @@ resolveSystemClass(Thread* t, object loader, object spec, bool throw_, } if (Verbose) { - fprintf(stderr, "done parsing %s: %p\n", - &byteArrayBody(t, spec, 0), - class_); + fprintf( + stderr, "done parsing %s: %p\n", spec->body().begin(), class_); } - { const char* source = static_cast - (systemClassLoaderFinder(t, loader))->sourceUrl - (RUNTIME_ARRAY_BODY(file)); - + { + const char* source = static_cast(sysLoader->finder()) + ->sourceUrl(RUNTIME_ARRAY_BODY(file)); + if (source) { unsigned length = strlen(source); - object array = makeByteArray(t, length + 1); - memcpy(&byteArrayBody(t, array, 0), source, length); + GcByteArray* array = makeByteArray(t, length + 1); + memcpy(array->body().begin(), source, length); array = internByteArray(t, array); - - set(t, class_, ClassSource, array); + + class_->setSource(t, array); } } - object bootstrapClass = hashMapFind - (t, root(t, Machine::BootstrapClassMap), spec, byteArrayHash, - byteArrayEqual); + GcClass* bootstrapClass + = cast(t, + hashMapFind(t, + roots(t)->bootstrapClassMap(), + spec, + byteArrayHash, + byteArrayEqual)); if (bootstrapClass) { PROTECT(t, bootstrapClass); - + updateBootstrapClass(t, bootstrapClass, class_); class_ = bootstrapClass; } @@ -4440,91 +4917,103 @@ resolveSystemClass(Thread* t, object loader, object spec, bool throw_, } if (class_) { - hashMapInsert(t, classLoaderMap(t, loader), spec, class_, byteArrayHash); + hashMapInsert( + t, cast(t, loader->map()), spec, class_, byteArrayHash); updatePackageMap(t, class_); } else if (throw_) { - throwNew(t, throwType, "%s", &byteArrayBody(t, spec, 0)); + throwNew(t, throwType, "%s", spec->body().begin()); } } return class_; } -object -findLoadedClass(Thread* t, object loader, object spec) +GcClass* findLoadedClass(Thread* t, GcClassLoader* loader, GcByteArray* spec) { PROTECT(t, loader); PROTECT(t, spec); ACQUIRE(t, t->m->classLock); - return classLoaderMap(t, loader) ? hashMapFind - (t, classLoaderMap(t, loader), spec, byteArrayHash, byteArrayEqual) : 0; + return loader->map() + ? cast(t, + hashMapFind(t, + cast(t, loader->map()), + spec, + byteArrayHash, + byteArrayEqual)) + : 0; } -object -resolveClass(Thread* t, object loader, object spec, bool throw_, - Machine::Type throwType) +GcClass* resolveClass(Thread* t, + GcClassLoader* loader, + GcByteArray* spec, + bool throw_, + Gc::Type throwType) { - if (objectClass(t, loader) == type(t, Machine::SystemClassLoaderType)) { + if (objectClass(t, loader) == type(t, GcSystemClassLoader::Type)) { return resolveSystemClass(t, loader, spec, throw_, throwType); } else { PROTECT(t, loader); PROTECT(t, spec); - object c = findLoadedClass(t, loader, spec); + GcClass* c = findLoadedClass(t, loader, spec); if (c) { return c; } - if (byteArrayBody(t, spec, 0) == '[') { + if (spec->body()[0] == '[') { c = resolveArrayClass(t, loader, spec, throw_, throwType); } else { - if (root(t, Machine::LoadClassMethod) == 0) { - object m = resolveMethod - (t, root(t, Machine::BootLoader), "java/lang/ClassLoader", - "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); + if (roots(t)->loadClassMethod() == 0) { + GcMethod* m = resolveMethod(t, + roots(t)->bootLoader(), + "java/lang/ClassLoader", + "loadClass", + "(Ljava/lang/String;)Ljava/lang/Class;"); if (m) { - setRoot(t, Machine::LoadClassMethod, m); + roots(t)->setLoadClassMethod(t, m); - object classLoaderClass = type(t, Machine::ClassLoaderType); - - if (classVmFlags(t, classLoaderClass) & BootstrapFlag) { - resolveSystemClass - (t, root(t, Machine::BootLoader), - vm::className(t, classLoaderClass)); + GcClass* classLoaderClass = type(t, GcClassLoader::Type); + + if (classLoaderClass->vmFlags() & BootstrapFlag) { + resolveSystemClass( + t, roots(t)->bootLoader(), classLoaderClass->name()); } - } + } } - object method = findVirtualMethod - (t, root(t, Machine::LoadClassMethod), objectClass(t, loader)); + GcMethod* method = findVirtualMethod( + t, roots(t)->loadClassMethod(), objectClass(t, loader)); PROTECT(t, method); - - THREAD_RUNTIME_ARRAY(t, char, s, byteArrayLength(t, spec)); - replace('/', '.', RUNTIME_ARRAY_BODY(s), reinterpret_cast - (&byteArrayBody(t, spec, 0))); - object specString = makeString(t, "%s", RUNTIME_ARRAY_BODY(s)); + THREAD_RUNTIME_ARRAY(t, char, s, spec->length()); + replace('/', + '.', + RUNTIME_ARRAY_BODY(s), + reinterpret_cast(spec->body().begin())); + + GcString* specString = makeString(t, "%s", RUNTIME_ARRAY_BODY(s)); PROTECT(t, specString); - uintptr_t arguments[] = { reinterpret_cast(method), - reinterpret_cast(loader), - reinterpret_cast(specString) }; + uintptr_t arguments[] = {reinterpret_cast(method), + reinterpret_cast(loader), + reinterpret_cast(specString)}; - object jc = reinterpret_cast - (runRaw(t, invokeLoadClass, arguments)); + GcJclass* jc = cast( + t, reinterpret_cast(runRaw(t, invokeLoadClass, arguments))); if (LIKELY(jc)) { - c = jclassVmClass(t, jc); + c = jc->vmClass(); } else if (t->exception) { if (throw_) { - object e = type(t, throwType) == objectClass(t, t->exception) - ? t->exception - : makeThrowable(t, throwType, specString, 0, t->exception); + GcThrowable* e + = type(t, throwType) == objectClass(t, t->exception) + ? t->exception + : makeThrowable(t, throwType, specString, 0, t->exception); t->exception = 0; vm::throw_(t, e); } else { @@ -4538,69 +5027,79 @@ resolveClass(Thread* t, object loader, object spec, bool throw_, saveLoadedClass(t, loader, c); } else if (throw_) { - throwNew(t, throwType, "%s", &byteArrayBody(t, spec, 0)); + throwNew(t, throwType, "%s", spec->body().begin()); } return c; } } -object -resolveMethod(Thread* t, object class_, const char* methodName, - const char* methodSpec) +GcMethod* resolveMethod(Thread* t, + GcClass* class_, + const char* methodName, + const char* methodSpec) { PROTECT(t, class_); - object name = makeByteArray(t, methodName); + GcByteArray* name = makeByteArray(t, methodName); PROTECT(t, name); - object spec = makeByteArray(t, methodSpec); - - object method = findMethodInClass(t, class_, name, spec); + GcByteArray* spec = makeByteArray(t, methodSpec); + + GcMethod* method + = cast(t, findMethodInClass(t, class_, name, spec)); if (method == 0) { - throwNew(t, Machine::NoSuchMethodErrorType, "%s %s not found in %s", - methodName, methodSpec, &byteArrayBody - (t, className(t, class_), 0)); + throwNew(t, + GcNoSuchMethodError::Type, + "%s %s not found in %s", + methodName, + methodSpec, + class_->name()->body().begin()); } else { return method; } } -object -resolveField(Thread* t, object class_, const char* fieldName, - const char* fieldSpec) +GcField* resolveField(Thread* t, + GcClass* class_, + const char* fieldName, + const char* fieldSpec) { PROTECT(t, class_); - object name = makeByteArray(t, fieldName); + GcByteArray* name = makeByteArray(t, fieldName); PROTECT(t, name); - object spec = makeByteArray(t, fieldSpec); + GcByteArray* spec = makeByteArray(t, fieldSpec); PROTECT(t, spec); - - object field = findInInterfaces(t, class_, name, spec, findFieldInClass); - object c = class_; + GcField* field = cast( + t, findInInterfaces(t, class_, name, spec, findFieldInClass)); + + GcClass* c = class_; PROTECT(t, c); - for (; c != 0 and field == 0; c = classSuper(t, c)) { - field = findFieldInClass(t, c, name, spec); + for (; c != 0 and field == 0; c = c->super()) { + field = cast(t, findFieldInClass(t, c, name, spec)); } if (field == 0) { - throwNew(t, Machine::NoSuchFieldErrorType, "%s %s not found in %s", - fieldName, fieldSpec, &byteArrayBody(t, className(t, class_), 0)); + throwNew(t, + GcNoSuchFieldError::Type, + "%s %s not found in %s", + fieldName, + fieldSpec, + class_->name()->body().begin()); } else { return field; } } -bool -classNeedsInit(Thread* t, object c) +bool classNeedsInit(Thread* t, GcClass* c) { - if (classVmFlags(t, c) & NeedInitFlag) { - if (classVmFlags(t, c) & InitFlag) { + if (c->vmFlags() & NeedInitFlag) { + if (c->vmFlags() & InitFlag) { // the class is currently being initialized. If this the thread // which is initializing it, we should not try to initialize it // recursively. Otherwise, we must wait for the responsible @@ -4617,10 +5116,9 @@ classNeedsInit(Thread* t, object c) } } -bool -preInitClass(Thread* t, object c) +bool preInitClass(Thread* t, GcClass* c) { - int flags = classVmFlags(t, c); + int flags = c->vmFlags(); loadMemoryBarrier(); @@ -4628,8 +5126,8 @@ preInitClass(Thread* t, object c) PROTECT(t, c); ACQUIRE(t, t->m->classLock); - if (classVmFlags(t, c) & NeedInitFlag) { - if (classVmFlags(t, c) & InitFlag) { + if (c->vmFlags() & NeedInitFlag) { + if (c->vmFlags() & InitFlag) { // If the class is currently being initialized and this the thread // which is initializing it, we should not try to initialize it // recursively. @@ -4638,15 +5136,15 @@ preInitClass(Thread* t, object c) } // some other thread is on the job - wait for it to finish. - while (classVmFlags(t, c) & InitFlag) { + while (c->vmFlags() & InitFlag) { ENTER(t, Thread::IdleState); t->m->classLock->wait(t->systemThread, 0); } - } else if (classVmFlags(t, c) & InitErrorFlag) { - throwNew(t, Machine::NoClassDefFoundErrorType, "%s", - &byteArrayBody(t, className(t, c), 0)); + } else if (c->vmFlags() & InitErrorFlag) { + throwNew( + t, GcNoClassDefFoundError::Type, "%s", c->name()->body().begin()); } else { - classVmFlags(t, c) |= InitFlag; + c->vmFlags() |= InitFlag; return true; } } @@ -4654,47 +5152,45 @@ preInitClass(Thread* t, object c) return false; } -void -postInitClass(Thread* t, object c) +void postInitClass(Thread* t, GcClass* c) { PROTECT(t, c); ACQUIRE(t, t->m->classLock); if (t->exception - and instanceOf(t, type(t, Machine::ExceptionType), t->exception)) { - classVmFlags(t, c) |= NeedInitFlag | InitErrorFlag; - classVmFlags(t, c) &= ~InitFlag; + and instanceOf(t, type(t, GcException::Type), t->exception)) { + c->vmFlags() |= NeedInitFlag | InitErrorFlag; + c->vmFlags() &= ~InitFlag; - object exception = t->exception; + GcThrowable* exception = t->exception; t->exception = 0; - exception = makeThrowable - (t, Machine::ExceptionInInitializerErrorType, 0, 0, exception); - - set(t, exception, ExceptionInInitializerErrorException, - throwableCause(t, exception)); + GcExceptionInInitializerError* initExecption + = makeThrowable(t, GcExceptionInInitializerError::Type, 0, 0, exception) + ->as(t); - throw_(t, exception); + initExecption->setException(t, exception->cause()); + + throw_(t, initExecption->as(t)); } else { - classVmFlags(t, c) &= ~(NeedInitFlag | InitFlag); + c->vmFlags() &= ~(NeedInitFlag | InitFlag); } t->m->classLock->notifyAll(t->systemThread); } -void -initClass(Thread* t, object c) +void initClass(Thread* t, GcClass* c) { PROTECT(t, c); - object super = classSuper(t, c); + GcClass* super = c->super(); if (super) { initClass(t, super); } if (preInitClass(t, c)) { - OBJECT_RESOURCE(t, c, postInitClass(t, c)); + OBJECT_RESOURCE(t, c, postInitClass(t, cast(t, c))); - object initializer = classInitializer(t, c); + GcMethod* initializer = classInitializer(t, c); if (initializer) { Thread::ClassInitStack stack(t, c); @@ -4704,53 +5200,52 @@ initClass(Thread* t, object c) } } -object -resolveObjectArrayClass(Thread* t, object loader, object elementClass) +GcClass* resolveObjectArrayClass(Thread* t, + GcClassLoader* loader, + GcClass* elementClass) { PROTECT(t, loader); PROTECT(t, elementClass); - { object arrayClass = classRuntimeDataArrayClass - (t, getClassRuntimeData(t, elementClass)); + { + GcClass* arrayClass + = cast(t, getClassRuntimeData(t, elementClass)->arrayClass()); if (arrayClass) { return arrayClass; } } - object elementSpec = className(t, elementClass); + GcByteArray* elementSpec = elementClass->name(); PROTECT(t, elementSpec); - object spec; - if (byteArrayBody(t, elementSpec, 0) == '[') { - spec = makeByteArray(t, byteArrayLength(t, elementSpec) + 1); - byteArrayBody(t, spec, 0) = '['; - memcpy(&byteArrayBody(t, spec, 1), - &byteArrayBody(t, elementSpec, 0), - byteArrayLength(t, elementSpec)); + GcByteArray* spec; + if (elementSpec->body()[0] == '[') { + spec = makeByteArray(t, elementSpec->length() + 1); + spec->body()[0] = '['; + memcpy( + &spec->body()[1], elementSpec->body().begin(), elementSpec->length()); } else { - spec = makeByteArray(t, byteArrayLength(t, elementSpec) + 3); - byteArrayBody(t, spec, 0) = '['; - byteArrayBody(t, spec, 1) = 'L'; - memcpy(&byteArrayBody(t, spec, 2), - &byteArrayBody(t, elementSpec, 0), - byteArrayLength(t, elementSpec) - 1); - byteArrayBody(t, spec, byteArrayLength(t, elementSpec) + 1) = ';'; - byteArrayBody(t, spec, byteArrayLength(t, elementSpec) + 2) = 0; + spec = makeByteArray(t, elementSpec->length() + 3); + spec->body()[0] = '['; + spec->body()[1] = 'L'; + memcpy(&spec->body()[2], + elementSpec->body().begin(), + elementSpec->length() - 1); + spec->body()[elementSpec->length() + 1] = ';'; + spec->body()[elementSpec->length() + 2] = 0; } - object arrayClass = resolveClass(t, loader, spec); + GcClass* arrayClass = resolveClass(t, loader, spec); - set(t, getClassRuntimeData(t, elementClass), ClassRuntimeDataArrayClass, - arrayClass); + getClassRuntimeData(t, elementClass)->setArrayClass(t, arrayClass); return arrayClass; } -object -makeObjectArray(Thread* t, object elementClass, unsigned count) +object makeObjectArray(Thread* t, GcClass* elementClass, unsigned count) { - object arrayClass = resolveObjectArrayClass - (t, classLoader(t, elementClass), elementClass); + GcClass* arrayClass + = resolveObjectArrayClass(t, elementClass->loader(), elementClass); PROTECT(t, arrayClass); @@ -4760,36 +5255,73 @@ makeObjectArray(Thread* t, object elementClass, unsigned count) return array; } -object -findFieldInClass(Thread* t, object class_, object name, object spec) +static GcByteArray* getFieldName(Thread* t, object obj) { - return findInTable - (t, classFieldTable(t, class_), name, spec, fieldName, fieldSpec); + return reinterpret_cast(cast(t, obj)->name()); } -object -findMethodInClass(Thread* t, object class_, object name, object spec) +static GcByteArray* getFieldSpec(Thread* t, object obj) { - return findInTable - (t, classMethodTable(t, class_), name, spec, methodName, methodSpec); + return reinterpret_cast(cast(t, obj)->spec()); } -object -findInHierarchyOrNull(Thread* t, object class_, object name, object spec, - object (*find)(Thread*, object, object, object)) +static GcByteArray* getMethodName(Thread* t, object obj) { - object originalClass = class_; + return reinterpret_cast(cast(t, obj)->name()); +} + +static GcByteArray* getMethodSpec(Thread* t, object obj) +{ + return reinterpret_cast(cast(t, obj)->spec()); +} + +object findFieldInClass(Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec) +{ + return findInTable(t, + cast(t, class_->fieldTable()), + name, + spec, + getFieldName, + getFieldSpec); +} + +object findMethodInClass(Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec) +{ + return findInTable(t, + cast(t, class_->methodTable()), + name, + spec, + getMethodName, + getMethodSpec); +} + +object findInHierarchyOrNull( + Thread* t, + GcClass* class_, + GcByteArray* name, + GcByteArray* spec, + object (*find)(Thread*, GcClass*, GcByteArray*, GcByteArray*)) +{ + GcClass* originalClass = class_; object o = 0; - if ((classFlags(t, class_) & ACC_INTERFACE) - and classVirtualTable(t, class_)) - { - o = findInTable - (t, classVirtualTable(t, class_), name, spec, methodName, methodSpec); + if ((class_->flags() & ACC_INTERFACE) and class_->virtualTable()) { + o = findInTable(t, + cast(t, class_->virtualTable()), + name, + spec, + getMethodName, + getMethodSpec); } if (o == 0) { - for (; o == 0 and class_; class_ = classSuper(t, class_)) { + for (; o == 0 and class_; class_ = class_->super()) { o = find(t, class_, name, spec); } @@ -4801,8 +5333,7 @@ findInHierarchyOrNull(Thread* t, object class_, object name, object spec, return o; } -unsigned -parameterFootprint(Thread* t, const char* s, bool static_) +unsigned parameterFootprint(Thread* t, const char* s, bool static_) { unsigned footprint = 0; for (MethodSpecIterator it(t, s); it.hasNext();) { @@ -4813,19 +5344,18 @@ parameterFootprint(Thread* t, const char* s, bool static_) break; default: - ++ footprint; - break; + ++footprint; + break; } } if (not static_) { - ++ footprint; + ++footprint; } return footprint; } -void -addFinalizer(Thread* t, object target, void (*finalize)(Thread*, object)) +void addFinalizer(Thread* t, object target, void (*finalize)(Thread*, object)) { PROTECT(t, target); @@ -4834,109 +5364,115 @@ addFinalizer(Thread* t, object target, void (*finalize)(Thread*, object)) void* function; memcpy(&function, &finalize, BytesPerWord); - object f = makeFinalizer(t, 0, function, 0, 0, 0); - finalizerTarget(t, f) = target; - finalizerNext(t, f) = t->m->finalizers; + GcFinalizer* f = makeFinalizer(t, 0, function, 0, 0, 0); + f->target() = target; + f->next() = t->m->finalizers; t->m->finalizers = f; } -object -objectMonitor(Thread* t, object o, bool createNew) +GcMonitor* objectMonitor(Thread* t, object o, bool createNew) { - assert(t, t->state == Thread::ActiveState); + assertT(t, t->state == Thread::ActiveState); - object m = hashMapFind - (t, root(t, Machine::MonitorMap), o, objectHash, objectEqual); + object m = hashMapFind(t, roots(t)->monitorMap(), o, objectHash, objectEqual); if (m) { if (DebugMonitors) { fprintf(stderr, "found monitor %p for object %x\n", m, objectHash(t, o)); } - return m; + return cast(t, m); } else if (createNew) { PROTECT(t, o); PROTECT(t, m); - { ENTER(t, Thread::ExclusiveState); + { + ENTER(t, Thread::ExclusiveState); - m = hashMapFind - (t, root(t, Machine::MonitorMap), o, objectHash, objectEqual); + m = hashMapFind(t, roots(t)->monitorMap(), o, objectHash, objectEqual); if (m) { if (DebugMonitors) { - fprintf(stderr, "found monitor %p for object %x\n", - m, objectHash(t, o)); + fprintf( + stderr, "found monitor %p for object %x\n", m, objectHash(t, o)); } - return m; + return cast(t, m); } object head = makeMonitorNode(t, 0, 0); m = makeMonitor(t, 0, 0, 0, head, head, 0); if (DebugMonitors) { - fprintf(stderr, "made monitor %p for object %x\n", m, - objectHash(t, o)); + fprintf(stderr, "made monitor %p for object %x\n", m, objectHash(t, o)); } - hashMapInsert(t, root(t, Machine::MonitorMap), o, m, objectHash); + hashMapInsert(t, roots(t)->monitorMap(), o, m, objectHash); addFinalizer(t, o, removeMonitor); } - return m; + return cast(t, m); } else { return 0; } } -object -intern(Thread* t, object s) +object intern(Thread* t, object s) { PROTECT(t, s); ACQUIRE(t, t->m->referenceLock); - object n = hashMapFindNode - (t, root(t, Machine::StringMap), s, stringHash, stringEqual); + GcTriple* n + = hashMapFindNode(t, roots(t)->stringMap(), s, stringHash, stringEqual); if (n) { - return jreferenceTarget(t, tripleFirst(t, n)); + return cast(t, n->first())->target(); } else { - hashMapInsert(t, root(t, Machine::StringMap), s, 0, stringHash); + hashMapInsert(t, roots(t)->stringMap(), s, 0, stringHash); addFinalizer(t, s, removeString); return s; } } -void -walk(Thread* t, Heap::Walker* w, object o, unsigned start) +void walk(Thread* t, Heap::Walker* w, object o, unsigned start) { - object class_ = static_cast(t->m->heap->follow(objectClass(t, o))); - object objectMask = static_cast - (t->m->heap->follow(classObjectMask(t, class_))); + GcClass* class_ = t->m->heap->follow(objectClass(t, o)); + GcIntArray* objectMask = t->m->heap->follow(class_->objectMask()); bool more = true; if (objectMask) { - unsigned fixedSize = classFixedSize(t, class_); - unsigned arrayElementSize = classArrayElementSize(t, class_); - unsigned arrayLength - = (arrayElementSize ? - fieldAtOffset(o, fixedSize - BytesPerWord) : 0); + unsigned fixedSize = class_->fixedSize(); + unsigned arrayElementSize = class_->arrayElementSize(); + unsigned arrayLength = (arrayElementSize ? fieldAtOffset( + o, fixedSize - BytesPerWord) + : 0); - THREAD_RUNTIME_ARRAY(t, uint32_t, mask, intArrayLength(t, objectMask)); - memcpy(RUNTIME_ARRAY_BODY(mask), &intArrayBody(t, objectMask, 0), - intArrayLength(t, objectMask) * 4); + THREAD_RUNTIME_ARRAY(t, uint32_t, mask, objectMask->length()); + memcpy(RUNTIME_ARRAY_BODY(mask), + objectMask->body().begin(), + objectMask->length() * 4); - more = ::walk(t, w, RUNTIME_ARRAY_BODY(mask), fixedSize, arrayElementSize, - arrayLength, start); - } else if (classVmFlags(t, class_) & SingletonFlag) { - unsigned length = singletonLength(t, o); + more = ::walk(t, + w, + RUNTIME_ARRAY_BODY(mask), + fixedSize, + arrayElementSize, + arrayLength, + start); + } else if (class_->vmFlags() & SingletonFlag) { + GcSingleton* s = cast(t, o); + unsigned length = s->length(); if (length) { - more = ::walk(t, w, singletonMask(t, o), - (singletonCount(t, o) + 2) * BytesPerWord, 0, 0, start); + more = ::walk(t, + w, + singletonMask(t, s), + (singletonCount(t, s) + 2) * BytesPerWord, + 0, + 0, + start); } else if (start == 0) { more = w->visit(0); } @@ -4944,19 +5480,21 @@ walk(Thread* t, Heap::Walker* w, object o, unsigned start) more = w->visit(0); } - if (more and classVmFlags(t, class_) & ContinuationFlag) { + if (more and class_->vmFlags() & ContinuationFlag) { t->m->processor->walkContinuationBody(t, w, o, start); } } -int -walkNext(Thread* t, object o, int previous) +int walkNext(Thread* t, object o, int previous) { - class Walker: public Heap::Walker { + class Walker : public Heap::Walker { public: - Walker(): value(-1) { } + Walker() : value(-1) + { + } - bool visit(unsigned offset) { + bool visit(unsigned offset) + { value = offset; return false; } @@ -4968,8 +5506,7 @@ walkNext(Thread* t, object o, int previous) return walker.value; } -void -visitRoots(Machine* m, Heap::Visitor* v) +void visitRoots(Machine* m, Heap::Visitor* v) { v->visit(&(m->types)); v->visit(&(m->roots)); @@ -4985,64 +5522,60 @@ visitRoots(Machine* m, Heap::Visitor* v) } } -void -logTrace(FILE* f, const char* fmt, ...) +void logTrace(FILE* f, const char* fmt, ...) { - va_list a; - va_start(a, fmt); + va_list a; + va_start(a, fmt); #ifdef PLATFORM_WINDOWS - const unsigned length = _vscprintf(fmt, a); + const unsigned length = _vscprintf(fmt, a); #else - const unsigned length = vsnprintf(0, 0, fmt, a); + const unsigned length = vsnprintf(0, 0, fmt, a); #endif - va_end(a); + va_end(a); - RUNTIME_ARRAY(char, buffer, length + 1); - va_start(a, fmt); - vsnprintf(RUNTIME_ARRAY_BODY(buffer), length + 1, fmt, a); - va_end(a); - RUNTIME_ARRAY_BODY(buffer)[length] = 0; + RUNTIME_ARRAY(char, buffer, length + 1); + va_start(a, fmt); + vsnprintf(RUNTIME_ARRAY_BODY(buffer), length + 1, fmt, a); + va_end(a); + RUNTIME_ARRAY_BODY(buffer)[length] = 0; - ::fprintf(f, "%s", RUNTIME_ARRAY_BODY(buffer)); + ::fprintf(f, "%s", RUNTIME_ARRAY_BODY(buffer)); #ifdef PLATFORM_WINDOWS - ::OutputDebugStringA(RUNTIME_ARRAY_BODY(buffer)); + ::OutputDebugStringA(RUNTIME_ARRAY_BODY(buffer)); #endif } -void -printTrace(Thread* t, object exception) +void printTrace(Thread* t, GcThrowable* exception) { if (exception == 0) { - exception = makeThrowable(t, Machine::NullPointerExceptionType); + exception = makeThrowable(t, GcNullPointerException::Type); } - for (object e = exception; e; e = throwableCause(t, e)) { + for (GcThrowable* e = exception; e; e = e->cause()) { if (e != exception) { logTrace(errorLog(t), "caused by: "); } - logTrace(errorLog(t), "%s", &byteArrayBody - (t, className(t, objectClass(t, e)), 0)); + logTrace(errorLog(t), "%s", objectClass(t, e)->name()->body().begin()); - if (throwableMessage(t, e)) { - object m = throwableMessage(t, e); - THREAD_RUNTIME_ARRAY(t, char, message, stringLength(t, m) + 1); + if (e->message()) { + GcString* m = e->message(); + THREAD_RUNTIME_ARRAY(t, char, message, m->length(t) + 1); stringChars(t, m, RUNTIME_ARRAY_BODY(message)); logTrace(errorLog(t), ": %s\n", RUNTIME_ARRAY_BODY(message)); } else { logTrace(errorLog(t), "\n"); } - object trace = throwableTrace(t, e); + object trace = e->trace(); if (trace) { for (unsigned i = 0; i < objectArrayLength(t, trace); ++i) { - object e = objectArrayBody(t, trace, i); - const int8_t* class_ = &byteArrayBody - (t, className(t, methodClass(t, traceElementMethod(t, e))), 0); - const int8_t* method = &byteArrayBody - (t, methodName(t, traceElementMethod(t, e)), 0); - int line = t->m->processor->lineNumber - (t, traceElementMethod(t, e), traceElementIp(t, e)); + GcTraceElement* e + = cast(t, objectArrayBody(t, trace, i)); + GcMethod* m = cast(t, e->method()); + const int8_t* class_ = m->class_()->name()->body().begin(); + const int8_t* method = m->name()->body().begin(); + int line = t->m->processor->lineNumber(t, m, e->ip()); logTrace(errorLog(t), " at %s.%s ", class_, method); @@ -5059,7 +5592,7 @@ printTrace(Thread* t, object exception) } } - if (e == throwableCause(t, e)) { + if (e == e->cause()) { break; } } @@ -5067,23 +5600,25 @@ printTrace(Thread* t, object exception) ::fflush(errorLog(t)); } -object -makeTrace(Thread* t, Processor::StackWalker* walker) +object makeTrace(Thread* t, Processor::StackWalker* walker) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t): t(t), trace(0), index(0), protector(t, &trace) { } + Visitor(Thread* t) : t(t), trace(0), index(0), protector(t, &trace) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { if (trace == 0) { trace = makeObjectArray(t, walker->count()); - assert(t, trace); + assertT(t, trace); } - object e = makeTraceElement(t, walker->method(), walker->ip()); - assert(t, index < objectArrayLength(t, trace)); - set(t, trace, ArrayBody + (index * BytesPerWord), e); - ++ index; + GcTraceElement* e = makeTraceElement(t, walker->method(), walker->ip()); + assertT(t, index < objectArrayLength(t, trace)); + reinterpret_cast(trace)->setBodyElement(t, index, e); + ++index; return true; } @@ -5098,14 +5633,16 @@ makeTrace(Thread* t, Processor::StackWalker* walker) return v.trace ? v.trace : makeObjectArray(t, 0); } -object -makeTrace(Thread* t, Thread* target) +object makeTrace(Thread* t, Thread* target) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t): t(t), trace(0) { } + Visitor(Thread* t) : t(t), trace(0) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { trace = vm::makeTrace(t, walker); return false; } @@ -5119,22 +5656,20 @@ makeTrace(Thread* t, Thread* target) return v.trace ? v.trace : makeObjectArray(t, 0); } -void -runFinalizeThread(Thread* t) +void runFinalizeThread(Thread* t) { - object finalizeList = 0; + GcFinalizer* finalizeList = 0; PROTECT(t, finalizeList); - object cleanList = 0; + GcCleaner* cleanList = 0; PROTECT(t, cleanList); while (true) { - { ACQUIRE(t, t->m->stateLock); + { + ACQUIRE(t, t->m->stateLock); - while (t->m->finalizeThread - and root(t, Machine::ObjectsToFinalize) == 0 - and root(t, Machine::ObjectsToClean) == 0) - { + while (t->m->finalizeThread and roots(t)->objectsToFinalize() == 0 + and roots(t)->objectsToClean() == 0) { ENTER(t, Thread::IdleState); t->m->stateLock->wait(t->systemThread, 0); } @@ -5142,33 +5677,36 @@ runFinalizeThread(Thread* t) if (t->m->finalizeThread == 0) { return; } else { - finalizeList = root(t, Machine::ObjectsToFinalize); - setRoot(t, Machine::ObjectsToFinalize, 0); + finalizeList = roots(t)->objectsToFinalize(); + roots(t)->setObjectsToFinalize(t, 0); - cleanList = root(t, Machine::ObjectsToClean); - setRoot(t, Machine::ObjectsToClean, 0); + cleanList = roots(t)->objectsToClean(); + roots(t)->setObjectsToClean(t, 0); } } - for (; finalizeList; finalizeList = finalizerQueueNext(t, finalizeList)) { - finalizeObject(t, finalizerQueueTarget(t, finalizeList), "finalize"); + for (; finalizeList; finalizeList = finalizeList->queueNext()) { + finalizeObject(t, finalizeList->queueTarget(), "finalize"); } - for (; cleanList; cleanList = cleanerQueueNext(t, cleanList)) { + for (; cleanList; cleanList = cleanList->queueNext()) { finalizeObject(t, cleanList, "clean"); } } } -object -parseUtf8(Thread* t, const char* data, unsigned length) +object parseUtf8(Thread* t, const char* data, unsigned length) { - class Client: public Stream::Client { + class Client : public Stream::Client { public: - Client(Thread* t): t(t) { } + Client(Thread* t) : t(t) + { + } - virtual void handleError() { - if (false) abort(t); + virtual void handleError() + { + if (false) + abort(t); } private: @@ -5180,85 +5718,91 @@ parseUtf8(Thread* t, const char* data, unsigned length) return ::parseUtf8(t, s, length); } -object -parseUtf8(Thread* t, object array) +object parseUtf8(Thread* t, GcByteArray* array) { - for (unsigned i = 0; i < byteArrayLength(t, array) - 1; ++i) { - if (byteArrayBody(t, array, i) & 0x80) { + for (unsigned i = 0; i < array->length() - 1; ++i) { + if (array->body()[i] & 0x80) { goto slow_path; } } return array; - slow_path: - class Client: public Stream::Client { +slow_path: + class Client : public Stream::Client { public: - Client(Thread* t): t(t) { } + Client(Thread* t) : t(t) + { + } - virtual void handleError() { - if (false) abort(t); + virtual void handleError() + { + if (false) + abort(t); } private: Thread* t; } client(t); - class MyStream: public AbstractStream { + class MyStream : public AbstractStream { public: - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(Thread* t, MyStream* s): - Protector(t), s(s) - { } + MyProtector(Thread* t, MyStream* s) : Protector(t), s(s) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(s->array)); } MyStream* s; }; - MyStream(Thread* t, Client* client, object array): - AbstractStream(client, byteArrayLength(t, array) - 1), - array(array), - protector(t, this) - { } - - virtual void copy(uint8_t* dst, unsigned offset, unsigned size) { - memcpy(dst, &byteArrayBody(protector.t, array, offset), size); + MyStream(Thread* t, Client* client, GcByteArray* array) + : AbstractStream(client, array->length() - 1), + array(array), + protector(t, this) + { } - object array; + virtual void copy(uint8_t* dst, unsigned offset, unsigned size) + { + memcpy(dst, &array->body()[offset], size); + } + + GcByteArray* array; MyProtector protector; } s(t, &client, array); - return ::parseUtf8(t, s, byteArrayLength(t, array) - 1); + return ::parseUtf8(t, s, array->length() - 1); } -object -getCaller(Thread* t, unsigned target, bool skipMethodInvoke) +GcMethod* getCaller(Thread* t, unsigned target, bool skipMethodInvoke) { if (static_cast(target) == -1) { target = 2; } - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t, unsigned target, bool skipMethodInvoke): - t(t), method(0), count(0), target(target), - skipMethodInvoke(skipMethodInvoke) - { } + Visitor(Thread* t, unsigned target, bool skipMethodInvoke) + : t(t), + method(0), + count(0), + target(target), + skipMethodInvoke(skipMethodInvoke) + { + } - virtual bool visit(Processor::StackWalker* walker) { + virtual bool visit(Processor::StackWalker* walker) + { if (skipMethodInvoke - and methodClass - (t, walker->method()) == type(t, Machine::JmethodType) - and strcmp - (&byteArrayBody(t, methodName(t, walker->method()), 0), - reinterpret_cast("invoke")) - == 0) - { + and walker->method()->class_() == type(t, GcJmethod::Type) + and strcmp(walker->method()->name()->body().begin(), + reinterpret_cast("invoke")) == 0) { return true; } @@ -5266,30 +5810,32 @@ getCaller(Thread* t, unsigned target, bool skipMethodInvoke) method = walker->method(); return false; } else { - ++ count; + ++count; return true; } } Thread* t; - object method; + GcMethod* method; unsigned count; unsigned target; bool skipMethodInvoke; - } v(t, target, skipMethodInvoke); + } v(t, target, skipMethodInvoke); t->m->processor->walkStack(t, &v); return v.method; } -object -defineClass(Thread* t, object loader, const uint8_t* buffer, unsigned length) +object defineClass(Thread* t, + GcClassLoader* loader, + const uint8_t* buffer, + unsigned length) { PROTECT(t, loader); object c = parseClass(t, loader, buffer, length); - + // char name[byteArrayLength(t, className(t, c))]; // memcpy(name, &byteArrayBody(t, className(t, c), 0), // byteArrayLength(t, className(t, c))); @@ -5307,14 +5853,16 @@ defineClass(Thread* t, object loader, const uint8_t* buffer, unsigned length) PROTECT(t, c); - saveLoadedClass(t, loader, c); + saveLoadedClass(t, loader, cast(t, c)); return c; } -void -populateMultiArray(Thread* t, object array, int32_t* counts, - unsigned index, unsigned dimensions) +void populateMultiArray(Thread* t, + object array, + int32_t* counts, + unsigned index, + unsigned dimensions) { if (index + 1 == dimensions or counts[index] == 0) { return; @@ -5322,34 +5870,32 @@ populateMultiArray(Thread* t, object array, int32_t* counts, PROTECT(t, array); - object spec = className(t, objectClass(t, array)); + GcByteArray* spec = objectClass(t, array)->name(); PROTECT(t, spec); - object elementSpec = makeByteArray(t, byteArrayLength(t, spec) - 1); - memcpy(&byteArrayBody(t, elementSpec, 0), - &byteArrayBody(t, spec, 1), - byteArrayLength(t, spec) - 1); + GcByteArray* elementSpec = makeByteArray(t, spec->length() - 1); + memcpy(elementSpec->body().begin(), &spec->body()[1], spec->length() - 1); - object class_ = resolveClass - (t, classLoader(t, objectClass(t, array)), elementSpec); + GcClass* class_ + = resolveClass(t, objectClass(t, array)->loader(), elementSpec); PROTECT(t, class_); for (int32_t i = 0; i < counts[index]; ++i) { - object a = makeArray - (t, ceilingDivide - (counts[index + 1] * classArrayElementSize(t, class_), BytesPerWord)); - arrayLength(t, a) = counts[index + 1]; + GcArray* a = makeArray( + t, + ceilingDivide(counts[index + 1] * class_->arrayElementSize(), + BytesPerWord)); + a->length() = counts[index + 1]; setObjectClass(t, a, class_); - set(t, array, ArrayBody + (i * BytesPerWord), a); - + setField(t, array, ArrayBody + (i * BytesPerWord), a); + populateMultiArray(t, a, counts, index + 1, dimensions); } } -object -interruptLock(Thread* t, object thread) +object interruptLock(Thread* t, GcThread* thread) { - object lock = threadInterruptLock(t, thread); + object lock = thread->interruptLock(); loadMemoryBarrier(); @@ -5357,78 +5903,74 @@ interruptLock(Thread* t, object thread) PROTECT(t, thread); ACQUIRE(t, t->m->referenceLock); - if (threadInterruptLock(t, thread) == 0) { + if (thread->interruptLock() == 0) { object head = makeMonitorNode(t, 0, 0); - object lock = makeMonitor(t, 0, 0, 0, head, head, 0); + GcMonitor* lock = makeMonitor(t, 0, 0, 0, head, head, 0); storeStoreMemoryBarrier(); - set(t, thread, ThreadInterruptLock, lock); + thread->setInterruptLock(t, lock); } } - - return threadInterruptLock(t, thread); + + return thread->interruptLock(); } -void -clearInterrupted(Thread* t) +void clearInterrupted(Thread* t) { - monitorAcquire(t, interruptLock(t, t->javaThread)); - threadInterrupted(t, t->javaThread) = false; - monitorRelease(t, interruptLock(t, t->javaThread)); + monitorAcquire(t, cast(t, interruptLock(t, t->javaThread))); + t->javaThread->interrupted() = false; + monitorRelease(t, cast(t, interruptLock(t, t->javaThread))); } -void -threadInterrupt(Thread* t, object thread) +void threadInterrupt(Thread* t, GcThread* thread) { PROTECT(t, thread); - - monitorAcquire(t, interruptLock(t, thread)); - Thread* p = reinterpret_cast(threadPeer(t, thread)); + + monitorAcquire(t, cast(t, interruptLock(t, thread))); + Thread* p = reinterpret_cast(thread->peer()); if (p) { interrupt(t, p); } - threadInterrupted(t, thread) = true; - monitorRelease(t, interruptLock(t, thread)); + thread->interrupted() = true; + monitorRelease(t, cast(t, interruptLock(t, thread))); } -bool -threadIsInterrupted(Thread* t, object thread, bool clear) +bool threadIsInterrupted(Thread* t, GcThread* thread, bool clear) { PROTECT(t, thread); - - monitorAcquire(t, interruptLock(t, thread)); - bool v = threadInterrupted(t, thread); + + monitorAcquire(t, cast(t, interruptLock(t, thread))); + bool v = thread->interrupted(); if (clear) { - threadInterrupted(t, thread) = false; + thread->interrupted() = false; } - monitorRelease(t, interruptLock(t, thread)); + monitorRelease(t, cast(t, interruptLock(t, thread))); return v; } -void -noop() -{ } +void noop() +{ +} #include "type-constructors.cpp" -} // namespace vm +} // namespace vm // for debugging -AVIAN_EXPORT void -vmfPrintTrace(Thread* t, FILE* out) +AVIAN_EXPORT void vmfPrintTrace(Thread* t, FILE* out) { - class Visitor: public Processor::StackVisitor { + class Visitor : public Processor::StackVisitor { public: - Visitor(Thread* t, FILE* out): t(t), out(out) { } + Visitor(Thread* t, FILE* out) : t(t), out(out) + { + } - virtual bool visit(Processor::StackWalker* walker) { - const int8_t* class_ = &byteArrayBody - (t, className(t, methodClass(t, walker->method())), 0); - const int8_t* method = &byteArrayBody - (t, methodName(t, walker->method()), 0); - int line = t->m->processor->lineNumber - (t, walker->method(), walker->ip()); + virtual bool visit(Processor::StackWalker* walker) + { + const int8_t* class_ = walker->method()->class_()->name()->body().begin(); + const int8_t* method = walker->method()->name()->body().begin(); + int line = t->m->processor->lineNumber(t, walker->method(), walker->ip()); fprintf(out, " at %s.%s ", class_, method); @@ -5457,31 +5999,28 @@ vmfPrintTrace(Thread* t, FILE* out) fflush(out); } -AVIAN_EXPORT void -vmPrintTrace(Thread* t) +AVIAN_EXPORT void vmPrintTrace(Thread* t) { vmfPrintTrace(t, stderr); } // also for debugging -AVIAN_EXPORT void* -vmAddressFromLine(Thread* t, object m, unsigned line) +AVIAN_EXPORT void* vmAddressFromLine(GcMethod* m, unsigned line) { - object code = methodCode(t, m); + GcCode* code = m->code(); printf("code: %p\n", code); - object lnt = codeLineNumberTable(t, code); + GcLineNumberTable* lnt = code->lineNumberTable(); printf("lnt: %p\n", lnt); - + if (lnt) { unsigned last = 0; unsigned bottom = 0; - unsigned top = lineNumberTableLength(t, lnt); - for(unsigned i = bottom; i < top; i++) - { - uint64_t ln = lineNumberTableBody(t, lnt, i); - if(lineNumberLine(ln) == line) + unsigned top = lnt->length(); + for (unsigned i = bottom; i < top; i++) { + uint64_t ln = lnt->body()[i]; + if (lineNumberLine(ln) == line) return reinterpret_cast(lineNumberIp(ln)); - else if(lineNumberLine(ln) > line) + else if (lineNumberLine(ln) > line) return reinterpret_cast(last); last = lineNumberIp(ln); } diff --git a/src/main.cpp b/src/main.cpp index 7acb9e8783..dad5a1a768 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -19,30 +19,32 @@ #include #if (defined __MINGW32__) || (defined _MSC_VER) -# define PATH_SEPARATOR ';' +#define PATH_SEPARATOR ';' #else -# define PATH_SEPARATOR ':' +#define PATH_SEPARATOR ':' #endif #ifdef _MSC_VER -# define not ! -# define or || -# define and && -# define xor ^ +#define not! +#define or || +#define and && +#define xor ^ -#endif // not _MSC_VER +#endif // not _MSC_VER #ifdef BOOT_LIBRARY // since we aren't linking against libstdc++, we must implement this // ourselves: -extern "C" void __cxa_pure_virtual(void) { abort(); } +extern "C" void __cxa_pure_virtual(void) +{ + abort(); +} // we link against a System implmentation, which requires this at link // time, but it should not be used at runtime: -extern "C" uint64_t -vmNativeCall(void*, void*, unsigned, unsigned) +extern "C" uint64_t vmNativeCall(void*, void*, unsigned, unsigned) { abort(); // abort is not declared __declspec(noreturn) on MSVC, so we have to @@ -50,12 +52,11 @@ vmNativeCall(void*, void*, unsigned, unsigned) return 0; } -#endif // BOOT_LIBRARY +#endif // BOOT_LIBRARY namespace { -const char* -mainClass(const char* jar) +const char* mainClass(const char* jar) { using namespace vm; @@ -63,13 +64,17 @@ mainClass(const char* jar) class MyAllocator : public avian::util::Allocator { public: - MyAllocator(System* s): s(s) { } + MyAllocator(System* s) : s(s) + { + } - virtual void* tryAllocate(unsigned size) { + virtual void* tryAllocate(unsigned size) + { return s->tryAllocate(size); } - virtual void* allocate(unsigned size) { + virtual void* allocate(unsigned size) + { void* p = tryAllocate(size); if (p == 0) { abort(s); @@ -77,7 +82,8 @@ mainClass(const char* jar) return p; } - virtual void free(const void* p, unsigned) { + virtual void free(const void* p, unsigned) + { s->free(p); } @@ -94,11 +100,12 @@ mainClass(const char* jar) unsigned length; while (readLine(region->start(), region->length(), &start, &length)) { const unsigned PrefixLength = 12; - if (strncasecmp("Main-Class: ", reinterpret_cast - (region->start() + start), PrefixLength) == 0) - { + if (strncasecmp("Main-Class: ", + reinterpret_cast(region->start() + start), + PrefixLength) == 0) { result = static_cast(malloc(length + 1 - PrefixLength)); - memcpy(result, region->start() + start + PrefixLength, + memcpy(result, + region->start() + start + PrefixLength, length - PrefixLength); result[length - PrefixLength] = 0; break; @@ -116,26 +123,26 @@ mainClass(const char* jar) return result; } -void -usageAndExit(const char* name) +void usageAndExit(const char* name) { - fprintf - (stderr, "usage: %s\n" - "\t[{-cp|-classpath} ]\n" - "\t[-Xmx]\n" - "\t[-Xss]\n" - "\t[-Xbootclasspath/p:]\n" - "\t[-Xbootclasspath:]\n" - "\t[-Xbootclasspath/a:]\n" - "\t[-D= ...]\n" - "\t{|-jar } [ ...]\n", name); + fprintf( + stderr, + "usage: %s\n" + "\t[{-cp|-classpath} ]\n" + "\t[-Xmx]\n" + "\t[-Xss]\n" + "\t[-Xbootclasspath/p:]\n" + "\t[-Xbootclasspath:]\n" + "\t[-Xbootclasspath/a:]\n" + "\t[-D= ...]\n" + "\t{|-jar } [ ...]\n", + name); exit(-1); } -} // namespace +} // namespace -int -main(int ac, const char** av) +int main(int ac, const char** av) { JavaVMInitArgs vmArgs; vmArgs.version = JNI_VERSION_1_2; @@ -178,7 +185,7 @@ main(int ac, const char** av) if (jar) { classpath = jar; - + class_ = mainClass(jar); if (class_ == 0) { @@ -188,7 +195,7 @@ main(int ac, const char** av) } #ifdef BOOT_LIBRARY - ++ vmArgs.nOptions; + ++vmArgs.nOptions; #endif #ifdef BOOT_IMAGE @@ -196,7 +203,7 @@ main(int ac, const char** av) #endif #ifdef BOOT_BUILTINS - ++ vmArgs.nOptions; + ++vmArgs.nOptions; #endif RUNTIME_ARRAY(JavaVMOption, options, vmArgs.nOptions); @@ -206,27 +213,27 @@ main(int ac, const char** av) #ifdef BOOT_IMAGE vmArgs.options[optionIndex++].optionString - = const_cast("-Davian.bootimage=bootimageBin"); + = const_cast("-Davian.bootimage=bootimageBin"); vmArgs.options[optionIndex++].optionString - = const_cast("-Davian.codeimage=codeimageBin"); + = const_cast("-Davian.codeimage=codeimageBin"); #endif #ifdef BOOT_LIBRARY vmArgs.options[optionIndex++].optionString - = const_cast("-Davian.bootstrap=" BOOT_LIBRARY); + = const_cast("-Davian.bootstrap=" BOOT_LIBRARY); #endif #ifdef BOOT_BUILTINS vmArgs.options[optionIndex++].optionString - = const_cast("-Davian.builtins=" BOOT_BUILTINS); + = const_cast("-Davian.builtins=" BOOT_BUILTINS); #endif #define CLASSPATH_PROPERTY "-Djava.class.path=" unsigned classpathSize = strlen(classpath); - unsigned classpathPropertyBufferSize - = sizeof(CLASSPATH_PROPERTY) + classpathSize; + unsigned classpathPropertyBufferSize = sizeof(CLASSPATH_PROPERTY) + + classpathSize; RUNTIME_ARRAY(char, classpathPropertyBuffer, classpathPropertyBufferSize); memcpy(RUNTIME_ARRAY_BODY(classpathPropertyBuffer), @@ -238,12 +245,10 @@ main(int ac, const char** av) classpathSize + 1); vmArgs.options[optionIndex++].optionString - = RUNTIME_ARRAY_BODY(classpathPropertyBuffer); + = RUNTIME_ARRAY_BODY(classpathPropertyBuffer); for (int i = 1; i < ac; ++i) { - if (strncmp(av[i], "-X", 2) == 0 - or strncmp(av[i], "-D", 2) == 0) - { + if (strncmp(av[i], "-X", 2) == 0 or strncmp(av[i], "-D", 2) == 0) { vmArgs.options[optionIndex++].optionString = const_cast(av[i]); } } @@ -276,7 +281,7 @@ main(int ac, const char** av) for (int i = 0; i < argc; ++i) { e->SetObjectArrayElement(a, i, e->NewStringUTF(argv[i])); } - + e->CallStaticVoidMethod(c, m, a); } } diff --git a/src/openjdk/jni_md.h b/src/openjdk/jni_md.h index a14542a68a..aea3786dec 100644 --- a/src/openjdk/jni_md.h +++ b/src/openjdk/jni_md.h @@ -14,13 +14,12 @@ #include "stdint.h" #if (defined __MINGW32__) || (defined _MSC_VER) -# define JNIEXPORT __declspec(dllexport) -# define JNICALL __stdcall -#else // not (defined __MINGW32__) || (defined _MSC_VER) -# define JNIEXPORT __attribute__ ((visibility("default"))) \ - __attribute__ ((used)) -# define JNICALL -#endif // not (defined __MINGW32__) || (defined _MSC_VER) +#define JNIEXPORT __declspec(dllexport) +#define JNICALL __stdcall +#else // not (defined __MINGW32__) || (defined _MSC_VER) +#define JNIEXPORT __attribute__((visibility("default"))) __attribute__((used)) +#define JNICALL +#endif // not (defined __MINGW32__) || (defined _MSC_VER) #define JNIIMPORT @@ -28,4 +27,4 @@ typedef int32_t jint; typedef int64_t jlong; typedef int8_t jbyte; -#endif//JNI_MD_H +#endif // JNI_MD_H diff --git a/src/openjdk/stubs.cpp b/src/openjdk/stubs.cpp index af6a1d15e2..c2175fdd34 100644 --- a/src/openjdk/stubs.cpp +++ b/src/openjdk/stubs.cpp @@ -2,14 +2,12 @@ using namespace vm; -extern "C" AVIAN_EXPORT jint JNICALL -net_JNI_OnLoad(JavaVM*, void*) +extern "C" AVIAN_EXPORT jint JNICALL net_JNI_OnLoad(JavaVM*, void*) { return 0; } -extern "C" AVIAN_EXPORT jint JNICALL -management_JNI_OnLoad(JavaVM*, void*) +extern "C" AVIAN_EXPORT jint JNICALL management_JNI_OnLoad(JavaVM*, void*) { return 0; } diff --git a/src/process.cpp b/src/process.cpp index 14181147f1..2034ca5f08 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -16,8 +16,7 @@ using namespace vm; namespace { -unsigned -mangledSize(int8_t c) +unsigned mangledSize(int8_t c) { switch (c) { case '_': @@ -33,8 +32,7 @@ mangledSize(int8_t c) } } -unsigned -mangle(int8_t c, char* dst) +unsigned mangle(int8_t c, char* dst) { switch (c) { case '/': @@ -61,78 +59,81 @@ mangle(int8_t c, char* dst) return 6; default: - dst[0] = c; + dst[0] = c; return 1; } } -unsigned -jniNameLength(Thread* t, object method, bool decorate) +unsigned jniNameLength(Thread* t UNUSED, GcMethod* method, bool decorate) { unsigned size = 0; - object className = ::className(t, methodClass(t, method)); - for (unsigned i = 0; i < byteArrayLength(t, className) - 1; ++i) { - size += mangledSize(byteArrayBody(t, className, i)); + GcByteArray* className = method->class_()->name(); + for (unsigned i = 0; i < className->length() - 1; ++i) { + size += mangledSize(className->body()[i]); } - ++ size; + ++size; - object methodName = ::methodName(t, method); - for (unsigned i = 0; i < byteArrayLength(t, methodName) - 1; ++i) { - size += mangledSize(byteArrayBody(t, methodName, i)); + GcByteArray* methodName = method->name(); + for (unsigned i = 0; i < methodName->length() - 1; ++i) { + size += mangledSize(methodName->body()[i]); } if (decorate) { size += 2; - object methodSpec = ::methodSpec(t, method); - for (unsigned i = 1; i < byteArrayLength(t, methodSpec) - 1 - and byteArrayBody(t, methodSpec, i) != ')'; ++i) - { - size += mangledSize(byteArrayBody(t, methodSpec, i)); + GcByteArray* methodSpec = method->spec(); + for (unsigned i = 1; + i < methodSpec->length() - 1 and methodSpec->body()[i] != ')'; + ++i) { + size += mangledSize(methodSpec->body()[i]); } } return size; } -void -makeJNIName(Thread* t, const char* prefix, unsigned prefixLength, char* name, - object method, bool decorate) +void makeJNIName(Thread* t UNUSED, + const char* prefix, + unsigned prefixLength, + char* name, + GcMethod* method, + bool decorate) { memcpy(name, prefix, prefixLength); name += prefixLength; - object className = ::className(t, methodClass(t, method)); - for (unsigned i = 0; i < byteArrayLength(t, className) - 1; ++i) { - name += mangle(byteArrayBody(t, className, i), name); + GcByteArray* className = method->class_()->name(); + for (unsigned i = 0; i < className->length() - 1; ++i) { + name += mangle(className->body()[i], name); } *(name++) = '_'; - object methodName = ::methodName(t, method); - for (unsigned i = 0; i < byteArrayLength(t, methodName) - 1; ++i) { - name += mangle(byteArrayBody(t, methodName, i), name); + GcByteArray* methodName = method->name(); + for (unsigned i = 0; i < methodName->length() - 1; ++i) { + name += mangle(methodName->body()[i], name); } - + if (decorate) { *(name++) = '_'; *(name++) = '_'; - object methodSpec = ::methodSpec(t, method); - for (unsigned i = 1; i < byteArrayLength(t, methodSpec) - 1 - and byteArrayBody(t, methodSpec, i) != ')'; ++i) - { - name += mangle(byteArrayBody(t, methodSpec, i), name); + GcByteArray* methodSpec = method->spec(); + for (unsigned i = 1; + i < methodSpec->length() - 1 and methodSpec->body()[i] != ')'; + ++i) { + name += mangle(methodSpec->body()[i], name); } } *(name++) = 0; } -void* -resolveNativeMethod(Thread* t, const char* undecorated, const char* decorated) +void* resolveNativeMethod(Thread* t, + const char* undecorated, + const char* decorated) { for (System::Library* lib = t->m->libraries; lib; lib = lib->next()) { void* p = lib->resolve(undecorated); @@ -149,23 +150,30 @@ resolveNativeMethod(Thread* t, const char* undecorated, const char* decorated) return 0; } -void* -resolveNativeMethod(Thread* t, object method, const char* prefix, - unsigned prefixLength, int footprint UNUSED) +void* resolveNativeMethod(Thread* t, + GcMethod* method, + const char* prefix, + unsigned prefixLength, + int footprint UNUSED) { unsigned undecoratedSize = prefixLength + jniNameLength(t, method, false); // extra 6 is for code below: THREAD_RUNTIME_ARRAY(t, char, undecorated, undecoratedSize + 1 + 6); - makeJNIName(t, prefix, prefixLength, RUNTIME_ARRAY_BODY(undecorated) + 1, - method, false); + makeJNIName(t, + prefix, + prefixLength, + RUNTIME_ARRAY_BODY(undecorated) + 1, + method, + false); unsigned decoratedSize = prefixLength + jniNameLength(t, method, true); // extra 6 is for code below: THREAD_RUNTIME_ARRAY(t, char, decorated, decoratedSize + 1 + 6); - makeJNIName(t, prefix, prefixLength, RUNTIME_ARRAY_BODY(decorated) + 1, - method, true); + makeJNIName( + t, prefix, prefixLength, RUNTIME_ARRAY_BODY(decorated) + 1, method, true); - void* p = resolveNativeMethod(t, RUNTIME_ARRAY_BODY(undecorated) + 1, + void* p = resolveNativeMethod(t, + RUNTIME_ARRAY_BODY(undecorated) + 1, RUNTIME_ARRAY_BODY(decorated) + 1); if (p) { return p; @@ -175,27 +183,32 @@ resolveNativeMethod(Thread* t, object method, const char* prefix, // on windows, we also try the _%s@%d and %s@%d variants if (footprint == -1) { footprint = methodParameterFootprint(t, method) + 1; - if (methodFlags(t, method) & ACC_STATIC) { - ++ footprint; + if (method->flags() & ACC_STATIC) { + ++footprint; } } *RUNTIME_ARRAY_BODY(undecorated) = '_'; - vm::snprintf(RUNTIME_ARRAY_BODY(undecorated) + undecoratedSize + 1, 5, "@%d", + vm::snprintf(RUNTIME_ARRAY_BODY(undecorated) + undecoratedSize + 1, + 5, + "@%d", footprint * BytesPerWord); *RUNTIME_ARRAY_BODY(decorated) = '_'; - vm::snprintf(RUNTIME_ARRAY_BODY(decorated) + decoratedSize + 1, 5, "@%d", + vm::snprintf(RUNTIME_ARRAY_BODY(decorated) + decoratedSize + 1, + 5, + "@%d", footprint * BytesPerWord); - p = resolveNativeMethod(t, RUNTIME_ARRAY_BODY(undecorated), - RUNTIME_ARRAY_BODY(decorated)); + p = resolveNativeMethod( + t, RUNTIME_ARRAY_BODY(undecorated), RUNTIME_ARRAY_BODY(decorated)); if (p) { return p; } // one more try without the leading underscore - p = resolveNativeMethod(t, RUNTIME_ARRAY_BODY(undecorated) + 1, + p = resolveNativeMethod(t, + RUNTIME_ARRAY_BODY(undecorated) + 1, RUNTIME_ARRAY_BODY(decorated) + 1); if (p) { return p; @@ -205,8 +218,7 @@ resolveNativeMethod(Thread* t, object method, const char* prefix, return 0; } -object -resolveNativeMethod(Thread* t, object method) +GcNative* resolveNativeMethod(Thread* t, GcMethod* method) { void* p = resolveNativeMethod(t, method, "Avian_", 6, 3); if (p) { @@ -221,64 +233,62 @@ resolveNativeMethod(Thread* t, object method) return 0; } -} // namespace +} // namespace namespace vm { -void -resolveNative(Thread* t, object method) +void resolveNative(Thread* t, GcMethod* method) { PROTECT(t, method); - assert(t, methodFlags(t, method) & ACC_NATIVE); + assertT(t, method->flags() & ACC_NATIVE); - initClass(t, methodClass(t, method)); + initClass(t, method->class_()); - if (methodRuntimeDataNative(t, getMethodRuntimeData(t, method)) == 0) { - object native = resolveNativeMethod(t, method); + if (getMethodRuntimeData(t, method)->native() == 0) { + GcNative* native = resolveNativeMethod(t, method); if (UNLIKELY(native == 0)) { - throwNew(t, Machine::UnsatisfiedLinkErrorType, "%s.%s%s", - &byteArrayBody(t, className(t, methodClass(t, method)), 0), - &byteArrayBody(t, methodName(t, method), 0), - &byteArrayBody(t, methodSpec(t, method), 0)); + throwNew(t, + GcUnsatisfiedLinkError::Type, + "%s.%s%s", + method->class_()->name()->body().begin(), + method->name()->body().begin(), + method->spec()->body().begin()); } PROTECT(t, native); - object runtimeData = getMethodRuntimeData(t, method); + GcMethodRuntimeData* runtimeData = getMethodRuntimeData(t, method); // ensure other threads only see the methodRuntimeDataNative field // populated once the object it points to has been populated: storeStoreMemoryBarrier(); - set(t, runtimeData, MethodRuntimeDataNative, native); - } + runtimeData->setNative(t, native); + } } -int -findLineNumber(Thread* t, object method, unsigned ip) +int findLineNumber(Thread* t UNUSED, GcMethod* method, unsigned ip) { - if (methodFlags(t, method) & ACC_NATIVE) { + if (method->flags() & ACC_NATIVE) { return NativeLine; } // our parameter indicates the instruction following the one we care // about, so we back up first: - -- ip; + --ip; - object code = methodCode(t, method); - object lnt = codeLineNumberTable(t, code); + GcLineNumberTable* lnt = method->code()->lineNumberTable(); if (lnt) { unsigned bottom = 0; - unsigned top = lineNumberTableLength(t, lnt); + unsigned top = lnt->length(); for (unsigned span = top - bottom; span; span = top - bottom) { unsigned middle = bottom + (span / 2); - uint64_t ln = lineNumberTableBody(t, lnt, middle); + uint64_t ln = lnt->body()[middle]; if (ip >= lineNumberIp(ln) - and (middle + 1 == lineNumberTableLength(t, lnt) - or ip < lineNumberIp(lineNumberTableBody(t, lnt, middle + 1)))) - { + and (middle + 1 == lnt->length() + or ip < lineNumberIp(lnt->body()[middle + 1]))) { return lineNumberLine(ln); } else if (ip < lineNumberIp(ln)) { top = middle; @@ -287,8 +297,8 @@ findLineNumber(Thread* t, object method, unsigned ip) } } - if (top < lineNumberTableLength(t, lnt)) { - return lineNumberLine(lineNumberTableBody(t, lnt, top)); + if (top < lnt->length()) { + return lineNumberLine(lnt->body()[top]); } else { return UnknownLine; } @@ -297,4 +307,4 @@ findLineNumber(Thread* t, object method, unsigned ip) } } -} // namespace vm +} // namespace vm diff --git a/src/system/posix.cpp b/src/system/posix.cpp index 3ccec3b372..1fb94e58e2 100644 --- a/src/system/posix.cpp +++ b/src/system/posix.cpp @@ -9,29 +9,29 @@ details. */ #ifndef __STDC_CONSTANT_MACROS -# define __STDC_CONSTANT_MACROS +#define __STDC_CONSTANT_MACROS #endif #include "sys/types.h" #ifdef __APPLE__ -# include "CoreFoundation/CoreFoundation.h" -# include "sys/ucontext.h" -# undef assert +#include "CoreFoundation/CoreFoundation.h" +#include "sys/ucontext.h" +#undef assert #elif defined(__ANDROID__) -# include /* for sigcontext */ -# include /* for stack_t */ - typedef struct ucontext { - unsigned long uc_flags; - struct ucontext *uc_link; - stack_t uc_stack; - struct sigcontext uc_mcontext; - unsigned long uc_sigmask; - } ucontext_t; +#include /* for sigcontext */ +#include /* for stack_t */ +typedef struct ucontext { + unsigned long uc_flags; + struct ucontext* uc_link; + stack_t uc_stack; + struct sigcontext uc_mcontext; + unsigned long uc_sigmask; +} ucontext_t; #else -# if defined __FreeBSD__ -# include "limits.h" -# endif -# include "ucontext.h" +#if defined __FreeBSD__ +#include "limits.h" +#endif +#include "ucontext.h" #endif #include "sys/mman.h" @@ -56,8 +56,7 @@ #include #include - -#define ACQUIRE(x) MutexResource MAKE_NAME(mutexResource_) (x) +#define ACQUIRE(x) MutexResource MAKE_NAME(mutexResource_)(x) using namespace vm; using namespace avian::util; @@ -66,11 +65,13 @@ namespace { class MutexResource { public: - MutexResource(pthread_mutex_t& m): m(&m) { + MutexResource(pthread_mutex_t& m) : m(&m) + { pthread_mutex_lock(&m); } - ~MutexResource() { + ~MutexResource() + { pthread_mutex_unlock(m); } @@ -92,25 +93,22 @@ const unsigned SignalCount = 3; class MySystem; MySystem* system; -void -handleSignal(int signal, siginfo_t* info, void* context); +void handleSignal(int signal, siginfo_t* info, void* context); -void* -run(void* r) +void* run(void* r) { static_cast(r)->run(); return 0; } -void -pathOfExecutable(System* s, const char** retBuf, unsigned* size) +void pathOfExecutable(System* s, const char** retBuf, unsigned* size) { #ifdef __APPLE__ CFBundleRef bundle = CFBundleGetMainBundle(); CFURLRef url = CFBundleCopyExecutableURL(bundle); CFStringRef path = CFURLCopyPath(url); - path = CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, - path, CFSTR("")); + path = CFURLCreateStringByReplacingPercentEscapes( + kCFAllocatorDefault, path, CFSTR("")); CFIndex pathSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path); char* buffer = reinterpret_cast(allocate(s, pathSize)); if (CFStringGetFileSystemRepresentation(path, buffer, pathSize)) { @@ -130,21 +128,18 @@ const bool Verbose = false; const unsigned Notified = 1 << 0; -class MySystem: public System { +class MySystem : public System { public: - class Thread: public System::Thread { + class Thread : public System::Thread { public: - Thread(System* s, System::Runnable* r): - s(s), - r(r), - next(0), - flags(0) + Thread(System* s, System::Runnable* r) : s(s), r(r), next(0), flags(0) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&condition, 0); } - virtual void interrupt() { + virtual void interrupt() + { ACQUIRE(mutex); r->setInterrupted(true); @@ -158,7 +153,8 @@ class MySystem: public System { expect(s, rv == 0); } - virtual bool getAndClearInterrupted() { + virtual bool getAndClearInterrupted() + { ACQUIRE(mutex); bool interrupted = r->interrupted(); @@ -168,12 +164,14 @@ class MySystem: public System { return interrupted; } - virtual void join() { + virtual void join() + { int rv UNUSED = pthread_join(thread, 0); expect(s, rv == 0); } - virtual void dispose() { + virtual void dispose() + { pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condition); ::free(this); @@ -188,21 +186,25 @@ class MySystem: public System { unsigned flags; }; - class Mutex: public System::Mutex { + class Mutex : public System::Mutex { public: - Mutex(System* s): s(s) { - pthread_mutex_init(&mutex, 0); + Mutex(System* s) : s(s) + { + pthread_mutex_init(&mutex, 0); } - virtual void acquire() { + virtual void acquire() + { pthread_mutex_lock(&mutex); } - virtual void release() { + virtual void release() + { pthread_mutex_unlock(&mutex); } - virtual void dispose() { + virtual void dispose() + { pthread_mutex_destroy(&mutex); ::free(this); } @@ -211,17 +213,19 @@ class MySystem: public System { pthread_mutex_t mutex; }; - class Monitor: public System::Monitor { + class Monitor : public System::Monitor { public: - Monitor(System* s): s(s), owner_(0), first(0), last(0), depth(0) { - pthread_mutex_init(&mutex, 0); + Monitor(System* s) : s(s), owner_(0), first(0), last(0), depth(0) + { + pthread_mutex_init(&mutex, 0); } - virtual bool tryAcquire(System::Thread* context) { + virtual bool tryAcquire(System::Thread* context) + { Thread* t = static_cast(context); if (owner_ == t) { - ++ depth; + ++depth; return true; } else { switch (pthread_mutex_trylock(&mutex)) { @@ -230,7 +234,7 @@ class MySystem: public System { case 0: owner_ = t; - ++ depth; + ++depth; return true; default: @@ -239,21 +243,23 @@ class MySystem: public System { } } - virtual void acquire(System::Thread* context) { + virtual void acquire(System::Thread* context) + { Thread* t = static_cast(context); if (owner_ != t) { pthread_mutex_lock(&mutex); owner_ = t; } - ++ depth; + ++depth; } - virtual void release(System::Thread* context) { + virtual void release(System::Thread* context) + { Thread* t = static_cast(context); if (owner_ == t) { - if (-- depth == 0) { + if (--depth == 0) { owner_ = 0; pthread_mutex_unlock(&mutex); } @@ -262,7 +268,8 @@ class MySystem: public System { } } - void append(Thread* t) { + void append(Thread* t) + { #ifndef NDEBUG for (Thread* x = first; x; x = x->next) { expect(s, t != x); @@ -278,7 +285,8 @@ class MySystem: public System { } } - void remove(Thread* t) { + void remove(Thread* t) + { Thread* previous = 0; for (Thread* current = first; current;) { if (t == current) { @@ -309,7 +317,8 @@ class MySystem: public System { #endif } - virtual void wait(System::Thread* context, int64_t time) { + virtual void wait(System::Thread* context, int64_t time) + { wait(context, time, false); } @@ -318,7 +327,8 @@ class MySystem: public System { return wait(context, time, true); } - bool wait(System::Thread* context, int64_t time, bool clearInterrupted) { + bool wait(System::Thread* context, int64_t time, bool clearInterrupted) + { Thread* t = static_cast(context); if (owner_ == t) { @@ -327,8 +337,9 @@ class MySystem: public System { bool notified = false; unsigned depth = 0; - { ACQUIRE(t->mutex); - + { + ACQUIRE(t->mutex); + expect(s, (t->flags & Notified) == 0); interrupted = t->r->interrupted(); @@ -348,10 +359,10 @@ class MySystem: public System { // milliseconds) is infinity so as to avoid overflow: if (time and time < INT64_C(31536000000000000)) { int64_t then = s->now() + time; - timespec ts = { static_cast(then / 1000), - static_cast((then % 1000) * 1000 * 1000) }; - int rv UNUSED = pthread_cond_timedwait - (&(t->condition), &(t->mutex), &ts); + timespec ts = {static_cast(then / 1000), + static_cast((then % 1000) * 1000 * 1000)}; + int rv UNUSED + = pthread_cond_timedwait(&(t->condition), &(t->mutex), &ts); expect(s, rv == 0 or rv == ETIMEDOUT or rv == EINTR); } else { int rv UNUSED = pthread_cond_wait(&(t->condition), &(t->mutex)); @@ -369,7 +380,8 @@ class MySystem: public System { pthread_mutex_lock(&mutex); - { ACQUIRE(t->mutex); + { + ACQUIRE(t->mutex); t->flags = 0; } @@ -394,7 +406,8 @@ class MySystem: public System { } } - void doNotify(Thread* t) { + void doNotify(Thread* t) + { ACQUIRE(t->mutex); t->flags |= Notified; @@ -402,7 +415,8 @@ class MySystem: public System { expect(s, rv == 0); } - virtual void notify(System::Thread* context) { + virtual void notify(System::Thread* context) + { Thread* t = static_cast(context); if (owner_ == t) { @@ -421,7 +435,8 @@ class MySystem: public System { } } - virtual void notifyAll(System::Thread* context) { + virtual void notifyAll(System::Thread* context) + { Thread* t = static_cast(context); if (owner_ == t) { @@ -433,12 +448,14 @@ class MySystem: public System { sysAbort(s); } } - - virtual System::Thread* owner() { + + virtual System::Thread* owner() + { return owner_; } - virtual void dispose() { + virtual void dispose() + { expect(s, owner_ == 0); pthread_mutex_destroy(&mutex); ::free(this); @@ -452,23 +469,27 @@ class MySystem: public System { unsigned depth; }; - class Local: public System::Local { + class Local : public System::Local { public: - Local(System* s): s(s) { + Local(System* s) : s(s) + { int r UNUSED = pthread_key_create(&key, 0); expect(s, r == 0); } - virtual void* get() { + virtual void* get() + { return pthread_getspecific(key); } - virtual void set(void* p) { + virtual void set(void* p) + { int r UNUSED = pthread_setspecific(key, p); expect(s, r == 0); } - virtual void dispose() { + virtual void dispose() + { int r UNUSED = pthread_key_delete(key); expect(s, r == 0); @@ -479,23 +500,25 @@ class MySystem: public System { pthread_key_t key; }; - class Region: public System::Region { + class Region : public System::Region { public: - Region(System* s, uint8_t* start, size_t length): - s(s), - start_(start), - length_(length) - { } + Region(System* s, uint8_t* start, size_t length) + : s(s), start_(start), length_(length) + { + } - virtual const uint8_t* start() { + virtual const uint8_t* start() + { return start_; } - virtual size_t length() { + virtual size_t length() + { return length_; } - virtual void dispose() { + virtual void dispose() + { if (start_) { munmap(start_, length_); } @@ -507,11 +530,14 @@ class MySystem: public System { size_t length_; }; - class Directory: public System::Directory { + class Directory : public System::Directory { public: - Directory(System* s, DIR* directory): s(s), directory(directory) { } + Directory(System* s, DIR* directory) : s(s), directory(directory) + { + } - virtual const char* next() { + virtual const char* next() + { if (directory) { dirent* e = readdir(directory); if (e) { @@ -521,7 +547,8 @@ class MySystem: public System { return 0; } - virtual void dispose() { + virtual void dispose() + { if (directory) { closedir(directory); } @@ -532,40 +559,50 @@ class MySystem: public System { DIR* directory; }; - class Library: public System::Library { + class Library : public System::Library { public: - Library(System* s, void* p, const char* name, unsigned nameLength, - bool isMain): - s(s), - p(p), - mainExecutable(isMain), - name_(name), - nameLength(nameLength), - next_(0) - { } + Library(System* s, + void* p, + const char* name, + unsigned nameLength, + bool isMain) + : s(s), + p(p), + mainExecutable(isMain), + name_(name), + nameLength(nameLength), + next_(0) + { + } - virtual void* resolve(const char* function) { + virtual void* resolve(const char* function) + { return dlsym(p, function); } - virtual const char* name() { + virtual const char* name() + { return name_; } - virtual System::Library* next() { + virtual System::Library* next() + { return next_; } - virtual void setNext(System::Library* lib) { + virtual void setNext(System::Library* lib) + { next_ = lib; } - virtual void disposeAll() { + virtual void disposeAll() + { if (Verbose) { fprintf(stderr, "close %p\n", p); } - if (not mainExecutable) dlclose(p); + if (not mainExecutable) + dlclose(p); if (next_) { next_->disposeAll(); @@ -586,9 +623,7 @@ class MySystem: public System { System::Library* next_; }; - MySystem(): - threadVisitor(0), - visitTarget(0) + MySystem() : threadVisitor(0), visitTarget(0) { expect(this, system == 0); system = this; @@ -601,30 +636,36 @@ class MySystem: public System { } // Returns true on success, false on failure - bool unregisterHandler(int index) { + bool unregisterHandler(int index) + { return sigaction(signals[index], oldHandlers + index, 0) == 0; } // Returns true on success, false on failure - bool registerHandler(int index) { + bool registerHandler(int index) + { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sigemptyset(&(sa.sa_mask)); sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = handleSignal; - + return sigaction(signals[index], &sa, oldHandlers + index) == 0; } - virtual void* tryAllocate(unsigned sizeInBytes) { + virtual void* tryAllocate(unsigned sizeInBytes) + { return malloc(sizeInBytes); } - virtual void free(const void* p) { - if (p) ::free(const_cast(p)); + virtual void free(const void* p) + { + if (p) + ::free(const_cast(p)); } - virtual void* tryAllocateExecutable(unsigned sizeInBytes) { + virtual void* tryAllocateExecutable(unsigned sizeInBytes) + { #ifdef MAP_32BIT // map to the lower 32 bits of memory when possible so as to avoid // expensive relative jumps @@ -633,34 +674,42 @@ class MySystem: public System { const unsigned Extra = 0; #endif - void* p = mmap(0, sizeInBytes, PROT_EXEC | PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON | Extra, -1, 0); + void* p = mmap(0, + sizeInBytes, + PROT_EXEC | PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON | Extra, + -1, + 0); if (p == MAP_FAILED) { return 0; } else { -// fprintf(stderr, "executable from %p to %p\n", p, -// static_cast(p) + sizeInBytes); + // fprintf(stderr, "executable from %p to %p\n", p, + // static_cast(p) + sizeInBytes); return static_cast(p); } } - virtual void freeExecutable(const void* p, unsigned sizeInBytes) { + virtual void freeExecutable(const void* p, unsigned sizeInBytes) + { munmap(const_cast(p), sizeInBytes); } - virtual bool success(Status s) { + virtual bool success(Status s) + { return s == 0; } - virtual Status attach(Runnable* r) { + virtual Status attach(Runnable* r) + { Thread* t = new (allocate(this, sizeof(Thread))) Thread(this, r); t->thread = pthread_self(); r->attach(t); return 0; } - virtual Status start(Runnable* r) { + virtual Status start(Runnable* r) + { Thread* t = new (allocate(this, sizeof(Thread))) Thread(this, r); r->attach(t); int rv UNUSED = pthread_create(&(t->thread), 0, run, r); @@ -668,25 +717,29 @@ class MySystem: public System { return 0; } - virtual Status make(System::Mutex** m) { + virtual Status make(System::Mutex** m) + { *m = new (allocate(this, sizeof(Mutex))) Mutex(this); return 0; } - virtual Status make(System::Monitor** m) { + virtual Status make(System::Monitor** m) + { *m = new (allocate(this, sizeof(Monitor))) Monitor(this); return 0; } - virtual Status make(System::Local** l) { + virtual Status make(System::Local** l) + { *l = new (allocate(this, sizeof(Local))) Local(this); return 0; } - virtual Status visit(System::Thread* st UNUSED, System::Thread* sTarget, + virtual Status visit(System::Thread* st UNUSED, + System::Thread* sTarget, ThreadVisitor* visitor) { - assert(this, st != sTarget); + assertT(this, st != sTarget); Thread* target = static_cast(sTarget); @@ -698,14 +751,17 @@ class MySystem: public System { mach_port_t port = pthread_mach_thread_np(target->thread); - if (thread_suspend(port)) return -1; + if (thread_suspend(port)) + return -1; THREAD_STATE_TYPE state; mach_msg_type_number_t stateCount = THREAD_STATE_COUNT; - kern_return_t rv = thread_get_state - (port, THREAD_STATE, reinterpret_cast(&state), - &stateCount); - + kern_return_t rv + = thread_get_state(port, + THREAD_STATE, + reinterpret_cast(&state), + &stateCount); + if (rv == 0) { visitor->visit(reinterpret_cast(THREAD_STATE_IP(state)), reinterpret_cast(THREAD_STATE_STACK(state)), @@ -715,12 +771,13 @@ class MySystem: public System { thread_resume(port); return rv ? -1 : 0; -#else // not __APPLE__ +#else // not __APPLE__ Thread* t = static_cast(st); ACQUIRE_MONITOR(t, visitLock); - while (threadVisitor) visitLock->wait(t, 0); + while (threadVisitor) + visitLock->wait(t, 0); threadVisitor = visitor; visitTarget = target; @@ -729,7 +786,8 @@ class MySystem: public System { int result; if (rv == 0) { - while (visitTarget) visitLock->wait(t, 0); + while (visitTarget) + visitLock->wait(t, 0); result = 0; } else { @@ -743,10 +801,11 @@ class MySystem: public System { system->visitLock->notifyAll(t); return result; -#endif // not __APPLE__ +#endif // not __APPLE__ } - virtual Status map(System::Region** region, const char* name) { + virtual Status map(System::Region** region, const char* name) + { Status status = 1; int fd = ::open(name, O_RDONLY); @@ -757,29 +816,31 @@ class MySystem: public System { void* data = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (data) { *region = new (allocate(this, sizeof(Region))) - Region(this, static_cast(data), s.st_size); + Region(this, static_cast(data), s.st_size); status = 0; } } close(fd); } - + return status; } - virtual Status open(System::Directory** directory, const char* name) { + virtual Status open(System::Directory** directory, const char* name) + { Status status = 1; - + DIR* d = opendir(name); if (d) { *directory = new (allocate(this, sizeof(Directory))) Directory(this, d); status = 0; } - + return status; } - virtual FileType stat(const char* name, unsigned* length) { + virtual FileType stat(const char* name, unsigned* length) + { #ifdef __FreeBSD__ // Now the hack below causes the error "Dereferencing type-punned // pointer will break strict aliasing rules", so another workaround @@ -816,15 +877,18 @@ class MySystem: public System { } } - virtual const char* libraryPrefix() { + virtual const char* libraryPrefix() + { return SO_PREFIX; } - virtual const char* librarySuffix() { + virtual const char* librarySuffix() + { return SO_SUFFIX; } - virtual const char* toAbsolutePath(Allocator* allocator, const char* name) { + virtual const char* toAbsolutePath(Allocator* allocator, const char* name) + { if (name[0] == '/') { return copy(allocator, name); } else { @@ -833,8 +897,7 @@ class MySystem: public System { } } - virtual Status load(System::Library** lib, - const char* name) + virtual Status load(System::Library** lib, const char* name) { unsigned nameLength = (name ? strlen(name) : 0); bool isMain = name == 0; @@ -842,7 +905,7 @@ class MySystem: public System { pathOfExecutable(this, &name, &nameLength); } void* p = dlopen(name, RTLD_LAZY | RTLD_LOCAL); - + if (p) { if (Verbose) { fprintf(stderr, "open %s as %p\n", name, p); @@ -860,7 +923,7 @@ class MySystem: public System { } *lib = new (allocate(this, sizeof(Library))) - Library(this, p, n, nameLength, isMain); + Library(this, p, n, nameLength, isMain); return 0; } else { @@ -871,34 +934,41 @@ class MySystem: public System { } } - virtual char pathSeparator() { + virtual char pathSeparator() + { return ':'; } - virtual char fileSeparator() { + virtual char fileSeparator() + { return '/'; } - virtual int64_t now() { - timeval tv = { 0, 0 }; + virtual int64_t now() + { + timeval tv = {0, 0}; gettimeofday(&tv, 0); - return (static_cast(tv.tv_sec) * 1000) + - (static_cast(tv.tv_usec) / 1000); + return (static_cast(tv.tv_sec) * 1000) + + (static_cast(tv.tv_usec) / 1000); } - virtual void yield() { + virtual void yield() + { sched_yield(); } - virtual void exit(int code) { + virtual void exit(int code) + { ::exit(code); } - virtual void abort() { + virtual void abort() + { avian::system::crash(); } - virtual void dispose() { + virtual void dispose() + { visitLock->dispose(); expect(this, unregisterHandler(InterruptSignalIndex)); @@ -944,14 +1014,13 @@ void handleSignal(int signal, siginfo_t*, void* context) } } -} // namespace +} // namespace namespace vm { -AVIAN_EXPORT System* -makeSystem() +AVIAN_EXPORT System* makeSystem() { return new (malloc(sizeof(MySystem))) MySystem(); } -} // namespace vm +} // namespace vm diff --git a/src/system/posix/signal.cpp b/src/system/posix/signal.cpp index d10051108b..257808ff87 100644 --- a/src/system/posix/signal.cpp +++ b/src/system/posix/signal.cpp @@ -40,7 +40,6 @@ namespace system { namespace posix { - const int InvalidSignal = -1; const int SegFaultSignal = SIGSEGV; const unsigned SegFaultSignalIndex = 0; @@ -53,11 +52,9 @@ const unsigned AltSegFaultSignalIndex = 1; const int DivideByZeroSignal = SIGFPE; const unsigned DivideByZeroSignalIndex = 2; -const int signals[] - = {SegFaultSignal, AltSegFaultSignal, DivideByZeroSignal}; +const int signals[] = {SegFaultSignal, AltSegFaultSignal, DivideByZeroSignal}; const unsigned SignalCount = 3; - } struct SignalRegistrar::Data { @@ -68,7 +65,7 @@ struct SignalRegistrar::Data { Data() { - if(instance) { + if (instance) { crash(); } @@ -125,8 +122,8 @@ void handleSignal(int signal, siginfo_t*, void* context) crash(); } - bool jump - = SignalRegistrar::Data::instance->handlers[index]->handleSignal(&ip, &frame, &stack, &thread); + bool jump = SignalRegistrar::Data::instance->handlers[index]->handleSignal( + &ip, &frame, &stack, &thread); if (jump) { // I'd like to use setcontext here (and get rid of the @@ -150,7 +147,7 @@ void handleSignal(int signal, siginfo_t*, void* context) } } -} // namespace posix +} // namespace posix NO_RETURN void crash() { @@ -190,9 +187,9 @@ bool SignalRegistrar::Data::registerHandler(Handler* handler, int index) bool SignalRegistrar::registerHandler(Signal signal, Handler* handler) { - switch(signal) { + switch (signal) { case SegFault: - if(!data->registerHandler(handler, posix::SegFaultSignalIndex)) { + if (!data->registerHandler(handler, posix::SegFaultSignalIndex)) { return false; } if (posix::AltSegFaultSignal != posix::InvalidSignal) { @@ -209,9 +206,9 @@ bool SignalRegistrar::registerHandler(Signal signal, Handler* handler) bool SignalRegistrar::unregisterHandler(Signal signal) { - switch(signal) { + switch (signal) { case SegFault: - if(!data->registerHandler(0, posix::SegFaultSignalIndex)) { + if (!data->registerHandler(0, posix::SegFaultSignalIndex)) { return false; } if (posix::AltSegFaultSignal != posix::InvalidSignal) { diff --git a/src/system/windows.cpp b/src/system/windows.cpp index a8e565ce55..f6a390e797 100644 --- a/src/system/windows.cpp +++ b/src/system/windows.cpp @@ -12,11 +12,11 @@ #include "windows.h" #ifdef _MSC_VER -# define S_ISREG(x) ((x) & _S_IFREG) -# define S_ISDIR(x) ((x) & _S_IFDIR) -# define FTIME _ftime_s +#define S_ISREG(x) ((x)&_S_IFREG) +#define S_ISDIR(x) ((x)&_S_IFDIR) +#define FTIME _ftime_s #else -# define FTIME _ftime +#define FTIME _ftime #endif #undef max @@ -36,50 +36,46 @@ WaitForSingleObjectEx((hHandle), (dwMilliseconds), FALSE) #define CreateEvent(lpEventAttributes, bManualReset, bInitialState, lpName) \ - CreateEventEx((lpEventAttributes), (lpName), ((bManualReset)?CREATE_EVENT_MANUAL_RESET:0)|((bInitialState)?CREATE_EVENT_INITIAL_SET:0), EVENT_ALL_ACCESS) + CreateEventEx((lpEventAttributes), \ + (lpName), \ + ((bManualReset) ? CREATE_EVENT_MANUAL_RESET : 0) \ + | ((bInitialState) ? CREATE_EVENT_INITIAL_SET : 0), \ + EVENT_ALL_ACCESS) -#define CreateMutex(lpEventAttributes, bInitialOwner, lpName) \ - CreateMutexEx((lpEventAttributes), (lpName), (bInitialOwner)?CREATE_MUTEX_INITIAL_OWNER:0, MUTEX_ALL_ACCESS) +#define CreateMutex(lpEventAttributes, bInitialOwner, lpName) \ + CreateMutexEx((lpEventAttributes), \ + (lpName), \ + (bInitialOwner) ? CREATE_MUTEX_INITIAL_OWNER : 0, \ + MUTEX_ALL_ACCESS) #include "thread-emulation.h" #endif -#if defined(WINAPI_PARTITION_PHONE) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) -// Headers in Windows Phone 8 DevKit contain severe error, so let's define needed functions on our own -extern "C" -{ +#if defined(WINAPI_PARTITION_PHONE) \ + && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) +// Headers in Windows Phone 8 DevKit contain severe error, so let's define +// needed functions on our own +extern "C" { WINBASEAPI -_Ret_maybenull_ -HANDLE -WINAPI -CreateFileMappingFromApp( - _In_ HANDLE hFile, - _In_opt_ PSECURITY_ATTRIBUTES SecurityAttributes, - _In_ ULONG PageProtection, - _In_ ULONG64 MaximumSize, - _In_opt_ PCWSTR Name - ); +_Ret_maybenull_ HANDLE WINAPI + CreateFileMappingFromApp(_In_ HANDLE hFile, + _In_opt_ PSECURITY_ATTRIBUTES SecurityAttributes, + _In_ ULONG PageProtection, + _In_ ULONG64 MaximumSize, + _In_opt_ PCWSTR Name); WINBASEAPI -_Ret_maybenull_ __out_data_source(FILE) -PVOID -WINAPI -MapViewOfFileFromApp( - _In_ HANDLE hFileMappingObject, - _In_ ULONG DesiredAccess, - _In_ ULONG64 FileOffset, - _In_ SIZE_T NumberOfBytesToMap - ); +_Ret_maybenull_ __out_data_source(FILE) PVOID WINAPI + MapViewOfFileFromApp(_In_ HANDLE hFileMappingObject, + _In_ ULONG DesiredAccess, + _In_ ULONG64 FileOffset, + _In_ SIZE_T NumberOfBytesToMap); WINBASEAPI -BOOL -WINAPI -UnmapViewOfFile( - _In_ LPCVOID lpBaseAddress - ); +BOOL WINAPI UnmapViewOfFile(_In_ LPCVOID lpBaseAddress); } -#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) +#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE) #else @@ -93,7 +89,7 @@ UnmapViewOfFile( #endif -#define ACQUIRE(s, x) MutexResource MAKE_NAME(mutexResource_) (s, x) +#define ACQUIRE(s, x) MutexResource MAKE_NAME(mutexResource_)(s, x) using namespace vm; @@ -101,26 +97,27 @@ namespace { class MutexResource { public: - MutexResource(System* s, HANDLE m): s(s), m(m) { + MutexResource(System* s, HANDLE m) : s(s), m(m) + { int r UNUSED = WaitForSingleObject(m, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); } - ~MutexResource() { + ~MutexResource() + { bool success UNUSED = ReleaseMutex(m); - assert(s, success); + assertT(s, success); } private: - System* s; + System* s; HANDLE m; }; class MySystem; MySystem* system; -DWORD WINAPI -run(void* r) +DWORD WINAPI run(void* r) { static_cast(r)->run(); return 0; @@ -131,35 +128,33 @@ const bool Verbose = false; const unsigned Waiting = 1 << 0; const unsigned Notified = 1 << 1; -class MySystem: public System { +class MySystem : public System { public: - class Thread: public System::Thread { + class Thread : public System::Thread { public: - Thread(System* s, System::Runnable* r): - s(s), - r(r), - next(0), - flags(0) + Thread(System* s, System::Runnable* r) : s(s), r(r), next(0), flags(0) { mutex = CreateMutex(0, false, 0); - assert(s, mutex); + assertT(s, mutex); event = CreateEvent(0, true, false, 0); - assert(s, event); + assertT(s, event); } - virtual void interrupt() { + virtual void interrupt() + { ACQUIRE(s, mutex); r->setInterrupted(true); if (flags & Waiting) { int r UNUSED = SetEvent(event); - assert(s, r != 0); + assertT(s, r != 0); } } - virtual bool getAndClearInterrupted() { + virtual bool getAndClearInterrupted() + { ACQUIRE(s, mutex); bool interrupted = r->interrupted(); @@ -169,12 +164,14 @@ class MySystem: public System { return interrupted; } - virtual void join() { + virtual void join() + { int r UNUSED = WaitForSingleObject(thread, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); } - virtual void dispose() { + virtual void dispose() + { CloseHandle(event); CloseHandle(mutex); CloseHandle(thread); @@ -190,24 +187,28 @@ class MySystem: public System { unsigned flags; }; - class Mutex: public System::Mutex { + class Mutex : public System::Mutex { public: - Mutex(System* s): s(s) { + Mutex(System* s) : s(s) + { mutex = CreateMutex(0, false, 0); - assert(s, mutex); + assertT(s, mutex); } - virtual void acquire() { + virtual void acquire() + { int r UNUSED = WaitForSingleObject(mutex, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); } - virtual void release() { + virtual void release() + { bool success UNUSED = ReleaseMutex(mutex); - assert(s, success); + assertT(s, success); } - virtual void dispose() { + virtual void dispose() + { CloseHandle(mutex); ::free(this); } @@ -216,19 +217,21 @@ class MySystem: public System { HANDLE mutex; }; - class Monitor: public System::Monitor { + class Monitor : public System::Monitor { public: - Monitor(System* s): s(s), owner_(0), first(0), last(0), depth(0) { + Monitor(System* s) : s(s), owner_(0), first(0), last(0), depth(0) + { mutex = CreateMutex(0, false, 0); - assert(s, mutex); + assertT(s, mutex); } - virtual bool tryAcquire(System::Thread* context) { + virtual bool tryAcquire(System::Thread* context) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ == t) { - ++ depth; + ++depth; return true; } else { switch (WaitForSingleObject(mutex, 0)) { @@ -237,7 +240,7 @@ class MySystem: public System { case WAIT_OBJECT_0: owner_ = t; - ++ depth; + ++depth; return true; default: @@ -246,34 +249,37 @@ class MySystem: public System { } } - virtual void acquire(System::Thread* context) { + virtual void acquire(System::Thread* context) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ != t) { int r UNUSED = WaitForSingleObject(mutex, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); owner_ = t; } - ++ depth; + ++depth; } - virtual void release(System::Thread* context) { + virtual void release(System::Thread* context) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ == t) { - if (-- depth == 0) { + if (--depth == 0) { owner_ = 0; bool success UNUSED = ReleaseMutex(mutex); - assert(s, success); + assertT(s, success); } } else { sysAbort(s); } } - void append(Thread* t) { + void append(Thread* t) + { #ifndef NDEBUG for (Thread* x = first; x; x = x->next) { expect(s, t != x); @@ -288,7 +294,8 @@ class MySystem: public System { } } - void remove(Thread* t) { + void remove(Thread* t) + { Thread* previous = 0; for (Thread* current = first; current;) { if (t == current) { @@ -318,7 +325,8 @@ class MySystem: public System { #endif } - virtual void wait(System::Thread* context, int64_t time) { + virtual void wait(System::Thread* context, int64_t time) + { wait(context, time, false); } @@ -327,9 +335,10 @@ class MySystem: public System { return wait(context, time, true); } - bool wait(System::Thread* context, int64_t time, bool clearInterrupted) { + bool wait(System::Thread* context, int64_t time, bool clearInterrupted) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ == t) { // Initialized here to make gcc 4.2 a happy compiler @@ -339,7 +348,8 @@ class MySystem: public System { int r UNUSED; - { ACQUIRE(s, t->mutex); + { + ACQUIRE(s, t->mutex); expect(s, (t->flags & Notified) == 0); @@ -357,20 +367,20 @@ class MySystem: public System { owner_ = 0; bool success UNUSED = ReleaseMutex(mutex); - assert(s, success); + assertT(s, success); if (not interrupted) { success = ResetEvent(t->event); - assert(s, success); + assertT(s, success); success = ReleaseMutex(t->mutex); - assert(s, success); + assertT(s, success); r = WaitForSingleObject(t->event, (time ? time : INFINITE)); - assert(s, r == WAIT_OBJECT_0 or r == WAIT_TIMEOUT); + assertT(s, r == WAIT_OBJECT_0 or r == WAIT_TIMEOUT); r = WaitForSingleObject(t->mutex, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); interrupted = t->r->interrupted(); if (interrupted and clearInterrupted) { @@ -382,9 +392,10 @@ class MySystem: public System { } r = WaitForSingleObject(mutex, INFINITE); - assert(s, r == WAIT_OBJECT_0); + assertT(s, r == WAIT_OBJECT_0); - { ACQUIRE(s, t->mutex); + { + ACQUIRE(s, t->mutex); t->flags = 0; } @@ -409,18 +420,20 @@ class MySystem: public System { } } - void doNotify(Thread* t) { + void doNotify(Thread* t) + { ACQUIRE(s, t->mutex); t->flags |= Notified; bool success UNUSED = SetEvent(t->event); - assert(s, success); + assertT(s, success); } - virtual void notify(System::Thread* context) { + virtual void notify(System::Thread* context) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ == t) { if (first) { @@ -438,9 +451,10 @@ class MySystem: public System { } } - virtual void notifyAll(System::Thread* context) { + virtual void notifyAll(System::Thread* context) + { Thread* t = static_cast(context); - assert(s, t); + assertT(s, t); if (owner_ == t) { for (Thread* t = first; t; t = t->next) { @@ -451,13 +465,15 @@ class MySystem: public System { sysAbort(s); } } - - virtual System::Thread* owner() { + + virtual System::Thread* owner() + { return owner_; } - virtual void dispose() { - assert(s, owner_ == 0); + virtual void dispose() + { + assertT(s, owner_ == 0); CloseHandle(mutex); ::free(this); } @@ -470,25 +486,29 @@ class MySystem: public System { unsigned depth; }; - class Local: public System::Local { + class Local : public System::Local { public: - Local(System* s): s(s) { + Local(System* s) : s(s) + { key = TlsAlloc(); - assert(s, key != TLS_OUT_OF_INDEXES); + assertT(s, key != TLS_OUT_OF_INDEXES); } - virtual void* get() { + virtual void* get() + { return TlsGetValue(key); } - virtual void set(void* p) { + virtual void set(void* p) + { bool r UNUSED = TlsSetValue(key, p); - assert(s, r); + assertT(s, r); } - virtual void dispose() { + virtual void dispose() + { bool r UNUSED = TlsFree(key); - assert(s, r); + assertT(s, r); ::free(this); } @@ -497,30 +517,40 @@ class MySystem: public System { unsigned key; }; - class Region: public System::Region { + class Region : public System::Region { public: - Region(System* system, uint8_t* start, size_t length, HANDLE mapping, - HANDLE file): - system(system), - start_(start), - length_(length), - mapping(mapping), - file(file) - { } + Region(System* system, + uint8_t* start, + size_t length, + HANDLE mapping, + HANDLE file) + : system(system), + start_(start), + length_(length), + mapping(mapping), + file(file) + { + } - virtual const uint8_t* start() { + virtual const uint8_t* start() + { return start_; } - virtual size_t length() { + virtual size_t length() + { return length_; } - virtual void dispose() { + virtual void dispose() + { if (start_) { - if (start_) UnmapViewOfFile(start_); - if (mapping) CloseHandle(mapping); - if (file) CloseHandle(file); + if (start_) + UnmapViewOfFile(start_); + if (mapping) + CloseHandle(mapping); + if (file) + CloseHandle(file); } system->free(this); } @@ -532,11 +562,14 @@ class MySystem: public System { HANDLE file; }; - class Directory: public System::Directory { + class Directory : public System::Directory { public: - Directory(System* s): s(s), handle(0), findNext(false) { } + Directory(System* s) : s(s), handle(0), findNext(false) + { + } - virtual const char* next() { + virtual const char* next() + { if (handle and handle != INVALID_HANDLE_VALUE) { if (findNext) { if (FindNextFile(handle, &data)) { @@ -550,7 +583,8 @@ class MySystem: public System { return 0; } - virtual void dispose() { + virtual void dispose() + { if (handle and handle != INVALID_HANDLE_VALUE) { FindClose(handle); } @@ -563,37 +597,41 @@ class MySystem: public System { bool findNext; }; - class Library: public System::Library { + class Library : public System::Library { public: - Library(System* s, HMODULE handle, const char* name): - s(s), - handle(handle), - name_(name), - next_(0) - { } + Library(System* s, HMODULE handle, const char* name) + : s(s), handle(handle), name_(name), next_(0) + { + } - virtual void* resolve(const char* function) { + virtual void* resolve(const char* function) + { void* address; FARPROC p = GetProcAddress(handle, function); memcpy(&address, &p, BytesPerWord); return address; } - virtual const char* name() { + virtual const char* name() + { return name_; } - virtual System::Library* next() { + virtual System::Library* next() + { return next_; } - virtual void setNext(System::Library* lib) { + virtual void setNext(System::Library* lib) + { next_ = lib; } - virtual void disposeAll() { + virtual void disposeAll() + { if (Verbose) { - fprintf(stderr, "close %p\n", handle); fflush(stderr); + fprintf(stderr, "close %p\n", handle); + fflush(stderr); } if (name_) { @@ -623,72 +661,88 @@ class MySystem: public System { system = this; mutex = CreateMutex(0, false, 0); - assert(this, mutex); + assertT(this, mutex); } - virtual void* tryAllocate(unsigned sizeInBytes) { + virtual void* tryAllocate(unsigned sizeInBytes) + { return malloc(sizeInBytes); } - virtual void free(const void* p) { - if (p) ::free(const_cast(p)); + virtual void free(const void* p) + { + if (p) + ::free(const_cast(p)); } - #if !defined(AVIAN_AOT_ONLY) - virtual void* tryAllocateExecutable(unsigned sizeInBytes) { - return VirtualAlloc - (0, sizeInBytes, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); +#if !defined(AVIAN_AOT_ONLY) + virtual void* tryAllocateExecutable(unsigned sizeInBytes) + { + return VirtualAlloc( + 0, sizeInBytes, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } - virtual void freeExecutable(const void* p, unsigned) { + virtual void freeExecutable(const void* p, unsigned) + { int r UNUSED = VirtualFree(const_cast(p), 0, MEM_RELEASE); - assert(this, r); + assertT(this, r); } - #endif +#endif - virtual bool success(Status s) { + virtual bool success(Status s) + { return s == 0; } - virtual Status attach(Runnable* r) { + virtual Status attach(Runnable* r) + { Thread* t = new (allocate(this, sizeof(Thread))) Thread(this, r); - bool success UNUSED = DuplicateHandle - (GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), - &(t->thread), 0, false, DUPLICATE_SAME_ACCESS); - assert(this, success); + bool success UNUSED = DuplicateHandle(GetCurrentProcess(), + GetCurrentThread(), + GetCurrentProcess(), + &(t->thread), + 0, + false, + DUPLICATE_SAME_ACCESS); + assertT(this, success); r->attach(t); return 0; } - virtual Status start(Runnable* r) { + virtual Status start(Runnable* r) + { Thread* t = new (allocate(this, sizeof(Thread))) Thread(this, r); r->attach(t); DWORD id; t->thread = CreateThread(0, 0, run, r, 0, &id); - assert(this, t->thread); + assertT(this, t->thread); return 0; } - virtual Status make(System::Mutex** m) { + virtual Status make(System::Mutex** m) + { *m = new (allocate(this, sizeof(Mutex))) Mutex(this); return 0; } - virtual Status make(System::Monitor** m) { + virtual Status make(System::Monitor** m) + { *m = new (allocate(this, sizeof(Monitor))) Monitor(this); return 0; } - virtual Status make(System::Local** l) { + virtual Status make(System::Local** l) + { *l = new (allocate(this, sizeof(Local))) Local(this); return 0; } - virtual Status visit(System::Thread* st UNUSED, System::Thread* sTarget, + virtual Status visit(System::Thread* st UNUSED, + System::Thread* sTarget, ThreadVisitor* visitor) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - assert(this, st != sTarget); + assertT(this, st != sTarget); Thread* target = static_cast(sTarget); @@ -703,15 +757,15 @@ class MySystem: public System { rv = GetThreadContext(target->thread, &context); if (rv) { -# ifdef ARCH_x86_32 +#ifdef ARCH_x86_32 visitor->visit(reinterpret_cast(context.Eip), reinterpret_cast(context.Esp), reinterpret_cast(context.Ebp)); -# elif defined ARCH_x86_64 +#elif defined ARCH_x86_64 visitor->visit(reinterpret_cast(context.Rip), reinterpret_cast(context.Rsp), reinterpret_cast(context.Rbp)); -# endif +#endif success = true; } @@ -721,22 +775,33 @@ class MySystem: public System { return (success ? 0 : 1); #else - #pragma message("TODO: http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.application.unhandledexception(v=vs.105).aspx") +#pragma message( \ + "TODO: http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.application.unhandledexception(v=vs.105).aspx") return false; #endif } - virtual Status map(System::Region** region, const char* name) { + virtual Status map(System::Region** region, const char* name) + { Status status = 1; size_t nameLen = strlen(name) * 2; RUNTIME_ARRAY(wchar_t, wideName, nameLen + 1); - MultiByteToWideChar(CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); + MultiByteToWideChar( + CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - HANDLE file = CreateFileW(RUNTIME_ARRAY_BODY(wideName), FILE_READ_DATA, FILE_SHARE_READ, 0, - OPEN_EXISTING, 0, 0); + HANDLE file = CreateFileW(RUNTIME_ARRAY_BODY(wideName), + FILE_READ_DATA, + FILE_SHARE_READ, + 0, + OPEN_EXISTING, + 0, + 0); #else - HANDLE file = CreateFile2(RUNTIME_ARRAY_BODY(wideName), GENERIC_READ, FILE_SHARE_READ, - OPEN_EXISTING, 0); + HANDLE file = CreateFile2(RUNTIME_ARRAY_BODY(wideName), + GENERIC_READ, + FILE_SHARE_READ, + OPEN_EXISTING, + 0); #endif if (file != INVALID_HANDLE_VALUE) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) @@ -744,14 +809,16 @@ class MySystem: public System { #else FILE_STANDARD_INFO info; unsigned size = INVALID_FILE_SIZE; - if(GetFileInformationByHandleEx(file, FileStandardInfo, &info, sizeof(info))) + if (GetFileInformationByHandleEx( + file, FileStandardInfo, &info, sizeof(info))) size = info.EndOfFile.QuadPart; #endif if (size != INVALID_FILE_SIZE) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) HANDLE mapping = CreateFileMapping(file, 0, PAGE_READONLY, 0, size, 0); #else - HANDLE mapping = CreateFileMappingFromApp(file, 0, PAGE_READONLY, size, 0); + HANDLE mapping + = CreateFileMappingFromApp(file, 0, PAGE_READONLY, size, 0); #endif if (mapping) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) @@ -761,8 +828,8 @@ class MySystem: public System { #endif if (data) { *region = new (allocate(this, sizeof(Region))) - Region(this, static_cast(data), size, file, mapping); - status = 0; + Region(this, static_cast(data), size, file, mapping); + status = 0; } if (status) { @@ -775,11 +842,12 @@ class MySystem: public System { CloseHandle(file); } } - + return status; } - virtual Status open(System::Directory** directory, const char* name) { + virtual Status open(System::Directory** directory, const char* name) + { Status status = 1; unsigned length = strlen(name); @@ -792,7 +860,12 @@ class MySystem: public System { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) d->handle = FindFirstFile(RUNTIME_ARRAY_BODY(buffer), &(d->data)); #else - d->handle = FindFirstFileEx(RUNTIME_ARRAY_BODY(buffer), FindExInfoStandard, &(d->data), FindExSearchNameMatch, 0, 0); + d->handle = FindFirstFileEx(RUNTIME_ARRAY_BODY(buffer), + FindExInfoStandard, + &(d->data), + FindExSearchNameMatch, + 0, + 0); #endif if (d->handle == INVALID_HANDLE_VALUE) { d->dispose(); @@ -800,23 +873,24 @@ class MySystem: public System { *directory = d; status = 0; } - + return status; } - virtual FileType stat(const char* name, unsigned* length) { + virtual FileType stat(const char* name, unsigned* length) + { size_t nameLen = strlen(name) * 2; RUNTIME_ARRAY(wchar_t, wideName, nameLen + 1); - MultiByteToWideChar(CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); + MultiByteToWideChar( + CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); WIN32_FILE_ATTRIBUTE_DATA data; - if (GetFileAttributesExW - (RUNTIME_ARRAY_BODY(wideName), GetFileExInfoStandard, &data)) - { + if (GetFileAttributesExW( + RUNTIME_ARRAY_BODY(wideName), GetFileExInfoStandard, &data)) { if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { return TypeDirectory; } else { *length = (data.nFileSizeHigh * static_cast(MAXDWORD + 1)) - + data.nFileSizeLow; + + data.nFileSizeLow; return TypeFile; } } else { @@ -824,11 +898,13 @@ class MySystem: public System { } } - virtual const char* libraryPrefix() { + virtual const char* libraryPrefix() + { return SO_PREFIX; } - virtual const char* librarySuffix() { + virtual const char* librarySuffix() + { return SO_SUFFIX; } @@ -836,11 +912,9 @@ class MySystem: public System { const char* name) { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - if (strncmp(name, "//", 2) == 0 - or strncmp(name, "\\\\", 2) == 0 + if (strncmp(name, "//", 2) == 0 or strncmp(name, "\\\\", 2) == 0 or strncmp(name + 1, ":/", 2) == 0 - or strncmp(name + 1, ":\\", 2) == 0) - { + or strncmp(name + 1, ":\\", 2) == 0) { return copy(allocator, name); } else { TCHAR buffer[MAX_PATH]; @@ -848,20 +922,21 @@ class MySystem: public System { return append(allocator, buffer, "\\", name); } #else - #pragma message("TODO:http://lunarfrog.com/blog/2012/05/21/winrt-folders-access/ Windows.ApplicationModel.Package.Current.InstalledLocation") +#pragma message( \ + "TODO:http://lunarfrog.com/blog/2012/05/21/winrt-folders-access/ Windows.ApplicationModel.Package.Current.InstalledLocation") return copy(allocator, name); #endif } - virtual Status load(System::Library** lib, - const char* name) + virtual Status load(System::Library** lib, const char* name) { HMODULE handle; unsigned nameLength = (name ? strlen(name) : 0); if (name) { size_t nameLen = nameLength * 2; RUNTIME_ARRAY(wchar_t, wideName, nameLen + 1); - MultiByteToWideChar(CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); + MultiByteToWideChar( + CP_UTF8, 0, name, -1, RUNTIME_ARRAY_BODY(wideName), nameLen + 1); #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) handle = LoadLibraryW(RUNTIME_ARRAY_BODY(wideName)); @@ -872,14 +947,16 @@ class MySystem: public System { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) handle = GetModuleHandle(0); #else - // Most of WinRT/WP8 applications can not host native object files inside main executable - assert(this, false); + // Most of WinRT/WP8 applications can not host native object files inside + // main executable + assertT(this, false); #endif } - + if (handle) { if (Verbose) { - fprintf(stderr, "open %s as %p\n", name, handle); fflush(stderr); + fprintf(stderr, "open %s as %p\n", name, handle); + fflush(stderr); } char* n; @@ -903,15 +980,18 @@ class MySystem: public System { } } - virtual char pathSeparator() { + virtual char pathSeparator() + { return ';'; } - virtual char fileSeparator() { + virtual char fileSeparator() + { return '\\'; } - virtual int64_t now() { + virtual int64_t now() + { // We used to use _ftime here, but that only gives us 1-second // resolution on Windows 7. _ftime_s might work better, but MinGW // doesn't have it as of this writing. So we use this mess instead: @@ -921,7 +1001,8 @@ class MySystem: public System { | time.dwLowDateTime) / 10000) - 11644473600000LL; } - virtual void yield() { + virtual void yield() + { #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) SwitchToThread(); #else @@ -929,15 +1010,18 @@ class MySystem: public System { #endif } - virtual void exit(int code) { + virtual void exit(int code) + { ::exit(code); } - virtual void abort() { + virtual void abort() + { avian::system::crash(); } - virtual void dispose() { + virtual void dispose() + { system = 0; CloseHandle(mutex); ::free(this); @@ -946,14 +1030,13 @@ class MySystem: public System { HANDLE mutex; }; -} // namespace +} // namespace namespace vm { -AVIAN_EXPORT System* -makeSystem() +AVIAN_EXPORT System* makeSystem() { return new (malloc(sizeof(MySystem))) MySystem(); } -} // namespace vm +} // namespace vm diff --git a/src/system/windows/signal.cpp b/src/system/windows/signal.cpp index 2b16aee7d0..34cd5e27a8 100644 --- a/src/system/windows/signal.cpp +++ b/src/system/windows/signal.cpp @@ -49,9 +49,10 @@ struct SignalRegistrar::Data { LPTOP_LEVEL_EXCEPTION_FILTER oldHandler; #endif - Data() : crashDumpDirectory(0), + Data() + : crashDumpDirectory(0), #if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - oldHandler(0) + oldHandler(0) #endif { if (instance) { @@ -68,9 +69,11 @@ struct SignalRegistrar::Data { bool registerHandler(Handler* handler, int index); - bool findHandler() { + bool findHandler() + { for (unsigned i = 0; i < windows::HandlerCount; ++i) { - if (handlers[i]) return true; + if (handlers[i]) + return true; } return false; } @@ -95,21 +98,16 @@ struct MINIDUMP_EXCEPTION_INFORMATION { struct MINIDUMP_USER_STREAM_INFORMATION; struct MINIDUMP_CALLBACK_INFORMATION; -enum MINIDUMP_TYPE { - MiniDumpNormal = 0, - MiniDumpWithFullMemory = 2 -}; +enum MINIDUMP_TYPE { MiniDumpNormal = 0, MiniDumpWithFullMemory = 2 }; -typedef BOOL (*MiniDumpWriteDumpType)(HANDLE processHandle, - DWORD processId, - HANDLE file, - MINIDUMP_TYPE type, - const MINIDUMP_EXCEPTION_INFORMATION - * exception, - const MINIDUMP_USER_STREAM_INFORMATION - * userStream, - const MINIDUMP_CALLBACK_INFORMATION - * callback); +typedef BOOL (*MiniDumpWriteDumpType)( + HANDLE processHandle, + DWORD processId, + HANDLE file, + MINIDUMP_TYPE type, + const MINIDUMP_EXCEPTION_INFORMATION* exception, + const MINIDUMP_USER_STREAM_INFORMATION* userStream, + const MINIDUMP_CALLBACK_INFORMATION* callback); #endif @@ -118,8 +116,9 @@ void dump(LPEXCEPTION_POINTERS e, const char* directory) HINSTANCE dbghelp = LoadLibrary("dbghelp.dll"); if (dbghelp) { - MiniDumpWriteDumpType MiniDumpWriteDump = reinterpret_cast - (GetProcAddress(dbghelp, "MiniDumpWriteDump")); + MiniDumpWriteDumpType MiniDumpWriteDump + = reinterpret_cast( + GetProcAddress(dbghelp, "MiniDumpWriteDump")); if (MiniDumpWriteDump) { char name[MAX_PATH]; @@ -129,8 +128,8 @@ void dump(LPEXCEPTION_POINTERS e, const char* directory) MAX_PATH, "%s\\crash-%" LLD ".mdmp", directory, - (static_cast(tb.time) * 1000) + static_cast - (tb.millitm)); + (static_cast(tb.time) * 1000) + + static_cast(tb.millitm)); HANDLE file = CreateFile(name, FILE_WRITE_DATA, 0, 0, CREATE_ALWAYS, 0, 0); @@ -206,10 +205,12 @@ LONG CALLBACK handleException(LPEXCEPTION_POINTERS e) { SignalRegistrar::Handler* handler = 0; if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) { - handler = SignalRegistrar::Data::instance->handlers[SignalRegistrar::SegFault]; + handler + = SignalRegistrar::Data::instance->handlers[SignalRegistrar::SegFault]; } else if (e->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO) { - handler = SignalRegistrar::Data::instance->handlers[SignalRegistrar::DivideByZero]; + handler = SignalRegistrar::Data::instance + ->handlers[SignalRegistrar::DivideByZero]; } if (handler) { @@ -278,7 +279,7 @@ SignalRegistrar::~SignalRegistrar() bool SignalRegistrar::Data::registerHandler(Handler* handler, int index) { - if(index != SegFault && index != DivideByZero) { + if (index != SegFault && index != DivideByZero) { crash(); } diff --git a/src/thunks.cpp b/src/thunks.cpp index 9c0278876b..e97e21aa12 100644 --- a/src/thunks.cpp +++ b/src/thunks.cpp @@ -66,7 +66,7 @@ THUNK(instanceOfFromReference) THUNK(makeNewGeneral64) THUNK(makeNew64) THUNK(makeNewFromReference) -THUNK(set) +THUNK(setObject) THUNK(getJClass64) THUNK(getJClassFromReference) THUNK(gcIfNecessary) diff --git a/src/tools/binary-to-object/main.cpp b/src/tools/binary-to-object/main.cpp index 3e29b319cd..4cd9ff5879 100644 --- a/src/tools/binary-to-object/main.cpp +++ b/src/tools/binary-to-object/main.cpp @@ -24,48 +24,59 @@ #include -extern "C" -void __cxa_pure_virtual() { +extern "C" void __cxa_pure_virtual() +{ abort(); } -void* operator new(size_t size) { +void* operator new(size_t size) +{ return malloc(size); } -void operator delete(void*) { abort(); } +void operator delete(void*) +{ + abort(); +} namespace { using namespace avian::tools; using namespace avian::util; -bool -writeObject(uint8_t* data, size_t size, OutputStream* out, const char* startName, - const char* endName, const char* format, - const char* architecture, unsigned alignment, bool writable, - bool executable) +bool writeObject(uint8_t* data, + size_t size, + OutputStream* out, + const char* startName, + const char* endName, + const char* format, + const char* architecture, + unsigned alignment, + bool writable, + bool executable) { - Platform* platform = Platform::getPlatform(PlatformInfo(PlatformInfo::formatFromString(format), PlatformInfo::archFromString(architecture))); + Platform* platform = Platform::getPlatform( + PlatformInfo(PlatformInfo::formatFromString(format), + PlatformInfo::archFromString(architecture))); - if(!platform) { + if (!platform) { fprintf(stderr, "unsupported platform: %s/%s\n", format, architecture); return false; } - SymbolInfo symbols[] = { - SymbolInfo(0, startName), - SymbolInfo(size, endName) - }; + SymbolInfo symbols[] = {SymbolInfo(0, startName), SymbolInfo(size, endName)}; - unsigned accessFlags = (writable ? Platform::Writable : 0) | (executable ? Platform::Executable : 0); - - return platform->writeObject(out, Slice(symbols, 2), Slice(data, size), accessFlags, alignment); + unsigned accessFlags = (writable ? Platform::Writable : 0) + | (executable ? Platform::Executable : 0); + return platform->writeObject(out, + Slice(symbols, 2), + Slice(data, size), + accessFlags, + alignment); } -void -usageAndExit(const char* name) +void usageAndExit(const char* name) { fprintf(stderr, "usage: %s " @@ -75,10 +86,9 @@ usageAndExit(const char* name) exit(-1); } -} // namespace +} // namespace -int -main(int argc, const char** argv) +int main(int argc, const char** argv) { if (argc < 7 or argc > 10) { usageAndExit(argv[0]); @@ -111,26 +121,16 @@ main(int argc, const char** argv) if (r != -1) { #ifdef WIN32 HANDLE fm; - HANDLE h = (HANDLE) _get_osfhandle (fd); + HANDLE h = (HANDLE)_get_osfhandle(fd); - fm = CreateFileMapping( - h, - NULL, - PAGE_READONLY, - 0, - 0, - NULL); - data = static_cast(MapViewOfFile( - fm, - FILE_MAP_READ, - 0, - 0, - s.st_size)); + fm = CreateFileMapping(h, NULL, PAGE_READONLY, 0, 0, NULL); + data = static_cast( + MapViewOfFile(fm, FILE_MAP_READ, 0, 0, s.st_size)); CloseHandle(fm); #else - data = static_cast - (mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0)); + data = static_cast( + mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0)); #endif size = s.st_size; } @@ -142,9 +142,16 @@ main(int argc, const char** argv) if (data) { FileOutputStream out(argv[2]); if (out.isValid()) { - success = writeObject - (data, size, &out, argv[3], argv[4], argv[5], argv[6], alignment, - writable, executable); + success = writeObject(data, + size, + &out, + argv[3], + argv[4], + argv[5], + argv[6], + alignment, + writable, + executable); } else { fprintf(stderr, "unable to open %s\n", argv[2]); } diff --git a/src/tools/bootimage-generator/main.cpp b/src/tools/bootimage-generator/main.cpp index 62b840a256..bdb4102c00 100644 --- a/src/tools/bootimage-generator/main.cpp +++ b/src/tools/bootimage-generator/main.cpp @@ -26,7 +26,10 @@ // since we aren't linking against libstdc++, we must implement this // ourselves: -extern "C" void __cxa_pure_virtual(void) { abort(); } +extern "C" void __cxa_pure_virtual(void) +{ + abort(); +} using namespace vm; using namespace avian::tools; @@ -38,8 +41,8 @@ namespace { const unsigned HeapCapacity = 512 * 1024 * 1024; const unsigned TargetFixieSizeInBytes = 8 + (TargetBytesPerWord * 2); -const unsigned TargetFixieSizeInWords = ceilingDivide - (TargetFixieSizeInBytes, TargetBytesPerWord); +const unsigned TargetFixieSizeInWords + = ceilingDivide(TargetFixieSizeInBytes, TargetBytesPerWord); const unsigned TargetFixieAge = 0; const unsigned TargetFixieFlags = 2; const unsigned TargetFixieSize = 4; @@ -78,9 +81,12 @@ class Field { unsigned targetSize; }; -void -init(Field* f, Type type, unsigned buildOffset, unsigned buildSize, - unsigned targetOffset, unsigned targetSize) +void init(Field* f, + Type type, + unsigned buildOffset, + unsigned buildSize, + unsigned targetOffset, + unsigned targetSize) { f->type = type; f->buildOffset = buildOffset; @@ -91,41 +97,42 @@ init(Field* f, Type type, unsigned buildOffset, unsigned buildSize, class TypeMap { public: - enum Kind { - NormalKind, - SingletonKind, - PoolKind - }; + enum Kind { NormalKind, SingletonKind, PoolKind }; - TypeMap(unsigned buildFixedSizeInWords, unsigned targetFixedSizeInWords, - unsigned fixedFieldCount, Kind kind = NormalKind, + TypeMap(unsigned buildFixedSizeInWords, + unsigned targetFixedSizeInWords, + unsigned fixedFieldCount, + Kind kind = NormalKind, unsigned buildArrayElementSizeInBytes = 0, unsigned targetArrayElementSizeInBytes = 0, - Type arrayElementType = Type_none): - buildFixedSizeInWords(buildFixedSizeInWords), - targetFixedSizeInWords(targetFixedSizeInWords), - fixedFieldCount(fixedFieldCount), - buildArrayElementSizeInBytes(buildArrayElementSizeInBytes), - targetArrayElementSizeInBytes(targetArrayElementSizeInBytes), - arrayElementType(arrayElementType), - kind(kind) - { } + Type arrayElementType = Type_none) + : buildFixedSizeInWords(buildFixedSizeInWords), + targetFixedSizeInWords(targetFixedSizeInWords), + fixedFieldCount(fixedFieldCount), + buildArrayElementSizeInBytes(buildArrayElementSizeInBytes), + targetArrayElementSizeInBytes(targetArrayElementSizeInBytes), + arrayElementType(arrayElementType), + kind(kind) + { + } - uintptr_t* targetFixedOffsets() { + uintptr_t* targetFixedOffsets() + { return reinterpret_cast(this + 1); } - Field* fixedFields() { - return reinterpret_cast - (targetFixedOffsets() + (buildFixedSizeInWords * BytesPerWord)); + Field* fixedFields() + { + return reinterpret_cast(targetFixedOffsets() + + (buildFixedSizeInWords * BytesPerWord)); } static unsigned sizeInBytes(unsigned buildFixedSizeInWords, unsigned fixedFieldCount) { return sizeof(TypeMap) - + (buildFixedSizeInWords * BytesPerWord * BytesPerWord) - + (sizeof(Field) * fixedFieldCount); + + (buildFixedSizeInWords * BytesPerWord * BytesPerWord) + + (sizeof(Field) * fixedFieldCount); } unsigned buildFixedSizeInWords; @@ -167,40 +174,46 @@ class TypeMap { // of primitive classes before generating the heap image so that we // need not populate them lazily at runtime. -bool -endsWith(const char* suffix, const char* s, unsigned length) +bool endsWith(const char* suffix, const char* s, unsigned length) { unsigned suffixLength = strlen(suffix); return length >= suffixLength - and memcmp(suffix, s + (length - suffixLength), suffixLength) == 0; + and memcmp(suffix, s + (length - suffixLength), suffixLength) == 0; } -object -getNonStaticFields(Thread* t, object typeMaps, object c, object fields, - unsigned* count, object* array) +GcVector* getNonStaticFields(Thread* t, + GcHashMap* typeMaps, + GcClass* c, + GcVector* fields, + unsigned* count, + GcByteArray** array) { PROTECT(t, typeMaps); PROTECT(t, c); PROTECT(t, fields); - *array = hashMapFind(t, typeMaps, c, objectHash, objectEqual); + *array = cast( + t, + hashMapFind( + t, typeMaps, reinterpret_cast(c), objectHash, objectEqual)); if (*array) { - *count += reinterpret_cast(&byteArrayBody(t, *array, 0)) - ->fixedFieldCount; + *count += reinterpret_cast((*array)->body().begin()) + ->fixedFieldCount; } else { - if (classSuper(t, c)) { - fields = getNonStaticFields - (t, typeMaps, classSuper(t, c), fields, count, array); + if (c->super()) { + fields + = getNonStaticFields(t, typeMaps, c->super(), fields, count, array); } - if (classFieldTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classFieldTable(t, c)); ++i) { - object field = arrayBody(t, classFieldTable(t, c), i); + if (GcArray* ftable = cast(t, c->fieldTable())) { + PROTECT(t, ftable); + for (unsigned i = 0; i < ftable->length(); ++i) { + GcField* field = cast(t, ftable->body()[i]); - if ((fieldFlags(t, field) & ACC_STATIC) == 0) { - ++ (*count); - fields = vectorAppend(t, fields, field); + if ((field->flags() & ACC_STATIC) == 0) { + ++(*count); + fields = vectorAppend(t, fields, reinterpret_cast(field)); } } } @@ -209,37 +222,44 @@ getNonStaticFields(Thread* t, object typeMaps, object c, object fields, return vectorAppend(t, fields, 0); } -object -allFields(Thread* t, object typeMaps, object c, unsigned* count, object* array) +GcVector* allFields(Thread* t, + GcHashMap* typeMaps, + GcClass* c, + unsigned* count, + GcByteArray** array) { PROTECT(t, typeMaps); PROTECT(t, c); - object fields = makeVector(t, 0, 0); + GcVector* fields = makeVector(t, 0, 0); PROTECT(t, fields); - *array = hashMapFind(t, typeMaps, c, objectHash, objectEqual); + *array = cast( + t, + hashMapFind( + t, typeMaps, reinterpret_cast(c), objectHash, objectEqual)); bool includeMembers; if (*array) { includeMembers = false; - *count += reinterpret_cast(&byteArrayBody(t, *array, 0)) - ->fixedFieldCount; + *count += reinterpret_cast((*array)->body().begin()) + ->fixedFieldCount; } else { includeMembers = true; - if (classSuper(t, c)) { - fields = getNonStaticFields - (t, typeMaps, classSuper(t, c), fields, count, array); + if (c->super()) { + fields + = getNonStaticFields(t, typeMaps, c->super(), fields, count, array); } } - if (classFieldTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classFieldTable(t, c)); ++i) { - object field = arrayBody(t, classFieldTable(t, c), i); + if (GcArray* ftable = cast(t, c->fieldTable())) { + PROTECT(t, ftable); + for (unsigned i = 0; i < ftable->length(); ++i) { + GcField* field = cast(t, ftable->body()[i]); - if (includeMembers or (fieldFlags(t, field) & ACC_STATIC)) { - ++ (*count); - fields = vectorAppend(t, fields, field); + if (includeMembers or (field->flags() & ACC_STATIC)) { + ++(*count); + fields = vectorAppend(t, fields, reinterpret_cast(field)); } } } @@ -247,95 +267,117 @@ allFields(Thread* t, object typeMaps, object c, unsigned* count, object* array) return fields; } -TypeMap* -classTypeMap(Thread* t, object typeMaps, object p) +TypeMap* classTypeMap(Thread* t, GcHashMap* typeMaps, object p) { - return reinterpret_cast - (&byteArrayBody - (t, hashMapFind(t, typeMaps, p, objectHash, objectEqual), 0)); + return reinterpret_cast( + cast(t, hashMapFind(t, typeMaps, p, objectHash, objectEqual)) + ->body() + .begin()); } -TypeMap* -typeMap(Thread* t, object typeMaps, object p) +TypeMap* typeMap(Thread* t, GcHashMap* typeMaps, object p) { - return reinterpret_cast - (&byteArrayBody - (t, objectClass(t, p) == type(t, Machine::SingletonType) - ? hashMapFind(t, typeMaps, p, objectHash, objectEqual) - : hashMapFind(t, typeMaps, objectClass(t, p), objectHash, objectEqual), - 0)); + return reinterpret_cast( + cast( + t, + objectClass(t, p) == type(t, GcSingleton::Type) + ? hashMapFind(t, typeMaps, p, objectHash, objectEqual) + : hashMapFind(t, + typeMaps, + reinterpret_cast(objectClass(t, p)), + objectHash, + objectEqual)) + ->body() + .begin()); } -unsigned -targetFieldOffset(Thread* t, object typeMaps, object field) +unsigned targetFieldOffset(Thread* t, GcHashMap* typeMaps, GcField* field) { // if (strcmp(reinterpret_cast - // (&byteArrayBody(t, className(t, fieldClass(t, field)), 0)), + // (&byteArrayBody(t, className(t, field->class_()), 0)), // "java/lang/Throwable") == 0) trap(); - return ((fieldFlags(t, field) & ACC_STATIC) - ? typeMap(t, typeMaps, classStaticTable(t, fieldClass(t, field))) - : classTypeMap(t, typeMaps, fieldClass(t, field))) - ->targetFixedOffsets()[fieldOffset(t, field)]; + return ((field->flags() & ACC_STATIC) + ? typeMap( + t, + typeMaps, + reinterpret_cast(field->class_()->staticTable())) + : classTypeMap( + t, typeMaps, reinterpret_cast(field->class_()))) + ->targetFixedOffsets()[field->offset()]; } -object -makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, - const char* className, const char* methodName, - const char* methodSpec, object typeMaps) +GcTriple* makeCodeImage(Thread* t, + Zone* zone, + BootImage* image, + uint8_t* code, + const char* className, + const char* methodName, + const char* methodSpec, + GcHashMap* typeMaps) { PROTECT(t, typeMaps); t->m->classpath->interceptMethods(t); - object constants = 0; + GcTriple* constants = 0; PROTECT(t, constants); - - object calls = 0; + + GcTriple* calls = 0; PROTECT(t, calls); - object methods = 0; + GcPair* methods = 0; PROTECT(t, methods); DelayedPromise* addresses = 0; - class MyOffsetResolver: public OffsetResolver { + class MyOffsetResolver : public OffsetResolver { public: - MyOffsetResolver(object* typeMaps): typeMaps(typeMaps) { } + MyOffsetResolver(GcHashMap** typeMaps) : typeMaps(typeMaps) + { + } - virtual unsigned fieldOffset(Thread* t, object field) { + virtual unsigned fieldOffset(Thread* t, GcField* field) + { return targetFieldOffset(t, *typeMaps, field); } - object* typeMaps; + GcHashMap** typeMaps; } resolver(&typeMaps); - Finder* finder = static_cast - (systemClassLoaderFinder(t, root(t, Machine::BootLoader))); + Finder* finder = static_cast( + roots(t)->bootLoader()->as(t)->finder()); for (Finder::Iterator it(finder); it.hasMore();) { unsigned nameSize = 0; const char* name = it.next(&nameSize); if (endsWith(".class", name, nameSize) - and (className == 0 or strncmp(name, className, nameSize - 6) == 0)) - { - // fprintf(stderr, "pass 1 %.*s\n", nameSize - 6, name); - object c = resolveSystemClass - (t, root(t, Machine::BootLoader), - makeByteArray(t, "%.*s", nameSize - 6, name), true); + and (className == 0 or strncmp(name, className, nameSize - 6) == 0)) { + if (false) { + fprintf(stderr, "pass 1 %.*s\n", nameSize - 6, name); + } + GcClass* c + = resolveSystemClass(t, + roots(t)->bootLoader(), + makeByteArray(t, "%.*s", nameSize - 6, name), + true); PROTECT(t, c); System::Region* region = finder->find(name); - - { THREAD_RESOURCE(t, System::Region*, region, region->dispose()); - class Client: public Stream::Client { + { + THREAD_RESOURCE(t, System::Region*, region, region->dispose()); + + class Client : public Stream::Client { public: - Client(Thread* t): t(t) { } + Client(Thread* t) : t(t) + { + } - virtual void NO_RETURN handleError() { + virtual void NO_RETURN handleError() + { abort(t); } @@ -347,8 +389,8 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, uint32_t magic = s.read4(); expect(t, magic == 0xCAFEBABE); - s.read2(); // minor version - s.read2(); // major version + s.read2(); // minor version + s.read2(); // major version unsigned count = s.read2() - 1; if (count) { @@ -395,39 +437,50 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, s.skip(s.read2()); break; - default: abort(t); + default: + abort(t); } } - object array = makeByteArray - (t, TypeMap::sizeInBytes(count + 2, count + 2)); + GcByteArray* array + = makeByteArray(t, TypeMap::sizeInBytes(count + 2, count + 2)); - TypeMap* map = new (&byteArrayBody(t, array, 0)) TypeMap - (count + 2, count + 2, count + 2, TypeMap::PoolKind); + TypeMap* map = new (array->body().begin()) + TypeMap(count + 2, count + 2, count + 2, TypeMap::PoolKind); for (unsigned i = 0; i < count + 2; ++i) { expect(t, i < map->buildFixedSizeInWords); - map->targetFixedOffsets()[i * BytesPerWord] - = i * TargetBytesPerWord; + map->targetFixedOffsets()[i * BytesPerWord] = i + * TargetBytesPerWord; - init(new (map->fixedFields() + i) Field, RUNTIME_ARRAY_BODY(types)[i], - i * BytesPerWord, BytesPerWord, i * TargetBytesPerWord, + init(new (map->fixedFields() + i) Field, + RUNTIME_ARRAY_BODY(types)[i], + i* BytesPerWord, + BytesPerWord, + i* TargetBytesPerWord, TargetBytesPerWord); } - hashMapInsert - (t, typeMaps, hashMapFind - (t, root(t, Machine::PoolMap), c, objectHash, objectEqual), array, - objectHash); + hashMapInsert( + t, + typeMaps, + reinterpret_cast(hashMapFind(t, + roots(t)->poolMap(), + reinterpret_cast(c), + objectHash, + objectEqual)), + reinterpret_cast(array), + objectHash); } } - { object array = 0; + { + GcByteArray* array = 0; PROTECT(t, array); unsigned count = 0; - object fields = allFields(t, typeMaps, c, &count, &array); + GcVector* fields = allFields(t, typeMaps, c, &count, &array); PROTECT(t, fields); THREAD_RUNTIME_ARRAY(t, Field, memberFields, count + 1); @@ -441,8 +494,7 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, buildMemberOffset = 0; targetMemberOffset = 0; - TypeMap* map = reinterpret_cast - (&byteArrayBody(t, array, 0)); + TypeMap* map = reinterpret_cast(array->body().begin()); for (unsigned j = 0; j < map->fixedFieldCount; ++j) { Field* f = map->fixedFields() + j; @@ -451,11 +503,15 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, targetMemberOffset = f->targetOffset + f->targetSize; - ++ memberIndex; + ++memberIndex; } } else { - init(new (RUNTIME_ARRAY_BODY(memberFields)) Field, Type_object, 0, - BytesPerWord, 0, TargetBytesPerWord); + init(new (RUNTIME_ARRAY_BODY(memberFields)) Field, + Type_object, + 0, + BytesPerWord, + 0, + TargetBytesPerWord); memberIndex = 1; buildMemberOffset = BytesPerWord; @@ -465,30 +521,40 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, const unsigned StaticHeader = 3; THREAD_RUNTIME_ARRAY(t, Field, staticFields, count + StaticHeader); - - init(new (RUNTIME_ARRAY_BODY(staticFields)) Field, Type_object, 0, - BytesPerWord, 0, TargetBytesPerWord); - init(new (RUNTIME_ARRAY_BODY(staticFields) + 1) Field, Type_intptr_t, - BytesPerWord, BytesPerWord, TargetBytesPerWord, + init(new (RUNTIME_ARRAY_BODY(staticFields)) Field, + Type_object, + 0, + BytesPerWord, + 0, TargetBytesPerWord); - init(new (RUNTIME_ARRAY_BODY(staticFields) + 2) Field, Type_object, - BytesPerWord * 2, BytesPerWord, TargetBytesPerWord * 2, + init(new (RUNTIME_ARRAY_BODY(staticFields) + 1) Field, + Type_intptr_t, + BytesPerWord, + BytesPerWord, + TargetBytesPerWord, + TargetBytesPerWord); + + init(new (RUNTIME_ARRAY_BODY(staticFields) + 2) Field, + Type_object, + BytesPerWord * 2, + BytesPerWord, + TargetBytesPerWord * 2, TargetBytesPerWord); unsigned staticIndex = StaticHeader; unsigned buildStaticOffset = BytesPerWord * StaticHeader; unsigned targetStaticOffset = TargetBytesPerWord * StaticHeader; - for (unsigned i = 0; i < vectorSize(t, fields); ++i) { - object field = vectorBody(t, fields, i); + for (unsigned i = 0; i < fields->size(); ++i) { + GcField* field = cast(t, fields->body()[i]); if (field) { - unsigned buildSize = fieldSize(t, fieldCode(t, field)); + unsigned buildSize = fieldSize(t, field->code()); unsigned targetSize = buildSize; Type type; - switch (fieldCode(t, field)) { + switch (field->code()) { case ObjectField: type = Type_object; targetSize = TargetBytesPerWord; @@ -514,85 +580,107 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, type = Type_int64_t; break; - default: abort(t); + default: + abort(t); } - if (fieldFlags(t, field) & ACC_STATIC) { + if (field->flags() & ACC_STATIC) { targetStaticOffset = pad(targetStaticOffset, targetSize); - buildStaticOffset = fieldOffset(t, field); + buildStaticOffset = field->offset(); init(new (RUNTIME_ARRAY_BODY(staticFields) + staticIndex) Field, - type, buildStaticOffset, buildSize, targetStaticOffset, + type, + buildStaticOffset, + buildSize, + targetStaticOffset, targetSize); targetStaticOffset += targetSize; - ++ staticIndex; + ++staticIndex; } else { targetMemberOffset = pad(targetMemberOffset, targetSize); - buildMemberOffset = fieldOffset(t, field); + buildMemberOffset = field->offset(); init(new (RUNTIME_ARRAY_BODY(memberFields) + memberIndex) Field, - type, buildMemberOffset, buildSize, targetMemberOffset, + type, + buildMemberOffset, + buildSize, + targetMemberOffset, targetSize); targetMemberOffset += targetSize; - ++ memberIndex; + ++memberIndex; } } else { targetMemberOffset = pad(targetMemberOffset, TargetBytesPerWord); } } - - if (hashMapFind(t, typeMaps, c, objectHash, objectEqual) == 0) { - object array = makeByteArray - (t, TypeMap::sizeInBytes - (ceilingDivide(classFixedSize(t, c), BytesPerWord), memberIndex)); - TypeMap* map = new (&byteArrayBody(t, array, 0)) TypeMap - (ceilingDivide(classFixedSize(t, c), BytesPerWord), - ceilingDivide(targetMemberOffset, TargetBytesPerWord), memberIndex); + if (hashMapFind(t, + typeMaps, + reinterpret_cast(c), + objectHash, + objectEqual) == 0) { + GcByteArray* array = makeByteArray( + t, + TypeMap::sizeInBytes(ceilingDivide(c->fixedSize(), BytesPerWord), + memberIndex)); + + TypeMap* map = new (array->body().begin()) + TypeMap(ceilingDivide(c->fixedSize(), BytesPerWord), + ceilingDivide(targetMemberOffset, TargetBytesPerWord), + memberIndex); for (unsigned i = 0; i < memberIndex; ++i) { Field* f = RUNTIME_ARRAY_BODY(memberFields) + i; - expect(t, f->buildOffset - < map->buildFixedSizeInWords * BytesPerWord); + expect(t, + f->buildOffset < map->buildFixedSizeInWords * BytesPerWord); map->targetFixedOffsets()[f->buildOffset] = f->targetOffset; map->fixedFields()[i] = *f; } - hashMapInsert(t, typeMaps, c, array, objectHash); + hashMapInsert(t, + typeMaps, + reinterpret_cast(c), + reinterpret_cast(array), + objectHash); } - if (classStaticTable(t, c)) { - object array = makeByteArray - (t, TypeMap::sizeInBytes - (singletonCount(t, classStaticTable(t, c)) + 2, staticIndex)); + if (c->staticTable()) { + GcByteArray* array = makeByteArray( + t, + TypeMap::sizeInBytes(singletonCount(t, c->staticTable()) + 2, + staticIndex)); - TypeMap* map = new (&byteArrayBody(t, array, 0)) TypeMap - (singletonCount(t, classStaticTable(t, c)) + 2, - ceilingDivide(targetStaticOffset, TargetBytesPerWord), staticIndex, - TypeMap::SingletonKind); + TypeMap* map = new (array->body().begin()) + TypeMap(singletonCount(t, c->staticTable()) + 2, + ceilingDivide(targetStaticOffset, TargetBytesPerWord), + staticIndex, + TypeMap::SingletonKind); for (unsigned i = 0; i < staticIndex; ++i) { Field* f = RUNTIME_ARRAY_BODY(staticFields) + i; - expect(t, f->buildOffset - < map->buildFixedSizeInWords * BytesPerWord); + expect(t, + f->buildOffset < map->buildFixedSizeInWords * BytesPerWord); map->targetFixedOffsets()[f->buildOffset] = f->targetOffset; map->fixedFields()[i] = *f; } - hashMapInsert - (t, typeMaps, classStaticTable(t, c), array, objectHash); + hashMapInsert(t, + typeMaps, + reinterpret_cast(c->staticTable()), + reinterpret_cast(array), + objectHash); } } } @@ -603,64 +691,71 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, const char* name = it.next(&nameSize); if (endsWith(".class", name, nameSize) - and (className == 0 or strncmp(name, className, nameSize - 6) == 0)) - { - // fprintf(stderr, "pass 2 %.*s\n", nameSize - 6, name); - object c = resolveSystemClass - (t, root(t, Machine::BootLoader), - makeByteArray(t, "%.*s", nameSize - 6, name), true); - + and (className == 0 or strncmp(name, className, nameSize - 6) == 0)) { + if (false) { + fprintf(stderr, "pass 2 %.*s\n", nameSize - 6, name); + } + GcClass* c = 0; PROTECT(t, c); - if (classMethodTable(t, c)) { - for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) { - object method = arrayBody(t, classMethodTable(t, c), i); + c = resolveSystemClass(t, + roots(t)->bootLoader(), + makeByteArray(t, "%.*s", nameSize - 6, name), + true); + + if (GcArray* mtable = cast(t, c->methodTable())) { + PROTECT(t, mtable); + for (unsigned i = 0; i < mtable->length(); ++i) { + GcMethod* method = cast(t, mtable->body()[i]); if (((methodName == 0 - or ::strcmp - (reinterpret_cast - (&byteArrayBody - (t, vm::methodName(t, method), 0)), methodName) == 0) + or ::strcmp( + reinterpret_cast(method->name()->body().begin()), + methodName) == 0) and (methodSpec == 0 - or ::strcmp - (reinterpret_cast - (&byteArrayBody - (t, vm::methodSpec(t, method), 0)), methodSpec) - == 0))) - { - if (methodCode(t, method) - or (methodFlags(t, method) & ACC_NATIVE)) - { + or ::strcmp(reinterpret_cast( + method->spec()->body().begin()), + methodSpec) == 0))) { + if (method->code() or (method->flags() & ACC_NATIVE)) { PROTECT(t, method); - t->m->processor->compileMethod - (t, zone, &constants, &calls, &addresses, method, &resolver); + t->m->processor->compileMethod( + t, + zone, + reinterpret_cast(&constants), + reinterpret_cast(&calls), + &addresses, + method, + &resolver); - if (methodCode(t, method)) { - methods = makePair(t, method, methods); + if (method->code()) { + methods = makePair(t, + reinterpret_cast(method), + reinterpret_cast(methods)); } } - object addendum = methodAddendum(t, method); - if (addendum and methodAddendumExceptionTable(t, addendum)) { + GcMethodAddendum* addendum = method->addendum(); + if (addendum and addendum->exceptionTable()) { PROTECT(t, addendum); + GcShortArray* exceptionTable + = cast(t, addendum->exceptionTable()); + PROTECT(t, exceptionTable); // resolve exception types now to avoid trying to update // immutable references at runtime - for (unsigned i = 0; i < shortArrayLength - (t, methodAddendumExceptionTable(t, addendum)); ++i) - { - uint16_t index = shortArrayBody - (t, methodAddendumExceptionTable(t, addendum), i) - 1; + for (unsigned i = 0; i < exceptionTable->length(); ++i) { + uint16_t index = exceptionTable->body()[i] - 1; - object o = singletonObject - (t, addendumPool(t, addendum), index); + object o = singletonObject(t, addendum->pool(), index); - if (objectClass(t, o) == type(t, Machine::ReferenceType)) { - o = resolveClass - (t, root(t, Machine::BootLoader), referenceName(t, o)); - - set(t, addendumPool(t, addendum), - SingletonBody + (index * BytesPerWord), o); + if (objectClass(t, o) == type(t, GcReference::Type)) { + o = reinterpret_cast( + resolveClass(t, + roots(t)->bootLoader(), + cast(t, o)->name())); + + addendum->pool()->setBodyElement( + t, index, reinterpret_cast(o)); } } } @@ -670,30 +765,29 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, } } - for (; calls; calls = tripleThird(t, calls)) { - object method = tripleFirst(t, calls); + for (; calls; calls = cast(t, calls->third())) { + GcMethod* method = cast(t, calls->first()); uintptr_t address; - if (methodFlags(t, method) & ACC_NATIVE) { + if (method->flags() & ACC_NATIVE) { address = reinterpret_cast(code + image->thunks.native.start); } else { - address = codeCompiled(t, methodCode(t, method)); + address = method->code()->compiled(); } - static_cast(pointerValue(t, tripleSecond(t, calls))) - ->listener->resolve(address, 0); + static_cast(cast(t, calls->second())->value()) + ->listener->resolve(address, 0); } for (; addresses; addresses = addresses->next) { uint8_t* value = reinterpret_cast(addresses->basis->value()); expect(t, value >= code); - addresses->listener->resolve - (static_cast(value - code), 0); + addresses->listener->resolve(static_cast(value - code), 0); } - for (; methods; methods = pairSecond(t, methods)) { - codeCompiled(t, methodCode(t, pairFirst(t, methods))) - -= reinterpret_cast(code); + for (; methods; methods = cast(t, methods->second())) { + cast(t, methods->first())->code()->compiled() + -= reinterpret_cast(code); } t->m->processor->normalizeVirtualThunks(t); @@ -701,110 +795,109 @@ makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code, return constants; } -void -visitRoots(Thread* t, BootImage* image, HeapWalker* w, object constants) +void visitRoots(Thread* t, BootImage* image, HeapWalker* w, GcTriple* constants) { Machine* m = t->m; - for (HashMapIterator it(t, classLoaderMap(t, root(t, Machine::BootLoader))); - it.hasMore();) - { - w->visitRoot(tripleSecond(t, it.next())); + for (HashMapIterator it(t, cast(t, roots(t)->bootLoader()->map())); + it.hasMore();) { + w->visitRoot(it.next()->second()); } - image->bootLoader = w->visitRoot(root(t, Machine::BootLoader)); - image->appLoader = w->visitRoot(root(t, Machine::AppLoader)); - image->types = w->visitRoot(m->types); + image->bootLoader + = w->visitRoot(reinterpret_cast(roots(t)->bootLoader())); + image->appLoader + = w->visitRoot(reinterpret_cast(roots(t)->appLoader())); + image->types = w->visitRoot(reinterpret_cast(m->types)); m->processor->visitRoots(t, w); - for (; constants; constants = tripleThird(t, constants)) { - w->visitRoot(tripleFirst(t, constants)); + for (; constants; constants = cast(t, constants->third())) { + w->visitRoot(constants->first()); } } -unsigned -targetOffset(Thread* t, object typeMaps, object p, unsigned offset) +unsigned targetOffset(Thread* t, GcHashMap* typeMaps, object p, unsigned offset) { TypeMap* map = typeMap(t, typeMaps, p); if (map->targetArrayElementSizeInBytes - and offset >= map->buildFixedSizeInWords * BytesPerWord) - { + and offset >= map->buildFixedSizeInWords * BytesPerWord) { return (map->targetFixedSizeInWords * TargetBytesPerWord) - + (((offset - (map->buildFixedSizeInWords * BytesPerWord)) - / map->buildArrayElementSizeInBytes) - * map->targetArrayElementSizeInBytes); + + (((offset - (map->buildFixedSizeInWords * BytesPerWord)) + / map->buildArrayElementSizeInBytes) + * map->targetArrayElementSizeInBytes); } else { return map->targetFixedOffsets()[offset]; } } -unsigned -targetSize(Thread* t, object typeMaps, object p) +unsigned targetSize(Thread* t, GcHashMap* typeMaps, object p) { TypeMap* map = typeMap(t, typeMaps, p); if (map->targetArrayElementSizeInBytes) { return map->targetFixedSizeInWords - + ceilingDivide(map->targetArrayElementSizeInBytes - * fieldAtOffset - (p, (map->buildFixedSizeInWords - 1) * BytesPerWord), - TargetBytesPerWord); + + ceilingDivide( + map->targetArrayElementSizeInBytes + * fieldAtOffset( + p, (map->buildFixedSizeInWords - 1) * BytesPerWord), + TargetBytesPerWord); } else { switch (map->kind) { case TypeMap::NormalKind: return map->targetFixedSizeInWords; case TypeMap::SingletonKind: - return map->targetFixedSizeInWords + singletonMaskSize - (map->targetFixedSizeInWords - 2, TargetBitsPerWord); + return map->targetFixedSizeInWords + + singletonMaskSize(map->targetFixedSizeInWords - 2, + TargetBitsPerWord); case TypeMap::PoolKind: { - unsigned maskSize = poolMaskSize - (map->targetFixedSizeInWords - 2, TargetBitsPerWord); + unsigned maskSize + = poolMaskSize(map->targetFixedSizeInWords - 2, TargetBitsPerWord); - return map->targetFixedSizeInWords + maskSize + singletonMaskSize - (map->targetFixedSizeInWords - 2 + maskSize, TargetBitsPerWord); + return map->targetFixedSizeInWords + maskSize + + singletonMaskSize(map->targetFixedSizeInWords - 2 + maskSize, + TargetBitsPerWord); } - default: abort(t); + default: + abort(t); } } } -unsigned -objectMaskCount(TypeMap* map) +unsigned objectMaskCount(TypeMap* map) { unsigned count = map->targetFixedSizeInWords; if (map->targetArrayElementSizeInBytes) { - ++ count; + ++count; } return count; } -unsigned -targetSize(Thread* t, object typeMaps, object referer, unsigned refererOffset, - object p) +unsigned targetSize(Thread* t, + GcHashMap* typeMaps, + object referer, + unsigned refererOffset, + object p) { - if (referer - and objectClass(t, referer) == type(t, Machine::ClassType) - and (refererOffset * BytesPerWord) == ClassObjectMask) - { + if (referer and objectClass(t, referer) == type(t, GcClass::Type) + and (refererOffset * BytesPerWord) == ClassObjectMask) { return (TargetBytesPerWord * 2) - + pad - (ceilingDivide - (objectMaskCount - (classTypeMap(t, typeMaps, referer)), 32) * 4, TargetBytesPerWord); + + pad(ceilingDivide( + objectMaskCount(classTypeMap(t, typeMaps, referer)), 32) + * 4, + TargetBytesPerWord); } else { return targetSize(t, typeMaps, p); } } -void -copy(Thread* t, uint8_t* src, uint8_t* dst, Type type) +void copy(Thread* t, uint8_t* src, uint8_t* dst, Type type) { switch (type) { case Type_int8_t: @@ -812,21 +905,24 @@ copy(Thread* t, uint8_t* src, uint8_t* dst, Type type) break; case Type_int16_t: { - int16_t s; memcpy(&s, src, 2); + int16_t s; + memcpy(&s, src, 2); int16_t d = targetV2(s); memcpy(dst, &d, 2); } break; case Type_int32_t: case Type_float: { - int32_t s; memcpy(&s, src, 4); + int32_t s; + memcpy(&s, src, 4); int32_t d = targetV4(s); memcpy(dst, &d, 4); } break; case Type_int64_t: case Type_double: { - int64_t s; memcpy(&s, src, 8); + int64_t s; + memcpy(&s, src, 8); int64_t d = targetV8(s); memcpy(dst, &d, 8); } break; @@ -836,7 +932,8 @@ copy(Thread* t, uint8_t* src, uint8_t* dst, Type type) break; case Type_intptr_t: { - intptr_t s; memcpy(&s, src, BytesPerWord); + intptr_t s; + memcpy(&s, src, BytesPerWord); target_intptr_t d = targetVW(s); memcpy(dst, &d, TargetBytesPerWord); } break; @@ -845,12 +942,12 @@ copy(Thread* t, uint8_t* src, uint8_t* dst, Type type) memset(dst, 0, TargetBytesPerWord); } break; - default: abort(t); + default: + abort(t); } } -bool -nonObjectsEqual(uint8_t* src, uint8_t* dst, Type type) +bool nonObjectsEqual(uint8_t* src, uint8_t* dst, Type type) { switch (type) { case Type_int8_t: @@ -878,18 +975,17 @@ nonObjectsEqual(uint8_t* src, uint8_t* dst, Type type) case Type_object_nogc: return true; - default: abort(); - } + default: + abort(); + } } -bool -nonObjectsEqual(TypeMap* map, uint8_t* src, uint8_t* dst) +bool nonObjectsEqual(TypeMap* map, uint8_t* src, uint8_t* dst) { for (unsigned i = 0; i < map->fixedFieldCount; ++i) { Field* field = map->fixedFields() + i; - if (not nonObjectsEqual - (src + field->buildOffset, dst + field->targetOffset, field->type)) - { + if (not nonObjectsEqual( + src + field->buildOffset, dst + field->targetOffset, field->type)) { return false; } } @@ -899,11 +995,11 @@ nonObjectsEqual(TypeMap* map, uint8_t* src, uint8_t* dst) unsigned count = fieldAtOffset(src, fixedSize - BytesPerWord); for (unsigned i = 0; i < count; ++i) { - if (not nonObjectsEqual - (src + fixedSize + (i * map->buildArrayElementSizeInBytes), - dst + (map->targetFixedSizeInWords * TargetBytesPerWord) - + (i * map->targetArrayElementSizeInBytes), map->arrayElementType)) - { + if (not nonObjectsEqual( + src + fixedSize + (i * map->buildArrayElementSizeInBytes), + dst + (map->targetFixedSizeInWords * TargetBytesPerWord) + + (i * map->targetArrayElementSizeInBytes), + map->arrayElementType)) { return false; } } @@ -912,16 +1008,16 @@ nonObjectsEqual(TypeMap* map, uint8_t* src, uint8_t* dst) return true; } -void -copy(Thread* t, object typeMaps, object p, uint8_t* dst) +void copy(Thread* t, GcHashMap* typeMaps, object p, uint8_t* dst) { TypeMap* map = typeMap(t, typeMaps, p); - + uint8_t* src = reinterpret_cast(p); for (unsigned i = 0; i < map->fixedFieldCount; ++i) { Field* field = map->fixedFields() + i; - if (field->type > Type_array) abort(t); + if (field->type > Type_array) + abort(t); copy(t, src + field->buildOffset, dst + field->targetOffset, field->type); } @@ -930,27 +1026,32 @@ copy(Thread* t, object typeMaps, object p, uint8_t* dst) unsigned count = fieldAtOffset(p, fixedSize - BytesPerWord); for (unsigned i = 0; i < count; ++i) { - copy(t, src + fixedSize + (i * map->buildArrayElementSizeInBytes), + copy(t, + src + fixedSize + (i * map->buildArrayElementSizeInBytes), dst + (map->targetFixedSizeInWords * TargetBytesPerWord) - + (i * map->targetArrayElementSizeInBytes), map->arrayElementType); + + (i * map->targetArrayElementSizeInBytes), + map->arrayElementType); } - if (objectClass(t, p) == type(t, Machine::ClassType)) { + if (objectClass(t, p) == type(t, GcClass::Type)) { uint16_t fixedSize; uint8_t arrayElementSize; - object array = hashMapFind(t, typeMaps, p, objectHash, objectEqual); + GcByteArray* array = cast( + t, hashMapFind(t, typeMaps, p, objectHash, objectEqual)); + PROTECT(t, array); + + GcClass* c = cast(t, p); + PROTECT(t, c); if (array) { - TypeMap* classMap = reinterpret_cast - (&byteArrayBody(t, array, 0)); + TypeMap* classMap = reinterpret_cast(array->body().begin()); - fixedSize = targetV2 - (classMap->targetFixedSizeInWords * TargetBytesPerWord); + fixedSize + = targetV2(classMap->targetFixedSizeInWords * TargetBytesPerWord); arrayElementSize = classMap->targetArrayElementSizeInBytes; - } else if (classFixedSize(t, p) == BytesPerWord * 2 - and classArrayElementSize(t, p) == BytesPerWord) - { + } else if (c->fixedSize() == BytesPerWord * 2 + and c->arrayElementSize() == BytesPerWord) { fixedSize = targetV2(TargetBytesPerWord * 2); arrayElementSize = TargetBytesPerWord; @@ -958,31 +1059,33 @@ copy(Thread* t, object typeMaps, object p, uint8_t* dst) fixedSize = 0; arrayElementSize = 0; } - + if (fixedSize) { memcpy(dst + TargetClassFixedSize, &fixedSize, 2); memcpy(dst + TargetClassArrayElementSize, &arrayElementSize, 1); } - + // if (strcmp("vm::lineNumberTable", - // reinterpret_cast(&byteArrayBody(t, className(t, p), 0))) == 0) trap(); + // reinterpret_cast(&byteArrayBody(t, className(t, + // p), 0))) == 0) trap(); } } else { switch (map->kind) { case TypeMap::NormalKind: - if (objectClass(t, p) == type(t, Machine::FieldType)) { - uint16_t offset = targetV2(targetFieldOffset(t, typeMaps, p)); + if (objectClass(t, p) == type(t, GcField::Type)) { + uint16_t offset + = targetV2(targetFieldOffset(t, typeMaps, cast(t, p))); memcpy(dst + TargetFieldOffset, &offset, 2); } break; case TypeMap::SingletonKind: { - unsigned maskSize = singletonMaskSize - (map->targetFixedSizeInWords - 2, TargetBitsPerWord); + unsigned maskSize = singletonMaskSize(map->targetFixedSizeInWords - 2, + TargetBitsPerWord); - target_uintptr_t targetLength = targetVW - (map->targetFixedSizeInWords - 2 + maskSize); + target_uintptr_t targetLength + = targetVW(map->targetFixedSizeInWords - 2 + maskSize); memcpy(dst + TargetBytesPerWord, &targetLength, TargetBytesPerWord); uint8_t* mask = dst + (map->targetFixedSizeInWords * TargetBytesPerWord); @@ -993,38 +1096,38 @@ copy(Thread* t, object typeMaps, object p, uint8_t* dst) if (field->type == Type_object) { unsigned offset = field->targetOffset / TargetBytesPerWord; reinterpret_cast(mask)[offset / 32] - |= targetV4(static_cast(1) << (offset % 32)); + |= targetV4(static_cast(1) << (offset % 32)); } } if (DebugNativeTarget) { - expect - (t, memcmp - (src + (map->targetFixedSizeInWords * TargetBytesPerWord), mask, - singletonMaskSize - (map->targetFixedSizeInWords - 2, TargetBitsPerWord) - * TargetBytesPerWord) == 0); + expect(t, + memcmp(src + (map->targetFixedSizeInWords * TargetBytesPerWord), + mask, + singletonMaskSize(map->targetFixedSizeInWords - 2, + TargetBitsPerWord) * TargetBytesPerWord) + == 0); } } break; case TypeMap::PoolKind: { - unsigned poolMaskSize = vm::poolMaskSize - (map->targetFixedSizeInWords - 2, TargetBitsPerWord); + unsigned poolMaskSize = vm::poolMaskSize(map->targetFixedSizeInWords - 2, + TargetBitsPerWord); - unsigned objectMaskSize = singletonMaskSize - (map->targetFixedSizeInWords - 2 + poolMaskSize, TargetBitsPerWord); + unsigned objectMaskSize = singletonMaskSize( + map->targetFixedSizeInWords - 2 + poolMaskSize, TargetBitsPerWord); - target_uintptr_t targetLength = targetVW - (map->targetFixedSizeInWords - 2 + poolMaskSize + objectMaskSize); + target_uintptr_t targetLength = targetVW(map->targetFixedSizeInWords - 2 + + poolMaskSize + objectMaskSize); memcpy(dst + TargetBytesPerWord, &targetLength, TargetBytesPerWord); uint8_t* poolMask = dst - + (map->targetFixedSizeInWords * TargetBytesPerWord); + + (map->targetFixedSizeInWords * TargetBytesPerWord); memset(poolMask, 0, poolMaskSize * TargetBytesPerWord); - uint8_t* objectMask = dst - + ((map->targetFixedSizeInWords + poolMaskSize) * TargetBytesPerWord); + uint8_t* objectMask = dst + ((map->targetFixedSizeInWords + poolMaskSize) + * TargetBytesPerWord); memset(objectMask, 0, objectMaskSize * TargetBytesPerWord); @@ -1033,15 +1136,14 @@ copy(Thread* t, object typeMaps, object p, uint8_t* dst) switch (field->type) { case Type_object: reinterpret_cast(objectMask)[i / 32] - |= targetV4(static_cast(1) << (i % 32)); + |= targetV4(static_cast(1) << (i % 32)); break; case Type_float: case Type_double: - reinterpret_cast(poolMask) - [i / TargetBitsPerWord] - |= targetVW - (static_cast(1) << (i % TargetBitsPerWord)); + reinterpret_cast(poolMask)[i / TargetBitsPerWord] + |= targetVW(static_cast(1) + << (i % TargetBitsPerWord)); break; default: @@ -1050,29 +1152,31 @@ copy(Thread* t, object typeMaps, object p, uint8_t* dst) } if (DebugNativeTarget) { - expect - (t, memcmp - (src + (map->targetFixedSizeInWords * TargetBytesPerWord), poolMask, - (poolMaskSize + singletonMaskSize - (map->targetFixedSizeInWords - 2 + poolMaskSize, - TargetBitsPerWord)) - * TargetBytesPerWord) == 0); + expect(t, + memcmp(src + (map->targetFixedSizeInWords * TargetBytesPerWord), + poolMask, + (poolMaskSize + + singletonMaskSize( + map->targetFixedSizeInWords - 2 + poolMaskSize, + TargetBitsPerWord)) * TargetBytesPerWord) == 0); } } break; - default: abort(t); + default: + abort(t); } } } -void -copy(Thread* t, object typeMaps, object referer, unsigned refererOffset, - object p, uint8_t* dst) +void copy(Thread* t, + GcHashMap* typeMaps, + object referer, + unsigned refererOffset, + object p, + uint8_t* dst) { - if (referer - and objectClass(t, referer) == type(t, Machine::ClassType) - and (refererOffset * BytesPerWord) == ClassObjectMask) - { + if (referer and objectClass(t, referer) == type(t, GcClass::Type) + and (refererOffset * BytesPerWord) == ClassObjectMask) { TypeMap* map = classTypeMap(t, typeMaps, referer); memset(dst, 0, TargetBytesPerWord); @@ -1089,17 +1193,16 @@ copy(Thread* t, object typeMaps, object referer, unsigned refererOffset, Field* field = map->fixedFields() + i; if (field->type == Type_object) { unsigned offset = field->targetOffset / TargetBytesPerWord; - reinterpret_cast(dst + (TargetBytesPerWord * 2)) - [offset / 32] |= targetV4(static_cast(1) << (offset % 32)); + reinterpret_cast(dst + (TargetBytesPerWord * 2))[offset / 32] + |= targetV4(static_cast(1) << (offset % 32)); } } if (map->targetArrayElementSizeInBytes - and map->arrayElementType == Type_object) - { + and map->arrayElementType == Type_object) { unsigned offset = map->targetFixedSizeInWords; - reinterpret_cast(dst + (TargetBytesPerWord * 2)) - [offset / 32] |= targetV4(static_cast(1) << (offset % 32)); + reinterpret_cast(dst + (TargetBytesPerWord * 2))[offset / 32] + |= targetV4(static_cast(1) << (offset % 32)); } } else { copy(t, typeMaps, p, dst); @@ -1107,62 +1210,81 @@ copy(Thread* t, object typeMaps, object referer, unsigned refererOffset, if (DebugNativeTarget) { expect(t, targetSize(t, typeMaps, p) == baseSize(t, p, objectClass(t, p))); - expect(t, nonObjectsEqual - (typeMap(t, typeMaps, p), reinterpret_cast(p), dst)); + expect(t, + nonObjectsEqual( + typeMap(t, typeMaps, p), reinterpret_cast(p), dst)); } } -HeapWalker* -makeHeapImage(Thread* t, BootImage* image, target_uintptr_t* heap, - target_uintptr_t* map, unsigned capacity, object constants, - object typeMaps) +HeapWalker* makeHeapImage(Thread* t, + BootImage* image, + target_uintptr_t* heap, + target_uintptr_t* map, + unsigned capacity, + GcTriple* constants, + GcHashMap* typeMaps) { - class Visitor: public HeapVisitor { + class Visitor : public HeapVisitor { public: - Visitor(Thread* t, object typeMaps, target_uintptr_t* heap, - target_uintptr_t* map, unsigned capacity): - t(t), typeMaps(typeMaps), currentObject(0), currentNumber(0), - currentOffset(0), heap(heap), map(map), position(0), capacity(capacity) - { } + Visitor(Thread* t, + GcHashMap* typeMaps, + target_uintptr_t* heap, + target_uintptr_t* map, + unsigned capacity) + : t(t), + typeMaps(typeMaps), + currentObject(0), + currentNumber(0), + currentOffset(0), + heap(heap), + map(map), + position(0), + capacity(capacity) + { + } - void visit(unsigned number) { + void visit(unsigned number) + { if (currentObject) { if (DebugNativeTarget) { - expect - (t, targetOffset - (t, typeMaps, currentObject, currentOffset * BytesPerWord) - == currentOffset * BytesPerWord); + expect(t, + targetOffset( + t, typeMaps, currentObject, currentOffset * BytesPerWord) + == currentOffset * BytesPerWord); } - unsigned offset = currentNumber - 1 - + (targetOffset - (t, typeMaps, currentObject, currentOffset * BytesPerWord) - / TargetBytesPerWord); + unsigned offset + = currentNumber - 1 + + (targetOffset( + t, typeMaps, currentObject, currentOffset * BytesPerWord) + / TargetBytesPerWord); unsigned mark = heap[offset] & (~TargetPointerMask); unsigned value = number | (mark << TargetBootShift); - if (value) targetMarkBit(map, offset); + if (value) + targetMarkBit(map, offset); heap[offset] = targetVW(value); } } - virtual void root() { + virtual void root() + { currentObject = 0; } - virtual unsigned visitNew(object p) { + virtual unsigned visitNew(object p) + { if (p) { - unsigned size = targetSize - (t, typeMaps, currentObject, currentOffset, p); + unsigned size + = targetSize(t, typeMaps, currentObject, currentOffset, p); unsigned number; if ((currentObject - and objectClass(t, currentObject) == type(t, Machine::ClassType) + and objectClass(t, currentObject) == type(t, GcClass::Type) and (currentOffset * BytesPerWord) == ClassStaticTable) - or instanceOf(t, type(t, Machine::SystemClassLoaderType), p)) - { + or instanceOf(t, type(t, GcSystemClassLoader::Type), p)) { // Static tables and system classloaders must be allocated // as fixed objects in the heap image so that they can be // marked as dirty and visited during GC. Otherwise, @@ -1181,23 +1303,31 @@ makeHeapImage(Thread* t, BootImage* image, target_uintptr_t* heap, memset(heap + position, 0, TargetFixieSizeInBytes); uint16_t age = targetV2(FixieTenureThreshold + 1); - memcpy(reinterpret_cast(heap + position) - + TargetFixieAge, &age, 2); + memcpy(reinterpret_cast(heap + position) + TargetFixieAge, + &age, + 2); uint16_t flags = targetV2(1); - memcpy(reinterpret_cast(heap + position) - + TargetFixieFlags, &flags, 2); + memcpy(reinterpret_cast(heap + position) + TargetFixieFlags, + &flags, + 2); uint32_t targetSize = targetV4(size); - memcpy(reinterpret_cast(heap + position) - + TargetFixieSize, &targetSize, 4); + memcpy(reinterpret_cast(heap + position) + TargetFixieSize, + &targetSize, + 4); - copy(t, typeMaps, currentObject, currentOffset, p, + copy(t, + typeMaps, + currentObject, + currentOffset, + p, reinterpret_cast(dst)); dst[0] |= FixedMark; - memset(heap + position + TargetFixieSizeInWords + size, 0, + memset(heap + position + TargetFixieSizeInWords + size, + 0, maskSize * TargetBytesPerWord); number = (dst - heap) + 1; @@ -1205,7 +1335,11 @@ makeHeapImage(Thread* t, BootImage* image, target_uintptr_t* heap, } else { expect(t, position + size < capacity); - copy(t, typeMaps, currentObject, currentOffset, p, + copy(t, + typeMaps, + currentObject, + currentOffset, + p, reinterpret_cast(heap + position)); number = position + 1; @@ -1220,22 +1354,25 @@ makeHeapImage(Thread* t, BootImage* image, target_uintptr_t* heap, } } - virtual void visitOld(object, unsigned number) { + virtual void visitOld(object, unsigned number) + { visit(number); } - virtual void push(object object, unsigned number, unsigned offset) { + virtual void push(object object, unsigned number, unsigned offset) + { currentObject = object; currentNumber = number; currentOffset = offset; } - virtual void pop() { + virtual void pop() + { currentObject = 0; } Thread* t; - object typeMaps; + GcHashMap* typeMaps; object currentObject; unsigned currentNumber; unsigned currentOffset; @@ -1247,52 +1384,59 @@ makeHeapImage(Thread* t, BootImage* image, target_uintptr_t* heap, HeapWalker* w = makeHeapWalker(t, &visitor); visitRoots(t, image, w, constants); - + image->heapSize = visitor.position * TargetBytesPerWord; return w; } -void -updateConstants(Thread* t, object constants, HeapMap* heapTable) +void updateConstants(Thread* t, GcTriple* constants, HeapMap* heapTable) { - for (; constants; constants = tripleThird(t, constants)) { - unsigned target = heapTable->find(tripleFirst(t, constants)); + for (; constants; constants = cast(t, constants->third())) { + unsigned target = heapTable->find(constants->first()); expect(t, target > 0); - for (Promise::Listener* pl = static_cast - (pointerValue(t, tripleSecond(t, constants)))->listener; - pl; pl = pl->next) - { + for (Promise::Listener* pl + = static_cast( + cast(t, constants->second())->value())->listener; + pl; + pl = pl->next) { pl->resolve((target - 1) * TargetBytesPerWord, 0); } } } -BootImage::Thunk -targetThunk(BootImage::Thunk t) +BootImage::Thunk targetThunk(BootImage::Thunk t) { - return BootImage::Thunk - (targetV4(t.start), targetV4(t.frameSavedOffset), targetV4(t.length)); + return BootImage::Thunk( + targetV4(t.start), targetV4(t.frameSavedOffset), targetV4(t.length)); } -void -writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutput, - BootImage* image, uint8_t* code, const char* className, - const char* methodName, const char* methodSpec, - const char* bootimageStart, const char* bootimageEnd, - const char* codeimageStart, const char* codeimageEnd, - bool useLZMA) +void writeBootImage2(Thread* t, + OutputStream* bootimageOutput, + OutputStream* codeOutput, + BootImage* image, + uint8_t* code, + const char* className, + const char* methodName, + const char* methodSpec, + const char* bootimageStart, + const char* bootimageEnd, + const char* codeimageStart, + const char* codeimageEnd, + bool useLZMA) { - setRoot(t, Machine::OutOfMemoryError, - make(t, type(t, Machine::OutOfMemoryErrorType))); + GcThrowable* throwable + = cast(t, make(t, type(t, GcOutOfMemoryError::Type))); + // sequence point, for gc (don't recombine statements) + roots(t)->setOutOfMemoryError(t, throwable); Zone zone(t->m->system, t->m->heap, 64 * 1024); class MyCompilationHandler : public Processor::CompilationHandler { public: - - String heapDup(const char* name) { + String heapDup(const char* name) + { String ret(name); char* n = (char*)heap->allocate(ret.length + 1); memcpy(n, ret.text, ret.length + 1); @@ -1300,55 +1444,67 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp return ret; } - virtual void compiled(const void* code, unsigned size UNUSED, unsigned frameSize UNUSED, const char* name) { + virtual void compiled(const void* code, + unsigned size UNUSED, + unsigned frameSize UNUSED, + const char* name) + { uint64_t offset = reinterpret_cast(code) - codeOffset; symbols.add(SymbolInfo(offset, heapDup(name))); // printf("%ld %ld %s.%s%s\n", offset, offset + size, class_, name, spec); } - virtual void dispose() {} + virtual void dispose() + { + } DynamicArray symbols; uint64_t codeOffset; Heap* heap; - MyCompilationHandler(uint64_t codeOffset, Heap* heap): - codeOffset(codeOffset), - heap(heap) {} + MyCompilationHandler(uint64_t codeOffset, Heap* heap) + : codeOffset(codeOffset), heap(heap) + { + } } compilationHandler(reinterpret_cast(code), t->m->heap); t->m->processor->addCompilationHandler(&compilationHandler); - object classPoolMap; - object typeMaps; - object constants; + GcHashMap* classPoolMap; + GcHashMap* typeMaps; + GcTriple* constants; - { classPoolMap = makeHashMap(t, 0, 0); + { + classPoolMap = makeHashMap(t, 0, 0); PROTECT(t, classPoolMap); - setRoot(t, Machine::PoolMap, classPoolMap); + roots(t)->setPoolMap(t, classPoolMap); typeMaps = makeHashMap(t, 0, 0); PROTECT(t, typeMaps); #include "type-maps.cpp" - for (unsigned i = 0; i < arrayLength(t, t->m->types); ++i) { + for (unsigned i = 0; i < t->m->types->length(); ++i) { Type* source = types[i]; unsigned typeCount = 0; unsigned fieldCount = 1; while (source[typeCount] != Type_none) { - ++ typeCount; + ++typeCount; if (source[typeCount] != Type_pad) { - ++ fieldCount; + ++fieldCount; } } THREAD_RUNTIME_ARRAY(t, Field, fields, fieldCount); - init(new (RUNTIME_ARRAY_BODY(fields)) Field, Type_object, 0, - BytesPerWord, 0, TargetBytesPerWord); + init(new (RUNTIME_ARRAY_BODY(fields)) Field, + Type_object, + 0, + BytesPerWord, + 0, + TargetBytesPerWord); unsigned buildOffset = BytesPerWord; unsigned targetOffset = TargetBytesPerWord; @@ -1416,7 +1572,8 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp buildSize = targetSize = 0; break; - default: abort(t); + default: + abort(t); } if (source[j] == Type_array) { @@ -1432,8 +1589,12 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp targetOffset = pad(targetOffset, targetSize); - init(new (RUNTIME_ARRAY_BODY(fields) + (fieldOffset++)) Field, type, - buildOffset, buildSize, targetOffset, targetSize); + init(new (RUNTIME_ARRAY_BODY(fields) + (fieldOffset++)) Field, + type, + buildOffset, + buildSize, + targetOffset, + targetSize); buildOffset += buildSize; targetOffset += targetSize; @@ -1447,7 +1608,7 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp if (sawArray) { fixedFieldCount = fieldCount - 2; arrayElementType = type; - buildArrayElementSize = buildSize; + buildArrayElementSize = buildSize; targetArrayElementSize = targetSize; } else { fixedFieldCount = fieldCount; @@ -1456,153 +1617,174 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp targetArrayElementSize = 0; } - object array = makeByteArray - (t, TypeMap::sizeInBytes - (ceilingDivide(buildOffset, BytesPerWord), fixedFieldCount)); + GcByteArray* array = makeByteArray( + t, + TypeMap::sizeInBytes(ceilingDivide(buildOffset, BytesPerWord), + fixedFieldCount)); - TypeMap* map = new (&byteArrayBody(t, array, 0)) TypeMap - (ceilingDivide(buildOffset, BytesPerWord), - ceilingDivide(targetOffset, TargetBytesPerWord), - fixedFieldCount, TypeMap::NormalKind, buildArrayElementSize, - targetArrayElementSize, arrayElementType); + TypeMap* map = new (array->body().begin()) + TypeMap(ceilingDivide(buildOffset, BytesPerWord), + ceilingDivide(targetOffset, TargetBytesPerWord), + fixedFieldCount, + TypeMap::NormalKind, + buildArrayElementSize, + targetArrayElementSize, + arrayElementType); for (unsigned j = 0; j < fixedFieldCount; ++j) { Field* f = RUNTIME_ARRAY_BODY(fields) + j; - expect(t, f->buildOffset - < map->buildFixedSizeInWords * BytesPerWord); + expect(t, f->buildOffset < map->buildFixedSizeInWords * BytesPerWord); map->targetFixedOffsets()[f->buildOffset] = f->targetOffset; map->fixedFields()[j] = *f; } - hashMapInsert - (t, typeMaps, vm::type(t, static_cast(i)), array, - objectHash); + hashMapInsert( + t, + typeMaps, + reinterpret_cast(vm::type(t, static_cast(i))), + reinterpret_cast(array), + objectHash); } - constants = makeCodeImage - (t, &zone, image, code, className, methodName, methodSpec, typeMaps); + constants = makeCodeImage( + t, &zone, image, code, className, methodName, methodSpec, typeMaps); PROTECT(t, constants); // these roots will not be used when the bootimage is loaded, so // there's no need to preserve them: - setRoot(t, Machine::PoolMap, 0); - setRoot(t, Machine::ByteArrayMap, makeWeakHashMap(t, 0, 0)); + roots(t)->setPoolMap(t, 0); + + GcWeakHashMap* map = makeWeakHashMap(t, 0, 0); + // sequence point, for gc (don't recombine statements) + roots(t)->setByteArrayMap(t, map->as(t)); // name all primitive classes so we don't try to update immutable // references at runtime: - { object name = makeByteArray(t, "void"); - set(t, type(t, Machine::JvoidType), ClassName, name); - + { + GcByteArray* name = makeByteArray(t, "void"); + // sequence point, for gc (don't recombine statements) + type(t, GcJvoid::Type)->setName(t, name); + name = makeByteArray(t, "boolean"); - set(t, type(t, Machine::JbooleanType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJboolean::Type)->setName(t, name); name = makeByteArray(t, "byte"); - set(t, type(t, Machine::JbyteType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJbyte::Type)->setName(t, name); name = makeByteArray(t, "short"); - set(t, type(t, Machine::JshortType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJshort::Type)->setName(t, name); name = makeByteArray(t, "char"); - set(t, type(t, Machine::JcharType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJchar::Type)->setName(t, name); name = makeByteArray(t, "int"); - set(t, type(t, Machine::JintType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJint::Type)->setName(t, name); name = makeByteArray(t, "float"); - set(t, type(t, Machine::JfloatType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJfloat::Type)->setName(t, name); name = makeByteArray(t, "long"); - set(t, type(t, Machine::JlongType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJlong::Type)->setName(t, name); name = makeByteArray(t, "double"); - set(t, type(t, Machine::JdoubleType), ClassName, name); + // sequence point, for gc (don't recombine statements) + type(t, GcJdouble::Type)->setName(t, name); } // resolve primitive array classes in case they are needed at // runtime: - { object name = makeByteArray(t, "[B"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + { + GcByteArray* name = makeByteArray(t, "[B"); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[Z"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[S"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[C"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[I"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[J"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[F"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); name = makeByteArray(t, "[D"); - resolveSystemClass(t, root(t, Machine::BootLoader), name, true); + resolveSystemClass(t, roots(t)->bootLoader(), name, true); } } - target_uintptr_t* heap = static_cast - (t->m->heap->allocate(HeapCapacity)); + target_uintptr_t* heap + = static_cast(t->m->heap->allocate(HeapCapacity)); - target_uintptr_t* heapMap = static_cast - (t->m->heap->allocate(heapMapSize(HeapCapacity))); + target_uintptr_t* heapMap = static_cast( + t->m->heap->allocate(heapMapSize(HeapCapacity))); memset(heapMap, 0, heapMapSize(HeapCapacity)); - HeapWalker* heapWalker = makeHeapImage - (t, image, heap, heapMap, HeapCapacity, constants, typeMaps); + HeapWalker* heapWalker = makeHeapImage( + t, image, heap, heapMap, HeapCapacity, constants, typeMaps); updateConstants(t, constants, heapWalker->map()); - image->bootClassCount = hashMapSize - (t, classLoaderMap(t, root(t, Machine::BootLoader))); + image->bootClassCount + = cast(t, roots(t)->bootLoader()->map())->size(); - unsigned* bootClassTable = static_cast - (t->m->heap->allocate(image->bootClassCount * sizeof(unsigned))); + unsigned* bootClassTable = static_cast( + t->m->heap->allocate(image->bootClassCount * sizeof(unsigned))); - { unsigned i = 0; - for (HashMapIterator it - (t, classLoaderMap(t, root(t, Machine::BootLoader))); - it.hasMore();) - { - bootClassTable[i++] = targetVW - (heapWalker->map()->find(tripleSecond(t, it.next()))); + { + unsigned i = 0; + for (HashMapIterator it(t, + cast(t, roots(t)->bootLoader()->map())); + it.hasMore();) { + bootClassTable[i++] + = targetVW(heapWalker->map()->find(it.next()->second())); } } - image->appClassCount = hashMapSize - (t, classLoaderMap(t, root(t, Machine::AppLoader))); + image->appClassCount + = cast(t, roots(t)->appLoader()->map())->size(); - unsigned* appClassTable = static_cast - (t->m->heap->allocate(image->appClassCount * sizeof(unsigned))); + unsigned* appClassTable = static_cast( + t->m->heap->allocate(image->appClassCount * sizeof(unsigned))); - { unsigned i = 0; - for (HashMapIterator it - (t, classLoaderMap(t, root(t, Machine::AppLoader))); - it.hasMore();) - { - appClassTable[i++] = targetVW - (heapWalker->map()->find(tripleSecond(t, it.next()))); + { + unsigned i = 0; + for ( + HashMapIterator it(t, cast(t, roots(t)->appLoader()->map())); + it.hasMore();) { + appClassTable[i++] + = targetVW(heapWalker->map()->find(it.next()->second())); } } - image->stringCount = hashMapSize(t, root(t, Machine::StringMap)); - unsigned* stringTable = static_cast - (t->m->heap->allocate(image->stringCount * sizeof(unsigned))); + image->stringCount = roots(t)->stringMap()->size(); + unsigned* stringTable = static_cast( + t->m->heap->allocate(image->stringCount * sizeof(unsigned))); - { unsigned i = 0; - for (HashMapIterator it(t, root(t, Machine::StringMap)); it.hasMore();) { - stringTable[i++] = targetVW - (heapWalker->map()->find - (jreferenceTarget(t, tripleFirst(t, it.next())))); + { + unsigned i = 0; + for (HashMapIterator it(t, roots(t)->stringMap()); it.hasMore();) { + stringTable[i++] + = targetVW(heapWalker->map()->find(reinterpret_cast( + cast(t, it.next()->first())->target()))); } } @@ -1613,18 +1795,23 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp image->magic = BootImage::Magic; image->initialized = 0; - fprintf(stderr, "class count %d string count %d call count %d\n" + fprintf(stderr, + "class count %d string count %d call count %d\n" "heap size %d code size %d\n", - image->bootClassCount, image->stringCount, image->callCount, - image->heapSize, image->codeSize); + image->bootClassCount, + image->stringCount, + image->callCount, + image->heapSize, + image->codeSize); Buffer bootimageData; if (true) { - { BootImage targetImage; + { + BootImage targetImage; #ifdef FIELD -# undef FIELD +#undef FIELD #endif #define FIELD(name) targetImage.name = targetV4(image->name); @@ -1632,54 +1819,63 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp #undef FIELD #define THUNK_FIELD(name) \ - targetImage.thunks.name = targetThunk(image->thunks.name); + targetImage.thunks.name = targetThunk(image->thunks.name); #include "bootimage-fields.cpp" #undef THUNK_FIELD bootimageData.write(&targetImage, sizeof(BootImage)); } - bootimageData.write(bootClassTable, image->bootClassCount * sizeof(unsigned)); + bootimageData.write(bootClassTable, + image->bootClassCount * sizeof(unsigned)); bootimageData.write(appClassTable, image->appClassCount * sizeof(unsigned)); bootimageData.write(stringTable, image->stringCount * sizeof(unsigned)); bootimageData.write(callTable, image->callCount * sizeof(unsigned) * 2); unsigned offset = sizeof(BootImage) - + (image->bootClassCount * sizeof(unsigned)) - + (image->appClassCount * sizeof(unsigned)) - + (image->stringCount * sizeof(unsigned)) - + (image->callCount * sizeof(unsigned) * 2); + + (image->bootClassCount * sizeof(unsigned)) + + (image->appClassCount * sizeof(unsigned)) + + (image->stringCount * sizeof(unsigned)) + + (image->callCount * sizeof(unsigned) * 2); while (offset % TargetBytesPerWord) { uint8_t c = 0; bootimageData.write(&c, 1); - ++ offset; + ++offset; } - bootimageData.write(heapMap, pad(heapMapSize(image->heapSize), TargetBytesPerWord)); + bootimageData.write(heapMap, + pad(heapMapSize(image->heapSize), TargetBytesPerWord)); bootimageData.write(heap, pad(image->heapSize, TargetBytesPerWord)); // fwrite(code, pad(image->codeSize, TargetBytesPerWord), 1, codeOutput); - - Platform* platform = Platform::getPlatform(PlatformInfo((PlatformInfo::Format)AVIAN_TARGET_FORMAT, (PlatformInfo::Architecture)AVIAN_TARGET_ARCH)); - if(!platform) { - fprintf(stderr, "unsupported platform: target-format = %d / target-arch = %d\n", AVIAN_TARGET_FORMAT, AVIAN_TARGET_ARCH); + Platform* platform = Platform::getPlatform( + PlatformInfo((PlatformInfo::Format)AVIAN_TARGET_FORMAT, + (PlatformInfo::Architecture)AVIAN_TARGET_ARCH)); + + if (!platform) { + fprintf(stderr, + "unsupported platform: target-format = %d / target-arch = %d\n", + AVIAN_TARGET_FORMAT, + AVIAN_TARGET_ARCH); abort(); } - SymbolInfo bootimageSymbols[] = { - SymbolInfo(0, bootimageStart), - SymbolInfo(bootimageData.length, bootimageEnd) - }; + SymbolInfo bootimageSymbols[] + = {SymbolInfo(0, bootimageStart), + SymbolInfo(bootimageData.length, bootimageEnd)}; uint8_t* bootimage; unsigned bootimageLength; if (useLZMA) { #ifdef AVIAN_USE_LZMA - bootimage = encodeLZMA(t->m->system, t->m->heap, bootimageData.data, - bootimageData.length, &bootimageLength); + bootimage = encodeLZMA(t->m->system, + t->m->heap, + bootimageData.data, + bootimageData.length, + &bootimageLength); fprintf(stderr, "compressed heap size %d\n", bootimageLength); #else @@ -1690,7 +1886,11 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp bootimageLength = bootimageData.length; } - platform->writeObject(bootimageOutput, Slice(bootimageSymbols, 2), Slice(bootimage, bootimageLength), Platform::Writable, TargetBytesPerWord); + platform->writeObject(bootimageOutput, + Slice(bootimageSymbols, 2), + Slice(bootimage, bootimageLength), + Platform::Writable, + TargetBytesPerWord); if (useLZMA) { t->m->heap->free(bootimage, bootimageLength); @@ -1699,16 +1899,22 @@ writeBootImage2(Thread* t, OutputStream* bootimageOutput, OutputStream* codeOutp compilationHandler.symbols.add(SymbolInfo(0, codeimageStart)); compilationHandler.symbols.add(SymbolInfo(image->codeSize, codeimageEnd)); - platform->writeObject(codeOutput, Slice(compilationHandler.symbols), Slice(code, image->codeSize), Platform::Executable, TargetBytesPerWord); + platform->writeObject(codeOutput, + Slice(compilationHandler.symbols), + Slice(code, image->codeSize), + Platform::Executable, + TargetBytesPerWord); - for(SymbolInfo* sym = compilationHandler.symbols.begin(); sym != compilationHandler.symbols.end() - 2; sym++) { - t->m->heap->free(const_cast((const void*)sym->name.text), sym->name.length + 1); + for (SymbolInfo* sym = compilationHandler.symbols.begin(); + sym != compilationHandler.symbols.end() - 2; + sym++) { + t->m->heap->free(const_cast((const void*)sym->name.text), + sym->name.length + 1); } } } -uint64_t -writeBootImage(Thread* t, uintptr_t* arguments) +uint64_t writeBootImage(Thread* t, uintptr_t* arguments) { OutputStream* bootimageOutput = reinterpret_cast(arguments[0]); OutputStream* codeOutput = reinterpret_cast(arguments[1]); @@ -1724,16 +1930,24 @@ writeBootImage(Thread* t, uintptr_t* arguments) const char* codeimageEnd = reinterpret_cast(arguments[10]); bool useLZMA = arguments[11]; - writeBootImage2 - (t, bootimageOutput, codeOutput, image, code, className, methodName, - methodSpec, bootimageStart, bootimageEnd, codeimageStart, codeimageEnd, - useLZMA); + writeBootImage2(t, + bootimageOutput, + codeOutput, + image, + code, + className, + methodName, + methodSpec, + bootimageStart, + bootimageEnd, + codeimageStart, + codeimageEnd, + useLZMA); return 1; } -char* -myStrndup(const char* src, unsigned length) +char* myStrndup(const char* src, unsigned length) { char* s = static_cast(malloc(length + 1)); memcpy(s, src, length); @@ -1742,8 +1956,7 @@ myStrndup(const char* src, unsigned length) } class Arguments { -public: - + public: const char* classpath; const char* bootimage; @@ -1761,10 +1974,11 @@ public: bool useLZMA; - bool maybeSplit(const char* src, char*& destA, char*& destB) { - if(src) { + bool maybeSplit(const char* src, char*& destA, char*& destB) + { + if (src) { const char* split = strchr(src, ':'); - if(!split) { + if (!split) { return false; } @@ -1774,25 +1988,32 @@ public: return true; } - Arguments(int ac, const char** av): - entryClass(0), - entryMethod(0), - entrySpec(0), - bootimageStart(0), - bootimageEnd(0), - codeimageStart(0), - codeimageEnd(0) + Arguments(int ac, const char** av) + : entryClass(0), + entryMethod(0), + entrySpec(0), + bootimageStart(0), + bootimageEnd(0), + codeimageStart(0), + codeimageEnd(0) { ArgParser parser; Arg classpath(parser, true, "cp", ""); Arg bootimage(parser, true, "bootimage", ""); Arg codeimage(parser, true, "codeimage", ""); - Arg entry(parser, false, "entry", "[.[]]"); - Arg bootimageSymbols(parser, false, "bootimage-symbols", ":"); - Arg codeimageSymbols(parser, false, "codeimage-symbols", ":"); + Arg entry( + parser, false, "entry", "[.[]]"); + Arg bootimageSymbols(parser, + false, + "bootimage-symbols", + ":"); + Arg codeimageSymbols(parser, + false, + "codeimage-symbols", + ":"); Arg useLZMA(parser, false, "use-lzma", 0); - if(!parser.parse(ac, av)) { + if (!parser.parse(ac, av)) { parser.printUsage(av[0]); exit(1); } @@ -1802,11 +2023,12 @@ public: this->codeimage = codeimage.value; this->useLZMA = useLZMA.value != 0; - if(entry.value) { - if(const char* entryClassEnd = strchr(entry.value, '.')) { + if (entry.value) { + if (const char* entryClassEnd = strchr(entry.value, '.')) { entryClass = myStrndup(entry.value, entryClassEnd - entry.value); - if(const char* entryMethodEnd = strchr(entryClassEnd, '(')) { - entryMethod = myStrndup(entryClassEnd + 1, entryMethodEnd - entryClassEnd - 1); + if (const char* entryMethodEnd = strchr(entryClassEnd, '(')) { + entryMethod = myStrndup(entryClassEnd + 1, + entryMethodEnd - entryClassEnd - 1); entrySpec = strdup(entryMethodEnd); } else { entryMethod = strdup(entryClassEnd + 1); @@ -1816,85 +2038,84 @@ public: } } - if(!maybeSplit(bootimageSymbols.value, bootimageStart, bootimageEnd) || - !maybeSplit(codeimageSymbols.value, codeimageStart, codeimageEnd)) - { + if (!maybeSplit(bootimageSymbols.value, bootimageStart, bootimageEnd) + || !maybeSplit(codeimageSymbols.value, codeimageStart, codeimageEnd)) { fprintf(stderr, "wrong format for symbols\n"); parser.printUsage(av[0]); exit(1); } - if(!bootimageStart) { + if (!bootimageStart) { bootimageStart = strdup("_binary_bootimage_bin_start"); } - if(!bootimageEnd) { + if (!bootimageEnd) { bootimageEnd = strdup("_binary_bootimage_bin_end"); } - if(!codeimageStart) { + if (!codeimageStart) { codeimageStart = strdup("_binary_codeimage_bin_start"); } - if(!codeimageEnd) { + if (!codeimageEnd) { codeimageEnd = strdup("_binary_codeimage_bin_end"); } - } - ~Arguments() { - if(entryClass) { + ~Arguments() + { + if (entryClass) { free(entryClass); } - if(entryMethod) { + if (entryMethod) { free(entryMethod); } - if(entrySpec) { + if (entrySpec) { free(entrySpec); } - if(bootimageStart) { + if (bootimageStart) { free(bootimageStart); } - if(bootimageEnd) { + if (bootimageEnd) { free(bootimageEnd); } - if(codeimageStart) { + if (codeimageStart) { free(codeimageStart); } - if(codeimageEnd) { + if (codeimageEnd) { free(codeimageEnd); } } - void dump() { + void dump() + { printf( - "classpath = %s\n" - "bootimage = %s\n" - "codeimage = %s\n" - "entryClass = %s\n" - "entryMethod = %s\n" - "entrySpec = %s\n" - "bootimageStart = %s\n" - "bootimageEnd = %s\n" - "codeimageStart = %s\n" - "codeimageEnd = %s\n", - classpath, - bootimage, - codeimage, - entryClass, - entryMethod, - entrySpec, - bootimageStart, - bootimageEnd, - codeimageStart, - codeimageEnd); + "classpath = %s\n" + "bootimage = %s\n" + "codeimage = %s\n" + "entryClass = %s\n" + "entryMethod = %s\n" + "entrySpec = %s\n" + "bootimageStart = %s\n" + "bootimageEnd = %s\n" + "codeimageStart = %s\n" + "codeimageEnd = %s\n", + classpath, + bootimage, + codeimage, + entryClass, + entryMethod, + entrySpec, + bootimageStart, + bootimageEnd, + codeimageStart, + codeimageEnd); } }; -} // namespace +} // namespace -int -main(int ac, const char** av) +int main(int ac, const char** av) { Arguments args(ac, av); // args.dump(); @@ -1905,13 +2126,13 @@ main(int ac, const char** av) Finder* f = makeFinder(s, h, args.classpath, 0); Processor* p = makeProcessor(s, h, 0, false); - // todo: currently, the compiler cannot compile code with jumps or - // calls spanning more than the maximum size of an immediate value - // in a branch instruction for the target architecture (~32MB on ARM). - // When that limitation is removed, we'll be able to specify a - // capacity as large as we like here: +// todo: currently, the compiler cannot compile code with jumps or +// calls spanning more than the maximum size of an immediate value +// in a branch instruction for the target architecture (~32MB on ARM). +// When that limitation is removed, we'll be able to specify a +// capacity as large as we like here: #if (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86_64) \ - || (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86) + || (AVIAN_TARGET_ARCH == AVIAN_ARCH_X86) const unsigned CodeCapacity = 128 * 1024 * 1024; #else const unsigned CodeCapacity = 30 * 1024 * 1024; @@ -1921,8 +2142,8 @@ main(int ac, const char** av) BootImage image; p->initialize(&image, code); - Machine* m = new (h->allocate(sizeof(Machine))) Machine - (s, h, f, 0, p, c, 0, 0, 0, 0, 128 * 1024); + Machine* m = new (h->allocate(sizeof(Machine))) + Machine(s, h, f, 0, p, c, 0, 0, 0, 0, 128 * 1024); Thread* t = p->makeThread(m, 0, 0); enter(t, Thread::ActiveState); diff --git a/src/tools/object-writer/elf.cpp b/src/tools/object-writer/elf.cpp index 6f39d48fc9..2733ee0225 100644 --- a/src/tools/object-writer/elf.cpp +++ b/src/tools/object-writer/elf.cpp @@ -64,7 +64,7 @@ #define STV_DEFAULT 0 -#define SYMBOL_INFO(bind, type) (((bind) << 4) + ((type) & 0xf)) +#define SYMBOL_INFO(bind, type) (((bind) << 4) + ((type)&0xf)) #define OSABI ELFOSABI_SYSV @@ -73,7 +73,7 @@ namespace { using namespace avian::tools; using namespace avian::util; -template +template struct ElfTypes { typedef uint16_t Half; typedef uint32_t Word; @@ -85,10 +85,10 @@ struct ElfTypes { static const unsigned BytesPerWord = sizeof(AddrTy); }; -template +template struct Symbol_Ty; -template<> +template <> struct Symbol_Ty { typedef ElfTypes Elf; @@ -100,7 +100,7 @@ struct Symbol_Ty { Elf::Xword st_size; }; -template<> +template <> struct Symbol_Ty { typedef ElfTypes Elf; @@ -120,9 +120,9 @@ using avian::endian::Endianness; #define V4 Endianness::v4 #define VANY Endianness::vAny - -unsigned getElfPlatform(PlatformInfo::Architecture arch) { - switch(arch) { +unsigned getElfPlatform(PlatformInfo::Architecture arch) +{ + switch (arch) { case PlatformInfo::x86_64: return EM_X86_64; case PlatformInfo::x86: @@ -134,7 +134,8 @@ unsigned getElfPlatform(PlatformInfo::Architecture arch) { } } -const char* getSectionName(unsigned accessFlags, unsigned& sectionFlags) { +const char* getSectionName(unsigned accessFlags, unsigned& sectionFlags) +{ sectionFlags = SHF_ALLOC; if (accessFlags & Platform::Writable) { if (accessFlags & Platform::Executable) { @@ -152,10 +153,9 @@ const char* getSectionName(unsigned accessFlags, unsigned& sectionFlags) { } } -template +template class ElfPlatform : public Platform { -public: - + public: typedef ElfTypes Elf; static const unsigned Class = Elf::BytesPerWord / 4; @@ -191,16 +191,19 @@ public: typedef Symbol_Ty Symbol; - static const unsigned Encoding = TargetLittleEndian ? ELFDATA2LSB : ELFDATA2MSB; + static const unsigned Encoding = TargetLittleEndian ? ELFDATA2LSB + : ELFDATA2MSB; const unsigned machine; - ElfPlatform(PlatformInfo::Architecture arch): - Platform(PlatformInfo(PlatformInfo::Elf, arch)), - machine(getElfPlatform(arch)) {} + ElfPlatform(PlatformInfo::Architecture arch) + : Platform(PlatformInfo(PlatformInfo::Elf, arch)), + machine(getElfPlatform(arch)) + { + } class FileWriter { - public: + public: unsigned sectionCount; unsigned sectionStringTableSectionNumber; @@ -209,9 +212,8 @@ public: FileHeader header; StringTable strings; - FileWriter(unsigned machine): - sectionCount(0), - dataOffset(sizeof(FileHeader)) + FileWriter(unsigned machine) + : sectionCount(0), dataOffset(sizeof(FileHeader)) { memset(&header, 0, sizeof(FileHeader)); header.e_ident[EI_MAG0] = V1(ELFMAG0); @@ -236,7 +238,8 @@ public: header.e_shentsize = V2(sizeof(SectionHeader)); } - void writeHeader(OutputStream* out) { + void writeHeader(OutputStream* out) + { header.e_shnum = V2(sectionCount); header.e_shstrndx = V2(sectionStringTableSectionNumber); out->writeChunk(&header, sizeof(FileHeader)); @@ -244,18 +247,14 @@ public: }; class SectionWriter { - public: + public: FileWriter& file; String name; SectionHeader header; const size_t* dataSize; const uint8_t* const* data; - SectionWriter(FileWriter& file): - file(file), - name(""), - dataSize(0), - data(0) + SectionWriter(FileWriter& file) : file(file), name(""), dataSize(0), data(0) { memset(&header, 0, sizeof(SectionHeader)); file.sectionCount++; @@ -264,24 +263,19 @@ public: header.sh_name = V4(nameOffset); } - SectionWriter( - FileWriter& file, - const char* chname, - unsigned type, - AddrTy flags, - unsigned alignment, - AddrTy addr, - const uint8_t* const* data, - size_t* dataSize, - size_t entsize = 0, - unsigned link = 0): - - file(file), - name(chname), - dataSize(dataSize), - data(data) + SectionWriter(FileWriter& file, + const char* chname, + unsigned type, + AddrTy flags, + unsigned alignment, + AddrTy addr, + const uint8_t* const* data, + size_t* dataSize, + size_t entsize = 0, + unsigned link = 0) + : file(file), name(chname), dataSize(dataSize), data(data) { - if(strcmp(chname, ".shstrtab") == 0) { + if (strcmp(chname, ".shstrtab") == 0) { file.sectionStringTableSectionNumber = file.sectionCount; } file.sectionCount++; @@ -300,8 +294,9 @@ public: header.sh_entsize = VANY(static_cast(entsize)); } - void writeHeader(OutputStream* out) { - if(dataSize) { + void writeHeader(OutputStream* out) + { + if (dataSize) { header.sh_offset = VANY(file.dataOffset); header.sh_size = VANY(static_cast(*dataSize)); file.dataOffset += *dataSize; @@ -310,17 +305,20 @@ public: out->writeChunk(&header, sizeof(SectionHeader)); } - void writeData(OutputStream* out) { - if(data) { + void writeData(OutputStream* out) + { + if (data) { out->writeChunk(*data, *dataSize); } } - - }; - virtual bool writeObject(OutputStream* out, Slice symbols, Slice data, unsigned accessFlags, unsigned alignment) { - + virtual bool writeObject(OutputStream* out, + Slice symbols, + Slice data, + unsigned accessFlags, + unsigned alignment) + { unsigned sectionFlags; const char* sectionName = getSectionName(accessFlags, sectionFlags); @@ -332,18 +330,46 @@ public: const int bodySectionNumber = 1; const int stringTableSectionNumber = 3; - SectionWriter sections[] = { - SectionWriter(file), // null section - SectionWriter(file, sectionName, SHT_PROGBITS, sectionFlags, alignment, 0, &data.items, &data.count), // body section - SectionWriter(file, ".shstrtab", SHT_STRTAB, 0, 1, 0, &file.strings.data, &file.strings.length), - SectionWriter(file, ".strtab", SHT_STRTAB, 0, 1, 0, &symbolStringTable.data, &symbolStringTable.length), - SectionWriter(file, ".symtab", SHT_SYMTAB, 0, 8, 0, &symbolTable.data, &symbolTable.length, sizeof(Symbol), stringTableSectionNumber) - }; + SectionWriter sections[] = {SectionWriter(file), // null section + SectionWriter(file, + sectionName, + SHT_PROGBITS, + sectionFlags, + alignment, + 0, + &data.items, + &data.count), // body section + SectionWriter(file, + ".shstrtab", + SHT_STRTAB, + 0, + 1, + 0, + &file.strings.data, + &file.strings.length), + SectionWriter(file, + ".strtab", + SHT_STRTAB, + 0, + 1, + 0, + &symbolStringTable.data, + &symbolStringTable.length), + SectionWriter(file, + ".symtab", + SHT_SYMTAB, + 0, + 8, + 0, + &symbolTable.data, + &symbolTable.length, + sizeof(Symbol), + stringTableSectionNumber)}; // for some reason, string tables require a null first element... symbolStringTable.add(""); - for(SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { + for (SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { size_t nameOffset = symbolStringTable.add(sym->name); Symbol symbolStruct; @@ -358,11 +384,11 @@ public: file.writeHeader(out); - for(unsigned i = 0; i < file.sectionCount; i++) { + for (unsigned i = 0; i < file.sectionCount; i++) { sections[i].writeHeader(out); } - for(unsigned i = 0; i < file.sectionCount; i++) { + for (unsigned i = 0; i < file.sectionCount; i++) { sections[i].writeData(out); } @@ -374,4 +400,4 @@ ElfPlatform elfX86Platform(PlatformInfo::x86); ElfPlatform elfArmPlatform(PlatformInfo::Arm); ElfPlatform elfX86_64Platform(PlatformInfo::x86_64); -} // namespace +} // namespace diff --git a/src/tools/object-writer/endianness.h b/src/tools/object-writer/endianness.h index 182b249c52..0eef233d1a 100644 --- a/src/tools/object-writer/endianness.h +++ b/src/tools/object-writer/endianness.h @@ -22,60 +22,69 @@ static union { const bool LittleEndian = _DetectEndianness.c[0] == 1; -template +template class Endianness { -public: - static inline uint8_t v1(uint8_t v) { + public: + static inline uint8_t v1(uint8_t v) + { return v; } - static inline uint16_t v2(uint16_t v) { - if(LittleEndian == TargetLittleEndian) { + static inline uint16_t v2(uint16_t v) + { + if (LittleEndian == TargetLittleEndian) { return v; } else { return ((v >> 8) & 0xFF) | (v << 8); } } - static inline uint32_t v4(uint32_t v) { - if(LittleEndian == TargetLittleEndian) { + static inline uint32_t v4(uint32_t v) + { + if (LittleEndian == TargetLittleEndian) { return v; } else { - return - ((v >> 24) & 0x000000FF) | - ((v >> 8) & 0x0000FF00) | - ((v << 8) & 0x00FF0000) | - ((v << 24)); + return ((v >> 24) & 0x000000FF) | ((v >> 8) & 0x0000FF00) + | ((v << 8) & 0x00FF0000) | ((v << 24)); } } - static inline uint32_t vAny(uint32_t v) { + static inline uint32_t vAny(uint32_t v) + { return v4(v); } - static inline uint64_t v8(uint64_t v) { - if(LittleEndian == TargetLittleEndian) { + static inline uint64_t v8(uint64_t v) + { + if (LittleEndian == TargetLittleEndian) { return v; } else { - return - ((static_cast(v) >> 56) & (static_cast(0xff) << 0)) | - ((static_cast(v) >> 40) & (static_cast(0xff) << 8)) | - ((static_cast(v) >> 24) & (static_cast(0xff) << 16)) | - ((static_cast(v) >> 8) & (static_cast(0xff) << 24)) | - ((static_cast(v) << 8) & (static_cast(0xff) << 32)) | - ((static_cast(v) << 24) & (static_cast(0xff) << 40)) | - ((static_cast(v) << 40) & (static_cast(0xff) << 48)) | - ((static_cast(v) << 56)); + return ((static_cast(v) >> 56) + & (static_cast(0xff) << 0)) + | ((static_cast(v) >> 40) + & (static_cast(0xff) << 8)) + | ((static_cast(v) >> 24) + & (static_cast(0xff) << 16)) + | ((static_cast(v) >> 8) + & (static_cast(0xff) << 24)) + | ((static_cast(v) << 8) + & (static_cast(0xff) << 32)) + | ((static_cast(v) << 24) + & (static_cast(0xff) << 40)) + | ((static_cast(v) << 40) + & (static_cast(0xff) << 48)) + | ((static_cast(v) << 56)); } } - static inline uint64_t vAny(uint64_t v) { + static inline uint64_t vAny(uint64_t v) + { return v8(v); } }; -} // namespace endian +} // namespace endian -} // namespace avian +} // namespace avian -#endif // AVIAN_ENDIANNESS_H +#endif // AVIAN_ENDIANNESS_H diff --git a/src/tools/object-writer/mach-o.cpp b/src/tools/object-writer/mach-o.cpp index 89dec28e25..524407a381 100644 --- a/src/tools/object-writer/mach-o.cpp +++ b/src/tools/object-writer/mach-o.cpp @@ -55,18 +55,17 @@ using avian::endian::Endianness; #define V4 Endianness::v4 #define VANY Endianness::vAny -inline unsigned -log(unsigned n) +inline unsigned log(unsigned n) { unsigned r = 0; - for (unsigned i = 1; i < n; ++r) i <<= 1; + for (unsigned i = 1; i < n; ++r) + i <<= 1; return r; } -template +template class MachOPlatform : public Platform { -public: - + public: struct FileHeader { uint32_t magic; cpu_type_t cputype; @@ -81,7 +80,6 @@ public: }; }; - struct SegmentCommand { uint32_t cmd; uint32_t cmdsize; @@ -112,7 +110,7 @@ public: struct NList { union { - uint32_t n_strx; + uint32_t n_strx; } n_un; uint8_t n_type; uint8_t n_sect; @@ -133,16 +131,20 @@ public: static const unsigned Segment = BytesPerWord == 8 ? 0x19 : 1; static const unsigned Magic = BytesPerWord == 8 ? 0xfeedfacf : 0xfeedface; - static inline unsigned - pad(unsigned n) + static inline unsigned pad(unsigned n) { return (n + (BytesPerWord - 1)) & ~(BytesPerWord - 1); } - virtual bool writeObject(OutputStream* out, Slice symbols, Slice data, unsigned accessFlags, unsigned alignment) { + virtual bool writeObject(OutputStream* out, + Slice symbols, + Slice data, + unsigned accessFlags, + unsigned alignment) + { cpu_type_t cpuType; cpu_subtype_t cpuSubType; - switch(info.arch) { + switch (info.arch) { case PlatformInfo::x86_64: cpuType = CPU_TYPE_X86_64; cpuSubType = CPU_SUBTYPE_X86_64_ALL; @@ -177,53 +179,49 @@ public: } FileHeader header = { - V4(Magic), // magic - static_cast(V4(cpuType)), - static_cast(V4(cpuSubType)), - V4(MH_OBJECT), // filetype, - V4(2), // ncmds - V4(sizeof(SegmentCommand) - + sizeof(Section) - + sizeof(SymtabCommand)), // sizeofcmds - { V4(0) } // flags + V4(Magic), // magic + static_cast(V4(cpuType)), + static_cast(V4(cpuSubType)), + V4(MH_OBJECT), // filetype, + V4(2), // ncmds + V4(sizeof(SegmentCommand) + sizeof(Section) + + sizeof(SymtabCommand)), // sizeofcmds + {V4(0)} // flags }; AddrTy finalSize = pad(data.count); SegmentCommand segment = { - V4(Segment), // cmd - V4(sizeof(SegmentCommand) + sizeof(Section)), // cmdsize - "", // segname - VANY(static_cast(0)), // vmaddr - VANY(static_cast(finalSize)), // vmsize - VANY(static_cast(sizeof(FileHeader) - + sizeof(SegmentCommand) - + sizeof(Section) - + sizeof(SymtabCommand))), // fileoff - VANY(static_cast(finalSize)), // filesize - static_cast(V4(7)), // maxprot - static_cast(V4(7)), // initprot - V4(1), // nsects - V4(0) // flags + V4(Segment), // cmd + V4(sizeof(SegmentCommand) + sizeof(Section)), // cmdsize + "", // segname + VANY(static_cast(0)), // vmaddr + VANY(static_cast(finalSize)), // vmsize + VANY(static_cast(sizeof(FileHeader) + sizeof(SegmentCommand) + + sizeof(Section) + + sizeof(SymtabCommand))), // fileoff + VANY(static_cast(finalSize)), // filesize + static_cast(V4(7)), // maxprot + static_cast(V4(7)), // initprot + V4(1), // nsects + V4(0) // flags }; strncpy(segment.segname, segmentName, sizeof(segment.segname)); Section sect = { - "", // sectname - "", // segname - VANY(static_cast(0)), // addr - VANY(static_cast(finalSize)), // size - V4(sizeof(FileHeader) - + sizeof(SegmentCommand) - + sizeof(Section) - + sizeof(SymtabCommand)), // offset - V4(log(alignment)), // align - V4(0), // reloff - V4(0), // nreloc - V4(S_REGULAR), // flags - V4(0), // reserved1 - V4(0), // reserved2 + "", // sectname + "", // segname + VANY(static_cast(0)), // addr + VANY(static_cast(finalSize)), // size + V4(sizeof(FileHeader) + sizeof(SegmentCommand) + sizeof(Section) + + sizeof(SymtabCommand)), // offset + V4(log(alignment)), // align + V4(0), // reloff + V4(0), // nreloc + V4(S_REGULAR), // flags + V4(0), // reserved1 + V4(0), // reserved2 }; strncpy(sect.segname, segmentName, sizeof(sect.segname)); @@ -233,36 +231,30 @@ public: strings.add(""); Buffer symbolList; - for(SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { + for (SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { unsigned offset = strings.length; strings.write("_", 1); strings.add(sym->name); NList symbol = { - { V4(offset) }, // n_un - V1(N_SECT | N_EXT), // n_type - V1(1), // n_sect - V2(0), // n_desc - VANY(static_cast(sym->addr)) // n_value + {V4(offset)}, // n_un + V1(N_SECT | N_EXT), // n_type + V1(1), // n_sect + V2(0), // n_desc + VANY(static_cast(sym->addr)) // n_value }; symbolList.write(&symbol, sizeof(NList)); } SymtabCommand symbolTable = { - V4(LC_SYMTAB), // cmd - V4(sizeof(SymtabCommand)), // cmdsize - V4(sizeof(FileHeader) - + sizeof(SegmentCommand) - + sizeof(Section) - + sizeof(SymtabCommand) - + finalSize), // symoff - V4(symbols.count), // nsyms - V4(sizeof(FileHeader) - + sizeof(SegmentCommand) - + sizeof(Section) - + sizeof(SymtabCommand) - + finalSize - + (sizeof(NList) * symbols.count)), // stroff - V4(strings.length), // strsize + V4(LC_SYMTAB), // cmd + V4(sizeof(SymtabCommand)), // cmdsize + V4(sizeof(FileHeader) + sizeof(SegmentCommand) + sizeof(Section) + + sizeof(SymtabCommand) + finalSize), // symoff + V4(symbols.count), // nsyms + V4(sizeof(FileHeader) + sizeof(SegmentCommand) + sizeof(Section) + + sizeof(SymtabCommand) + finalSize + + (sizeof(NList) * symbols.count)), // stroff + V4(strings.length), // strsize }; out->writeChunk(&header, sizeof(header)); @@ -279,14 +271,15 @@ public: return true; } - - MachOPlatform(PlatformInfo::Architecture arch): - Platform(PlatformInfo(PlatformInfo::MachO, arch)) {} - + + MachOPlatform(PlatformInfo::Architecture arch) + : Platform(PlatformInfo(PlatformInfo::MachO, arch)) + { + } }; MachOPlatform darwinx86Platform(PlatformInfo::x86); MachOPlatform darwinArmPlatform(PlatformInfo::Arm); MachOPlatform darwinx86_64Platform(PlatformInfo::x86_64); -} // namespace +} // namespace diff --git a/src/tools/object-writer/pe.cpp b/src/tools/object-writer/pe.cpp index 4b644950b8..dd3e976041 100644 --- a/src/tools/object-writer/pe.cpp +++ b/src/tools/object-writer/pe.cpp @@ -18,16 +18,18 @@ namespace { // --- winnt.h ---- -#define IMAGE_SIZEOF_SHORT_NAME 8 +#define IMAGE_SIZEOF_SHORT_NAME 8 -#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // Relocation info stripped from file. -#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // Line nunbers stripped from file. -#define IMAGE_FILE_MACHINE_AMD64 0x8664 // AMD64 (K8) -#define IMAGE_FILE_MACHINE_I386 0x014c // Intel 386. -#define IMAGE_FILE_MACHINE_ARM 0x01c0 // ARM Little-Endian -#define IMAGE_FILE_MACHINE_THUMB 0x01c2 // ARM Thumb/Thumb-2 Little-Endian -#define IMAGE_FILE_MACHINE_ARMNT 0x01c4 // ARM Thumb-2 Little-Endian -#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine. +#define IMAGE_FILE_RELOCS_STRIPPED \ + 0x0001 // Relocation info stripped from file. +#define IMAGE_FILE_LINE_NUMS_STRIPPED \ + 0x0004 // Line nunbers stripped from file. +#define IMAGE_FILE_MACHINE_AMD64 0x8664 // AMD64 (K8) +#define IMAGE_FILE_MACHINE_I386 0x014c // Intel 386. +#define IMAGE_FILE_MACHINE_ARM 0x01c0 // ARM Little-Endian +#define IMAGE_FILE_MACHINE_THUMB 0x01c2 // ARM Thumb/Thumb-2 Little-Endian +#define IMAGE_FILE_MACHINE_ARMNT 0x01c4 // ARM Thumb-2 Little-Endian +#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 32 bit word machine. #define IMAGE_SCN_ALIGN_1BYTES 0x100000 #define IMAGE_SCN_ALIGN_2BYTES 0x200000 @@ -79,8 +81,7 @@ struct IMAGE_SYMBOL { } __attribute__((packed)); // --- winnt.h ---- -inline unsigned -pad(unsigned n) +inline unsigned pad(unsigned n) { return (n + (4 - 1)) & ~(4 - 1); } @@ -88,13 +89,11 @@ pad(unsigned n) using namespace avian::tools; using namespace avian::util; -template +template class WindowsPlatform : public Platform { -public: - - + public: class FileWriter { - public: + public: unsigned sectionCount; unsigned symbolCount; unsigned dataStart; @@ -105,11 +104,11 @@ public: StringTable strings; Buffer symbols; - FileWriter(unsigned machine, unsigned machineMask, unsigned symbolCount): - sectionCount(0), - symbolCount(symbolCount), - dataStart(sizeof(IMAGE_FILE_HEADER)), - dataOffset(0) + FileWriter(unsigned machine, unsigned machineMask, unsigned symbolCount) + : sectionCount(0), + symbolCount(symbolCount), + dataStart(sizeof(IMAGE_FILE_HEADER)), + dataOffset(0) { header.Machine = machine; // header.NumberOfSections = sectionCount; @@ -120,11 +119,11 @@ public: // header.NumberOfSymbols = symbolCount; header.SizeOfOptionalHeader = 0; header.Characteristics = IMAGE_FILE_RELOCS_STRIPPED - | IMAGE_FILE_LINE_NUMS_STRIPPED - | machineMask; + | IMAGE_FILE_LINE_NUMS_STRIPPED | machineMask; } - void writeHeader(OutputStream* out) { + void writeHeader(OutputStream* out) + { header.NumberOfSections = sectionCount; header.PointerToSymbolTable = dataStart + dataOffset; dataOffset = pad(dataOffset + symbolCount * sizeof(IMAGE_SYMBOL)); @@ -132,21 +131,27 @@ public: out->writeChunk(&header, sizeof(IMAGE_FILE_HEADER)); } - void addSymbol(String name, unsigned addr, unsigned sectionNumber, unsigned type, unsigned storageClass) { + void addSymbol(String name, + unsigned addr, + unsigned sectionNumber, + unsigned type, + unsigned storageClass) + { unsigned nameOffset = strings.add(name); IMAGE_SYMBOL symbol = { - { { 0, 0 } }, // Name - addr, // Value - static_cast(sectionNumber), // SectionNumber - static_cast(type), // Type - static_cast(storageClass), // StorageClass - 0, // NumberOfAuxSymbols + {{0, 0}}, // Name + addr, // Value + static_cast(sectionNumber), // SectionNumber + static_cast(type), // Type + static_cast(storageClass), // StorageClass + 0, // NumberOfAuxSymbols }; - symbol.N.Name.Long = nameOffset+4; + symbol.N.Name.Long = nameOffset + 4; symbols.write(&symbol, sizeof(IMAGE_SYMBOL)); } - void writeData(OutputStream* out) { + void writeData(OutputStream* out) + { out->writeChunk(symbols.data, symbols.length); uint32_t size = strings.length + 4; out->writeChunk(&size, 4); @@ -155,7 +160,7 @@ public: }; class SectionWriter { - public: + public: FileWriter& file; IMAGE_SECTION_HEADER header; size_t dataSize; @@ -163,17 +168,12 @@ public: const uint8_t* data; unsigned dataOffset; - SectionWriter( - FileWriter& file, - const char* name, - unsigned sectionMask, - const uint8_t* data, - size_t dataSize): - - file(file), - dataSize(dataSize), - finalSize(pad(dataSize)), - data(data) + SectionWriter(FileWriter& file, + const char* name, + unsigned sectionMask, + const uint8_t* data, + size_t dataSize) + : file(file), dataSize(dataSize), finalSize(pad(dataSize)), data(data) { file.sectionCount++; file.dataStart += sizeof(IMAGE_SECTION_HEADER); @@ -190,21 +190,25 @@ public: header.Characteristics = sectionMask; } - void writeHeader(OutputStream* out) { + void writeHeader(OutputStream* out) + { header.PointerToRawData = dataOffset + file.dataStart; out->writeChunk(&header, sizeof(IMAGE_SECTION_HEADER)); } - void writeData(OutputStream* out) { + void writeData(OutputStream* out) + { out->writeChunk(data, dataSize); out->writeRepeat(0, finalSize - dataSize); } - - }; - virtual bool writeObject(OutputStream* out, Slice symbols, Slice data, unsigned accessFlags, unsigned alignment) { - + virtual bool writeObject(OutputStream* out, + Slice symbols, + Slice data, + unsigned accessFlags, + unsigned alignment) + { int machine; int machineMask; @@ -245,9 +249,8 @@ public: if (accessFlags & Platform::Writable) { if (accessFlags & Platform::Executable) { sectionName = ".rwx"; - sectionMask |= IMAGE_SCN_MEM_WRITE - | IMAGE_SCN_MEM_EXECUTE - | IMAGE_SCN_CNT_CODE; + sectionMask |= IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE + | IMAGE_SCN_CNT_CODE; } else { sectionName = ".data"; sectionMask |= IMAGE_SCN_MEM_WRITE; @@ -259,11 +262,12 @@ public: FileWriter file(machine, machineMask, symbols.count); - SectionWriter section(file, sectionName, sectionMask, data.items, data.count); + SectionWriter section( + file, sectionName, sectionMask, data.items, data.count); file.writeHeader(out); - for(SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { + for (SymbolInfo* sym = symbols.begin(); sym != symbols.end(); sym++) { file.addSymbol(sym->name, sym->addr, 1, 0, 2); } @@ -271,18 +275,19 @@ public: section.writeData(out); - file.writeData(out); + file.writeData(out); return true; - } - WindowsPlatform(): - Platform(PlatformInfo(PlatformInfo::Pe, Architecture)) {} + WindowsPlatform() : Platform(PlatformInfo(PlatformInfo::Pe, Architecture)) + { + } }; WindowsPlatform<4, PlatformInfo::x86> windows32Platform; WindowsPlatform<8, PlatformInfo::x86_64> windows64Platform; -WindowsPlatform<4, PlatformInfo::Arm> windowsRtPlatform; // Windows Phone 8 and Windows RT +WindowsPlatform<4, PlatformInfo::Arm> + windowsRtPlatform; // Windows Phone 8 and Windows RT -} // namespace +} // namespace diff --git a/src/tools/object-writer/tools.cpp b/src/tools/object-writer/tools.cpp index 1f4af566d1..5bd3739825 100644 --- a/src/tools/object-writer/tools.cpp +++ b/src/tools/object-writer/tools.cpp @@ -21,112 +21,115 @@ namespace avian { namespace tools { -Buffer::Buffer(): - capacity(100), - length(0), - data((uint8_t*)malloc(capacity)) {} +Buffer::Buffer() : capacity(100), length(0), data((uint8_t*)malloc(capacity)) +{ +} -Buffer::~Buffer() { +Buffer::~Buffer() +{ free(data); } -void Buffer::ensure(size_t more) { - if(length + more > capacity) { +void Buffer::ensure(size_t more) +{ + if (length + more > capacity) { capacity = capacity * 2 + more; data = (uint8_t*)realloc(data, capacity); } } -void Buffer::write(const void* d, size_t size) { +void Buffer::write(const void* d, size_t size) +{ ensure(size); memcpy(data + length, d, size); length += size; } -unsigned StringTable::add(String str) { +unsigned StringTable::add(String str) +{ unsigned offset = Buffer::length; Buffer::write(str.text, str.length + 1); return offset; } -void OutputStream::write(uint8_t byte) { +void OutputStream::write(uint8_t byte) +{ writeChunk(&byte, 1); } -void OutputStream::writeRepeat(uint8_t byte, size_t size) { - for(size_t i = 0; i < size; i++) { +void OutputStream::writeRepeat(uint8_t byte, size_t size) +{ + for (size_t i = 0; i < size; i++) { write(byte); } } -FileOutputStream::FileOutputStream(const char* name): - file(fopen(name, "wb")) {} +FileOutputStream::FileOutputStream(const char* name) : file(fopen(name, "wb")) +{ +} -FileOutputStream::~FileOutputStream() { - if(file) { +FileOutputStream::~FileOutputStream() +{ + if (file) { fclose(file); } } -bool FileOutputStream::isValid() { +bool FileOutputStream::isValid() +{ return file; } -void FileOutputStream::writeChunk(const void* data, size_t size) { +void FileOutputStream::writeChunk(const void* data, size_t size) +{ fwrite(data, size, 1, file); } -void FileOutputStream::write(uint8_t byte) { +void FileOutputStream::write(uint8_t byte) +{ fputc(byte, file); } - Platform* Platform::first = 0; -PlatformInfo::Format PlatformInfo::formatFromString(const char* format) { - if (strcmp(format, "elf") == 0 - or strcmp(format, "linux") == 0 - or strcmp(format, "freebsd") == 0 - or strcmp(format, "qnx") == 0) - { +PlatformInfo::Format PlatformInfo::formatFromString(const char* format) +{ + if (strcmp(format, "elf") == 0 or strcmp(format, "linux") == 0 + or strcmp(format, "freebsd") == 0 or strcmp(format, "qnx") == 0) { return Elf; - } else if (strcmp(format, "pe") == 0 - or strcmp(format, "windows") == 0) - { + } else if (strcmp(format, "pe") == 0 or strcmp(format, "windows") == 0) { return Pe; - } else if (strcmp(format, "macho") == 0 - or strcmp(format, "darwin") == 0 - or strcmp(format, "ios") == 0 - or strcmp(format, "macosx") == 0) - { + } else if (strcmp(format, "macho") == 0 or strcmp(format, "darwin") == 0 + or strcmp(format, "ios") == 0 or strcmp(format, "macosx") == 0) { return MachO; } else { return UnknownFormat; } } -PlatformInfo::Architecture PlatformInfo::archFromString(const char* arch) { - if(strcmp(arch, "i386") == 0) { +PlatformInfo::Architecture PlatformInfo::archFromString(const char* arch) +{ + if (strcmp(arch, "i386") == 0) { return x86; - } else if(strcmp(arch, "x86_64") == 0) { + } else if (strcmp(arch, "x86_64") == 0) { return x86_64; - } else if(strcmp(arch, "arm") == 0) { + } else if (strcmp(arch, "arm") == 0) { return Arm; } else { return UnknownArch; } } -Platform* Platform::getPlatform(PlatformInfo info) { - for(Platform* p = first; p; p = p->next) { - if(p->info == info) { +Platform* Platform::getPlatform(PlatformInfo info) +{ + for (Platform* p = first; p; p = p->next) { + if (p->info == info) { return p; } } return 0; } -} // namespace tools - -} // namespace avian +} // namespace tools +} // namespace avian diff --git a/src/tools/type-generator/io.h b/src/tools/type-generator/io.h index 83810eba2f..346ca5fa84 100644 --- a/src/tools/type-generator/io.h +++ b/src/tools/type-generator/io.h @@ -7,7 +7,9 @@ There is NO WARRANTY for this software. See license.txt for details. */ - + +#include + #include "assert.h" #ifndef AVIAN_TOOLS_TYPE_GENERATOR_IO_H @@ -19,8 +21,10 @@ namespace typegenerator { class Input { public: - virtual ~Input() { } - + virtual ~Input() + { + } + virtual void dispose() = 0; virtual int peek() = 0; @@ -31,16 +35,20 @@ class Input { virtual unsigned column() = 0; - void skipSpace() { + void skipSpace() + { bool quit = false; while (not quit) { int c = peek(); switch (c) { - case ' ': case '\t': case '\n': + case ' ': + case '\t': + case '\n': read(); break; - default: quit = true; + default: + quit = true; } } } @@ -54,56 +62,66 @@ class FileInput : public Input { unsigned column_; bool close; - FileInput(const char* file, FILE* stream = 0, bool close = true): - file(file), stream(stream), line_(1), column_(1), close(close) - { } + FileInput(const char* file, FILE* stream = 0, bool close = true) + : file(file), stream(stream), line_(1), column_(1), close(close) + { + } - virtual ~FileInput() { + virtual ~FileInput() + { dispose(); } - virtual void dispose() { + virtual void dispose() + { if (stream and close) { fclose(stream); stream = 0; } } - virtual int peek() { + virtual int peek() + { int c = getc(stream); ungetc(c, stream); return c; } - virtual int read() { + virtual int read() + { int c = getc(stream); if (c == '\n') { - ++ line_; + ++line_; column_ = 1; } else { - ++ column_; + ++column_; } return c; } - virtual unsigned line() { + virtual unsigned line() + { return line_; } - virtual unsigned column() { + virtual unsigned column() + { return column_; } }; class Output { public: - virtual ~Output() { } - + virtual ~Output() + { + } + virtual void dispose() = 0; - virtual void write(const char* s) = 0; + virtual void write(const std::string& s) = 0; - void write(int i) { + void write(int i) + { static const int Size = 32; char s[Size]; int c UNUSED = ::snprintf(s, Size, "%d", i); @@ -118,32 +136,37 @@ class FileOutput : public Output { FILE* stream; bool close; - FileOutput(const char* file, FILE* stream = 0, bool close = true): - file(file), stream(stream), close(close) - { } + FileOutput(const char* file, FILE* stream = 0, bool close = true) + : file(file), stream(stream), close(close) + { + } - virtual ~FileOutput() { + virtual ~FileOutput() + { dispose(); } - virtual void dispose() { + virtual void dispose() + { if (stream and close) { fclose(stream); stream = 0; } } - virtual void write(const char* s) { - fputs(s, stream); + virtual void write(const std::string& s) + { + fputs(s.c_str(), stream); } - const char* filename() { + const char* filename() + { return file; } }; -} // namespace typegenerator -} // namespace tools -} // namespace avian +} // namespace typegenerator +} // namespace tools +} // namespace avian -#endif // AVIAN_TOOLS_TYPE_GENERATOR_IO_H +#endif // AVIAN_TOOLS_TYPE_GENERATOR_IO_H diff --git a/src/tools/type-generator/main.cpp b/src/tools/type-generator/main.cpp index 90affb4e3c..04e329721c 100644 --- a/src/tools/type-generator/main.cpp +++ b/src/tools/type-generator/main.cpp @@ -14,8 +14,16 @@ #include "string.h" #include "errno.h" +#include +#include +#include +#include +#include + #include "avian/constants.h" #include "avian/finder.h" + +#include #include #include "io.h" @@ -23,426 +31,227 @@ #include "assert.h" +using namespace avian::util; + #define UNREACHABLE abort() #define UNUSED __attribute__((unused)) -void operator delete(void*) { abort(); } - -extern "C" void __cxa_pure_virtual(void) { abort(); } - using namespace vm; using namespace avian::tools::typegenerator; +namespace avian { +namespace tools { +namespace typegenerator { + +class Class; + +class Field { + public: + std::string name; + size_t elementSize; + size_t offset; + uintptr_t ownerId; + bool noassert; + bool nogc; + bool polyfill; + bool threadParam; + + std::string javaSpec; + std::string typeName; + + Field(Class* ownerId, + const std::string& typeName, + const std::string& javaSpec, + const std::string& name) + : name(name), + elementSize(-1), + offset(0), + ownerId(reinterpret_cast(ownerId)), + noassert(false), + nogc(false), + polyfill(false), + threadParam(false), + javaSpec(javaSpec), + typeName(typeName) + { + } + + std::string dump() const + { + std::ostringstream ss; + ss << "field " << name << ":" << typeName << ":" << javaSpec + << ", size=" << elementSize << ", offset=" << offset; + if (noassert) { + ss << " noassert"; + } + if (nogc) { + ss << " nogc"; + } + if (polyfill) { + ss << " polyfill"; + } + return ss.str(); + } +}; + +class Method { + public: + std::string javaName; + std::string javaSpec; + + Method(const std::string& javaName, const std::string& javaSpec) + : javaName(javaName), javaSpec(javaSpec) + { + } + + bool operator==(const Method& o) const + { + return javaName == o.javaName && javaSpec == o.javaSpec; + } + + bool operator<(const Method& o) const + { + return javaName < o.javaName + || (javaName == o.javaName && javaSpec < o.javaSpec); + } + std::string dump() const + { + return "method " + javaName + javaSpec; + } +}; + +class Class { + public: + // "simple" name, used for generated code, defined in types.def + std::string name; + + // Name of the backing Java class, empty if there isn't one + std::string javaName; + + Class* super; + + std::vector fields; + std::set methods; + + Field* arrayField; + + bool overridesMethods; + + int fixedSize; + + Class(const std::string& name) + : name(name), + super(0), + arrayField(0), + overridesMethods(false), + fixedSize(-1) + { + } + + std::string dump() const + { + std::ostringstream ss; + ss << "class " << name; + if (javaName.size() > 0) { + ss << "(" << javaName << ")"; + } + if (super) { + ss << " : " << super->name << "(" << super->javaName << ")"; + } + ss << " {\n"; + + for (std::vector::const_iterator it = fields.begin(); + it != fields.end(); + it++) { + ss << " " << (*it)->dump() << "\n"; + } + + for (std::set::const_iterator it = methods.begin(); + it != methods.end(); + ++it) { + ss << " " << it->dump() << "\n"; + } + ss << "}"; + return ss.str(); + } + + void dumpToStdout() const AVIAN_EXPORT + { + printf("%s\n", dump().c_str()); + } +}; + +class Module { + public: + // Map from java-level name to Class + std::map javaClasses; + + std::map classes; + + void add(Class* cl) + { + assert(classes.find(cl->name) == classes.end()); + classes[cl->name] = cl; + if (cl->javaName != "") { + assert(javaClasses.find(cl->javaName) == javaClasses.end()); + javaClasses[cl->javaName] = cl; + } + } +}; +} +} +} + namespace { namespace local { #ifndef POINTER_SIZE -# define POINTER_SIZE sizeof(void*) +#define POINTER_SIZE sizeof(void*) #endif const unsigned BytesPerWord = POINTER_SIZE; -inline unsigned -pad(unsigned size, unsigned alignment) -{ - unsigned n = alignment; - while (size and n % size) ++ n; - return n - alignment; -} - -inline unsigned -pad(unsigned n) -{ - unsigned extra = n % BytesPerWord; - return (extra ? n + BytesPerWord - extra : n); -} - -inline bool -equal(const char* a, const char* b) +inline bool equal(const char* a, const char* b) { return strcmp(a, b) == 0; } -inline bool -endsWith(const char* a, const char* b) +inline bool endsWith(const std::string& b, const std::string& a) { - unsigned al = strlen(a); - unsigned bl = strlen(b); - return (bl >= al) and strncmp(a, b + (bl - al), al) == 0; + if (b.size() > a.size()) { + return false; + } + return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin()); } -inline const char* -take(unsigned n, const char* c) +std::string enumName(Module& module, Field& f) { - char* r = static_cast(malloc(n + 1)); - assert(r); - memcpy(r, c, n); - r[n] = 0; - return r; -} - -class Scalar : public Object { - public: - Object* owner; - const char* typeName; - const char* name; - unsigned elementSize; - bool noassert; - bool nogc; - - static Scalar* make(Object* owner, const char* typeName, const char* name, - unsigned size) - { - Scalar* o = allocate(); - o->type = Object::Scalar; - o->owner = owner; - o->typeName = typeName; - o->name = name; - o->elementSize = size; - o->noassert = false; - o->nogc = false; - return o; - } -}; - -class Array : public Scalar { - public: - static Array* make(Object* owner, const char* typeName, const char* name, - unsigned elementSize) - { - Array* o = allocate(); - o->type = Object::Array; - o->owner = owner; - o->typeName = typeName; - o->name = name; - o->elementSize = elementSize; - o->noassert = false; - o->nogc = false; - return o; - } -}; - -unsigned -arrayElementSize(Object* o) -{ - switch (o->type) { - case Object::Array: - return static_cast(o)->elementSize; - - default: - UNREACHABLE; - } -} - -Object* -memberOwner(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->owner; - - default: - UNREACHABLE; - } -} - -const char* -memberTypeName(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->typeName; - - default: - UNREACHABLE; - } -} - -const char* -memberTypeEnumName(Object* o) -{ - const char* n = memberTypeName(o); - if (strcmp("void*", n) == 0) { + std::string& type = f.typeName; + if (type == "void*") { return "word"; + } else if (type == "maybe_object") { + return "uintptr_t"; + } else if (f.javaSpec.size() != 0 + && (f.javaSpec[0] == 'L' || f.javaSpec[0] == '[')) { + return "object"; + } + std::map::iterator it = module.classes.find(f.typeName); + assert(f.typeName.size() > 0); + if (it != module.classes.end()) { + return "object"; } else { - return n; + return f.typeName; } } -const char*& -memberName(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->name; - - default: - UNREACHABLE; - } -} - -unsigned -memberSize(Object* o) -{ - switch (o->type) { - case Object::Scalar: - return static_cast(o)->elementSize; - - default: - UNREACHABLE; - } -} - -unsigned -memberElementSize(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->elementSize; - - default: - UNREACHABLE; - } -} - -bool& -memberNoAssert(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->noassert; - - default: - UNREACHABLE; - } -} - -bool& -memberNoGC(Object* o) -{ - switch (o->type) { - case Object::Scalar: - case Object::Array: - return static_cast(o)->nogc; - - default: - UNREACHABLE; - } -} - -bool -memberGC(Object* o) -{ - return not memberNoGC(o) and equal(memberTypeName(o), "object"); -} - -class Method : public Object { - public: - Object* owner; - const char* name; - const char* spec; - - static Method* make(Object* owner, const char* name, const char* spec) - { - Method* o = allocate(); - o->type = Object::Method; - o->owner = owner; - o->name = name; - o->spec = spec; - return o; - } -}; - -const char* -methodName(Object* o) -{ - switch (o->type) { - case Object::Method: - return static_cast(o)->name; - - default: - UNREACHABLE; - } -} - -const char* -methodSpec(Object* o) -{ - switch (o->type) { - case Object::Method: - return static_cast(o)->spec; - - default: - UNREACHABLE; - } -} - -class Type : public Object { - public: - const char* name; - const char* javaName; - Object* super; - List members; - List methods; - bool overridesMethods; - - static Type* make(Object::ObjectType type, const char* name, - const char* javaName) - { - Type* o = allocate(); - o->type = type; - o->name = name; - o->javaName = javaName; - o->super = 0; - o->members.first = o->members.last = 0; - o->methods.first = o->methods.last = 0; - o->overridesMethods = false; - return o; - } -}; - -const char* -typeName(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->name; - - default: - UNREACHABLE; - } -} - -const char* -typeJavaName(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->javaName; - - default: - UNREACHABLE; - } -} - -Object* -typeMembers(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->members.first; - - default: - UNREACHABLE; - } -} - -Object* -typeMethods(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->methods.first; - - default: - UNREACHABLE; - } -} - -bool& -typeOverridesMethods(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->overridesMethods; - - default: - UNREACHABLE; - } -} - -void -addMember(Object* o, Object* member) -{ - switch (o->type) { - case Object::Type: - if (member->type == Object::Array) { - static_cast(o)->members.append - (Scalar::make(o, "uintptr_t", "length", BytesPerWord)); - } - static_cast(o)->members.append(member); - break; - - default: - UNREACHABLE; - } -} - -void -addMethod(Object* o, Object* method) -{ - switch (o->type) { - case Object::Type: - for (Object* p = typeMethods(o); p; p = cdr(p)) { - Object* m = car(p); - if (equal(methodName(m), methodName(method)) - and equal(methodSpec(m), methodSpec(method))) - { - setCar(p, method); - return; - } - } - static_cast(o)->methods.append(method); - break; - - default: - UNREACHABLE; - } -} - -Object*& -typeSuper(Object* o) -{ - switch (o->type) { - case Object::Type: - return static_cast(o)->super; - - default: - UNREACHABLE; - } -} - -class Number : public Object { - public: - unsigned value; - - static Number* make(unsigned value) { - Number* o = allocate(); - o->type = Object::Number; - o->value = value; - return o; - } -}; - -unsigned -number(Object* o) -{ - assert(o->type == Object::Number); - return static_cast(o)->value; -} - class Character : public Object { public: char value; - static Character* make(char value) { + static Character* make(char value) + { Character* o = allocate(); o->type = Object::Character; o->value = value; @@ -450,8 +259,7 @@ class Character : public Object { } }; -char -character(Object* o) +char character(Object* o) { assert(o->type == Object::Character); return static_cast(o)->value; @@ -461,19 +269,22 @@ class String : public Object { public: const char* value; - static String* make(Object* s) { + static String* make(Object* s) + { assert(s); String* o = allocate(); o->type = Object::String; - + unsigned length = 0; - for (Object* p = s; p; p = cdr(p)) ++ length; + for (Object* p = s; p; p = cdr(p)) + ++length; char* value = static_cast(malloc(length + 1)); assert(value); unsigned i = 0; - for (Object* p = s; p; p = cdr(p)) value[i++] = character(car(p)); + for (Object* p = s; p; p = cdr(p)) + value[i++] = character(car(p)); value[i] = 0; o->value = value; @@ -481,8 +292,7 @@ class String : public Object { } }; -const char* -string(Object* o) +const char* string(Object* o) { assert(o->type == Object::String); return static_cast(o)->value; @@ -490,40 +300,23 @@ string(Object* o) class Singleton : public Object { public: - static Singleton* make(Object::ObjectType type) { + static Singleton* make(Object::ObjectType type) + { Singleton* o = allocate(); o->type = type; return o; } }; -bool -endsWith(char c, const char* s) +std::string capitalize(const std::string& s) { - assert(s); - if (*s == 0) return false; - - while (*s) ++ s; - return (*(s - 1) == c); + if (s[0] >= 'a' && s[0] <= 'z') { + return (char)(s[0] + 'A' - 'a') + s.substr(1, s.size() - 1); + } + return s; } -const char* -capitalize(const char* s) -{ - assert(s); - unsigned length = strlen(s); - assert(length); - char* r = static_cast(malloc(length + 1)); - assert(r); - - memcpy(r, s, length + 1); - if (r[0] >= 'a' and r[0] <= 'z') r[0] = (r[0] - 'a') + 'A'; - - return r; -} - -Object* -read(Input* in, Object* eos, int level) +Object* read(Input* in, Object* eos, int level) { List s; @@ -557,7 +350,10 @@ read(Input* in, Object* eos, int level) } } break; - case ' ': case '\t': case '\n': case '\r': { + case ' ': + case '\t': + case '\n': + case '\r': { if (s.first) { return String::make(s.first); } @@ -583,289 +379,205 @@ read(Input* in, Object* eos, int level) } } -Object* -declaration(const char* name, Object* declarations) +bool namesPointer(const std::string& s) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: - if (equal(name, typeName(o))) return o; - break; - - default: UNREACHABLE; - } - } - return 0; + return s == "Collector" or s == "Disposer" or endsWith("*", s); } -Object* -javaDeclaration(const char* name, Object* declarations) +unsigned sizeOf(Module& module, const std::string& type) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: - if (typeJavaName(o) and equal(name, typeJavaName(o))) return o; - break; - - default: UNREACHABLE; - } - } - return 0; -} - -Object* -derivationChain(Object* o) -{ - Object* chain = 0; - for (Object* p = o; p; p = typeSuper(p)) { - chain = cons(p, chain); - } - return chain; -} - -class MemberIterator { - public: - Object* types; - Object* type; - Object* members; - Object* member; - int index_; - unsigned offset_; - unsigned size_; - unsigned padding_; - unsigned alignment_; - unsigned sawSuperclassBoundary; - - MemberIterator(Object* type, bool skipSupers = false): - types(derivationChain(type)), - type(car(types)), - members(0), - member(0), - index_(-1), - offset_(BytesPerWord), - size_(0), - padding_(0), - alignment_(BytesPerWord), - sawSuperclassBoundary(true) - { - while (skipSupers and hasMore() and this->type != type) next(); - padding_ = 0; - alignment_ = BytesPerWord; - } - - bool hasMore() { - if (members) { - return true; - } else { - while (types) { - if (member) { - assert(member->type == Object::Scalar); - offset_ = ((offset_ + size_) + (BytesPerWord - 1)) - & ~(BytesPerWord - 1); - alignment_ = BytesPerWord; - sawSuperclassBoundary = true; - member = 0; - } else { - sawSuperclassBoundary = false; - } - - type = car(types); - members = typeMembers(type); - types = cdr(types); - if (members) return true; - } - return false; - } - } - - Object* next() { - assert(hasMore()); - - if (member) { - assert(member->type == Object::Scalar); - offset_ += size_; - } - - member = car(members); - members = cdr(members); - - ++ index_; - - switch (member->type) { - case Object::Scalar: { - size_ = memberSize(member); - padding_ = pad(size_, alignment_); - alignment_ = (alignment_ + size_ + padding_) % 8; - } break; - - case Object::Array: { - size_ = 0x7FFFFFFF; - padding_ = pad(memberElementSize(member), alignment_); - alignment_ = 0; - } break; - - default: UNREACHABLE; - } - - offset_ += padding_; - - // fprintf(stderr, - // "type: %s; member: %s; size: %d; padding: %d; alignment: %d;" - // " offset: %d;\n", - // typeName(type), memberName(member), size_, padding_, alignment_, - // offset_); - - return member; - } - - unsigned offset() { - return offset_; - } - - unsigned size() { - return size_; - } - - unsigned padding() { - return padding_; - } - - unsigned space() { - return size_ + padding_; - } - - unsigned index() { - return index_; - } - - unsigned alignment() { - return alignment_; - } -}; - -bool -namesPointer(const char* s) -{ - return equal(s, "Collector") - or equal(s, "Disposer") - or endsWith('*', s); -} - -unsigned -sizeOf(const char* type) -{ - if (equal(type, "object") - or equal(type, "intptr_t") or equal(type, "uintptr_t")) - { + if (type == "object" or type == "intptr_t" or type == "uintptr_t" + or type == "maybe_object") { return BytesPerWord; - } else if (equal(type, "unsigned") or equal(type, "int")) { + } else if (type == "unsigned" or type == "int") { return sizeof(int); - } else if (equal(type, "bool")) { + } else if (type == "bool") { return sizeof(bool); - } else if (equal(type, "int8_t") or equal(type, "uint8_t")) { + } else if (type == "int8_t" or type == "uint8_t") { return sizeof(uint8_t); - } else if (equal(type, "int16_t") or equal(type, "uint16_t")) { + } else if (type == "int16_t" or type == "uint16_t") { return sizeof(uint16_t); - } else if (equal(type, "int32_t") or equal(type, "uint32_t")) { + } else if (type == "int32_t" or type == "uint32_t") { return sizeof(uint32_t); - } else if (equal(type, "int64_t") or equal(type, "uint64_t")) { + } else if (type == "int64_t" or type == "uint64_t") { return sizeof(uint64_t); - } else if (equal(type, "char")) { + } else if (type == "char") { return sizeof(char); } else if (endsWith("[0]", type)) { return 0; } else if (namesPointer(type)) { return BytesPerWord; } else { - fprintf(stderr, "unexpected type: %s\n", type); - abort(); + std::map::iterator it = module.classes.find(type); + if (it != module.classes.end()) { + return BytesPerWord; + } else { + fprintf(stderr, "unexpected type: %s\n", type.c_str()); + abort(); + } } } -Object* -parseArray(Object* t, Object* p) +struct FieldSpec { + bool isArray; + std::string aliasName; + bool require; + Field* field; + + FieldSpec() + { + } + + FieldSpec(bool isArray, Field* field) + : isArray(isArray), require(false), field(field) + { + } +}; + +class ClassParser { + public: + Class* cl; + std::map fields; + + ClassParser(Class* cl) : cl(cl) + { + } + + void add(FieldSpec f) + { + if (f.field->polyfill) { + if (fields.find(f.field->name) == fields.end()) { + fields[f.field->name] = f.field; + cl->fields.push_back(f.field); + } else { + fields[f.field->name]->threadParam = true; + } + return; + } + if (f.aliasName.size() > 0) { + if (fields.find(f.aliasName) == fields.end()) { + if (fields.find(f.field->name) != fields.end()) { + // printf("alias %s.%s -> %s.%s\n", cl->name.c_str(), + // f.field->name.c_str(), cl->name.c_str(), f.aliasName.c_str()); + std::map::iterator it + = fields.find(f.field->name); + assert(it != fields.end()); + Field* renamed = it->second; + fields.erase(it); + fields[f.aliasName] = renamed; + + renamed->name = f.aliasName; + + // TODO: this currently works around how avian uses an object (either + // a char[] or byte[]) for String.data + renamed->typeName = f.field->typeName; + renamed->javaSpec = f.field->javaSpec; + } else { + // printf("ignoring absent alias %s.%s -> %s.%s\n", cl->name.c_str(), + // f.field->name.c_str(), cl->name.c_str(), f. aliasName.c_str()); + } + } else { + // printf("ignoring already defined alias %s.%s -> %s.%s\n", + // cl->name.c_str(), f.field->name.c_str(), cl->name.c_str(), f. + // aliasName.c_str()); + } + } else { + if (fields.find(f.field->name) == fields.end()) { + // printf("add %s.%s\n", cl->name.c_str(), f.field->name.c_str()); + fields[f.field->name] = f.field; + if (f.isArray) { + add(FieldSpec(false, new Field(cl, "uintptr_t", "", "length"))); + assert(!cl->arrayField); + cl->arrayField = f.field; + } else { + cl->fields.push_back(f.field); + } + } else { + // printf("required check %s.%s\n", cl->name.c_str(), + // f.field->name.c_str()); + assert(f.aliasName.size() > 0 || f.require); + fields[f.field->name]->nogc |= f.field->nogc; + fields[f.field->name]->noassert |= f.field->noassert; + } + } + } + + void setSuper(Class* super) + { + assert(!cl->super); + cl->super = super; + assert(!super->arrayField); + assert(fields.size() == 0); + for (std::vector::iterator it = super->fields.begin(); + it != super->fields.end(); + it++) { + add(FieldSpec(false, *it)); + } + } +}; + +FieldSpec parseArray(Module&, ClassParser& clparser, Object* p) { const char* typeName = string(car(p)); p = cdr(p); const char* name = string(car(p)); - return Array::make(t, typeName, name, sizeOf(typeName)); + assert(!clparser.cl->arrayField); + return FieldSpec(true, new Field(clparser.cl, typeName, "", name)); } -Object* -parseMember(Object* t, Object* p); - -Object* -parseMember(Object* t, Object* p, bool* isNew) -{ - Object* member = parseMember(t, p); - for (MemberIterator it(t); it.hasMore();) { - Object* m = it.next(); - if (equal(memberName(m), memberName(member))) { - if (not equal(memberTypeName(m), memberTypeName(member))) { - abort(); - } - *isNew = false; - return m; - } - } - *isNew = true; - return member; -} - -Object* -parseMember(Object* t, Object* p) +FieldSpec parseVerbatimField(Module&, ClassParser& clparser, Object* p) { const char* spec = string(car(p)); - if (equal(spec, "array")) { - return parseArray(t, cdr(p)); - } else if (equal(spec, "noassert")) { - bool isNew; - Object* member = parseMember(t, cdr(p), &isNew); - memberNoAssert(member) = true; - return isNew ? member : 0; - } else if (equal(spec, "nogc")) { - bool isNew; - Object* member = parseMember(t, cdr(p), &isNew); - memberNoGC(member) = true; - return isNew ? member : 0; - } else if (equal(spec, "require")) { - bool isNew; - Object* member = parseMember(t, cdr(p), &isNew); - return isNew ? member : 0; - } else if (equal(spec, "alias")) { - bool isNew; - Object* member = parseMember(t, cdr(cdr(p)), &isNew); - memberName(member) = string(car(cdr(p))); - return 0; - } else { - return Scalar::make(t, spec, string(car(cdr(p))), sizeOf(spec)); - } + const char* name = string(car(cdr(p))); + return FieldSpec(false, new Field(clparser.cl, spec, "", name)); } -void -parseSubdeclaration(Object* t, Object* p, Object* declarations) +FieldSpec parseField(Module& module, ClassParser& clparser, Object* p) +{ + FieldSpec f; + const char* spec = string(car(p)); + if (equal(spec, "field")) { + return parseVerbatimField(module, clparser, cdr(p)); + } else if (equal(spec, "array")) { + return parseArray(module, clparser, cdr(p)); + } else if (equal(spec, "noassert")) { + f = parseField(module, clparser, cdr(p)); + f.field->noassert = true; + f.require = true; + } else if (equal(spec, "nogc")) { + f = parseField(module, clparser, cdr(p)); + f.field->nogc = true; + f.require = true; + } else if (equal(spec, "require")) { + f = parseField(module, clparser, cdr(p)); + f.require = true; + } else if (equal(spec, "alias")) { + const char* name = string(car(cdr(p))); + f = parseField(module, clparser, cdr(cdr(p))); + f.aliasName = name; + } else if (equal(spec, "polyfill")) { + f = parseField(module, clparser, cdr(p)); + f.field->polyfill = true; + } else { + return parseVerbatimField(module, clparser, p); + } + return f; +} + +void parseSubdeclaration(Module& module, ClassParser& clparser, Object* p) { const char* front = string(car(p)); if (equal(front, "extends")) { - assert(t->type == Object::Type); - assert(typeSuper(t) == 0); - typeSuper(t) = declaration(string(car(cdr(p))), declarations); - assert(typeSuper(t)); - assert(typeSuper(t)->type == Object::Type); + Class* super = module.classes[string(car(cdr(p)))]; + clparser.setSuper(super); } else { - Object* member = parseMember(t, p); - if (member) { - addMember(t, member); - } + clparser.add(parseField(module, clparser, p)); } } -const char* -append(const char* a, const char* b, const char* c, const char* d) +const char* append(const char* a, const char* b, const char* c, const char* d) { unsigned al = strlen(a); unsigned bl = strlen(b); @@ -879,14 +591,12 @@ append(const char* a, const char* b, const char* c, const char* d) return p; } -const char* -append(const char* a, const char* b) +const char* append(const char* a, const char* b) { return append(a, b, "", ""); } -const char* -fieldType(const char* spec) +const char* fieldType(const char* spec) { switch (*spec) { case 'B': @@ -905,17 +615,17 @@ fieldType(const char* spec) case '[': return "object"; - default: abort(); + default: + abort(); } } -void -parseJavaClass(Object* type, Stream* s, Object* declarations) +void parseJavaClass(Module& module, ClassParser& clparser, Stream* s) { uint32_t magic = s->read4(); assert(magic == 0xCAFEBABE); - s->read2(); // minor version - s->read2(); // major version + s->read2(); // minor version + s->read2(); // major version unsigned poolCount = s->read2() - 1; uintptr_t pool[poolCount]; @@ -957,27 +667,28 @@ parseJavaClass(Object* type, Stream* s, Object* declarations) pool[i] = s->read4(); break; - default: abort(); + default: + abort(); } } - s->read2(); // flags - s->read2(); // name + s->read2(); // flags + s->read2(); // name unsigned superIndex = s->read2(); if (superIndex) { - const char* name = reinterpret_cast - (pool[pool[superIndex - 1] - 1]); - typeSuper(type) = javaDeclaration(name, declarations); - assert(typeSuper(type)); + const char* name + = reinterpret_cast(pool[pool[superIndex - 1] - 1]); + Class* super = module.javaClasses[name]; + clparser.setSuper(super); } unsigned interfaceCount = s->read2(); s->skip(interfaceCount * 2); -// for (unsigned i = 0; i < interfaceCount; ++i) { -// const char* name = reinterpret_cast -// (pool[pool[s->read2() - 1] - 1]); -// } + // for (unsigned i = 0; i < interfaceCount; ++i) { + // const char* name = reinterpret_cast + // (pool[pool[s->read2() - 1] - 1]); + // } unsigned fieldCount = s->read2(); for (unsigned i = 0; i < fieldCount; ++i) { @@ -1001,17 +712,14 @@ parseJavaClass(Object* type, Stream* s, Object* declarations) const char* spec = reinterpret_cast(pool[specIndex - 1]); const char* memberType = fieldType(spec); - Object* member = Scalar::make - (type, memberType, name, sizeOf(memberType)); - - addMember(type, member); + clparser.add( + FieldSpec(false, new Field(clparser.cl, memberType, spec, name))); } } - if (typeSuper(type)) { - for (Object* p = typeMethods(typeSuper(type)); p; p = cdr(p)) { - addMethod(type, car(p)); - } + if (clparser.cl->super) { + clparser.cl->methods.insert(clparser.cl->super->methods.begin(), + clparser.cl->super->methods.end()); } unsigned methodCount = s->read2(); @@ -1030,614 +738,638 @@ parseJavaClass(Object* type, Stream* s, Object* declarations) const char* spec = reinterpret_cast(pool[specIndex - 1]); if ((flags & (ACC_STATIC | ACC_PRIVATE)) == 0 and *name != '<') { - Object* method = Method::make(type, name, spec); - addMethod(type, method); - typeOverridesMethods(type) = true; - } + clparser.cl->methods.insert(Method(name, spec)); + clparser.cl->overridesMethods = true; + } } } -Object* -parseType(Finder* finder, Object::ObjectType type, Object* p, - Object* declarations) +void parseType(Finder* finder, Module& module, Object* p) { const char* name = string(car(p)); + Class* cl = new Class(name); + + ClassParser clparser(cl); + const char* javaName = 0; if (cdr(p) and car(cdr(p))->type == Object::String) { p = cdr(p); javaName = string(car(p)); + cl->javaName = javaName; } - Type* t = Type::make(type, name, javaName); - bool isJavaType = javaName and *javaName != '['; if (isJavaType) { - class Client: public Stream::Client { + class Client : public Stream::Client { public: - virtual void NO_RETURN handleError() { + virtual void NO_RETURN handleError() + { abort(); } } client; System::Region* region = finder->find(append(javaName, ".class")); - if (region == 0) return 0; + if (region == 0) { + return; + } Stream s(&client, region->start(), region->length()); - parseJavaClass(t, &s, declarations); + parseJavaClass(module, clparser, &s); region->dispose(); } + module.add(cl); + for (p = cdr(p); p; p = cdr(p)) { - if (type == Object::Type) { - parseSubdeclaration(t, car(p), declarations); - } else { - Object* member = parseMember(t, car(p)); - if (member) { - assert(member->type == Object::Scalar); - addMember(t, member); - } - } + parseSubdeclaration(module, clparser, car(p)); } if (not isJavaType) { - if (type == Object::Type and typeSuper(t)) { - for (Object* p = typeMethods(typeSuper(t)); p; p = cdr(p)) { - addMethod(t, car(p)); - } + if (cl->super) { + cl->methods.insert(cl->super->methods.begin(), cl->super->methods.end()); } } - - return t; } -Object* -parseDeclaration(Finder* finder, Object* p, Object* declarations) +void parseDeclaration(Finder* finder, Module& module, Object* p) { const char* spec = string(car(p)); if (equal(spec, "type")) { - return parseType(finder, Object::Type, cdr(p), declarations); + parseType(finder, module, cdr(p)); } else { fprintf(stderr, "unexpected declaration spec: %s\n", spec); abort(); } } -Object* -parse(Finder* finder, Input* in) +void parse(Finder* finder, Input* in, Module& module) { Object* eos = Singleton::make(Object::Eos); List declarations; Object* o; while ((o = read(in, eos, 0)) != eos) { - Object* declaration = parseDeclaration(finder, o, declarations.first); - if (declaration) { - declarations.append(declaration); - } - } - - return declarations.first; -} - -void -writeAccessorName(Output* out, Object* member, bool unsafe = false) -{ - const char* owner = typeName(memberOwner(member)); - out->write(owner); - out->write(capitalize(memberName(member))); - if (unsafe) { - out->write("Unsafe"); + parseDeclaration(finder, module, o); } } -void -writeOffset(Output* out, Object* offset, bool allocationStyle = false) +void layoutClass(Module& module, Class* cl) { - if (offset) { - bool wrote = false; - unsigned padLevel = 0; - for (Object* p = offset; p; p = cdr(p)) { - Object* o = car(p); - if (wrote) { - out->write(" + "); - } - switch (o->type) { - case Object::Number: { - if (number(o)) { - out->write(number(o)); - wrote = true; - } - } break; + if (cl->fixedSize >= 0) { + return; + } - case Object::Array: { - out->write("pad(("); - if (allocationStyle) { - out->write("length"); - } else { - out->write(typeName(memberOwner(o))); - out->write("Length"); - out->write("(o)"); - } - out->write(" * "); - out->write(arrayElementSize(o)); - out->write(")"); - ++ padLevel; - wrote = true; - } break; + unsigned offset = BytesPerWord; - default: UNREACHABLE; - } + unsigned size = 0; + unsigned alignment = BytesPerWord; + + alignment = BytesPerWord; + + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + it++) { + Field& f = **it; + + f.elementSize = sizeOf(module, f.typeName); + + if (!f.polyfill) { // polyfills contribute no size + alignment = f.elementSize; + offset = (offset + alignment - 1) & ~(alignment - 1); + f.offset = offset; + + size = f.elementSize; + + offset += size; } + } + if (cl->arrayField) { + Field& f = *cl->arrayField; - for (unsigned i = 0; i < padLevel; ++i) out->write(")"); - } else { - out->write("0"); + f.elementSize = sizeOf(module, f.typeName); + + alignment = f.elementSize; + offset = (offset + alignment - 1) & ~(alignment - 1); + f.offset = offset; + } + // offset = (offset + BytesPerWord - 1) & ~(BytesPerWord - 1); + cl->fixedSize = offset; +} + +void layoutClasses(Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + layoutClass(module, cl); } } -void -writeAccessor(Output* out, Object* member, Object* offset, bool unsafe = false) +void writeOffset(Output* out, size_t offset) { - const char* typeName = memberTypeName(member); + out->write(offset); +} - if (not unsafe) { - out->write("const unsigned "); - out->write(capitalize(local::typeName(memberOwner(member)))); - out->write(capitalize(memberName(member))); - out->write(" = "); - writeOffset(out, offset); - out->write(";\n\n"); - - out->write("#define HAVE_"); - out->write(capitalize(local::typeName(memberOwner(member)))); - out->write(capitalize(memberName(member))); - out->write(" 1\n\n"); - } - - out->write("inline "); - - if (endsWith("[0]", typeName)) { - out->write(take(strlen(typeName) - 3, typeName)); - out->write("*"); - } else { - out->write(typeName); - out->write("&"); - } - - out->write("\n"); - writeAccessorName(out, member, unsafe); - out->write("(Thread* t UNUSED, object"); - out->write(" o"); - if (member->type != Object::Scalar) { - out->write(", unsigned i"); - } - out->write(") {\n"); - - if (memberOwner(member)->type == Object::Type) { - if (not unsafe) { - out->write(" assert(t, t->m->unsafe or "); - out->write("instanceOf(t, arrayBodyUnsafe"); - out->write("(t, t->m->types, Machine::"); - out->write(capitalize(local::typeName(memberOwner(member)))); - out->write("Type)"); - out->write(", o));\n"); - - if (member->type != Object::Scalar) { - out->write(" assert(t, i < "); - out->write(local::typeName(memberOwner(member))); - out->write("Length(t, o));\n"); - } - } - } - - out->write(" return reinterpret_cast<"); - - if (endsWith("[0]", typeName)) { - out->write(take(strlen(typeName) - 3, typeName)); - out->write("*"); - } else { - out->write(typeName); - out->write("&"); - } - - out->write(">(reinterpret_cast(o)"); - out->write("["); - - out->write(capitalize(local::typeName(memberOwner(member)))); - out->write(capitalize(memberName(member))); - - if (member->type != Object::Scalar) { - out->write(" + (i * "); - unsigned elementSize = sizeOf(memberTypeName(member)); - out->write(elementSize); +void writeOffset(Output* out, Class* cl) +{ + out->write(cl->fixedSize); + if (cl->arrayField) { + out->write(" + pad(length * "); + out->write(cl->arrayField->elementSize); out->write(")"); } - out->write("]);\n}\n\n"); } -Object* -typeBodyOffset(Object* type, Object* offset) +std::string cppClassName(Class* cl) { - MemberIterator it(type, true); - while (it.hasMore()) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { - offset = cons(Number::make(it.space()), offset); - } break; - - case Object::Array: { - if (it.padding()) offset = cons(Number::make(it.padding()), offset); - offset = cons(m, offset); - } break; - - default: UNREACHABLE; - } - } - unsigned padding = pad(BytesPerWord, it.alignment()); - if (padding) offset = cons(Number::make(padding), offset); - return offset; -} - -Object* -typeOffset(Object* type, Object* super) -{ - if (super) { - return typeBodyOffset(super, typeOffset(super, typeSuper(super))); + if (cl->name == "jobject") { + return "object"; } else { - return (type->type == Object::Type ? - cons(Number::make(BytesPerWord), 0) : 0); + return "Gc" + capitalize(cl->name) + "*"; } } -Object* -typeOffset(Object* type) +std::string cppFieldType(Module& module, Field& f) { - return typeOffset(0, type); -} - -void -writeAccessors(Output* out, Object* declarations) -{ - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - Object* offset = typeOffset - (o, o->type == Object::Type ? typeSuper(o) : 0); - for (MemberIterator it(o, true); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { - if (it.padding()) offset = cons(Number::make(it.padding()), offset); - writeAccessor(out, m, offset); - if (memberNoAssert(m)) { - writeAccessor(out, m, offset, true); - } - offset = cons(Number::make(it.size()), offset); - } break; - - case Object::Array: { - if (it.padding()) offset = cons(Number::make(it.padding()), offset); - writeAccessor(out, m, offset); - if (memberNoAssert(m)) { - writeAccessor(out, m, offset, true); - } - offset = cons(m, offset); - } break; - - default: UNREACHABLE; - } + if (f.javaSpec.size() != 0) { + if (f.javaSpec[0] == 'L') { + std::string className = f.javaSpec.substr(1, f.javaSpec.size() - 2); + std::map::iterator it + = module.javaClasses.find(className); + if (it != module.javaClasses.end()) { + return cppClassName(it->second); } - } break; + } else if (f.javaSpec[0] == '[') { + std::map::iterator it + = module.javaClasses.find(f.javaSpec); + if (it != module.javaClasses.end()) { + return cppClassName(it->second); + } + } + } + std::map::iterator it = module.classes.find(f.typeName); + assert(f.typeName.size() > 0); + if (it != module.classes.end()) { + return cppClassName(it->second); + } else if (f.typeName == "maybe_object") { + return "uintptr_t"; + } else { + return f.typeName; + } +} - default: break; +void writeAccessor(Output* out, Class* cl, Field& field) +{ + std::string typeName = field.typeName; + + out->write("const unsigned "); + out->write(capitalize(cl->name)); + out->write(capitalize(field.name)); + out->write(" = "); + writeOffset(out, field.offset); + out->write(";\n\n"); + + out->write("#define HAVE_"); + out->write(capitalize(cl->name)); + out->write(capitalize(field.name)); + out->write(" 1\n\n"); +} + +void writeAccessors(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + ++it) { + Field& f = **it; + + if (!f.polyfill) { + writeAccessor(out, cl, f); + } + } + if (cl->arrayField) { + writeAccessor(out, cl, *cl->arrayField); } } } -unsigned -typeFixedSize(Object* type) +void writeSizes(Output* out, Module& module) { - unsigned length = BytesPerWord; - for (MemberIterator it(type); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { - length = pad(it.offset() + it.size()); - } break; + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; - case Object::Array: break; + out->write("const unsigned FixedSizeOf"); + out->write(capitalize(cl->name)); + out->write(" = "); + out->write(cl->fixedSize); + out->write(";\n\n"); - default: UNREACHABLE; - } - } - return length; -} - -unsigned -typeArrayElementSize(Object* type) -{ - for (MemberIterator it(type); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: break; - - case Object::Array: { - return memberElementSize(m); - } break; - - default: UNREACHABLE; - } - } - return 0; -} - -void -writeSizes(Output* out, Object* declarations) -{ - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - out->write("const unsigned FixedSizeOf"); - out->write(capitalize(typeName(o))); + if (cl->arrayField) { + out->write("const unsigned ArrayElementSizeOf"); + out->write(capitalize(cl->name)); out->write(" = "); - out->write(typeFixedSize(o)); + out->write(cl->arrayField->elementSize); out->write(";\n\n"); - - int aes = typeArrayElementSize(o); - if (aes) { - out->write("const unsigned ArrayElementSizeOf"); - out->write(capitalize(typeName(o))); - out->write(" = "); - out->write(aes); - out->write(";\n\n"); - } - } break; - - default: break; } } } -const char* -obfuscate(const char* s) +std::string obfuscate(const std::string& s) { - if (equal(s, "default")) { - return "default_"; - } else if (equal(s, "template")) { - return "template_"; - } else if (equal(s, "class")) { - return "class_"; - } else if (equal(s, "register")) { - return "register_"; - } else if (equal(s, "this")) { - return "this_"; + if (s == "default" || s == "template" || s == "class" || s == "register" + || s == "this") { + return s + "_"; } else { return s; } } -void -writeConstructorParameters(Output* out, Object* t) +void writeConstructorParameters(Output* out, Module& module, Class* cl) { - for (MemberIterator it(t); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + ++it) { + Field& f = **it; + if (!f.polyfill) { out->write(", "); - out->write(memberTypeName(m)); + out->write(cppFieldType(module, f)); out->write(" "); - out->write(obfuscate(memberName(m))); - } break; - - default: break; - } + out->write(obfuscate(f.name)); + } } } -void -writeConstructorArguments(Output* out, Object* t) +void writeConstructorArguments(Output* out, Class* cl) { - for (MemberIterator it(t); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + ++it) { + Field& f = **it; + if (!f.polyfill) { out->write(", "); - out->write(obfuscate(memberName(m))); - } break; - - default: break; - } - } -} - -void -writeConstructorInitializations(Output* out, Object* t) -{ - for (MemberIterator it(t); it.hasMore();) { - Object* m = it.next(); - switch (m->type) { - case Object::Scalar: { - out->write(" "); - writeAccessorName(out, m); - out->write("(t, o) = "); - out->write(obfuscate(memberName(m))); - out->write(";\n"); - } break; - - default: break; - } - } -} - -void -writeInitializerDeclarations(Output* out, Object* declarations) -{ - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - out->write("void init"); - out->write(capitalize(typeName(o))); - out->write("(Thread* t, object o"); - - writeConstructorParameters(out, o); - - out->write(");\n\n"); - } break; - - default: break; + out->write(obfuscate(f.name)); } } } -void -writeConstructorDeclarations(Output* out, Object* declarations) +void writeConstructorInitializations(Output* out, Class* cl) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - out->write("object make"); - out->write(capitalize(typeName(o))); - out->write("(Thread* t"); - - writeConstructorParameters(out, o); - - out->write(");\n\n"); - } break; - - default: break; + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + ++it) { + Field& f = **it; + if (!f.polyfill) { + out->write(" o->set"); + out->write(capitalize(f.name)); + out->write("(t, "); + out->write(obfuscate(f.name)); + out->write(");\n"); } } } -void -writeInitializers(Output* out, Object* declarations) +void writeClassDeclarations(Output* out, Module& module) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - out->write("void\ninit"); - out->write(capitalize(typeName(o))); - out->write("(Thread* t, object o"); - - writeConstructorParameters(out, o); + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + it++) { + Class* cl = it->second; - out->write(")\n{\n"); - - out->write(" setObjectClass(t, o, "); - out->write("arrayBody(t, t->m->types, Machine::"); - out->write(capitalize(typeName(o))); - out->write("Type));\n"); - - writeConstructorInitializations(out, o); - - out->write("}\n\n"); - } break; - - default: break; - } + out->write("class Gc"); + out->write(capitalize(cl->name)); + out->write(";\n"); } + out->write("\n"); } -void -writeConstructors(Output* out, Object* declarations) +bool isFieldGcVisible(Module& module, Field& f) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - out->write("object make"); - out->write(capitalize(typeName(o))); - out->write("(Thread* t"); - - writeConstructorParameters(out, o); + return enumName(module, f) == "object" && !f.nogc; +} - out->write(")\n{\n"); +bool isFieldGcMarkable(Module& module, Field& f) +{ + return (f.typeName == "maybe_object" || enumName(module, f) == "object") + && !f.nogc; +} - bool hasObjectMask = strcmp(typeName(o), "singleton") == 0; - for (MemberIterator it(o); it.hasMore();) { - Object* m = it.next(); - if (m->type == Object::Scalar - and equal(memberTypeName(m), "object") - and not memberNoGC(m)) - { - out->write(" PROTECT(t, "); - out->write(obfuscate(memberName(m))); - out->write(");\n"); +void writeClassAccessors(Output* out, Module& module, Class* cl) +{ + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + ++it) { + Field& f = **it; - hasObjectMask = true; - } else if (m->type == Object::Array - and equal(memberTypeName(m), "object") - and not memberNoGC(m)) - { - hasObjectMask = true; - } - } - - out->write(" object o = allocate(t, "); - writeOffset(out, typeOffset(o), true); - if (hasObjectMask) { - out->write(", true"); + if (!f.polyfill) { + out->write(" void set"); + out->write(capitalize(f.name)); + out->write("(Thread* t UNUSED, "); + out->write(cppFieldType(module, f)); + out->write(" value) { "); + if (isFieldGcMarkable(module, f)) { + out->write("setField(t, this , "); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write(", reinterpret_cast(value));"); } else { - out->write(", false"); + out->write("field_at<"); + out->write(cppFieldType(module, f)); + out->write(">("); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write(") = value;"); } - out->write(");\n"); + out->write(" }\n"); - out->write(" init"); - out->write(capitalize(typeName(o))); - out->write("(t, o"); - writeConstructorArguments(out, o); - out->write(");\n"); - - out->write(" return o;\n}\n\n"); - } break; - - default: break; + out->write(" "); + out->write(cppFieldType(module, f)); + out->write("* "); + out->write(obfuscate(f.name)); + out->write("Ptr() { return &field_at<"); + out->write(cppFieldType(module, f)); + out->write(">("); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write("); }\n"); } + + out->write(" "); + out->write(cppFieldType(module, f)); + if (!f.polyfill && !isFieldGcMarkable(module, f)) { + out->write("&"); + } + out->write(" "); + out->write(obfuscate(f.name)); + if (f.threadParam || f.polyfill) { + out->write("(Thread*"); + } else { + out->write("("); + } + if (f.polyfill) { + out->write("); // polyfill, assumed to be implemented elsewhere\n"); + } else { + out->write(") { return field_at<"); + out->write(cppFieldType(module, f)); + out->write(">("); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write("); }\n"); + } + } + if (cl->arrayField) { + Field& f = *cl->arrayField; + out->write(" avian::util::Slice<"); + if (isFieldGcVisible(module, f)) { + out->write("const "); + } + out->write(cppFieldType(module, f)); + out->write("> "); + out->write(obfuscate(f.name)); + out->write("() { return avian::util::Slice<"); + if (isFieldGcVisible(module, f)) { + out->write("const "); + } + out->write(cppFieldType(module, f)); + out->write("> (&field_at<"); + if (isFieldGcVisible(module, f)) { + out->write("const "); + } + out->write(cppFieldType(module, f)); + out->write(">("); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write("), field_at("); + out->write(capitalize(cl->name)); + out->write("Length)); }\n"); + + out->write(" void set"); + out->write(capitalize(f.name)); + out->write("Element(Thread* t UNUSED, size_t index, "); + out->write(cppFieldType(module, f)); + out->write(" value) { "); + if (isFieldGcMarkable(module, f)) { + out->write("setField(t, this , "); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write(" + index * ("); + out->write(sizeOf(module, f.typeName)); + out->write("), reinterpret_cast(value));"); + } else { + out->write("field_at<"); + out->write(cppFieldType(module, f)); + out->write(">("); + out->write(capitalize(cl->name)); + out->write(capitalize(f.name)); + out->write(" + index * ("); + out->write(sizeOf(module, f.typeName)); + out->write(")) = value;"); + } + out->write(" }\n"); } } -void -writeEnums(Output* out, Object* declarations) +void writeClasses(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + it++) { + Class* cl = it->second; + + out->write("class Gc"); + out->write(capitalize(cl->name)); + out->write(": public GcObject {\n"); + out->write(" public:\n"); + out->write(" static const Gc::Type Type = Gc::"); + out->write(capitalize(cl->name)); + out->write("Type;\n"); + out->write(" static const size_t FixedSize = FixedSizeOf"); + out->write(capitalize(cl->name)); + out->write(";\n\n"); + + out->write(" static Gc" + capitalize(cl->name) + "* makeZeroed(Thread* t"); + if (cl->arrayField) { + out->write(", uintptr_t length"); + } + out->write(");\n"); + + writeClassAccessors(out, module, cl); + + out->write("};\n\n"); + } +} + +void writeInitializerDeclarations(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + out->write("void init"); + out->write(capitalize(cl->name)); + out->write("(Thread* t, Gc"); + out->write(capitalize(cl->name)); + out->write("* o"); + + writeConstructorParameters(out, module, cl); + + out->write(");\n\n"); + } +} + +void writeConstructorDeclarations(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + out->write("Gc"); + out->write(capitalize(cl->name)); + out->write("* make"); + out->write(capitalize(cl->name)); + out->write("(Thread* t"); + + writeConstructorParameters(out, module, cl); + + out->write(");\n\n"); + } +} + +void writeInitializers(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + out->write("void init"); + out->write(capitalize(cl->name)); + out->write("(Thread* t, Gc"); + out->write(capitalize(cl->name)); + out->write("* o"); + + writeConstructorParameters(out, module, cl); + + out->write(")\n{\n"); + + out->write(" setObjectClass(t, reinterpret_cast(o), "); + out->write( + "reinterpret_cast(reinterpret_cast(t->m->types)->" + "body()[Gc::"); + out->write(capitalize(cl->name)); + out->write("Type]));\n"); + + writeConstructorInitializations(out, cl); + + out->write("}\n\n"); + } +} + +void writeConstructors(Output* out, Module& module) +{ + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + + bool hasObjectMask = cl->name == "singleton"; + + std::string name = "Gc" + capitalize(cl->name); + + out->write(name + "* " + name + "::makeZeroed(Thread* t"); + if (cl->arrayField) { + out->write(", uintptr_t length"); + } + out->write(")\n{\n"); + out->write(" " + name + "* o = reinterpret_cast<" + name + + "*>(allocate(t, "); + writeOffset(out, cl); + if (hasObjectMask) { + out->write(", true"); + } else { + out->write(", false"); + } + out->write("));\n"); + out->write(" setObjectClass(t, reinterpret_cast(o), "); + out->write( + "reinterpret_cast(reinterpret_cast(t->m->types)->" + "body()[Gc::"); + out->write(capitalize(cl->name)); + out->write("Type]));\n"); + out->write(" return o;\n"); + out->write("}\n\n"); + + out->write(name + "* make" + capitalize(cl->name)); + out->write("(Thread* t"); + + writeConstructorParameters(out, module, cl); + + out->write(")\n{\n"); + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + it++) { + Field& f = **it; + if (enumName(module, f) == "object" and not f.nogc) { + out->write(" PROTECT(t, "); + out->write(obfuscate(f.name)); + out->write(");\n"); + + hasObjectMask = true; + } + } + if (cl->arrayField) { + Field& f = *cl->arrayField; + if (f.typeName == "object" and not f.nogc) { + hasObjectMask = true; + } + } + + out->write(" " + name + "* o = reinterpret_cast<" + name + + "*>(allocate(t, "); + writeOffset(out, cl); + if (hasObjectMask) { + out->write(", true"); + } else { + out->write(", false"); + } + out->write("));\n"); + + out->write(" init"); + out->write(capitalize(cl->name)); + out->write("(t, o"); + writeConstructorArguments(out, cl); + out->write(");\n"); + + out->write(" return o;\n}\n\n"); + } +} + +void writeEnums(Output* out, Module& module) { bool wrote = false; - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - if (wrote) { - out->write(",\n"); - } else { - wrote = true; - } - out->write(capitalize(typeName(o))); - out->write("Type"); - } break; - - default: break; + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + if (wrote) { + out->write(",\n"); + } else { + wrote = true; } + out->write(capitalize(cl->name)); + out->write("Type"); } if (wrote) { out->write("\n"); - } + } } -unsigned -methodCount(Object* o) -{ - unsigned c = 0; - for (Object* p = typeMethods(o); p; p = cdr(p)) ++c; - return c; -} - -void -set(uint32_t* mask, unsigned index) +void set(uint32_t* mask, unsigned index) { if (index < 32) { *mask |= 1 << index; @@ -1646,316 +1378,280 @@ set(uint32_t* mask, unsigned index) } } -uint32_t -typeObjectMask(Object* type) +uint32_t typeObjectMask(Module& module, Class* cl) { - assert(typeFixedSize(type) + typeArrayElementSize(type) + assert(cl->fixedSize + (cl->arrayField ? cl->arrayField->elementSize : 0) < 32 * BytesPerWord); uint32_t mask = 1; - for (MemberIterator it(type); it.hasMore();) { - Object* m = it.next(); - unsigned offset = it.offset() / BytesPerWord; + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + it++) { + Field& f = **it; + unsigned offset = f.offset / BytesPerWord; + if (isFieldGcVisible(module, f)) { + set(&mask, offset); + } + } - switch (m->type) { - case Object::Scalar: { - if (memberGC(m)) { - set(&mask, offset); - } - } break; - - case Object::Array: { - if (memberGC(m)) { - set(&mask, offset); - } - } break; - - default: UNREACHABLE; + if (cl->arrayField) { + Field& f = *cl->arrayField; + unsigned offset = f.offset / BytesPerWord; + if (isFieldGcVisible(module, f)) { + set(&mask, offset); } } return mask; } -void -writeInitialization(Output* out, Object* type) +void writeInitialization(Output* out, + Module& module, + std::set& alreadyInited, + Class* cl) { - out->write("bootClass(t, Machine::"); - out->write(capitalize(typeName(type))); + if (alreadyInited.find(cl) != alreadyInited.end()) { + return; + } + alreadyInited.insert(cl); + if (cl->super && cl->name != "intArray" && cl->name != "class") { + writeInitialization(out, module, alreadyInited, cl->super); + } + out->write("bootClass(t, Gc::"); + out->write(capitalize(cl->name)); out->write("Type, "); - if (typeSuper(type)) { - out->write("Machine::"); - out->write(capitalize(typeName(typeSuper(type)))); + if (cl->super) { + out->write("Gc::"); + out->write(capitalize(cl->super->name)); out->write("Type"); } else { - out->write("-1"); + out->write("-1"); } out->write(", "); - if (typeObjectMask(type) != 1) { - out->write(typeObjectMask(type)); + if (typeObjectMask(module, cl) != 1) { + out->write(typeObjectMask(module, cl)); } else { - out->write("0"); + out->write("0"); } out->write(", "); - out->write(typeFixedSize(type)); + out->write(cl->fixedSize); out->write(", "); - out->write(typeArrayElementSize(type)); + out->write(cl->arrayField ? cl->arrayField->elementSize : 0); out->write(", "); - out->write(methodCount(type)); + out->write(cl->methods.size()); out->write(");\n"); } -unsigned -typeCount(Object* declarations) +void writeInitializations(Output* out, Module& module) { - unsigned count = 0; - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - switch (o->type) { - case Object::Type: { - ++ count; - } break; + std::set alreadyInited; - default: break; - } - } - return count; -} + writeInitialization(out, module, alreadyInited, module.classes["intArray"]); + writeInitialization(out, module, alreadyInited, module.classes["class"]); -Object* -reorder(Object* declarations) -{ - Object* intArrayType = 0; - Object* classType = 0; - for (Object** p = &declarations; *p;) { - Object* o = car(*p); - if (o->type == Object::Type and equal(typeName(o), "intArray")) { - intArrayType = o; - *p = cdr(*p); - } else if (o->type == Object::Type and equal(typeName(o), "class")) { - classType = o; - *p = cdr(*p); - } else { - p = &cdr(*p); - } - } - - return cons(intArrayType, cons(classType, declarations)); -} - -void -writeInitializations(Output* out, Object* declarations) -{ - declarations = reorder(declarations); - - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - if (o->type == Object::Type) { - writeInitialization(out, o); + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + if (cl->name != "intArray" && cl->name != "class") { + writeInitialization(out, module, alreadyInited, cl); } } } -void -writeJavaInitialization(Output* out, Object* type) +void writeJavaInitialization(Output* out, Class* cl) { - out->write("bootJavaClass(t, Machine::"); - out->write(capitalize(typeName(type))); + out->write("bootJavaClass(t, Gc::"); + out->write(capitalize(cl->name)); out->write("Type, "); - if (typeSuper(type)) { - out->write("Machine::"); - out->write(capitalize(typeName(typeSuper(type)))); + if (cl->super) { + out->write("Gc::"); + out->write(capitalize(cl->super->name)); out->write("Type"); } else { - out->write("-1"); + out->write("-1"); } out->write(", \""); - out->write(typeJavaName(type)); + out->write(cl->javaName); out->write("\", "); - if (typeOverridesMethods(type)) { - out->write(methodCount(type)); + if (cl->overridesMethods) { + out->write(cl->methods.size()); } else { out->write("-1"); } out->write(", bootMethod);\n"); } -void -writeJavaInitializations(Output* out, Object* declarations) +void writeJavaInitializations(Output* out, Module& module) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - if (o->type == Object::Type and typeJavaName(o)) { - writeJavaInitialization(out, o); + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + if (cl->javaName.size()) { + writeJavaInitialization(out, cl); } } } -void -writeNameInitialization(Output* out, Object* type) +void writeNameInitialization(Output* out, Class* cl) { - out->write("nameClass(t, Machine::"); - out->write(capitalize(typeName(type))); + out->write("nameClass(t, Gc::"); + out->write(capitalize(cl->name)); out->write("Type, \""); - if (equal(typeName(type), "jbyte") - or equal(typeName(type), "jboolean") - or equal(typeName(type), "jshort") - or equal(typeName(type), "jchar") - or equal(typeName(type), "jint") - or equal(typeName(type), "jlong") - or equal(typeName(type), "jfloat") - or equal(typeName(type), "jdouble") - or equal(typeName(type), "jvoid")) - { - out->write(typeName(type) + 1); + if (cl->name == "jbyte" or cl->name == "jboolean" or cl->name == "jshort" + or cl->name == "jchar" or cl->name == "jint" or cl->name == "jlong" + or cl->name == "jfloat" or cl->name == "jdouble" or cl->name == "jvoid") { + out->write(cl->name.substr(1, cl->name.size() - 1)); } else { out->write("vm::"); - out->write(typeName(type)); + out->write(cl->name); } out->write("\");\n"); } -void -writeNameInitializations(Output* out, Object* declarations) +void writeNameInitializations(Output* out, Module& module) { - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - if (o->type == Object::Type and typeJavaName(o) == 0) { - writeNameInitialization(out, o); + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + if (!cl->javaName.size()) { + writeNameInitialization(out, cl); } } } -void -writeMap(Output* out, Object* type) +void writeMap(Output* out, Module& module, Class* cl) { - for (MemberIterator it(type); it.hasMore();) { - Object* m = it.next(); + std::ostringstream ss; + uintptr_t ownerId = 0; + for (std::vector::iterator it = cl->fields.begin(); + it != cl->fields.end(); + it++) { + Field& f = **it; - if (it.sawSuperclassBoundary) { - it.sawSuperclassBoundary = false; - out->write("Type_pad, "); + if (ownerId && ownerId != f.ownerId) { + ss << "Type_pad, "; + } + ownerId = f.ownerId; + + ss << "Type_"; + ss << enumName(module, f); + if (f.nogc) { + ss << "_nogc"; } - switch (m->type) { - case Object::Scalar: { - out->write("Type_"); - out->write(memberTypeEnumName(m)); - if (memberNoGC(m)) { - out->write("_nogc"); - } - } break; - - case Object::Array: { - out->write("Type_array, "); - out->write("Type_"); - out->write(memberTypeEnumName(m)); - } break; - - default: UNREACHABLE; - } - - out->write(", "); + ss << ", "; } - out->write("Type_none"); + if (cl->arrayField) { + Field& f = *cl->arrayField; + if (ownerId && ownerId != f.ownerId) { + ss << "Type_pad, "; + } + ss << "Type_array, "; + ss << "Type_"; + ss << enumName(module, f); + ss << ", "; + } + + ss << "Type_none"; + + out->write(ss.str()); } -void -writeMaps(Output* out, Object* declarations) +void writeMaps(Output* out, Module& module) { - unsigned count = 0; - for (Object* p = declarations; p; p = cdr(p)) { - if (car(p)->type == Object::Type) { - ++ count; - } - } - out->write("Type types[]["); - out->write(count); + out->write(module.classes.size()); out->write("] = {\n"); bool wrote = false; - for (Object* p = declarations; p; p = cdr(p)) { - Object* o = car(p); - if (o->type == Object::Type) { - if (wrote) { - out->write(",\n"); - } else { - wrote = true; - } - - out->write("// "); - out->write(typeName(o)); - out->write("\n{ "); - writeMap(out, o); - out->write(" }"); + for (std::map::iterator it = module.classes.begin(); + it != module.classes.end(); + ++it) { + Class* cl = it->second; + if (wrote) { + out->write(",\n"); + } else { + wrote = true; } + + out->write("// "); + out->write(cl->name); + out->write("\n{ "); + writeMap(out, module, cl); + out->write(" }"); } out->write("\n};"); } -void -usageAndExit(const char* command) -{ - fprintf(stderr, - "usage: %s " - "{enums,declarations,constructors,initializations," - "java-initializations,name-initializations,maps}\n", - command); - exit(-1); -} +} // namespace local -} // namespace local +} // namespace -} // namespace - -extern "C" uint64_t -vmNativeCall(void*, void*, unsigned, unsigned) +extern "C" uint64_t vmNativeCall(void*, void*, unsigned, unsigned) { abort(); } -extern "C" void -vmJump(void*, void*, void*, void*, uintptr_t, uintptr_t) +extern "C" void vmJump(void*, void*, void*, void*, uintptr_t, uintptr_t) { abort(); } -int -main(int ac, char** av) +int main(int ac, char** av) { - if (ac != 5 - or not (local::equal(av[4], "enums") - or local::equal(av[4], "declarations") - or local::equal(av[4], "constructors") - or local::equal(av[4], "initializations") - or local::equal(av[4], "java-initializations") - or local::equal(av[4], "name-initializations") - or local::equal(av[4], "maps"))) - { - local::usageAndExit(av[0]); + ArgParser parser; + Arg classpath(parser, true, "cp", ""); + Arg input(parser, true, "i", ""); + Arg output(parser, true, "o", ""); + Arg outputType(parser, + true, + "t", + ""); + + if (!parser.parse(ac, av)) { + parser.printUsage(av[0]); + exit(1); + } + + if (!(local::equal(outputType.value, "enums") + || local::equal(outputType.value, "declarations") + || local::equal(outputType.value, "constructors") + || local::equal(outputType.value, "initializations") + || local::equal(outputType.value, "java-initializations") + || local::equal(outputType.value, "name-initializations") + || local::equal(outputType.value, "maps"))) { + parser.printUsage(av[0]); + exit(1); } System* system = makeSystem(); class MyAllocator : public avian::util::Allocator { public: - MyAllocator(System* s): s(s) { } + MyAllocator(System* s) : s(s) + { + } - virtual void* tryAllocate(unsigned size) { + virtual void* tryAllocate(unsigned size) + { return s->tryAllocate(size); } - virtual void* allocate(unsigned size) { + virtual void* allocate(unsigned size) + { void* p = tryAllocate(size); if (p == 0) { abort(s); @@ -1963,59 +1659,63 @@ main(int ac, char** av) return p; } - virtual void free(const void* p, unsigned) { + virtual void free(const void* p, unsigned) + { s->free(p); } System* s; } allocator(system); - Finder* finder = makeFinder(system, &allocator, av[1], 0); + Finder* finder = makeFinder(system, &allocator, classpath.value, 0); - FILE* inStream = ::fopen(av[2], "rb"); + FILE* inStream = ::fopen(input.value, "rb"); if (inStream == 0) { - fprintf(stderr, "unable to open %s: %s\n", av[2], strerror(errno)); - return -1; + fprintf(stderr, "unable to open %s: %s\n", input.value, strerror(errno)); + exit(1); } + FileInput in(0, inStream, false); - Object* declarations = local::parse(finder, &in); + Module module; + local::parse(finder, &in, module); + local::layoutClasses(module); finder->dispose(); system->dispose(); - FILE* outStream = ::fopen(av[3], "wb"); + FILE* outStream = ::fopen(output.value, "wb"); if (outStream == 0) { - fprintf(stderr, "unable to open %s: %s\n", av[3], strerror(errno)); - return -1; + fprintf(stderr, "unable to open %s: %s\n", output.value, strerror(errno)); + exit(1); } FileOutput out(0, outStream, false); - if (local::equal(av[4], "enums")) { - local::writeEnums(&out, declarations); - } else if (local::equal(av[4], "declarations")) { + if (local::equal(outputType.value, "enums")) { + local::writeEnums(&out, module); + } else if (local::equal(outputType.value, "declarations")) { out.write("const unsigned TypeCount = "); - out.Output::write(local::typeCount(declarations)); + out.Output::write(module.classes.size()); out.write(";\n\n"); - local::writeAccessors(&out, declarations); - local::writeSizes(&out, declarations); - local::writeInitializerDeclarations(&out, declarations); - local::writeConstructorDeclarations(&out, declarations); - } else if (local::equal(av[4], "constructors")) { - local::writeInitializers(&out, declarations); - local::writeConstructors(&out, declarations); - } else if (local::equal(av[4], "initializations")) { - local::writeInitializations(&out, declarations); - } else if (local::equal(av[4], "java-initializations")) { - local::writeJavaInitializations(&out, declarations); - } else if (local::equal(av[4], "name-initializations")) { - local::writeNameInitializations(&out, declarations); - } else if (local::equal(av[4], "maps")) { - local::writeMaps(&out, declarations); + local::writeClassDeclarations(&out, module); + local::writeAccessors(&out, module); + local::writeSizes(&out, module); + local::writeClasses(&out, module); + local::writeInitializerDeclarations(&out, module); + local::writeConstructorDeclarations(&out, module); + } else if (local::equal(outputType.value, "constructors")) { + local::writeInitializers(&out, module); + local::writeConstructors(&out, module); + } else if (local::equal(outputType.value, "initializations")) { + local::writeInitializations(&out, module); + } else if (local::equal(outputType.value, "java-initializations")) { + local::writeJavaInitializations(&out, module); + } else if (local::equal(outputType.value, "name-initializations")) { + local::writeNameInitializations(&out, module); + } else if (local::equal(outputType.value, "maps")) { + local::writeMaps(&out, module); } out.write("\n"); - - return 0; } diff --git a/src/tools/type-generator/sexpr.h b/src/tools/type-generator/sexpr.h index 07eb6e0d72..40be9b2483 100644 --- a/src/tools/type-generator/sexpr.h +++ b/src/tools/type-generator/sexpr.h @@ -7,7 +7,7 @@ There is NO WARRANTY for this software. See license.txt for details. */ - + #ifndef AVIAN_TOOLS_TYPE_GENERATOR_SEXPR_H #define AVIAN_TOOLS_TYPE_GENERATOR_SEXPR_H @@ -16,7 +16,8 @@ namespace tools { namespace typegenerator { template -inline T* allocate() { +inline T* allocate() +{ T* t = static_cast(malloc(sizeof(T))); assert(t); return t; @@ -30,7 +31,6 @@ class Object { Method, Type, Pair, - Number, Character, String, Eos @@ -44,7 +44,8 @@ class Pair : public Object { Object* car; Object* cdr; - static Pair* make(Object* car, Object* cdr) { + static Pair* make(Object* car, Object* cdr) + { Pair* o = allocate(); o->type = Object::Pair; o->car = car; @@ -53,26 +54,31 @@ class Pair : public Object { } }; -inline Object* cons(Object* car, Object* cdr) { +inline Object* cons(Object* car, Object* cdr) +{ return Pair::make(car, cdr); } -inline Object*& car(Object* o) { +inline Object*& car(Object* o) +{ assert(o->type == Object::Pair); return static_cast(o)->car; } -inline void setCar(Object* o, Object* v) { +inline void setCar(Object* o, Object* v) +{ assert(o->type == Object::Pair); static_cast(o)->car = v; } -inline Object*& cdr(Object* o) { +inline Object*& cdr(Object* o) +{ assert(o->type == Object::Pair); return static_cast(o)->cdr; } -inline void setCdr(Object* o, Object* v) { +inline void setCdr(Object* o, Object* v) +{ assert(o->type == Object::Pair); static_cast(o)->cdr = v; } @@ -82,9 +88,12 @@ class List { Object* first; Object* last; - List(): first(0), last(0) { } + List() : first(0), last(0) + { + } - void append(Object* o) { + void append(Object* o) + { Object* p = cons(o, 0); if (last) { setCdr(last, p); @@ -95,8 +104,8 @@ class List { } }; -} // namespace typegenerator -} // namespace tools -} // namespace avian +} // namespace typegenerator +} // namespace tools +} // namespace avian -#endif // AVIAN_TOOLS_TYPE_GENERATOR_SEXPR_H +#endif // AVIAN_TOOLS_TYPE_GENERATOR_SEXPR_H diff --git a/src/types.def b/src/types.def index 0b6b63f5ab..5adffbb963 100644 --- a/src/types.def +++ b/src/types.def @@ -4,7 +4,7 @@ (array void* vtable)) (type jclass java/lang/Class - (require object vmClass)) + (require class vmClass)) (type jaccessibleObject java/lang/reflect/AccessibleObject) @@ -22,8 +22,8 @@ (type cloneable java/lang/Cloneable) -(type singleton - (array uintptr_t body)) +(type singleton avian/Singleton + (array maybe_object body)) (type classLoader java/lang/ClassLoader (object map)) @@ -49,25 +49,20 @@ (object pool) (object signers)) -(type methodRuntimeData - (object native)) - -(type pointer - (void* value)) - (type native (void* function) (uint8_t fast)) +(type methodRuntimeData + (native native)) + +(type pointer + (void* value)) + (type nativeIntercept (extends native) (object original)) -(type finder - (void* finder) - (object name) - (object next)) - (type region (void* region) (uint32_t position)) @@ -78,22 +73,6 @@ (type lineNumberTable (array uint64_t body)) -(type code - (object pool) - (object exceptionHandlerTable) - (object lineNumberTable) - (intptr_t compiled) - (uint32_t compiledSize) - (uint16_t maxStack) - (uint16_t maxLocals) - (array uint8_t body)) - -(type reference - (uint8_t kind) - (object class) - (object name) - (object spec)) - (type invocation (uint16_t bootstrap) (int32_t index) @@ -112,14 +91,7 @@ (void* finalize) (nogc object next) (object queueTarget) - (object queueNext)) - -(type hashMap - (uint32_t size) - (object array)) - -(type weakHashMap - (extends hashMap)) + (finalizer queueNext)) (type list (uint32_t size) @@ -136,14 +108,14 @@ (type treeNode (object value) - (object left) - (object right)) + (treeNode left) + (treeNode right)) (type callNode (intptr_t address) - (object target) + (method target) (uintptr_t flags) - (object next)) + (callNode next)) (type wordArray (array uintptr_t body)) @@ -151,6 +123,13 @@ (type array (noassert array object body)) +(type hashMap + (uint32_t size) + (field array array)) + +(type weakHashMap + (extends hashMap)) + (type pair (object first) (object second)) @@ -170,16 +149,16 @@ (type innerClassReference avian/InnerClassReference) (type continuationContext - (object next) + (continuationContext next) (object before) (object after) (object continuation) - (object method)) + (method method)) (type continuation avian/Continuations$Continuation - (object next) - (object context) - (object method) + (continuation next) + (continuationContext context) + (method method) (void* address) (uintptr_t returnAddressOffset) (uintptr_t framePointerOffset) @@ -190,7 +169,9 @@ (type string java/lang/String (alias data object value) (alias length uint32_t count) - (alias hashCode uint32_t hash)) + (alias hashCode uint32_t hash) + (polyfill uint32_t offset) + (polyfill uint32_t length)) (type thread java/lang/Thread (require object sleepLock) @@ -205,7 +186,7 @@ (type stackTraceElement java/lang/StackTraceElement) (type throwable java/lang/Throwable - (alias message object detailMessage) + (alias message string detailMessage) (alias trace object backtrace) (alias trace object stackState)) @@ -293,13 +274,14 @@ (type double java/lang/Double) (type referenceQueue java/lang/ref/ReferenceQueue - (alias front object head)) + (alias front jreference head) + (require object jnext)) (type jreference java/lang/ref/Reference (alias target object referent) - (alias queue object queue) - (alias jNext object next) - (alias jNext object queueNext) + (alias queue referenceQueue queue) + (alias jNext jreference next) + (alias jNext jreference queueNext) (alias vmNext object discovered) (alias vmNext object pendingNext) (nogc object target) @@ -313,12 +295,23 @@ (type phantomReference java/lang/ref/PhantomReference) (type cleaner sun/misc/Cleaner - (object queueNext)) + (cleaner queueNext)) (type byteArray [B (extends jobject) (array int8_t body)) +(type reference + (uint8_t kind) + (byteArray class) + (byteArray name) + (byteArray spec)) + +(type finder + (void* finder) + (byteArray name) + (finder next)) + (type booleanArray [Z (extends jobject) (array uint8_t body)) @@ -335,6 +328,17 @@ (extends jobject) (array int32_t body)) +(type code avian/Code + (singleton pool) + (intArray stackMap) + (object exceptionHandlerTable) + (lineNumberTable lineNumberTable) + (intptr_t compiled) + (uint32_t compiledSize) + (uint16_t maxStack) + (uint16_t maxLocals) + (array uint8_t body)) + (type longArray [J (extends jobject) (array int64_t body)) @@ -373,3 +377,43 @@ (type jvoid (extends jobject)) + +(type roots + (classLoader bootLoader) + (classLoader appLoader) + (hashMap bootstrapClassMap) + (hashMap packageMap) + (method findLoadedClassMethod) + (method loadClassMethod) + (hashMap monitorMap) + (hashMap stringMap) + (hashMap byteArrayMap) + (hashMap poolMap) + (vector classRuntimeDataTable) + (vector methodRuntimeDataTable) + (vector jNIMethodTable) + (vector jNIFieldTable) + (pair shutdownHooks) + (thread finalizerThread) + (finalizer objectsToFinalize) + (cleaner objectsToClean) + (throwable nullPointerException) + (throwable arithmeticException) + (throwable arrayIndexOutOfBoundsException) + (throwable outOfMemoryError) + (throwable shutdownInProgress) + (finder virtualFileFinders) + (field array virtualFiles) + (field array arrayInterfaceTable) + (object threadTerminated)) + +(type compileRoots + (field array callTable) + (treeNode methodTree) + (treeNode methodTreeSentinal) + (object objectPools) + (object staticTableArray) + (wordArray virtualThunks) + (method receiveMethod) + (method windMethod) + (method rewindMethod)) diff --git a/src/util.cpp b/src/util.cpp index fce0cd538f..bf7bd77d3d 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -17,18 +17,19 @@ namespace { class TreeContext { public: - - class MyProtector: public Thread::Protector { + class MyProtector : public Thread::Protector { public: - MyProtector(Thread* thread, TreeContext* context): - Protector(thread), context(context) - { } + MyProtector(Thread* thread, TreeContext* context) + : Protector(thread), context(context) + { + } - virtual void visit(Heap::Visitor* v) { + virtual void visit(Heap::Visitor* v) + { v->visit(&(context->root)); v->visit(&(context->node)); - for (List* p = context->ancestors; p; p = p->next) { + for (List* p = context->ancestors; p; p = p->next) { v->visit(&(p->item)); } } @@ -36,50 +37,51 @@ class TreeContext { TreeContext* context; }; - TreeContext(Thread* thread, Zone* zone): - zone(zone), root(0), node(0), ancestors(0), protector(thread, this), - fresh(false) - { } - + TreeContext(Thread* thread, Zone* zone) + : zone(zone), + root(0), + node(0), + ancestors(0), + protector(thread, this), + fresh(false) + { + } + Zone* zone; - object root; - object node; - List* ancestors; + GcTreeNode* root; + GcTreeNode* node; + List* ancestors; MyProtector protector; bool fresh; }; -List* -path(TreeContext* c, object node, List* next) +List* path(TreeContext* c, + GcTreeNode* node, + List* next) { - return new(c->zone) List(node, next); + return new (c->zone) List(node, next); } -inline object -getTreeNodeValue(Thread*, object n) +inline object getTreeNodeValue(Thread*, GcTreeNode* n) { - return reinterpret_cast - (alias(n, TreeNodeValue) & PointerMask); + return reinterpret_cast(alias(n, TreeNodeValue) & PointerMask); } -inline void -setTreeNodeValue(Thread* t, object n, object value) +inline void setTreeNodeValue(Thread* t, GcTreeNode* n, object value) { intptr_t red = alias(n, TreeNodeValue) & (~PointerMask); - set(t, n, TreeNodeValue, value); + n->setValue(t, value); alias(n, TreeNodeValue) |= red; } -inline bool -treeNodeRed(Thread*, object n) +inline bool treeNodeRed(Thread*, GcTreeNode* n) { return (alias(n, TreeNodeValue) & (~PointerMask)) == 1; } -inline void -setTreeNodeRed(Thread*, object n, bool red) +inline void setTreeNodeRed(Thread*, GcTreeNode* n, bool red) { if (red) { alias(n, TreeNodeValue) |= 1; @@ -88,28 +90,29 @@ setTreeNodeRed(Thread*, object n, bool red) } } -inline object -cloneTreeNode(Thread* t, object n) +inline GcTreeNode* cloneTreeNode(Thread* t, GcTreeNode* n) { PROTECT(t, n); - object newNode = makeTreeNode - (t, getTreeNodeValue(t, n), treeNodeLeft(t, n), treeNodeRight(t, n)); + GcTreeNode* newNode + = makeTreeNode(t, getTreeNodeValue(t, n), n->left(), n->right()); setTreeNodeRed(t, newNode, treeNodeRed(t, n)); return newNode; } -object -treeFind(Thread* t, object tree, intptr_t key, object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)) +GcTreeNode* treeFind(Thread* t, + GcTreeNode* tree, + intptr_t key, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)) { - object node = tree; + GcTreeNode* node = tree; while (node != sentinal) { intptr_t difference = compare(t, key, getTreeNodeValue(t, node)); if (difference < 0) { - node = treeNodeLeft(t, node); + node = node->left(); } else if (difference > 0) { - node = treeNodeRight(t, node); + node = node->right(); } else { return node; } @@ -118,19 +121,22 @@ treeFind(Thread* t, object tree, intptr_t key, object sentinal, return 0; } -void -treeFind(Thread* t, TreeContext* c, object old, intptr_t key, object node, - object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)) +void treeFind(Thread* t, + TreeContext* c, + GcTreeNode* old, + intptr_t key, + GcTreeNode* node, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)) { PROTECT(t, old); PROTECT(t, node); PROTECT(t, sentinal); - object newRoot = cloneTreeNode(t, old); + GcTreeNode* newRoot = cloneTreeNode(t, old); PROTECT(t, newRoot); - object new_ = newRoot; + GcTreeNode* new_ = newRoot; PROTECT(t, new_); int count = 0; @@ -140,14 +146,14 @@ treeFind(Thread* t, TreeContext* c, object old, intptr_t key, object node, intptr_t difference = compare(t, key, getTreeNodeValue(t, old)); if (difference < 0) { - old = treeNodeLeft(t, old); - object n = cloneTreeNode(t, old); - set(t, new_, TreeNodeLeft, n); + old = old->left(); + GcTreeNode* n = cloneTreeNode(t, old); + new_->setLeft(t, n); new_ = n; } else if (difference > 0) { - old = treeNodeRight(t, old); - object n = cloneTreeNode(t, old); - set(t, new_, TreeNodeRight, n); + old = old->right(); + GcTreeNode* n = cloneTreeNode(t, old); + new_->setRight(t, n); new_ = n; } else { c->fresh = false; @@ -157,7 +163,7 @@ treeFind(Thread* t, TreeContext* c, object old, intptr_t key, object node, return; } - if (++ count > 100) { + if (++count > 100) { // if we've gone this deep, we probably have an unbalanced tree, // which should only happen if there's a serious bug somewhere // in our insertion process @@ -173,132 +179,119 @@ treeFind(Thread* t, TreeContext* c, object old, intptr_t key, object node, c->ancestors = c->ancestors; } -object -leftRotate(Thread* t, object n) +GcTreeNode* leftRotate(Thread* t, GcTreeNode* n) { PROTECT(t, n); - object child = cloneTreeNode(t, treeNodeRight(t, n)); - set(t, n, TreeNodeRight, treeNodeLeft(t, child)); - set(t, child, TreeNodeLeft, n); + GcTreeNode* child = cloneTreeNode(t, n->right()); + n->setRight(t, child->left()); + child->setLeft(t, n); return child; } -object -rightRotate(Thread* t, object n) +GcTreeNode* rightRotate(Thread* t, GcTreeNode* n) { PROTECT(t, n); - object child = cloneTreeNode(t, treeNodeLeft(t, n)); - set(t, n, TreeNodeLeft, treeNodeRight(t, child)); - set(t, child, TreeNodeRight, n); + GcTreeNode* child = cloneTreeNode(t, n->left()); + n->setLeft(t, child->right()); + child->setRight(t, n); return child; } -object -treeAdd(Thread* t, TreeContext* c) +GcTreeNode* treeAdd(Thread* t, TreeContext* c) { - object new_ = c->node; + GcTreeNode* new_ = c->node; PROTECT(t, new_); - object newRoot = c->root; + GcTreeNode* newRoot = c->root; PROTECT(t, newRoot); // rebalance setTreeNodeRed(t, new_, true); while (c->ancestors != 0 and treeNodeRed(t, c->ancestors->item)) { - if (c->ancestors->item - == treeNodeLeft(t, c->ancestors->next->item)) - { - if (treeNodeRed - (t, treeNodeRight(t, c->ancestors->next->item))) - { + if (c->ancestors->item == c->ancestors->next->item->left()) { + if (treeNodeRed(t, c->ancestors->next->item->right())) { setTreeNodeRed(t, c->ancestors->item, false); - object n = cloneTreeNode - (t, treeNodeRight(t, c->ancestors->next->item)); + GcTreeNode* n = cloneTreeNode(t, c->ancestors->next->item->right()); - set(t, c->ancestors->next->item, TreeNodeRight, n); + c->ancestors->next->item->setRight(t, n); - setTreeNodeRed(t, treeNodeRight(t, c->ancestors->next->item), false); + setTreeNodeRed(t, c->ancestors->next->item->right(), false); setTreeNodeRed(t, c->ancestors->next->item, true); new_ = c->ancestors->next->item; c->ancestors = c->ancestors->next->next; } else { - if (new_ == treeNodeRight(t, c->ancestors->item)) { + if (new_ == c->ancestors->item->right()) { new_ = c->ancestors->item; c->ancestors = c->ancestors->next; - object n = leftRotate(t, new_); + GcTreeNode* n = leftRotate(t, new_); - if (new_ == treeNodeRight(t, c->ancestors->item)) { - set(t, c->ancestors->item, TreeNodeRight, n); + if (new_ == c->ancestors->item->right()) { + c->ancestors->item->setRight(t, n); } else { - set(t, c->ancestors->item, TreeNodeLeft, n); + c->ancestors->item->setLeft(t, n); } c->ancestors = path(c, n, c->ancestors); } setTreeNodeRed(t, c->ancestors->item, false); setTreeNodeRed(t, c->ancestors->next->item, true); - object n = rightRotate(t, c->ancestors->next->item); + GcTreeNode* n = rightRotate(t, c->ancestors->next->item); if (c->ancestors->next->next == 0) { newRoot = n; - } else if (treeNodeRight(t, c->ancestors->next->next->item) - == c->ancestors->next->item) - { - set(t, c->ancestors->next->next->item, TreeNodeRight, n); + } else if (c->ancestors->next->next->item->right() + == c->ancestors->next->item) { + c->ancestors->next->next->item->setRight(t, n); } else { - set(t, c->ancestors->next->next->item, TreeNodeLeft, n); + c->ancestors->next->next->item->setLeft(t, n); } // done } - } else { // this is just the reverse of the code above (right and - // left swapped): - if (treeNodeRed - (t, treeNodeLeft(t, c->ancestors->next->item))) - { + } else { // this is just the reverse of the code above (right and + // left swapped): + if (treeNodeRed(t, c->ancestors->next->item->left())) { setTreeNodeRed(t, c->ancestors->item, false); - object n = cloneTreeNode - (t, treeNodeLeft(t, c->ancestors->next->item)); + GcTreeNode* n = cloneTreeNode(t, c->ancestors->next->item->left()); - set(t, c->ancestors->next->item, TreeNodeLeft, n); + c->ancestors->next->item->setLeft(t, n); - setTreeNodeRed(t, treeNodeLeft(t, c->ancestors->next->item), false); + setTreeNodeRed(t, c->ancestors->next->item->left(), false); setTreeNodeRed(t, c->ancestors->next->item, true); new_ = c->ancestors->next->item; c->ancestors = c->ancestors->next->next; } else { - if (new_ == treeNodeLeft(t, c->ancestors->item)) { + if (new_ == c->ancestors->item->left()) { new_ = c->ancestors->item; c->ancestors = c->ancestors->next; - object n = rightRotate(t, new_); + GcTreeNode* n = rightRotate(t, new_); - if (new_ == treeNodeLeft(t, c->ancestors->item)) { - set(t, c->ancestors->item, TreeNodeLeft, n); + if (new_ == c->ancestors->item->left()) { + c->ancestors->item->setLeft(t, n); } else { - set(t, c->ancestors->item, TreeNodeRight, n); + c->ancestors->item->setRight(t, n); } c->ancestors = path(c, n, c->ancestors); } setTreeNodeRed(t, c->ancestors->item, false); setTreeNodeRed(t, c->ancestors->next->item, true); - object n = leftRotate(t, c->ancestors->next->item); + GcTreeNode* n = leftRotate(t, c->ancestors->next->item); if (c->ancestors->next->next == 0) { newRoot = n; - } else if (treeNodeLeft(t, c->ancestors->next->next->item) - == c->ancestors->next->item) - { - set(t, c->ancestors->next->next->item, TreeNodeLeft, n); + } else if (c->ancestors->next->next->item->left() + == c->ancestors->next->item) { + c->ancestors->next->next->item->setLeft(t, n); } else { - set(t, c->ancestors->next->next->item, TreeNodeRight, n); + c->ancestors->next->next->item->setRight(t, n); } // done } @@ -310,24 +303,26 @@ treeAdd(Thread* t, TreeContext* c) return newRoot; } -} // namespace +} // namespace namespace vm { -object -hashMapFindNode(Thread* t, object map, object key, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)) +GcTriple* hashMapFindNode(Thread* t, + GcHashMap* map, + object key, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)) { - bool weak = objectClass(t, map) == type(t, Machine::WeakHashMapType); + bool weak = objectClass(t, map) == type(t, GcWeakHashMap::Type); - object array = hashMapArray(t, map); + GcArray* array = map->array(); if (array) { - unsigned index = hash(t, key) & (arrayLength(t, array) - 1); - for (object n = arrayBody(t, array, index); n; n = tripleThird(t, n)) { - object k = tripleFirst(t, n); + unsigned index = hash(t, key) & (array->length() - 1); + for (GcTriple* n = cast(t, array->body()[index]); n; + n = cast(t, n->third())) { + object k = n->first(); if (weak) { - k = jreferenceTarget(t, k); + k = cast(t, k)->target(); if (k == 0) { continue; } @@ -341,41 +336,43 @@ hashMapFindNode(Thread* t, object map, object key, return 0; } -void -hashMapResize(Thread* t, object map, uint32_t (*hash)(Thread*, object), - unsigned size) +void hashMapResize(Thread* t, + GcHashMap* map, + uint32_t (*hash)(Thread*, object), + unsigned size) { PROTECT(t, map); - object newArray = 0; + GcArray* newArray = 0; if (size) { - object oldArray = hashMapArray(t, map); + GcArray* oldArray = map->array(); PROTECT(t, oldArray); unsigned newLength = nextPowerOfTwo(size); - if (oldArray and arrayLength(t, oldArray) == newLength) { + if (oldArray and oldArray->length() == newLength) { return; } newArray = makeArray(t, newLength); - if (oldArray != hashMapArray(t, map)) { + if (oldArray != map->array()) { // a resize was performed during a GC via the makeArray call // above; nothing left to do return; } if (oldArray) { - bool weak = objectClass(t, map) == type(t, Machine::WeakHashMapType); - for (unsigned i = 0; i < arrayLength(t, oldArray); ++i) { - object next; - for (object p = arrayBody(t, oldArray, i); p; p = next) { - next = tripleThird(t, p); + bool weak = objectClass(t, map) == type(t, GcWeakHashMap::Type); + for (unsigned i = 0; i < oldArray->length(); ++i) { + GcTriple* next; + for (GcTriple* p = cast(t, oldArray->body()[i]); p; + p = next) { + next = cast(t, p->third()); - object k = tripleFirst(t, p); + object k = p->first(); if (weak) { - k = jreferenceTarget(t, k); + k = cast(t, k)->target(); if (k == 0) { continue; } @@ -383,19 +380,21 @@ hashMapResize(Thread* t, object map, uint32_t (*hash)(Thread*, object), unsigned index = hash(t, k) & (newLength - 1); - set(t, p, TripleThird, arrayBody(t, newArray, index)); - set(t, newArray, ArrayBody + (index * BytesPerWord), p); + p->setThird(t, newArray->body()[index]); + newArray->setBodyElement(t, index, p); } } } } - - set(t, map, HashMapArray, newArray); + + map->setArray(t, newArray); } -void -hashMapInsert(Thread* t, object map, object key, object value, - uint32_t (*hash)(Thread*, object)) +void hashMapInsert(Thread* t, + GcHashMap* map, + object key, + object value, + uint32_t (*hash)(Thread*, object)) { // note that we reinitialize the array variable whenever an // allocation (and thus possibly a collection) occurs, in case the @@ -405,19 +404,19 @@ hashMapInsert(Thread* t, object map, object key, object value, uint32_t h = hash(t, key); - bool weak = objectClass(t, map) == type(t, Machine::WeakHashMapType); + bool weak = objectClass(t, map) == type(t, GcWeakHashMap::Type); - object array = hashMapArray(t, map); + GcArray* array = map->array(); - ++ hashMapSize(t, map); + ++map->size(); - if (array == 0 or hashMapSize(t, map) >= arrayLength(t, array) * 2) { + if (array == 0 or map->size() >= array->length() * 2) { PROTECT(t, key); PROTECT(t, value); - hashMapResize(t, map, hash, array ? arrayLength(t, array) * 2 : 16); + hashMapResize(t, map, hash, array ? array->length() * 2 : 16); - array = hashMapArray(t, map); + array = map->array(); } object k = key; @@ -426,159 +425,164 @@ hashMapInsert(Thread* t, object map, object key, object value, PROTECT(t, key); PROTECT(t, value); - object r = makeWeakReference(t, 0, 0, 0, 0); - jreferenceTarget(t, r) = key; - jreferenceVmNext(t, r) = t->m->weakReferences; - t->m->weakReferences = r; + GcWeakReference* r = makeWeakReference(t, 0, 0, 0, 0); + + r->setTarget(t, key); + r->setVmNext(t, t->m->weakReferences); + t->m->weakReferences = r->as(t); k = r; - array = hashMapArray(t, map); + array = map->array(); } - object n = makeTriple(t, k, value, 0); + GcTriple* n = makeTriple(t, k, value, 0); - array = hashMapArray(t, map); + array = map->array(); - unsigned index = h & (arrayLength(t, array) - 1); + unsigned index = h & (array->length() - 1); - set(t, n, TripleThird, arrayBody(t, array, index)); - set(t, array, ArrayBody + (index * BytesPerWord), n); + n->setThird(t, array->body()[index]); + array->setBodyElement(t, index, n); - if (hashMapSize(t, map) <= arrayLength(t, array) / 3) { + if (map->size() <= array->length() / 3) { // this might happen if nodes were removed during GC in which case // we weren't able to resize at the time - hashMapResize(t, map, hash, arrayLength(t, array) / 2); + hashMapResize(t, map, hash, array->length() / 2); } } -object -hashMapRemoveNode(Thread* t, object map, unsigned index, object p, object n) +GcTriple* hashMapRemoveNode(Thread* t, + GcHashMap* map, + unsigned index, + GcTriple* p, + GcTriple* n) { if (p) { - set(t, p, TripleThird, tripleThird(t, n)); + p->setThird(t, n->third()); } else { - set(t, hashMapArray(t, map), ArrayBody + (index * BytesPerWord), - tripleThird(t, n)); + map->array()->setBodyElement(t, index, n->third()); } - -- hashMapSize(t, map); + --map->size(); return n; } -object -hashMapRemove(Thread* t, object map, object key, - uint32_t (*hash)(Thread*, object), - bool (*equal)(Thread*, object, object)) +object hashMapRemove(Thread* t, + GcHashMap* map, + object key, + uint32_t (*hash)(Thread*, object), + bool (*equal)(Thread*, object, object)) { - bool weak = objectClass(t, map) == type(t, Machine::WeakHashMapType); + bool weak = objectClass(t, map) == type(t, GcWeakHashMap::Type); - object array = hashMapArray(t, map); + GcArray* array = map->array(); object o = 0; if (array) { - unsigned index = hash(t, key) & (arrayLength(t, array) - 1); - object p = 0; - for (object n = arrayBody(t, array, index); n;) { - object k = tripleFirst(t, n); + unsigned index = hash(t, key) & (array->length() - 1); + GcTriple* p = 0; + for (GcTriple* n = cast(t, array->body()[index]); n;) { + object k = n->first(); if (weak) { - k = jreferenceTarget(t, k); + k = cast(t, k)->target(); if (k == 0) { - n = tripleThird(t, hashMapRemoveNode(t, map, index, p, n)); + n = cast(t, + hashMapRemoveNode(t, map, index, p, n)->third()); continue; } } if (equal(t, key, k)) { - o = tripleSecond(t, hashMapRemoveNode(t, map, index, p, n)); + o = hashMapRemoveNode(t, map, index, p, n)->second(); break; } else { p = n; - n = tripleThird(t, n); + n = cast(t, n->third()); } } - if ((not t->m->collecting) - and hashMapSize(t, map) <= arrayLength(t, array) / 3) - { + if ((not t->m->collecting) and map->size() <= array->length() / 3) { PROTECT(t, o); - hashMapResize(t, map, hash, arrayLength(t, array) / 2); + hashMapResize(t, map, hash, array->length() / 2); } } return o; } -void -listAppend(Thread* t, object list, object value) +void listAppend(Thread* t, GcList* list, object value) { PROTECT(t, list); - ++ listSize(t, list); - + ++list->size(); + object p = makePair(t, value, 0); - if (listFront(t, list)) { - set(t, listRear(t, list), PairSecond, p); + if (list->front()) { + cast(t, list->rear())->setSecond(t, p); } else { - set(t, list, ListFront, p); + list->setFront(t, p); } - set(t, list, ListRear, p); + list->setRear(t, p); } -object -vectorAppend(Thread* t, object vector, object value) +GcVector* vectorAppend(Thread* t, GcVector* vector, object value) { - if (vectorLength(t, vector) == vectorSize(t, vector)) { + if (vector->length() == vector->size()) { PROTECT(t, vector); PROTECT(t, value); - object newVector = makeVector - (t, vectorSize(t, vector), max(16, vectorSize(t, vector) * 2)); + GcVector* newVector + = makeVector(t, vector->size(), max(16, vector->size() * 2)); - if (vectorSize(t, vector)) { - memcpy(&vectorBody(t, newVector, 0), - &vectorBody(t, vector, 0), - vectorSize(t, vector) * BytesPerWord); + if (vector->size()) { + for (size_t i = 0; i < vector->size(); i++) { + newVector->setBodyElement(t, i, vector->body()[i]); + } } vector = newVector; } - set(t, vector, VectorBody + (vectorSize(t, vector) * BytesPerWord), value); - ++ vectorSize(t, vector); + vector->setBodyElement(t, vector->size(), value); + ++vector->size(); return vector; } -object -growArray(Thread* t, object array) +GcArray* growArray(Thread* t, GcArray* array) { PROTECT(t, array); - object newArray = makeArray - (t, array == 0 ? 16 : (arrayLength(t, array) * 2)); + GcArray* newArray = makeArray(t, array == 0 ? 16 : (array->length() * 2)); if (array) { - memcpy(&arrayBody(t, newArray, 0), &arrayBody(t, array, 0), - arrayLength(t, array)); + for (size_t i = 0; i < array->length(); i++) { + newArray->setBodyElement(t, i, array->body()[i]); + } } return newArray; } -object -treeQuery(Thread* t, object tree, intptr_t key, object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)) +object treeQuery(Thread* t, + GcTreeNode* tree, + intptr_t key, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)) { - object node = treeFind(t, tree, key, sentinal, compare); + GcTreeNode* node = treeFind(t, tree, key, sentinal, compare); return (node ? getTreeNodeValue(t, node) : 0); } -object -treeInsert(Thread* t, Zone* zone, object tree, intptr_t key, object value, - object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)) +GcTreeNode* treeInsert(Thread* t, + Zone* zone, + GcTreeNode* tree, + intptr_t key, + object value, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)) { PROTECT(t, tree); PROTECT(t, sentinal); - object node = makeTreeNode(t, value, sentinal, sentinal); + GcTreeNode* node = makeTreeNode(t, value, sentinal, sentinal); TreeContext c(t, zone); treeFind(t, &c, tree, key, node, sentinal, compare); @@ -587,11 +591,14 @@ treeInsert(Thread* t, Zone* zone, object tree, intptr_t key, object value, return treeAdd(t, &c); } -void -treeUpdate(Thread* t, object tree, intptr_t key, object value, object sentinal, - intptr_t (*compare)(Thread* t, intptr_t key, object b)) +void treeUpdate(Thread* t, + GcTreeNode* tree, + intptr_t key, + object value, + GcTreeNode* sentinal, + intptr_t (*compare)(Thread* t, intptr_t key, object b)) { setTreeNodeValue(t, treeFind(t, tree, key, sentinal, compare), value); } -} // namespace vm +} // namespace vm diff --git a/src/util/arg-parser.cpp b/src/util/arg-parser.cpp index a6274e1186..80c5429ef3 100644 --- a/src/util/arg-parser.cpp +++ b/src/util/arg-parser.cpp @@ -17,40 +17,41 @@ namespace avian { namespace util { -Arg::Arg(ArgParser& parser, bool required, const char* name, const char* desc): - next(0), - required(required), - name(name), - desc(desc), - value(0) +Arg::Arg(ArgParser& parser, bool required, const char* name, const char* desc) + : next(0), required(required), name(name), desc(desc), value(0) { *parser.last = this; parser.last = &next; } -ArgParser::ArgParser(): - first(0), - last(&first) {} +ArgParser::ArgParser() : first(0), last(&first) +{ +} -bool ArgParser::parse(int ac, const char* const* av) { +bool ArgParser::parse(int ac, const char* const* av) +{ Arg* state = 0; - for(int i = 1; i < ac; i++) { - if(state) { - if(state->value) { - fprintf(stderr, "duplicate parameter %s: '%s' and '%s'\n", state->name, state->value, av[i]); + for (int i = 1; i < ac; i++) { + if (state) { + if (state->value) { + fprintf(stderr, + "duplicate parameter %s: '%s' and '%s'\n", + state->name, + state->value, + av[i]); return false; } state->value = av[i]; state = 0; } else { - if(av[i][0] != '-') { + if (av[i][0] != '-') { fprintf(stderr, "expected -parameter\n"); return false; } bool found = false; - for(Arg* arg = first; arg; arg = arg->next) { - if(strcmp(arg->name, &av[i][1]) == 0) { + for (Arg* arg = first; arg; arg = arg->next) { + if (strcmp(arg->name, &av[i][1]) == 0) { found = true; if (arg->desc == 0) { arg->value = "true"; @@ -66,13 +67,13 @@ bool ArgParser::parse(int ac, const char* const* av) { } } - if(state) { + if (state) { fprintf(stderr, "expected argument after -%s\n", state->name); return false; } - for(Arg* arg = first; arg; arg = arg->next) { - if(arg->required && !arg->value) { + for (Arg* arg = first; arg; arg = arg->next) { + if (arg->required && !arg->value) { fprintf(stderr, "expected value for %s\n", arg->name); return false; } @@ -81,11 +82,12 @@ bool ArgParser::parse(int ac, const char* const* av) { return true; } -void ArgParser::printUsage(const char* exe) { +void ArgParser::printUsage(const char* exe) +{ fprintf(stderr, "usage:\n%s \\\n", exe); - for(Arg* arg = first; arg; arg = arg->next) { + for (Arg* arg = first; arg; arg = arg->next) { const char* lineEnd = arg->next ? " \\" : ""; - if(arg->required) { + if (arg->required) { fprintf(stderr, " -%s\t%s%s\n", arg->name, arg->desc, lineEnd); } else if (arg->desc) { fprintf(stderr, " [-%s\t%s]%s\n", arg->name, arg->desc, lineEnd); @@ -95,5 +97,5 @@ void ArgParser::printUsage(const char* exe) { } } -} // namespace util -} // namespace avian +} // namespace util +} // namespace avian diff --git a/src/util/fixed-allocator.cpp b/src/util/fixed-allocator.cpp index ea8e237322..91d0d88621 100644 --- a/src/util/fixed-allocator.cpp +++ b/src/util/fixed-allocator.cpp @@ -42,8 +42,8 @@ void* FixedAllocator::allocate(unsigned size) void FixedAllocator::free(const void* p, unsigned size) { - if (p >= memory.begin() and static_cast(p) + size - == memory.begin() + offset) { + if (p >= memory.begin() + and static_cast(p) + size == memory.begin() + offset) { offset -= size; } else { abort(a); diff --git a/test/jni.cpp b/test/jni.cpp index 6bc11e12c2..70d5b63ed3 100644 --- a/test/jni.cpp +++ b/test/jni.cpp @@ -19,123 +19,175 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) return JNI_VERSION_1_6; } -extern "C" JNIEXPORT jdouble JNICALL -Java_JNI_addDoubles -(JNIEnv*, jclass, - jdouble a1, jdouble a2, jdouble a3, jdouble a4, jdouble a5, jdouble a6, - jdouble a7, jdouble a8, jdouble a9, jdouble a10, jdouble a11, jdouble a12, - jdouble a13, jdouble a14, jdouble a15, jdouble a16, jdouble a17, jdouble a18, - jdouble a19, jdouble a20) +extern "C" JNIEXPORT jdouble JNICALL Java_JNI_addDoubles(JNIEnv*, + jclass, + jdouble a1, + jdouble a2, + jdouble a3, + jdouble a4, + jdouble a5, + jdouble a6, + jdouble a7, + jdouble a8, + jdouble a9, + jdouble a10, + jdouble a11, + jdouble a12, + jdouble a13, + jdouble a14, + jdouble a15, + jdouble a16, + jdouble a17, + jdouble a18, + jdouble a19, + jdouble a20) { return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 - + a14 + a15 + a16 + a17 + a18 + a19 + a20; + + a14 + a15 + a16 + a17 + a18 + a19 + a20; +} + +extern "C" JNIEXPORT jfloat JNICALL Java_JNI_addFloats(JNIEnv*, + jclass, + jfloat a1, + jfloat a2, + jfloat a3, + jfloat a4, + jfloat a5, + jfloat a6, + jfloat a7, + jfloat a8, + jfloat a9, + jfloat a10, + jfloat a11, + jfloat a12, + jfloat a13, + jfloat a14, + jfloat a15, + jfloat a16, + jfloat a17, + jfloat a18, + jfloat a19, + jfloat a20) +{ + return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + + a14 + a15 + a16 + a17 + a18 + a19 + a20; +} + +extern "C" JNIEXPORT jdouble JNICALL Java_JNI_addMix(JNIEnv*, + jclass, + jfloat a1, + jdouble a2, + jfloat a3, + jdouble a4, + jfloat a5, + jfloat a6, + jfloat a7, + jfloat a8, + jfloat a9, + jfloat a10, + jfloat a11, + jfloat a12, + jfloat a13, + jfloat a14, + jfloat a15, + jdouble a16, + jfloat a17, + jfloat a18, + jfloat a19, + jfloat a20) +{ + return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + + a14 + a15 + a16 + a17 + a18 + a19 + a20; } extern "C" JNIEXPORT jfloat JNICALL -Java_JNI_addFloats -(JNIEnv*, jclass, - jfloat a1, jfloat a2, jfloat a3, jfloat a4, jfloat a5, jfloat a6, - jfloat a7, jfloat a8, jfloat a9, jfloat a10, jfloat a11, jfloat a12, - jfloat a13, jfloat a14, jfloat a15, jfloat a16, jfloat a17, jfloat a18, - jfloat a19, jfloat a20) -{ - return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 - + a14 + a15 + a16 + a17 + a18 + a19 + a20; -} - -extern "C" JNIEXPORT jdouble JNICALL -Java_JNI_addMix -(JNIEnv*, jclass, - jfloat a1, jdouble a2, jfloat a3, jdouble a4, jfloat a5, jfloat a6, - jfloat a7, jfloat a8, jfloat a9, jfloat a10, jfloat a11, jfloat a12, - jfloat a13, jfloat a14, jfloat a15, jdouble a16, jfloat a17, jfloat a18, - jfloat a19, jfloat a20) -{ - return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 - + a14 + a15 + a16 + a17 + a18 + a19 + a20; -} - -extern "C" JNIEXPORT jfloat JNICALL -Java_JNI_doEcho__F(JNIEnv* e, jclass c, jfloat f) + Java_JNI_doEcho__F(JNIEnv* e, jclass c, jfloat f) { jvalue value; value.f = f; - jvalue array[] = { value }; - return e->CallStaticFloatMethodA - (c, e->GetStaticMethodID(c, "echo", "(F)F"), array); + jvalue array[] = {value}; + return e->CallStaticFloatMethodA( + c, e->GetStaticMethodID(c, "echo", "(F)F"), array); } extern "C" JNIEXPORT jdouble JNICALL -Java_JNI_doEcho__D(JNIEnv* e, jclass c, jdouble f) + Java_JNI_doEcho__D(JNIEnv* e, jclass c, jdouble f) { jvalue value; value.d = f; - jvalue array[] = { value }; - return e->CallStaticDoubleMethodA - (c, e->GetStaticMethodID(c, "echo", "(D)D"), array); + jvalue array[] = {value}; + return e->CallStaticDoubleMethodA( + c, e->GetStaticMethodID(c, "echo", "(D)D"), array); } extern "C" JNIEXPORT jlong JNICALL -Java_JNI_fromReflectedMethod(JNIEnv* e, jclass, jobject method) + Java_JNI_fromReflectedMethod(JNIEnv* e, jclass, jobject method) { return reinterpret_cast(e->FromReflectedMethod(method)); } extern "C" JNIEXPORT jobject JNICALL -Java_JNI_toReflectedMethod(JNIEnv* e, jclass, jclass c, jlong id, - jboolean isStatic) + Java_JNI_toReflectedMethod(JNIEnv* e, + jclass, + jclass c, + jlong id, + jboolean isStatic) { return e->ToReflectedMethod(c, reinterpret_cast(id), isStatic); } extern "C" JNIEXPORT jint JNICALL -Java_JNI_callStaticIntMethod(JNIEnv* e, jclass, jclass c, jlong id) + Java_JNI_callStaticIntMethod(JNIEnv* e, jclass, jclass c, jlong id) { return e->CallStaticIntMethod(c, reinterpret_cast(id)); } extern "C" JNIEXPORT jobject JNICALL -Java_JNI_newObject(JNIEnv* e, jclass, jclass c, jlong id) + Java_JNI_newObject(JNIEnv* e, jclass, jclass c, jlong id) { return e->NewObject(c, reinterpret_cast(id)); } extern "C" JNIEXPORT jlong JNICALL -Java_JNI_fromReflectedField(JNIEnv* e, jclass, jobject field) + Java_JNI_fromReflectedField(JNIEnv* e, jclass, jobject field) { return reinterpret_cast(e->FromReflectedField(field)); } extern "C" JNIEXPORT jobject JNICALL -Java_JNI_toReflectedField(JNIEnv* e, jclass, jclass c, jlong id, - jboolean isStatic) + Java_JNI_toReflectedField(JNIEnv* e, + jclass, + jclass c, + jlong id, + jboolean isStatic) { return e->ToReflectedField(c, reinterpret_cast(id), isStatic); } extern "C" JNIEXPORT jint JNICALL -Java_JNI_getStaticIntField(JNIEnv* e, jclass, jclass c, jlong id) + Java_JNI_getStaticIntField(JNIEnv* e, jclass, jclass c, jlong id) { return e->GetStaticIntField(c, reinterpret_cast(id)); } extern "C" JNIEXPORT jobject JNICALL -Java_JNI_testLocalRef(JNIEnv* e, jclass, jobject o) + Java_JNI_testLocalRef(JNIEnv* e, jclass, jobject o) { return e->NewLocalRef(o); } extern "C" JNIEXPORT jobject JNICALL -Java_Buffers_allocateNative(JNIEnv* e, jclass, jint capacity) + Java_Buffers_allocateNative(JNIEnv* e, jclass, jint capacity) { void* p = allocate(e, capacity); - if (p == 0) return 0; + if (p == 0) + return 0; return e->NewDirectByteBuffer(p, capacity); } extern "C" JNIEXPORT void JNICALL -Java_Buffers_freeNative(JNIEnv* e, jclass, jobject b) + Java_Buffers_freeNative(JNIEnv* e, jclass, jobject b) { free(e->GetDirectBufferAddress(b)); } diff --git a/unittest/codegen/assembler-test.cpp b/unittest/codegen/assembler-test.cpp index d115e81ee8..fa20b9a26c 100644 --- a/unittest/codegen/assembler-test.cpp +++ b/unittest/codegen/assembler-test.cpp @@ -22,61 +22,63 @@ #include "test-harness.h" - using namespace avian::codegen; using namespace vm; class BasicEnv { -public: + public: System* s; Heap* heap; Architecture* arch; - BasicEnv(): - s(makeSystem()), - heap(makeHeap(s, 32 * 1024)), - arch(makeArchitectureNative(s, true)) + BasicEnv() + : s(makeSystem()), + heap(makeHeap(s, 32 * 1024)), + arch(makeArchitectureNative(s, true)) { arch->acquire(); } - ~BasicEnv() { + ~BasicEnv() + { arch->release(); s->dispose(); } }; class Asm { -public: + public: Zone zone; Assembler* a; - Asm(BasicEnv& env): - zone(env.s, env.heap, 8192), - a(env.arch->makeAssembler(env.heap, &zone)) - { } + Asm(BasicEnv& env) + : zone(env.s, env.heap, 8192), a(env.arch->makeAssembler(env.heap, &zone)) + { + } - ~Asm() { + ~Asm() + { a->dispose(); } }; - -TEST(BasicAssembler) { +TEST(BasicAssembler) +{ BasicEnv env; Asm a(env); } -TEST(ArchitecturePlan) { +TEST(ArchitecturePlan) +{ BasicEnv env; - for(int op = (int)lir::Call; op < (int)lir::AlignedJump; op++) { + for (int op = (int)lir::Call; op < (int)lir::AlignedJump; op++) { bool thunk; OperandMask mask; - env.arch->plan((lir::UnaryOperation)op, vm::TargetBytesPerWord, mask, &thunk); + env.arch->plan( + (lir::UnaryOperation)op, vm::TargetBytesPerWord, mask, &thunk); assertFalse(thunk); assertNotEqual(static_cast(0), mask.typeMask); assertNotEqual(static_cast(0), mask.registerMask); } - } diff --git a/unittest/codegen/registers-test.cpp b/unittest/codegen/registers-test.cpp index 215e9fa4cb..f565e813d7 100644 --- a/unittest/codegen/registers-test.cpp +++ b/unittest/codegen/registers-test.cpp @@ -14,12 +14,11 @@ #include "test-harness.h" - using namespace avian::codegen; using namespace vm; - -TEST(RegisterIterator) { +TEST(RegisterIterator) +{ RegisterMask regs(0x55); assertEqual(0, regs.start); assertEqual(7, regs.limit); diff --git a/unittest/test-harness.cpp b/unittest/test-harness.cpp index 449ffc9ed0..13be65e104 100644 --- a/unittest/test-harness.cpp +++ b/unittest/test-harness.cpp @@ -14,28 +14,28 @@ // since we aren't linking against libstdc++, we must implement this // ourselves: -extern "C" void __cxa_pure_virtual(void) { abort(); } +extern "C" void __cxa_pure_virtual(void) +{ + abort(); +} Test* Test::first = 0; Test** Test::last = &first; -Test::Test(const char* name): - next(0), - failures(0), - runs(0), - name(name) +Test::Test(const char* name) : next(0), failures(0), runs(0), name(name) { *last = this; last = &next; } -bool Test::runAll() { +bool Test::runAll() +{ int failures = 0; - for(Test* t = Test::first; t; t = t->next) { + for (Test* t = Test::first; t; t = t->next) { printf("%32s: ", t->name); t->run(); failures += t->failures; - if(t->failures > 0) { + if (t->failures > 0) { printf("failure\n"); } else { printf("success\n"); @@ -44,8 +44,9 @@ bool Test::runAll() { return failures == 0; } -int main(int argc UNUSED, char** argv UNUSED) { - if(Test::runAll()) { +int main(int argc UNUSED, char** argv UNUSED) +{ + if (Test::runAll()) { return 0; } return 1; diff --git a/unittest/util/arg-parser-test.cpp b/unittest/util/arg-parser-test.cpp index fec617ceee..f699845c7c 100644 --- a/unittest/util/arg-parser-test.cpp +++ b/unittest/util/arg-parser-test.cpp @@ -8,7 +8,6 @@ There is NO WARRANTY for this software. See license.txt for details. */ - #include #include "avian/common.h" @@ -19,17 +18,14 @@ using namespace avian::util; -TEST(ArgParser) { +TEST(ArgParser) +{ { ArgParser parser; Arg arg1(parser, false, "arg1", ""); Arg required2(parser, true, "required2", ""); - const char* args[] = { - "myExecutable", - "-arg1", "myValue1", - "-required2", "myRequired2", - 0 - }; + const char* args[] + = {"myExecutable", "-arg1", "myValue1", "-required2", "myRequired2", 0}; assertTrue(parser.parse(sizeof(args) / sizeof(char*) - 1, args)); assertEqual("myValue1", arg1.value); assertEqual("myRequired2", required2.value); @@ -39,12 +35,7 @@ TEST(ArgParser) { ArgParser parser; Arg arg1(parser, false, "arg1", ""); Arg required2(parser, true, "required2", ""); - const char* args[] = { - "myExecutable", - "-arg1", "myValue1", - "-required2", - 0 - }; + const char* args[] = {"myExecutable", "-arg1", "myValue1", "-required2", 0}; assertFalse(parser.parse(sizeof(args) / sizeof(char*) - 1, args)); } @@ -52,11 +43,7 @@ TEST(ArgParser) { ArgParser parser; Arg arg1(parser, false, "arg1", ""); Arg required2(parser, true, "required2", ""); - const char* args[] = { - "myExecutable", - "-arg1", "myValue1", - 0 - }; + const char* args[] = {"myExecutable", "-arg1", "myValue1", 0}; assertFalse(parser.parse(sizeof(args) / sizeof(char*) - 1, args)); } }