Skip to content

Commit a495c8d

Browse files
committed
don't require rules to worry about run-time borrow errors
1 parent 966f43e commit a495c8d

36 files changed

Lines changed: 1124 additions & 369 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 87 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5726,17 +5726,23 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
57265726
auto bind = tgt_ir->argsToBind(ctx_, expr, all_args);
57275727
auto *operand = tgt_ir->refExprOperand();
57285728
auto effect = tgt_ir->refExprEffect();
5729+
auto setup = tgt_ir->refExprSetup();
57295730
// The C++ expression is a reference to the argument, or an element of it.
57305731
auto *base = expr->isGLValue() ? tgt_ir->refExprBase() : nullptr;
5731-
bool discards_ref =
5732-
base && operand->size() == 1 && !effect.empty() && isVoid();
5732+
bool discards_ref = DiscardsRef(expr, *tgt_ir);
57335733
// The temporaries of an argument that a pointer is returned to live as long
57345734
// as the binding.
57355735
if (base && !discards_ref && all_args[base->n]->HasSideEffects(ctx_) &&
57365736
ReturnsPointerToArg(all_args[base->n])) {
57375737
bind[base->n] = true;
57385738
}
57395739
auto first = ArgsToEvaluateFirst(expr, *tgt_ir, all_args, bind);
5740+
// The object that init constructs is constructed first, rather than its
5741+
// arguments evaluated first one by one.
5742+
auto num_params = std::min(tgt_ir->params.size(), all_args.size());
5743+
bool init_first =
5744+
tgt_ir->alwaysConstructsInit() &&
5745+
std::find(first.begin() + num_params, first.end(), true) != first.end();
57405746
std::vector<std::string> values, names;
57415747
// Bindings in a global initializer are local to the expansion too.
57425748
clang::DeclContext *binding_context = curr_function_;
@@ -5745,7 +5751,7 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
57455751
ctx_, ctx_.getTranslationUnitDecl(), expr->getExprLoc());
57465752
}
57475753
for (size_t i = 0; binding_context && i < all_args.size(); ++i) {
5748-
if (!bind[i] && !first[i]) {
5754+
if ((!bind[i] && !first[i]) || (init_first && i >= num_params)) {
57495755
continue;
57505756
}
57515757
// The rule takes the value of a transparent union.
@@ -5806,6 +5812,14 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
58065812
}
58075813
}
58085814

