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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
use std::{fmt::Display, collections::{HashSet, HashMap}};

use super::arch::{Instr, InstructionSelector, VCode, VCodeGenerator};

#[derive(Default)]
pub struct Module {
    name: String,
    functions: Vec<Function>,
}

impl Module {
    pub fn lower_to_vcode<I, S>(self) -> VCode<I>
    where
        S: InstructionSelector<Instruction = I>,
        I: Instr,
    {
        let mut gen = VCodeGenerator::<I, S>::new_module(&self.name);
        let mut selector = S::default();

        for (i, function) in self.functions.iter().enumerate() {
            gen.add_function(&function.name, FunctionId(i));
        }

        for (f, func) in self.functions.into_iter().enumerate() {
            gen.switch_to_function(FunctionId(f));
            for (i, block) in func.blocks.iter().enumerate() {
                if block.deleted {
                    continue;
                }

                gen.push_label(BasicBlockId(FunctionId(f), i));
            }

            for (i, block) in func.blocks.into_iter().enumerate() {
                if block.deleted {
                    continue;
                }

                gen.switch_to_label(BasicBlockId(FunctionId(f), i));
                for instr in block.instructions {
                    selector.select_instr(&mut gen, instr.yielded, instr.type_, instr.operation);
                }
                selector.select_term(&mut gen, block.terminator);
            }
        }

        gen.build(selector)
    }
}

impl Display for Module {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "/* module {} */", self.name)?;
        for (i, func) in self.functions.iter().enumerate() {
            writeln!(f, "\n\n@{}: {}", i, func)?;
        }

        Ok(())
    }
}

#[derive(Clone)]
pub enum Type {
    Void,
    Integer(bool, u8),
}

impl Display for Type {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Type::Void => write!(f, "void"),
            Type::Integer(signed, width) => {
                write!(f, "{}{}", if *signed { "i" } else { "u" }, width)
            }
        }
    }
}

struct Function {
    name: String,
    arg_types: Vec<Type>,
    ret_type: Type,
    variables: Vec<Variable>,
    blocks: Vec<BasicBlock>,
    value_index: usize,
}

impl Display for Function {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "function {} @{}(", self.ret_type, self.name)?;
        let mut first = true;
        for arg_type in self.arg_types.iter() {
            if first {
                first = false;
            } else {
                write!(f, ", ")?;
            }
            write!(f, "{}", arg_type)?;
        }
        writeln!(f, ") {{")?;

        for (i, var) in self.variables.iter().enumerate() {
            writeln!(f, "    #{} : {} // {}", i, var.type_, var.name)?;
        }

        for (i, block) in self.blocks.iter().enumerate() {
            if !block.deleted {
                write!(f, "{}: // preds =", i)?;
                for pred in block.predecessors.iter() {
                    write!(f, " {}", pred)?;
                }
                write!(f, "\n{}", block)?;
            }
        }
        write!(f, "}}")
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct FunctionId(usize);

impl Display for FunctionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "@{}", self.0)
    }
}

struct Variable {
    name: String,
    type_: Type,
}

#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct VariableId(usize);

impl Display for VariableId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "#{}", self.0)
    }
}

struct BasicBlock {
    deleted: bool,
    predecessors: HashSet<BasicBlockId>,
    instructions: Vec<Instruction>,
    terminator: Terminator,
}

impl Display for BasicBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for instruction in self.instructions.iter() {
            writeln!(f, "    {}", instruction)?;
        }
        writeln!(f, "    {}", self.terminator)
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct BasicBlockId(FunctionId, usize);

impl Display for BasicBlockId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "${}", self.1)
    }
}

struct Instruction {
    yielded: Option<Value>,
    type_: Type,
    operation: Operation,
}

impl Display for Instruction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(yielded) = &self.yielded {
            write!(f, "{} = ", yielded)?;
        }

        write!(f, "{} {}", self.type_, self.operation)
    }
}

pub trait ToIntegerOperation {
    fn to_integer_operation(self) -> Operation;
}

impl ToIntegerOperation for i8 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for u8 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for i16 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for u16 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for i32 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for u32 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for i64 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for u64 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for i128 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

