From 541362b7a0d50db29d00822dce3443ef294ea4cc Mon Sep 17 00:00:00 2001 From: dytlzl Date: Sun, 18 Oct 2026 17:33:05 +0900 Subject: [PATCH] refactor: split parser and generator responsibilities --- src/ast.rs | 422 +------------- src/ast/declarations.rs | 104 ++-- src/ast/functions.rs | 75 +++ src/ast/statements.rs | 466 ++++++++++++++++ src/ctype.rs | 516 +----------------- src/ctype/arithmetic.rs | 109 ++++ src/ctype/compatibility.rs | 80 +++ src/ctype/layout.rs | 145 +++++ src/ctype/lowering.rs | 119 ++++ src/ctype/records.rs | 82 +++ src/generator/aarch64/generator.rs | 333 +---------- src/generator/aarch64/generator/calls.rs | 142 +++++ .../aarch64/generator/control_flow.rs | 190 +++++++ src/generator/llvm/generator.rs | 436 +-------------- src/generator/llvm/generator/calls.rs | 95 ++++ src/generator/llvm/generator/control_flow.rs | 349 ++++++++++++ src/generator/x86_64/generator.rs | 344 +----------- src/generator/x86_64/generator/calls.rs | 118 ++++ .../x86_64/generator/control_flow.rs | 238 ++++++++ src/node.rs | 438 +-------------- src/node/debug.rs | 122 +++++ src/node/effects.rs | 44 ++ src/node/types.rs | 243 +++++++++ src/node/walk.rs | 46 ++ 24 files changed, 2780 insertions(+), 2476 deletions(-) create mode 100644 src/ast/functions.rs create mode 100644 src/ast/statements.rs create mode 100644 src/ctype/arithmetic.rs create mode 100644 src/ctype/compatibility.rs create mode 100644 src/ctype/layout.rs create mode 100644 src/ctype/lowering.rs create mode 100644 src/ctype/records.rs create mode 100644 src/generator/aarch64/generator/calls.rs create mode 100644 src/generator/aarch64/generator/control_flow.rs create mode 100644 src/generator/llvm/generator/calls.rs create mode 100644 src/generator/llvm/generator/control_flow.rs create mode 100644 src/generator/x86_64/generator/calls.rs create mode 100644 src/generator/x86_64/generator/control_flow.rs create mode 100644 src/node/debug.rs create mode 100644 src/node/effects.rs create mode 100644 src/node/types.rs create mode 100644 src/node/walk.rs diff --git a/src/ast.rs b/src/ast.rs index 91021b8..d4865c2 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -1,3 +1,5 @@ +mod functions; +mod statements; use crate::ctype::{Qualifiers, StructDefinition, StructMember, StructType, Type}; use crate::error; use crate::func::Func; @@ -451,426 +453,6 @@ impl<'a> AstBuilderImpl<'a> { self.cur >= self.tokens.len() || matches!(self.tokens[self.cur].tt, TokenType::EOF) } - fn stmt(&mut self) -> Node { - while self.attempt_reserved("__extension__").is_some() {} - self.declaration_attributes(false, None, true); - if matches!( - self.tokens[self.cur].tt, - TokenType::Reserved | TokenType::Ident - ) && matches!( - self.tokens[self.cur].s_value.as_str(), - "asm" | "__asm" | "__asm__" - ) { - let token = self.tokens[self.cur].clone(); - self.cur += 1; - return self.inline_assembly(token); - } - if self.attempt_static_assert() { - return Node { - nt: NodeType::Block, - ..Node::default() - }; - } - if self.tokens[self.cur].tt == TokenType::Ident && self.tokens[self.cur + 1].s_value == ":" - { - let token = self.attempt_ident().unwrap(); - self.expect_reserved(":"); - if !self.defined_labels.insert(token.s_value.to_string()) { - self.error_logger - .print_error_position(token.pos, "duplicate label"); - } - let id = *self - .labels - .entry(token.s_value.to_string()) - .or_insert(token.pos); - let vla_scope = self.vla_active.clone(); - let lhs = Some(Box::new(self.stmt())); - return Node { - nt: NodeType::Label, - token: Some(token), - lhs, - value: Some(id), - vla_scope, - ..Node::default() - }; - } - if let Some(token) = self.attempt_reserved("goto") { - let name = self.attempt_ident().unwrap_or_else(|| { - self.error_logger - .print_error_position(self.tokens[self.cur].pos, "goto requires a label"); - unreachable!() - }); - let id = *self - .labels - .entry(name.s_value.to_string()) - .or_insert(name.pos); - self.expect_reserved(";"); - return Node { - nt: NodeType::Goto, - token: Some(token.clone()), - value: Some(id), - args: self.dynamic_objects.clone(), - vla_scope: self.vla_active.clone(), - ..Node::default() - }; - } - if let Some(token) = self.attempt_reserved("typedef") { - self.typedef_definition(); - self.expect_reserved(";"); - return Node { - nt: NodeType::Block, - token: Some(token.clone()), - children: self.take_bounds(), - ..Node::default() - }; - } - if let Some(token) = self.attempt_reserved(";") { - return Node { - nt: NodeType::Block, - token: Some(token.clone()), - ..Node::default() - }; - } - if let Some(t) = self.attempt_reserved("switch") { - self.expect_reserved("("); - let cond = self.expr(); - self.expect_reserved(")"); - if cond - .resolve_type() - .is_none_or(|ty| ty.integer_info().is_none()) - { - self.error_logger - .print_error_position(t.pos, "switch requires an integer expression"); - } - self.switch_vla_depths.push(self.vla_active.len()); - self.jump_depths.push(self.dynamic_objects.len()); - self.switch_stack.push(vec![]); - self.switch_types - .push(cond.resolve_type().unwrap().promoted()); - let body = self.stmt(); - let cases = self.switch_stack.pop().unwrap(); - self.switch_types.pop(); - self.switch_vla_depths.pop(); - self.jump_depths.pop(); - return Node { - nt: NodeType::Switch, - token: Some(t.clone()), - cond: Some(Box::new(cond)), - then: Some(Box::new(body)), - children: cases, - ..Node::default() - }; - } - if let Some(t) = self - .attempt_reserved("case") - .or_else(|| self.attempt_reserved("default")) - { - if self.switch_stack.is_empty() { - self.error_logger - .print_error_position(t.pos, "case or default requires an enclosing switch"); - } - if self.vla_active.len() > *self.switch_vla_depths.last().unwrap() { - self.error_logger.print_error_position( - t.pos, - "switch label enters the scope of a variably modified declaration", - ); - } - let value = if t.s_value == "case" { - let expr = self.ternary(); - let value = self.eval(&expr); - Some(self.switch_types.last().unwrap().convert_constant(value) as usize) - } else { - None - }; - self.expect_reserved(":"); - if self - .switch_stack - .last() - .unwrap() - .iter() - .any(|case| case.value == value) - { - self.error_logger - .print_error_position(t.pos, "duplicate switch label"); - } - let mut node = Node { - nt: NodeType::Case, - token: Some(t.clone()), - value, - ..Node::default() - }; - self.switch_stack.last_mut().unwrap().push(node.clone()); - node.lhs = Some(Box::new(self.stmt())); - return node; - } - if let Some(t) = self.attempt_reserved("if") { - self.expect_reserved("("); - let cond = self.expr(); - self.expect_reserved(")"); - let then = self.stmt(); - let mut els: Option = None; - if self.attempt_reserved("else").is_some() { - els = Some(self.stmt()); - } - return Node::new_if_node(Some(t.clone()), cond, then, els); - } - if let Some(t) = self.attempt_reserved("do") { - self.loop_stack.push(t.pos); - self.continue_depths - .insert(t.pos, self.dynamic_objects.len()); - self.jump_depths.push(self.dynamic_objects.len()); - let body = self.stmt(); - self.loop_stack.pop(); - self.jump_depths.pop(); - self.expect_reserved("while"); - self.expect_reserved("("); - let cond = self.expr(); - self.expect_reserved(")"); - self.expect_reserved(";"); - let mut node = Node::new_while_node(Some(t.clone()), cond, body); - node.nt = NodeType::DoWhile; - return node; - } - if let Some(t) = self.attempt_reserved("while") { - self.expect_reserved("("); - let cond = self.expr(); - self.expect_reserved(")"); - self.loop_stack.push(t.pos); - self.continue_depths - .insert(t.pos, self.dynamic_objects.len()); - self.jump_depths.push(self.dynamic_objects.len()); - let body = self.stmt(); - self.loop_stack.pop(); - self.jump_depths.pop(); - return Node::new_while_node(Some(t.clone()), cond, body); - } - if let Some(t) = self.attempt_reserved("for") { - let object_depth = self.dynamic_objects.len(); - let bound_depth = self.vla_active.len(); - self.scope_stack.push(HashMap::new()); - self.expect_reserved("("); - let mut ini: Option = None; - let mut cond: Option = None; - let mut upd: Option = None; - if self.attempt_reserved(";").is_none() { - ini = Some( - if let Some((ty, storage, alignment)) = self.attempt_automatic_type(false) { - self.local_variable_definition_with_storage(ty, storage, alignment) - } else { - self.expr() - }, - ); - self.expect_reserved(";"); - } - if self.attempt_reserved(";").is_none() { - cond = Some(self.expr()); - self.expect_reserved(";"); - } - if self.attempt_reserved(")").is_none() { - upd = Some(self.expr()); - self.expect_reserved(")"); - } - self.loop_stack.push(t.pos); - self.continue_depths - .insert(t.pos, self.dynamic_objects.len()); - self.jump_depths.push(self.dynamic_objects.len()); - let body = self.stmt(); - self.loop_stack.pop(); - self.jump_depths.pop(); - self.scope_stack.pop(); - let loop_node = Node::new_for_node(Some(t.clone()), ini, cond, upd, body); - let mut children = vec![loop_node]; - children.extend(self.cleanup_arrays(object_depth)); - self.dynamic_objects.truncate(object_depth); - self.vla_active.truncate(bound_depth); - return Node { - nt: NodeType::Block, - children, - ..Node::default() - }; - } - if let Some(node) = self.consume_block() { - return node; - } - let mut requested_alignment = self.object_alignment_annotations(); - let mut thread_local = false; - while let Some(value) = self.attempt_alignment_specifier() { - requested_alignment = requested_alignment.max(value); - } - let inline = self.attempt_inline(); - let storage = self - .attempt_reserved("static") - .or_else(|| self.attempt_reserved("extern")); - let inline = inline.or_else(|| self.attempt_inline()); - let mut storage = storage; - loop { - requested_alignment = requested_alignment.max(self.object_alignment_annotations()); - if self.attempt_thread_local() { - thread_local = true; - } else if let Some(token) = self - .attempt_reserved("static") - .or_else(|| self.attempt_reserved("extern")) - { - if storage.is_some() { - self.error_logger - .print_error_position(token.pos, "conflicting storage classes"); - } else { - storage = Some(token); - } - } else { - break; - } - } - if thread_local && storage.is_none() { - self.error_logger.print_error_position( - self.tokens[self.cur - 1].pos, - "block thread-local declaration requires static or extern storage", - ); - } - if storage.is_some() || inline.is_some() || thread_local { - let mut storage = storage.cloned().unwrap_or_else(|| { - inline.cloned().unwrap_or_else(|| Token { - s_value: "static".to_owned().into(), - ..self.tokens[self.cur - 1].clone() - }) - }); - if matches!( - storage.s_value.as_str(), - "inline" | "__inline" | "__inline__" - ) { - storage.s_value = "extern".to_owned().into(); - } - requested_alignment = requested_alignment.max(self.object_alignment_annotations()); - let ty = self.expect_type(); - requested_alignment = requested_alignment.max(self.object_alignment_annotations()); - let declaration = self.local_static_definition( - ty, - &storage, - inline.is_some(), - requested_alignment, - thread_local, - ); - self.expect_reserved(";"); - return declaration; - } - let node = if let Some((ty, storage, alignment)) = self.attempt_automatic_type(false) { - if storage == AutomaticStorage::Register && requested_alignment != 0 { - self.error_logger.print_error_position( - self.tokens[self.cur].pos, - "alignment cannot be applied to a register object", - ); - } - if self.tokens[self.cur].s_value == ";" { - if alignment.max(requested_alignment) != 0 { - self.error_logger.print_error_position( - self.tokens[self.cur].pos, - "alignment requires an object declaration", - ); - } - Node { - nt: NodeType::Block, - ..Node::default() - } - } else { - self.local_variable_definition_with_storage( - ty, - storage, - alignment.max(requested_alignment), - ) - } - } else if requested_alignment != 0 { - self.error_logger.print_error_position( - self.tokens[self.cur].pos, - "alignment requires an object declaration", - ); - unreachable!() - } else if let Some(t) = self.attempt_reserved("continue") { - let target = self.loop_stack.last().copied().unwrap_or_else(|| { - self.error_logger - .print_error_position(t.pos, "continue requires an enclosing loop"); - unreachable!() - }); - Node { - nt: NodeType::Continue, - token: Some(t.clone()), - value: Some(target), - ..Node::default() - } - } else if let Some(t) = self.attempt_reserved("break") { - Node { - nt: NodeType::Break, - token: Some(t.clone()), - ..Node::default() - } - } else if let Some(t) = self.attempt_reserved("return") { - let mut operand = if self.tokens[self.cur].s_value == ";" { - None - } else { - Some(self.expr()) - }; - let expected_void = self.return_type == Some(Type::Void); - let actual_void = operand - .as_ref() - .is_none_or(|operand| operand.resolve_type() == Some(Type::Void)); - if expected_void != actual_void { - self.error_logger.print_error_position( - t.pos, - "return value does not match function return type", - ); - } - if let Some(value) = &operand { - if !expected_void { - self.expect_conversion(self.return_type.as_ref().unwrap(), value); - } - } - if !expected_void { - if let Some(value) = &mut operand { - Self::cast_integer(value, self.return_type.as_ref().unwrap()); - } - } - Node { - nt: NodeType::Return, - token: Some(t.clone()), - lhs: operand.map(Box::new), - offset: self.return_pointer, - ..Node::default() - } - } else { - self.expr() - }; - self.expect_reserved(";"); - self.cleanup_jump(node) - } - - pub fn consume_block(&mut self) -> Option { - let (token, mut children, cleanup) = self.consume_block_parts()?; - children.extend(cleanup); - Some(Node { - nt: NodeType::Block, - token: Some(token), - children, - ..Node::default() - }) - } - - fn consume_block_parts(&mut self) -> Option<(Token, Vec, Vec)> { - if let Some(t) = self.attempt_reserved("{") { - self.scope_stack.push(HashMap::new()); - let object_depth = self.dynamic_objects.len(); - let bound_depth = self.vla_active.len(); - let mut children: Vec = Vec::new(); - while self.attempt_reserved("}").is_none() { - children.push(self.stmt()); - } - let cleanup = self.cleanup_arrays(object_depth); - self.dynamic_objects.truncate(object_depth); - self.vla_active.truncate(bound_depth); - self.scope_stack.pop(); - Some((t.clone(), children, cleanup)) - } else { - None - } - } pub fn expr(&mut self) -> Node { let first = self.assign(); let Some(token) = self.attempt_reserved(",") else { diff --git a/src/ast/declarations.rs b/src/ast/declarations.rs index e23739a..b97157c 100644 --- a/src/ast/declarations.rs +++ b/src/ast/declarations.rs @@ -7,6 +7,16 @@ use crate::node::{Node, NodeType}; use crate::token::{Token, TokenType}; use std::rc::Rc; +struct GlobalDeclaration { + base: Type, + alignment: usize, + internal: bool, + external: bool, + inline: bool, + thread_local: bool, + attributes: DeclarationAttributes, +} + impl AstBuilderImpl<'_> { pub(super) fn new_local_variable(&mut self, ty: Type, alignment: usize) -> (Node, bool) { let mut alignments = vec![alignment]; @@ -261,10 +271,10 @@ impl AstBuilderImpl<'_> { .is_some() } - pub(super) fn global_definition(&mut self) { + fn global_declaration_specifiers(&mut self) -> Option { while self.attempt_reserved("__extension__").is_some() {} if self.attempt_static_assert() { - return; + return None; } // Attribute collection belongs to this declaration header, not its body or parameters. self.declaration_attributes_state = Some(DeclarationAttributes::default()); @@ -340,7 +350,7 @@ impl AstBuilderImpl<'_> { } self.typedef_definition(); self.expect_reserved(";"); - return; + return None; } if storage .as_ref() @@ -385,9 +395,33 @@ impl AstBuilderImpl<'_> { "inline requires a function declaration", ); } - return; + return None; } - let inherited_attributes = self.declaration_attributes_state.take().unwrap_or_default(); + let attributes = self.declaration_attributes_state.take().unwrap_or_default(); + Some(GlobalDeclaration { + base, + alignment, + internal, + external, + inline, + thread_local, + attributes, + }) + } + + pub(super) fn global_definition(&mut self) { + let Some(GlobalDeclaration { + base, + alignment, + internal, + external, + inline, + thread_local, + attributes: inherited_attributes, + }) = self.global_declaration_specifiers() + else { + return; + }; loop { self.declaration_attributes_state = Some(inherited_attributes.clone()); let mut alignments = vec![alignment]; @@ -541,65 +575,7 @@ impl AstBuilderImpl<'_> { self.expect_reserved(";"); return; } - let (_, result, _) = ty.function_signature_ref().unwrap(); - if definition && result.unqualified() != &Type::Void { - self.expect_object_type(result, &token); - } - self.return_pointer = if definition && matches!(result, Type::Struct(_)) { - self.offset_size = self.offset_size.div_ceil(8) * 8 + 8; - Some(self.offset_size) - } else { - None - }; - self.variadic_last = args.last().and_then(|arg| arg.offset); - let (parameters, _, variadic) = ty.function_signature_ref().unwrap(); - self.variadic_parameters = variadic.then(|| parameters.to_vec()); - self.return_type = Some(result.clone()); - self.current_function = Some(token.clone()); - self.labels.clear(); - self.defined_labels.clear(); - let mut bounds = self.take_bounds(); - Self::resolve_parameter_bounds(&mut bounds, &args); - self.mutable_static = None; - let mut body = self.consume_block(); - if body.is_some() { - let (parameters, result, _) = ty.function_signature_ref().unwrap(); - if parameters - .iter() - .chain(std::iter::once(result)) - .any(|ty| matches!(ty.unqualified(), Type::LongDouble(128))) - { - self.error_logger.print_error_position(token.pos, "extended long double parameters and results in function definitions are not supported"); - } - if parameters - .iter() - .chain(std::iter::once(result)) - .any(|ty| matches!(ty.unqualified(), Type::Float16)) - { - self.error_logger.print_error_position(token.pos, - "_Float16 parameters and results in function definitions are not supported"); - } - } - if let Some(body) = &mut body { - bounds.append(&mut body.children); - body.children = bounds; - self.resolve_vla_gotos(body); - } - self.vla_active.clear(); - for (name, position) in &self.labels { - if !self.defined_labels.contains(name) { - self.error_logger - .print_error_position(*position, "goto target is not defined"); - } - } - self.return_type = None; - self.current_function = None; - self.variadic_last = args.last().and_then(|arg| arg.offset); - self.variadic_parameters = None; - self.scope_stack.pop(); - if body.is_none() { - self.expect_reserved(";"); - } + let body = self.parse_function_body(&token, &ty, &args); if self.functions[token.s_value.as_str()].body.is_some() { if body.is_some() { if !replaceable_inline_body || !external_definition { diff --git a/src/ast/functions.rs b/src/ast/functions.rs new file mode 100644 index 0000000..1d8f557 --- /dev/null +++ b/src/ast/functions.rs @@ -0,0 +1,75 @@ +use super::AstBuilderImpl; +use crate::{ctype::Type, node::Node, token::Token}; + +impl AstBuilderImpl<'_> { + pub(super) fn parse_function_body( + &mut self, + token: &Token, + ty: &Type, + args: &[Node], + ) -> Option { + let (_, result, _) = ty.function_signature_ref().unwrap(); + if result.unqualified() != &Type::Void { + self.expect_object_type(result, token); + } + self.return_pointer = if matches!(result, Type::Struct(_)) { + self.offset_size = self.offset_size.div_ceil(8) * 8 + 8; + Some(self.offset_size) + } else { + None + }; + self.variadic_last = args.last().and_then(|arg| arg.offset); + let (parameters, _, variadic) = ty.function_signature_ref().unwrap(); + self.variadic_parameters = variadic.then(|| parameters.to_vec()); + self.return_type = Some(result.clone()); + self.current_function = Some(token.clone()); + self.labels.clear(); + self.defined_labels.clear(); + let mut bounds = self.take_bounds(); + Self::resolve_parameter_bounds(&mut bounds, args); + self.mutable_static = None; + let mut body = self.consume_block(); + if body.is_some() { + let (parameters, result, _) = ty.function_signature_ref().unwrap(); + if parameters + .iter() + .chain(std::iter::once(result)) + .any(|ty| matches!(ty.unqualified(), Type::LongDouble(128))) + { + self.error_logger.print_error_position(token.pos, "extended long double parameters and results in function definitions are not supported"); + } + if parameters + .iter() + .chain(std::iter::once(result)) + .any(|ty| matches!(ty.unqualified(), Type::Float16)) + { + self.error_logger.print_error_position( + token.pos, + "_Float16 parameters and results in function definitions are not supported", + ); + } + } + if let Some(body) = &mut body { + bounds.append(&mut body.children); + body.children = bounds; + self.resolve_vla_gotos(body); + } + self.vla_active.clear(); + for (name, position) in &self.labels { + if !self.defined_labels.contains(name) { + self.error_logger + .print_error_position(*position, "goto target is not defined"); + } + } + self.return_type = None; + self.current_function = None; + self.variadic_last = args.last().and_then(|arg| arg.offset); + self.variadic_parameters = None; + self.scope_stack.pop(); + if body.is_none() { + self.expect_reserved(";"); + } + + body + } +} diff --git a/src/ast/statements.rs b/src/ast/statements.rs new file mode 100644 index 0000000..57d36ab --- /dev/null +++ b/src/ast/statements.rs @@ -0,0 +1,466 @@ +use super::{AstBuilderImpl, AutomaticStorage}; +use crate::{ + ctype::Type, + node::{Node, NodeType}, + token::{Token, TokenType}, +}; +use std::collections::HashMap; + +impl<'a> AstBuilderImpl<'a> { + pub(super) fn stmt(&mut self) -> Node { + while self.attempt_reserved("__extension__").is_some() {} + self.declaration_attributes(false, None, true); + if matches!( + self.tokens[self.cur].tt, + TokenType::Reserved | TokenType::Ident + ) && matches!( + self.tokens[self.cur].s_value.as_str(), + "asm" | "__asm" | "__asm__" + ) { + let token = self.tokens[self.cur].clone(); + self.cur += 1; + return self.inline_assembly(token); + } + if self.attempt_static_assert() { + return Node { + nt: NodeType::Block, + ..Node::default() + }; + } + if self.tokens[self.cur].tt == TokenType::Ident && self.tokens[self.cur + 1].s_value == ":" + { + return self.label_statement(); + } + if let Some(token) = self.attempt_reserved("goto") { + return self.goto_statement(token); + } + if let Some(token) = self.attempt_reserved("typedef") { + self.typedef_definition(); + self.expect_reserved(";"); + return Node { + nt: NodeType::Block, + token: Some(token.clone()), + children: self.take_bounds(), + ..Node::default() + }; + } + if let Some(token) = self.attempt_reserved(";") { + return Node { + nt: NodeType::Block, + token: Some(token.clone()), + ..Node::default() + }; + } + if let Some(t) = self.attempt_reserved("switch") { + return self.switch_statement(t); + } + if let Some(t) = self + .attempt_reserved("case") + .or_else(|| self.attempt_reserved("default")) + { + return self.case_statement(t); + } + if let Some(t) = self.attempt_reserved("if") { + return self.if_statement(t); + } + if let Some(t) = self.attempt_reserved("do") { + return self.do_statement(t); + } + if let Some(t) = self.attempt_reserved("while") { + return self.while_statement(t); + } + if let Some(t) = self.attempt_reserved("for") { + return self.for_statement(t); + } + if let Some(node) = self.consume_block() { + return node; + } + self.declaration_or_expression_statement() + } + + pub fn consume_block(&mut self) -> Option { + let (token, mut children, cleanup) = self.consume_block_parts()?; + children.extend(cleanup); + Some(Node { + nt: NodeType::Block, + token: Some(token), + children, + ..Node::default() + }) + } + + pub(super) fn consume_block_parts(&mut self) -> Option<(Token, Vec, Vec)> { + if let Some(t) = self.attempt_reserved("{") { + self.scope_stack.push(HashMap::new()); + let object_depth = self.dynamic_objects.len(); + let bound_depth = self.vla_active.len(); + let mut children: Vec = Vec::new(); + while self.attempt_reserved("}").is_none() { + children.push(self.stmt()); + } + let cleanup = self.cleanup_arrays(object_depth); + self.dynamic_objects.truncate(object_depth); + self.vla_active.truncate(bound_depth); + self.scope_stack.pop(); + Some((t.clone(), children, cleanup)) + } else { + None + } + } + + fn goto_statement(&mut self, token: &'a Token) -> Node { + let name = self.attempt_ident().unwrap_or_else(|| { + self.error_logger + .print_error_position(self.tokens[self.cur].pos, "goto requires a label"); + unreachable!() + }); + let id = *self + .labels + .entry(name.s_value.to_string()) + .or_insert(name.pos); + self.expect_reserved(";"); + Node { + nt: NodeType::Goto, + token: Some(token.clone()), + value: Some(id), + args: self.dynamic_objects.clone(), + vla_scope: self.vla_active.clone(), + ..Node::default() + } + } + + fn switch_statement(&mut self, t: &'a Token) -> Node { + self.expect_reserved("("); + let cond = self.expr(); + self.expect_reserved(")"); + if cond + .resolve_type() + .is_none_or(|ty| ty.integer_info().is_none()) + { + self.error_logger + .print_error_position(t.pos, "switch requires an integer expression"); + } + self.switch_vla_depths.push(self.vla_active.len()); + self.jump_depths.push(self.dynamic_objects.len()); + self.switch_stack.push(vec![]); + self.switch_types + .push(cond.resolve_type().unwrap().promoted()); + let body = self.stmt(); + let cases = self.switch_stack.pop().unwrap(); + self.switch_types.pop(); + self.switch_vla_depths.pop(); + self.jump_depths.pop(); + Node { + nt: NodeType::Switch, + token: Some(t.clone()), + cond: Some(Box::new(cond)), + then: Some(Box::new(body)), + children: cases, + ..Node::default() + } + } + + fn if_statement(&mut self, t: &'a Token) -> Node { + self.expect_reserved("("); + let cond = self.expr(); + self.expect_reserved(")"); + let then = self.stmt(); + let mut els: Option = None; + if self.attempt_reserved("else").is_some() { + els = Some(self.stmt()); + } + Node::new_if_node(Some(t.clone()), cond, then, els) + } + + fn do_statement(&mut self, t: &'a Token) -> Node { + self.loop_stack.push(t.pos); + self.continue_depths + .insert(t.pos, self.dynamic_objects.len()); + self.jump_depths.push(self.dynamic_objects.len()); + let body = self.stmt(); + self.loop_stack.pop(); + self.jump_depths.pop(); + self.expect_reserved("while"); + self.expect_reserved("("); + let cond = self.expr(); + self.expect_reserved(")"); + self.expect_reserved(";"); + let mut node = Node::new_while_node(Some(t.clone()), cond, body); + node.nt = NodeType::DoWhile; + node + } + + fn while_statement(&mut self, t: &'a Token) -> Node { + self.expect_reserved("("); + let cond = self.expr(); + self.expect_reserved(")"); + self.loop_stack.push(t.pos); + self.continue_depths + .insert(t.pos, self.dynamic_objects.len()); + self.jump_depths.push(self.dynamic_objects.len()); + let body = self.stmt(); + self.loop_stack.pop(); + self.jump_depths.pop(); + Node::new_while_node(Some(t.clone()), cond, body) + } + + fn for_statement(&mut self, t: &'a Token) -> Node { + let object_depth = self.dynamic_objects.len(); + let bound_depth = self.vla_active.len(); + self.scope_stack.push(HashMap::new()); + self.expect_reserved("("); + let mut ini: Option = None; + let mut cond: Option = None; + let mut upd: Option = None; + if self.attempt_reserved(";").is_none() { + ini = Some( + if let Some((ty, storage, alignment)) = self.attempt_automatic_type(false) { + self.local_variable_definition_with_storage(ty, storage, alignment) + } else { + self.expr() + }, + ); + self.expect_reserved(";"); + } + if self.attempt_reserved(";").is_none() { + cond = Some(self.expr()); + self.expect_reserved(";"); + } + if self.attempt_reserved(")").is_none() { + upd = Some(self.expr()); + self.expect_reserved(")"); + } + self.loop_stack.push(t.pos); + self.continue_depths + .insert(t.pos, self.dynamic_objects.len()); + self.jump_depths.push(self.dynamic_objects.len()); + let body = self.stmt(); + self.loop_stack.pop(); + self.jump_depths.pop(); + self.scope_stack.pop(); + let loop_node = Node::new_for_node(Some(t.clone()), ini, cond, upd, body); + let mut children = vec![loop_node]; + children.extend(self.cleanup_arrays(object_depth)); + self.dynamic_objects.truncate(object_depth); + self.vla_active.truncate(bound_depth); + Node { + nt: NodeType::Block, + children, + ..Node::default() + } + } + + fn case_statement(&mut self, t: &'a Token) -> Node { + if self.switch_stack.is_empty() { + self.error_logger + .print_error_position(t.pos, "case or default requires an enclosing switch"); + } + if self.vla_active.len() > *self.switch_vla_depths.last().unwrap() { + self.error_logger.print_error_position( + t.pos, + "switch label enters the scope of a variably modified declaration", + ); + } + let value = if t.s_value == "case" { + let expr = self.ternary(); + let value = self.eval(&expr); + Some(self.switch_types.last().unwrap().convert_constant(value) as usize) + } else { + None + }; + self.expect_reserved(":"); + if self + .switch_stack + .last() + .unwrap() + .iter() + .any(|case| case.value == value) + { + self.error_logger + .print_error_position(t.pos, "duplicate switch label"); + } + let mut node = Node { + nt: NodeType::Case, + token: Some(t.clone()), + value, + ..Node::default() + }; + self.switch_stack.last_mut().unwrap().push(node.clone()); + node.lhs = Some(Box::new(self.stmt())); + node + } + + fn label_statement(&mut self) -> Node { + let token = self.attempt_ident().unwrap(); + self.expect_reserved(":"); + if !self.defined_labels.insert(token.s_value.to_string()) { + self.error_logger + .print_error_position(token.pos, "duplicate label"); + } + let id = *self + .labels + .entry(token.s_value.to_string()) + .or_insert(token.pos); + let vla_scope = self.vla_active.clone(); + let lhs = Some(Box::new(self.stmt())); + Node { + nt: NodeType::Label, + token: Some(token), + lhs, + value: Some(id), + vla_scope, + ..Node::default() + } + } + + fn declaration_or_expression_statement(&mut self) -> Node { + let mut requested_alignment = self.object_alignment_annotations(); + let mut thread_local = false; + while let Some(value) = self.attempt_alignment_specifier() { + requested_alignment = requested_alignment.max(value); + } + let inline = self.attempt_inline(); + let storage = self + .attempt_reserved("static") + .or_else(|| self.attempt_reserved("extern")); + let inline = inline.or_else(|| self.attempt_inline()); + let mut storage = storage; + loop { + requested_alignment = requested_alignment.max(self.object_alignment_annotations()); + if self.attempt_thread_local() { + thread_local = true; + } else if let Some(token) = self + .attempt_reserved("static") + .or_else(|| self.attempt_reserved("extern")) + { + if storage.is_some() { + self.error_logger + .print_error_position(token.pos, "conflicting storage classes"); + } else { + storage = Some(token); + } + } else { + break; + } + } + if thread_local && storage.is_none() { + self.error_logger.print_error_position( + self.tokens[self.cur - 1].pos, + "block thread-local declaration requires static or extern storage", + ); + } + if storage.is_some() || inline.is_some() || thread_local { + let mut storage = storage.cloned().unwrap_or_else(|| { + inline.cloned().unwrap_or_else(|| Token { + s_value: "static".to_owned().into(), + ..self.tokens[self.cur - 1].clone() + }) + }); + if matches!( + storage.s_value.as_str(), + "inline" | "__inline" | "__inline__" + ) { + storage.s_value = "extern".to_owned().into(); + } + requested_alignment = requested_alignment.max(self.object_alignment_annotations()); + let ty = self.expect_type(); + requested_alignment = requested_alignment.max(self.object_alignment_annotations()); + let declaration = self.local_static_definition( + ty, + &storage, + inline.is_some(), + requested_alignment, + thread_local, + ); + self.expect_reserved(";"); + return declaration; + } + let node = if let Some((ty, storage, alignment)) = self.attempt_automatic_type(false) { + if storage == AutomaticStorage::Register && requested_alignment != 0 { + self.error_logger.print_error_position( + self.tokens[self.cur].pos, + "alignment cannot be applied to a register object", + ); + } + if self.tokens[self.cur].s_value == ";" { + if alignment.max(requested_alignment) != 0 { + self.error_logger.print_error_position( + self.tokens[self.cur].pos, + "alignment requires an object declaration", + ); + } + Node { + nt: NodeType::Block, + ..Node::default() + } + } else { + self.local_variable_definition_with_storage( + ty, + storage, + alignment.max(requested_alignment), + ) + } + } else if requested_alignment != 0 { + self.error_logger.print_error_position( + self.tokens[self.cur].pos, + "alignment requires an object declaration", + ); + unreachable!() + } else if let Some(t) = self.attempt_reserved("continue") { + let target = self.loop_stack.last().copied().unwrap_or_else(|| { + self.error_logger + .print_error_position(t.pos, "continue requires an enclosing loop"); + unreachable!() + }); + Node { + nt: NodeType::Continue, + token: Some(t.clone()), + value: Some(target), + ..Node::default() + } + } else if let Some(t) = self.attempt_reserved("break") { + Node { + nt: NodeType::Break, + token: Some(t.clone()), + ..Node::default() + } + } else if let Some(t) = self.attempt_reserved("return") { + let mut operand = if self.tokens[self.cur].s_value == ";" { + None + } else { + Some(self.expr()) + }; + let expected_void = self.return_type == Some(Type::Void); + let actual_void = operand + .as_ref() + .is_none_or(|operand| operand.resolve_type() == Some(Type::Void)); + if expected_void != actual_void { + self.error_logger.print_error_position( + t.pos, + "return value does not match function return type", + ); + } + if let Some(value) = &operand { + if !expected_void { + self.expect_conversion(self.return_type.as_ref().unwrap(), value); + } + } + if !expected_void { + if let Some(value) = &mut operand { + Self::cast_integer(value, self.return_type.as_ref().unwrap()); + } + } + Node { + nt: NodeType::Return, + token: Some(t.clone()), + lhs: operand.map(Box::new), + offset: self.return_pointer, + ..Node::default() + } + } else { + self.expr() + }; + self.expect_reserved(";"); + self.cleanup_jump(node) + } +} diff --git a/src/ctype.rs b/src/ctype.rs index 3084f0f..0b8bb40 100644 --- a/src/ctype.rs +++ b/src/ctype.rs @@ -1,7 +1,12 @@ +mod arithmetic; +mod compatibility; +mod layout; +mod lowering; +mod records; + use std::{ borrow::Cow, cell::RefCell, - fmt, rc::{Rc, Weak}, }; @@ -69,84 +74,6 @@ pub struct StructMember { pub anonymous: bool, } -impl StructType { - pub fn new(id: usize) -> (Self, Rc>) { - let definition = Rc::new(RefCell::new(StructDefinition::default())); - ( - Self { - id, - definition: Rc::downgrade(&definition), - }, - definition, - ) - } - pub fn definition(&self) -> Rc> { - self.definition - .upgrade() - .expect("struct definitions outlive the compiler pipeline") - } - pub fn has_bit_fields(&self) -> bool { - self.definition().borrow().has_bit_fields - } - pub fn members(&self) -> Vec { - self.definition().borrow().members.clone() - } - pub fn member(&self, index: usize) -> StructMember { - self.definition().borrow().members[index].clone() - } - pub fn visible_members(&self) -> Vec<(String, Vec)> { - self.members() - .iter() - .enumerate() - .flat_map(|(index, member)| { - if member.anonymous { - let Type::Struct(child) = member.ty.unqualified() else { - unreachable!() - }; - child - .visible_members() - .into_iter() - .map(|(name, mut path)| { - path.insert(0, index); - (name, path) - }) - .collect() - } else { - vec![(member.name.clone(), vec![index])] - } - }) - .collect() - } - pub fn member_path(&self, name: &str) -> Option> { - let definition = self.definition(); - let definition = definition.borrow(); - for (index, member) in definition.members.iter().enumerate() { - if member.anonymous { - let Type::Struct(child) = member.ty.unqualified() else { - unreachable!() - }; - if let Some(mut path) = child.member_path(name) { - path.insert(0, index); - return Some(path); - } - } else if member.name == name { - return Some(vec![index]); - } - } - None - } -} -impl PartialEq for StructType { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } -} -impl fmt::Debug for StructType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Struct({})", self.id) - } -} - /// Recursive type components are shared; lowering uses copy-on-write mutations. #[derive(Clone, PartialEq, Debug)] pub enum Type { @@ -195,111 +122,6 @@ impl Type { Self::integer(32, !cfg!(all(target_arch = "aarch64", target_os = "linux"))) } - pub fn compatible(&self, other: &Self) -> bool { - match (self.unqualified(), other.unqualified()) { - (Self::Enum(left), Self::Enum(right)) => left == right, - (Self::Enum(value), other) | (other, Self::Enum(value)) => { - value.underlying.borrow().compatible(other) - } - (Self::Ptr(left), Self::Ptr(right)) - | (Self::Arr(left, _), Self::Vla(right, _)) - | (Self::Vla(left, _), Self::Arr(right, _) | Self::Vla(right, _)) => { - left.qualifiers() == right.qualifiers() && left.compatible(right) - } - (Self::Arr(left, count), Self::Arr(right, other_count)) => { - (count == other_count || count.is_none() || other_count.is_none()) - && left.qualifiers() == right.qualifiers() - && left.compatible(right) - } - (Self::Func(args, result), Self::Func(other_args, other_result)) - | (Self::VariadicFunc(args, result), Self::VariadicFunc(other_args, other_result)) => { - args.len() == other_args.len() - && args - .iter() - .zip(other_args.iter()) - .all(|(left, right)| left.parameter_compatible(right)) - && result.qualifiers() == other_result.qualifiers() - && result.compatible(other_result) - } - (left, right) => left == right, - } - } - - /// Return the scalar members of a validated GNU transparent union. - pub fn transparent_union_members(&self) -> Option> { - let Self::Struct(record) = self.unqualified() else { - return None; - }; - if record.definition().borrow().transparent_union { - Some(record.members()) - } else { - None - } - } - - fn parameter_compatible(&self, other: &Self) -> bool { - match ( - self.transparent_union_members(), - other.transparent_union_members(), - ) { - (Some(_), Some(_)) | (None, None) => self.compatible(other), - (Some(members), None) => members.iter().any(|member| member.ty.compatible(other)), - (None, Some(members)) => members.iter().any(|member| self.compatible(&member.ty)), - } - } - - /// Normalize a transparent-union parameter without changing ordinary union values or results. - pub fn parameter_for_codegen(&self) -> Self { - let mut ty = self.clone(); - ty.lower_parameter_for_codegen(); - ty - } - - pub(crate) fn lower_parameter_for_codegen(&mut self) { - let first = if let Self::Struct(record) = self.unqualified() { - let definition = record.definition(); - let definition = definition.borrow(); - definition - .transparent_union - .then(|| definition.members[0].ty.clone()) - } else { - None - }; - if let Some(first) = first { - *self = if matches!(first.unqualified(), Self::Ptr(_)) { - // Opaque pointer ABI types also break recursive callback parameter types. - Self::Ptr(Rc::new(Self::Void)) - } else { - first - }; - } - self.lower_for_codegen(); - } - - /// Typedef redeclarations require identical types, not merely compatible array bounds or enums. - pub fn identical(&self, other: &Self) -> bool { - self.qualifiers() == other.qualifiers() && self.identical_unqualified(other) - } - - fn identical_unqualified(&self, other: &Self) -> bool { - match (self.unqualified(), other.unqualified()) { - (Self::Ptr(left), Self::Ptr(right)) => left.identical(right), - (Self::Arr(left, count), Self::Arr(right, other_count)) => { - count == other_count && left.identical(right) - } - (Self::Func(args, result), Self::Func(other_args, other_result)) - | (Self::VariadicFunc(args, result), Self::VariadicFunc(other_args, other_result)) => { - args.len() == other_args.len() - && args - .iter() - .zip(other_args.iter()) - .all(|(left, right)| left.identical_unqualified(right)) - && result.identical(other_result) - } - (left, right) => left == right, - } - } - /// GNU type queries ignore outer qualification, including qualification of array elements. pub fn unqualified_for_type_query(&self) -> Self { match self.unqualified() { @@ -388,106 +210,6 @@ impl Type { ) } - pub fn is_arithmetic(&self) -> bool { - self.integer_info().is_some() || self.float_bits().is_some() - } - pub fn float_value(&self, bits: usize) -> f64 { - if self.float_bits() == Some(32) { - f32::from_bits(bits as u32) as f64 - } else { - f64::from_bits(bits as u64) - } - } - pub fn float_constant(&self, value: f64) -> usize { - if self.float_bits() == Some(32) { - (value as f32).to_bits() as usize - } else { - value.to_bits() as usize - } - } - - pub fn integer(bits: u8, signed: bool) -> Self { - match (bits, signed) { - (8, true) => Self::I8, - (32, true) => Self::I32, - _ => Self::Integer { bits, signed }, - } - } - pub fn integer_info(&self) -> Option<(u8, bool)> { - match self { - Self::Bool => Some((8, false)), - Self::I8 | Self::SignedChar => Some((8, true)), - Self::I32 => Some((32, true)), - Self::Integer { bits, signed } => Some((*bits, *signed)), - Self::LongLong { signed } => Some((64, *signed)), - Self::Enum(value) => value.underlying.borrow().integer_info(), - Self::Qualified(child, _) | Self::Aligned(child, _) => child.integer_info(), - _ => None, - } - } - pub fn promoted(&self) -> Self { - if let Self::Enum(value) = self.unqualified() { - return value.underlying.borrow().promoted(); - } - if self.integer_info().is_some_and(|(bits, _)| bits < 32) { - Self::I32 - } else { - self.clone() - } - } - pub fn arithmetic_type(lhs: &Self, rhs: &Self) -> Self { - if lhs.float_bits().is_some() || rhs.float_bits().is_some() { - let bits = lhs - .float_bits() - .unwrap_or(0) - .max(rhs.float_bits().unwrap_or(0)); - return if matches!(lhs.unqualified(), Self::LongDouble(_)) - || matches!(rhs.unqualified(), Self::LongDouble(_)) - { - Self::LongDouble(bits) - } else { - Self::Float(bits) - }; - } - let lhs = lhs.promoted(); - let rhs = rhs.promoted(); - let (Some((lb, ls)), Some((rb, rs))) = (lhs.integer_info(), rhs.integer_info()) else { - return lhs; - }; - let bits = lb.max(rb); - let signed = match lb.cmp(&rb) { - std::cmp::Ordering::Equal => ls && rs, - std::cmp::Ordering::Greater => ls, - std::cmp::Ordering::Less => rs, - }; - if matches!(lhs.unqualified(), Self::LongLong { .. }) - || matches!(rhs.unqualified(), Self::LongLong { .. }) - { - Self::LongLong { signed } - } else { - Self::integer(bits, signed) - } - } - - pub fn convert_constant(&self, value: i64) -> i64 { - if let Self::Enum(ty) = self.unqualified() { - return ty.underlying.borrow().convert_constant(value); - } - if *self == Self::Bool { - return i64::from(value != 0); - } - match self.integer_info() { - Some((bits, signed)) if bits < 64 => { - let shift = 64 - bits; - if signed { - (value << shift) >> shift - } else { - (value as u64 & ((1u64 << bits) - 1)) as i64 - } - } - _ => value, - } - } pub fn unqualified(&self) -> &Self { match self { Self::Qualified(child, _) | Self::Aligned(child, _) => child.unqualified(), @@ -517,232 +239,6 @@ impl Type { } } - /// Erase source qualifiers and enum identities after semantic validation. - pub fn lowered_for_codegen(&self) -> Self { - let mut ty = self.clone(); - ty.lower_for_codegen(); - ty - } - - /// Normalize an owned type after validation, reusing its child storage. - #[inline] - pub(crate) fn lower_for_codegen(&mut self) { - // Scalar annotations need no recursive normalization. - match self { - Self::Enum(..) - | Self::Ptr(..) - | Self::Arr(..) - | Self::Vla(..) - | Self::Vector(..) - | Self::Func(..) - | Self::VariadicFunc(..) - | Self::Qualified(..) - | Self::Aligned(..) => self.lower_compound_for_codegen(), - _ => {} - } - } - - fn lower_compound_for_codegen(&mut self) { - if matches!(self, Self::Qualified(..)) { - let Self::Qualified(child, _) = std::mem::take(self) else { - unreachable!() - }; - *self = Rc::unwrap_or_clone(child); - self.lower_for_codegen(); - return; - } - match self { - Self::Enum(value) => { - let underlying = value.underlying.borrow().clone(); - *self = underlying; - self.lower_for_codegen(); - } - Self::Ptr(child) - | Self::Arr(child, _) - | Self::Vla(child, _) - | Self::Vector(child, _) - | Self::Aligned(child, _) => Rc::make_mut(child).lower_for_codegen(), - Self::Func(args, result) | Self::VariadicFunc(args, result) => { - for arg in Rc::make_mut(args) { - arg.lower_parameter_for_codegen(); - } - Rc::make_mut(result).lower_for_codegen(); - } - _ => {} - } - } - pub fn function_signature(&self) -> Option<(Vec, Type, bool)> { - self.function_signature_ref() - .map(|(args, result, variadic)| (args.to_vec(), result.clone(), variadic)) - } - - /// Inspect a signature without cloning its parameter and result types. - pub(crate) fn function_signature_ref(&self) -> Option<(&[Type], &Type, bool)> { - match self.unqualified() { - Self::Func(args, result) => Some((args, result, false)), - Self::VariadicFunc(args, result) => Some((args, result, true)), - _ => None, - } - } - - /// Reuse an owned signature's storage when constructing a call. - pub(crate) fn into_function_signature(self) -> Option<(Vec, Type, bool)> { - match self { - Self::Func(args, result) => Some(( - Rc::unwrap_or_clone(args), - Rc::unwrap_or_clone(result), - false, - )), - Self::VariadicFunc(args, result) => { - Some((Rc::unwrap_or_clone(args), Rc::unwrap_or_clone(result), true)) - } - Self::Qualified(child, _) | Self::Aligned(child, _) => { - Rc::unwrap_or_clone(child).into_function_signature() - } - _ => None, - } - } - - /// Whether the type describes an object with a known layout, including zero-sized GNU objects. - pub fn is_complete_object(&self) -> bool { - match self.unqualified() { - Self::Void | Self::Func(..) | Self::VariadicFunc(..) => false, - Self::Arr(child, count) => count.is_some() && child.is_complete_object(), - Self::Vla(child, _) => child.is_complete_object(), - Self::Struct(record) => record.definition().borrow().complete, - _ => true, - } - } - - pub fn checked_size_of(&self) -> Option { - match self { - Self::Arr(child, size) => child.checked_size_of()?.checked_mul(size.unwrap_or(0)), - _ => Some(self.size_of()), - } - } - - pub fn size_of(&self) -> usize { - match self { - Type::Void => 0, - Type::Bool => 1, - Type::I8 | Type::SignedChar => 1, - Type::I32 => 4, - Type::Integer { bits, .. } => (*bits as usize) / 8, - Type::LongLong { .. } => 8, - Type::Integer128 { .. } => 16, - Type::Enum(value) => value.underlying.borrow().size_of(), - Type::Float16 => 2, - Type::LongDouble(80) => 16, - Type::Float(bits) | Type::LongDouble(bits) => usize::from(*bits) / 8, - Type::Ptr(_) => 8, - Type::Arr(t, s) => t.size_of() * s.unwrap_or(0), - Type::Vla(..) => 8, - Type::Vector(element, lanes) => element.size_of() * lanes, - Type::Struct(ty) => ty.definition().borrow().size, - Type::Func(..) | Type::VariadicFunc(..) => 1, - Type::Qualified(child, _) | Type::Aligned(child, _) => child.size_of(), - } - } - pub(crate) fn contains_volatile_subobject(&self) -> bool { - self.qualifiers().volatile - || match self.unqualified() { - Self::Arr(child, _) | Self::Vla(child, _) => child.contains_volatile_subobject(), - Self::Struct(record) => record - .definition() - .borrow() - .members - .iter() - .any(|member| member.ty.contains_volatile_subobject()), - // A volatile pointee does not make the pointer object volatile. - _ => false, - } - } - - pub fn contains_vector(&self) -> bool { - match self.unqualified() { - Self::Arr(child, _) | Self::Vla(child, _) => child.contains_vector(), - Self::Vector(..) => true, - Self::Struct(record) => record - .definition() - .borrow() - .members - .iter() - .any(|member| member.ty.contains_vector()), - _ => false, - } - } - - pub fn contains_float16(&self) -> bool { - match self.unqualified() { - Self::Float16 => true, - Self::Arr(child, _) | Self::Vla(child, _) => child.contains_float16(), - Self::Struct(ty) => ty - .definition() - .borrow() - .members - .iter() - .any(|member| member.ty.contains_float16()), - _ => false, - } - } - - /// Whether an object contains a non-binary64 long double format. - pub fn contains_extended_long_double(&self) -> bool { - match self.unqualified() { - Self::LongDouble(bits) => *bits != 64, - Self::Arr(child, _) | Self::Vla(child, _) => child.contains_extended_long_double(), - Self::Struct(ty) => ty - .definition() - .borrow() - .members - .iter() - .any(|member| member.ty.contains_extended_long_double()), - _ => false, - } - } - - pub fn contains_typedef_alignment(&self) -> bool { - match self { - Self::Arr(child, _) | Self::Vla(child, _) | Self::Qualified(child, _) => { - child.contains_typedef_alignment() - } - Self::Struct(record) => record - .definition() - .borrow() - .members - .iter() - .any(|member| member.ty.contains_typedef_alignment()), - Self::Aligned(child, alignment) => { - *alignment != child.natural_align_of() || child.contains_typedef_alignment() - } - _ => false, - } - } - - pub fn natural_align_of(&self) -> usize { - if let Self::Qualified(child, _) | Self::Aligned(child, _) = self { - return child.natural_align_of(); - } - if let Self::Struct(ty) = self.unqualified() { - let definition = ty.definition(); - let definition = definition.borrow(); - if definition.natural_align != 0 { - return definition.natural_align; - } - } - self.align_of() - } - - pub fn align_of(&self) -> usize { - match self { - Self::Void => 1, - Self::Arr(child, _) | Self::Vla(child, _) => child.align_of(), - Self::Struct(ty) => ty.definition().borrow().align.max(1), - Self::Qualified(child, _) => child.align_of(), - Self::Aligned(_, alignment) => *alignment, - _ => self.size_of(), - } - } pub fn dest_type(&self) -> Option { self.dest_type_ref().cloned() } diff --git a/src/ctype/arithmetic.rs b/src/ctype/arithmetic.rs new file mode 100644 index 0000000..7cd648c --- /dev/null +++ b/src/ctype/arithmetic.rs @@ -0,0 +1,109 @@ +use super::Type; + +impl Type { + pub fn is_arithmetic(&self) -> bool { + self.integer_info().is_some() || self.float_bits().is_some() + } + + pub fn float_value(&self, bits: usize) -> f64 { + if self.float_bits() == Some(32) { + f32::from_bits(bits as u32) as f64 + } else { + f64::from_bits(bits as u64) + } + } + + pub fn float_constant(&self, value: f64) -> usize { + if self.float_bits() == Some(32) { + (value as f32).to_bits() as usize + } else { + value.to_bits() as usize + } + } + + pub fn integer(bits: u8, signed: bool) -> Self { + match (bits, signed) { + (8, true) => Self::I8, + (32, true) => Self::I32, + _ => Self::Integer { bits, signed }, + } + } + + pub fn integer_info(&self) -> Option<(u8, bool)> { + match self { + Self::Bool => Some((8, false)), + Self::I8 | Self::SignedChar => Some((8, true)), + Self::I32 => Some((32, true)), + Self::Integer { bits, signed } => Some((*bits, *signed)), + Self::LongLong { signed } => Some((64, *signed)), + Self::Enum(value) => value.underlying.borrow().integer_info(), + Self::Qualified(child, _) | Self::Aligned(child, _) => child.integer_info(), + _ => None, + } + } + + pub fn promoted(&self) -> Self { + if let Self::Enum(value) = self.unqualified() { + return value.underlying.borrow().promoted(); + } + if self.integer_info().is_some_and(|(bits, _)| bits < 32) { + Self::I32 + } else { + self.clone() + } + } + + pub fn arithmetic_type(lhs: &Self, rhs: &Self) -> Self { + if lhs.float_bits().is_some() || rhs.float_bits().is_some() { + let bits = lhs + .float_bits() + .unwrap_or(0) + .max(rhs.float_bits().unwrap_or(0)); + return if matches!(lhs.unqualified(), Self::LongDouble(_)) + || matches!(rhs.unqualified(), Self::LongDouble(_)) + { + Self::LongDouble(bits) + } else { + Self::Float(bits) + }; + } + let lhs = lhs.promoted(); + let rhs = rhs.promoted(); + let (Some((lb, ls)), Some((rb, rs))) = (lhs.integer_info(), rhs.integer_info()) else { + return lhs; + }; + let bits = lb.max(rb); + let signed = match lb.cmp(&rb) { + std::cmp::Ordering::Equal => ls && rs, + std::cmp::Ordering::Greater => ls, + std::cmp::Ordering::Less => rs, + }; + if matches!(lhs.unqualified(), Self::LongLong { .. }) + || matches!(rhs.unqualified(), Self::LongLong { .. }) + { + Self::LongLong { signed } + } else { + Self::integer(bits, signed) + } + } + + pub fn convert_constant(&self, value: i64) -> i64 { + if let Self::Enum(ty) = self.unqualified() { + return ty.underlying.borrow().convert_constant(value); + } + if *self == Self::Bool { + return i64::from(value != 0); + } + match self.integer_info() { + Some((bits, signed)) if bits < 64 => { + let shift = 64 - bits; + if signed { + (value << shift) >> shift + } else { + (value as u64 & ((1u64 << bits) - 1)) as i64 + } + } + _ => value, + } + } +} diff --git a/src/ctype/compatibility.rs b/src/ctype/compatibility.rs new file mode 100644 index 0000000..e361b81 --- /dev/null +++ b/src/ctype/compatibility.rs @@ -0,0 +1,80 @@ +use super::{StructMember, Type}; + +impl Type { + pub fn compatible(&self, other: &Self) -> bool { + match (self.unqualified(), other.unqualified()) { + (Self::Enum(left), Self::Enum(right)) => left == right, + (Self::Enum(value), other) | (other, Self::Enum(value)) => { + value.underlying.borrow().compatible(other) + } + (Self::Ptr(left), Self::Ptr(right)) + | (Self::Arr(left, _), Self::Vla(right, _)) + | (Self::Vla(left, _), Self::Arr(right, _) | Self::Vla(right, _)) => { + left.qualifiers() == right.qualifiers() && left.compatible(right) + } + (Self::Arr(left, count), Self::Arr(right, other_count)) => { + (count == other_count || count.is_none() || other_count.is_none()) + && left.qualifiers() == right.qualifiers() + && left.compatible(right) + } + (Self::Func(args, result), Self::Func(other_args, other_result)) + | (Self::VariadicFunc(args, result), Self::VariadicFunc(other_args, other_result)) => { + args.len() == other_args.len() + && args + .iter() + .zip(other_args.iter()) + .all(|(left, right)| left.parameter_compatible(right)) + && result.qualifiers() == other_result.qualifiers() + && result.compatible(other_result) + } + (left, right) => left == right, + } + } + + /// Return the scalar members of a validated GNU transparent union. + pub fn transparent_union_members(&self) -> Option> { + let Self::Struct(record) = self.unqualified() else { + return None; + }; + if record.definition().borrow().transparent_union { + Some(record.members()) + } else { + None + } + } + + fn parameter_compatible(&self, other: &Self) -> bool { + match ( + self.transparent_union_members(), + other.transparent_union_members(), + ) { + (Some(_), Some(_)) | (None, None) => self.compatible(other), + (Some(members), None) => members.iter().any(|member| member.ty.compatible(other)), + (None, Some(members)) => members.iter().any(|member| self.compatible(&member.ty)), + } + } + + /// Typedef redeclarations require identical types, not merely compatible array bounds or enums. + pub fn identical(&self, other: &Self) -> bool { + self.qualifiers() == other.qualifiers() && self.identical_unqualified(other) + } + + fn identical_unqualified(&self, other: &Self) -> bool { + match (self.unqualified(), other.unqualified()) { + (Self::Ptr(left), Self::Ptr(right)) => left.identical(right), + (Self::Arr(left, count), Self::Arr(right, other_count)) => { + count == other_count && left.identical(right) + } + (Self::Func(args, result), Self::Func(other_args, other_result)) + | (Self::VariadicFunc(args, result), Self::VariadicFunc(other_args, other_result)) => { + args.len() == other_args.len() + && args + .iter() + .zip(other_args.iter()) + .all(|(left, right)| left.identical_unqualified(right)) + && result.identical(other_result) + } + (left, right) => left == right, + } + } +} diff --git a/src/ctype/layout.rs b/src/ctype/layout.rs new file mode 100644 index 0000000..a3090ac --- /dev/null +++ b/src/ctype/layout.rs @@ -0,0 +1,145 @@ +use super::Type; + +impl Type { + /// Whether the type describes an object with a known layout, including zero-sized GNU objects. + pub fn is_complete_object(&self) -> bool { + match self.unqualified() { + Self::Void | Self::Func(..) | Self::VariadicFunc(..) => false, + Self::Arr(child, count) => count.is_some() && child.is_complete_object(), + Self::Vla(child, _) => child.is_complete_object(), + Self::Struct(record) => record.definition().borrow().complete, + _ => true, + } + } + + pub fn checked_size_of(&self) -> Option { + match self { + Self::Arr(child, size) => child.checked_size_of()?.checked_mul(size.unwrap_or(0)), + _ => Some(self.size_of()), + } + } + + pub fn size_of(&self) -> usize { + match self { + Type::Void => 0, + Type::Bool => 1, + Type::I8 | Type::SignedChar => 1, + Type::I32 => 4, + Type::Integer { bits, .. } => (*bits as usize) / 8, + Type::LongLong { .. } => 8, + Type::Integer128 { .. } => 16, + Type::Enum(value) => value.underlying.borrow().size_of(), + Type::Float16 => 2, + Type::LongDouble(80) => 16, + Type::Float(bits) | Type::LongDouble(bits) => usize::from(*bits) / 8, + Type::Ptr(_) => 8, + Type::Arr(t, s) => t.size_of() * s.unwrap_or(0), + Type::Vla(..) => 8, + Type::Vector(element, lanes) => element.size_of() * lanes, + Type::Struct(ty) => ty.definition().borrow().size, + Type::Func(..) | Type::VariadicFunc(..) => 1, + Type::Qualified(child, _) | Type::Aligned(child, _) => child.size_of(), + } + } + + pub(crate) fn contains_volatile_subobject(&self) -> bool { + self.qualifiers().volatile + || match self.unqualified() { + Self::Arr(child, _) | Self::Vla(child, _) => child.contains_volatile_subobject(), + Self::Struct(record) => record + .definition() + .borrow() + .members + .iter() + .any(|member| member.ty.contains_volatile_subobject()), + // A volatile pointee does not make the pointer object volatile. + _ => false, + } + } + + pub fn contains_vector(&self) -> bool { + match self.unqualified() { + Self::Arr(child, _) | Self::Vla(child, _) => child.contains_vector(), + Self::Vector(..) => true, + Self::Struct(record) => record + .definition() + .borrow() + .members + .iter() + .any(|member| member.ty.contains_vector()), + _ => false, + } + } + + pub fn contains_float16(&self) -> bool { + match self.unqualified() { + Self::Float16 => true, + Self::Arr(child, _) | Self::Vla(child, _) => child.contains_float16(), + Self::Struct(ty) => ty + .definition() + .borrow() + .members + .iter() + .any(|member| member.ty.contains_float16()), + _ => false, + } + } + + /// Whether an object contains a non-binary64 long double format. + pub fn contains_extended_long_double(&self) -> bool { + match self.unqualified() { + Self::LongDouble(bits) => *bits != 64, + Self::Arr(child, _) | Self::Vla(child, _) => child.contains_extended_long_double(), + Self::Struct(ty) => ty + .definition() + .borrow() + .members + .iter() + .any(|member| member.ty.contains_extended_long_double()), + _ => false, + } + } + + pub fn contains_typedef_alignment(&self) -> bool { + match self { + Self::Arr(child, _) | Self::Vla(child, _) | Self::Qualified(child, _) => { + child.contains_typedef_alignment() + } + Self::Struct(record) => record + .definition() + .borrow() + .members + .iter() + .any(|member| member.ty.contains_typedef_alignment()), + Self::Aligned(child, alignment) => { + *alignment != child.natural_align_of() || child.contains_typedef_alignment() + } + _ => false, + } + } + + pub fn natural_align_of(&self) -> usize { + if let Self::Qualified(child, _) | Self::Aligned(child, _) = self { + return child.natural_align_of(); + } + if let Self::Struct(ty) = self.unqualified() { + let definition = ty.definition(); + let definition = definition.borrow(); + if definition.natural_align != 0 { + return definition.natural_align; + } + } + self.align_of() + } + + pub fn align_of(&self) -> usize { + match self { + Self::Void => 1, + Self::Arr(child, _) | Self::Vla(child, _) => child.align_of(), + Self::Struct(ty) => ty.definition().borrow().align.max(1), + Self::Qualified(child, _) => child.align_of(), + Self::Aligned(_, alignment) => *alignment, + _ => self.size_of(), + } + } +} diff --git a/src/ctype/lowering.rs b/src/ctype/lowering.rs new file mode 100644 index 0000000..3090280 --- /dev/null +++ b/src/ctype/lowering.rs @@ -0,0 +1,119 @@ +use super::Type; +use std::rc::Rc; + +impl Type { + /// Normalize a transparent-union parameter without changing ordinary union values or results. + pub fn parameter_for_codegen(&self) -> Self { + let mut ty = self.clone(); + ty.lower_parameter_for_codegen(); + ty + } + + pub(crate) fn lower_parameter_for_codegen(&mut self) { + let first = if let Self::Struct(record) = self.unqualified() { + let definition = record.definition(); + let definition = definition.borrow(); + definition + .transparent_union + .then(|| definition.members[0].ty.clone()) + } else { + None + }; + if let Some(first) = first { + *self = if matches!(first.unqualified(), Self::Ptr(_)) { + // Opaque pointer ABI types also break recursive callback parameter types. + Self::Ptr(Rc::new(Self::Void)) + } else { + first + }; + } + self.lower_for_codegen(); + } + + /// Erase source qualifiers and enum identities after semantic validation. + pub fn lowered_for_codegen(&self) -> Self { + let mut ty = self.clone(); + ty.lower_for_codegen(); + ty + } + + /// Normalize an owned type after validation, reusing its child storage. + #[inline] + pub(crate) fn lower_for_codegen(&mut self) { + // Scalar annotations need no recursive normalization. + match self { + Self::Enum(..) + | Self::Ptr(..) + | Self::Arr(..) + | Self::Vla(..) + | Self::Vector(..) + | Self::Func(..) + | Self::VariadicFunc(..) + | Self::Qualified(..) + | Self::Aligned(..) => self.lower_compound_for_codegen(), + _ => {} + } + } + + fn lower_compound_for_codegen(&mut self) { + if matches!(self, Self::Qualified(..)) { + let Self::Qualified(child, _) = std::mem::take(self) else { + unreachable!() + }; + *self = Rc::unwrap_or_clone(child); + self.lower_for_codegen(); + return; + } + match self { + Self::Enum(value) => { + let underlying = value.underlying.borrow().clone(); + *self = underlying; + self.lower_for_codegen(); + } + Self::Ptr(child) + | Self::Arr(child, _) + | Self::Vla(child, _) + | Self::Vector(child, _) + | Self::Aligned(child, _) => Rc::make_mut(child).lower_for_codegen(), + Self::Func(args, result) | Self::VariadicFunc(args, result) => { + for arg in Rc::make_mut(args) { + arg.lower_parameter_for_codegen(); + } + Rc::make_mut(result).lower_for_codegen(); + } + _ => {} + } + } + + pub fn function_signature(&self) -> Option<(Vec, Type, bool)> { + self.function_signature_ref() + .map(|(args, result, variadic)| (args.to_vec(), result.clone(), variadic)) + } + + /// Inspect a signature without cloning its parameter and result types. + pub(crate) fn function_signature_ref(&self) -> Option<(&[Type], &Type, bool)> { + match self.unqualified() { + Self::Func(args, result) => Some((args, result, false)), + Self::VariadicFunc(args, result) => Some((args, result, true)), + _ => None, + } + } + + /// Reuse an owned signature's storage when constructing a call. + pub(crate) fn into_function_signature(self) -> Option<(Vec, Type, bool)> { + match self { + Self::Func(args, result) => Some(( + Rc::unwrap_or_clone(args), + Rc::unwrap_or_clone(result), + false, + )), + Self::VariadicFunc(args, result) => { + Some((Rc::unwrap_or_clone(args), Rc::unwrap_or_clone(result), true)) + } + Self::Qualified(child, _) | Self::Aligned(child, _) => { + Rc::unwrap_or_clone(child).into_function_signature() + } + _ => None, + } + } +} diff --git a/src/ctype/records.rs b/src/ctype/records.rs new file mode 100644 index 0000000..ff0fabf --- /dev/null +++ b/src/ctype/records.rs @@ -0,0 +1,82 @@ +use super::{StructDefinition, StructMember, StructType, Type}; +use std::{cell::RefCell, fmt, rc::Rc}; + +impl StructType { + pub fn new(id: usize) -> (Self, Rc>) { + let definition = Rc::new(RefCell::new(StructDefinition::default())); + ( + Self { + id, + definition: Rc::downgrade(&definition), + }, + definition, + ) + } + pub fn definition(&self) -> Rc> { + self.definition + .upgrade() + .expect("struct definitions outlive the compiler pipeline") + } + pub fn has_bit_fields(&self) -> bool { + self.definition().borrow().has_bit_fields + } + pub fn members(&self) -> Vec { + self.definition().borrow().members.clone() + } + pub fn member(&self, index: usize) -> StructMember { + self.definition().borrow().members[index].clone() + } + pub fn visible_members(&self) -> Vec<(String, Vec)> { + self.members() + .iter() + .enumerate() + .flat_map(|(index, member)| { + if member.anonymous { + let Type::Struct(child) = member.ty.unqualified() else { + unreachable!() + }; + child + .visible_members() + .into_iter() + .map(|(name, mut path)| { + path.insert(0, index); + (name, path) + }) + .collect() + } else { + vec![(member.name.clone(), vec![index])] + } + }) + .collect() + } + pub fn member_path(&self, name: &str) -> Option> { + let definition = self.definition(); + let definition = definition.borrow(); + for (index, member) in definition.members.iter().enumerate() { + if member.anonymous { + let Type::Struct(child) = member.ty.unqualified() else { + unreachable!() + }; + if let Some(mut path) = child.member_path(name) { + path.insert(0, index); + return Some(path); + } + } else if member.name == name { + return Some(vec![index]); + } + } + None + } +} + +impl PartialEq for StructType { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl fmt::Debug for StructType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Struct({})", self.id) + } +} diff --git a/src/generator/aarch64/generator.rs b/src/generator/aarch64/generator.rs index be96886..926f8bd 100644 --- a/src/generator/aarch64/generator.rs +++ b/src/generator/aarch64/generator.rs @@ -1,5 +1,7 @@ mod aggregate; mod atomic; +mod calls; +mod control_flow; mod globals; mod inline_asm; @@ -708,45 +710,21 @@ impl<'a> AsmGenerator<'a> { ] .into(); } - NodeType::Conditional | NodeType::If => { - let branch_num = node.token.as_ref().unwrap().pos; - let branch = |child: &Node| { - if node.nt == NodeType::If { - self.gen_statements(std::slice::from_ref(child), options) - } else { - self.gen_node(child, options) - } - }; - return vec![ - self.gen_node(node.cond.as_ref().unwrap(), options), - Self::pop(X8), - Assembly::inst2(CMP, X8, 0), - Assembly::inst1(JE, ElseFlag(branch_num)), - branch(node.then.as_deref().unwrap()), - Assembly::inst1(JMP, EndFlag(branch_num)), - format!("{}:", ElseFlag(branch_num)).into(), - node.els - .as_deref() - .map(branch) - .unwrap_or_else(|| vec![].into()), - format!("{}:", EndFlag(branch_num)).into(), - if matches!(node.nt, NodeType::Conditional) - && node - .resolve_type() - .is_some_and(|ty| ty.integer_info().is_some()) - { - vec![ - Self::pop(X8), - Self::normalize_integer(&node.resolve_type().unwrap(), X8), - Self::push(X8), - ] - .into() - } else { - vec![].into() - }, - ] - .into(); + NodeType::Conditional + | NodeType::If + | NodeType::Block + | NodeType::Return + | NodeType::While + | NodeType::DoWhile + | NodeType::For + | NodeType::Switch + | NodeType::Case + | NodeType::Continue + | NodeType::Goto + | NodeType::Label => { + return self.gen_control_flow(node, options); } + NodeType::Assign => { return vec![ self.gen_addr(node.lhs.as_ref().unwrap(), options), @@ -794,95 +772,8 @@ impl<'a> AsmGenerator<'a> { ] .into(); } - NodeType::CallFunc => { - if matches!(node.resolve_type(), Some(Type::Struct(_))) - || node - .args - .iter() - .any(|arg| matches!(arg.resolve_type(), Some(Type::Struct(_)))) - { - return self.aggregate_call(node, options); - } - if node.resolve_type().unwrap().float_bits().is_some() - || node - .args - .iter() - .any(|arg| arg.resolve_type().unwrap().float_bits().is_some()) - { - return self.float_call(node, options); - } - let fixed = if matches!(self.target_os, Os::MacOS) && node.variadic { - node.parameter_types.len() - } else { - node.args.len() - }; - let types = node - .args - .iter() - .rev() - .enumerate() - .map(|(i, arg)| { - node.parameter_types - .get(i) - .cloned() - .unwrap_or_else(|| arg.resolve_type().unwrap()) - }) - .collect::>(); - let (stack_slots, stack_size) = self.stack_arguments(&types, fixed); - let mut lines = vec![ - node.lhs - .as_ref() - .map(|callee| self.gen_node(callee, options)) - .unwrap_or_else(|| vec![].into()), - node.args - .iter() - .map(|arg| self.gen_node(arg, options)) - .collect::>() - .into(), - ]; - lines.push(Assembly::inst3(SUB, X10, X19, stack_size)); - lines.push(Assembly::inst3(AND, X10, X10, "#-16")); - lines.push(Assembly::inst2(MOV, SP, X10)); - for (i, register) in ARGS_REG.iter().take(fixed).enumerate() { - lines.push(Assembly::inst2( - LDR, - *register, - PtrAdd(X19, format!("#{}", i * 8)), - )); - } - for (i, slot, size) in stack_slots { - lines.push(Assembly::inst2(LDR, X8, PtrAdd(X19, format!("#{}", i * 8)))); - lines.push(Assembly::inst3(ADD, X11, SP, slot)); - lines.push(Assembly::inst2(STR, X8, Ptr(X11, size))); - } - lines.extend([ - if node.lhs.is_some() { - vec![ - Assembly::inst2( - LDR, - X12, - PtrAdd(X19, format!("#{}", node.args.len() * 8)), - ), - Assembly::inst1(BLR, X12), - ] - .into() - } else { - Assembly::inst1(BL, self.with_prefix(&node.global_name)) - }, - Assembly::inst3( - ADD, - X19, - X19, - (node.args.len() + usize::from(node.lhs.is_some())) * 8, - ), - Assembly::inst2(MOV, SP, X29), - node.cty - .as_ref() - .map(|ty| Self::normalize_integer(ty, X0)) - .unwrap_or_else(|| vec![].into()), - Self::push(X0), - ]); - return lines.into(); + NodeType::CallFunc | NodeType::VaStart | NodeType::VaEnd => { + return self.gen_calls(node, options); } NodeType::Sequence => { let mut lines = vec![]; @@ -899,140 +790,7 @@ impl<'a> AsmGenerator<'a> { NodeType::DefVar => { return self.gen_statements(&node.children, options); } - NodeType::Block => { - return self.gen_statements(&node.children, options); - } - NodeType::Return => { - if matches!(node.resolve_type(), Some(Type::Struct(_))) { - return self.aggregate_return(node, options); - } - if node.lhs.is_none() { - return Self::epilogue(options.offset); - } - return vec![ - self.gen_node(node.lhs.as_ref().unwrap(), options), - Self::pop(X0), - if let Some(bits) = node.resolve_type().and_then(|ty| ty.float_bits()) { - Assembly::inst2(FMOV, Float(0, bits), if bits == 32 { W0 } else { X0 }) - } else { - vec![].into() - }, - Self::epilogue(options.offset), - ] - .into(); - } - NodeType::While => { - let branch_num = node.token.as_ref().unwrap().pos; - let options = Options { - breakable_branch_num: branch_num, - ..options - }; - let v = vec![ - format!(".Lcontinue.{}:", branch_num).into(), - format!("{}:", BeginFlag(branch_num)).into(), - self.gen_node(node.cond.as_ref().unwrap(), options), - Self::pop(X8), - Assembly::inst2(CMP, X8, 0), - Assembly::inst1(JE, EndFlag(branch_num)), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - options, - ), - Assembly::inst1(JMP, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ]; - return v.into(); - } - NodeType::DoWhile => { - let branch_num = node.token.as_ref().unwrap().pos; - let options = Options { - breakable_branch_num: branch_num, - ..options - }; - return vec![ - format!("{}:", BeginFlag(branch_num)).into(), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - options, - ), - format!(".Lcontinue.{}:", branch_num).into(), - self.gen_node(node.cond.as_ref().unwrap(), options), - Self::pop(X8), - Assembly::inst2(CMP, X8, 0), - Assembly::inst1(JNE, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ] - .into(); - } - NodeType::For => { - let branch_num = node.token.as_ref().unwrap().pos; - let options = Options { - breakable_branch_num: branch_num, - ..options - }; - let v = vec![ - node.ini.as_ref().map_or(Vec::new().into(), |node| { - self.gen_statements(std::slice::from_ref(node.as_ref()), options) - }), - format!("{}:", BeginFlag(branch_num)).into(), - node.cond - .as_ref() - .map_or(Assembly::inst2(MOV, X8, 1), |node| { - vec![self.gen_node(node, options), Self::pop(X8)].into() - }), - Assembly::inst2(CMP, X8, 0), - Assembly::inst1(JE, EndFlag(branch_num)), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - options, - ), - format!(".Lcontinue.{}:", branch_num).into(), - node.upd.as_ref().map_or(Vec::new().into(), |node| { - vec![self.gen_node(node, options), Self::pop(X8)].into() - }), - Assembly::inst1(JMP, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ]; - return v.into(); - } - NodeType::Switch => { - let branch_num = node.token.as_ref().unwrap().pos; - let mut lines = vec![ - self.gen_node(node.cond.as_ref().unwrap(), options), - Self::pop(X8), - ]; - let mut default = format!("{}", EndFlag(branch_num)); - for case in &node.children { - let label = format!(".Lcase.{}", case.token.as_ref().unwrap().pos); - if let Some(value) = case.value { - lines.push(Assembly::inst2(MOV, X9, value)); - lines.push(Assembly::inst2(CMP, X8, X9)); - lines.push(Assembly::inst1(JE, label)); - } else { - default = label; - } - } - lines.push(Assembly::inst1(JMP, default)); - lines.push(self.gen_node( - node.then.as_ref().unwrap(), - Options { - breakable_branch_num: branch_num, - ..options - }, - )); - lines.push(format!("{}:", EndFlag(branch_num)).into()); - return lines.into(); - } - NodeType::Case => { - return vec![ - format!(".Lcase.{}:", node.token.as_ref().unwrap().pos).into(), - self.gen_statements( - std::slice::from_ref(node.lhs.as_deref().unwrap()), - options, - ), - ] - .into(); - } + NodeType::Break => { if options.breakable_branch_num != 0 { return Assembly::inst1(JMP, EndFlag(options.breakable_branch_num)); @@ -1043,22 +801,6 @@ impl<'a> AsmGenerator<'a> { ); } } - NodeType::Continue => { - return Assembly::inst1(JMP, format!(".Lcontinue.{}", node.value.unwrap())); - } - NodeType::Goto => { - return Assembly::inst1(JMP, format!(".Lgoto.{}", node.value.unwrap())); - } - NodeType::Label => { - return vec![ - format!(".Lgoto.{}:", node.value.unwrap()).into(), - self.gen_statements( - std::slice::from_ref(node.lhs.as_deref().unwrap()), - options, - ), - ] - .into(); - } NodeType::FloatAbs => { let shift = 65 - node.resolve_type().unwrap().float_bits().unwrap() as usize; return vec![ @@ -1082,42 +824,7 @@ impl<'a> AsmGenerator<'a> { lines.extend([Assembly::inst2(CLZ, register, register), Self::push(X8)]); return lines.into(); } - NodeType::VaStart | NodeType::VaEnd => { - let mut lines = vec![ - self.gen_node(node.lhs.as_ref().unwrap(), options), - Self::pop(X11), - ]; - if node.nt == NodeType::VaStart { - let (gp, fp, stack) = crate::generator::abi::variadic_state( - node, - crate::generator::Arch::Aarch64, - self.target_os, - ); - lines.extend([ - Assembly::inst3(ADD, X8, X29, options.offset + 32 + stack), - Assembly::inst2(STR, X8, Ptr(X11, 8)), - ]); - if !matches!(self.target_os, Os::MacOS) { - for (position, top) in [(8, 64), (16, 192)] { - lines.extend([ - Assembly::inst3(ADD, X8, X29, top), - Assembly::inst3(ADD, X10, X11, position), - Assembly::inst2(STR, X8, Ptr(X10, 8)), - ]); - } - for (position, remaining) in [(24, (8 - gp) * 8), (28, (8 - fp) * 16)] { - lines.extend([ - Assembly::inst2(MOV, X8, 0), - Assembly::inst3(SUB, X8, X8, remaining), - Assembly::inst3(ADD, X10, X11, position), - Assembly::inst2(STR, X8, Ptr(X10, 4)), - ]); - } - } - } - lines.push(Self::push(0)); - return lines.into(); - } + NodeType::Prefetch(write, locality) => { return self.gen_prefetch(node, write, locality, options); } diff --git a/src/generator/aarch64/generator/calls.rs b/src/generator/aarch64/generator/calls.rs new file mode 100644 index 0000000..4efa572 --- /dev/null +++ b/src/generator/aarch64/generator/calls.rs @@ -0,0 +1,142 @@ +use super::super::assembly::Assembly; +use super::super::instruction::{InstOperand::*, InstOperator::*, Register::*}; +use super::{ARGS_REG, AsmGenerator, Options}; +use crate::generator::Os; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; + +impl AsmGenerator<'_> { + pub(super) fn gen_calls(&self, node: &Node, options: Options) -> Assembly { + match node.nt { + NodeType::CallFunc => { + if matches!(node.resolve_type(), Some(Type::Struct(_))) + || node + .args + .iter() + .any(|arg| matches!(arg.resolve_type(), Some(Type::Struct(_)))) + { + return self.aggregate_call(node, options); + } + if node.resolve_type().unwrap().float_bits().is_some() + || node + .args + .iter() + .any(|arg| arg.resolve_type().unwrap().float_bits().is_some()) + { + return self.float_call(node, options); + } + let fixed = if matches!(self.target_os, Os::MacOS) && node.variadic { + node.parameter_types.len() + } else { + node.args.len() + }; + let types = node + .args + .iter() + .rev() + .enumerate() + .map(|(i, arg)| { + node.parameter_types + .get(i) + .cloned() + .unwrap_or_else(|| arg.resolve_type().unwrap()) + }) + .collect::>(); + let (stack_slots, stack_size) = self.stack_arguments(&types, fixed); + let mut lines = vec![ + node.lhs + .as_ref() + .map(|callee| self.gen_node(callee, options)) + .unwrap_or_else(|| vec![].into()), + node.args + .iter() + .map(|arg| self.gen_node(arg, options)) + .collect::>() + .into(), + ]; + lines.push(Assembly::inst3(SUB, X10, X19, stack_size)); + lines.push(Assembly::inst3(AND, X10, X10, "#-16")); + lines.push(Assembly::inst2(MOV, SP, X10)); + for (i, register) in ARGS_REG.iter().take(fixed).enumerate() { + lines.push(Assembly::inst2( + LDR, + *register, + PtrAdd(X19, format!("#{}", i * 8)), + )); + } + for (i, slot, size) in stack_slots { + lines.push(Assembly::inst2(LDR, X8, PtrAdd(X19, format!("#{}", i * 8)))); + lines.push(Assembly::inst3(ADD, X11, SP, slot)); + lines.push(Assembly::inst2(STR, X8, Ptr(X11, size))); + } + lines.extend([ + if node.lhs.is_some() { + vec![ + Assembly::inst2( + LDR, + X12, + PtrAdd(X19, format!("#{}", node.args.len() * 8)), + ), + Assembly::inst1(BLR, X12), + ] + .into() + } else { + Assembly::inst1(BL, self.with_prefix(&node.global_name)) + }, + Assembly::inst3( + ADD, + X19, + X19, + (node.args.len() + usize::from(node.lhs.is_some())) * 8, + ), + Assembly::inst2(MOV, SP, X29), + node.cty + .as_ref() + .map(|ty| Self::normalize_integer(ty, X0)) + .unwrap_or_else(|| vec![].into()), + Self::push(X0), + ]); + lines.into() + } + NodeType::VaStart | NodeType::VaEnd => { + let mut lines = vec![ + self.gen_node(node.lhs.as_ref().unwrap(), options), + Self::pop(X11), + ]; + if node.nt == NodeType::VaStart { + let (gp, fp, stack) = crate::generator::abi::variadic_state( + node, + crate::generator::Arch::Aarch64, + self.target_os, + ); + lines.extend([ + Assembly::inst3(ADD, X8, X29, options.offset + 32 + stack), + Assembly::inst2(STR, X8, Ptr(X11, 8)), + ]); + if !matches!(self.target_os, Os::MacOS) { + for (position, top) in [(8, 64), (16, 192)] { + lines.extend([ + Assembly::inst3(ADD, X8, X29, top), + Assembly::inst3(ADD, X10, X11, position), + Assembly::inst2(STR, X8, Ptr(X10, 8)), + ]); + } + for (position, remaining) in [(24, (8 - gp) * 8), (28, (8 - fp) * 16)] { + lines.extend([ + Assembly::inst2(MOV, X8, 0), + Assembly::inst3(SUB, X8, X8, remaining), + Assembly::inst3(ADD, X10, X11, position), + Assembly::inst2(STR, X8, Ptr(X10, 4)), + ]); + } + } + } + lines.push(Self::push(0)); + lines.into() + } + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/generator/aarch64/generator/control_flow.rs b/src/generator/aarch64/generator/control_flow.rs new file mode 100644 index 0000000..ac15227 --- /dev/null +++ b/src/generator/aarch64/generator/control_flow.rs @@ -0,0 +1,190 @@ +use super::super::assembly::Assembly; +use super::super::instruction::{InstOperand::*, InstOperator::*, Register::*}; +use super::{AsmGenerator, Options}; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; + +impl AsmGenerator<'_> { + pub(super) fn gen_control_flow(&self, node: &Node, options: Options) -> Assembly { + match node.nt { + NodeType::Conditional | NodeType::If => { + let branch_num = node.token.as_ref().unwrap().pos; + let branch = |child: &Node| { + if node.nt == NodeType::If { + self.gen_statements(std::slice::from_ref(child), options) + } else { + self.gen_node(child, options) + } + }; + vec![ + self.gen_node(node.cond.as_ref().unwrap(), options), + Self::pop(X8), + Assembly::inst2(CMP, X8, 0), + Assembly::inst1(JE, ElseFlag(branch_num)), + branch(node.then.as_deref().unwrap()), + Assembly::inst1(JMP, EndFlag(branch_num)), + format!("{}:", ElseFlag(branch_num)).into(), + node.els + .as_deref() + .map(branch) + .unwrap_or_else(|| vec![].into()), + format!("{}:", EndFlag(branch_num)).into(), + if matches!(node.nt, NodeType::Conditional) + && node + .resolve_type() + .is_some_and(|ty| ty.integer_info().is_some()) + { + vec![ + Self::pop(X8), + Self::normalize_integer(&node.resolve_type().unwrap(), X8), + Self::push(X8), + ] + .into() + } else { + vec![].into() + }, + ] + .into() + } + NodeType::Block => self.gen_statements(&node.children, options), + NodeType::Return => { + if matches!(node.resolve_type(), Some(Type::Struct(_))) { + return self.aggregate_return(node, options); + } + if node.lhs.is_none() { + return Self::epilogue(options.offset); + } + vec![ + self.gen_node(node.lhs.as_ref().unwrap(), options), + Self::pop(X0), + if let Some(bits) = node.resolve_type().and_then(|ty| ty.float_bits()) { + Assembly::inst2(FMOV, Float(0, bits), if bits == 32 { W0 } else { X0 }) + } else { + vec![].into() + }, + Self::epilogue(options.offset), + ] + .into() + } + NodeType::While => { + let branch_num = node.token.as_ref().unwrap().pos; + let options = Options { + breakable_branch_num: branch_num, + ..options + }; + let v = vec![ + format!(".Lcontinue.{}:", branch_num).into(), + format!("{}:", BeginFlag(branch_num)).into(), + self.gen_node(node.cond.as_ref().unwrap(), options), + Self::pop(X8), + Assembly::inst2(CMP, X8, 0), + Assembly::inst1(JE, EndFlag(branch_num)), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + options, + ), + Assembly::inst1(JMP, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ]; + v.into() + } + NodeType::DoWhile => { + let branch_num = node.token.as_ref().unwrap().pos; + let options = Options { + breakable_branch_num: branch_num, + ..options + }; + vec![ + format!("{}:", BeginFlag(branch_num)).into(), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + options, + ), + format!(".Lcontinue.{}:", branch_num).into(), + self.gen_node(node.cond.as_ref().unwrap(), options), + Self::pop(X8), + Assembly::inst2(CMP, X8, 0), + Assembly::inst1(JNE, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ] + .into() + } + NodeType::For => { + let branch_num = node.token.as_ref().unwrap().pos; + let options = Options { + breakable_branch_num: branch_num, + ..options + }; + let v = vec![ + node.ini.as_ref().map_or(Vec::new().into(), |node| { + self.gen_statements(std::slice::from_ref(node.as_ref()), options) + }), + format!("{}:", BeginFlag(branch_num)).into(), + node.cond + .as_ref() + .map_or(Assembly::inst2(MOV, X8, 1), |node| { + vec![self.gen_node(node, options), Self::pop(X8)].into() + }), + Assembly::inst2(CMP, X8, 0), + Assembly::inst1(JE, EndFlag(branch_num)), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + options, + ), + format!(".Lcontinue.{}:", branch_num).into(), + node.upd.as_ref().map_or(Vec::new().into(), |node| { + vec![self.gen_node(node, options), Self::pop(X8)].into() + }), + Assembly::inst1(JMP, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ]; + v.into() + } + NodeType::Switch => { + let branch_num = node.token.as_ref().unwrap().pos; + let mut lines = vec![ + self.gen_node(node.cond.as_ref().unwrap(), options), + Self::pop(X8), + ]; + let mut default = format!("{}", EndFlag(branch_num)); + for case in &node.children { + let label = format!(".Lcase.{}", case.token.as_ref().unwrap().pos); + if let Some(value) = case.value { + lines.push(Assembly::inst2(MOV, X9, value)); + lines.push(Assembly::inst2(CMP, X8, X9)); + lines.push(Assembly::inst1(JE, label)); + } else { + default = label; + } + } + lines.push(Assembly::inst1(JMP, default)); + lines.push(self.gen_node( + node.then.as_ref().unwrap(), + Options { + breakable_branch_num: branch_num, + ..options + }, + )); + lines.push(format!("{}:", EndFlag(branch_num)).into()); + lines.into() + } + NodeType::Case => vec![ + format!(".Lcase.{}:", node.token.as_ref().unwrap().pos).into(), + self.gen_statements(std::slice::from_ref(node.lhs.as_deref().unwrap()), options), + ] + .into(), + NodeType::Continue => { + Assembly::inst1(JMP, format!(".Lcontinue.{}", node.value.unwrap())) + } + NodeType::Goto => Assembly::inst1(JMP, format!(".Lgoto.{}", node.value.unwrap())), + NodeType::Label => vec![ + format!(".Lgoto.{}:", node.value.unwrap()).into(), + self.gen_statements(std::slice::from_ref(node.lhs.as_deref().unwrap()), options), + ] + .into(), + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/generator/llvm/generator.rs b/src/generator/llvm/generator.rs index e96f4ae..58e20a1 100644 --- a/src/generator/llvm/generator.rs +++ b/src/generator/llvm/generator.rs @@ -1,5 +1,7 @@ mod aggregate; mod atomic; +mod calls; +mod control_flow; mod globals; mod inline_asm; @@ -902,112 +904,24 @@ impl<'a> IrGenerator<'a> { )); return lines; } - NodeType::LogicalAnd | NodeType::LogicalOr => { - let mut lines = vec![]; - let predicate = self.gen_predicate(node.lhs.as_ref().unwrap(), options, &mut lines); - let slot = options.expression_slots[&node.token.as_ref().unwrap().pos]; - let rhs_label = options.new_label(); - let short_label = options.new_label(); - let end_label = options.new_label(); - let is_and = matches!(node.nt, NodeType::LogicalAnd); - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, - if is_and { &rhs_label } else { &short_label }, - if is_and { &short_label } else { &rhs_label } - )); - lines.push(format!("{}:", short_label)); - lines.push(format!( - " store i32 {}, ptr %{}, align 4", - if is_and { 0 } else { 1 }, - slot - )); - lines.push(format!(" br label %{}", end_label)); - lines.push(format!("{}:", rhs_label)); - let predicate = self.gen_predicate(node.rhs.as_ref().unwrap(), options, &mut lines); - let value = options.new_temporary(); - lines.push(format!(" %{} = zext i1 {} to i32", value, predicate)); - lines.push(format!(" store i32 %{}, ptr %{}, align 4", value, slot)); - lines.push(format!(" br label %{}", end_label)); - lines.push(format!("{}:", end_label)); - lines.push(format!( - " %{} = load i32, ptr %{}, align 4", - options.new_register(), - slot - )); - return lines; + NodeType::LogicalAnd + | NodeType::LogicalOr + | NodeType::Conditional + | NodeType::Block + | NodeType::Return + | NodeType::If + | NodeType::While + | NodeType::For + | NodeType::DoWhile + | NodeType::Switch + | NodeType::Case + | NodeType::Break + | NodeType::Continue + | NodeType::Goto + | NodeType::Label => { + return self.gen_control_flow(node, options); } - NodeType::Conditional => { - if node.resolve_type_view().as_deref() == Some(&Type::Void) { - let mut lines = vec![]; - let predicate = - self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); - let then_label = options.new_label(); - let else_label = options.new_label(); - let end_label = options.new_label(); - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, then_label, else_label - )); - for (label, branch) in [ - (&then_label, node.then.as_ref().unwrap()), - (&else_label, node.els.as_ref().unwrap()), - ] { - lines.push(format!("{}:", label)); - lines.extend(self.gen_node(branch, options)); - options.register_queue.pop(); - lines.push(format!(" br label %{}", end_label)); - } - lines.push(format!("{}:", end_label)); - options.register_queue.push("0".to_string()); - return lines; - } - let mut lines = vec![]; - let ty = node.resolve_type_view().unwrap(); - let slot = options.expression_slots[&node.token.as_ref().unwrap().pos]; - let predicate = - self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); - let then_label = options.new_label(); - let else_label = options.new_label(); - let end_label = options.new_label(); - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, then_label, else_label - )); - for (label, branch) in [ - (&then_label, node.then.as_ref().unwrap()), - (&else_label, node.els.as_ref().unwrap()), - ] { - lines.push(format!("{}:", label)); - lines.extend(self.gen_node(branch, options)); - let value = options.register_queue.pop().unwrap(); - let value = Self::convert_integer( - value, - &branch.resolve_type_view().unwrap(), - &ty, - options, - &mut lines, - ); - lines.push(format!( - " store {} {}, ptr %{}, align {}", - Self::gen_type(&ty), - value, - slot, - Self::align(&ty) - )); - lines.push(format!(" br label %{}", end_label)); - } - lines.push(format!("{}:", end_label)); - lines.push(format!( - " %{} = load {}, ptr %{}, align {}", - options.new_register(), - Self::gen_type(&ty), - slot, - Self::align(&ty) - )); - return lines; - } NodeType::Assign => { let mut lines = self.gen_node(node.rhs.as_ref().unwrap(), options); let value = options.register_queue.pop().unwrap(); @@ -1110,74 +1024,8 @@ impl<'a> IrGenerator<'a> { options.register_queue.push(format!("%{}", old)); return lines; } - NodeType::CallFunc => { - if matches!(node.resolve_type_view().as_deref(), Some(Type::Struct(_))) - || node.args.iter().any(|arg| { - matches!(arg.resolve_type_view().as_deref(), Some(Type::Struct(_))) - }) - { - return self.aggregate_call(node, options); - } - let parameters = &node.parameter_types; - let result = node.cty.as_ref().unwrap(); - let variadic = node.variadic; - let mut lines = vec![]; - let callee = if let Some(callee) = &node.lhs { - lines.extend(self.gen_node(callee, options)); - options.register_queue.pop().unwrap() - } else { - self.symbol_name(&node.global_name) - }; - let mut arguments = vec![]; - for (i, arg) in node.args.iter().enumerate() { - lines.extend(self.gen_node(arg, options)); - let value = options.register_queue.pop().unwrap(); - let source = Type::decay_view(arg.resolve_type_view().unwrap()); - let ty = parameters - .get(node.args.len() - i - 1) - .map(Cow::Borrowed) - .unwrap_or_else(|| { - if source.integer_info().is_some() { - Cow::Owned(source.promoted()) - } else { - Cow::Borrowed(source.as_ref()) - } - }); - let value = Self::convert_integer(value, &source, &ty, options, &mut lines); - arguments.push(format!("{} {}", Self::abi_parameter_type(&ty), value)); - } - arguments.reverse(); - let signature = if variadic { - format!( - " ({}, ...)", - parameters - .iter() - .map(Self::gen_type) - .collect::>() - .join(", ") - ) - } else { - String::new() - }; - if *result == Type::Void { - lines.push(format!( - " call void{} {}({})", - signature, - callee, - arguments.join(", ") - )); - options.register_queue.push("0".to_string()); - return lines; - } - lines.push(format!( - " %{} = call {}{} {}({})", - options.new_register(), - Self::abi_result_type(result), - signature, - callee, - arguments.join(", ") - )); - return lines; + NodeType::CallFunc | NodeType::VaStart | NodeType::VaEnd => { + return self.gen_calls(node, options); } NodeType::Sequence => { let mut lines = vec![]; @@ -1197,238 +1045,7 @@ impl<'a> IrGenerator<'a> { .flat_map(|node| self.gen_node(node, options)) .collect(); } - NodeType::Block => { - return node - .children - .iter() - .flat_map(|node| self.gen_node(node, options)) - .collect(); - } - NodeType::Return => { - if matches!(options.return_ty, Type::Struct(_)) { - return self.aggregate_return(node, options); - } - if options.return_ty == Type::Void { - let mut lines = if let Some(operand) = &node.lhs { - self.gen_node(operand, options) - } else { - vec![] - }; - if node.lhs.is_some() { - options.register_queue.pop(); - } - lines.push(" ret void".to_string()); - options.terminated = true; - return lines; - } - if node.lhs.is_none() { - options.terminated = true; - return vec![" ret void".to_string()]; - } - let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); - let value = options.register_queue.pop().unwrap(); - let source_ty = node.resolve_type_view().unwrap(); - let target_ty = options.return_ty.clone(); - let value = - Self::convert_integer(value, &source_ty, &target_ty, options, &mut lines); - lines.push(format!( - " ret {} {}", - Self::gen_type_with_opaque_ptr(&target_ty), - value - )); - options.terminated = true; - return lines; - } - NodeType::If => { - let mut lines = vec![]; - let predicate = - self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); - let then_label = options.new_label(); - let else_label = options.new_label(); - let end_label = options.new_label(); - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, then_label, else_label, - )); - - lines.push(format!("{}:", then_label)); - options.terminated = false; - lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); - let then_terminated = options.terminated; - if !then_terminated { - lines.push(format!(" br label %{}", end_label)); - } - lines.push(format!("{}:", else_label)); - options.terminated = false; - if let Some(els) = &node.els { - lines.extend(self.gen_node(els, options)); - } - let else_terminated = options.terminated; - if !else_terminated { - lines.push(format!(" br label %{}", end_label)); - } - - options.terminated = then_terminated && else_terminated; - if !options.terminated { - lines.push(format!("{}:", end_label)); - } - return lines; - } - NodeType::While | NodeType::For => { - let mut lines = vec![]; - if let Some(initializer) = &node.ini { - lines.extend(self.gen_node(initializer, options)); - } - let condition_label = options.new_label(); - let body_label = options.new_label(); - let update_label = format!("continue.{}", node.token.as_ref().unwrap().pos); - let end_label = options.new_label(); - lines.push(format!(" br label %{}", condition_label)); - lines.push(format!("{}:", condition_label)); - let predicate = if let Some(condition) = &node.cond { - self.gen_predicate(condition, options, &mut lines) - } else { - "true".to_string() - }; - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, body_label, end_label - )); - lines.push(format!("{}:", body_label)); - options.break_labels.push(end_label.clone()); - lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); - options.break_labels.pop(); - if !options.terminated { - lines.push(format!(" br label %{}", update_label)); - } - options.terminated = false; - lines.push(format!("{}:", update_label)); - if let Some(update) = &node.upd { - lines.extend(self.gen_node(update, options)); - } - lines.push(format!(" br label %{}", condition_label)); - lines.push(format!("{}:", end_label)); - return lines; - } - NodeType::DoWhile => { - let body_label = options.new_label(); - let condition_label = format!("continue.{}", node.token.as_ref().unwrap().pos); - let end_label = options.new_label(); - let mut lines = vec![ - format!(" br label %{}", body_label), - format!("{}:", body_label), - ]; - options.break_labels.push(end_label.clone()); - lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); - options.break_labels.pop(); - if !options.terminated { - lines.push(format!(" br label %{}", condition_label)); - } - options.terminated = false; - lines.push(format!("{}:", condition_label)); - let predicate = - self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); - lines.push(format!( - " br i1 {}, label %{}, label %{}", - predicate, body_label, end_label - )); - lines.push(format!("{}:", end_label)); - return lines; - } - NodeType::Switch => { - let mut lines = self.gen_node(node.cond.as_ref().unwrap(), options); - let value = options.register_queue.pop().unwrap(); - let selector_ty = node - .cond - .as_ref() - .unwrap() - .resolve_type_view() - .unwrap() - .promoted(); - let value = Self::convert_integer( - value, - &node.cond.as_ref().unwrap().resolve_type_view().unwrap(), - &selector_ty, - options, - &mut lines, - ); - let end = options.new_label(); - let default = node - .children - .iter() - .find(|case| case.value.is_none()) - .map(|case| format!("case.{}", case.token.as_ref().unwrap().pos)) - .unwrap_or(end.clone()); - lines.push(format!( - " switch {} {}, label %{} [", - Self::gen_type(&selector_ty), - value, - default - )); - for case in &node.children { - if let Some(value) = case.value { - lines.push(format!( - " {} {}, label %case.{}", - Self::gen_type(&selector_ty), - value as i64, - case.token.as_ref().unwrap().pos - )); - } - } - lines.push(" ]".to_string()); - options.terminated = true; - options.break_labels.push(end.clone()); - lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); - options.break_labels.pop(); - if !options.terminated { - lines.push(format!(" br label %{}", end)); - } - lines.push(format!("{}:", end)); - options.terminated = false; - return lines; - } - NodeType::Case => { - let label = format!("case.{}", node.token.as_ref().unwrap().pos); - let mut lines = vec![]; - if !options.terminated { - lines.push(format!(" br label %{}", label)); - } - lines.push(format!("{}:", label)); - options.terminated = false; - lines.extend(self.gen_node(node.lhs.as_ref().unwrap(), options)); - return lines; - } - NodeType::Break => { - let Some(label) = options.break_labels.last() else { - self.error_logger.print_error_position( - node.token.as_ref().unwrap().pos, - "unexpected break found", - ); - unreachable!() - }; - options.terminated = true; - return vec![format!(" br label %{}", label)]; - } - NodeType::Continue => { - options.terminated = true; - return vec![format!(" br label %continue.{}", node.value.unwrap())]; - } - NodeType::Goto => { - options.terminated = true; - return vec![format!(" br label %goto.{}", node.value.unwrap())]; - } - NodeType::Label => { - let label = format!("goto.{}", node.value.unwrap()); - let mut lines = vec![]; - if !options.terminated { - lines.push(format!(" br label %{label}")); - } - lines.push(format!("{label}:")); - options.terminated = false; - lines.extend(self.gen_node(node.lhs.as_ref().unwrap(), options)); - return lines; - } NodeType::FloatAbs => { let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); let value = options.register_queue.pop().unwrap(); @@ -1462,18 +1079,7 @@ impl<'a> IrGenerator<'a> { } return lines; } - NodeType::VaStart | NodeType::VaEnd => { - let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); - let pointer = options.register_queue.pop().unwrap(); - let intrinsic = if node.nt == NodeType::VaStart { - "va_start" - } else { - "va_end" - }; - lines.push(format!(" call void @llvm.{intrinsic}(ptr {pointer})")); - options.register_queue.push("0".into()); - return lines; - } + NodeType::StackAlloc => { let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); let size = options.register_queue.pop().unwrap(); diff --git a/src/generator/llvm/generator/calls.rs b/src/generator/llvm/generator/calls.rs new file mode 100644 index 0000000..0882652 --- /dev/null +++ b/src/generator/llvm/generator/calls.rs @@ -0,0 +1,95 @@ +use super::{IrGenerator, Options}; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; +use std::borrow::Cow; + +impl IrGenerator<'_> { + pub(super) fn gen_calls(&self, node: &Node, options: &mut Options) -> Vec { + match node.nt { + NodeType::CallFunc => { + if matches!(node.resolve_type_view().as_deref(), Some(Type::Struct(_))) + || node.args.iter().any(|arg| { + matches!(arg.resolve_type_view().as_deref(), Some(Type::Struct(_))) + }) + { + return self.aggregate_call(node, options); + } + let parameters = &node.parameter_types; + let result = node.cty.as_ref().unwrap(); + let variadic = node.variadic; + let mut lines = vec![]; + let callee = if let Some(callee) = &node.lhs { + lines.extend(self.gen_node(callee, options)); + options.register_queue.pop().unwrap() + } else { + self.symbol_name(&node.global_name) + }; + let mut arguments = vec![]; + for (i, arg) in node.args.iter().enumerate() { + lines.extend(self.gen_node(arg, options)); + let value = options.register_queue.pop().unwrap(); + let source = Type::decay_view(arg.resolve_type_view().unwrap()); + let ty = parameters + .get(node.args.len() - i - 1) + .map(Cow::Borrowed) + .unwrap_or_else(|| { + if source.integer_info().is_some() { + Cow::Owned(source.promoted()) + } else { + Cow::Borrowed(source.as_ref()) + } + }); + let value = Self::convert_integer(value, &source, &ty, options, &mut lines); + arguments.push(format!("{} {}", Self::abi_parameter_type(&ty), value)); + } + arguments.reverse(); + let signature = if variadic { + format!( + " ({}, ...)", + parameters + .iter() + .map(Self::gen_type) + .collect::>() + .join(", ") + ) + } else { + String::new() + }; + if *result == Type::Void { + lines.push(format!( + " call void{} {}({})", + signature, + callee, + arguments.join(", ") + )); + options.register_queue.push("0".to_string()); + return lines; + } + lines.push(format!( + " %{} = call {}{} {}({})", + options.new_register(), + Self::abi_result_type(result), + signature, + callee, + arguments.join(", ") + )); + lines + } + NodeType::VaStart | NodeType::VaEnd => { + let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); + let pointer = options.register_queue.pop().unwrap(); + let intrinsic = if node.nt == NodeType::VaStart { + "va_start" + } else { + "va_end" + }; + lines.push(format!(" call void @llvm.{intrinsic}(ptr {pointer})")); + options.register_queue.push("0".into()); + lines + } + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/generator/llvm/generator/control_flow.rs b/src/generator/llvm/generator/control_flow.rs new file mode 100644 index 0000000..c1b1880 --- /dev/null +++ b/src/generator/llvm/generator/control_flow.rs @@ -0,0 +1,349 @@ +use super::{IrGenerator, Options}; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; + +impl IrGenerator<'_> { + pub(super) fn gen_control_flow(&self, node: &Node, options: &mut Options) -> Vec { + match node.nt { + NodeType::LogicalAnd | NodeType::LogicalOr => { + let mut lines = vec![]; + let predicate = self.gen_predicate(node.lhs.as_ref().unwrap(), options, &mut lines); + let slot = options.expression_slots[&node.token.as_ref().unwrap().pos]; + let rhs_label = options.new_label(); + let short_label = options.new_label(); + let end_label = options.new_label(); + let is_and = matches!(node.nt, NodeType::LogicalAnd); + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, + if is_and { &rhs_label } else { &short_label }, + if is_and { &short_label } else { &rhs_label } + )); + lines.push(format!("{}:", short_label)); + lines.push(format!( + " store i32 {}, ptr %{}, align 4", + if is_and { 0 } else { 1 }, + slot + )); + lines.push(format!(" br label %{}", end_label)); + lines.push(format!("{}:", rhs_label)); + let predicate = self.gen_predicate(node.rhs.as_ref().unwrap(), options, &mut lines); + let value = options.new_temporary(); + lines.push(format!(" %{} = zext i1 {} to i32", value, predicate)); + lines.push(format!(" store i32 %{}, ptr %{}, align 4", value, slot)); + lines.push(format!(" br label %{}", end_label)); + lines.push(format!("{}:", end_label)); + lines.push(format!( + " %{} = load i32, ptr %{}, align 4", + options.new_register(), + slot + )); + lines + } + NodeType::Conditional => { + if node.resolve_type_view().as_deref() == Some(&Type::Void) { + let mut lines = vec![]; + let predicate = + self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); + let then_label = options.new_label(); + let else_label = options.new_label(); + let end_label = options.new_label(); + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, then_label, else_label + )); + for (label, branch) in [ + (&then_label, node.then.as_ref().unwrap()), + (&else_label, node.els.as_ref().unwrap()), + ] { + lines.push(format!("{}:", label)); + lines.extend(self.gen_node(branch, options)); + options.register_queue.pop(); + lines.push(format!(" br label %{}", end_label)); + } + lines.push(format!("{}:", end_label)); + options.register_queue.push("0".to_string()); + return lines; + } + + let mut lines = vec![]; + let ty = node.resolve_type_view().unwrap(); + let slot = options.expression_slots[&node.token.as_ref().unwrap().pos]; + let predicate = + self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); + let then_label = options.new_label(); + let else_label = options.new_label(); + let end_label = options.new_label(); + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, then_label, else_label + )); + for (label, branch) in [ + (&then_label, node.then.as_ref().unwrap()), + (&else_label, node.els.as_ref().unwrap()), + ] { + lines.push(format!("{}:", label)); + lines.extend(self.gen_node(branch, options)); + let value = options.register_queue.pop().unwrap(); + let value = Self::convert_integer( + value, + &branch.resolve_type_view().unwrap(), + &ty, + options, + &mut lines, + ); + lines.push(format!( + " store {} {}, ptr %{}, align {}", + Self::gen_type(&ty), + value, + slot, + Self::align(&ty) + )); + lines.push(format!(" br label %{}", end_label)); + } + lines.push(format!("{}:", end_label)); + lines.push(format!( + " %{} = load {}, ptr %{}, align {}", + options.new_register(), + Self::gen_type(&ty), + slot, + Self::align(&ty) + )); + lines + } + NodeType::Block => node + .children + .iter() + .flat_map(|node| self.gen_node(node, options)) + .collect(), + NodeType::Return => { + if matches!(options.return_ty, Type::Struct(_)) { + return self.aggregate_return(node, options); + } + if options.return_ty == Type::Void { + let mut lines = if let Some(operand) = &node.lhs { + self.gen_node(operand, options) + } else { + vec![] + }; + if node.lhs.is_some() { + options.register_queue.pop(); + } + lines.push(" ret void".to_string()); + options.terminated = true; + return lines; + } + if node.lhs.is_none() { + options.terminated = true; + return vec![" ret void".to_string()]; + } + let mut lines = self.gen_node(node.lhs.as_ref().unwrap(), options); + let value = options.register_queue.pop().unwrap(); + let source_ty = node.resolve_type_view().unwrap(); + let target_ty = options.return_ty.clone(); + let value = + Self::convert_integer(value, &source_ty, &target_ty, options, &mut lines); + lines.push(format!( + " ret {} {}", + Self::gen_type_with_opaque_ptr(&target_ty), + value + )); + options.terminated = true; + lines + } + NodeType::If => { + let mut lines = vec![]; + let predicate = + self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); + let then_label = options.new_label(); + let else_label = options.new_label(); + let end_label = options.new_label(); + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, then_label, else_label, + )); + + lines.push(format!("{}:", then_label)); + options.terminated = false; + lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); + let then_terminated = options.terminated; + if !then_terminated { + lines.push(format!(" br label %{}", end_label)); + } + + lines.push(format!("{}:", else_label)); + options.terminated = false; + if let Some(els) = &node.els { + lines.extend(self.gen_node(els, options)); + } + let else_terminated = options.terminated; + if !else_terminated { + lines.push(format!(" br label %{}", end_label)); + } + + options.terminated = then_terminated && else_terminated; + if !options.terminated { + lines.push(format!("{}:", end_label)); + } + lines + } + NodeType::While | NodeType::For => { + let mut lines = vec![]; + if let Some(initializer) = &node.ini { + lines.extend(self.gen_node(initializer, options)); + } + let condition_label = options.new_label(); + let body_label = options.new_label(); + let update_label = format!("continue.{}", node.token.as_ref().unwrap().pos); + let end_label = options.new_label(); + lines.push(format!(" br label %{}", condition_label)); + lines.push(format!("{}:", condition_label)); + let predicate = if let Some(condition) = &node.cond { + self.gen_predicate(condition, options, &mut lines) + } else { + "true".to_string() + }; + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, body_label, end_label + )); + lines.push(format!("{}:", body_label)); + options.break_labels.push(end_label.clone()); + lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); + options.break_labels.pop(); + if !options.terminated { + lines.push(format!(" br label %{}", update_label)); + } + options.terminated = false; + lines.push(format!("{}:", update_label)); + if let Some(update) = &node.upd { + lines.extend(self.gen_node(update, options)); + } + lines.push(format!(" br label %{}", condition_label)); + lines.push(format!("{}:", end_label)); + lines + } + NodeType::DoWhile => { + let body_label = options.new_label(); + let condition_label = format!("continue.{}", node.token.as_ref().unwrap().pos); + let end_label = options.new_label(); + let mut lines = vec![ + format!(" br label %{}", body_label), + format!("{}:", body_label), + ]; + options.break_labels.push(end_label.clone()); + lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); + options.break_labels.pop(); + if !options.terminated { + lines.push(format!(" br label %{}", condition_label)); + } + options.terminated = false; + lines.push(format!("{}:", condition_label)); + let predicate = + self.gen_predicate(node.cond.as_ref().unwrap(), options, &mut lines); + lines.push(format!( + " br i1 {}, label %{}, label %{}", + predicate, body_label, end_label + )); + lines.push(format!("{}:", end_label)); + lines + } + NodeType::Switch => { + let mut lines = self.gen_node(node.cond.as_ref().unwrap(), options); + let value = options.register_queue.pop().unwrap(); + let selector_ty = node + .cond + .as_ref() + .unwrap() + .resolve_type_view() + .unwrap() + .promoted(); + let value = Self::convert_integer( + value, + &node.cond.as_ref().unwrap().resolve_type_view().unwrap(), + &selector_ty, + options, + &mut lines, + ); + let end = options.new_label(); + let default = node + .children + .iter() + .find(|case| case.value.is_none()) + .map(|case| format!("case.{}", case.token.as_ref().unwrap().pos)) + .unwrap_or(end.clone()); + lines.push(format!( + " switch {} {}, label %{} [", + Self::gen_type(&selector_ty), + value, + default + )); + for case in &node.children { + if let Some(value) = case.value { + lines.push(format!( + " {} {}, label %case.{}", + Self::gen_type(&selector_ty), + value as i64, + case.token.as_ref().unwrap().pos + )); + } + } + lines.push(" ]".to_string()); + options.terminated = true; + options.break_labels.push(end.clone()); + lines.extend(self.gen_node(node.then.as_ref().unwrap(), options)); + options.break_labels.pop(); + if !options.terminated { + lines.push(format!(" br label %{}", end)); + } + lines.push(format!("{}:", end)); + options.terminated = false; + lines + } + NodeType::Case => { + let label = format!("case.{}", node.token.as_ref().unwrap().pos); + let mut lines = vec![]; + if !options.terminated { + lines.push(format!(" br label %{}", label)); + } + lines.push(format!("{}:", label)); + options.terminated = false; + lines.extend(self.gen_node(node.lhs.as_ref().unwrap(), options)); + lines + } + NodeType::Break => { + let Some(label) = options.break_labels.last() else { + self.error_logger.print_error_position( + node.token.as_ref().unwrap().pos, + "unexpected break found", + ); + unreachable!() + }; + options.terminated = true; + vec![format!(" br label %{}", label)] + } + NodeType::Continue => { + options.terminated = true; + vec![format!(" br label %continue.{}", node.value.unwrap())] + } + NodeType::Goto => { + options.terminated = true; + vec![format!(" br label %goto.{}", node.value.unwrap())] + } + NodeType::Label => { + let label = format!("goto.{}", node.value.unwrap()); + let mut lines = vec![]; + if !options.terminated { + lines.push(format!(" br label %{label}")); + } + lines.push(format!("{label}:")); + options.terminated = false; + lines.extend(self.gen_node(node.lhs.as_ref().unwrap(), options)); + lines + } + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/generator/x86_64/generator.rs b/src/generator/x86_64/generator.rs index e5f8285..d5e78e3 100644 --- a/src/generator/x86_64/generator.rs +++ b/src/generator/x86_64/generator.rs @@ -1,5 +1,7 @@ mod aggregate; mod atomic; +mod calls; +mod control_flow; mod globals; mod inline_asm; @@ -670,83 +672,23 @@ impl<'a> AsmGenerator<'a> { ] .into(); } - NodeType::LogicalAnd => { - let branch_num = node.token.as_ref().unwrap().pos; - return vec![ - self.gen_node(node.lhs.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JE, EndFlag(branch_num)), - self.gen_node(node.rhs.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - format!("{}:", EndFlag(branch_num)).into(), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(SETNE, AL), - Assembly::inst2(MOVZX, RAX, AL), - Assembly::inst1(PUSH, RAX), - ] - .into(); - } - NodeType::LogicalOr => { - let branch_num = node.token.as_ref().unwrap().pos; - return vec![ - self.gen_node(node.lhs.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JNE, EndFlag(branch_num)), - self.gen_node(node.rhs.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - format!("{}:", EndFlag(branch_num)).into(), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(SETNE, AL), - Assembly::inst2(MOVZX, RAX, AL), - Assembly::inst1(PUSH, RAX), - ] - .into(); - } - NodeType::Conditional | NodeType::If => { - let branch_num = node.token.as_ref().unwrap().pos; - let branch = |child: &Node| { - if node.nt == NodeType::If { - self.gen_statements( - std::slice::from_ref(child), - offset, - breakable_branch_num, - ) - } else { - self.gen_node(child, offset, breakable_branch_num) - } - }; - return vec![ - self.gen_node(node.cond.as_ref().unwrap(), offset, breakable_branch_num), - Assembly::inst1(POP, RAX), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JE, ElseFlag(branch_num)), - branch(node.then.as_deref().unwrap()), - Assembly::inst1(JMP, EndFlag(branch_num)), - format!("{}:", ElseFlag(branch_num)).into(), - node.els - .as_deref() - .map(branch) - .unwrap_or_else(|| vec![].into()), - format!("{}:", EndFlag(branch_num)).into(), - if matches!(node.nt, NodeType::Conditional) - && node - .resolve_type() - .is_some_and(|ty| ty.integer_info().is_some()) - { - vec![ - Assembly::inst1(POP, RAX), - Self::normalize_integer(&node.resolve_type().unwrap(), RAX), - Assembly::inst1(PUSH, RAX), - ] - .into() - } else { - vec![].into() - }, - ] - .into(); + NodeType::LogicalAnd + | NodeType::LogicalOr + | NodeType::Conditional + | NodeType::If + | NodeType::Block + | NodeType::Return + | NodeType::While + | NodeType::DoWhile + | NodeType::For + | NodeType::Switch + | NodeType::Case + | NodeType::Continue + | NodeType::Goto + | NodeType::Label => { + return self.gen_control_flow(node, offset, breakable_branch_num); } + NodeType::Assign => { return vec![ self.gen_addr(node.lhs.as_ref().unwrap(), offset, breakable_branch_num), @@ -795,77 +737,8 @@ impl<'a> AsmGenerator<'a> { ] .into(); } - NodeType::CallFunc => { - if matches!(node.resolve_type(), Some(Type::Struct(_))) - || node - .args - .iter() - .any(|arg| matches!(arg.resolve_type(), Some(Type::Struct(_)))) - { - return self.aggregate_call(node, offset, breakable_branch_num); - } - if node.resolve_type().unwrap().float_bits().is_some() - || node - .args - .iter() - .any(|arg| arg.resolve_type().unwrap().float_bits().is_some()) - { - return self.float_call(node, offset, breakable_branch_num); - } - let stack_size = node.args.len().saturating_sub(ARGS_REG.len()) * 8; - return vec![ - node.lhs - .as_ref() - .map(|callee| self.gen_node(callee, offset, breakable_branch_num)) - .unwrap_or_else(|| vec![].into()), - Assembly::inst2(MOV, RAX, RSP), - Assembly::inst2(ADD, RAX, 8), - Assembly::inst2(SUB, RAX, node.args.len().saturating_sub(ARGS_REG.len()) * 8), - Assembly::inst2(MOV, RDI, 16), - Assembly::inst0(CQO), - Assembly::inst1(IDIV, RDI), - Assembly::inst2(SUB, RSP, RDX), - Assembly::inst1(PUSH, RDX), - node.args - .iter() - .map(|node| self.gen_node(node, offset, breakable_branch_num)) - .collect::>() - .into(), - ARGS_REG - .iter() - .take(node.args.len()) - .map(|op| Assembly::inst1(POP, *op)) - .collect::>() - .into(), - Assembly::inst2(MOV, RAX, 0), - if node.lhs.is_some() { - vec![ - // The saved callee sits above the alignment padding. - Assembly::inst2(MOV, R10, PtrAdd(RSP, format!("{stack_size}"))), - Assembly::inst2(ADD, R10, stack_size + 8), - Assembly::inst2(ADD, R10, RSP), - Assembly::inst2(MOV, R10, Ptr(R10, 8)), - Assembly::inst1(CALL, R10), - ] - .into() - } else { - Assembly::inst1(CALL, self.with_prefix(&node.global_name)) - }, - Assembly::inst2(ADD, RSP, node.args.len().saturating_sub(ARGS_REG.len()) * 8), - Assembly::inst1(POP, RDI), - Assembly::inst2(ADD, RSP, RDI), - if node.lhs.is_some() { - Assembly::inst2(ADD, RSP, 8) - } else { - vec![].into() - }, - node.cty - .as_ref() - .map(|ty| Self::normalize_integer(ty, RAX)) - .unwrap_or_else(|| vec![].into()), - Assembly::inst1(PUSH, RAX), - ] - .into(); + NodeType::CallFunc | NodeType::VaStart | NodeType::VaEnd => { + return self.gen_calls(node, offset, breakable_branch_num); } NodeType::Sequence => { let mut lines = vec![]; @@ -882,138 +755,7 @@ impl<'a> AsmGenerator<'a> { NodeType::DefVar => { return self.gen_statements(&node.children, offset, breakable_branch_num); } - NodeType::Block => { - return self.gen_statements(&node.children, offset, breakable_branch_num); - } - NodeType::Return => { - if matches!(node.resolve_type(), Some(Type::Struct(_))) { - return self.aggregate_return(node, offset, breakable_branch_num); - } - if node.lhs.is_none() { - return Assembly::epilogue(); - } - return vec![ - self.gen_node(node.lhs.as_ref().unwrap(), offset, breakable_branch_num), - Assembly::inst1(POP, RAX), - if let Some(bits) = node.resolve_type().and_then(|ty| ty.float_bits()) { - Assembly::inst2( - if bits == 32 { MOVD } else { MOVQ }, - Xmm(0), - if bits == 32 { EAX } else { RAX }, - ) - } else { - vec![].into() - }, - Assembly::epilogue(), - ] - .into(); - } - NodeType::While => { - let branch_num = node.token.as_ref().unwrap().pos; - let v = vec![ - format!(".Lcontinue.{}:", branch_num).into(), - format!("{}:", BeginFlag(branch_num)).into(), - self.gen_node(node.cond.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JE, EndFlag(branch_num)), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - offset, - branch_num, - ), - Assembly::inst1(JMP, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ]; - return v.into(); - } - NodeType::DoWhile => { - let branch_num = node.token.as_ref().unwrap().pos; - return vec![ - format!("{}:", BeginFlag(branch_num)).into(), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - offset, - branch_num, - ), - format!(".Lcontinue.{}:", branch_num).into(), - self.gen_node(node.cond.as_ref().unwrap(), offset, branch_num), - Assembly::inst1(POP, RAX), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JNE, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ] - .into(); - } - NodeType::For => { - let branch_num = node.token.as_ref().unwrap().pos; - let v = vec![ - node.ini.as_ref().map_or(Vec::new().into(), |node| { - self.gen_statements(std::slice::from_ref(node.as_ref()), offset, branch_num) - }), - format!("{}:", BeginFlag(branch_num)).into(), - node.cond - .as_ref() - .map_or(Assembly::inst2(MOV, RAX, 1), |node| { - vec![ - self.gen_node(node, offset, branch_num), - Assembly::inst1(POP, RAX), - ] - .into() - }), - Assembly::inst2(CMP, RAX, 0), - Assembly::inst1(JE, EndFlag(branch_num)), - self.gen_statements( - std::slice::from_ref(node.then.as_deref().unwrap()), - offset, - branch_num, - ), - format!(".Lcontinue.{}:", branch_num).into(), - node.upd.as_ref().map_or(Vec::new().into(), |node| { - vec![ - self.gen_node(node, offset, branch_num), - Assembly::inst1(POP, RAX), - ] - .into() - }), - Assembly::inst1(JMP, BeginFlag(branch_num)), - format!("{}:", EndFlag(branch_num)).into(), - ]; - return v.into(); - } - NodeType::Switch => { - let branch_num = node.token.as_ref().unwrap().pos; - let mut lines = vec![ - self.gen_node(node.cond.as_ref().unwrap(), offset, breakable_branch_num), - Assembly::inst1(POP, RAX), - ]; - let mut default = format!("{}", EndFlag(branch_num)); - for case in &node.children { - let label = format!(".Lcase.{}", case.token.as_ref().unwrap().pos); - if let Some(value) = case.value { - lines.push(Assembly::inst2(MOV, RDI, value)); - lines.push(Assembly::inst2(CMP, RAX, RDI)); - lines.push(Assembly::inst1(JE, label)); - } else { - default = label; - } - } - lines.push(Assembly::inst1(JMP, default)); - lines.push(self.gen_node(node.then.as_ref().unwrap(), offset, branch_num)); - lines.push(format!("{}:", EndFlag(branch_num)).into()); - return lines.into(); - } - NodeType::Case => { - return vec![ - format!(".Lcase.{}:", node.token.as_ref().unwrap().pos).into(), - self.gen_statements( - std::slice::from_ref(node.lhs.as_deref().unwrap()), - offset, - breakable_branch_num, - ), - ] - .into(); - } + NodeType::Break => { if breakable_branch_num != 0 { return Assembly::inst1(JMP, EndFlag(breakable_branch_num)); @@ -1024,23 +766,6 @@ impl<'a> AsmGenerator<'a> { ); } } - NodeType::Continue => { - return Assembly::inst1(JMP, format!(".Lcontinue.{}", node.value.unwrap())); - } - NodeType::Goto => { - return Assembly::inst1(JMP, format!(".Lgoto.{}", node.value.unwrap())); - } - NodeType::Label => { - return vec![ - format!(".Lgoto.{}:", node.value.unwrap()).into(), - self.gen_statements( - std::slice::from_ref(node.lhs.as_deref().unwrap()), - offset, - breakable_branch_num, - ), - ] - .into(); - } NodeType::FloatAbs => { let shift = 65 - node.resolve_type().unwrap().float_bits().unwrap() as usize; return vec![ @@ -1081,32 +806,7 @@ impl<'a> AsmGenerator<'a> { lines.push(Assembly::inst1(PUSH, RAX)); return lines.into(); } - NodeType::VaStart | NodeType::VaEnd => { - let mut lines = vec![ - self.gen_node(node.lhs.as_ref().unwrap(), offset, breakable_branch_num), - Assembly::inst1(POP, R11), - ]; - if node.nt == NodeType::VaStart { - let (gp, fp, stack) = crate::generator::abi::variadic_state( - node, - crate::generator::Arch::X86_64, - self.target_os, - ); - lines.extend([ - Assembly::inst2(MOV, EAX, gp * 8), - Assembly::inst2(MOV, PtrOffset(R11, 0, 4), EAX), - Assembly::inst2(MOV, EAX, 48 + fp * 16), - Assembly::inst2(MOV, PtrOffset(R11, 4, 4), EAX), - Assembly::inst2(LEA, RAX, PtrOffset(RBP, 16 + stack, 8)), - Assembly::inst2(MOV, PtrOffset(R11, 8, 8), RAX), - Assembly::inst2(MOV, RAX, RBP), - Assembly::inst2(SUB, RAX, offset), - Assembly::inst2(MOV, PtrOffset(R11, 16, 8), RAX), - ]); - } - lines.push(Assembly::inst1(PUSH, 0)); - return lines.into(); - } + NodeType::Prefetch(_, locality) => { return self.gen_prefetch(node, locality, offset, breakable_branch_num); } diff --git a/src/generator/x86_64/generator/calls.rs b/src/generator/x86_64/generator/calls.rs new file mode 100644 index 0000000..7ebe378 --- /dev/null +++ b/src/generator/x86_64/generator/calls.rs @@ -0,0 +1,118 @@ +use super::super::assembly::Assembly; +use super::super::instruction::{InstOperand::*, InstOperator::*, Register::*}; +use super::{ARGS_REG, AsmGenerator}; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; + +impl AsmGenerator<'_> { + pub(super) fn gen_calls( + &self, + node: &Node, + offset: usize, + breakable_branch_num: usize, + ) -> Assembly { + match node.nt { + NodeType::CallFunc => { + if matches!(node.resolve_type(), Some(Type::Struct(_))) + || node + .args + .iter() + .any(|arg| matches!(arg.resolve_type(), Some(Type::Struct(_)))) + { + return self.aggregate_call(node, offset, breakable_branch_num); + } + if node.resolve_type().unwrap().float_bits().is_some() + || node + .args + .iter() + .any(|arg| arg.resolve_type().unwrap().float_bits().is_some()) + { + return self.float_call(node, offset, breakable_branch_num); + } + let stack_size = node.args.len().saturating_sub(ARGS_REG.len()) * 8; + vec![ + node.lhs + .as_ref() + .map(|callee| self.gen_node(callee, offset, breakable_branch_num)) + .unwrap_or_else(|| vec![].into()), + Assembly::inst2(MOV, RAX, RSP), + Assembly::inst2(ADD, RAX, 8), + Assembly::inst2(SUB, RAX, node.args.len().saturating_sub(ARGS_REG.len()) * 8), + Assembly::inst2(MOV, RDI, 16), + Assembly::inst0(CQO), + Assembly::inst1(IDIV, RDI), + Assembly::inst2(SUB, RSP, RDX), + Assembly::inst1(PUSH, RDX), + node.args + .iter() + .map(|node| self.gen_node(node, offset, breakable_branch_num)) + .collect::>() + .into(), + ARGS_REG + .iter() + .take(node.args.len()) + .map(|op| Assembly::inst1(POP, *op)) + .collect::>() + .into(), + Assembly::inst2(MOV, RAX, 0), + if node.lhs.is_some() { + vec![ + // The saved callee sits above the alignment padding. + Assembly::inst2(MOV, R10, PtrAdd(RSP, format!("{stack_size}"))), + Assembly::inst2(ADD, R10, stack_size + 8), + Assembly::inst2(ADD, R10, RSP), + Assembly::inst2(MOV, R10, Ptr(R10, 8)), + Assembly::inst1(CALL, R10), + ] + .into() + } else { + Assembly::inst1(CALL, self.with_prefix(&node.global_name)) + }, + Assembly::inst2(ADD, RSP, node.args.len().saturating_sub(ARGS_REG.len()) * 8), + Assembly::inst1(POP, RDI), + Assembly::inst2(ADD, RSP, RDI), + if node.lhs.is_some() { + Assembly::inst2(ADD, RSP, 8) + } else { + vec![].into() + }, + node.cty + .as_ref() + .map(|ty| Self::normalize_integer(ty, RAX)) + .unwrap_or_else(|| vec![].into()), + Assembly::inst1(PUSH, RAX), + ] + .into() + } + NodeType::VaStart | NodeType::VaEnd => { + let mut lines = vec![ + self.gen_node(node.lhs.as_ref().unwrap(), offset, breakable_branch_num), + Assembly::inst1(POP, R11), + ]; + if node.nt == NodeType::VaStart { + let (gp, fp, stack) = crate::generator::abi::variadic_state( + node, + crate::generator::Arch::X86_64, + self.target_os, + ); + lines.extend([ + Assembly::inst2(MOV, EAX, gp * 8), + Assembly::inst2(MOV, PtrOffset(R11, 0, 4), EAX), + Assembly::inst2(MOV, EAX, 48 + fp * 16), + Assembly::inst2(MOV, PtrOffset(R11, 4, 4), EAX), + Assembly::inst2(LEA, RAX, PtrOffset(RBP, 16 + stack, 8)), + Assembly::inst2(MOV, PtrOffset(R11, 8, 8), RAX), + Assembly::inst2(MOV, RAX, RBP), + Assembly::inst2(SUB, RAX, offset), + Assembly::inst2(MOV, PtrOffset(R11, 16, 8), RAX), + ]); + } + lines.push(Assembly::inst1(PUSH, 0)); + lines.into() + } + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/generator/x86_64/generator/control_flow.rs b/src/generator/x86_64/generator/control_flow.rs new file mode 100644 index 0000000..97d577a --- /dev/null +++ b/src/generator/x86_64/generator/control_flow.rs @@ -0,0 +1,238 @@ +use super::super::assembly::Assembly; +use super::super::instruction::{InstOperand::*, InstOperator::*, Register::*}; +use super::AsmGenerator; +use crate::{ + ctype::Type, + node::{Node, NodeType}, +}; + +impl AsmGenerator<'_> { + pub(super) fn gen_control_flow( + &self, + node: &Node, + offset: usize, + breakable_branch_num: usize, + ) -> Assembly { + match node.nt { + NodeType::LogicalAnd => { + let branch_num = node.token.as_ref().unwrap().pos; + vec![ + self.gen_node(node.lhs.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JE, EndFlag(branch_num)), + self.gen_node(node.rhs.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + format!("{}:", EndFlag(branch_num)).into(), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(SETNE, AL), + Assembly::inst2(MOVZX, RAX, AL), + Assembly::inst1(PUSH, RAX), + ] + .into() + } + NodeType::LogicalOr => { + let branch_num = node.token.as_ref().unwrap().pos; + vec![ + self.gen_node(node.lhs.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JNE, EndFlag(branch_num)), + self.gen_node(node.rhs.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + format!("{}:", EndFlag(branch_num)).into(), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(SETNE, AL), + Assembly::inst2(MOVZX, RAX, AL), + Assembly::inst1(PUSH, RAX), + ] + .into() + } + NodeType::Conditional | NodeType::If => { + let branch_num = node.token.as_ref().unwrap().pos; + let branch = |child: &Node| { + if node.nt == NodeType::If { + self.gen_statements( + std::slice::from_ref(child), + offset, + breakable_branch_num, + ) + } else { + self.gen_node(child, offset, breakable_branch_num) + } + }; + vec![ + self.gen_node(node.cond.as_ref().unwrap(), offset, breakable_branch_num), + Assembly::inst1(POP, RAX), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JE, ElseFlag(branch_num)), + branch(node.then.as_deref().unwrap()), + Assembly::inst1(JMP, EndFlag(branch_num)), + format!("{}:", ElseFlag(branch_num)).into(), + node.els + .as_deref() + .map(branch) + .unwrap_or_else(|| vec![].into()), + format!("{}:", EndFlag(branch_num)).into(), + if matches!(node.nt, NodeType::Conditional) + && node + .resolve_type() + .is_some_and(|ty| ty.integer_info().is_some()) + { + vec![ + Assembly::inst1(POP, RAX), + Self::normalize_integer(&node.resolve_type().unwrap(), RAX), + Assembly::inst1(PUSH, RAX), + ] + .into() + } else { + vec![].into() + }, + ] + .into() + } + NodeType::Block => self.gen_statements(&node.children, offset, breakable_branch_num), + NodeType::Return => { + if matches!(node.resolve_type(), Some(Type::Struct(_))) { + return self.aggregate_return(node, offset, breakable_branch_num); + } + if node.lhs.is_none() { + return Assembly::epilogue(); + } + vec![ + self.gen_node(node.lhs.as_ref().unwrap(), offset, breakable_branch_num), + Assembly::inst1(POP, RAX), + if let Some(bits) = node.resolve_type().and_then(|ty| ty.float_bits()) { + Assembly::inst2( + if bits == 32 { MOVD } else { MOVQ }, + Xmm(0), + if bits == 32 { EAX } else { RAX }, + ) + } else { + vec![].into() + }, + Assembly::epilogue(), + ] + .into() + } + NodeType::While => { + let branch_num = node.token.as_ref().unwrap().pos; + let v = vec![ + format!(".Lcontinue.{}:", branch_num).into(), + format!("{}:", BeginFlag(branch_num)).into(), + self.gen_node(node.cond.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JE, EndFlag(branch_num)), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + offset, + branch_num, + ), + Assembly::inst1(JMP, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ]; + v.into() + } + NodeType::DoWhile => { + let branch_num = node.token.as_ref().unwrap().pos; + vec![ + format!("{}:", BeginFlag(branch_num)).into(), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + offset, + branch_num, + ), + format!(".Lcontinue.{}:", branch_num).into(), + self.gen_node(node.cond.as_ref().unwrap(), offset, branch_num), + Assembly::inst1(POP, RAX), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JNE, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ] + .into() + } + NodeType::For => { + let branch_num = node.token.as_ref().unwrap().pos; + let v = vec![ + node.ini.as_ref().map_or(Vec::new().into(), |node| { + self.gen_statements(std::slice::from_ref(node.as_ref()), offset, branch_num) + }), + format!("{}:", BeginFlag(branch_num)).into(), + node.cond + .as_ref() + .map_or(Assembly::inst2(MOV, RAX, 1), |node| { + vec![ + self.gen_node(node, offset, branch_num), + Assembly::inst1(POP, RAX), + ] + .into() + }), + Assembly::inst2(CMP, RAX, 0), + Assembly::inst1(JE, EndFlag(branch_num)), + self.gen_statements( + std::slice::from_ref(node.then.as_deref().unwrap()), + offset, + branch_num, + ), + format!(".Lcontinue.{}:", branch_num).into(), + node.upd.as_ref().map_or(Vec::new().into(), |node| { + vec![ + self.gen_node(node, offset, branch_num), + Assembly::inst1(POP, RAX), + ] + .into() + }), + Assembly::inst1(JMP, BeginFlag(branch_num)), + format!("{}:", EndFlag(branch_num)).into(), + ]; + v.into() + } + NodeType::Switch => { + let branch_num = node.token.as_ref().unwrap().pos; + let mut lines = vec![ + self.gen_node(node.cond.as_ref().unwrap(), offset, breakable_branch_num), + Assembly::inst1(POP, RAX), + ]; + let mut default = format!("{}", EndFlag(branch_num)); + for case in &node.children { + let label = format!(".Lcase.{}", case.token.as_ref().unwrap().pos); + if let Some(value) = case.value { + lines.push(Assembly::inst2(MOV, RDI, value)); + lines.push(Assembly::inst2(CMP, RAX, RDI)); + lines.push(Assembly::inst1(JE, label)); + } else { + default = label; + } + } + lines.push(Assembly::inst1(JMP, default)); + lines.push(self.gen_node(node.then.as_ref().unwrap(), offset, branch_num)); + lines.push(format!("{}:", EndFlag(branch_num)).into()); + lines.into() + } + NodeType::Case => vec![ + format!(".Lcase.{}:", node.token.as_ref().unwrap().pos).into(), + self.gen_statements( + std::slice::from_ref(node.lhs.as_deref().unwrap()), + offset, + breakable_branch_num, + ), + ] + .into(), + NodeType::Continue => { + Assembly::inst1(JMP, format!(".Lcontinue.{}", node.value.unwrap())) + } + NodeType::Goto => Assembly::inst1(JMP, format!(".Lgoto.{}", node.value.unwrap())), + NodeType::Label => vec![ + format!(".Lgoto.{}:", node.value.unwrap()).into(), + self.gen_statements( + std::slice::from_ref(node.lhs.as_deref().unwrap()), + offset, + breakable_branch_num, + ), + ] + .into(), + _ => unreachable!("node dispatched to the wrong generator"), + } + } +} diff --git a/src/node.rs b/src/node.rs index e90419b..754d4b3 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,8 +1,11 @@ +mod debug; +mod effects; +mod types; +mod walk; + use crate::ctype::{BitField, Type}; use crate::token::Token; -use std::borrow::Cow; use std::mem::swap; -use std::rc::Rc; #[derive(Debug, PartialEq, Clone, Copy)] pub enum AtomicRmwOperation { @@ -161,73 +164,6 @@ pub struct Node { } impl Node { - /// Direct children in structural order, not source-language evaluation order. - pub(crate) fn child_nodes(&self) -> impl Iterator { - [ - &self.lhs, &self.rhs, &self.cond, &self.then, &self.els, &self.ini, &self.upd, - ] - .into_iter() - .filter_map(|child| child.as_deref()) - .chain(&self.children) - .chain(&self.args) - } - - pub(crate) fn child_nodes_mut(&mut self) -> impl Iterator { - [ - &mut self.lhs, - &mut self.rhs, - &mut self.cond, - &mut self.then, - &mut self.els, - &mut self.ini, - &mut self.upd, - ] - .into_iter() - .filter_map(|child| child.as_deref_mut()) - .chain(&mut self.children) - .chain(&mut self.args) - } - - /// Whether evaluating this expression can call, write, or read a volatile value. - pub(crate) fn has_side_effects(&self) -> bool { - Self::has_effects(self, true) - } - - fn has_effects(node: &Self, value: bool) -> bool { - if matches!( - node.nt, - NodeType::Assign - | NodeType::SuffixIncr - | NodeType::SuffixDecr - | NodeType::CallFunc - | NodeType::AddOverflow - | NodeType::SubOverflow - | NodeType::VaStart - | NodeType::VaEnd - | NodeType::Prefetch(..) - | NodeType::Atomic(_) - | NodeType::InlineAsm(_, _) - | NodeType::ZeroFill { .. } - | NodeType::CopyBytes { .. } - ) || (value - && (node.volatile_access - || node.object_type().is_some_and(|ty| { - ty.qualifiers().volatile - && !matches!(ty.unqualified(), Type::Arr(..) | Type::Vla(..)) - }))) - { - return true; - } - if node.nt == NodeType::Addr { - return node - .lhs - .as_deref() - .is_some_and(|child| Self::has_effects(child, false)); - } - node.child_nodes() - .any(|child| Self::has_effects(child, true)) - } - pub fn new_with_op(token: Option, nt: NodeType, lhs: Node, rhs: Node) -> Self { let (mut lhs, mut rhs) = (lhs, rhs); if let NodeType::Add = nt { @@ -256,63 +192,6 @@ impl Node { node } - /// Recompute an arithmetic result after changing its operands or their types. - /// Refresh children first when changing an existing expression tree. - pub fn refresh_arithmetic_type(&mut self) { - // Reuse cty so queries need neither a subtree walk nor a separate cache. - if matches!( - self.nt, - NodeType::Add - | NodeType::Sub - | NodeType::Mul - | NodeType::Div - | NodeType::Mod - | NodeType::BitLeft - | NodeType::BitRight - | NodeType::BitAnd - | NodeType::BitXor - | NodeType::BitOr - | NodeType::BitNot - ) { - self.cty = self - .infer_arithmetic_type_view() - .filter(|ty| ty.is_arithmetic()) - .map(Cow::into_owned); - } - } - - fn infer_arithmetic_type_view(&self) -> Option> { - let lhs = self.lhs.as_ref()?.resolve_type_view()?; - match self.nt { - NodeType::Add | NodeType::Sub => { - let rhs = self.rhs.as_ref()?; - if self.nt == NodeType::Sub && rhs.dest_type_view().is_some() { - Some(Cow::Owned(Type::I32)) - } else if lhs.dest_type_ref().is_some() { - Some(lhs) - } else { - Some(Cow::Owned(Type::arithmetic_type( - &lhs, - rhs.resolve_type_view()?.as_ref(), - ))) - } - } - NodeType::Mul - | NodeType::Div - | NodeType::Mod - | NodeType::BitAnd - | NodeType::BitXor - | NodeType::BitOr => Some(Cow::Owned(Type::arithmetic_type( - &lhs, - self.rhs.as_ref()?.resolve_type_view()?.as_ref(), - ))), - NodeType::BitLeft | NodeType::BitRight | NodeType::BitNot => { - Some(Cow::Owned(lhs.promoted())) - } - _ => None, - } - } - pub fn new_with_num(token: Option, value: usize) -> Self { Self { nt: NodeType::Num, @@ -357,312 +236,6 @@ impl Node { ..Self::default() } } - pub fn contains_case(&self) -> bool { - if matches!(self.nt, NodeType::Switch) { - return false; - } - if matches!(self.nt, NodeType::Case | NodeType::Label) { - return true; - } - self.children.iter().any(Self::contains_case) - || [ - &self.lhs, &self.rhs, &self.cond, &self.then, &self.els, &self.ini, &self.upd, - ] - .into_iter() - .flatten() - .any(|node| node.contains_case()) - } - - pub fn object_type(&self) -> Option { - self.object_type_view().map(Cow::into_owned) - } - pub(crate) fn object_type_view(&self) -> Option> { - match self.nt { - NodeType::LocalVar | NodeType::GlobalVar => self.cty.as_ref().map(Cow::Borrowed), - NodeType::Deref => self.lhs.as_ref()?.dest_type_view(), - NodeType::SuffixIncr | NodeType::SuffixDecr => self.lhs.as_ref()?.object_type_view(), - _ => self.resolve_type_view(), - } - } - pub(crate) fn is_volatile_object(&self) -> bool { - match self.nt { - NodeType::LocalVar | NodeType::GlobalVar => { - self.cty.as_ref().is_some_and(|ty| ty.qualifiers().volatile) - } - NodeType::Deref => self - .object_type_view() - .is_some_and(|ty| ty.qualifiers().volatile), - NodeType::SuffixIncr | NodeType::SuffixDecr => self - .lhs - .as_ref() - .is_some_and(|node| node.is_volatile_object()), - // Value expressions discard outer object qualifiers in resolve_type. - _ => false, - } - } - pub fn resolve_type(&self) -> Option { - self.resolve_type_view().map(Cow::into_owned) - } - /// Borrow stored expression types; own types constructed by value conversion. - pub(crate) fn resolve_type_view(&self) -> Option> { - if self.bit_field.is_some_and(|field| field.width < 32) { - return Some(Cow::Owned(Type::I32)); - } - self.resolve_qualified_type_view().map(|ty| { - if let Type::Qualified(child, _) = ty.as_ref() { - if let Type::Arr(element, size) = child.unqualified() { - return Cow::Owned(Type::Arr( - Rc::new(Type::Qualified(Rc::clone(element), ty.qualifiers())), - *size, - )); - } - if let Type::Vla(element, offset) = child.unqualified() { - return Cow::Owned(Type::Vla( - Rc::new(Type::Qualified(Rc::clone(element), ty.qualifiers())), - *offset, - )); - } - } - Type::unqualified_view(ty) - }) - } - pub(crate) fn resolve_qualified_type(&self) -> Option { - self.resolve_qualified_type_view().map(Cow::into_owned) - } - pub(crate) fn resolve_qualified_type_view(&self) -> Option> { - match self.nt { - NodeType::Num => Some( - self.cty - .as_ref() - .map_or(Cow::Owned(Type::I32), Cow::Borrowed), - ), - NodeType::LocalVar - | NodeType::GlobalVar - | NodeType::CallFunc - | NodeType::AddOverflow - | NodeType::SubOverflow - | NodeType::BitScan { .. } - | NodeType::VaStart - | NodeType::VaEnd - | NodeType::StackAlloc - | NodeType::Prefetch(..) - | NodeType::Atomic(_) - | NodeType::ZeroFill { .. } - | NodeType::CopyBytes { .. } => self.cty.as_ref().map(Cow::Borrowed), - NodeType::Addr => { - if let Some(ty) = self.lhs.as_ref().unwrap().object_type_view() { - Some(Cow::Owned(Type::Ptr(Rc::new(ty.into_owned())))) - } else { - self.cty.as_ref().map(Cow::Borrowed) - } - } - NodeType::Deref => self.lhs.as_ref().unwrap().dest_type_view(), - NodeType::Cast | NodeType::FloatAbs | NodeType::InlineAsm(_, _) => { - self.cty.as_ref().map(Cow::Borrowed) - } - NodeType::Add - | NodeType::Sub - | NodeType::Mul - | NodeType::Div - | NodeType::Mod - | NodeType::BitLeft - | NodeType::BitRight - | NodeType::BitAnd - | NodeType::BitXor - | NodeType::BitOr - | NodeType::BitNot => self - .cty - .as_ref() - .map(Cow::Borrowed) - .or_else(|| self.infer_arithmetic_type_view()), - NodeType::Eq - | NodeType::Ne - | NodeType::Lt - | NodeType::Le - | NodeType::LogicalAnd - | NodeType::LogicalOr => Some(Cow::Owned(Type::I32)), - NodeType::Conditional => { - let then = self - .then - .as_ref() - .unwrap() - .resolve_type_view() - .map(Type::decay_view); - let otherwise = self - .els - .as_ref() - .unwrap() - .resolve_type_view() - .map(Type::decay_view); - if then.as_ref().is_some_and(|ty| ty.is_arithmetic()) - && otherwise.as_ref().is_some_and(|ty| ty.is_arithmetic()) - { - Some(Cow::Owned(Type::arithmetic_type( - then.as_ref().unwrap(), - otherwise.as_ref().unwrap(), - ))) - } else if then.as_ref().is_some_and(|ty| matches!(**ty, Type::Ptr(_))) { - then - } else if otherwise - .as_ref() - .is_some_and(|ty| matches!(**ty, Type::Ptr(_))) - { - otherwise - } else { - then - } - } - NodeType::Sequence => self.children.last().and_then(Node::resolve_type_view), - _ => { - if let Some(node) = self.lhs.as_ref() { - if let Some(ty) = node.resolve_type_view() { - return Some(ty); - } - } - if let Some(node) = self.rhs.as_ref() { - if let Some(ty) = node.resolve_type_view() { - return Some(ty); - } - } - if let Some(node) = self.then.as_ref() { - if let Some(ty) = node.resolve_type_view() { - return Some(ty); - } - } - None - } - } - } - pub fn dest_type(&self) -> Option { - self.dest_type_view().map(Cow::into_owned) - } - pub(crate) fn dest_type_view(&self) -> Option> { - match Type::unqualified_view(self.resolve_type_view()?) { - Cow::Borrowed(ty) => ty.dest_type_ref().map(Cow::Borrowed), - Cow::Owned(Type::Ptr(child) | Type::Arr(child, _) | Type::Vla(child, _)) => { - Some(Cow::Owned(Rc::unwrap_or_clone(child))) - } - Cow::Owned(_) => None, - } - } - pub fn to_debug_string(&self, indent: usize) -> String { - match self.nt { - NodeType::Num => { - format!("Num: {}", self.value.unwrap()) - } - NodeType::LocalVar => { - format!( - "LocalVar: {{ type: {:?}, offset: {} }}", - self.cty.as_ref().unwrap(), - self.offset.unwrap() - ) - } - NodeType::GlobalVar => { - format!("GlobalVar: {{ name: {}{} }}", &self.global_name, &self.dest) - } - _ => [ - vec![format!("{:?}:", self.nt)], - self.ini - .iter() - .map(|c| { - format!( - "{}ini->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.cond - .iter() - .map(|c| { - format!( - "{}cond->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.upd - .iter() - .map(|c| { - format!( - "{}upd->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.then - .iter() - .map(|c| { - format!( - "{}then->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.els - .iter() - .map(|c| { - format!( - "{}els->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.lhs - .iter() - .map(|c| { - format!( - "{}lhs->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.rhs - .iter() - .map(|c| { - format!( - "{}rhs->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.children - .iter() - .map(|c| { - format!( - "{}children->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - self.args - .iter() - .map(|c| { - format!( - "{}args->{}", - " ".repeat(indent), - c.to_debug_string(indent + 2) - ) - }) - .collect::>(), - ] - .concat() - .join("\n"), - } - } -} - -impl std::fmt::Debug for Node { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.to_debug_string(2)) - } } /// Decode GNU numbered register operands, leaving target-specific modifiers to the backend. @@ -708,6 +281,7 @@ pub(crate) fn render_inline_assembly( mod tests { use super::*; use crate::ctype::Qualifiers; + use std::{borrow::Cow, rc::Rc}; fn object(ty: Type) -> Node { Node { diff --git a/src/node/debug.rs b/src/node/debug.rs new file mode 100644 index 0000000..c9acf05 --- /dev/null +++ b/src/node/debug.rs @@ -0,0 +1,122 @@ +use super::{Node, NodeType}; + +impl Node { + pub fn to_debug_string(&self, indent: usize) -> String { + match self.nt { + NodeType::Num => { + format!("Num: {}", self.value.unwrap()) + } + NodeType::LocalVar => { + format!( + "LocalVar: {{ type: {:?}, offset: {} }}", + self.cty.as_ref().unwrap(), + self.offset.unwrap() + ) + } + NodeType::GlobalVar => { + format!("GlobalVar: {{ name: {}{} }}", &self.global_name, &self.dest) + } + _ => [ + vec![format!("{:?}:", self.nt)], + self.ini + .iter() + .map(|c| { + format!( + "{}ini->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.cond + .iter() + .map(|c| { + format!( + "{}cond->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.upd + .iter() + .map(|c| { + format!( + "{}upd->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.then + .iter() + .map(|c| { + format!( + "{}then->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.els + .iter() + .map(|c| { + format!( + "{}els->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.lhs + .iter() + .map(|c| { + format!( + "{}lhs->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.rhs + .iter() + .map(|c| { + format!( + "{}rhs->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.children + .iter() + .map(|c| { + format!( + "{}children->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + self.args + .iter() + .map(|c| { + format!( + "{}args->{}", + " ".repeat(indent), + c.to_debug_string(indent + 2) + ) + }) + .collect::>(), + ] + .concat() + .join("\n"), + } + } +} + +impl std::fmt::Debug for Node { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.to_debug_string(2)) + } +} diff --git a/src/node/effects.rs b/src/node/effects.rs new file mode 100644 index 0000000..a70db07 --- /dev/null +++ b/src/node/effects.rs @@ -0,0 +1,44 @@ +use super::{Node, NodeType}; +use crate::ctype::Type; + +impl Node { + /// Whether evaluating this expression can call, write, or read a volatile value. + pub(crate) fn has_side_effects(&self) -> bool { + Self::has_effects(self, true) + } + + fn has_effects(node: &Self, value: bool) -> bool { + if matches!( + node.nt, + NodeType::Assign + | NodeType::SuffixIncr + | NodeType::SuffixDecr + | NodeType::CallFunc + | NodeType::AddOverflow + | NodeType::SubOverflow + | NodeType::VaStart + | NodeType::VaEnd + | NodeType::Prefetch(..) + | NodeType::Atomic(_) + | NodeType::InlineAsm(_, _) + | NodeType::ZeroFill { .. } + | NodeType::CopyBytes { .. } + ) || (value + && (node.volatile_access + || node.object_type().is_some_and(|ty| { + ty.qualifiers().volatile + && !matches!(ty.unqualified(), Type::Arr(..) | Type::Vla(..)) + }))) + { + return true; + } + if node.nt == NodeType::Addr { + return node + .lhs + .as_deref() + .is_some_and(|child| Self::has_effects(child, false)); + } + node.child_nodes() + .any(|child| Self::has_effects(child, true)) + } +} diff --git a/src/node/types.rs b/src/node/types.rs new file mode 100644 index 0000000..dbe86f2 --- /dev/null +++ b/src/node/types.rs @@ -0,0 +1,243 @@ +use super::{Node, NodeType}; +use crate::ctype::Type; +use std::{borrow::Cow, rc::Rc}; + +impl Node { + /// Recompute an arithmetic result after changing its operands or their types. + /// Refresh children first when changing an existing expression tree. + pub fn refresh_arithmetic_type(&mut self) { + // Reuse cty so queries need neither a subtree walk nor a separate cache. + if matches!( + self.nt, + NodeType::Add + | NodeType::Sub + | NodeType::Mul + | NodeType::Div + | NodeType::Mod + | NodeType::BitLeft + | NodeType::BitRight + | NodeType::BitAnd + | NodeType::BitXor + | NodeType::BitOr + | NodeType::BitNot + ) { + self.cty = self + .infer_arithmetic_type_view() + .filter(|ty| ty.is_arithmetic()) + .map(Cow::into_owned); + } + } + + fn infer_arithmetic_type_view(&self) -> Option> { + let lhs = self.lhs.as_ref()?.resolve_type_view()?; + match self.nt { + NodeType::Add | NodeType::Sub => { + let rhs = self.rhs.as_ref()?; + if self.nt == NodeType::Sub && rhs.dest_type_view().is_some() { + Some(Cow::Owned(Type::I32)) + } else if lhs.dest_type_ref().is_some() { + Some(lhs) + } else { + Some(Cow::Owned(Type::arithmetic_type( + &lhs, + rhs.resolve_type_view()?.as_ref(), + ))) + } + } + NodeType::Mul + | NodeType::Div + | NodeType::Mod + | NodeType::BitAnd + | NodeType::BitXor + | NodeType::BitOr => Some(Cow::Owned(Type::arithmetic_type( + &lhs, + self.rhs.as_ref()?.resolve_type_view()?.as_ref(), + ))), + NodeType::BitLeft | NodeType::BitRight | NodeType::BitNot => { + Some(Cow::Owned(lhs.promoted())) + } + _ => None, + } + } + + pub fn object_type(&self) -> Option { + self.object_type_view().map(Cow::into_owned) + } + + pub(crate) fn object_type_view(&self) -> Option> { + match self.nt { + NodeType::LocalVar | NodeType::GlobalVar => self.cty.as_ref().map(Cow::Borrowed), + NodeType::Deref => self.lhs.as_ref()?.dest_type_view(), + NodeType::SuffixIncr | NodeType::SuffixDecr => self.lhs.as_ref()?.object_type_view(), + _ => self.resolve_type_view(), + } + } + + pub(crate) fn is_volatile_object(&self) -> bool { + match self.nt { + NodeType::LocalVar | NodeType::GlobalVar => { + self.cty.as_ref().is_some_and(|ty| ty.qualifiers().volatile) + } + NodeType::Deref => self + .object_type_view() + .is_some_and(|ty| ty.qualifiers().volatile), + NodeType::SuffixIncr | NodeType::SuffixDecr => self + .lhs + .as_ref() + .is_some_and(|node| node.is_volatile_object()), + // Value expressions discard outer object qualifiers in resolve_type. + _ => false, + } + } + + pub fn resolve_type(&self) -> Option { + self.resolve_type_view().map(Cow::into_owned) + } + + /// Borrow stored expression types; own types constructed by value conversion. + pub(crate) fn resolve_type_view(&self) -> Option> { + if self.bit_field.is_some_and(|field| field.width < 32) { + return Some(Cow::Owned(Type::I32)); + } + self.resolve_qualified_type_view().map(|ty| { + if let Type::Qualified(child, _) = ty.as_ref() { + if let Type::Arr(element, size) = child.unqualified() { + return Cow::Owned(Type::Arr( + Rc::new(Type::Qualified(Rc::clone(element), ty.qualifiers())), + *size, + )); + } + if let Type::Vla(element, offset) = child.unqualified() { + return Cow::Owned(Type::Vla( + Rc::new(Type::Qualified(Rc::clone(element), ty.qualifiers())), + *offset, + )); + } + } + Type::unqualified_view(ty) + }) + } + + pub(crate) fn resolve_qualified_type(&self) -> Option { + self.resolve_qualified_type_view().map(Cow::into_owned) + } + + pub(crate) fn resolve_qualified_type_view(&self) -> Option> { + match self.nt { + NodeType::Num => Some( + self.cty + .as_ref() + .map_or(Cow::Owned(Type::I32), Cow::Borrowed), + ), + NodeType::LocalVar + | NodeType::GlobalVar + | NodeType::CallFunc + | NodeType::AddOverflow + | NodeType::SubOverflow + | NodeType::BitScan { .. } + | NodeType::VaStart + | NodeType::VaEnd + | NodeType::StackAlloc + | NodeType::Prefetch(..) + | NodeType::Atomic(_) + | NodeType::ZeroFill { .. } + | NodeType::CopyBytes { .. } => self.cty.as_ref().map(Cow::Borrowed), + NodeType::Addr => { + if let Some(ty) = self.lhs.as_ref().unwrap().object_type_view() { + Some(Cow::Owned(Type::Ptr(Rc::new(ty.into_owned())))) + } else { + self.cty.as_ref().map(Cow::Borrowed) + } + } + NodeType::Deref => self.lhs.as_ref().unwrap().dest_type_view(), + NodeType::Cast | NodeType::FloatAbs | NodeType::InlineAsm(_, _) => { + self.cty.as_ref().map(Cow::Borrowed) + } + NodeType::Add + | NodeType::Sub + | NodeType::Mul + | NodeType::Div + | NodeType::Mod + | NodeType::BitLeft + | NodeType::BitRight + | NodeType::BitAnd + | NodeType::BitXor + | NodeType::BitOr + | NodeType::BitNot => self + .cty + .as_ref() + .map(Cow::Borrowed) + .or_else(|| self.infer_arithmetic_type_view()), + NodeType::Eq + | NodeType::Ne + | NodeType::Lt + | NodeType::Le + | NodeType::LogicalAnd + | NodeType::LogicalOr => Some(Cow::Owned(Type::I32)), + NodeType::Conditional => { + let then = self + .then + .as_ref() + .unwrap() + .resolve_type_view() + .map(Type::decay_view); + let otherwise = self + .els + .as_ref() + .unwrap() + .resolve_type_view() + .map(Type::decay_view); + if then.as_ref().is_some_and(|ty| ty.is_arithmetic()) + && otherwise.as_ref().is_some_and(|ty| ty.is_arithmetic()) + { + Some(Cow::Owned(Type::arithmetic_type( + then.as_ref().unwrap(), + otherwise.as_ref().unwrap(), + ))) + } else if then.as_ref().is_some_and(|ty| matches!(**ty, Type::Ptr(_))) { + then + } else if otherwise + .as_ref() + .is_some_and(|ty| matches!(**ty, Type::Ptr(_))) + { + otherwise + } else { + then + } + } + NodeType::Sequence => self.children.last().and_then(Node::resolve_type_view), + _ => { + if let Some(node) = self.lhs.as_ref() { + if let Some(ty) = node.resolve_type_view() { + return Some(ty); + } + } + if let Some(node) = self.rhs.as_ref() { + if let Some(ty) = node.resolve_type_view() { + return Some(ty); + } + } + if let Some(node) = self.then.as_ref() { + if let Some(ty) = node.resolve_type_view() { + return Some(ty); + } + } + None + } + } + } + + pub fn dest_type(&self) -> Option { + self.dest_type_view().map(Cow::into_owned) + } + + pub(crate) fn dest_type_view(&self) -> Option> { + match Type::unqualified_view(self.resolve_type_view()?) { + Cow::Borrowed(ty) => ty.dest_type_ref().map(Cow::Borrowed), + Cow::Owned(Type::Ptr(child) | Type::Arr(child, _) | Type::Vla(child, _)) => { + Some(Cow::Owned(Rc::unwrap_or_clone(child))) + } + Cow::Owned(_) => None, + } + } +} diff --git a/src/node/walk.rs b/src/node/walk.rs new file mode 100644 index 0000000..ed6b647 --- /dev/null +++ b/src/node/walk.rs @@ -0,0 +1,46 @@ +use super::{Node, NodeType}; + +impl Node { + /// Direct children in structural order, not source-language evaluation order. + pub(crate) fn child_nodes(&self) -> impl Iterator { + [ + &self.lhs, &self.rhs, &self.cond, &self.then, &self.els, &self.ini, &self.upd, + ] + .into_iter() + .filter_map(|child| child.as_deref()) + .chain(&self.children) + .chain(&self.args) + } + + pub(crate) fn child_nodes_mut(&mut self) -> impl Iterator { + [ + &mut self.lhs, + &mut self.rhs, + &mut self.cond, + &mut self.then, + &mut self.els, + &mut self.ini, + &mut self.upd, + ] + .into_iter() + .filter_map(|child| child.as_deref_mut()) + .chain(&mut self.children) + .chain(&mut self.args) + } + + pub fn contains_case(&self) -> bool { + if matches!(self.nt, NodeType::Switch) { + return false; + } + if matches!(self.nt, NodeType::Case | NodeType::Label) { + return true; + } + self.children.iter().any(Self::contains_case) + || [ + &self.lhs, &self.rhs, &self.cond, &self.then, &self.els, &self.ini, &self.upd, + ] + .into_iter() + .flatten() + .any(|node| node.contains_case()) + } +}