5815+
if (init_first) {
5816+
values.push_back(
5817+
std::format("{{ {} }}", ConvertInitFragment(expr, all_args)));
5818+
auto name = NewTempName();
5819+
names.push_back("mut " + name);
5820+
bound_inits_.emplace(expr, std::move(name));
5821+
}
5822+
58095823
auto saved_borrows = std::exchange(mut_borrows_, {});
58105824
auto saved_borrowed_args = std::exchange(borrowed_args_, {});
58115825
auto outer_borrows = std::exchange(borrows_, false);
@@ -5817,7 +5831,8 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
58175831
result =
58185832
'{' + ConvertIRFragment(effect, bindings, expr, all_args, ctx) + '}';
58195833
} else if (base && ReturnsPointerToArg(all_args[base->n])) {
5820-
auto str = ConvertIRFragment(effect, bindings, expr, all_args, ctx);
5834+
auto str = ConvertIRFragment(effect, bindings, expr, all_args, ctx) +
5835+
ConvertIRFragment(setup, bindings, expr, all_args, ctx);
58215836
std::string index;
58225837
if (operand->size() > 1) {
58235838
index = ConvertIRFragment(llvm::ArrayRef(*operand).drop_front(), bindings,
@@ -5834,19 +5849,22 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
58345849
tgt_ir->body.back())
58355850
->prefix;
58365851
result = std::format(
5837-
"{}{} {}", ConvertIRFragment(effect, bindings, expr, all_args, ctx),
5852+
"{}{}{} {}", ConvertIRFragment(effect, bindings, expr, all_args, ctx),
5853+
ConvertIRFragment(setup, bindings, expr, all_args, ctx),
58385854
prefix == "&mut" ? "&raw mut"
58395855
: prefix == "&" ? "&raw const"
58405856
: prefix,
58415857
ConvertIRFragment(*operand, bindings, expr, all_args, ctx));
5842-
if (!effect.empty()) {
5858+
if (!effect.empty() || !setup.empty()) {
58435859
result = '{' + result + '}';
58445860
}
58455861
} else {
58465862
place = operand && !isAddrOf() && !isVoid();
5847-
result = ConvertIRFragment(
5848-
place && values.empty() && effect.empty() ? *operand : tgt_ir->body,
5849-
bindings, expr, all_args, ctx);
5863+
result = ConvertIRFragment(place && values.empty() && effect.empty() &&
5864+
setup.empty()
5865+
? *operand
5866+
: tgt_ir->body,
5867+
bindings, expr, all_args, ctx);
58505868
if (tgt_ir->multi_statement) {
58515869
result = '{' + result + '}';
58525870
}
@@ -5874,10 +5892,11 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
58745892
}
58755893
// A place is reached through a reference to it, out of the match or the
58765894
// block that computes it, so that it can be assigned.
5877-
if (place && (!values.empty() || !effect.empty())) {
5895+
if (place && (!values.empty() || !effect.empty() || !setup.empty())) {
58785896
result = std::format("(*{})", result);
58795897
}
58805898
returned_place_ = place && base;
5899+
bound_inits_.erase(expr);
58815900
if (!effects.empty()) {
58825901
result = std::format("{{ {} {} }}", effects, result);
58835902
}
@@ -5896,11 +5915,54 @@ bool Converter::UsedOnce(const TranslationRule::ExprRule &rule, unsigned n) {
58965915
return uses == 1;
58975916
}
58985917

5899-
std::vector<bool>
5900-
Converter::ArgsToEvaluateFirst(clang::Expr *, const TranslationRule::ExprRule &,
5901-
llvm::ArrayRef<clang::Expr *> args,
5902-
const std::vector<bool> &) {
5903-
return std::vector<bool>(args.size());
5918+
namespace {
5919+
// The variables that expr names, other than pointers and references, whose
5920+
// targets Rust doesn't borrow through the names.
5921+
void CollectNamedObjects(const clang::Stmt *stmt,
5922+
std::vector<const clang::VarDecl *> &vars) {
5923+
if (auto *ref = clang::dyn_cast<clang::DeclRefExpr>(stmt)) {
5924+
auto *var = clang::dyn_cast<clang::VarDecl>(ref->getDecl());
5925+
if (var && !var->getType()->isPointerType() &&
5926+
!var->getType()->isReferenceType()) {
5927+
vars.push_back(var);
5928+
}
5929+
}
5930+
for (auto *child : stmt->children()) {
5931+
if (child) {
5932+
CollectNamedObjects(child, vars);
5933+
}
5934+
}
5935+
}
5936+
} // namespace
5937+
5938+
// The object that init constructs from the remaining arguments, unless it may
5939+
// not be constructed, is constructed first if any of them names an object that
5940+
// the body borrows mutably, which Rust doesn't let the construction borrow too.
5941+
std::vector<bool> Converter::ArgsToEvaluateFirst(
5942+
clang::Expr *, const TranslationRule::ExprRule &rule,
5943+
llvm::ArrayRef<clang::Expr *> args, const std::vector<bool> &) {
5944+
std::vector<bool> first(args.size());
5945+
if (!rule.alwaysConstructsInit()) {
5946+
return first;
5947+
}
5948+
auto num_params = std::min(rule.params.size(), args.size());
5949+
std::vector<const clang::VarDecl *> borrowed;
5950+
TranslationRule::AnyFragment(rule.body, [&](const auto &frag) {
5951+
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&frag);
5952+
if (ph && ph->n < num_params &&
5953+
ph->access == TranslationRule::Access::kBorrowMut) {
5954+
CollectNamedObjects(args[ph->n], borrowed);
5955+
}
5956+
return false;
5957+
});
5958+
if (llvm::any_of(args.drop_front(num_params), [&](clang::Expr *arg) {
5959+
return llvm::any_of(borrowed, [&](const clang::VarDecl *var) {
5960+
return ReferencesVar(arg, var);
5961+
});
5962+
})) {
5963+
std::fill(first.begin() + num_params, first.end(), true);
5964+
}
5965+
return first;
59045966
}
59055967

59065968
bool Converter::ReturnsPointerToArg(clang::Expr *) { return false; }
@@ -5978,7 +6040,8 @@ std::string Converter::ConvertIRFragment(
59786040
result += ConvertMappedMethodCall(expr, **mc, bindings, all_args, ctx);
59796041
} else if (auto *re =
59806042
std::get_if<std::unique_ptr<RefExprFragment>>(&frag)) {
5981-
result += (*re)->prefix + ' ' +
6043+
result += ConvertIRFragment((*re)->setup, bindings, expr, all_args, ctx) +
6044+
(*re)->prefix + ' ' +
59826045
ConvertIRFragment((*re)->inner, bindings, expr, all_args, ctx);
59836046
} else if (auto *call =
59846047
std::get_if<std::unique_ptr<GenericCallFragment>>(&frag)) {
@@ -6137,6 +6200,9 @@ Converter::ConvertInitFragment(clang::Expr *expr,
61376200
if (!tgt_ir || !tgt_ir->usesInit()) {
61386201
llvm::report_fatal_error("expression rule does not use Init");
61396202
}
6203+
if (auto it = bound_inits_.find(expr); it != bound_inits_.end()) {
6204+
return it->second;
6205+
}
61406206
auto type = RuleRegistry::GetInitType(ctx_, expr);
61416207

61426208
Buffer buf(*this);
@@ -6210,6 +6276,11 @@ bool Converter::isObject() const {
62106276
return !curr_expr_kind_.empty() && curr_expr_kind_.back() == ExprKind::Object;
62116277
}
62126278

6279+
bool Converter::DiscardsRef(const clang::Expr *expr,
6280+
const TranslationRule::ExprRule &rule) const {
6281+
return expr->isGLValue() && isVoid() && rule.refExprDiscardable();
6282+
}
6283+
62136284
bool Converter::isVoid() const {
62146285
return curr_expr_kind_.empty() || curr_expr_kind_.back() == ExprKind::Void;
62156286
}

‎cpp2rust/converter/converter.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -950,6 +950,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
950950
// Bound initializer arguments may need a mapped move constructor when
951951
// forwarding the original rvalue from its pointer binding.
952952
std::unordered_set<const clang::VarDecl *> bound_init_args_;
953+
// The variables bound to the objects that the init of rules construct.
954+
std::unordered_map<const clang::Expr *, std::string> bound_inits_;
953955

954956
// Updates the pointee using its previous value, borrowing it once.
955957
virtual std::string
@@ -979,6 +981,11 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
979981
llvm::ArrayRef<clang::Expr *> args,
980982
const std::vector<bool> &bind);
981983

984+
// Whether expr discards the reference that its rule returns, so only the
985+
// statements before the reference are emitted.
986+
bool DiscardsRef(const clang::Expr *expr,
987+
const TranslationRule::ExprRule &rule) const;
988+
982989
// Borrows the arguments that the body of a rule borrows mutably and uses
983990
// more than once for the whole call, rather than once for each use.
984991
virtual void BorrowArgsForCall(clang::Expr *expr,

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3234,10 +3234,11 @@ struct ArgUses {
32343234
};
32353235

32363236
std::vector<ArgUses> GetArgUses(const TranslationRule::ExprRule &rule,
3237-
size_t num_args) {
3237+
size_t num_args, bool discards_ref) {
32383238
std::vector<ArgUses> uses(num_args);
32393239
// The reference returned to an argument is not a use of it, in place or as
3240-
// a pointer to it, other than the index of an element.
3240+
// a pointer to it, other than the computation of the index of an element,
3241+
// which a discarded reference doesn't need.
32413242
auto body = llvm::ArrayRef(rule.body);
32423243
if (rule.refExprBase()) {
32433244
body = rule.refExprEffect();
@@ -3255,7 +3256,8 @@ std::vector<ArgUses> GetArgUses(const TranslationRule::ExprRule &rule,
32553256
return false;
32563257
};
32573258
TranslationRule::AnyFragment(body, add);
3258-
if (rule.refExprBase()) {
3259+
if (rule.refExprBase() && !discards_ref) {
3260+
TranslationRule::AnyFragment(rule.refExprSetup(), add);
32593261
TranslationRule::AnyFragment(
32603262
llvm::ArrayRef(*rule.refExprOperand()).drop_front(), add);
32613263
}
@@ -3271,14 +3273,17 @@ const clang::VarDecl *GetReferencedVar(const clang::Expr *expr) {
32713273
namespace {
32723274
// Whether evaluating an expression borrows no value that another expression
32733275
// may borrow mutably: constants, and the values of the variables that are
3274-
// values of their own, as is_own_value tells.
3276+
// values of their own, as is_own_value tells. If reads_pointees, the pointers
3277+
// it evaluates to are read through too, so this, whose object is unknown, is
3278+
// not one.
32753279
class BorrowsNothingVisitor
32763280
: public clang::ConstStmtVisitor<BorrowsNothingVisitor, bool> {
32773281
public:
32783282
BorrowsNothingVisitor(
3279-
clang::ASTContext &ctx,
3283+
clang::ASTContext &ctx, bool reads_pointees,
32803284
llvm::function_ref<bool(const clang::DeclRefExpr *)> is_own_value)
3281-
: ctx_(ctx), is_own_value_(is_own_value) {}
3285+
: ctx_(ctx), reads_pointees_(reads_pointees),
3286+
is_own_value_(is_own_value) {}
32823287

32833288
bool Traverse(const clang::Expr *expr) {
32843289
return expr->isEvaluatable(ctx_) || Visit(expr);
@@ -3288,7 +3293,7 @@ class BorrowsNothingVisitor
32883293

32893294
bool VisitStringLiteral(const clang::StringLiteral *) { return true; }
32903295

3291-
bool VisitCXXThisExpr(const clang::CXXThisExpr *) { return true; }
3296+
bool VisitCXXThisExpr(const clang::CXXThisExpr *) { return !reads_pointees_; }
32923297

32933298
bool VisitParenExpr(const clang::ParenExpr *expr) {
32943299
return Traverse(expr->getSubExpr());
@@ -3330,23 +3335,34 @@ class BorrowsNothingVisitor
33303335

33313336
private:
33323337
clang::ASTContext &ctx_;
3338+
bool reads_pointees_;
33333339
llvm::function_ref<bool(const clang::DeclRefExpr *)> is_own_value_;
33343340
};
33353341
} // namespace
33363342

33373343
bool ConverterRefCount::BorrowsNothing(
3338-
const clang::Expr *arg, llvm::ArrayRef<const clang::VarDecl *> vars) const {
3344+
const clang::Expr *arg, llvm::ArrayRef<const clang::VarDecl *> vars,
3345+
bool reads_pointees) const {
33393346
// A scalar is a value of its own, unless it is accessed through a
3340-
// reference, as is an unboxed variable.
3347+
// reference, as is an unboxed variable. Of those, only the arrays of
3348+
// non-pointer scalars and such scalars are known to have no pointees but
3349+
// themselves.
33413350
return BorrowsNothingVisitor(
3342-
ctx_,
3351+
ctx_, reads_pointees,
33433352
[&](const clang::DeclRefExpr *ref) {
33443353
auto *var = clang::dyn_cast<clang::VarDecl>(ref->getDecl());
3345-
return var && var->hasLocalStorage() &&
3346-
!llvm::is_contained(vars, var) &&
3347-
!GetDeclRefType(curr_function_, ref, var)
3348-
->isReferenceType() &&
3349-
(var->getType()->isScalarType() || IsUnboxedVar(var));
3354+
if (!var || !var->hasLocalStorage() ||
3355+
llvm::is_contained(vars, var) ||
3356+
GetDeclRefType(curr_function_, ref, var)
3357+
->isReferenceType()) {
3358+
return false;
3359+
}
3360+
if (reads_pointees) {
3361+
auto *element = var->getType()->getBaseElementTypeUnsafe();
3362+
return element->isArithmeticType() ||
3363+
element->isEnumeralType();
3364+
}
3365+
return var->getType()->isScalarType() || IsUnboxedVar(var);
33503366
})
33513367
.Traverse(arg);
33523368
}
@@ -3359,14 +3375,19 @@ bool ConverterRefCount::BorrowsNothing(
33593375
std::vector<bool> ConverterRefCount::ArgsToEvaluateFirst(
33603376
clang::Expr *expr, const TranslationRule::ExprRule &rule,
33613377
llvm::ArrayRef<clang::Expr *> args, const std::vector<bool> &bind) {
3362-
std::vector<bool> first(args.size());
3363-
auto uses = GetArgUses(rule, args.size());
3378+
auto first = Converter::ArgsToEvaluateFirst(expr, rule, args, bind);
3379+
auto uses = GetArgUses(rule, args.size(), DiscardsRef(expr, rule));
33643380
std::vector<const clang::VarDecl *> borrowed;
3381+
bool borrows_library_objects = true;
33653382
for (unsigned i = 0; i < args.size(); ++i) {
33663383
// The receiver of a call through a pointer is reached through it.
33673384
if (uses[i].borrow_mut && !RuleRegistry::ParamIsPointer(ctx_, expr, i) &&
33683385
(args[i]->getType()->isPointerType() || !IsUnboxedPlace(args[i]))) {
33693386
borrowed.push_back(GetReferencedVar(args[i]));
3387+
auto type = args[i]->getType();
3388+
auto *record = (type->isPointerType() ? type->getPointeeType() : type)
3389+
->getAsRecordDecl();
3390+
borrows_library_objects &= record && !IsUserDefinedDecl(record);
33703391
}
33713392
}
33723393
if (borrowed.empty()) {
@@ -3387,9 +3408,20 @@ std::vector<bool> ConverterRefCount::ArgsToEvaluateFirst(
33873408
(arg->isPRValue() || rule.takesAddress(ctx_, expr, i, arg) ||
33883409
(arg->isLValue() && uses[i].only_moved));
33893410
if (!first[i] && arg->HasSideEffects(ctx_)) {
3390-
break;
3411+
return first;
33913412
}
33923413
}
3414+
// The object that init constructs from the remaining arguments, unless it
3415+
// may not be constructed, is constructed first if any of them, or what a
3416+
// pointer among them points to, may be a borrowed value. Only a library
3417+
// object is known not to be among the pointees that BorrowsNothing allows.
3418+
if (rule.alwaysConstructsInit() &&
3419+
llvm::any_of(args.drop_front(num_args), [&](clang::Expr *arg) {
3420+
return !borrows_library_objects ||
3421+
!BorrowsNothing(arg, borrowed, /*reads_pointees=*/true);
3422+
})) {
3423+
std::fill(first.begin() + num_args, first.end(), true);
3424+
}
33933425
return first;
33943426
}
33953427

@@ -3398,7 +3430,7 @@ std::vector<bool> ConverterRefCount::ArgsToEvaluateFirst(
33983430
void ConverterRefCount::BorrowArgsForCall(clang::Expr *expr,
33993431
const TranslationRule::ExprRule &rule,
34003432
llvm::ArrayRef<clang::Expr *> args) {
3401-
auto uses = GetArgUses(rule, args.size());
3433+
auto uses = GetArgUses(rule, args.size(), DiscardsRef(expr, rule));
34023434
for (unsigned i = 0; i < args.size(); ++i) {
34033435
auto *arg = args[i];
34043436
if (!uses[i].borrow_mut || uses[i].count < 2 ||

‎cpp2rust/converter/models/converter_refcount.h‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,9 +364,12 @@ class ConverterRefCount final : public Converter {
364364

365365
// Whether evaluating arg borrows no value that another expression may
366366
// borrow mutably: constants, and the values of local scalars and pointers,
367-
// other than those of vars.
367+
// other than those of vars. If reads_pointees, also whether what the
368+
// pointers it evaluates to point to is such a value: a local array of
369+
// non-pointer scalars, or such a scalar.
368370
bool BorrowsNothing(const clang::Expr *arg,
369-
llvm::ArrayRef<const clang::VarDecl *> vars) const;
371+
llvm::ArrayRef<const clang::VarDecl *> vars,
372+
bool reads_pointees = false) const;
370373

371374
bool ReturnsPointerToArg(clang::Expr *arg) override;
372375

0 commit comments

Comments
 (0)