text
stringlengths
8
6.88M
#ifndef MODULEFILE_H #define MODULEFILE_H class ModuleFile { const char* const fname; ModuleFile(const char* const fname); public: static ModuleFile from(const char* const fnameIn); const char* get() const; }; #endif
#pragma once #include <vector> #include <thread> #include <threadpool/task.h> #include <threadpool/worker.h> #include <threadpool/queue.h> namespace threadpool { class ThreadPool { public: ~ThreadPool() { stop(); } void start(size_t threadsCount) { threads_.clear(); for (size_t i = 0; i < threadsCount; ++i) { threads_.push_back(std::thread(Worker(&tasks_))); } } void stop() { tasks_.stop(); for (std::thread& thread: threads_) { thread.join(); } threads_.clear(); } /** * ThreadPool object is responsible for deleting the allocated task object. * The caller should not do it himself again. */ void add(ITask* task) { tasks_.push(task); } private: std::vector<std::thread> threads_; TaskQueue tasks_; }; } // namespace threadpool
#include<iostream> using namespace std; class complex{ float re,im; public: complex() { re=0; im=0; } void input() { cout<<"enter real part"<<"\n"; cin>>re; cout<<"enter imaginary part"<<"\n"; cin>>im; } void display() { cout<<re<<"+"<<"i"<<im; } complex operator+(complex c2); complex operator-(complex c2); friend complex operator*(complex c1,complex c2); friend complex operator/(complex c1,complex c2); friend istream& operator>>(istream& zin, complex& c); friend ostream& operator<<(ostream& zout,const complex c); }; complex complex :: operator+(complex c2 ) { complex temp; temp.re=re + c2.re; temp.im=im + c2.im; return temp;} complex complex :: operator-(complex c2) { complex temp; temp.re=re-c2.re; temp.im=im-c2.im; return temp; } complex operator*(complex c1,complex c2) { complex c3; c3.re=c1.re*c2.re - c1.im*c2.im; c3.im=c1.re*c2.im + c1.im*c2.re; return c3; } complex operator/(complex c1,complex c2) { complex c3; int x=c2.re*c2.re + c2.im*c2.im; if(c2.im<0) { c3.re=c1.re*c2.re - c1.im*c2.im; c3.im=c1.re*c2.im +c1.im*c2.re; } else{ c3.re=c1.re*c2.re + c1.im*c2.im; c3.im= c1.im*c2.re-c1.re*c2.im;} c3.re=c3.re/x; c3.im=c3.im/x; } istream& operator>>(istream& zin,complex& c) { zin>>c.re; zin>>c.im; return zin; } ostream& operator<<(ostream& zout,const complex c) { zout<<c.re<<"+i"<<c.im; return zout; } int main() { complex c1,c2,c3; cout<<"enter 1st complexno"<<"\n"; cin>>c1; cout<<"enter 2nd complex no"<<"\n"; cin>>c2; cout<<"1st"<<"\n"; cout<<c1; cout<<"\n"; cout<<"2nd"<<"\n"; cout<<c2; cout<<"\n"; int x; char f='y'; while(f!='n'){ cout<<"enter your choice(1-addition/2-substraction/3-multplication/4-division)"<<"\n"; cin>>x; switch(x){ case(1): cout<<"addtion"<<"\n"; c3=c1+c2; cout<<c3; cout<<"\n"; break; case(2): cout<<"substraction"<<"\n"; c3=c1-c2; c3.display(); cout<<"\n"; break; case(3): cout<<"multipliaction"<<"\n"; c3=operator*(c1,c2); cout<<c3; cout<<"\n"; break; case(4): cout<<"division"<<"\n"; c3=operator/(c1,c2); c3.display(); break; } cout<<"want to continue(y/n)"<<"\n"; cin>>f; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 2002 - 2011 * * Bytecode compiler for ECMAScript -- overview, common data and functions * * @author Jens Lindstrom */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/compiler/es_native.h" #include "modules/ecmascript/carakan/src/compiler/es_instruction_data.h" #include "modules/ecmascript/carakan/src/util/es_instruction_string.h" #include "modules/ecmascript/carakan/src/compiler/es_analyzer.h" #ifdef ES_NATIVE_SUPPORT #ifdef ARCHITECTURE_ARM #define SCRATCHI1 ES_CodeGenerator::REG_R0 #define SCRATCHI2 ES_CodeGenerator::REG_R1 #define SCRATCHD1 ES_CodeGenerator::VFPREG_D0 #define SCRATCHD2 ES_CodeGenerator::VFPREG_D1 #define SCRATCHS1 ES_CodeGenerator::VFPREG_S0 #define SCRATCHS2 ES_CodeGenerator::VFPREG_S1 #define SCRATCHS3 ES_CodeGenerator::VFPREG_S2 #define SCRATCHS4 ES_CodeGenerator::VFPREG_S3 #define CONTEXT_POINTER ES_CodeGenerator::REG_R9 #define REGISTER_FRAME_POINTER ES_CodeGenerator::REG_R10 #define PARAMETERS_COUNT ES_CodeGenerator::REG_R1 #define VALUE_TRANSFER_POINTER ES_CodeGenerator::REG_R8 /* These registers are used for the output from the code generated by EmitAllocateObject(). */ #define ALLOCATED_OBJECT_REGISTER ES_CodeGenerator::REG_R8 #define ALLOCATED_OBJECT_NAMED_PROPERTIES_REGISTER ES_CodeGenerator::REG_R4 #define ALLOCATED_OBJECT_INDEXED_PROPERTIES_REGISTER ES_CodeGenerator::REG_R5 /* Until decided when/if, leave in previous code to handle inline allocations + constructor_final_classes */ #ifdef SUPPORT_INLINE_ALLOCATION #error "Not currently supported" #endif // SUPPORT_INLINE_ALLOCATION #ifndef ES_VALUES_AS_NANS # error "Unsupported configuration." #endif // ES_VALUES_AS_NANS #if IEEE_BITS_HI # define SCRATCHI_TYPE SCRATCHI2 # define SCRATCHI_IVALUE SCRATCHI1 # define SCRATCHI_DVALUEH SCRATCHI2 # define SCRATCHI_DVALUEL SCRATCHI1 #else // IEEE_BITS_HI # define SCRATCHI_TYPE SCRATCHI1 # define SCRATCHI_IVALUE SCRATCHI2 # define SCRATCHI_DVALUEH SCRATCHI1 # define SCRATCHI_DVALUEL SCRATCHI2 #endif // IEEE_BITS_HI #define DECLARE_NOTHING() ES_DECLARE_NOTHING() #define ES_OFFSETOF_SUBOBJECT(basecls, subcls) (static_cast<int>(reinterpret_cast<UINTPTR>(static_cast<basecls *>(reinterpret_cast<subcls *>(static_cast<UINTPTR>(0x100))))) - 0x100) #define OBJECT_MEMBER(reg, cls, member) reg, ES_OFFSETOF(cls, member) /* Byte offset from REG_SP where stack-bound register values are located. The scratch space is used when saving/restoring condition state (VFP only.) */ #ifdef ARCHITECTURE_ARM_VFP #define STACK_VALUE_OFFSET 8 #else #define STACK_VALUE_OFFSET 0 #endif // ARCHITECTURE_ARM_VFP static int VALUE_OFFSET(unsigned index) { return index * sizeof(ES_Value_Internal); } static int VALUE_OFFSET(ES_Native::VirtualRegister *vr) { if (vr->stack_frame_offset == INT_MAX) return VALUE_OFFSET(vr->index); else { int size = vr->stack_frame_type == ESTYPE_DOUBLE ? 8 : 4; return -(size + STACK_VALUE_OFFSET + vr->stack_frame_offset); } } static int DVALUE_OFFSET(ES_Native::VirtualRegister *vr) { return VALUE_OFFSET(vr); } static int TYPE_OFFSET(unsigned index) { return index * sizeof(ES_Value_Internal) + VALUE_TYPE_OFFSET; } static int TYPE_OFFSET(ES_Native::VirtualRegister *vr) { OP_ASSERT(vr->stack_frame_offset == INT_MAX); return TYPE_OFFSET(vr->index); } static int IVALUE_OFFSET(unsigned index) { return index * sizeof(ES_Value_Internal) + VALUE_IVALUE_OFFSET; } static int IVALUE_OFFSET(ES_Native::VirtualRegister *vr) { if (vr->stack_frame_offset == INT_MAX) return IVALUE_OFFSET(vr->index); else { OP_ASSERT(vr->stack_frame_type == ESTYPE_INT32 || vr->stack_frame_type == ESTYPE_BOOLEAN); return VALUE_OFFSET(vr); } } static ES_CodeGenerator::Register BASE_REGISTER(ES_Native::VirtualRegister *vr) { return vr->stack_frame_offset == INT_MAX ? REGISTER_FRAME_POINTER : ES_CodeGenerator::REG_SP; } static ES_CodeGenerator::Register BASE_REGISTER(const ES_Native::Operand &op) { return BASE_REGISTER(op.virtual_register); } static ES_CodeGenerator::Register INTEGER_REGISTER(ES_Native::NativeRegister *nr) { return static_cast<ES_CodeGenerator::Register>(nr->register_code); } static ES_CodeGenerator::Register INTEGER_REGISTER(const ES_Native::Operand &op) { return INTEGER_REGISTER(op.native_register); } #ifdef ARCHITECTURE_ARM_VFP static ES_CodeGenerator::VFPDoubleRegister DOUBLE_REGISTER(ES_Native::NativeRegister *nr) { return static_cast<ES_CodeGenerator::VFPDoubleRegister>(nr->register_code); } static ES_CodeGenerator::VFPDoubleRegister DOUBLE_REGISTER(const ES_Native::Operand &op) { return DOUBLE_REGISTER(op.native_register); } #endif // ARCHITECTURE_ARM_VFP static ES_Native::NativeRegister * INTEGER_NR(ES_Native *native, ES_CodeGenerator::Register reg) { OP_ASSERT(reg >= ES_CodeGenerator::REG_R2 || reg <= ES_CodeGenerator::REG_R8); return native->NR(reg - ES_CodeGenerator::REG_R2); } static ES_CodeGenerator::Register TYPE_REGISTER(ES_CodeGenerator::Register reg1, ES_CodeGenerator::Register reg2) { OP_ASSERT((reg1 & 1) == 0); OP_ASSERT(reg1 + 1 == reg2); #if IEEE_BITS_HI return reg2; #else // IEEE_BITS_HI return reg1; #endif // IEEE_BITS_HI } static ES_CodeGenerator::Register IVALUE_REGISTER(ES_CodeGenerator::Register reg1, ES_CodeGenerator::Register reg2) { OP_ASSERT((reg1 & 1) == 0); OP_ASSERT(reg1 + 1 == reg2); #if IEEE_BITS_HI return reg1; #else // IEEE_BITS_HI return reg2; #endif // IEEE_BITS_HI } static ES_CodeGenerator::Register DVALUEH_REGISTER(ES_CodeGenerator::Register reg1, ES_CodeGenerator::Register reg2) { return TYPE_REGISTER(reg1, reg2); } static ES_CodeGenerator::Register DVALUEL_REGISTER(ES_CodeGenerator::Register reg1, ES_CodeGenerator::Register reg2) { return IVALUE_REGISTER(reg1, reg2); } static void AddImmediateToRegister(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, int value, ES_CodeGenerator::Register target, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { if (ES_CodeGenerator::Operand::EncodeImmediate(value)) cg.ADD(source, value, target, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); else if (ES_CodeGenerator::Operand::EncodeImmediate(-value)) cg.SUB(source, -value, target, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); else { ES_CodeGenerator::Register scratch; if (source != target) scratch = target; else if (source == SCRATCHI1) scratch = SCRATCHI2; else scratch = SCRATCHI1; BOOL subtract = FALSE; if (ES_CodeGenerator::NotOperand::EncodeImmediate(value)) cg.MOV(value, scratch, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); else if (ES_CodeGenerator::NotOperand::EncodeImmediate(-value)) { cg.MOV(value, scratch, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); subtract = TRUE; } else { ES_CodeGenerator::Constant *constant = cg.NewConstant(value); cg.LDR(constant, scratch, condition); } if (subtract) cg.SUB(source, scratch, target, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); else cg.ADD(source, scratch, target, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); } } static void AddImmediateToRegister(ES_CodeGenerator &cg, int value, ES_CodeGenerator::Register target, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { AddImmediateToRegister(cg, target, value, target, condition); } static void MoveImmediateToRegister(ES_CodeGenerator &cg, int value, ES_CodeGenerator::Register target, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { if (ES_CodeGenerator::NotOperand::EncodeImmediate(value)) cg.MOV(value, target, ES_CodeGenerator::UNSET_CONDITION_CODES, condition); else { ES_CodeGenerator::Constant *constant = cg.NewConstant(value); cg.LDR(constant, target, condition); } } static void MovePointerToRegister(ES_CodeGenerator &cg, void *value, ES_CodeGenerator::Register target, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { ES_CodeGenerator::Constant *constant = cg.NewConstant(value); cg.LDR(constant, target, condition); } static void CompareRegisterToImmediate(ES_CodeGenerator &cg, ES_CodeGenerator::Register lhs, int rhs, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { if (ES_CodeGenerator::NegOperand::EncodeImmediate(rhs)) cg.CMP(lhs, rhs, condition); else { OP_ASSERT(lhs != SCRATCHI1); MoveImmediateToRegister(cg, rhs, SCRATCHI1, condition); cg.CMP(lhs, SCRATCHI1, condition); } } static void EqCompareRegisterToImmediate(ES_CodeGenerator &cg, ES_CodeGenerator::Register lhs, int rhs, ES_NativeJumpCondition condition = ES_NATIVE_CONDITION_ALWAYS) { if (ES_CodeGenerator::Operand::EncodeImmediate(rhs)) cg.TEQ(lhs, rhs, condition); else { OP_ASSERT(lhs != SCRATCHI1); MoveImmediateToRegister(cg, rhs, SCRATCHI1, condition); cg.TEQ(lhs, SCRATCHI1, condition); } } static void LoadValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register base, unsigned offset, ES_CodeGenerator::Register dst1, ES_CodeGenerator::Register dst2) { if ((dst1 & 1) == 0 && dst1 + 1 == dst2 && ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_DOUBLE_WORD)) cg.LDRD(base, offset, dst1); else if (ES_CodeGenerator::SupportedOffset(offset + 4)) { cg.LDR(base, offset, dst1); cg.LDR(base, offset + 4, dst2); } else { AddImmediateToRegister(cg, base, offset, dst2); cg.LDR(dst2, 4, dst1, TRUE, FALSE); cg.LDR(dst2, 0, dst2); } } static void LoadValue(ES_CodeGenerator &cg, ES_Native::VirtualRegister *source, ES_CodeGenerator::Register dst1, ES_CodeGenerator::Register dst2) { LoadValue(cg, BASE_REGISTER(source), VALUE_OFFSET(source), dst1, dst2); } static void LoadOffset(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, unsigned offset, ES_CodeGenerator::Register target) { if (ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_WORD)) cg.LDR(source, offset, target); else { AddImmediateToRegister(cg, source, offset, target); cg.LDR(target, 0, target); } } static void StoreOffset(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, ES_CodeGenerator::Register base, unsigned offset, ES_CodeGenerator::Register scratch) { OP_ASSERT((scratch != SCRATCHI1 || source != SCRATCHI2) && (scratch != SCRATCHI2 || source != SCRATCHI1)); if (ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_WORD)) cg.STR(source, base, offset); else { AddImmediateToRegister(cg, base, offset, scratch); cg.STR(source, scratch, 0); } } static void StoreValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register src1, ES_CodeGenerator::Register src2, ES_CodeGenerator::Register base, unsigned offset) { if ((src1 & 1) == 0 && src1 + 1 == src2 && ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_DOUBLE_WORD)) cg.STRD(src1, base, offset); else if (ES_CodeGenerator::SupportedOffset(offset + 4)) { cg.STR(src1, base, offset); cg.STR(src2, base, offset + 4); } else { ES_CodeGenerator::Register dst; if (src1 == SCRATCHI1) { cg.PUSH(ES_CodeGenerator::REG_R8); dst = ES_CodeGenerator::REG_R8; } else dst = SCRATCHI1; AddImmediateToRegister(cg, base, offset, dst); cg.STR(src1, dst, 4, TRUE, FALSE); cg.STR(src2, dst, 0); if (src1 == SCRATCHI1) cg.POP(ES_CodeGenerator::REG_R8); } } static void StoreValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register src1, ES_CodeGenerator::Register src2, ES_Native::VirtualRegister *target) { StoreValue(cg, src1, src2, BASE_REGISTER(target), VALUE_OFFSET(target)); } static void CopyValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register src_base, unsigned src_offset, ES_CodeGenerator::Register dst_base, unsigned dst_offset) { OP_ASSERT(src_base != SCRATCHI1 && src_base != SCRATCHI2); OP_ASSERT(dst_base != SCRATCHI1 && dst_base != SCRATCHI2); LoadValue(cg, src_base, src_offset, SCRATCHI1, SCRATCHI2); StoreValue(cg, SCRATCHI1, SCRATCHI2, dst_base, dst_offset); } static void CopyValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register src_base, unsigned src_offset, ES_Native::VirtualRegister *dst_vr) { CopyValue(cg, src_base, src_offset, BASE_REGISTER(dst_vr), VALUE_OFFSET(dst_vr->index)); } static void CopyValue(ES_CodeGenerator &cg, ES_Native::VirtualRegister *src_vr, ES_CodeGenerator::Register dst_base, unsigned dst_offset) { CopyValue(cg, BASE_REGISTER(src_vr), VALUE_OFFSET(src_vr->index), dst_base, dst_offset); } static void CopyValue(ES_CodeGenerator &cg, ES_Native::VirtualRegister *src_vr, ES_Native::VirtualRegister *dst_vr) { CopyValue(cg, BASE_REGISTER(src_vr), VALUE_OFFSET(src_vr->index), BASE_REGISTER(dst_vr), VALUE_OFFSET(dst_vr->index)); } static void CopyDataToValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, ES_CodeGenerator::Register source_type, ES_Native::VirtualRegister *target_vr) { ES_CodeGenerator::OutOfOrderBlock *handle_untyped = cg.StartOutOfOrderBlock(); CopyValue(cg, source, 0, target_vr); cg.EndOutOfOrderBlock(); unsigned handled = (~(ES_STORAGE_BITS_DOUBLE | ES_STORAGE_BITS_WHATEVER) << ES_STORAGE_TYPE_SHIFT) & ES_STORAGE_TYPE_MASK; MoveImmediateToRegister(cg, handled, SCRATCHI1); cg.TST(source_type, SCRATCHI1); cg.Jump(handle_untyped->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); ES_CodeGenerator::JumpTarget *non_null_target = cg.ForwardJump(); ES_CodeGenerator::OutOfOrderBlock *handle_null = cg.StartOutOfOrderBlock(); cg.TEQ(SCRATCHI_IVALUE, 0); cg.Jump(non_null_target, ES_NATIVE_CONDITION_NOT_EQUAL); MoveImmediateToRegister(cg, ESTYPE_NULL, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); cg.EndOutOfOrderBlock(); cg.LDR(source, 0, SCRATCHI_IVALUE); cg.TST(source_type, ES_STORAGE_NULL_MASK); cg.Jump(handle_null->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.SetJumpTarget(non_null_target); MoveImmediateToRegister(cg, ES_VALUE_TYPE_INIT_MASK, SCRATCHI_TYPE); cg.ORR(source_type, SCRATCHI_TYPE, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); cg.SetOutOfOrderContinuationPoint(handle_untyped); cg.SetOutOfOrderContinuationPoint(handle_null); } static void CopyTypedDataToValue(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, unsigned source_offset, ES_StorageType source_type, ES_Native::VirtualRegister *target_vr) { if (source_type == ES_STORAGE_WHATEVER || source_type == ES_STORAGE_DOUBLE) CopyValue(cg, source, source_offset, target_vr); else { LoadOffset(cg, source, source_offset, SCRATCHI_IVALUE); ES_CodeGenerator::OutOfOrderBlock *null_block = NULL; if (ES_Layout_Info::IsNullable(source_type)) { null_block = cg.StartOutOfOrderBlock(); MoveImmediateToRegister(cg, ESTYPE_NULL, SCRATCHI2); cg.STR(SCRATCHI2, BASE_REGISTER(target_vr), TYPE_OFFSET(target_vr->index)); cg.EndOutOfOrderBlock(); cg.TEQ(SCRATCHI_IVALUE, 0); cg.Jump(null_block->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); } MoveImmediateToRegister(cg, ES_Value_Internal::ConvertToValueType(source_type), SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); if (null_block) cg.SetOutOfOrderContinuationPoint(null_block); } } static void CopyValueToData2(ES_CodeGenerator &cg, ES_CodeGenerator::Register source, ES_CodeGenerator::Register target, ES_CodeGenerator::JumpTarget *size_4_target, ES_CodeGenerator::JumpTarget *size_8_target) { unsigned target_offset = 0; OP_ASSERT(size_4_target || size_8_target); ES_CodeGenerator::JumpTarget *done_target = NULL; if (size_8_target) { cg.SetJumpTarget(size_8_target, FALSE); if (!size_4_target) { CopyValue(cg, source, 0, target, target_offset); size_8_target = NULL; } else { cg.LDR(source, 4, SCRATCHI1); cg.STR(SCRATCHI1, target, target_offset + 4); } } if (size_4_target || size_8_target) { if (size_4_target) cg.SetJumpTarget(size_4_target, FALSE); cg.LDR(source, 0, SCRATCHI1); cg.STR(SCRATCHI1, target, target_offset); } if (done_target) cg.SetJumpTarget(done_target); } static void CopyValueToData(ES_CodeGenerator &cg, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register target, ES_CodeGenerator::Register target_type, ES_CodeGenerator::JumpTarget *slow_case_target) { unsigned target_offset = 0; ES_CodeGenerator::OutOfOrderBlock *handle_untyped = cg.StartOutOfOrderBlock(); CopyValue(cg, source_vr, target, target_offset); cg.EndOutOfOrderBlock(); unsigned handled = (~(ES_STORAGE_BITS_DOUBLE | ES_STORAGE_BITS_WHATEVER) << ES_STORAGE_TYPE_SHIFT) & ES_STORAGE_TYPE_MASK; MoveImmediateToRegister(cg, handled, SCRATCHI1); cg.TST(target_type, SCRATCHI1); cg.Jump(handle_untyped->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); cg.LDR(BASE_REGISTER(source_vr), TYPE_OFFSET(source_vr->index), SCRATCHI2); ES_CodeGenerator::JumpTarget *non_null = cg.ForwardJump(), *done_target = cg.ForwardJump(); cg.TST(target_type, ES_STORAGE_NULL_MASK); cg.Jump(non_null, ES_NATIVE_CONDITION_EQUAL); cg.CMP(SCRATCHI2, ESTYPE_NULL); cg.Jump(non_null, ES_NATIVE_CONDITION_NOT_EQUAL); cg.MOV(0, SCRATCHI1); cg.STR(SCRATCHI1, target, target_offset); cg.Jump(done_target); cg.SetJumpTarget(non_null); MoveImmediateToRegister(cg, ES_VALUE_TYPE_INIT_MASK, SCRATCHI1); cg.ORR(target_type, SCRATCHI1, SCRATCHI1); cg.CMP(SCRATCHI1, SCRATCHI2); cg.Jump(slow_case_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), SCRATCHI1); cg.STR(SCRATCHI1, target, target_offset); cg.SetJumpTarget(done_target); cg.SetOutOfOrderContinuationPoint(handle_untyped); } static void CopyValueToTypedData(ES_CodeGenerator &cg, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register target, unsigned target_offset, ES_StorageType target_type, ES_CodeGenerator::JumpTarget *type_check_fail, ES_CodeGenerator::Register scratch1, ES_CodeGenerator::Register scratch2) { /* Assert that scratch1 and scratch2 isn't a combination of SCRATCHI1 and SCRATCHI2 since StoreOffset will clobber those. */ OP_ASSERT((scratch1 != SCRATCHI1 || scratch2 != SCRATCHI2) && (scratch1 != SCRATCHI2 || scratch2 != SCRATCHI1)); ES_CodeGenerator::Register type = TYPE_REGISTER(scratch1, scratch2); ES_CodeGenerator::Register value = IVALUE_REGISTER(scratch1, scratch2); if (target_type == ES_STORAGE_WHATEVER || target_type == ES_STORAGE_DOUBLE) { LoadValue(cg, source_vr, scratch1, scratch2); if (target_type == ES_STORAGE_DOUBLE && type_check_fail) { cg.CMP(type, ESTYPE_DOUBLE); cg.Jump(type_check_fail, ES_NATIVE_CONDITION_GREATER); } StoreValue(cg, scratch1, scratch2, target, target_offset); } else if (type_check_fail) { ES_ValueType value_type = ES_Value_Internal::ConvertToValueType(target_type); LoadValue(cg, source_vr, scratch1, scratch2); if (ES_Layout_Info::IsNullable(target_type)) { cg.CMP(type, ESTYPE_NULL); cg.MOV(0, value, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); cg.CMP(type, value_type, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(type_check_fail, ES_NATIVE_CONDITION_NOT_EQUAL); StoreOffset(cg, value, target, target_offset, type); } else { cg.CMP(type, value_type); cg.Jump(type_check_fail, ES_NATIVE_CONDITION_NOT_EQUAL); StoreOffset(cg, value, target, target_offset, type); } } else if (target_type == ES_STORAGE_NULL) { cg.MOV(0, value); StoreOffset(cg, value, target, target_offset, type); } else if (target_type != ES_STORAGE_UNDEFINED) { OP_ASSERT(ES_Layout_Info::SizeOf(target_type) == 4); cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), value); StoreOffset(cg, value, target, target_offset, type); } } static void JumpToSize(ES_CodeGenerator &cg, unsigned size, ES_CodeGenerator::JumpTarget *&size_4_target, ES_CodeGenerator::JumpTarget *&size_8_target) { if (size == 4) { if (!size_4_target) size_4_target = cg.ForwardJump(); cg.Jump(size_4_target); } else { OP_ASSERT(size == 8); if (!size_8_target) size_8_target = cg.ForwardJump(); cg.Jump(size_8_target); } } void ES_Native::EmitTypeConversionHandlers(VirtualRegister *source_vr, ES_CodeGenerator::Register properties, unsigned offset, ES_CodeGenerator::JumpTarget *null_target, ES_CodeGenerator::JumpTarget *int_to_double_target) { ES_CodeGenerator::Register source(ES_CodeGenerator::REG_R2); OP_ASSERT(source != properties); ES_CodeGenerator::OutOfOrderBlock *int_to_double_block = NULL; if (int_to_double_target) { int_to_double_block = cg.StartOutOfOrderBlock(); cg.SetJumpTarget(int_to_double_target); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(source_vr), source); #ifdef ARCHITECTURE_ARM_VFP if (ARCHITECTURE_HAS_FPU()) { cg.LDR(source, VALUE_IVALUE_OFFSET, SCRATCHI1); cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOD(SCRATCHS1, SCRATCHD1); if (ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_DOUBLE)) cg.FSTD(SCRATCHD1, properties, offset); else { AddImmediateToRegister(cg, properties, offset, SCRATCHI1); cg.FSTD(SCRATCHD1, SCRATCHI1, 0); } } else #endif // ARCHITECTURE_ARM_VFP { cg.LDR(source, VALUE_IVALUE_OFFSET, ES_CodeGenerator::REG_R0); AddImmediateToRegister(cg, properties, offset, ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreIntAsDouble)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } cg.EndOutOfOrderBlock(); } ES_CodeGenerator::OutOfOrderBlock *null_block = NULL; if (null_target) { null_block = cg.StartOutOfOrderBlock(); cg.SetJumpTarget(null_target); cg.MOV(0, source); StoreOffset(cg, source, properties, offset, SCRATCHI2); cg.EndOutOfOrderBlock(); } if (int_to_double_block) cg.SetOutOfOrderContinuationPoint(int_to_double_block); if (null_block) cg.SetOutOfOrderContinuationPoint(null_block); } static ES_CodeGenerator::OutOfOrderBlock * RecoverFromFailedPropertyValueTransfer(ES_Native *native, ES_Native::VirtualRegister *target_vr, ES_CodeGenerator::Register transfer_register) { if (!native->is_light_weight) { ES_CodeGenerator &cg = native->cg; ES_CodeGenerator::OutOfOrderBlock *recover = cg.StartOutOfOrderBlock(); cg.SetOutOfOrderContinuationPoint(native->current_slow_case); native->current_slow_case = NULL; native->property_value_fail = cg.ForwardJump(); native->EmitRegisterTypeCheck(target_vr, ESTYPE_OBJECT, native->property_value_fail); int register_offset = static_cast<int>(VALUE_OFFSET(target_vr->index)) - static_cast<int>(native->property_value_offset); if (register_offset) AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, register_offset, transfer_register); else cg.MOV(REGISTER_FRAME_POINTER, transfer_register); cg.EndOutOfOrderBlock(); return recover; } else return NULL; } unsigned ES_ArchitecureMixin::StackSpaceAllocated() { ES_Native *self = static_cast<ES_Native *>(this); unsigned stack_space_allocated = 3 * sizeof(void *); if (self->code->type == ES_Code::TYPE_FUNCTION) { stack_space_allocated += sizeof(void *); if (self->code->CanHaveVariableObject()) stack_space_allocated += sizeof(void *); stack_space_allocated += sizeof(void *); } if ((stack_space_allocated + sizeof(void *)) & sizeof(void *)) stack_frame_padding = sizeof(void *); else stack_frame_padding = 0; stack_space_allocated += stack_frame_padding; return stack_space_allocated; } ES_CodeGenerator::Constant * ES_ArchitecureMixin::GetInstructionHandler(ES_Instruction instruction) { ES_Native *self = static_cast<ES_Native *>(this); if (!c_ih) { c_ih = OP_NEWGROA_L(ES_CodeGenerator::Constant *, ESI_LAST_INSTRUCTION, self->arena); op_memset(c_ih, 0, sizeof (ES_CodeGenerator::Constant *) * ESI_LAST_INSTRUCTION); } if (!c_ih[instruction]) c_ih[instruction] = self->cg.NewConstant(g_ecma_instruction_handlers[instruction]); return c_ih[instruction]; } void ES_ArchitecureMixin::LoadObjectOperand(unsigned source_index, ES_CodeGenerator::Register target) { ES_Native *self = static_cast<ES_Native *>(this); ES_Native::VirtualRegister *source_vr = self->VR(source_index); if (self->property_value_read_vr && self->property_value_nr) { OP_ASSERT(self->property_value_read_vr == source_vr); LoadOffset(self->cg, INTEGER_REGISTER(self->property_value_nr), self->property_value_offset, target); } else self->cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), target); } ES_Boxed * AllocateSimple(ES_Context *context, ES_Heap *heap, unsigned nbytes) { return heap->AllocateSimple(context, nbytes); } void ES_ArchitecureMixin::EmitAllocateObject(ES_Class *actual_klass, ES_Class *final_klass, unsigned property_count, unsigned *nindexed, ES_Compact_Indexed_Properties *representation, ES_CodeGenerator::JumpTarget *slow_case) { OP_ASSERT(!actual_klass->HasHashTableProperties()); DECLARE_NOTHING(); ES_Native *self = static_cast<ES_Native *>(this); ES_CodeGenerator &cg = self->cg; ES_Native::ObjectAllocationData data; self->GetObjectAllocationData(data, actual_klass, final_klass, property_count, nindexed, representation); OP_ASSERT(data.named_bytes >= sizeof(ES_Box) + (final_klass ? final_klass : actual_klass)->SizeOf(property_count)); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R8); /* Carve a chunk off the heap's current free block, check that it was big enough and if so, update the heap's current_top pointer. */ #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitAllocateObject(): allocate memory\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT ES_CodeGenerator::Register heap(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register current_top(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register current_limit(ES_CodeGenerator::REG_R4); unsigned total_bytes = data.main_bytes + data.named_bytes + data.indexed_bytes; ES_CodeGenerator::OutOfOrderBlock *simple_allocation = cg.StartOutOfOrderBlock(); MoveImmediateToRegister(cg, total_bytes, ES_CodeGenerator::REG_R2); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, heap), ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&AllocateSimple)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.MOV(ES_CodeGenerator::REG_R0, object); cg.EndOutOfOrderBlock(); slow_case = simple_allocation->GetJumpTarget(); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, heap), heap); cg.LDR(OBJECT_MEMBER(heap, ES_Heap, current_top), object); cg.LDR(OBJECT_MEMBER(heap, ES_Heap, current_limit), current_limit); AddImmediateToRegister(cg, object, total_bytes, current_top); cg.CMP(current_top, current_limit); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER); cg.STR(current_top, OBJECT_MEMBER(heap, ES_Heap, current_top)); ES_CodeGenerator::Register bytes_live(ES_CodeGenerator::REG_R3); cg.LDR(OBJECT_MEMBER(heap, ES_Heap, bytes_live), bytes_live); AddImmediateToRegister(cg, bytes_live, total_bytes, bytes_live); cg.STR(bytes_live, OBJECT_MEMBER(heap, ES_Heap, bytes_live)); cg.SetOutOfOrderContinuationPoint(simple_allocation); /* Initialize object. */ /* R4 == ALLOCATED_OBJECT_NAMED_PROPERTIES_REGISTER */ ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register indexed_properties(ES_CodeGenerator::REG_R5); AddImmediateToRegister(cg, object, data.main_bytes + sizeof(ES_Box), properties); if (nindexed) if (representation) MovePointerToRegister(cg, representation, indexed_properties); else AddImmediateToRegister(cg, object, data.main_bytes + data.named_bytes, indexed_properties); else cg.MOV(0, indexed_properties); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitAllocateObject(): initialize ES_Object\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT MoveImmediateToRegister(cg, data.gctag + (data.main_bytes << 16), ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, data.object_bits, ES_CodeGenerator::REG_R1); MoveImmediateToRegister(cg, property_count, ES_CodeGenerator::REG_R2); MovePointerToRegister(cg, actual_klass, ES_CodeGenerator::REG_R3); /* Store R0-R5. */ cg.STM(object, 0x003f); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitAllocateObject(): initialize ES_Properties\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT MoveImmediateToRegister(cg, GCTAG_ES_Box + (data.named_bytes << 16), SCRATCHI1); cg.STR(SCRATCHI1, object, data.main_bytes); if (nindexed) { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitAllocateObject(): initialize 'length' property\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT /* Set length property. */ MoveImmediateToRegister(cg, ESTYPE_INT32, SCRATCHI_TYPE); MoveImmediateToRegister(cg, data.length, SCRATCHI_IVALUE); cg.STRD(SCRATCHI1, properties, 0); if (!representation) { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitAllocateObject(): initialize ES_Compact_Indexed_Properties\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT MoveImmediateToRegister(cg, GCTAG_ES_Compact_Indexed_Properties + (data.indexed_bytes << 16), ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, *nindexed, ES_CodeGenerator::REG_R1); MoveImmediateToRegister(cg, data.length, ES_CodeGenerator::REG_R2); /* Store R0-R3. */ cg.STM(indexed_properties, 0x0007); } } } void ES_ArchitecureMixin::EmitInitProperty(ES_CodeWord *word, const ES_CodeGenerator::Register properties, unsigned index) { ES_Native *self = static_cast<ES_Native *>(this); ES_CodeGenerator &cg = self->cg; ES_Code *code = self->code; ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register ivalue(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register dvalueh(DVALUEH_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register dvaluel(DVALUEL_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); switch (word ? word->instruction : ESI_LOAD_UNDEFINED) { case ESI_LOAD_STRING: { JString *value = code->GetString(word[2].index); MoveImmediateToRegister(cg, ESTYPE_STRING, type); MovePointerToRegister(cg, value, ivalue); } break; case ESI_LOAD_DOUBLE: { double &value = code->data->doubles[word[2].index]; if (op_isnan(value)) MoveImmediateToRegister(cg, ESTYPE_DOUBLE, type); else { UINT32 high, low; op_explode_double(value, high, low); MoveImmediateToRegister(cg, high, dvalueh); MoveImmediateToRegister(cg, low, dvaluel); } } break; case ESI_LOAD_INT32: MoveImmediateToRegister(cg, ESTYPE_INT32, type); MoveImmediateToRegister(cg, word[2].immediate, ivalue); break; case ESI_LOAD_NULL: MoveImmediateToRegister(cg, ESTYPE_NULL, type); cg.MOV(0, ivalue); break; case ESI_LOAD_UNDEFINED: MoveImmediateToRegister(cg, ESTYPE_UNDEFINED, type); cg.MOV(1, ivalue); // "hidden boolean" break; case ESI_LOAD_TRUE: MoveImmediateToRegister(cg, ESTYPE_BOOLEAN, type); cg.MOV(1, ivalue); break; case ESI_LOAD_FALSE: MoveImmediateToRegister(cg, ESTYPE_BOOLEAN, type); cg.MOV(0, ivalue); break; case ESI_PUTI_IMM: case ESI_PUTN_IMM: case ESI_INIT_PROPERTY: { ES_Native::VirtualRegister *source_vr = self->VR(word[3].index); ES_ValueType value_type; BOOL type_known = self->GetType(source_vr, value_type); if (!type_known || (value_type != ESTYPE_UNDEFINED && value_type != ESTYPE_NULL)) LoadValue(cg, source_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); else cg.MOV(value_type, type); if (word->instruction == ESI_PUTI_IMM) if (!type_known) { cg.CMP(type, ESTYPE_UNDEFINED); cg.MOV(1, ivalue, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); } else if (value_type == ESTYPE_UNDEFINED) cg.MOV(1, ivalue); } break; default: OP_ASSERT(FALSE); } StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, properties, VALUE_OFFSET(index)); } void ES_ArchitecureMixin::EmitFunctionCall(ES_CodeGenerator::Constant *function) { ES_Native *self = static_cast<ES_Native *>(this); if (self->is_light_weight) self->cg.MOV(ES_CodeGenerator::REG_LR, ES_CodeGenerator::REG_R8); self->cg.LDR(function, ES_CodeGenerator::REG_LR); self->cg.BLX(ES_CodeGenerator::REG_LR); if (self->is_light_weight) self->cg.MOV(ES_CodeGenerator::REG_R8, ES_CodeGenerator::REG_LR); } //#define DUMP_TRAMPOLINE_CODE_VECTORS #ifndef DUMP_TRAMPOLINE_CODE_VECTORS const unsigned cv_BytecodeToNativeTrampoline_vfp[] = { 0xe92d5ff0, // push {r4, r5, r6, r7, r8, r9, sl, fp, ip, lr} 0xed2d8b10, // vpush {d8 - d15} 0xe5909000, // ldr r9, [r0] 0xe590800c, // ldr r8, [r0, #12] 0xe5983000, // ldr r3, [r8] 0xe52d3004, // push {r3} ; (str r3, [sp, #-4]!) 0xe588d000, // str sp, [r8] 0xe5907008, // ldr r7, [r0, #8] 0xe3a04000, // mov r4, #0 0xe52d4004, // push {r4} ; (str r4, [sp, #-4]!) 0xe587d000, // str sp, [r7] 0xe5906004, // ldr r6, [r0, #4] 0xe3a05000, // mov r5, #0 0xe92d0060, // push {r5, r6} 0xe590a010, // ldr sl, [r0, #16] 0xe52d0004, // push {r0} ; (str r0, [sp, #-4]!) 0xe1a0e00f, // mov lr, pc 0xe590f014, // ldr pc, [r0, #20] 0xe49d0004, // pop {r0} ; (ldr r0, [sp], #4) 0xe5907008, // ldr r7, [r0, #8] 0xe3a02000, // mov r2, #0 0xe5872000, // str r2, [r7] 0xe28dd00c, // add sp, sp, #12 0xe590800c, // ldr r8, [r0, #12] 0xe49d2004, // pop {r2} ; (ldr r2, [sp], #4) 0xe5882000, // str r2, [r8] 0xe3a00001, // mov r0, #1 0xecbd8b10, // vpop {d8 - d15} 0xe8bd9ff0 // pop {r4, r5, r6, r7, r8, r9, sl, fp, ip, pc} }; const unsigned cv_BytecodeToNativeTrampoline[] = { 0xe92d5ff0, // push {r4, r5, r6, r7, r8, r9, sl, fp, ip, lr} 0xe5909000, // ldr r9, [r0] 0xe590800c, // ldr r8, [r0, #12] 0xe5983000, // ldr r3, [r8] 0xe52d3004, // push {r3} ; (str r3, [sp, #-4]!) 0xe588d000, // str sp, [r8] 0xe5907008, // ldr r7, [r0, #8] 0xe3a04000, // mov r4, #0 0xe52d4004, // push {r4} ; (str r4, [sp, #-4]!) 0xe587d000, // str sp, [r7] 0xe5906004, // ldr r6, [r0, #4] 0xe3a05000, // mov r5, #0 0xe92d0060, // push {r5, r6} 0xe590a010, // ldr sl, [r0, #16] 0xe52d0004, // push {r0} ; (str r0, [sp, #-4]!) 0xe1a0e00f, // mov lr, pc 0xe590f014, // ldr pc, [r0, #20] 0xe49d0004, // pop {r0} ; (ldr r0, [sp], #4) 0xe5907008, // ldr r7, [r0, #8] 0xe3a02000, // mov r2, #0 0xe5872000, // str r2, [r7] 0xe28dd00c, // add sp, sp, #12 0xe590800c, // ldr r8, [r0, #12] 0xe49d2004, // pop {r2} ; (ldr r2, [sp], #4) 0xe5882000, // str r2, [r8] 0xe3a00001, // mov r0, #1 0xe8bd9ff0 // pop {r4, r5, r6, r7, r8, r9, sl, fp, ip, pc} }; const unsigned cv_ReconstructNativeStackTrampoline1[] = { 0xe52de004, // push {lr} ; (str lr, [sp, #-4]!) 0xe1a04000, // mov r4, r0 0xe1a05001, // mov r5, r1 0xe1a00009, // mov r0, r9 0xe1a0100d, // mov r1, sp 0xe594d020, // ldr sp, [r4, #32] 0xe1a0e00f, // mov lr, pc 0xe594f01c, // ldr pc, [r4, #28] 0xe1a01005, // mov r1, r5 0xe1a0d000, // mov sp, r0 0xe49de004, // pop {lr} ; (ldr lr, [sp], #4) 0xe594f018 // ldr pc, [r4, #24] }; const unsigned cv_ReconstructNativeStackTrampoline2[] = { 0xe52de004, // push {lr} ; (str lr, [sp, #-4]!) 0xe1a04000, // mov r4, r0 0xe1a05001, // mov r5, r1 0xe1a00009, // mov r0, r9 0xe1a0100d, // mov r1, sp 0xe594d020, // ldr sp, [r4, #32] 0xe1a0e00f, // mov lr, pc 0xe594f01c, // ldr pc, [r4, #28] 0xe1a01005, // mov r1, r5 0xe1a0d000, // mov sp, r0 0xe594f018 // ldr pc, [r4, #24] }; const unsigned cv_ThrowFromMachineCode_vfp[] = { 0xe5901004, // ldr r1, [r0, #4] 0xe3a02000, // mov r2, #0 0xe5812000, // str r2, [r1] 0xe5901008, // ldr r1, [r0, #8] 0xe591d000, // ldr sp, [r1] 0xe49d2004, // pop {r2} ; (ldr r2, [sp], #4) 0xe5812000, // str r2, [r1] 0xe3a00000, // mov r0, #0 0xecbd8b10, // vpop {d8 - d15} 0xe8bd9ff0 // pop {r4, r5, r6, r7, r8, r9, sl, fp, ip, pc} }; const unsigned cv_ThrowFromMachineCode[] = { 0xe5901004, // ldr r1, [r0, #4] 0xe3a02000, // mov r2, #0 0xe5812000, // str r2, [r1] 0xe5901008, // ldr r1, [r0, #8] 0xe591d000, // ldr sp, [r1] 0xe49d2004, // pop {r2} ; (ldr r2, [sp], #4) 0xe5812000, // str r2, [r1] 0xe3a00000, // mov r0, #0 0xe8bd9ff0 // pop {r4, r5, r6, r7, r8, r9, sl, fp, ip, pc} }; #else // DUMP_TRAMPOLINE_CODE_VECTORS static const OpExecMemory * DumpCodeVector(const char *key, ES_CodeGenerator &cg) { extern FILE *g_native_disassembler_file; FILE *stored_native_disassembler_file = g_native_disassembler_file; g_native_disassembler_file = stdout; fprintf(g_native_disassembler_file, "const unsigned %s[] =\n{\n", key); cg.DumpCodeVector(); const OpExecMemory *block = cg.GetCode(g_executableMemory); fprintf(g_native_disassembler_file, "};\n"); fflush(g_native_disassembler_file); cg.Finalize(g_executableMemory, block); g_native_disassembler_file = stored_native_disassembler_file; return block; } #endif // DUMP_TRAMPOLINE_CODE_VECTORS /* static */ BOOL (*ES_Native::GetBytecodeToNativeTrampoline())(void **, unsigned) { #ifndef DUMP_TRAMPOLINE_CODE_VECTORS # ifdef CONSTANT_DATA_IS_EXECUTABLE if (ES_CodeGenerator::SupportsVFP()) return (BOOL (*)(void **, unsigned))(cv_BytecodeToNativeTrampoline_vfp); else return (BOOL (*)(void **, unsigned))(cv_BytecodeToNativeTrampoline); # else // CONSTANT_DATA_IS_EXECUTABLE if (!g_ecma_bytecode_to_native_block) { if (ES_CodeGenerator::SupportsVFP()) { g_ecma_bytecode_to_native_block = g_executableMemory->AllocateL(sizeof cv_BytecodeToNativeTrampoline_vfp); op_memcpy(g_ecma_bytecode_to_native_block->address, cv_BytecodeToNativeTrampoline_vfp, sizeof cv_BytecodeToNativeTrampoline_vfp); } else { g_ecma_bytecode_to_native_block = g_executableMemory->AllocateL(sizeof cv_BytecodeToNativeTrampoline); op_memcpy(g_ecma_bytecode_to_native_block->address, cv_BytecodeToNativeTrampoline, sizeof cv_BytecodeToNativeTrampoline); } OpExecMemoryManager::FinalizeL(g_ecma_bytecode_to_native_block); } return reinterpret_cast<BOOL (*)(void **, unsigned)>(g_ecma_bytecode_to_native_block->address); # endif // CONSTANT_DATA_IS_EXECUTABLE #else // DUMP_TRAMPOLINE_CODE_VECTORS if (!g_ecma_bytecode_to_native_block) { ES_CodeGenerator cg; ES_CodeGenerator::Register pointers(ES_CodeGenerator::REG_R0); //ES_CodeGenerator::Register argc(ES_CodeGenerator::REG_R1); ES_CodeGenerator::Register scratch1(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register native_stack_frame(ES_CodeGenerator::REG_R7); ES_CodeGenerator::Register stack_ptr(ES_CodeGenerator::REG_R8); #define POINTER(name) pointers, TRAMPOLINE_POINTER_##name * sizeof(void *) cg.PUSH(0x5ff0); // R4-R12 + LR /* context => R10 */ cg.LDR(POINTER(CONTEXT), CONTEXT_POINTER); /* Save previous value of context->stack_ptr. */ cg.LDR(POINTER(CONTEXT_STACK_PTR), stack_ptr); cg.LDR(stack_ptr, 0, ES_CodeGenerator::REG_R3); cg.PUSH(ES_CodeGenerator::REG_R3); /* SP => context->stack_ptr */ cg.STR(ES_CodeGenerator::REG_SP, stack_ptr, 0); /* Set-up a terminating native stack frame, with a register frame pointer corresponding to the calling code's register frame. */ cg.LDR(POINTER(CONTEXT_NATIVE_STACK_FRAME), native_stack_frame); cg.MOV(0, ES_CodeGenerator::REG_R4); cg.PUSH(ES_CodeGenerator::REG_R4); cg.STR(ES_CodeGenerator::REG_SP, native_stack_frame, 0); cg.LDR(POINTER(CONTEXT_REG), ES_CodeGenerator::REG_R6); cg.MOV(0, ES_CodeGenerator::REG_R5); cg.PUSH(1 << ES_CodeGenerator::REG_R5 | 1 << ES_CodeGenerator::REG_R6); /* reg => R11 */ cg.LDR(POINTER(REGISTER_FRAME), REGISTER_FRAME_POINTER); cg.PUSH(pointers); cg.MOV(ES_CodeGenerator::REG_PC, ES_CodeGenerator::REG_LR); cg.LDR(POINTER(TRAMPOLINE_DISPATCHER), ES_CodeGenerator::REG_PC); cg.POP(pointers); /* NULL => context->native_stack_frame */ cg.LDR(POINTER(CONTEXT_NATIVE_STACK_FRAME), native_stack_frame); cg.MOV(0, scratch1); cg.STR(scratch1, native_stack_frame, 0); /* Drop terminating stack frame. */ cg.ADD(ES_CodeGenerator::REG_SP, 12, ES_CodeGenerator::REG_SP); /* Restore previous context->stack_ptr. */ cg.LDR(POINTER(CONTEXT_STACK_PTR), stack_ptr); cg.POP(scratch1); cg.STR(scratch1, stack_ptr, 0); cg.MOV(1, ES_CodeGenerator::REG_R0); cg.POP(0x9ff0); // R4-R12 + PC #undef POINTER g_ecma_bytecode_to_native_block = DumpCodeVector("cv_BytecodeToNativeTrampoline", cg); GetReconstructNativeStackTrampoline(TRUE); GetReconstructNativeStackTrampoline(FALSE); GetThrowFromMachineCode(); } return reinterpret_cast<BOOL (*)(void **, unsigned)>(g_ecma_bytecode_to_native_block->address); #endif // DUMP_TRAMPOLINE_CODE_VECTORS } /* static */ void * ES_Native::GetReconstructNativeStackTrampoline(BOOL prologue_entry_point) { #ifndef DUMP_TRAMPOLINE_CODE_VECTORS # ifdef CONSTANT_DATA_IS_EXECUTABLE if (prologue_entry_point) return const_cast<unsigned *>(cv_ReconstructNativeStackTrampoline1); else return const_cast<unsigned *>(cv_ReconstructNativeStackTrampoline2); # else // CONSTANT_DATA_IS_EXECUTABLE const OpExecMemory **block; const unsigned *cv; unsigned cv_length; if (prologue_entry_point) block = &g_ecma_reconstruct_native_stack1_block, cv = cv_ReconstructNativeStackTrampoline1, cv_length = sizeof cv_ReconstructNativeStackTrampoline1; else block = &g_ecma_reconstruct_native_stack2_block, cv = cv_ReconstructNativeStackTrampoline2, cv_length = sizeof cv_ReconstructNativeStackTrampoline2; if (!*block) { *block = g_executableMemory->AllocateL(cv_length); op_memcpy((*block)->address, cv, cv_length); OpExecMemoryManager::FinalizeL(*block); } return (*block)->address; # endif // CONSTANT_DATA_IS_EXECUTABLE #else // DUMP_TRAMPOLINE_CODE_VECTORS const OpExecMemory **block; const char *cv; if (prologue_entry_point) block = &g_ecma_reconstruct_native_stack1_block, cv = "cv_ReconstructNativeStackTrampoline1"; else block = &g_ecma_reconstruct_native_stack2_block, cv = "cv_ReconstructNativeStackTrampoline2"; if (!*block) { ES_CodeGenerator cg; ES_CodeGenerator::Register pointers(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register argc(ES_CodeGenerator::REG_R5); cg.PUSH(ES_CodeGenerator::REG_LR); cg.MOV(ES_CodeGenerator::REG_R0, pointers); cg.MOV(ES_CodeGenerator::REG_R1, argc); #define POINTER(name) pointers, TRAMPOLINE_POINTER_##name * sizeof(void *) cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(ES_CodeGenerator::REG_SP, ES_CodeGenerator::REG_R1); cg.LDR(POINTER(STACK_LIMIT), ES_CodeGenerator::REG_SP); cg.MOV(ES_CodeGenerator::REG_PC, ES_CodeGenerator::REG_LR); cg.LDR(POINTER(RECONSTRUCT_NATIVE_STACK), ES_CodeGenerator::REG_PC); cg.MOV(argc, PARAMETERS_COUNT); cg.MOV(ES_CodeGenerator::REG_R0, ES_CodeGenerator::REG_SP); if (prologue_entry_point) cg.POP(ES_CodeGenerator::REG_LR); cg.LDR(POINTER(NATIVE_DISPATCHER), ES_CodeGenerator::REG_PC); #undef POINTER *block = DumpCodeVector(cv, cg); } return (*block)->address; #endif // DUMP_TRAMPOLINE_CODE_VECTORS } /* static */ void (*ES_Native::GetThrowFromMachineCode())(void **) { #ifndef DUMP_TRAMPOLINE_CODE_VECTORS # ifdef CONSTANT_DATA_IS_EXECUTABLE if (ES_CodeGenerator::SupportsVFP()) return (void (*)(void **))(cv_ThrowFromMachineCode_vfp); else return (void (*)(void **))(cv_ThrowFromMachineCode); # else // CONSTANT_DATA_IS_EXECUTABLE if (!g_ecma_throw_from_machine_code_block) { if (ES_CodeGenerator::SupportsVFP()) { g_ecma_throw_from_machine_code_block = g_executableMemory->AllocateL(sizeof cv_ThrowFromMachineCode_vfp); op_memcpy(g_ecma_throw_from_machine_code_block->address, cv_ThrowFromMachineCode_vfp, sizeof cv_ThrowFromMachineCode_vfp); } else { g_ecma_throw_from_machine_code_block = g_executableMemory->AllocateL(sizeof cv_ThrowFromMachineCode); op_memcpy(g_ecma_throw_from_machine_code_block->address, cv_ThrowFromMachineCode, sizeof cv_ThrowFromMachineCode); } OpExecMemoryManager::FinalizeL(g_ecma_throw_from_machine_code_block); } return reinterpret_cast<void (*)(void **)>(g_ecma_throw_from_machine_code_block->address); # endif // CONSTANT_DATA_IS_EXECUTABLE #else // DUMP_TRAMPOLINE_CODE_VECTORS if (!g_ecma_throw_from_machine_code_block) { ES_CodeGenerator cg; ES_CodeGenerator::Register pointers(ES_CodeGenerator::REG_R0); ES_CodeGenerator::Register scratch1(ES_CodeGenerator::REG_R1); ES_CodeGenerator::Register scratch2(ES_CodeGenerator::REG_R2); #define POINTER(name) pointers, THROW_POINTER_##name * sizeof(void *) /* NULL => context->native_stack_frame */ cg.LDR(POINTER(CONTEXT_NATIVE_STACK_FRAME), scratch1); cg.MOV(0, scratch2); cg.STR(scratch2, scratch1, 0); /* context->stack_ptr => SP, NULL => context->stack_ptr */ cg.LDR(POINTER(CONTEXT_STACK_PTR), scratch1); cg.LDR(scratch1, 0, ES_CodeGenerator::REG_SP); cg.POP(scratch2); cg.STR(scratch2, scratch1, 0); cg.MOV(0, ES_CodeGenerator::REG_R0); cg.POP(0x9ff0); // R4-R12 + PC #undef POINTER g_ecma_throw_from_machine_code_block = DumpCodeVector("cv_ThrowFromMachineCode", cg); } return reinterpret_cast<void (*)(void **)>(g_ecma_throw_from_machine_code_block->address); #endif // DUMP_TRAMPOLINE_CODE_VECTORS } #ifdef DEBUG_ENABLE_OPASSERT /* static */ BOOL ES_Native::IsAddressInBytecodeToNativeTrampoline(void *address) { #if !defined DUMP_TRAMPOLINE_CODE_VECTORS && defined CONSTANT_DATA_IS_EXECUTABLE if (ES_CodeGenerator::SupportsVFP()) return reinterpret_cast<unsigned *>(address) >= cv_BytecodeToNativeTrampoline_vfp && reinterpret_cast<unsigned *>(address) < cv_BytecodeToNativeTrampoline_vfp + ARRAY_SIZE(cv_BytecodeToNativeTrampoline); else return reinterpret_cast<unsigned *>(address) >= cv_BytecodeToNativeTrampoline && reinterpret_cast<unsigned *>(address) < cv_BytecodeToNativeTrampoline + ARRAY_SIZE(cv_BytecodeToNativeTrampoline); #else // !DUMP_TRAMPOLINE_CODE_VECTORS && CONSTANT_DATA_IS_EXECUTABLE return TRUE; #endif // !DUMP_TRAMPOLINE_CODE_VECTORS && CONSTANT_DATA_IS_EXECUTABLE } #endif // DEBUG_ENABLE_OPASSERT void ES_Native::UpdateCode(ES_Code *new_code) { code = new_code; OP_ASSERT(c_code == NULL); } /* The limitation checked for here is the LDR/STR instruction, used to load/store words from memory, which has an immediate offset range of +/- 4096. With a pointer to register zero in a native register, we can easily access the first 512 virtual registers, but beyond that we need to calculate an offset into a second native register to use as an offset each and every time we access such a virtual register. Not worth the effort. (Of course, we could extend the range to 1024 virtual registers by adding 4096 to the register frame pointer and using negative offsets for the first 512 registers, but the number of functions with 513-1024 registers, that is interesting to JIT in the first place, is probably quite close to zero.) */ BOOL ES_Native::CheckLimits() { if (!ES_CodeGenerator::SupportedOffset(code->data->register_frame_size * sizeof(ES_Value_Internal))) return FALSE; return TRUE; } void ES_Native::InitializeNativeRegisters() { integer_registers_count = ARM_INTEGER_REGISTER_COUNT; double_registers_count = ARCHITECTURE_HAS_FPU() ? ARM_DOUBLE_REGISTER_COUNT : 0; native_registers_count = integer_registers_count + double_registers_count; native_registers = OP_NEWGROA_L(NativeRegister, native_registers_count, Arena()); for (unsigned index = 0; index < native_registers_count; ++index) { NativeRegister &native_register = native_registers[index]; native_register.first_allocation = native_register.last_allocation = native_register.current_allocation = native_register.previous_allocation = NULL; native_register.type = index < integer_registers_count ? NativeRegister::TYPE_INTEGER : NativeRegister::TYPE_DOUBLE; } native_registers[ARM_REGISTER_INDEX_R2].register_code = ARM_REGISTER_CODE_R2; native_registers[ARM_REGISTER_INDEX_R3].register_code = ARM_REGISTER_CODE_R3; native_registers[ARM_REGISTER_INDEX_R4].register_code = ARM_REGISTER_CODE_R4; native_registers[ARM_REGISTER_INDEX_R5].register_code = ARM_REGISTER_CODE_R5; native_registers[ARM_REGISTER_INDEX_R6].register_code = ARM_REGISTER_CODE_R6; native_registers[ARM_REGISTER_INDEX_R7].register_code = ARM_REGISTER_CODE_R7; native_registers[ARM_REGISTER_INDEX_R8].register_code = ARM_REGISTER_CODE_R8; #ifdef ARCHITECTURE_ARM_VFP if (ARCHITECTURE_HAS_FPU()) { native_registers[ARM_REGISTER_INDEX_D2].register_code = ARM_REGISTER_CODE_D2; native_registers[ARM_REGISTER_INDEX_D3].register_code = ARM_REGISTER_CODE_D3; native_registers[ARM_REGISTER_INDEX_D4].register_code = ARM_REGISTER_CODE_D4; native_registers[ARM_REGISTER_INDEX_D5].register_code = ARM_REGISTER_CODE_D5; native_registers[ARM_REGISTER_INDEX_D6].register_code = ARM_REGISTER_CODE_D6; native_registers[ARM_REGISTER_INDEX_D7].register_code = ARM_REGISTER_CODE_D7; native_registers[ARM_REGISTER_INDEX_D8].register_code = ARM_REGISTER_CODE_D8; native_registers[ARM_REGISTER_INDEX_D9].register_code = ARM_REGISTER_CODE_D9; native_registers[ARM_REGISTER_INDEX_D10].register_code = ARM_REGISTER_CODE_D10; native_registers[ARM_REGISTER_INDEX_D11].register_code = ARM_REGISTER_CODE_D11; native_registers[ARM_REGISTER_INDEX_D12].register_code = ARM_REGISTER_CODE_D12; native_registers[ARM_REGISTER_INDEX_D13].register_code = ARM_REGISTER_CODE_D13; native_registers[ARM_REGISTER_INDEX_D14].register_code = ARM_REGISTER_CODE_D14; native_registers[ARM_REGISTER_INDEX_D15].register_code = ARM_REGISTER_CODE_D15; } #endif // ARCHITECTURE_ARM_VFP } static void SetupNativeStackFrame(ES_Native *nc, ES_Code *code, unsigned &stack_space_allocated, unsigned &stack_frame_padding, BOOL &has_variable_object, BOOL entry_point = FALSE) { ES_CodeGenerator &cg = nc->cg; unsigned local_stack_space_allocated = 0; DECLARE_NOTHING(); /* Push previous frame pointer and record new one. */ cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, native_stack_frame), ES_CodeGenerator::REG_R4); cg.PUSH(1 << ES_CodeGenerator::REG_R4 | 1 << ES_CodeGenerator::REG_LR); cg.STR(ES_CodeGenerator::REG_SP, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, native_stack_frame)); local_stack_space_allocated += sizeof(void *); if (!nc->c_code) nc->c_code = cg.NewConstant(code); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R8); cg.LDR(nc->c_code, ES_CodeGenerator::REG_R7); unsigned registers(1 << ES_CodeGenerator::REG_R8 | 1 << ES_CodeGenerator::REG_R7); local_stack_space_allocated += 2 * sizeof(void *); if (code->type == ES_Code::TYPE_FUNCTION) { if (entry_point) { cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, arguments_object), ES_CodeGenerator::REG_R6); cg.MOV(0, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, arguments_object)); } else cg.MOV(0, ES_CodeGenerator::REG_R6); registers |= 1 << ES_CodeGenerator::REG_R6; local_stack_space_allocated += sizeof(void *); has_variable_object = code->CanHaveVariableObject(); if (has_variable_object) { if (entry_point) { cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, variable_object), ES_CodeGenerator::REG_R5); cg.MOV(0, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, variable_object)); } else cg.MOV(0, ES_CodeGenerator::REG_R5); registers |= 1 << ES_CodeGenerator::REG_R5; local_stack_space_allocated += sizeof(void *); } cg.MOV(PARAMETERS_COUNT, ES_CodeGenerator::REG_R4); registers |= 1 << ES_CodeGenerator::REG_R4; local_stack_space_allocated += sizeof(void *); } else has_variable_object = FALSE; cg.PUSH(registers); if (((local_stack_space_allocated + sizeof(void *)) & sizeof(void *)) != 0) { cg.SUB(ES_CodeGenerator::REG_SP, 4, ES_CodeGenerator::REG_SP); local_stack_space_allocated += stack_frame_padding = sizeof(void *); } else stack_frame_padding = 0; if (!entry_point) stack_space_allocated = local_stack_space_allocated; } void ES_Native::EmitRegisterTypeCheck(VirtualRegister *source, ES_ValueType value_type, ES_CodeGenerator::JumpTarget *slow_case, BOOL invert_result) { OP_ASSERT((property_value_fail && property_value_fail == slow_case) || property_value_needs_type_check || property_value_read_vr == NULL || property_value_read_vr != source); OP_ASSERT(source->stack_frame_offset == INT_MAX); if (!slow_case) { if (!current_slow_case) EmitSlowCaseCall(); slow_case = current_slow_case->GetJumpTarget(); } if (property_value_read_vr == source && property_value_nr && !property_value_fail) LoadOffset(cg, INTEGER_REGISTER(property_value_nr), property_value_offset + VALUE_TYPE_OFFSET, SCRATCHI1); else cg.LDR(BASE_REGISTER(source), TYPE_OFFSET(source), SCRATCHI1); if (value_type == ESTYPE_INT32_OR_DOUBLE) { cg.CMP(SCRATCHI1, ESTYPE_INT32); cg.Jump(slow_case, invert_result ? ES_NATIVE_CONDITION_LESS_OR_EQUAL : ES_NATIVE_CONDITION_GREATER); } else if (value_type == ESTYPE_DOUBLE) { cg.CMP(SCRATCHI1, ESTYPE_DOUBLE); cg.Jump(slow_case, invert_result ? ES_NATIVE_CONDITION_LESS_OR_EQUAL : ES_NATIVE_CONDITION_GREATER); } else { cg.CMP(SCRATCHI1, value_type); cg.Jump(slow_case, invert_result ? ES_NATIVE_CONDITION_EQUAL : ES_NATIVE_CONDITION_NOT_EQUAL); } } void ES_Native::EmitLoadRegisterValue(NativeRegister *target, VirtualRegister *source, ES_CodeGenerator::JumpTarget *type_check_fail) { if (source->stack_frame_offset != INT_MAX) { OP_ASSERT((target->type == NativeRegister::TYPE_INTEGER && (source->stack_frame_type == ESTYPE_INT32 || source->stack_frame_type == ESTYPE_BOOLEAN)) || source->stack_frame_type == ESTYPE_DOUBLE); type_check_fail = NULL; } if (target->type == NativeRegister::TYPE_INTEGER) { if (type_check_fail) EmitRegisterTypeCheck(source, ESTYPE_INT32, type_check_fail); cg.LDR(BASE_REGISTER(source), IVALUE_OFFSET(source), INTEGER_REGISTER(target)); } #ifdef ARCHITECTURE_ARM_VFP if (target->type == NativeRegister::TYPE_DOUBLE) { if (type_check_fail) { LoadValue(cg, source, SCRATCHI1, SCRATCHI2); cg.CMP(SCRATCHI_TYPE, ESTYPE_DOUBLE); cg.Jump(type_check_fail, ES_NATIVE_CONDITION_GREATER); cg.FMDRR(SCRATCHI_TYPE, SCRATCHI_IVALUE, DOUBLE_REGISTER(target)); } else cg.FLDD(BASE_REGISTER(source), DVALUE_OFFSET(source), DOUBLE_REGISTER(target)); } #endif // ARCHITECTURE_ARM_VFP } BOOL ES_Native::IsComplexStore(VirtualRegister *target, NativeRegister *source) { #ifdef ARCHITECTURE_ARM_VFP return (source->type == NativeRegister::TYPE_DOUBLE && target->stack_frame_offset == INT_MAX); #else return FALSE; #endif // ARCHITECTURE_ARM_VFP } void ES_Native::EmitSaveCondition() { #ifdef ARCHITECTURE_ARM_VFP if (is_light_weight) cg.STR(ES_CodeGenerator::REG_LR, ES_CodeGenerator::REG_SP, -4); cg.MRS(ES_CodeGenerator::REG_LR); #endif // ARCHITECTURE_ARM_VFP } void ES_Native::EmitRestoreCondition() { #ifdef ARCHITECTURE_ARM_VFP cg.MSR(ES_CodeGenerator::REG_LR, FALSE, FALSE, FALSE, TRUE); if (is_light_weight) cg.LDR(ES_CodeGenerator::REG_SP, -4, ES_CodeGenerator::REG_LR); #endif // ARCHITECTURE_ARM_VFP } void ES_Native::EmitStoreRegisterValue(VirtualRegister *target, NativeRegister *source, BOOL write_type, BOOL saved_condition) { if (target->stack_frame_offset != INT_MAX) { OP_ASSERT(target->stack_frame_type == (source->type == NativeRegister::TYPE_INTEGER ? ESTYPE_INT32 : ESTYPE_DOUBLE)); write_type = FALSE; } if (source->type == NativeRegister::TYPE_INTEGER) { cg.STR(INTEGER_REGISTER(source), BASE_REGISTER(target), IVALUE_OFFSET(target)); if (write_type) { cg.MOV(ESTYPE_INT32, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES); cg.STR(SCRATCHI1, REGISTER_FRAME_POINTER, TYPE_OFFSET(target)); } } #ifdef ARCHITECTURE_ARM_VFP if (source->type == NativeRegister::TYPE_DOUBLE) { if (target->stack_frame_offset == INT_MAX) { ES_CodeGenerator::Register type(SCRATCHI_TYPE), value(SCRATCHI_IVALUE); cg.FMRRD(DOUBLE_REGISTER(source), type, value); cg.CMP(type, ESTYPE_DOUBLE); cg.MOV(ESTYPE_DOUBLE, type, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_GREATER); StoreValue(cg, SCRATCHI1, SCRATCHI2, target); } else cg.FSTD(DOUBLE_REGISTER(source), BASE_REGISTER(target), DVALUE_OFFSET(target)); } #endif // ARCHITECTURE_ARM_VFP } void ES_Native::EmitStoreGlobalObject(VirtualRegister *target_vr) { if (!c_global_object) c_global_object = cg.NewConstant(code->global_object); cg.LDR(c_global_object, SCRATCHI_IVALUE); cg.MOV(ESTYPE_OBJECT, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } void ES_Native::EmitStoreConstantBoolean(VirtualRegister *target_vr, BOOL value) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(value ? 1 : 0, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } void ES_Native::EmitConvertRegisterValue(NativeRegister *target, VirtualRegister *source, unsigned handled, unsigned possible, ES_CodeGenerator::JumpTarget *slow_case) { if (target->type == NativeRegister::TYPE_INTEGER) { ES_CodeGenerator::JumpTarget *is_integer = NULL, *is_finished = NULL; if (handled == ESTYPE_BITS_DOUBLE) { if (handled != possible) EmitRegisterTypeCheck(source, ESTYPE_DOUBLE, slow_case); } else { cg.LDR(BASE_REGISTER(source), TYPE_OFFSET(source), SCRATCHI1); if ((handled & ESTYPE_BITS_INT32) != 0) { is_integer = cg.ForwardJump(); cg.CMP(SCRATCHI1, ESTYPE_INT32); cg.Jump(is_integer, ES_NATIVE_CONDITION_EQUAL); } if ((handled & ESTYPE_BITS_NULL) != 0) { if (!is_finished) is_finished = cg.ForwardJump(); cg.CMP(SCRATCHI1, ESTYPE_NULL); cg.MOV(0, INTEGER_REGISTER(target), ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); cg.Jump(is_finished, ES_NATIVE_CONDITION_EQUAL); } if ((handled & ESTYPE_BITS_UNDEFINED) != 0) { if (!is_finished) is_finished = cg.ForwardJump(); cg.CMP(SCRATCHI1, ESTYPE_UNDEFINED); cg.MOV(0, INTEGER_REGISTER(target), ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); cg.Jump(is_finished, ES_NATIVE_CONDITION_EQUAL); } if ((handled & ESTYPE_BITS_DOUBLE) != 0) { if (handled != possible) { cg.CMP(SCRATCHI1, ESTYPE_DOUBLE); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); } } else if (handled != possible) cg.Jump(slow_case); } if ((handled & ESTYPE_BITS_DOUBLE) != 0) { cg.FLDD(BASE_REGISTER(source), DVALUE_OFFSET(source), SCRATCHD1); cg.FTOSIZD(SCRATCHD1, SCRATCHS1); cg.FMRS(SCRATCHS1, INTEGER_REGISTER(target)); cg.CMP(INTEGER_REGISTER(target), INT_MAX); cg.CMP(INTEGER_REGISTER(target), INT_MIN, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); if (is_integer) { if (!is_finished) is_finished = cg.ForwardJump(); cg.Jump(is_finished); } } if (is_integer) { cg.SetJumpTarget(is_integer); cg.LDR(BASE_REGISTER(source), IVALUE_OFFSET(source), INTEGER_REGISTER(target)); } if (is_finished) cg.SetJumpTarget(is_finished); } #ifdef ARCHITECTURE_ARM_VFP if (target->type == NativeRegister::TYPE_DOUBLE) { LoadValue(cg, source, SCRATCHI1, SCRATCHI2); if (handled == ESTYPE_BITS_INT32) { if (handled != possible) { cg.CMP(SCRATCHI_TYPE, ESTYPE_INT32); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } cg.FMSR(SCRATCHI_IVALUE, SCRATCHS1); cg.FSITOD(SCRATCHS1, DOUBLE_REGISTER(target)); } else { if (handled == (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE) && handled == possible) { cg.CMP(SCRATCHI_TYPE, ESTYPE_INT32); cg.FMSR(SCRATCHI_IVALUE, SCRATCHS1, ES_NATIVE_CONDITION_EQUAL); cg.FSITOD(SCRATCHS1, DOUBLE_REGISTER(target), ES_NATIVE_CONDITION_EQUAL); cg.FMDRR(SCRATCHI_TYPE, SCRATCHI_IVALUE, DOUBLE_REGISTER(target), ES_NATIVE_CONDITION_NOT_EQUAL); } else { ES_CodeGenerator::JumpTarget *is_finished = NULL, *load_existing = NULL; if ((handled & ESTYPE_BITS_INT32) != 0) { is_finished = cg.ForwardJump(); cg.CMP(SCRATCHI_TYPE, ESTYPE_INT32); cg.FMSR(SCRATCHI_IVALUE, SCRATCHS1, ES_NATIVE_CONDITION_EQUAL); cg.FSITOD(SCRATCHS1, DOUBLE_REGISTER(target), ES_NATIVE_CONDITION_EQUAL); cg.Jump(is_finished, ES_NATIVE_CONDITION_EQUAL); } if ((handled & ESTYPE_BITS_UNDEFINED) != 0) { if (!load_existing) load_existing = cg.ForwardJump(); cg.CMP(SCRATCHI_TYPE, ESTYPE_UNDEFINED); cg.Jump(load_existing, ES_NATIVE_CONDITION_EQUAL); } if ((handled & ESTYPE_BITS_NULL) != 0) { if (!load_existing) load_existing = cg.ForwardJump(); cg.CMP(SCRATCHI1, ESTYPE_NULL); cg.Jump(load_existing, ES_NATIVE_CONDITION_EQUAL); } if (handled != possible) { cg.CMP(SCRATCHI_TYPE, ESTYPE_DOUBLE); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); } if (load_existing) cg.SetJumpTarget(load_existing); cg.FMDRR(SCRATCHI_TYPE, SCRATCHI_IVALUE, DOUBLE_REGISTER(target)); if (is_finished) cg.SetJumpTarget(is_finished); } } } #endif // ARCHITECTURE_ARM_VFP } void ES_Native::EmitSetRegisterType(VirtualRegister *target, ES_ValueType type) { if (type != ESTYPE_DOUBLE) { cg.MOV(type, SCRATCHI1); cg.STR(SCRATCHI1, BASE_REGISTER(target), TYPE_OFFSET(target)); } } void ES_Native::EmitSetRegisterValue(VirtualRegister *target, const ES_Value_Internal &value, BOOL write_type, BOOL saved_condition) { if (target->stack_frame_offset != INT_MAX) write_type = FALSE; if (value.IsDouble()) { unsigned high, low; op_explode_double(value.GetDouble(), high, low); MoveImmediateToRegister(cg, high, SCRATCHI_TYPE); MoveImmediateToRegister(cg, low, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target); } else if (value.IsUndefined() || value.IsNull()) EmitSetRegisterType(target, value.Type()); else { if (write_type) cg.MOV(value.Type(), SCRATCHI_TYPE); if (value.IsInt32()) MoveImmediateToRegister(cg, value.GetInt32(), SCRATCHI_IVALUE); else if (value.IsBoolean()) cg.MOV(value.GetBoolean(), SCRATCHI_IVALUE); else if (value.IsString() || value.IsObject()) { ES_CodeGenerator::Constant *constant = cg.NewConstant(value.GetDecodedBoxed()); cg.LDR(constant, SCRATCHI_IVALUE); } if (write_type) StoreValue(cg, SCRATCHI1, SCRATCHI2, target); else cg.STR(SCRATCHI_IVALUE, BASE_REGISTER(target), IVALUE_OFFSET(target)); } } void ES_Native::EmitSetRegisterValueFromStackFrameStorage(VirtualRegister *target) { if (target->stack_frame_type == ESTYPE_DOUBLE) { LoadValue(cg, target, SCRATCHI1, SCRATCHI2); cg.CMP(SCRATCHI_TYPE, ESTYPE_DOUBLE); cg.MOV(ESTYPE_DOUBLE, SCRATCHI_TYPE, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_GREATER); } else { cg.MOV(target->stack_frame_type, SCRATCHI_TYPE); cg.LDR(BASE_REGISTER(target), IVALUE_OFFSET(target), SCRATCHI_IVALUE); } target->stack_frame_offset = INT_MAX; StoreValue(cg, SCRATCHI1, SCRATCHI2, target); } void ES_Native::EmitRegisterCopy(const Operand &source, const Operand &target, ES_CodeGenerator::JumpTarget *slow_case) { if (source.native_register && target.virtual_register) EmitStoreRegisterValue(target.virtual_register, source.native_register, TRUE); else if (source.virtual_register && target.native_register) if (source.codeword) { OP_ASSERT(target.native_register->type == NativeRegister::TYPE_INTEGER); MoveImmediateToRegister(cg, source.codeword->immediate, INTEGER_REGISTER(target)); } else EmitLoadRegisterValue(target.native_register, source.virtual_register, NULL); else if (source.codeword) EmitRegisterInt32Assign(source, target); else if (source.native_register && target.native_register) if (target.native_register->type == NativeRegister::TYPE_DOUBLE) if (source.native_register->type == NativeRegister::TYPE_INTEGER) { cg.FMSR(INTEGER_REGISTER(source.native_register), SCRATCHS1); cg.FSITOD(SCRATCHS1, DOUBLE_REGISTER(target.native_register)); } else cg.FCPYD(DOUBLE_REGISTER(source.native_register), DOUBLE_REGISTER(target)); else if (source.native_register->type == NativeRegister::TYPE_INTEGER) cg.MOV(INTEGER_REGISTER(source.native_register), INTEGER_REGISTER(target)); else { OP_ASSERT(slow_case); cg.FTOSIZD(DOUBLE_REGISTER(source.native_register), SCRATCHS1); cg.FMRS(SCRATCHS1, INTEGER_REGISTER(target)); cg.CMP(INTEGER_REGISTER(target), INT_MAX); cg.CMP(INTEGER_REGISTER(target), INT_MIN, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); } else OP_ASSERT(FALSE); } void ES_Native::EmitRegisterCopy(VirtualRegister *source, VirtualRegister *target) { OP_ASSERT(source->stack_frame_offset == INT_MAX); OP_ASSERT(target->stack_frame_offset == INT_MAX); CopyValue(cg, source, target); } void ES_Native::EmitRegisterInt32Copy(VirtualRegister *source, VirtualRegister *target) { cg.MOV(ESTYPE_INT32, SCRATCHI1); cg.STR(SCRATCHI1, BASE_REGISTER(target), TYPE_OFFSET(target)); cg.LDR(BASE_REGISTER(source), IVALUE_OFFSET(source), SCRATCHI2); cg.STR(SCRATCHI2, BASE_REGISTER(target), IVALUE_OFFSET(target)); } void ES_Native::EmitRegisterInt32Assign(const Operand &source, const Operand &target) { OP_ASSERT(source.codeword); ES_CodeGenerator::Register itarget; if (target.native_register && target.native_register->type == NativeRegister::TYPE_INTEGER) itarget = INTEGER_REGISTER(target); else itarget = SCRATCHI1; MoveImmediateToRegister(cg, source.codeword->immediate, itarget); if (target.native_register) if (target.native_register->type == NativeRegister::TYPE_INTEGER) return; else { cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOD(SCRATCHS1, DOUBLE_REGISTER(target)); } else { cg.STR(SCRATCHI1, BASE_REGISTER(target), IVALUE_OFFSET(target.virtual_register)); EmitSetRegisterType(target.virtual_register, ESTYPE_INT32); } } void ES_Native::EmitRegisterInt32Assign(int source, NativeRegister *target) { MoveImmediateToRegister(cg, source, INTEGER_REGISTER(target)); } void ES_Native::EmitRegisterDoubleAssign(const double *value, const Operand &target) { if (target.native_register) { ES_CodeGenerator::Constant *constant = cg.NewConstant(*value); cg.FLDD(constant, DOUBLE_REGISTER(target)); } else if (op_isnan(*value)) { cg.MOV(ESTYPE_DOUBLE, SCRATCHI1); cg.STR(SCRATCHI1, BASE_REGISTER(target), TYPE_OFFSET(target.virtual_register)); } else { unsigned high, low; op_explode_double(*value, high, low); MoveImmediateToRegister(cg, high, SCRATCHI_TYPE); MoveImmediateToRegister(cg, low, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target.virtual_register); } } void ES_Native::EmitRegisterStringAssign(JString *value, const Operand &target) { ES_CodeGenerator::Constant *constant = cg.NewConstant(value); if (target.native_register) cg.LDR(constant, INTEGER_REGISTER(target)); else { cg.MOV(ESTYPE_STRING, SCRATCHI_TYPE); cg.LDR(constant, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target.virtual_register); } } void ES_Native::EmitToPrimitive(VirtualRegister *source) { if (!current_slow_case) EmitSlowCaseCall(); cg.LDR(BASE_REGISTER(source), TYPE_OFFSET(source), SCRATCHI1); cg.CMP(SCRATCHI1, ESTYPE_OBJECT); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); } void ES_Native::EmitInstructionHandlerCall() { if (is_light_weight) LEAVE(OpStatus::ERR); ES_CodeWord *word = CurrentCodeWord(); ES_Instruction instruction = word->instruction; if (instruction == ESI_TOPRIMITIVE) instruction = ESI_TOPRIMITIVE1; if (word == entry_point_cw && !entry_point_jump_target) entry_point_jump_target = EmitEntryPoint(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (current_slow_case) { OpString annotation; annotation.AppendL(" from EmitInstructionHandlerCall() for "); annotation.AppendL(annotator.GetInstructionName(word->instruction)); annotation.AppendFormat(UNI_L(" (cw_index=%u):\n"), cw_index); cg.Annotate(annotation.CStr()); } #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT switch (instruction) { case ESI_EVAL: case ESI_CALL: case ESI_CONSTRUCT: { ES_CodeGenerator::Constant *constant; if (word->instruction == ESI_EVAL || word->instruction == ESI_CALL) constant = c_CallFromMachineCode ? c_CallFromMachineCode : c_CallFromMachineCode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::CallFromMachineCode)); else constant = c_ConstructFromMachineCode ? c_ConstructFromMachineCode : c_ConstructFromMachineCode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ConstructFromMachineCode)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(constant, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); } break; case ESI_GETN_IMM: case ESI_GET_LENGTH: case ESI_PUTN_IMM: case ESI_INIT_PROPERTY: { ES_CodeGenerator::Constant *constant; if (instruction == ESI_GETN_IMM || instruction == ESI_GET_LENGTH) { if (!c_GetNamedImmediate) c_GetNamedImmediate = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::GetNamedImmediate)); constant = c_GetNamedImmediate; } else { if (!c_PutNamedImmediate) c_PutNamedImmediate = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::PutNamedImmediate)); constant = c_PutNamedImmediate; } cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(constant, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); } break; case ESI_GET_GLOBAL: case ESI_PUT_GLOBAL: { ES_CodeGenerator::Constant *constant; if (instruction == ESI_GET_GLOBAL) if (code->global_caches[word[3].index].class_id == ES_Class::GLOBAL_IMMEDIATE_CLASS_ID) { if (!c_GetGlobalImmediate) c_GetGlobalImmediate = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::GetGlobalImmediate)); constant = c_GetGlobalImmediate; } else { if (!c_GetGlobal) c_GetGlobal = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::GetGlobal)); constant = c_GetGlobal; } else { if (!c_PutGlobal) c_PutGlobal = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::PutGlobal)); constant = c_PutGlobal; } cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(constant, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); } break; case ESI_REDIRECTED_CALL: { DECLARE_NOTHING(); cg.MOV(constructor ? 1 : 0, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, in_constructor)); } default: { DECLARE_NOTHING(); if (!c_codewords) c_codewords = cg.NewConstant(code->data->codewords); cg.LDR(c_codewords, ES_CodeGenerator::REG_R1); AddImmediateToRegister(cg, (cw_index + 1) * sizeof(ES_CodeWord), ES_CodeGenerator::REG_R1); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(GetInstructionHandler(word->instruction), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); /* Clear the in_constructor flag set prior to call */ if (instruction == ESI_REDIRECTED_CALL && constructor) { cg.MOV(0, SCRATCHI2); cg.STR(SCRATCHI2, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, in_constructor)); } switch (word->instruction) { case ESI_GET: case ESI_GETI_IMM: case ESI_PUT: case ESI_PUTI_IMM: { if (!c_UpdateNativeDispatcher) c_UpdateNativeDispatcher = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::UpdateNativeDispatcher)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, code->data->instruction_offsets[instruction_index + 1] + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(c_UpdateNativeDispatcher, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); } } } break; } } void ES_Native::EmitSlowCaseCall(BOOL failed_inlined_function) { if (is_light_weight) { if (!light_weight_failure) EmitLightWeightFailure(); current_slow_case = light_weight_failure; } else { current_slow_case = cg.StartOutOfOrderBlock(); #ifdef ES_SLOW_CASE_PROFILING extern BOOL g_slow_case_summary; if (g_slow_case_summary) { MovePointerToRegister(cg, context->rt_data->slow_case_calls + CurrentCodeWord()->instruction, SCRATCHI1); cg.LDR(SCRATCHI1, 0, SCRATCHI2); cg.ADD(SCRATCHI2, 1, SCRATCHI2); cg.STR(SCRATCHI2, SCRATCHI1, 0); } #endif // ES_SLOW_CASE_PROFILING if (property_value_read_vr && property_value_nr) { CopyTypedDataToValue(cg, INTEGER_REGISTER(property_value_nr), property_value_offset, property_value_needs_type_check ? ES_STORAGE_WHATEVER : ES_STORAGE_OBJECT, property_value_read_vr); current_slow_case_main = cg.Here(); } else current_slow_case_main = NULL; if (failed_inlined_function) { DECLARE_NOTHING(); if (!c_code) c_code = cg.NewConstant(code); cg.MOV(1, SCRATCHI1); cg.LDR(c_code, SCRATCHI2); cg.STR(SCRATCHI1, OBJECT_MEMBER(SCRATCHI2, ES_Code, has_failed_inlined_function)); } EmitInstructionHandlerCall(); cg.EndOutOfOrderBlock(); } if (property_value_fail) { cg.StartOutOfOrderBlock(); cg.SetJumpTarget(property_value_fail); if (is_light_weight || current_slow_case_main == NULL) cg.Jump(current_slow_case->GetJumpTarget()); else cg.Jump(current_slow_case_main); cg.EndOutOfOrderBlock(FALSE); property_value_fail = NULL; } } void ES_Native::EmitLightWeightFailure() { if (!light_weight_failure) { light_weight_failure = cg.StartOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from EmitLightWeightFailure():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(fncode->GetData()->formals_count, PARAMETERS_COUNT); light_weight_wrong_argc = cg.Here(); BOOL has_variable_object; SetupNativeStackFrame(this, code, stack_space_allocated, stack_frame_padding, has_variable_object); ES_CodeGenerator::Constant *constant = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::LightWeightDispatcherFailure)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(constant, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.CMP(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); cg.ADD(ES_CodeGenerator::REG_SP, stack_space_allocated, ES_CodeGenerator::REG_SP); cg.POP(ES_CodeGenerator::REG_PC); cg.EndOutOfOrderBlock(FALSE); } } void ES_Native::EmitExecuteBytecode(unsigned start_instruction_index, unsigned end_instruction_index, BOOL last_in_slow_case) { if (!c_ExecuteBytecode) c_ExecuteBytecode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ExecuteBytecode)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, start_instruction_index, ES_CodeGenerator::REG_R1); if (constructor) MoveImmediateToRegister(cg, ~end_instruction_index, ES_CodeGenerator::REG_R2); else AddImmediateToRegister(cg, ES_CodeGenerator::REG_R1, end_instruction_index - start_instruction_index, ES_CodeGenerator::REG_R2); cg.LDR(c_ExecuteBytecode, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); } static BOOL IsMultipleOfTwo(int value) { return (value & (value - 1)) == 0; } static unsigned Log2(int value) { for (unsigned result = 1;; ++result) if (1 << result == value) return result; } void ES_Native::EmitInt32Arithmetic(Int32ArithmeticType type, const Operand &target, const Operand &lhs, const Operand &rhs, BOOL as_condition, ES_CodeGenerator::JumpTarget *overflow_target) { OP_ASSERT(target.native_register); OP_ASSERT(lhs.native_register || lhs.codeword); OP_ASSERT(rhs.native_register || rhs.codeword); OP_ASSERT(lhs.native_register || rhs.native_register); ES_CodeGenerator::SetConditionCodes set_condition_codes = (as_condition || overflow_target) ? ES_CodeGenerator::SET_CONDITION_CODES : ES_CodeGenerator::UNSET_CONDITION_CODES; ES_CodeGenerator::Register rtarget = INTEGER_REGISTER(target); ES_CodeGenerator::Register rlhs, rrhs; const ES_CodeWord *lhs_codeword = lhs.codeword, *rhs_codeword = rhs.codeword; BOOL is_shift = type >= INT32ARITHMETIC_LSHIFT && type <= INT32ARITHMETIC_RSHIFT_UNSIGNED; if (lhs.native_register) rlhs = INTEGER_REGISTER(lhs); else if (!lhs_codeword) { UseInPlace(lhs.virtual_register); cg.LDR(BASE_REGISTER(lhs.virtual_register), IVALUE_OFFSET(lhs.virtual_register), SCRATCHI1); rlhs = SCRATCHI1; } else if (is_shift || !ES_CodeGenerator::Operand::EncodeImmediate(lhs_codeword->immediate)) { MoveImmediateToRegister(cg, lhs_codeword->immediate, SCRATCHI1); rlhs = SCRATCHI1; lhs_codeword = NULL; } if (rhs.native_register) rrhs = INTEGER_REGISTER(rhs); else if (!rhs_codeword) { UseInPlace(rhs.virtual_register); cg.LDR(BASE_REGISTER(rhs.virtual_register), IVALUE_OFFSET(rhs.virtual_register), SCRATCHI2); rrhs = SCRATCHI2; } else if (!ES_CodeGenerator::Operand::EncodeImmediate(rhs_codeword->immediate)) { MoveImmediateToRegister(cg, rhs_codeword->immediate, SCRATCHI2); rrhs = SCRATCHI2; rhs_codeword = NULL; } switch (type) { case INT32ARITHMETIC_LSHIFT: if (!rhs_codeword) { cg.AND(rrhs, 31, SCRATCHI2); cg.MOV(ES_CodeGenerator::NotOperand(rlhs, SCRATCHI2, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), rtarget, set_condition_codes); } else if (rhs_codeword->immediate == 0) cg.MOV(rlhs, rtarget, set_condition_codes); else cg.MOV(ES_CodeGenerator::NotOperand(rlhs, rhs_codeword->immediate & 31u, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), rtarget, set_condition_codes); break; case INT32ARITHMETIC_RSHIFT_SIGNED: if (!rhs_codeword) { cg.AND(rrhs, 31, SCRATCHI2); cg.MOV(ES_CodeGenerator::NotOperand(rlhs, SCRATCHI2, ES_CodeGenerator::SHIFT_ARITHMETIC_RIGHT), rtarget, set_condition_codes); } else if (rhs_codeword->immediate == 0) cg.MOV(rlhs, rtarget, set_condition_codes); else cg.MOV(ES_CodeGenerator::NotOperand(rlhs, rhs_codeword->immediate & 31u, ES_CodeGenerator::SHIFT_ARITHMETIC_RIGHT), rtarget, set_condition_codes); break; case INT32ARITHMETIC_RSHIFT_UNSIGNED: if (!rhs_codeword) { cg.AND(rrhs, 31, SCRATCHI2); cg.MOV(ES_CodeGenerator::NotOperand(rlhs, SCRATCHI2, ES_CodeGenerator::SHIFT_LOGICAL_RIGHT), rtarget, set_condition_codes); if (overflow_target) cg.Jump(overflow_target, ES_NATIVE_CONDITION_NEGATIVE); } else if (rhs_codeword->immediate == 0) { cg.MOV(rlhs, rtarget, set_condition_codes); if (overflow_target) cg.Jump(overflow_target, ES_NATIVE_CONDITION_NEGATIVE); } else cg.MOV(ES_CodeGenerator::NotOperand(rlhs, rhs_codeword->immediate & 31u, ES_CodeGenerator::SHIFT_LOGICAL_RIGHT), rtarget, set_condition_codes); break; case INT32ARITHMETIC_AND: if (!lhs_codeword && !rhs_codeword) cg.AND(rlhs, rrhs, rtarget, set_condition_codes); else if (rhs_codeword) cg.AND(rlhs, rhs_codeword->immediate, rtarget, set_condition_codes); else cg.AND(rrhs, lhs_codeword->immediate, rtarget, set_condition_codes); break; case INT32ARITHMETIC_OR: if (!lhs_codeword && !rhs_codeword) cg.ORR(rlhs, rrhs, rtarget, set_condition_codes); else if (rhs_codeword) cg.ORR(rlhs, rhs_codeword->immediate, rtarget, set_condition_codes); else cg.ORR(rrhs, lhs_codeword->immediate, rtarget, set_condition_codes); break; case INT32ARITHMETIC_XOR: if (!lhs_codeword && !rhs_codeword) cg.EOR(rlhs, rrhs, rtarget, set_condition_codes); else if (rhs_codeword) cg.EOR(rlhs, rhs_codeword->immediate, rtarget, set_condition_codes); else cg.EOR(rrhs, lhs_codeword->immediate, rtarget, set_condition_codes); break; case INT32ARITHMETIC_ADD: if (!lhs_codeword && !rhs_codeword) cg.ADD(rlhs, rrhs, rtarget, set_condition_codes); else if (rhs_codeword) cg.ADD(rlhs, rhs_codeword->immediate, rtarget, set_condition_codes); else cg.ADD(rrhs, lhs_codeword->immediate, rtarget, set_condition_codes); if (overflow_target) cg.Jump(overflow_target, ES_NATIVE_CONDITION_OVERFLOW); break; case INT32ARITHMETIC_SUB: if (!lhs_codeword && !rhs_codeword) cg.SUB(rlhs, rrhs, rtarget, set_condition_codes); else if (!lhs_codeword) cg.SUB(rlhs, rhs_codeword->immediate, rtarget, set_condition_codes); else cg.RSB(rrhs, lhs_codeword->immediate, rtarget, set_condition_codes); if (overflow_target) cg.Jump(overflow_target, ES_NATIVE_CONDITION_OVERFLOW); break; case INT32ARITHMETIC_MUL: if (lhs_codeword || rhs_codeword) { ES_CodeGenerator::Register src, dst = rtarget; int imm; if (!lhs_codeword) { src = rlhs; imm = rhs_codeword->immediate; } else { src = rrhs; imm = lhs_codeword->immediate; } if (imm == 0) { if (overflow_target) { cg.TST(src, src); cg.Jump(overflow_target, ES_NATIVE_CONDITION_NEGATIVE); } cg.MOV(0, dst, set_condition_codes); return; } else if (imm < 0) { if (overflow_target) { cg.TEQ(src, 0); cg.Jump(overflow_target, ES_NATIVE_CONDITION_EQUAL); } } else if (IsMultipleOfTwo(imm) || IsMultipleOfTwo(imm + 1)) { if (overflow_target) { CompareRegisterToImmediate(cg, src, INT_MAX / imm); cg.Jump(overflow_target, ES_NATIVE_CONDITION_GREATER); CompareRegisterToImmediate(cg, src, INT_MIN / imm); cg.Jump(overflow_target, ES_NATIVE_CONDITION_LESS); } if (IsMultipleOfTwo(imm)) cg.MOV(ES_CodeGenerator::Operand(src, Log2(imm)), dst, set_condition_codes); else cg.RSB(src, ES_CodeGenerator::Operand(src, Log2(imm + 1)), dst, set_condition_codes); return; } MoveImmediateToRegister(cg, imm, SCRATCHI1); cg.SMULL(src, SCRATCHI1, SCRATCHI1, dst); } else { if (overflow_target) { ES_CodeGenerator::JumpTarget *safe = cg.ForwardJump(); cg.CMP(rlhs, 0); cg.CMP(rrhs, 0, ES_NATIVE_CONDITION_LESS_OR_EQUAL); cg.Jump(safe, ES_NATIVE_CONDITION_GREATER); /* Both are either negative or zero. This check will catch the case of at least one being zero. It will "falsely" catch the case of both being zero too, but I'm fine with that. */ cg.TST(rlhs, rrhs); cg.Jump(overflow_target, ES_NATIVE_CONDITION_EQUAL); cg.SetJumpTarget(safe); } cg.SMULL(rlhs, rrhs, SCRATCHI1, rtarget); } if (overflow_target) { cg.CMP(SCRATCHI1, 0); cg.CMP(SCRATCHI1, -1, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(overflow_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.TEQ(SCRATCHI1, rtarget); cg.Jump(overflow_target, ES_NATIVE_CONDITION_NEGATIVE); } if (as_condition) cg.TST(rtarget, rtarget); break; case INT32ARITHMETIC_DIV: case INT32ARITHMETIC_REM: OP_ASSERT(rhs.virtual_register && rhs_codeword && IsMultipleOfTwo(rhs_codeword->immediate)); OP_ASSERT(overflow_target); ES_CodeGenerator::Register src = rlhs, dst = rtarget; int imm = rhs_codeword->immediate; if (type == INT32ARITHMETIC_DIV) { if (imm == 1) { if (src != dst || set_condition_codes == ES_CodeGenerator::SET_CONDITION_CODES) cg.MOV(src, dst, set_condition_codes); } else { /* Check if the result will be an integer. */ cg.TST(src, imm - 1); cg.Jump(overflow_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.MOV(ES_CodeGenerator::Operand(src, Log2(imm), ES_CodeGenerator::SHIFT_ARITHMETIC_RIGHT), dst, set_condition_codes); } } else { if (imm == 1) cg.MOV(0, dst, set_condition_codes); else cg.AND(src, imm - 1, dst, set_condition_codes); } } } void ES_Native::EmitInt32Complement(const Operand &target, const Operand &source, BOOL as_condition) { cg.MVN(INTEGER_REGISTER(source), INTEGER_REGISTER(target), as_condition ? ES_CodeGenerator::SET_CONDITION_CODES : ES_CodeGenerator::UNSET_CONDITION_CODES); } void ES_Native::EmitInt32Negate(const Operand &target, const Operand &source, BOOL as_condition, ES_CodeGenerator::JumpTarget *overflow_target) { ES_CodeGenerator::Register src(INTEGER_REGISTER(source)); ES_CodeGenerator::Register dst(INTEGER_REGISTER(target)); ES_CodeGenerator::Register use_dst; if (src == dst) use_dst = SCRATCHI1; else use_dst = dst; cg.RSB(src, 0, use_dst); /* Detect zero and INT_MIN cases: check if src and dst have the same sign; if they do, our negation obviously failed. */ cg.TEQ(src, use_dst); cg.Jump(overflow_target, ES_NATIVE_CONDITION_POSITIVE_OR_ZERO); if (dst != use_dst) cg.MOV(use_dst, dst); } void ES_Native::EmitInt32IncOrDec(BOOL inc, const Operand &target, ES_CodeGenerator::JumpTarget *overflow_target) { if (inc) cg.ADD(INTEGER_REGISTER(target), 1, INTEGER_REGISTER(target), overflow_target != NULL ? ES_CodeGenerator::SET_CONDITION_CODES : ES_CodeGenerator::UNSET_CONDITION_CODES); else cg.SUB(INTEGER_REGISTER(target), 1, INTEGER_REGISTER(target), overflow_target != NULL ? ES_CodeGenerator::SET_CONDITION_CODES : ES_CodeGenerator::UNSET_CONDITION_CODES); if (overflow_target) cg.Jump(overflow_target, ES_NATIVE_CONDITION_OVERFLOW); } void ES_Native::EmitInt32Relational(RelationalType relational_type, const Operand &lhs, const Operand &rhs, const Operand *value_target, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target, ArithmeticBlock *arithmetic_block) { OP_ASSERT(!true_target || !false_target); OP_ASSERT(lhs.native_register || rhs.native_register); if (lhs.native_register && rhs.native_register) cg.CMP(INTEGER_REGISTER(lhs), INTEGER_REGISTER(rhs)); else if (lhs.native_register) CompareRegisterToImmediate(cg, INTEGER_REGISTER(lhs), rhs.codeword->immediate); else { CompareRegisterToImmediate(cg, INTEGER_REGISTER(rhs), lhs.codeword->immediate); switch (relational_type) { case RELATIONAL_LT: relational_type = RELATIONAL_GT; break; case RELATIONAL_LTE: relational_type = RELATIONAL_GTE; break; case RELATIONAL_GT: relational_type = RELATIONAL_LT; break; case RELATIONAL_GTE: relational_type = RELATIONAL_LTE; break; } } if (value_target && value_target->virtual_register->stack_frame_offset == INT_MAX) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI1); if (value_target->virtual_register->stack_frame_offset == INT_MAX) cg.STR(SCRATCHI1, BASE_REGISTER(value_target->virtual_register), TYPE_OFFSET(value_target->virtual_register)); } ES_NativeJumpCondition true_condition, false_condition; switch (relational_type) { case RELATIONAL_EQ: true_condition = ES_NATIVE_CONDITION_EQUAL, false_condition = ES_NATIVE_CONDITION_NOT_EQUAL; break; case RELATIONAL_NEQ: true_condition = ES_NATIVE_CONDITION_NOT_EQUAL, false_condition = ES_NATIVE_CONDITION_EQUAL; break; case RELATIONAL_LT: true_condition = ES_NATIVE_CONDITION_LESS, false_condition = ES_NATIVE_CONDITION_GREATER_OR_EQUAL; break; case RELATIONAL_LTE: true_condition = ES_NATIVE_CONDITION_LESS_OR_EQUAL, false_condition = ES_NATIVE_CONDITION_GREATER; break; case RELATIONAL_GT: true_condition = ES_NATIVE_CONDITION_GREATER, false_condition = ES_NATIVE_CONDITION_LESS_OR_EQUAL; break; default: true_condition = ES_NATIVE_CONDITION_GREATER_OR_EQUAL, false_condition = ES_NATIVE_CONDITION_LESS; } ES_CodeGenerator::OutOfOrderBlock *trampoline = NULL; if ((true_target || false_target) && arithmetic_block && FlushToVirtualRegisters(arithmetic_block, TRUE)) { trampoline = cg.StartOutOfOrderBlock(); FlushToVirtualRegisters(arithmetic_block, FALSE, TRUE); if (true_target) { cg.Jump(true_target); true_target = trampoline->GetJumpTarget(); } else { cg.Jump(false_target); false_target = trampoline->GetJumpTarget(); } cg.EndOutOfOrderBlock(FALSE); } if (value_target) { cg.MOV(0, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES, false_condition); cg.MOV(1, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES, true_condition); cg.STR(SCRATCHI1, BASE_REGISTER(value_target->virtual_register), IVALUE_OFFSET(value_target->virtual_register)); } if (true_target) cg.Jump(true_target, true_condition); else if (false_target) cg.Jump(false_target, false_condition); if (trampoline) FlushToVirtualRegisters(arithmetic_block, FALSE, FALSE); } void ES_Native::EmitDoubleArithmetic(DoubleArithmeticType type, const Operand &target, const Operand &lhs, const Operand &rhs, BOOL as_condition) { OP_ASSERT(target.native_register); OP_ASSERT(lhs.native_register); OP_ASSERT(rhs.native_register); switch (type) { case DOUBLEARITHMETIC_ADD: cg.FADDD(DOUBLE_REGISTER(lhs), DOUBLE_REGISTER(rhs), DOUBLE_REGISTER(target)); break; case DOUBLEARITHMETIC_SUB: cg.FSUBD(DOUBLE_REGISTER(lhs), DOUBLE_REGISTER(rhs), DOUBLE_REGISTER(target)); break; case DOUBLEARITHMETIC_MUL: cg.FMULD(DOUBLE_REGISTER(lhs), DOUBLE_REGISTER(rhs), DOUBLE_REGISTER(target)); break; case DOUBLEARITHMETIC_DIV: cg.FDIVD(DOUBLE_REGISTER(lhs), DOUBLE_REGISTER(rhs), DOUBLE_REGISTER(target)); } if (as_condition) { cg.FCMPZD(DOUBLE_REGISTER(target)); cg.FMSTAT(); } } void ES_Native::EmitDoubleRelational(RelationalType relational_type, const Operand &lhs, const Operand &rhs, const Operand *value_target, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target, ArithmeticBlock *arithmetic_block) { OP_ASSERT(!true_target || !false_target); OP_ASSERT(lhs.native_register); OP_ASSERT(rhs.native_register); cg.FCMPD(DOUBLE_REGISTER(lhs), DOUBLE_REGISTER(rhs)); cg.FMSTAT(); if (value_target && value_target->virtual_register->stack_frame_offset == INT_MAX) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI1); if (value_target->virtual_register->stack_frame_offset == INT_MAX) cg.STR(SCRATCHI1, BASE_REGISTER(value_target->virtual_register), TYPE_OFFSET(value_target->virtual_register)); } ES_NativeJumpCondition true_condition, false_condition; switch (relational_type) { case RELATIONAL_EQ: true_condition = ES_NATIVE_CONDITION_EQUAL, false_condition = ES_NATIVE_CONDITION_NOT_EQUAL; break; case RELATIONAL_NEQ: true_condition = ES_NATIVE_CONDITION_NOT_EQUAL, false_condition = ES_NATIVE_CONDITION_EQUAL; break; case RELATIONAL_LT: true_condition = ES_NATIVE_CONDITION_LESS, false_condition = ES_NATIVE_CONDITION_GREATER_OR_EQUAL; break; case RELATIONAL_LTE: true_condition = ES_NATIVE_CONDITION_LESS_OR_EQUAL, false_condition = ES_NATIVE_CONDITION_GREATER; break; case RELATIONAL_GT: true_condition = ES_NATIVE_CONDITION_GREATER, false_condition = ES_NATIVE_CONDITION_LESS_OR_EQUAL; break; default: true_condition = ES_NATIVE_CONDITION_GREATER_OR_EQUAL, false_condition = ES_NATIVE_CONDITION_LESS; } ES_CodeGenerator::OutOfOrderBlock *trampoline = NULL; if ((true_target || false_target) && arithmetic_block && FlushToVirtualRegisters(arithmetic_block, TRUE)) { trampoline = cg.StartOutOfOrderBlock(); FlushToVirtualRegisters(arithmetic_block, FALSE, TRUE); if (true_target) { cg.Jump(true_target); true_target = trampoline->GetJumpTarget(); } else { cg.Jump(false_target); false_target = trampoline->GetJumpTarget(); } cg.EndOutOfOrderBlock(FALSE); } if (value_target) { cg.MOV(1, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES, true_condition); cg.MOV(0, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES, false_condition); if (true_condition == ES_NATIVE_CONDITION_LESS || true_condition == ES_NATIVE_CONDITION_LESS_OR_EQUAL) cg.MOV(0, SCRATCHI1, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_OVERFLOW); cg.STR(SCRATCHI1, BASE_REGISTER(value_target->virtual_register), IVALUE_OFFSET(value_target->virtual_register)); } ES_CodeGenerator::JumpTarget *skip_target = NULL; if (true_condition == ES_NATIVE_CONDITION_LESS || true_condition == ES_NATIVE_CONDITION_LESS_OR_EQUAL) if (true_target) cg.Jump(skip_target = cg.ForwardJump(), ES_NATIVE_CONDITION_OVERFLOW); else if (false_target) cg.Jump(false_target, ES_NATIVE_CONDITION_OVERFLOW); if (true_target) cg.Jump(true_target, true_condition); else if (false_target) cg.Jump(false_target, false_condition); if (skip_target) cg.SetJumpTarget(skip_target); if (trampoline) FlushToVirtualRegisters(arithmetic_block, FALSE, FALSE); } void ES_Native::EmitDoubleNegate(const Operand &target, const Operand &source, BOOL as_condition) { OP_ASSERT(target.native_register); OP_ASSERT(source.native_register); cg.FNEGD(DOUBLE_REGISTER(source), DOUBLE_REGISTER(target)); if (as_condition) { cg.FCMPZD(DOUBLE_REGISTER(target)); cg.FMSTAT(); } } void ES_Native::EmitDoubleIncOrDec(BOOL inc, const Operand &target) { OP_ASSERT(target.native_register); cg.MOV(inc ? 1 : -1, SCRATCHI1); cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOD(SCRATCHS1, SCRATCHD1); cg.FADDD(DOUBLE_REGISTER(target), SCRATCHD1, DOUBLE_REGISTER(target)); } void ES_Native::EmitNullOrUndefinedComparison(BOOL eq, VirtualRegister *vr, const Operand *value_target, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target) { ES_CodeGenerator::Register type(ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(vr), TYPE_OFFSET(vr), type); cg.CMP(type, ESTYPE_NULL); cg.CMP(type, ESTYPE_UNDEFINED, ES_NATIVE_CONDITION_NOT_EQUAL); if (value_target) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(eq ? 0 : 1, SCRATCHI_IVALUE, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_NOT_EQUAL); cg.MOV(eq ? 1 : 0, SCRATCHI_IVALUE, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); StoreValue(cg, SCRATCHI1, SCRATCHI2, value_target->virtual_register); } if (true_target) cg.Jump(true_target, eq ? ES_NATIVE_CONDITION_EQUAL : ES_NATIVE_CONDITION_NOT_EQUAL); else if (false_target) cg.Jump(false_target, eq ? ES_NATIVE_CONDITION_NOT_EQUAL : ES_NATIVE_CONDITION_EQUAL); } void ES_Native::EmitStrictNullOrUndefinedComparison(BOOL eq, VirtualRegister *vr, ES_ValueType type, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target) { cg.LDR(BASE_REGISTER(vr), TYPE_OFFSET(vr), SCRATCHI1); cg.CMP(SCRATCHI1, type); if (true_target) cg.Jump(true_target, eq ? ES_NATIVE_CONDITION_EQUAL : ES_NATIVE_CONDITION_NOT_EQUAL); else if (false_target) cg.Jump(false_target, eq ? ES_NATIVE_CONDITION_NOT_EQUAL : ES_NATIVE_CONDITION_EQUAL); } void ES_Native::EmitComparison(BOOL eq, BOOL strict, VirtualRegister *lhs_vr, VirtualRegister *rhs_vr, unsigned handled_types, const Operand *value_target, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target) { DECLARE_NOTHING(); if (!eq) { ES_CodeGenerator::JumpTarget *temporary = false_target; false_target = true_target; true_target = temporary; } ES_CodeGenerator::JumpTarget *use_true_target = true_target; ES_CodeGenerator::JumpTarget *use_false_target = false_target; if (value_target || !use_true_target) use_true_target = cg.ForwardJump(); if (value_target || !use_false_target) use_false_target = cg.ForwardJump(); ES_CodeGenerator::Register lhs_type(TYPE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5)); ES_CodeGenerator::Register lhs_value(IVALUE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5)); ES_CodeGenerator::Register rhs_type(TYPE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); ES_CodeGenerator::Register rhs_value(IVALUE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); LoadValue(cg, lhs_vr, ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5); LoadValue(cg, rhs_vr, ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7); ES_CodeGenerator::JumpTarget *jt_slow_case = cg.ForwardJump(); cg.CMP(lhs_type, rhs_type); cg.Jump(jt_slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); if (handled_types) { if (handled_types & (ESTYPE_BITS_NULL | ESTYPE_BITS_UNDEFINED)) { cg.CMP(lhs_type, ESTYPE_NULL); cg.CMP(lhs_type, ESTYPE_UNDEFINED, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_true_target, ES_NATIVE_CONDITION_EQUAL); } ES_CodeGenerator::JumpTarget *jt_next = NULL; if (handled_types & (ESTYPE_BITS_BOOLEAN | ESTYPE_BITS_INT32)) { jt_next = cg.ForwardJump(); if ((handled_types & (ESTYPE_BITS_BOOLEAN | ESTYPE_BITS_INT32)) == (ESTYPE_BITS_BOOLEAN | ESTYPE_BITS_INT32)) { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitComparison(): comparing ESTYPE_INT32+ESTYPE_BOOLEAN\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.CMP(lhs_type, ESTYPE_BOOLEAN); cg.CMP(lhs_type, ESTYPE_INT32, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(jt_next, ES_NATIVE_CONDITION_NOT_EQUAL); } else { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (handled_types & ESTYPE_BOOLEAN) cg.Annotate(UNI_L(" EmitComparison(): comparing ESTYPE_BOOLEAN\n")); else cg.Annotate(UNI_L(" EmitComparison(): comparing ESTYPE_INT32\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.CMP(lhs_type, (handled_types & ESTYPE_BOOLEAN) ? ESTYPE_BOOLEAN : ESTYPE_INT32); cg.Jump(jt_next, ES_NATIVE_CONDITION_NOT_EQUAL); } cg.TEQ(lhs_value, rhs_value); cg.Jump(use_true_target, ES_NATIVE_CONDITION_EQUAL); cg.Jump(use_false_target); } if (handled_types & ESTYPE_BITS_OBJECT) { if (jt_next) cg.SetJumpTarget(jt_next); jt_next = cg.ForwardJump(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitComparison(): comparing ESTYPE_OBJECT\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.CMP(lhs_type, ESTYPE_OBJECT); cg.Jump(jt_next, ES_NATIVE_CONDITION_NOT_EQUAL); cg.TEQ(lhs_value, rhs_value); cg.Jump(use_true_target, ES_NATIVE_CONDITION_EQUAL); ES_CodeGenerator::OutOfOrderBlock *compare_shifty_objects = cg.StartOutOfOrderBlock(); if (!c_CompareShiftyObjects) c_CompareShiftyObjects = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::CompareShiftyObjects)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(lhs_value, ES_CodeGenerator::REG_R1); cg.MOV(rhs_value, ES_CodeGenerator::REG_R2); cg.LDR(c_CompareShiftyObjects, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(use_true_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_false_target); cg.EndOutOfOrderBlock(FALSE); cg.LDR(OBJECT_MEMBER(lhs_value, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_MULTIPLE_IDENTITIES); cg.LDR(OBJECT_MEMBER(rhs_value, ES_Object, object_bits), SCRATCHI1, ES_NATIVE_CONDITION_EQUAL); cg.TST(SCRATCHI1, ES_Object::MASK_MULTIPLE_IDENTITIES, ES_NATIVE_CONDITION_EQUAL); cg.Jump(compare_shifty_objects->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_false_target); } if (handled_types & ESTYPE_BITS_STRING) { if (jt_next) cg.SetJumpTarget(jt_next); jt_next = cg.ForwardJump(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitComparison(): comparing ESTYPE_STRING\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.CMP(lhs_type, ESTYPE_STRING); cg.Jump(jt_next, ES_NATIVE_CONDITION_NOT_EQUAL); cg.TEQ(lhs_value, rhs_value); cg.Jump(use_true_target, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(lhs_value, JString, length), SCRATCHI1); cg.LDR(OBJECT_MEMBER(rhs_value, JString, length), SCRATCHI2); cg.TEQ(SCRATCHI1, SCRATCHI2); cg.Jump(use_false_target, ES_NATIVE_CONDITION_NOT_EQUAL); if (!c_Equals) c_Equals = cg.NewFunction(reinterpret_cast<void (*)()>(&Equals)); cg.MOV(lhs_value, ES_CodeGenerator::REG_R0); cg.MOV(rhs_value, ES_CodeGenerator::REG_R1); cg.LDR(c_Equals, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(use_true_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_false_target); } ES_CodeGenerator::OutOfOrderBlock *update; if (jt_next) { update = cg.StartOutOfOrderBlock(); cg.SetJumpTarget(jt_next); } else update = NULL; #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitComparison(): calling ES_Execution_Context::UpdateComparison\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (!c_UpdateComparison) c_UpdateComparison = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::UpdateComparison)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index, ES_CodeGenerator::REG_R1); cg.LDR(c_UpdateComparison, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.BX(ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_NOT_EQUAL); if (update) { cg.EndOutOfOrderBlock(); cg.SetOutOfOrderContinuationPoint(update); } } cg.SetJumpTarget(jt_slow_case); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (strict) cg.Annotate(UNI_L(" EmitComparison(): calling ES_Execution_Context::EqStrict\n")); else cg.Annotate(UNI_L(" EmitComparison(): calling ES_Execution_Context::EqFromMachineCode\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(rhs_vr), ES_CodeGenerator::REG_R2); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(lhs_vr), ES_CodeGenerator::REG_R1); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); if (strict) { if (!c_EqStrict) c_EqStrict = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::EqStrict)); cg.LDR(c_EqStrict, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } else { MoveImmediateToRegister(cg, cw_index, ES_CodeGenerator::REG_R3); if (!c_EqFromMachineCode) c_EqFromMachineCode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::EqFromMachineCode)); cg.LDR(c_EqFromMachineCode, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(use_true_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_false_target); if (value_target) { ES_CodeGenerator::JumpTarget *jt_when_true = true_target ? true_target : cg.ForwardJump(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitComparison(): storing result in value target\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.SetJumpTarget(use_true_target); cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(eq ? 1 : 0, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, value_target->virtual_register); cg.Jump(jt_when_true); cg.SetJumpTarget(use_false_target); cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(eq ? 0 : 1, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, value_target->virtual_register); if (false_target) cg.Jump(false_target); if (!true_target) cg.SetJumpTarget(jt_when_true); } else { if (!true_target) cg.SetJumpTarget(use_true_target); if (!false_target) cg.SetJumpTarget(use_false_target); } } void ES_Native::EmitInstanceOf(VirtualRegister *object_vr, VirtualRegister *constructor_vr, const Operand *value_target, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target) { DECLARE_NOTHING(); ES_CodeGenerator::JumpTarget *use_true_target = true_target; ES_CodeGenerator::JumpTarget *use_false_target = false_target; if (value_target || !true_target) use_true_target = cg.ForwardJump(); if (value_target || !false_target) use_false_target = cg.ForwardJump(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register constructor_type(TYPE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5)); ES_CodeGenerator::Register constructor(IVALUE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5)); /* right-hand side not an object => exception (because it must be a function, and ToObject() never produces a function) */ if (!IsType(constructor_vr, ESTYPE_OBJECT)) { LoadValue(cg, constructor_vr, ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5); cg.CMP(constructor_type, ESTYPE_OBJECT); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } else cg.LDR(BASE_REGISTER(constructor_vr), IVALUE_OFFSET(constructor_vr), constructor); ES_CodeGenerator::Register constructor_bits(constructor_type); cg.LDR(constructor, 0, constructor_bits); cg.AND(constructor_bits, ES_Header::MASK_GCTAG, constructor_bits); cg.TEQ(constructor_bits, GCTAG_ES_Object_Function); cg.TEQ(constructor_bits, GCTAG_ES_Object_RegExp_CTOR, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register object_type(TYPE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); ES_CodeGenerator::Register object(IVALUE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); if (!IsType(object_vr, ESTYPE_OBJECT)) { LoadValue(cg, object_vr, ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7); cg.CMP(object_type, ESTYPE_OBJECT); cg.Jump(use_false_target, ES_NATIVE_CONDITION_NOT_EQUAL); } else cg.LDR(BASE_REGISTER(object_vr), IVALUE_OFFSET(object_vr), object); ES_CodeGenerator::JumpTarget *simple_case = cg.ForwardJump(); ES_CodeGenerator::Register constructor_class(object_type); ES_CodeGenerator::Register constructor_class_id(ES_CodeGenerator::REG_R8); cg.LDR(OBJECT_MEMBER(constructor, ES_Object, klass), constructor_class); cg.LDR(OBJECT_MEMBER(constructor_class, ES_Class, class_id), constructor_class_id); CompareRegisterToImmediate(cg, constructor_class_id, code->global_object->GetNativeFunctionWithPrototypeClass()->GetId(context)); CompareRegisterToImmediate(cg, constructor_class_id, code->global_object->GetBuiltInConstructorClass()->GetId(context), ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(simple_case, ES_NATIVE_CONDITION_EQUAL); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(object, ES_CodeGenerator::REG_R1); cg.MOV(constructor, ES_CodeGenerator::REG_R2); EmitFunctionCall(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::InstanceOf))); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(use_true_target, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(use_false_target); cg.SetJumpTarget(simple_case); cg.LDR(OBJECT_MEMBER(constructor, ES_Object, properties), SCRATCHI1); ES_CodeGenerator::Register prototype_type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register prototype(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); LoadValue(cg, SCRATCHI1, ES_Function::GetPropertyOffset(ES_Function::PROTOTYPE), ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); cg.CMP(prototype_type, ESTYPE_OBJECT); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::JumpTarget *loop = cg.Here(); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), SCRATCHI1); cg.LDR(OBJECT_MEMBER(SCRATCHI1, ES_Class, static_data), SCRATCHI1); cg.LDR(OBJECT_MEMBER(SCRATCHI1, ES_Class_Data, prototype), object); cg.TEQ(object, prototype); cg.Jump(use_true_target, ES_NATIVE_CONDITION_EQUAL); cg.TEQ(object, 0); cg.Jump(loop, ES_NATIVE_CONDITION_NOT_EQUAL); if (use_false_target != false_target) { cg.SetJumpTarget(use_false_target); if (value_target) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(0, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, value_target->virtual_register); } } ES_CodeGenerator::JumpTarget *finished = NULL; if (false_target) cg.Jump(false_target); else cg.Jump(finished = cg.ForwardJump()); if (use_true_target != true_target) { cg.SetJumpTarget(use_true_target); if (value_target) { cg.MOV(ESTYPE_BOOLEAN, SCRATCHI_TYPE); cg.MOV(1, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, value_target->virtual_register); } if (true_target) cg.Jump(true_target); } if (finished) cg.SetJumpTarget(finished); } void ES_Native::EmitConditionalJump(ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target, BOOL check_implicit_boolean, ArithmeticBlock *arithmetic_block) { BOOL more_to_flush = FALSE; if (check_implicit_boolean) { DECLARE_NOTHING(); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, implicit_bool), SCRATCHI1); cg.TEQ(SCRATCHI1, 0); } else if (arithmetic_block) { more_to_flush = FlushToVirtualRegisters(arithmetic_block, TRUE); if (more_to_flush) { ES_CodeGenerator::OutOfOrderBlock *trampoline = cg.StartOutOfOrderBlock(); FlushToVirtualRegisters(arithmetic_block, FALSE, TRUE); if (true_target) { cg.Jump(true_target); true_target = trampoline->GetJumpTarget(); } else { cg.Jump(false_target); false_target = trampoline->GetJumpTarget(); } cg.EndOutOfOrderBlock(FALSE); } } if (true_target) cg.Jump(true_target, ES_NATIVE_CONDITION_NOT_EQUAL); else if (false_target) cg.Jump(false_target, ES_NATIVE_CONDITION_EQUAL); if (more_to_flush) FlushToVirtualRegisters(arithmetic_block, FALSE, FALSE); } void ES_Native::EmitConditionalJumpOnValue(VirtualRegister *value_vr, ES_CodeGenerator::JumpTarget *true_target, ES_CodeGenerator::JumpTarget *false_target) { ES_CodeGenerator::OutOfOrderBlock *slow_case = cg.StartOutOfOrderBlock(); if (!c_ReturnAsBoolean) c_ReturnAsBoolean = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Value_Internal::ReturnAsBoolean)); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(value_vr), ES_CodeGenerator::REG_R0); EmitFunctionCall(c_ReturnAsBoolean); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.EndOutOfOrderBlock(); ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); LoadValue(cg, value_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); cg.CMP(type, ESTYPE_BOOLEAN); cg.CMP(type, ESTYPE_INT32, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.TEQ(value, 0); cg.SetOutOfOrderContinuationPoint(slow_case); if (true_target) cg.Jump(true_target, ES_NATIVE_CONDITION_NOT_EQUAL); else cg.Jump(false_target, ES_NATIVE_CONDITION_EQUAL); } void ES_Native::EmitNewObject(VirtualRegister *target_vr, ES_Class *klass, ES_CodeWord *first_property, unsigned nproperties) { OP_ASSERT(nproperties == klass->Count()); EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); EmitAllocateObject(klass, klass, 0, NULL, NULL, slow_case); ES_CodeGenerator::Register object(ALLOCATED_OBJECT_REGISTER); ES_CodeGenerator::Register properties(ALLOCATED_OBJECT_NAMED_PROPERTIES_REGISTER); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitNewObject(): update target virtual register\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(ESTYPE_OBJECT, SCRATCHI_TYPE); cg.MOV(object, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitNewObject(): copy property values\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT for (unsigned index = 0; index < nproperties; ++index) { ES_Layout_Info layout = klass->GetLayoutInfoAtIndex(ES_LayoutIndex(index)); ES_StorageType type = layout.GetStorageType(); ES_CodeGenerator::JumpTarget *null_target = NULL, *int_to_double_target = NULL; ES_ValueType value_type; VirtualRegister *source_vr = VR(first_property[index].index); BOOL known_type = GetType(source_vr, value_type); ES_StorageType source_type = ES_STORAGE_WHATEVER; if (known_type) source_type = ES_Value_Internal::ConvertToStorageType(value_type); BOOL skip_write = FALSE; if (type != ES_STORAGE_WHATEVER && source_type != type) skip_write = EmitTypeConversionCheck(type, source_type, source_vr, current_slow_case->GetJumpTarget(), null_target, int_to_double_target); if (!skip_write) CopyValueToTypedData(cg, source_vr, properties, layout.GetOffset(), layout.GetStorageType(), NULL, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); EmitTypeConversionHandlers(source_vr, properties, layout.GetOffset(), null_target, int_to_double_target); } EmitNewObjectSetPropertyCount(nproperties); } #ifdef SUPPORT_INLINE_ALLOCATION void ES_Native::EmitNewObjectValue(ES_CodeWord *word, unsigned index) { ES_CodeGenerator::Register properties(ALLOCATED_OBJECT_NAMED_PROPERTIES_REGISTER); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT OpString annotation; JString *name = constructor_final_class->GetNameAtIndex(index); annotation.AppendFormat(UNI_L(" from EmitNewObjectValue(), for property %u: '"), index); annotation.Append(Storage(context, name), Length(name)); annotation.AppendL("'\n"); cg.Annotate(annotation.CStr()); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT EmitInitProperty(word, properties, index); } #endif // SUPPORT_INLINE_ALLOCATION void ES_Native::EmitNewObjectSetPropertyCount(unsigned nproperties) { DECLARE_NOTHING(); MoveImmediateToRegister(cg, nproperties, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(ALLOCATED_OBJECT_REGISTER, ES_Object, property_count)); } void ES_Native::EmitNewArray(VirtualRegister *target_vr, unsigned length, unsigned &capacity, ES_Compact_Indexed_Properties *representation) { DECLARE_NOTHING(); ES_Class *klass = code->global_object->GetArrayClass(); ES_CodeGenerator::Register object(ALLOCATED_OBJECT_REGISTER); ES_CodeGenerator::Register indexed_properties(ALLOCATED_OBJECT_INDEXED_PROPERTIES_REGISTER); if (CanAllocateObject(klass, length)) { ES_CodeGenerator::OutOfOrderBlock *slow_case = cg.StartOutOfOrderBlock(); EmitInstructionHandlerCall(); if (!representation) { cg.LDR(BASE_REGISTER(target_vr), IVALUE_OFFSET(target_vr), object); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), indexed_properties); } cg.EndOutOfOrderBlock(); EmitAllocateObject(klass, klass, 1, &length, representation, slow_case->GetJumpTarget()); capacity = length; ES_CodeGenerator::Register type(SCRATCHI_TYPE), value(SCRATCHI_IVALUE); cg.MOV(ESTYPE_OBJECT, type); cg.MOV(object, value); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); cg.SetOutOfOrderContinuationPoint(slow_case); } else { capacity = length; EmitInstructionHandlerCall(); if (!representation) { cg.LDR(BASE_REGISTER(target_vr), IVALUE_OFFSET(target_vr), object); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), indexed_properties); } } cg.ADD(indexed_properties, ES_OFFSETOF(ES_Compact_Indexed_Properties, values), indexed_properties); } void ES_Native::EmitNewArrayValue(VirtualRegister *target_vr, ES_CodeWord *word, unsigned index) { ES_CodeGenerator::Register indexed_properties(ALLOCATED_OBJECT_INDEXED_PROPERTIES_REGISTER); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT OpString annotation; annotation.AppendFormat(UNI_L(" from EmitNewArrayValue(), for index %u:\n"), index); cg.Annotate(annotation.CStr()); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT EmitInitProperty(word, indexed_properties, index); } void ES_Native::EmitNewArrayReset(VirtualRegister *target_vr, unsigned start_index, unsigned end_index) { ES_CodeGenerator::Register indexed_properties(ALLOCATED_OBJECT_INDEXED_PROPERTIES_REGISTER); cg.MOV(ESTYPE_UNDEFINED, SCRATCHI_TYPE); cg.MOV(0, SCRATCHI_IVALUE); for (unsigned index = start_index; index < end_index; ++index) StoreValue(cg, SCRATCHI1, SCRATCHI2, indexed_properties, VALUE_OFFSET(index)); } static void ES_CheckIsBuiltin(ES_CodeGenerator &cg, ES_Native::VirtualRegister *function_vr, ES_BuiltInFunction builtin, ES_CodeGenerator::JumpTarget *slow_case) { DECLARE_NOTHING(); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), SCRATCHI1); cg.LDR(OBJECT_MEMBER(SCRATCHI1, ES_Object, object_bits), SCRATCHI1); cg.MOV(ES_CodeGenerator::Operand(SCRATCHI1, ES_Object::FUNCTION_ID_SHIFT, ES_CodeGenerator::SHIFT_LOGICAL_RIGHT), SCRATCHI1); cg.TEQ(SCRATCHI1, builtin); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } void ES_Native::EmitCall(VirtualRegister *this_vr, VirtualRegister *function_vr, unsigned argc, ES_BuiltInFunction builtin) { DECLARE_NOTHING(); ES_CodeGenerator::JumpTarget *slow_case; if (!current_slow_case) EmitSlowCaseCall(); slow_case = current_slow_case->GetJumpTarget(); BOOL is_call = CurrentCodeWord()->instruction != ESI_CONSTRUCT; if (builtin != ES_BUILTIN_FN_NONE && builtin != ES_BUILTIN_FN_DISABLE) { if (builtin == ES_BUILTIN_FN_sqrt || builtin == ES_BUILTIN_FN_abs || builtin == ES_BUILTIN_FN_sin || builtin == ES_BUILTIN_FN_cos) { if (argc != 1) goto normal_builtin_call; VirtualRegister *arg_vr = this_vr + 2; ES_ValueType argtype; #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitCall(), inlining Math.sqrt() or Math.abs():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (!GetType(arg_vr, argtype) || argtype == ESTYPE_INT32_OR_DOUBLE) { unsigned argbits = code->data->profile_data[cw_index + 2]; if (argbits == ESTYPE_BITS_INT32) argtype = ESTYPE_INT32; else if (ARCHITECTURE_HAS_FPU() && ((argbits & ESTYPE_BITS_DOUBLE) != 0 || argtype == ESTYPE_INT32_OR_DOUBLE)) argtype = ESTYPE_DOUBLE; else goto normal_builtin_call; ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); EmitRegisterTypeCheck(arg_vr, argtype, slow_case); } else if (!ARCHITECTURE_HAS_FPU() && argtype == ESTYPE_DOUBLE) goto normal_call; else ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); if (builtin == ES_BUILTIN_FN_sqrt) if (ARCHITECTURE_HAS_FPU()) { if (argtype == ESTYPE_INT32) { cg.LDR(BASE_REGISTER(arg_vr), IVALUE_OFFSET(arg_vr), SCRATCHI1); cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOD(SCRATCHS1, SCRATCHD1); } else cg.FLDD(BASE_REGISTER(arg_vr), DVALUE_OFFSET(arg_vr), SCRATCHD1); cg.FSQRTD(SCRATCHD1, SCRATCHD1); cg.FSTD(SCRATCHD1, BASE_REGISTER(this_vr), DVALUE_OFFSET(this_vr)); } else goto normal_builtin_call; else if (builtin == ES_BUILTIN_FN_abs) if (argtype == ESTYPE_INT32) { LoadValue(cg, arg_vr, SCRATCHI1, SCRATCHI2); cg.TST(SCRATCHI_IVALUE, 0x80000000u); cg.RSB(SCRATCHI_IVALUE, 0, SCRATCHI_IVALUE, ES_CodeGenerator::SET_CONDITION_CODES, ES_NATIVE_CONDITION_NEGATIVE); cg.Jump(slow_case, ES_NATIVE_CONDITION_NEGATIVE); StoreValue(cg, SCRATCHI1, SCRATCHI2, this_vr); } else if (ARCHITECTURE_HAS_FPU()) { cg.FLDD(BASE_REGISTER(arg_vr), DVALUE_OFFSET(arg_vr), SCRATCHD1); cg.FABSD(SCRATCHD1, SCRATCHD1); cg.FSTD(SCRATCHD1, BASE_REGISTER(this_vr), DVALUE_OFFSET(this_vr)); } else goto normal_builtin_call; else { ES_CodeGenerator::Constant *constant; if (builtin == ES_BUILTIN_FN_sin) { if (!c_MathSin) c_MathSin = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::MathSin)); constant = c_MathSin; } else { if (!c_MathCos) c_MathCos = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::MathCos)); constant = c_MathCos; } AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr), ES_CodeGenerator::REG_R0); EmitFunctionCall(constant); } } else if (builtin == ES_BUILTIN_FN_push && argc != 1) goto normal_builtin_call; else if (builtin == ES_BUILTIN_FN_pow) { if (argc != 2) goto normal_builtin_call; if ((code->data->profile_data[cw_index + 2] & ~(ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) != 0) goto normal_builtin_call; ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); VirtualRegister *number_vr = this_vr + 2, *exp_vr = this_vr + 3; ES_Value_Internal exp_value; if (IsImmediate(exp_vr, exp_value, TRUE)) if (exp_value.IsNumber()) { double exp = exp_value.GetNumAsDouble(); if (op_isfinite(exp)) if (exp == 2) { if (!IsType(number_vr, ESTYPE_DOUBLE)) { ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); LoadValue(cg, number_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); if (!IsType(number_vr, ESTYPE_INT32)) { cg.CMP(type, ESTYPE_INT32); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } cg.SMULL(value, value, SCRATCHI1, value); cg.TEQ(value, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_NEGATIVE); cg.TEQ(SCRATCHI1, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, this_vr); return; } } else if (ARCHITECTURE_HAS_FPU() && (exp == 0.5 || exp == -0.5)) { ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); LoadValue(cg, number_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); BOOL is_int32 = IsType(number_vr, ESTYPE_INT32); BOOL is_double = IsType(number_vr, ESTYPE_DOUBLE); if (!is_int32 && !is_double) { cg.CMP(type, ESTYPE_INT32); cg.FMSR(value, SCRATCHS1, ES_NATIVE_CONDITION_EQUAL); cg.FSITOD(SCRATCHS1, SCRATCHD1, ES_NATIVE_CONDITION_EQUAL); cg.FMDRR(type, value, SCRATCHD1, ES_NATIVE_CONDITION_LESS); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); } cg.FSQRTD(SCRATCHD1, SCRATCHD1); if (exp == -0.5) { cg.FLDD(cg.NewConstant(1.0), SCRATCHD2); cg.FDIVD(SCRATCHD2, SCRATCHD1, SCRATCHD1); } cg.FMRRD(SCRATCHD1, type, value); cg.CMP(type, ESTYPE_DOUBLE); cg.MOV(ESTYPE_DOUBLE, type, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_GREATER); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, this_vr); return; } } if (!c_MathPow) c_MathPow = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::MathPow)); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr), ES_CodeGenerator::REG_R0); EmitFunctionCall(c_MathPow); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); } else if (builtin == ES_BUILTIN_FN_charCodeAt || builtin == ES_BUILTIN_FN_charAt) { ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); EmitRegisterTypeCheck(this_vr, ESTYPE_STRING, slow_case); if (argc > 0) EmitRegisterTypeCheck(this_vr + 2, ESTYPE_INT32, slow_case); EmitInt32StringIndexedGet(this_vr, this_vr, argc > 0 ? this_vr + 2 : NULL, 0, builtin == ES_BUILTIN_FN_charCodeAt); } else if (builtin == ES_BUILTIN_FN_fromCharCode && argc == 1) { VirtualRegister *arg_vr = this_vr + 2; ES_Value_Internal arg_value; if (IsImmediate(arg_vr, arg_value, TRUE)) { if (arg_value.IsInt32()) { int arg = arg_value.GetNumAsInt32(); if (arg >= 0 && arg < STRING_NUMCHARS) { ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); cg.MOV(ESTYPE_STRING, type); MovePointerToRegister(cg, context->rt_data->strings[STRING_nul + arg], value); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, this_vr); return; } } goto normal_builtin_call; } else { ES_CheckIsBuiltin(cg, function_vr, builtin, slow_case); EmitRegisterTypeCheck(arg_vr, ESTYPE_INT32, slow_case); cg.LDR(BASE_REGISTER(arg_vr), IVALUE_OFFSET(arg_vr), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, STRING_NUMCHARS); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, rt_data), value); AddImmediateToRegister(cg, value, ES_OFFSETOF(ESRT_Data, strings) + STRING_nul * sizeof(void *), value); cg.ADD(value, ES_CodeGenerator::Operand(SCRATCHI2, 2), value); cg.LDR(value, 0, value); cg.MOV(ESTYPE_STRING, type); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, this_vr); } } else if (builtin == ES_BUILTIN_FN_push) { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitCall(): inline Array.prototype.push\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT EmitRegisterTypeCheck(this_vr, ESTYPE_OBJECT, slow_case); ES_Value_Internal value; EmitInt32IndexedPut(this_vr, NULL, 0, this_vr + 2, FALSE, FALSE, value, TRUE); } else if (builtin == ES_BUILTIN_FN_OTHER) { normal_builtin_call: ES_CodeGenerator::Register header(ES_CodeGenerator::REG_R1); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R4); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); cg.LDR(function, 0, header); cg.AND(header, ES_Header::MASK_GCTAG, header); cg.TEQ(header, GCTAG_ES_Object_Function); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register fncode(ES_CodeGenerator::REG_R3); cg.LDR(OBJECT_MEMBER(function, ES_Function, function_code), fncode); cg.TEQ(fncode, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(argc, ES_CodeGenerator::REG_R1); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr->index + 2), ES_CodeGenerator::REG_R2); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr), ES_CodeGenerator::REG_R3); cg.LDR(OBJECT_MEMBER(function, ES_Function, data.builtin.call), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); ES_CodeGenerator::OutOfOrderBlock *exception_thrown = cg.StartOutOfOrderBlock(); { /* This call doesn't return. */ if (!c_ThrowFromMachineCode) c_ThrowFromMachineCode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ThrowFromMachineCode)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); EmitFunctionCall(c_ThrowFromMachineCode); } cg.EndOutOfOrderBlock(FALSE); cg.TEQ(ES_CodeGenerator::REG_R0, 0); cg.Jump(exception_thrown->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); } else goto normal_call; } else { normal_call: ES_CodeGenerator::Register object_bits(ES_CodeGenerator::REG_R1); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); cg.LDR(OBJECT_MEMBER(function, ES_Object, object_bits), object_bits); cg.TST(object_bits, is_call ? ES_Object::MASK_IS_NATIVE_FN : ES_Object::MASK_IS_DISPATCHED_CTOR); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); if (is_call) { cg.LDR(OBJECT_MEMBER(function, ES_Function, function_code), function); cg.LDR(OBJECT_MEMBER(function, ES_FunctionCode, native_dispatcher), function); cg.TEQ(function, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); } else cg.LDR(OBJECT_MEMBER(function, ES_Function, data.native.native_ctor_dispatcher), function); cg.MOV(argc, PARAMETERS_COUNT); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr->index), REGISTER_FRAME_POINTER); cg.BLX(function); SetFunctionCallReturnTarget(cg.Here()); AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, -VALUE_OFFSET(this_vr->index), REGISTER_FRAME_POINTER); } } void ES_Native::EmitRedirectedCall(VirtualRegister *function_vr, VirtualRegister *apply_vr, BOOL check_constructor_object_result) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register apply(ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(apply_vr), IVALUE_OFFSET(apply_vr), apply); cg.LDR(OBJECT_MEMBER(apply, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_IS_APPLY_FN); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); /* Sets stack_frame_padding as a side-effect. */ StackSpaceAllocated(); cg.LDR(ES_CodeGenerator::REG_SP, stack_frame_padding, PARAMETERS_COUNT); cg.CMP(PARAMETERS_COUNT, ES_REDIRECTED_CALL_MAXIMUM_ARGUMENTS); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register function_code(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register dispatcher(ES_CodeGenerator::REG_R5); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); cg.LDR(OBJECT_MEMBER(function, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_IS_NATIVE_FN); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(function, ES_Function, function_code), function_code); cg.LDR(OBJECT_MEMBER(function_code, ES_FunctionCode, native_dispatcher), dispatcher); cg.TEQ(dispatcher, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); if (constructor) { LoadValue(cg, VR(0), ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7); cg.PUSH((1 << 6) | (1 << 7)); } cg.STR(function, BASE_REGISTER(VR(1)), IVALUE_OFFSET(VR(1))); cg.BLX(dispatcher); SetFunctionCallReturnTarget(cg.Here()); if (constructor) { cg.POP((1 << 6) | (1 << 7)); ES_CodeGenerator::JumpTarget *keep_object_result = NULL; if (check_constructor_object_result) { /* Restore reg[0] if return value isn't an object. */ cg.LDR(BASE_REGISTER(VR(0)), TYPE_OFFSET(VR(0)), SCRATCHI1); cg.CMP(SCRATCHI1, ESTYPE_OBJECT); keep_object_result = cg.ForwardJump(); cg.Jump(keep_object_result, ES_NATIVE_CONDITION_EQUAL); } StoreValue(cg, ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7, VR(0)); if (keep_object_result) cg.SetJumpTarget(keep_object_result); } } void ES_Native::EmitApply(VirtualRegister *apply_vr, VirtualRegister *this_vr, VirtualRegister *function_vr, unsigned argc) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register apply(ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(apply_vr), IVALUE_OFFSET(apply_vr), apply); cg.LDR(OBJECT_MEMBER(apply, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_IS_APPLY_FN); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register function_code(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register dispatcher(ES_CodeGenerator::REG_R5); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); cg.LDR(OBJECT_MEMBER(function, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_IS_NATIVE_FN); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(function, ES_Function, function_code), function_code); cg.LDR(OBJECT_MEMBER(function_code, ES_FunctionCode, native_dispatcher), dispatcher); cg.TEQ(dispatcher, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); AddImmediateToRegister(cg, VALUE_OFFSET(this_vr), REGISTER_FRAME_POINTER); MoveImmediateToRegister(cg, argc, PARAMETERS_COUNT); cg.BLX(dispatcher); SetFunctionCallReturnTarget(cg.Here()); AddImmediateToRegister(cg, -VALUE_OFFSET(this_vr), REGISTER_FRAME_POINTER); } void ES_Native::EmitEval(VirtualRegister *this_vr, VirtualRegister *function_vr, unsigned argc) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object_bits(ES_CodeGenerator::REG_R3); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); cg.LDR(OBJECT_MEMBER(function, ES_Object, object_bits), object_bits); cg.TST(object_bits, ES_Object::MASK_IS_EVAL_FN); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); if (!c_EvalFromMachineCode) c_EvalFromMachineCode = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::EvalFromMachineCode)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index, ES_CodeGenerator::REG_R1); cg.LDR(c_EvalFromMachineCode, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } ES_CodeGenerator::OutOfOrderBlock * ES_Native::EmitInlinedCallPrologue(VirtualRegister *this_vr, VirtualRegister *function_vr, ES_Function *function, unsigned char *mark_failure, unsigned argc, BOOL function_fetched) { DECLARE_NOTHING(); ES_CodeGenerator::OutOfOrderBlock *failure = cg.StartOutOfOrderBlock(); cg.SUB(REGISTER_FRAME_POINTER, VALUE_OFFSET(this_vr->index), REGISTER_FRAME_POINTER); if (!function_fetched) { MoveImmediateToRegister(cg, ESTYPE_OBJECT, SCRATCHI_TYPE); MovePointerToRegister(cg, function, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, function_vr); } if (!c_code) c_code = cg.NewConstant(code); cg.LDR(c_code, SCRATCHI1); cg.MOV(1, SCRATCHI2); cg.STR(SCRATCHI2, OBJECT_MEMBER(SCRATCHI1, ES_Code, has_failed_inlined_function)); MovePointerToRegister(cg, mark_failure, SCRATCHI1); cg.LDRB(SCRATCHI1, 0, SCRATCHI2); cg.ORR(SCRATCHI2, ES_CodeStatic::GET_FAILED_INLINE, SCRATCHI2); cg.STRB(SCRATCHI2, SCRATCHI1, 0); if (!c_ForceUpdateNativeDispatcher) c_ForceUpdateNativeDispatcher = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ForceUpdateNativeDispatcher)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(c_ForceUpdateNativeDispatcher, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.BX(ES_CodeGenerator::REG_R0); cg.EndOutOfOrderBlock(FALSE); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" EmitInlinedCallPrologue():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT AddImmediateToRegister(cg, VALUE_OFFSET(this_vr->index), REGISTER_FRAME_POINTER); return failure; } void ES_Native::EmitInlinedCallEpilogue(VirtualRegister *this_vr, VirtualRegister *function_vr, unsigned argc) { AddImmediateToRegister(cg, -VALUE_OFFSET(this_vr->index), REGISTER_FRAME_POINTER); } void ES_Native::EmitReturn() { if (cw_index != code->data->instruction_offsets[code->data->instruction_count - 1]) cg.Jump(epilogue_jump_target); } void ES_Native::EmitNormalizeValue(VirtualRegister *vr, ES_CodeGenerator::JumpTarget *slow_case) { ES_CodeGenerator::JumpTarget *is_int = NULL; if (!ARCHITECTURE_HAS_FPU()) { EmitRegisterTypeCheck(vr, ESTYPE_INT32, slow_case); return; } else { is_int = cg.ForwardJump(); EmitRegisterTypeCheck(vr, ESTYPE_INT32, is_int, TRUE); } EmitRegisterTypeCheck(vr, ESTYPE_DOUBLE, slow_case); if (!slow_case) { OP_ASSERT(current_slow_case != NULL); slow_case = current_slow_case->GetJumpTarget(); } cg.FLDD(BASE_REGISTER(vr), DVALUE_OFFSET(vr), ES_CodeGenerator::VFPREG_D0); cg.FTOSID(SCRATCHD1, ES_CodeGenerator::VFPREG_S4); cg.FSITOD(ES_CodeGenerator::VFPREG_S4, ES_CodeGenerator::VFPREG_D1); cg.FCMPD(ES_CodeGenerator::VFPREG_D0, ES_CodeGenerator::VFPREG_D1); cg.FMSTAT(); // checks both in-equality and un-ordered cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.FMRS(ES_CodeGenerator::VFPREG_S4, SCRATCHI_IVALUE); MoveImmediateToRegister(cg, ESTYPE_INT32, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, vr); cg.SetJumpTarget(is_int); } void ES_Native::EmitInt32IndexedGet(VirtualRegister *target_vr, VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R3); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_SIMPLE_COMPACT_INDEXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), properties); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R4); /* Check that (constant) index is within array's capacity: */ if (!index_vr) { cg.LDR(OBJECT_MEMBER(properties, ES_Compact_Indexed_Properties, capacity), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, constant_index); cg.Jump(slow_case, ES_NATIVE_CONDITION_LOWER_OR_SAME); AddImmediateToRegister(cg, properties, VALUE_OFFSET(constant_index) + ES_OFFSETOF(ES_Compact_Indexed_Properties, values[0]), index); } else { cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), index); cg.LDR(OBJECT_MEMBER(properties, ES_Compact_Indexed_Properties, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.ADD(properties, ES_CodeGenerator::Operand(index, 3), index); cg.ADD(index, ES_OFFSETOF(ES_Compact_Indexed_Properties, values[0]), index); } if (property_value_write_vr) { OP_ASSERT(property_value_write_vr == target_vr); cg.LDR(index, VALUE_TYPE_OFFSET, SCRATCHI1); cg.CMP(SCRATCHI1, ESTYPE_UNDEFINED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); SetPropertyValueTransferRegister(INTEGER_NR(this, VALUE_TRANSFER_POINTER), 0, TRUE); cg.MOV(index, VALUE_TRANSFER_POINTER); if (current_slow_case) { ES_CodeGenerator::OutOfOrderBlock *recover = cg.StartOutOfOrderBlock(); cg.SetOutOfOrderContinuationPoint(current_slow_case); current_slow_case = NULL; AddImmediateToRegister(cg, REGISTER_FRAME_POINTER, VALUE_OFFSET(target_vr->index), VALUE_TRANSFER_POINTER); cg.EndOutOfOrderBlock(); cg.SetOutOfOrderContinuationPoint(recover); } } else { LoadValue(cg, index, 0, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); cg.CMP(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3), ESTYPE_UNDEFINED); cg.TEQ(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3), 0, ES_NATIVE_CONDITION_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, target_vr); } } void ES_Native::EmitInt32IndexedPut(VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index, VirtualRegister *source_vr, BOOL known_type, BOOL known_value, const ES_Value_Internal &the_value, BOOL is_push) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register indexed_properties(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register klass(ES_CodeGenerator::REG_R4); unsigned length_offset = code->global_object->GetArrayClass()->GetLayoutInfoAtIndex(ES_LayoutIndex(0)).GetOffset(); LoadObjectOperand(object_vr->index, object); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case; if (!is_light_weight && property_value_read_vr && property_value_nr) { ES_CodeGenerator::OutOfOrderBlock *flush_object_vr = cg.StartOutOfOrderBlock(); MoveImmediateToRegister(cg, ESTYPE_OBJECT, SCRATCHI1); cg.STR(SCRATCHI1, BASE_REGISTER(object_vr), TYPE_OFFSET(object_vr)); cg.STR(object, BASE_REGISTER(object_vr), IVALUE_OFFSET(object_vr)); cg.Jump(current_slow_case_main); cg.EndOutOfOrderBlock(FALSE); slow_case = flush_object_vr->GetJumpTarget(); } else slow_case = current_slow_case->GetJumpTarget(); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_MUTABLE_COMPACT_INDEXED); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), indexed_properties); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), klass); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register value(ES_CodeGenerator::REG_R6); if (is_push) { /* Theory: When inlining Array.prototype.push, do the class check early since we'll need to get the 'length' property from the array object. If the class id check holds, it is not just guaranteed that the object is an array, but also that the type of length is UINT32. */ cg.LDR(OBJECT_MEMBER(klass, ES_Class, class_id), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, code->global_object->GetArrayClass()->GetId(context)); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), SCRATCHI1); cg.LDR(SCRATCHI1, length_offset, index); } else if (index_vr) cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), index); else MoveImmediateToRegister(cg, constant_index, index); ES_CodeGenerator::OutOfOrderBlock *check_capacity_and_length = !is_push ? cg.StartOutOfOrderBlock() : NULL; ES_CodeGenerator::JumpTarget *no_length_update = !is_push ? check_capacity_and_length->GetContinuationTarget() : NULL; /* If the index is equal to or higher than capacity, the put can't be performed, so jump to the slow case. This is an unsigned comparison, so if the index is negative, it will appear higher than capacity (which can be assumed to be at most INT_MAX.) */ cg.LDR(OBJECT_MEMBER(indexed_properties, ES_Compact_Indexed_Properties, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); /* Check if object requires a length update + if it is an instance of Array */ if (!is_push) { cg.LDR(object, 0, SCRATCHI2); cg.AND(SCRATCHI2, ES_Header::MASK_GCTAG, SCRATCHI2); cg.TEQ(SCRATCHI2, GCTAG_ES_Object_Array); cg.Jump(no_length_update, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(klass, ES_Class, class_id), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, code->global_object->GetArrayClass()->GetId(context)); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } /* We get to this slow case because index>=top. We get this far in the slow case if index<capacity. Since top is defined to be the same as capacity on non-arrays, index>=top&&index<capacity => instanceof Array. Thus we can assume that the first named property on the object is 'length'. */ cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), SCRATCHI1); /* Check if 'length' is higher than the assigned index, in which case we shouldn't update it. */ if (!is_push) { cg.LDR(SCRATCHI1, length_offset, SCRATCHI2); cg.CMP(index, SCRATCHI2); cg.Jump(no_length_update, ES_NATIVE_CONDITION_LOWER); } /* Update 'length' to index+1. We're ignoring overflow here, see comment in EmitInt32IndexedPut() in es_native_ia32.cpp for an explanation. Also update 'top' which must have been equal to 'length', since 'length' is obviously less 'capacity'. */ cg.ADD(index, 1, SCRATCHI2); cg.STR(SCRATCHI2, SCRATCHI1, length_offset); cg.STR(SCRATCHI2, OBJECT_MEMBER(indexed_properties, ES_Compact_Indexed_Properties, top)); if (check_capacity_and_length) { cg.EndOutOfOrderBlock(); cg.LDR(OBJECT_MEMBER(indexed_properties, ES_Compact_Indexed_Properties, top), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(check_capacity_and_length->GetJumpTarget(), ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.SetOutOfOrderContinuationPoint(check_capacity_and_length); } cg.ADD(indexed_properties, ES_CodeGenerator::Operand(index, 3), value); cg.ADD(value, ES_OFFSETOF(ES_Compact_Indexed_Properties, values), value); ES_CodeGenerator::Register value_type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value_value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); if (known_type && the_value.Type() != ESTYPE_DOUBLE && the_value.Type() != ESTYPE_STRING && the_value.Type() != ESTYPE_OBJECT) { cg.MOV(the_value.Type(), value_type); if (known_value || the_value.IsNullOrUndefined()) switch (the_value.Type()) { case ESTYPE_NULL: break; case ESTYPE_UNDEFINED: cg.MOV(1, value_value); break; case ESTYPE_BOOLEAN: cg.MOV(the_value.GetBoolean() ? 1 : 0, value_value); break; case ESTYPE_INT32: MoveImmediateToRegister(cg, the_value.GetInt32(), value_value); } else cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), value_value); } else { LoadValue(cg, source_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); if (!known_type) { cg.CMP(value_type, ESTYPE_UNDEFINED); cg.MOV(1, value_value, ES_CodeGenerator::UNSET_CONDITION_CODES, ES_NATIVE_CONDITION_EQUAL); } } cg.STRD(ES_CodeGenerator::REG_R2, value, 0); if (is_push) { /* The return value of Array.prototype.push is the new value of the 'length' property. We know that 'object_vr' is the receiver of the call to Array.prototype.push and that that register doubles as return register, so write the new length here instead of doing a EmitLengthGet which will check types that we've already checked. */ cg.MOV(ESTYPE_INT32, SCRATCHI_TYPE); cg.ADD(index, 1, SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, object_vr); } } void ES_Native::EmitInt32ByteArrayGet(VirtualRegister *target_vr, VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register bytearray(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R4); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_BYTE_ARRAY_INDEXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), bytearray); if (index_vr) cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), index); else MoveImmediateToRegister(cg, constant_index, index); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, byte_array), bytearray); cg.LDRB(bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 0, TRUE, SCRATCHI_IVALUE); cg.MOV(ESTYPE_INT32, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } void ES_Native::EmitInt32ByteArrayPut(VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index, VirtualRegister *source_vr, int *known_value) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register bytearray(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R4); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_BYTE_ARRAY_INDEXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), bytearray); if (index_vr) cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), index); else MoveImmediateToRegister(cg, constant_index, index); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); if (known_value) MoveImmediateToRegister(cg, static_cast<signed char>(*known_value), SCRATCHI1); else cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), SCRATCHI1); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, byte_array), bytearray); cg.STRB(SCRATCHI1, bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 0, TRUE); } static void EmitTypedArrayPrecondition(ES_Native &native, ES_Native::VirtualRegister *object_vr, ES_Native::VirtualRegister *index_vr, unsigned constant_index) { DECLARE_NOTHING(); ES_CodeGenerator &cg = native.cg; ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register bytearray(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R5); if (!native.current_slow_case) native.EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = native.current_slow_case->GetJumpTarget(); native.LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI2); cg.TST(SCRATCHI2, ES_Object::MASK_TYPE_ARRAY_INDEXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), bytearray); if (index_vr) cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), index); else MoveImmediateToRegister(cg, constant_index, index); } void ES_Native::EmitInt32TypedArrayGet(VirtualRegister *target_vr, VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index, unsigned type_array_bits) { DECLARE_NOTHING(); ANNOTATE("EmitInt32TypedArrayGet"); ES_CodeGenerator::Register bytearray(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register kind(ES_CodeGenerator::REG_R6); EmitTypedArrayPrecondition(*this, object_vr, index_vr, constant_index); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, kind), kind); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, byte_offset), SCRATCHI1); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, byte_array), bytearray); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, byte_array), bytearray); cg.ADD(SCRATCHI1, bytearray, bytearray); ES_CodeGenerator::JumpTarget *done_int_target = NULL; ES_CodeGenerator::JumpTarget *done_target = NULL; unsigned array_kind = ES_Type_Array_Indexed::Int8Array; unsigned handled = type_array_bits; if (type_array_bits & ES_Type_Array_Indexed::AnyIntArray) done_int_target = cg.ForwardJump(); for(; handled; array_kind++) { ES_CodeGenerator::JumpTarget *next; if (!(handled & 1)) { handled = handled >> 1; continue; } handled = handled >> 1; if (handled) next = cg.ForwardJump(); else next = slow_case; CompareRegisterToImmediate(cg, kind, array_kind); cg.Jump(next, ES_NATIVE_CONDITION_NOT_EQUAL); switch (array_kind) { case ES_Type_Array_Indexed::Int8Array: ANNOTATE("EmitInt32TypedArrayGet, Int8Array"); cg.LDRSB(bytearray, index, TRUE, SCRATCHI_IVALUE); cg.Jump(done_int_target, ES_NATIVE_UNCONDITIONAL); break; case ES_Type_Array_Indexed::Uint8Array: case ES_Type_Array_Indexed::Uint8ClampedArray: ANNOTATE("EmitInt32TypedArrayGet, Uint8Array"); cg.LDRB(bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 0, TRUE, SCRATCHI_IVALUE); cg.Jump(done_int_target, ES_NATIVE_UNCONDITIONAL); break; case ES_Type_Array_Indexed::Int16Array: ANNOTATE("EmitInt32TypedArrayGet, Int16Array"); cg.ADD(index, index, index); cg.LDRSH(bytearray, index, TRUE, SCRATCHI_IVALUE); cg.Jump(done_int_target, ES_NATIVE_UNCONDITIONAL); break; case ES_Type_Array_Indexed::Uint16Array: ANNOTATE("EmitInt32TypedArrayGet, Uint16Array"); cg.ADD(index, index, index); cg.LDRH(bytearray, index, TRUE, SCRATCHI_IVALUE); cg.Jump(done_int_target, ES_NATIVE_UNCONDITIONAL); break; case ES_Type_Array_Indexed::Int32Array: ANNOTATE("EmitInt32TypedArrayGet, Int32Array"); cg.LDR(bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 2, TRUE, SCRATCHI_IVALUE); cg.Jump(done_int_target, ES_NATIVE_UNCONDITIONAL); break; case ES_Type_Array_Indexed::Uint32Array: ANNOTATE("EmitInt32TypedArrayGet, Uint32Array"); cg.LDR(bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 2, TRUE, SCRATCHI_IVALUE); cg.TST(SCRATCHI_IVALUE, 0x80000000u); cg.Jump(done_int_target, ES_NATIVE_CONDITION_EQUAL); if (ARCHITECTURE_HAS_FPU()) { cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FUITOD(SCRATCHS1, SCRATCHD1); cg.FSTD(SCRATCHD1, BASE_REGISTER(target_vr), DVALUE_OFFSET(target_vr)); } else { AddImmediateToRegister(cg, BASE_REGISTER(target_vr), DVALUE_OFFSET(target_vr), ES_CodeGenerator::REG_R1); if (SCRATCHI1 != ES_CodeGenerator::REG_R0) cg.MOV(SCRATCHI_IVALUE, ES_CodeGenerator::REG_R0); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreUIntAsDouble)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } done_target = cg.ForwardJump(); cg.Jump(done_target); break; case ES_Type_Array_Indexed::Float32Array: ANNOTATE("EmitInt32TypedArrayGet, Float32Array"); cg.ADD(bytearray, ES_CodeGenerator::Operand(index, 2, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), SCRATCHI1); if (ARCHITECTURE_HAS_FPU()) { cg.FLDS(SCRATCHI1, 0, SCRATCHS1); cg.FCVTDS(SCRATCHS1, SCRATCHD1); cg.FSTD(SCRATCHD1, BASE_REGISTER(target_vr), DVALUE_OFFSET(target_vr)); } else { AddImmediateToRegister(cg, BASE_REGISTER(target_vr), DVALUE_OFFSET(target_vr), ES_CodeGenerator::REG_R1); cg.MOV(bytearray, ES_CodeGenerator::REG_R0); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreFloatAsDouble)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } if (handled || done_int_target) { if (!done_target) done_target = cg.ForwardJump(); cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } else return; break; case ES_Type_Array_Indexed::Float64Array: ANNOTATE("EmitInt32TypedArrayGet, Float64Array"); cg.ADD(bytearray, ES_CodeGenerator::Operand(index, 3, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), bytearray); CopyValue(cg, bytearray, 0, target_vr); if (done_int_target) { if (!done_target) done_target = cg.ForwardJump(); cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } else if (!done_target) return; } if (next != slow_case) cg.SetJumpTarget(next); } if (done_int_target) { cg.SetJumpTarget(done_int_target); cg.MOV(ESTYPE_INT32, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } if (done_target) cg.SetJumpTarget(done_target); } static void LoadDoubleAsInt(ES_Native &n, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register dst, BOOL has_fpu, BOOL do_truncate, ES_CodeGenerator::JumpTarget *slow_case) { ES_CodeGenerator &cg = n.cg; if (has_fpu) { cg.FLDD(BASE_REGISTER(source_vr), DVALUE_OFFSET(source_vr), SCRATCHD1); if (do_truncate) cg.FTOSIZD(SCRATCHD1, SCRATCHS1); else cg.FTOSID(SCRATCHD1, SCRATCHS1); cg.FMRS(SCRATCHS1, dst); cg.CMP(dst, INT_MAX); cg.CMP(dst, INT_MIN, ES_NATIVE_CONDITION_NOT_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); } else { AddImmediateToRegister(cg, BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), ES_CodeGenerator::REG_R0); if (do_truncate) cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::GetDoubleAsInt)), ES_CodeGenerator::REG_LR); else cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::GetDoubleAsIntRound)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); if (dst != ES_CodeGenerator::REG_R0) cg.MOV(ES_CodeGenerator::REG_R0, dst); } } static void StoreDoubleAsFloat2(ES_Native &n, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register dst, ES_CodeGenerator::JumpTarget *slow_case, BOOL has_fpu) { ES_CodeGenerator &cg = n.cg; if (has_fpu) { cg.FLDD(BASE_REGISTER(source_vr), DVALUE_OFFSET(source_vr), SCRATCHD1); cg.FCVTSD(SCRATCHD1, SCRATCHS1); cg.FSTS(SCRATCHS1, dst, 0); } else { AddImmediateToRegister(cg, BASE_REGISTER(source_vr), DVALUE_OFFSET(source_vr), ES_CodeGenerator::REG_R0); if (dst != ES_CodeGenerator::REG_R1) cg.MOV(dst, ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreDoubleAsFloat)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } } static void StoreIntAsFloat2(ES_Native &n, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register dst, ES_CodeGenerator::JumpTarget *slow_case, BOOL has_fpu) { ES_CodeGenerator &cg = n.cg; if (has_fpu) { cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), SCRATCHI1); cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOS(SCRATCHS1, SCRATCHS1); cg.FSTS(SCRATCHS1, dst, 0); } else { cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), ES_CodeGenerator::REG_R0); if (dst != ES_CodeGenerator::REG_R1) cg.MOV(dst, ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreIntAsFloat)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } } static void StoreIntAsDouble2(ES_Native &n, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register dst, ES_CodeGenerator::JumpTarget *slow_case, BOOL has_fpu) { ES_CodeGenerator &cg = n.cg; if (has_fpu) { cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), SCRATCHI1); cg.FMSR(SCRATCHI1, SCRATCHS1); cg.FSITOD(SCRATCHS1, SCRATCHD1); cg.FSTD(SCRATCHD1, dst, 0); } else { cg.LDR(BASE_REGISTER(source_vr), IVALUE_OFFSET(source_vr), ES_CodeGenerator::REG_R0); if (dst != ES_CodeGenerator::REG_R1) cg.MOV(dst, ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::StoreIntAsDouble)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } } static BOOL EmitInt32TypedArrayPutLoadSource(ES_Native &native, ES_Native::VirtualRegister *source_vr, ES_CodeGenerator::Register value, unsigned char source_type_bits, ES_ValueType *known_type, BOOL has_fpu, BOOL do_truncate, ES_CodeGenerator::JumpTarget *slow_case) { ES_CodeGenerator &cg = native.cg; if (known_type) { if (*known_type == ESTYPE_DOUBLE) { LoadDoubleAsInt(native, source_vr, value, has_fpu, do_truncate, slow_case); return TRUE; } else if (*known_type == ESTYPE_INT32) cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), value); } else { if ((source_type_bits & (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) == (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) { ES_CodeGenerator::OutOfOrderBlock *double_to_int = cg.StartOutOfOrderBlock(); ANNOTATE("EmitInt32TypedArrayPut, convert double to int"); LoadDoubleAsInt(native, source_vr, value, has_fpu, do_truncate, slow_case); cg.EndOutOfOrderBlock(); cg.LDR(BASE_REGISTER(source_vr), TYPE_OFFSET(source_vr->index), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, ESTYPE_INT32); cg.Jump(double_to_int->GetJumpTarget(), ES_NATIVE_CONDITION_LESS); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), value); cg.SetOutOfOrderContinuationPoint(double_to_int); return TRUE; } else if (source_type_bits & ESTYPE_BITS_INT32) { native.EmitRegisterTypeCheck(source_vr, ESTYPE_INT32, slow_case); cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), value); } else if (source_type_bits & ESTYPE_BITS_DOUBLE) { native.EmitRegisterTypeCheck(source_vr, ESTYPE_DOUBLE, slow_case); LoadDoubleAsInt(native, source_vr, value, has_fpu, do_truncate, slow_case); return TRUE; } } return FALSE; } void ES_Native::EmitInt32TypedArrayPut(VirtualRegister *object_vr, VirtualRegister *index_vr, unsigned constant_index, unsigned type_array_bits, VirtualRegister *source_vr, unsigned char source_type_bits, ES_Value_Internal *known_value, ES_ValueType *known_type) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ANNOTATE("EmitInt32TypedArrayPut"); OP_ASSERT(!known_type || *known_type == ESTYPE_DOUBLE || *known_type == ESTYPE_INT32); OP_ASSERT((source_type_bits & ~(ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) == 0); ES_CodeGenerator::Register bytearray(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register index(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register kind(ES_CodeGenerator::REG_R6); EmitTypedArrayPrecondition(*this, object_vr, index_vr, constant_index); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, kind), kind); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, byte_offset), SCRATCHI1); cg.LDR(OBJECT_MEMBER(bytearray, ES_Type_Array_Indexed, byte_array), bytearray); cg.LDR(OBJECT_MEMBER(bytearray, ES_Byte_Array_Indexed, byte_array), bytearray); cg.ADD(SCRATCHI1, bytearray, bytearray); ES_CodeGenerator::JumpTarget *next = NULL; ES_CodeGenerator::JumpTarget *done_target = cg.ForwardJump(); if (type_array_bits & ES_Type_Array_Indexed::AnyIntArray) { ES_CodeGenerator::Register value(ES_CodeGenerator::REG_R7); if (type_array_bits & ES_Type_Array_Indexed::AnyFloatArray) next = cg.ForwardJump(); else next = slow_case; CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint32Array); cg.Jump(next, ES_NATIVE_CONDITION_GREATER); BOOL needed_double_conversion = FALSE; if (known_value) { ES_CodeGenerator::JumpTarget *done = NULL; BOOL loaded_known_value = FALSE; if (type_array_bits & (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray)) { ES_CodeGenerator::JumpTarget *not_clamped = NULL; if ((type_array_bits & ES_Type_Array_Indexed::AnyIntArray) != (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray)) { not_clamped = cg.ForwardJump(); CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint8ClampedArray); cg.Jump(not_clamped, ES_NATIVE_CONDITION_NOT_EQUAL); } MoveImmediateToRegister(cg, known_value->AsNumber(context).GetNumAsUint8Clamped(), value); if (not_clamped) { done = cg.ForwardJump(); cg.Jump(done); cg.SetJumpTarget(not_clamped); } else loaded_known_value = TRUE; } if (!loaded_known_value) MoveImmediateToRegister(cg, known_value->AsNumber(context).GetNumAsUInt32(), value); if (done) cg.SetJumpTarget(done); } else { BOOL needs_truncation = (type_array_bits & ES_Type_Array_Indexed::AnyIntArray) != (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray); needed_double_conversion = EmitInt32TypedArrayPutLoadSource(*this, source_vr, value, source_type_bits, known_type, ARCHITECTURE_HAS_FPU(), needs_truncation, slow_case); } ES_CodeGenerator::JumpTarget *next_int = NULL; if (type_array_bits & ES_Type_Array_Indexed::AnyInt8Array) { ANNOTATE("EmitInt32TypedArrayPut, (U)Int8Array"); if (type_array_bits & (ES_Type_Array_Indexed::AnyInt16Array | ES_Type_Array_Indexed::AnyInt32Array)) next_int = cg.ForwardJump(); else next_int = next; if (type_array_bits & (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray)) CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint8ClampedArray); else CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint8Array); cg.Jump(next_int, ES_NATIVE_CONDITION_GREATER); if (!known_value && (type_array_bits & (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray))) { ES_CodeGenerator::JumpTarget *write_value = cg.ForwardJump(); cg.Jump(write_value, ES_NATIVE_CONDITION_NOT_EQUAL); /* If source_vr has been converted from a double _and_ it wasn't only at a clamped type, repeat the load, but with different rounding. */ if (needed_double_conversion && ((type_array_bits & ES_Type_Array_Indexed::AnyIntArray) != (0x1 << ES_Type_Array_Indexed::Uint8ClampedArray))) EmitInt32TypedArrayPutLoadSource(*this, source_vr, value, source_type_bits, known_type, ARCHITECTURE_HAS_FPU(), FALSE, slow_case); CompareRegisterToImmediate(cg, value, 0); MoveImmediateToRegister(cg, 0, value, ES_NATIVE_CONDITION_LESS); CompareRegisterToImmediate(cg, value, 0xff); MoveImmediateToRegister(cg, 0xff, value, ES_NATIVE_CONDITION_GREATER); cg.SetJumpTarget(write_value); } cg.STRB(value, bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 0, TRUE); cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } if (type_array_bits & ES_Type_Array_Indexed::AnyInt16Array) { ANNOTATE("EmitInt32TypedArrayPut, (U)Int16Array"); if (next_int) cg.SetJumpTarget(next_int); if (type_array_bits & ES_Type_Array_Indexed::AnyInt32Array) next_int = cg.ForwardJump(); else next_int = next; if ((type_array_bits & ES_Type_Array_Indexed::AnyInt8Array) == 0) { CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Int16Array); /* If TRUE, an 8-bit array. Subsequent cases cannot apply, so slow case. */ cg.Jump(slow_case, ES_NATIVE_CONDITION_LESS); } CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint16Array); cg.Jump(next_int, ES_NATIVE_CONDITION_GREATER); cg.ADD(index, index, index); cg.STRH(value, bytearray, index, TRUE); cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } if (type_array_bits & ES_Type_Array_Indexed::AnyInt32Array) { ANNOTATE("EmitInt32TypedArrayPut, (U)Int32Array"); if (next_int) cg.SetJumpTarget(next_int); if ((type_array_bits & ES_Type_Array_Indexed::AnyInt16Array) == 0) { CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Int32Array); /* If TRUE, has an integral kind. Subsequent float cases cannot apply, so slow case. */ cg.Jump(slow_case, ES_NATIVE_CONDITION_LESS); } CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Uint32Array); cg.Jump(next, ES_NATIVE_CONDITION_GREATER); cg.STR(value, bytearray, index, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 2, TRUE); cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } } if (type_array_bits & ES_Type_Array_Indexed::Float32ArrayBit) { ANNOTATE("EmitInt32TypedArrayPut, Float32Array"); if (next) cg.SetJumpTarget(next); if (type_array_bits & ES_Type_Array_Indexed::Float64ArrayBit) next = cg.ForwardJump(); else next = slow_case; CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Float32Array); cg.Jump(next, ES_NATIVE_CONDITION_NOT_EQUAL); cg.ADD(bytearray, ES_CodeGenerator::Operand(index, 2, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), bytearray); if (known_type) { if (*known_type == ESTYPE_DOUBLE) StoreDoubleAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); else if (*known_type == ESTYPE_INT32) StoreIntAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); } else { if ((source_type_bits & (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) == (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) { ES_CodeGenerator::OutOfOrderBlock *double_to_float = cg.StartOutOfOrderBlock(); ANNOTATE("EmitInt32TypedArrayPut, convert double to float"); StoreDoubleAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); cg.EndOutOfOrderBlock(); cg.LDR(BASE_REGISTER(source_vr), TYPE_OFFSET(source_vr->index), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, ESTYPE_INT32); cg.Jump(double_to_float->GetJumpTarget(), ES_NATIVE_CONDITION_LESS); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); StoreIntAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); cg.SetOutOfOrderContinuationPoint(double_to_float); } else if (source_type_bits & ESTYPE_BITS_INT32) { EmitRegisterTypeCheck(source_vr, ESTYPE_INT32, slow_case); StoreIntAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); } else if (source_type_bits & ESTYPE_BITS_DOUBLE) { EmitRegisterTypeCheck(source_vr, ESTYPE_DOUBLE, slow_case); StoreDoubleAsFloat2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); } } cg.Jump(done_target, ES_NATIVE_UNCONDITIONAL); } if (type_array_bits & ES_Type_Array_Indexed::Float64ArrayBit) { ANNOTATE("EmitInt32TypedArrayPut, Float64Array"); if (next) cg.SetJumpTarget(next); CompareRegisterToImmediate(cg, kind, ES_Type_Array_Indexed::Float64Array); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.ADD(bytearray, ES_CodeGenerator::Operand(index, 3, ES_CodeGenerator::SHIFT_LOGICAL_LEFT), bytearray); if (known_type) { if (*known_type == ESTYPE_DOUBLE) CopyValue(cg, source_vr, bytearray, 0); else if (*known_type == ESTYPE_INT32) StoreIntAsDouble2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); } else { if ((source_type_bits & (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) == (ESTYPE_BITS_INT32 | ESTYPE_BITS_DOUBLE)) { ES_CodeGenerator::OutOfOrderBlock *int_to_double = cg.StartOutOfOrderBlock(); ANNOTATE("EmitInt32TypedArrayPut, convert int to double"); StoreIntAsDouble2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); cg.EndOutOfOrderBlock(); cg.LDR(BASE_REGISTER(source_vr), TYPE_OFFSET(source_vr->index), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, ESTYPE_INT32); cg.Jump(int_to_double->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_GREATER); CopyValue(cg, source_vr, bytearray, 0); cg.SetOutOfOrderContinuationPoint(int_to_double); } else if (source_type_bits & ESTYPE_BITS_INT32) { EmitRegisterTypeCheck(source_vr, ESTYPE_INT32, slow_case); StoreIntAsDouble2(*this, source_vr, bytearray, slow_case, ARCHITECTURE_HAS_FPU()); } else if (source_type_bits & ESTYPE_BITS_DOUBLE) { EmitRegisterTypeCheck(source_vr, ESTYPE_DOUBLE, slow_case); CopyValue(cg, source_vr, bytearray, 0); } } } cg.SetJumpTarget(done_target); } void ES_Native::EmitGetEnumerated(VirtualRegister *target_vr, VirtualRegister *object_vr, VirtualRegister *name_vr) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register name(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register enumerated_class_id(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register object_class_id(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register type(ES_CodeGenerator::REG_R6); cg.LDR(BASE_REGISTER(name_vr), IVALUE_OFFSET(name_vr), name); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_string), SCRATCHI1); cg.TEQ(name, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_class_id), enumerated_class_id); ES_CodeGenerator::Register property_value(object_class_id); ES_CodeGenerator::OutOfOrderBlock *indexed = cg.StartOutOfOrderBlock(); cg.TEQ(enumerated_class_id, ES_Class::NOT_CACHED_CLASS_ID); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(object, ES_Object, object_bits), SCRATCHI1); cg.TST(SCRATCHI1, ES_Object::MASK_SIMPLE_COMPACT_INDEXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); ES_CodeGenerator::Register index(name); ES_CodeGenerator::Register indexed_properties(enumerated_class_id); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_index), index); cg.LDR(OBJECT_MEMBER(object, ES_Object, indexed_properties), indexed_properties); cg.LDR(OBJECT_MEMBER(indexed_properties, ES_Compact_Indexed_Properties, capacity), SCRATCHI1); cg.CMP(index, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.ADD(indexed_properties, ES_OFFSETOF(ES_Compact_Indexed_Properties, values), property_value); cg.ADD(property_value, ES_CodeGenerator::Operand(index, 3), property_value); LoadValue(cg, property_value, 0, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); cg.CMP(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3), ESTYPE_UNDEFINED); cg.CMP(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3), 0, ES_NATIVE_CONDITION_EQUAL); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, target_vr); cg.EndOutOfOrderBlock(); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class_id); cg.LDR(OBJECT_MEMBER(object_class_id, ES_Class, class_id), object_class_id); cg.TEQ(enumerated_class_id, object_class_id); cg.Jump(indexed->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register enumerated_limit(enumerated_class_id); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_limit), enumerated_limit); cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.CMP(SCRATCHI1, enumerated_limit); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_LESS_OR_EQUAL); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_cached_type), type); ES_CodeGenerator::Register enumerated_cached_offset(enumerated_class_id); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_cached_offset), enumerated_cached_offset); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), property_value); cg.ADD(property_value, enumerated_cached_offset, property_value); CopyDataToValue(cg, property_value, type, target_vr); cg.SetOutOfOrderContinuationPoint(indexed); } void ES_Native::EmitPutEnumerated(VirtualRegister *object_vr, VirtualRegister *name_vr, VirtualRegister *source_vr) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register name(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register enumerated_class_id(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register object_class_id(ES_CodeGenerator::REG_R5); cg.LDR(BASE_REGISTER(name_vr), IVALUE_OFFSET(name_vr), name); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_string), SCRATCHI1); cg.TEQ(name, SCRATCHI1); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_class_id), enumerated_class_id); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class_id); cg.LDR(OBJECT_MEMBER(object_class_id, ES_Class, class_id), object_class_id); cg.TEQ(enumerated_class_id, object_class_id); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register enumerated_limit(object_class_id); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_limit), enumerated_limit); cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.CMP(SCRATCHI1, enumerated_limit); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_LESS_OR_EQUAL); ES_CodeGenerator::Register enumerated_cached_offset(enumerated_class_id); ES_CodeGenerator::Register property_value(enumerated_limit); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_cached_offset), enumerated_cached_offset); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), property_value); cg.ADD(property_value, enumerated_cached_offset, property_value); ES_CodeGenerator::Register type(ES_CodeGenerator::REG_R6); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, enumerated_cached_type), type); CopyValueToData(cg, source_vr, property_value, type, current_slow_case->GetJumpTarget()); } void ES_Native::EmitInt32StringIndexedGet(VirtualRegister *target_vr, VirtualRegister *string_vr, VirtualRegister *index_vr, unsigned constant_index, BOOL returnCharCode) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register string(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register value(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register offset(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register length(ES_CodeGenerator::REG_R5); LoadObjectOperand(string_vr->index, string); cg.LDR(OBJECT_MEMBER(string, JString, value), value); cg.TST(value, 1); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.ADD(value, ES_OFFSETOF(JStringStorage, storage), value); cg.LDR(OBJECT_MEMBER(string, JString, offset), offset); cg.ADD(value, ES_CodeGenerator::Operand(offset, 1), value); cg.LDR(OBJECT_MEMBER(string, JString, length), length); if (index_vr || !ES_CodeGenerator::Operand::EncodeImmediate(constant_index)) { if (index_vr) cg.LDR(BASE_REGISTER(index_vr), IVALUE_OFFSET(index_vr), offset); else { MoveImmediateToRegister(cg, constant_index, offset); constant_index = 0; } cg.CMP(offset, length); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.ADD(value, ES_CodeGenerator::Operand(offset, 1), value); } else { cg.CMP(length, constant_index); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); if (!ES_CodeGenerator::SupportedOffset(constant_index * 2, ES_CodeGenerator::LOAD_STORE_HALF_WORD)) { AddImmediateToRegister(cg, value, constant_index * 2, value); constant_index = 0; } } ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); ES_CodeGenerator::Register character(IVALUE_REGISTER(ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7)); cg.LDRH(value, constant_index * 2, character); if (returnCharCode) cg.MOV(ESTYPE_INT32, type); else { cg.CMP(character, STRING_NUMCHARS); cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER_OR_SAME); cg.MOV(ESTYPE_STRING, type); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, rt_data), string); AddImmediateToRegister(cg, string, ES_OFFSETOF(ESRT_Data, strings) + STRING_nul * sizeof(void *), string); cg.ADD(string, ES_CodeGenerator::Operand(character, 2), string); cg.LDR(string, 0, character); } StoreValue(cg, ES_CodeGenerator::REG_R6, ES_CodeGenerator::REG_R7, target_vr); } void ES_Native::EmitPrimitiveNamedGet(VirtualRegister *target_vr, ES_Object *check_object, ES_Object *property_object, unsigned class_id, unsigned property_offset, ES_StorageType storage_type, ES_Object *function) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object_class(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register klass_id(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register value(ES_CodeGenerator::REG_R7); MovePointerToRegister(cg, check_object, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class); cg.LDR(OBJECT_MEMBER(object_class, ES_Class, class_id), klass_id); EqCompareRegisterToImmediate(cg, klass_id, class_id); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); if (function) { MovePointerToRegister(cg, function, SCRATCHI_IVALUE); MoveImmediateToRegister(cg, ESTYPE_OBJECT, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } else if (property_object) { if (check_object != property_object) MovePointerToRegister(cg, property_object, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), value); if (property_value_write_vr == target_vr && (storage_type == ES_STORAGE_OBJECT || storage_type == ES_STORAGE_WHATEVER)) { SetPropertyValueTransferRegister(INTEGER_NR(this, ES_CodeGenerator::REG_R7), property_offset, storage_type != ES_STORAGE_OBJECT); if (current_slow_case) if (ES_CodeGenerator::OutOfOrderBlock *recover_from_failure = RecoverFromFailedPropertyValueTransfer(this, target_vr, ES_CodeGenerator::REG_R7)) cg.SetOutOfOrderContinuationPoint(recover_from_failure); } else CopyTypedDataToValue(cg, value, property_offset, storage_type, target_vr); } else EmitSetRegisterType(target_vr, ESTYPE_UNDEFINED); } void ES_Native::EmitFetchFunction(VirtualRegister *target_vr, ES_Object *function, VirtualRegister *object_vr, unsigned class_id, BOOL fetch_value) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object_class(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register klass_id(ES_CodeGenerator::REG_R4); LoadObjectOperand(object_vr->index, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class); cg.LDR(OBJECT_MEMBER(object_class, ES_Class, class_id), klass_id); EqCompareRegisterToImmediate(cg, klass_id, class_id); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); if (fetch_value) { MovePointerToRegister(cg, function, SCRATCHI_IVALUE); MoveImmediateToRegister(cg, ESTYPE_OBJECT, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } } static void ES_EmitGetCachePositiveBranch(ES_CodeGenerator &cg, const ES_Native::GetCacheGroup &group, const ES_Native::GetCacheGroup::Entry &entry, ES_CodeGenerator::JumpTarget **copy_value, ES_CodeGenerator::Register object, ES_CodeGenerator::Register value, BOOL properties_loaded, BOOL jump_when_finished) { DECLARE_NOTHING(); OP_ASSERT(entry.positive); if (!properties_loaded) cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), value); if (!group.single_offset && entry.positive_offset) AddImmediateToRegister(cg, value, entry.positive_offset, value); if (jump_when_finished) cg.Jump(copy_value[group.storage_type]); } static const ES_Native::GetCacheGroup * ES_FindGroupByStorageType(const ES_Native::GetCacheGroup *groups, ES_StorageType storage_type) { while (groups->storage_type != storage_type) ++groups; return groups; } static void ES_EmitGetCacheNegativeBranch(ES_CodeGenerator &cg, const ES_Native::GetCacheGroup *groups, const ES_Native::GetCacheGroup &group, const ES_Native::GetCacheGroup::Entry &entry, ES_CodeGenerator::JumpTarget **copy_value, ES_CodeGenerator::Register object, ES_CodeGenerator::Register value, BOOL jump_when_finished) { DECLARE_NOTHING(); OP_ASSERT(entry.prototype); const ES_Native::GetCacheGroup *actual_group; if (entry.prototype_storage_type == group.storage_type) actual_group = &group; else { actual_group = ES_FindGroupByStorageType(groups, entry.prototype_storage_type); jump_when_finished = TRUE; } MovePointerToRegister(cg, entry.prototype, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), value); if (!actual_group->single_offset && entry.prototype_offset) AddImmediateToRegister(cg, value, entry.prototype_offset, value); if (jump_when_finished) cg.Jump(copy_value[actual_group->storage_type]); } void ES_Native::EmitNamedGet(VirtualRegister *target_vr, VirtualRegister *object_vr, const ES_Native::GetCacheAnalysis &analysis, BOOL for_inlined_function_call, BOOL fetch_value) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object_class(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register klass_id(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register property_count(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register value; const ES_Native::GetCacheGroup *groups = analysis.groups; unsigned groups_count = analysis.groups_count; const ES_Native::GetCacheNegative *negatives = analysis.negatives; unsigned negatives_count = analysis.negatives_count; /* Storage type indexed array of jump targets for jumping to the code that actually copies the value from a certain storage type. Only set for those storage types we actually handle. */ ES_CodeGenerator::JumpTarget *copy_value[FIRST_SPECIAL_TYPE] = { NULL }; BOOL load_properties = FALSE; unsigned positive_count = 0; for (unsigned group_index = 0; group_index < groups_count; ++group_index) { const GetCacheGroup &group = groups[group_index]; if (!load_properties) for (unsigned entry_index = 0; !load_properties && entry_index < group.entries_count; ++entry_index) if (group.entries[entry_index].positive && ++positive_count > 1) load_properties = TRUE; if (!copy_value[group.storage_type]) copy_value[group.storage_type] = cg.ForwardJump(); } if (property_value_read_vr) value = ES_CodeGenerator::REG_R6; else value = ES_CodeGenerator::REG_R7; ES_CodeGenerator::JumpTarget *jt_not_found = negatives_count ? cg.ForwardJump() : NULL; ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); LoadObjectOperand(object_vr->index, object); property_value_nr = NULL; cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class); ES_CodeGenerator::JumpTarget *jt_finished = cg.ForwardJump(); cg.LDR(OBJECT_MEMBER(object_class, ES_Class, class_id), klass_id); if (load_properties) cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), value); ES_CodeGenerator::OutOfOrderBlock *recover_from_failure = NULL; BOOL property_value_transfer = property_value_write_vr == target_vr; if (property_value_transfer) { SetPropertyValueTransferRegister(INTEGER_NR(this, ES_CodeGenerator::REG_R7), property_value_write_offset, FALSE); recover_from_failure = RecoverFromFailedPropertyValueTransfer(this, target_vr, ES_CodeGenerator::REG_R7); } /* Somewhat silly, but makes it easier to read the code below. :-) */ BOOL properties_loaded = load_properties; ES_CodeGenerator::JumpTarget *jt_next_group = NULL; for (unsigned group_index = 0; group_index < groups_count; ++group_index) { const GetCacheGroup &group = groups[group_index]; BOOL last_group = group_index == groups_count - 1; BOOL last_group_with_entries = last_group || groups[group_index + 1].only_secondary_entries; if (!jt_next_group) jt_next_group = last_group_with_entries && !negatives_count ? slow_case : cg.ForwardJump(); unsigned entry_index = 0; while (entry_index < group.entries_count) { const GetCacheGroup::Entry &entry = group.entries[entry_index]; if (entry.prototype && entry.prototype_secondary_entry) { OP_ASSERT(!entry.positive && !entry.negative); ++entry_index; } else break; } for (unsigned index = entry_index; index < group.entries_count; ++index) if (group.entries[index].limit != UINT_MAX) { cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), property_count); break; } for (; entry_index < group.entries_count; ++entry_index) { const GetCacheGroup::Entry &entry = group.entries[entry_index]; BOOL last_entry = entry_index == group.entries_count - 1; ES_CodeGenerator::JumpTarget *jt_next_entry = NULL; CompareRegisterToImmediate(cg, klass_id, entry.class_id); BOOL need_positive_cache_hit_code = FALSE; BOOL need_negative_cache_hit_code = FALSE; BOOL need_limit_check = FALSE; if (entry.positive) { if (!properties_loaded) /* Need to load properties pointer. */ need_positive_cache_hit_code = TRUE; if (!group.single_offset && entry.positive_offset) /* Need to add offset to 'properties'. */ need_positive_cache_hit_code = TRUE; } if (entry.limit != UINT_MAX) /* Need limit check. */ need_limit_check = TRUE; if (entry.prototype) { /* All secondary entries should precede any regular entries, so the loop above should have skipped them all. */ OP_ASSERT(!entry.prototype_secondary_entry); /* Need to fetch properties pointer from prototype object. */ need_negative_cache_hit_code = TRUE; } if (!need_positive_cache_hit_code && !need_negative_cache_hit_code && !need_limit_check) /* The class ID check is all we need. */ if (last_entry) /* This is the last entry; jump to next group, or slow-case, if class ID check failed, and fall through to the value copying code if it succeeded. */ cg.Jump(jt_next_group, ES_NATIVE_CONDITION_NOT_EQUAL); else /* Otherwise jump to the value copying code if the class ID check succeeded, and fall through to the next entry if it failed. */ cg.Jump(copy_value[group.storage_type], ES_NATIVE_CONDITION_EQUAL); else { /* We need to execute one or more instructions after a successful class ID check, so first jump to the next entry, or next group (or slow-case,) if it failed. */ if (last_entry) cg.Jump(jt_next_group, ES_NATIVE_CONDITION_NOT_EQUAL); else cg.Jump(jt_next_entry = cg.ForwardJump(), ES_NATIVE_CONDITION_NOT_EQUAL); if (need_limit_check) { /* Perform limit check. */ CompareRegisterToImmediate(cg, property_count, entry.limit); if (!need_negative_cache_hit_code) { /* This cache either has no negative side at all, or doesn't need to execute any instructions if the limit check fails. */ ES_CodeGenerator::JumpTarget *jt_negative; if (entry.negative) { /* Failed limit check => property doesn't exist. */ if (!jt_not_found) jt_not_found = cg.ForwardJump(); jt_negative = jt_not_found; } else /* Failed limit check => cache entry not valid, and since we've done a class ID check, we know no other cache entry is valid either. */ jt_negative = slow_case; if (!need_positive_cache_hit_code && !last_entry) { cg.Jump(copy_value[group.storage_type], ES_NATIVE_CONDITION_HIGHER); cg.Jump(jt_negative); } else { cg.Jump(jt_negative, ES_NATIVE_CONDITION_LOWER_OR_SAME); ES_EmitGetCachePositiveBranch(cg, group, entry, copy_value, object, value, properties_loaded, !last_entry); } } else if (!need_positive_cache_hit_code) { /* This cache either has no positive side at all, or doesn't need to execute any additional instructions if the limit check succeeded, but do if the limit check failed. */ ES_CodeGenerator::JumpTarget *jt_positive; if (entry.positive) /* Successful limit check => copy value (at single offset, or zero offset.) */ jt_positive = copy_value[group.storage_type]; else /* "Successful" limit check => cache entry not valid, and since we've done a class ID check, we know no other cache entry is valid either. */ jt_positive = slow_case; cg.Jump(jt_positive, ES_NATIVE_CONDITION_HIGHER); ES_EmitGetCacheNegativeBranch(cg, groups, group, entry, copy_value, object, value, !last_entry); } else { /* We need to execute some additional instruction both on successful and failed limit check. Generate jump that skips the "negative branch" if the limit check fails. */ ES_CodeGenerator::JumpTarget *jt_positive = cg.ForwardJump(); cg.Jump(jt_positive, ES_NATIVE_CONDITION_HIGHER); ES_EmitGetCacheNegativeBranch(cg, groups, group, entry, copy_value, object, value, TRUE); cg.SetJumpTarget(jt_positive); ES_EmitGetCachePositiveBranch(cg, group, entry, copy_value, object, value, properties_loaded, !last_entry); } } else { /* No limit check needed, but some additional instructions need to be executed. */ /* Since we'll have no limit check, we must have exactly one branch of additional instructions. */ OP_ASSERT(need_positive_cache_hit_code != need_negative_cache_hit_code); if (need_positive_cache_hit_code) ES_EmitGetCachePositiveBranch(cg, group, entry, copy_value, object, value, properties_loaded, !last_entry); else ES_EmitGetCacheNegativeBranch(cg, groups, group, entry, copy_value, object, value, !last_entry); } if (jt_next_entry) cg.SetJumpTarget(jt_next_entry); } } unsigned offset_immediate = group.single_offset ? group.common_offset : 0; cg.SetJumpTarget(copy_value[group.storage_type]); if (property_value_transfer) { if (group.storage_type == ES_STORAGE_WHATEVER) { LoadOffset(cg, value, offset_immediate + VALUE_TYPE_OFFSET, SCRATCHI2); EqCompareRegisterToImmediate(cg, SCRATCHI2, ESTYPE_OBJECT); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } else if (group.storage_type == ES_STORAGE_OBJECT_OR_NULL) { LoadOffset(cg, value, offset_immediate, SCRATCHI2); EqCompareRegisterToImmediate(cg, SCRATCHI2, 0); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); } if (offset_immediate != property_value_offset) AddImmediateToRegister(cg, value, offset_immediate, ES_CodeGenerator::REG_R7); else if (value != ES_CodeGenerator::REG_R7) cg.MOV(value, ES_CodeGenerator::REG_R7); } else if (fetch_value) CopyTypedDataToValue(cg, value, offset_immediate, group.storage_type, target_vr); if (!last_group || jt_not_found) cg.Jump(jt_finished); if (!last_group_with_entries) { cg.SetJumpTarget(jt_next_group); jt_next_group = NULL; } } if (negatives_count) { if (jt_next_group) cg.SetJumpTarget(jt_next_group); for (unsigned index = 0; index < negatives_count; ++index) if (negatives[index].limit != UINT_MAX) { cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), property_count); break; } for (unsigned index = 0; index < negatives_count; ++index) { BOOL last_missing = index == negatives_count - 1; CompareRegisterToImmediate(cg, klass_id, negatives[index].class_id); if (negatives[index].limit == UINT_MAX) if (last_missing) cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); else cg.Jump(jt_not_found, ES_NATIVE_CONDITION_EQUAL); else { ES_CodeGenerator::JumpTarget *jt_next = NULL; if (last_missing) jt_next = slow_case; else jt_next = cg.ForwardJump(); cg.Jump(jt_next, ES_NATIVE_CONDITION_NOT_EQUAL); CompareRegisterToImmediate(cg, property_count, negatives[index].limit); if (last_missing) cg.Jump(slow_case, ES_NATIVE_CONDITION_HIGHER); else { cg.Jump(jt_not_found, ES_NATIVE_CONDITION_LOWER_OR_SAME); cg.Jump(slow_case); cg.SetJumpTarget(jt_next); } } } } if (jt_not_found) { cg.SetJumpTarget(jt_not_found); EmitSetRegisterType(target_vr, ESTYPE_UNDEFINED); } cg.SetJumpTarget(jt_finished); if (!property_value_nr) property_value_write_vr = NULL; if (recover_from_failure) cg.SetOutOfOrderContinuationPoint(recover_from_failure); } static void ES_EmitPropertyArraySizeCheck(ES_CodeGenerator &cg, ES_CodeGenerator::Register properties, unsigned size, ES_CodeGenerator::Register scratch, ES_CodeGenerator::JumpTarget *failure) { ES_DECLARE_NOTHING(); /* Offset from 'properties' to the size part of ES_Header::header. */ int objectsize_offset = -static_cast<int>(sizeof(ES_Header)) + 2; cg.LDRH(properties, objectsize_offset, scratch); if (size >= LARGE_OBJECT_LIMIT) { /* If the object's size is not 0xffff, then it's not allocated as a large object, meaning its size is smaller than LARGE_OBJECT_LIMIT and thus smaller than 'size'. */ CompareRegisterToImmediate(cg, scratch, 0xffff); cg.Jump(failure, ES_NATIVE_CONDITION_NOT_EQUAL); /* Offset from 'properties' to ES_PageHeader::limit. */ int pagelimit_offset = -static_cast<int>(sizeof(ES_Header)) - ES_PageHeader::HeaderSize() + ES_OFFSETOF(ES_PageHeader, limit); /* The object must be allocated as a large object, so calculate the page's actual size and use that as the size of the object. */ cg.LDR(properties, pagelimit_offset, scratch); cg.SUB(scratch, properties, scratch); cg.ADD(scratch, static_cast<int>(sizeof(ES_Header)), scratch); } /* Check that the object's size is at least 'size'. */ CompareRegisterToImmediate(cg, scratch, size); cg.Jump(failure, ES_NATIVE_CONDITION_LESS); } void ES_Native::EmitNamedPut(VirtualRegister *object_vr, VirtualRegister *source_vr, JString *name, BOOL has_complex_cache, ES_StorageType source_type) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register object_class(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register class_id(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R5); ES_CodeGenerator::Register source(ES_CodeGenerator::REG_R6); unsigned constant_cached_offset = 0; LoadObjectOperand(object_vr->index, object); ES_Code::PropertyCache *cache = &code->property_put_caches[CurrentCodeWord()[4].index]; OP_ASSERT(cache->class_id != ES_Class::NOT_CACHED_CLASS_ID); #ifdef SUPPORT_INLINE_ALLOCATION if (constructor_final_class && object_vr->index == 0) { CopyValue(cg, source_vr, properties, cache->cached_index, object, object_class); return; } #endif // SUPPORT_INLINE_ALLOCATION if (!current_slow_case) EmitSlowCaseCall(); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), properties); ES_CodeGenerator::JumpTarget *slow_case; if (!is_light_weight && property_value_read_vr && property_value_nr) { ES_CodeGenerator::OutOfOrderBlock *flush_object_vr = cg.StartOutOfOrderBlock(); cg.MOV(object, SCRATCHI_IVALUE); cg.MOV(ESTYPE_OBJECT, SCRATCHI_TYPE); StoreValue(cg, SCRATCHI1, SCRATCHI2, object_vr); cg.Jump(current_slow_case_main); cg.EndOutOfOrderBlock(FALSE); slow_case = flush_object_vr->GetJumpTarget(); } else slow_case = current_slow_case->GetJumpTarget(); cg.LDR(OBJECT_MEMBER(object, ES_Object, klass), object_class); cg.LDR(OBJECT_MEMBER(object_class, ES_Class, class_id), class_id); while (!ES_Code::IsSimplePropertyCache(cache, FALSE)) cache = cache->next; ES_CodeGenerator::JumpTarget *size_4_target = NULL, *size_8_target = NULL, *null_target = NULL, *int_to_double_target = NULL; AddImmediateToRegister(cg, BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr->index), source); if (has_complex_cache) { unsigned cache_size = 0; ES_CodeGenerator::JumpTarget *new_class_slow_case = NULL; while (TRUE) { ES_Code::PropertyCache *next_cache = cache_size++ < MAX_PROPERTY_CACHE_SIZE ? cache->next : NULL; while (next_cache && (!ES_Code::IsSimplePropertyCache(next_cache, FALSE) || cache->class_id == next_cache->class_id)) next_cache = next_cache->next; unsigned current_id = cache->class_id; ES_CodeGenerator::JumpTarget *jt_next_unpaired = next_cache ? cg.ForwardJump() : slow_case; EqCompareRegisterToImmediate(cg, class_id, current_id); cg.Jump(jt_next_unpaired, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::JumpTarget *jt_next = NULL; while (cache->class_id == current_id) { ES_StorageType type = cache->GetStorageType(); ES_CodeGenerator::JumpTarget *current_slow_case = slow_case; jt_next = cache->next != next_cache && next_cache ? cg.ForwardJump() : NULL; BOOL needs_limit_check = cache->object_class->NeedLimitCheck(cache->GetLimit(), cache->data.new_class != NULL); unsigned size = ES_Layout_Info::SizeOf(type); if (needs_limit_check) { cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, cache->GetLimit()); /* The cache limit checks are as follows: In both cases the stored cache limit is the index that we wrote the property to originally. For the case where cache->data.new_class is not NULL, we are appending a new property which means that the stored index must at this point be equal to the property count, and if it isn't the cache is invalid. If cache->data.new_class is NULL we are writing into an object, and thus for the cache to be valid, the cache limit must be less than the property count, i.e. if the property count is less than or equal to the cache limit the cache is invalid. */ if (cache->data.new_class) cg.Jump(jt_next ? jt_next : slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); else cg.Jump(jt_next ? jt_next : slow_case, ES_NATIVE_CONDITION_LESS_OR_EQUAL); } if (cache->data.new_class) { OP_ASSERT(!cache->data.new_class->HasHashTableProperties()); ES_EmitPropertyArraySizeCheck(cg, properties, cache->GetOffset() + size + sizeof(ES_Header), SCRATCHI2, slow_case); if (cache->data.new_class != cache->object_class) { MovePointerToRegister(cg, cache->data.new_class, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, klass)); } cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.ADD(SCRATCHI1, 1, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, property_count)); if (!new_class_slow_case) { ES_CodeGenerator::OutOfOrderBlock *revert_put_cached_new = cg.StartOutOfOrderBlock(); cg.STR(object_class, OBJECT_MEMBER(object, ES_Object, klass)); cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.SUB(SCRATCHI1, 1, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, property_count)); cg.Jump(slow_case); cg.EndOutOfOrderBlock(FALSE); new_class_slow_case = revert_put_cached_new->GetJumpTarget(); } current_slow_case = new_class_slow_case; } if (cache->GetOffset() != 0) AddImmediateToRegister(cg, properties, cache->GetOffset(), properties); BOOL skip_write = FALSE; if (type != ES_STORAGE_WHATEVER && source_type != type) skip_write = EmitTypeConversionCheck(type, source_type, source_vr, current_slow_case, null_target, int_to_double_target); if (type == ES_STORAGE_NULL) { if (!null_target) null_target = cg.ForwardJump(); cg.Jump(null_target); } else if (!skip_write) JumpToSize(cg, size, size_4_target, size_8_target); if (jt_next) cg.SetJumpTarget(jt_next); if (cache->next) cache = cache->next; else { OP_ASSERT(next_cache == NULL); break; } } if (next_cache) { cg.SetJumpTarget(jt_next_unpaired); cache = next_cache; } else break; } if (size_4_target || size_8_target) CopyValueToData2(cg, source, properties, size_4_target, size_8_target); } else { EqCompareRegisterToImmediate(cg, class_id, cache->class_id); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); constant_cached_offset = cache->GetOffset(); ES_StorageType constant_cached_type = cache->GetStorageType(); if (cache->data.new_class) { OP_ASSERT(!cache->data.new_class->HasHashTableProperties()); if (cache->object_class->NeedLimitCheck(cache->GetLimit(), TRUE)) { cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI2); EqCompareRegisterToImmediate(cg, SCRATCHI2, cache->GetLimit()); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); } ES_EmitPropertyArraySizeCheck(cg, properties, constant_cached_offset + ES_Layout_Info::SizeOf(constant_cached_type) + sizeof(ES_Header), SCRATCHI2, slow_case); if (cache->data.new_class != cache->object_class) { MovePointerToRegister(cg, cache->data.new_class, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, klass)); } cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.ADD(SCRATCHI1, 1, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, property_count)); ES_CodeGenerator::OutOfOrderBlock *revert_put_cached_new = cg.StartOutOfOrderBlock(); if (cache->data.new_class != cache->object_class) cg.STR(object_class, OBJECT_MEMBER(object, ES_Object, klass)); cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI1); cg.SUB(SCRATCHI1, 1, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(object, ES_Object, property_count)); cg.Jump(slow_case); cg.EndOutOfOrderBlock(FALSE); slow_case = revert_put_cached_new->GetJumpTarget(); } else if (cache->object_class->NeedLimitCheck(cache->GetLimit(), FALSE)) { cg.LDR(OBJECT_MEMBER(object, ES_Object, property_count), SCRATCHI2); CompareRegisterToImmediate(cg, SCRATCHI2, cache->GetLimit()); cg.Jump(slow_case, ES_NATIVE_CONDITION_LESS_OR_EQUAL); } BOOL skip_write = FALSE; if (constant_cached_type != ES_STORAGE_WHATEVER && source_type != constant_cached_type) skip_write = EmitTypeConversionCheck(constant_cached_type, source_type, source_vr, slow_case, null_target, int_to_double_target); if (!skip_write) CopyValueToTypedData(cg, source_vr, properties, constant_cached_offset, constant_cached_type, NULL, object, object_class); } EmitTypeConversionHandlers(source_vr, properties, constant_cached_offset, null_target, int_to_double_target); } void ES_Native::EmitLengthGet(VirtualRegister *target_vr, VirtualRegister *object_vr, unsigned handled, unsigned possible, ES_CodeGenerator::JumpTarget *slow_case) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::OutOfOrderBlock *handle_object = NULL; if (handled & ESTYPE_BITS_OBJECT) { if (!slow_case) { if (!current_slow_case) EmitSlowCaseCall(); slow_case = current_slow_case->GetJumpTarget(); } if (handled & ESTYPE_BITS_STRING) handle_object = cg.StartOutOfOrderBlock(); if (handled != possible) EmitRegisterTypeCheck(object_vr, ESTYPE_OBJECT, slow_case); ES_CodeGenerator::Register array(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register klass(ES_CodeGenerator::REG_R3); ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R4); ES_CodeGenerator::Register class_id(ES_CodeGenerator::REG_R5); LoadObjectOperand(object_vr->index, array); cg.LDR(OBJECT_MEMBER(array, ES_Object, klass), klass); cg.LDR(OBJECT_MEMBER(klass, ES_Class, class_id), class_id); EqCompareRegisterToImmediate(cg, class_id, code->global_object->GetArrayClass()->GetId(context)); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); cg.LDR(OBJECT_MEMBER(array, ES_Object, properties), properties); CopyTypedDataToValue(cg, properties, 0, ES_STORAGE_INT32, target_vr); if (!handle_object) return; cg.EndOutOfOrderBlock(); slow_case = handle_object->GetJumpTarget(); } if (possible != ESTYPE_BITS_STRING) { if (!slow_case) { if (!current_slow_case) EmitSlowCaseCall(); slow_case = current_slow_case->GetJumpTarget(); } EmitRegisterTypeCheck(object_vr, ESTYPE_STRING, slow_case); } ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); LoadObjectOperand(object_vr->index, value); cg.MOV(ESTYPE_INT32, type); cg.LDR(OBJECT_MEMBER(value, JString, length), value); StoreValue(cg, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3, target_vr); if (handle_object) cg.SetOutOfOrderContinuationPoint(handle_object); } void ES_Native::EmitFetchPropertyValue(VirtualRegister *target_vr, VirtualRegister *object_vr, ES_Object *static_object, ES_Class *klass, unsigned property_index) { DECLARE_NOTHING(); ES_CodeGenerator::Register object(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register properties(VALUE_TRANSFER_POINTER); if (object_vr) cg.LDR(BASE_REGISTER(object_vr), IVALUE_OFFSET(object_vr), object); else MovePointerToRegister(cg, static_object, object); cg.LDR(OBJECT_MEMBER(object, ES_Object, properties), properties); ES_Layout_Info layout = klass->GetLayoutInfoAtInfoIndex(ES_PropertyIndex(property_index)); ES_StorageType storage_type = layout.GetStorageType(); if (property_value_write_vr && (storage_type == ES_STORAGE_OBJECT || storage_type == ES_STORAGE_WHATEVER)) { OP_ASSERT(property_value_write_vr == target_vr); SetPropertyValueTransferRegister(INTEGER_NR(this, VALUE_TRANSFER_POINTER), layout.GetOffset(), storage_type != ES_STORAGE_OBJECT); } else CopyTypedDataToValue(cg, properties, layout.GetOffset(), storage_type, target_vr); } void ES_Native::EmitGlobalGet(VirtualRegister *target_vr, unsigned class_id, unsigned cached_offset, unsigned cached_type) { if (class_id != ES_Class::NOT_CACHED_CLASS_ID) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); if (!c_global_object) c_global_object = cg.NewConstant(code->global_object); ES_CodeGenerator::Register global_object(ES_CodeGenerator::REG_R2); ES_StorageType type = ES_Value_Internal::StorageTypeFromCachedTypeBits(cached_type); cg.LDR(c_global_object, global_object); ES_CodeGenerator::Register klass(ES_CodeGenerator::REG_R3), id(klass); cg.LDR(OBJECT_MEMBER(global_object, ES_Object, klass), klass); cg.LDR(OBJECT_MEMBER(klass, ES_Class, class_id), id); EqCompareRegisterToImmediate(cg, id, class_id); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R7); cg.LDR(OBJECT_MEMBER(global_object, ES_Object, properties), properties); if (property_value_write_vr && (type == ES_STORAGE_OBJECT || type == ES_STORAGE_WHATEVER)) { OP_ASSERT(property_value_write_vr == target_vr); SetPropertyValueTransferRegister(INTEGER_NR(this, ES_CodeGenerator::REG_R7), cached_offset, type != ES_STORAGE_OBJECT); if (current_slow_case) { ES_CodeGenerator::OutOfOrderBlock *recover_from_failure = RecoverFromFailedPropertyValueTransfer(this, target_vr, ES_CodeGenerator::REG_R7); if (recover_from_failure) cg.SetOutOfOrderContinuationPoint(recover_from_failure); } } else CopyTypedDataToValue(cg, properties, cached_offset, type, target_vr); } else EmitInstructionHandlerCall(); if (!property_value_nr) property_value_write_vr = NULL; } void ES_Native::EmitGlobalPut(VirtualRegister *source_vr, unsigned class_id, unsigned cached_offset, unsigned cached_type, ES_StorageType source_type) { if (class_id != ES_Class::NOT_CACHED_CLASS_ID) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); if (!c_global_object) c_global_object = cg.NewConstant(code->global_object); ES_CodeGenerator::Register global_object(ES_CodeGenerator::REG_R2); cg.LDR(c_global_object, global_object); ES_CodeGenerator::Register klass(ES_CodeGenerator::REG_R3), id(klass); cg.LDR(OBJECT_MEMBER(global_object, ES_Object, klass), klass); cg.LDR(OBJECT_MEMBER(klass, ES_Class, class_id), id); EqCompareRegisterToImmediate(cg, id, class_id); cg.Jump(slow_case, ES_NATIVE_CONDITION_NOT_EQUAL); ES_CodeGenerator::Register properties(ES_CodeGenerator::REG_R3); cg.LDR(OBJECT_MEMBER(global_object, ES_Object, properties), properties); ES_CodeGenerator::JumpTarget *null_target = NULL, *int_to_double_target = NULL; ES_StorageType type = ES_Value_Internal::StorageTypeFromCachedTypeBits(cached_type); BOOL skip_write = FALSE; if (type != ES_STORAGE_WHATEVER && source_type != type) skip_write = EmitTypeConversionCheck(type, source_type, source_vr, slow_case, null_target, int_to_double_target); if (!skip_write) CopyValueToTypedData(cg, source_vr, properties, cached_offset, type, slow_case, ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5); EmitTypeConversionHandlers(source_vr, properties, cached_offset, null_target, int_to_double_target); } else EmitInstructionHandlerCall(); } void ES_Native::EmitGlobalImmediateGet(VirtualRegister *target_vr, unsigned index, BOOL for_inlined_function_call, BOOL fetch_value) { DECLARE_NOTHING(); if (for_inlined_function_call) { if (!c_code) c_code = cg.NewConstant(code); ES_CodeGenerator::Register code_pointer(ES_CodeGenerator::REG_R2); cg.LDR(c_code, code_pointer); ES_CodeGenerator::OutOfOrderBlock *failed_inlined_function = cg.StartOutOfOrderBlock(); cg.MOV(1, SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(code_pointer, ES_Code, has_failed_inlined_function)); EmitInstructionHandlerCall(); cg.EndOutOfOrderBlock(FALSE); cg.LDR(OBJECT_MEMBER(code_pointer, ES_Code, global_object), SCRATCHI2); cg.LDR(OBJECT_MEMBER(SCRATCHI2, ES_Global_Object, immediate_function_serial_nr), SCRATCHI2); EqCompareRegisterToImmediate(cg, SCRATCHI2, code->global_object->immediate_function_serial_nr); cg.Jump(failed_inlined_function->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); } if (fetch_value) { if (!c_global_object) c_global_object = cg.NewConstant(code->global_object); cg.LDR(c_global_object, SCRATCHI1); cg.LDR(OBJECT_MEMBER(SCRATCHI1, ES_Global_Object, variable_values), ES_CodeGenerator::REG_R2); CopyValue(cg, ES_CodeGenerator::REG_R2, VALUE_OFFSET(index), target_vr); } } void ES_Native::EmitGlobalImmediatePut(unsigned index, VirtualRegister *source_vr) { DECLARE_NOTHING(); if (!c_global_object) c_global_object = cg.NewConstant(code->global_object); cg.LDR(c_global_object, SCRATCHI1); cg.LDR(OBJECT_MEMBER(SCRATCHI1, ES_Global_Object, variable_values), ES_CodeGenerator::REG_R2); CopyValue(cg, source_vr, ES_CodeGenerator::REG_R2, VALUE_OFFSET(index)); } void ES_Native::EmitLexicalGet(VirtualRegister *target_vr, VirtualRegister *function_vr, unsigned scope_index, unsigned variable_index) { DECLARE_NOTHING(); if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::JumpTarget *slow_case = current_slow_case->GetJumpTarget(); ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register variables(ES_CodeGenerator::REG_R3); cg.LDR(BASE_REGISTER(function_vr), IVALUE_OFFSET(function_vr), function); unsigned offset = ES_OFFSETOF(ES_Function, scope_chain) + scope_index * sizeof(ES_Object *); if (ES_CodeGenerator::SupportedOffset(offset, ES_CodeGenerator::LOAD_STORE_WORD)) cg.LDR(function, offset, variables); else { AddImmediateToRegister(cg, function, offset, variables); cg.LDR(variables, 0, variables); } cg.LDR(OBJECT_MEMBER(variables, ES_Object, properties), variables); AddImmediateToRegister(cg, variables, 4, variables); LoadValue(cg, variables, VALUE_OFFSET(variable_index), ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5); cg.CMP(TYPE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5), ESTYPE_BOXED); cg.Jump(slow_case, ES_NATIVE_CONDITION_EQUAL); StoreValue(cg, ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5, target_vr); } void ES_Native::EmitFormatString(VirtualRegister *target_vr, VirtualRegister *source_vr, unsigned cache_index) { if (!current_slow_case) EmitSlowCaseCall(); ES_CodeGenerator::Register string(ES_CodeGenerator::REG_R2); ES_CodeGenerator::Register from(ES_CodeGenerator::REG_R3); cg.LDR(BASE_REGISTER(source_vr), VALUE_OFFSET(source_vr), string); cg.LDR(cg.NewConstant(&code->format_string_caches[cache_index].from), from); cg.TEQ(string, from); cg.Jump(current_slow_case->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.MOV(ESTYPE_STRING, SCRATCHI_TYPE); cg.LDR(cg.NewConstant(&code->format_string_caches[cache_index].to), SCRATCHI_IVALUE); StoreValue(cg, SCRATCHI1, SCRATCHI2, target_vr); } void ES_Native::EmitTableSwitch(VirtualRegister *value_vr, int minimum, int maximum, ES_CodeGenerator::Constant *table, ES_CodeGenerator::JumpTarget *default_target) { DECLARE_NOTHING(); ES_CodeGenerator::Register type(TYPE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_CodeGenerator::Register value(IVALUE_REGISTER(ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3)); ES_ValueType known_type; if (!GetType(value_vr, known_type)) known_type = ESTYPE_UNDEFINED; else if (known_type != ESTYPE_INT32 && known_type != ESTYPE_DOUBLE && known_type != ESTYPE_INT32_OR_DOUBLE) { cg.Jump(default_target); return; } if (known_type != ESTYPE_INT32) { ES_CodeGenerator::OutOfOrderBlock *convert_double = NULL; if (known_type != ESTYPE_DOUBLE) convert_double = cg.StartOutOfOrderBlock(); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.ADD(REGISTER_FRAME_POINTER, VALUE_OFFSET(value_vr), ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::GetDoubleAsInt)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.MOV(ES_CodeGenerator::REG_R0, value); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, implicit_bool), SCRATCHI1); cg.TEQ(SCRATCHI1, 0); cg.Jump(default_target, ES_NATIVE_CONDITION_NOT_EQUAL); if (convert_double) { cg.EndOutOfOrderBlock(); LoadValue(cg, value_vr, ES_CodeGenerator::REG_R2, ES_CodeGenerator::REG_R3); cg.CMP(type, ESTYPE_DOUBLE); cg.Jump(convert_double->GetJumpTarget(), ES_NATIVE_CONDITION_LESS_OR_EQUAL); if (known_type != ESTYPE_INT32_OR_DOUBLE) { cg.CMP(type, ESTYPE_INT32); cg.Jump(default_target, ES_NATIVE_CONDITION_NOT_EQUAL); } cg.SetOutOfOrderContinuationPoint(convert_double); } } else cg.LDR(BASE_REGISTER(value_vr), IVALUE_OFFSET(value_vr), value); if (minimum != 0) AddImmediateToRegister(cg, -minimum, value); CompareRegisterToImmediate(cg, value, maximum - minimum); cg.Jump(default_target, ES_NATIVE_CONDITION_HIGHER); ES_CodeGenerator::Register jump_table(ES_CodeGenerator::REG_R3); cg.LDR(cg.AddressOf(table), jump_table); cg.LDR(jump_table, value, ES_CodeGenerator::SHIFT_LOGICAL_LEFT, 2, TRUE, ES_CodeGenerator::REG_PC); } ES_CodeGenerator::JumpTarget * ES_Native::EmitPreConditionsStart(unsigned cw_index) { DECLARE_NOTHING(); ES_CodeGenerator::OutOfOrderBlock *slow_case = cg.StartOutOfOrderBlock(); if (!c_code) c_code = cg.NewConstant(code); cg.MOV(1, ES_CodeGenerator::REG_R0); cg.LDR(c_code, ES_CodeGenerator::REG_R1); cg.STR(ES_CodeGenerator::REG_R0, OBJECT_MEMBER(ES_CodeGenerator::REG_R1, ES_Code, has_failed_preconditions)); if (!c_ForceUpdateNativeDispatcher) c_ForceUpdateNativeDispatcher = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ForceUpdateNativeDispatcher)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MoveImmediateToRegister(cg, cw_index + (constructor ? code->data->codewords_count : 0), ES_CodeGenerator::REG_R1); cg.LDR(c_ForceUpdateNativeDispatcher, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.BX(ES_CodeGenerator::REG_R0); cg.EndOutOfOrderBlock(FALSE); return slow_case->GetJumpTarget(); } void ES_Native::EmitArithmeticBlockSlowPath(ArithmeticBlock *arithmetic_block) { DECLARE_NOTHING(); unsigned end_instruction_index = arithmetic_block->end_instruction_index; unsigned last_instruction_index = end_instruction_index - 1; unsigned last_cw_index = code->data->instruction_offsets[last_instruction_index]; switch (code->data->codewords[last_cw_index].instruction) { case ESI_RETURN_VALUE: case ESI_JUMP_IF_TRUE: case ESI_JUMP_IF_FALSE: end_instruction_index = last_instruction_index; } unsigned end_cw_index = code->data->instruction_offsets[end_instruction_index]; arithmetic_block->slow_case = current_slow_case = cg.StartOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT OpString annotation; annotation.AppendFormat(UNI_L(" from EmitArithmeticBlockSlowPath(), for block [%u, %u)"), arithmetic_block->start_cw_index, arithmetic_block->end_cw_index); if (end_cw_index == last_cw_index) { annotation.AppendL(" with trailing "); annotation.AppendL(g_instruction_strings[code->data->codewords[last_cw_index].instruction]); } annotation.AppendL(":\n"); cg.Annotate(annotation.CStr()); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (!is_light_weight) EmitExecuteBytecode(arithmetic_block->start_instruction_index, end_instruction_index, end_cw_index != last_cw_index); if (end_cw_index == last_cw_index) { if (end_cw_index == entry_point_cw_index) entry_point_jump_target = EmitEntryPoint(); switch (code->data->codewords[last_cw_index].instruction) { case ESI_RETURN_VALUE: cw_index = last_cw_index; EmitRegisterCopy(VR(code->data->codewords[last_cw_index + 1].index), VR(0)); cg.Jump(epilogue_jump_target); cg.EndOutOfOrderBlock(FALSE); break; case ESI_JUMP_IF_TRUE: case ESI_JUMP_IF_FALSE: ES_CodeGenerator::JumpTarget *true_target = NULL, *false_target = NULL; Operand value_target; GetConditionalTargets(last_cw_index, value_target, true_target, false_target); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, implicit_bool), SCRATCHI1); cg.TEQ(SCRATCHI1, 0); if (true_target) cg.Jump(true_target, ES_NATIVE_CONDITION_NOT_EQUAL); else cg.Jump(false_target, ES_NATIVE_CONDITION_EQUAL); cg.EndOutOfOrderBlock(); } } else cg.EndOutOfOrderBlock(); } ES_CodeGenerator::JumpTarget * ES_Native::EmitEntryPoint(BOOL custom_light_weight_entry) { if (is_light_weight) { DECLARE_NOTHING(); if (entry_point_cw_index == 0 && prologue_entry_point) return NULL; ES_CodeGenerator::JumpTarget *real_entry_point = NULL; ES_CodeGenerator::OutOfOrderBlock *the_lightweight_entry_point = NULL; if (!custom_light_weight_entry) { real_entry_point = cg.Here(); the_lightweight_entry_point = cg.StartOutOfOrderBlock(); } cg.ADD(ES_CodeGenerator::REG_SP, StackSpaceAllocated() - sizeof(void *), ES_CodeGenerator::REG_SP); cg.POP(SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, native_stack_frame)); cg.POP(ES_CodeGenerator::REG_LR); if (!custom_light_weight_entry) { cg.Jump(real_entry_point); cg.EndOutOfOrderBlock(FALSE); return the_lightweight_entry_point->GetJumpTarget(); } else return NULL; } #ifndef OPPSEUDOTHREAD_STACK_SWAPPING else if (prologue_entry_point) { ES_CodeGenerator::JumpTarget *real_entry_point = cg.Here(); ES_CodeGenerator::OutOfOrderBlock *the_prologue_entry_point = cg.StartOutOfOrderBlock(); BOOL has_variable_object; SetupNativeStackFrame(this, code, stack_space_allocated, stack_frame_padding, has_variable_object, TRUE); cg.Jump(real_entry_point); cg.EndOutOfOrderBlock(FALSE); return the_prologue_entry_point->GetJumpTarget(); } #endif // OPPSEUDOTHREAD_STACK_SWAPPING else return cg.Here(); } ES_CodeGenerator::JumpTarget * ES_Native::EmitInlineResumption(unsigned class_id, VirtualRegister *object_vr, ES_CodeGenerator::JumpTarget *failure, unsigned char *mark_failure) { DECLARE_NOTHING(); entry_point_jump_target = EmitEntryPoint(FALSE); ES_CodeGenerator::OutOfOrderBlock *extra_check = cg.StartOutOfOrderBlock(); LoadObjectOperand(object_vr->index, SCRATCHI2); cg.LDR(OBJECT_MEMBER(SCRATCHI2, ES_Object, klass), SCRATCHI2); cg.LDR(OBJECT_MEMBER(SCRATCHI2, ES_Class, class_id), SCRATCHI2); EqCompareRegisterToImmediate(cg, SCRATCHI2, class_id); cg.Jump(entry_point_jump_target, ES_NATIVE_CONDITION_EQUAL); /* Update profile data to indicate that the instruction failed inlining. */ MovePointerToRegister(cg, mark_failure, SCRATCHI1); cg.LDRB(SCRATCHI1, 0, SCRATCHI2); cg.ORR(SCRATCHI2, ES_CodeStatic::GET_FAILED_INLINE, SCRATCHI2); cg.STRB(SCRATCHI2, SCRATCHI1, 0); cg.Jump(failure); cg.EndOutOfOrderBlock(FALSE); return extra_check->GetJumpTarget(); } void ES_Native::EmitTick() { DECLARE_NOTHING(); if (!check_out_of_time) { check_out_of_time = cg.StartOutOfOrderBlock(); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::CheckOutOfTimeFromMachineCode)), ES_CodeGenerator::REG_PC); cg.EndOutOfOrderBlock(FALSE); } ES_CodeGenerator::Register time_until_check(ES_CodeGenerator::REG_R2); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, time_until_check), time_until_check); cg.SUB(time_until_check, 1, time_until_check, ES_CodeGenerator::SET_CONDITION_CODES); cg.STR(time_until_check, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, time_until_check), ES_NATIVE_CONDITION_NOT_EQUAL); cg.Call(check_out_of_time->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); } static ES_CodeGenerator::OutOfOrderBlock * InitializeFormals(ES_Native *native, unsigned formals_count) { ES_CodeGenerator &cg = native->cg; ES_CodeGenerator::OutOfOrderBlock *initialize_formals = cg.StartOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from GeneratePrologue(), initializing formals to undefined:\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(ESTYPE_UNDEFINED, ES_CodeGenerator::REG_R0); unsigned vr_index = 2 + formals_count - 1; if (formals_count > 1) { /* Let PARAMETERS_COUNT be the number of formals to set to undefined minus one. This will be at least zero, because this is a slow case that is only called the function is called with too few arguments. */ cg.RSB(PARAMETERS_COUNT, formals_count - 1, PARAMETERS_COUNT); ES_NativeJumpCondition condition(ES_NATIVE_CONDITION_ALWAYS); while (TRUE) { cg.STR(ES_CodeGenerator::REG_R0, BASE_REGISTER(native->VR(vr_index)), TYPE_OFFSET(native->VR(vr_index)), condition); if (--vr_index < 2) break; cg.SUB(PARAMETERS_COUNT, 1, PARAMETERS_COUNT, ES_CodeGenerator::SET_CONDITION_CODES); condition = ES_NATIVE_CONDITION_POSITIVE_OR_ZERO; } } else cg.STR(ES_CodeGenerator::REG_R0, BASE_REGISTER(native->VR(vr_index)), TYPE_OFFSET(native->VR(vr_index))); cg.EndOutOfOrderBlock(); return initialize_formals; } void ES_Native::GeneratePrologue() { DECLARE_NOTHING(); if (!constructor && code->data->codewords_count == 1 && code->data->codewords[0].instruction == ESI_RETURN_NO_VALUE) return; cg.StartPrologue(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from GeneratePrologue():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (entry_point_cw == code->data->codewords && prologue_entry_point && !entry_point_jump_target) entry_point_jump_target = cg.Here(); BOOL has_variable_object = FALSE; if (is_trivial) { if (code->type == ES_Code::TYPE_FUNCTION) { ES_FunctionCodeStatic *data = fncode->GetData(); if (is_inlined_function_call) { for (unsigned index = inlined_call_argc; index < data->formals_count; index++) EmitSetRegisterType(VR(2 + index), ESTYPE_UNDEFINED); } else if (data->formals_count > 0) { ES_CodeGenerator::OutOfOrderBlock *initialize_formals = InitializeFormals(this, data->formals_count); cg.CMP(PARAMETERS_COUNT, data->formals_count); cg.Jump(initialize_formals->GetJumpTarget(), ES_NATIVE_CONDITION_LESS); cg.SetOutOfOrderContinuationPoint(initialize_formals); } } } else { if (is_light_weight) { if (!light_weight_failure) EmitLightWeightFailure(); if (fncode) if (is_inlined_function_call) { ES_FunctionCode *fncode = static_cast<ES_FunctionCode *>(code); for (unsigned index = inlined_call_argc; index < fncode->GetData()->formals_count; ++index) EmitSetRegisterType(VR(2 + index), ESTYPE_UNDEFINED); } else { cg.CMP(PARAMETERS_COUNT, fncode->GetData()->formals_count); cg.Jump(light_weight_wrong_argc, ES_NATIVE_CONDITION_NOT_EQUAL); } if (optimization_data->uses_this && !code->data->is_strict_mode) { ES_CodeGenerator::OutOfOrderBlock *prepare_this(cg.StartOutOfOrderBlock()); ES_CodeGenerator::Constant *c_PrepareThisObjectLightWeight(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::PrepareThisObjectLightWeight))); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R1); EmitFunctionCall(c_PrepareThisObjectLightWeight); cg.EndOutOfOrderBlock(); EmitRegisterTypeCheck(VR(0), ESTYPE_OBJECT, prepare_this->GetJumpTarget()); cg.SetOutOfOrderContinuationPoint(prepare_this); } } else { #ifdef OPPSEUDOTHREAD_STACK_SWAPPING /* A loop dispatcher will have its stack frame created by ES_Execution_Context::ReconstructNativeStack(). */ if (!loop_dispatcher) #endif // OPPSEUDOTHREAD_STACK_SWAPPING { SetupNativeStackFrame(this, code, stack_space_allocated, stack_frame_padding, has_variable_object); OP_ASSERT(StackSpaceAllocated() == stack_space_allocated); } else stack_space_allocated = StackSpaceAllocated(); ES_CodeGenerator::OutOfOrderBlock *stack_or_register_limit_exceeded = cg.StartOutOfOrderBlock(); ES_CodeGenerator::Constant *constant = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::StackOrRegisterLimitExceeded)); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from GeneratePrologue(), calling StackOrRegisterLimitExceeded():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(constructor ? 1 : 0, ES_CodeGenerator::REG_R1); cg.LDR(constant, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.ADD(ES_CodeGenerator::REG_SP, stack_space_allocated, ES_CodeGenerator::REG_SP); cg.POP(ES_CodeGenerator::REG_PC); cg.EndOutOfOrderBlock(FALSE); if (entry_point_cw_index == 0 && !prologue_entry_point) { ES_CodeGenerator::OutOfOrderBlock *entry_point = cg.StartOutOfOrderBlock(); entry_point_jump_target = cg.Here(); cg.LDR(ES_CodeGenerator::REG_SP, stack_frame_padding, PARAMETERS_COUNT); cg.EndOutOfOrderBlock(); cg.SetOutOfOrderContinuationPoint(entry_point); } cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, stack_limit), SCRATCHI1); cg.CMP(ES_CodeGenerator::REG_SP, SCRATCHI1); cg.Jump(stack_or_register_limit_exceeded->GetJumpTarget(), ES_NATIVE_CONDITION_LOWER); cg.MOV(PARAMETERS_COUNT, ES_CodeGenerator::REG_R4); cg.LDR(OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, reg_limit), SCRATCHI1); AddImmediateToRegister(cg, -static_cast<int>(code->data->register_frame_size * sizeof(ES_Value_Internal)), SCRATCHI1); cg.MOV(ES_CodeGenerator::REG_R4, PARAMETERS_COUNT); cg.CMP(SCRATCHI1, REGISTER_FRAME_POINTER); cg.Jump(stack_or_register_limit_exceeded->GetJumpTarget(), ES_NATIVE_CONDITION_LOWER); if (fncode) { if (!constructor && optimization_data->uses_this && !code->data->is_strict_mode) { ES_CodeGenerator::OutOfOrderBlock *prepare_this(cg.StartOutOfOrderBlock()); ES_CodeGenerator::Constant *c_PrepareThisObject(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Native::PrepareThisObject))); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from GeneratePrologue(), calling PrepareThis():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(PARAMETERS_COUNT, ES_CodeGenerator::REG_R4); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R1); cg.LDR(c_PrepareThisObject, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.MOV(ES_CodeGenerator::REG_R4, PARAMETERS_COUNT); cg.EndOutOfOrderBlock(); EmitRegisterTypeCheck(VR(0), ESTYPE_OBJECT, prepare_this->GetJumpTarget()); cg.SetOutOfOrderContinuationPoint(prepare_this); } ES_FunctionCodeStatic *data = fncode->GetData(); ES_CodeGenerator::OutOfOrderBlock *create_arguments_object; /* Create arguments array, if necessary. */ BOOL may_use_arguments = !data->is_strict_mode || data->has_redirected_call; if (data->arguments_index == ES_FunctionCodeStatic::ARGUMENTS_NOT_USED && may_use_arguments) create_arguments_object = cg.StartOutOfOrderBlock(); else create_arguments_object = NULL; if (data->arguments_index != ES_FunctionCodeStatic::ARGUMENTS_NOT_USED || may_use_arguments) { #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GeneratePrologue(): create arguments object\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT ES_CodeGenerator::Constant *c_CreateArgumentsObject(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::CreateArgumentsObject))); if (data->formals_count != 0) cg.MOV(PARAMETERS_COUNT, ES_CodeGenerator::REG_R5); cg.MOV(PARAMETERS_COUNT, ES_CodeGenerator::REG_R3); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(VR(1)), IVALUE_OFFSET(VR(1)), ES_CodeGenerator::REG_R1); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(c_CreateArgumentsObject, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); if (data->formals_count != 0) cg.MOV(ES_CodeGenerator::REG_R5, PARAMETERS_COUNT); if (create_arguments_object) cg.EndOutOfOrderBlock(); } ES_CodeGenerator::OutOfOrderBlock *initialize_formals; if (data->formals_count != 0) initialize_formals = InitializeFormals(this, data->formals_count); else initialize_formals = NULL; if (create_arguments_object || initialize_formals) { cg.CMP(PARAMETERS_COUNT, data->formals_count); if (initialize_formals) cg.Jump(initialize_formals->GetJumpTarget(), ES_NATIVE_CONDITION_LOWER); if (create_arguments_object) cg.Jump(create_arguments_object->GetJumpTarget(), ES_NATIVE_CONDITION_HIGHER); if (initialize_formals) cg.SetOutOfOrderContinuationPoint(initialize_formals); if (create_arguments_object) cg.SetOutOfOrderContinuationPoint(create_arguments_object); } EmitTick(); if (constructor) { ES_CodeGenerator::Register object(ALLOCATED_OBJECT_REGISTER); BOOL inline_allocation = constructor_final_class && CanAllocateObject(constructor_final_class, 0); ES_CodeGenerator::OutOfOrderBlock *complex_case = cg.StartOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GeneratePrologue(): calling ES_Execution_Context::AllocateObjectFromMachineCodeComplex()\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::AllocateObjectFromMachineCodeComplex)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.MOV(ES_CodeGenerator::REG_R0, object); cg.EndOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GeneratePrologue(): verifying ctor.prototype hasn't changed\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT ES_CodeGenerator::Register function(ES_CodeGenerator::REG_R1); ES_CodeGenerator::Register function_properties(ES_CodeGenerator::REG_R2); cg.LDR(BASE_REGISTER(VR(1)), IVALUE_OFFSET(VR(1)), function); cg.LDR(OBJECT_MEMBER(function, ES_Object, properties), function_properties); unsigned prototype_offset = ES_Function::GetPropertyOffset(ES_Function::PROTOTYPE); if (constructor_prototype) { LoadValue(cg, function_properties, prototype_offset, ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5); MovePointerToRegister(cg, constructor_prototype, ES_CodeGenerator::REG_R0); cg.CMP(TYPE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5), ESTYPE_OBJECT); cg.CMP(IVALUE_REGISTER(ES_CodeGenerator::REG_R4, ES_CodeGenerator::REG_R5), ES_CodeGenerator::REG_R0, ES_NATIVE_CONDITION_EQUAL); cg.Jump(complex_case->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); } else { cg.LDR(function_properties, prototype_offset + VALUE_TYPE_OFFSET, ES_CodeGenerator::REG_R0); cg.CMP(ES_CodeGenerator::REG_R0, ESTYPE_OBJECT); cg.Jump(complex_case->GetJumpTarget(), ES_NATIVE_CONDITION_EQUAL); } ES_CodeGenerator::OutOfOrderBlock *non_trivial; if (inline_allocation) non_trivial = cg.StartOutOfOrderBlock(); else non_trivial = NULL; #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GeneratePrologue(): calling ES_Execution_Context::AllocateObjectFromMachineCodeSimple()\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); MovePointerToRegister(cg, constructor_class, ES_CodeGenerator::REG_R1); cg.LDR(cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::AllocateObjectFromMachineCodeSimple)), ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.MOV(ES_CodeGenerator::REG_R0, object); if (non_trivial) { cg.EndOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GeneratePrologue(): inlined object allocation \n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT EmitAllocateObject(constructor_class, constructor_final_class, 0, 0, NULL, non_trivial->GetJumpTarget()); cg.SetOutOfOrderContinuationPoint(non_trivial); } cg.SetOutOfOrderContinuationPoint(complex_case); cg.MOV(ESTYPE_OBJECT, TYPE_REGISTER(ES_CodeGenerator::REG_R0, ES_CodeGenerator::REG_R1)); cg.MOV(object, IVALUE_REGISTER(ES_CodeGenerator::REG_R0, ES_CodeGenerator::REG_R1)); StoreValue(cg, ES_CodeGenerator::REG_R0, ES_CodeGenerator::REG_R1, VR(0)); } } } if (loop_dispatcher && first_loop_io) { if (!c_ReadLoopIO) c_ReadLoopIO = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::ReadLoopIO)); if (!c_code) c_code = cg.NewConstant(code); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(c_code, ES_CodeGenerator::REG_R1); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R2); cg.LDR(c_ReadLoopIO, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } } cg.EndPrologue(); } void ES_Native::GenerateEpilogue() { cg.SetJumpTarget(epilogue_jump_target); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" from GenerateEpilogue():\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT if (!constructor && code->data->codewords_count == 1 && code->data->codewords[0].instruction == ESI_RETURN_NO_VALUE) { if (!is_inlined_function_call) cg.BX(ES_CodeGenerator::REG_LR); return; } if (loop_dispatcher && first_loop_io) { if (!c_WriteLoopIO) c_WriteLoopIO = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::WriteLoopIO)); if (!c_code) c_code = cg.NewConstant(code); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(c_code, ES_CodeGenerator::REG_R1); cg.MOV(REGISTER_FRAME_POINTER, ES_CodeGenerator::REG_R2); cg.LDR(c_WriteLoopIO, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); } if (!is_trivial && !is_light_weight) { DECLARE_NOTHING(); if (code->type == ES_Code::TYPE_FUNCTION) { ES_FunctionCode *fncode = static_cast<ES_FunctionCode *>(code); ES_FunctionCodeStatic *data = fncode->GetData(); ES_CodeGenerator::OutOfOrderBlock *detach_arguments; if (data->arguments_index == ES_FunctionCodeStatic::ARGUMENTS_NOT_USED) detach_arguments = cg.StartOutOfOrderBlock(); else detach_arguments = NULL; #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GenerateEpilogue(): detach arguments object\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT ES_CodeGenerator::Constant *c_DetachArgumentsObject = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::DetachArgumentsObject)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); if (!detach_arguments) cg.LDR(ES_CodeGenerator::REG_SP, stack_space_allocated - 4 * sizeof(void *), ES_CodeGenerator::REG_R1); cg.LDR(c_DetachArgumentsObject, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); if (detach_arguments) { cg.EndOutOfOrderBlock(); cg.LDR(ES_CodeGenerator::REG_SP, stack_space_allocated - 4 * sizeof(void *), ES_CodeGenerator::REG_R1); cg.TEQ(ES_CodeGenerator::REG_R1, 0); cg.Jump(detach_arguments->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.SetOutOfOrderContinuationPoint(detach_arguments); } if (data->CanHaveVariableObject()) { ES_CodeGenerator::OutOfOrderBlock *detach_variables = cg.StartOutOfOrderBlock(); #ifdef NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT cg.Annotate(UNI_L(" GenerateEpilogue(): detach variables object\n")); #endif // NATIVE_DISASSEMBLER_ANNOTATION_SUPPORT ES_CodeGenerator::Constant *c_DetachArgumentsObject = cg.NewFunction(reinterpret_cast<void (*)()>(&ES_Execution_Context::DetachVariableObject)); cg.MOV(CONTEXT_POINTER, ES_CodeGenerator::REG_R0); cg.LDR(c_DetachArgumentsObject, ES_CodeGenerator::REG_LR); cg.BLX(ES_CodeGenerator::REG_LR); cg.EndOutOfOrderBlock(); cg.LDR(ES_CodeGenerator::REG_SP, stack_space_allocated - 5 * sizeof(void *), ES_CodeGenerator::REG_R1); cg.TEQ(ES_CodeGenerator::REG_R1, 0); cg.Jump(detach_variables->GetJumpTarget(), ES_NATIVE_CONDITION_NOT_EQUAL); cg.SetOutOfOrderContinuationPoint(detach_variables); } } cg.ADD(ES_CodeGenerator::REG_SP, StackSpaceAllocated() - sizeof (void *), ES_CodeGenerator::REG_SP); cg.POP(SCRATCHI1); cg.STR(SCRATCHI1, OBJECT_MEMBER(CONTEXT_POINTER, ES_Execution_Context, native_stack_frame)); cg.POP(ES_CodeGenerator::REG_PC); } else if (!is_inlined_function_call) cg.BX(ES_CodeGenerator::REG_LR); } /* static */ unsigned ES_NativeStackFrame::GetFrameSize(ES_Code *code, BOOL include_return_address) { /* Previous stack frame, register frame pointer and code pointer: */ unsigned frame_size = 3 * sizeof(void *); if (code->type == ES_Code::TYPE_FUNCTION) { /* Arguments object and arguments count: */ frame_size += 2 * sizeof(void *); if (code->CanHaveVariableObject()) /* Variable object: */ frame_size += sizeof(void *); } if ((frame_size + sizeof(void *)) & sizeof(void *)) frame_size += sizeof(void *); if (include_return_address) frame_size += sizeof(void *); return frame_size; } #endif // ARCHITECTURE_ARM #endif // ES_NATIVE_SUPPORT
#include <vector> using namespace std; // 21-02-15 // My Solution (87%) // empty arry error vector<int> solution(vector<int> &A, int K) { if ( A.size() <=0 ) return A; // (100%) if ( K%A.size()==0 ) return A; for(unsigned int i=0; i<K%A.size(); i++) { int num=A.back(); A.pop_back(); A.insert(A.begin(),num); } return A; }
// Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdPersistent_Naming_HeaderFile #define _StdPersistent_Naming_HeaderFile #include <StdObjMgt_Attribute.hxx> #include <StdObjMgt_Persistent.hxx> #include <StdPersistent_HArray1.hxx> #include <StdLPersistent_HArray1.hxx> #include <StdLPersistent_HString.hxx> #include <TNaming_Naming.hxx> class TNaming_Name; class StdPersistent_Naming { public: class NamedShape : public StdObjMgt_Attribute<TNaming_NamedShape> { public: //! Read persistent data from a file. inline void Read (StdObjMgt_ReadData& theReadData) { theReadData >> myOldShapes >> myNewShapes >> myShapeStatus >> myVersion; } //! Read persistent data from a file. inline void Write (StdObjMgt_WriteData& theWriteData) const { theWriteData << myOldShapes << myNewShapes << myShapeStatus << myVersion; } //! Gets persistent child objects inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const { if (!myOldShapes.IsNull()) theChildren.Append(myOldShapes); if (!myNewShapes.IsNull()) theChildren.Append(myNewShapes); } //! Returns persistent type name inline Standard_CString PName() const { return "PNaming_NamedShape"; } //! Import transient attribute from the persistent data. void Import (const Handle(TNaming_NamedShape)& theAttribute) const; private: Handle(StdPersistent_HArray1::Shape1) myOldShapes; Handle(StdPersistent_HArray1::Shape1) myNewShapes; Standard_Integer myShapeStatus; Standard_Integer myVersion; }; class Name : public StdObjMgt_Persistent { public: //! Read persistent data from a file. Standard_EXPORT virtual void Read (StdObjMgt_ReadData& theReadData); //! Read persistent data from a file. Standard_EXPORT virtual void Write (StdObjMgt_WriteData& theWriteData) const; //! Gets persistent child objects inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const { if (!myArgs.IsNull()) theChildren.Append(myArgs); if (!myStop.IsNull()) theChildren.Append(myStop); } //! Returns persistent type name inline Standard_CString PName() const { return "PNaming_Name"; } //! Import transient object from the persistent data. Standard_EXPORT virtual void Import (TNaming_Name& theName, const Handle(TDF_Data)& theDF) const; private: Standard_Integer myType; Standard_Integer myShapeType; Handle(StdLPersistent_HArray1::Persistent) myArgs; Handle(StdObjMgt_Persistent) myStop; Standard_Integer myIndex; }; class Name_1 : public Name { public: //! Read persistent data from a file. Standard_EXPORT virtual void Read (StdObjMgt_ReadData& theReadData); //! Read persistent data from a file. Standard_EXPORT virtual void Write (StdObjMgt_WriteData& theWriteData) const; //! Gets persistent child objects inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const { Name::PChildren(theChildren); if (!myContextLabel.IsNull()) theChildren.Append(myContextLabel); } //! Returns persistent type name inline Standard_CString PName() const { return "PNaming_Name_1"; } //! Import transient object from the persistent data. Standard_EXPORT virtual void Import (TNaming_Name& theName, const Handle(TDF_Data)& theDF) const; private: Handle(StdLPersistent_HString::Ascii) myContextLabel; }; class Name_2 : public Name_1 { public: //! Read persistent data from a file. Standard_EXPORT virtual void Read (StdObjMgt_ReadData& theReadData); //! Read persistent data from a file. Standard_EXPORT virtual void Write (StdObjMgt_WriteData& theWriteData) const; //! Gets persistent child objects inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const { Name_1::PChildren(theChildren); } //! Returns persistent type name inline Standard_CString PName() const { return "PNaming_Name_2"; } //! Import transient object from the persistent data. Standard_EXPORT virtual void Import (TNaming_Name& theName, const Handle(TDF_Data)& theDF) const; private: Standard_Integer myOrientation; }; class Naming : public StdObjMgt_Attribute<TNaming_Naming>::SingleRef { public: //! Import transient attribute from the persistent data. Standard_EXPORT virtual void ImportAttribute(); }; class Naming_1 : public Naming { public: //! Import transient attribute from the persistent data. Standard_EXPORT virtual void ImportAttribute(); }; typedef Naming Naming_2; }; #endif
#include <stdio.h> #include<stdlib.h> /*Programa que pide al usuario n numeros y llena un vector los organiza en orden ascendente y los muestra con punteros*/ int main() { int tam,aux; int *vec; printf("Ingrese tamaņo del Vector: "); scanf("%d",&tam); vec=new int[tam]; printf("Ingrese Elementos del vector:\n"); for(int i=0;i<tam;i++){ scanf("%d",&vec[i]); } printf("\nMostrando Vector:\n"); for(int i=0;i<tam;i++){ printf("%d ",*(vec+i)); } for(int i=0;i<tam;i++){ for(int j=0;j<tam;j++){ if(vec[j] > vec[j+1]){ aux=vec[j]; vec[j]=vec[j+1]; vec[j+1]=aux; } } } printf("\nMostrando Vector en orden ascendente:\n"); for(int i=0;i<tam;i++){ printf("%d ",*(vec+i)); } delete[]vec; return 0; }
#include <bits/stdc++.h> #define MAX 100002 #define WHITE 0 //not_visited #define GRAY 1 //being visited #define BLACK 2 //finish visit using namespace std; list<int>LISTA[MAX]; char MARC[MAX] = {}, ciclo = false; int cont = 0; void DFS(int v); int main() { map<string, int>mapa; string p1, p2; int pp = 1; while(cin>>p1>>p2) { if(mapa[p1]==0) mapa[p1] = pp++; if(mapa[p2]==0) mapa[p2] = pp++; LISTA[mapa[p1]].push_back(mapa[p2]); } for(int i=1;i<pp;i++) { if(MARC[i]==WHITE) { DFS(i); ciclo = false; } } printf("%d\n", cont); return 0; } void DFS(int v) { MARC[v] = GRAY; int w = *LISTA[v].begin(); if(MARC[w] == WHITE) DFS(w); else if(MARC[w] == GRAY) { ciclo = true; cont++; } MARC[w] = MARC[v] = BLACK; }
// Fill out your copyright notice in the Description page of Project Settings. #include "MyStructs.h" #pragma once #include "GameFramework/Actor.h" #include "BoltBlock.generated.h" //就是拿在手上和扔出去的方块 UCLASS() class FIGHTWITHBLOCK_API ABoltBlock : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ABoltBlock(); UPROPERTY(VisibleAnywhere) class UStaticMeshComponent* StaticMesh; UPROPERTY(VisibleAnywhere) class UProjectileMovementComponent* ProjectileMovement; UPROPERTY(VisibleAnywhere) class UBoxComponent* CollisionComponent; UPROPERTY(VisibleAnywhere) class USphereComponent* ExplosionCollisionComponent; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; void SetInitProperty(FBlock Block,class AMyCharacter* Owner_); UFUNCTION() void OnRep_Init(); UFUNCTION() void OnRep_Explosion(); //void SetFireDirection(const FVector& Direction, float DropForce); UFUNCTION() void BeginOverlap(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, int32 OtherBodyIndex, bool FromSweep, const FHitResult& Hit); UPROPERTY(Replicated) FBlock BlockProperty; void Explosion(); void BeBreak(); TSubclassOf<class APoisonCPP> PoisonClass; private: UPROPERTY(ReplicatedUsing = OnRep_Init) bool IsInit = false; UPROPERTY(ReplicatedUsing = OnRep_Explosion) bool IsExplosion = false; bool bExplosion = false; bool bBreak = false; class AMyCharacter* Owner; };
// // shelpers.cpp // ShellProgram // // Created by Quincy Copeland on 2/3/19. // Copyright © 2019 Quincy Copeland. All rights reserved. // #include "shelpers.hpp" /* text handling functions */ bool splitOnSymbol(std::vector<std::string>& words, int i, char c) { if(words[i].size() < 2){ return false; } int pos; if((pos = words[i].find(c)) != std::string::npos){ if(pos == 0){ //starts with symbol words.insert(words.begin() + i + 1, words[i].substr(1, words[i].size() -1)); words[i] = words[i].substr(0,1); } else { //symbol in middle or end words.insert(words.begin() + i + 1, std::string{c}); std::string after = words[i].substr(pos + 1, words[i].size() - pos - 1); if(!after.empty()){ words.insert(words.begin() + i + 2, after); } words[i] = words[i].substr(0, pos); } return true; } else { return false; } } std::vector<std::string> tokenize(const std::string& s) { std::vector<std::string> ret; int pos = 0; int space; //split on spaces while((space = s.find(' ', pos)) != std::string::npos){ std::string word = s.substr(pos, space - pos); if(!word.empty()){ ret.push_back(word); } pos = space + 1; } std::string lastWord = s.substr(pos, s.size() - pos); if(!lastWord.empty()){ ret.push_back(lastWord); } for(int i = 0; i < ret.size(); ++i) { for(auto c : {'&', '<', '>', '|'}) { if(splitOnSymbol(ret, i, c)) { --i; break; } } } return ret; } std::ostream& operator<<(std::ostream& outs, const Command& c) { outs << c.exec << " argv: "; for(const auto& arg : c.argv){ if(arg) {outs << arg << ' ';}} outs << "fds: " << c.fdStdin << ' ' << c.fdStdout << ' ' << (c.background ? "background" : ""); return outs; } //returns an empty vector on error /* You'll need to fill in a few gaps in this function and add appropriate error handling at the end. */ std::vector<Command> getCommands(const std::vector<std::string>& tokens) { std::vector<Command> ret(std::count(tokens.begin(), tokens.end(), "|") + 1); //1 + num |'s comman int first = 0; int fd0 = 0; int fd1 = 0; int pipeFD[2]; int last = std::find(tokens.begin(), tokens.end(), "|") - tokens.begin(); bool error = false; for(int i = 0; i < ret.size(); ++i) { if((tokens[first] == "&") || (tokens[first] == "<") || (tokens[first] == ">") || (tokens[first] == "|")){ error = true; break; } ret[i].exec = tokens[first]; ret[i].argv.push_back(tokens[first].c_str()); //argv0 = program name std::cout << "exec start: " << ret[i].exec << std::endl; ret[i].fdStdin = 0; ret[i].fdStdout = 1; ret[i].background = false; for(int j = first + 1; j < last; ++j) { if(tokens[j] == ">" || tokens[j] == "<" ){ if (tokens[j] == ">") { //std::cout << "TOKENNNNN " << tokens[j] << std::endl; fd1 = open(tokens[j + 1].c_str(), O_RDWR|O_CREAT, 0666); if (fd1 == -1) { perror("open error"); //exit(1); } ret[i].argv.push_back(nullptr); ret[i].fdStdout = fd1; } else if (tokens[j] == "<") { fd0 = open(tokens[j + 1].c_str(), O_RDONLY); std::cout << "FD0\n"; if (fd0 == -1) { perror("open"); //exit(1); } ret[i].fdStdin = fd0; } } else if(tokens[j] == "&") { //Fill this in if you choose to do the optional "background command" part assert(false); } else { //otherwise this is a normal command line argument! ret[i].argv.push_back(tokens[j].c_str()); } } if(i > 0) { /* there are multiple commands. Open open a pipe and Connect the ends to the fds for the commands! */ fd1 = pipe(pipeFD); if (fd1 == -1) { perror("pipe failed"); exit(1); } ret[i - 1].fdStdout = pipeFD[1]; //0 read end , 1 is the write end ret[i].fdStdin = pipeFD[0]; std::cout << "FD-OUT " << ret[i-1].fdStdout << std::endl; std::cout << "FD-IN " << ret[i].fdStdin << std::endl; } //exec wants argv to have a nullptr at the end! ret[i].argv.push_back(nullptr); //find the next pipe character first = last + 1; if(first < tokens.size()) { last = std::find(tokens.begin() + first, tokens.end(), "|") - tokens.begin(); } } if(error) { //close any file descriptors you opened in this function! close(fd0); close(fd1); close(pipeFD[0]); close(pipeFD[1]); } return ret; }
int brightness = 0; // how bright the LED is int fadeAmount = 3; int sensorLimit = 250; char val = '0'; const int red1 = 11; const int red2 = 23; const int red3 = 24; const int red4 = 26; const int red5 = 28; const int red6 = 30; const int red7 = 32; const int red8 = 34; const int red9 = 36; const int green1 = 2; const int green2 = 3; const int green3 = 4; const int green4 = 5; const int green5 = 6; const int green6 = 7; const int green7 = 8; const int green8 = 9; const int green9 = 10; int sensor1; int sensor2; int sensor3; int sensor4; int sensor5; int sensor6; int sensor7; int sensor8; int sensor9; void setup() { pinMode(red1, OUTPUT); pinMode(red2, OUTPUT); pinMode(red3, OUTPUT); pinMode(red4, OUTPUT); pinMode(red5, OUTPUT); pinMode(red6, OUTPUT); pinMode(red7, OUTPUT); pinMode(red8, OUTPUT); pinMode(red9, OUTPUT); pinMode(green1, OUTPUT); pinMode(green2, OUTPUT); pinMode(green3, OUTPUT); pinMode(green4, OUTPUT); pinMode(green5, OUTPUT); pinMode(green6, OUTPUT); pinMode(green7, OUTPUT); pinMode(green8, OUTPUT); pinMode(green9, OUTPUT); Serial.begin(9600); } void loop() { int sensor1 = analogRead(A0); int sensor2 = analogRead(A1)*2; int sensor3 = analogRead(A2); int sensor4 = analogRead(A3)*4/3; int sensor5 = analogRead(A4); int sensor6 = analogRead(A5)*2; int sensor7 = analogRead(A6); int sensor8 = analogRead(A7); int sensor9 = analogRead(A8); int a = 0; if(sensor1<sensorLimit){ digitalWrite(red1, 1); analogWrite(green1, 0); } else{ digitalWrite(red1, 0); analogWrite(green1, brightness); } if(sensor2<sensorLimit){ digitalWrite(red2, 1); analogWrite(green2, 0); } else{ digitalWrite(red2, 0); analogWrite(green2, brightness); } if(sensor3<sensorLimit){ digitalWrite(red3, 1); analogWrite(green3, 0); } else{ digitalWrite(red3, 0); analogWrite(green3, brightness); } if(sensor4<sensorLimit){ digitalWrite(red4, 1); analogWrite(green4, 0); } else{ digitalWrite(red4, 0); analogWrite(green4, brightness); } if(sensor5<sensorLimit){ digitalWrite(red5, 1); analogWrite(green5, 0); } else{ digitalWrite(red5, 0); analogWrite(green5, brightness); } if(sensor6<sensorLimit){ digitalWrite(red6, 1); analogWrite(green6, 0); } else{ digitalWrite(red6, 0); analogWrite(green6, brightness); } if(sensor7<sensorLimit){ digitalWrite(red7, 1); analogWrite(green7, 0); } else{ digitalWrite(red7, 0); analogWrite(green7, brightness); } if(sensor8<sensorLimit){ digitalWrite(red8, 1); analogWrite(green8, 0); } else{ digitalWrite(red8, 0); analogWrite(green8, brightness); } if(sensor9<sensorLimit){ digitalWrite(red9, 1); analogWrite(green9, 0); } else{ digitalWrite(red9, 0); analogWrite(green9, brightness); } // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // wait for 30 milliseconds to see the dimming effect \ if (Serial.available() && val == '0') { // If data is available to read, val = Serial.read(); // read it and store it in val } if (val == '1'){ Serial.print(sensor1, DEC); Serial.write(-10); Serial.print(sensor2, DEC); Serial.write(-11); Serial.print(sensor3, DEC); Serial.write(-12); Serial.print(sensor4, DEC); Serial.write(-13); Serial.print(sensor5, DEC); Serial.write(-14); Serial.print(sensor6, DEC); Serial.write(-15); Serial.print(sensor7, DEC); Serial.write(-16); Serial.print(sensor8, DEC); Serial.write(-17); Serial.print(sensor9, DEC); Serial.write(-18); } delay(100); }
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstdlib> #include <memory.h> #include <string> #include <cstring> #include <map> #include <set> #include <queue> #include <deque> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; const int N = 201111; struct cell { int l, r, mn; } a[N * 4]; int pos[N]; void build(int x, int l, int r) { a[x].l = l; a[x].r = r; a[x].mn = -1e9; if (l != r) { build(x + x, l, (l + r) >> 1); build(x + x + 1, ((l + r) >> 1) + 1, r); } else { pos[l] = x; } } void modify(int x, int val) { x = pos[x]; a[x].mn = val; x >>= 1; while (x) { a[x].mn = min(a[x + x].mn, a[x + x + 1].mn); x /= 2; } } int findmin(int x, int l, int r) { if (r < a[x].l || l > a[x].r) return 1e9; if (l <= a[x].l && a[x].r <= r) return a[x].mn; return min(findmin(x + x, l, r), findmin(x + x + 1, l, r)); } bool ans[N]; pair<int, int> w[N]; struct ev { int pos, type, tag; bool operator<(const ev& A) const { if (pos != A.pos) return pos < A.pos; return type < A.type; } } evs[N * 4]; int X1[N], Y1[N], X2[N], Y2[N]; int n, m, k, q; void doit() { build(1, 0, max(n, m) + 1); int ke = 0; for (int i = 0; i < k; ++i) { evs[ke].pos = w[i].first; evs[ke].type = 0; evs[ke].tag = w[i].second; ke++; } for (int i = 0; i < q; ++i) { evs[ke].pos = X2[i]; evs[ke].type = 1; evs[ke].tag = i; ke++; } sort(evs, evs + ke); for (int i = 0; i < ke; ++i) { if (evs[i].type == 0) { modify(evs[i].tag, evs[i].pos); } else { int result = findmin(1, Y1[ evs[i].tag ], Y2[ evs[i].tag ]); if (result >= X1[evs[i].tag]) { ans[evs[i].tag] = true; } } } } int main() { scanf("%d%d", &n, &m); scanf("%d%d", &k, &q); for (int i = 0; i < k; ++i) { scanf("%d%d", &w[i].first, &w[i].second); } for (int i = 0; i < q; ++i) { scanf("%d%d%d%d", X1+i, Y1+i, X2+i, Y2+i); } doit(); for (int i = 0; i < k; ++i) { swap(w[i].first, w[i].second); } for (int i = 0; i < q; ++i) { swap(X1[i], Y1[i]); swap(X2[i], Y2[i]); } doit(); for (int i = 0; i < q; ++i) if (ans[i]) puts("YES"); else puts("NO"); return 0; }
#ifndef __TANK_H__ #define __TANK_H__ #include "Graphic.h" enum Dir { UP, DOWN, LEFT, RIGHT }; class Tank { public: virtual void Display() = 0; virtual void Move() = 0; protected: int m_x; int m_y; COLORREF m_color; Dir m_dir; int m_step; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/security_manager/include/security_manager.h" #include "modules/security_manager/src/security_gadget_representation.h" #include "modules/security_manager/src/security_utilities.h" #ifdef GADGET_SUPPORT # include "modules/gadgets/OpGadgetClass.h" # include "modules/gadgets/OpGadget.h" #endif # include "modules/url/url_man.h" # include "modules/url/protocols/scomm.h" # include "modules/url/protocols/comm.h" # include "modules/pi/network/OpSocketAddress.h" /* IPAddress */ /* static */ int IPAddress::Compare(const IPv6Address &a, const IPv6Address &b) { for (unsigned i = 0; i < 16; i++) { if (a[i] > b[i]) return 1; else if (a[i] < b[i]) return -1; } return 0; } OP_STATUS IPAddress::Parse(const uni_char *ip_addr_str, BOOL same_protocol, const uni_char **end_addr) { /* Now parse that thing... This may not even work because we don't * know whether the format of the string is decimal or hex. For IPv4, * We assume decimal because FromString accepts decimal format. * * For IPv6, components are hexadecimal. * * For IPv4: %d.%d.%d.%d * For IPv6: %x:%x:%x:%x:%x:%x:%x:%x */ unsigned a[8] = {0}; if (uni_sscanf(ip_addr_str, UNI_L("%d.%d.%d.%d"), &a[0], &a[1], &a[2], &a[3]) == 4) { if (same_protocol && !is_ipv4 || a[0] > 0xff || a[1] > 0xff || a[2] > 0xff || a[3] > 0xff) return OpStatus::ERR; is_ipv4 = TRUE; u.ipv4 = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]; if (end_addr) { /* Move buffer pointer past parsed address string. */ unsigned dots_to_see = 3; while (dots_to_see > 0) { if (*ip_addr_str == '.') dots_to_see--; ip_addr_str++; } while (*ip_addr_str >= '0' && *ip_addr_str <= '9') ip_addr_str++; } } else { /* For IPv6 text representations, the above syntactic form is the * canonical & expanded version. RFC-5952 defines some * syntatic rules that should be used to shorten addresses * with consecutive zero-valued components to make them more * human friendly. An application must be capable of accepting * those shorthands as input. */ int run_length_start = -1; unsigned fields_read = 0; for (unsigned i = 0; i < 8; i++) { if (*ip_addr_str == ':') { if (run_length_start >= 0 || ip_addr_str[1] != ':') return OpStatus::ERR; run_length_start = i; ip_addr_str += 2; } else if (*ip_addr_str == '-' || *ip_addr_str == 0) break; else if (uni_sscanf(ip_addr_str, UNI_L("%x"), &a[fields_read]) == 1) { if (a[fields_read] > 0xffff) return OpStatus::ERR; fields_read++; while (*ip_addr_str != ':' && *ip_addr_str != '-' && *ip_addr_str != 0) ip_addr_str++; if (*ip_addr_str == ':' && ip_addr_str[1] != ':') ip_addr_str++; } else return OpStatus::ERR; } if (same_protocol && is_ipv4) return OpStatus::ERR; if (run_length_start >= 0) { unsigned zero_run_length = 8 - fields_read; if (fields_read > 0) { op_memmove(&a[run_length_start + zero_run_length], &a[run_length_start], (fields_read - run_length_start) * sizeof(unsigned)); for (unsigned i = 0; i < zero_run_length; i++) a[run_length_start + i] = 0; } } is_ipv4 = FALSE; for (unsigned i = 0; i < 8; i++) { u.ipv6[2*i] = (a[i] >> 8) & 0xff; u.ipv6[2*i + 1] = a[i] & 0xff; } } if (end_addr) *end_addr = ip_addr_str; return OpStatus::OK; } /* static */ OP_STATUS IPAddress::Export(const IPv4Address &addr, OpString &text) { // %d.%d.%d.%d, 4 times 3 digits + 3 dots + \0 uni_char buf[4*3 + 3 + 1]; // ARRAY OK 2010-11-10 jborsodi unsigned a, b, c, d; a = (addr >> 24) & 0xff; b = (addr >> 16) & 0xff; c = (addr >> 8) & 0xff; d = addr & 0xff; if (uni_sprintf(buf, UNI_L("%d.%d.%d.%d"), a, b, c, d) < 0) return OpStatus::ERR; return text.Append(buf); } /* static */ OP_STATUS IPAddress::Export(const IPv6Address &addr, OpString &text, BOOL for_user) { // %x:%x:%x:%x:%x:%x:%x:%x, 8 times 4 digits + 7 colons + \0 uni_char buf[8*4 + 7 + 1]; // ARRAY OK 2010-11-11 jborsodi unsigned digits[8]; // ARRAY OK 2010-11-10 jborsodi for (unsigned i = 0; i < 8; ++i) { digits[i] = (addr[i*2] << 8) | addr[i*2 + 1]; } if (for_user) { unsigned run_length = 0; unsigned run_length_start = 0; unsigned running_length = 0; unsigned i = 0; for (; i < 8; i++) if (digits[i] == 0) running_length++; else { if (running_length > 1 && run_length < running_length) { run_length = running_length; run_length_start = i - run_length; } running_length = 0; } if (running_length > 1 && run_length < running_length) { run_length = running_length; run_length_start = i - run_length; } if (run_length > 0) { buf[0] = 0; for (unsigned i = 0; i < 8; i++) if (i == run_length_start) { if (uni_sprintf(buf + uni_strlen(buf), i == 0 ? UNI_L("::") : UNI_L(":")) < 0) return OpStatus::ERR; i += run_length - 1; } else { if (uni_sprintf(buf + uni_strlen(buf), i < 7 ? UNI_L("%x:") : UNI_L("%x"), digits[i]) < 0) return OpStatus::ERR; } return text.Append(buf); } } if (uni_sprintf(buf, UNI_L("%x:%x:%x:%x:%x:%x:%x:%x"), digits[0], digits[1], digits[2], digits[3], digits[4], digits[5], digits[6], digits[7]) < 0) return OpStatus::ERR; return text.Append(buf); } OP_STATUS IPAddress::Export(OpString &text, BOOL for_user) { if (is_ipv4) return Export(u.ipv4, text); else return Export(u.ipv6, text, for_user); } /* IPRange */ OP_STATUS IPRange::Parse(const uni_char *expr) { IPAddress from_address; RETURN_IF_ERROR(from_address.Parse(expr, FALSE, &expr)); while (uni_isspace(*expr)) expr++; if (*expr == 0) { FromAddress(from_address); return OpStatus::OK; } else if (*expr++ == '-') { IPAddress to_address; to_address.is_ipv4 = from_address.is_ipv4; while (uni_isspace(*expr)) expr++; RETURN_IF_ERROR(to_address.Parse(expr, TRUE)); return WithRange(from_address, to_address); } else return OpStatus::ERR; } int IPRange::Compare(const IPv4Address a) const { OP_ASSERT(is_ipv4); if (a >= u.ipv4.from && a <= u.ipv4.to) return 0; else if (a < u.ipv4.from) return -1; else return 1; } int IPRange::Compare(const IPv6Address &a) const { OP_ASSERT(!is_ipv4); int low_res = IPAddress::Compare(a, u.ipv6.from); int high_res = IPAddress::Compare(a, u.ipv6.to); if (low_res >= 0 && high_res <= 0) return 0; else if (low_res < 0) return -1; else return 1; } OP_STATUS IPRange::Compare(const IPAddress &a, int &result) const { if (a.is_ipv4 != is_ipv4) return OpStatus::ERR; result = is_ipv4 ? Compare(a.u.ipv4) : Compare(a.u.ipv6); return OpStatus::OK; } /* private */ void IPRange::SetRange(const IPAddress &from_address, const IPAddress &to_address) { OP_ASSERT(from_address.is_ipv4 == to_address.is_ipv4); is_ipv4 = from_address.is_ipv4; if (is_ipv4) { u.ipv4.from = from_address.u.ipv4; u.ipv4.to = to_address.u.ipv4; } else { op_memcpy(&u.ipv6.from, from_address.u.ipv6, sizeof(u.ipv6.from)); op_memcpy(&u.ipv6.to, to_address.u.ipv6, sizeof(u.ipv6.to)); } } void IPRange::FromAddress(const IPAddress &address) { SetRange(address, address); } OP_STATUS IPRange::WithRange(const IPAddress &from_address, const IPAddress &to_address) { if (from_address.is_ipv4 != to_address.is_ipv4) return OpStatus::ERR; if (from_address.is_ipv4 && from_address.u.ipv4 > to_address.u.ipv4) return OpStatus::ERR; else if (!from_address.is_ipv4 && IPAddress::Compare(from_address.u.ipv6, to_address.u.ipv6) > 0) return OpStatus::ERR; SetRange(from_address, to_address); return OpStatus::OK; } /* static */ OP_STATUS IPRange::Export(const IPRange &range, OpString &from, OpString &to, BOOL for_user) { if (range.is_ipv4) { RETURN_IF_ERROR(IPAddress::Export(range.u.ipv4.from, from)); RETURN_IF_ERROR(IPAddress::Export(range.u.ipv4.to, to)); } else { RETURN_IF_ERROR(IPAddress::Export(range.u.ipv6.from, from, for_user)); RETURN_IF_ERROR(IPAddress::Export(range.u.ipv6.to, to, for_user)); } return OpStatus::OK; } /* static */ OP_STATUS IPRange::Export(const IPRange &range, OpString &text, BOOL for_user) { if (range.is_ipv4) { RETURN_IF_ERROR(IPAddress::Export(range.u.ipv4.from, text)); RETURN_IF_ERROR(text.Append(UNI_L("-"))); RETURN_IF_ERROR(IPAddress::Export(range.u.ipv4.to, text)); } else { RETURN_IF_ERROR(IPAddress::Export(range.u.ipv6.from, text, for_user)); RETURN_IF_ERROR(text.Append(UNI_L("-"))); RETURN_IF_ERROR(IPAddress::Export(range.u.ipv6.to, text, for_user)); } return OpStatus::OK; } /* OpSecurityUtilities */ OpSecurityUtilities::OpSecurityUtilities() #ifdef PUBLIC_DOMAIN_LIST : m_public_domain_list(NULL) #endif // PUBLIC_DOMAIN_LIST { } OpSecurityUtilities::~OpSecurityUtilities() { #ifdef PUBLIC_DOMAIN_LIST OP_DELETE(m_public_domain_list); #endif // PUBLIC_DOMAIN_LIST } /* static */ BOOL OpSecurityUtilities::IsIPAddressOrRange(const uni_char *str) { int dots = 0; int colons = 0; int dashes = 0; int alphas = 0; int digits = 0; int hexs = 0; int colon_group = 0; const uni_char *q = NULL; for (q = str; q && *q != '\0'; q++) { if (*q == '.') dots++; else if (*q == ':') { colons++; if (q > str && q[-1] == ':') colon_group++; } else if (*q == '-') dashes++; else if (uni_isalpha(*q)) { if ((*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F')) hexs++; alphas++; } else if (uni_isdigit(*q)) digits++; } bool is_ip = false; // check for IPv4 or IPv4 range (0.0.0.0 or 0.0.0.0-1.1.1.1) if (!alphas && !colons && (dots == 3 || (dots == 6 && dashes == 1))) { if (dashes == 1) { if (digits >= 8 && digits <= 24) is_ip = true; } else { if (digits >= 4 && digits <= 12) is_ip = true; } } // check for IPv6 or IPv6 range. else if (!dots && colons >= 2 && colons <= 14 && dashes <= 1 && hexs == alphas) { if (dashes == 0) is_ip = colon_group == 0 ? colons == 7 : colons <= 7; else is_ip = colon_group == 0 ? colons == 14 : true; } return is_ip; } /* static */ OP_STATUS OpSecurityUtilities::ParsePortRange(const uni_char *expr, unsigned int &low, unsigned int &high) { uni_char *end = NULL; long n = uni_strtol(expr, const_cast<uni_char**>(&end), 10, NULL); if (n == LONG_MAX || n <= 0) return OpStatus::ERR; low = static_cast<unsigned int>(n); expr = end; while (uni_isspace(*expr)) expr++; if (*expr++ == '-') { while (uni_isspace(*expr)) expr++; long m = uni_strtol(expr, const_cast<uni_char**>(&end), 10, NULL); if (m == LONG_MAX || m <= 0 || m < n) return OpStatus::ERR; high = static_cast<unsigned int>(m); } else high = low; return OpStatus::OK; } /* static */ OP_STATUS OpSecurityUtilities::ExtractIPAddress(OpSocketAddress *sa, IPAddress &addr) { OpString ip_addr; RETURN_IF_ERROR(sa->ToString(&ip_addr)); return addr.Parse(ip_addr.CStr()); } /* static */ OP_STATUS OpSecurityUtilities::ResolveURL(const URL &url, IPAddress &addr, OpSecurityState &state) { OpSocketAddress* sa = NULL; ServerName* server = (ServerName *)url.GetAttribute(URL::KServerName, static_cast<void*>(NULL)); if (server == NULL) return OpStatus::ERR; if (server->IsHostResolved()) { state.suspended = FALSE; if (state.host_resolving_comm != NULL) { SComm::SafeDestruction( state.host_resolving_comm ); state.host_resolving_comm = NULL; } if ((sa = server->SocketAddress()) == NULL || !sa->IsValid()) return OpStatus::ERR; return ExtractIPAddress(sa, addr); } if (state.host_resolving_comm == NULL) { Comm *comm = 0; CommState s; comm = Comm::Create(g_main_message_handler, server, 80); if (!comm) return OpStatus::ERR; // First, start the lookup. s = comm->LookUpName(server); if (s == COMM_REQUEST_FINISHED) { // Got it sa = comm->HostName()->SocketAddress(); SComm::SafeDestruction(comm); return ExtractIPAddress(sa, addr); } else if (s != COMM_LOADING && s != COMM_WAITING_FOR_SYNC_DNS) { SComm::SafeDestruction(comm); return OpStatus::ERR; } state.suspended = TRUE; state.host_resolving_comm = comm; return OpStatus::OK; } else { SComm::SafeDestruction(state.host_resolving_comm); state.host_resolving_comm = NULL; state.suspended = FALSE; return OpStatus::ERR; } } /* static */ BOOL OpSecurityUtilities::IsSafeToExport(const URL &url) { switch (url.Type()) { case URL_HTTP: case URL_HTTPS: case URL_FTP: case URL_FILE: case URL_DATA: return TRUE; default: return FALSE; } } OP_STATUS OpSecurityUtilities::IsPublicDomain(const uni_char *domain, BOOL &is_public_domain, BOOL *top_domain_was_known_to_exist) { if (top_domain_was_known_to_exist) *top_domain_was_known_to_exist = FALSE; // Require at least one internal dot in the string const uni_char *period_pos = uni_strchr(domain, '.'); BOOL has_inner_dot = period_pos && *(period_pos+1) != '\0'; #ifdef PUBLIC_DOMAIN_LIST if (!has_inner_dot) { // No need to check against the database since it's incomplete and we will assume // that it's a top domain (known or unknown) is_public_domain = TRUE; return OpStatus::OK; } if (!m_public_domain_list) { m_public_domain_list = OP_NEW(PublicDomainDatabase, ()); if (!m_public_domain_list) { return OpStatus::ERR_NO_MEMORY; } OpFile pdd_file; OP_STATUS status = pdd_file.Construct(UNI_L("public_domains.dat"), OPFILE_INI_FOLDER); if (OpStatus::IsSuccess(status)) { status = m_public_domain_list->ReadDatabase(pdd_file); } if (OpStatus::IsError(status)) { OP_DELETE(m_public_domain_list); m_public_domain_list = NULL; return status; } } OP_BOOLEAN result = m_public_domain_list->IsPublicDomain(domain, top_domain_was_known_to_exist); if (OpStatus::IsError(result)) { return result; } is_public_domain = (result == OpBoolean::IS_TRUE); return OpStatus::OK; #else is_public_domain = !has_inner_dot; return OpStatus::OK; #endif // PUBLIC_DOMAIN_LIST }
/* * PrintService.cpp * * Created on: 10/12/2019 * Author: Jean */ #include <PrintService.h> PrintService::PrintService() { // TODO Auto-generated constructor stub } void PrintService::print( mkl_LCD lcd, Contador *ContadorSeg, Contador *ContadorSegD, Contador *ContadorMin, Contador *ContadorMinD, cook_t Tipo, door_t Porta, giro_t Giro, Dec2ascii Decoder){ lcd.setCursor(1,3); lcd.putChar(':'); lcd.setCursor(1,5); lcd.putChar(Decoder.decode(ContadorSeg->readQ())); lcd.setCursor(1,4); lcd.putChar(Decoder.decode(ContadorSegD->readQ())); lcd.setCursor(1,2); lcd.putChar(Decoder.decode(ContadorMin->readQ())); lcd.setCursor(1,1); if(ContadorMinD->readQ()==0) lcd.putChar(' '); else lcd.putChar(Decoder.decode(ContadorMinD->readQ())); lcd.setCursor(1,8); switch(Tipo){ case edicao:lcd.putString("EDICAO"); break; case inc3: lcd.putString("INC+3 "); break; case inc5: lcd.putString("INC+5 "); break; case inc7: lcd.putString("INC+7 "); break; case pipoca: lcd.putString("PIP "); break; case lasanha: lcd.putString("LAS "); break; case pizza: lcd.putString("PIZ "); } lcd.setCursor(2,6); switch(Porta){ case open: lcd.putString("P-OP "); break; case closed: lcd.putString("P-CL"); break; } lcd.setCursor(2,12); switch(Giro){ case g_on: lcd.putString("G-ON "); break; case g_off: lcd.putString("G-OFF"); break; } }
#include <ostream> #include <type_traits> template<typename T, typename Class, template<typename, typename> typename C> std::ostream& print_container(std::ostream& os, C<T, Class>& values) { if constexpr (std::is_same<C<T, Class>, std::stack<T, Class>>::value) { os << "{ "; while (!values.empty()) { os << values.top() << ", "; values.pop(); } return os << "}\n"; } else { os << "{ "; for (auto const& v : values) { os << v << ", "; } return os << "}\n"; } }
#include "hill_climber.h" void HillClimber::draw( sf::RenderTarget& target, sf::RenderStates states ) const { texture.loadFromImage(result); sprite.setTexture(texture); states.transform *= getTransform(); target.draw(sprite, states); } double HillClimber::pixel_similatity( const sf::Color &a, const sf::Color &b ) const { double pixel_sim = 0; pixel_sim += abs(a.r - b.r); pixel_sim += abs(a.g - b.g); pixel_sim += abs(a.b - b.b); pixel_sim += abs(a.a - b.a); return 1 - (pixel_sim / (255 * 4.0f)); } bool HillClimber::is_better( const sf::Rect<unsigned> &rect, const sf::Color color ) const { double current_similarity = 0; double new_similarity = 0; for (unsigned y = rect.top; y != rect.top + rect.height; ++y) { for (unsigned x = rect.left; x != rect.left + rect.width; ++x) { current_similarity += pixel_similatity( original.getPixel(x, y), result.getPixel(x, y) ); new_similarity += pixel_similatity( original.getPixel(x, y), color ); } } // Normalize to [0-1] current_similarity = current_similarity / (rect.height * rect.width); new_similarity = new_similarity / (rect.height * rect.width); return (new_similarity > current_similarity); } sf::Rect<unsigned> HillClimber::create_random_rect() const { sf::Vector2u top_left( width_distribution(generator), height_distribution(generator) ); sf::Vector2u bottom_right( width_distribution(generator), height_distribution(generator) ); if (top_left.x > bottom_right.x) { std::swap(top_left.x, bottom_right.x); } if (top_left.y > bottom_right.y) { std::swap(top_left.y, bottom_right.y); } sf::Rect<unsigned> rect { top_left.x, top_left.y, bottom_right.x - top_left.x, bottom_right.y - top_left.y }; if (rect.width * rect.height == 0) { return create_random_rect(); } else { return rect; } } HillClimber::HillClimber(const std::string &path) { original.loadFromFile(path); width = original.getSize().x; height = original.getSize().y; width_distribution = std::uniform_int_distribution<unsigned>(0, width); height_distribution = std::uniform_int_distribution<unsigned>(0, height); color_distribution = std::uniform_int_distribution<unsigned>(0, 255); result.create(width, height, sf::Color::Black); } void HillClimber::step() { auto rect = create_random_rect(); sf::Color color( color_distribution(generator), color_distribution(generator), color_distribution(generator) ); if (is_better(rect, color)) { for (unsigned y = rect.top; y != rect.top + rect.height; ++y) { for (unsigned x = rect.left; x != rect.left + rect.width; ++x) { result.setPixel(x, y, color); } } } } unsigned HillClimber::get_width() const { return width; } unsigned HillClimber::get_height() const { return height; }
// // Created by 钟奇龙 on 2019-05-01. // #include <iostream> #include <string> #include <queue> using namespace std; class Node{ public: int data; Node *left; Node *right; Node(int x):data(x),left(NULL),right(NULL){} }; string serialByPreOrder(Node *root){ if(!root) return "#!"; string res = to_string(root->data) + "!"; res += serialByPreOrder(root->left); res += serialByPreOrder(root->right); return res; } vector<string> split(const string& str, const string& pattern) { vector<string> ret; if (pattern.empty()) return ret; size_t start = 0, index = str.find_first_of(pattern, 0); while (index != str.npos) { if (start != index) ret.push_back(str.substr(start, index - start)); start = index + 1; index = str.find_first_of(pattern, start); } if (!str.substr(start).empty()) ret.push_back(str.substr(start)); return ret; } Node* reconByPre(queue<string> &str_queue){ if(str_queue.empty()) return NULL; string cur = str_queue.front(); str_queue.pop(); if(cur == "#") return NULL; Node *node = new Node(stoi(cur)); node->left = reconByPre(str_queue); node->right = reconByPre(str_queue); return node; } Node* reconByPreString(string preStr){ vector<string> values(split(preStr,"!")); queue<string> str_queue; for(int i=0; i<values.size(); ++i){ str_queue.push(values[i]); } return reconByPre(str_queue); } int main(){ Node *node1 = new Node(1); Node *node2 = new Node(2); Node *node3 = new Node(3); Node *node4 = new Node(4); Node *node5 = new Node(5); Node *node6 = new Node(6); Node *node7 = new Node(7); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; node3->left = node6; node5->right = node7; string serial = serialByPreOrder(node1); cout<<serial<<endl; Node *res = reconByPreString(serial); return 0; }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #include "Core/Arguments.hpp" #include <iostream> namespace Push { Arguments::Arguments(int argc, char** argv) { for(int index = 0; index < argc; ++index) { auto arg = argv[index]; if(arg && arg[0] == '-' && arg[2] == 0) { auto& values = m_values[arg[1]]; for(index += 1; index < argc && argv[index] && argv[index][0] != '-'; index += 1) { std::string str(argv[index]); if(str.front() == '"' && str.back() == '"') { values.push_back(std::string(str.begin() + 1, str.end() - 1)); } else { values.push_back(std::move(str)); } } index -= 1; } } } const std::vector<std::string>& Arguments::GetValues(char option) { return m_values[option]; } }
#pragma once #include "Drawable.h" #include "Hitbox.h" #include "includes.h" class Tile : public Drawable { public: Tile(); Tile(int,std::string); Tile(int,std::string,std::string); Tile(int,sf::Texture&); Tile(int,sf::Texture&,sf::Texture&); void addWall(std::string); void deleteWall(); void setWalkable(bool); bool loadTexture(std::string); bool loadWallTexture(std::string); void drawOnPosition(sf::RenderWindow&, sf::Vector2f); int getId(); bool intersects(Hitbox&,const sf::Vector2f&); private: bool canWalkOn = 1; bool hasWall = 0; int ID = 0; std::string name; std::shared_ptr<sf::Texture> tileTexture; std::shared_ptr<sf::Texture> wallTexture; std::shared_ptr<Hitbox> hitbox; sf::Sprite sprite; std::shared_ptr<sf::Sprite> wallSprite; };
// RAVEN BEGIN // bdube: note that this file is no longer merged with Doom3 updates // // MERGE_DATE 9/30/2004 #ifndef __GAME_WEAPON_H__ #define __GAME_WEAPON_H__ /* =============================================================================== Player Weapon =============================================================================== */ typedef enum { WP_READY, WP_OUTOFAMMO, WP_RELOAD, WP_HOLSTERED, WP_RISING, WP_LOWERING, WP_FLASHLIGHT, } weaponStatus_t; static const int MAX_WEAPONMODS = 4; static const int MAX_AMMOTYPES = 16; class idPlayer; class idItem; class idAnimatedEntity; class idProjectile; class rvWeapon; class rvViewWeapon : public idAnimatedEntity { public: CLASS_PROTOTYPE( rvViewWeapon ); rvViewWeapon( void ); virtual ~rvViewWeapon( void ); // Init void Spawn ( void ); // save games void Save ( idSaveGame *savefile ) const; // archives object for save game file void Restore ( idRestoreGame *savefile ); // unarchives object from save game file // Weapon definition management void Clear ( void ); // GUIs void PostGUIEvent ( const char* event ); virtual void SetModel ( const char *modelname, int mods = 0 ); void SetPowerUpSkin ( const char *name ); void UpdateSkin ( void ); // State control/player interface void Think ( void ); // Visual presentation void PresentWeapon ( bool showViewModel ); // Networking virtual void WriteToSnapshot ( idBitMsgDelta &msg ) const; virtual void ReadFromSnapshot ( const idBitMsgDelta &msg ); virtual bool ClientReceiveEvent ( int event, int time, const idBitMsg &msg ); virtual void ClientPredictionThink ( void ); virtual bool ClientStale ( void ); virtual void ConvertLocalToWorldTransform( idVec3 &offset, idMat3 &axis ); virtual void UpdateModelTransform ( void ); // Debugging virtual void GetDebugInfo ( debugInfoProc_t proc, void* userData ); void SetSkin ( const char *skinname ); void SetSkin ( const idDeclSkin* skin ); void SetOverlayShader ( const idMaterial* material ); virtual void GetPosition ( idVec3& origin, idMat3& axis ) const; private: idStrList pendingGUIEvents; // effects const idDeclSkin * saveSkin; const idDeclSkin * invisSkin; const idDeclSkin * saveWorldSkin; const idDeclSkin * worldInvisSkin; const idDeclSkin * saveHandsSkin; const idDeclSkin * handsSkin; void Event_CallFunction ( const char* function ); friend class rvWeapon; rvWeapon* weapon; }; class rvWeapon : public idClass { public: CLASS_PROTOTYPE( rvWeapon ); rvWeapon( void ); virtual ~rvWeapon( void ); enum { WPLIGHT_MUZZLEFLASH, WPLIGHT_MUZZLEFLASH_WORLD, WPLIGHT_FLASHLIGHT, WPLIGHT_FLASHLIGHT_WORLD, WPLIGHT_GUI, WPLIGHT_MAX }; enum { EVENT_RELOAD = idEntity::EVENT_MAXEVENTS, EVENT_ENDRELOAD, EVENT_CHANGESKIN, EVENT_MAXEVENTS }; void Init ( idPlayer* _owner, const idDeclEntityDef* def, int weaponIndex, bool isStrogg = false ); // Virtual overrides void Spawn ( void ); virtual void Think ( void ); virtual void CleanupWeapon ( void ) {} virtual void WriteToSnapshot ( idBitMsgDelta &msg ) const; virtual void ReadFromSnapshot ( const idBitMsgDelta &msg ); virtual bool ClientReceiveEvent ( int event, int time, const idBitMsg &msg ); virtual void ClientStale ( void ); virtual void ClientUnstale ( void ) { } virtual void Attack ( bool altFire, int num_attacks, float spread, float fuseOffset, float power ); virtual void GetDebugInfo ( debugInfoProc_t proc, void* userData ); virtual void SpectatorCycle ( void ) { } virtual bool NoFireWhileSwitching ( void ) const { return false; } void Save ( idSaveGame *savefile ) const; void Restore ( idRestoreGame *savefile ); virtual void PreSave ( void ); virtual void PostSave ( void ); // Visual presentation bool BloodSplat ( float size ); void MuzzleFlash ( void ); void MuzzleRise ( idVec3 &origin, idMat3 &axis ); float GetMuzzleFlashLightParm ( int parm ); void SetMuzzleFlashLightParm ( int parm, float value ); void GetAngleOffsets ( int *average, float *scale, float *max ); void GetTimeOffsets ( float *time, float *scale ); bool GetGlobalJointTransform ( bool viewModel, const jointHandle_t jointHandle, idVec3 &origin, idMat3 &axis, const idVec3& offset = vec3_origin ); // State control/player interface void LowerWeapon ( void ); void RaiseWeapon ( void ); void Raise ( void ); void PutAway ( void ); void Hide ( void ); void Show ( void ); void HideWorldModel ( void ); void ShowWorldModel ( void ); void SetFlashlight ( bool on = true ); void Flashlight ( void ); void SetPushVelocity ( const idVec3 &pushVelocity ); void Reload ( void ); void OwnerDied ( void ); void BeginAttack ( void ); void EndAttack ( void ); bool IsReady ( void ) const; bool IsReloading ( void ) const; bool IsHolstered ( void ) const; bool ShowCrosshair ( void ) const; bool CanDrop ( void ) const; bool CanZoom ( void ) const; void CancelReload ( void ); void SetStatus ( weaponStatus_t status ); bool AutoReload ( void ); bool IsHidden ( void ) const; void EjectBrass ( void ); // Network helpers void NetReload ( void ); void NetEndReload ( void ); void NetCatchup ( void ); // Ammo static int GetAmmoIndexForName ( const char *ammoname ); static const char* GetAmmoNameForIndex ( int index ); int GetAmmoType ( void ) const; int AmmoAvailable ( void ) const; int AmmoInClip ( void ) const; void ResetAmmoClip ( void ); int ClipSize ( void ) const; int LowAmmo ( void ) const; int AmmoRequired ( void ) const; void AddToClip ( int amount ); void UseAmmo ( int amount ); void SetClip ( int amount ); int TotalAmmoCount ( void ) const; // Attack bool PerformAttack ( idVec3& muzzleOrigin, idMat3& muzzleAxis, float dmgPower ); void LaunchProjectiles ( idDict& dict, const idVec3& muzzleOrigin, const idMat3& muzzleAxis, int num_projectiles, float spread, float fuseOffset, float power ); void Hitscan ( const idDict& dict, const idVec3& muzzleOrigin, const idMat3& muzzleAxis, int num_hitscans, float spread, float power ); void AlertMonsters ( void ); // Mods int GetMods ( void ) const; // Zoom idUserInterface* GetZoomGui ( void ) const; float GetZoomTime ( void ) const; int GetZoomFov ( void ) const; rvViewWeapon* GetViewModel ( void ) const; idAnimatedEntity* GetWorldModel ( void ) const; idPlayer* GetOwner ( void ) const; const char * GetIcon ( void ) const; renderLight_t& GetLight ( int light ); const idAngles& GetViewModelAngles ( void ) const; const idVec3& GetViewModelOffset ( void ) const; static void CacheWeapon ( const char *weaponName ); static void SkipFromSnapshot ( const idBitMsgDelta &msg ); void EnterCinematic ( void ); void ExitCinematic ( void ); protected: virtual void OnLaunchProjectile ( idProjectile* proj ); void SetState ( const char *statename, int blendFrames ); void PostState ( const char *statename, int blendFrames ); void ExecuteState ( const char *statename ); void PlayAnim ( int channel, const char *animname, int blendFrames ); void PlayCycle ( int channel, const char *animname, int blendFrames ); bool AnimDone ( int channel, int blendFrames ); bool StartSound ( const char *soundName, const s_channelType channel, int soundShaderFlags, bool broadcast, int *length ); void StopSound ( const s_channelType channel, bool broadcast ); rvClientEffect* PlayEffect ( const char* effectName, jointHandle_t joint, bool loop = false, const idVec3& endOrigin = vec3_origin, bool broadcast = false ); void FindViewModelPositionStyle ( idVec3& viewOffset, idAngles& viewAngles ) const; public: void InitLights ( void ); void InitWorldModel ( void ); void InitViewModel ( void ); void InitDefs ( void ); void FreeLight ( int lightID ); void UpdateLight ( int lightID ); void UpdateMuzzleFlash ( void ); void UpdateFlashlight ( void ); void UpdateGUI ( void ); void UpdateCrosshairGUI ( idUserInterface* gui ) const; idMat3 ForeshortenAxis ( const idMat3& axis ) const; // Script state management struct weaponStateFlags_s { bool attack :1; bool reload :1; bool netReload :1; bool netEndReload :1; bool raiseWeapon :1; bool lowerWeapon :1; bool flashlight :1; bool zoom :1; } wsfl; // Generic flags struct weaponFlags_s { bool attackAltHitscan :1; bool attackHitscan :1; bool hide :1; bool disabled :1; bool hasBloodSplat :1; bool silent_fire :1; bool zoomHideCrosshair :1; bool flashlightOn :1; bool hasWindupAnim :1; } wfl; // joints from models jointHandle_t barrelJointView; jointHandle_t flashJointView; jointHandle_t ejectJointView; jointHandle_t guiLightJointView; jointHandle_t flashlightJointView; jointHandle_t flashJointWorld; jointHandle_t ejectJointWorld; jointHandle_t flashlightJointWorld; weaponStatus_t status; int lastAttack; // hiding weapon int hideTime; float hideDistance; int hideStartTime; float hideStart; float hideEnd; float hideOffset; // Attack idVec3 pushVelocity; int kick_endtime; int muzzle_kick_time; int muzzle_kick_maxtime; idAngles muzzle_kick_angles; idVec3 muzzle_kick_offset; idVec3 muzzleOrigin; idMat3 muzzleAxis; float muzzleOffset; idEntityPtr<idEntity> projectileEnt; idVec3 ejectOffset; int fireRate; int altFireRate; float spread; int nextAttackTime; // we maintain local copies of the projectile and brass dictionaries so they // do not have to be copied across the DLL boundary when entities are spawned idDict attackAltDict; idDict attackDict; idDict brassDict; // Melee const idDeclEntityDef * meleeDef; float meleeDistance; // zoom int zoomFov; // variable zoom fov per weapon (-1 is no zoom) idUserInterface* zoomGui; // whether or not to overlay a zoom scope float zoomTime; // time it takes to zoom in // lights renderLight_t lights[WPLIGHT_MAX]; int lightHandles[WPLIGHT_MAX]; idVec3 guiLightOffset; int muzzleFlashEnd; int muzzleFlashTime; idVec3 muzzleFlashViewOffset; bool flashlightOn; idVec3 flashlightViewOffset; // ammo management int ammoType; int ammoRequired; // amount of ammo to use each shot. 0 means weapon doesn't need ammo. int clipSize; // 0 means no reload int ammoClip; int lowAmmo; // if ammo in clip hits this threshold, snd_ int maxAmmo; // multiplayer int clipPredictTime; // these are the player render view parms, which include bobbing idVec3 playerViewOrigin; idMat3 playerViewAxis; // View Model idVec3 viewModelOrigin; idMat3 viewModelAxis; idAngles viewModelAngles; idVec3 viewModelOffset; // weighting for viewmodel offsets int weaponAngleOffsetAverages; float weaponAngleOffsetScale; float weaponAngleOffsetMax; float weaponOffsetTime; float weaponOffsetScale; // General idStr icon; bool isStrogg; bool forceGUIReload; public: idDict spawnArgs; protected: idEntityPtr<rvViewWeapon> viewModel; idAnimator* viewAnimator; idEntityPtr<idAnimatedEntity> worldModel; idAnimator* worldAnimator; const idDeclEntityDef* weaponDef; idScriptObject* scriptObject; idPlayer * owner; int weaponIndex; int mods; float viewModelForeshorten; rvStateThread stateThread; int animDoneTime[ANIM_NumAnimChannels]; private: stateResult_t State_Raise ( const stateParms_t& parms ); stateResult_t State_Lower ( const stateParms_t& parms ); stateResult_t State_ExitCinematic ( const stateParms_t& parms ); stateResult_t State_NetCatchup ( const stateParms_t& parms ); stateResult_t Frame_EjectBrass ( const stateParms_t& parms ); // store weapon index information for death messages int methodOfDeath; // multiplayer hitscans int hitscanAttackDef; CLASS_STATES_PROTOTYPE ( rvWeapon ); }; ID_INLINE rvViewWeapon* rvWeapon::GetViewModel ( void ) const { return viewModel.GetEntity(); } ID_INLINE idAnimatedEntity* rvWeapon::GetWorldModel ( void ) const { return worldModel; } ID_INLINE idPlayer* rvWeapon::GetOwner ( void ) const { return owner; } ID_INLINE const char* rvWeapon::GetIcon ( void ) const { return icon; } ID_INLINE renderLight_t& rvWeapon::GetLight ( int light ) { assert ( light < WPLIGHT_MAX ); return lights[light]; } ID_INLINE const idAngles& rvWeapon::GetViewModelAngles( void ) const { return viewModelAngles; } ID_INLINE const idVec3& rvWeapon::GetViewModelOffset ( void ) const { return viewModelOffset; } ID_INLINE int rvWeapon::GetZoomFov ( void ) const { return zoomFov; } ID_INLINE idUserInterface* rvWeapon::GetZoomGui ( void ) const { return zoomGui; } ID_INLINE float rvWeapon::GetZoomTime ( void ) const { return zoomTime; } ID_INLINE int rvWeapon::GetMods ( void ) const { return mods; } ID_INLINE void rvWeapon::PreSave ( void ) { } ID_INLINE void rvWeapon::PostSave ( void ) { } #endif /* !__GAME_WEAPON_H__ */ // RAVEN END
#include <iberbar/RHI/D3D9/CommandContext.h> #include <iberbar/RHI/D3D9/Types.h> #include <iberbar/RHI/D3D9/Device.h> #include <iberbar/RHI/D3D9/Buffer.h> #include <iberbar/RHI/D3D9/Shader.h> #include <iberbar/RHI/D3D9/ShaderState.h> #include <iberbar/RHI/D3D9/ShaderVariables.h> #include <iberbar/RHI/D3D9/VertexDeclaration.h> #include <iberbar/RHI/D3D9/Texture.h> #include <iberbar/RHI/D3D9/RenderState.h> #include <iberbar/RHI/ShaderVariables.h> iberbar::RHI::D3D9::CCommandContext::CCommandContext( CDevice* pDevice ) : ICommandContext() , m_pDevice( pDevice ) , m_pVertexBuffer( nullptr ) , m_pIndexBuffer( nullptr ) , m_pShaderState( nullptr ) , m_pBlendState( nullptr ) , m_pBlendStateDefault( nullptr ) , m_pTexture() { m_pDevice->AddRef(); memset( m_pTexture, 0, sizeof( m_pTexture ) ); } iberbar::RHI::D3D9::CCommandContext::~CCommandContext() { for ( int i = 0; i < 8; i++ ) { UNKNOWN_SAFE_RELEASE_NULL( m_pTexture[ i ] ); } UNKNOWN_SAFE_RELEASE_NULL( m_pVertexBuffer ); UNKNOWN_SAFE_RELEASE_NULL( m_pIndexBuffer ); UNKNOWN_SAFE_RELEASE_NULL( m_pBlendState ); UNKNOWN_SAFE_RELEASE_NULL( m_pBlendStateDefault ); UNKNOWN_SAFE_RELEASE_NULL( m_pDevice ); } void iberbar::RHI::D3D9::CCommandContext::SetVertexBuffer( IVertexBuffer* pVertexBuffer ) { if ( m_pVertexBuffer != pVertexBuffer ) { UNKNOWN_SAFE_RELEASE_NULL( m_pVertexBuffer ); m_pVertexBuffer = (CVertexBuffer*)pVertexBuffer; UNKNOWN_SAFE_ADDREF( m_pVertexBuffer ); } } void iberbar::RHI::D3D9::CCommandContext::SetIndexBuffer( IIndexBuffer* pIndexBuffer ) { if ( m_pIndexBuffer != pIndexBuffer ) { UNKNOWN_SAFE_RELEASE_NULL( m_pIndexBuffer ); m_pIndexBuffer = (CIndexBuffer*)pIndexBuffer; UNKNOWN_SAFE_ADDREF( m_pIndexBuffer ); } } void iberbar::RHI::D3D9::CCommandContext::SetShaderState( IShaderState* pShaderState ) { if ( m_pShaderState != pShaderState ) { UNKNOWN_SAFE_RELEASE_NULL( m_pShaderState ); m_pShaderState = (CShaderState*)pShaderState; UNKNOWN_SAFE_ADDREF( m_pShaderState ); } } void iberbar::RHI::D3D9::CCommandContext::SetShaderVariableTable( EShaderType eShaderType, IShaderVariableTable* pShaderVariableTable ) { if ( m_pShaderVariableTables[ (int)eShaderType ] != pShaderVariableTable ) { UNKNOWN_SAFE_RELEASE_NULL( m_pShaderVariableTables[ (int)eShaderType ] ); m_pShaderVariableTables[ (int)eShaderType ] = (CShaderVariableTable*)pShaderVariableTable; UNKNOWN_SAFE_ADDREF( m_pShaderVariableTables[ (int)eShaderType ] ); } } void iberbar::RHI::D3D9::CCommandContext::SetBlendState( IBlendState* pBlendState ) { if ( m_pBlendState == pBlendState ) return; if ( m_pBlendState != nullptr && pBlendState != nullptr && m_pBlendState->Equal( pBlendState ) ) return; UNKNOWN_SAFE_RELEASE_NULL( m_pBlendState ); m_pBlendState = (CBlendState*)pBlendState; if ( m_pBlendState == nullptr ) { m_pBlendState = m_pBlendStateDefault; m_pBlendState->AddRef(); } PrepareBlendState(); } void iberbar::RHI::D3D9::CCommandContext::SetBlendStateDefault( IBlendState* pBlendState ) { assert( pBlendState ); UNKNOWN_SAFE_RELEASE_NULL( m_pBlendStateDefault ); m_pBlendStateDefault = (CBlendState*)pBlendState; m_pBlendStateDefault->AddRef(); SetBlendState( m_pBlendStateDefault ); } void iberbar::RHI::D3D9::CCommandContext::DrawElements( UPrimitiveType nPrimitiveType, UIndexFormat nIndexFormat, uint32 nCount, uint32 nOffset ) { IDirect3DDevice9* pD3DDevice = m_pDevice->GetD3DDevice(); PrepareDraw(); uint32 nVertexCount = nCount / 2 * 4; //uint32 nVertexCount = nCount * 3; pD3DDevice->DrawIndexedPrimitive( ConvertPrimitiveType( nPrimitiveType ), 0, 0, nVertexCount, 0, nCount ); CleanResources(); } void iberbar::RHI::D3D9::CCommandContext::PrepareDraw() { IDirect3DDevice9* pd3dDevice = m_pDevice->GetD3DDevice(); // 顶点声明的启用 m_pDevice->GetD3DDevice()->SetVertexDeclaration( m_pShaderState->GetVertexDeclaration()->GetD3DVertexDeclaration() ); m_pDevice->SetVertexShader( m_pShaderState->GetVertexShader()->GetD3DShader() ); m_pDevice->SetPixelShader( m_pShaderState->GetPixelShader()->GetD3DShader() ); m_pDevice->BindVertexBuffer( m_pVertexBuffer->GetD3DVertexBuffer(), m_pShaderState->GetVertexDeclaration()->GetStride() ); m_pDevice->BindIndexBuffer( m_pIndexBuffer->GetD3DIndexBuffer() ); // 准备shader变量 PrepareShaderVariables(); // //ID3DXConstantTable* pD3DConstTablePixel = pShader->GetD3DPixelShaderConstTable(); //// //// 设置 shader 的 Sampler //auto& ShaderVars_Samplers = m_pShaderVariableTable->GetSamplers(); //if ( ShaderVars_Samplers.empty() == false ) //{ // D3DXHANDLE hTex = nullptr; // UINT nCount; // D3DXCONSTANT_DESC TexDesc; // const UShaderSampler* pSampler = nullptr; // CTexture* pTextureTemp = nullptr; // for ( size_t i = 0, s = ShaderVars_Samplers.size(); i < s; i++ ) // { // hTex = pD3DConstTablePixel->GetConstantByName( 0, ShaderVars_Samplers[ i ].strName.c_str() ); // if ( hTex == nullptr ) // continue; // pD3DConstTablePixel->GetConstantDesc( hTex, &TexDesc, &nCount ); // if ( TexDesc.Type == D3DXPT_SAMPLER2D ) // { // pSampler = &ShaderVars_Samplers[ i ].Value; // pTextureTemp = (CTexture*)(ITexture*)(pSampler->pTexture); // m_pDevice->SetTexture( TexDesc.RegisterIndex, pTextureTemp == nullptr ? nullptr : pTextureTemp->GetD3DTexture() ); // m_pDevice->SetSamplerState( TexDesc.RegisterIndex, pSampler->State ); // } // } //} //// //// 设置 Shader 的 bool布尔变量 //auto& ShaderVars_Bools = m_pShaderVars->GetBools(); //if ( ShaderVars_Bools.empty() == false ) //{ // D3DXHANDLE pHandle = nullptr; // UINT nCount; // D3DXCONSTANT_DESC TexDesc; // for ( size_t i = 0, s = ShaderVars_Bools.size(); i < s; i++ ) // { // pHandle = pD3DConstTablePixel->GetConstantByName( 0, ShaderVars_Bools[ i ].strName.c_str() ); // if ( pHandle == nullptr ) // continue; // pD3DConstTablePixel->GetConstantDesc( pHandle, &TexDesc, &nCount ); // if ( TexDesc.Type == D3DXPT_BOOL ) // { // pD3DConstTablePixel->SetBool( m_pDevice->GetD3DDevice(), pHandle, ShaderVars_Bools[ i ].Value == false ? FALSE : TRUE ); // } // } //} /* m_pDevice->GetD3DDevice()->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); m_pDevice->GetD3DDevice()->SetRenderState( D3DRS_LIGHTING, FALSE ); m_pDevice->GetD3DDevice()->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE )*/; //pd3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );; //pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); //启用深度测试 pd3dDevice->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, FALSE ); //pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); //pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); //pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); //pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ); //pd3dDevice->SetRenderState( D3DRS_SEPARATEALPHABLENDENABLE, TRUE ); //pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); //pd3dDevice->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED ); pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_FLAT ); //设置平面着色模式 //pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_RESULTARG, D3DTA_CURRENT ); //pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); //pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); //pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); } void iberbar::RHI::D3D9::CCommandContext::PrepareShaderVariableTable( EShaderType eShaderType, CShaderVariableTable* pShaderVariableTable ) { if ( pShaderVariableTable == nullptr ) { return; } IDirect3DDevice9* pD3DDevice = m_pDevice->GetD3DDevice(); if ( eShaderType == EShaderType::PixelShader ) { // 填充Sampler auto& SamplerStates = pShaderVariableTable->GetSamplerStates(); CSamplerState* pSamplerStateTemp = nullptr; for ( size_t i = 0, s = SamplerStates.size(); i < s; i++ ) { //pTextureTemp = (CTexture*)(RHI::ITexture*)Samplers[ i ].pTexture; //m_pDevice->SetTexture( (uint32)i, pTextureTemp == nullptr ? nullptr : pTextureTemp->GetD3DTexture() ); //if ( pTextureTemp != nullptr ) //{ // m_pDevice->SetSamplerState( (uint32)i, Samplers[ i ].pSamplerState->GetSamplerDesc() ); //} pSamplerStateTemp = SamplerStates[ i ]; if ( pSamplerStateTemp == nullptr ) { m_pDevice->SetSamplerState( (uint32)i, UTextureSamplerState::s_Default ); } else { m_pDevice->SetSamplerState( (uint32)i, pSamplerStateTemp->GetSamplerDesc() ); } } auto& Textures = pShaderVariableTable->GetTextures(); CTexture* pTextureTemp = nullptr; for ( size_t i = 0, s = SamplerStates.size(); i < s; i++ ) { pTextureTemp = Textures[ i ]; m_pDevice->SetTexture( (uint32)i, pTextureTemp == nullptr ? nullptr : pTextureTemp->GetD3DTexture() ); } } const uint8* pVarsBuffer = pShaderVariableTable->GetBuffer(); const CShaderReflection* pReflection = pShaderVariableTable->GetShaderReflection(); const CShaderReflectionBuffer* pReflectionBuffer = pReflection->GetBuffer(); const CShaderReflectionVariable* pReflectionVar = nullptr; int nVarCount = pReflectionBuffer->GetVariableCountInternal(); ID3DXConstantTable* pD3DConstTable = pShaderVariableTable->GetShaderInternal()->GetD3DConstTable(); for ( int i = 0, s = nVarCount; i < s; i++ ) { pReflectionVar = pReflectionBuffer->GetVariableByIndexInternal( i ); pD3DConstTable->SetValue( pD3DDevice, pReflectionVar->GetD3DHandle(), pVarsBuffer + pReflectionVar->GetOffset(), pReflectionVar->GetTotalSize() ); } float viewport[ 2 ] = { (float)m_pDevice->GetContextSize().w, (float)m_pDevice->GetContextSize().h }; pReflectionVar = pReflectionBuffer->GetVariableByNameInternal( "g_viewport" ); if ( pReflectionVar ) { pD3DConstTable->SetValue( pD3DDevice, pReflectionVar->GetD3DHandle(), viewport, sizeof( float ) * 2 ); } } void iberbar::RHI::D3D9::CCommandContext::PrepareShaderVariables() { // 填充普通变量 IDirect3DDevice9* pD3DDevice = m_pDevice->GetD3DDevice(); PrepareShaderVariableTable( EShaderType::VertexShader, m_pShaderVariableTables[ (int)EShaderType::VertexShader ] ); PrepareShaderVariableTable( EShaderType::PixelShader, m_pShaderVariableTables[ (int)EShaderType::PixelShader ] ); } void iberbar::RHI::D3D9::CCommandContext::PrepareBlendState() { //if ( m_pBlendState == nullptr ) //{ // SetBlendState( m_pBlendStateDefault ); //} assert( m_pBlendState ); IDirect3DDevice9* pD3DDevice = m_pDevice->GetD3DDevice(); const UBlendDesc& BlendDesc = m_pBlendState->GetDesc(); BOOL AlphaTest = BlendDesc.RenderTargets[ 0 ].BlendEnable == true ? TRUE : FALSE; pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, AlphaTest ); pD3DDevice->SetRenderState( D3DRS_SRCBLEND, ConvertBlend( BlendDesc.RenderTargets[ 0 ].SrcBlend ) ); pD3DDevice->SetRenderState( D3DRS_DESTBLEND, ConvertBlend( BlendDesc.RenderTargets[ 0 ].DestBlend ) ); pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, AlphaTest ); pD3DDevice->SetRenderState( D3DRS_BLENDOP, ConvertBlendOP( BlendDesc.RenderTargets[ 0 ].BlendOp ) ); pD3DDevice->SetRenderState( D3DRS_SRCBLENDALPHA, ConvertBlend( BlendDesc.RenderTargets[ 0 ].SrcBlendAlpha ) ); pD3DDevice->SetRenderState( D3DRS_DESTBLENDALPHA, ConvertBlend( BlendDesc.RenderTargets[ 0 ].DestBlendAlpha ) ); pD3DDevice->SetRenderState( D3DRS_BLENDOPALPHA, ConvertBlendOP( BlendDesc.RenderTargets[ 0 ].BlendOpAlpha ) ); pD3DDevice->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED ); } void iberbar::RHI::D3D9::CCommandContext::CleanResources() { UNKNOWN_SAFE_RELEASE_NULL( m_pShaderState ); for ( int i = 0, s = (int)EShaderType::__Count; i < s; i ++ ) { UNKNOWN_SAFE_RELEASE_NULL( m_pShaderVariableTables[i] ); } UNKNOWN_SAFE_RELEASE_NULL( m_pVertexBuffer ); UNKNOWN_SAFE_RELEASE_NULL( m_pIndexBuffer ); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined ENCODINGS_HAVE_TABLE_DRIVEN && defined ENCODINGS_HAVE_CHINESE #include "modules/encodings/tablemanager/optablemanager.h" #include "modules/encodings/encoders/iso-2022-cn-encoder.h" #include "modules/encodings/encoders/encoder-utility.h" #define ISO2022CN_SBCS 0x0F /* SI: Switch to ASCII mode */ #define ISO2022CN_DBCS 0x0E /* SO: Switch to DBCS mode */ UTF16toISO2022CNConverter::UTF16toISO2022CNConverter() : m_cur_charset(ASCII), m_so_initialized(NONE), m_ss2_initialized(FALSE), m_gbk_table1(NULL), m_gbk_table2(NULL), m_cns11643_table1(NULL), m_cns11643_table2(NULL), m_gbk_table1top(0), m_gbk_table2len(0), m_cns116431_table1top(0), m_cns1143_table2len(0) { } OP_STATUS UTF16toISO2022CNConverter::Construct() { if (OpStatus::IsError(this->OutputConverter::Construct())) return OpStatus::ERR; long gbk_table1len, cns1143_table1len; m_gbk_table1 = reinterpret_cast<const unsigned char *>(g_table_manager->Get("gbk-rev-table-1", gbk_table1len)); m_gbk_table2 = reinterpret_cast<const unsigned char *>(g_table_manager->Get("gbk-rev-table-2", m_gbk_table2len)); m_cns11643_table1 = reinterpret_cast<const unsigned char *>(g_table_manager->Get("cns11643-rev-table-1", cns1143_table1len)); m_cns11643_table2 = reinterpret_cast<const unsigned char *>(g_table_manager->Get("cns11643-rev-table-2", m_cns1143_table2len)); // Determine which characters are supported by the tables m_gbk_table1top = 0x4E00 + gbk_table1len / 2; m_cns116431_table1top = 0x4E00 + cns1143_table1len / 2; return m_gbk_table1 && m_gbk_table2 && m_cns11643_table1 && m_cns11643_table2 ? OpStatus::OK : OpStatus::ERR; } UTF16toISO2022CNConverter::~UTF16toISO2022CNConverter() { if (g_table_manager) { g_table_manager->Release(m_gbk_table1); g_table_manager->Release(m_gbk_table2); g_table_manager->Release(m_cns11643_table1); g_table_manager->Release(m_cns11643_table2); } } int UTF16toISO2022CNConverter::switch_charset(const char *tag, size_t taglen, BOOL need_so, char *output, int spaceleft) { // Don't split character and its escape, make sure we have enough space // left in the buffer for the switch and a character int lengthneeded = taglen + (need_so ? 1 : 0); if (lengthneeded + 2 > spaceleft) { return 0; } else { op_memcpy(output, tag, taglen); if (need_so) { output[taglen] = ISO2022CN_DBCS; } return lengthneeded; } } int UTF16toISO2022CNConverter::Convert(const void *src, int len, void *dest, int maxlen, int *read_p) { int read = 0; int written = 0; const UINT16 *input = reinterpret_cast<const UINT16 *>(src); int utf16len = len / 2; char *output = reinterpret_cast<char *>(dest); while (read < utf16len && written < maxlen) { if (*input < 128) { // ASCII if (m_cur_charset != ASCII) { if (written + 2 > maxlen) { // Don't split escape code goto leave; } *(output ++) = ISO2022CN_SBCS; // SI written ++; m_cur_charset = ASCII; } switch (*input) { case 0x1B: // <ESC> case ISO2022CN_DBCS: // <SO> // Always switch back to ASCII for invalid characters if (m_cur_charset != ASCII) { if (written + 2 > maxlen) { // Don't split escape code goto leave; } *(output ++) = ISO2022CN_SBCS; // SI written ++; m_cur_charset = ASCII; } #ifdef ENCODINGS_HAVE_ENTITY_ENCODING if (!CannotRepresent(*input, read, &output, &written, maxlen)) { goto leave; } #else *(output ++) = '?'; CannotRepresent(*input, read); #endif break; case 0x0A: // <LF> case 0x0D: // <CR> case 0x00: // <nul> // CR and LF and end-of-string reset state m_so_initialized = NONE; m_ss2_initialized = FALSE; /* Fall through */ default: *(output ++) = static_cast<char>(*input); } written ++; } else { char gb2312_rowcell[2] = { 0, 0 }; char cns11643_dbcsdata[2] = { 0, 0 }; char cns11643_plane = 0; char cns11643_rowcell[2] = { 0, 0 }; // Try to find the character in the currently active SO // charset first. If that fails, try to find it in the // others: // // GB2312 -> TRY_CNS_11643 -> FAIL // CNS_11643 -> TRY_GB2312 -> FAIL // (ASCII ->) TRY_GB2312 -> TRY_CNS_11643 -> FAIL BOOL found = FALSE; enum cn_charset new_charset = (m_cur_charset == ASCII) ? TRY_GB2312 : m_cur_charset; do { switch (new_charset) { case GB2312: case TRY_GB2312: if (*input >= 0x4E00 && *input < m_gbk_table1top) { gb2312_rowcell[1] = m_gbk_table1[(*input - 0x4E00) * 2]; gb2312_rowcell[0] = m_gbk_table1[(*input - 0x4E00) * 2 + 1]; } else { lookup_dbcs_table(m_gbk_table2, m_gbk_table2len, *input, gb2312_rowcell); } // Since we're using a GBK table, we have codepoints // outside GB2312's range. We treat those as undefined. if (static_cast<unsigned char>(gb2312_rowcell[0]) > 0xA0 && static_cast<unsigned char>(gb2312_rowcell[0]) < 0xFE && static_cast<unsigned char>(gb2312_rowcell[1]) > 0xA0) { // This codepoint is valid in ISO 2022-CN (but might // be undefined in GB2312, but we ignore that case) if (m_cur_charset != GB2312) { if (m_so_initialized != GB2312) { size_t bytes_added = switch_charset("\x1B$)A", 4, (m_cur_charset == ASCII), output, maxlen - written); if (!bytes_added) { // Don't split goto leave; } written += bytes_added; output += bytes_added; } else { if (written + 3 > maxlen) { // Don't split goto leave; } *(output ++) = ISO2022CN_DBCS; written ++; } m_so_initialized = m_cur_charset = GB2312; } else if (written + 2 > maxlen) { // Don't split character goto leave; } // Our table is in EUC-CN encoding, so we strip the high-bit *(output ++) = gb2312_rowcell[0] & 0x7F; *(output ++) = gb2312_rowcell[1] & 0x7F; written += 2; found = TRUE; } else { // Not found in (or valid for) GB2312; try next encoding new_charset = (m_cur_charset == CNS_11643_1) ? FAIL : TRY_CNS_11643; } break; case CNS_11643_1: case TRY_CNS_11643: if (*input >= 0x4E00 && *input < m_cns116431_table1top) { cns11643_dbcsdata[1] = m_cns11643_table1[(*input - 0x4E00) * 2]; cns11643_dbcsdata[0] = m_cns11643_table1[(*input - 0x4E00) * 2 + 1]; } else { lookup_dbcs_table(m_cns11643_table2, m_cns1143_table2len, *input, cns11643_dbcsdata); } if (cns11643_dbcsdata[0] != 0 && cns11643_dbcsdata[1] != 0) { // Convert into plane, row and cell data: // What we have is a little-endian number where the two // most significant bits are the plane (1 = plane 1, 2 = // plane 2, 3 = plane 14), the next seven bits is the row // and the seven least significant bits are the cell. unsigned int value = (static_cast<unsigned char>(cns11643_dbcsdata[0]) << 8) | static_cast<unsigned char>(cns11643_dbcsdata[1]); cns11643_plane = static_cast<char>(value >> 14); cns11643_rowcell[0] = ((value >> 7) & (0x7F)); cns11643_rowcell[1] = (value & 0x7F); } // ISO 2022-CN only supports plane 1 and 2 if (1 == cns11643_plane) { if (m_cur_charset != CNS_11643_1) { if (m_so_initialized != CNS_11643_1) { size_t bytes_added = switch_charset("\x1B$)G", 4, (m_cur_charset == ASCII), output, maxlen - written); if (!bytes_added) { // Don't split goto leave; } written += bytes_added; output += bytes_added; } else { if (written + 3 > maxlen) { // Don't split goto leave; } *(output ++) = ISO2022CN_DBCS; written ++; } m_so_initialized = m_cur_charset = CNS_11643_1; } else if (written + 2 > maxlen) { // Don't split character goto leave; } *(output ++) = cns11643_rowcell[0]; *(output ++) = cns11643_rowcell[1]; written += 2; found = TRUE; } else if (2 == cns11643_plane) { if (!m_ss2_initialized) { // Need to initialize the CNS 11643 plane 2 size_t bytes_added = switch_charset("\x1B$*H", 4, FALSE, output, maxlen - written); if (!bytes_added) { // Don't split goto leave; } written += bytes_added; output += bytes_added; m_ss2_initialized = TRUE; } if (written + 4 > maxlen) { // Don't split goto leave; } *(output ++) = 0x1B; *(output ++) = 0x4E; *(output ++) = cns11643_rowcell[0]; *(output ++) = cns11643_rowcell[1]; written += 4; found = TRUE; } else { // Character in another plane than 1 or 2, or an // unconvertible character new_charset = (m_cur_charset == CNS_11643_1) ? TRY_GB2312 : FAIL; } break; } } while (!found && FAIL != new_charset); if (!found) { // Always switch back to ASCII for invalid characters if (m_cur_charset != ASCII) { if (written + 2 > maxlen) { // Don't split goto leave; } *(output ++) = ISO2022CN_SBCS; written ++; m_cur_charset = ASCII; } #ifdef ENCODINGS_HAVE_ENTITY_ENCODING if (!CannotRepresent(*input, read, &output, &written, maxlen)) { goto leave; } #else *(output ++) = '?'; written ++; CannotRepresent(*input, read); #endif } } read ++; // Counting UTF-16 characters, not bytes input ++; } // In ISO 2022-CN, we want to switch back to ASCII at end of line, // so if we have read all the input bytes and have space left in the // output buffer, we switch back. if (read == utf16len && written < maxlen) { written += ReturnToInitialState(output); // output pointer is now invalid } leave: *read_p = read * 2; // Counting bytes, not UTF-16 characters m_num_converted += read; return written; } const char *UTF16toISO2022CNConverter::GetDestinationCharacterSet() { return "iso-2022-cn"; } int UTF16toISO2022CNConverter::ReturnToInitialState(void *dest) { int written = 0; if (ASCII != m_cur_charset) { // Switch back to ASCII mode if (dest) { char *output = reinterpret_cast<char *>(dest); *output = ISO2022CN_SBCS; m_cur_charset = ASCII; } ++ written; } // Reset state if (dest) { m_so_initialized = NONE; m_ss2_initialized = FALSE; } return written; } void UTF16toISO2022CNConverter::Reset() { this->OutputConverter::Reset(); m_cur_charset = ASCII; m_so_initialized = NONE; m_ss2_initialized = FALSE; } int UTF16toISO2022CNConverter::LongestSelfContainedSequenceForCharacter() { switch (m_cur_charset) { case ASCII: // Worst case: A character in the non-initialized SO charset // Initialize SO charset: 4 bytes // Output SO character: 1 byte // Output character: 2 bytes // Switch to ASCII mode: 1 byte return 4 + 1 + 2 + 1; // Non-worst case: A character in SS2 charset, with SS2 uninitialized // Initialize SS2 charset: 4 bytes // Output SS2 switch: 2 bytes // Output character: 2 bytes case CNS_11643_1: case GB2312: default: if (m_ss2_initialized) { // Worst case: A character in the other SO charset // Initialize SO charset: 4 bytes // Output character: 2 bytes // Switch to ASCII mode: 1 byte return 4 + 2 + 1; // SS2 character requires 2 + 2 bytes here } else { // Worst case: A character in the SS2 charset // Initialize SS2 charset: 4 bytes // Output SS2 switch: 2 bytes // Output character: 2 bytes // Switch to ASCII mode: 1 byte return 4 + 2 + 2 + 1; } } } #endif // ENCODINGS_HAVE_TABLE_DRIVEN && defined ENCODINGS_HAVE_CHINESE
/* * @Description: * @Author: Ren Qian * @Date: 2020-02-29 03:32:14 */ #ifndef LIDAR_LOCALIZATION_MAPPING_VIEWER_VIEWER_FLOW_HPP_ #define LIDAR_LOCALIZATION_MAPPING_VIEWER_VIEWER_FLOW_HPP_ #include <deque> #include <ros/ros.h> // subscriber #include "lidar_localization/subscriber/cloud_subscriber.hpp" #include "lidar_localization/subscriber/odometry_subscriber.hpp" #include "lidar_localization/subscriber/key_frame_subscriber.hpp" #include "lidar_localization/subscriber/key_frames_subscriber.hpp" // publisher #include "lidar_localization/publisher/odometry_publisher.hpp" #include "lidar_localization/publisher/cloud_publisher.hpp" // viewer #include "lidar_localization/mapping/viewer/viewer.hpp" namespace lidar_localization { class ViewerFlow { public: ViewerFlow(ros::NodeHandle& nh, std::string cloud_topic); bool Run(); bool SaveMap(); private: bool ReadData(); bool HasData(); bool ValidData(); bool PublishGlobalData(); bool PublishLocalData(); private: // subscriber std::shared_ptr<CloudSubscriber> cloud_sub_ptr_; std::shared_ptr<OdometrySubscriber> transformed_odom_sub_ptr_; std::shared_ptr<KeyFrameSubscriber> key_frame_sub_ptr_; std::shared_ptr<KeyFramesSubscriber> optimized_key_frames_sub_ptr_; // publisher std::shared_ptr<OdometryPublisher> optimized_odom_pub_ptr_; std::shared_ptr<CloudPublisher> current_scan_pub_ptr_; std::shared_ptr<CloudPublisher> global_map_pub_ptr_; std::shared_ptr<CloudPublisher> local_map_pub_ptr_; // viewer std::shared_ptr<Viewer> viewer_ptr_; std::deque<CloudData> cloud_data_buff_; std::deque<PoseData> transformed_odom_buff_; std::deque<KeyFrame> key_frame_buff_; std::deque<KeyFrame> optimized_key_frames_; std::deque<KeyFrame> all_key_frames_; CloudData current_cloud_data_; PoseData current_transformed_odom_; }; } #endif
#include "RedisFactory.h" #include "ConsistentHash.h" using namespace tinyredis; CRedisMap::CRedisMap(const VEC_REDIS_PARAM_t& vecParam) { for (VEC_REDIS_PARAM_t::const_iterator c_iter = vecParam.begin(); c_iter != vecParam.end(); ++c_iter) { CRedisClient* pNew = NULL; if (c_iter->m_strIp.size() > 0) { pNew = new CRedisClient(c_iter->m_strIp, c_iter->m_uPort16, c_iter->m_strPass, c_iter->m_uMiniSeconds); } else if (c_iter->m_strPath.size() > 0) { pNew = new CRedisClient(c_iter->m_strPath, c_iter->m_strPass, c_iter->m_uMiniSeconds); } m_mapIdxRedis.insert(std::make_pair(m_mapIdxRedis.size(), pNew)); } } CRedisMap::~CRedisMap() { for (MAP_IDX_REDIS_t::iterator iter = m_mapIdxRedis.begin(); iter != m_mapIdxRedis.end(); ++iter) { delete iter->second; } m_mapIdxRedis.clear(); } CRedisClient* CRedisMap::getRedis(uint32_t uKey) { uint32_t uIdx = __toIndex(uKey); MAP_IDX_REDIS_t::iterator iter = m_mapIdxRedis.find(uIdx); if (iter == m_mapIdxRedis.end()) return NULL; return iter->second; } CRedisClient* CRedisMap::getRedis(const std::string& strKey) { uint32_t uKey = __toKey(strKey); return getRedis(uKey); } uint32_t CRedisMap::__toIndex(uint32_t uKey) { return (uKey % m_mapIdxRedis.size()); } uint32_t CRedisMap::__toKey(const std::string& strKey) { return CHashFunction::fnvHash(strKey.data(), strKey.size()); } CRedisFactory::CRedisFactory() : m_pRedisMap(NULL) { } CRedisFactory::~CRedisFactory() { __cleanRedisMap(); } void CRedisFactory::addRedis(const std::string& strIp, uint16_t uPort16, const std::string& strPass, uint32_t uMiniSeconds) { m_vecRedisParam.push_back( SRedisParam(strIp, uPort16, strPass, uMiniSeconds) ); } void CRedisFactory::addRedis(const std::string& strPath, const std::string& strPass, uint32_t uMiniSeconds) { m_vecRedisParam.push_back( SRedisParam(strPath, strPass, uMiniSeconds) ); } CRedisClient* CRedisFactory::getRedis(uint32_t uKey) { return __getRedisMap()->getRedis(uKey); } CRedisClient* CRedisFactory::getRedis(const std::string& strKey) { return __getRedisMap()->getRedis(strKey); } CRedisMap* CRedisFactory::__getRedisMap() { if (m_pRedisMap == NULL) m_pRedisMap = new CRedisMap(m_vecRedisParam); return m_pRedisMap; } void CRedisFactory::__cleanRedisMap() { if (m_pRedisMap) { delete m_pRedisMap; m_pRedisMap = NULL; } }
// ::wali::wpds::fwpds #include "wali/wpds/fwpds/FWPDS.hpp" // ::wali::wpds::ewpds #include "wali/wpds/ewpds/EWPDS.hpp" // ::wali::wpds #include "wali/wpds/WPDS.hpp" #if defined(USE_AKASH_EWPDS) || defined(USING_AKASH_FWPDS) #include "wali/wpds/ewpds/ERule.hpp" #endif // ::wali::wfa #include "wali/wfa/WFA.hpp" #include "wali/wfa/TransFunctor.hpp" #include "wali/wfa/State.hpp" // ::wali::wpds #include "wali/wpds/RuleFunctor.hpp" #include "wali/wpds/Rule.hpp" // ::std #include <iostream> #include <string> #include <sstream> #include <fstream> #include <ctime> // ::wali #include "wali/KeySpace.hpp" #include "wali/Key.hpp" #include "wali/ref_ptr.hpp" // ::wali::util #include "wali/util/Timer.hpp" // ::wali::cprover #include "BplToPds.hpp" using namespace std; using namespace wali; using namespace wali::wfa; using namespace wali::wpds; using namespace wali::wpds::ewpds; using namespace wali::wpds::fwpds; using namespace wali::cprover; using namespace wali::domains::binrel; #include <pthread.h> #include <signal.h> #include <boost/cast.hpp> static pthread_t worker; extern "C" { void handle_sighup(int signum) { if(signum == SIGHUP){ pthread_cancel(worker); } } } namespace{ class WFACompare : public wali::wfa::ConstTransFunctor { public: class TransKey { public: /* wali::Key from; wali::Key stack; wali::Key to; */ std::string from; std::string stack; std::string to; TransKey(wali::Key f,wali::Key s,wali::Key t) : from(wali::key2str(f)), stack(wali::key2str(s)), to(wali::key2str(t)) {} bool operator < (const TransKey& other) const { return from < other.from || (from == other.from && ( stack < other.stack || (stack == other.stack && to < other.to))); } ostream& print(ostream& out) const { //out << "[" << wali::key2str(from) << " -- " << wali::key2str(stack) << " -> " << wali::key2str(to) << "]" << std::endl; out << "[" << from << " -- " << stack << " -> " << to << "]" << std::endl; return out; } }; typedef enum {READ_FIRST, READ_SECOND, COMPARE} Mode; typedef std::map< TransKey, wali::sem_elem_t > DataMap; WFACompare(std::string f="FIRST", std::string s="SECOND") : first(f), second(s), cur(READ_FIRST) {} virtual void operator() (const ITrans* t) { if(cur == READ_FIRST) firstData[TransKey(t->from(),t->stack(),t->to())] = t->weight(); else if(cur == READ_SECOND){ wali::SemElemTensor * wt = boost::polymorphic_downcast<SemElemTensor*>(t->weight().get_ptr()); secondData[TransKey(t->from(),t->stack(),t->to())] = wt;//->detensorTranspose(); } else assert(false && "Not in any read mode right now"); } void advance_mode() { if(cur == READ_FIRST) cur = READ_SECOND; else if(cur == READ_SECOND) cur = COMPARE; else assert(false && "Where do you want to go dude? You're at the end of the line!"); } bool diff(std::ostream * out = 0) { bool diffFound = false; assert(cur == COMPARE); for(DataMap::const_iterator iter = firstData.begin(); iter != firstData.end(); ++iter){ TransKey tk = iter->first; DataMap::iterator iter2 = secondData.find(tk); if(iter2 == secondData.end()){ if(!(iter->second == NULL) && !(iter->second->equal(iter->second->zero()))){ diffFound=true; if(out){ *out << "DIFF: Found in " << first << " but not in " << second << ":" << std::endl; (iter->first).print(*out); iter->second->print(*out); *out << std::endl; } } }else{ sem_elem_t fwpdswt = iter->second; sem_elem_tensor_t nwpdswt = boost::polymorphic_downcast<SemElemTensor*>(iter2->second.get_ptr()); if(!(iter2->second == NULL)){ nwpdswt = boost::polymorphic_downcast<SemElemTensor*>(nwpdswt->detensorTranspose().get_ptr())->transpose(); assert(!(nwpdswt == NULL)); } if((fwpdswt == NULL && nwpdswt != NULL) || (fwpdswt != NULL && nwpdswt == NULL) || !((fwpdswt)->equal(nwpdswt))){ diffFound=true; if(out){ *out << "DIFF: Found in both but weights differ: " << std::endl; (iter->first).print(*out); *out << std::endl << "[ " << first << " weight]" << std::endl; if(fwpdswt != NULL) fwpdswt->print(*out); else *out << "NULL" << std::endl; *out << std::endl << "[ " << second << " weight]" << std::endl; if(nwpdswt != NULL) nwpdswt->print(*out); else *out << "NULL" << std::endl; *out << std::endl; } }else{ //DEBUGGING if(out && 0){ *out << "Printing anyway:\n"; (iter->first).print(*out); *out << std::endl << "[ " << first << " weight]" << std::endl; if(iter->second != NULL) iter->second->print(*out); else *out << "NULL" << std::endl; *out << std::endl << "[ " << second << " weight]" << std::endl; if(iter2->second != NULL) iter2->second->print(*out); else *out << "NULL" << std::endl; *out << std::endl; } //DEBUGGING } } } for(DataMap::const_iterator iter = secondData.begin(); iter != secondData.end(); ++iter){ DataMap::iterator iter2 = firstData.find(iter->first); if(iter2 == firstData.end()){ if(!(iter->second == NULL) && !(iter->second->equal(iter->second->zero()))){ diffFound=true; if(out){ *out << "DIFF: Found in " << second << " but not in " << first << ":" << std::endl; (iter->first).print(*out); iter->second->print(*out); *out << std::endl; } } } } return diffFound; } private: string first; string second; Mode cur; DataMap firstData; DataMap secondData; }; class PDSCompare : public wali::wpds::ConstRuleFunctor { public: class RuleKey { public: wali::Key from_state; wali::Key from_stack; wali::Key to_state; wali::Key to_stack1; wali::Key to_stack2; RuleKey(wali::Key fstate,wali::Key fstack,wali::Key tstate, wali::Key tstack1, wali::Key tstack2) : from_state(fstate), from_stack(fstack), to_state(tstate), to_stack1(tstack1), to_stack2(tstack2) {} bool operator < (const RuleKey& other) const { return from_state < other.from_state || (from_state == other.from_state && ( from_stack < other.from_stack || (from_stack == other.from_stack && ( to_state < other.to_state || (to_state == other.to_state && ( to_stack1 < other.to_stack1 || (to_stack1 == other.to_stack1 && ( to_stack2 < other.to_stack2)))))))); } ostream& print(ostream& out) const { out << "[<" << wali::key2str(from_state) << " , " << wali::key2str(from_stack) << " > --> < " << wali::key2str(to_state) << " , " << wali::key2str(to_stack1) << " " << wali::key2str(to_stack2) << " >]" << std::endl; return out; } }; typedef enum {READ_FIRST, READ_SECOND, COMPARE} Mode; typedef std::map< RuleKey, wali::sem_elem_t > WeightMap; #if defined(USING_AKASH_EWPDS) || defined(USING_AKASH_FWPDS) typedef std::map< RuleKey, wali::merge_fn_t > MergeFnMap; #endif PDSCompare(std::string f="FIRST", std::string s="SECOND") : first(f), second(s), cur(READ_FIRST) {} virtual void operator() (const rule_t& t) { if(cur == READ_FIRST){ firstWts[RuleKey(t->from_state(),t->from_stack(),t->to_state(),t->to_stack1(),t->to_stack2())] = t->weight(); }else if(cur == READ_SECOND){ secondWts[RuleKey(t->from_state(),t->from_stack(),t->to_state(),t->to_stack1(),t->to_stack2())] = t->weight(); }else{ assert(false && "Not in any read mode right now"); } #if defined(USING_AKASH_EWPDS) || defined(USING_AKASH_FWPDS) if(cur == READ_FIRST){ firstMergeFns[RuleKey(t->from_state(),t->from_stack(),t->to_state(),t->to_stack1(),t->to_stack2())] = t->merge_fn(); }else if(cur == READ_SECOND){ secondMergeFns[RuleKey(t->from_state(),t->from_stack(),t->to_state(),t=>to_stack1(),t->to_stack2())] = t->merge_fn(); }else{ assert(false && "Not in any read mode right now"); } #endif } void advance_mode() { if(cur == READ_FIRST) cur = READ_SECOND; else if(cur == READ_SECOND) cur = COMPARE; else assert(false && "Where do you want to go dude? You're at the end of the line!"); } bool diff(std::ostream * out = 0) { bool diffFound = false; assert(cur == COMPARE); for(WeightMap::const_iterator iter = firstWts.begin(); iter != firstWts.end(); ++iter){ RuleKey tk = iter->first; WeightMap::iterator iter2 = secondWts.find(tk); if(iter2 == secondWts.end()){ if(!(iter->second == NULL) && !(iter->second->equal(iter->second->zero()))){ diffFound=true; if(out){ *out << "DIFF: Weight found in " << first << " but not in " << second << ":" << std::endl; (iter->first).print(*out); iter->second->print(*out); *out << std::endl; } } }else{ if((iter->second == NULL && iter2->second != NULL) || (iter->second != NULL && iter2->second == NULL) || !((iter->second)->equal(iter2->second))){ diffFound=true; if(out){ *out << "DIFF: Found in both but weights differ: " << std::endl; (iter->first).print(*out); *out << std::endl << "[ " << first << " weight]" << std::endl; if(iter->second != NULL) iter->second->print(*out); else *out << "NULL" << std::endl; *out << std::endl << "[ " << second << " weight]" << std::endl; if(iter2->second != NULL) iter2->second->print(*out); else *out << "NULL" << std::endl; *out << std::endl; } } } } for(WeightMap::const_iterator iter = secondWts.begin(); iter != secondWts.end(); ++iter){ WeightMap::iterator iter2 = firstWts.find(iter->first); if(iter2 == firstWts.end()){ if(!(iter->second == NULL) && !(iter->second->equal(iter->second->zero()))){ diffFound=true; if(out){ *out << "DIFF: Found in " << second << " but not in " << first << ":" << std::endl; (iter->first).print(*out); iter->second->print(*out); *out << std::endl; } } } } return diffFound; } private: string first; string second; Mode cur; WeightMap firstWts; WeightMap secondWts; #if defined(USING_AKASH_EWPDS) || defined(USING_AKASH_FWPDS) MergeFnMap firstMergeFns; MergeFnMap secondMergeFns; #endif }; } namespace goals { short dump = false; char * mainProc = NULL, * errLbl = NULL; string fname; prog * pg; FWPDS * originalPds = NULL; BddContext * con = NULL; void doPostStar(WPDS * pds, WFA& outfa) { WFA fa; wali::Key acc = wali::getKeySpace()->getKey("accept"); fa.addTrans(getPdsState(),getEntryStk(pg, mainProc), acc, pds->get_theZero()->one()); fa.setInitialState(getPdsState()); fa.addFinalState(acc); if(dump){ fstream outfile("init_outfa.dot", fstream::out); fa.print_dot(outfile, true); outfile.close(); } if(dump){ fstream outfile("init_outfa.txt", fstream::out); fa.print(outfile); outfile.close(); } cout << "[Newton Compare] Computing poststar..." << endl; FWPDS * fpds = NULL; fpds = dynamic_cast<FWPDS*>(pds); if(fpds == NULL){ pds->poststar(fa,outfa); }else{ fpds->poststarIGR(fa,outfa); } if(dump){ cout << "[Newton Compare] Dumping the output automaton in dot format to outfa.dot" << endl; fstream outfile("final_outfa.dot", fstream::out); outfa.print_dot(outfile, true); outfile.close(); } if(dump){ cout << "[Newton Compare] Dumping the output automaton to final_outfa.txt" << endl; fstream outfile("final_outfa.txt", fstream::out); outfa.print(outfile); outfile.close(); } } sem_elem_t computePathSummary(WPDS * pds, WFA& outfa) { cout << "[Newton Compare] Checking error label reachability..." << endl; WpdsStackSymbols syms; pds->for_each(syms); WFA errfa; wali::Key fin = wali::getKeySpace()->getKey("accept"); std::set<Key>::iterator it; errfa.addTrans(getPdsState(), getErrStk(pg), fin, outfa.getSomeWeight()); for(it = syms.gamma.begin(); it != syms.gamma.end(); it++) errfa.addTrans(fin, *it, fin, outfa.getSomeWeight()); errfa.setInitialState(getPdsState()); errfa.addFinalState(fin); WFA interfa; KeepRight wmaker; interfa = errfa.intersect(wmaker, outfa); cout << "[Newton Compare] Computing path summary..." << endl; interfa.path_summary(outfa.getSomeWeight()->one()); return interfa.getState(interfa.getInitialState())->weight(); } void runNwpds(WFA& outfa) { assert(originalPds && con && mainProc && errLbl); cout << "#################################################" << endl; cout << "[Newton Compare] Goal III: end-to-end NWPDS run" << endl; FWPDS * npds = new FWPDS(*originalPds); wali::set_verify_fwpds(false); npds->useNewton(true); #if defined(BINREL_STATS) con->resetStats(); #endif wali::util::Timer * t = new wali::util::Timer("NWPDS poststar",cout); t->measureAndReport =false; doPostStar(npds, outfa); sem_elem_t wt = computePathSummary(npds, outfa); if(npds->isOutputTensored()) wt = boost::polymorphic_downcast<SemElemTensor*>(wt.get_ptr())->detensorTranspose().get_ptr(); if(wt->equal(wt->zero())) cout << "[Newton Compare] NWPDS ==> error not reachable" << endl; else{ cout << "[Newton Compare] NWPDS ==> error reachable" << endl; } t->print(std::cout << "[Newton Compare] Time taken by NWPDS poststar: ") << endl; delete t; #if defined(BINREL_STATS) con->printStats(cout); #endif //if defined(BINREL_STATS) delete npds; } void runFwpds(WFA& outfa) { assert(originalPds && con && mainProc && errLbl); cout << "#################################################" << endl; cout << "[Newton Compare] Goal IV: end-to-end FWPDS run" << endl; FWPDS * fpds = new FWPDS(*originalPds); wali::set_verify_fwpds(false); fpds->useNewton(false); #if defined(BINREL_STATS) con->resetStats(); #endif wali::util::Timer * t = new wali::util::Timer("FWPDS poststar",cout); t->measureAndReport =false; doPostStar(fpds, outfa); sem_elem_t wt = computePathSummary(fpds, outfa); if(wt->equal(wt->zero())) cout << "[Newton Compare] FWPDS ==> error not reachable" << endl; else{ cout << "[Newton Compare] FWPDS ==> error reachable" << endl; } t->print(std::cout << "[Newton Compare] Time taken by FWPDS poststar: ") << endl; delete t; #if defined(BINREL_STATS) con->printStats(cout); #endif //if defined(BINREL_STATS) delete fpds; } void runWpds(WFA& outfa) { assert(originalPds && con && mainProc && errLbl); cout << "#################################################" << endl; cout << "[Newton Compare] Goal VI: end-to-end WPDS run" << endl; WPDS * pds = new WPDS(*originalPds); #if defined(BINREL_STATS) con->resetStats(); #endif wali::util::Timer * t = new wali::util::Timer("WPDS poststar",cout); t->measureAndReport =false; doPostStar(pds, outfa); sem_elem_t wt = computePathSummary(pds, outfa); if(wt->equal(wt->zero())) cout << "[Newton Compare] WPDS ==> error not reachable" << endl; else{ cout << "[Newton Compare] WPDS ==> error reachable" << endl; } t->print(std::cout << "[Newton Compare] Time taken by WPDS poststar: ") << endl; delete t; #if defined(BINREL_STATS) con->printStats(cout); #endif //if defined(BINREL_STATS) delete pds; } void compareWpdsNwpds() { assert(originalPds && con && mainProc && errLbl); WFACompare fac("WPDS", "NWPDS"); cout << "#################################################" << endl; cout << "[Newton Compare] Goal I: Check Correctness by comparing the result automaton: WPDS vs NWPDS" << endl; { WFA outfa; runWpds(outfa); outfa.for_each(fac); if(dump){ cout << "[Newton Compare] Dumping the result automaton for WPDS..." << endl; fstream out_fa_stream("wpds_out_fa.dot", fstream::out); TransDotty td(out_fa_stream,false, NULL); out_fa_stream << "digraph{" << endl; outfa.for_each(td); out_fa_stream << "}" << endl; } fac.advance_mode(); } { WFA outfa; runNwpds(outfa); outfa.for_each(fac); if(dump){ cout << "[Newton Compare] Dumping the result automaton for NWPDS..." << endl; fstream out_fa_stream("nwpds_out_fa.dot", fstream::out); TransDotty td(out_fa_stream,false, NULL); out_fa_stream << "digraph{" << endl; outfa.for_each(td); out_fa_stream << "}" << endl; } fac.advance_mode(); } { fstream fadiff("fa_diff",fstream::out); if(dump){ fac.diff(&fadiff); }else{ bool fadifffound = fac.diff(); if(fadifffound) fadiff << "FA DIFF FOUND!!!" << std::endl; } } } } using namespace goals; static short goal; void * work(void *) { int dump; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &dump); WFA outfa; switch(goal){ case 1: compareWpdsNwpds(); break; case 2: assert(0); break; case 3: runNwpds(outfa); break; case 4: runFwpds(outfa); break; case 5: assert(0); break; case 6: runWpds(outfa); break; default: assert(0 && "I don't understand that goal!!!"); } return NULL; } int main(int argc, char ** argv) { // register signal handler signal(SIGHUP, handle_sighup); if(argc < 3){ cerr << "Usage: " << endl << "./NewtonFwpdsCompare input_file goal(1/2) [<0/1> dump] [entry function (default:main)] [error label (default:error)]" << endl << "Goal: 1 --> Compare WPDS & NWPDS. Compute poststar and compare the output automata." << endl << "Goal: 2 [NOW DEFUNCT]--> Compare FWPDS & NWPDS. Compute poststar and check if any assertion can fail." << endl << "Goal: 3 --> Run NWPDS end-to-end." << endl << "Goal: 4 --> Run FWPDS end-to-end." << endl << "Goal: 5 [RESERVED] --> Will run old NWPDS end-to-end." << endl << "Goal: 6 --> Run WPDS end-to-end." << endl; return -1; } int curarg = 2; if(argc >= curarg){ stringstream s; s << argv[curarg-1]; fname = s.str(); } ++curarg; if(argc >= curarg){ stringstream s; s << argv[curarg-1]; s >> goal; } ++curarg; if(argc >= curarg){ stringstream s; s << argv[curarg-1]; s >> dump; } ++curarg; if(argc >= curarg){ stringstream s; delete mainProc; mainProc = argv[curarg-1]; } ++curarg; if(argc >= curarg){ stringstream s; delete errLbl; errLbl = argv[curarg-1]; } cout << "Verbosity Level: " << dump << std::endl; cout << "Goal #: " << goal << std::endl; cout << "[NewtonCompare] Parsing Program..." << endl; pg = parse_prog(fname.c_str()); if(!mainProc) mainProc = strdup("main"); if(!errLbl) errLbl = strdup("error"); cout << "[Newton Compare] Post processing parsed program... " << endl; make_void_returns_explicit(pg); remove_skip(pg); instrument_enforce(pg); instrument_asserts(pg, errLbl); instrument_call_return(pg); cout << "[Newton Compare] Obtaining PDS..." << endl; originalPds = new FWPDS(); con = pds_from_prog(originalPds, pg); if(dump){ cout << "[Newton Compare] Dumping PDS to pds.dot..." << endl; fstream pds_stream("pds.dot", fstream::out); RuleDotty rd(pds_stream); pds_stream << "digraph{" << endl; originalPds->for_each(rd); pds_stream << "}" << endl; } pthread_create(&worker, NULL, &work, NULL); void * dump; pthread_join(worker, &dump); // Clean Up. delete originalPds; deep_erase_prog(&pg); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Alexander Remen (alexr) */ #ifndef WEBMAILMANAGER_H #define WEBMAILMANAGER_H #include "modules/util/adt/opvector.h" #include "adjunct/quick/managers/DesktopManager.h" class PrefsFile; class WebmailManager : public DesktopManager<WebmailManager> { public: enum HandlerSource { HANDLER_PREINSTALLED, // Handler is shipped with Opera HANDLER_CUSTOM // Handler is added by user (HTML5 protocol handler) }; public: /** Initialization, run this before calling any other functions on this object */ OP_STATUS Init(); /** @return Number of providers known to WebmailManager */ unsigned int GetCount() const; /** Get the unique, persistent ID for a mail provider * @param index A number less than GetCount() * @return Unique, persistent ID for provider at index, can be used for functions that have ID parameter */ unsigned int GetIdByIndex(unsigned int index) const; /** Get the human-readable name of a mail provider * @param id ID of provider to get name for * @param name Human-readable name of provider, e.g. "Gmail" */ OP_STATUS GetName(unsigned int id, OpString& name) const; /** Get the human-readable URL of the favicon mail provider * @param id ID of provider to get name for * @param name Human-readable URL of provider favicon, e.g. "http://mail.google.com/favicon.ico" */ OP_STATUS GetFaviconURL(unsigned int id, OpString& favicon_url) const; /** Get the human-readable URL of the provider * @param id ID of provider to get name for * @param name Human-readable URL of provider" */ OP_STATUS GetURL(unsigned int id, OpString& url) const; /** Retrieve a URL to use for using a mailto: URL with a specific provider * @param id ID of provider to get URL for * @param mailto_url mailto: URL to use * @param target_url Outputs URL that will compose new mail */ OP_STATUS GetTargetURL(unsigned int id, const URL& mailto_url, URL& target_url) const; /** Retrieve a URL as a string to use for using a mailto: URL with a specific provider * @param id ID of provider to get URL as string for * @param mailto_url mailto: URL as string to use in * @param target_url Outputs URL as string that will compose new mail */ OP_STATUS GetTargetURL(unsigned int id, const OpStringC8& mailto_url_str, OpString8& target_url_str) const; /** Called when a web handler for the mailto protocol is added * @param url Web address to the handler (page) * @param description User firendly handler name * @param set_default If TRUE, Opera will set this handler as default mail handler * @return OpStatus::OK on success, otherwise OpStatus::ERR_NO_MEMORY on insufficient memory available */ OP_STATUS OnWebHandlerAdded(OpStringC url, OpStringC description, BOOL set_default); /** Called when a web handler for the mailto protocol is removed * @param url Web address to the handler (page) */ void OnWebHandlerRemoved(OpStringC url); /** Check if a given web handler has been added * @param url Web address to the handler (page) * @return TRUE if the handler represented by the url has been added by OnWebHandlerAdded, otherwise FALSE */ BOOL IsWebHandlerRegistered(OpStringC url); /** Retrieve the source of the web handler * @param id ID of provider to get source for * @param source How the handler was added to list, HANDLER_PREINSTALLED or HANDLER_CUSTOM * @return OpStatus::OK on success, otyherwise OpStatus::ERR on invalid ID */ OP_STATUS GetSource(unsigned int id, HandlerSource& source); protected: // Constructor and destructor protected to allow instantiation for testing OP_STATUS Init(PrefsFile* prefsfile); /** Replace %character with a string in a string and put it in a string * @param to_replace - character that is fto replace * @param string - the string that contains the %character and that will be changed * @param string_to_insert - string to insert instead of the %character * @return TRUE if it did replace something */ BOOL ReplaceFormat(const char to_be_replaced, OpString8& string, const OpStringC8 string_to_insert) const; private: /** Return an identifier that has is not being used or 0 if none is available * @return The identifer */ unsigned int GetFreeId() const; private: struct WebmailProvider { unsigned int id; OpString name; OpString8 url; OpString8 favicon_url; BOOL is_webhandler; // Only to be set for custom web handlers }; WebmailManager::WebmailProvider* GetProviderById(unsigned int id) const; OpAutoVector<WebmailProvider> m_providers; enum Attribute { MAILTO_TO, MAILTO_CC, MAILTO_BCC, MAILTO_SUBJECT, MAILTO_BODY, MAILTO_URL, MAILTO_ATTR_COUNT // don't remove, should be last }; }; #endif //WEBMAILMANAGER_H
// Select your favorite One //#define CLASSIC #define MY_APP // Include API header #include "rq.h" #include <iostream> // Code to Build redqueen.exe #ifdef CLASSIC int main( int argc, char *argv[ ] ) { if( 2 <= argc ) { for( auto i = 2; i < argc; ++i ) { if( 0 == strcmp( argv[ i ], "-preview" ) ) { rqSetPreviewWindow( true ); } } rqGo( argv[ 1 ] ); } return 0; } #endif // Code to Build Your Own Software #ifdef MY_APP int main( ) { //////////////////////// // Startup redqueen //////////////////////// rqStartup( ); //////////////////////// // Camera //////////////////////// auto camera_id = rqAddCamera( ); { rqSetCameraSample ( camera_id, 31 ); // AA samples can be an arbitrary number //rqSetCameraRegion ( camera_id, 16, 16, 496, 496 ); // Render Region rqSetCameraResolution ( camera_id, 512, 512 ); rqSetCameraProjection ( camera_id, Projection ::Perspective ); rqSetCameraAngleMeasure( camera_id, AngleMeasure::Vertical ); // Camera Pose - Shutter Open rqSetCameraTime ( camera_id, 0.0f ); rqSetCameraFOV ( camera_id, 40.0f ); rqSetCameraBokeh ( camera_id, 0.5f ); rqSetCameraPosition ( camera_id, 0, 1, -4 ); rqSetCameraTarget ( camera_id, 0, 1, 0 ); rqSetCameraUpVector ( camera_id, 0, 1, 0 ); // Camera Pose - Shutter Close rqSetCameraTime ( camera_id, 1.0f ); rqSetCameraFOV ( camera_id, 40.0f ); rqSetCameraBokeh ( camera_id, 0.5f ); rqSetCameraPosition ( camera_id, 0, 1, -4 ); rqSetCameraTarget ( camera_id, 0, 1, 0 ); rqSetCameraUpVector ( camera_id, 0, 1, 0 ); //rqSetCameraUpVector ( camera_id, 0.2, 1, 0 ); // Camera Blur :) // AOVs auto aov_id0 = rqAddCameraAOV( camera_id ); auto aov_id1 = rqAddCameraAOV( camera_id ); auto aov_id2 = rqAddCameraAOV( camera_id ); rqSetCameraAOVName ( camera_id, aov_id0, "normal.png" ); rqSetCameraAOVName ( camera_id, aov_id1, "lambertian.png" ); rqSetCameraAOVName ( camera_id, aov_id2, "my_data.png" ); rqSetCameraAOVChannel ( camera_id, aov_id0, Channel::Normal ); rqSetCameraAOVChannel ( camera_id, aov_id1, Channel::Lambertian ); rqSetCameraAOVChannel ( camera_id, aov_id2, Channel::UserData ); rqSetCameraAOVUserData ( camera_id, aov_id2, "my_data" ); } //////////////////////// // Shader //////////////////////// auto shader_id0 = rqAddShader( ); auto shader_id1 = rqAddShader( ); { float color_matrix[4][4] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 }; float uv_matrix[3][3] = { 2,0,0, 0,2,0, 0,0,1 }; auto surface_shader_id0 = rqAddSurfaceShader( shader_id0 ); rqSetShaderName ( shader_id0, "white" ); //rqSetShaderVisibility ( shader_id0, Visibility::InvisibleFromLight ); rqSetSurfaceColor ( shader_id0, surface_shader_id0, Element::Lambertian, 0.8f, 0.8f, 0.8f ); //rqSetSurfaceImage ( shader_id0, surface_shader_id0, Element::Emissive, "C:\\Shinji\\redqueen\\light.hdr", 1.0f, 0, 0 ); // null : identity matrix auto surface_shader_id1 = rqAddSurfaceShader( shader_id1 ); rqSetShaderName ( shader_id1, "glossy"); //rqSetShaderVisibility ( shader_id1, Visibility::InvisibleFromCamera ); rqSetSurfaceColor ( shader_id1, surface_shader_id1, Element::Lambertian, 0.9f, 0.9f, 0.9f ); rqSetSurfaceColor ( shader_id1, surface_shader_id1, Element::Glossy , 1.0f, 1.0f, 1.0f ); rqSetSurfaceColor ( shader_id1, surface_shader_id1, Element::Roughness , 0.2f, 0.2f, 0.2f ); rqSetSurfaceColor ( shader_id1, surface_shader_id1, Element::IOR , 5.0f, 5.0f, 5.0f ); // For Fresnel //rqSetSurfaceImage ( shader_id1, surface_shader_id1, Element::Glossy, "C:\\Shinji\\redqueen\\light.hdr", 1.0f, 0, 0 ); // null : identity matrix // Smoothing ( to create vertex normals and tangents ) rqSetShaderSmoothAngle( shader_id0, 30 ); rqSetShaderSmoothAngle( shader_id1, 30 ); /* // Displacement Map Example { rqAddDisplacementShader ( shader_id0 ); rqSetDisplacementVector ( shader_id0, 0, 0, 0, -0.1 ); //rqSetDisplacementImage ( shader_id0, 0, "C:\\Shinji\\redqueen\\stone.jpg", 0.2f, 0, 0 ); rqSetDisplacementLevel ( shader_id0, 0, 16 ); rqAddDisplacementShader ( shader_id0 ); rqSetDisplacementVector ( shader_id0, 1, 0, 0, 0.01 ); //rqSetDisplacementImage ( shader_id0, 1, "C:\\Shinji\\redqueen\\stone.jpg", 0.2f, 0, 0 ); rqSetDisplacementLevel ( shader_id0, 1, 4 ); } */ } //////////////////////// // Geometry //////////////////////// auto instanced_object_id = rqAddObject( ); { // Particles rqSetObjectName( instanced_object_id, "particles" ); { // Add Group auto part_id = rqAddPart ( instanced_object_id ); // xyzxyz... float positions[ ] = { 0.3, 0.2, 0, -0.3, 0.2, 0 }; float radii [ ] = { 0.2, 0.2 }; int ids [ ] = { 0, 1 }; rqSetShaderID ( instanced_object_id, part_id, shader_id1 ); rqAddPositions( instanced_object_id, part_id, 2, positions ); rqAddRadii ( instanced_object_id, part_id, 2, radii ); rqAddParticles( instanced_object_id, part_id, 2, ids ); } } // Add Object auto object_id = rqAddObject( ); { // Instance { float matrix0[4][4] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 }; float matrix1[4][4] = { 1,0,0,0, 0,1,0,0.5, 0,0,1,0, 0,0,0,1 }; auto instance_id0 = rqAddInstance( object_id ); auto instance_id1 = rqAddInstance( object_id ); rqSetInstance( object_id, instance_id0, instanced_object_id, matrix0 ); rqSetInstance( object_id, instance_id1, instanced_object_id, matrix1 ); } // Add Group auto part_id = rqAddPart ( object_id ); // Trianlges { // xyzxyz... float positions[ ] = { -1, 0, 1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 2, 1, -1, 2, -1, 1, 2, -1, 1, 2, 1, -1, 2, 1, -1, 0, 1, 1, 0, 1, 1, 2, 1, -1, 2, -1, -1, 0, -1, -1, 0, 1, -1, 2, 1, 1, 2, -1, 1, 0, -1, 1, 0, 1, 1, 2, 1 }; // uvuvuvuv... float uvs[ ] = { 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 }; // rgbrgb... float my_data[ ] = { 1,0,0, 1,0,0, 1,0,0, 1,0,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,0,1, 0,0,1, 0,0,1, 0,0,1, 0,1,1, 0,1,1, 0,1,1, 0,1,1, 1,0,1, 1,0,1, 1,0,1, 1,0,1 }; rqAddPositions ( object_id, part_id, 20, positions ); rqAddUVs ( object_id, part_id, 20, uvs ); rqAddVertexData( object_id, part_id, "my_data", 20, 3, my_data ); { int vertex_ids[ ] = { 0, 1, 2, 0, 2, 3 }; rqSetShaderID ( object_id, part_id, shader_id0 ); rqAddTriangles ( object_id, part_id, 2, vertex_ids ); } { int vertex_ids[ ] = { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; rqSetShaderID ( object_id, part_id, shader_id0 ); rqAddTetragons ( object_id, part_id, 4, vertex_ids ); } } // Cylinder (Ribbon) Example { // Add Group auto part_id = rqAddPart ( object_id ); // xyzxyz... float positions[ ] = { -1, 0.75, 0, -0.3, 1, 0.2, 0.3, 0.75, 0.2, 1, 1, 0 }; float radii [ ] = { 0.012, 0.008, 0.004, 0.0 }; int ids [ ] = { 0, 1, 2 }; rqSetShaderID ( object_id, part_id, shader_id1 ); rqAddPositions( object_id, part_id, 4, positions ); rqAddRadii ( object_id, part_id, 4, radii ); rqAddCylinders( object_id, part_id, 3, ids); } } //////////////////////// // Light //////////////////////// { /* auto point_light_id = rqAddPointLight( ); { rqSetPointLightPosition ( point_light_id, 2.5, 3.0, 2.5 ); rqSetPointLightColor ( point_light_id, 20, 2, 2 ); rqSetPointLightDirection ( point_light_id, -1, -1, -1 ); rqSetPointLightInnerAngle( point_light_id, 0 ); rqSetPointLightOuterAngle( point_light_id, 5 ); } */ auto parallel_light_id = rqAddParallelLight( ); { rqSetParallelLightDirection( parallel_light_id, 1, -1, 1 ); rqSetParallelLightColor ( parallel_light_id, 0.5, 0.5, 0.5 ); rqSetParallelLightPhoton ( parallel_light_id, 1000000 ); // Light AOVs auto aov_id = rqAddParallelLightAOV ( parallel_light_id ); rqSetParallelLightAOVName ( parallel_light_id, aov_id, "parallel_light_lambertian.hdr"); rqSetParallelLightAOVChannel ( parallel_light_id, aov_id, Channel::Lambertian ); } } //////////////////////// // Skylight //////////////////////// { rqSetSkyLightColor ( 0.5, 0.5, 1 ); rqSetSkyLightZenith ( 0, 1, 0 ); rqSetSkyLightNorth ( 0, 0, -1 ); rqSetSkyLightSample ( 64 ); rqSetSkyLightPhoton ( 1000000 ); //rqSetSkyLightImage ( "C:\\Shinji\\redqueen\\image.hdr" ); // Light AOVs auto aov_id = rqAddSkyLightAOV ( ); rqSetSkyLightAOVName ( aov_id, "sky_lambertian.hdr"); rqSetSkyLightAOVChannel ( aov_id, Channel::Lambertian ); } //////////////////////// // Display //////////////////////// rqSetPreviewWindow ( true ); //////////////////////// // Rendering //////////////////////// rqSetRendererClamp ( 1, 1, 1 ); rqSetRendererSample( 256 ); rqSetRendererBounce( 3 ); rqSetRendererResolution( 0.1 ); //rqSetRendererDistance ( 0 ); rqInitialize ( ); rqRender ( ); rqFinalize ( ); // Shutdown redqueen rqShutdown( ); return 0; } #endif
/* * PI */ constexpr double pi() { return std::atan(1)*4; }
#include <iostream> #include <vector> #include <string> enum AST_Type { AST_NODE, AST_EXP, AST_ID, AST_BEXP, AST_UEXP }; struct AST_Node { virtual ~AST_Node() {} virtual std::string prettyPrint() {return "ERROR";} virtual AST_Type getType() {return AST_NODE;} }; struct AST_Expression : public AST_Node { AST_Type getType() {return AST_EXP;}; }; struct AST_Identifier : public AST_Node { std::string name; AST_Identifier(const std::string name) : name(name) {} std::string prettyPrint() {return name;} AST_Type getType() {return AST_ID;} }; struct AST_BinaryExpression : public AST_Expression { std::string ppop; int op; AST_Expression& lhs; AST_Expression& rhs; AST_BinaryExpression(AST_Expression& lhs, int op, AST_Expression& rhs, const char* ppop) : lhs(lhs), rhs(rhs), op(op), ppop(ppop) {} std::string prettyPrint() {return "(" + lhs.prettyPrint() + " " + ppop + " " + rhs.prettyPrint() + ")"; } AST_Type getType() {return AST_BEXP;}; }; struct AST_UnaryExpression : public AST_Expression { int op; AST_Expression& child; AST_UnaryExpression(int op, AST_Expression& child) : op(op), child(child) {} std::string prettyPrint() {return "op " + child.prettyPrint();} AST_Type getType() {return AST_UEXP;}; };
// // OCXMLOptions.h // // Created by Wes Souza. // // ------------------------ // Copyright 2013 Zynga Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------ // // We declare a class to handle parsing and storing command line options and // arguments. This class also handles generating the options to pass to Clang // tooling - for instance, creating the parsePathList and compilationDatabase // objects. // #ifndef OCXMLOptions_h #define OCXMLOptions_h #include <string> #include <vector> #include "clang/tooling/JSONCompilationDatabase.h" #define OPTION_FRAMEWORK (1 << 0) #define OPTION_TABULATE (1 << 1) #define OPTION_VERBOSE (1 << 2) #define OPTION_ALL_ATTRIBUTES (1 << 3) #define OPTION_COMPILER (1 << 4) #define OPTION_OUTPUT (1 << 5) #define OPTION_NO_STRUCT (1 << 6) namespace OCXML { class Options { private: // This field is a bitmask which stores the set options. unsigned int flags; // These options are passed to the Clang compiler to create // the compilation database. std::string compilerOptions; // The output file for which to print the XML tree is currently // not in use. std::string outputFile; // The compilationDatabaseString which will be used to create the // compilationDatabase object - passed into Clang tooling to signify // how to compile each file. std::string compilationDatabaseString; clang::tooling::CompilationDatabase* compilationDatabase; // The list of source code we need to parse - passed into Clang // tooling. std::vector<std::string>* parsePathList; // These private methods initialize the options that are passed // over to Clang tooling. void initializeCompilationDatabase(); void initializeParsePathList(int argc, char* const* arguments); // The constructor simply takes the main method's arguments and // handles the option parsing. Options(int argc, char* const* argv); ~Options(); // This class field is a singleton instance of the Options class. static Options* globalOptions; public: // These functions return the objects needed by Clang tooling. clang::tooling::CompilationDatabase &getCompilations(); std::vector<std::string> &getParsePathList(); inline bool isOptionSet(int option){return (flags & option);} // These static methods help manage the singleton instance of // the options. static void setGlobalOptions(int argc, char* const* argv); static Options* getGlobalOptions(); static void deleteOptions(); }; } #endif
#include <iostream> #include <math.h> using namespace std; int main() { setlocale(LC_ALL, "Rus"); double x, y, a, b, z, phi; int choose; cout << "Введите значение z: " << endl; cin >> z; if (z > 0) x = 1 / pow(z, 2) + 2 * z; else x = 1 - pow(z, 3); cout << "Введите значение a: " << endl; cin >> a; cout << "Введите значение b: " << endl; cin >> b; cout << "Выберите значение функции phi: " << endl << "1) Phi=2x" << endl << "2) Phi=x^2" << endl << "3) Phi=x/3" << endl; cin >> choose; switch (choose) { case 1: phi = 2 * x; cout << "Phi=2x" << endl; y = ((2.5 * a*exp(-3 * x)) - (4 * b*pow(x, 2))) / (log(fabs(x)) + phi); break; case 2: phi = pow(x, 2); cout << "Phi=x^2" << endl; y = ((2.5 * a*exp(-3 * x)) - (4 * b*pow(x, 2))) / (log(fabs(x)) + phi); break; case 3: phi = x / 3; cout << "Phi=x/3" << endl; y = ((2.5 * a*exp(-3 * x)) - (4 * b*pow(x, 2))) / (log(fabs(x)) + phi); break; default: cout << "Некоректный ввод!" << endl; } cout << "Значение y = " << y << endl; if (z > 0) cout << "Значение z > 0, поэтому x = 1/(z^2 + 2z)" << endl; else cout << "Значение z <= 0, поэтому х = 1 - z^3" << endl; system("pause"); return 0; }
// Copyright (c) 2011 Alexander Poluektov (alexander.poluektov@gmail.com) // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/auto_unit_test.hpp> #include <steel/algorithm.hpp> #include <vector> #include <algorithm> #include <boost/assign.hpp> using namespace std; using namespace boost::assign; namespace aux { template <class T> struct always_false { bool operator()(T const&) const { return false; } }; template <class T> struct always_true { bool operator()(T const&) const { return true; } }; template <class T> struct first_n { explicit first_n(size_t n) : n(n), c(0) { } bool operator()(T const&) { return ++c < n; } size_t const n; size_t c; }; template <class F, class P, class T> struct composer { composer(F f, P p) : f(f), p(p) { } bool operator()(T& t) { f(t); return p(t); } F f; P p; }; struct change_in_place { void operator()(int& i) { i = -i; } }; template <class T, class F, class P> composer<F, P, T> compose(F f, P p) { return composer<F, P, T>(f, p); } } using namespace aux; BOOST_AUTO_TEST_SUITE(for_each_while); BOOST_AUTO_TEST_CASE(always_false_non_empty) { vector<int> v; v += 1, 2, 3, 4, 5; vector<int> v2(v); v2[0] = -1; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), always_false<int>())); BOOST_CHECK(std::equal(v.begin(), v.end(), v2.begin())); } BOOST_AUTO_TEST_CASE(always_false_empty) { vector<int> v; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), always_false<int>())); BOOST_CHECK(v.empty()); } BOOST_AUTO_TEST_CASE(always_true_non_empty) { vector<int> v; v += 1, 2, 3, 4, 5; vector<int> v2(v); v2[0] = -1; v2[1] = -2; v2[2] = -3; v2[3] = -4; v2[4] = -5; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), always_true<int>())); BOOST_CHECK(std::equal(v.begin(), v.end(), v2.begin())); } BOOST_AUTO_TEST_CASE(always_true_empty) { vector<int> v; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), always_true<int>())); BOOST_CHECK(v.empty()); } BOOST_AUTO_TEST_CASE(first_3) { vector<int> v; v += 1, 2, 3, 4, 5; vector<int> v2(v); v2[0] = -1; v2[1] = -2; v2[2] = -3; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), first_n<int>(3))); BOOST_CHECK(std::equal(v.begin(), v.end(), v2.begin())); } BOOST_AUTO_TEST_CASE(first_3_empty) { vector<int> v; steel::for_each_while(v.begin(), v.end(), compose<int>(change_in_place(), first_n<int>(3))); BOOST_CHECK(v.empty()); } BOOST_AUTO_TEST_SUITE_END(); namespace aux { struct tester { explicit tester(int v) : v(v) { } int v; }; bool compare(tester const& lhs, tester const& rhs) { return lhs.v > rhs.v; } } BOOST_AUTO_TEST_SUITE(min_element_bounded); BOOST_AUTO_TEST_CASE(less_works) { std::vector<int> v; v += 2, 3, 5, 1, 8, 0; { std::vector<int>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), 1); BOOST_CHECK(*it == 1); } { std::vector<int>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), 0); BOOST_CHECK(*it == 0); } { std::vector<int>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), -42); BOOST_CHECK(*it == 0); } } BOOST_AUTO_TEST_CASE(less_works_empty) { std::vector<int> v; std::vector<int>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), 1); BOOST_CHECK(it == v.end()); } BOOST_AUTO_TEST_CASE(comp_works) { typedef aux::tester t; std::vector<t> v; v += t(2), t(3), t(5), t(1), t(8), t(0); { std::vector<t>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), aux::compare, t(5)); BOOST_CHECK(it->v == 5); } { std::vector<t>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), aux::compare, t(8)); BOOST_CHECK(it->v == 8); } { std::vector<t>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), aux::compare, t(11)); BOOST_CHECK(it->v == 8); } } BOOST_AUTO_TEST_CASE(comp_works_empty) { typedef aux::tester t; std::vector<t> v; std::vector<t>::const_iterator it = steel::min_element_bounded(v.begin(), v.end(), aux::compare, t(5)); BOOST_CHECK(it == v.end()); } BOOST_AUTO_TEST_SUITE_END(); BOOST_AUTO_TEST_SUITE(max_element_bounded); BOOST_AUTO_TEST_CASE(less_works) { std::vector<int> v; v += 2, 3, 5, 1, 8, 0; { std::vector<int>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), 5); BOOST_CHECK(*it == 5); } { std::vector<int>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), 8); BOOST_CHECK(*it == 8); } { std::vector<int>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), 42); BOOST_CHECK(*it == 8); } } BOOST_AUTO_TEST_CASE(less_works_empty) { std::vector<int> v; std::vector<int>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), 8); BOOST_CHECK(it == v.end()); } BOOST_AUTO_TEST_CASE(comp_works) { typedef aux::tester t; std::vector<t> v; v += t(2), t(3), t(5), t(1), t(8), t(0); { std::vector<t>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), aux::compare, t(5)); BOOST_CHECK(it->v == 2); } { std::vector<t>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), aux::compare, t(0)); BOOST_CHECK(it->v == 0); } { std::vector<t>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), aux::compare, t(-42)); BOOST_CHECK(it->v == 0); } } BOOST_AUTO_TEST_CASE(comp_works_empty) { typedef aux::tester t; std::vector<t> v; std::vector<t>::const_iterator it = steel::max_element_bounded(v.begin(), v.end(), aux::compare, t(5)); BOOST_CHECK(it == v.end()); } BOOST_AUTO_TEST_SUITE_END();
// Created on: 1996-11-07 // Created by: Laurent BUCHARD // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntPatch_LineConstructor_HeaderFile #define _IntPatch_LineConstructor_HeaderFile #include <Adaptor3d_Surface.hxx> #include <IntPatch_SequenceOfLine.hxx> class Adaptor3d_TopolTool; //! The intersections algorithms compute the intersection //! on two surfaces and return the intersections lines as //! IntPatch_Line. class IntPatch_LineConstructor { public: DEFINE_STANDARD_ALLOC Standard_EXPORT IntPatch_LineConstructor(const Standard_Integer mode); Standard_EXPORT void Perform (const IntPatch_SequenceOfLine& SL, const Handle(IntPatch_Line)& L, const Handle(Adaptor3d_Surface)& S1, const Handle(Adaptor3d_TopolTool)& D1, const Handle(Adaptor3d_Surface)& S2, const Handle(Adaptor3d_TopolTool)& D2, const Standard_Real Tol); Standard_EXPORT Standard_Integer NbLines() const; Standard_EXPORT Handle(IntPatch_Line) Line (const Standard_Integer index) const; protected: private: IntPatch_SequenceOfLine slin; }; #endif // _IntPatch_LineConstructor_HeaderFile
#include <iostream> #include <string> int main(){ freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); std::string a = "qwertyuiopasdfghjklzxcvbnm"; char b; std::cin >> b; if (b != 'm'){ for (int i = 0; i < 26; ++i) if (a[i] == b) std::cout << a[i+1]; } else std::cout << 'q'; }
#include <algorithm> #include <chrono> #include <iostream> #include <vector> using namespace std::chrono; void getVectorInitTime() { std::vector<int> vec(1000); auto start = high_resolution_clock::now(); for (int i = 0; i < vec.size(); ++i) { vec[i] = i; } auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); std::cout << "Vector time: " << duration.count() << " microseconds" << std::endl; } void getArrayInitTime() { std::array<int, 1000> arr; auto start = high_resolution_clock::now(); for (int i = 0; i < arr.size(); ++i) { arr[i] = i; } auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); std::cout << "Array time: " << duration.count() << " microseconds" << std::endl; } int main() { getVectorInitTime(); getArrayInitTime(); return 0; }
#include "GnMeshPCH.h" #include "GnSQLiteQuery.h" GnSQLiteQuery::GnSQLiteQuery(sqlite3_stmt* pStatement, bool bEof) : mpStatement( pStatement ), mEof( bEof ) { #if ( GNUSE_OS == PLATFORM_IOS ) mColumnCount = sqlite3_column_count( pStatement ); #endif } gint GnSQLiteQuery::GetFieldDataType(gint iNumColumn) { #if ( GNUSE_OS == PLATFORM_IOS ) if ( iNumColumn < 0 || iNumColumn > mColumnCount-1 ) { GnLogA( "Error SQLite - iNumColumn" ); } return sqlite3_column_type( mpStatement, iNumColumn); #else return GNSQLITE_NULL ; #endif } gint GnSQLiteQuery::GetIntField(gint iNumColumn) { #if ( GNUSE_OS == PLATFORM_IOS ) if ( GetFieldDataType( iNumColumn ) == SQLITE_NULL ) return 0; else return sqlite3_column_int( mpStatement, iNumColumn ); #else return GNSQLITE_NULL ; #endif } double GnSQLiteQuery::GetFloatField(gint iNumColumn) { #if ( GNUSE_OS == PLATFORM_IOS ) if ( GetFieldDataType( iNumColumn ) == SQLITE_NULL ) return 0; else return sqlite3_column_double( mpStatement, iNumColumn ); #else return GNSQLITE_NULL; #endif } const gchar* GnSQLiteQuery::GetStringField(gint iNumColumn) { #if ( GNUSE_OS == PLATFORM_IOS ) if ( GetFieldDataType( iNumColumn ) == SQLITE_NULL ) return NULL; else return (const gchar*)sqlite3_column_text( mpStatement, iNumColumn ); #else return NULL; #endif }
#include <string> #include "NotifyProc.h" #include "PlayerManager.h" NotifyProc::NotifyProc() { this->name = "NotifyProc"; } NotifyProc::~NotifyProc() { } int NotifyProc::doRequest(CDLSocketHandler * /*clientHandler*/, InputPacket * /*inputPacket*/, Context * /*pt*/) { return 0; } int NotifyProc::doResponse(CDLSocketHandler * clientHandler, InputPacket * inputPacket, Context * pt) { int error_code = inputPacket->ReadShort(); std::string error_mag = inputPacket->ReadString(); if (error_code < 0) { LOGGER(E_LOG_ERROR) << "error code = " << error_code << " error msg = " << error_mag; return EXIT; } int uid = inputPacket->ReadInt(); int vipuid = inputPacket->ReadInt(); int vip_play_count[BETNUM] = { 0 }; int64_t vip_bet_array[BETNUM] = { 0 }; for (int i = 1; i < BETNUM; i++) { vip_play_count[i] = inputPacket->ReadShort(); vip_bet_array[i] = inputPacket->ReadInt64(); } int bankerid = inputPacket->ReadInt(); int64_t banker_money = inputPacket->ReadInt64(); for (int i = 1; i < BETNUM; i++) { int rate = PlayerManager::getInstance()->SavePlayerBetRecord(vipuid, i, vip_bet_array[i], vip_play_count[i]); PlayerManager::getInstance()->updateAreaBetLimit(banker_money, i, rate); } return 0; }
#include <iostream> #include <cmath> #include <string> using namespace std; int x,y,i; void primepro() { cout << "Type a number: "; cin >> x; for(i=1; i<x; i++) { if(x % i == 0) { cout << x << " is a composite number." << endl; break; } else { cout << x << " is a prime number." << endl; break; } } } void primeinf() { // x = 0; // for(i=1; i>0; i++) { // while (x>=2) { // x++; // if(x % i == 0) { // return 0; // } else { // cout << x << " is a prime number." << endl; // break; // } // } // } } int main() { primepro(); // primeinf(); return 0; }
#include <iostream> #include "core/types.h" #include "core/shader.h" using namespace std; uint32_t g_screenWidth = 600; uint32_t g_screenHeight = 600; struct Particle { Vec2 x0,x1; Vec2 v0; }; Particle g_particle; FILE* g_file; int g_frame; bool g_step = false; bool g_pause = false; float sqr(float x) { return x*x; } void Init() { g_file = fopen("dump.txt", "w"); fprintf(g_file, "{"); g_particle.x0 = Vec2(1.0f, 0.0f); g_particle.x1 = Vec2(1.0f, 0.0f); g_particle.v0 = Vec2(0.0f); } void GLUTUpdate() { glViewport(0, 0, g_screenWidth, g_screenHeight); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //gluPerspective(45.0f, g_screenWidth/float(g_screenHeight), 0.01f, 1000.0f); gluOrtho2D(-2.0, 2.0, -2.0f, 2.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //gluLookAt(sin(g_angle)*2.0f, 0.4f, cos(g_angle)*2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); float dt = 1.0f/60.0f; Vec2 v = g_particle.v0 + 0.5f*Vec2(0.0f, -9.8f)*dt + 0.5f*Vec2(0.0f, -9.8f)*sqr(0.5f*dt); Vec2 newx = g_particle.x0 + v*dt; // constrain Vec2 j = newx - Vec2(0.0f); float e = Length(j)-1.0f; newx -= Normalize(j)*e; /* float k0 = 1.0f; float k1 = -1.0f; float k2 = 0.0f; */ //float k0 = 3.0f/2.0f; //float k1 = -2.0f; //float k2 = 1.0f/2.0f; //float k0 = 2.5f + 2.0f*sqrtf(2.0f); //float k2 = 1.5f + sqrtf(2.0f); //float k1 = -(k0 + k2); float alpha = 0.5f;//2.0f - sqrtf(2.0f); float k0 = 2.0f-alpha; float k1 = 1.0f/alpha; float k2 = sqr(1.0f-alpha)/alpha; glPointSize(5.0f); glBegin(GL_POINTS); glColor3f(1.0f, 0.0f, 0.0f); glVertex2fv(g_particle.x0); glColor3f(0.0f, 1.0f, 0.0f); glVertex2fv(g_particle.x1); glColor3f(1.0f, 1.0f, 1.0f); glVertex2fv(newx); glEnd(); if (!g_pause || g_step) { float ke0 = (g_particle.x0.y+1.0f)*9.8f + Dot(g_particle.v0, g_particle.v0)*0.5f; //g_particle.v0 = (newx-g_particle.x0)/dt; g_particle.v0 = (newx*k0 - g_particle.x0*k1 + g_particle.x1*k2)/dt; //g_particle.v0 = (newx - g_particle.x1)/(2.0f*dt); //g_particle.v0 = (g_particle.x0-g_particle.x1)/dt; //g_particle.v0 = (newx-g_particle.x0)/dt + (newx-2.0f*g_particle.x0+g_particle.x1)/(2.0f*dt); //Vec2 dx = (newx-g_particle.x0)/dt; //Vec2 ddx = (-2.0f*g_particle.x0 + newx + g_particle.x1)/(dt*dt); //g_particle.v0 = dx + ddx*dt*0.3f; g_particle.x1 = g_particle.x0; g_particle.x0 = newx; /* // make velocity energy conserving float ke1 = (g_particle.x0.y+1.0f)*9.8f + Dot(g_particle.v0, g_particle.v0)*0.5f; float a = 0.5f*Dot(g_particle.v0, g_particle.v0); float b = Dot(g_particle.v0, g_particle.v0); float c = -(ke0-ke1); float e1, e2; SolveQuadratic(a, b, c, e1, e2); g_particle.v0 *= (1.0f + e2); */ } float ke = (g_particle.x0.y+1.0f)*9.8f + Dot(g_particle.v0, g_particle.v0)*0.5f; DrawString(0.0, 0.0, "%f", ke); fprintf(g_file, "%f,", g_particle.x0.y); if (g_frame++ == 1000) { fprintf(g_file, "0.0}\n"); fclose(g_file); exit(0); } g_step = false; // flip glutSwapBuffers(); } void GLUTReshape(int width, int height) { } void GLUTArrowKeys(int key, int x, int y) { } void GLUTArrowKeysUp(int key, int x, int y) { } void GLUTKeyboardDown(unsigned char key, int x, int y) { switch (key) { case 'e': { break; } case ' ': { g_step = true; break; } case 'p': { g_pause = !g_pause; break; } case 'r': { Init(); break; } case 'q': case 27: exit(0); break; }; } void GLUTKeyboardUp(unsigned char key, int x, int y) { switch (key) { case 'e': { break; } case 'd': { break; } case ' ': { break; } } } static int lastx; static int lasty; void GLUTMouseFunc(int b, int state, int x, int y) { switch (state) { case GLUT_UP: { lastx = x; lasty = y; } case GLUT_DOWN: { lastx = x; lasty = y; } } } void GLUTMotionFunc(int x, int y) { int dx = x-lastx; int dy = y-lasty; lastx = x; lasty = y; } void GLUTPassiveMotionFunc(int x, int y) { int dx = x-lastx; int dy = y-lasty; lastx = x; lasty = y; } int main(int argc, char* argv[]) { // init gl glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(g_screenWidth, g_screenHeight); glutCreateWindow("Empty"); glutPositionWindow(350, 100); #if WIN32 glewInit(); #endif Init(); glutMouseFunc(GLUTMouseFunc); glutReshapeFunc(GLUTReshape); glutDisplayFunc(GLUTUpdate); glutKeyboardFunc(GLUTKeyboardDown); glutKeyboardUpFunc(GLUTKeyboardUp); glutIdleFunc(GLUTUpdate); glutSpecialFunc(GLUTArrowKeys); glutSpecialUpFunc(GLUTArrowKeysUp); glutMotionFunc(GLUTMotionFunc); glutPassiveMotionFunc(GLUTPassiveMotionFunc); glutMainLoop(); }
#include <stdio.h> #include <stdlib.h> struct queue { int x; struct queue *next; }; typedef struct queue Q; typedef struct queue Q2; void enqueue(Q **list,int w) { Q *p,*temp; temp=(Q*)malloc(sizeof(Q)); temp->x=w; temp->next=NULL; p=*list; if(p==NULL) { *list=temp; } else{ while(p->next!=NULL) p=p->next; temp->next=p->next; p->next=temp; } } void display(Q *list) { Q *p; p=list; while(p!=NULL) { printf("%d ",p->x); p=p->next; } } char dequeue(Q **head) { Q *temp; int item; if (*head!=NULL){ temp = *head; item=temp->x; *head = temp->next; free(temp); return item; } return '\0'; } bool isEmpty2(Q *list) { if(list==NULL) return true; else return false; }
// MIT License // // Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved. // Distributed under the terms of the MIT License. // #include <iostream> #include <vector> #include "../libs/curl4cpp/curl4.hpp" int main(int argc, char** argv) noexcept { if(argc < 2) { std::cout << "Tuc - TinyUrl CLI\n" << argv[0] << " {link} ...\n"; return 1; } std::vector<std::string> args(argv, argv + argc); args.erase(args.begin()); curl4::CURL4 init = curl4::easy::init(); for(auto& arg : args) { { std::string val; init.setopt(CURLOPT_URL, "https://tinyurl.com/api-create.php?url=" + arg); init.setopt(CURLOPT_WRITEFUNCTION, curl4::easy::writefunc); init.setopt(CURLOPT_WRITEDATA, &val); CURLcode res = curl4::easy::perform(init); std::cout << arg + " -> " + val << '\n'; } } }
#pragma once // Unit 2 WinPCap.pdf // http://tlc.cuc.edu.cn/Course/Course/showAction/id/30 ¿Î³Ì×ÊÁÏ // P21-26 class PacketCapture { pcap_if_t* alldevs; pcap_if_t* d; pcap_t* adhandle; int no = 0; char errbuf[PCAP_ERRBUF_SIZE]; public: ~PacketCapture(); int retrieveDeviceList(); int selectAdapter(); int getOrder(); void getLocalMac(unsigned char* sha); unsigned long getLocalIp(); int setFilter(const char* packet_filter); void sendPacket(const unsigned char* packet); unsigned long WINAPI receivePacket(LPVOID lpParam); float timeSub(const timeval& a, const timeval& b); };
#ifndef SHOOTOUT_H #define SHOOTOUT_H #include <iostream> using namespace std; class Agent; class Item { protected: const int id; static int ID; public: Item(); virtual ~Item(); int getID() const; }; //armors class Armor:public Item { protected: int weigth; int protection; public: Armor(); Armor(int weigth, int protection); ~Armor(); int getWeight() const; int getProtection() const; virtual void takeHit(Agent* owner,int hit); // armura agentului owner este lovita cu hit hitpoints }; class HealingShield : public Armor { int healRate; // dupa fiecare lovitura, armura se vindeca cu healRate HP int maxProt; // protectia pe care o primeste de la inceput public: HealingShield(int _weigth,int _protection ,int heal); HealingShield(int _weigth,int _protection); HealingShield(); ~HealingShield(); void heal(); // vindecarea armurii cu healRate HP void takeHit(Agent* owner, int hit); // armura agentului owner este lovita cu hit hitpoints }; class ForceShield : public Armor { int numOfStops; // numarul de ture in care poate opri oricefel de lovitura public: ForceShield(int _weigth,int _protection,int stops); ForceShield(int _weigth,int _protection); ForceShield(); ~ForceShield(); void takeHit(Agent* owner, int hit); // armura agentului owner este lovita cu hit hitpoints }; class Kevlar : public Armor { double dmgReduction; // procentul care scade din puterea proiectilului pe care il incaseaza armura la o lovitura public: Kevlar(int _weigth,int _protection,int dmgRed); Kevlar(int _weigth,int _protection); Kevlar(); ~Kevlar(); void takeHit(Agent* owner, int hit); // armura agentului owner este lovita cu hit hitpoints }; //weapons class Weapon:public Item { protected: int dmg; // puterea armei public: Weapon(int damage); Weapon(); ~Weapon(); int getDmg(); virtual int shootDead(Agent* owner, Agent* that ) = 0; // Owner loveste that si intoarce 1 daca il omoara, 0 daca nu void getAffectedByArmor(Armor* armor); // reduce puterea armei in functie de armura }; class Revolver : public Weapon { int magazine; // numarul de ture care poate lovi consecutiv fara sa reincarce arma public: Revolver(int damage); Revolver(); ~Revolver(); int shootDead(Agent* owner , Agent* that); // Owner loveste that si intoarce 1 daca il omoara, 0 daca nu }; class Shotgun : public Weapon { int barrels; // nuamrul de lovituri pe care le efectueaza intr o tura public: Shotgun(int damage); Shotgun(); ~Shotgun(); int shootDead(Agent* owner, Agent* that); // Owner loveste that si intoarce 1 daca il omoara, 0 daca nu }; class Bow : public Weapon { double dmgMultiplier; // procentul cu care se mareste puterea armei la fiecare lovitura public: Bow(int damage); Bow(); ~Bow(); int shootDead(Agent* owner, Agent* that); // Owner loveste that si intoarce 1 daca il omoara, 0 daca nu }; //agents class Agent { protected: int x, y, moveOpt, hp, maxx, maxy, reach;// reach = aria de vizibilitate, x,y = coordonateele in matrice, unde maxx si maxy capacitatea matricei, moveOpt dicteaza miscarea in matrice Armor* armura; Weapon* arma; public: Agent(Armor* armor, Weapon* weapon, int _reach); // un agnet este initializat cu armura, arma si arie de vizibilitate Agent(int _reach); Agent(); virtual ~Agent(); virtual void moveInPattern() = 0; // deplasarea in matrice void setCoordinates(int _x, int _y, int _maxx,int _maxy); void setCoordinates(int _x, int _y); int getCoordinatesX() const; int getCoordinatesY() const; int shootWithWeaponDead(Agent* that); // loveste agentul that si intoarce 1 daca reuseste sa-l ucida void takeHitInArmor(int hit); // directionarea loviturii din metoda de mai sus void takeHitInHp(int hit); // -----------------||-------------------------- bool haveArmor() const; // verifica daca agentul are armura void getShot(int hit); // agentul primeste lovitura de hit hitpoints int getHp() const; int getWeaponDmg() const; int getArmorProtection() const; int getReach() const; }; class Krul :public Agent { public: Krul(Armor* armor, Weapon* weapon, int _reach); // Krul este intializat ca un agnet cu armura, arma si arie de vizibilitate Krul(int _reach); ~Krul(); void moveInPattern(); // deplasarea in matrice specifica lui Krul }; class Annesix :public Agent { int stepsTaken; public: Annesix(Armor* armor, Weapon* weapon , int _reach); // Annesix este intializat ca un agnet cu armura, arma si arie de vizibilitate Annesix(int _reach); ~Annesix(); void moveInPattern(); // deplasarea in matrice specifica lui Annesix }; class Board { const int n, m; // capacitatea matricei int** matrix; // matrice alocata dinamic const int numOfAgents; // numarul maxim de agenti int activeAgents; // numarul de agenti inregistrati initial in joc int agentsLeft; // numarul de agenti ramasi la un moment dat (utilizat pentru conditia de finalizare a jocului) typedef Agent* AgentPtr; //alias AgentPtr* agenti; // dupa initializarea din constructor, devine pointer la lista de pointeri AKA agent[i] e pointer la agentul i public: Board(int n, int m, int numA); ~Board(); void insertAgent(Agent* a, int _x, int _y ); // inserarea unui agent a in matrice pe pozitia x y void showBoard() const; bool nextRound(); // returneaza true daca a ramas un singur agent in viata, false daca nu int getAgentsLeft() const; void simulateAllGame(); // simulare a jocului pana la terminarea acestuia void simulateByRounds(); // simulare a jocului pe runde cu decizia de a continua, continua si arata tabla si oprire }; #endif
#include "Component.hpp" #include "Entity.hpp" Component::Component(Entity* parent) : p(parent), active(true) {} bool Component::isActive() const { return false; } void Component::setActive(bool active) { active = active; }
#include <algorithm> #include <array> #include <concepts> #include <optional> #include <string_view> #include <typeinfo> template <size_t max_length> class String { public: std::array<char, max_length> symbols; size_t len; constexpr String(const char* string, size_t length) : symbols(), len(length) { std::copy(string, string + length, symbols.begin()); } constexpr operator std::string_view() const { return std::string_view(symbols.data(), len); }; }; constexpr String<256> operator ""_cstr(const char* string, size_t length) { return String<256>(string, length); } template <class From, auto target> struct Mapping { template <class Base> static auto getTarget(const Base& object) requires std::derived_from<From, Base> { dynamic_cast<const From&>(object); return target; } }; template<class T, class U> inline std::optional<T> operator |(const std::optional<T>& lhs, const std::optional<U>& rhs) { if (lhs.has_value()) { return lhs; } return rhs; } template <class Base, class Target, class... Mappings> struct ClassMapper { private: template <class Mapping> static std::optional<Target> getTarget(const Base& object) { try { return {Mapping::getTarget(object)}; } catch(const std::bad_cast& e) { return std::optional<Target>{}; } } public: static std::optional<Target> map(const Base& object) { std::optional<Target> t = (getTarget<Mappings>(object) | ... | std::optional<Target>{}); return t.has_value() ? t : std::nullopt; } };
#include "Utilities.h" #include <hgevector.h> #include <stdlib.h> #include <math.h> void Trace( Pos* pos,const Pos& dst,float spd) { if(!((*pos)==dst)) { hgeVector v( dst.x - pos->x , dst.y - pos->y); v.Normalize(); if(!(abs(dst.x-pos->x) < spd && abs(dst.y-pos->y) < spd)) { pos->x += v.x*spd; pos->y += v.y*spd; } else { //Trace(pos, dst, spd/2.0f); *pos = dst; } } } void Rotate(Pos* inPos, Pos* outPos, float angle) { float a = cos(angle); float b = -sin(angle); float c = sin(angle); outPos->x = inPos->x*a+inPos->y*c; outPos->y = inPos->x*b+inPos->y*a; } bool CollidePiontInRound(float roundx, float roundy, float r, float x, float y) { if (abs(roundx - x) * abs(roundx - x) + abs(roundy - y) * abs(roundy - y) > abs(r) * abs(r)) return false; else return true; } //pt1 pt2是椭圆所在矩形的两个点 //cter 椭圆中心点 //pnt 判断点 bool CollidePiontInEllipse(Pos pt1, Pos pt2, Pos cter, Pos pnt) { float fRX=(pt2.x-pt1.x)/2.f; float fRY=(pt2.y-pt1.y)/2.f; if(pow(pnt.x-cter.x,2)+pow(pnt.y-cter.y,2)*(fRX/fRY)*(fRX/fRY) <= fRX*fRX) //在椭圆内部 return true; return false; }
#pragma once #ifndef _MULTIRECTANGLE_H #define _MULTIRECTANGLE_H #include "common.h" #include "opencv2/core.hpp" /* * A class that is able to specify multiple rectangles. * When this class gets read in from a string, it assumes all the * separate rectangles are the same size and are all some fixed * step away from eachother. */ class MultiRectangle { public: MultiRectangle(); MultiRectangle(const cv::Rect& initialRectangle, double xStep, double yStep, int totalRectangles, int rowSize = 1); ~MultiRectangle(); cv::Rect GetRectangle(int yIndex, int xIndex = 0) const; private: cv::Rect initialRectangle; double xStep; double yStep; int totalRectangles; int rowSize; }; #endif
/* Copyright 2014-2016 Tyler Gilbert, Inc; All Rights Reserved * */ #ifndef UI_EVENT_HPP_ #define UI_EVENT_HPP_ namespace sys { class SignalEvent; }; namespace ui { class Button; class ListItem; /*! \brief Event Class * \details This class defines actionable events (such as * button presses) that occur within and EventLoop and are handled * by Element::handle_event(). * */ class Event { public: enum { BUTTON_FLAG = 0x80, LIST_ITEM_FLAG = 0x40 }; /*! \details The event type */ enum event_type { NONE = 0, SETUP /*! This event is called at startup after all object have been constructed */ = 1, ENTER /*! This event is called when the element becomes active */ = 2, UPDATE /*! This event is called in a loop while the element is active */ = 3, BUTTON_ACTUATED /*! This event is called when a button is actuated (pressed and released). Use button() to access button details. */ = BUTTON_FLAG | 4, BUTTON_ACTUATION = BUTTON_ACTUATED, BUTTON_HELD /*! This event is called when a button is held. Use button() to access button details. */ = BUTTON_FLAG | 5, BUTTON_HOLD = BUTTON_HELD, BUTTON_PRESSED /*! This event is called when a button is pressed. Use button() to access button details. */ = BUTTON_FLAG | 6, BUTTON_RELEASED /*! This event is called when a button is released. Use button() to access button details. */ = BUTTON_FLAG | 7, NETWORK_DATA /*! This event is called when data arrives on the network */ = 8, SIGNAL /*! This event is called when data arrives on the network */ = 9, APPLICATION /*! This event is an application specific where the data is specified by the application */ = 10, LIST_ITEM_SELECTED /*! Select an item in a list */ = LIST_ITEM_FLAG | 11, LIST_ITEM_ACTUATED /*! Actuate an item in a list */ = LIST_ITEM_FLAG | 12, LIST_ACTUATED /*! Select an item in a list or menu */ = 13, LIST_ACTUATE = 13, LIST_UP /*! Scroll up in a list or menu */ = 14, LIST_DOWN /*! Scroll down in a list or menu */ = 15, SCROLL_UP /*! Scroll up (same as LIST_UP) */ = LIST_UP, SCROLL_DOWN /*! Scroll down (same as LIST_DOWN) */ = LIST_DOWN, MENU_BACK /*! Go back in the menu */ = 16, TAB_LEFT /*! Slide to the tab on the left */ = 17, TAB_RIGHT /*! Slide to the tab on the left */ = 18, MENU_ACTUATED /*! Select the item in the menu */ = 19, MENU_ACTUATE = 19, //EVENT_TYPE_TOTAL //omit TOTAL so that the compiler doesn't complain about not handling the case }; /*! \details Button definitions */ enum button_id { NO_BUTTON /*! No Button */, UP_BUTTON /*! Up Button */, DOWN_BUTTON /*! Down Button */, LEFT_BUTTON /*! LeftButton */, RIGHT_BUTTON /*! Right Button */, SELECT_BUTTON /*! Select Button */, BACK_BUTTON /*! Back Button */, EXIT_BUTTON /*! Exit Button */, USER_BUTTON0 /*! User button 0 */, USER_BUTTON1 /*! User button 1 */, USER_BUTTON2 /*! User button 2 */, USER_BUTTON3 /*! User button 3 */, USER_BUTTON4 /*! User button 4 */, USER_BUTTON5 /*! User button 5 */, USER_BUTTON6 /*! User button 6 */, USER_BUTTON7 /*! User button 7 */, USER_BUTTON8 /*! User button 8 */, USER_BUTTON9 /*! User button 9 */, USER_BUTTON10 /*! User button 10 */, USER_BUTTON11 /*! User button 11 */, USER_BUTTON12 /*! User button 12 */, USER_BUTTON13 /*! User button 13 */, USER_BUTTON14 /*! User button 14 */, USER_BUTTON15 /*! User button 15 */, //EVENT_BUTTON_TOTAL //omit TOTAL so that the compiler doesn't complain about not handling the case }; Event(); /*! \details Construct a new event with the specified type and object */ Event(enum event_type type, void * object = 0){ m_type = type; m_objects.object = object; } Event(enum event_type type, ui::Button * button){ m_type = type; m_objects.button = button; } ui::ListItem * list_item() const { if( m_type & LIST_ITEM_FLAG ){ return m_objects.list_item; } return 0; } ui::Button * button() const { if( m_type & BUTTON_FLAG ){ return m_objects.button; } return 0; } sys::SignalEvent * signal() const { if( m_type == SIGNAL ){ return m_objects.signal; } return 0; } void * application() const { if( m_type == APPLICATION ){ return m_objects.object; } return 0; } void set_event(enum event_type t, void * object = 0){ m_type = t; m_objects.object = 0; } void set_event(enum event_type t, ui::Button * button){ if( t & BUTTON_FLAG ){ m_type = t; m_objects.button = button; } } void set_type(enum event_type v) { m_type = v; } enum event_type type() const { return m_type; } private: enum event_type m_type; union event_objects { void * object; Button * button; ListItem * list_item; sys::SignalEvent * signal; } m_objects; }; }; #endif /* UI_EVENT_HPP_ */
/* replay Software Library Copyright (c) 2010-2019 Marius Elvert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef replay_vector4_hpp #define replay_vector4_hpp #include <iosfwd> #include <replay/vector2.hpp> #include <replay/vector3.hpp> namespace replay { /** 4-dimensional vector. \ingroup Math */ template <class type> class vector4 { public: /** Element type. */ typedef type value_type; /** Get a pointer to the internal array. */ constexpr type* ptr() { return data; } /** Get a pointer to the internal array. */ constexpr const type* ptr() const { return data; } /** Index access operator. */ template <class index_type> constexpr value_type& operator[](const index_type i) { return data[i]; } /** Index access operator. */ template <class index_type> constexpr const value_type operator[](const index_type i) const { return data[i]; } /** Set all elements to a single value. Default to zero. */ constexpr vector4<type>& reset(value_type value = value_type(0)); /** Assemble a 4D vector by concatenating a 3D vector and a 4th element. */ constexpr vector4<type>& reset(vector3<type> const& xyz, value_type w); /** Assemble a 4D vector by concatenating two 2D vectors. */ constexpr vector4<type>& reset(vector2<type> const& xy, vector2<type> const& zw); /** Assemble a 4D vector by concatenating a 2D vector and 2 more values. */ constexpr vector4<type>& reset(vector2<type> const& xy, value_type z, value_type w); /** Set the elements of the vector individually. \param x The first component. \param y The second component. \param z The third component. \param w The fourth component. */ constexpr vector4<type>& reset(value_type x, value_type y, value_type z, value_type w); vector4<type>& operator+=(vector4<type> const& rhs); vector4<type>& operator-=(vector4<type> const& rhs); vector4<type>& operator*=(type value); vector4<type>& operator/=(type value); vector4<type> operator-() const; bool operator==(vector4<type> const& operand) const; bool operator!=(vector4<type> const& operand) const; /** In-place negate. Negates each component of this vector. */ vector4<type>& negate(); type sum() const; type squared() const; /** Non-initializing constructor. Leaves all elements uninitialized. */ explicit vector4(uninitialized_tag) { } /** Constructor for user-defined conversions. \see convertible_tag */ template <class source_type> vector4(const source_type& other, typename convertible_tag<source_type, vector4>::type empty = 0) { *this = convert(other); } /** Single-value constructor. Sets all elements to the given value. Defaults to zero. */ constexpr explicit vector4(value_type value = value_type(0)) { reset(value); } /** Assemble a 4D vector by concatenating a 3D vector and a 4th element. */ constexpr vector4(vector3<type> const& xyz, value_type w) { reset(xyz, w); } /** Assemble a 4D vector by concatenating two 2D vectors. */ constexpr vector4(vector2<type> const& xy, vector2<type> const& zw) { reset(xy, zw); } /** Create a new vector from seperate values. \param x The first component. \param y The second component. \param z The third component. \param w The fourth component. */ constexpr vector4(value_type x, value_type y, value_type z, value_type w) { reset(x, y, z, w); } /** Assemble a 4D vector by concatenating a 2D vector and 2 more values. */ constexpr vector4(vector2<type> const& xy, value_type z, value_type w) { reset(xy, z, w); } /** Convert an array-like type to a 4D vector. The parameter needs to be indexable for at least 4 elements. */ template <class array_type> constexpr static vector4<type> cast(array_type const& src) { return vector4<type>(static_cast<type>(src[0]), static_cast<type>(src[1]), static_cast<type>(src[2]), static_cast<type>(src[3])); } private: /** The actual data. */ type data[4]; }; /** Scalar dot product of two 4D vectors. \relates vector4 \ingroup Math */ template <class type> inline type dot(vector4<type> const& lhs, vector4<type> const& rhs); /** Component wise multiplication of two 4D vectors. \relates vector4 \ingroup Math */ template <class type> inline vector4<type> comp(vector4<type> const& lhs, vector4<type> const& rhs); /** Scalar product. \relates vector4 \ingroup Math */ template <class type> vector4<type> operator*(const type lhs, vector4<type> rhs) { return rhs *= lhs; } /** Addition. \relates vector4 \ingroup Math */ template <class type> vector4<type> operator+(vector4<type> lhs, vector4<type> const& rhs) { return lhs += rhs; } /** Substraction. \relates vector4 \ingroup Math */ template <class type> vector4<type> operator-(vector4<type> lhs, vector4<type> const& rhs) { return lhs -= rhs; } /** Scalar product. \relates vector4 \ingroup Math */ template <class type> vector4<type> operator*(vector4<type> lhs, const type rhs) { return lhs *= rhs; } /** Scalar division. \relates vector4 \ingroup Math */ template <class type> vector4<type> operator/(vector4<type> lhs, const type rhs) { return lhs /= rhs; } /** A convenience typedef for a 4d floating-point vector. \relates vector4 \ingroup Math */ typedef vector4<float> vector4f; /** A convenience typedef for a 4d double-precision floating-point vector. \relates vector4 \ingroup Math */ typedef vector4<double> vector4d; /** Shorthandle for all 4d vectors \relates vector4 \ingroup Math */ template <class T> using v4 = vector4<T>; template <class T> inline v3<T> perspective_divide(v4<T> v) { return { v[0] / v[3], v[1] / v[3], v[2] / v[3] }; } } #include "vector4.inl" #endif // replay_vector4_hpp
/* Name: Copyright: Author: Xiaodong Xiao Date: 2019/10/30 20:11:06 Description: ac */ #include <bits/stdc++.h> using namespace std; int main() { string str; int kases; cin >> kases; while (kases--) { cin >> str; int cnt = 0; int ans = 0; for (int i = 0; i < str.size(); ++i) { if (str[i] == 'O') ans += ++cnt; else cnt = 0; } cout << ans << endl; } return 0; }
#include "mainwindow.h" #include "ui_mainwindow.h" int tamanoX=650; int tamanoY=500; QImage lienzo = QImage(tamanoX,tamanoY,QImage::Format_RGB32); MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { /*for (int x=0;x<tamanoX ; x++) { for (int y=0;y<tamanoY ;y++ ) { lienzo.setPixel(x,y,qRgb(255,255,255));//cambia el fondo del lienzo a color blanco (por defecto es negro) } }*/ int i; for (i=0;i<tamanoX;i++ ) { lienzo.setPixel(i,20,qRgb(255,0,0)); } QGraphicsScene *graphic = new QGraphicsScene(this); graphic->addPixmap(QPixmap::fromImage(lienzo)); ui->graphicsView->setScene(graphic); }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 1000000 int table[MAXN+10]; int main(int argc, char const *argv[]) { string str; int num; int lhs,rhs; int kase = 1; while( cin >> str ){ memset(table, 0, sizeof(table)); for(int i = 0 ; i < str.size() ; i++ ){ if( str[i] == '1' ) table[i+1]++; table[i+1] += table[i]; } printf("Case %d:\n",kase++); scanf("%d",&num); for(int i = 0 ; i < num ; i++ ){ scanf("%d %d",&lhs,&rhs); if( rhs < lhs ) swap(lhs,rhs); int tmp = table[rhs+1]-table[lhs]; if( tmp == 0 || tmp == rhs-lhs+1 ) printf("Yes\n"); else printf("No\n"); } } return 0; }
#pragma once #include "Task.hpp" namespace models { class ModelRepository { public: void registerSpecializedModel(Task model); bool getModel(const std::string &modelName, Task &model); }; }
#pragma once #include <map> #include <string> #include <ctime> #include <cstdlib> #include <iostream> #include "fstream" #include <SFML/Graphics.hpp> class Flashcards { private: Flashcards(); std::map<std::string, std::string> all_words; //contains all words std::map<std::string, std::string> correct_words; //contains correct answers std::map<std::string, std::string> wrong_words; //contains wrong answers std::map<std::string, std::string> asked_words; //contains already asked words std::string answer; //english word std::string question; //polish word public: static Flashcards & instance() { static Flashcards a; return a; } ~Flashcards(); std::string getAnswer(); std::string getQuestion(); void add(sf::String,sf::String); void show(); void saveToFile(); void loadFromFile(); void ask(); void random(); void isFull(); bool checkAsked(std::map<std::string, std::string>::iterator); void clearAll(); void clearHelpers(); void clear(); void clearFile(); };
#ifndef usersideConfiguration_h #define usersideConfiguration_h #include <Arduino.h> #include <MyWebserver.h> #include <configurationSaver.h> class Configurator{ MyWebserver myServer; ConfigurationSaver configurationSaver; public: void letConfigure(String (&adresses)[5]); void save(); void retrieve(String (&adresses)[5]) {configurationSaver.retrieve(adresses); } private: void setupConfigurableness(); bool handleConfigurableness(String (&adresses)[5]); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef CANVASWEBGLRENDERBUFFER_H #define CANVASWEBGLRENDERBUFFER_H #ifdef CANVAS3D_SUPPORT #include "modules/libvega/src/canvas/webglutils.h" class CanvasWebGLRenderbuffer; class CanvasWebGLRenderbufferPtr : public WebGLSmartPointer<CanvasWebGLRenderbuffer> { public: CanvasWebGLRenderbufferPtr(CanvasWebGLRenderbuffer *p = NULL) : WebGLSmartPointer<CanvasWebGLRenderbuffer>(p) { m_initId = 0; } CanvasWebGLRenderbufferPtr(const CanvasWebGLRenderbufferPtr &s) : WebGLSmartPointer<CanvasWebGLRenderbuffer>(s) { m_initId = 0; } void operator =(const CanvasWebGLRenderbufferPtr &s) { m_initId = 0; WebGLSmartPointer<CanvasWebGLRenderbuffer>::operator=(s); } void operator =(CanvasWebGLRenderbuffer *p) { m_initId = 0; WebGLSmartPointer<CanvasWebGLRenderbuffer>::operator=(p); } bool hasBeenInvalidated() const; void validate(); private: unsigned int m_initId; }; class CanvasWebGLRenderbuffer : public WebGLRefCounted { public: CanvasWebGLRenderbuffer(); ~CanvasWebGLRenderbuffer(); OP_STATUS create(VEGA3dRenderbufferObject::ColorFormat fmt, unsigned int width, unsigned int height); void destroyInternal(); VEGA3dRenderbufferObject* getBuffer(){return m_renderbuffer;} bool hasBeenBound() const { return m_hasBeenBound; } bool isInitialized() const { return m_initialized; } void setInitialized() { m_initialized = TRUE; } void setIsBound() { m_hasBeenBound = true; } bool isZeroSized() const { return m_zeroSizedBuffer; } unsigned int getInitId() const { return m_initId; } private: VEGA3dRenderbufferObject* m_renderbuffer; bool m_initialized; bool m_hasBeenBound; bool m_zeroSizedBuffer; unsigned int m_initId; // Incremented every time the renderbuffer is reinitialized. }; #endif //CANVAS3D_SUPPORT #endif //CANVASWEBGLRENDERBUFFER_H
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "CSWeapon.generated.h" class ACSCharacter; class USkeletalMeshComponent; class UDamageType; class UParticleSystem; UENUM(BlueprintType) enum class EWeaponState : uint8 { Idle, Firing, Reloading }; USTRUCT() struct FHitScanTrace { GENERATED_BODY() public: UPROPERTY() FHitResult Hit; UPROPERTY() FVector_NetQuantize TraceEnd; UPROPERTY() bool bDidHit; UPROPERTY() TEnumAsByte<EPhysicalSurface> SurfaceType; UPROPERTY() uint8 ReplicationCount; }; USTRUCT(BlueprintType) struct FWeaponData { GENERATED_USTRUCT_BODY() /** Infinite ammo for reloads */ UPROPERTY(EditDefaultsOnly, Category = "Ammo") bool bInfiniteAmmo; /** Infinite ammo in clip, no reload required */ UPROPERTY(EditDefaultsOnly, Category = "Ammo") bool bInfiniteClip; /** Max ammo */ UPROPERTY(EditDefaultsOnly, Category = "Ammo") int32 MaxAmmo; /** Clip size */ UPROPERTY(EditDefaultsOnly, Category = "Ammo") int32 AmmoPerClip; /** Initial clips */ UPROPERTY(EditDefaultsOnly, Category = "Ammo") int32 InitialClips; /** Failsafe reload duration if weapon doesn't have any animation for it */ UPROPERTY(EditDefaultsOnly, Category = "WeaponStats") float NoAnimReloadDuration; /** Weapon range */ UPROPERTY(EditDefaultsOnly, Category = "WeaponStats") float WeaponRange; UPROPERTY(EditDefaultsOnly, Category = "Weapon") float RateOfFire; /** Defaults */ FWeaponData() { bInfiniteAmmo = false; bInfiniteClip = false; MaxAmmo = 100; AmmoPerClip = 20; InitialClips = 5; RateOfFire = 700.0f; WeaponRange = 10000.0f; } }; USTRUCT() struct FWeaponAnim { GENERATED_USTRUCT_BODY() /** Animation played on pawn (3rd person view) */ UPROPERTY(EditDefaultsOnly, Category = "Animation") UAnimMontage* Pawn; UPROPERTY(EditDefaultsOnly, Category = "Animation") bool bHasWeaponAnims = false; /** Animation played on the weapon (3rd person view)*/ UPROPERTY(EditDefaultsOnly, Category = "Animation", meta = (EditCondition = "bHasWeaponAnims")) UAnimSequence* Weapon; }; UCLASS() class UE4COOP_API ACSWeapon : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ACSWeapon(); protected: /** Begin AActor Interface */ virtual void BeginPlay() override; virtual void PostInitializeComponents() override; /** End AActor Interface */ public: ////////////////////////////////////////////////////////////////////////// // Input /** [local + server] Start fire called by pawn */ void StartFire(); /** [local + server] Stop fire called by pawn */ void StopFire(); /** [all] Start reload called by the pawn */ UFUNCTION(BlueprintCallable, Category = "Weapon") void StartReload(bool bFromReplication = false); /** [local + server] Interrupt weapon reload */ virtual void StopReload(); protected: ////////////////////////////////////////////////////////////////////////// // Input - server side UFUNCTION(Reliable, server, WithValidation) void ServerStartFire(); UFUNCTION(Reliable, server, WithValidation) void ServerStopFire(); UFUNCTION(Reliable, server, WithValidation) void ServerStartReload(); UFUNCTION(Reliable, server, WithValidation) void ServerStopReload(); protected: ////////////////////////////////////////////////////////////////////////// // Reload && Ammo System /** [server] Performs actual reload */ virtual void ReloadWeapon(); /** Consume a bullet */ void UseAmmo(); protected: ////////////////////////////////////////////////////////////////////////// // Animation /** Play weapon animations on the character*/ float PlayAnimation(const FWeaponAnim& Animation, float PlayRate = 1.0f); /** Cancel playing weapon animations on the character */ void StopAnimation(const FWeaponAnim& Animation); /** Play weapon animations on the weapon */ float PlayWeaponAnimation(const FWeaponAnim& Animation, float PlayRate = 1.0f); /** Cancel weapon animations on the weapon */ void StopWeaponAnimation(const FWeaponAnim& Animation); public: ////////////////////////////////////////////////////////////////////////// // Control /** Check if weapon can fire */ bool CanFire() const; /** Check if weapon can be reloaded */ bool CanReload() const; ////////////////////////////////////////////////////////////////////////// // Reading data /** Check if weapon has infinite ammo*/ bool HasInfiniteAmmo() const; /** Check if weapon has infinite clip */ bool HasInfiniteClip() const; /** Check if weapon is reloading*/ UFUNCTION(BlueprintCallable, Category = "Weapon") bool IsReloading() const; /** Get reload animation length*/ UFUNCTION(BlueprintPure, Category = "Weapon") float GetReloadAnimationLength() const; /** Current Weapon Range */ UFUNCTION(BlueprintCallable, Category = "WeaponStats") float GetWeaponRange() const; /** Get total ammo */ UFUNCTION(BlueprintPure, Category = "WeaponStats") float GetCurrentAmmo() const; /** Get current ammo in clip */ UFUNCTION(BlueprintPure, Category = "WeaponStats") float GetCurrentAmmoInClip() const; /** Get Ammo in magazine */ UFUNCTION(BlueprintPure, Category = "WeaponStats") float GetCurrentAmmoInMagazine() const; /** Get max ammo */ UFUNCTION(BlueprintPure, Category = "WeaponStats") float GetMaxAmmo() const; /** Get current weapon state */ EWeaponState GetCurrentState() const; public: ////////////////////////////////////////////////////////////////////////// // Weapon Usage /** [server] Owner pawn is equipping weapon */ virtual void OnEquip(ACSCharacter* Character); protected: /** [local + server] Firing started */ virtual void OnFireStarted(); /** [local + server] Firing finished */ virtual void OnFireFinished(); /** [server] Fire & update ammo */ UFUNCTION(Reliable, server, WithValidation) void ServerHandleFiring(); /** [local + server] Handle weapon fire */ void HandleFiring(); /** [server + local] Fire the weapon, do damage and play fire FX */ virtual void Fire(); UFUNCTION(Server, Reliable, WithValidation) void ServerFire(); /** Update weapon state */ void SetWeaponState(EWeaponState NewState); /** Determine current weapon state */ void DetermineWeaponState(); /** [local] Player fire FX */ virtual void PlayFireEffects(FHitResult Hit, FVector TraceEnd, bool bDidHit, EPhysicalSurface SurfaceType); protected: ////////////////////////////////////////////////////////////////////////// // Replication /** Play Fire FX on remote clients */ UFUNCTION() void OnRep_HitScanTrace(); /** Start reload on remote clients too */ UFUNCTION() void OnRep_Reload(); protected: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") USkeletalMeshComponent* MeshComp; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") TSubclassOf<UDamageType> DamageType; UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Weapon") FName MuzzleSocketName; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* MuzzleEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* DefaultImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* FleshImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* TracerEffect; ////////////////////////////////////////////////////////////////////////// // Fire System UPROPERTY(EditDefaultsOnly, Category = "Weapon") TSubclassOf<class UCameraShake> FireCamShake; UPROPERTY(EditDefaultsOnly, Category = "Weapon") float BaseDamage; UPROPERTY(EditDefaultsOnly, Category = "Weapon") float VulnerableDamage; /* Bullet Spread In Degrees */ UPROPERTY(EditDefaultsOnly, Category = "Weapon", meta = (ClampMin = 0.0f)) float ShootConeAngle; float TimeBetweenShots; float LastFireTime; /** Handle for efficient management of HandleFiring timer */ FTimerHandle TimerHandle_HandleFiring; UPROPERTY(ReplicatedUsing=OnRep_HitScanTrace) FHitScanTrace HitScanTrace; /** Is weapon fire active? */ bool bWantsToFire; /** Current weapon state */ EWeaponState CurrentState; ////////////////////////////////////////////////////////////////////////// // Reload && Ammo System /** Reload animations */ UPROPERTY(EditDefaultsOnly, Category = "Weapon|Animation") FWeaponAnim ReloadAnim; /** Is reload animation playing? */ UPROPERTY(Transient, ReplicatedUsing = OnRep_Reload) bool bPendingReload; /** Is weapon currently reloading?*/ UPROPERTY(Transient, Replicated) bool bReloading; /** Current ammo inside magazine*/ UPROPERTY(Transient, Replicated) int32 CurrentAmmoInMagazine; /** Current total ammo */ UPROPERTY(Transient, Replicated) int32 CurrentAmmo; /** Current ammo - inside clip */ UPROPERTY(Transient, Replicated) int32 CurrentAmmoInClip; /** Handle for efficient management of StopReload timer */ FTimerHandle TimerHandle_StopReload; /** Handle for efficient management of ReloadWeapon timer */ FTimerHandle TimerHandle_ReloadWeapon; protected: /** Weapon data */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") FWeaponData WeaponConfig; /** Pawn owning this weapon */ UPROPERTY(Transient, Replicated) ACSCharacter* MyPawn; };
// // AABB.h // Odin.MacOSX // // Created by Daniel on 10/10/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef Odin_MacOSX_AABB_h #define Odin_MacOSX_AABB_h #include "Vector3.h" namespace odin { namespace math { namespace shape { class AABB { public: AABB(const vec3& minPoint, const vec3& maxPoint) : m_minPoint(minPoint), m_maxPoint(maxPoint) {} vec3 m_minPoint; vec3 m_maxPoint; }; } } } #endif
/******************************************************************************** ** Form generated from reading UI file 'dvrnvrplaybackdialog.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DVRNVRPLAYBACKDIALOG_H #define UI_DVRNVRPLAYBACKDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCalendarWidget> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QTimeEdit> QT_BEGIN_NAMESPACE class Ui_DVRNVRPlaybackDialog { public: QGridLayout *gridLayout; QSpacerItem *verticalSpacer; QLabel *d_label4; QLabel *label_6; QTimeEdit *timeedit; QLabel *label; QPushButton *setinittime; QPushButton *selectdir; QComboBox *selectChannel; QLabel *download_progress; QLabel *endtime; QLabel *label_4; QLabel *inittime; QLineEdit *dir; QLabel *label_8; QLabel *label_3; QLabel *label_5; QPushButton *download_button; QLineEdit *name; QLabel *label_7; QCalendarWidget *dateedit; QPushButton *closebutton; QLabel *timeError; QPushButton *setendtime; QLabel *d_label1; QLabel *label_2; QPushButton *play_button; void setupUi(QDialog *DVRNVRPlaybackDialog) { if (DVRNVRPlaybackDialog->objectName().isEmpty()) DVRNVRPlaybackDialog->setObjectName(QStringLiteral("DVRNVRPlaybackDialog")); DVRNVRPlaybackDialog->resize(456, 534); QFont font; font.setFamily(QStringLiteral("Ubuntu")); font.setPointSize(8); DVRNVRPlaybackDialog->setFont(font); DVRNVRPlaybackDialog->setAutoFillBackground(false); DVRNVRPlaybackDialog->setStyleSheet(QStringLiteral("")); gridLayout = new QGridLayout(DVRNVRPlaybackDialog); gridLayout->setObjectName(QStringLiteral("gridLayout")); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer, 17, 2, 1, 1); d_label4 = new QLabel(DVRNVRPlaybackDialog); d_label4->setObjectName(QStringLiteral("d_label4")); d_label4->setMaximumSize(QSize(80, 16777215)); gridLayout->addWidget(d_label4, 13, 0, 1, 1); label_6 = new QLabel(DVRNVRPlaybackDialog); label_6->setObjectName(QStringLiteral("label_6")); gridLayout->addWidget(label_6, 8, 0, 1, 1); timeedit = new QTimeEdit(DVRNVRPlaybackDialog); timeedit->setObjectName(QStringLiteral("timeedit")); timeedit->setCalendarPopup(false); gridLayout->addWidget(timeedit, 5, 1, 1, 1); label = new QLabel(DVRNVRPlaybackDialog); label->setObjectName(QStringLiteral("label")); gridLayout->addWidget(label, 7, 0, 1, 1); setinittime = new QPushButton(DVRNVRPlaybackDialog); setinittime->setObjectName(QStringLiteral("setinittime")); setinittime->setMaximumSize(QSize(100, 16777215)); QFont font1; font1.setUnderline(false); setinittime->setFont(font1); gridLayout->addWidget(setinittime, 7, 2, 1, 1); selectdir = new QPushButton(DVRNVRPlaybackDialog); selectdir->setObjectName(QStringLiteral("selectdir")); selectdir->setFlat(true); gridLayout->addWidget(selectdir, 11, 2, 1, 1); selectChannel = new QComboBox(DVRNVRPlaybackDialog); selectChannel->setObjectName(QStringLiteral("selectChannel")); gridLayout->addWidget(selectChannel, 0, 1, 1, 1); download_progress = new QLabel(DVRNVRPlaybackDialog); download_progress->setObjectName(QStringLiteral("download_progress")); gridLayout->addWidget(download_progress, 13, 1, 1, 1); endtime = new QLabel(DVRNVRPlaybackDialog); endtime->setObjectName(QStringLiteral("endtime")); gridLayout->addWidget(endtime, 8, 1, 1, 1); label_4 = new QLabel(DVRNVRPlaybackDialog); label_4->setObjectName(QStringLiteral("label_4")); gridLayout->addWidget(label_4, 12, 0, 1, 1); inittime = new QLabel(DVRNVRPlaybackDialog); inittime->setObjectName(QStringLiteral("inittime")); gridLayout->addWidget(inittime, 7, 1, 1, 1); dir = new QLineEdit(DVRNVRPlaybackDialog); dir->setObjectName(QStringLiteral("dir")); dir->setReadOnly(true); gridLayout->addWidget(dir, 11, 1, 1, 1); label_8 = new QLabel(DVRNVRPlaybackDialog); label_8->setObjectName(QStringLiteral("label_8")); gridLayout->addWidget(label_8, 5, 0, 1, 1); label_3 = new QLabel(DVRNVRPlaybackDialog); label_3->setObjectName(QStringLiteral("label_3")); gridLayout->addWidget(label_3, 11, 0, 1, 1); label_5 = new QLabel(DVRNVRPlaybackDialog); label_5->setObjectName(QStringLiteral("label_5")); QFont font2; font2.setPointSize(8); font2.setBold(true); font2.setWeight(75); label_5->setFont(font2); gridLayout->addWidget(label_5, 1, 0, 1, 2); download_button = new QPushButton(DVRNVRPlaybackDialog); download_button->setObjectName(QStringLiteral("download_button")); download_button->setMinimumSize(QSize(22, 22)); download_button->setMaximumSize(QSize(524645, 546456)); QFont font3; font3.setFamily(QStringLiteral("Nimbus Sans L")); font3.setBold(false); font3.setUnderline(true); font3.setWeight(50); download_button->setFont(font3); download_button->setFlat(true); gridLayout->addWidget(download_button, 14, 1, 1, 1); name = new QLineEdit(DVRNVRPlaybackDialog); name->setObjectName(QStringLiteral("name")); gridLayout->addWidget(name, 12, 1, 1, 1); label_7 = new QLabel(DVRNVRPlaybackDialog); label_7->setObjectName(QStringLiteral("label_7")); gridLayout->addWidget(label_7, 2, 0, 1, 2); dateedit = new QCalendarWidget(DVRNVRPlaybackDialog); dateedit->setObjectName(QStringLiteral("dateedit")); QFont font4; font4.setPointSize(7); dateedit->setFont(font4); dateedit->setStyleSheet(QLatin1String("\n" "/* header row */\n" "QCalendarWidget QWidget { alternate-background-color: rgb(128, 128, 128); }\n" "")); dateedit->setGridVisible(false); dateedit->setNavigationBarVisible(true); dateedit->setDateEditEnabled(true); gridLayout->addWidget(dateedit, 3, 1, 2, 2); closebutton = new QPushButton(DVRNVRPlaybackDialog); closebutton->setObjectName(QStringLiteral("closebutton")); gridLayout->addWidget(closebutton, 18, 2, 1, 1); timeError = new QLabel(DVRNVRPlaybackDialog); timeError->setObjectName(QStringLiteral("timeError")); QFont font5; font5.setPointSize(6); timeError->setFont(font5); gridLayout->addWidget(timeError, 9, 0, 1, 2); setendtime = new QPushButton(DVRNVRPlaybackDialog); setendtime->setObjectName(QStringLiteral("setendtime")); setendtime->setMaximumSize(QSize(100, 16777215)); gridLayout->addWidget(setendtime, 8, 2, 1, 1); d_label1 = new QLabel(DVRNVRPlaybackDialog); d_label1->setObjectName(QStringLiteral("d_label1")); QFont font6; font6.setBold(true); font6.setWeight(75); d_label1->setFont(font6); gridLayout->addWidget(d_label1, 10, 0, 1, 1); label_2 = new QLabel(DVRNVRPlaybackDialog); label_2->setObjectName(QStringLiteral("label_2")); label_2->setFont(font6); gridLayout->addWidget(label_2, 0, 0, 1, 1); play_button = new QPushButton(DVRNVRPlaybackDialog); play_button->setObjectName(QStringLiteral("play_button")); QFont font7; font7.setUnderline(true); play_button->setFont(font7); play_button->setMouseTracking(false); play_button->setFlat(true); gridLayout->addWidget(play_button, 14, 2, 1, 1); retranslateUi(DVRNVRPlaybackDialog); QMetaObject::connectSlotsByName(DVRNVRPlaybackDialog); } // setupUi void retranslateUi(QDialog *DVRNVRPlaybackDialog) { DVRNVRPlaybackDialog->setWindowTitle(QApplication::translate("DVRNVRPlaybackDialog", "DVR/NVR Playback", Q_NULLPTR)); d_label4->setText(QApplication::translate("DVRNVRPlaybackDialog", "Progreso:", Q_NULLPTR)); label_6->setText(QApplication::translate("DVRNVRPlaybackDialog", "Hasta:", Q_NULLPTR)); timeedit->setDisplayFormat(QApplication::translate("DVRNVRPlaybackDialog", "HH:mm", Q_NULLPTR)); label->setText(QApplication::translate("DVRNVRPlaybackDialog", "Desde:", Q_NULLPTR)); setinittime->setText(QApplication::translate("DVRNVRPlaybackDialog", "Fijar inicio", Q_NULLPTR)); selectdir->setText(QApplication::translate("DVRNVRPlaybackDialog", "...", Q_NULLPTR)); download_progress->setText(QString()); endtime->setText(QString()); label_4->setText(QApplication::translate("DVRNVRPlaybackDialog", "Nombre", Q_NULLPTR)); inittime->setText(QString()); dir->setText(QString()); label_8->setText(QApplication::translate("DVRNVRPlaybackDialog", "Hora", Q_NULLPTR)); label_3->setText(QApplication::translate("DVRNVRPlaybackDialog", "Directorio", Q_NULLPTR)); label_5->setText(QApplication::translate("DVRNVRPlaybackDialog", "Seleccionar Fecha/Hora", Q_NULLPTR)); download_button->setText(QApplication::translate("DVRNVRPlaybackDialog", "Descargar", Q_NULLPTR)); label_7->setText(QApplication::translate("DVRNVRPlaybackDialog", "Fecha", Q_NULLPTR)); closebutton->setText(QApplication::translate("DVRNVRPlaybackDialog", "Cerrar", Q_NULLPTR)); timeError->setText(QString()); setendtime->setText(QApplication::translate("DVRNVRPlaybackDialog", "Fijar final", Q_NULLPTR)); d_label1->setText(QApplication::translate("DVRNVRPlaybackDialog", "Descargar", Q_NULLPTR)); label_2->setText(QApplication::translate("DVRNVRPlaybackDialog", "Canal", Q_NULLPTR)); play_button->setText(QApplication::translate("DVRNVRPlaybackDialog", "Reproducir", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class DVRNVRPlaybackDialog: public Ui_DVRNVRPlaybackDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DVRNVRPLAYBACKDIALOG_H
//////////////////////////////////////////////////////////////////////////////// #include "convex_hull.h" #include <cellogram/delaunay.h> #include <cellogram/navigation.h> #include <igl/edges.h> #include <igl/boundary_loop.h> #include <igl/triangle/cdt.h> #include <igl/triangle/triangulate.h> #include <geogram/basic/geometry.h> #include <algorithm> #include <numeric> #include <stack> #undef IGL_STATIC_LIBRARY #include <igl/edge_lengths.h> //////////////////////////////////////////////////////////////////////////////// namespace cellogram { // ----------------------------------------------------------------------------- namespace { struct Compare { const std::vector<GEO::vec2> &points; int leftmost; // Leftmost point of the poly Compare(const std::vector<GEO::vec2> &points_) : points(points_) { } bool operator ()(int i1, int i2) { if (i2 == leftmost) { return false; } if (i1 == leftmost) { return true; } GEO::vec2 u = points[i1] - points[leftmost]; GEO::vec2 v = points[i2] - points[leftmost]; double d = det(u, v); return (d < 0 || (d == 0 && u.length2() < v.length2())); } }; bool inline salientAngle(const GEO::vec2 &a, const GEO::vec2 &b, const GEO::vec2 &c) { return (det(b - a, c - a) >= 0); } } // anonymous namespace //////////////////////////////////////////////////////////////////////////////// std::vector<int> convex_hull(const std::vector<GEO::vec2> &points) { Compare order(points); order.leftmost = 0; for(int i = 1; i < (int) points.size(); ++i) { if (points[i][0] < points[order.leftmost][0]) { order.leftmost = i; } else if (points[i][0] == points[order.leftmost][0] && points[i][1] < points[order.leftmost][1]) { order.leftmost = i; } } std::vector<int> index(points.size()); std::iota(index.begin(), index.end(), 0); std::sort(index.begin(), index.end(), order); std::vector<int> hull; for (int i : index) { hull.push_back(i); while (hull.size() > 3u && salientAngle(points[hull.end()[-3]], points[hull.end()[-2]], points[hull.end()[-1]])) { hull.end()[-2] = hull.back(); hull.pop_back(); // Pop inner vertices } } return hull; } //////////////////////////////////////////////////////////////////////////////// void triangulate_hull(std::vector<GEO::vec2> &hull, GEO::Mesh &M) { auto n = (GEO::index_t) hull.size(); M.clear(); M.vertices.create_vertices((int) hull.size()); for (GEO::index_t i = 0; i < n; ++i) { M.vertices.point(i) = GEO::vec3(hull[i][0], hull[i][1], 0); } M.facets.create_triangles(n - 2); for (GEO::index_t i = 1; i + 1 < n; ++i) { M.facets.set_vertex(i-1, 0, 0); M.facets.set_vertex(i-1, 1, i); M.facets.set_vertex(i-1, 2, i+1); } } //////////////////////////////////////////////////////////////////////////////// void convex_hull(const Eigen::MatrixXd &V, Eigen::VectorXi &P) { std::vector<GEO::vec2> pts(V.rows()); for (int i = 0; i < V.rows(); ++i) { pts[i] = GEO::vec2(V(i, 0), V(i, 1)); } auto hull = convex_hull(pts); P.resize(hull.size()); for (int i = 0; i < P.size(); ++i) { P(i) = hull[i]; } P.reverseInPlace(); } //////////////////////////////////////////////////////////////////////////////// void triangulate_convex_polygon(const Eigen::MatrixXd &P, Eigen::MatrixXd &V, Eigen::MatrixXi &F) { int n = (int) P.rows(); V = P; F.resize(n - 2, 3); for (int i = 1; i + 1 < n; ++i) { F.row(i-1) << 0, i, i+1; } } //////////////////////////////////////////////////////////////////////////////// void loose_convex_hull(const Eigen::MatrixXd &V, Eigen::VectorXi &L, double edge_length_ratio) { // Compute initial Delaunay triangulation Eigen::MatrixXi F; delaunay_triangulation(V, F); // Compute median edge length Eigen::MatrixXi E; Eigen::VectorXd lengths; igl::edges(F, E); igl::edge_lengths(V, E, lengths); int num_edges = (int) lengths.size(); std::nth_element(lengths.data(), lengths.data() + num_edges/2, lengths.data() + num_edges); double median_edge_length = lengths[num_edges/2]; // List border edges, prune incident triangle if length is higher than threshold NavigationData data(F); std::vector<bool> should_remove_face(F.rows(), false); // mark removed triangles std::vector<bool> marked_edges(num_edges, false); // mark edges in the pending queue std::stack<NavigationIndex> pending_edges; for (int f = 0; f < F.rows(); ++f) { for (int lv = 0; lv < F.cols(); ++lv) { auto index = index_from_face(F, data, f, lv); assert(index.edge < num_edges); if (switch_face(data, index).face < 0) { pending_edges.push(index); marked_edges[index.edge] = true; } } } while (!pending_edges.empty()) { NavigationIndex index = pending_edges.top(); pending_edges.pop(); double len = (V.row(index.vertex) - V.row(switch_vertex(data, index).vertex)).norm(); if (len > edge_length_ratio * median_edge_length) { // Remove facet, and visit face-adjacent edges should_remove_face[index.face] = true; NavigationIndex index2 = index; for (int lv = 0; lv < F.cols(); ++lv, index2 = next_around_face(data, index2)) { auto index3 = switch_face(data, index2); if (index3.face >= 0 && !marked_edges[index2.edge]) { pending_edges.push(index3); marked_edges[index3.edge] = true; } } } } // Extract selected faces int num_selected = 0; for (bool b : should_remove_face) { if (!b) ++num_selected; } Eigen::MatrixXi F2(num_selected, F.cols()); for (int f = 0, f2 = 0; f < F.rows(); ++f) { if (!should_remove_face[f]) { F2.row(f2) = F.row(f); ++f2; } } // Return boundary loop in the reduced triangulation igl::boundary_loop(F2, L); } //////////////////////////////////////////////////////////////////////////////// void triangulate_polygon(const Eigen::MatrixXd &P, Eigen::MatrixXd &V, Eigen::MatrixXi &F) { Eigen::MatrixXd PV = P.leftCols<2>(); Eigen::MatrixXi E, WE; Eigen::VectorXi J; E.resize(P.rows(), 2); int n = (int) P.rows(); for (int i = 0; i < n; ++i) { E.row(i) << i, (i+1)%n; } //igl::triangle::cdt(PV, E, "Q", V, F, WE, J); igl::triangle::triangulate(PV, E, Eigen::MatrixXd(0, 2), "Q", V, F); if (P.cols() == 3) { V.conservativeResize(V.rows(), 3); V.col(2).setZero(); } } //void triangulate_polygon(std::vector<int> &P, Eigen::MatrixXd &V, Eigen::MatrixXi &F) { // Eigen::MatrixXd // Eigen::MatrixXd PV = P.leftCols<2>(); // Eigen::MatrixXi E, WE; // Eigen::VectorXi J; // E.resize(P.rows(), 2); // int n = (int)P.rows(); // for (int i = 0; i < n; ++i) { // E.row(i) << i, (i + 1) % n; // } // igl::triangle::cdt(PV, E, "V", V, F, WE, J); // if (P.cols() == 3) { // V.conservativeResize(V.rows(), 3); // } //} // ----------------------------------------------------------------------------- } // namespace cellogram
#include <iostream> class Car { private: int _speed, _direction; public: Car(); Car(int speed, int direction); ~Car(); }; Car::Car() : _speed(0), _direction(0) { std::cout << "The car has been constructed (0mph:0degrees)\n"; } Car::Car(int speed, int direction) : _speed(speed), _direction(direction) { std::cout << "The car has been constructed (" << _speed << "mph:" << _direction << "degrees)\n"; } Car::~Car() { // Empty }
// Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. // Includes #include "tmx_object.hxx" #include <random> #include "utils/archive/archive_utils.hxx" TmxObject::TmxObject(const TMXTiledMap& map, const ValueVector& info) { // Get center point of calculation const auto div = Globals::getScreenPosition(); const auto size = map.getMapSize(); for_each(info.begin(), info.end(), [&](const Value& data) -> void { const auto& values = data.asValueMap(); // Run assertions on required data CCASSERT(values.find(__NAME__) not_eq values.end(), "TmxObject: No name was found..."); CCASSERT(values.find(__LAYER__) not_eq values.end(), "TmxObject: No layer was found..."); const auto name = values.at(__NAME__).asString(); const auto layer = values.at(__LAYER__).asString(); CCASSERT(map.getLayer(layer) not_eq nullptr, string("TmxObject: TiledMap does not contain layer by this name" + layer).c_str()); // Getting a reference to the exact layer const auto& tmx_layer = map.getLayer(layer); // create maps the be files PointH points; Vec2H positions; vector<Point> collistions; // By default, inverse positions are not enable. So check to see that they are const auto use_positions = values.find(__INVERSE__) not_eq values.end() and values.at(__INVERSE__).asBool(); const auto use_collistions = values.find(__COLLISIONS__) not_eq values.end() and values.at(__COLLISIONS__).asBool(); // Loop through all of the iteration of the map to generate the correct tiles. for (auto px = 0; px < size.width; px++) for (auto py = 0; py < size.height; py++) { // The point we are currently evaluating. const auto point = Point(px, py); // Assure the tile is not null if (tmx_layer->getTileAt(point) == nullptr) { if (use_collistions) collistions.emplace_back(point); continue; } // If the value set has GIDs, Assure that the gid of the tile is part of this list if (values.find(__GIDS__) not_eq values.end()) { const auto& gids = values.at(__GIDS__).asValueMap(); const auto& gid = tmx_layer->getTileGIDAt(point); if (gids.find(to_string(gid)) == gids.end()) continue; } // Calculate location on screen and construct position object const auto vx = div.x - ((size.width - 1) / 2 - px) * 108; const auto vy = div.y + ((size.height - 1) / 2 - py) * 108; const auto position = Vec2(vx, vy); // Insert tiles into the maps points.emplace(point, position); if (use_positions) positions.emplace(position, point); } // Emplace maps. The positions is only added if necessary and defined in the values point_map_.emplace(name, points); if (not positions.empty()) positions_map_.emplace(name, positions); if (not collistions.empty()) collistions_map_.emplace(name, collistions); }); } TmxObject::~TmxObject() { point_map_.clear(); positions_map_.clear(); } Point TmxObject::getPoint(const Vec2& position, const string& layer) { const auto& info = positions_map_.at(layer); const auto& itr = info.find(position); if (itr == info.end()) return Point(-1, -1); return itr->second; } Vec2 TmxObject::getPosition(const Point& point, const string& layer) { const auto& info = point_map_.at(layer); const auto& itr = info.find(point); if (itr == info.end()) return Vec2(-1, -1); return itr->second; } bool TmxObject::containsPoint(const Point& point, const string& layer) { const auto& info = point_map_.at(layer); return info.find(point) not_eq info.end(); } bool TmxObject::containsPosition(const Vec2& position, const string& layer) { const auto& info = positions_map_.at(layer); return info.find(position) not_eq info.end(); } PointH::const_iterator TmxObject::getPointPair(const Point& point, const string& layer) { const auto& info = point_map_.at(layer); return find_if(info.begin(), info.end(), [point](const pair<Point, Vec2> pair) { return point == pair.first; }); } Vec2H::const_iterator TmxObject::getPositionPair(const Vec2& position, const string& layer) { const auto& info = positions_map_.at(layer); return find_if(info.begin(), info.end(), [position](const pair<Vec2, Point> pair) { return position == pair.first; }); } // ReSharper disable once CppLocalVariableMayBeConst PointH::const_iterator TmxObject::getRandomPoint(const string& layer) { const auto& info = point_map_.at(layer); auto engine = mt19937(random_device{}()); auto distrobution = uniform_int_distribution<>(0, int(info.size()) - 1); auto it = info.begin(); std::advance(it, distrobution(engine)); return it; } // ReSharper disable once CppLocalVariableMayBeConst Vec2H::const_iterator TmxObject::getRandomPosition(const string& layer) { const auto& info = positions_map_.at(layer); auto engine = mt19937(random_device{}()); auto distrobution = uniform_int_distribution<>(0, int(info.size()) - 1); auto it = info.begin(); std::advance(it, distrobution(engine)); return it; }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define MAX 100 #define MOD 1000000007 /* add vars here */ ll n,k; ll ans = 0; vector<ll> b; /* add your algorithm here */ int main() { cin >> n >> k; rep(i,n) { ll a; scanf("%lld", &a); b.push_back(a); ans += a; } cout << ans << endl; for (int i = 0; i < n - k + 1; ++i) { ll sum = 0; for (int j = 0; j < k; ++j) { sum += b[i+j]; } if (sum < 0) { cout << i << endl; ans -= sum; for (int j = 0; j < k; ++j) { b[j+i] = 0; } } cout << ans << " " << sum << endl; } cout << " " << endl; cout << ans << endl; }
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) const int INF = 1<<29; const int MOD=1073741824; #define pp pair<ll,ll> typedef long long int ll; bool isPowerOfTwo (ll x) { return x && (!(x&(x-1))); } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } const int dx[] = {1,0,-1,0,1,1,-1,-1}; const int dy[] = {0,-1,0,1,1,-1,-1,1}; //////////////////////////////////////////////////////////////////// int main() { fastio(); int t=1; // cin>>t; while(t--) { ll n,r; double avg; cin>>n>>r>>avg; vector<pp> v; ll x,y,sum=0; REP(i,n){ cin>>x>>y; v.push_back({y,x}); sum+=x; } double ch=(double)sum/n; if(ch-avg>=0)return cout<<0,0; sort(v.begin(),v.end()); ll ans=0; REP(i,n){ ll diff=r-v[i].second; if(diff==0)continue; sum+=diff; ch=(double)sum/n; sum-=diff; if(ch<=avg){ sum+=diff; ans+=diff*v[i].first; } else{ ch=(double)sum/n; x=(ll)avg*n; ans+=(x-sum)*v[i].first; goto done; } } done: ; cout<<ans; } return 0; }
#include<iostream> using namespace std; class time{ public: static int n; time():id(++n){ Hr=Min=Sec=0; cout<<"\nCreated <"<<id;cout<<"> ";display();cout<<"\n"; } time(int h, int m,int s):id(++n){ Hr=h;Min=m;Sec=s; cout<<"\nCreated <"<<id;cout<<"> ";display();cout<<"\n"; } ~time(){ //n++; cout<<"\ndestroyed <"<<id;cout<<"> ";display();cout<<"\n"; }; void display(){ cout<<"Display says: "; cout<<Hr<<" : "<<Min<<" : "<<Sec; } void setH(int z){Hr=z;} time add(time a){ time b=time(Hr+a.Hr,Min+a.Min,Sec+a.Sec); cout<<"in add"; a.setH(77); return b; } private: int Hr; int Min; int Sec; const int id; }; int time::n=0; int main(){ time A(2,1,0); time B(0,1,2); time C=B.add(A);cout<<"jhjh"<<endl; //C.setH(7); C.display(); //B.~time(); }
#include "world.h" #include <math.h> World::World(RGB c) { background = c; } void World::AddObject(Object * obj) { objects.push_back(obj); } void World::AddLight(PointLight light) { lights.push_back(light); } HitInfo World::TraceRay(Ray3 ray) { HitInfo result; Vec3 normal; result.HitObject = NULL; double minimalDistance = infinity; // najbliższe trafienie double lastDistance = 0; // zmienna pomocnicza, ostatnia odległość for(int i=0;i<objects.size();i++) { if(objects[i]->HitTest(ray,lastDistance,normal) ) if(lastDistance < minimalDistance) { minimalDistance = lastDistance; result.HitObject = objects[i]; result.normal = normal; } } if(result.HitObject != NULL) { result.HitPoint = ray.pos + ray.dir * minimalDistance; result.ray = ray; result.dist = minimalDistance; result.world = this; } return result; } bool World::AnyObstacle(Vec3 A, Vec3 B) { // odległość od cieniowanego punktu do światła Vec3 vectorAB = B - A; double distAB = vectorAB.value(); double currDistance = infinity; // promień (półprosta) z cieniowanego punktu w kierunku światła Ray3 ray(A, vectorAB); Vec3 ignored; for(int i=0;i<objects.size();i++) { // jeśli jakiś obiekt jest na drodze promienia oraz trafienie // nastąpiło bliżej niż odległość punktu do światła, // obiekt jest w cieniu if (objects[i]->HitTest(ray, currDistance, ignored) && currDistance < distAB) return true; } return false; }
#include <string> class Resource { private: string _name; int _amount; public: Resource(string name); Resource(string, int initialAmount); int add(int amount); int getAmount(); };
#include "stdafx.h" #include "Window.h" #include "GameNode.h" #include "IsoMap.h" POINT Window::ptMouse = POINT{ 0,0 }; CTRL Window::_currentCTRL = CTRL_DRAW; Window::Window() { m_backBuffer = new Image(); m_backBuffer->Init(SUBWINSIZEX, SUBWINSIZEY); } Window::~Window() { SAFE_DELETE(m_backBuffer); } void Window::Init() { CreateSubWindow(); isActive = false; int tempX = 10; _btnDraw = CreateWindow("button", "Tile", // 자식으로 생성하면 안쪽에 만들어짐 WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // 클릭했을때 어떤 값을 반환할지 hMenu tempX, 0, 100, 20, hWnd, HMENU(0), g_hInstance, NULL); _btnEraser = CreateWindow("button", "Eraser", // 자식으로 생성하면 안쪽에 만들어짐 WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // 클릭했을때 어떤 값을 반환할지 hMenu tempX, 30, 100, 20, hWnd, HMENU(1), g_hInstance, NULL); _btnEraser = CreateWindow("button", "Init", // 자식으로 생성하면 안쪽에 만들어짐 WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, // 클릭했을때 어떤 값을 반환할지 hMenu tempX, 60, 100, 20, hWnd, HMENU(2), g_hInstance, NULL); _btnSave = CreateWindow("button", "Save", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 115, 0, 100, 20, hWnd, HMENU(3), g_hInstance, NULL); _btnLoad = CreateWindow("button", "Load", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 115, 30, 100, 20, hWnd, HMENU(4), g_hInstance, NULL); _btnStart = CreateWindow("button", "Start", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 115, 60, 100, 20, hWnd, HMENU(8), g_hInstance, NULL); _btnN1 = CreateWindow("button", "N1", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 35, 135, 35, 25, hWnd, HMENU(5), g_hInstance, NULL); _btnN2 = CreateWindow("button", "N2", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 35 + 60, 135, 35, 25, hWnd, HMENU(6), g_hInstance, NULL); _btnN3 = CreateWindow("button", "N3", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, tempX + 35 + 120, 135, 35, 25, hWnd, HMENU(7), g_hInstance, NULL); clickFrame = { 0,0 }; clickIndex = 0; } void Window::Release() { } void Window::Update() { if (currentScene != NULL) { currentScene->Update(); } } void Window::Render() { HDC hdc = GetDC(hWnd); PatBlt(m_backBuffer->GetMemDC(), 0, 0, SUBWINSIZEX, SUBWINSIZEY, WHITENESS); //============================== if (currentScene != NULL) { currentScene->Render(m_backBuffer->GetMemDC()); } //============================= m_backBuffer->Render(hdc); ReleaseDC(hWnd, hdc); } void Window::SetScene(GameNode * scene) { currentScene = scene; currentScene->Init(); } LRESULT Window::WndLogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_MOUSEMOVE: SUBWIN->SetIsActive(true); ptMouse.x = LOWORD(lParam); ptMouse.y = HIWORD(lParam); break; case WM_PAINT: { //HDC hdc = GetDC(hWnd); //IMAGE->FindImage("sub_bg")->Render(hdc); //ReleaseDC(hWnd, hdc); } break; case WM_COMMAND: // 프로그램 실행 중 사용자가 메뉴 항목을 선택하면 발생하는 메세지 switch (LOWORD(wParam)) { default: //// 클릭했을 때 0,1,2 값 중 하나가 들어옴 //_currentCTRL = (CTRL)(LOWORD(wParam)); switch (LOWORD(wParam)) { case CTRL_DRAW: case CTRL_ERASER: _currentCTRL = (CTRL)(LOWORD(wParam)); break; case CTRL_INIT: SUBWIN->GetIsoMap()->Init(); break; case CTRL_SAVE: SUBWIN->GetIsoMap()->Save(); break; case CTRL_LOAD: SUBWIN->GetIsoMap()->Load(); break; case CTRL_NUM1: case CTRL_NUM2: case CTRL_NUM3: SUBWIN->SetFrameIndex(LOWORD(wParam) - 5); break; case CTRL_START: SCENE->ChangeScene("PokemonWorld"); break; } break; } break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: PostQuitMessage(0); break; } break; default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } void Window::CreateSubWindow() { // 로그 윈도우 생성 int x, y, cx, cy; WNDCLASS wc; RECT rc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC)Window::WndLogProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetModuleHandle(NULL); wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = "sub"; RegisterClass(&wc); // 부모 윈도우 오른쪽에 위치하게 RECT rcWin; GetWindowRect(g_hWnd, &rcWin); cx = SUBWINSIZEX; cy = SUBWINSIZEY; x = rcWin.right; y = rcWin.top; rc.left = 0; rc.top = 0; rc.right = cx; rc.bottom = cy; HWND hParenthWnd = NULL; HINSTANCE hInst = NULL; hParenthWnd = g_hWnd; hInst = GetModuleHandle(NULL); hWnd = CreateWindow( "sub", "sub", WS_POPUP | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, x, y, cx, cy, hParenthWnd, NULL, hInst, NULL); AdjustWindowRect(&rc, WINSTYLE, FALSE); SetWindowPos(hWnd, NULL, x, y, (rc.right - rc.left), (rc.bottom - rc.top), SWP_NOZORDER); ShowWindow(hWnd, SW_SHOW); }
#include "foo.h" int foo() { return 1477; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Espen Sand */ #include "core/pch.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/dialogs/LicenseDialog.h" #include "adjunct/desktop_pi/DesktopGlobalApplication.h" #include "modules/encodings/detector/charsetdetector.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/util/opfile/opfile.h" #include "modules/widgets/OpMultiEdit.h" Str::LocaleString LicenseDialog::GetOkTextID() { return Str::D_I_AGREE; } Str::LocaleString LicenseDialog::GetCancelTextID() { return Str::D_I_DO_NOT_AGREE; } void LicenseDialog::OnInitVisibility() { SetTitle(UNI_L("Opera")); OpMultilineEdit* edit = (OpMultilineEdit*) GetWidgetByName("Edit"); if (edit) { OpString message; ReadFile(message); edit->SetText(message.CStr()); edit->SetReadOnly(TRUE); edit->SetTabStop(TRUE); g_input_manager->SetKeyboardInputContext(edit, FOCUS_REASON_ACTIVATE); } } UINT32 LicenseDialog::OnOk() { INT32 flag = g_pcui->GetIntegerPref(PrefsCollectionUI::AcceptLicense); // Value for 7.50 INT32 mask = 0x01; TRAPD(rc, g_pcui->WriteIntegerL(PrefsCollectionUI::AcceptLicense, flag|mask)); OP_ASSERT(OpStatus::IsSuccess(rc)); // FIXME: handle error sensibly TRAP(rc, g_prefsManager->CommitL()); OP_ASSERT(OpStatus::IsSuccess(rc)); // FIXME: handle error sensibly g_main_message_handler->PostMessage(MSG_QUICK_APPLICATION_START_CONTINUE, 0, 0); return 0; } void LicenseDialog::OnCancel() { //Cancelling start up dialog means that the user doesn't want to run Opera after all g_desktop_global_application->Exit(); } void LicenseDialog::ReadFile( OpString& message ) { // Step 1: Open file OpFile file; if (OpStatus::IsError(OpenLicenseFile(OPFILE_LANGUAGE_FOLDER, file)) && OpStatus::IsError(OpenLicenseFile(OPFILE_INI_FOLDER, file))) return; // Step 2: Read file. OpFileLength size; RETURN_VOID_IF_ERROR(file.GetFileLength(size)); if( size > 0 ) { char* buffer = OP_NEWA(char, size+1); if( buffer ) { OpFileLength bytes_read = 0; file.Read(buffer, size, &bytes_read); buffer[size] = 0; CharsetDetector detector; const char* encoding = detector.GetUTFEncodingFromBOM(buffer, size); if( encoding ) { TRAPD(rc, SetFromEncodingL(&message, encoding, buffer, size)); } else { TRAPD(rc, SetFromEncodingL(&message, "windows-1252", buffer, size)); } OP_DELETEA(buffer); } } } OP_STATUS LicenseDialog::OpenLicenseFile(OpFileFolder folder, OpFile& file) { RETURN_IF_ERROR(file.Construct(UNI_L("license.txt"), folder)); return file.Open(OPFILE_READ); }
// siglus.cc // 5/25/2014 jichi // // Hooking thiscall: http://tresp4sser.wordpress.com/2012/10/06/how-to-hook-thiscall-functions/ #include "engine/model/siglus.h" #include "engine/enginecontroller.h" #include "engine/enginedef.h" #include "engine/enginehash.h" #include "engine/enginesettings.h" #include "engine/engineutil.h" #include "engine/util/textunion.h" #include "hijack/hijackmanager.h" #include "winhook/hookcode.h" #include "winhook/hookfun.h" #include <qt_windows.h> #include <cstdint> #define DEBUG "model/siglus" #include "sakurakit/skdebug.h" // Used to get function's return address // http://stackoverflow.com/questions/8797943/finding-a-functions-address-in-c //#pragma intrinsic(_ReturnAddress) namespace { // unnamed namespace ScenarioHook { namespace Private { enum Type { Type1 // Old SiglusEngine2, arg in ecx , Type2 // New SiglusENgine2, arg in arg1, since リア充クラスメイト孕ませ催眠 in 9/26/2014 } type_; // static /** * Sample game: 聖娼女 体験版 * * IDA: sub_4DAC70 proc near ; Attributes: bp-based frame * * Observations: * - return: number of bytes = 2 * number of size * - arg1: unknown pointer, remains the same * - arg2: unknown, remains the same * - this (ecx) * - union * - char x 3: if size < (3 * 2 - 1) && * - pointer x 4 * - 0x0: UTF-16 text * - 0x4: the same as 0x0 * - 0x8: unknown variate pointer * - 0xc: wchar_t pointer to a flag, the pointed value is zero when union is used as a char * - 0x10: size of the text without null char * - 0x14: unknown size, always slightly larger than size * - 0x18: constant pointer * ... * * Sample stack: * 0025edf0 a8 f3 13 0a a8 f3 13 0a ィ・.ィ・. ; jichi: ecx = 0025edf0 * LPCWSTR LPCWSTR * 0025edf8 10 ee 25 00 d0 ee 37 01 ・.ミ・ * LPCWSTR LPCWSTR * 0025ee00 13 00 00 00 17 00 00 00 ...… * SIZE_T SIZE_T * * 0025ee08 18 0c f6 09 27 00 00 00 .・'... ; jichi: following three lines are constants * 0025ee10 01 00 00 00 01 00 00 00 ...... * 0025ee18 d2 d9 5d 9f 1c a2 e7 09 メル]・「・ * * 0025ee20 40 8c 10 07 00 00 00 00 @・.... * 0025ee28 00 00 00 00 00 00 00 00 ........ * 0025ee30 b8 ee ce 0c b8 ee ce 0c ク﨩.ク﨩. * 0025ee38 b8 ee ce 0c 00 00 00 00 ク﨩..... * 0025ee40 00 00 00 00 01 00 00 00 ....... * 0025ee48 00 00 00 00 00 00 00 00 ........ * 0025ee50 00 00 00 00 00 00 00 00 ........ * 0025ee58 00 00 00 00 00 00 00 00 ........ * * 0025ee60 01 00 00 00 01 00 00 00 ...... */ typedef int (__thiscall *hook_fun_t)(DWORD, DWORD, DWORD); // the first pointer is this // Use __fastcall to completely forward ecx and edx //typedef int (__fastcall *hook_fun_t)(void *, void *, DWORD, DWORD); hook_fun_t oldHookFun; /** * Hooking thiscall using fastcall: http://tresp4sser.wordpress.com/2012/10/06/how-to-hook-thiscall-functions/ * - thiscall: this is in ecx and the first argument * - fastcall: the first two parameters map to ecx and edx */ int __fastcall newHookFun(DWORD ecx, DWORD edx, DWORD arg1, DWORD arg2) { Q_UNUSED(edx); auto arg = (TextUnionW *)(type_ == Type1 ? ecx : arg1); if (!arg || !arg->isValid()) return oldHookFun(ecx, arg1, arg2); // ret = size * 2 enum { role = Engine::ScenarioRole, sig = 0 }; //return oldHookFun(arg, arg1, arg2); QString oldText = QString::fromUtf16(arg->getText(), arg->size), newText = EngineController::instance()->dispatchTextW(oldText, role, sig); if (newText == oldText) return oldHookFun(ecx, arg1, arg2); // ret = size * 2 if (newText.isEmpty()) return arg->size * 2; // estimated painted bytes auto argValue = *arg; arg->setLongText(newText); int ret = oldHookFun(ecx, arg1, arg2); // ret = size * 2 // Restoring is indispensible, and as a result, the default hook does not work *arg = argValue; return ret; } /** * jichi 8/16/2013: Insert new siglus hook * See (CaoNiMaGeBi): http://tieba.baidu.com/p/2531786952 * * 013bac6e cc int3 * 013bac6f cc int3 * 013bac70 /$ 55 push ebp ; jichi: function starts * 013bac71 |. 8bec mov ebp,esp * 013bac73 |. 6a ff push -0x1 * 013bac75 |. 68 d8306201 push siglusen.016230d8 * 013bac7a |. 64:a1 00000000 mov eax,dword ptr fs:[0] * 013bac80 |. 50 push eax * 013bac81 |. 81ec dc020000 sub esp,0x2dc * 013bac87 |. a1 90f46b01 mov eax,dword ptr ds:[0x16bf490] * 013bac8c |. 33c5 xor eax,ebp * 013bac8e |. 8945 f0 mov dword ptr ss:[ebp-0x10],eax * 013bac91 |. 53 push ebx * 013bac92 |. 56 push esi * 013bac93 |. 57 push edi * 013bac94 |. 50 push eax * ... * 013baf32 |. 3bd7 |cmp edx,edi ; jichi: ITH hook here, char saved in edi * 013baf34 |. 75 4b |jnz short siglusen.013baf81 */ ulong search(ulong startAddress, ulong stopAddress, Type *type) { ulong addr; { const uint8_t bytes1[] = { 0x3b,0xd7, // 013baf32 |. 3bd7 |cmp edx,edi ; jichi: ITH hook here, char saved in edi 0x75,0x4b // 013baf34 |. 75 4b |jnz short siglusen.013baf81 }; addr = MemDbg::findBytes(bytes1, sizeof(bytes1), startAddress, stopAddress); if (addr && type) *type = Type1; } if (!addr) { const uint8_t bytes2[] = { // 81fe0c300000 0x81,0xfe, 0x0c,0x30,0x00,0x00 // 0114124a 81fe 0c300000 cmp esi,0x300c ; jichi: hook here }; addr = MemDbg::findBytes(bytes2, sizeof(bytes2), startAddress, stopAddress); if (addr && type) *type = Type2; } if (!addr) return 0; const uint8_t bytes[] = { 0x55, // 013bac70 /$ 55 push ebp ; jichi: function starts 0x8b,0xec, // 013bac71 |. 8bec mov ebp,esp 0x6a,0xff // 013bac73 |. 6a ff push -0x1 }; //enum { range = 0x300 }; // 0x013baf32 - 0x013bac70 = 706 = 0x2c2 //enum { range = 0x400 }; // 0x013baf32 - 0x013bac70 = 0x36a enum { range = 0x500 }; // 0x00b6bcf8 - 0x00b6b880 = 0x478 return MemDbg::findBytes(bytes, sizeof(bytes), addr - range, addr); //if (!reladdr) // //ConsoleOutput("vnreng:Siglus2: pattern not found"); // return 0; //addr += reladdr; //return addr; } } // namespace Private bool attach(ulong startAddress, ulong stopAddress) // attach scenario { ulong addr = Private::search(startAddress, stopAddress, &Private::type_); if (!addr) return false; return Private::oldHookFun = (Private::hook_fun_t)winhook::replace_fun(addr, (ulong)Private::newHookFun); } } // namespace ScenarioHook namespace OtherHook { namespace Private { TextUnionW *arg_, argValue_; bool hookBefore(winhook::hook_stack *s) { static QString text_; auto arg = (TextUnionW *)s->stack[0]; if (!arg || !arg->isValid()) return true; LPCWSTR text = arg->getText(); // Skip all ascii if (!text || !*text || *text <= 127 || arg->size > Engine::MaxTextSize) // there could be garbage return true; int role = Engine::OtherRole; ulong split = s->stack[3]; if (split <= 0xffff || !Engine::isAddressReadable(split)) { // skip modifying scenario thread //role = Engine::ScenarioRole; return true; } else { split = *(DWORD *)split; switch (split) { case 0x54: case 0x26: role = Engine::NameRole; } } auto sig = Engine::hashThreadSignature(role, split); QString oldText = QString::fromUtf16(text, arg->size), newText = EngineController::instance()->dispatchTextW(oldText, role, sig); if (oldText == newText) return true; arg_ = arg; argValue_ = *arg; text_ = newText; arg->setLongText(text_); return true; } bool hookAfter(winhook::hook_stack *) // this hookAfter is not needed for this other hook { if (arg_) { *arg_ = argValue_; arg_ = nullptr; } return true; } ulong search(ulong startAddress, ulong stopAddress) { const uint8_t bytes[] = { 0xc7,0x47, 0x14, 0x07,0x00,0x00,0x00, // 0042cf20 c747 14 07000000 mov dword ptr ds:[edi+0x14],0x7 0xc7,0x47, 0x10, 0x00,0x00,0x00,0x00, // 0042cf27 c747 10 00000000 mov dword ptr ds:[edi+0x10],0x0 0x66,0x89,0x0f, // 0042cf2e 66:890f mov word ptr ds:[edi],cx 0x8b,0xcf, // 0042cf31 8bcf mov ecx,edi 0x50, // 0042cf33 50 push eax 0xe8 //XX4 // 0042cf34 e8 e725f6ff call .0038f520 ; jichi: hook here }; enum { addr_offset = sizeof(bytes) - 1 }; // +4 for the call address ulong addr = MemDbg::findBytes(bytes, sizeof(bytes), startAddress, stopAddress); if (!addr) return 0; return addr + addr_offset; } } // namespace Private bool attach(ulong startAddress, ulong stopAddress) { ulong addr = Private::search(startAddress, stopAddress); return addr && winhook::hook_both(addr, Private::hookBefore, Private::hookAfter); } } // namespace OtherHook } // unnamed namespace /** Public class */ bool SiglusEngine::attach() { ulong startAddress, stopAddress; if (!Engine::getProcessMemoryRange(&startAddress, &stopAddress)) return false; if (!ScenarioHook::attach(startAddress, stopAddress)) return false; if (OtherHook::attach(startAddress, stopAddress)) DOUT("other hook found"); else DOUT("other hook NOT FOUND"); // Allow change font HijackManager::instance()->attachFunction((ulong)::GetGlyphOutlineW); return true; } // EOF
// Project_3.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "ShennonFano.h" int main() { system("chcp 1251");//Установка кодовой страницы setlocale(LC_ALL, "ru_RU.UTF-8"); //wcout.imbue(locale("rus_rus.866")); std::wstring test_string = L"Ленин — жил. Ленин — жив. Ленин — будет жить."; ShennonFano shennon; auto table = shennon.get_table(test_string); auto encode_str = shennon.encode(test_string, table); auto decode_str = shennon.decode(encode_str, table); auto table_iterator = table.Nodes().create_list_iterator(); while (table_iterator->has_next()) { auto table_node = table_iterator->next(); std::wcout << "Letter : " << table_node->get_key() << " | Code : " << table_node->get_value() << " | Freq: " << table_node->get_count() << std::endl; } size_t decode_size = (decode_str.size() + 1) * sizeof(wchar_t); size_t encode_size = ceil(encode_str.size() / 8.0); std::wcout << "Decode string : " << decode_str << " | size : " << decode_size << std::endl; std::wcout << "Encode string : " << encode_str << " | size : " << encode_size << std::endl; std::cout << "Compression ratio : " << encode_size / (double)decode_size << std::endl; return 0; }
/* XMRig * Copyright (c) 2014-2019 heapwolf <https://github.com/heapwolf> * Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/http/HttpData.h" #include "3rdparty/llhttp/llhttp.h" #include "3rdparty/rapidjson/document.h" #include "3rdparty/rapidjson/error/en.h" #include "base/io/json/Json.h" #include <uv.h> #include <stdexcept> /* Status Codes */ #define HTTP_STATUS_MAP(XX) \ XX(100, CONTINUE, Continue) \ XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ XX(102, PROCESSING, Processing) \ XX(200, OK, OK) \ XX(201, CREATED, Created) \ XX(202, ACCEPTED, Accepted) \ XX(203, NON_AUTHORITATIVE_INFORMATION, Non-Authoritative Information) \ XX(204, NO_CONTENT, No Content) \ XX(205, RESET_CONTENT, Reset Content) \ XX(206, PARTIAL_CONTENT, Partial Content) \ XX(207, MULTI_STATUS, Multi-Status) \ XX(208, ALREADY_REPORTED, Already Reported) \ XX(226, IM_USED, IM Used) \ XX(300, MULTIPLE_CHOICES, Multiple Choices) \ XX(301, MOVED_PERMANENTLY, Moved Permanently) \ XX(302, FOUND, Found) \ XX(303, SEE_OTHER, See Other) \ XX(304, NOT_MODIFIED, Not Modified) \ XX(305, USE_PROXY, Use Proxy) \ XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ XX(400, BAD_REQUEST, Bad Request) \ XX(401, UNAUTHORIZED, Unauthorized) \ XX(402, PAYMENT_REQUIRED, Payment Required) \ XX(403, FORBIDDEN, Forbidden) \ XX(404, NOT_FOUND, Not Found) \ XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ XX(406, NOT_ACCEPTABLE, Not Acceptable) \ XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ XX(408, REQUEST_TIMEOUT, Request Timeout) \ XX(409, CONFLICT, Conflict) \ XX(410, GONE, Gone) \ XX(411, LENGTH_REQUIRED, Length Required) \ XX(412, PRECONDITION_FAILED, Precondition Failed) \ XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ XX(414, URI_TOO_LONG, URI Too Long) \ XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ XX(417, EXPECTATION_FAILED, Expectation Failed) \ XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ XX(423, LOCKED, Locked) \ XX(424, FAILED_DEPENDENCY, Failed Dependency) \ XX(426, UPGRADE_REQUIRED, Upgrade Required) \ XX(428, PRECONDITION_REQUIRED, Precondition Required) \ XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ XX(501, NOT_IMPLEMENTED, Not Implemented) \ XX(502, BAD_GATEWAY, Bad Gateway) \ XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ XX(508, LOOP_DETECTED, Loop Detected) \ XX(510, NOT_EXTENDED, Not Extended) \ XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) \ enum http_status { # define XX(num, name, string) HTTP_STATUS_##name = num, HTTP_STATUS_MAP(XX) # undef XX }; namespace xmrig { const std::string HttpData::kApplicationJson = "application/json"; const std::string HttpData::kContentType = "Content-Type"; const std::string HttpData::kContentTypeL = "content-type"; const std::string HttpData::kTextPlain = "text/plain"; static const char *http_status_str(enum http_status s) { switch (s) { # define XX(num, name, string) case HTTP_STATUS_##name: return #string; HTTP_STATUS_MAP(XX) # undef XX default: return "<unknown>"; } } } // namespace xmrig bool xmrig::HttpData::isJSON() const { if (!headers.count(kContentTypeL)) { return false; } auto &type = headers.at(kContentTypeL); return type == kApplicationJson || type == kTextPlain; } const char *xmrig::HttpData::methodName() const { return llhttp_method_name(static_cast<llhttp_method>(method)); } rapidjson::Document xmrig::HttpData::json() const { if (status < 0) { throw std::runtime_error(statusName()); } if (!isJSON()) { throw std::runtime_error("the response is not a valid JSON response"); } using namespace rapidjson; Document doc; if (doc.Parse(body.c_str()).HasParseError()) { throw std::runtime_error(GetParseError_En(doc.GetParseError())); } if (doc.IsObject() && !doc.ObjectEmpty()) { const char *error = Json::getString(doc, "error"); if (error) { throw std::runtime_error(error); } } return doc; } const char *xmrig::HttpData::statusName(int status) { if (status < 0) { return uv_strerror(status); } return http_status_str(static_cast<http_status>(status)); }
#include "ticket.h" std::ostream &operator << (std::ostream &os, const Seat &s) { os << s.type << ' ' << s.num + station::INITIAL_QUANTITY << ' ' << s.price; return os; } std::ostream &operator << (std::ostream &os, const ticket &t) { os << t.tID << ' ' << t.from << ' ' << t.Date << ' ' << t.leave << ' ' << t.to << ' '; os<<t.Date2<< ' ' << t.arrive << ' '; for (int i = 0; i < t.seat.size(); i++) os << t.seat[i] << ' '; return os; } bool cmpByFirstDim(const std::pair<shortString,shortString> &lhs, const std::pair<shortString,shortString>& rhs) { return lhs.first < rhs.first; } std::pair<bool,String> checkTransfer //返回是否构成中转方案和中转站 (const train &T1, const train &T2, const String &from, const String &to) { int x = T1.getStationID(from), y = T2.getStationID(to); for (int i = x + 1; i < T1.n; i++) { // 以T1.s[i]为中转站 // std::cout << "transfer check: " <<T1.s[i].name<< endl; int j = 0; while (j < y && (T2.s[j] != T1.s[i]||T1.s[i].arrive > T2.s[j].leave)) { // std::cout << T2.s[j].name << endl; j++; } if (j < y) return std::make_pair(true,T1.s[i].name); } return std::make_pair(false,String("")); } void myMin(ticketPair &p1,const ticketPair &p2) { if (!p1.first.valid() || p2.second.arrive - p2.first.leave < p1.second.arrive - p1.first.leave) p1 = p2; } void ticketSystem::add(const String &st, const String &id) { #ifdef DEBUGMODE std::cout << "add: Train #" << id << " will pass station " << st << endl; #endif B.insert(std::make_pair(st,id),id); } vector<ticket> ticketSystem::query(const String &from, const String &to, const date &d,const String &catalog) { auto V = B.listof(std::make_pair(from,String()), cmpByFirstDim); auto U = B.listof(std::make_pair(to, String()), cmpByFirstDim); #ifdef DEBUGMODE std::cout << "------------------DEBUG-----------------------------------" << endl; std::cout << "Trains at " << from << endl; for (int i = 0; i < V.size(); i++) std::cout << V[i].second << endl; std::cout << "Trains at " << to << endl; for (int i = 0; i < V.size(); i++) std::cout << U[i].second<< endl; std::cout << "----------------------------------------------------------" << endl; #endif // DEBUG_MODE vector<String> C; int i = 0, j = 0; while (i < V.size()) { while (j < U.size() && U[j].second < V[i].second) j++; if (j == U.size()) break; if (V[i].second == U[j].second) C.push_back(V[i].second); i++; } vector<ticket> ret; for (i = 0; i < C.size(); i++) { train t = TS->query(C[i]).second; if (catalog.contain(t.catalog) && t.ok(from, to))ret.push_back(ticket(t,from,to,d)); } return ret; } ticketPair ticketSystem::transfer(const String &from, const String &to, const date &d,const String &catalog) { auto V = B.listof(std::make_pair(from, String()), cmpByFirstDim); auto U = B.listof(std::make_pair(to, String()), cmpByFirstDim); #ifdef DEBUGMODE std::cout << "------------------DEBUG-----------------------------------" << endl; std::cout << "Trains at " << from << endl; for (int i = 0; i < V.size(); i++) std::cout << V[i].second << endl; std::cout << "Trains at " << to << endl; for (int i = 0; i < U.size(); i++) std::cout << U[i].second << endl; std::cout << "----------------------------------------------------------" << endl; #endif // DEBUG_MODE ticketPair ret; for (int i = 0; i < V.size(); i++) { train T1 = TS->query(V[i].second).second; if (!catalog.contain(T1.catalog)) continue; for (int j = 0; j < U.size(); j++) { train T2 = TS->query(U[j].second).second; if (!catalog.contain(T2.catalog)) continue; //std::cout << "check: " << T1.ID << " " << T2.ID << endl; auto check = checkTransfer(T1, T2, from, to); if (check.first) myMin(ret, ticketPair(ticket(T1, from, check.second, d), ticket(T2, check.second, to, d)) ); } } return ret; }
#include "Snowflakes.h" #include "../engine/Math.h" #include <ctime> Snowflake::Snowflake(gfx::Canvas* canvasToSet, float sizeToSet, float opacityToSet, int distortionOffsetToSet) : Primitive (canvasToSet, 1, Color(255,255,0)) { _opacity = opacityToSet; _size = sizeToSet * _opacity; _weight = _opacity * _opacity; _distortionOffset = distortionOffsetToSet; this->motionBlur(true); this->location(50, 50); this->momentum(0, 300 * (_opacity * _opacity + 0.25)); } void Snowflake::move(float dt, float x, float y, unsigned long long ms) { int frequency = 2000; float factor = (float)((ms + _distortionOffset) % frequency) / frequency; float strength = 0.25; float noise = sin(factor * 2 * math::PI) * strength; Point tmpMomentum(_momentum.y() * noise, _momentum.y() * (1 - abs(noise))); location(location().x() + (x + tmpMomentum.x()) * dt, location().y() + (y + tmpMomentum.y()) * dt); _translate(location().x(), location().y()); } void Snowflake::draw() { int x = (int)round(this->location().x()); int y = (int)round(this->location().y()); Color white(255,255,255); float opacity = _opacity; bool mb = this->motionBlur(); _canvas->px(x+1, y-7, white, mb, (int)(opacity *48 )); _canvas->px(x, y-6, white, mb, (int)(opacity *65 )); _canvas->px(x+1, y-6, white, mb, (int)(opacity *131 )); _canvas->px(x-5, y-5, white, mb, (int)(opacity *49 )); _canvas->px(x-4, y-5, white, mb, (int)(opacity *32 )); _canvas->px(x-2, y-5, white, mb, (int)(opacity *45 )); _canvas->px(x-1, y-5, white, mb, (int)(opacity *58 )); _canvas->px(x, y-5, white, mb, (int)(opacity *125 )); _canvas->px(x+1, y-5, white, mb, (int)(opacity *137 )); _canvas->px(x+2, y-5, white, mb, (int)(opacity *38 )); _canvas->px(x-6, y-4, white, mb, (int)(opacity *49 )); _canvas->px(x-5, y-4, white, mb, (int)(opacity *175 )); _canvas->px(x-4, y-4, white, mb, (int)(opacity *105 )); _canvas->px(x-3, y-4, white, mb, (int)(opacity *134 )); _canvas->px(x-2, y-4, white, mb, (int)(opacity *57 )); _canvas->px(x-1, y-4, white, mb, (int)(opacity *138 )); _canvas->px(x, y-4, white, mb, (int)(opacity *222 )); _canvas->px(x+1, y-4, white, mb, (int)(opacity *182 )); _canvas->px(x+2, y-4, white, mb, (int)(opacity *98 )); _canvas->px(x+3, y-4, white, mb, (int)(opacity *30 )); _canvas->px(x-6, y-3, white, mb, (int)(opacity *27 )); _canvas->px(x-5, y-3, white, mb, (int)(opacity *159 )); _canvas->px(x-4, y-3, white, mb, (int)(opacity *231 )); _canvas->px(x-3, y-3, white, mb, (int)(opacity *184 )); _canvas->px(x-2, y-3, white, mb, (int)(opacity *80 )); _canvas->px(x-1, y-3, white, mb, (int)(opacity *92 )); _canvas->px(x, y-3, white, mb, (int)(opacity *231 )); _canvas->px(x+1, y-3, white, mb, (int)(opacity *148 )); _canvas->px(x+2, y-3, white, mb, (int)(opacity *55 )); _canvas->px(x+3, y-3, white, mb, (int)(opacity *54 )); _canvas->px(x+4, y-3, white, mb, (int)(opacity *35 )); _canvas->px(x-6, y-2, white, mb, (int)(opacity *54 )); _canvas->px(x-5, y-2, white, mb, (int)(opacity *162 )); _canvas->px(x-4, y-2, white, mb, (int)(opacity *232 )); _canvas->px(x-3, y-2, white, mb, (int)(opacity *254 )); _canvas->px(x-2, y-2, white, mb, (int)(opacity *178 )); _canvas->px(x-1, y-2, white, mb, (int)(opacity *158 )); _canvas->px(x, y-2, white, mb, (int)(opacity *249 )); _canvas->px(x+1, y-2, white, mb, (int)(opacity *125 )); _canvas->px(x+2, y-2, white, mb, (int)(opacity *99 )); _canvas->px(x+3, y-2, white, mb, (int)(opacity *128 )); _canvas->px(x+4, y-2, white, mb, (int)(opacity *106 )); _canvas->px(x+5, y-2, white, mb, (int)(opacity *91 )); _canvas->px(x+6, y-2, white, mb, (int)(opacity *68 )); _canvas->px(x+7, y-2, white, mb, (int)(opacity *19 )); _canvas->px(x-6, y-1, white, mb, (int)(opacity *49 )); _canvas->px(x-5, y-1, white, mb, (int)(opacity *77 )); _canvas->px(x-4, y-1, white, mb, (int)(opacity *120 )); _canvas->px(x-3, y-1, white, mb, (int)(opacity *209 )); _canvas->px(x-2, y-1, white, mb, (int)(opacity *255 )); _canvas->px(x-1, y-1, white, mb, (int)(opacity *224 )); _canvas->px(x, y-1, white, mb, (int)(opacity *230 )); _canvas->px(x+1, y-1, white, mb, (int)(opacity *158 )); _canvas->px(x+2, y-1, white, mb, (int)(opacity *197 )); _canvas->px(x+3, y-1, white, mb, (int)(opacity *212 )); _canvas->px(x+4, y-1, white, mb, (int)(opacity *188 )); _canvas->px(x+5, y-1, white, mb, (int)(opacity *125 )); _canvas->px(x+6, y-1, white, mb, (int)(opacity *54 )); _canvas->px(x-6, y, white, mb, (int)(opacity *90 )); _canvas->px(x-5, y, white, mb, (int)(opacity *96 )); _canvas->px(x-4, y, white, mb, (int)(opacity *107 )); _canvas->px(x-3, y, white, mb, (int)(opacity *145 )); _canvas->px(x-2, y, white, mb, (int)(opacity *224 )); _canvas->px(x-1, y, white, mb, (int)(opacity *255 )); _canvas->px(x, y, white, mb, (int)(opacity *255 )); _canvas->px(x+1, y, white, mb, (int)(opacity *241 )); _canvas->px(x+2, y, white, mb, (int)(opacity *205 )); _canvas->px(x+3, y, white, mb, (int)(opacity *152 )); _canvas->px(x+4, y, white, mb, (int)(opacity *139 )); _canvas->px(x+5, y, white, mb, (int)(opacity *50 )); _canvas->px(x-6, y+1, white, mb, (int)(opacity *115 )); _canvas->px(x-5, y+1, white, mb, (int)(opacity *214 )); _canvas->px(x-4, y+1, white, mb, (int)(opacity *234 )); _canvas->px(x-3, y+1, white, mb, (int)(opacity *255 )); _canvas->px(x-2, y+1, white, mb, (int)(opacity *253 )); _canvas->px(x-1, y+1, white, mb, (int)(opacity *255 )); _canvas->px(x, y+1, white, mb, (int)(opacity *255 )); _canvas->px(x+1, y+1, white, mb, (int)(opacity *189 )); _canvas->px(x+2, y+1, white, mb, (int)(opacity *113 )); _canvas->px(x+3, y+1, white, mb, (int)(opacity *68 )); _canvas->px(x+4, y+1, white, mb, (int)(opacity *64 )); _canvas->px(x+5, y+1, white, mb, (int)(opacity *41 )); _canvas->px(x-8, y+2, white, mb, (int)(opacity *34 )); _canvas->px(x-7, y+2, white, mb, (int)(opacity *143 )); _canvas->px(x-6, y+2, white, mb, (int)(opacity *195 )); _canvas->px(x-5, y+2, white, mb, (int)(opacity *231 )); _canvas->px(x-4, y+2, white, mb, (int)(opacity *203 )); _canvas->px(x-3, y+2, white, mb, (int)(opacity *150 )); _canvas->px(x-2, y+2, white, mb, (int)(opacity *171 )); _canvas->px(x-1, y+2, white, mb, (int)(opacity *244 )); _canvas->px(x, y+2, white, mb, (int)(opacity *183 )); _canvas->px(x+1, y+2, white, mb, (int)(opacity *246 )); _canvas->px(x+2, y+2, white, mb, (int)(opacity *175 )); _canvas->px(x+3, y+2, white, mb, (int)(opacity *101 )); _canvas->px(x+4, y+2, white, mb, (int)(opacity *92 )); _canvas->px(x+5, y+2, white, mb, (int)(opacity *43 )); _canvas->px(x-8, y+3, white, mb, (int)(opacity *27 )); _canvas->px(x-7, y+3, white, mb, (int)(opacity *73 )); _canvas->px(x-6, y+3, white, mb, (int)(opacity *88 )); _canvas->px(x-5, y+3, white, mb, (int)(opacity *142 )); _canvas->px(x-4, y+3, white, mb, (int)(opacity *106 )); _canvas->px(x-3, y+3, white, mb, (int)(opacity *91 )); _canvas->px(x-2, y+3, white, mb, (int)(opacity *193 )); _canvas->px(x-1, y+3, white, mb, (int)(opacity *249 )); _canvas->px(x, y+3, white, mb, (int)(opacity *128 )); _canvas->px(x+1, y+3, white, mb, (int)(opacity *164 )); _canvas->px(x+2, y+3, white, mb, (int)(opacity *224 )); _canvas->px(x+3, y+3, white, mb, (int)(opacity *200 )); _canvas->px(x+4, y+3, white, mb, (int)(opacity *102 )); _canvas->px(x+5, y+3, white, mb, (int)(opacity *24 )); _canvas->px(x-6, y+4, white, mb, (int)(opacity *9 )); _canvas->px(x-5, y+4, white, mb, (int)(opacity *62 )); _canvas->px(x-4, y+4, white, mb, (int)(opacity *50 )); _canvas->px(x-3, y+4, white, mb, (int)(opacity *118 )); _canvas->px(x-2, y+4, white, mb, (int)(opacity *209 )); _canvas->px(x-1, y+4, white, mb, (int)(opacity *213 )); _canvas->px(x, y+4, white, mb, (int)(opacity *88 )); _canvas->px(x+1, y+4, white, mb, (int)(opacity *98 )); _canvas->px(x+2, y+4, white, mb, (int)(opacity *166 )); _canvas->px(x+3, y+4, white, mb, (int)(opacity *196 )); _canvas->px(x+4, y+4, white, mb, (int)(opacity *140 )); _canvas->px(x+5, y+4, white, mb, (int)(opacity *31 )); _canvas->px(x-5, y+5, white, mb, (int)(opacity *8 )); _canvas->px(x-4, y+5, white, mb, (int)(opacity *48 )); _canvas->px(x-3, y+5, white, mb, (int)(opacity *122 )); _canvas->px(x-2, y+5, white, mb, (int)(opacity *212 )); _canvas->px(x-1, y+5, white, mb, (int)(opacity *178 )); _canvas->px(x, y+5, white, mb, (int)(opacity *82 )); _canvas->px(x+1, y+5, white, mb, (int)(opacity *48 )); _canvas->px(x+2, y+5, white, mb, (int)(opacity *83 )); _canvas->px(x+3, y+5, white, mb, (int)(opacity *98 )); _canvas->px(x+4, y+5, white, mb, (int)(opacity *132 )); _canvas->px(x+5, y+5, white, mb, (int)(opacity *54 )); _canvas->px(x-5, y+6, white, mb, (int)(opacity *5 )); _canvas->px(x-4, y+6, white, mb, (int)(opacity *75 )); _canvas->px(x-3, y+6, white, mb, (int)(opacity *182 )); _canvas->px(x-2, y+6, white, mb, (int)(opacity *82 )); _canvas->px(x-1, y+6, white, mb, (int)(opacity *31 )); _canvas->px(x, y+6, white, mb, (int)(opacity *8 )); _canvas->px(x+1, y+6, white, mb, (int)(opacity *12 )); _canvas->px(x+2, y+6, white, mb, (int)(opacity *20 )); _canvas->px(x+3, y+6, white, mb, (int)(opacity *16 )); _canvas->px(x+4, y+6, white, mb, (int)(opacity *15 )); _canvas->px(x-4, y+7, white, mb, (int)(opacity *42 )); _canvas->px(x-3, y+7, white, mb, (int)(opacity *121 )); _canvas->px(x-2, y+7, white, mb, (int)(opacity *24 )); _canvas->px(x-3, y+8, white, mb, (int)(opacity *32 )); }
// // Created by gurumurt on 7/2/18. // #ifndef OPENCLDISPATCHER_ORDERED_AGGREGATION_H #define OPENCLDISPATCHER_ORDERED_AGGREGATION_H #endif //OPENCLDISPATCHER_ORDERED_AGGREGATION_H #include "include/headers.h" #include "include/Environment.h" #include "include/data_api.h" #include "include/kernel_api.h" #include "include/runtime_api.h" #include "include/Importkernel.h" #include <math.h> #include <chrono> enum device_num { cpu = 1, gpu = 0 }; enum agg_variant{ atomic = 0, branched_inc = 1, branched_dec = 2 }; double cpu_nanosecs, gpu_nanosecs; struct { string name; string src; int local_size; }av[3]; int ps_size; kernel_info BitonicSortKernel, PartialPrefixSum,FinalPS; void initialize_aggregates(){ av[0].name = "atomic_aggregate"; av[0].src = readKernelFile("kernels/ordered_aggregate_kernels/atomic_aggregate.cl"); av[0].local_size = 1; av[1].name = "atomic_sequential_aggregate"; av[1].src = readKernelFile("kernels/ordered_aggregate_kernels/atomic_sequential_aggregate.cl"); av[1].local_size = 1; av[2].name = "branched_aggregate"; av[2].src = readKernelFile("kernels/ordered_aggregate_kernels/branched_aggregate.cl"); av[2].local_size = 8192; // av[3].name = "partial_sequential_aggregate"; // av[3].src = readKernelFile("kernels/ordered_aggregate_kernels/branched_array_aggregate.cl"); // av[3].local_size = 8192; // // av[4].name = "partial_atomic_aggregate"; // av[4].src = readKernelFile("kernels/ordered_aggregate_kernels/partial_atomic_aggregate.cl"); // av[4].local_size = 1; } void initialize_kernels(){ BitonicSortKernel.name = "_kernel_bitonic_sort"; BitonicSortKernel.src = readKernelFile("kernels/sort_kernels/BitonicSort.cl"); BitonicSortKernel.local_size = 2; PartialPrefixSum.name = "_kernel_index_value"; PartialPrefixSum.src = readKernelFile("kernels/prefix_sum/IndexValue.cl"); PartialPrefixSum.local_size = 2; FinalPS.name = "FinalPS"; FinalPS.src = readKernelFile("kernels/prefix_sum/FinalPS.cl"); FinalPS.local_size = 2; initialize_aggregates(); } using namespace std::chrono; unsigned int *bm, *ps; unsigned int *cpu_res, *gpu_res; void unique_percent_generate(int size = 1024, int unique=2){ //Creating percentage unique values for(int i=1;i<size-unique;i++){ bm[i]=0; } for(int i=size-unique;i<size;i++){ bm[i]=1; } } void unique_percent_generate_val(int size = 1024, int unique=2){ //Creating percentage unique values for(int i=0;i<size-unique;i++){ bm[i]=1; } int add_val = 2; for(int i=size-unique;i<size;i++){ bm[i]=++add_val; } } void percent_generate_val(int size = 1024, int repeat= 2){ int add_num = 1; for(int i = 0; i < size; i++){ for(int j = 0; (j<repeat-1)&&(i<size-1);j++){ bm[i] = add_num; i++; } bm[i] = add_num; add_num++; } } void percent_generate(int size = 1024, int repeat= 2){ for(int i = 1; i < size; i++){ for(int j = 0; (j<repeat-1)&&(i<size-1);j++){ bm[i] = 0; i++; } bm[i] = 1; } } //generates dataset with repeat number of groups of random sizes void random_generate(int size = 1024, int repeat= 2){ } void prepare_data_val(int size = 1024, int repeat=2,short type=0){ bm = (unsigned int*)calloc((unsigned int)size,sizeof(unsigned int)); ps = (unsigned int*)calloc((unsigned int)size,sizeof(unsigned int)); if(type) unique_percent_generate_val(size,repeat); else percent_generate_val(size,repeat); // cout<<"input values"<<endl; // for(int i = 0;i<size;i++) // cout<<bm[i]<<endl; } void prepare_data(int size = 1024, int repeat=2,short type=0){ bm = (unsigned int*)calloc((unsigned int)size,sizeof(unsigned int)); ps = (unsigned int*)calloc((unsigned int)size,sizeof(unsigned int)); bm[0] = 0; if(type) unique_percent_generate(size,repeat); else percent_generate(size,repeat); //Derive prefix-sum from the results ps[0] = 0; for (int i = 1; i < size; i++) { ps[i] = ps[i - 1] + bm[i]; } // cout<<"Prefix sum"<<endl; // for(int i = 0;i<size;i++) // cout<<ps[i]<<endl; ps_size=ps[size-1]; cpu_res = (unsigned int*)calloc((unsigned int)ps[size- 1]+1,sizeof(unsigned int)); gpu_res = (unsigned int*)calloc((unsigned int)ps[size - 1]+1,sizeof(unsigned int)); } void add_arguments(int variant, int dev, int size, unsigned int* res){ cl_device_id d = device[dev][0]; add_data("PS", ps, d, size); if (variant != 1) add_data("BM", bm, d, size); add_data("res", res, d, ps[size - 1]+1); } string kernel_name; void add_variant_kernel(int variant, int dev){ cl_device_id d = device[dev][0]; kernel_name = av[variant].name; string kernel_source = av[variant].src; add_kernel(kernel_name, d, kernel_source); } bool flags_variant[2][2] = {{true,true},{true,true}}; double testTime; unsigned int* execute_variant(int variant=1, int dev=0, int size = 1024, int ls = 1,unsigned int* res = gpu_res){ vector<string> arguments; vector<int> param; testTime = 0; cl_device_id d = device[dev][0]; add_data("PS", ps, d, size); // if (variant == 2) // add_data("BM", bm, d, size); add_data("res", res, d, ps[size - 1] + 1); size_t ITERATOR = 8192; stringstream _sStream; _sStream << " -DITERATOR=" << ITERATOR; string kernel_name = av[variant].name; string kernel_source = av[variant].src; add_kernel(kernel_name, d, kernel_source,_sStream.str()); // cout<<"kernel source \n"<<kernel_source<<endl; arguments.push_back("PS"); // if (variant == 2) // arguments.push_back("BM"); arguments.push_back("res"); if(variant!=4) execute(d, kernel_name, arguments, param, (size_t) size/av[variant].local_size,(size_t) ls); else execute(d, kernel_name, arguments, param, (size_t) size/av[variant].local_size,(size_t) 32); testTime = nanoSeconds; unsigned int* r = get_data("res",d,ps[size - 1]+1); // cout<<r[0]<<"\t"; // // for(int i = 0;i<ps[size - 1]+1;i++){ // cout<<r[i]<<"\n"; // } clear_data(arguments,d); return r; } double cpu_time, gpu_time, total_time; double PPS_time, PS_time, AGG_time; int ITERATOR = 32; unsigned int* execute_variant_with_PS(int variant=1, int dev=0, int size = 1024, unsigned int* res = gpu_res){ vector<string> arguments; vector<int> param; cl_device_id d = device[dev][0]; //Compute PS first uint _m_offset_size = size/ITERATOR; uint *_m_offset_arr = (uint *) calloc((uint)_m_offset_size, sizeof(uint)); uint *_m_index_arr = (uint *) calloc((uint)size, sizeof(uint)); stringstream _sStream; _sStream << " -DOFFSET_SIZE=" << _m_offset_size << " -DITERATOR=" << ITERATOR; //add data to the device add_data("input_data", bm, d, size); add_data("index_array", _m_index_arr, d, size); add_data("offset_array", _m_offset_arr, d, _m_offset_size); arguments.push_back("input_data"); arguments.push_back("index_array"); arguments.push_back("offset_array"); //Add pps kernel add_kernel(PartialPrefixSum.name, d, PartialPrefixSum.src, _sStream.str()); //Execute partial prefix-sum execute(d, PartialPrefixSum.name, arguments, param, (size_t) _m_offset_size,(size_t) 1); total_time += nanoSeconds; PPS_time = nanoSeconds; arguments.clear(); arguments.push_back("index_array"); arguments.push_back("offset_array"); //Add final kernel add_kernel(FinalPS.name, d, FinalPS.src, _sStream.str()); //Execute partial prefix-sum execute(d, FinalPS.name, arguments, param, (size_t) _m_offset_size,(size_t) 1); total_time += nanoSeconds; PS_time = nanoSeconds; //Add code for executing variants unsigned int *ps = get_data("index_array",d,size); // cout<<"PS"<<endl; // for(int i=0;i<size;i++){ // cout<<ps[i]<<endl; // } //Create result buffer unsigned int result_size = ps[size - 1] + 1; ps_size= result_size; res = (unsigned int *) calloc((unsigned int)size, sizeof(unsigned int )); add_data("res", res, d, result_size); add_data("Prefix_sum", ps, d, size); arguments.clear(); arguments.push_back("Prefix_sum"); arguments.push_back("res"); //Change kernel add_kernel(av[variant].name,d,av[variant].src); if(variant!=4) execute(d, av[variant].name, arguments, param, (size_t) size/av[variant].local_size,(size_t) 32); else execute(d, av[variant].name, arguments, param, (size_t) size/av[variant].local_size,(size_t) 32); total_time += nanoSeconds; // print_data("res",d,ps[size - 1]+1); unsigned int* r = get_data("res",d,ps[size - 1]+1); // for(int i = 0;i<result_size; i++){ // cout<<r[i]<<endl; // } // cout<<"result"<<endl; // exit(0); clear_data(arguments,d); return r; } int compare; int aggregate_value; double gpu_PPS, gpu_PS; double cpu_PPS, cpu_PS; void compute_aggregate(int variant = 1, int data_size = 1024){ unsigned int* res1 = execute_variant_with_PS(variant,1,data_size,gpu_res); gpu_time = total_time; gpu_PPS = PPS_time; gpu_PS = PS_time; total_time = 0; PS_time = 0; PPS_time = 0; unsigned int* res2 = execute_variant_with_PS(variant,0,data_size,cpu_res); cpu_time = total_time; cpu_PPS = PPS_time; cpu_PS = PS_time; total_time = 0; PS_time = 0; PPS_time = 0; compare=memcmp(&res1[2],&res2[2],sizeof(unsigned int)*(ps[data_size - 1]-2)); compare = 0; } int* base_res; double baseline; void baseline_compute(int size){ baseline=0; high_resolution_clock::time_point t1,t2; t1 = high_resolution_clock::now(); // cout<<"Test"<<endl; base_res = new int[size]; // cout<<"Test"<<endl; int j=0; int local_val = 1; for(int i = 1; i<size;i++){ if(bm[i-1] != bm[i]){ base_res[j]=local_val; local_val = 0; j++; } local_val++; } // cout<<"Test"<<endl; t2 = high_resolution_clock::now(); baseline = duration_cast<nanoseconds>(t2 - t1).count(); // cout<<baseline<<endl; } void test_single_variant(){ cout<<"Baseline Test\n"; prepare_data_val((int)pow(2,25), 32, 1); baseline_compute((int)pow(2,25)); initialize_kernels(); initialize_aggregates(); setup_environment(); int data_size = 1024; int iterate = 1; // cout<<"Testing local aggregate\n"; prepare_data(data_size,32,1); // compute_aggregate(0,data_size); // compute_aggregate(1,data_size); // compute_aggregate(2,data_size); // compute_aggregate(3,data_size); compute_aggregate(0,data_size); // compute_aggregate(1,data_size); cout<<baseline<<"\t"<<cpu_time<<"\t"<<gpu_time<<endl; } void execute_repeats(){ int iterate = 1; int steps = 2; cout<<"PS-size\tDataSize\ti\tj\tCPU_PPS_AVG\tCPU_PS_AVG\tCPU_AVG\tGPU_PPS_AVG\tGPU_AVG\tBaseline\tCompare\tQ\n"; for(int data_size = (int) pow(2,6);data_size<=(int)pow(2,13);data_size*=steps) { for (int i = steps; i <= data_size; i *= steps) { for (int q = 0; q < 2; q++) { prepare_data_val(data_size, i, q); baseline_compute(data_size); for (int j = 0; j < 2; j++) { double cpu_average = 0; double cpu_pps_average = 0; double cpu_ps_average = 0; double gpu_average = 0; double gpu_pps_average = 0; double gpu_ps_average = 0; for (int z = 0; z < iterate; z++) { initialize_kernels(); setup_environment(); compute_aggregate(j, data_size); cpu_average += cpu_time; cpu_pps_average += cpu_PPS; cpu_ps_average += cpu_PS; gpu_average += gpu_time; gpu_pps_average += gpu_PPS; gpu_ps_average += gpu_PS; } cout << ps_size << "\t" << data_size << "\t" << i << "\t" << j << "\t" << cpu_pps_average / iterate << "\t" << cpu_ps_average / iterate << "\t" << cpu_average / iterate << "\t" << gpu_ps_average / iterate << "\t" << gpu_pps_average / iterate << "\t" << gpu_average / iterate << "\t" << baseline << "\t" << compare << "\t" << q << "\n"; } } } } } void DimensionsOrderedAggregation(){ initialize_aggregates(); size_t powerSize = 20; size_t inputDataSize = pow(2,powerSize); size_t avgSize = 10; //average iteration size short compareResult=0; cout<<"Input\tValuesPerGroup\tVariant\tCompareResult\tWorkGroupSize\tExecutionTime\tTestResult"<<endl; // for(inputDataSize=pow(2,18);inputDataSize<=pow(2,powerSize);inputDataSize*=2){ // for(size_t groupSize = 32; groupSize <=inputDataSize;groupSize*=2){ prepare_data(inputDataSize, 1, 0); for(int i = 0;pow(2,i)<=8192;i++){ for(int variant =0;variant<=4;variant++) { unsigned int *re = execute_variant(variant, 1, inputDataSize, pow(2,i)); double timer = 0; for (int j = 0; j < avgSize; j++) { unsigned int *res2 = execute_variant(variant, 1, inputDataSize, pow(2,i)); timer += nanoSeconds; compareResult = memcmp(re, res2, sizeof(unsigned int) * (ps[inputDataSize - 1])); } cout << inputDataSize << "\t" << "32" << "\t"<< variant << "\t" << compareResult << "\t" << pow(2,i) << "\t" << timer / avgSize << "\t" << re[0] << endl; } } // } } //Choose API double choose(int variant=1, int dev=0, int size = 1024){ string kernelFile = "kernels/ordered_aggregate_kernels/"; string name,src; int local_size; switch(variant){ case 0: name = "atomic_aggregate"; src = readKernelFile(kernelFile + name + ".cl"); local_size = 1; break; case 1: name = "atomic_sequential_aggregate"; src = readKernelFile(kernelFile + name + ".cl"); local_size = 32; break; case 2: name = "branched_aggregate"; src = readKernelFile(kernelFile + name + ".cl"); local_size = 32; break; case 3: name = "partial_sequential_aggregate"; src = readKernelFile(kernelFile + name + ".cl"); local_size = 32; break; case 4: name = "partial_atomic_aggregate"; src = readKernelFile(kernelFile + name + ".cl"); local_size = 1; break; default: cout<<"Variant not found"<<endl; return -1; } vector<string> arguments; vector<int> param; cl_device_id d = device[dev][0]; uint _m_offset_size = (uint) size/ITERATOR; uint *_m_offset_arr = (uint *) calloc((uint)_m_offset_size, sizeof(uint)); uint *_m_index_arr = (uint *) calloc((uint)size, sizeof(uint)); stringstream _sStream; _sStream << " -DOFFSET_SIZE=" << _m_offset_size << " -DITERATOR=" << ITERATOR; //add data to the device add_data("input_data", bm, d, size); add_data("index_array", _m_index_arr, d, size); add_data("offset_array", _m_offset_arr, d, _m_offset_size); arguments.push_back("input_data"); arguments.push_back("index_array"); arguments.push_back("offset_array"); //Add pps kernel add_kernel(PartialPrefixSum.name, d, PartialPrefixSum.src, _sStream.str()); //Execute partial prefix-sum execute(d, PartialPrefixSum.name, arguments, param, (size_t) _m_offset_size,(size_t) 1); total_time += nanoSeconds; arguments.clear(); arguments.push_back("index_array"); arguments.push_back("offset_array"); //Add final kernel add_kernel(FinalPS.name, d, FinalPS.src, _sStream.str()); //Execute partial prefix-sum execute(d, FinalPS.name, arguments, param, (size_t) _m_offset_size,(size_t) 1); total_time += nanoSeconds; //Add code for executing variants unsigned int *ps = get_data("index_array",d,size); //Create result buffer unsigned int result_size = ps[size - 1] + 1; ps_size= result_size; unsigned int *res = (unsigned int *) calloc((unsigned int)size, sizeof(unsigned int )); add_data("res", res, d, result_size); add_data("Prefix_sum", ps, d, size); arguments.clear(); arguments.push_back("Prefix_sum"); arguments.push_back("res"); //Change kernel add_kernel(av[variant].name,d,av[variant].src); if(variant!=4) execute(d, av[variant].name, arguments, param, (size_t) size/local_size,(size_t) 1); else execute(d, av[variant].name, arguments, param, (size_t) size/local_size,(size_t) 32); total_time += nanoSeconds; clear_data(arguments,d); return total_time; }
#pragma once #include"ProductionStack.h" #include<unordered_map> #include"ProductionManager.h" #include<fstream> class ParserState { public: ParserState(int state_ID); virtual ~ParserState(); void init(); virtual ParserState* transfer(string input); virtual void calFollowSet(ProductionStack& p, set<ProductionStack>& fps ) = 0; //计算状态内的一个表达式的follow集合 virtual void stateGrow(ProductionManager& pm) = 0; virtual bool operator==( const ParserState& p)const= 0; //必须要重载一个==函数 virtual bool operator<(const ParserState& p)const=0; virtual void printState()const; virtual void outputStateAsFile(ofstream& fout)const; bool addNextState(string key, ParserState* s); bool addProduction(ProductionStack &p); //注意,这里采用了值传递,也就是说每隔state对象内部保存有独立的productionStack对象副本!!!可能会出错 bool addProductionAsMerge(ProductionStack& p); // 再强化一下C++的值传递和引用传递的区别特别是对于类来说 const unordered_map<string, ParserState*>& getNextStates()const; static set<string> convertFirstSetToString(set<Node*>& firstset); ATTRIBUTE_READ_ONLY(set<ProductionStack>, productions); ATTRIBUTE_MEMBER_FUNC(int, stateID) ATTRIBUTE_MEMBER_FUNC(bool,isProcess) protected: bool isProcess; int stateID; //stateID >=0 有效, stateID = -1时,表示不错在该状态, stateID=-2是表示状态未分配id值 set<ProductionStack> productions; //集合 unordered_map<string, ParserState*> nextStates; };
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: board_manager.h * Author: raphael * * Created on May 23, 2020, 9:35 AM */ #ifndef BOARD_MANAGER_H #define BOARD_MANAGER_H #include <unistd.h> #include "core_simulation.h" #include "mydevices.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif class Board_manager{ public: void connect_to_Internet(Board& ma_board); void connect_to_Bluetooth(); int compute_mean_pulse_10values(Board& ma_board); void send_music_request(Board& ma_board, int mean_pulse); void send_music_to_bluetooth_device(Board& ma_board, Bibliotheque& ma_biblio,char* music); }; #endif /* BOARD_MANAGER_H */
#include "EditShape.h" void EditShape::move(ofVec2f dir) { if (Mask::selShape > -1) { MaskElem& elem = Mask::elems[Mask::selShape]; if (Mask::selPoints.size() > 0) { for (vector<vector<int>>::iterator it = Mask::selPoints.begin(); it != Mask::selPoints.end(); ++it) { MyPoint& point = elem.points[(*it)[0]]; if ((*it)[1] == 1) point.cp1 += dir; else if ((*it)[1] == 2) point.cp2 += dir; else point.pos += dir; } } else { for (vector<MyPoint>::iterator it = elem.points.begin(); it != elem.points.end(); ++it) it->translate(dir); } elem.update(); } } void EditShape::scale(bool up, bool shift) { if (Mask::selShape > -1) { MaskElem& elem = Mask::elems[Mask::selShape]; ofPoint middle = elem.shape.getCentroid2D(); float scaleFactor = shift ? 0.005 : 0.05; for (vector<MyPoint>::iterator it = elem.points.begin(); it != elem.points.end(); ++it) { ofVec2f dist = (*it).pos - middle; if (up) (*it).pos += dist * scaleFactor; else (*it).pos -= dist * scaleFactor; if ((*it).isCurve) { dist = (*it).cp1 - middle; if (up) (*it).cp1 += dist * scaleFactor; else (*it).cp1 -= dist * scaleFactor; dist = (*it).cp2 - middle; if (up) (*it).cp2 += dist * scaleFactor; else (*it).cp2 -= dist * scaleFactor; } } elem.update(); } } void EditShape::addPoint() { if (Mask::selShape > -1 && Mask::selPoints.size() > 0) { MaskElem& elem = Mask::elems[Mask::selShape]; int selPoint = Mask::selPoints[0][0]; MyPoint point = elem.points[selPoint]; int index = selPoint + 1; if (index > elem.points.size() - 1) index = 0; MyPoint nextPoint = elem.points[index]; ofVec2f newPoint = ofVec2f(point.pos); newPoint -= nextPoint.pos; newPoint *= 0.5; newPoint += nextPoint.pos; elem.points.insert(elem.points.begin() + index, MyPoint(newPoint)); elem.update(); } } void EditShape::addRect() { MaskElem elem; elem.points.push_back(MyPoint(ofVec2f(ofGetWidth() / 2 - 100, ofGetHeight() / 2 - 100))); elem.points.push_back(MyPoint(ofVec2f(ofGetWidth() / 2 + 100, ofGetHeight() / 2 - 100))); elem.points.push_back(MyPoint(ofVec2f(ofGetWidth() / 2 + 100, ofGetHeight() / 2 + 100))); elem.points.push_back(MyPoint(ofVec2f(ofGetWidth() / 2 - 100, ofGetHeight() / 2 + 100))); elem.update(); Mask::elems.push_back(elem); Mask::selShape = Mask::elems.size() - 1; Mask::selChange = true; } void EditShape::addCircle() { MaskElem elem; float c = 0.551915024494 * 100; ofVec2f p00 = ofVec2f(ofGetWidth() / 2, ofGetHeight() / 2 + 100); ofVec2f p01 = ofVec2f(ofGetWidth() / 2 + c, ofGetHeight() / 2 + 100); ofVec2f p02 = ofVec2f(ofGetWidth() / 2 + 100, ofGetHeight() / 2 + c); ofVec2f p10 = ofVec2f(ofGetWidth() / 2 + 100, ofGetHeight() / 2); ofVec2f p11 = ofVec2f(ofGetWidth() / 2 + 100, ofGetHeight() / 2 - c); ofVec2f p12 = ofVec2f(ofGetWidth() / 2 + c, ofGetHeight() / 2 - 100); ofVec2f p20 = ofVec2f(ofGetWidth() / 2, ofGetHeight() / 2 - 100); ofVec2f p21 = ofVec2f(ofGetWidth() / 2 - c, ofGetHeight() / 2 - 100); ofVec2f p22 = ofVec2f(ofGetWidth() / 2 - 100, ofGetHeight() / 2 - c); ofVec2f p30 = ofVec2f(ofGetWidth() / 2 - 100, ofGetHeight() / 2); ofVec2f p31 = ofVec2f(ofGetWidth() / 2 - 100, ofGetHeight() / 2 + c); ofVec2f p32 = ofVec2f(ofGetWidth() / 2 - c, ofGetHeight() / 2 + 100); elem.points.push_back(MyPoint(p30, p32, p31)); elem.points.push_back(MyPoint(p20, p22, p21)); elem.points.push_back(MyPoint(p10, p12, p11)); elem.points.push_back(MyPoint(p00, p02, p01)); elem.update(); Mask::elems.push_back(elem); Mask::selShape = Mask::elems.size() - 1; Mask::selChange = true; } void EditShape::copyShape() { if (Mask::selShape > -1) { Mask::elems.push_back(MaskElem(Mask::elems[Mask::selShape])); Mask::selShape = Mask::elems.size() - 1; Mask::selChange = true; } } void EditShape::removePoint() { if (Mask::selShape > -1 && Mask::selPoints.size() > 0) { MaskElem& elem = Mask::elems[Mask::selShape]; if (elem.points.size() > 3) { int selPoint = Mask::selPoints[0][0]; elem.points.erase(elem.points.begin() + selPoint); elem.update(); Mask::selPoints.clear(); } } } void EditShape::removeShape() { if (Mask::selShape > -1) { Mask::elems.erase(Mask::elems.begin() + Mask::selShape); Mask::selShape = -1; Mask::selChange = true; } } void EditShape::toggleSpline() { if (Mask::selShape > -1 && Mask::selPoints.size() > 0) { int selPoint = Mask::selPoints[0][0]; MaskElem& elem = Mask::elems[Mask::selShape]; MyPoint& point = elem.points[selPoint]; int index = selPoint - 1; if (index < 0) index = elem.points.size() - 1; MyPoint& lastPoint = elem.points[index]; if (!point.isCurve) { ofVec2f cp1 = ofVec2f(lastPoint.pos); cp1 -= point.pos; cp1 *= 0.6; cp1 += point.pos; ofVec2f cp2 = ofVec2f(point.pos); cp2 -= lastPoint.pos; cp2 *= 0.6; cp2 += lastPoint.pos; point.makeCurve(cp1, cp2); } else point.isCurve = false; elem.update(); } } void EditShape::moveShapeUp(bool up) { if (Mask::selShape > -1 && Mask::elems.size() > 1) { int nextIndex; if (up) { nextIndex = Mask::selShape + 1; if (nextIndex >= Mask::elems.size()) nextIndex = 0; } else { nextIndex = Mask::selShape - 1; if (nextIndex < 0) nextIndex = Mask::elems.size() - 1; } iter_swap(Mask::elems.begin() + Mask::selShape, Mask::elems.begin() + nextIndex); Mask::selShape = nextIndex; } }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Path.hpp" #include "Core/Singleton.hpp" namespace Push { class Settings : public Singleton<Settings> { public: void SetScreenWidth(float width); float GetScreenWidth() const; void SetScreenHeight(float height); float GetScreenHeight() const; void SetScreenScale(float height); float GetScreenScale() const; void SetPath(BundleType type, const Path& path, bool absolute); const Path& GetPath(BundleType type) const; Path GetPath(BundleType type, const Path& path) const; private: Path m_resourcePath; Path m_settingsPath; float m_screenWidth = 1024.f; float m_screenHeight = 768.f; float m_screenScale = 1.f; }; }
//使用するヘッダーファイル #include"GameL\DrawTexture.h" #include"GameL\WinInputs.h" #include"GameL\SceneManager.h" #include"GameL\HitBoxManager.h" #include "GameL\Audio.h" #include"GameHead.h" #include"ObjBoss2.h" //使用するネームスペース using namespace GameL; extern bool m_start_boss; CObjBoss2::CObjBoss2(float x, float y) { m_px = x; m_py = y; } //イニシャライズ void CObjBoss2::Init() { m_vx = 0.0f; //移動ベクトル m_vy = 0.0f; m_posture = 0.0f; //右向き0.0f,左向き1,0f m_time = 0; m_time_ud = 0; m_ani_time = 0; m_ani_frame = 1; //静止フレームを初期化する m_speed_power = 0.5f;//通常速度 m_ani_max_time = 4; //アニメーション間隔幅 m_boss_hp = 12; //敵のヒットポイント(最大12) m_damage = 2; m_time_die = 0; m_move = false; //true=右 false=左 m_del = false; m_time_d = 0; //blockとの追突状態確認用 m_hit_up = false; m_hit_down = false; m_hit_left = false; m_hit_right = false; m_inputf = true; // true = 入力可 false = 入力不可 //当たり判定用のHitBoxを作成 Hits::SetHitBox(this, m_px, m_py, 150, 75, ELEMENT_ENEMY, OBJ_BOSS_SECOND, 1); } //アクション void CObjBoss2::Action() { //摩擦 m_vx += -(m_vx * 0.098); m_vy += -(m_vy * 0.098); //自由落下運動 //m_vy += 9.8 / (16.0f); //自身のHitBoxを持ってくる CHitBox* hit = Hits::GetHitBox(this); //ダミー int d; //ブロックとの当たり判定実行 CObjBlock*pb = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); pb->BlockHitBoss2(&m_px, &m_py, false, &m_hit_up, &m_hit_down, &m_hit_left, &m_hit_right, &m_vx, &m_vy, &d ); //位置の更新 m_px += m_vx; m_py += m_vy; m_speed_power = 0.0f; //スピードを0にする if (m_start_boss == false) { //通常速度 m_speed_power = 0.5f; m_ani_max_time = 4; m_time++; if (m_time > 80) { m_time = 0; //オブジェクト作成 CObjBubble* objbu = new CObjBubble(m_px, m_py); Objs::InsertObj(objbu, OBJ_BUBBLE, 100); Audio::Start(8); //音 } } //ブロック衝突で向き変更 /*if (m_hit_left == true) { m_move = true; } if (m_hit_right == true) { m_move = false; }*/ if (m_hit_down == true) { m_move = true; } if (m_hit_up == true) { m_move = false; } //inputフラグがオンの時に移動を可能にする if (m_inputf == true) { //方向 if (m_move == false) { m_vy += m_speed_power; m_posture = 1.0f; m_ani_time += 1; } else if (m_move == true) { m_vy -= m_speed_power; m_posture = 0.0f; m_ani_time += 1; } } if (m_ani_time > m_ani_max_time) { m_ani_frame += 1; m_ani_time = 0; } if (m_ani_frame == 4) { m_ani_frame = 0; } //攻撃を受けたら体力を減らす //主人公とATTACK系統との当たり判定 if (hit->CheckElementHit(ELEMENT_ATTACK) == true) { //ノックバック処理 if (m_posture == 0.0f) { //m_vy = -10; //m_vx += 15; } if (m_posture == 1.0f) { //m_vy = -10; //m_vx -= 15; } Audio::Start(4); //ダメージ音 m_time_d = 30; //敵の無敵時間をセット m_boss_hp -= 1; //敵の体力を減らす } if (m_time_d > 0) { m_time_d--; if (m_time_d <= 0) { m_time_d = 0; } } //HPが0以下の時に消滅処理に移行する if (m_del == false && m_boss_hp <= 0) { CObjBlock* block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); block->Setwall(true); m_time_die = 30; m_inputf = false; //動きを制御 m_del = true; m_time_dead = 80; //死亡時間をセット m_vy += 9.8 / (16.0f); //自由落下運動 } //ブロック情報を持ってくる CObjBlock*block = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //HitBoxの位置の変更 hit->SetPos(m_px + block->GetScrollX(), m_py -32 + block->GetScrollY()); if (m_del == true) { hit->SetInvincibility(true); //無敵にする m_eff_flag = true; //画像切り替え用フラグ m_speed_power = 0.0f; //動きを止める m_start_boss = true; } if (m_time_dead > 0) { m_time_dead--; if (m_time_dead <= 0) { this->SetStatus(false); //画像の削除 Hits::DeleteHitBox(this); //ヒットボックスの削除 m_time_dead = 0; Scene::SetScene(new CSceneStageClear()); } } } //ドロー void CObjBoss2::Draw() { int AniData[4] = { 0,1,2,3, }; //描写カラー情報 float c[4] = { 1.0f,1.0f,1.0f,1.0f, }; float a[4] = { 10.0f,0.6f,0.6f,0.7f }; RECT_F src;//描写元切り取り位置 RECT_F dst;//描写先表示位置 //ブロック情報を持ってくる CObjBlock*pb = (CObjBlock*)Objs::GetObj(OBJ_BLOCK); //表示位置の設定 dst.m_top = 0.0f + m_py - 32 + pb->GetScrollY(); dst.m_left = (150.0f * m_posture) + m_px + pb->GetScrollX(); dst.m_right = (150 - 150.0f *m_posture) + m_px + pb->GetScrollX(); dst.m_bottom = 100.0f + m_py - 32 + pb->GetScrollY(); //敵の状態で描画を変更 if (m_del == true) { //切り取り位置の設定 src.m_top = 20.0f; src.m_left = 820.0f; src.m_right = 1020.0f; src.m_bottom = 110.0f; if (m_eff_flag == true) Draw::Draw(15, &src, &dst, c, 0.0f); } else { //切り取り位置の設定 src.m_top = 0.0f; src.m_left = 0.0f + AniData[m_ani_frame] * 150; src.m_right = 150.0f + AniData[m_ani_frame] * 150; src.m_bottom = 100.0f; //0番目に登録したグラフィックをsrc・dst・cの情報を元に描写 if (m_time_d > 0) { Draw::Draw(12, &src, &dst, a, 0.0f); } else { Draw::Draw(12, &src, &dst, c, 0.0f); } } }
#include "PassedTest.h" #include "JsonArraySerialization.h" // :: Constants :: const QString SCALES_JSON_KEY = "scales"; // :: Lifecycle :: PassedTest::PassedTest(int id) : PassedTestPreview() { setId(id); } // :: Serializable :: QJsonObject PassedTest::toJson() const { auto json = PassedTestPreview::toJson(); json[SCALES_JSON_KEY] = jsonArrayFromSerializableObjects(getScales()); return json; } void PassedTest::initWithJsonObject(const QJsonObject &json) { PassedTestPreview::initWithJsonObject(json); if (json.contains(SCALES_JSON_KEY) && json[SCALES_JSON_KEY].isArray()) { auto jsonArray = json[SCALES_JSON_KEY].toArray(); setScales(serializableObjectsFromJsonArray<QList, ScaleStatistics>(jsonArray)); } } // :: Public accessors :: // :: Scales :: QList<ScaleStatistics> PassedTest::getScales() const { return m_scales; } void PassedTest::setScales(const QList<ScaleStatistics> &scales) { m_scales = scales; }
/** * Copyright (c) 2022, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file sql_help.hh */ #ifndef sql_help_hh #define sql_help_hh #include <map> #include "base/attr_line.hh" #include "help_text.hh" extern string_attr_type<void> SQL_COMMAND_ATTR; extern string_attr_type<void> SQL_KEYWORD_ATTR; extern string_attr_type<void> SQL_IDENTIFIER_ATTR; extern string_attr_type<void> SQL_FUNCTION_ATTR; extern string_attr_type<void> SQL_STRING_ATTR; extern string_attr_type<void> SQL_NUMBER_ATTR; extern string_attr_type<void> SQL_OPERATOR_ATTR; extern string_attr_type<void> SQL_PAREN_ATTR; extern string_attr_type<void> SQL_GARBAGE_ATTR; extern string_attr_type<void> SQL_COMMENT_ATTR; void annotate_sql_statement(attr_line_t& al_inout); extern std::multimap<std::string, help_text*> sqlite_function_help; std::string sql_keyword_re(); std::vector<const help_text*> find_sql_help_for_line(const attr_line_t& al, size_t x); #endif
/** * Peripheral Definition File * * IWDG - Independent watchdog * * MCUs containing this peripheral: * - STM32F1xx * - STM32F2xx * - STM32F4xx * - STM32L1xx */ #pragma once #include <cstdint> #include <cstddef> namespace io { struct Iwdg { /** Key register */ struct Kr { Kr(const uint32_t raw=0) { r = raw; } static const uint32_t WRITE_ACCESS = 0x00005555; static const uint32_t REFRESH = 0x0000aaaa; static const uint32_t START = 0x0000cccc; union { uint32_t r; uint32_t KEY; // Key value uint16_t KEY16; // 16 bit access }; }; /** Prescaler register */ struct Pr { Pr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t PRE : 3; // prescaler divider uint32_t : 29; }; struct Pre { static const uint32_t DIV_4 = 0; static const uint32_t DIV_8 = 1; static const uint32_t DIV_16 = 2; static const uint32_t DIV_32 = 3; static const uint32_t DIV_64 = 4; static const uint32_t DIV_128 = 5; static const uint32_t DIV_256 = 6; }; union { uint32_t r; uint32_t PRE; // 32 bit access uint16_t PRE16; // 16 bit access Bits b; }; }; /** Reload register */ struct Rlr { Rlr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t RL : 12; // Watchdog counter reload value uint32_t : 20; }; union { uint32_t r; uint32_t RL; // 32 bit access uint16_t RL16; // 16 bit access Bits b; }; }; /** Status register */ struct Sr { Sr(const uint32_t raw=0) { r = raw; } struct Bits { const uint32_t PVU : 1; // Watchdog prescaler value update const uint32_t RVU : 1; // Watchdog counter reload value update uint32_t : 30; }; union { uint32_t r; Bits b; }; }; volatile Kr KR; // Key register volatile Pr PR; // Prescaler register volatile Rlr RLR; // Reload register volatile Sr SR; // Status register }; }
// // Amina Shaikym 201627535 // #include "am_pm_clock.h" am_pm_clock::am_pm_clock(): hours {12}, minutes{0}, seconds{0}, am{true}{} am_pm_clock::am_pm_clock(unsigned int hrs, unsigned int mins, unsigned int secs, bool am_val): hours(hrs), minutes(mins), seconds(secs), am(am_val){} am_pm_clock::am_pm_clock(const am_pm_clock &clock): hours(clock.hours), minutes(clock.minutes), seconds(clock.seconds), am(clock.am){} am_pm_clock& am_pm_clock::operator=(const am_pm_clock& clock){ this->hours=clock.hours; this->minutes=clock.minutes; this->seconds=clock.seconds; this->am=clock.am; return *this; } void am_pm_clock::toggle_am_pm(){ if(am){ am=false; }else{ am=true; } } void am_pm_clock::reset() { am= true; hours=12; seconds=0; minutes=0; } void am_pm_clock::advance_one_sec() { ++seconds; if(seconds==60) { seconds=0; minutes++; if(minutes==60) { minutes=0; hours++; if(hours==12) { toggle_am_pm(); } if(hours>12) { hours=hours-12; } } } } void am_pm_clock::advance_n_secs(unsigned int n) { for(size_t i=0;i<n;i++) { advance_one_sec(); } } unsigned int am_pm_clock::get_hours() const { return hours; } void am_pm_clock::set_hours(unsigned int hrs) { if(hrs>12||hrs<0) { throw std::invalid_argument("NOT LEGAL HOUR VALUE"); } hours=hrs; } unsigned int am_pm_clock::get_minutes() const{ return minutes; } void am_pm_clock::set_minutes(unsigned int mins){ if(mins>59||mins<0) { throw std::invalid_argument("NOT LEGAL MINUTE VALUE"); } minutes=mins; } unsigned int am_pm_clock::get_seconds() const { return seconds; } void am_pm_clock::set_seconds(unsigned int secs){ if(secs>59||secs<0) { throw std::invalid_argument("NOT LEGAL SECOND VALUE"); } seconds=secs; } bool am_pm_clock::is_am() const { return am; } void am_pm_clock::set_am(bool am_val){ am=am_val; } am_pm_clock::~am_pm_clock(){}
#include<iostream> #include<stack> #include<string> #include"Task_2.cpp" using namespace std; printInfix(Node x) { Node l; Node r; l=x->left; r=x-> if(!isOperator(l.p)) } int main() { printInfix(main3()); return 0; }
#ifndef MYTABLEWIDGET_H #define MYTABLEWIDGET_H #include <QObject> #include <QtCore> #include <QtGui> #include <QtWidgets> #include "NoFocusDelegate.h" class myTableWidget : public QTableWidget { Q_OBJECT public: explicit myTableWidget(QWidget *parent = 0); QTableWidgetItem * itemSetting(int row, int col, QString text, bool center = true); void removeAllItems(); QList<QTableWidgetItem *> checkedItems(int col = 0); QStringList checkedItemsList(int id, int col = 0); QStringList speicalList(QString arg, int spe, bool ok = true, int col = 0); int countByArg(int column, QString arg); QTableWidgetItem *findItemByArg(int column, QString arg); int countChecked(int column = 0); bool containByCol(int column, QString arg); void setAllItemText(QString arg = QString()); QString currentItemText(); QString columnItemText(int column); public Q_SLOTS: void onScrollValueChanged(int value); signals: void itemSender(QTableWidgetItem *item); void isTristate(bool tristate); void onItemSelectionChanged(Qt::CheckState state); protected: void contextMenuEvent(QContextMenuEvent *event); private: // CheckBoxHeaderView *cHeaderView; QScrollBar *vScrollBar; }; #endif // MYTABLEWIDGET_H
#pragma once #include <SWI-Prolog.h> #include <initializer_list> #include <map> #include <ostream> #include <string> #include <vector> class PrologTermHolder; class PrologAtom; class PrologString; class PrologVariable; class PrologList; class PrologFunctor; namespace std { template<> struct std::less<PrologTermHolder> { bool operator()( const PrologTermHolder& lhs, const PrologTermHolder& rhs) const; }; } class PrologLifetime { public: static void begin(int argc, char *argv[]); static void end(); }; class PrologTermHolder { public: PrologTermHolder(term_t term); PrologAtom asAtom() const; PrologString asString() const; PrologVariable asVariable() const; PrologList asList() const; PrologFunctor asFunctor() const; term_t term() const; protected: term_t term_; }; class PrologTerm : public PrologTermHolder { friend std::ostream &operator<<( std::ostream &os, const PrologTerm &printable); public: typedef std::function<void (std::ostream&, term_t)> PrintFnTy; static PrologTerm from(term_t term); void print(std::ostream &os) const; protected: PrologTerm(PrintFnTy printFn); PrologTerm(term_t term, PrintFnTy printFn); private: PrintFnTy printer_; }; class PrologAtom : public PrologTerm { public: PrologAtom(std::string name); PrologAtom(const char *name); PrologAtom(term_t term); static PrologAtom fromPrologAtom(atom_t atom); std::string str() const; protected: PrologAtom(); }; class PrologString : public PrologTerm { public: PrologString(std::string string); PrologString(const char *string); PrologString(term_t term); std::string str() const; }; class PrologVariable : public PrologTerm { public: PrologVariable(); PrologVariable(term_t term); }; class PrologList : public PrologTerm { public: PrologList(std::vector<PrologTerm> terms); PrologList(term_t term); }; class PrologTermVector : public PrologTerm { public: PrologTermVector(size_t size); PrologTermVector(std::initializer_list<PrologTerm> args); PrologTermVector(std::vector<PrologTerm> args); size_t size() const; PrologTermHolder at(size_t idx) const; protected: PrologTermVector(term_t term, size_t size); private: size_t size_; }; class PrologFunctor : public PrologTerm { public: PrologFunctor(std::string name, PrologTermVector args); PrologFunctor(term_t term); std::string name() const; size_t arity() const; PrologTermVector args() const; }; class PrologConjunction : public PrologFunctor { public: PrologConjunction(PrologList args); }; class PrologSolution : public std::map<PrologTermHolder, PrologTerm> { public: typedef std::map<PrologTermHolder, PrologTerm> SolutionTy; PrologSolution(SolutionTy solution); PrologTerm get(PrologTermHolder variable) const; }; class PrologQuery { public: PrologQuery(std::string predicate, PrologTermVector terms); PrologQuery(PrologFunctor functor); std::vector<PrologSolution> solutions() const; std::vector<PrologSolution> solutions(PrologTermVector terms) const; void execute() const; private: std::string predicate_; PrologTermVector terms_; }; class PrologCall { public: static void run(PrologFunctor funcor); static void fact(PrologTerm term); static void consult(const char *filename); static void compile(const char *descriptor, std::string program); };
#include "ThrowProcess.h" #include "HallHandler.h" #include "Logger.h" #include "Configure.h" #include "GameServerConnect.h" #include "PlayerManager.h" #include "GameCmd.h" #include "ProcessManager.h" #include "RobotDefine.h" #include <string> using namespace std; ThrowProcess::ThrowProcess() { this->name = "ThrowProcess"; } ThrowProcess::~ThrowProcess() { } int ThrowProcess::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { HallHandler* clientHandler = dynamic_cast<HallHandler*> (client); if (clientHandler == NULL) return 0; Player* player = PlayerManager::getInstance().getPlayer(clientHandler->uid); if (player == NULL) return 0; OutputPacket requestPacket; requestPacket.Begin(CLIENT_MSG_THROW_CARD, player->id); requestPacket.WriteInt(player->id); requestPacket.WriteInt(player->tid); requestPacket.End(); this->send(clientHandler, &requestPacket); ULOGGER(E_LOG_DEBUG, player->id) << "name=" << player->name << " money=" << player->money << " currmax=" << player->currmax; return 0; } int ThrowProcess::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { HallHandler* hallHandler = dynamic_cast<HallHandler*>(clientHandler); Player* player = PlayerManager::getInstance().getPlayer(hallHandler->uid); int retcode = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); if(retcode < 0 || player == NULL) { ULOGGER(E_LOG_WARNING, hallHandler->uid) << "retcode=" << retcode << " retmsg=" << retmsg; if(retcode == -1) return 0; return EXIT; } int uid = inputPacket->ReadInt(); short ustatus = inputPacket->ReadShort(); int tid = inputPacket->ReadInt(); short tstatus = inputPacket->ReadShort(); player->currRound = inputPacket->ReadByte(); int throwid = inputPacket->ReadInt(); int64_t betcoin = inputPacket->ReadInt64(); int64_t money = inputPacket->ReadInt64(); player->currmax = inputPacket->ReadInt64(); int nextid = inputPacket->ReadInt(); int64_t sumbetcoin = inputPacket->ReadInt64(); int64_t selfmoney = inputPacket->ReadInt64(); player->optype = inputPacket->ReadShort(); int64_t sumpool = inputPacket->ReadInt64(); ULOGGER(E_LOG_DEBUG, uid) << "user status:" << ustatus << " tid:" << tid << " table status:" << tstatus << " nextid:" << nextid; if (tid != player->tid) { ULOGGER(E_LOG_INFO, uid) << "[robot exit] tid=" << tid << " not equal player->tid=" << player->tid; return EXIT; } for(int i = 0; i < GAME_PLAYER; ++i) { if(player->player_array[i].id == throwid) { player->player_array[i].hascard = 0; break; } } if (uid == nextid) { player->startBetCoinTimer(uid, ROBOT_BASE_BET_TIMEROUT + rand() % ROBOT_RAND_BET_TIMEROUT); ULOGGER(E_LOG_DEBUG, uid) << "startBetCoinTimer"; } return 0; } REGISTER_PROCESS(CLIENT_MSG_THROW_CARD, ThrowProcess)
#include <stdint.h> #include "crc32c.h" namespace leveldb { namespace crc32c { uint32_t Extend(uint32_t init_crc, const char* data, size_t n) { return crc32c_append(init_crc, (const unsigned char *)data, n); } } // namespace crc32c } // namespace leveldb
#include <bits/stdc++.h> using namespace std; struct tNode{ int data; tNode *left; tNode *right; tNode(int x):data(x),left(NULL),right(NULL){} }; class Solution{ public: //方法1 破坏原树(递归方法) tNode* mirror(tNode *root){ if(!root){ return root; } tNode *left = mirror(root->left); tNode *right = mirror(root->right); root->left = right; root->right = left; return root; } //方法1 破坏原树(非递归方法) tNode* mirror2(tNode *root){ if(!root){ return root; } stack<tNode*> node_stack; node_stack.push(root); while(!node_stack.empty()){ tNode *cur = node_stack.top(); node_stack.pop(); tNode *temp = cur->left; cur->left = cur->right; cur->right = temp; if(cur->right){ node_stack.push(cur->right); } if(cur->left){ node_stack.push(cur->left); } } return root; } //2.不破坏原树,返回新的镜像(递归) tNode* mirrorCopy(tNode *root){ if(!root){ return root; } tNode *newNode = new tNode(root->data); newNode->right = mirrorCopy(root->left); newNode->left = mirrorCopy(root->right); return newNode; } //2.不破坏原树,返回新的镜像(非递归) tNode* mirrorCopy2(tNode *root){ if(!root){ return root; } tNode *newRoot = new tNode(root->data); stack<tNode*> node_stack; stack<tNode*> node_stack_copy; node_stack.push(root); node_stack_copy.push(newRoot); while(node_stack.empty() == false){ tNode *cur = node_stack.top(); node_stack.pop(); tNode *cur_copy = node_stack_copy.top(); node_stack_copy.pop(); if(cur->right){ cur_copy->left = new tNode(cur->right->data); node_stack.push(cur->right); node_stack_copy.push(cur_copy->left); } if(cur->left){ cur_copy->right = new tNode(cur->left->data); node_stack.push(cur->left); node_stack_copy.push(cur_copy->right); } } return newRoot; } //3.判断两棵树是否相互镜像 bool judge_mirror(tNode *root1,tNode *root2){ if(!root1 && !root2){ return true; } if(!root1 || !root2){ return false; } if(root1->data != root2->data){ return false; } return judge_mirror(root1->left,root2->right) && judge_mirror(root1->right,root2->left); } }; int main(){ return 0; }
#include "yascos.hpp"
#include "LR.h" int main() { string trainPath = "..\\example\\horseColic\\testSet_train.txt"; string testPath = "..\\example\\horseColic\\testSet_test.txt"; string testSavePath = "..\\example\\horseColic\\testSet_test_result.txt"; Logistic loghorse; loghorse.dataLoad(loghorse.dataTrain, trainPath);//train loghorse.stoGradDescent(500, 0.001); loghorse.dataLoad(loghorse.dataTest, testPath);//test loghorse.logTest(testSavePath); return 0; }
// Created on: 2014-10-08 // Created by: Kirill Gavrilov // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _OpenGl_SetOfShaderPrograms_HeaderFile #define _OpenGl_SetOfShaderPrograms_HeaderFile #include <Graphic3d_ShaderFlags.hxx> #include <Graphic3d_TypeOfShadingModel.hxx> #include <NCollection_DataMap.hxx> class OpenGl_ShaderProgram; //! Alias to programs array of predefined length class OpenGl_SetOfPrograms : public Standard_Transient { DEFINE_STANDARD_RTTI_INLINE(OpenGl_SetOfPrograms, Standard_Transient) public: //! Empty constructor OpenGl_SetOfPrograms() {} //! Access program by index Handle(OpenGl_ShaderProgram)& ChangeValue (Standard_Integer theProgramBits) { return myPrograms[theProgramBits]; } protected: Handle(OpenGl_ShaderProgram) myPrograms[Graphic3d_ShaderFlags_NB]; //!< programs array }; //! Alias to 2D programs array of predefined length class OpenGl_SetOfShaderPrograms : public Standard_Transient { DEFINE_STANDARD_RTTI_INLINE(OpenGl_SetOfShaderPrograms, Standard_Transient) public: //! Empty constructor OpenGl_SetOfShaderPrograms() {} //! Constructor OpenGl_SetOfShaderPrograms (const Handle(OpenGl_SetOfPrograms)& thePrograms) { for (Standard_Integer aSetIter = 0; aSetIter < Graphic3d_TypeOfShadingModel_NB - 1; ++aSetIter) { myPrograms[aSetIter] = thePrograms; } } //! Access program by index Handle(OpenGl_ShaderProgram)& ChangeValue (Graphic3d_TypeOfShadingModel theShadingModel, Standard_Integer theProgramBits) { Handle(OpenGl_SetOfPrograms)& aSet = myPrograms[theShadingModel - 1]; if (aSet.IsNull()) { aSet = new OpenGl_SetOfPrograms(); } return aSet->ChangeValue (theProgramBits); } protected: Handle(OpenGl_SetOfPrograms) myPrograms[Graphic3d_TypeOfShadingModel_NB - 1]; //!< programs array, excluding Graphic3d_TypeOfShadingModel_Unlit }; typedef NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_SetOfShaderPrograms)> OpenGl_MapOfShaderPrograms; #endif // _OpenGl_SetOfShaderPrograms_HeaderFile
/********************************************************************** *Project : EngineTask * *Author : Jorge Cásedas * *Starting date : 24/06/2020 * *Ending date : 03/07/2020 * *Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library * **********************************************************************/ #pragma once namespace engine { /// /// Component that keep track of the position and scale of an object, use for Entity classes /// class Transform { float lastXPos; float lastYPos; float lastZPos; float xPos; float yPos; float zPos; float xSize; float ySize; float zSize; public: Transform(); void SetScale(float x, float y, float z); void GetScale(float& x, float& y, float& z); void SetPosition(float x, float y, float z); void GetPosition(float &x, float &y, float &z); void Translate(float x, float y, float z); void GetLastTransformation(float& x, float& y, float& z); private: void ResetLastPos(); }; }
#include <vector> class hash_node { public: int key; hash_node(int hashcode); hash_node* next; }; class hashtable { private: bool is_chained; int table_size; int num_entries; int num_collisions; std::vector<std::vector<int>> table; public: hashtable(int size); double get_load_factor(); int get_num_collisions(); void add(int hashcode, bool use_chaining); int gen_key(); int key_mod_tablesize(); int mid_square(); void clear(); };
#include <stdio.h> #include <stdlib.h> #include <map> #include <tuple> #include <cstddef> #include <limits> #ifndef INCLUDES #define INCLUDES #include "Move.h" #endif class Zobrist{ public: std::map<std::tuple<int,int,int>,uint64_t> hash_map; // stores a hashcode for each possible move int total_playouts; std::map<std::tuple<int,int,int>,int> wins; // stores number of wins when using a move std::map<std::tuple<int,int,int>,int> playouts; // stores number of playouts using a move Zobrist(); uint64_t get_hash(uint64_t,Move); };
#pragma once #include <NxPhysics.h> namespace scene { class SceneBSP; } namespace entity { class Entity; } namespace physics { void CreateBSPEntity(const string& name, const scene::SceneBSP* scene, entity::Entity* entity); }
#include<iostream> using namespace std; int main() { int num,sum=0; cout<<"Enter the num"<<endl; cin>>num; if(num<1) cout<<"it is not a natural number"; for(int i=1;i<=num;i++) { sum+=i; } cout<<"Sum of natural number is "<<sum; return(0); }