Improve casts

This commit is contained in:
Sofia 2026-04-13 21:27:46 +03:00
parent c8d4b653da
commit 1555c12bbd
3 changed files with 40 additions and 6 deletions

View File

@ -12,12 +12,28 @@ namespace types {
auto bool_ty = std::shared_ptr<Type>{
new FundamentalType{ FundamentalTypeKind::Bool } };
for (auto& source_ty : { int_ty, char_ty, bool_ty }) {
for (auto& target_ty : { int_ty, char_ty, bool_ty }) {
casts.push_back(CastDefinition{ source_ty, target_ty, false,
[](codegen::Builder& builder, std::shared_ptr<Type> target, llvm::Value* value) {
return builder.builder->CreateSExtOrTrunc(value, target->codegen(builder), "cast");
} });
auto numerical_types = { int_ty, char_ty, bool_ty };
for (auto& source_ty : numerical_types) {
for (auto& target_ty : numerical_types) {
if (types::types_equal(source_ty, target_ty)) {
casts.push_back(CastDefinition{ source_ty, target_ty, true,
[](codegen::Builder&, std::shared_ptr<Type>, llvm::Value* value) {
return value;
} });
}
else if (target_ty->is_signed()) {
casts.push_back(CastDefinition{ source_ty, target_ty, false,
[](codegen::Builder& builder, std::shared_ptr<Type> target, llvm::Value* value) {
return builder.builder->CreateSExtOrTrunc(value, target->codegen(builder), "cast");
} });
}
else {
casts.push_back(CastDefinition{ source_ty, target_ty, false,
[](codegen::Builder& builder, std::shared_ptr<Type> target, llvm::Value* value) {
return builder.builder->CreateZExtOrTrunc(value, target->codegen(builder), "cast");
} });
}
}
}

View File

@ -75,6 +75,10 @@ namespace types {
return {};
}
bool Type::is_signed() {
false;
}
std::pair<llvm::Value*, std::shared_ptr<Type>> FundamentalType::load(codegen::Builder&, llvm::Value* ptr) {
auto self = std::make_shared<FundamentalType>(*this);
return std::pair(ptr, self);
@ -124,6 +128,18 @@ namespace types {
}
}
bool FundamentalType::is_signed() {
switch (this->m_ty) {
case FundamentalTypeKind::Int:
return true;
case FundamentalTypeKind::Bool:
case FundamentalTypeKind::Char:
return false;
default:
throw std::runtime_error("Invalid type");
}
}
std::string FunctionType::formatted() {
std::stringstream out{ "" };
out << "(";

View File

@ -33,6 +33,7 @@ namespace types {
virtual llvm::Value* sub(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs);
virtual llvm::Value* lt(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs);
virtual llvm::Value* gt(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs);
virtual bool is_signed();
};
class FundamentalType : public Type {
@ -47,6 +48,7 @@ namespace types {
virtual llvm::Value* sub(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) override;
virtual llvm::Value* lt(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) override;
virtual llvm::Value* gt(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) override;
virtual bool is_signed() override;
};