From a2fce49b26315eee97a34634c063eeeefcd54f7c Mon Sep 17 00:00:00 2001 From: David Mak Date: Fri, 6 Oct 2023 11:47:28 +0800 Subject: [PATCH] core: Allocate exceptions at the beginning of function Only one instance of exception is necessary, as exceptions will always be initialized before being thrown. --- nac3core/src/codegen/expr.rs | 11 ++++++++--- nac3core/src/codegen/mod.rs | 2 ++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/nac3core/src/codegen/expr.rs b/nac3core/src/codegen/expr.rs index d66dec08..89db94d3 100644 --- a/nac3core/src/codegen/expr.rs +++ b/nac3core/src/codegen/expr.rs @@ -459,9 +459,14 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> { params: [Option>; 3], loc: Location, ) { - let ty = self.get_llvm_type(generator, self.primitives.exception).into_pointer_type(); - let zelf_ty: BasicTypeEnum = ty.get_element_type().into_struct_type().into(); - let zelf = generator.gen_var_alloc(self, zelf_ty, Some("exn")).unwrap(); + let zelf = if let Some(exception_val) = self.exception_val { + exception_val + } else { + let ty = self.get_llvm_type(generator, self.primitives.exception).into_pointer_type(); + let zelf_ty: BasicTypeEnum = ty.get_element_type().into_struct_type().into(); + let zelf = generator.gen_var_alloc(self, zelf_ty, Some("exn")).unwrap(); + self.exception_val.insert(zelf).to_owned() + }; let int32 = self.ctx.i32_type(); let zero = int32.const_zero(); unsafe { diff --git a/nac3core/src/codegen/mod.rs b/nac3core/src/codegen/mod.rs index 28a4d60f..da5cee89 100644 --- a/nac3core/src/codegen/mod.rs +++ b/nac3core/src/codegen/mod.rs @@ -146,6 +146,7 @@ pub struct CodeGenContext<'ctx, 'a> { pub const_strings: HashMap>, // stores the alloca for variables pub init_bb: BasicBlock<'ctx>, + pub exception_val: Option>, /// The header and exit basic blocks of a loop in this context. See /// https://llvm.org/docs/LoopTerminology.html for explanation of these terminology. pub loop_target: Option<(BasicBlock<'ctx>, BasicBlock<'ctx>)>, @@ -802,6 +803,7 @@ pub fn gen_func_impl<'ctx, G: CodeGenerator, F: FnOnce(&mut G, &mut CodeGenConte type_cache, primitives, init_bb, + exception_val: Default::default(), builder, module, unifier,