From bb4d1c6045c2b3c15406b41e80a637e9b35c33f4 Mon Sep 17 00:00:00 2001 From: Sofia Date: Mon, 13 Apr 2026 18:11:54 +0300 Subject: [PATCH] Add binops --- src/binops.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/binops.h | 8 +++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/binops.cpp b/src/binops.cpp index 9a323a6..83cd39d 100644 --- a/src/binops.cpp +++ b/src/binops.cpp @@ -3,6 +3,61 @@ namespace types { std::vector create_binops() { + std::vector definitions{}; + + auto int_ty = std::shared_ptr{ + new types::FundamentalType{ types::FundamentalTypeKind::Int } }; + auto char_ty = std::shared_ptr{ + new types::FundamentalType{ types::FundamentalTypeKind::Char } }; + auto bool_ty = std::shared_ptr{ + new types::FundamentalType{ types::FundamentalTypeKind::Bool } }; + + for (auto& ty : { int_ty, char_ty, bool_ty }) { + // Arithmetic binops + definitions.push_back(BinopDefinition{ + ty, types::BinOp::Add, ty, + ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) { + return builder.builder->CreateAdd(lhs, rhs, "add"); + } }); + + definitions.push_back(BinopDefinition{ + ty, types::BinOp::Sub, ty, + ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) { + return builder.builder->CreateSub(lhs, rhs, "sub"); + } }); + + // Comparisons + definitions.push_back(BinopDefinition{ + ty, types::BinOp::LessThan, ty, + bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) { + return builder.builder->CreateICmpSLE(lhs, rhs, "icmpsle"); + } }); + + definitions.push_back(BinopDefinition{ + ty, types::BinOp::GreaterThan, ty, + bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) { + return builder.builder->CreateICmpSGT(lhs, rhs, "icmpsgt"); + } }); + } + + return definitions; + } + + std::optional find_binop( + std::vector& binops, + std::shared_ptr lhs, + BinOp op, + std::shared_ptr rhs) { + for (auto& binop : binops) { + if (binop.op != op) { + continue; + } + if (!types_equal(lhs, binop.lhs) || !types_equal(rhs, binop.rhs)) { + continue; + } + + return binop; + } return {}; } } \ No newline at end of file diff --git a/src/binops.h b/src/binops.h index 706fca7..bfba32d 100644 --- a/src/binops.h +++ b/src/binops.h @@ -23,11 +23,17 @@ namespace types { BinOp op; std::shared_ptr rhs; std::shared_ptr result; - llvm::Value* (*codegen)(codegen::Builder& builder); + llvm::Value* (*codegen)(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs); }; std::vector create_binops(); + std::optional find_binop( + std::vector& binops, + std::shared_ptr lhs, + BinOp op, + std::shared_ptr rhs); + } #endif \ No newline at end of file