c-programming

Simple C programs
git clone git://git.laack.co/c-programming.git
Log | Files | Refs

commit 191aeec243095ec36ef4ad46af712f1efa7f02f8
parent 9764c0d3186a99bb2c0e28068d057a43c6554aee
Author: Andrew Laack <andrew@laack.co>
Date:   Mon, 12 Oct 2026 21:39:34 -0500

Start from scratch; use nice asm so I don't have to get too in the weeds of casey's ir

Diffstat:
Mperf-aware-programming/8086-ref/Makefile | 6+++---
Aperf-aware-programming/8086-ref/sim.cpp | 191+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dperf-aware-programming/8086-ref/sim86.cpp | 77-----------------------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86.h | 133-------------------------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_decode.cpp | 285-------------------------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_decode.h | 60------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_instruction_table.inl | 248-------------------------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_memory.cpp | 51---------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_memory.h | 31-------------------------------
Dperf-aware-programming/8086-ref/sim86_text.cpp | 160-------------------------------------------------------------------------------
Dperf-aware-programming/8086-ref/sim86_text.h | 14--------------
Aperf-aware-programming/8086-ref/source/0043.asm | 8++++++++
Aperf-aware-programming/8086-ref/source/0044.asm | 12++++++++++++
Dperf-aware-programming/8086-ref/source/listing_0043_immediate_movs | 0
Dperf-aware-programming/8086-ref/source/listing_0044_register_movs | 0
Rperf-aware-programming/8086-ref/source/listing_0043_immediate_movs.asm -> perf-aware-programming/8086-ref/source/og/listing_0043_immediate_movs.asm | 0
Rperf-aware-programming/8086-ref/source/listing_0044_register_movs.asm -> perf-aware-programming/8086-ref/source/og/listing_0044_register_movs.asm | 0
17 files changed, 214 insertions(+), 1062 deletions(-)

