Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions gcc/rust/typecheck/rust-hir-type-check-item.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,55 @@
#include "rust-type-util.h"
#include "rust-tyty-variance-analysis.h"
#include "rust-tyty.h"
#include "options.h"
#include "rust-compile-base.h"
#include "rust-compile-context.h"

namespace Rust {
namespace Resolver {

// Const-evaluate the discriminants of a repr(C) enum and warn when a value does
// not fit into a C int/unsigned int. Done here, during type resolution, using
// the compile context (a singleton shared with the backend).
static void
check_repr_c_enum_discriminants (Compile::Context *ctx, TyTy::BaseType *type)
{
if (type->get_kind () != TyTy::TypeKind::ADT)
return;

auto &adt = static_cast<TyTy::ADTType &> (*type);
if (!adt.is_enum ()
|| adt.get_repr_options ().repr_kind != TyTy::ADTType::ReprKind::C)
return;

const int64_t c_int_min = -2147483648LL;
const int64_t c_uint_max = 4294967295LL;

for (auto &variant : adt.get_variants ())
{
if (!variant->has_discriminant ())
continue;

HIR::Expr &discriminant = variant->get_discriminant ();
TyTy::BaseType *discrim_ty = nullptr;
if (!ctx->get_tyctx ()->lookup_type (
discriminant.get_mappings ().get_hirid (), &discrim_ty))
continue;

tree folded
= Compile::HIRCompileBase::query_compile_const_expr (ctx, discrim_ty,
discriminant);
if (folded == error_mark_node || TREE_CODE (folded) != INTEGER_CST)
continue;

widest_int value = wi::to_widest (folded);
if (wi::lts_p (value, c_int_min) || wi::gts_p (value, c_uint_max))
rust_warning_at (discriminant.get_locus (), OPT_Woverflow,
"%<repr(C)%> enum discriminant does not fit into C "
"%<int%> nor into C %<unsigned int%>");
}
}

TypeCheckItem::TypeCheckItem () : TypeCheckBase (), infered (nullptr) {}

TyTy::BaseType *
Expand Down Expand Up @@ -470,6 +515,9 @@ TypeCheckItem::visit (HIR::Enum &enum_decl)
infered = type;

context->get_variance_analysis_ctx ().add_type_constraints (*type);

if (flag_unused_check_2_0)
check_repr_c_enum_discriminants (Compile::Context::get (), type);
}

void
Expand Down
19 changes: 19 additions & 0 deletions gcc/testsuite/rust/compile/repr-c-enums-larger-than-int_0.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// { dg-additional-options "-frust-unused-check-2.0" }
// { dg-skip-if "discriminant needs a 64-bit isize" { ! lp64 } }
#![feature(no_core)]
#![no_core]

#[repr(C)]
pub enum Big {
A = 9223372036854775807,
// { dg-warning "enum discriminant does not fit into C" "" { target *-*-* } .-1 }
}

#[repr(C)]
pub enum Small {
B = 5,
}

pub enum NoRepr {
C = 9223372036854775807,
}
Loading