void TR::InstructionAbsoluteRelocation::apply(TR::CodeGenerator *codeGen) { intptrj_t *cursor = (intptrj_t*)getUpdateLocation(); intptrj_t address = (intptrj_t)getInstruction()->getBinaryEncoding(); if (useEndAddress()) address += getInstruction()->getBinaryLength(); AOTcgDiag2(codeGen->comp(), "TR::InstructionAbsoluteRelocation::apply cursor=" POINTER_PRINTF_FORMAT " instruction=" POINTER_PRINTF_FORMAT "\n", cursor, address); *cursor = address; }
/* * find all the leaders (instruction) in the InstrList given, * leaders returned as an ArrayList(set) of Instruction* */ ArrayList *findLeaders(InstrList *iList){ Instruction *temp_ins; ArrayList *leaders = al_newGeneric(AL_LIST_SET, addressCompare, refPrint, NULL); int i=0; //add first instr into leader list Instruction *instr = getInstruction(iList, i); al_add(leaders, (void *)(instr->addr)); for(i=0;i<iList->numInstrs;i++){ Instruction *instr = getInstruction(iList, i); //ignore non-jump instructions and native invocations if(!isBranch(iList, instr) && !isRetInstruction(iList, instr) && !(isInvokeInstruction(iList, instr) && INSTR_HAS_FLAG(instr, INSTR_IS_SCRIPT_INVOKE)) ) continue; /* add: * instr as target of jump * instr immediately after jump */ if(isBranch(iList, instr)){ if(!instr->jmpOffset){ printInstruction(instr); } assert(instr->jmpOffset); al_add(leaders, (void *)(instr->addr + instr->jmpOffset)); assert(instr->length>0); al_add(leaders, (void *)(instr->addr + instr->length)); } else if(isRetInstruction(iList, instr)){ if(i < iList->numInstrs-1){ temp_ins = getInstruction(iList, i+1); al_add(leaders, (void *)(temp_ins->addr)); } } else{ //non-native invoke and document.write() which generate code if(i < iList->numInstrs-1){ assert(isInvokeInstruction(iList, instr) && INSTR_HAS_FLAG(instr, INSTR_IS_SCRIPT_INVOKE)); temp_ins = getInstruction(iList, i+1); al_add(leaders, (void *)(temp_ins->addr)); } } } return leaders; }
/* Function to invoke Command Line interface */ void debug_interface() { char c; char next_instr[WORD_SIZE * WORDS_PERINSTR]; int i,j,val; printf("Last Instruction Executed : %s\n", instruction); printf("Mode : %s \t Current IP Value: %s\n", (mode == USER_MODE)?"USER":"******" ,reg[IP_REG]); if(getInstruction(next_instr) == 0) //gets the next instruction to be executed printf("Next Instruction to be Executed : %s\n", next_instr); while(1) { i=0; printf("\n# "); scanf("%c",&c); while(c!='\n') { command[i++] = c; scanf("%c",&c); } command[i] = '\0'; if(command[0] == '\0') strcpy(command,prev_command); if(command[0]!='\0') { strcpy(prev_command,command); // backup this command val = runCommand(command); if(val == 1) return; } } }
int main(int argc, char *argv[]) { unsigned int ip; unsigned int acc; char start = 1; // ignores first 0 ip char noHalt = 1; // flag to determine if HALT has been called FILE *fp; // Open File if ((fp=fopen(argv[1], "r"))==NULL) { printf("ERROR: File Doesn't Exist\n"); exit(1); } while (!feof(fp)) { fscanf(fp, "%3d %4d", &ip, &acc); if (start || ip!=0) { printf("%03d %04d ", ip, acc); getInstruction(acc, noHalt); start = 0; } else printf("%03d\n", ip); //Determine if HALT has already been called if (acc == HALT) { noHalt = 0; } } fclose(fp); return 0; }
void xml::lex::getMisc(xml::token *tok) { static const char* s_startPI = "<?"; static const char* s_endPI = "?>"; static const char* s_startComment = "<!--"; static const char* s_endComment = "-->"; handleWhitespace(); if (handleReserved(s_startPI) != false) { tok->m_type = xml::_instruction; getInstruction(tok); if (handleReserved(s_endPI) == false) { throw GException("XML Parser", 4, m_line, m_byte); } } else if (handleReserved(s_startComment) != false) { tok->m_type = xml::_comment; getComment(tok); if (handleReserved(s_endComment) == false) { throw GException("XML Parser", 5, m_line, m_byte); } } else { m_state = m_nextState; } }
/** * Top module to extract the whole string into final OpCode * * Input: * String instructions,with appropriate arguments * * Return OpCode in int type */ unsigned int interpret(String *instruction){ stringTrimLeft(instruction); String *instString = stringRemoveWordNotContaining(instruction," "); char *instChar = stringSubstringInChar(instString,0,instString->length); instructionTable inst = getInstruction(instChar); if(inst.type == FDA_TYPE) return inst.opCode | FDA(instruction); else if(inst.type == FBA_TYPE) return inst.opCode | FBA(instruction); else if(inst.type == FA_TYPE) return inst.opCode | FA(instruction); else if(inst.type == FSFD_TYPE) return inst.opCode | FSFD(instruction); else if(inst.type == N_TYPE) return inst.opCode | N(instruction); else if(inst.type == NS_TYPE) return inst.opCode | NS(instruction); else if(inst.type == S_TYPE) return inst.opCode | S(instruction); else if(inst.type == K_TYPE) return inst.opCode | K(instruction); else if(inst.type == FK_TYPE) return inst.opCode | FK(instruction); else Throw(ERR_ILLEGAL_ARGUMENT); }
static bool getFragmentToCompile(Core &core, uint32_t startPc, std::vector<InstructionOpcode> &opcode, std::vector<Operands> &operands, bool &endOfBlock, uint32_t &nextPc) { uint32_t pc = startPc; opcode.clear(); operands.clear(); endOfBlock = false; nextPc = pc; InstructionOpcode opc; Operands ops; InstructionProperties *properties; do { if (!getInstruction(core, pc, opc, ops)) { endOfBlock = true; break; } instructionTransform(opc, ops, core, pc); properties = &instructionProperties[opc]; nextPc = pc + properties->size / 2; if (properties->mayBranch()) endOfBlock = true; if (!properties->function) break; opcode.push_back(opc); operands.push_back(ops); pc = nextPc; } while (!properties->mayBranch()); return !opcode.empty(); }
/* * mark basicBlock start and end, based on the given list of leaders. */ void markBasicBlockBoundary(InstrList *iList, ArrayList *leaders){ Instruction *instr; int i; for(i=0;i<iList->numInstrs;i++){ instr = getInstruction(iList, i); if(al_contains(leaders, (void *)(instr->addr))){ INSTR_SET_FLAG(instr, INSTR_IS_BBL_START); if(i>0){ instr = getInstruction(iList, i-1); INSTR_SET_FLAG(instr, INSTR_IS_BBL_END); } } } instr = getInstruction(iList, iList->numInstrs-1); INSTR_SET_FLAG(instr, INSTR_IS_BBL_END); //printInstruction(instr); }
QVariant InstructionsModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { auto instruction = getInstruction(index); assert(instruction); switch (index.column()) { case IMC_INSTRUCTION: return tr("%1:\t%2").arg(instruction->addr(), 0, 16).arg(instruction->toString()); default: unreachable(); } } else if (role == Qt::BackgroundRole) { auto instruction = getInstruction(index); assert(instruction); if (std::binary_search(highlightedInstructions_.begin(), highlightedInstructions_.end(), instruction)) { return QColor(highlightColor); } } return QVariant(); }
uv_err_t UVDGBArchitecture::parseCurrentInstruction(UVDIteratorCommon &iterCommon) { //Reduce errors from stale data if( !iterCommon.m_instruction ) { uv_assert_err_ret(getInstruction(&iterCommon.m_instruction)); uv_assert_ret(iterCommon.m_instruction); } uv_assert_err_ret(iterCommon.m_instruction->parseCurrentInstruction(iterCommon)); return UV_ERR_OK; }
//evaluate instruction void eval() { int instr = program[ip]; printf("*Evaluating instruction %s...\n", getInstruction(instr)); switch(instr) { case PUSH: { stack[++sp] = program[++ip]; printf("**Pushed %i onto the stack.\n", stack[sp]); break; } case ADD: { int a = stack[sp--]; int b = stack[sp--]; registers[rp] = a + b; printf("**Added %i and %i to get %i.\n", a, b, registers[rp]); break; } case POP: { registers[rp] = stack[sp--]; printf("**Popped %i onto register %s.\n", registers[rp], getReg(rp)); break; } case PEEK: { registers[rp] = stack[sp]; printf("**Peeked %i onto register %s.\n", registers[rp], getReg(rp)); break; } case SET: { int reg = program[++ip]; int val = program[++ip]; registers[reg] = val; printf("**Loaded %i into register %s.\n", val, getReg(reg)); break; } case HALT: { running = false; printf("**Halting.\n"); break; } } ip++; //increment IP at end of eval() }
/// \brief Perform the quicksort. /// void *operator()() { // TODO: This should be raised as a run-time error. assert(CompareFn && "Comparison function is unknown!"); auto const Caller = ThreadListener.getActiveFunction(); assert(Caller && !Caller->isShim()); auto const Call = llvm::ImmutableCallSite(Caller->getActiveInstruction()); auto const KeyPtrObj = Caller->getPointerObject(Call.getArgument(0)); auto const ArrayPtrObj = Caller->getPointerObject(Call.getArgument(1)); ThreadListener.pushShimFunction(); auto const Shim = ThreadListener.getActiveFunction(); // Array element is always the left side of comparison, key object is // always the right side of comparison. auto CompareFnArg = CompareFn->arg_begin(); Shim->setPointerObject( &*CompareFnArg, ArrayPtrObj); Shim->setPointerObject(&*++CompareFnArg, KeyPtrObj ); acquireMemory(); auto const Result = bsearch(); releaseMemory(); ThreadListener.popShimFunction(); // The C standard specifies the result is not const. auto const Unqualified = const_cast<char *>(Result); // Notify of the returned pointer (and its pointer object). auto const CallInst = Call.getInstruction(); auto const Idx = seec::trace::getThreadEnvironment().getInstructionIndex(); ThreadListener.notifyValue(Idx, CallInst, reinterpret_cast<void *>(Unqualified)); // Note that Caller is invalidated when the shim function is pushed, so we // need to retrieve a new pointer to the active function. ThreadListener.getActiveFunction() ->setPointerObject(CallInst, Result ? ArrayPtrObj : seec::trace::PointerTarget{}); // const_cast due to the C standard. return Unqualified; }
/* * This function does the following: * 1. Loads OS Startup Code. * 2. Copies the instruction to be parsed as per the address specified by the IP register. * 3. Checks whether interrupt is disabled. If not th clock ticks. * 4. Begins the lexical analysis by getting the first token and passing it as arguement to executeOneInstruction. * 5. If step flag is enabled enters debug mode * 6. Finally checks if time slice allocated is over or not. If yes and mode is user mode ,and if interrupt is enabled then * INT 0 code is run. */ void run(int is_timer_enabled) { if (is_timer_enabled) resetTimer(); loadStartupCode(); int instr; while (1) { YY_FLUSH_BUFFER; if (getInstruction(instruction) == -1) continue; //gets the next instruction in variable instruction instr = yylex(); if (mode == USER_MODE && is_timer_enabled) timerTick(); executeOneInstruction(instr); if ((watch_count > 0 && checkWatch() == 1) || step_flag == 1) debugInterface(); if (isTimerCountZero() && is_timer_enabled && mode == USER_MODE) { resetTimer(); invokeHardwareInterrupt(0); if (step_flag == 1) printf("TIMER Interrupt\n"); } } }
/* * Creates memeory for the program to run and gets the instruction code along * with the registers. */ void build_and_execute_um(FILE* program){ memorySegments = newMem(); instantiateMem(memorySegments, INITIAL_SET_SIZE); initializeRegisters(registers, numRegisters); mapProgram(program); programCounter = 0; numInstructions = instructionLength(); //programPointer = getInstructions(memorySegments); while(programCounter < numInstructions){ UM_Word instruction = getInstruction(programCounter); Instruction instr = parseInstruction(instruction); execute_instruction(instr); if(instr.op == HALT) break; } freeMem(memorySegments); }
void executeCompilation(int pTypeCompilation) { //pTypeCompilation == COMPILE -> Solo modo de compilacion (generación de archivo). //pTypeCompilation == COMPILEANDSIMULE -> Modo de compilación + simulación (no generación de archivo, guardado en memoria). printf("Compiling... "); updateConsole(); verifyTypeCompilation(pTypeCompilation, START); int totalInstructions = getLastInstruction(); for(i = 0; i <= totalInstructions; i = i + 1) { int compiledInstruction = compileInstruction(getInstruction(i)); saveCompiledInstruction(pTypeCompilation, compiledInstruction, i); } verifyTypeCompilation(pTypeCompilation, END); printf("Ok.\n"); updateConsole(); }
/** *\ Arreglo registro[] Datos recibidos del microcontrolador. *\ Variable i Contador. */ int main() { uint32_t registro[16],Banderas[4]={0,0,0,0},contador=0,*R,*B; uint8_t sram[64], *RAM; int i,num_instructions; char** instructions; ins_t read; instruction_t instruction; R=registro; B=Banderas; RAM=sram; for (i=0;i<=16;i++) { registro[i]=0; } registro[SP]=64; for (i=0;i<=64;i++) { sram[i]=i; } num_instructions = readFile("code.txt", &read); if(num_instructions==-1) return 0; if(read.array==NULL) return 0; instructions = read.array; //Arreglo con las instrucciones while (contador<num_instructions) { instruction = getInstruction(instructions[R[PC]]); // Instrucción en la posición 0 decodeInstruction(instruction,R,B,RAM); // Debe ser modificada de acuerdo a cada código visualizacion_registro(R,B,RAM,instruction); contador++; } for(i=0; i<num_instructions; i++){ free(read.array[i]); } free(read.array); return 0; }
void DSMonitor::watch(DSNodeHandle N, std::vector<Value*> VS, std::string M) { if (N.isNull() || N.getNode()->isCollapsedNode()) { unwatch(); return; } this->N = N; this->VS = VS; this->message = M; DSGraph *G = N.getNode()->getParentGraph(); caption = getCaption(N.getNode(), G); if (!VS.empty()) { Instruction *I = getInstruction(VS[0]); if (I && I->getMetadata("dbg")) { const DebugLoc DL = I->getDebugLoc(); auto *scope = cast<DIScope>(DL.getScope()); location = scope->getFilename().str() + ":" + std::to_string(DL.getLine()) + ":" + std::to_string(DL.getCol()); } } }
void DSMonitor::warn() { if (!smack::SmackOptions::Warnings) return; if (location != "") errs() << location << ": "; errs() << "warning: collapsing DSA node\n"; if (message != "") errs() << message << "\n"; if (VS.empty()) { errs() << "(unknown value)" << "\n"; } else { if (Instruction *I = getInstruction(VS[0])) { if (BasicBlock *B = I->getParent()) { if (Function *F = B->getParent()) { if (F->hasName()) errs() << "in function:\n " << F->getName() << "\n"; } if (B->hasName()) errs() << "in block:\n " << I->getParent()->getName() << "\n"; } errs() << "at instruction:\n" << *I << "\n"; } for (auto V : VS) errs() << "at value:\n" << *V << "\n"; if (caption != "") errs() << "node:\n " << caption << "\n"; } errs() << "\n"; }
//calls get instruction and increments pc counter void fetchInstruction() { getInstruction(); pc += NEXT_INSTRUCTION; }
llvm::Instruction const *RuntimeErrorState::getInstruction() const { auto Index = Parent.getFunctionLookup(); return Index.getInstruction(InstructionIndex); }
int main(void) { // FILE pointer // read from file and write to file FILE* fin = NULL; FILE* fout = NULL; // Instruction type R_Type R = {0, 0, 0, 0, 0, 0}; I_Type I = {0, 0, 0, 0}; J_Type J = {0, 0}; // buffer string // read assembly code // and write machine code char* InstPtr = NULL; char buffer[512] = {0, }; char Instruction[128] = {0, }; char machineCode[44] = {0, }; char machineCode_out[44] = {0, }; // confirm I-type format int i_type_ = 0; // open file assemblycode.txt and machinecode.txt if((fin = fopen("assemblycode.txt", "rt")) == NULL) { puts("fopen('assemblycode.txt') error!!"); return 0; } if((fout = fopen("machinecode.txt", "wt")) == NULL) { puts("fopen('machinecode.txt') error!!"); return 0; } // init machine code and printout to file initCode(machineCode_out, machineCode); fputs(machineCode_out, fout); fputs("\n", fout); // read file line from "assemblycode.txt" while(fgets(buffer, 512, fin) ) { // initialize machineCode buffer string // and Instruction buffer string to zero memset(machineCode, 0, 36); memset(Instruction, 0, 128); strcpy(Instruction, buffer); // copy instruction to buffer InstPtr = getInstruction(Instruction); // and get operation code fputs(buffer,stdout); // check Instruction type // and read instruction and // write to structure if(IsR_Type(InstPtr)) { R = ReadR_Type(buffer); R_TypeToBinaryCode(machineCode, R); } else if(i_type_ = IsI_Type(InstPtr)) { switch (i_type_) { case 1: I = ReadI_Type_I(buffer); break; case 2: I = ReadI_Type_II(buffer); break; case 3: I = ReadI_Type_II(buffer); break; case 4: I = ReadI_Type_IV(buffer); break; } I_TypeToBinaryCode(machineCode, I); } else if(IsJ_Type(InstPtr)) { J = ReadJ_Type(buffer); J_TypeToBinaryCode(machineCode, J); } // if instruction is inaccurate // print error message else { puts("Incorrect istruction!!"); fputs("Incorrect instruction!!", fout); } // divide 32bit machine code to four part // and print machine code to "machinecode.txt" divide_8bit(machineCode_out, machineCode); puts(machineCode_out); fputs(machineCode_out, fout); fputs("\n", fout); } fclose(fin); fclose(fout); return 0; }
u_int16_t HardwareInstructionFetcher::fetchInstruction(u_int16_t _programmCounter) { return getInstruction(_programmCounter); }
void fetch () { getInstruction(); pc ++; //printf("After it is %d \n",pc); }
/* * Look for InlineReturn instructions that are the only "non-weak" use * of a DefInlineFP. In this case we can kill both, which may allow * removing a SpillFrame as well. */ void optimizeActRecs(Trace* trace, DceState& state) { FTRACE(5, "AR:vvvvvvvvvvvvvvvvvvvvv\n"); SCOPE_EXIT { FTRACE(5, "AR:^^^^^^^^^^^^^^^^^^^^^\n"); }; bool killedFrames = false; forEachInst(trace, [&](IRInstruction* inst) { switch (inst->getOpcode()) { case DecRefKillThis: { auto frame = inst->getSrc(1); auto frameInst = frame->getInstruction(); if (frameInst->getOpcode() == DefInlineFP) { FTRACE(5, "DecRefKillThis ({}): weak use of frame {}\n", inst->getIId(), frameInst->getIId()); state[frameInst].incWeakUse(); } } break; case InlineReturn: { auto frameUses = inst->getSrc(0)->getUseCount(); auto srcInst = inst->getSrc(0)->getInstruction(); if (srcInst->getOpcode() == DefInlineFP) { auto weakUses = state[srcInst].weakUseCount(); // We haven't counted this InlineReturn as a weak use yet, // which is where this '1' comes from. if (frameUses - weakUses == 1) { FTRACE(5, "killing frame {}\n", srcInst->getIId()); killedFrames = true; state[srcInst].setDead(); } } } break; default: break; } }); if (!killedFrames) return; /* * The first time through, we've counted up weak uses of the frame * and then finally marked it dead. The instructions in between * that were weak uses may need modifications now that their frame * is going away. */ forEachInst(trace, [&](IRInstruction* inst) { switch (inst->getOpcode()) { case DecRefKillThis: { auto fp = inst->getSrc(1); if (state[fp->getInstruction()].isDead()) { FTRACE(5, "DecRefKillThis ({}) -> DecRef\n", inst->getIId()); inst->setOpcode(DecRef); inst->setSrc(1, nullptr); inst->setNumSrcs(1); } } break; case InlineReturn: { auto fp = inst->getSrc(0); if (state[fp->getInstruction()].isDead()) { FTRACE(5, "InlineReturn ({}) setDead\n", inst->getIId()); state[inst].setDead(); } } break; case DefInlineFP: FTRACE(5, "DefInlineFP ({}): weak/strong uses: {}/{}\n", inst->getIId(), state[inst].weakUseCount(), inst->getDst()->getUseCount()); break; default: break; } }); }
int main(void) { uint32_t reg[16]={0}; //se creo un arreglo de 13 variables de 32 bits para los 13 registros char bandera[4]={0}; //La bandera se definio como un arreglo de 4 variables siendo la primera la bandera de negativo int ch=0,j=0,z; uint16_t Mnem=0x0; uint8_t MemRAM[256],m=0; reg[13]=0x100; for(j=0;j<=0xff;j++) { MemRAM[j]=0xff; } int num_instructions; ins_t read; char** instructions; instruction_t instruction; num_instructions = readFile("code.txt", &read); if(num_instructions==-1) { return 0; } if(read.array==NULL) { return 0; } instructions = read.array; initscr(); /* Inicia modo curses */ curs_set(0); /* Cursor Invisible */ raw(); /* Activa modo raw */ keypad(stdscr, TRUE); /* Obtener F1, F2, etc */ noecho(); /* No imprimir los caracteres leidos */ start_color(); /* Permite manejar colores */ init_pair(1, COLOR_WHITE, COLOR_CYAN); /* Pair 1 -> Texto blanco fondo cyan */ bkgd(COLOR_PAIR(1)); //se rellena el todo el fondo de color cyan mostrar_registro(reg); move(4, 40); printw("Banderas"); move(6, 40); printw("N=%d\n",bandera[0]); move(7, 40); printw("Z=%d\n",bandera[1]); move(8, 40); printw("C=%d\n",bandera[2]); move(9, 40); printw("V=%d\n",bandera[3]); move(11, 40); printw("PC=%X\n",reg[15]*2); move(12, 40); printw("LR=%X\n",reg[14]*2); move(13, 40); printw("SP=%X\n",reg[13]); move(4, 55); printw("Emulador ARM Cortex-M0"); mostrar_ram(MemRAM); initIO();showPorts(); border( ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE, ACS_ULCORNER, ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER ); refresh(); while(ch != 'q') { ch = getch(); /* Espera entrada del usuario */ if(ch=='a'||ch=='b') { teclas(ch,&m); } clear(); INT(irq, reg, MemRAM, bandera, &m); showPorts(); move(2, 15); printw("%s",instructions[reg[15]]); instruction = getInstruction(instructions[reg[15]]); decodeInstruction(instruction, reg, bandera, MemRAM, &Mnem); mostrar_registro(reg); move(2, 40); printw("Instruccion --> 0x%.4X",Mnem); move(4, 40); printw("Banderas"); move(6, 40); printw("N=%d\n",bandera[0]); move(7, 40); printw("Z=%d\n",bandera[1]); move(8, 40); printw("C=%d\n",bandera[2]); move(9, 40); printw("V=%d\n",bandera[3]); move(11, 40); printw("PC=%X\n",reg[15]*2); move(12, 40); printw("LR=%X\n",reg[14]); move(13, 40); printw("SP=%X\n",reg[13]); move(4, 55); printw("Emulador ARM Cortex-M0"); move(5, 55); printw("Presione q para Salir"); move(6, 55); printw("Presione a para modificar el estado del puerto A"); move(7, 55); printw("Presione b para modificar el estado del puerto B"); mostrar_ram(MemRAM); border( ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE, ACS_ULCORNER, ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER ); refresh(); /* Imprime en la pantalla Sin esto el printw no es mostrado */ } attroff(COLOR_PAIR(1)); /* DEshabilita los colores Pair 1 */ endwin(); free(read.array); /* Finaliza el modo curses */ return 0; }