diff --git a/perf-aware-programming/8086-ref/Makefile b/perf-aware-programming/8086-ref/Makefile @@ -1,6 +1,6 @@ build: - g++ sim86.cpp -o simulate + g++ sim.cpp -o sim.out run: build - ./simulate source/listing_0043_immediate_movs - ./simulate source/listing_0044_register_movs + ./sim.out source/0043.asm + ./sim.out source/0044.asm diff --git a/perf-aware-programming/8086-ref/sim.cpp b/perf-aware-programming/8086-ref/sim.cpp @@ -0,0 +1,191 @@ +#include <filesystem> +#include <fstream> +#include <string> +#include <vector> +#include <unistd.h> +#include <iostream> + + +enum Mnemonic { + MOV, + UNKNOWN +}; + +void printMnemonic(Mnemonic mn) { + switch(mn) { + case (MOV): + std::cout << "mov"; + break; + case (UNKNOWN): + std::cout << "unknown"; + break; + } +} + + +int isHalfReg(std::string reg) { + if(reg[1] == 'l' || reg[1] == 'h') { + return 1; + } + return 0; +} + +Mnemonic getMnemonic(std::string line) { + if(line.substr(0,3) == "mov") { + return MOV; + } + return UNKNOWN; +} + +std::string readFileToString(std::string filePath) { + auto in = std::ifstream(filePath); + std::ostringstream sstr; + sstr << in.rdbuf(); + return sstr.str(); +} + + +// assumes entire instruction is input +std::string parseDestination(std::string st) { + std::string source = st.substr(st.find(' ')+1); + return source.substr(source.find(' ')+1); +} + + +// assumes entire instruction is input +std::string parseSource(std::string st) { + std::string source = st.substr(st.find(' ')+1); + return source.substr(0,source.find(',')); +} + +void printRegisters(std::vector<std::pair<std::string,uint16_t>> registers) { + for(auto& reg : registers) { + printf("\t%s: 0x%.2X\n", reg.first.c_str(), reg.second); + } +} + + +// return -1 for not register or byte offset into register vector +int8_t getReg(std::string location) { + if (location == "ax") { + return 0; + } + if (location == "bx") { + return 2; + } + if (location == "cx") { + return 4; + } + if (location == "dx") { + return 6; + } + if (location == "sp") { + return 8; + } + if (location == "bp") { + return 10; + } + if (location == "si") { + return 12; + } + if (location == "di") { + return 14; + } + + return -1; +} + +uint16_t valueAt(std::vector<std::pair<std::string,uint16_t>> registers, int idx) { + return registers[idx/2].second; +} + +int main(int argc, char** argv) { + + std::vector<std::pair<std::string,uint16_t>> registers{}; + registers.push_back({"ax",0}); + registers.push_back({"bx",0}); + registers.push_back({"cx",0}); + registers.push_back({"dx",0}); + registers.push_back({"sp",0}); + registers.push_back({"bp",0}); + registers.push_back({"si",0}); + registers.push_back({"di",0}); + + std::string ftext = readFileToString(argv[1]); + std::vector<std::string> lines {}; + + std::string acc = ""; + + for(size_t i = 0; i < ftext.size(); ++i) { + if(ftext[i] == '\n') { + lines.push_back(acc); + acc = ""; + } + else { + acc += ftext[i]; + } + } + if(acc != "") { + lines.push_back(acc); + } + + std::cout << "INSTRUCTIONS:" << std::endl; + + for(auto& line : lines) { + Mnemonic mne = getMnemonic(line); + printMnemonic(mne); + std::cout << " "; + + std::string source = parseSource(line); + std::string dest = parseDestination(line); + std::cout << source << ", " << dest; + + if(mne == MOV) { + auto reg = getReg(source); + + if(reg != -1) { + try { + if(isHalfReg(source)) { + auto before = registers[reg/2].second; + auto current = registers[reg/2].second; + if(reg%2 == 1) { + // lower (right) + current -= current & 0b0000000011111111; + current += std::stoi(dest); + } else { + // upper (left) + current -= current & 0b1111111100000000; + current += std::stoi(dest) << 8; + } + registers[reg/2].second = current; + printf("\t; 0x%.2X->0x%.2X", before , current); + } else { + auto before = registers[reg/2].second; + auto current = std::stoi(dest); + registers[reg/2].second = current; + printf("\t; 0x%.2X->0x%.2X", before , current); + } + } catch (...) { + auto num = getReg(dest); + if(num == -1) { + return -1; // not implemented yet + } + auto destVal = valueAt(registers,num); + + auto before = registers[reg/2].second; + auto current = destVal; + registers[reg/2].second = current; + printf("\t; 0x%.2X->0x%.2X", before , current); + + } + } + } + std::cout << std::endl; + + } + + std::cout << std::endl; + std::cout << "FINAL REGISTERS:" << std::endl; + printRegisters(registers); + +} diff --git a/perf-aware-programming/8086-ref/sim86.cpp b/perf-aware-programming/8086-ref/sim86.cpp @@ -1,77 +0,0 @@ -#include "sim86.h" - -#include "sim86_memory.h" -#include "sim86_text.h" -#include "sim86_decode.h" - -#include "sim86_memory.cpp" -#include "sim86_text.cpp" -#include "sim86_decode.cpp" - -static void DisAsm8086(memory *Memory, u32 DisAsmByteCount, segmented_access DisAsmStart) -{ - segmented_access At = DisAsmStart; - - disasm_context Context = DefaultDisAsmContext(); - - u32 Count = DisAsmByteCount; - while(Count) - { - instruction Instruction = DecodeInstruction(&Context, Memory, &At); - if(Instruction.Op) - { - if(Count >= Instruction.Size) - { - Count -= Instruction.Size; - } - else - { - fprintf(stderr, "ERROR: Instruction extends outside disassembly region\n"); - break; - } - - UpdateContext(&Context, Instruction); - printf("%s", GetMnemonic(Instruction.Op)); - unsigned char before = 0x10; - unsigned char after = 12; - printf(" ; 0x%x->0x%x", before, after); - printf("\n"); - -// if(IsPrintable(Instruction)) - // { - // PrintInstruction(Instruction, stdout); - - // } - - } - else - { - fprintf(stderr, "ERROR: Unrecognized binary in instruction stream.\n"); - break; - } - } -} - -int main(int ArgCount, char **Args) -{ - memory *Memory = (memory *)malloc(sizeof(memory)); - - if(ArgCount > 1) - { - for(int ArgIndex = 1; ArgIndex < ArgCount; ++ArgIndex) - { - char *FileName = Args[ArgIndex]; - u32 BytesRead = LoadMemoryFromFile(FileName, Memory, 0); - - printf("; %s disassembly:\n", FileName); - printf("bits 16\n"); - DisAsm8086(Memory, BytesRead, {}); - } - } - else - { - fprintf(stderr, "USAGE: %s [8086 machine code file] ...\n", Args[0]); - } - - return 0; -} diff --git a/perf-aware-programming/8086-ref/sim86.h b/perf-aware-programming/8086-ref/sim86.h @@ -1,133 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -#include <stdio.h> -#include <stdlib.h> -#include <stdint.h> -#include <assert.h> - -typedef uint8_t u8; -typedef uint16_t u16; -typedef uint32_t u32; -typedef uint64_t u64; - -typedef int8_t s8; -typedef int16_t s16; -typedef int32_t s32; -typedef int64_t s64; - -typedef int32_t b32; - -#define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0])) - -enum operation_type -{ - Op_None, - -#define INST(Mnemonic, ...) Op_##Mnemonic, -#define INSTALT(...) -#include "sim86_instruction_table.inl" - - Op_Count, -}; - -enum instruction_flag -{ - Inst_Lock = (1 << 0), - Inst_Rep = (1 << 1), - Inst_Segment = (1 << 2), - Inst_Wide = (1 << 3), -}; - -enum register_index -{ - Register_none, - - Register_a, - Register_b, - Register_c, - Register_d, - Register_sp, - Register_bp, - Register_si, - Register_di, - Register_es, - Register_cs, - Register_ss, - Register_ds, - Register_ip, - Register_flags, - - Register_count, -}; - -enum effective_address_base -{ - EffectiveAddress_direct, - - EffectiveAddress_bx_si, - EffectiveAddress_bx_di, - EffectiveAddress_bp_si, - EffectiveAddress_bp_di, - EffectiveAddress_si, - EffectiveAddress_di, - EffectiveAddress_bp, - EffectiveAddress_bx, - - EffectiveAddress_count, -}; - -struct effective_address_expression -{ - register_index Segment; - effective_address_base Base; - s32 Displacement; -}; - -struct register_access -{ - register_index Index; - u8 Offset; - u8 Count; -}; - -enum operand_type -{ - Operand_None, - Operand_Register, - Operand_Memory, - Operand_Immediate, - Operand_RelativeImmediate, -}; - -struct instruction_operand -{ - operand_type Type; - union - { - effective_address_expression Address; - register_access Register; - u32 ImmediateU32; - s32 ImmediateS32; - }; -}; - -struct instruction -{ - u32 Address; - u32 Size; - - operation_type Op; - u32 Flags; - - instruction_operand Operands[2]; -}; diff --git a/perf-aware-programming/8086-ref/sim86_decode.cpp b/perf-aware-programming/8086-ref/sim86_decode.cpp @@ -1,285 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -instruction_format InstructionFormats[] = -{ -#include "sim86_instruction_table.inl" -}; - -static disasm_context DefaultDisAsmContext(void) -{ - disasm_context Result = {}; - - Result.DefaultSegment = Register_ds; - - return Result; -} - -static instruction_operand GetRegOperand(u32 IntelRegIndex, b32 Wide) -{ - // NOTE(casey): This maps Intel's REG and RM field encodings for registers to our encoding for registers. - register_access RegTable[][2] = - { - {{Register_a, 0, 1}, {Register_a, 0, 2}}, - {{Register_c, 0, 1}, {Register_c, 0, 2}}, - {{Register_d, 0, 1}, {Register_d, 0, 2}}, - {{Register_b, 0, 1}, {Register_b, 0, 2}}, - {{Register_a, 1, 1}, {Register_sp, 0, 2}}, - {{Register_c, 1, 1}, {Register_bp, 0, 2}}, - {{Register_d, 1, 1}, {Register_si, 0, 2}}, - {{Register_b, 1, 1}, {Register_di, 0, 2}}, - }; - - instruction_operand Result = {}; - Result.Type = Operand_Register; - Result.Register = RegTable[IntelRegIndex & 0x7][(Wide != 0)]; - - return Result; -} - -// NOTE(casey): ParseDataValue is not a real function, it's basically just a macro that is used in -// TryParse. It should never be called otherwise, but that is not something you can do in C++. -// In other languages it would be a "local function". -static u32 ParseDataValue(memory *Memory, segmented_access *Access, b32 Exists, b32 Wide, b32 SignExtended) -{ - u32 Result = {}; - - if(Exists) - { - if(Wide) - { - u8 D0 = ReadMemory(Memory, GetAbsoluteAddressOf(*Access, 0)); - u8 D1 = ReadMemory(Memory, GetAbsoluteAddressOf(*Access, 1)); - Result = (D1 << 8) | D0; - Access->SegmentOffset += 2; - } - else - { - Result = ReadMemory(Memory, GetAbsoluteAddressOf(*Access)); - if(SignExtended) - { - Result = (s32)*(s8 *)&Result; - } - Access->SegmentOffset += 1; - } - } - - return Result; -} - -static instruction TryDecode(disasm_context *Context, instruction_format *Inst, memory *Memory, segmented_access At) -{ - instruction Dest = {}; - u32 HasBits = 0; - u32 Bits[Bits_Count] = {}; - b32 Valid = true; - - u32 StartingAddress = GetAbsoluteAddressOf(At); - - u8 BitsPendingCount = 0; - u8 BitsPending = 0; - for(u32 BitsIndex = 0; Valid && (BitsIndex < ArrayCount(Inst->Bits)); ++BitsIndex) - { - instruction_bits TestBits = Inst->Bits[BitsIndex]; - if((TestBits.Usage == Bits_Literal) && (TestBits.BitCount == 0)) - { - // NOTE(casey): That's the end of the instruction format. - break; - } - - u32 ReadBits = TestBits.Value; - if(TestBits.BitCount != 0) - { - if(BitsPendingCount == 0) - { - BitsPendingCount = 8; - BitsPending = ReadMemory(Memory, GetAbsoluteAddressOf(At)); - ++At.SegmentOffset; - } - - // NOTE(casey): If this assert fires, it means we have an error in our table, - // since there are no 8086 instructions that have bit values straddling a - // byte boundary. - assert(TestBits.BitCount <= BitsPendingCount); - - BitsPendingCount -= TestBits.BitCount; - ReadBits = BitsPending; - ReadBits >>= BitsPendingCount; - ReadBits &= ~(0xff << TestBits.BitCount); - } - - if(TestBits.Usage == Bits_Literal) - { - // NOTE(casey): This is a "required" sequence - Valid = Valid && (ReadBits == TestBits.Value); - } - else - { - Bits[TestBits.Usage] |= (ReadBits << TestBits.Shift); - HasBits |= (1 << TestBits.Usage); - } - } - - if(Valid) - { - u32 Mod = Bits[Bits_MOD]; - u32 RM = Bits[Bits_RM]; - u32 W = Bits[Bits_W]; - b32 S = Bits[Bits_S]; - b32 D = Bits[Bits_D]; - - b32 HasDirectAddress = ((Mod == 0b00) && (RM == 0b110)); - b32 HasDisplacement = ((Bits[Bits_HasDisp]) || (Mod == 0b10) || (Mod == 0b01) || HasDirectAddress); - b32 DisplacementIsW = ((Bits[Bits_DispAlwaysW]) || (Mod == 0b10) || HasDirectAddress); - b32 DataIsW = ((Bits[Bits_WMakesDataW]) && !S && W); - - Bits[Bits_Disp] |= ParseDataValue(Memory, &At, HasDisplacement, DisplacementIsW, (!DisplacementIsW)); - Bits[Bits_Data] |= ParseDataValue(Memory, &At, Bits[Bits_HasData], DataIsW, S); - - Dest.Op = Inst->Op; - Dest.Flags = Context->AdditionalFlags; - Dest.Address = StartingAddress; - Dest.Size = GetAbsoluteAddressOf(At) - StartingAddress; - if(W) - { - Dest.Flags |= Inst_Wide; - } - - u32 Disp = Bits[Bits_Disp]; - s16 Displacement = (s16)Disp; - - instruction_operand *RegOperand = &Dest.Operands[D ? 0 : 1]; - instruction_operand *ModOperand = &Dest.Operands[D ? 1 : 0]; - - if(HasBits & (1 << Bits_SR)) - { - RegOperand->Type = Operand_Register; - RegOperand->Register.Index = (register_index)(Register_es + (Bits[Bits_SR] & 0x3)); - RegOperand->Register.Count = 2; - } - - if(HasBits & (1 << Bits_REG)) - { - *RegOperand = GetRegOperand(Bits[Bits_REG], W); - } - - if(HasBits & (1 << Bits_MOD)) - { - if(Mod == 0b11) - { - *ModOperand = GetRegOperand(RM, W || (Bits[Bits_RMRegAlwaysW])); - } - else - { - ModOperand->Type = Operand_Memory; - ModOperand->Address.Segment = Context->DefaultSegment; - ModOperand->Address.Displacement = Displacement; - - if((Mod == 0b00) && (RM == 0b110)) - { - ModOperand->Address.Base = EffectiveAddress_direct; - } - else - { - ModOperand->Address.Base = (effective_address_base)(1+RM); - } - } - } - - // - // NOTE(casey): Because there are some strange opcodes that do things like have an immediate as - // a _destination_ ("out", for example), I define immediates and other "additional operands" to - // go in "whatever slot was not used by the reg and mod fields". - // - - instruction_operand *LastOperand = &Dest.Operands[0]; - if(LastOperand->Type) - { - LastOperand = &Dest.Operands[1]; - } - - if(Bits[Bits_RelJMPDisp]) - { - LastOperand->Type = Operand_RelativeImmediate; - LastOperand->ImmediateS32 = Displacement + Dest.Size; - } - - if(Bits[Bits_HasData]) - { - LastOperand->Type = Operand_Immediate; - LastOperand->ImmediateU32 = Bits[Bits_Data]; - } - - if(HasBits & (1 << Bits_V)) - { - if(Bits[Bits_V]) - { - LastOperand->Type = Operand_Register; - LastOperand->Register.Index = Register_c; - LastOperand->Register.Offset = 0; - LastOperand->Register.Count = 1; - } - else - { - LastOperand->Type = Operand_Immediate; - LastOperand->ImmediateS32 = 1; - } - } - } - - return Dest; -} - -static instruction DecodeInstruction(disasm_context *Context, memory *Memory, segmented_access *At) -{ - /* TODO(casey): Hmm. It seems like this is a very inefficient way to parse - instructions, isn't it? For every instruction, we check every entry in the - table until we find a match. Is this bad design? Or did the person who wrote - it know what they were doing, and has a plan for how it can be optimized - later? Only time will tell... :) */ - - instruction Result = {}; - for(u32 Index = 0; Index < ArrayCount(InstructionFormats); ++Index) - { - instruction_format Inst = InstructionFormats[Index]; - Result = TryDecode(Context, &Inst, Memory, *At); - if(Result.Op) - { - At->SegmentOffset += Result.Size; - break; - } - } - - return Result; -} - -static void UpdateContext(disasm_context *Context, instruction Instruction) -{ - if(Instruction.Op == Op_lock) - { - Context->AdditionalFlags |= Inst_Lock; - } - else if(Instruction.Op == Op_rep) - { - Context->AdditionalFlags |= Inst_Rep; - } - else if(Instruction.Op == Op_segment) - { - Context->AdditionalFlags |= Inst_Segment; - Context->DefaultSegment = Instruction.Operands[1].Register.Index; - } - else - { - Context->AdditionalFlags = 0; - Context->DefaultSegment = Register_ds; - } -} diff --git a/perf-aware-programming/8086-ref/sim86_decode.h b/perf-aware-programming/8086-ref/sim86_decode.h @@ -1,60 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -enum instruction_bits_usage : u8 -{ - Bits_Literal, - Bits_MOD, - Bits_REG, - Bits_RM, - Bits_SR, - Bits_Disp, - Bits_Data, - - Bits_HasDisp, - Bits_DispAlwaysW, - Bits_HasData, - Bits_WMakesDataW, - Bits_RMRegAlwaysW, - Bits_RelJMPDisp, - Bits_D, - Bits_S, - Bits_W, - Bits_V, - Bits_Z, - - Bits_Count, -}; - -struct instruction_bits -{ - instruction_bits_usage Usage; - u8 BitCount; - u8 Shift; - u8 Value; -}; - -struct instruction_format -{ - operation_type Op; - instruction_bits Bits[16]; -}; - -struct disasm_context -{ - register_index DefaultSegment; - u32 AdditionalFlags; -}; - -static disasm_context DefaultDisAsmContext(void); -static instruction DecodeInstruction(disasm_context *Context, memory *Memory, segmented_access *At); -static void UpdateContext(disasm_context *Context, instruction Instruction); diff --git a/perf-aware-programming/8086-ref/sim86_instruction_table.inl b/perf-aware-programming/8086-ref/sim86_instruction_table.inl @@ -1,248 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -/* - NOTE(casey): This instruction table is a direct translation of table 4-12 in the Intel 8086 manual. - The macros are designed to allow direct transcription, without changing the order or manner - of specification in the table in any way. Additional "implicit" versions of the macros are provided - so that hard-coded fields can be supplied uniformly. - - The table is also designed to allow you to include it multiple times to "pull out" other things - from the table, such as opcode mnemonics as strings or enums, etc. -*/ - -#ifndef INST -#define INST(Mnemonic, Encoding, ...) {Op_##Mnemonic, Encoding, __VA_ARGS__}, -#endif - -#ifndef INSTALT -#define INSTALT INST -#endif - -#define B(Bits) {Bits_Literal, sizeof(#Bits)-1, 0, 0b##Bits} -#define D {Bits_D, 1} -#define S {Bits_S, 1} -#define W {Bits_W, 1} -#define V {Bits_V, 1} -#define Z {Bits_Z, 1} - -#define XXX {Bits_Data, 3, 0} -#define YYY {Bits_Data, 3, 3} -#define RM {Bits_RM, 3} -#define MOD {Bits_MOD, 2} -#define REG {Bits_REG, 3} -#define SR {Bits_SR, 2} - -#define ImpW(Value) {Bits_W, 0, 0, Value} -#define ImpREG(Value) {Bits_REG, 0, 0, Value} -#define ImpMOD(Value) {Bits_MOD, 0, 0, Value} -#define ImpRM(Value) {Bits_RM, 0, 0, Value} -#define ImpD(Value) {Bits_D, 0, 0, Value} -#define ImpS(Value) {Bits_S, 0, 0, Value} - -#define DISP {Bits_HasDisp, 0, 0, 1} -#define ADDR {Bits_HasDisp, 0, 0, 1}, {Bits_DispAlwaysW, 0, 0, 1} -#define DATA {Bits_HasData, 0, 0, 1} -#define DATA_IF_W {Bits_WMakesDataW, 0, 0, 1} -#define Flags(F) {F, 0, 0, 1} - -INST(mov, {B(100010), D, W, MOD, REG, RM}) -INSTALT(mov, {B(1100011), W, MOD, B(000), RM, DATA, DATA_IF_W, ImpD(0)}) -INSTALT(mov, {B(1011), W, REG, DATA, DATA_IF_W, ImpD(1)}) -INSTALT(mov, {B(1010000), W, ADDR, ImpREG(0), ImpMOD(0), ImpRM(0b110), ImpD(1)}) -INSTALT(mov, {B(1010001), W, ADDR, ImpREG(0), ImpMOD(0), ImpRM(0b110), ImpD(0)}) -INSTALT(mov, {B(100011), D, B(0), MOD, B(0), SR, RM}) // NOTE(casey): This collapses 2 entries in the 8086 table by adding an explicit D bit - -INST(push, {B(11111111), MOD, B(110), RM, ImpW(1)}) -INSTALT(push, {B(01010), REG, ImpW(1)}) -INSTALT(push, {B(000), SR, B(110), ImpW(1)}) - -INST(pop, {B(10001111), MOD, B(000), RM, ImpW(1)}) -INSTALT(pop, {B(01011), REG, ImpW(1)}) -INSTALT(pop, {B(000), SR, B(111), ImpW(1)}) - -INST(xchg, {B(1000011), W, MOD, REG, RM, ImpD(1)}) -INSTALT(xchg, {B(10010), REG, ImpMOD(0b11), ImpW(1), ImpRM(0)}) - -INST(in, {B(1110010), W, DATA, ImpREG(0), ImpD(1)}) -INSTALT(in, {B(1110110), W, ImpREG(0), ImpD(1), ImpMOD(0b11), ImpRM(2), Flags(Bits_RMRegAlwaysW)}) -INST(out, {B(1110011), W, DATA, ImpREG(0), ImpD(0)}) -INSTALT(out, {B(1110111), W, ImpREG(0), ImpD(0), ImpMOD(0b11), ImpRM(2), Flags(Bits_RMRegAlwaysW)}) - -INST(xlat, {B(11010111)}) -INST(lea, {B(10001101), MOD, REG, RM, ImpD(1), ImpW(1)}) -INST(lds, {B(11000101), MOD, REG, RM, ImpD(1), ImpW(1)}) -INST(les, {B(11000100), MOD, REG, RM, ImpD(1), ImpW(1)}) -INST(lahf, {B(10011111)}) -INST(sahf, {B(10011110)}) -INST(pushf, {B(10011100)}) -INST(popf, {B(10011101)}) - -INST(add, {B(000000), D, W, MOD, REG, RM}) -INSTALT(add, {B(100000), S, W, MOD, B(000), RM, DATA, DATA_IF_W}) -INSTALT(add, {B(0000010), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(adc, {B(000100), D, W, MOD, REG, RM}) -INSTALT(adc, {B(100000), S, W, MOD, B(010), RM, DATA, DATA_IF_W}) -INSTALT(adc, {B(0001010), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(inc, {B(1111111), W, MOD, B(000), RM}) -INSTALT(inc, {B(01000), REG, ImpW(1)}) - -INST(aaa, {B(00110111)}) -INST(daa, {B(00100111)}) - -INST(sub, {B(001010), D, W, MOD, REG, RM}) -INSTALT(sub, {B(100000), S, W, MOD, B(101), RM, DATA, DATA_IF_W}) -INSTALT(sub, {B(0010110), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(sbb, {B(000110), D, W, MOD, REG, RM}) -INSTALT(sbb, {B(100000), S, W, MOD, B(011), RM, DATA, DATA_IF_W}) -INSTALT(sbb, {B(0001110), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(dec, {B(1111111), W, MOD, B(001), RM}) -INSTALT(dec, {B(01001), REG, ImpW(1)}) - -INST(neg, {B(1111011), W, MOD, B(011), RM}) - -INST(cmp, {B(001110), D, W, MOD, REG, RM}) -INSTALT(cmp, {B(100000), S, W, MOD, B(111), RM, DATA, DATA_IF_W}) -INSTALT(cmp, {B(0011110), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) // TODO(casey): The manual table suggests this data is only 8-bit, but wouldn't it be 16 as well? - -INST(aas, {B(00111111)}) -INST(das, {B(00101111)}) -INST(mul, {B(1111011), W, MOD, B(100), RM, ImpS(0)}) -INST(imul, {B(1111011), W, MOD, B(101), RM, ImpS(1)}) -INST(aam, {B(11010100), B(00001010)}) // TODO(casey): The manual says this has a DISP... but how could it? What for?? -INST(div, {B(1111011), W, MOD, B(110), RM, ImpS(0)}) -INST(idiv, {B(1111011), W, MOD, B(111), RM, ImpS(1)}) -INST(aad, {B(11010101), B(00001010)}) -INST(cbw, {B(10011000)}) -INST(cwd, {B(10011001)}) - -INST(not, {B(1111011), W, MOD, B(010), RM}) -INST(shl, {B(110100), V, W, MOD, B(100), RM}) -INST(shr, {B(110100), V, W, MOD, B(101), RM}) -INST(sar, {B(110100), V, W, MOD, B(111), RM}) -INST(rol, {B(110100), V, W, MOD, B(000), RM}) -INST(ror, {B(110100), V, W, MOD, B(001), RM}) -INST(rcl, {B(110100), V, W, MOD, B(010), RM}) -INST(rcr, {B(110100), V, W, MOD, B(011), RM}) - -INST(and, {B(001000), D, W, MOD, REG, RM}) -INSTALT(and, {B(1000000), W, MOD, B(100), RM, DATA, DATA_IF_W}) -INSTALT(and, {B(0010010), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(test, {B(100001), D, W, MOD, REG, RM}) -INSTALT(test, {B(1111011), W, MOD, B(000), RM, DATA, DATA_IF_W}) -INSTALT(test, {B(1010100), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) // TODO(casey): The manual table suggests this data is only 8-bit, but it seems like it could be 16 too? - -INST(or, {B(000010), D, W, MOD, REG, RM}) -INSTALT(or, {B(1000000), W, MOD, B(001), RM, DATA, DATA_IF_W}) -INSTALT(or, {B(0000110), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(xor, {B(001100), D, W, MOD, REG, RM}) -INSTALT(xor, {B(1000000), W, MOD, B(110), RM, DATA, DATA_IF_W}) // TODO(casey): The manual has conflicting information about this encoding, but I believe this is the correct binary pattern. -INSTALT(xor, {B(0011010), W, DATA, DATA_IF_W, ImpREG(0), ImpD(1)}) - -INST(rep, {B(1111001), Z}) -INST(movs, {B(1010010), W}) -INST(cmps, {B(1010011), W}) -INST(scas, {B(1010111), W}) -INST(lods, {B(1010110), W}) -INST(stos, {B(1010101), W}) - -INST(call, {B(11101000), ADDR}) -INSTALT(call, {B(11111111), MOD, B(010), RM, ImpW(1)}) -INSTALT(call, {B(10011010), ADDR, DATA, ImpW(1)}) -INSTALT(call, {B(11111111), MOD, B(011), RM, ImpW(1)}) - -INST(jmp, {B(11101001), ADDR}) -INSTALT(jmp, {B(11101011), DISP}) -INSTALT(jmp, {B(11111111), MOD, B(100), RM, ImpW(1)}) -INSTALT(jmp, {B(11101010), ADDR, DATA, ImpW(1)}) -INSTALT(jmp, {B(11111111), MOD, B(101), RM, ImpW(1)}) - -INST(ret, {B(11000011)}) -INSTALT(ret, {B(11000010), DATA, DATA_IF_W, ImpW(1)}) -INSTALT(ret, {B(11001011)}) -INSTALT(ret, {B(11001010), DATA, DATA_IF_W, ImpW(1)}) - -INST(je, {B(01110100), DISP, Flags(Bits_RelJMPDisp)}) -INST(jl, {B(01111100), DISP, Flags(Bits_RelJMPDisp)}) -INST(jle, {B(01111110), DISP, Flags(Bits_RelJMPDisp)}) -INST(jb, {B(01110010), DISP, Flags(Bits_RelJMPDisp)}) -INST(jbe, {B(01110110), DISP, Flags(Bits_RelJMPDisp)}) -INST(jp, {B(01111010), DISP, Flags(Bits_RelJMPDisp)}) -INST(jo, {B(01110000), DISP, Flags(Bits_RelJMPDisp)}) -INST(js, {B(01111000), DISP, Flags(Bits_RelJMPDisp)}) -INST(jne, {B(01110101), DISP, Flags(Bits_RelJMPDisp)}) -INST(jnl, {B(01111101), DISP, Flags(Bits_RelJMPDisp)}) -INST(jg, {B(01111111), DISP, Flags(Bits_RelJMPDisp)}) -INST(jnb, {B(01110011), DISP, Flags(Bits_RelJMPDisp)}) -INST(ja, {B(01110111), DISP, Flags(Bits_RelJMPDisp)}) -INST(jnp, {B(01111011), DISP, Flags(Bits_RelJMPDisp)}) -INST(jno, {B(01110001), DISP, Flags(Bits_RelJMPDisp)}) -INST(jns, {B(01111001), DISP, Flags(Bits_RelJMPDisp)}) -INST(loop, {B(11100010), DISP, Flags(Bits_RelJMPDisp)}) -INST(loopz, {B(11100001), DISP, Flags(Bits_RelJMPDisp)}) -INST(loopnz, {B(11100000), DISP, Flags(Bits_RelJMPDisp)}) -INST(jcxz, {B(11100011), DISP, Flags(Bits_RelJMPDisp)}) - -INST(int, {B(11001101), DATA}) -INST(int3, {B(11001100)}) // TODO(casey): The manual does not suggest that this intrinsic has an "int3" mnemonic, but NASM thinks so - -INST(into, {B(11001110)}) -INST(iret, {B(11001111)}) - -INST(clc, {B(11111000)}) -INST(cmc, {B(11110101)}) -INST(stc, {B(11111001)}) -INST(cld, {B(11111100)}) -INST(std, {B(11111101)}) -INST(cli, {B(11111010)}) -INST(sti, {B(11111011)}) -INST(hlt, {B(11110100)}) -INST(wait, {B(10011011)}) -INST(esc, {B(11011), XXX, MOD, YYY, RM}) -INST(lock, {B(11110000)}) -INST(segment, {B(001), SR, B(110)}) - -#undef INST -#undef INSTALT - -#undef B -#undef D -#undef S -#undef W -#undef V -#undef Z - -#undef XXX -#undef YYY -#undef RM -#undef MOD -#undef REG -#undef SR - -#undef ImpW -#undef ImpREG -#undef ImpMOD -#undef ImpRM -#undef ImpD -#undef ImpS - -#undef DISP -#undef ADDR -#undef DATA -#undef DATA_IF_W -#undef Flags diff --git a/perf-aware-programming/8086-ref/sim86_memory.cpp b/perf-aware-programming/8086-ref/sim86_memory.cpp @@ -1,51 +0,0 @@ -/* ======================================================================== - $File: work/tools/sim86/sim86_memory.cpp $ - $Date: 2023/03/15 08:30:12 UTC $ - $Revision: 2 $ - $Creator: Casey Muratori $ - $Notice: (C) Copyright by Molly Rocket, Inc., All Rights Reserved. $ - ======================================================================== */ - -#ifdef __unix -#define fopen_s(pFile,filename,mode) ((*(pFile))=fopen((filename), (mode)))==NULL -#endif - -static u32 GetAbsoluteAddressOf(u16 SegmentBase, u16 SegmentOffset, u16 AdditionalOffset) -{ - u32 Result = (((u32)SegmentBase << 4) + (u32)(SegmentOffset + AdditionalOffset)) & MEMORY_ACCESS_MASK; - return Result; -} - -static u32 GetAbsoluteAddressOf(segmented_access Access, u16 AdditionalOffset) -{ - u32 Result = GetAbsoluteAddressOf(Access.SegmentBase, Access.SegmentOffset, AdditionalOffset); - return Result; -} - -static u8 ReadMemory(memory *Memory, u32 AbsoluteAddress) -{ - assert(AbsoluteAddress < ArrayCount(Memory->Bytes)); - u8 Result = Memory->Bytes[AbsoluteAddress]; - return Result; -} - -static u32 LoadMemoryFromFile(char *FileName, memory *Memory, u32 AtOffset) -{ - u32 Result = 0; - - if(AtOffset < ArrayCount(Memory->Bytes)) - { - FILE *File = {}; - if(fopen_s(&File, FileName, "rb") == 0) - { - Result = fread(Memory->Bytes + AtOffset, 1, ArrayCount(Memory->Bytes) - AtOffset, File); - fclose(File); - } - else - { - fprintf(stderr, "ERROR: Unable to open %s.\n", FileName); - } - } - - return Result; -} diff --git a/perf-aware-programming/8086-ref/sim86_memory.h b/perf-aware-programming/8086-ref/sim86_memory.h @@ -1,31 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -struct memory -{ - u8 Bytes[1024*1024]; -}; -#define MEMORY_ACCESS_MASK 0xfffff -static_assert((ArrayCount(memory::Bytes) - 1) == MEMORY_ACCESS_MASK, "Memory size doesn't match access mask"); - -struct segmented_access -{ - u16 SegmentBase; - u16 SegmentOffset; -}; - -static u32 GetAbsoluteAddressOf(u16 SegmentBase, u16 SegmentOffset, u16 AdditionalOffset = 0); -static u32 GetAbsoluteAddressOf(segmented_access Access, u16 AdditionalOffset = 0); - -static u8 ReadMemory(memory *Memory, u32 AbsoluteAddress); - -static u32 LoadMemoryFromFile(char *FileName, memory *Memory, u32 AtOffset); diff --git a/perf-aware-programming/8086-ref/sim86_text.cpp b/perf-aware-programming/8086-ref/sim86_text.cpp @@ -1,160 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -char const *OpcodeMnemonics[] = -{ - "", - -#define INST(Mnemonic, ...) #Mnemonic, -#define INSTALT(...) -#include "sim86_instruction_table.inl" -}; - -static char const *GetMnemonic(operation_type Op) -{ - char const *Result = OpcodeMnemonics[Op]; - return Result; -} - -static char const *GetRegName(register_access Reg) -{ - char const *Names[][3] = - { - {"", "", ""}, - {"al", "ah", "ax"}, - {"bl", "bh", "bx"}, - {"cl", "ch", "cx"}, - {"dl", "dh", "dx"}, - {"sp", "sp", "sp"}, - {"bp", "bp", "bp"}, - {"si", "si", "si"}, - {"di", "di", "di"}, - {"es", "es", "es"}, - {"cs", "cs", "cs"}, - {"ss", "ss", "ss"}, - {"ds", "ds", "ds"}, - {"ip", "ip", "ip"}, - {"flags", "flags", "flags"} - }; - static_assert(ArrayCount(Names) == Register_count, "Text table mismatch for register_index"); - - char const *Result = Names[Reg.Index][(Reg.Count == 2) ? 2 : Reg.Offset&1]; - return Result; -} - -static char const *GetEffectiveAddressExpression(effective_address_expression Address) -{ - char const *RMBase[] = - { - "", - "bx+si", - "bx+di", - "bp+si", - "bp+di", - "si", - "di", - "bp", - "bx", - }; - static_assert(ArrayCount(RMBase) == EffectiveAddress_count, "Text table mismatch for effective_base_address"); - char const *Result = RMBase[Address.Base]; - return Result; -} - -static b32 IsPrintable(instruction Instruction) -{ - b32 Result = !((Instruction.Op == Op_lock) || - (Instruction.Op == Op_rep) || - (Instruction.Op == Op_segment)); - - return Result; -} - -static void PrintInstruction(instruction Instruction, FILE *Dest) -{ - u32 Flags = Instruction.Flags; - u32 W = Flags & Inst_Wide; - - if(Flags & Inst_Lock) - { - if(Instruction.Op == Op_xchg) - { - // NOTE(casey): This is just a stupidity for matching assembler expectations. - instruction_operand Temp = Instruction.Operands[0]; - Instruction.Operands[0] = Instruction.Operands[1]; - Instruction.Operands[1] = Temp; - } - fprintf(Dest, "lock "); - } - - char const *MnemonicSuffix = ""; - if(Flags & Inst_Rep) - { - printf("rep "); - MnemonicSuffix = W ? "w" : "b"; - } - - fprintf(Dest, "%s%s ", GetMnemonic(Instruction.Op), MnemonicSuffix); - - char const *Separator = ""; - for(u32 OperandIndex = 0; OperandIndex < ArrayCount(Instruction.Operands); ++OperandIndex) - { - instruction_operand Operand = Instruction.Operands[OperandIndex]; - if(Operand.Type != Operand_None) - { - fprintf(Dest, "%s", Separator); - Separator = ", "; - - switch(Operand.Type) - { - case Operand_None: {} break; - - case Operand_Register: - { - fprintf(Dest, "%s", GetRegName(Operand.Register)); - } break; - - case Operand_Memory: - { - effective_address_expression Address = Operand.Address; - - if(Instruction.Operands[0].Type != Operand_Register) - { - fprintf(Dest, "%s ", W ? "word" : "byte"); - } - - if(Flags & Inst_Segment) - { - printf("%s:", GetRegName({Address.Segment, 0, 2})); - } - - fprintf(Dest, "[%s", GetEffectiveAddressExpression(Address)); - if(Address.Displacement != 0) - { - fprintf(Dest, "%+d", Address.Displacement); - } - fprintf(Dest, "]"); - } break; - - case Operand_Immediate: - { - fprintf(Dest, "%d", Operand.ImmediateS32); - } break; - - case Operand_RelativeImmediate: - { - fprintf(Dest, "$%+d", Operand.ImmediateS32); - } break; - } - } - } -} diff --git a/perf-aware-programming/8086-ref/sim86_text.h b/perf-aware-programming/8086-ref/sim86_text.h @@ -1,14 +0,0 @@ -/* ======================================================================== - - (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Please see https://computerenhance.com for more information - - ======================================================================== */ - -static b32 IsPrintable(instruction Instruction); -static void PrintInstruction(instruction Instruction, FILE *Dest); diff --git a/perf-aware-programming/8086-ref/source/0043.asm b/perf-aware-programming/8086-ref/source/0043.asm @@ -0,0 +1,8 @@ +mov ax, 1 +mov bx, 2 +mov cx, 3 +mov dx, 4 +mov sp, 5 +mov bp, 6 +mov si, 7 +mov di, 8 diff --git a/perf-aware-programming/8086-ref/source/0044.asm b/perf-aware-programming/8086-ref/source/0044.asm @@ -0,0 +1,12 @@ +mov ax, 1 +mov bx, 2 +mov cx, 3 +mov dx, 4 +mov sp, ax +mov bp, bx +mov si, cx +mov di, dx +mov dx, sp +mov cx, bp +mov bx, si +mov ax, di diff --git a/perf-aware-programming/8086-ref/source/listing_0043_immediate_movs b/perf-aware-programming/8086-ref/source/listing_0043_immediate_movs Binary files differ. diff --git a/perf-aware-programming/8086-ref/source/listing_0044_register_movs b/perf-aware-programming/8086-ref/source/listing_0044_register_movs Binary files differ. diff --git a/perf-aware-programming/8086-ref/source/listing_0043_immediate_movs.asm b/perf-aware-programming/8086-ref/source/og/listing_0043_immediate_movs.asm diff --git a/perf-aware-programming/8086-ref/source/listing_0044_register_movs.asm b/perf-aware-programming/8086-ref/source/og/listing_0044_register_movs.asm