4 use clippy_utils::diagnostics::span_lint_and_sugg;
5 use clippy_utils::source::snippet;
6 use clippy_utils::ty::{for_each_top_level_late_bound_region, is_copy};
7 use clippy_utils::{is_self, is_self_ty};
8 use core::ops::ControlFlow;
9 use if_chain::if_chain;
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_errors::Applicability;
14 use rustc_hir::intravisit::FnKind;
15 use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind};
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_middle::ty::adjustment::{Adjust, PointerCast};
18 use rustc_middle::ty::layout::LayoutOf;
19 use rustc_middle::ty::{self, RegionKind};
20 use rustc_session::{declare_tool_lint, impl_lint_pass};
21 use rustc_span::def_id::LocalDefId;
22 use rustc_span::{sym, Span};
23 use rustc_target::spec::abi::Abi;
24 use rustc_target::spec::Target;
26 declare_clippy_lint! {
28 /// Checks for functions taking arguments by reference, where
29 /// the argument type is `Copy` and small enough to be more efficient to always
32 /// ### Why is this bad?
33 /// In many calling conventions instances of structs will
34 /// be passed through registers if they fit into two or less general purpose
37 /// ### Known problems
38 /// This lint is target register size dependent, it is
39 /// limited to 32-bit to try and reduce portability problems between 32 and
40 /// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
41 /// will be different.
43 /// The configuration option `trivial_copy_size_limit` can be set to override
44 /// this limit for a project.
46 /// This lint attempts to allow passing arguments by reference if a reference
47 /// to that argument is returned. This is implemented by comparing the lifetime
48 /// of the argument and return value for equality. However, this can cause
49 /// false positives in cases involving multiple lifetimes that are bounded by
52 /// Also, it does not take account of other similar cases where getting memory addresses
53 /// matters; namely, returning the pointer to the argument in question,
54 /// and passing the argument, as both references and pointers,
55 /// to a function that needs the memory address. For further details, refer to
56 /// [this issue](https://github.com/rust-lang/rust-clippy/issues/5953)
57 /// that explains a real case in which this false positive
58 /// led to an **undefined behavior** introduced with unsafe code.
63 /// fn foo(v: &u32) {}
70 #[clippy::version = "pre 1.29.0"]
71 pub TRIVIALLY_COPY_PASS_BY_REF,
73 "functions taking small copyable arguments by reference"
76 declare_clippy_lint! {
78 /// Checks for functions taking arguments by value, where
79 /// the argument type is `Copy` and large enough to be worth considering
80 /// passing by reference. Does not trigger if the function is being exported,
81 /// because that might induce API breakage, if the parameter is declared as mutable,
82 /// or if the argument is a `self`.
84 /// ### Why is this bad?
85 /// Arguments passed by value might result in an unnecessary
86 /// shallow copy, taking up more space in the stack and requiring a call to
87 /// `memcpy`, which can be expensive.
91 /// #[derive(Clone, Copy)]
92 /// struct TooLarge([u8; 2048]);
94 /// fn foo(v: TooLarge) {}
99 /// # #[derive(Clone, Copy)]
100 /// # struct TooLarge([u8; 2048]);
101 /// fn foo(v: &TooLarge) {}
103 #[clippy::version = "1.49.0"]
104 pub LARGE_TYPES_PASSED_BY_VALUE,
106 "functions taking large arguments by value"
109 #[derive(Copy, Clone)]
110 pub struct PassByRefOrValue {
113 avoid_breaking_exported_api: bool,
116 impl<'tcx> PassByRefOrValue {
118 ref_min_size: Option<u64>,
120 avoid_breaking_exported_api: bool,
123 let ref_min_size = ref_min_size.unwrap_or_else(|| {
124 let bit_width = u64::from(target.pointer_width);
125 // Cap the calculated bit width at 32-bits to reduce
126 // portability problems between 32 and 64-bit targets
127 let bit_width = cmp::min(bit_width, 32);
128 #[expect(clippy::integer_division)]
129 let byte_width = bit_width / 8;
130 // Use a limit of 2 times the register byte width
137 avoid_breaking_exported_api,
141 fn check_poly_fn(&mut self, cx: &LateContext<'tcx>, def_id: LocalDefId, decl: &FnDecl<'_>, span: Option<Span>) {
142 if self.avoid_breaking_exported_api && cx.access_levels.is_exported(def_id) {
146 let fn_sig = cx.tcx.fn_sig(def_id);
147 let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id));
149 // Gather all the lifetimes found in the output type which may affect whether
150 // `TRIVIALLY_COPY_PASS_BY_REF` should be linted.
151 let mut output_regions = FxHashSet::default();
152 for_each_top_level_late_bound_region(fn_sig.skip_binder().output(), |region| -> ControlFlow<!> {
153 output_regions.insert(region);
154 ControlFlow::Continue(())
157 for (index, (input, ty)) in iter::zip(
159 fn_sig.skip_binder().inputs().iter().map(|&ty| fn_sig.rebind(ty)),
163 // All spans generated from a proc-macro invocation are the same...
165 Some(s) if s == input.span => continue,
169 match *ty.skip_binder().kind() {
170 ty::Ref(lt, ty, Mutability::Not) => {
172 RegionKind::ReLateBound(index, region)
173 if index.as_u32() == 0 && output_regions.contains(®ion) =>
177 // Early bound regions on functions are either from the containing item, are bounded by another
178 // lifetime, or are used as a bound for a type or lifetime.
179 RegionKind::ReEarlyBound(..) => continue,
183 let ty = cx.tcx.erase_late_bound_regions(fn_sig.rebind(ty));
185 && let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes())
186 && size <= self.ref_min_size
187 && let hir::TyKind::Rptr(_, MutTy { ty: decl_ty, .. }) = input.kind
189 if let Some(typeck) = cx.maybe_typeck_results() {
190 // Don't lint if an unsafe pointer is created.
191 // TODO: Limit the check only to unsafe pointers to the argument (or part of the argument)
192 // which escape the current function.
193 if typeck.node_types().iter().any(|(_, &ty)| ty.is_unsafe_ptr())
197 .flat_map(|(_, a)| a)
198 .any(|a| matches!(a.kind, Adjust::Pointer(PointerCast::UnsafeFnPointer)))
203 let value_type = if fn_body.and_then(|body| body.params.get(index)).map_or(false, is_self) {
206 snippet(cx, decl_ty.span, "_").into()
210 TRIVIALLY_COPY_PASS_BY_REF,
212 &format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.ref_min_size),
213 "consider passing by value instead",
215 Applicability::Unspecified,
220 ty::Adt(_, _) | ty::Array(_, _) | ty::Tuple(_) => {
221 // if function has a body and parameter is annotated with mut, ignore
222 if let Some(param) = fn_body.and_then(|body| body.params.get(index)) {
223 match param.pat.kind {
224 PatKind::Binding(BindingAnnotation::Unannotated, _, _, _) => {},
228 let ty = cx.tcx.erase_late_bound_regions(ty);
232 if !is_self_ty(input);
233 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
234 if size > self.value_max_size;
238 LARGE_TYPES_PASSED_BY_VALUE,
240 &format!("this argument ({} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", size, self.value_max_size),
241 "consider passing by reference instead",
242 format!("&{}", snippet(cx, input.span, "_")),
243 Applicability::MaybeIncorrect,
255 impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PASSED_BY_VALUE]);
257 impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue {
258 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
259 if item.span.from_expansion() {
263 if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
264 self.check_poly_fn(cx, item.def_id, method_sig.decl, None);
270 cx: &LateContext<'tcx>,
272 decl: &'tcx FnDecl<'_>,
273 _body: &'tcx Body<'_>,
277 if span.from_expansion() {
282 FnKind::ItemFn(.., header) => {
283 if header.abi != Abi::Rust {
286 let attrs = cx.tcx.hir().attrs(hir_id);
288 if let Some(meta_items) = a.meta_item_list() {
289 if a.has_name(sym::proc_macro_derive)
290 || (a.has_name(sym::inline) && attr::list_contains_name(&meta_items, sym::always))
297 FnKind::Method(..) => (),
298 FnKind::Closure => return,
301 // Exclude non-inherent impls
302 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
305 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
311 self.check_poly_fn(cx, cx.tcx.hir().local_def_id(hir_id), decl, Some(span));