impl ToIntegerOperation for u128 {
    fn to_integer_operation(self) -> Operation {
        Operation::Integer(true, self.to_le_bytes().to_vec())
    }
}

pub enum Operation {
    Identity(Value),

    Integer(bool, Vec<u8>),

    Add(Value, Value),
    Sub(Value, Value),
    Mul(Value, Value),
    Div(Value, Value),
    Mod(Value, Value),
    Bsl(Value, Value),
    Bsr(Value, Value),
    Eq(Value, Value),
    Ne(Value, Value),
    Lt(Value, Value),
    Le(Value, Value),
    Gt(Value, Value),
    Ge(Value, Value),
    BitAnd(Value, Value),
    BitOr(Value, Value),
    BitXor(Value, Value),

    Phi(Vec<(BasicBlockId, Value)>),

    GetVar(VariableId),
    SetVar(VariableId, Value),

    Call(FunctionId, Vec<Value>),
    CallIndirect(Value, Vec<Value>),
}

impl Display for Operation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Operation::Identity(val) => write!(f, "id {}", val),

            Operation::Integer(signed, val) => {
                if *signed {
                    write!(f, "iconst ")?;
                } else {
                    write!(f, "uconst ")?;
                }

                if val.is_empty() {
                    write!(f, "0")
                } else {
                    for byte in val.iter().rev() {
                        write!(f, "{:02x}", byte)?;
                    }
                    Ok(())
                }
            }

            Operation::Add(a, b) => write!(f, "addi {}, {}", a, b),
            Operation::Sub(a, b) => write!(f, "subi {}, {}", a, b),
            Operation::Mul(a, b) => write!(f, "muli {}, {}", a, b),
            Operation::Div(a, b) => write!(f, "divi {}, {}", a, b),
            Operation::Mod(a, b) => write!(f, "mod {}, {}", a, b),
            Operation::Bsl(a, b) => write!(f, "shiftl {}, {}", a, b),
            Operation::Bsr(a, b) => write!(f, "shiftr {}, {}", a, b),
            Operation::Eq(a, b) => write!(f, "eqi {}, {}", a, b),
            Operation::Ne(a, b) => write!(f, "neqi {}, {}", a, b),
            Operation::Lt(a, b) => write!(f, "lti {}, {}", a, b),
            Operation::Le(a, b) => write!(f, "leqi {}, {}", a, b),
            Operation::Gt(a, b) => write!(f, "gti {}, {}", a, b),
            Operation::Ge(a, b) => write!(f, "geqi {}, {}", a, b),
            Operation::BitAnd(a, b) => write!(f, "andi {}, {}", a, b),
            Operation::BitOr(a, b) => write!(f, "ori {}, {}", a, b),
            Operation::BitXor(a, b) => write!(f, "xori {}, {}", a, b),

            Operation::Phi(maps) => {
                write!(f, "phi ")?;
                let mut first = true;
                for (block, value) in maps {
                    if first {
                        first = false;
                    } else {
                        write!(f, ", ")?;
                    }

                    write!(f, "{} => {}", block, value)?;
                }
                Ok(())
            }

            Operation::GetVar(var) => write!(f, "get {}", var),
            Operation::SetVar(var, val) => write!(f, "set {}, {}", var, val),

            Operation::Call(func, args) => {
                write!(f, "call {}(", func)?;
                let mut first = true;
                for arg in args {
                    if first {
                        first = false;
                    } else {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", arg)?;
                }
                write!(f, ")")
            }

            Operation::CallIndirect(func, args) => {
                write!(f, "icall {}(", func)?;
                let mut first = true;
                for arg in args {
                    if first {
                        first = false;
                    } else {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", arg)?;
                }
                write!(f, ")")
            }
        }
    }
}

pub enum Terminator {
    NoTerminator,
    ReturnVoid,
    Return(Value),
    Jump(BasicBlockId),
    Branch(Value, BasicBlockId, BasicBlockId),
}

impl Display for Terminator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Terminator::NoTerminator => write!(f, "noterm"),
            Terminator::ReturnVoid => write!(f, "ret void"),
            Terminator::Return(v) => write!(f, "ret {}", v),
            Terminator::Jump(b) => write!(f, "jump {}", b),
            Terminator::Branch(c, t, e) => write!(f, "branch {}, {}, {}", c, t, e),
        }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct Value(usize);

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "%{}", self.0)
    }
}

