blob: 808752e3070b03e833e3f9d7472f52c85a903483 [file] [log] [blame]
/*
* Android "Almost" C Compiler.
* This is a compiler for a small subset of the C language, intended for use
* in scripting environments where speed and memory footprint are important.
*
* This code is based upon the "unobfuscated" version of the
* Obfuscated Tiny C compiler, see the file LICENSE for details.
*
*/
#define LOG_TAG "acc"
#include <cutils/log.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <cutils/hashmap.h>
#if defined(__i386__)
#include <sys/mman.h>
#endif
#if defined(__arm__)
#define DEFAULT_ARM_CODEGEN
#define PROVIDE_ARM_CODEGEN
#elif defined(__i386__)
#define DEFAULT_X86_CODEGEN
#define PROVIDE_X86_CODEGEN
#elif defined(__x86_64__)
#define DEFAULT_X64_CODEGEN
#define PROVIDE_X64_CODEGEN
#endif
#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
#define ARM_USE_VFP
#endif
#include <acc/acc.h>
#define LOG_API(...) do {} while(0)
// #define LOG_API(...) fprintf (stderr, __VA_ARGS__)
#define LOG_STACK(...) do {} while(0)
// #define LOG_STACK(...) fprintf (stderr, __VA_ARGS__)
// #define PROVIDE_TRACE_CODEGEN
// Uncomment to disable ARM peephole optimizations
// #define DISABLE_ARM_PEEPHOLE
// Uncomment to save input to a text file in DEBUG_DUMP_PATTERN
// #define DEBUG_SAVE_INPUT_TO_FILE
#ifdef DEBUG_SAVE_INPUT_TO_FILE
#ifdef ARM_USE_VFP
#define DEBUG_DUMP_PATTERN "/data/misc/acc_dump/%d.c"
#else
#define DEBUG_DUMP_PATTERN "/tmp/acc_dump/%d.c"
#endif
#endif
#define assert(b) assertImpl(b, __LINE__)
namespace acc {
// Subset of STL vector.
template<class E> class Vector {
public:
Vector() {
mpBase = 0;
mUsed = 0;
mSize = 0;
}
~Vector() {
if (mpBase) {
for(size_t i = 0; i < mUsed; i++) {
mpBase[mUsed].~E();
}
free(mpBase);
}
}
inline E& operator[](size_t i) {
return mpBase[i];
}
inline E& front() {
return mpBase[0];
}
inline E& back() {
return mpBase[mUsed - 1];
}
void pop_back() {
mUsed -= 1;
mpBase[mUsed].~E();
}
void push_back(const E& item) {
* ensure(1) = item;
}
size_t size() {
return mUsed;
}
private:
E* ensure(int n) {
size_t newUsed = mUsed + n;
if (newUsed > mSize) {
size_t newSize = mSize * 2 + 10;
if (newSize < newUsed) {
newSize = newUsed;
}
mpBase = (E*) realloc(mpBase, sizeof(E) * newSize);
mSize = newSize;
}
E* result = mpBase + mUsed;
mUsed = newUsed;
return result;
}
E* mpBase;
size_t mUsed;
size_t mSize;
};
class ErrorSink {
public:
void error(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
verror(fmt, ap);
va_end(ap);
}
virtual ~ErrorSink() {}
virtual void verror(const char* fmt, va_list ap) = 0;
};
class Compiler : public ErrorSink {
typedef int tokenid_t;
enum TypeTag {
TY_INT, // 0
TY_CHAR, // 1
TY_SHORT, // 2
TY_VOID, // 3
TY_FLOAT, // 4
TY_DOUBLE, // 5
TY_POINTER, // 6
TY_ARRAY, // 7
TY_STRUCT, // 8
TY_FUNC, // 9
TY_PARAM // 10
};
struct Type {
TypeTag tag;
tokenid_t id; // For function arguments, global vars, local vars, struct elements
tokenid_t structTag; // For structs the name of the struct
int length; // length of array, offset of struct element. -1 means struct is forward defined
int alignment; // for structs only
Type* pHead; // For a struct this is the prototype struct.
Type* pTail;
};
enum ExpressionType {
ET_RVALUE,
ET_LVALUE
};
struct ExpressionValue {
ExpressionValue() {
et = ET_RVALUE;
pType = NULL;
}
ExpressionType et;
Type* pType;
};
class ICodeBuf {
public:
virtual ~ICodeBuf() {}
virtual void init(int size) = 0;
virtual void setErrorSink(ErrorSink* pErrorSink) = 0;
virtual void o4(int n) = 0;
virtual void ob(int n) = 0;
virtual void* getBase() = 0;
virtual intptr_t getSize() = 0;
virtual intptr_t getPC() = 0;
// Call this before trying to modify code in the buffer.
virtual void flush() = 0;
};
class CodeBuf : public ICodeBuf {
char* ind; // Output code pointer
char* pProgramBase;
ErrorSink* mErrorSink;
int mSize;
bool mOverflowed;
void release() {
if (pProgramBase != 0) {
free(pProgramBase);
pProgramBase = 0;
}
}
bool check(int n) {
int newSize = ind - pProgramBase + n;
bool overflow = newSize > mSize;
if (overflow && !mOverflowed) {
mOverflowed = true;
if (mErrorSink) {
mErrorSink->error("Code too large: %d bytes", newSize);
}
}
return overflow;
}
public:
CodeBuf() {
pProgramBase = 0;
ind = 0;
mErrorSink = 0;
mSize = 0;
mOverflowed = false;
}
virtual ~CodeBuf() {
release();
}
virtual void init(int size) {
release();
mSize = size;
pProgramBase = (char*) calloc(1, size);
ind = pProgramBase;
}
virtual void setErrorSink(ErrorSink* pErrorSink) {
mErrorSink = pErrorSink;
}
virtual void o4(int n) {
if(check(4)) {
return;
}
* (int*) ind = n;
ind += 4;
}
/*
* Output a byte. Handles all values, 0..ff.
*/
virtual void ob(int n) {
if(check(1)) {
return;
}
*ind++ = n;
}
virtual void* getBase() {
return (void*) pProgramBase;
}
virtual intptr_t getSize() {
return ind - pProgramBase;
}
virtual intptr_t getPC() {
return (intptr_t) ind;
}
virtual void flush() {}
};
/**
* A code generator creates an in-memory program, generating the code on
* the fly. There is one code generator implementation for each supported
* architecture.
*
* The code generator implements the following abstract machine:
* R0 - the accumulator.
* FP - a frame pointer for accessing function arguments and local
* variables.
* SP - a stack pointer for storing intermediate results while evaluating
* expressions. The stack pointer grows downwards.
*
* The function calling convention is that all arguments are placed on the
* stack such that the first argument has the lowest address.
* After the call, the result is in R0. The caller is responsible for
* removing the arguments from the stack.
* The R0 register is not saved across function calls. The
* FP and SP registers are saved.
*/
class CodeGenerator {
public:
CodeGenerator() {
mErrorSink = 0;
pCodeBuf = 0;
pushType();
}
virtual ~CodeGenerator() {}
virtual void init(ICodeBuf* pCodeBuf) {
this->pCodeBuf = pCodeBuf;
pCodeBuf->setErrorSink(mErrorSink);
}
virtual void setErrorSink(ErrorSink* pErrorSink) {
mErrorSink = pErrorSink;
if (pCodeBuf) {
pCodeBuf->setErrorSink(mErrorSink);
}
}
/* Give the code generator some utility types so it can
* use its own types as needed for the results of some
* operations like gcmp.
*/
void setTypes(Type* pInt) {
mkpInt = pInt;
}
/* Emit a function prolog.
* pDecl is the function declaration, which gives the arguments.
* Save the old value of the FP.
* Set the new value of the FP.
* Convert from the native platform calling convention to
* our stack-based calling convention. This may require
* pushing arguments from registers to the stack.
* Allocate "N" bytes of stack space. N isn't known yet, so
* just emit the instructions for adjusting the stack, and return
* the address to patch up. The patching will be done in
* functionExit().
* returns address to patch with local variable size.
*/
virtual int functionEntry(Type* pDecl) = 0;
/* Emit a function epilog.
* Restore the old SP and FP register values.
* Return to the calling function.
* argCount - the number of arguments to the function.
* localVariableAddress - returned from functionEntry()
* localVariableSize - the size in bytes of the local variables.
*/
virtual void functionExit(Type* pDecl, int localVariableAddress,
int localVariableSize) = 0;
/* load immediate value to R0 */
virtual void li(int i) = 0;
/* Load floating point value from global address. */
virtual void loadFloat(int address, Type* pType) = 0;
/* Add the struct offset in bytes to R0, change the type to pType */
virtual void addStructOffsetR0(int offset, Type* pType) = 0;
/* Jump to a target, and return the address of the word that
* holds the target data, in case it needs to be fixed up later.
*/
virtual int gjmp(int t) = 0;
/* Test R0 and jump to a target if the test succeeds.
* l = 0: je, l == 1: jne
* Return the address of the word that holds the targed data, in
* case it needs to be fixed up later.
*/
virtual int gtst(bool l, int t) = 0;
/* Compare TOS against R0, and store the boolean result in R0.
* Pops TOS.
* op specifies the comparison.
*/
virtual void gcmp(int op) = 0;
/* Perform the arithmetic op specified by op. TOS is the
* left argument, R0 is the right argument.
* Pops TOS.
*/
virtual void genOp(int op) = 0;
/* Compare 0 against R0, and store the boolean result in R0.
* op specifies the comparison.
*/
virtual void gUnaryCmp(int op) = 0;
/* Perform the arithmetic op specified by op. 0 is the
* left argument, R0 is the right argument.
*/
virtual void genUnaryOp(int op) = 0;
/* Push R0 onto the stack. (Also known as "dup" for duplicate.)
*/
virtual void pushR0() = 0;
/* Turn R0, TOS into R0 TOS R0 */
virtual void over() = 0;
/* Pop R0 from the stack. (Also known as "drop")
*/
virtual void popR0() = 0;
/* Store R0 to the address stored in TOS.
* The TOS is popped.
*/
virtual void storeR0ToTOS() = 0;
/* Load R0 from the address stored in R0.
*/
virtual void loadR0FromR0() = 0;
/* Load the absolute address of a variable to R0.
* If ea <= LOCAL, then this is a local variable, or an
* argument, addressed relative to FP.
* else it is an absolute global address.
*
* et is ET_RVALUE for things like string constants, ET_LVALUE for
* variables.
*/
virtual void leaR0(int ea, Type* pPointerType, ExpressionType et) = 0;
/* Load the pc-relative address of a forward-referenced variable to R0.
* Return the address of the 4-byte constant so that it can be filled
* in later.
*/
virtual int leaForward(int ea, Type* pPointerType) = 0;
/**
* Convert R0 to the given type.
*/
void convertR0(Type* pType) {
convertR0Imp(pType, false);
}
void castR0(Type* pType) {
convertR0Imp(pType, true);
}
virtual void convertR0Imp(Type* pType, bool isCast) = 0;
/* Emit code to adjust the stack for a function call. Return the
* label for the address of the instruction that adjusts the
* stack size. This will be passed as argument "a" to
* endFunctionCallArguments.
*/
virtual int beginFunctionCallArguments() = 0;
/* Emit code to store R0 to the stack at byte offset l.
* Returns stack size of object (typically 4 or 8 bytes)
*/
virtual size_t storeR0ToArg(int l, Type* pArgType) = 0;
/* Patch the function call preamble.
* a is the address returned from beginFunctionCallArguments
* l is the number of bytes the arguments took on the stack.
* Typically you would also emit code to convert the argument
* list into whatever the native function calling convention is.
* On ARM for example you would pop the first 5 arguments into
* R0..R4
*/
virtual void endFunctionCallArguments(Type* pDecl, int a, int l) = 0;
/* Emit a call to an unknown function. The argument "symbol" needs to
* be stored in the location where the address should go. It forms
* a chain. The address will be patched later.
* Return the address of the word that has to be patched.
*/
virtual int callForward(int symbol, Type* pFunc) = 0;
/* Call a function pointer. L is the number of bytes the arguments
* take on the stack. The address of the function is stored at
* location SP + l.
*/
virtual void callIndirect(int l, Type* pFunc) = 0;
/* Adjust SP after returning from a function call. l is the
* number of bytes of arguments stored on the stack. isIndirect
* is true if this was an indirect call. (In which case the
* address of the function is stored at location SP + l.)
*/
virtual void adjustStackAfterCall(Type* pDecl, int l, bool isIndirect) = 0;
/* Generate a symbol at the current PC. t is the head of a
* linked list of addresses to patch.
*/
virtual void gsym(int t) = 0;
/* Resolve a forward reference function at the current PC.
* t is the head of a
* linked list of addresses to patch.
* (Like gsym, but using absolute address, not PC relative address.)
*/
virtual void resolveForward(int t) = 0;
/*
* Do any cleanup work required at the end of a compile.
* For example, an instruction cache might need to be
* invalidated.
* Return non-zero if there is an error.
*/
virtual int finishCompile() = 0;
/**
* Adjust relative branches by this amount.
*/
virtual int jumpOffset() = 0;
/**
* Memory alignment (in bytes) for this type of data
*/
virtual size_t alignmentOf(Type* type) = 0;
/**
* Array element alignment (in bytes) for this type of data.
*/
virtual size_t sizeOf(Type* type) = 0;
virtual Type* getR0Type() {
return mExpressionStack.back().pType;
}
virtual ExpressionType getR0ExpressionType() {
return mExpressionStack.back().et;
}
virtual void setR0ExpressionType(ExpressionType et) {
mExpressionStack.back().et = et;
}
virtual size_t getExpressionStackDepth() {
return mExpressionStack.size();
}
virtual void forceR0RVal() {
if (getR0ExpressionType() == ET_LVALUE) {
loadR0FromR0();
}
}
protected:
/*
* Output a byte. Handles all values, 0..ff.
*/
void ob(int n) {
pCodeBuf->ob(n);
}
void o4(int data) {
pCodeBuf->o4(data);
}
intptr_t getBase() {
return (intptr_t) pCodeBuf->getBase();
}
intptr_t getPC() {
return pCodeBuf->getPC();
}
intptr_t getSize() {
return pCodeBuf->getSize();
}
void flush() {
pCodeBuf->flush();
}
void error(const char* fmt,...) {
va_list ap;
va_start(ap, fmt);
mErrorSink->verror(fmt, ap);
va_end(ap);
}
void assertImpl(bool test, int line) {
if (!test) {
error("code generator assertion failed at line %s:%d.", __FILE__, line);
LOGD("code generator assertion failed at line %s:%d.", __FILE__, line);
* (char*) 0 = 0;
}
}
void setR0Type(Type* pType) {
assert(pType != NULL);
mExpressionStack.back().pType = pType;
mExpressionStack.back().et = ET_RVALUE;
}
void setR0Type(Type* pType, ExpressionType et) {
assert(pType != NULL);
mExpressionStack.back().pType = pType;
mExpressionStack.back().et = et;
}
Type* getTOSType() {
return mExpressionStack[mExpressionStack.size()-2].pType;
}
void pushType() {
if (mExpressionStack.size()) {
mExpressionStack.push_back(mExpressionStack.back());
} else {
mExpressionStack.push_back(ExpressionValue());
}
}
void overType() {
size_t size = mExpressionStack.size();
if (size >= 2) {
mExpressionStack.push_back(mExpressionStack.back());
mExpressionStack[size-1] = mExpressionStack[size-2];
mExpressionStack[size-2] = mExpressionStack[size];
}
}
void popType() {
mExpressionStack.pop_back();
}
bool bitsSame(Type* pA, Type* pB) {
return collapseType(pA->tag) == collapseType(pB->tag);
}
TypeTag collapseType(TypeTag tag) {
static const TypeTag collapsedTag[] = {
TY_INT,
TY_INT,
TY_INT,
TY_VOID,
TY_FLOAT,
TY_DOUBLE,
TY_INT,
TY_INT,
TY_VOID,
TY_VOID,
TY_VOID
};
return collapsedTag[tag];
}
TypeTag collapseTypeR0() {
return collapseType(getR0Type()->tag);
}
static bool isFloatType(Type* pType) {
return isFloatTag(pType->tag);
}
static bool isFloatTag(TypeTag tag) {
return tag == TY_FLOAT || tag == TY_DOUBLE;
}
static bool isPointerType(Type* pType) {
return isPointerTag(pType->tag);
}
static bool isPointerTag(TypeTag tag) {
return tag == TY_POINTER || tag == TY_ARRAY;
}
Type* getPointerArithmeticResultType(Type* a, Type* b) {
TypeTag aTag = a->tag;
TypeTag bTag = b->tag;
if (aTag == TY_POINTER) {
return a;
}
if (bTag == TY_POINTER) {
return b;
}
if (aTag == TY_ARRAY) {
return a->pTail;
}
if (bTag == TY_ARRAY) {
return b->pTail;
}
return NULL;
}
Type* mkpInt;
private:
Vector<ExpressionValue> mExpressionStack;
ICodeBuf* pCodeBuf;
ErrorSink* mErrorSink;
};
#ifdef PROVIDE_ARM_CODEGEN
static size_t rotateRight(size_t n, size_t rotate) {
return (n >> rotate) | (n << (32 - rotate));
}
static size_t rotateLeft(size_t n, size_t rotate) {
return (n << rotate) | (n >> (32 - rotate));
}
static bool encode12BitImmediate(size_t immediate, size_t* pResult) {
for(size_t i = 0; i < 16; i++) {
size_t rotate = i * 2;
size_t mask = rotateRight(0xff, rotate);
if ((immediate | mask) == mask) {
size_t bits8 = rotateLeft(immediate, rotate);
// assert(bits8 <= 0xff);
*pResult = (i << 8) | bits8;
return true;
}
}
return false;
}
static size_t decode12BitImmediate(size_t immediate) {
size_t data = immediate & 0xff;
size_t rotate = 2 * ((immediate >> 8) & 0xf);
return rotateRight(data, rotate);
}
static bool isPowerOfTwo(size_t n) {
return (n != 0) & ((n & (n-1)) == 0);
}
static size_t log2(size_t n) {
int result = 0;
while (n >>= 1) {
result++;
}
return result;
}
class ARMCodeBuf : public ICodeBuf {
ICodeBuf* mpBase;
ErrorSink* mErrorSink;
class CircularQueue {
static const int SIZE = 16; // Must be power of 2
static const int MASK = SIZE-1;
unsigned int mBuf[SIZE];
int mHead;
int mCount;
public:
CircularQueue() {
mHead = 0;
mCount = 0;
}
void pushBack(unsigned int data) {
mBuf[(mHead + mCount) & MASK] = data;
mCount += 1;
}
unsigned int popFront() {
unsigned int result = mBuf[mHead];
mHead = (mHead + 1) & MASK;
mCount -= 1;
return result;
}
void popBack(int n) {
mCount -= n;
}
inline int count() {
return mCount;
}
bool empty() {
return mCount == 0;
}
bool full() {
return mCount == SIZE;
}
// The valid indexes are 1 - count() to 0
unsigned int operator[](int i) {
return mBuf[(mHead + mCount + i) & MASK];
}
};
CircularQueue mQ;
void error(const char* fmt,...) {
va_list ap;
va_start(ap, fmt);
mErrorSink->verror(fmt, ap);
va_end(ap);
}
void flush() {
while (!mQ.empty()) {
mpBase->o4(mQ.popFront());
}
mpBase->flush();
}
public:
ARMCodeBuf(ICodeBuf* pBase) {
mpBase = pBase;
}
virtual ~ARMCodeBuf() {
delete mpBase;
}
void init(int size) {
mpBase->init(size);
}
void setErrorSink(ErrorSink* pErrorSink) {
mErrorSink = pErrorSink;
mpBase->setErrorSink(pErrorSink);
}
void o4(int n) {
if (mQ.full()) {
mpBase->o4(mQ.popFront());
}
mQ.pushBack(n);
#ifndef DISABLE_ARM_PEEPHOLE
// Peephole check
bool didPeep;
do {
static const unsigned int opMask = 0x01e00000;
static const unsigned int immediateMask = 0x00000fff;
static const unsigned int BMask = 0x00400000;
didPeep = false;
if (mQ.count() >= 4) {
// Operand by a small constant
// push;mov #imm;pop;op ==> op #imm
if (mQ[-4] == 0xe92d0001 && // stmfd r13!, {r0}
(mQ[-3] & ~immediateMask) == 0xe3a00000 && // mov r0, #X
mQ[-2] == 0xe8bd0002 && // ldmea r13!, {r1}
(mQ[-1] & ~opMask) == (0xe0810000 & ~opMask)) { // OP r0, r1, r0
unsigned int movConst = mQ[-3];
unsigned int op = mQ[-1];
unsigned int combined = 0xe2000000 | (op & opMask) | (movConst & immediateMask);
// fprintf(stderr, "op %x movConst %x combined %x\n", op, movConst, combined);
if (! (combined == 0xe2800000 || combined == 0xe2400000)) { // add/sub #0
mQ.popBack(4);
mQ.pushBack(combined);
didPeep = true;
} else {
mQ.popBack(4);
didPeep = true;
}
}
}
// Load local variable
// sub r0,r11,#imm;ldr/ldrb r0,[r0] ==> ldr/ldrb r0, [r11,#-imm]
if (mQ.count() >= 2) {
if ((mQ[-2] & ~immediateMask) == 0xe24b0000) { // sub r0,r11,#imm
const unsigned int encodedImmediate = mQ[-2] & immediateMask;
const unsigned int ld = mQ[-1];
if ((ld & ~BMask) == 0xe5900000) { // ldr{b} r0, [r0]
unsigned int combined = encodedImmediate | (0xE51B0000 | (ld & BMask)); // ldr r0, [r11, #-0]
mQ.popBack(2);
mQ.pushBack(combined);
didPeep = true;
} else if (ld == 0xedd07a00) { // ldcl p10, c7, [r0, #0x000]
unsigned int decodedImmediate = decode12BitImmediate(encodedImmediate);
if (decodedImmediate <= 1020 && ((decodedImmediate & 3) == 0)) {
unsigned int combined = (decodedImmediate >> 2) | 0xed5b7a00; // ldcl p10, c7, [r11, #-0]
mQ.popBack(2);
mQ.pushBack(combined);
didPeep = true;
}
}
}
}
// Constant array lookup
if (mQ.count() >= 6 &&
mQ[-6] == 0xe92d0001 && // stmfd r13!, {r0}
(mQ[-5] & ~immediateMask)== 0xe3a00000 && // mov r0, #0x00000001
mQ[-4] == 0xe8bd0002 && // ldmea r13!, {r1}
(mQ[-3] & ~immediateMask)== 0xe3a02000 && // mov r2, #0x00000004
mQ[-2] == 0xe0000092 && // mul r0, r2, r0
mQ[-1] == 0xe0810000) { // add r0, r1, r0
unsigned int mov1 = mQ[-5];
unsigned int mov2 = mQ[-3];
unsigned int const1 = decode12BitImmediate(mov1);
unsigned int const2 = decode12BitImmediate(mov2);
unsigned int comboConst = const1 * const2;
size_t immediate = 0;
if (encode12BitImmediate(comboConst, &immediate)) {
mQ.popBack(6);
unsigned int add = immediate | 0xE2800000; // add r0, r0, #n
if (comboConst) {
mQ.pushBack(add);
}
didPeep = true;
}
}
// Pointer arithmetic with a stride that is a power of two
if (mQ.count() >= 3 &&
(mQ[-3] & ~ immediateMask) == 0xe3a02000 && // mov r2, #stride
mQ[-2] == 0xe0000092 && // mul r0, r2, r0
mQ[-1] == 0xe0810000) { // add r0, r1, r0
int stride = decode12BitImmediate(mQ[-3]);
if (isPowerOfTwo(stride)) {
mQ.popBack(3);
unsigned int add = 0xe0810000 | (log2(stride) << 7); // add r0, r1, r0, LSL #log2(stride)
mQ.pushBack(add);
didPeep = true;
}
}
} while (didPeep);
#endif
}
void ob(int n) {
error("ob() not supported.");
}
void* getBase() {
flush();
return mpBase->getBase();
}
intptr_t getSize() {
flush();
return mpBase->getSize();
}
intptr_t getPC() {
flush();
return mpBase->getPC();
}
};
class ARMCodeGenerator : public CodeGenerator {
public:
ARMCodeGenerator() {
#ifdef ARM_USE_VFP
// LOGD("Using ARM VFP hardware floating point.");
#else
// LOGD("Using ARM soft floating point.");
#endif
}
virtual ~ARMCodeGenerator() {}
/* returns address to patch with local variable size
*/
virtual int functionEntry(Type* pDecl) {
mStackUse = 0;
// sp -> arg4 arg5 ...
// Push our register-based arguments back on the stack
int regArgCount = calcRegArgCount(pDecl);
if (regArgCount > 0) {
mStackUse += regArgCount * 4;
o4(0xE92D0000 | ((1 << regArgCount) - 1)); // stmfd sp!, {}
}
// sp -> arg0 arg1 ...
o4(0xE92D4800); // stmfd sp!, {fp, lr}
mStackUse += 2 * 4;
// sp, fp -> oldfp, retadr, arg0 arg1 ....
o4(0xE1A0B00D); // mov fp, sp
LOG_STACK("functionEntry: %d\n", mStackUse);
int pc = getPC();
o4(0xE24DD000); // sub sp, sp, # <local variables>
// We don't know how many local variables we are going to use,
// but we will round the allocation up to a multiple of
// STACK_ALIGNMENT, so it won't affect the stack alignment.
return pc;
}
virtual void functionExit(Type* pDecl, int localVariableAddress, int localVariableSize) {
// Round local variable size up to a multiple of stack alignment
localVariableSize = ((localVariableSize + STACK_ALIGNMENT - 1) /
STACK_ALIGNMENT) * STACK_ALIGNMENT;
// Patch local variable allocation code:
if (localVariableSize < 0 || localVariableSize > 255) {
error("localVariables out of range: %d", localVariableSize);
}
*(char*) (localVariableAddress) = localVariableSize;
#ifdef ARM_USE_VFP
{
Type* pReturnType = pDecl->pHead;
switch(pReturnType->tag) {
case TY_FLOAT:
o4(0xEE170A90); // fmrs r0, s15
break;
case TY_DOUBLE:
o4(0xEC510B17); // fmrrd r0, r1, d7
break;
default:
break;
}
}
#endif
// sp -> locals .... fp -> oldfp, retadr, arg0, arg1, ...
o4(0xE1A0E00B); // mov lr, fp
o4(0xE59BB000); // ldr fp, [fp]
o4(0xE28ED004); // add sp, lr, #4
// sp -> retadr, arg0, ...
o4(0xE8BD4000); // ldmfd sp!, {lr}
// sp -> arg0 ....
// We store the PC into the lr so we can adjust the sp before
// returning. We need to pull off the registers we pushed
// earlier. We don't need to actually store them anywhere,
// just adjust the stack.
int regArgCount = calcRegArgCount(pDecl);
if (regArgCount) {
o4(0xE28DD000 | (regArgCount << 2)); // add sp, sp, #argCount << 2
}
o4(0xE12FFF1E); // bx lr
}
/* load immediate value */
virtual void li(int t) {
liReg(t, 0);
setR0Type(mkpInt);
}
virtual void loadFloat(int address, Type* pType) {
setR0Type(pType);
// Global, absolute address
o4(0xE59F0000); // ldr r0, .L1
o4(0xEA000000); // b .L99
o4(address); // .L1: .word ea
// .L99:
switch (pType->tag) {
case TY_FLOAT:
#ifdef ARM_USE_VFP
o4(0xEDD07A00); // flds s15, [r0]
#else
o4(0xE5900000); // ldr r0, [r0]
#endif
break;
case TY_DOUBLE:
#ifdef ARM_USE_VFP
o4(0xED907B00); // fldd d7, [r0]
#else
o4(0xE1C000D0); // ldrd r0, [r0]
#endif
break;
default:
assert(false);
break;
}
}
virtual void addStructOffsetR0(int offset, Type* pType) {
if (offset) {
size_t immediate = 0;
if (encode12BitImmediate(offset, &immediate)) {
o4(0xE2800000 | immediate); // add r0, r0, #offset
} else {
error("structure offset out of range: %d", offset);
}
}
setR0Type(pType, ET_LVALUE);
}
virtual int gjmp(int t) {
int pc = getPC();
o4(0xEA000000 | encodeAddress(t)); // b .L33
return pc;
}
/* l = 0: je, l == 1: jne */
virtual int gtst(bool l, int t) {
Type* pR0Type = getR0Type();
TypeTag tagR0 = pR0Type->tag;
switch(tagR0) {
case TY_FLOAT:
#ifdef ARM_USE_VFP
o4(0xEEF57A40); // fcmpzs s15
o4(0xEEF1FA10); // fmstat
#else
callRuntime((void*) runtime_is_non_zero_f);
o4(0xE3500000); // cmp r0,#0
#endif
break;
case TY_DOUBLE:
#ifdef ARM_USE_VFP
o4(0xEEB57B40); // fcmpzd d7
o4(0xEEF1FA10); // fmstat
#else
callRuntime((void*) runtime_is_non_zero_d);
o4(0xE3500000); // cmp r0,#0
#endif
break;
default:
o4(0xE3500000); // cmp r0,#0
break;
}
int branch = l ? 0x1A000000 : 0x0A000000; // bne : beq
int pc = getPC();
o4(branch | encodeAddress(t));
return pc;
}
virtual void gcmp(int op) {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = collapseType(pR0Type->tag);
TypeTag tagTOS = collapseType(pTOSType->tag);
if (tagR0 == TY_INT && tagTOS == TY_INT) {
setupIntPtrArgs();
o4(0xE1510000); // cmp r1, r1
switch(op) {
case OP_EQUALS:
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
break;
case OP_NOT_EQUALS:
o4(0x03A00000); // moveq r0,#0
o4(0x13A00001); // movne r0,#1
break;
case OP_LESS_EQUAL:
o4(0xD3A00001); // movle r0,#1
o4(0xC3A00000); // movgt r0,#0
break;
case OP_GREATER:
o4(0xD3A00000); // movle r0,#0
o4(0xC3A00001); // movgt r0,#1
break;
case OP_GREATER_EQUAL:
o4(0xA3A00001); // movge r0,#1
o4(0xB3A00000); // movlt r0,#0
break;
case OP_LESS:
o4(0xA3A00000); // movge r0,#0
o4(0xB3A00001); // movlt r0,#1
break;
default:
error("Unknown comparison op %d", op);
break;
}
} else if (tagR0 == TY_DOUBLE || tagTOS == TY_DOUBLE) {
setupDoubleArgs();
#ifdef ARM_USE_VFP
o4(0xEEB46BC7); // fcmped d6, d7
o4(0xEEF1FA10); // fmstat
switch(op) {
case OP_EQUALS:
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
break;
case OP_NOT_EQUALS:
o4(0x03A00000); // moveq r0,#0
o4(0x13A00001); // movne r0,#1
break;
case OP_LESS_EQUAL:
o4(0xD3A00001); // movle r0,#1
o4(0xC3A00000); // movgt r0,#0
break;
case OP_GREATER:
o4(0xD3A00000); // movle r0,#0
o4(0xC3A00001); // movgt r0,#1
break;
case OP_GREATER_EQUAL:
o4(0xA3A00001); // movge r0,#1
o4(0xB3A00000); // movlt r0,#0
break;
case OP_LESS:
o4(0xA3A00000); // movge r0,#0
o4(0xB3A00001); // movlt r0,#1
break;
default:
error("Unknown comparison op %d", op);
break;
}
#else
switch(op) {
case OP_EQUALS:
callRuntime((void*) runtime_cmp_eq_dd);
break;
case OP_NOT_EQUALS:
callRuntime((void*) runtime_cmp_ne_dd);
break;
case OP_LESS_EQUAL:
callRuntime((void*) runtime_cmp_le_dd);
break;
case OP_GREATER:
callRuntime((void*) runtime_cmp_gt_dd);
break;
case OP_GREATER_EQUAL:
callRuntime((void*) runtime_cmp_ge_dd);
break;
case OP_LESS:
callRuntime((void*) runtime_cmp_lt_dd);
break;
default:
error("Unknown comparison op %d", op);
break;
}
#endif
} else {
setupFloatArgs();
#ifdef ARM_USE_VFP
o4(0xEEB47AE7); // fcmpes s14, s15
o4(0xEEF1FA10); // fmstat
switch(op) {
case OP_EQUALS:
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
break;
case OP_NOT_EQUALS:
o4(0x03A00000); // moveq r0,#0
o4(0x13A00001); // movne r0,#1
break;
case OP_LESS_EQUAL:
o4(0xD3A00001); // movle r0,#1
o4(0xC3A00000); // movgt r0,#0
break;
case OP_GREATER:
o4(0xD3A00000); // movle r0,#0
o4(0xC3A00001); // movgt r0,#1
break;
case OP_GREATER_EQUAL:
o4(0xA3A00001); // movge r0,#1
o4(0xB3A00000); // movlt r0,#0
break;
case OP_LESS:
o4(0xA3A00000); // movge r0,#0
o4(0xB3A00001); // movlt r0,#1
break;
default:
error("Unknown comparison op %d", op);
break;
}
#else
switch(op) {
case OP_EQUALS:
callRuntime((void*) runtime_cmp_eq_ff);
break;
case OP_NOT_EQUALS:
callRuntime((void*) runtime_cmp_ne_ff);
break;
case OP_LESS_EQUAL:
callRuntime((void*) runtime_cmp_le_ff);
break;
case OP_GREATER:
callRuntime((void*) runtime_cmp_gt_ff);
break;
case OP_GREATER_EQUAL:
callRuntime((void*) runtime_cmp_ge_ff);
break;
case OP_LESS:
callRuntime((void*) runtime_cmp_lt_ff);
break;
default:
error("Unknown comparison op %d", op);
break;
}
#endif
}
setR0Type(mkpInt);
}
virtual void genOp(int op) {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = pR0Type->tag;
TypeTag tagTOS = pTOSType->tag;
bool isFloatR0 = isFloatTag(tagR0);
bool isFloatTOS = isFloatTag(tagTOS);
if (!isFloatR0 && !isFloatTOS) {
setupIntPtrArgs();
bool isPtrR0 = isPointerTag(tagR0);
bool isPtrTOS = isPointerTag(tagTOS);
if (isPtrR0 || isPtrTOS) {
if (isPtrR0 && isPtrTOS) {
if (op != OP_MINUS) {
error("Unsupported pointer-pointer operation %d.", op);
}
if (! typeEqual(pR0Type, pTOSType)) {
error("Incompatible pointer types for subtraction.");
}
o4(0xE0410000); // sub r0,r1,r0
setR0Type(mkpInt);
int size = sizeOf(pR0Type->pHead);
if (size != 1) {
pushR0();
li(size);
// TODO: Optimize for power-of-two.
genOp(OP_DIV);
}
} else {
if (! (op == OP_PLUS || (op == OP_MINUS && isPtrR0))) {
error("Unsupported pointer-scalar operation %d", op);
}
Type* pPtrType = getPointerArithmeticResultType(
pR0Type, pTOSType);
int size = sizeOf(pPtrType->pHead);
if (size != 1) {
// TODO: Optimize for power-of-two.
liReg(size, 2);
if (isPtrR0) {
o4(0x0E0010192); // mul r1,r2,r1
} else {
o4(0x0E0000092); // mul r0,r2,r0
}
}
switch(op) {
case OP_PLUS:
o4(0xE0810000); // add r0,r1,r0
break;
case OP_MINUS:
o4(0xE0410000); // sub r0,r1,r0
break;
}
setR0Type(pPtrType);
}
} else {
switch(op) {
case OP_MUL:
o4(0x0E0000091); // mul r0,r1,r0
break;
case OP_DIV:
callRuntime((void*) runtime_DIV);
break;
case OP_MOD:
callRuntime((void*) runtime_MOD);
break;
case OP_PLUS:
o4(0xE0810000); // add r0,r1,r0
break;
case OP_MINUS:
o4(0xE0410000); // sub r0,r1,r0
break;
case OP_SHIFT_LEFT:
o4(0xE1A00011); // lsl r0,r1,r0
break;
case OP_SHIFT_RIGHT:
o4(0xE1A00051); // asr r0,r1,r0
break;
case OP_BIT_AND:
o4(0xE0010000); // and r0,r1,r0
break;
case OP_BIT_XOR:
o4(0xE0210000); // eor r0,r1,r0
break;
case OP_BIT_OR:
o4(0xE1810000); // orr r0,r1,r0
break;
case OP_BIT_NOT:
o4(0xE1E00000); // mvn r0, r0
break;
default:
error("Unimplemented op %d\n", op);
break;
}
}
} else {
Type* pResultType = tagR0 > tagTOS ? pR0Type : pTOSType;
if (pResultType->tag == TY_DOUBLE) {
setupDoubleArgs();
switch(op) {
case OP_MUL:
#ifdef ARM_USE_VFP
o4(0xEE267B07); // fmuld d7, d6, d7
#else
callRuntime((void*) runtime_op_mul_dd);
#endif
break;
case OP_DIV:
#ifdef ARM_USE_VFP
o4(0xEE867B07); // fdivd d7, d6, d7
#else
callRuntime((void*) runtime_op_div_dd);
#endif
break;
case OP_PLUS:
#ifdef ARM_USE_VFP
o4(0xEE367B07); // faddd d7, d6, d7
#else
callRuntime((void*) runtime_op_add_dd);
#endif
break;
case OP_MINUS:
#ifdef ARM_USE_VFP
o4(0xEE367B47); // fsubd d7, d6, d7
#else
callRuntime((void*) runtime_op_sub_dd);
#endif
break;
default:
error("Unsupported binary floating operation %d\n", op);
break;
}
} else {
setupFloatArgs();
switch(op) {
case OP_MUL:
#ifdef ARM_USE_VFP
o4(0xEE677A27); // fmuls s15, s14, s15
#else
callRuntime((void*) runtime_op_mul_ff);
#endif
break;
case OP_DIV:
#ifdef ARM_USE_VFP
o4(0xEEC77A27); // fdivs s15, s14, s15
#else
callRuntime((void*) runtime_op_div_ff);
#endif
break;
case OP_PLUS:
#ifdef ARM_USE_VFP
o4(0xEE777A27); // fadds s15, s14, s15
#else
callRuntime((void*) runtime_op_add_ff);
#endif
break;
case OP_MINUS:
#ifdef ARM_USE_VFP
o4(0xEE777A67); // fsubs s15, s14, s15
#else
callRuntime((void*) runtime_op_sub_ff);
#endif
break;
default:
error("Unsupported binary floating operation %d\n", op);
break;
}
}
setR0Type(pResultType);
}
}
virtual void gUnaryCmp(int op) {
if (op != OP_LOGICAL_NOT) {
error("Unknown unary cmp %d", op);
} else {
Type* pR0Type = getR0Type();
TypeTag tag = collapseType(pR0Type->tag);
switch(tag) {
case TY_INT:
o4(0xE3A01000); // mov r1, #0
o4(0xE1510000); // cmp r1, r0
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
break;
case TY_FLOAT:
#ifdef ARM_USE_VFP
o4(0xEEF57A40); // fcmpzs s15
o4(0xEEF1FA10); // fmstat
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
#else
callRuntime((void*) runtime_is_zero_f);
#endif
break;
case TY_DOUBLE:
#ifdef ARM_USE_VFP
o4(0xEEB57B40); // fcmpzd d7
o4(0xEEF1FA10); // fmstat
o4(0x03A00001); // moveq r0,#1
o4(0x13A00000); // movne r0,#0
#else
callRuntime((void*) runtime_is_zero_d);
#endif
break;
default:
error("gUnaryCmp unsupported type");
break;
}
}
setR0Type(mkpInt);
}
virtual void genUnaryOp(int op) {
Type* pR0Type = getR0Type();
TypeTag tag = collapseType(pR0Type->tag);
switch(tag) {
case TY_INT:
switch(op) {
case OP_MINUS:
o4(0xE3A01000); // mov r1, #0
o4(0xE0410000); // sub r0,r1,r0
break;
case OP_BIT_NOT:
o4(0xE1E00000); // mvn r0, r0
break;
default:
error("Unknown unary op %d\n", op);
break;
}
break;
case TY_FLOAT:
case TY_DOUBLE:
switch (op) {
case OP_MINUS:
if (tag == TY_FLOAT) {
#ifdef ARM_USE_VFP
o4(0xEEF17A67); // fnegs s15, s15
#else
callRuntime((void*) runtime_op_neg_f);
#endif
} else {
#ifdef ARM_USE_VFP
o4(0xEEB17B47); // fnegd d7, d7
#else
callRuntime((void*) runtime_op_neg_d);
#endif
}
break;
case OP_BIT_NOT:
error("Can't apply '~' operator to a float or double.");
break;
default:
error("Unknown unary op %d\n", op);
break;
}
break;
default:
error("genUnaryOp unsupported type");
break;
}
}
virtual void pushR0() {
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
#ifdef ARM_USE_VFP
switch (r0ct ) {
case TY_FLOAT:
o4(0xED6D7A01); // fstmfds sp!,{s15}
mStackUse += 4;
break;
case TY_DOUBLE:
o4(0xED2D7B02); // fstmfdd sp!,{d7}
mStackUse += 8;
break;
default:
o4(0xE92D0001); // stmfd sp!,{r0}
mStackUse += 4;
}
#else
if (r0ct != TY_DOUBLE) {
o4(0xE92D0001); // stmfd sp!,{r0}
mStackUse += 4;
} else {
o4(0xE92D0003); // stmfd sp!,{r0,r1}
mStackUse += 8;
}
#endif
pushType();
LOG_STACK("pushR0: %d\n", mStackUse);
}
virtual void over() {
// We know it's only used for int-ptr ops (++/--)
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
Type* pTOSType = getTOSType();
TypeTag tosct = collapseType(pTOSType->tag);
assert (r0ct == TY_INT && tosct == TY_INT);
o4(0xE8BD0002); // ldmfd sp!,{r1}
o4(0xE92D0001); // stmfd sp!,{r0}
o4(0xE92D0002); // stmfd sp!,{r1}
overType();
mStackUse += 4;
}
virtual void popR0() {
Type* pTOSType = getTOSType();
TypeTag tosct = collapseType(pTOSType->tag);
#ifdef ARM_USE_VFP
if (tosct == TY_FLOAT || tosct == TY_DOUBLE) {
error("Unsupported popR0 float/double");
}
#endif
switch (tosct){
case TY_INT:
case TY_FLOAT:
o4(0xE8BD0001); // ldmfd sp!,{r0}
mStackUse -= 4;
break;
case TY_DOUBLE:
o4(0xE8BD0003); // ldmfd sp!,{r0, r1} // Restore R0
mStackUse -= 8;
break;
default:
error("Can't pop this type.");
break;
}
popType();
LOG_STACK("popR0: %d\n", mStackUse);
}
virtual void storeR0ToTOS() {
Type* pPointerType = getTOSType();
assert(pPointerType->tag == TY_POINTER);
Type* pDestType = pPointerType->pHead;
convertR0(pDestType);
o4(0xE8BD0004); // ldmfd sp!,{r2}
popType();
mStackUse -= 4;
switch (pDestType->tag) {
case TY_POINTER:
case TY_INT:
o4(0xE5820000); // str r0, [r2]
break;
case TY_FLOAT:
#ifdef ARM_USE_VFP
o4(0xEDC27A00); // fsts s15, [r2, #0]
#else
o4(0xE5820000); // str r0, [r2]
#endif
break;
case TY_SHORT:
o4(0xE1C200B0); // strh r0, [r2]
break;
case TY_CHAR:
o4(0xE5C20000); // strb r0, [r2]
break;
case TY_DOUBLE:
#ifdef ARM_USE_VFP
o4(0xED827B00); // fstd d7, [r2, #0]
#else
o4(0xE1C200F0); // strd r0, [r2]
#endif
break;
case TY_STRUCT:
{
int size = sizeOf(pDestType);
if (size > 0) {
liReg(size, 1);
callRuntime((void*) runtime_structCopy);
}
}
break;
default:
error("storeR0ToTOS: unimplemented type %d",
pDestType->tag);
break;
}
setR0Type(pDestType);
}
virtual void loadR0FromR0() {
Type* pPointerType = getR0Type();
assert(pPointerType->tag == TY_POINTER);
Type* pNewType = pPointerType->pHead;
TypeTag tag = pNewType->tag;
switch (tag) {
case TY_POINTER:
case TY_INT:
o4(0xE5900000); // ldr r0, [r0]
break;
case TY_FLOAT:
#ifdef ARM_USE_VFP
o4(0xEDD07A00); // flds s15, [r0, #0]
#else
o4(0xE5900000); // ldr r0, [r0]
#endif
break;
case TY_SHORT:
o4(0xE1D000F0); // ldrsh r0, [r0]
break;
case TY_CHAR:
o4(0xE5D00000); // ldrb r0, [r0]
break;
case TY_DOUBLE:
#ifdef ARM_USE_VFP
o4(0xED907B00); // fldd d7, [r0, #0]
#else
o4(0xE1C000D0); // ldrd r0, [r0]
#endif
break;
case TY_ARRAY:
pNewType = pNewType->pTail;
break;
case TY_STRUCT:
break;
default:
error("loadR0FromR0: unimplemented type %d", tag);
break;
}
setR0Type(pNewType);
}
virtual void leaR0(int ea, Type* pPointerType, ExpressionType et) {
if (ea > -LOCAL && ea < LOCAL) {
// Local, fp relative
size_t immediate = 0;
bool inRange = false;
if (ea < 0) {
inRange = encode12BitImmediate(-ea, &immediate);
o4(0xE24B0000 | immediate); // sub r0, fp, #ea
} else {
inRange = encode12BitImmediate(ea, &immediate);
o4(0xE28B0000 | immediate); // add r0, fp, #ea
}
if (! inRange) {
error("Offset out of range: %08x", ea);
}
} else {
// Global, absolute.
o4(0xE59F0000); // ldr r0, .L1
o4(0xEA000000); // b .L99
o4(ea); // .L1: .word 0
// .L99:
}
setR0Type(pPointerType, et);
}
virtual int leaForward(int ea, Type* pPointerType) {
setR0Type(pPointerType);
int result = ea;
int pc = getPC();
int offset = 0;
if (ea) {
offset = (pc - ea - 8) >> 2;
if ((offset & 0xffff) != offset) {
error("function forward reference out of bounds");
}
} else {
offset = 0;
}
o4(0xE59F0000 | offset); // ldr r0, .L1
if (ea == 0) {
o4(0xEA000000); // b .L99
result = getPC();
o4(ea); // .L1: .word 0
// .L99:
}
return result;
}
virtual void convertR0Imp(Type* pType, bool isCast){
Type* pR0Type = getR0Type();
if (isPointerType(pType) && isPointerType(pR0Type)) {
Type* pA = pR0Type;
Type* pB = pType;
// Array decays to pointer
if (pA->tag == TY_ARRAY && pB->tag == TY_POINTER) {
pA = pA->pTail;
}
if (! (typeEqual(pA, pB)
|| pB->pHead->tag == TY_VOID
|| (pA->tag == TY_POINTER && pB->tag == TY_POINTER && isCast)
)) {
error("Incompatible pointer or array types");
}
} else if (bitsSame(pType, pR0Type)) {
// do nothing special
} else {
TypeTag r0Tag = collapseType(pR0Type->tag);
TypeTag destTag = collapseType(pType->tag);
if (r0Tag == TY_INT) {
if (destTag == TY_FLOAT) {
#ifdef ARM_USE_VFP
o4(0xEE070A90); // fmsr s15, r0
o4(0xEEF87AE7); // fsitos s15, s15
#else
callRuntime((void*) runtime_int_to_float);
#endif
} else {
assert(destTag == TY_DOUBLE);
#ifdef ARM_USE_VFP
o4(0xEE070A90); // fmsr s15, r0
o4(0xEEB87BE7); // fsitod d7, s15
#else
callRuntime((void*) runtime_int_to_double);
#endif
}
} else if (r0Tag == TY_FLOAT) {
if (destTag == TY_INT) {
#ifdef ARM_USE_VFP
o4(0xEEFD7AE7); // ftosizs s15, s15
o4(0xEE170A90); // fmrs r0, s15
#else
callRuntime((void*) runtime_float_to_int);
#endif
} else {
assert(destTag == TY_DOUBLE);
#ifdef ARM_USE_VFP
o4(0xEEB77AE7); // fcvtds d7, s15
#else
callRuntime((void*) runtime_float_to_double);
#endif
}
} else {
if (r0Tag == TY_DOUBLE) {
if (destTag == TY_INT) {
#ifdef ARM_USE_VFP
o4(0xEEFD7BC7); // ftosizd s15, d7
o4(0xEE170A90); // fmrs r0, s15
#else
callRuntime((void*) runtime_double_to_int);
#endif
} else {
if(destTag == TY_FLOAT) {
#ifdef ARM_USE_VFP
o4(0xEEF77BC7); // fcvtsd s15, d7
#else
callRuntime((void*) runtime_double_to_float);
#endif
} else {
incompatibleTypes(pR0Type, pType);
}
}
} else {
incompatibleTypes(pR0Type, pType);
}
}
}
setR0Type(pType);
}
virtual int beginFunctionCallArguments() {
int pc = getPC();
o4(0xE24DDF00); // Placeholder sub sp, sp, #0
return pc;
}
virtual size_t storeR0ToArg(int l, Type* pArgType) {
convertR0(pArgType);
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
#ifdef ARM_USE_VFP
switch(r0ct) {
case TY_INT:
if (l < 0 || l > 4096-4) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xE58D0000 | l); // str r0, [sp, #l]
return 4;
case TY_FLOAT:
if (l < 0 || l > 1020 || (l & 3)) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xEDCD7A00 | (l >> 2)); // fsts s15, [sp, #l]
return 4;
case TY_DOUBLE: {
// Align to 8 byte boundary
int l2 = (l + 7) & ~7;
if (l2 < 0 || l2 > 1020 || (l2 & 3)) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xED8D7B00 | (l2 >> 2)); // fstd d7, [sp, #l2]
return (l2 - l) + 8;
}
default:
assert(false);
return 0;
}
#else
switch(r0ct) {
case TY_INT:
case TY_FLOAT:
if (l < 0 || l > 4096-4) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xE58D0000 + l); // str r0, [sp, #l]
return 4;
case TY_DOUBLE: {
// Align to 8 byte boundary
int l2 = (l + 7) & ~7;
if (l2 < 0 || l2 > 4096-8) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xE58D0000 + l2); // str r0, [sp, #l]
o4(0xE58D1000 + l2 + 4); // str r1, [sp, #l+4]
return (l2 - l) + 8;
}
default:
assert(false);
return 0;
}
#endif
}
virtual void endFunctionCallArguments(Type* pDecl, int a, int l) {
int argumentStackUse = l;
// Have to calculate register arg count from actual stack size,
// in order to properly handle ... functions.
int regArgCount = l >> 2;
if (regArgCount > 4) {
regArgCount = 4;
}
if (regArgCount > 0) {
argumentStackUse -= regArgCount * 4;
o4(0xE8BD0000 | ((1 << regArgCount) - 1)); // ldmfd sp!,{}
}
mStackUse += argumentStackUse;
// Align stack.
int missalignment = mStackUse - ((mStackUse / STACK_ALIGNMENT)
* STACK_ALIGNMENT);
mStackAlignmentAdjustment = 0;
if (missalignment > 0) {
mStackAlignmentAdjustment = STACK_ALIGNMENT - missalignment;
}
l += mStackAlignmentAdjustment;
if (l < 0 || l > 0x3FC) {
error("L out of range for stack adjustment: 0x%08x", l);
}
flush();
* (int*) a = 0xE24DDF00 | (l >> 2); // sub sp, sp, #0 << 2
mStackUse += mStackAlignmentAdjustment;
LOG_STACK("endFunctionCallArguments mStackUse: %d, mStackAlignmentAdjustment %d\n",
mStackUse, mStackAlignmentAdjustment);
}
virtual int callForward(int symbol, Type* pFunc) {
setR0Type(pFunc->pHead);
// Forward calls are always short (local)
int pc = getPC();
o4(0xEB000000 | encodeAddress(symbol));
return pc;
}
virtual void callIndirect(int l, Type* pFunc) {
assert(pFunc->tag == TY_FUNC);
popType(); // Get rid of indirect fn pointer type
int argCount = l >> 2;
int poppedArgs = argCount > 4 ? 4 : argCount;
int adjustedL = l - (poppedArgs << 2) + mStackAlignmentAdjustment;
if (adjustedL < 0 || adjustedL > 4096-4) {
error("l out of range for stack offset: 0x%08x", l);
}
o4(0xE59DC000 | (0xfff & adjustedL)); // ldr r12, [sp,#adjustedL]
o4(0xE12FFF3C); // blx r12
Type* pReturnType = pFunc->pHead;
setR0Type(pReturnType);
#ifdef ARM_USE_VFP
switch(pReturnType->tag) {
case TY_FLOAT:
o4(0xEE070A90); // fmsr s15, r0
break;
case TY_DOUBLE:
o4(0xEC410B17); // fmdrr d7, r0, r1
break;
default:
break;
}
#endif
}
virtual void adjustStackAfterCall(Type* pDecl, int l, bool isIndirect) {
int argCount = l >> 2;
// Have to calculate register arg count from actual stack size,
// in order to properly handle ... functions.
int regArgCount = l >> 2;
if (regArgCount > 4) {
regArgCount = 4;
}
int stackArgs = argCount - regArgCount;
int stackUse = stackArgs + (isIndirect ? 1 : 0)
+ (mStackAlignmentAdjustment >> 2);
if (stackUse) {
if (stackUse < 0 || stackUse > 255) {
error("L out of range for stack adjustment: 0x%08x", l);
}
o4(0xE28DDF00 | stackUse); // add sp, sp, #stackUse << 2
mStackUse -= stackUse * 4;
LOG_STACK("adjustStackAfterCall: %d\n", mStackUse);
}
}
virtual int jumpOffset() {
return 8;
}
/* output a symbol and patch all calls to it */
virtual void gsym(int t) {
int n;
int base = getBase();
int pc = getPC();
while (t) {
int data = * (int*) t;
int decodedOffset = ((BRANCH_REL_ADDRESS_MASK & data) << 2);
if (decodedOffset == 0) {
n = 0;
} else {
n = base + decodedOffset; /* next value */
}
*(int *) t = (data & ~BRANCH_REL_ADDRESS_MASK)
| encodeRelAddress(pc - t - 8);
t = n;
}
}
/* output a symbol and patch all calls to it */
virtual void resolveForward(int t) {
if (t) {
int pc = getPC();
*(int *) t = pc;
}
}
virtual int finishCompile() {
#if defined(__arm__)
const long base = long(getBase());
const long curr = long(getPC());
int err = cacheflush(base, curr, 0);
return err;
#else
return 0;
#endif
}
/**
* alignment (in bytes) for this type of data
*/
virtual size_t alignmentOf(Type* pType){
switch(pType->tag) {
case TY_CHAR:
return 1;
case TY_SHORT:
return 2;
case TY_DOUBLE:
return 8;
case TY_ARRAY:
return alignmentOf(pType->pHead);
case TY_STRUCT:
return pType->pHead->alignment & 0x7fffffff;
case TY_FUNC:
error("alignment of func not supported");
return 1;
default:
return 4;
}
}
/**
* Array element alignment (in bytes) for this type of data.
*/
virtual size_t sizeOf(Type* pType){
switch(pType->tag) {
case TY_INT:
return 4;
case TY_SHORT:
return 2;
case TY_CHAR:
return 1;
case TY_FLOAT:
return 4;
case TY_DOUBLE:
return 8;
case TY_POINTER:
return 4;
case TY_ARRAY:
return pType->length * sizeOf(pType->pHead);
case TY_STRUCT:
return pType->pHead->length;
default:
error("Unsupported type %d", pType->tag);
return 0;
}
}
private:
static const int BRANCH_REL_ADDRESS_MASK = 0x00ffffff;
/** Encode a relative address that might also be
* a label.
*/
int encodeAddress(int value) {
int base = getBase();
if (value >= base && value <= getPC() ) {
// This is a label, encode it relative to the base.
value = value - base;
}
return encodeRelAddress(value);
}
int encodeRelAddress(int value) {
return BRANCH_REL_ADDRESS_MASK & (value >> 2);
}
int calcRegArgCount(Type* pDecl) {
int reg = 0;
Type* pArgs = pDecl->pTail;
while (pArgs && reg < 4) {
Type* pArg = pArgs->pHead;
if ( pArg->tag == TY_DOUBLE) {
int evenReg = (reg + 1) & ~1;
if (evenReg >= 4) {
break;
}
reg = evenReg + 2;
} else {
reg++;
}
pArgs = pArgs->pTail;
}
return reg;
}
void setupIntPtrArgs() {
o4(0xE8BD0002); // ldmfd sp!,{r1}
mStackUse -= 4;
popType();
}
/* Pop TOS to R1 (use s14 if VFP)
* Make sure both R0 and TOS are floats. (Could be ints)
* We know that at least one of R0 and TOS is already a float
*/
void setupFloatArgs() {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = collapseType(pR0Type->tag);
TypeTag tagTOS = collapseType(pTOSType->tag);
if (tagR0 != TY_FLOAT) {
assert(tagR0 == TY_INT);
#ifdef ARM_USE_VFP
o4(0xEE070A90); // fmsr s15, r0
o4(0xEEF87AE7); // fsitos s15, s15
#else
callRuntime((void*) runtime_int_to_float);
#endif
}
if (tagTOS != TY_FLOAT) {
assert(tagTOS == TY_INT);
assert(tagR0 == TY_FLOAT);
#ifdef ARM_USE_VFP
o4(0xECBD7A01); // fldmfds sp!, {s14}
o4(0xEEB87AC7); // fsitos s14, s14
#else
o4(0xE92D0001); // stmfd sp!,{r0} // push R0
o4(0xE59D0004); // ldr r0, [sp, #4]
callRuntime((void*) runtime_int_to_float);
o4(0xE1A01000); // mov r1, r0
o4(0xE8BD0001); // ldmfd sp!,{r0} // pop R0
o4(0xE28DD004); // add sp, sp, #4 // Pop sp
#endif
} else {
// Pop TOS
#ifdef ARM_USE_VFP
o4(0xECBD7A01); // fldmfds sp!, {s14}
#else
o4(0xE8BD0002); // ldmfd sp!,{r1}
#endif
}
mStackUse -= 4;
popType();
}
/* Pop TOS into R2..R3 (use D6 if VFP)
* Make sure both R0 and TOS are doubles. Could be floats or ints.
* We know that at least one of R0 and TOS are already a double.
*/
void setupDoubleArgs() {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = collapseType(pR0Type->tag);
TypeTag tagTOS = collapseType(pTOSType->tag);
if (tagR0 != TY_DOUBLE) {
if (tagR0 == TY_INT) {
#ifdef ARM_USE_VFP
o4(0xEE070A90); // fmsr s15, r0
o4(0xEEB87BE7); // fsitod d7, s15
#else
callRuntime((void*) runtime_int_to_double);
#endif
} else {
assert(tagR0 == TY_FLOAT);
#ifdef ARM_USE_VFP
o4(0xEEB77AE7); // fcvtds d7, s15
#else
callRuntime((void*) runtime_float_to_double);
#endif
}
}
if (tagTOS != TY_DOUBLE) {
#ifdef ARM_USE_VFP
if (tagTOS == TY_INT) {
o4(0xECFD6A01); // fldmfds sp!,{s13}
o4(0xEEB86BE6); // fsitod d6, s13
} else {
assert(tagTOS == TY_FLOAT);
o4(0xECFD6A01); // fldmfds sp!,{s13}
o4(0xEEB76AE6); // fcvtds d6, s13
}
#else
o4(0xE92D0003); // stmfd sp!,{r0,r1} // push r0,r1
o4(0xE59D0008); // ldr r0, [sp, #8]
if (tagTOS == TY_INT) {
callRuntime((void*) runtime_int_to_double);
} else {
assert(tagTOS == TY_FLOAT);
callRuntime((void*) runtime_float_to_double);
}
o4(0xE1A02000); // mov r2, r0
o4(0xE1A03001); // mov r3, r1
o4(0xE8BD0003); // ldmfd sp!,{r0, r1} // Restore R0
o4(0xE28DD004); // add sp, sp, #4 // Pop sp
#endif
mStackUse -= 4;
} else {
#ifdef ARM_USE_VFP
o4(0xECBD6B02); // fldmfdd sp!, {d6}
#else
o4(0xE8BD000C); // ldmfd sp!,{r2,r3}
#endif
mStackUse -= 8;
}
popType();
}
void liReg(int t, int reg) {
assert(reg >= 0 && reg < 16);
int rN = (reg & 0xf) << 12;
size_t encodedImmediate;
if (encode12BitImmediate(t, &encodedImmediate)) {
o4(0xE3A00000 | encodedImmediate | rN); // mov rN, #0
} else if (encode12BitImmediate(-(t+1), &encodedImmediate)) {
// mvn means move constant ^ ~0
o4(0xE3E00000 | encodedImmediate | rN); // mvn rN, #0
} else {
o4(0xE51F0000 | rN); // ldr rN, .L3
o4(0xEA000000); // b .L99
o4(t); // .L3: .word 0
// .L99:
}
}
void incompatibleTypes(Type* pR0Type, Type* pType) {
error("Incompatible types old: %d new: %d", pR0Type->tag, pType->tag);
}
void callRuntime(void* fn) {
o4(0xE59FC000); // ldr r12, .L1
o4(0xEA000000); // b .L99
o4((int) fn); //.L1: .word fn
o4(0xE12FFF3C); //.L99: blx r12
}
// Integer math:
static int runtime_DIV(int b, int a) {
return a / b;
}
static int runtime_MOD(int b, int a) {
return a % b;
}
static void runtime_structCopy(void* src, size_t size, void* dest) {
memcpy(dest, src, size);
}
#ifndef ARM_USE_VFP
// Comparison to zero
static int runtime_is_non_zero_f(float a) {
return a != 0;
}
static int runtime_is_non_zero_d(double a) {
return a != 0;
}
// Comparison to zero
static int runtime_is_zero_f(float a) {
return a == 0;
}
static int runtime_is_zero_d(double a) {
return a == 0;
}
// Type conversion
static int runtime_float_to_int(float a) {
return (int) a;
}
static double runtime_float_to_double(float a) {
return (double) a;
}
static int runtime_double_to_int(double a) {
return (int) a;
}
static float runtime_double_to_float(double a) {
return (float) a;
}
static float runtime_int_to_float(int a) {
return (float) a;
}
static double runtime_int_to_double(int a) {
return (double) a;
}
// Comparisons float
static int runtime_cmp_eq_ff(float b, float a) {
return a == b;
}
static int runtime_cmp_ne_ff(float b, float a) {
return a != b;
}
static int runtime_cmp_lt_ff(float b, float a) {
return a < b;
}
static int runtime_cmp_le_ff(float b, float a) {
return a <= b;
}
static int runtime_cmp_ge_ff(float b, float a) {
return a >= b;
}
static int runtime_cmp_gt_ff(float b, float a) {
return a > b;
}
// Comparisons double
static int runtime_cmp_eq_dd(double b, double a) {
return a == b;
}
static int runtime_cmp_ne_dd(double b, double a) {
return a != b;
}
static int runtime_cmp_lt_dd(double b, double a) {
return a < b;
}
static int runtime_cmp_le_dd(double b, double a) {
return a <= b;
}
static int runtime_cmp_ge_dd(double b, double a) {
return a >= b;
}
static int runtime_cmp_gt_dd(double b, double a) {
return a > b;
}
// Math float
static float runtime_op_add_ff(float b, float a) {
return a + b;
}
static float runtime_op_sub_ff(float b, float a) {
return a - b;
}
static float runtime_op_mul_ff(float b, float a) {
return a * b;
}
static float runtime_op_div_ff(float b, float a) {
return a / b;
}
static float runtime_op_neg_f(float a) {
return -a;
}
// Math double
static double runtime_op_add_dd(double b, double a) {
return a + b;
}
static double runtime_op_sub_dd(double b, double a) {
return a - b;
}
static double runtime_op_mul_dd(double b, double a) {
return a * b;
}
static double runtime_op_div_dd(double b, double a) {
return a / b;
}
static double runtime_op_neg_d(double a) {
return -a;
}
#endif
static const int STACK_ALIGNMENT = 8;
int mStackUse;
// This variable holds the amount we adjusted the stack in the most
// recent endFunctionCallArguments call. It's examined by the
// following adjustStackAfterCall call.
int mStackAlignmentAdjustment;
};
#endif // PROVIDE_ARM_CODEGEN
#ifdef PROVIDE_X86_CODEGEN
class X86CodeGenerator : public CodeGenerator {
public:
X86CodeGenerator() {}
virtual ~X86CodeGenerator() {}
/* returns address to patch with local variable size
*/
virtual int functionEntry(Type* pDecl) {
o(0xe58955); /* push %ebp, mov %esp, %ebp */
return oad(0xec81, 0); /* sub $xxx, %esp */
}
virtual void functionExit(Type* pDecl, int localVariableAddress, int localVariableSize) {
o(0xc3c9); /* leave, ret */
*(int *) localVariableAddress = localVariableSize; /* save local variables */
}
/* load immediate value */
virtual void li(int i) {
oad(0xb8, i); /* mov $xx, %eax */
setR0Type(mkpInt);
}
virtual void loadFloat(int address, Type* pType) {
setR0Type(pType);
switch (pType->tag) {
case TY_FLOAT:
oad(0x05D9, address); // flds
break;
case TY_DOUBLE:
oad(0x05DD, address); // fldl
break;
default:
assert(false);
break;
}
}
virtual void addStructOffsetR0(int offset, Type* pType) {
if (offset) {
oad(0x05, offset); // addl offset, %eax
}
setR0Type(pType, ET_LVALUE);
}
virtual int gjmp(int t) {
return psym(0xe9, t);
}
/* l = 0: je, l == 1: jne */
virtual int gtst(bool l, int t) {
Type* pR0Type = getR0Type();
TypeTag tagR0 = pR0Type->tag;
bool isFloatR0 = isFloatTag(tagR0);
if (isFloatR0) {
o(0xeed9); // fldz
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
} else {
o(0xc085); // test %eax, %eax
}
// Use two output statements to generate one instruction.
o(0x0f); // je/jne xxx
return psym(0x84 + l, t);
}
virtual void gcmp(int op) {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = pR0Type->tag;
TypeTag tagTOS = pTOSType->tag;
bool isFloatR0 = isFloatTag(tagR0);
bool isFloatTOS = isFloatTag(tagTOS);
if (!isFloatR0 && !isFloatTOS) {
int t = decodeOp(op);
o(0x59); /* pop %ecx */
o(0xc139); /* cmp %eax,%ecx */
li(0);
o(0x0f); /* setxx %al */
o(t + 0x90);
o(0xc0);
popType();
} else {
setupFloatOperands();
switch (op) {
case OP_EQUALS:
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
o(0xc0940f); // sete %al
o(0xc29b0f); // setnp %dl
o(0xd021); // andl %edx, %eax
break;
case OP_NOT_EQUALS:
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
o(0xc0950f); // setne %al
o(0xc29a0f); // setp %dl
o(0xd009); // orl %edx, %eax
break;
case OP_GREATER_EQUAL:
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x05c4f6); // testb $5, %ah
o(0xc0940f); // sete %al
break;
case OP_LESS:
o(0xc9d9); // fxch %st(1)
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
o(0xc0970f); // seta %al
break;
case OP_LESS_EQUAL:
o(0xc9d9); // fxch %st(1)
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
o(0xc0930f); // setea %al
break;
case OP_GREATER:
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x45c4f6); // testb $69, %ah
o(0xc0940f); // sete %al
break;
default:
error("Unknown comparison op");
}
o(0xc0b60f); // movzbl %al, %eax
}
setR0Type(mkpInt);
}
virtual void genOp(int op) {
Type* pR0Type = getR0Type();
Type* pTOSType = getTOSType();
TypeTag tagR0 = pR0Type->tag;
TypeTag tagTOS = pTOSType->tag;
bool isFloatR0 = isFloatTag(tagR0);
bool isFloatTOS = isFloatTag(tagTOS);
if (!isFloatR0 && !isFloatTOS) {
bool isPtrR0 = isPointerTag(tagR0);
bool isPtrTOS = isPointerTag(tagTOS);
if (isPtrR0 || isPtrTOS) {
if (isPtrR0 && isPtrTOS) {
if (op != OP_MINUS) {
error("Unsupported pointer-pointer operation %d.", op);
}
if (! typeEqual(pR0Type, pTOSType)) {
error("Incompatible pointer types for subtraction.");
}
o(0x59); /* pop %ecx */
o(decodeOp(op));
popType();
setR0Type(mkpInt);
int size = sizeOf(pR0Type->pHead);
if (size != 1) {
pushR0();
li(size);
// TODO: Optimize for power-of-two.
genOp(OP_DIV);
}
} else {
if (! (op == OP_PLUS || (op == OP_MINUS && isPtrR0))) {
error("Unsupported pointer-scalar operation %d", op);
}
Type* pPtrType = getPointerArithmeticResultType(
pR0Type, pTOSType);
o(0x59); /* pop %ecx */
int size = sizeOf(pPtrType->pHead);
if (size != 1) {
// TODO: Optimize for power-of-two.
if (isPtrR0) {
oad(0xC969, size); // imull $size, %ecx
} else {
oad(0xC069, size); // mul $size, %eax
}
}
o(decodeOp(op));
popType();
setR0Type(pPtrType);
}
} else {
o(0x59); /* pop %ecx */
o(decodeOp(op));
if (op == OP_MOD)
o(0x92); /* xchg %edx, %eax */
popType();
}
} else {
Type* pResultType = tagR0 > tagTOS ? pR0Type : pTOSType;
setupFloatOperands();
// Both float. x87 R0 == left hand, x87 R1 == right hand
switch (op) {
case OP_MUL:
o(0xc9de); // fmulp
break;
case OP_DIV:
o(0xf1de); // fdivp
break;
case OP_PLUS:
o(0xc1de); // faddp
break;
case OP_MINUS:
o(0xe1de); // fsubp
break;
default:
error("Unsupported binary floating operation.");
break;
}
setR0Type(pResultType);
}
}
virtual void gUnaryCmp(int op) {
if (op != OP_LOGICAL_NOT) {
error("Unknown unary cmp %d", op);
} else {
Type* pR0Type = getR0Type();
TypeTag tag = collapseType(pR0Type->tag);
switch(tag) {
case TY_INT: {
oad(0xb9, 0); /* movl $0, %ecx */
int t = decodeOp(op);
o(0xc139); /* cmp %eax,%ecx */
li(0);
o(0x0f); /* setxx %al */
o(t + 0x90);
o(0xc0);
}
break;
case TY_FLOAT:
case TY_DOUBLE:
o(0xeed9); // fldz
o(0xe9da); // fucompp
o(0xe0df); // fnstsw %ax
o(0x9e); // sahf
o(0xc0950f); // setne %al
o(0xc29a0f); // setp %dl
o(0xd009); // orl %edx, %eax
o(0xc0b60f); // movzbl %al, %eax
o(0x01f083); // xorl $1, %eax
break;
default:
error("gUnaryCmp unsupported type");
break;
}
}
setR0Type(mkpInt);
}
virtual void genUnaryOp(int op) {
Type* pR0Type = getR0Type();
TypeTag tag = collapseType(pR0Type->tag);
switch(tag) {
case TY_INT:
oad(0xb9, 0); /* movl $0, %ecx */
o(decodeOp(op));
break;
case TY_FLOAT:
case TY_DOUBLE:
switch (op) {
case OP_MINUS:
o(0xe0d9); // fchs
break;
case OP_BIT_NOT:
error("Can't apply '~' operator to a float or double.");
break;
default:
error("Unknown unary op %d\n", op);
break;
}
break;
default:
error("genUnaryOp unsupported type");
break;
}
}
virtual void pushR0() {
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
switch(r0ct) {
case TY_INT:
o(0x50); /* push %eax */
break;
case TY_FLOAT:
o(0x50); /* push %eax */
o(0x241cd9); // fstps 0(%esp)
break;
case TY_DOUBLE:
o(0x50); /* push %eax */
o(0x50); /* push %eax */
o(0x241cdd); // fstpl 0(%esp)
break;
default:
error("pushR0 unsupported type %d", r0ct);
break;
}
pushType();
}
virtual void over() {
// We know it's only used for int-ptr ops (++/--)
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
Type* pTOSType = getTOSType();
TypeTag tosct = collapseType(pTOSType->tag);
assert (r0ct == TY_INT && tosct == TY_INT);
o(0x59); /* pop %ecx */
o(0x50); /* push %eax */
o(0x51); /* push %ecx */
overType();
}
virtual void popR0() {
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
switch(r0ct) {
case TY_INT:
o(0x58); /* popl %eax */
break;
case TY_FLOAT:
o(0x2404d9); // flds (%esp)
o(0x58); /* popl %eax */
break;
case TY_DOUBLE:
o(0x2404dd); // fldl (%esp)
o(0x58); /* popl %eax */
o(0x58); /* popl %eax */
break;
default:
error("popR0 unsupported type %d", r0ct);
break;
}
popType();
}
virtual void storeR0ToTOS() {
Type* pPointerType = getTOSType();
assert(pPointerType->tag == TY_POINTER);
Type* pTargetType = pPointerType->pHead;
convertR0(pTargetType);
o(0x59); /* pop %ecx */
popType();
switch (pTargetType->tag) {
case TY_POINTER:
case TY_INT:
o(0x0189); /* movl %eax/%al, (%ecx) */
break;
case TY_SHORT:
o(0x018966); /* movw %ax, (%ecx) */
break;
case TY_CHAR:
o(0x0188); /* movl %eax/%al, (%ecx) */
break;
case TY_FLOAT:
o(0x19d9); /* fstps (%ecx) */
break;
case TY_DOUBLE:
o(0x19dd); /* fstpl (%ecx) */
break;
case TY_STRUCT:
{
// TODO: use alignment information to use movsw/movsl instead of movsb
int size = sizeOf(pTargetType);
if (size > 0) {
o(0x9c); // pushf
o(0x57); // pushl %edi
o(0x56); // pushl %esi
o(0xcf89); // movl %ecx, %edi
o(0xc689); // movl %eax, %esi
oad(0xb9, size); // mov #size, %ecx
o(0xfc); // cld
o(0xf3); // rep
o(0xa4); // movsb
o(0x5e); // popl %esi
o(0x5f); // popl %edi
o(0x9d); // popf
}
}
break;
default:
error("storeR0ToTOS: unsupported type %d",
pTargetType->tag);
break;
}
setR0Type(pTargetType);
}
virtual void loadR0FromR0() {
Type* pPointerType = getR0Type();
assert(pPointerType->tag == TY_POINTER);
Type* pNewType = pPointerType->pHead;
TypeTag tag = pNewType->tag;
switch (tag) {
case TY_POINTER:
case TY_INT:
o2(0x008b); /* mov (%eax), %eax */
break;
case TY_SHORT:
o(0xbf0f); /* movswl (%eax), %eax */
ob(0);
break;
case TY_CHAR:
o(0xbe0f); /* movsbl (%eax), %eax */
ob(0); /* add zero in code */
break;
case TY_FLOAT:
o2(0x00d9); // flds (%eax)
break;
case TY_DOUBLE:
o2(0x00dd); // fldl (%eax)
break;
case TY_ARRAY:
pNewType = pNewType->pTail;
break;
case TY_STRUCT:
break;
default:
error("loadR0FromR0: unsupported type %d", tag);
break;
}
setR0Type(pNewType);
}
virtual void leaR0(int ea, Type* pPointerType, ExpressionType et) {
gmov(10, ea); /* leal EA, %eax */
setR0Type(pPointerType, et);
}
virtual int leaForward(int ea, Type* pPointerType) {
oad(0xb8, ea); /* mov $xx, %eax */
setR0Type(pPointerType);
return getPC() - 4;
}
virtual void convertR0Imp(Type* pType, bool isCast){
Type* pR0Type = getR0Type();
if (pR0Type == NULL) {
assert(false);
setR0Type(pType);
return;
}
if (isPointerType(pType) && isPointerType(pR0Type)) {
Type* pA = pR0Type;
Type* pB = pType;
// Array decays to pointer
if (pA->tag == TY_ARRAY && pB->tag == TY_POINTER) {
pA = pA->pTail;
}
if (! (typeEqual(pA, pB)
|| pB->pHead->tag == TY_VOID
|| (pA->tag == TY_POINTER && pB->tag == TY_POINTER && isCast)
)) {
error("Incompatible pointer or array types");
}
} else if (bitsSame(pType, pR0Type)) {
// do nothing special
} else if (isFloatType(pType) && isFloatType(pR0Type)) {
// do nothing special, both held in same register on x87.
} else {
TypeTag r0Tag = collapseType(pR0Type->tag);
TypeTag destTag = collapseType(pType->tag);
if (r0Tag == TY_INT && isFloatTag(destTag)) {
// Convert R0 from int to float
o(0x50); // push %eax
o(0x2404DB); // fildl 0(%esp)
o(0x58); // pop %eax
} else if (isFloatTag(r0Tag) && destTag == TY_INT) {
// Convert R0 from float to int. Complicated because
// need to save and restore the rounding mode.
o(0x50); // push %eax
o(0x50); // push %eax
o(0x02247cD9); // fnstcw 2(%esp)
o(0x2444b70f); // movzwl 2(%esp), %eax
o(0x02);
o(0x0cb4); // movb $12, %ah
o(0x24048966); // movw %ax, 0(%esp)
o(0x242cd9); // fldcw 0(%esp)
o(0x04245cdb); // fistpl 4(%esp)
o(0x02246cd9); // fldcw 2(%esp)
o(0x58); // pop %eax
o(0x58); // pop %eax
} else {
error("Incompatible types old: %d new: %d",
pR0Type->tag, pType->tag);
}
}
setR0Type(pType);
}
virtual int beginFunctionCallArguments() {
return oad(0xec81, 0); /* sub $xxx, %esp */
}
virtual size_t storeR0ToArg(int l, Type* pArgType) {
convertR0(pArgType);
Type* pR0Type = getR0Type();
TypeTag r0ct = collapseType(pR0Type->tag);
switch(r0ct) {
case TY_INT:
oad(0x248489, l); /* movl %eax, xxx(%esp) */
return 4;
case TY_FLOAT:
oad(0x249CD9, l); /* fstps xxx(%esp) */
return 4;
case TY_DOUBLE:
oad(0x249CDD, l); /* fstpl xxx(%esp) */
return 8;
default:
assert(false);
return 0;
}
}
virtual void endFunctionCallArguments(Type* pDecl, int a, int l) {
* (int*) a = l;
}
virtual int callForward(int symbol, Type* pFunc) {
assert(pFunc->tag == TY_FUNC);
setR0Type(pFunc->pHead);
return psym(0xe8, symbol); /* call xxx */
}
virtual void callIndirect(int l, Type* pFunc) {
assert(pFunc->tag == TY_FUNC);
popType(); // Get rid of indirect fn pointer type
setR0Type(pFunc->pHead);
oad(0x2494ff, l); /* call *xxx(%esp) */
}
virtual void adjustStackAfterCall(Type* pDecl, int l, bool isIndirect) {
assert(pDecl->tag == TY_FUNC);
if (isIndirect) {
l += 4;
}
if (l > 0) {
oad(0xc481, l); /* add $xxx, %esp */
}
}
virtual int jumpOffset() {
return 5;
}
/* output a symbol and patch all calls to it */
virtual void gsym(int t) {
int n;
int pc = getPC();
while (t) {
n = *(int *) t; /* next value */
*(int *) t = pc - t - 4;
t = n;
}
}
/* output a symbol and patch all calls to it, using absolute address */
virtual void resolveForward(int t) {
int n;
int pc = getPC();
while (t) {
n = *(int *) t; /* next value */
*(int *) t = pc;
t = n;
}
}
virtual int finishCompile() {
size_t pagesize = 4096;