From 1dd2ac805451f5bdaf11c51927ae3f059c97e37b Mon Sep 17 00:00:00 2001 From: xuqingqing Date: Tue, 10 May 2022 17:55:27 +0800 Subject: [PATCH] fix when "x[i] op= y" evaluates x[i] more than once When evaluates x twice in "x op= y", which was detectable if evaluating y affects x. We should identify such cases and evaluate y first. For reference see this bug in the go git repository: Fix golang/go#52811 --- go/statements.cc | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/go/statements.cc b/go/statements.cc index 95fa3c487..9e59ee579 100644 --- a/go/statements.cc +++ b/go/statements.cc @@ -1302,6 +1302,18 @@ Assignment_operation_statement::do_lower(Gogo*, Named_object*, go_unreachable(); } + // While we encountering "lhs op= func", we need keep return value to + // temporary var to avoid func affecting lhs. + // var val_temp VAL_TYPE = RHS + if (this->rhs_->classification() == + Expression::Expression_classification::EXPRESSION_CALL) + { + Temporary_statement *ts = + make_temporary(this->rhs_->type(), this->rhs_, loc); + b->add_statement(ts); + this->rhs_ = Expression::make_temporary_reference(ts, loc); + } + Expression* binop = Expression::make_binary(op, lval, this->rhs_, loc); Statement* s = Statement::make_assignment(this->lhs_, binop, loc); if (b->statements()->empty())