/// [`ModuleBuilder`] is used to build a module.
///
/// # Example
/// ```rust
/// # fn testy() -> Option<()> {
/// # use codegem::ir::*;
/// let mut builder = ModuleBuilder::default()
///     .with_name("uwu");
/// let main = builder.new_function("main", &[], &Type::Void);
/// builder.switch_to_function(main);
/// let entry = builder.push_block()?;
/// builder.switch_to_block(entry);
/// let val = builder.push_instruction(
///     &Type::Integer(true, 32),
///     69u32.to_integer_operation()
/// )?;
/// builder.set_terminator(Terminator::Return(val));
/// let module = builder.build();
/// # Some(())
/// # }
/// ```
#[derive(Default)]
pub struct ModuleBuilder {
    internal: Module,
    current_function: Option<usize>,
    current_block: Option<usize>,
}

impl ModuleBuilder {
    /// Sets the name of the module being built.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// let builder = ModuleBuilder::default()
    ///     .with_name("uwu");
    /// ```
    pub fn with_name(mut self, name: &str) -> Self {
        self.internal.name = name.to_owned();
        self
    }

    /// Consumes the builder and returns a module, performing some mandatory transformations such
    /// as dead code elimination and Phi operation lowering, as well as checking for malformed IR.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// let empty_module = ModuleBuilder::default()
    ///     .build();
    /// ```
    // TODO: return Result<Module, MalformedIrError> on malformed IR instead of panicking.
    pub fn build(mut self) -> Module {
        for (f, func) in self.internal.functions.iter_mut().enumerate() {
            let mut blocks_prec = vec![HashSet::new(); func.blocks.len()];
            for (i, block) in func.blocks.iter().enumerate() {
                match &block.terminator {
                    Terminator::NoTerminator => (),
                    Terminator::ReturnVoid => (),
                    Terminator::Return(_) => (),

                    Terminator::Jump(next) => {
                        let this = BasicBlockId(FunctionId(f), i);
                        blocks_prec[next.1].insert(this);
                    }

                    Terminator::Branch(_, on_true, on_false) => {
                        let this = BasicBlockId(FunctionId(f), i);
                        blocks_prec[on_true.1].insert(this);
                        blocks_prec[on_false.1].insert(this);
                    }
                }
            }

            for (block, prec) in func.blocks.iter_mut().zip(blocks_prec.into_iter()) {
                block.predecessors = prec;
            }

            let mut removed = Vec::new();
            while {
                removed.clear();

                for (i, block) in func.blocks.iter_mut().enumerate() {
                    if block.deleted || i == 0 {
                        continue;
                    }

                    if block.predecessors.is_empty() {
                        block.deleted = true;
                        removed.push(BasicBlockId(FunctionId(f), i));
                    }
                }

                for block in func.blocks.iter_mut() {
                    for remove in removed.iter() {
                        block.predecessors.remove(remove);
                    }
                }

                !removed.is_empty()
            } {}

            for block in func.blocks.iter() {
                if block.deleted {
                    continue;
                }

                if let Terminator::Branch(_, a, b) = block.terminator {
                    if func.blocks[a.1].predecessors.len() > 1 || func.blocks[b.1].predecessors.len() > 1 {
                        panic!("malformed ir");
                    }
                }
            }

            let mut var_map = HashMap::new();
            let mut phi_to_var_map = HashMap::new();
            for (i, block) in func.blocks.iter_mut().enumerate() {
                if block.deleted {
                    continue;
                }

                match block.predecessors.len() {
                    0 => (),

                    1 => {
                        let prev = block.predecessors.iter().next().unwrap().1;
                        for var in func.arg_types.len()..func.variables.len() {
                            let var = VariableId(var);
                            if let Some(&val) = var_map.get(&(var, prev)) {
                                var_map.insert((var, i), val);
                            }
                        }
                    }

                    _ => {
                        for var in func.arg_types.len()..func.variables.len() {
                            let var = VariableId(var);
                            let operation = Operation::Phi(Vec::new());
                            let val = Value(func.value_index);
                            func.value_index += 1;
                            let phi = Instruction {
                                yielded: Some(val),
                                type_: func.variables[var.0].type_.clone(),
                                operation,
                            };
                            block.instructions.insert(0, phi);
                            var_map.insert((var, i), val);
                            phi_to_var_map.insert(val, var);
                        }
                    }
                }

                let mut to_remove = Vec::new();
                for (j, instruction) in block.instructions.iter_mut().enumerate() {
                    match instruction.operation {
                        Operation::GetVar(var) => {
                            match var_map.get(&(var, i)) {
                                Some(&val) => {
                                    instruction.operation = Operation::Identity(val);
                                }

                                None => {
                                    panic!("malformed ir");
                                }
                            }
                        }

                        Operation::SetVar(var, val) => {
                            var_map.insert((var, i), val);
                            to_remove.push(j);
                        }

                        _ => (),
                    }
                }

                for remove in to_remove.into_iter().rev() {
                    block.instructions.remove(remove);
                }
            }

            for block in func.blocks.iter_mut() {
                if block.deleted {
                    continue;
                }

                if block.predecessors.len() > 1 {
                    for instruction in block.instructions.iter_mut() {
                        if let Operation::Phi(mapping) = &mut instruction.operation {
                            if let Some(&var) = instruction.yielded.as_ref().and_then(|v| phi_to_var_map.get(v)) {
                                *mapping = block.predecessors.iter().filter_map(|&v| var_map.get(&(var, v.1)).map(|&u| (v, u))).collect();
                            }
                        }
                    }
                }
            }
        }

        self.internal
    }

