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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::fmt;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)]
pub enum Cmp {
Slt,
Sle,
Sgt,
Sge,
Eq,
Ne,
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Instr<'a> {
Add(Value, Value),
Sub(Value, Value),
Mul(Value, Value),
Div(Value, Value),
Rem(Value, Value),
Cmp(Type<'a>, Cmp, Value, Value),
And(Value, Value),
Or(Value, Value),
Copy(Value),
Ret(Option<Value>),
Jnz(Value, String, String),
Jmp(String),
Call(String, Vec<(Type<'a>, Value)>),
Alloc4(u32),
Alloc8(u64),
Alloc16(u128),
Store(Type<'a>, Value, Value),
Load(Type<'a>, Value),
Blit(Value, Value, u64),
}
impl<'a> fmt::Display for Instr<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Add(lhs, rhs) => write!(f, "add {}, {}", lhs, rhs),
Self::Sub(lhs, rhs) => write!(f, "sub {}, {}", lhs, rhs),
Self::Mul(lhs, rhs) => write!(f, "mul {}, {}", lhs, rhs),
Self::Div(lhs, rhs) => write!(f, "div {}, {}", lhs, rhs),
Self::Rem(lhs, rhs) => write!(f, "rem {}, {}", lhs, rhs),
Self::Cmp(ty, cmp, lhs, rhs) => {
assert!(
!matches!(ty, Type::Aggregate(_)),
"Cannot compare aggregate types"
);
write!(
f,
"c{}{} {}, {}",
match cmp {
Cmp::Slt => "slt",
Cmp::Sle => "sle",
Cmp::Sgt => "sgt",
Cmp::Sge => "sge",
Cmp::Eq => "eq",
Cmp::Ne => "ne",
},
ty,
lhs,
rhs,
)
}
Self::And(lhs, rhs) => write!(f, "and {}, {}", lhs, rhs),
Self::Or(lhs, rhs) => write!(f, "or {}, {}", lhs, rhs),
Self::Copy(val) => write!(f, "copy {}", val),
Self::Ret(val) => match val {
Some(val) => write!(f, "ret {}", val),
None => write!(f, "ret"),
},
Self::Jnz(val, if_nonzero, if_zero) => {
write!(f, "jnz {}, @{}, @{}", val, if_nonzero, if_zero)
}
Self::Jmp(label) => write!(f, "jmp @{}", label),
Self::Call(name, args) => {
write!(
f,
"call ${}({})",
name,
args.iter()
.map(|(ty, temp)| format!("{} {}", ty, temp))
.collect::<Vec<String>>()
.join(", "),
)
}
Self::Alloc4(size) => write!(f, "alloc4 {}", size),
Self::Alloc8(size) => write!(f, "alloc8 {}", size),
Self::Alloc16(size) => write!(f, "alloc16 {}", size),
Self::Store(ty, dest, value) => {
if matches!(ty, Type::Aggregate(_)) {
unimplemented!("Store to an aggregate type");
}
write!(f, "store{} {}, {}", ty, value, dest)
}
Self::Load(ty, src) => {
if matches!(ty, Type::Aggregate(_)) {
unimplemented!("Load aggregate type");
}
write!(f, "load{} {}", ty, src)
}
Self::Blit(src, dst, n) => write!(f, "blit {}, {}, {}", src, dst, n),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Type<'a> {
Word,
Long,
Single,
Double,
Byte,
Halfword,
Aggregate(&'a TypeDef<'a>),
}
impl<'a> Type<'a> {
pub fn into_abi(self) -> Self {
match self {
Self::Byte | Self::Halfword => Self::Word,
other => other,
}
}
pub fn into_base(self) -> Self {
match self {
Self::Byte | Self::Halfword => Self::Word,
Self::Aggregate(_) => Self::Long,
other => other,
}
}
pub fn size(&self) -> u64 {
match self {
Self::Byte => 1,
Self::Halfword => 2,
Self::Word | Self::Single => 4,
Self::Long | Self::Double => 8,
Self::Aggregate(td) => {
let mut sz = 0_u64;
for (item, repeat) in td.items.iter() {
sz += item.size() * (*repeat as u64);
}
sz
}
}
}
}
impl<'a> fmt::Display for Type<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Byte => write!(f, "b"),
Self::Halfword => write!(f, "h"),
Self::Word => write!(f, "w"),
Self::Long => write!(f, "l"),
Self::Single => write!(f, "s"),
Self::Double => write!(f, "d"),
Self::Aggregate(td) => write!(f, ":{}", td.name),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Value {
Temporary(String),
Global(String),
Const(u64),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Temporary(name) => write!(f, "%{}", name),
Self::Global(name) => write!(f, "${}", name),
Self::Const(value) => write!(f, "{}", value),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct DataDef<'a> {
pub linkage: Linkage,
pub name: String,
pub align: Option<u64>,
pub items: Vec<(Type<'a>, DataItem)>,
}
impl<'a> DataDef<'a> {
pub fn new(
linkage: Linkage,
name: String,
align: Option<u64>,
items: Vec<(Type<'a>, DataItem)>,
) -> Self {
Self {
linkage,
name,
align,
items,
}
}
}
impl<'a> fmt::Display for DataDef<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}data ${} = ", self.linkage, self.name)?;
if let Some(align) = self.align {
write!(f, "align {} ", align)?;
}
write!(
f,
"{{ {} }}",
self.items
.iter()
.map(|(ty, item)| format!("{} {}", ty, item))
.collect::<Vec<String>>()
.join(", ")
)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum DataItem {
Symbol(String, Option<u64>),
Str(String),
Const(u64),
}
impl fmt::Display for DataItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Symbol(name, offset) => match offset {
Some(off) => write!(f, "${} +{}", name, off),
None => write!(f, "${}", name),
},
Self::Str(string) => write!(f, "\"{}\"", string),
Self::Const(val) => write!(f, "{}", val),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct TypeDef<'a> {
pub name: String,
pub align: Option<u64>,
pub items: Vec<(Type<'a>, usize)>,
}
impl<'a> fmt::Display for TypeDef<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "type :{} = ", self.name)?;
if let Some(align) = self.align {
write!(f, "align {} ", align)?;
}
write!(
f,
"{{ {} }}",
self.items
.iter()
.map(|(ty, count)| if *count > 1 {
format!("{} {}", ty, count)
} else {
format!("{}", ty)
})
.collect::<Vec<String>>()
.join(", "),
)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Statement<'a> {
Assign(Value, Type<'a>, Instr<'a>),
Volatile(Instr<'a>),
}
impl<'a> fmt::Display for Statement<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Assign(temp, ty, instr) => {
assert!(matches!(temp, Value::Temporary(_)));
write!(f, "{} ={} {}", temp, ty, instr)
}
Self::Volatile(instr) => write!(f, "{}", instr),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct Block<'a> {
pub label: String,
pub statements: Vec<Statement<'a>>,
}
impl<'a> Block<'a> {
pub fn add_instr(&mut self, instr: Instr<'a>) {
self.statements.push(Statement::Volatile(instr));
}
pub fn assign_instr(&mut self, temp: Value, ty: Type<'a>, instr: Instr<'a>) {
self.statements
.push(Statement::Assign(temp, ty.into_base(), instr));
}
pub fn jumps(&self) -> bool {
let last = self.statements.last();
if let Some(Statement::Volatile(instr)) = last {
matches!(instr, Instr::Ret(_) | Instr::Jmp(_) | Instr::Jnz(..))
} else {
false
}
}
}
impl<'a> fmt::Display for Block<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "@{}", self.label)?;
write!(
f,
"{}",
self.statements
.iter()
.map(|instr| format!("\t{}", instr))
.collect::<Vec<String>>()
.join("\n")
)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct Function<'a> {
pub linkage: Linkage,
pub name: String,
pub arguments: Vec<(Type<'a>, Value)>,
pub return_ty: Option<Type<'a>>,
pub blocks: Vec<Block<'a>>,
}
impl<'a> Function<'a> {
pub fn new(
linkage: Linkage,
name: String,
arguments: Vec<(Type<'a>, Value)>,
return_ty: Option<Type<'a>>,
) -> Self {
Function {
linkage,
name,
arguments,
return_ty,
blocks: Vec::new(),
}
}
pub fn add_block(&mut self, label: String) -> &mut Block<'a> {
self.blocks.push(Block {
label,
statements: Vec::new(),
});
self.blocks.last_mut().unwrap()
}
#[deprecated(
since = "3.0.0",
note = "Use `self.blocks.last()` or `self.blocks.last_mut()` instead."
)]
pub fn last_block(&mut self) -> &Block {
self.blocks
.last()
.expect("Function must have at least one block")
}
pub fn add_instr(&mut self, instr: Instr<'a>) {
self.blocks
.last_mut()
.expect("Last block must be present")
.add_instr(instr);
}
pub fn assign_instr(&mut self, temp: Value, ty: Type<'a>, instr: Instr<'a>) {
self.blocks
.last_mut()
.expect("Last block must be present")
.assign_instr(temp, ty, instr);
}
}
impl<'a> fmt::Display for Function<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}function", self.linkage)?;
if let Some(ty) = &self.return_ty {
write!(f, " {}", ty)?;
}
writeln!(
f,
" ${name}({args}) {{",
name = self.name,
args = self
.arguments
.iter()
.map(|(ty, temp)| format!("{} {}", ty, temp))
.collect::<Vec<String>>()
.join(", "),
)?;
for blk in self.blocks.iter() {
writeln!(f, "{}", blk)?;
}
write!(f, "}}")
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct Linkage {
pub exported: bool,
pub section: Option<String>,
pub secflags: Option<String>,
}
impl Linkage {
pub fn private() -> Linkage {
Linkage {
exported: false,
section: None,
secflags: None,
}
}
pub fn private_with_section(section: String) -> Linkage {
Linkage {
exported: false,
section: Some(section),
secflags: None,
}
}
pub fn public() -> Linkage {
Linkage {
exported: true,
section: None,
secflags: None,
}
}
pub fn public_with_section(section: String) -> Linkage {
Linkage {
exported: true,
section: Some(section),
secflags: None,
}
}
}
impl fmt::Display for Linkage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.exported {
write!(f, "export ")?;
}
if let Some(section) = &self.section {
write!(f, "section \"{}\"", section)?;
if let Some(secflags) = &self.secflags {
write!(f, " \"{}\"", secflags)?;
}
write!(f, " ")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct Module<'a> {
functions: Vec<Function<'a>>,
types: Vec<TypeDef<'a>>,
data: Vec<DataDef<'a>>,
}
impl<'a> Module<'a> {
pub fn new() -> Module<'a> {
Module {
functions: Vec::new(),
types: Vec::new(),
data: Vec::new(),
}
}
pub fn add_function(&mut self, func: Function<'a>) -> &mut Function<'a> {
self.functions.push(func);
return self.functions.last_mut().unwrap();
}
pub fn add_type(&mut self, def: TypeDef<'a>) -> &mut TypeDef<'a> {
self.types.push(def);
self.types.last_mut().unwrap()
}
pub fn add_data(&mut self, data: DataDef<'a>) -> &mut DataDef<'a> {
self.data.push(data);
self.data.last_mut().unwrap()
}
}
impl<'a> fmt::Display for Module<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for func in self.functions.iter() {
writeln!(f, "{}", func)?;
}
for ty in self.types.iter() {
writeln!(f, "{}", ty)?;
}
for data in self.data.iter() {
writeln!(f, "{}", data)?;
}
Ok(())
}
}