3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::is_self_ty;
5 use clippy_utils::source::snippet;
6 use clippy_utils::ty::is_copy;
7 use if_chain::if_chain;
9 use rustc_errors::Applicability;
11 use rustc_hir::intravisit::FnKind;
12 use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind};
13 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::{sym, Span};
17 use rustc_target::abi::LayoutOf;
18 use rustc_target::spec::abi::Abi;
19 use rustc_target::spec::Target;
21 declare_clippy_lint! {
22 /// **What it does:** Checks for functions taking arguments by reference, where
23 /// the argument type is `Copy` and small enough to be more efficient to always
26 /// **Why is this bad?** In many calling conventions instances of structs will
27 /// be passed through registers if they fit into two or less general purpose
30 /// **Known problems:** This lint is target register size dependent, it is
31 /// limited to 32-bit to try and reduce portability problems between 32 and
32 /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
33 /// will be different.
35 /// The configuration option `trivial_copy_size_limit` can be set to override
36 /// this limit for a project.
38 /// This lint attempts to allow passing arguments by reference if a reference
39 /// to that argument is returned. This is implemented by comparing the lifetime
40 /// of the argument and return value for equality. However, this can cause
41 /// false positives in cases involving multiple lifetimes that are bounded by
48 /// fn foo(v: &u32) {}
55 pub TRIVIALLY_COPY_PASS_BY_REF,
57 "functions taking small copyable arguments by reference"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for functions taking arguments by value, where
62 /// the argument type is `Copy` and large enough to be worth considering
63 /// passing by reference. Does not trigger if the function is being exported,
64 /// because that might induce API breakage, if the parameter is declared as mutable,
65 /// or if the argument is a `self`.
67 /// **Why is this bad?** Arguments passed by value might result in an unnecessary
68 /// shallow copy, taking up more space in the stack and requiring a call to
69 /// `memcpy`, which can be expensive.
74 /// #[derive(Clone, Copy)]
75 /// struct TooLarge([u8; 2048]);
78 /// fn foo(v: TooLarge) {}
81 /// #[derive(Clone, Copy)]
82 /// struct TooLarge([u8; 2048]);
85 /// fn foo(v: &TooLarge) {}
87 pub LARGE_TYPES_PASSED_BY_VALUE,
89 "functions taking large arguments by value"
92 #[derive(Copy, Clone)]
93 pub struct PassByRefOrValue {
98 impl<'tcx> PassByRefOrValue {
99 pub fn new(ref_min_size: Option<u64>, value_max_size: u64, target: &Target) -> Self {
100 let ref_min_size = ref_min_size.unwrap_or_else(|| {
101 let bit_width = u64::from(target.pointer_width);
102 // Cap the calculated bit width at 32-bits to reduce
103 // portability problems between 32 and 64-bit targets
104 let bit_width = cmp::min(bit_width, 32);
105 #[allow(clippy::integer_division)]
106 let byte_width = bit_width / 8;
107 // Use a limit of 2 times the register byte width
117 fn check_poly_fn(&mut self, cx: &LateContext<'tcx>, hir_id: HirId, decl: &FnDecl<'_>, span: Option<Span>) {
118 let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
120 let fn_sig = cx.tcx.fn_sig(fn_def_id);
121 let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
123 let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id));
125 for (index, (input, &ty)) in decl.inputs.iter().zip(fn_sig.inputs()).enumerate() {
126 // All spans generated from a proc-macro invocation are the same...
128 Some(s) if s == input.span => return,
133 ty::Ref(input_lt, ty, Mutability::Not) => {
134 // Use lifetimes to determine if we're returning a reference to the
135 // argument. In that case we can't switch to pass-by-value as the
136 // argument will not live long enough.
137 let output_lts = match *fn_sig.output().kind() {
138 ty::Ref(output_lt, _, _) => vec![output_lt],
139 ty::Adt(_, substs) => substs.regions().collect(),
144 if !output_lts.contains(&input_lt);
146 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
147 if size <= self.ref_min_size;
148 if let hir::TyKind::Rptr(_, MutTy { ty: ref decl_ty, .. }) = input.kind;
150 let value_type = if is_self_ty(decl_ty) {
153 snippet(cx, decl_ty.span, "_").into()
157 TRIVIALLY_COPY_PASS_BY_REF,
159 &format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.ref_min_size),
160 "consider passing by value instead",
162 Applicability::Unspecified,
168 ty::Adt(_, _) | ty::Array(_, _) | ty::Tuple(_) => {
169 // if function has a body and parameter is annotated with mut, ignore
170 if let Some(param) = fn_body.and_then(|body| body.params.get(index)) {
171 match param.pat.kind {
172 PatKind::Binding(BindingAnnotation::Unannotated, _, _, _) => {},
178 if !cx.access_levels.is_exported(hir_id);
180 if !is_self_ty(input);
181 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
182 if size > self.value_max_size;
186 LARGE_TYPES_PASSED_BY_VALUE,
188 &format!("this argument ({} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", size, self.value_max_size),
189 "consider passing by reference instead",
190 format!("&{}", snippet(cx, input.span, "_")),
191 Applicability::MaybeIncorrect,
203 impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PASSED_BY_VALUE]);
205 impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue {
206 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
207 if item.span.from_expansion() {
211 if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
212 self.check_poly_fn(cx, item.hir_id(), &*method_sig.decl, None);
218 cx: &LateContext<'tcx>,
220 decl: &'tcx FnDecl<'_>,
221 _body: &'tcx Body<'_>,
225 if span.from_expansion() {
230 FnKind::ItemFn(.., header, _) => {
231 if header.abi != Abi::Rust {
234 let attrs = cx.tcx.hir().attrs(hir_id);
236 if let Some(meta_items) = a.meta_item_list() {
237 if a.has_name(sym::proc_macro_derive)
238 || (a.has_name(sym::inline) && attr::list_contains_name(&meta_items, sym::always))
245 FnKind::Method(..) => (),
246 FnKind::Closure => return,
249 // Exclude non-inherent impls
250 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
253 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
259 self.check_poly_fn(cx, hir_id, decl, Some(span));