1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// m68k Instruction Timing Calclator

use crate::M68kType;
use crate::state::ClockCycles;
use crate::instructions::{Size, Sign, Direction, Target, Instruction};


#[derive(Clone, Debug, PartialEq, Eq)]
pub struct M68kInstructionTiming {
    pub cputype: M68kType,
    pub bus_size: Size,

    pub branched: bool,
    pub reps: u16,

    pub accesses: u8,
    pub internal: u8,
    pub on_branch: u8,
    pub per_rep: u8,
}

impl M68kInstructionTiming {
    pub fn new(cputype: M68kType, bus_width: u8) -> Self {
        let bus_size = if bus_width <= 16 { Size::Word } else { Size::Long };
        Self {
            cputype,
            bus_size,

            branched: false,
            reps: 0,

            accesses: 0,
            internal: 0,
            on_branch: 0,
            per_rep: 0,
        }
    }

    pub fn reset(&mut self) {
        self.accesses = 0;
        self.internal = 0;
        self.on_branch = 0;
        self.per_rep = 0;
    }

    #[inline(always)]
    pub fn add_access(&mut self, size: Size) -> &mut Self {
        self.accesses += self.access_size(size);
        self
    }

    #[inline(always)]
    pub fn add_internal(&mut self, clocks: u8) -> &mut Self {
        self.internal += clocks;
        self
    }

    #[inline(always)]
    pub fn sub_internal(&mut self, clocks: u8) -> &mut Self {
        self.internal = self.internal.saturating_sub(clocks);
        self
    }

    #[inline(always)]
    pub fn add_if_long(&mut self, size: Size, clocks: u8) -> &mut Self {
        self.internal += if size == Size::Long { clocks } else { 0 };
        self
    }

    #[inline(always)]
    pub fn add_reg_v_mem(&mut self, target: &Target, reg: u8, mem: u8) -> &mut Self {
        self.internal += match target {
            Target::DirectDReg(_) | Target::DirectAReg(_) => reg,
            _ => mem,
        };
        self
    }

    #[inline(always)]
    pub fn add_word_v_long(&mut self, size: Size, word: u8, long: u8) -> &mut Self {
        self.internal += if size != Size::Long { word } else { long };
        self
    }

    #[inline(always)]
    pub fn add_standard_set(&mut self, size: Size, target: &Target, areg: (u8, u8), dreg: (u8, u8), mem: (u8, u8)) -> &mut Self {
        match target {
            Target::DirectDReg(_) => self.add_word_v_long(size, dreg.0, dreg.1),
            Target::DirectAReg(_) => self.add_word_v_long(size, areg.0, dreg.1),
            _ => self.add_word_v_long(size, mem.0, mem.1),
        }
    }

    #[inline(always)]
    pub fn add_immediate_set(&mut self, size: Size, target: &Target, reg: (u8, u8), mem: (u8, u8)) -> &mut Self {
        match target {
            Target::DirectDReg(_) | Target::DirectAReg(_) => self.add_word_v_long(size, reg.0, reg.1),
            _ => self.add_word_v_long(size, mem.0, mem.1),
        }
    }

    #[inline(always)]
    pub fn add_indirect_set(&mut self, target: &Target, areg: u8, aoff: u8, indoff: u8, indw: u8, indl: u8) -> &mut Self {
        match target {
            Target::IndirectAReg(_) => self.add_internal(areg),
            Target::IndirectRegOffset(_, None, _) => self.add_internal(aoff),
            Target::IndirectRegOffset(_, Some(_), _) => self.add_internal(indoff),
            Target::IndirectMemory(_, Size::Long) => self.add_internal(indl),
            Target::IndirectMemory(_, _) => self.add_internal(indw),
            _ => panic!("This timing set can't be used with {:?} targetting", target),
        }
    }

    #[inline(always)]
    pub fn add_reg_mem_set(&mut self, size: Size, target: &Target, reg: (u8, u8), mem: (u8, u8)) -> &mut Self {
        match target {
            Target::DirectDReg(_) | Target::DirectAReg(_) => self.add_word_v_long(size, reg.0, reg.1),
            _ => self.add_word_v_long(size, mem.0, mem.1),
        }
    }

    #[inline(always)]
    pub fn add_on_branch(&mut self, clocks: u8) -> &mut Self {
        self.on_branch += clocks;
        self
    }

    #[inline(always)]
    pub fn add_per_rep(&mut self, clocks: u8) -> &mut Self {
        self.per_rep += clocks;
        self
    }