    /// Adds a new function to the module being built. Returns a [`FunctionId`], which can be used
    /// to reference the built function.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) {
    /// let main_func = builder.new_function("main", &[], &Type::Void);
    /// # }
    /// ```
    pub fn new_function(
        &mut self,
        name: &str,
        args: &[(&str, Type)],
        ret_type: &Type,
    ) -> FunctionId {
        let id = self.internal.functions.len();
        self.internal.functions.push(Function {
            name: name.to_owned(),
            arg_types: args.iter().map(|(_, t)| t.clone()).collect(),
            ret_type: ret_type.clone(),
            variables: args
                .iter()
                .map(|(n, t)| Variable {
                    name: (*n).to_owned(),
                    type_: t.clone(),
                })
                .collect(),
            blocks: Vec::new(),
            value_index: 0,
        });
        FunctionId(id)
    }

    /// Switches the function to which the builder is currently adding blocks and instructions.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) {
    /// let main_func = builder.new_function("main", &[], &Type::Void);
    /// builder.switch_to_function(main_func);
    /// # }
    /// ```
    pub fn switch_to_function(&mut self, id: FunctionId) {
        self.current_function = Some(id.0);
        self.current_block = None;
    }

    /// Adds a new basic block to the current function. Returns a [`BasicBlockId`], which can be used
    /// to reference the built basic block. Returns None if there is no function currently
    /// selected.
    ///
    /// A basic block is a single strand of code that does not have any control flow within it.
    /// Function calls do not count as control flow in this case. Each basic block contains
    /// instructions and ends with a single terminator, which may jump to one or more basic blocks,
    /// or exit from the current function or program.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) -> Option<()> {
    /// let entry_block = builder.push_block()?;
    /// # None
    /// # }
    /// ```
    pub fn push_block(&mut self) -> Option<BasicBlockId> {
        if let Some(func_id) = self.current_function {
            let func = unsafe { self.internal.functions.get_unchecked_mut(func_id) };
            let block_id = func.blocks.len();
            func.blocks.push(BasicBlock {
                deleted: false,
                predecessors: HashSet::new(),
                instructions: Vec::new(),
                terminator: Terminator::NoTerminator,
            });
            Some(BasicBlockId(FunctionId(func_id), block_id))
        } else {
            None
        }
    }

    /// Switches the basic block to which the builder is currently adding blocks and instructions.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) -> Option<()> {
    /// let entry_block = builder.push_block()?;
    /// builder.switch_to_block(entry_block);
    /// # None
    /// # }
    /// ```
    pub fn switch_to_block(&mut self, id: BasicBlockId) {
        match self.current_function {
            Some(x) if id.0 .0 == x => self.current_block = Some(id.1),
            _ => self.current_block = None,
        }
    }

