Compare commits

..

No commits in common. "025fb089c9d87d8c5092eafef64b9853bb933d31" and "8bef0ab8f278780e0e5a5b16439926e05e933031" have entirely different histories.

24 changed files with 64 additions and 233 deletions

View File

@ -660,8 +660,7 @@ impl Nac3 {
let pass_options = PassBuilderOptions::create(); let pass_options = PassBuilderOptions::create();
pass_options.set_merge_functions(true); pass_options.set_merge_functions(true);
let passes = format!("default<O{}>", self.llvm_options.opt_level as u32); let result = main.run_passes("default<O3>", &target_machine, pass_options);
let result = main.run_passes(passes.as_str(), &target_machine, pass_options);
if let Err(err) = result { if let Err(err) = result {
panic!("Failed to run optimization for module `main`: {}", err.to_string()); panic!("Failed to run optimization for module `main`: {}", err.to_string());
} }

View File

@ -339,7 +339,6 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
let mut return_slot = None; let mut return_slot = None;
if fun.count_params() > 0 { if fun.count_params() > 0 {
let sret_id = Attribute::get_named_enum_kind_id("sret"); let sret_id = Attribute::get_named_enum_kind_id("sret");
let byref_id = Attribute::get_named_enum_kind_id("byref");
let byval_id = Attribute::get_named_enum_kind_id("byval"); let byval_id = Attribute::get_named_enum_kind_id("byval");
let offset = if fun.get_enum_attribute(AttributeLoc::Param(0), sret_id).is_some() { let offset = if fun.get_enum_attribute(AttributeLoc::Param(0), sret_id).is_some() {
@ -351,8 +350,7 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
0 0
}; };
for (i, param) in params.iter().enumerate() { for (i, param) in params.iter().enumerate() {
let loc = AttributeLoc::Param((i + offset) as u32); if fun.get_enum_attribute(AttributeLoc::Param((i + offset) as u32), byval_id).is_some() {
if fun.get_enum_attribute(loc, byref_id).is_some() || fun.get_enum_attribute(loc, byval_id).is_some() {
// lazy update // lazy update
if loc_params.is_empty() { if loc_params.is_empty() {
loc_params.extend(params[0..i+offset].iter().copied()); loc_params.extend(params[0..i+offset].iter().copied());
@ -717,11 +715,11 @@ pub fn gen_call<'ctx, 'a, G: CodeGenerator>(
Some(ctx.get_llvm_type(generator, fun.0.ret)) Some(ctx.get_llvm_type(generator, fun.0.ret))
}; };
let has_sret = ret_type.map_or(false, |ret_type| need_sret(ctx.ctx, ret_type)); let has_sret = ret_type.map_or(false, |ret_type| need_sret(ctx.ctx, ret_type));
let mut byrefs = Vec::new(); let mut byvals = Vec::new();
let mut params = let mut params =
args.iter().enumerate().map(|(i, arg)| match ctx.get_llvm_type(generator, arg.ty) { args.iter().enumerate().map(|(i, arg)| match ctx.get_llvm_type(generator, arg.ty) {
BasicTypeEnum::StructType(ty) if is_extern => { BasicTypeEnum::StructType(ty) if is_extern => {
byrefs.push((i, ty)); byvals.push((i, ty));
ty.ptr_type(AddressSpace::default()).into() ty.ptr_type(AddressSpace::default()).into()
}, },
x => x x => x
@ -741,19 +739,9 @@ pub fn gen_call<'ctx, 'a, G: CodeGenerator>(
} else { } else {
0 0
}; };
for (i, ty) in byvals {
// The attribute ID used to mark arguments of a structure type. fun_val.add_attribute(AttributeLoc::Param((i as u32) + offset),
// Structure-Typed parameters of extern functions must **not** be marked as `byval`, as ctx.ctx.create_type_attribute(Attribute::get_named_enum_kind_id("byval"), ty.as_any_type_enum()));
// `byval` explicitly specifies that the argument is to be passed on the stack, which breaks
// on most ABIs where the first several arguments are expected to be passed in registers.
let passing_attr_id = Attribute::get_named_enum_kind_id(
if is_extern { "byref" } else { "byval" }
);
for (i, ty) in byrefs {
fun_val.add_attribute(
AttributeLoc::Param((i as u32) + offset),
ctx.ctx.create_type_attribute(passing_attr_id, ty.as_any_type_enum())
);
} }
fun_val fun_val
}); });

View File

@ -327,6 +327,7 @@ impl WorkerRegistry {
self.llvm_options.opt_level self.llvm_options.opt_level
).expect(format!("could not create target machine from properties {:?}", self.llvm_options.target).as_str()); ).expect(format!("could not create target machine from properties {:?}", self.llvm_options.target).as_str());
let passes = format!("default<O{}>", self.llvm_options.opt_level as u32); let passes = format!("default<O{}>", self.llvm_options.opt_level as u32);
let result = module.run_passes(passes.as_str(), &target_machine, pass_options); let result = module.run_passes(passes.as_str(), &target_machine, pass_options);
if let Err(err) = result { if let Err(err) = result {
panic!("Failed to run optimization for module `{}`: {}", panic!("Failed to run optimization for module `{}`: {}",

View File

@ -20,41 +20,20 @@
#define usize uint16_t #define usize uint16_t
#endif #endif
struct cslice { void output_int32(const int32_t x) {
const void *data; printf("%d\n", x);
usize len;
};
void output_int32(const int32_t x, bool newline) {
printf("%d", x);
if (newline) {
fputc('\n', stdout);
}
} }
void output_int64(const int64_t x) { void output_int64(const int64_t x) {
printf("%ld", x); printf("%ld\n", x);
if (newline) {
fputc('\n', stdout);
}
} }
void output_uint32(const uint32_t x) { void output_uint32(const uint32_t x) {
printf("%d", x); printf("%d\n", x);
if (newline) {
fputc('\n', stdout);
}
} }
void output_uint64(const uint64_t x) { void output_uint64(const uint64_t x) {
printf("%ld", x); printf("%ld\n", x);
if (newline) {
fputc('\n', stdout);
}
} }
void output_asciiart(const int32_t x) { void output_asciiart(const int32_t x) {
@ -64,29 +43,20 @@ void output_asciiart(const int32_t x) {
} else { } else {
fputc(chars[x], stdout); fputc(chars[x], stdout);
} }
if (newline) {
fputc('\n', stdout);
}
} }
void output_str(struct cslice *slice, bool newline) { struct cslice_int32 {
for (usize i = 0; i < slice->len; ++i) { const int32_t* data;
fputc(((const char *) slice->data)[i], stdout); usize len;
} };
if (newline) { void output_int32_list(struct cslice_int32* slice) {
fputc('\n', stdout);
}
}
void output_int32_list(struct cslice *slice) {
fputc('[', stdout); fputc('[', stdout);
for (usize i = 0; i < slice->len; ++i) { for (usize i = 0; i < slice->len; ++i) {
if (i == slice->len - 1) { if (i == slice->len - 1) {
printf("%d", ((const int32_t *) slice->data)[i]); printf("%d", slice->data[i]);
} else { } else {
printf("%d, ", ((const int32_t *) slice->data)[i]); printf("%d, ", slice->data[i]);
} }
} }
puts("]"); puts("]");

View File

@ -1,7 +1,3 @@
use std::io;
use std::io::Write;
use std::process::exit;
mod cslice { mod cslice {
// copied from https://github.com/dherman/cslice // copied from https://github.com/dherman/cslice
use std::marker::PhantomData; use std::marker::PhantomData;
@ -23,60 +19,30 @@ mod cslice {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_int32(x: i32, newline: bool) { pub extern "C" fn output_int32(x: i32) {
let str = format!("{x}"); println!("{}", x);
if newline {
println!("{str}");
} else {
print!("{str}");
}
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_int64(x: i64, newline: bool) { pub extern "C" fn output_int64(x: i64) {
let str = format!("{x}"); println!("{}", x);
if newline {
println!("{str}");
} else {
print!("{str}");
}
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_uint32(x: u32, newline: bool) { pub extern "C" fn output_uint32(x: u32) {
let str = format!("{x}"); println!("{}", x);
if newline {
println!("{str}");
} else {
print!("{str}");
}
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_uint64(x: u64, newline: bool) { pub extern "C" fn output_uint64(x: u64) {
let str = format!("{x}"); println!("{}", x);
if newline {
println!("{str}");
} else {
print!("{str}");
}
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_float64(x: f64, newline: bool) { pub extern "C" fn output_float64(x: f64) {
// debug output to preserve the digits after the decimal points // debug output to preserve the digits after the decimal points
// to match python `print` function // to match python `print` function
let str = format!("{:?}", x); println!("{:?}", x);
if newline {
println!("{str}");
} else {
print!("{str}");
}
} }
#[no_mangle] #[no_mangle]
@ -90,18 +56,7 @@ pub extern "C" fn output_asciiart(x: i32) {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn output_str(x: &cslice::CSlice<u8>, newline: bool) { pub extern "C" fn output_int32_list(x: &cslice::CSlice<i32>) {
for e in x.as_ref().iter() {
print!("{}", char::from(*e));
}
if newline {
println!("");
}
}
#[no_mangle]
pub extern "C" fn output_int32_list(x: &cslice::CSlice<i32>, newline: bool) {
print!("["); print!("[");
let mut it = x.as_ref().iter().peekable(); let mut it = x.as_ref().iter().peekable();
while let Some(e) = it.next() { while let Some(e) = it.next() {
@ -111,11 +66,7 @@ pub extern "C" fn output_int32_list(x: &cslice::CSlice<i32>, newline: bool) {
print!("{}, ", e); print!("{}, ", e);
} }
} }
print!("]"); println!("]");
if newline {
println!("");
}
} }
#[no_mangle] #[no_mangle]
@ -124,19 +75,10 @@ pub extern "C" fn __nac3_personality(_state: u32, _exception_object: u32, _conte
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn __nac3_raise(state: u32, exception_object: u32, context: u32) -> u32 { pub extern "C" fn __nac3_raise(_state: u32, _exception_object: u32, _context: u32) -> u32 {
writeln!(io::stderr(), unimplemented!();
"__nac3_raise(state: {:#010x}, _exception_object: {:#010x}, _context: {:#010x})",
state,
exception_object,
context
).unwrap();
exit(101);
} }
#[no_mangle]
pub extern "C" fn __nac3_end_catch() {}
extern "C" { extern "C" {
fn run() -> i32; fn run() -> i32;
} }

View File

@ -48,12 +48,6 @@ def patch(module):
else: else:
sys.stdout.write(" .,-:;i+hHM$*#@ "[x]) sys.stdout.write(" .,-:;i+hHM$*#@ "[x])
def output(x, newline: bool=True):
if newline:
print(x)
else:
print(x, end="")
def extern(fun): def extern(fun):
name = fun.__name__ name = fun.__name__
if name == "output_asciiart": if name == "output_asciiart":
@ -64,10 +58,9 @@ def patch(module):
"output_int32_list", "output_int32_list",
"output_uint32", "output_uint32",
"output_uint64", "output_uint64",
"output_float64", "output_float64"
"output_str",
}: }:
return output return print
else: else:
raise NotImplementedError raise NotImplementedError

View File

@ -1,9 +1,9 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
@extern @extern
def output_int64(x: int64, newline: bool=True): def output_int64(x: int64):
... ...

View File

@ -1,5 +1,5 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
def f1(a: int32 = 4): def f1(a: int32 = 4):

View File

@ -1,61 +0,0 @@
@extern
def output_int32(x: int32, newline: bool=True):
...
@extern
def output_int64(x: int64, newline: bool=True):
...
@extern
def output_uint32(x: uint32, newline: bool=True):
...
@extern
def output_uint64(x: uint64, newline: bool=True):
...
@extern
def output_int32_list(x: list[int32], newline: bool=True):
...
@extern
def output_asciiart(x: int32):
...
@extern
def output_str(x: str, newline: bool=True):
...
def test_output_int32():
output_int32(-128)
def test_output_int64():
output_int64(int64(-256))
def test_output_uint32():
output_uint32(uint32(128))
def test_output_uint64():
output_uint64(uint64(256))
def test_output_asciiart():
for i in range(17):
output_asciiart(i)
output_asciiart(0)
def test_output_int32_list():
output_int32_list([0, 1, 3, 5, 10])
def test_output_str_family():
output_str("hello ", newline=False)
output_str("world")
def run() -> int32:
test_output_int32()
test_output_int64()
test_output_uint32()
test_output_uint64()
test_output_asciiart()
test_output_int32_list()
test_output_str_family()
return 0

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
class A: class A:

View File

@ -1,5 +1,5 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...

View File

@ -1,9 +1,9 @@
@extern @extern
def output_int32_list(x: list[int32], newline: bool=True): def output_int32_list(x: list[int32]):
... ...
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
class A: class A:

View File

@ -1,7 +1,7 @@
# For Loop using an increasing range() expression as its iterable # For Loop using an increasing range() expression as its iterable
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
def run() -> int32: def run() -> int32:

View File

@ -1,7 +1,7 @@
# For Loop using a decreasing range() expression as its iterable # For Loop using a decreasing range() expression as its iterable
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
def run() -> int32: def run() -> int32:

View File

@ -1,7 +1,7 @@
# For Loop using a list as its iterable # For Loop using a list as its iterable
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
def run() -> int32: def run() -> int32:

View File

@ -1,7 +1,7 @@
# For Loop using an range() expression as its iterable, additionally reassigning the target on each iteration # For Loop using an range() expression as its iterable, additionally reassigning the target on each iteration
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
def run() -> int32: def run() -> int32:

View File

@ -1,17 +1,17 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
@extern @extern
def output_uint32(x: uint32, newline: bool=True): def output_uint32(x: uint32):
... ...
@extern @extern
def output_int64(x: int64, newline: bool=True): def output_int64(x: int64):
... ...
@extern @extern
def output_uint64(x: uint64, newline: bool=True): def output_uint64(x: uint64):
... ...
@extern @extern
def output_float64(x: float, newline: bool=True): def output_float64(x: float):
... ...

View File

@ -1,19 +1,19 @@
from __future__ import annotations from __future__ import annotations
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
@extern @extern
def output_uint32(x: uint32, newline: bool=True): def output_uint32(x: uint32):
... ...
@extern @extern
def output_int64(x: int64, newline: bool=True): def output_int64(x: int64):
... ...
@extern @extern
def output_uint64(x: uint64, newline: bool=True): def output_uint64(x: uint64):
... ...
@extern @extern
def output_float64(x: float, newline: bool=True): def output_float64(x: float):
... ...
def run() -> int32: def run() -> int32:

View File

@ -1,5 +1,5 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
class A: class A:

View File

@ -1,5 +1,5 @@
@extern @extern
def output_float64(f: float, newline: bool=True): def output_float64(f: float):
... ...

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
@extern @extern
def output_int32(a: int32, newline: bool=True): def output_int32(a: int32):
... ...
class A: class A:

View File

@ -1,9 +1,9 @@
@extern @extern
def output_int32_list(x: list[int32], newline: bool=True): def output_int32_list(x: list[int32]):
... ...
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
class A: class A:

View File

@ -1,5 +1,5 @@
@extern @extern
def output_int32(x: int32, newline: bool=True): def output_int32(x: int32):
... ...
class A: class A:

View File

@ -370,8 +370,7 @@ fn main() {
let pass_options = PassBuilderOptions::create(); let pass_options = PassBuilderOptions::create();
pass_options.set_merge_functions(true); pass_options.set_merge_functions(true);
let passes = format!("default<O{}>", opt_level as u32); let result = main.run_passes("default<O3>", &target_machine, pass_options);
let result = main.run_passes(passes.as_str(), &target_machine, pass_options);
if let Err(err) = result { if let Err(err) = result {
panic!("Failed to run optimization for module `main`: {}", err.to_string()); panic!("Failed to run optimization for module `main`: {}", err.to_string());
} }