    pub fn add_target(&mut self, size: Size, target: &Target) -> &mut Self {
        match target {
            Target::Immediate(_) => self.add_access(size),
            Target::DirectDReg(_) => self,
            Target::DirectAReg(_) => self,
            Target::IndirectAReg(_) => self.add_access(size),
            Target::IndirectARegInc(_) => self.add_access(size),
            Target::IndirectARegDec(_) => self.add_access(size).add_internal(2),
            Target::IndirectRegOffset(_, index_reg, _) => match index_reg {
                None => self.add_access(size).add_internal(4),
                Some(_) => self.add_access(size).add_internal(6),
            },
            Target::IndirectMemoryPreindexed(_, index_reg, _, _) | Target::IndirectMemoryPostindexed(_, index_reg, _, _) => {
                // TODO this is very wrong, but the 68020 timings are complicated
                match index_reg {
                    None => self.add_access(size).add_internal(4),
                    Some(_) => self.add_access(size).add_internal(6),
                }
            },
            Target::IndirectMemory(_, addr_size) => self.add_access(*addr_size).add_access(size),
        }
    }

    pub fn add_two_targets(&mut self, size: Size, src: &Target, dest: &Target) -> &mut Self {
        match (src, dest) {
            (Target::IndirectARegDec(_), Target::IndirectARegDec(_)) => {
                self.add_target(size, src).add_target(size, dest).sub_internal(2)
            },
            _ => self.add_target(size, src).add_target(size, dest),
        }
    }

    pub fn add_movem(&mut self, size: Size, target: &Target, dir: Direction, n: u8) -> &mut Self {
        if dir == Direction::FromTarget {
            match target {
                Target::IndirectAReg(_) => self.add_word_v_long(size, 12 + 4 * n, 12 + 8 * n),
                Target::IndirectARegInc(_) => self.add_word_v_long(size, 12 + 4 * n, 12 + 8 * n),
                Target::IndirectRegOffset(_, None, _) => self.add_word_v_long(size, 16 + 4 * n, 16 + 8 * n),
                Target::IndirectRegOffset(_, Some(_), _) => self.add_word_v_long(size, 18 + 4 * n, 18 + 8 * n),
                Target::IndirectMemory(_, Size::Long) => self.add_word_v_long(size, 20 + 4 * n, 20 + 8 * n),
                Target::IndirectMemory(_, _) => self.add_word_v_long(size, 16 + 4 * n, 16 + 8 * n),
                _ => panic!("This timing set can't be used with {:?} targetting", target),
            }
        } else {
            match target {
                Target::IndirectAReg(_) => self.add_word_v_long(size, 8 + 4 * n, 8 + 8 * n),
                Target::IndirectARegDec(_) => self.add_word_v_long(size, 8 + 4 * n, 8 + 8 * n),
                Target::IndirectRegOffset(_, None, _) => self.add_word_v_long(size, 12 + 4 * n, 12 + 8 * n),
                Target::IndirectRegOffset(_, Some(_), _) => self.add_word_v_long(size, 14 + 4 * n, 14 + 8 * n),
                Target::IndirectMemory(_, Size::Long) => self.add_word_v_long(size, 16 + 4 * n, 16 + 8 * n),
                Target::IndirectMemory(_, _) => self.add_word_v_long(size, 12 + 4 * n, 12 + 8 * n),
                _ => panic!("This timing set can't be used with {:?} targetting", target),
            }
        }
    }

    pub fn add_instruction(&mut self, instruction: &Instruction) -> &mut Self {
        match self.cputype {
            M68kType::MC68000 | M68kType::MC68010 => self.add_instruction_68000(instruction),
            _ => self.add_instruction_68020(instruction),
        }
    }

    pub fn add_instruction_68000(&mut self, instruction: &Instruction) -> &mut Self {
        match instruction {
            Instruction::ABCD(_, dest) => self.add_reg_v_mem(dest, 6, 18),

            Instruction::ADD(Target::Immediate(x), dest, size) if *x <= 8 => {
                self.add_immediate_set(*size, dest, (4, 8), (8, 12)).add_target(*size, dest)
            }, // ADDQ
            Instruction::ADD(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 16), (12, 20)).add_target(*size, dest)
            }, // ADDI

            Instruction::ADD(src, dest, size) => self
                .add_standard_set(*size, dest, (8, 6), (4, 6), (8, 12))
                .add_two_targets(*size, src, dest),
            Instruction::ADDA(target, _, size) => self.add_word_v_long(*size, 8, 6).add_target(*size, target),
            Instruction::ADDX(_, dest, size) => self.add_reg_mem_set(*size, dest, (4, 8), (18, 30)),