    /// Pushes an instruction to the current block in the current function. Returns an optional
    /// [`Value`] depending on if there is a selected function and block, and if the instruction
    /// does yield a value. (Some [`Operation`]s, such as [`Operation::SetVar`], do not return
    /// anything.)
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) -> Option<()> {
    /// builder.push_instruction(
    ///     &Type::Integer(true, 32),
    ///     69i32.to_integer_operation()
    /// );
    /// # None
    /// # }
    pub fn push_instruction(&mut self, type_: &Type, instr: Operation) -> Option<Value> {
        if let Some(func_id) = self.current_function {
            if let Some(block_id) = self.current_block {
                let yielded = match &instr {
                    Operation::SetVar(_, _) => false,
                    Operation::Call(f, _) => {
                        if let Some(f) = self.internal.functions.get(f.0) {
                            !matches!(f.ret_type, Type::Void)
                        } else {
                            false
                        }
                    }

                    _ => true,
                };
                let func = unsafe { self.internal.functions.get_unchecked_mut(func_id) };
                let block = unsafe { func.blocks.get_unchecked_mut(block_id) };
                let yielded = if yielded {
                    Some(Value(func.value_index))
                } else {
                    None
                };
                func.value_index += 1;
                block.instructions.push(Instruction {
                    yielded,
                    type_: type_.clone(),
                    operation: instr,
                });
                if let Type::Void = type_ {
                    return None;
                } else {
                    return yielded;
                }
            }
        }

        None
    }

    /// Sets the [`Terminator`] of the current basic block.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) {
    /// builder.set_terminator(Terminator::ReturnVoid);
    /// # }
    pub fn set_terminator(&mut self, terminator: Terminator) {
        if let Some(func_id) = self.current_function {
            if let Some(block_id) = self.current_block {
                let func = unsafe { self.internal.functions.get_unchecked_mut(func_id) };
                let block = unsafe { func.blocks.get_unchecked_mut(block_id) };
                block.terminator = terminator;
            }
        }
    }

    /// Pushes a variable of the given name and type to the current function. This variable can be
    /// used anywhere in the function it is defined in. Currently, creating an [`Operation::GetVar`]
    /// instruction before an [`Operation::SetVar`] instruction is undefined behaviour. Returns a
    /// [`VariableId`] if there is a currently selected function, which can be used to reference
    /// the variable.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) {
    /// let i = builder.push_variable("i", &Type::Integer(true, 32));
    /// # }
    /// ```
    pub fn push_variable(&mut self, name: &str, type_: &Type) -> Option<VariableId> {
        if let Some(func_id) = self.current_function {
            let func = unsafe { self.internal.functions.get_unchecked_mut(func_id) };
            let id = func.variables.len();
            func.variables.push(Variable {
                name: name.to_owned(),
                type_: type_.clone(),
            });
            Some(VariableId(id))
        } else {
            None
        }
    }

    /// Gets the currently selected function.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) {
    /// let current = builder.get_function();
    /// # }
    /// ```
    pub fn get_function(&self) -> Option<FunctionId> {
        self.current_function.map(FunctionId)
    }

    /// Gets the arguments of the given function as variables
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) -> Option<()> {
    /// let current = builder.get_function()?;
    /// let args = builder.get_function_args(current)?;
    /// # None
    /// # }
    /// ```
    pub fn get_function_args(&self, func: FunctionId) -> Option<Vec<VariableId>> {
        self.internal
            .functions
            .get(func.0)
            .map(|f| (0..f.arg_types.len()).into_iter().map(VariableId).collect())
    }

    /// Gets the currently selected basic block.
    ///
    /// # Example
    /// ```rust
    /// # use codegem::ir::*;
    /// # fn testy(builder: &mut ModuleBuilder) -> Option<()> {
    /// let current = builder.get_block()?;
    /// # None
    /// # }
    /// ```
    pub fn get_block(&self) -> Option<BasicBlockId> {
        if let Some(f) = self.get_function() {
            self.current_block.map(|b| BasicBlockId(f, b))
        } else {
            None
        }
    }
}