Skip to content

Commit df26331

Browse files
committed
Refactor: Simply negate for unsigned unary minus
It seems negation internally uses 2's complement. Refactor: LLVM: Combine visit_IntegerUnaryMinus() and visit_UnsignedIntegerUnaryMinus()
1 parent 6b2a69c commit df26331

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

src/libasr/codegen/asr_to_llvm.cpp

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5345,7 +5345,8 @@ class ASRToLLVMVisitor : public ASR::BaseVisitor<ASRToLLVMVisitor>
53455345
tmp = builder->CreateNot(tmp);
53465346
}
53475347

5348-
void visit_IntegerUnaryMinus(const ASR::IntegerUnaryMinus_t &x) {
5348+
template <typename T>
5349+
void handle_SU_IntegerUnaryMinus(const T& x) {
53495350
if (x.m_value) {
53505351
this->visit_expr_wrapper(x.m_value, true);
53515352
return;
@@ -5356,15 +5357,12 @@ class ASRToLLVMVisitor : public ASR::BaseVisitor<ASRToLLVMVisitor>
53565357
tmp = builder->CreateSub(zero, tmp);
53575358
}
53585359

5360+
void visit_IntegerUnaryMinus(const ASR::IntegerUnaryMinus_t &x) {
5361+
handle_SU_IntegerUnaryMinus(x);
5362+
}
5363+
53595364
void visit_UnsignedIntegerUnaryMinus(const ASR::UnsignedIntegerUnaryMinus_t &x) {
5360-
if (x.m_value) {
5361-
this->visit_expr_wrapper(x.m_value, true);
5362-
return;
5363-
}
5364-
this->visit_expr_wrapper(x.m_arg, true);
5365-
int kind = ASRUtils::extract_kind_from_ttype_t(ASRUtils::expr_type(x.m_arg));
5366-
llvm::Value *one = llvm::ConstantInt::get(context, llvm::APInt(kind * 8, 1, true));
5367-
tmp = builder->CreateAdd(builder->CreateNot(tmp), one); // compute 2's complement
5365+
handle_SU_IntegerUnaryMinus(x);
53685366
}
53695367

53705368
void visit_RealUnaryMinus(const ASR::RealUnaryMinus_t &x) {

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3602,9 +3602,8 @@ class CommonVisitor : public AST::BaseVisitor<Struct> {
36023602
if (ASRUtils::expr_value(operand) != nullptr) {
36033603
int64_t op_value = ASR::down_cast<ASR::UnsignedIntegerConstant_t>(
36043604
ASRUtils::expr_value(operand))->m_n;
3605-
op_value = (~op_value) + 1; // compute 2's complement
36063605
value = ASR::down_cast<ASR::expr_t>(ASR::make_UnsignedIntegerConstant_t(
3607-
al, x.base.base.loc, op_value, operand_type));
3606+
al, x.base.base.loc, -op_value, operand_type));
36083607
}
36093608
tmp = ASR::make_UnsignedIntegerUnaryMinus_t(al, x.base.base.loc, operand,
36103609
operand_type, value);

0 commit comments

Comments
 (0)