            Instruction::AND(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 14), (12, 20)).add_target(*size, dest)
            },
            Instruction::AND(src, dest, size) => self
                .add_standard_set(*size, dest, (0, 0), (4, 6), (8, 12))
                .add_two_targets(*size, src, dest),
            Instruction::ANDtoCCR(_) => self.add_internal(20),
            Instruction::ANDtoSR(_) => self.add_internal(20),

            Instruction::ASL(_, target, size) | Instruction::ASR(_, target, size) => {
                self.add_word_v_long(*size, 6, 8).add_per_rep(2).add_target(*size, target)
            },

            Instruction::Bcc(_, _) => self.add_internal(8).add_on_branch(2),
            Instruction::BRA(_) => self.add_internal(10),
            Instruction::BSR(_) => self.add_internal(18),

            Instruction::BCHG(bit, target, size) => match bit {
                Target::Immediate(_) => self.add_reg_v_mem(target, 12, 12),
                _ => self.add_reg_v_mem(target, 8, 8),
            }
            .add_target(*size, target),
            Instruction::BCLR(bit, target, size) => match bit {
                Target::Immediate(_) => self.add_reg_v_mem(target, 14, 12),
                _ => self.add_reg_v_mem(target, 10, 8),
            }
            .add_target(*size, target),
            Instruction::BSET(bit, target, size) => match bit {
                Target::Immediate(_) => self.add_reg_v_mem(target, 12, 12),
                _ => self.add_reg_v_mem(target, 8, 8),
            }
            .add_target(*size, target),
            Instruction::BTST(bit, target, size) => match bit {
                Target::Immediate(_) => self.add_reg_v_mem(target, 10, 8),
                _ => self.add_reg_v_mem(target, 6, 4),
            }
            .add_target(*size, target),

            Instruction::CHK(_, _, _) => self.add_internal(10),
            Instruction::CLR(target, size) => self
                .add_reg_v_mem(target, 4, 8)
                .add_word_v_long(*size, 0, 2)
                .add_target(*size, target),

            Instruction::CMP(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 14), (8, 12)).add_target(*size, dest)
            },
            Instruction::CMP(src, dest, size) => self
                .add_standard_set(*size, dest, (6, 6), (4, 6), (0, 0))
                .add_two_targets(*size, src, dest),
            Instruction::CMPA(target, _, size) => self.add_word_v_long(*size, 6, 6).add_target(*size, target),

            Instruction::DBcc(_, _, _) => self.add_internal(10).add_on_branch(4),
            Instruction::DIVW(src, _, sign) => match sign {
                Sign::Unsigned => self.add_internal(140).add_target(Size::Long, src),
                Sign::Signed => self.add_internal(158).add_target(Size::Long, src),
            },

            Instruction::EOR(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 16), (12, 20)).add_target(*size, dest)
            },
            Instruction::EOR(src, dest, size) => self
                .add_standard_set(*size, dest, (0, 0), (4, 8), (8, 12))
                .add_two_targets(*size, src, dest),
            Instruction::EORtoCCR(_) => self.add_internal(20),
            Instruction::EORtoSR(_) => self.add_internal(20),

            Instruction::EXG(_, _) => self.add_internal(6),
            Instruction::EXT(_, _, _) => self.add_internal(4),

            Instruction::ILLEGAL => self.add_internal(4),

            Instruction::JMP(target) => self.add_indirect_set(target, 8, 10, 14, 10, 12),
            Instruction::JSR(target) => self.add_indirect_set(target, 16, 18, 22, 18, 20),

            Instruction::LEA(target, _) => self.add_indirect_set(target, 4, 8, 12, 8, 12),
            Instruction::LINK(_, _) => self.add_internal(16),
            Instruction::LSL(_, target, size) | Instruction::LSR(_, target, size) => {
                self.add_word_v_long(*size, 6, 8).add_per_rep(2).add_target(*size, target)
            },

            Instruction::MOVE(src, dest, size) => self.add_internal(4).add_two_targets(*size, src, dest),
            Instruction::MOVEA(target, _, size) => self.add_internal(4).add_target(*size, target),
            Instruction::MOVEfromSR(target) => self.add_reg_v_mem(target, 6, 8).add_target(Size::Word, target),
            Instruction::MOVEtoSR(target) => self.add_internal(12).add_target(Size::Word, target),
            Instruction::MOVEfromCCR(target) => self.add_internal(12).add_target(Size::Word, target),
            Instruction::MOVEtoCCR(target) => self.add_internal(12).add_target(Size::Word, target),
            Instruction::MOVEC(target, _, _) => self.add_reg_v_mem(target, 10, 12),
            Instruction::MOVEM(target, size, dir, mask) => self.add_movem(*size, target, *dir, mask.count_ones() as u8),
            Instruction::MOVEP(_, _, _, size, _) => self.add_word_v_long(*size, 16, 24),
            Instruction::MOVEQ(_, _) => self.add_internal(4),
            Instruction::MOVEUSP(_, _) => self.add_internal(4),

            Instruction::MULW(src, _, _) => self.add_internal(70).add_target(Size::Word, src),

            Instruction::NBCD(target) => self.add_reg_v_mem(target, 6, 8),
            Instruction::NEG(target, size) => self.add_reg_mem_set(*size, target, (4, 6), (8, 12)).add_target(*size, target),
            Instruction::NEGX(target, size) => self.add_reg_mem_set(*size, target, (4, 6), (8, 12)).add_target(*size, target),

            Instruction::NOP => self.add_internal(4),
            Instruction::NOT(target, size) => self.add_reg_mem_set(*size, target, (4, 6), (8, 12)).add_target(*size, target),

            Instruction::OR(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 16), (12, 20)).add_target(*size, dest)
            },
            Instruction::OR(src, dest, size) => self
                .add_standard_set(*size, dest, (0, 0), (4, 6), (8, 12))
                .add_two_targets(*size, src, dest),
            Instruction::ORtoCCR(_) => self.add_internal(20),
            Instruction::ORtoSR(_) => self.add_internal(20),

            Instruction::PEA(target) => self.add_indirect_set(target, 12, 16, 20, 16, 20),

            Instruction::RESET => self.add_internal(132),

            Instruction::ROL(_, target, size) | Instruction::ROR(_, target, size) => {
                self.add_word_v_long(*size, 6, 8).add_per_rep(2).add_target(*size, target)
            },
            Instruction::ROXL(_, target, size) | Instruction::ROXR(_, target, size) => {
                self.add_word_v_long(*size, 6, 8).add_per_rep(2).add_target(*size, target)
            },

            Instruction::RTE => self.add_internal(20),
            Instruction::RTR => self.add_internal(20),
            Instruction::RTS => self.add_internal(16),
            //Instruction::RTD(offset) => ,
            Instruction::SBCD(_, dest) => self.add_reg_v_mem(dest, 6, 18),
            Instruction::Scc(_, target) => self
                .add_reg_v_mem(target, 4, 8)
                .add_on_branch(2)
                .add_target(Size::Byte, target),
            Instruction::STOP(_) => self.add_internal(4),

            Instruction::SUB(Target::Immediate(x), Target::DirectAReg(_), Size::Byte)
            | Instruction::SUB(Target::Immediate(x), Target::DirectAReg(_), Size::Word)
                if *x <= 8 =>
            {
                self.add_internal(8)
            }, // SUBQ with an address reg as dest
            Instruction::SUB(Target::Immediate(x), dest, size) if *x <= 8 => {
                self.add_immediate_set(*size, dest, (4, 8), (8, 12)).add_target(*size, dest)
            }, // SUBQ
            Instruction::SUB(Target::Immediate(_), dest, size) => {
                self.add_immediate_set(*size, dest, (8, 16), (12, 20)).add_target(*size, dest)
            }, // SUBI

            Instruction::SUB(src, dest, size) => self
                .add_standard_set(*size, dest, (0, 0), (4, 6), (8, 12))
                .add_two_targets(*size, src, dest),
            Instruction::SUBA(target, _, size) => self.add_word_v_long(*size, 8, 6).add_target(*size, target),
            Instruction::SUBX(_, dest, size) => self.add_reg_mem_set(*size, dest, (4, 8), (18, 30)),

            Instruction::SWAP(_) => self.add_internal(4),

            Instruction::TAS(target) => self.add_reg_v_mem(target, 4, 14).add_target(Size::Byte, target),
            Instruction::TST(target, size) => self.add_internal(4).add_target(*size, target),
            Instruction::TRAP(_) => self.add_internal(34),
            Instruction::TRAPV => self.add_internal(34),

            Instruction::UNLK(_) => self.add_internal(12),
            Instruction::UnimplementedA(_) => self.add_internal(34),
            Instruction::UnimplementedF(_) => self.add_internal(34),
            _ => {
                //panic!("Unexpected instruction for cpu type {:?}: {:?}", self.cputype, instruction);
                self.add_internal(4)
            },
        }
    }

    pub fn add_instruction_68020(&mut self, _instruction: &Instruction) -> &mut Self {
        //match instruction {
        //    // TODO implement
        //    _ => self.add_internal(4),
        //}
        self.add_internal(4)
    }

    pub fn performed_reset(&mut self) {
        self.internal = 0;
        self.accesses = 4;
        self.branched = false;
        self.reps = 0;
    }

    pub fn increase_reps(&mut self, reps: u16) {
        self.reps += reps;
    }

    pub fn branch_taken(&mut self) {
        self.branched = true;
    }

    pub fn calculate_clocks(&self) -> ClockCycles {
        //println!("{:?}", self);
        (self.accesses as ClockCycles * 4)
            + self.internal as ClockCycles
            + (if self.branched { self.on_branch as ClockCycles } else { 0 })
            + self.per_rep as ClockCycles * self.reps
    }

    #[inline(always)]
    pub fn access_size(&self, size: Size) -> u8 {
        if self.bus_size == Size::Word && size == Size::Long {
            2
        } else {
            1
        }
    }
}