xref: /llvm-project/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp (revision 0fba450b9756a496224efd06e5ba76c9a61d3e15)
1 //===--- EasilySwappableParametersCheck.cpp - clang-tidy ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "EasilySwappableParametersCheck.h"
10 #include "../utils/OptionsUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/RecursiveASTVisitor.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Lex/Lexer.h"
15 #include "llvm/ADT/SmallSet.h"
16 
17 #define DEBUG_TYPE "EasilySwappableParametersCheck"
18 #include "llvm/Support/Debug.h"
19 
20 namespace optutils = clang::tidy::utils::options;
21 
22 /// The default value for the MinimumLength check option.
23 static constexpr std::size_t DefaultMinimumLength = 2;
24 
25 /// The default value for ignored parameter names.
26 static const std::string DefaultIgnoredParameterNames =
27     optutils::serializeStringList({"\"\"", "iterator", "Iterator", "begin",
28                                    "Begin", "end", "End", "first", "First",
29                                    "last", "Last", "lhs", "LHS", "rhs", "RHS"});
30 
31 /// The default value for ignored parameter type suffixes.
32 static const std::string DefaultIgnoredParameterTypeSuffixes =
33     optutils::serializeStringList({"bool",
34                                    "Bool",
35                                    "_Bool",
36                                    "it",
37                                    "It",
38                                    "iterator",
39                                    "Iterator",
40                                    "inputit",
41                                    "InputIt",
42                                    "forwardit",
43                                    "FowardIt",
44                                    "bidirit",
45                                    "BidirIt",
46                                    "constiterator",
47                                    "const_iterator",
48                                    "Const_Iterator",
49                                    "Constiterator",
50                                    "ConstIterator",
51                                    "RandomIt",
52                                    "randomit",
53                                    "random_iterator",
54                                    "ReverseIt",
55                                    "reverse_iterator",
56                                    "reverse_const_iterator",
57                                    "ConstReverseIterator",
58                                    "Const_Reverse_Iterator",
59                                    "const_reverse_iterator"
60                                    "Constreverseiterator",
61                                    "constreverseiterator"});
62 
63 /// The default value for the QualifiersMix check option.
64 static constexpr bool DefaultQualifiersMix = false;
65 
66 /// The default value for the ModelImplicitConversions check option.
67 static constexpr bool DefaultModelImplicitConversions = true;
68 
69 /// The default value for suppressing diagnostics about parameters that are
70 /// used together.
71 static constexpr bool DefaultSuppressParametersUsedTogether = true;
72 
73 /// The default value for the NamePrefixSuffixSilenceDissimilarityTreshold
74 /// check option.
75 static constexpr std::size_t
76     DefaultNamePrefixSuffixSilenceDissimilarityTreshold = 1;
77 
78 using namespace clang::ast_matchers;
79 
80 namespace clang {
81 namespace tidy {
82 namespace bugprone {
83 
84 using TheCheck = EasilySwappableParametersCheck;
85 
86 namespace filter {
87 class SimilarlyUsedParameterPairSuppressor;
88 
89 static bool isIgnoredParameter(const TheCheck &Check, const ParmVarDecl *Node);
90 static inline bool
91 isSimilarlyUsedParameter(const SimilarlyUsedParameterPairSuppressor &Suppressor,
92                          const ParmVarDecl *Param1, const ParmVarDecl *Param2);
93 static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold,
94                                             StringRef Str1, StringRef Str2);
95 } // namespace filter
96 
97 namespace model {
98 
99 /// The language features involved in allowing the mix between two parameters.
100 enum class MixFlags : unsigned char {
101   Invalid = 0, //< Sentinel bit pattern. DO NOT USE!
102 
103   //< Certain constructs (such as pointers to noexcept/non-noexcept functions)
104   // have the same CanonicalType, which would result in false positives.
105   // During the recursive modelling call, this flag is set if a later diagnosed
106   // canonical type equivalence should be thrown away.
107   WorkaroundDisableCanonicalEquivalence = 1,
108 
109   None = 2,           //< Mix between the two parameters is not possible.
110   Trivial = 4,        //< The two mix trivially, and are the exact same type.
111   Canonical = 8,      //< The two mix because the types refer to the same
112                       // CanonicalType, but we do not elaborate as to how.
113   TypeAlias = 16,     //< The path from one type to the other involves
114                       // desugaring type aliases.
115   ReferenceBind = 32, //< The mix involves the binding power of "const &".
116   Qualifiers = 64,    //< The mix involves change in the qualifiers.
117   ImplicitConversion = 128, //< The mixing of the parameters is possible
118                             // through implicit conversions between the types.
119 
120   LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue =*/ImplicitConversion)
121 };
122 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
123 
124 /// Returns whether the SearchedFlag is turned on in the Data.
125 static inline bool hasFlag(MixFlags Data, MixFlags SearchedFlag) {
126   assert(SearchedFlag != MixFlags::Invalid &&
127          "can't be used to detect lack of all bits!");
128 
129   // "Data & SearchedFlag" would need static_cast<bool>() in conditions.
130   return (Data & SearchedFlag) == SearchedFlag;
131 }
132 
133 #ifndef NDEBUG
134 
135 // The modelling logic of this check is more complex than usual, and
136 // potentially hard to understand without the ability to see into the
137 // representation during the recursive descent. This debug code is only
138 // compiled in 'Debug' mode, or if LLVM_ENABLE_ASSERTIONS config is turned on.
139 
140 /// Formats the MixFlags enum into a useful, user-readable representation.
141 static inline std::string formatMixFlags(MixFlags F) {
142   if (F == MixFlags::Invalid)
143     return "#Inv!";
144 
145   SmallString<8> Str{"-------"};
146 
147   if (hasFlag(F, MixFlags::None))
148     // Shows the None bit explicitly, as it can be applied in the recursion
149     // even if other bits are set.
150     Str[0] = '!';
151   if (hasFlag(F, MixFlags::Trivial))
152     Str[1] = 'T';
153   if (hasFlag(F, MixFlags::Canonical))
154     Str[2] = 'C';
155   if (hasFlag(F, MixFlags::TypeAlias))
156     Str[3] = 't';
157   if (hasFlag(F, MixFlags::ReferenceBind))
158     Str[4] = '&';
159   if (hasFlag(F, MixFlags::Qualifiers))
160     Str[5] = 'Q';
161   if (hasFlag(F, MixFlags::ImplicitConversion))
162     Str[6] = 'i';
163 
164   if (hasFlag(F, MixFlags::WorkaroundDisableCanonicalEquivalence))
165     Str.append("(~C)");
166 
167   return Str.str().str();
168 }
169 
170 #else
171 
172 static inline std::string formatMixFlags(MixFlags F);
173 
174 #endif // NDEBUG
175 
176 /// The results of the steps of an Implicit Conversion Sequence is saved in
177 /// an instance of this record.
178 ///
179 /// A ConversionSequence maps the steps of the conversion with a member for
180 /// each type involved in the conversion. Imagine going from a hypothetical
181 /// Complex class to projecting it to the real part as a const double.
182 ///
183 /// I.e., given:
184 ///
185 ///    struct Complex {
186 ///      operator double() const;
187 ///    };
188 ///
189 ///    void functionBeingAnalysed(Complex C, const double R);
190 ///
191 /// we will get the following sequence:
192 ///
193 /// (Begin=) Complex
194 ///
195 ///     The first standard conversion is a qualification adjustment.
196 /// (AfterFirstStandard=) const Complex
197 ///
198 ///     Then the user-defined conversion is executed.
199 /// (UDConvOp.ConversionOperatorResultType=) double
200 ///
201 ///     Then this 'double' is qualifier-adjusted to 'const double'.
202 /// (AfterSecondStandard=) double
203 ///
204 /// The conversion's result has now been calculated, so it ends here.
205 /// (End=) double.
206 ///
207 /// Explicit storing of Begin and End in this record is needed, because
208 /// getting to what Begin and End here are needs further resolution of types,
209 /// e.g. in the case of typedefs:
210 ///
211 ///     using Comp = Complex;
212 ///     using CD = const double;
213 ///     void functionBeingAnalysed2(Comp C, CD R);
214 ///
215 /// In this case, the user will be diagnosed with a potential conversion
216 /// between the two typedefs as written in the code, but to elaborate the
217 /// reasoning behind this conversion, we also need to show what the typedefs
218 /// mean. See FormattedConversionSequence towards the bottom of this file!
219 struct ConversionSequence {
220   enum UserDefinedConversionKind { UDCK_None, UDCK_Ctor, UDCK_Oper };
221 
222   struct UserDefinedConvertingConstructor {
223     const CXXConstructorDecl *Fun;
224     QualType ConstructorParameterType;
225     QualType UserDefinedType;
226   };
227 
228   struct UserDefinedConversionOperator {
229     const CXXConversionDecl *Fun;
230     QualType UserDefinedType;
231     QualType ConversionOperatorResultType;
232   };
233 
234   /// The type the conversion stared from.
235   QualType Begin;
236 
237   /// The intermediate type after the first Standard Conversion Sequence.
238   QualType AfterFirstStandard;
239 
240   /// The details of the user-defined conversion involved, as a tagged union.
241   union {
242     char None;
243     UserDefinedConvertingConstructor UDConvCtor;
244     UserDefinedConversionOperator UDConvOp;
245   };
246   UserDefinedConversionKind UDConvKind;
247 
248   /// The intermediate type after performing the second Standard Conversion
249   /// Sequence.
250   QualType AfterSecondStandard;
251 
252   /// The result type the conversion targeted.
253   QualType End;
254 
255   ConversionSequence() : None(0), UDConvKind(UDCK_None) {}
256   ConversionSequence(QualType From, QualType To)
257       : Begin(From), None(0), UDConvKind(UDCK_None), End(To) {}
258 
259   explicit operator bool() const {
260     return !AfterFirstStandard.isNull() || UDConvKind != UDCK_None ||
261            !AfterSecondStandard.isNull();
262   }
263 
264   /// Returns all the "steps" (non-unique and non-similar) types involved in
265   /// the conversion sequence. This method does **NOT** return Begin and End.
266   SmallVector<QualType, 4> getInvolvedTypesInSequence() const {
267     SmallVector<QualType, 4> Ret;
268     auto EmplaceIfDifferent = [&Ret](QualType QT) {
269       if (QT.isNull())
270         return;
271       if (Ret.empty())
272         Ret.emplace_back(QT);
273       else if (Ret.back() != QT)
274         Ret.emplace_back(QT);
275     };
276 
277     EmplaceIfDifferent(AfterFirstStandard);
278     switch (UDConvKind) {
279     case UDCK_Ctor:
280       EmplaceIfDifferent(UDConvCtor.ConstructorParameterType);
281       EmplaceIfDifferent(UDConvCtor.UserDefinedType);
282       break;
283     case UDCK_Oper:
284       EmplaceIfDifferent(UDConvOp.UserDefinedType);
285       EmplaceIfDifferent(UDConvOp.ConversionOperatorResultType);
286       break;
287     case UDCK_None:
288       break;
289     }
290     EmplaceIfDifferent(AfterSecondStandard);
291 
292     return Ret;
293   }
294 
295   /// Updates the steps of the conversion sequence with the steps from the
296   /// other instance.
297   ///
298   /// \note This method does not check if the resulting conversion sequence is
299   /// sensible!
300   ConversionSequence &update(const ConversionSequence &RHS) {
301     if (!RHS.AfterFirstStandard.isNull())
302       AfterFirstStandard = RHS.AfterFirstStandard;
303     switch (RHS.UDConvKind) {
304     case UDCK_Ctor:
305       UDConvKind = UDCK_Ctor;
306       UDConvCtor = RHS.UDConvCtor;
307       break;
308     case UDCK_Oper:
309       UDConvKind = UDCK_Oper;
310       UDConvOp = RHS.UDConvOp;
311       break;
312     case UDCK_None:
313       break;
314     }
315     if (!RHS.AfterSecondStandard.isNull())
316       AfterSecondStandard = RHS.AfterSecondStandard;
317 
318     return *this;
319   }
320 
321   /// Sets the user-defined conversion to the given constructor.
322   void setConversion(const UserDefinedConvertingConstructor &UDCC) {
323     UDConvKind = UDCK_Ctor;
324     UDConvCtor = UDCC;
325   }
326 
327   /// Sets the user-defined conversion to the given operator.
328   void setConversion(const UserDefinedConversionOperator &UDCO) {
329     UDConvKind = UDCK_Oper;
330     UDConvOp = UDCO;
331   }
332 
333   /// Returns the type in the conversion that's formally "in our hands" once
334   /// the user-defined conversion is executed.
335   QualType getTypeAfterUserDefinedConversion() const {
336     switch (UDConvKind) {
337     case UDCK_Ctor:
338       return UDConvCtor.UserDefinedType;
339     case UDCK_Oper:
340       return UDConvOp.ConversionOperatorResultType;
341     case UDCK_None:
342       return {};
343     }
344     llvm_unreachable("Invalid UDConv kind.");
345   }
346 
347   const CXXMethodDecl *getUserDefinedConversionFunction() const {
348     switch (UDConvKind) {
349     case UDCK_Ctor:
350       return UDConvCtor.Fun;
351     case UDCK_Oper:
352       return UDConvOp.Fun;
353     case UDCK_None:
354       return {};
355     }
356     llvm_unreachable("Invalid UDConv kind.");
357   }
358 
359   /// Returns the SourceRange in the text that corresponds to the interesting
360   /// part of the user-defined conversion. This is either the parameter type
361   /// in a converting constructor, or the conversion result type in a conversion
362   /// operator.
363   SourceRange getUserDefinedConversionHighlight() const {
364     switch (UDConvKind) {
365     case UDCK_Ctor:
366       return UDConvCtor.Fun->getParamDecl(0)->getSourceRange();
367     case UDCK_Oper:
368       // getReturnTypeSourceRange() does not work for CXXConversionDecls as the
369       // returned type is physically behind the declaration's name ("operator").
370       if (const FunctionTypeLoc FTL = UDConvOp.Fun->getFunctionTypeLoc())
371         if (const TypeLoc RetLoc = FTL.getReturnLoc())
372           return RetLoc.getSourceRange();
373       return {};
374     case UDCK_None:
375       return {};
376     }
377     llvm_unreachable("Invalid UDConv kind.");
378   }
379 };
380 
381 /// Contains the metadata for the mixability result between two types,
382 /// independently of which parameters they were calculated from.
383 struct MixData {
384   /// The flag bits of the mix indicating what language features allow for it.
385   MixFlags Flags = MixFlags::Invalid;
386 
387   /// A potentially calculated common underlying type after desugaring, that
388   /// both sides of the mix can originate from.
389   QualType CommonType;
390 
391   /// The steps an implicit conversion performs to get from one type to the
392   /// other.
393   ConversionSequence Conversion, ConversionRTL;
394 
395   /// True if the MixData was specifically created with only a one-way
396   /// conversion modelled.
397   bool CreatedFromOneWayConversion = false;
398 
399   MixData(MixFlags Flags) : Flags(Flags) {}
400   MixData(MixFlags Flags, QualType CommonType)
401       : Flags(Flags), CommonType(CommonType) {}
402   MixData(MixFlags Flags, ConversionSequence Conv)
403       : Flags(Flags), Conversion(Conv), CreatedFromOneWayConversion(true) {}
404   MixData(MixFlags Flags, ConversionSequence LTR, ConversionSequence RTL)
405       : Flags(Flags), Conversion(LTR), ConversionRTL(RTL) {}
406   MixData(MixFlags Flags, QualType CommonType, ConversionSequence LTR,
407           ConversionSequence RTL)
408       : Flags(Flags), CommonType(CommonType), Conversion(LTR),
409         ConversionRTL(RTL) {}
410 
411   void sanitize() {
412     assert(Flags != MixFlags::Invalid && "sanitize() called on invalid bitvec");
413 
414     MixFlags CanonicalAndWorkaround =
415         MixFlags::Canonical | MixFlags::WorkaroundDisableCanonicalEquivalence;
416     if ((Flags & CanonicalAndWorkaround) == CanonicalAndWorkaround) {
417       // A workaround for too eagerly equivalent canonical types was requested,
418       // and a canonical equivalence was proven. Fulfill the request and throw
419       // this result away.
420       Flags = MixFlags::None;
421       return;
422     }
423 
424     if (hasFlag(Flags, MixFlags::None)) {
425       // If anywhere down the recursion a potential mix "path" is deemed
426       // impossible, throw away all the other bits because the mix is not
427       // possible.
428       Flags = MixFlags::None;
429       return;
430     }
431 
432     if (Flags == MixFlags::Trivial)
433       return;
434 
435     if (static_cast<bool>(Flags ^ MixFlags::Trivial))
436       // If the mix involves somewhere trivial equivalence but down the
437       // recursion other bit(s) were set, remove the trivial bit, as it is not
438       // trivial.
439       Flags &= ~MixFlags::Trivial;
440 
441     bool ShouldHaveImplicitConvFlag = false;
442     if (CreatedFromOneWayConversion && Conversion)
443       ShouldHaveImplicitConvFlag = true;
444     else if (!CreatedFromOneWayConversion && Conversion && ConversionRTL)
445       // Only say that we have implicit conversion mix possibility if it is
446       // bidirectional. Otherwise, the compiler would report an *actual* swap
447       // at a call site...
448       ShouldHaveImplicitConvFlag = true;
449 
450     if (ShouldHaveImplicitConvFlag)
451       Flags |= MixFlags::ImplicitConversion;
452     else
453       Flags &= ~MixFlags::ImplicitConversion;
454   }
455 
456   bool isValid() const { return Flags >= MixFlags::None; }
457 
458   bool indicatesMixability() const { return Flags > MixFlags::None; }
459 
460   /// Add the specified flag bits to the flags.
461   MixData operator|(MixFlags EnableFlags) const {
462     if (CreatedFromOneWayConversion) {
463       MixData M{Flags | EnableFlags, Conversion};
464       M.CommonType = CommonType;
465       return M;
466     }
467     return {Flags | EnableFlags, CommonType, Conversion, ConversionRTL};
468   }
469 
470   /// Add the specified flag bits to the flags.
471   MixData &operator|=(MixFlags EnableFlags) {
472     Flags |= EnableFlags;
473     return *this;
474   }
475 
476   /// Add the specified qualifiers to the common type in the Mix.
477   MixData qualify(Qualifiers Quals) const {
478     SplitQualType Split = CommonType.split();
479     Split.Quals.addQualifiers(Quals);
480     QualType CommonType{Split.Ty, Split.Quals.getAsOpaqueValue()};
481 
482     if (CreatedFromOneWayConversion) {
483       MixData M{Flags, Conversion};
484       M.CommonType = CommonType;
485       return M;
486     }
487     return {Flags, CommonType, Conversion, ConversionRTL};
488   }
489 };
490 
491 /// A named tuple that contains the information for a mix between two concrete
492 /// parameters.
493 struct Mix {
494   const ParmVarDecl *First, *Second;
495   MixData Data;
496 
497   Mix(const ParmVarDecl *F, const ParmVarDecl *S, MixData Data)
498       : First(F), Second(S), Data(std::move(Data)) {}
499 
500   void sanitize() { Data.sanitize(); }
501   MixFlags flags() const { return Data.Flags; }
502   bool flagsValid() const { return Data.isValid(); }
503   bool mixable() const { return Data.indicatesMixability(); }
504   QualType commonUnderlyingType() const { return Data.CommonType; }
505   const ConversionSequence &leftToRightConversionSequence() const {
506     return Data.Conversion;
507   }
508   const ConversionSequence &rightToLeftConversionSequence() const {
509     return Data.ConversionRTL;
510   }
511 };
512 
513 // NOLINTNEXTLINE(misc-redundant-expression): Seems to be a bogus warning.
514 static_assert(std::is_trivially_copyable<Mix>::value &&
515                   std::is_trivially_move_constructible<Mix>::value &&
516                   std::is_trivially_move_assignable<Mix>::value,
517               "Keep frequently used data simple!");
518 
519 struct MixableParameterRange {
520   /// A container for Mixes.
521   using MixVector = SmallVector<Mix, 8>;
522 
523   /// The number of parameters iterated to build the instance.
524   std::size_t NumParamsChecked = 0;
525 
526   /// The individual flags and supporting information for the mixes.
527   MixVector Mixes;
528 
529   /// Gets the leftmost parameter of the range.
530   const ParmVarDecl *getFirstParam() const {
531     // The first element is the LHS of the very first mix in the range.
532     assert(!Mixes.empty());
533     return Mixes.front().First;
534   }
535 
536   /// Gets the rightmost parameter of the range.
537   const ParmVarDecl *getLastParam() const {
538     // The builder function breaks building an instance of this type if it
539     // finds something that can not be mixed with the rest, by going *forward*
540     // in the list of parameters. So at any moment of break, the RHS of the last
541     // element of the mix vector is also the last element of the mixing range.
542     assert(!Mixes.empty());
543     return Mixes.back().Second;
544   }
545 };
546 
547 /// Helper enum for the recursive calls in the modelling that toggle what kinds
548 /// of implicit conversions are to be modelled.
549 enum ImplicitConversionModellingMode : unsigned char {
550   //< No implicit conversions are modelled.
551   ICMM_None,
552 
553   //< The full implicit conversion sequence is modelled.
554   ICMM_All,
555 
556   //< Only model a unidirectional implicit conversion and within it only one
557   // standard conversion sequence.
558   ICMM_OneWaySingleStandardOnly
559 };
560 
561 static MixData
562 isLRefEquallyBindingToType(const TheCheck &Check,
563                            const LValueReferenceType *LRef, QualType Ty,
564                            const ASTContext &Ctx, bool IsRefRHS,
565                            ImplicitConversionModellingMode ImplicitMode);
566 
567 static MixData
568 approximateImplicitConversion(const TheCheck &Check, QualType LType,
569                               QualType RType, const ASTContext &Ctx,
570                               ImplicitConversionModellingMode ImplicitMode);
571 
572 static inline bool isUselessSugar(const Type *T) {
573   return isa<DecayedType, ElaboratedType, ParenType>(T);
574 }
575 
576 /// Approximate the way how LType and RType might refer to "essentially the
577 /// same" type, in a sense that at a particular call site, an expression of
578 /// type LType and RType might be successfully passed to a variable (in our
579 /// specific case, a parameter) of type RType and LType, respectively.
580 /// Note the swapped order!
581 ///
582 /// The returned data structure is not guaranteed to be properly set, as this
583 /// function is potentially recursive. It is the caller's responsibility to
584 /// call sanitize() on the result once the recursion is over.
585 static MixData
586 calculateMixability(const TheCheck &Check, QualType LType, QualType RType,
587                     const ASTContext &Ctx,
588                     ImplicitConversionModellingMode ImplicitMode) {
589   LLVM_DEBUG(llvm::dbgs() << ">>> calculateMixability for LType:\n";
590              LType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n";
591              RType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';);
592 
593   // Certain constructs match on the last catch-all getCanonicalType() equality,
594   // which is perhaps something not what we want. If this variable is true,
595   // the canonical type equality will be ignored.
596   bool RecursiveReturnDiscardingCanonicalType = false;
597 
598   if (LType == RType) {
599     LLVM_DEBUG(llvm::dbgs() << "<<< calculateMixability. Trivial equality.\n");
600     return {MixFlags::Trivial, LType};
601   }
602 
603   // Dissolve certain type sugars that do not affect the mixability of one type
604   // with the other, and also do not require any sort of elaboration for the
605   // user to understand.
606   if (isUselessSugar(LType.getTypePtr())) {
607     LLVM_DEBUG(llvm::dbgs()
608                << "--- calculateMixability. LHS is useless sugar.\n");
609     return calculateMixability(Check, LType.getSingleStepDesugaredType(Ctx),
610                                RType, Ctx, ImplicitMode);
611   }
612   if (isUselessSugar(RType.getTypePtr())) {
613     LLVM_DEBUG(llvm::dbgs()
614                << "--- calculateMixability. RHS is useless sugar.\n");
615     return calculateMixability(
616         Check, LType, RType.getSingleStepDesugaredType(Ctx), Ctx, ImplicitMode);
617   }
618 
619   // At a particular call site, what could be passed to a 'T' or 'const T' might
620   // also be passed to a 'const T &' without the call site putting a direct
621   // side effect on the passed expressions.
622   if (const auto *LRef = LType->getAs<LValueReferenceType>()) {
623     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. LHS is &.\n");
624     return isLRefEquallyBindingToType(Check, LRef, RType, Ctx, false,
625                                       ImplicitMode) |
626            MixFlags::ReferenceBind;
627   }
628   if (const auto *RRef = RType->getAs<LValueReferenceType>()) {
629     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. RHS is &.\n");
630     return isLRefEquallyBindingToType(Check, RRef, LType, Ctx, true,
631                                       ImplicitMode) |
632            MixFlags::ReferenceBind;
633   }
634 
635   // Dissolve typedefs after the qualifiers outside the typedef are dealt with.
636   if (LType->getAs<TypedefType>()) {
637     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. LHS is typedef.\n");
638     return calculateMixability(Check, LType.getSingleStepDesugaredType(Ctx),
639                                RType, Ctx, ImplicitMode) |
640            MixFlags::TypeAlias;
641   }
642   if (RType->getAs<TypedefType>()) {
643     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. RHS is typedef.\n");
644     return calculateMixability(Check, LType,
645                                RType.getSingleStepDesugaredType(Ctx), Ctx,
646                                ImplicitMode) |
647            MixFlags::TypeAlias;
648   }
649 
650   // A parameter of type 'cvr1 T' and another of potentially differently
651   // qualified 'cvr2 T' may bind with the same power, if the user so requested.
652   if (LType.getLocalCVRQualifiers() != RType.getLocalCVRQualifiers()) {
653     LLVM_DEBUG(if (LType.getLocalCVRQualifiers()) llvm::dbgs()
654                << "--- calculateMixability. LHS is CVR.\n");
655     LLVM_DEBUG(if (RType.getLocalCVRQualifiers()) llvm::dbgs()
656                << "--- calculateMixability. RHS is CVR.\n");
657 
658     if (!Check.QualifiersMix) {
659       LLVM_DEBUG(llvm::dbgs()
660                  << "<<< calculateMixability. QualifiersMix turned off.\n");
661       return {MixFlags::None};
662     }
663 
664     return calculateMixability(Check, LType.getLocalUnqualifiedType(),
665                                RType.getLocalUnqualifiedType(), Ctx,
666                                ImplicitMode) |
667            MixFlags::Qualifiers;
668   }
669   if (LType.getLocalCVRQualifiers() == RType.getLocalCVRQualifiers() &&
670       LType.getLocalCVRQualifiers() != 0) {
671     LLVM_DEBUG(llvm::dbgs()
672                << "--- calculateMixability. LHS and RHS same CVR.\n");
673     // Apply the same qualifier back into the found common type if we found
674     // a common type between the unqualified versions.
675     return calculateMixability(Check, LType.getLocalUnqualifiedType(),
676                                RType.getLocalUnqualifiedType(), Ctx,
677                                ImplicitMode)
678         .qualify(LType.getLocalQualifiers());
679   }
680 
681   if (LType->isPointerType() && RType->isPointerType()) {
682     // If both types are pointers, and pointed to the exact same type,
683     // LType == RType took care of that. Try to see if the pointee type has
684     // some other match. However, this must not consider implicit conversions.
685     LLVM_DEBUG(llvm::dbgs()
686                << "--- calculateMixability. LHS and RHS are Ptrs.\n");
687     MixData MixOfPointee =
688         calculateMixability(Check, LType->getPointeeType(),
689                             RType->getPointeeType(), Ctx, ICMM_None);
690     if (hasFlag(MixOfPointee.Flags,
691                 MixFlags::WorkaroundDisableCanonicalEquivalence))
692       RecursiveReturnDiscardingCanonicalType = true;
693 
694     MixOfPointee.sanitize();
695     if (MixOfPointee.indicatesMixability()) {
696       LLVM_DEBUG(llvm::dbgs()
697                  << "<<< calculateMixability. Pointees are mixable.\n");
698       return MixOfPointee;
699     }
700   }
701 
702   if (ImplicitMode > ICMM_None) {
703     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. Start implicit...\n");
704     MixData MixLTR =
705         approximateImplicitConversion(Check, LType, RType, Ctx, ImplicitMode);
706     LLVM_DEBUG(
707         if (hasFlag(MixLTR.Flags, MixFlags::ImplicitConversion)) llvm::dbgs()
708             << "--- calculateMixability. Implicit Left -> Right found.\n";);
709 
710     if (ImplicitMode == ICMM_OneWaySingleStandardOnly && MixLTR.Conversion &&
711         !MixLTR.Conversion.AfterFirstStandard.isNull() &&
712         MixLTR.Conversion.UDConvKind == ConversionSequence::UDCK_None &&
713         MixLTR.Conversion.AfterSecondStandard.isNull()) {
714       // The invoker of the method requested only modelling a single standard
715       // conversion, in only the forward direction, and they got just that.
716       LLVM_DEBUG(llvm::dbgs() << "<<< calculateMixability. Implicit "
717                                  "conversion, one-way, standard-only.\n");
718       return {MixFlags::ImplicitConversion, MixLTR.Conversion};
719     }
720 
721     // Otherwise if the invoker requested a full modelling, do the other
722     // direction as well.
723     MixData MixRTL =
724         approximateImplicitConversion(Check, RType, LType, Ctx, ImplicitMode);
725     LLVM_DEBUG(
726         if (hasFlag(MixRTL.Flags, MixFlags::ImplicitConversion)) llvm::dbgs()
727             << "--- calculateMixability. Implicit Right -> Left found.\n";);
728 
729     if (MixLTR.Conversion && MixRTL.Conversion) {
730       LLVM_DEBUG(
731           llvm::dbgs()
732           << "<<< calculateMixability. Implicit conversion, bidirectional.\n");
733       return {MixFlags::ImplicitConversion, MixLTR.Conversion,
734               MixRTL.Conversion};
735     }
736   }
737 
738   if (RecursiveReturnDiscardingCanonicalType)
739     LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. Before CanonicalType, "
740                                "Discard was enabled.\n");
741 
742   // Certain kinds unfortunately need to be side-stepped for canonical type
743   // matching.
744   if (LType->getAs<FunctionProtoType>() || RType->getAs<FunctionProtoType>()) {
745     // Unfortunately, the canonical type of a function pointer becomes the
746     // same even if exactly one is "noexcept" and the other isn't, making us
747     // give a false positive report irrespective of implicit conversions.
748     LLVM_DEBUG(llvm::dbgs()
749                << "--- calculateMixability. Discarding potential canonical "
750                   "equivalence on FunctionProtoTypes.\n");
751     RecursiveReturnDiscardingCanonicalType = true;
752   }
753 
754   MixData MixToReturn{MixFlags::None};
755 
756   // If none of the previous logic found a match, try if Clang otherwise
757   // believes the types to be the same.
758   QualType LCanonical = LType.getCanonicalType();
759   if (LCanonical == RType.getCanonicalType()) {
760     LLVM_DEBUG(llvm::dbgs()
761                << "<<< calculateMixability. Same CanonicalType.\n");
762     MixToReturn = {MixFlags::Canonical, LCanonical};
763   }
764 
765   if (RecursiveReturnDiscardingCanonicalType)
766     MixToReturn |= MixFlags::WorkaroundDisableCanonicalEquivalence;
767 
768   LLVM_DEBUG(if (MixToReturn.Flags == MixFlags::None) llvm::dbgs()
769              << "<<< calculateMixability. No match found.\n");
770   return MixToReturn;
771 }
772 
773 /// Calculates if the reference binds an expression of the given type. This is
774 /// true iff 'LRef' is some 'const T &' type, and the 'Ty' is 'T' or 'const T'.
775 ///
776 /// \param ImplicitMode is forwarded in the possible recursive call to
777 /// calculateMixability.
778 static MixData
779 isLRefEquallyBindingToType(const TheCheck &Check,
780                            const LValueReferenceType *LRef, QualType Ty,
781                            const ASTContext &Ctx, bool IsRefRHS,
782                            ImplicitConversionModellingMode ImplicitMode) {
783   LLVM_DEBUG(llvm::dbgs() << ">>> isLRefEquallyBindingToType for LRef:\n";
784              LRef->dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand Type:\n";
785              Ty.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';);
786 
787   QualType ReferredType = LRef->getPointeeType();
788   if (!ReferredType.isLocalConstQualified() &&
789       ReferredType->getAs<TypedefType>()) {
790     LLVM_DEBUG(
791         llvm::dbgs()
792         << "--- isLRefEquallyBindingToType. Non-const LRef to Typedef.\n");
793     ReferredType = ReferredType.getDesugaredType(Ctx);
794     if (!ReferredType.isLocalConstQualified()) {
795       LLVM_DEBUG(llvm::dbgs()
796                  << "<<< isLRefEquallyBindingToType. Typedef is not const.\n");
797       return {MixFlags::None};
798     }
799 
800     LLVM_DEBUG(llvm::dbgs() << "--- isLRefEquallyBindingToType. Typedef is "
801                                "const, considering as const LRef.\n");
802   } else if (!ReferredType.isLocalConstQualified()) {
803     LLVM_DEBUG(llvm::dbgs()
804                << "<<< isLRefEquallyBindingToType. Not const LRef.\n");
805     return {MixFlags::None};
806   };
807 
808   assert(ReferredType.isLocalConstQualified() &&
809          "Reaching this point means we are sure LRef is effectively a const&.");
810 
811   if (ReferredType == Ty) {
812     LLVM_DEBUG(
813         llvm::dbgs()
814         << "<<< isLRefEquallyBindingToType. Type of referred matches.\n");
815     return {MixFlags::Trivial, ReferredType};
816   }
817 
818   QualType NonConstReferredType = ReferredType;
819   NonConstReferredType.removeLocalConst();
820   if (NonConstReferredType == Ty) {
821     LLVM_DEBUG(llvm::dbgs() << "<<< isLRefEquallyBindingToType. Type of "
822                                "referred matches to non-const qualified.\n");
823     return {MixFlags::Trivial, NonConstReferredType};
824   }
825 
826   LLVM_DEBUG(
827       llvm::dbgs()
828       << "--- isLRefEquallyBindingToType. Checking mix for underlying type.\n");
829   return IsRefRHS ? calculateMixability(Check, Ty, NonConstReferredType, Ctx,
830                                         ImplicitMode)
831                   : calculateMixability(Check, NonConstReferredType, Ty, Ctx,
832                                         ImplicitMode);
833 }
834 
835 static inline bool isDerivedToBase(const CXXRecordDecl *Derived,
836                                    const CXXRecordDecl *Base) {
837   return Derived && Base && Derived->isCompleteDefinition() &&
838          Base->isCompleteDefinition() && Derived->isDerivedFrom(Base);
839 }
840 
841 static Optional<QualType>
842 approximateStandardConversionSequence(const TheCheck &Check, QualType From,
843                                       QualType To, const ASTContext &Ctx) {
844   LLVM_DEBUG(llvm::dbgs() << ">>> approximateStdConv for LType:\n";
845              From.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n";
846              To.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';);
847 
848   // A standard conversion sequence consists of the following, in order:
849   //  * Maybe either LValue->RValue conv., Array->Ptr conv., Function->Ptr conv.
850   //  * Maybe Numeric promotion or conversion.
851   //  * Maybe function pointer conversion.
852   //  * Maybe qualifier adjustments.
853   QualType WorkType = From;
854   // Get out the qualifiers of the original type. This will always be
855   // re-applied to the WorkType to ensure it is the same qualification as the
856   // original From was.
857   auto QualifiersToApply = From.split().Quals.getAsOpaqueValue();
858 
859   // LValue->RValue is irrelevant for the check, because it is a thing to be
860   // done at a call site, and will be performed if need be performed.
861 
862   // Array->Ptr decay.
863   if (const auto *ArrayT = dyn_cast<ArrayType>(From)) {
864     LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Array->Ptr decayed.\n");
865     WorkType = ArrayT->getPointeeType();
866   }
867 
868   // Function->Pointer conversions are also irrelevant, because a
869   // "FunctionType" cannot be the type of a parameter variable, so this
870   // conversion is only meaningful at call sites.
871 
872   // Numeric promotions and conversions.
873   const auto *FromBuiltin = WorkType->getAs<BuiltinType>();
874   const auto *ToBuiltin = To->getAs<BuiltinType>();
875   bool FromNumeric = FromBuiltin && (FromBuiltin->isIntegerType() ||
876                                      FromBuiltin->isFloatingType());
877   bool ToNumeric =
878       ToBuiltin && (ToBuiltin->isIntegerType() || ToBuiltin->isFloatingType());
879   if (FromNumeric && ToNumeric) {
880     // If both are integral types, the numeric conversion is performed.
881     // Reapply the qualifiers of the original type, however, so
882     // "const int -> double" in this case moves over to
883     // "const double -> double".
884     LLVM_DEBUG(llvm::dbgs()
885                << "--- approximateStdConv. Conversion between numerics.\n");
886     WorkType = QualType{ToBuiltin, QualifiersToApply};
887   }
888 
889   const auto *FromEnum = WorkType->getAs<EnumType>();
890   const auto *ToEnum = To->getAs<EnumType>();
891   if (FromEnum && ToNumeric && FromEnum->isUnscopedEnumerationType()) {
892     // Unscoped enumerations (or enumerations in C) convert to numerics.
893     LLVM_DEBUG(llvm::dbgs()
894                << "--- approximateStdConv. Unscoped enum to numeric.\n");
895     WorkType = QualType{ToBuiltin, QualifiersToApply};
896   } else if (FromNumeric && ToEnum && ToEnum->isUnscopedEnumerationType()) {
897     // Numeric types convert to enumerations only in C.
898     if (Ctx.getLangOpts().CPlusPlus) {
899       LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Numeric to unscoped "
900                                  "enum, not possible in C++!\n");
901       return {};
902     }
903 
904     LLVM_DEBUG(llvm::dbgs()
905                << "--- approximateStdConv. Numeric to unscoped enum.\n");
906     WorkType = QualType{ToEnum, QualifiersToApply};
907   }
908 
909   // Check for pointer conversions.
910   const auto *FromPtr = WorkType->getAs<PointerType>();
911   const auto *ToPtr = To->getAs<PointerType>();
912   if (FromPtr && ToPtr) {
913     if (ToPtr->isVoidPointerType()) {
914       LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. To void pointer.\n");
915       WorkType = QualType{ToPtr, QualifiersToApply};
916     }
917 
918     const auto *FromRecordPtr = FromPtr->getPointeeCXXRecordDecl();
919     const auto *ToRecordPtr = ToPtr->getPointeeCXXRecordDecl();
920     if (isDerivedToBase(FromRecordPtr, ToRecordPtr)) {
921       LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Derived* to Base*\n");
922       WorkType = QualType{ToPtr, QualifiersToApply};
923     }
924   }
925 
926   // Model the slicing Derived-to-Base too, as "BaseT temporary = derived;"
927   // can also be compiled.
928   const auto *FromRecord = WorkType->getAsCXXRecordDecl();
929   const auto *ToRecord = To->getAsCXXRecordDecl();
930   if (isDerivedToBase(FromRecord, ToRecord)) {
931     LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Derived To Base.\n");
932     WorkType = QualType{ToRecord->getTypeForDecl(), QualifiersToApply};
933   }
934 
935   if (Ctx.getLangOpts().CPlusPlus17 && FromPtr && ToPtr) {
936     // Function pointer conversion: A noexcept function pointer can be passed
937     // to a non-noexcept one.
938     const auto *FromFunctionPtr =
939         FromPtr->getPointeeType()->getAs<FunctionProtoType>();
940     const auto *ToFunctionPtr =
941         ToPtr->getPointeeType()->getAs<FunctionProtoType>();
942     if (FromFunctionPtr && ToFunctionPtr &&
943         FromFunctionPtr->hasNoexceptExceptionSpec() &&
944         !ToFunctionPtr->hasNoexceptExceptionSpec()) {
945       LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. noexcept function "
946                                  "pointer to non-noexcept.\n");
947       WorkType = QualType{ToPtr, QualifiersToApply};
948     }
949   }
950 
951   // Qualifier adjustments are modelled according to the user's request in
952   // the QualifiersMix check config.
953   LLVM_DEBUG(llvm::dbgs()
954              << "--- approximateStdConv. Trying qualifier adjustment...\n");
955   MixData QualConv = calculateMixability(Check, WorkType, To, Ctx, ICMM_None);
956   QualConv.sanitize();
957   if (hasFlag(QualConv.Flags, MixFlags::Qualifiers)) {
958     LLVM_DEBUG(llvm::dbgs()
959                << "<<< approximateStdConv. Qualifiers adjusted.\n");
960     WorkType = To;
961   }
962 
963   if (WorkType == To) {
964     LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Reached 'To' type.\n");
965     return {WorkType};
966   }
967 
968   LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Did not reach 'To'.\n");
969   return {};
970 }
971 
972 namespace {
973 
974 /// Helper class for storing possible user-defined conversion calls that
975 /// *could* take place in an implicit conversion, and selecting the one that
976 /// most likely *does*, if any.
977 class UserDefinedConversionSelector {
978 public:
979   /// The conversion associated with a conversion function, together with the
980   /// mixability flags of the conversion function's parameter or return type
981   /// to the rest of the sequence the selector is used in, and the sequence
982   /// that applied through the conversion itself.
983   struct PreparedConversion {
984     const CXXMethodDecl *ConversionFun;
985     MixFlags Flags;
986     ConversionSequence Seq;
987 
988     PreparedConversion(const CXXMethodDecl *CMD, MixFlags F,
989                        ConversionSequence S)
990         : ConversionFun(CMD), Flags(F), Seq(S) {}
991   };
992 
993   UserDefinedConversionSelector(const TheCheck &Check) : Check(Check) {}
994 
995   /// Adds the conversion between the two types for the given function into
996   /// the possible implicit conversion set. FromType and ToType is either:
997   ///   * the result of a standard sequence and a converting ctor parameter
998   ///   * the return type of a conversion operator and the expected target of
999   ///     an implicit conversion.
1000   void addConversion(const CXXMethodDecl *ConvFun, QualType FromType,
1001                      QualType ToType) {
1002     // Try to go from the FromType to the ToType wiht only a single implicit
1003     // conversion, to see if the conversion function is applicable.
1004     MixData Mix =
1005         calculateMixability(Check, FromType, ToType, ConvFun->getASTContext(),
1006                             ICMM_OneWaySingleStandardOnly);
1007     Mix.sanitize();
1008     if (!Mix.indicatesMixability())
1009       return;
1010 
1011     LLVM_DEBUG(llvm::dbgs() << "--- tryConversion. Found viable with flags: "
1012                             << formatMixFlags(Mix.Flags) << '\n');
1013     FlaggedConversions.emplace_back(ConvFun, Mix.Flags, Mix.Conversion);
1014   }
1015 
1016   /// Selects the best conversion function that is applicable from the
1017   /// prepared set of potential conversion functions taken.
1018   Optional<PreparedConversion> operator()() const {
1019     if (FlaggedConversions.empty()) {
1020       LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n");
1021       return {};
1022     }
1023     if (FlaggedConversions.size() == 1) {
1024       LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Single.\n");
1025       return FlaggedConversions.front();
1026     }
1027 
1028     Optional<PreparedConversion> BestConversion;
1029     unsigned short HowManyGoodConversions = 0;
1030     for (const auto &Prepared : FlaggedConversions) {
1031       LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Candidate flags: "
1032                               << formatMixFlags(Prepared.Flags) << '\n');
1033       if (!BestConversion) {
1034         BestConversion = Prepared;
1035         ++HowManyGoodConversions;
1036         continue;
1037       }
1038 
1039       bool BestConversionHasImplicit =
1040           hasFlag(BestConversion->Flags, MixFlags::ImplicitConversion);
1041       bool ThisConversionHasImplicit =
1042           hasFlag(Prepared.Flags, MixFlags::ImplicitConversion);
1043       if (!BestConversionHasImplicit && ThisConversionHasImplicit)
1044         // This is a worse conversion, because a better one was found earlier.
1045         continue;
1046 
1047       if (BestConversionHasImplicit && !ThisConversionHasImplicit) {
1048         // If the so far best selected conversion needs a previous implicit
1049         // conversion to match the user-defined converting function, but this
1050         // conversion does not, this is a better conversion, and we can throw
1051         // away the previously selected conversion(s).
1052         BestConversion = Prepared;
1053         HowManyGoodConversions = 1;
1054         continue;
1055       }
1056 
1057       if (BestConversionHasImplicit == ThisConversionHasImplicit)
1058         // The current conversion is the same in term of goodness than the
1059         // already selected one.
1060         ++HowManyGoodConversions;
1061     }
1062 
1063     if (HowManyGoodConversions == 1) {
1064       LLVM_DEBUG(llvm::dbgs()
1065                  << "--- selectUserDefinedConv. Unique result. Flags: "
1066                  << formatMixFlags(BestConversion->Flags) << '\n');
1067       return BestConversion;
1068     }
1069 
1070     LLVM_DEBUG(llvm::dbgs()
1071                << "--- selectUserDefinedConv. No, or ambiguous.\n");
1072     return {};
1073   }
1074 
1075 private:
1076   llvm::SmallVector<PreparedConversion, 2> FlaggedConversions;
1077   const TheCheck &Check;
1078 };
1079 
1080 } // namespace
1081 
1082 static Optional<ConversionSequence>
1083 tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
1084                        QualType ToType) {
1085   if (!RD || !RD->isCompleteDefinition())
1086     return {};
1087   RD = RD->getDefinition();
1088 
1089   LLVM_DEBUG(llvm::dbgs() << ">>> tryConversionOperators: " << RD->getName()
1090                           << " to:\n";
1091              ToType.dump(llvm::dbgs(), RD->getASTContext());
1092              llvm::dbgs() << '\n';);
1093 
1094   UserDefinedConversionSelector ConversionSet{Check};
1095 
1096   for (const NamedDecl *Method : RD->getVisibleConversionFunctions()) {
1097     const auto *Con = dyn_cast<CXXConversionDecl>(Method);
1098     if (!Con || Con->isExplicit())
1099       continue;
1100     LLVM_DEBUG(llvm::dbgs() << "--- tryConversionOperators. Trying:\n";
1101                Con->dump(llvm::dbgs()); llvm::dbgs() << '\n';);
1102 
1103     // Try to go from the result of conversion operator to the expected type,
1104     // without calculating another user-defined conversion.
1105     ConversionSet.addConversion(Con, Con->getConversionType(), ToType);
1106   }
1107 
1108   if (Optional<UserDefinedConversionSelector::PreparedConversion>
1109           SelectedConversion = ConversionSet()) {
1110     QualType RecordType{RD->getTypeForDecl(), 0};
1111 
1112     ConversionSequence Result{RecordType, ToType};
1113     // The conversion from the operator call's return type to ToType was
1114     // modelled as a "pre-conversion" in the operator call, but it is the
1115     // "post-conversion" from the point of view of the original conversion
1116     // we are modelling.
1117     Result.AfterSecondStandard = SelectedConversion->Seq.AfterFirstStandard;
1118 
1119     ConversionSequence::UserDefinedConversionOperator ConvOp;
1120     ConvOp.Fun = cast<CXXConversionDecl>(SelectedConversion->ConversionFun);
1121     ConvOp.UserDefinedType = RecordType;
1122     ConvOp.ConversionOperatorResultType = ConvOp.Fun->getConversionType();
1123     Result.setConversion(ConvOp);
1124 
1125     LLVM_DEBUG(llvm::dbgs() << "<<< tryConversionOperators. Found result.\n");
1126     return Result;
1127   }
1128 
1129   LLVM_DEBUG(llvm::dbgs() << "<<< tryConversionOperators. No conversion.\n");
1130   return {};
1131 }
1132 
1133 static Optional<ConversionSequence>
1134 tryConvertingConstructors(const TheCheck &Check, QualType FromType,
1135                           const CXXRecordDecl *RD) {
1136   if (!RD || !RD->isCompleteDefinition())
1137     return {};
1138   RD = RD->getDefinition();
1139 
1140   LLVM_DEBUG(llvm::dbgs() << ">>> tryConveringConstructors: " << RD->getName()
1141                           << " from:\n";
1142              FromType.dump(llvm::dbgs(), RD->getASTContext());
1143              llvm::dbgs() << '\n';);
1144 
1145   UserDefinedConversionSelector ConversionSet{Check};
1146 
1147   for (const CXXConstructorDecl *Con : RD->ctors()) {
1148     if (Con->isCopyOrMoveConstructor() ||
1149         !Con->isConvertingConstructor(/* AllowExplicit =*/false))
1150       continue;
1151     LLVM_DEBUG(llvm::dbgs() << "--- tryConvertingConstructors. Trying:\n";
1152                Con->dump(llvm::dbgs()); llvm::dbgs() << '\n';);
1153 
1154     // Try to go from the original FromType to the converting constructor's
1155     // parameter type without another user-defined conversion.
1156     ConversionSet.addConversion(Con, FromType, Con->getParamDecl(0)->getType());
1157   }
1158 
1159   if (Optional<UserDefinedConversionSelector::PreparedConversion>
1160           SelectedConversion = ConversionSet()) {
1161     QualType RecordType{RD->getTypeForDecl(), 0};
1162 
1163     ConversionSequence Result{FromType, RecordType};
1164     Result.AfterFirstStandard = SelectedConversion->Seq.AfterFirstStandard;
1165 
1166     ConversionSequence::UserDefinedConvertingConstructor Ctor;
1167     Ctor.Fun = cast<CXXConstructorDecl>(SelectedConversion->ConversionFun);
1168     Ctor.ConstructorParameterType = Ctor.Fun->getParamDecl(0)->getType();
1169     Ctor.UserDefinedType = RecordType;
1170     Result.setConversion(Ctor);
1171 
1172     LLVM_DEBUG(llvm::dbgs()
1173                << "<<< tryConvertingConstructors. Found result.\n");
1174     return Result;
1175   }
1176 
1177   LLVM_DEBUG(llvm::dbgs() << "<<< tryConvertingConstructors. No conversion.\n");
1178   return {};
1179 }
1180 
1181 /// Returns whether an expression of LType can be used in an RType context, as
1182 /// per the implicit conversion rules.
1183 ///
1184 /// Note: the result of this operation, unlike that of calculateMixability, is
1185 /// **NOT** symmetric.
1186 static MixData
1187 approximateImplicitConversion(const TheCheck &Check, QualType LType,
1188                               QualType RType, const ASTContext &Ctx,
1189                               ImplicitConversionModellingMode ImplicitMode) {
1190   LLVM_DEBUG(llvm::dbgs() << ">>> approximateImplicitConversion for LType:\n";
1191              LType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n";
1192              RType.dump(llvm::dbgs(), Ctx);
1193              llvm::dbgs() << "\nimplicit mode: " << ImplicitMode << '\n';);
1194   if (LType == RType)
1195     return {MixFlags::Trivial, LType};
1196 
1197   // An implicit conversion sequence consists of the following, in order:
1198   //  * Maybe standard conversion sequence.
1199   //  * Maybe user-defined conversion.
1200   //  * Maybe standard conversion sequence.
1201   ConversionSequence ImplicitSeq{LType, RType};
1202   QualType WorkType = LType;
1203 
1204   Optional<QualType> AfterFirstStdConv =
1205       approximateStandardConversionSequence(Check, LType, RType, Ctx);
1206   if (AfterFirstStdConv) {
1207     LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard "
1208                                "Pre-Conversion found!\n");
1209     ImplicitSeq.AfterFirstStandard = AfterFirstStdConv.getValue();
1210     WorkType = ImplicitSeq.AfterFirstStandard;
1211   }
1212 
1213   if (ImplicitMode == ICMM_OneWaySingleStandardOnly)
1214     // If the caller only requested modelling of a standard conversion, bail.
1215     return {ImplicitSeq.AfterFirstStandard.isNull()
1216                 ? MixFlags::None
1217                 : MixFlags::ImplicitConversion,
1218             ImplicitSeq};
1219 
1220   if (Ctx.getLangOpts().CPlusPlus) {
1221     bool FoundConversionOperator = false, FoundConvertingCtor = false;
1222 
1223     if (const auto *LRD = WorkType->getAsCXXRecordDecl()) {
1224       Optional<ConversionSequence> ConversionOperatorResult =
1225           tryConversionOperators(Check, LRD, RType);
1226       if (ConversionOperatorResult) {
1227         LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
1228                                    "conversion operator.\n");
1229         ImplicitSeq.update(ConversionOperatorResult.getValue());
1230         WorkType = ImplicitSeq.getTypeAfterUserDefinedConversion();
1231         FoundConversionOperator = true;
1232       }
1233     }
1234 
1235     if (const auto *RRD = RType->getAsCXXRecordDecl()) {
1236       // Use the original "LType" here, and not WorkType, because the
1237       // conversion to the converting constructors' parameters will be
1238       // modelled in the recursive call.
1239       Optional<ConversionSequence> ConvCtorResult =
1240           tryConvertingConstructors(Check, LType, RRD);
1241       if (ConvCtorResult) {
1242         LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
1243                                    "converting constructor.\n");
1244         ImplicitSeq.update(ConvCtorResult.getValue());
1245         WorkType = ImplicitSeq.getTypeAfterUserDefinedConversion();
1246         FoundConvertingCtor = true;
1247       }
1248     }
1249 
1250     if (FoundConversionOperator && FoundConvertingCtor) {
1251       // If both an operator and a ctor matches, the sequence is ambiguous.
1252       LLVM_DEBUG(llvm::dbgs()
1253                  << "<<< approximateImplicitConversion. Found both "
1254                     "user-defined conversion kinds in the same sequence!\n");
1255       return {MixFlags::None};
1256     }
1257   }
1258 
1259   // After the potential user-defined conversion, another standard conversion
1260   // sequence might exist.
1261   LLVM_DEBUG(
1262       llvm::dbgs()
1263       << "--- approximateImplicitConversion. Try to find post-conversion.\n");
1264   MixData SecondStdConv = approximateImplicitConversion(
1265       Check, WorkType, RType, Ctx, ICMM_OneWaySingleStandardOnly);
1266   if (SecondStdConv.indicatesMixability()) {
1267     LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard "
1268                                "Post-Conversion found!\n");
1269 
1270     // The single-step modelling puts the modelled conversion into the "PreStd"
1271     // variable in the recursive call, but from the PoV of this function, it is
1272     // the post-conversion.
1273     ImplicitSeq.AfterSecondStandard =
1274         SecondStdConv.Conversion.AfterFirstStandard;
1275     WorkType = ImplicitSeq.AfterSecondStandard;
1276   }
1277 
1278   if (ImplicitSeq) {
1279     LLVM_DEBUG(llvm::dbgs()
1280                << "<<< approximateImplicitConversion. Found a conversion.\n");
1281     return {MixFlags::ImplicitConversion, ImplicitSeq};
1282   }
1283 
1284   LLVM_DEBUG(
1285       llvm::dbgs() << "<<< approximateImplicitConversion. No match found.\n");
1286   return {MixFlags::None};
1287 }
1288 
1289 static MixableParameterRange modelMixingRange(
1290     const TheCheck &Check, const FunctionDecl *FD, std::size_t StartIndex,
1291     const filter::SimilarlyUsedParameterPairSuppressor &UsageBasedSuppressor) {
1292   std::size_t NumParams = FD->getNumParams();
1293   assert(StartIndex < NumParams && "out of bounds for start");
1294   const ASTContext &Ctx = FD->getASTContext();
1295 
1296   MixableParameterRange Ret;
1297   // A parameter at index 'StartIndex' had been trivially "checked".
1298   Ret.NumParamsChecked = 1;
1299 
1300   for (std::size_t I = StartIndex + 1; I < NumParams; ++I) {
1301     const ParmVarDecl *Ith = FD->getParamDecl(I);
1302     StringRef ParamName = Ith->getName();
1303     LLVM_DEBUG(llvm::dbgs()
1304                << "Check param #" << I << " '" << ParamName << "'...\n");
1305     if (filter::isIgnoredParameter(Check, Ith)) {
1306       LLVM_DEBUG(llvm::dbgs() << "Param #" << I << " is ignored. Break!\n");
1307       break;
1308     }
1309 
1310     StringRef PrevParamName = FD->getParamDecl(I - 1)->getName();
1311     if (!ParamName.empty() && !PrevParamName.empty() &&
1312         filter::prefixSuffixCoverUnderThreshold(
1313             Check.NamePrefixSuffixSilenceDissimilarityTreshold, PrevParamName,
1314             ParamName)) {
1315       LLVM_DEBUG(llvm::dbgs() << "Parameter '" << ParamName
1316                               << "' follows a pattern with previous parameter '"
1317                               << PrevParamName << "'. Break!\n");
1318       break;
1319     }
1320 
1321     // Now try to go forward and build the range of [Start, ..., I, I + 1, ...]
1322     // parameters that can be messed up at a call site.
1323     MixableParameterRange::MixVector MixesOfIth;
1324     for (std::size_t J = StartIndex; J < I; ++J) {
1325       const ParmVarDecl *Jth = FD->getParamDecl(J);
1326       LLVM_DEBUG(llvm::dbgs()
1327                  << "Check mix of #" << J << " against #" << I << "...\n");
1328 
1329       if (isSimilarlyUsedParameter(UsageBasedSuppressor, Ith, Jth)) {
1330         // Consider the two similarly used parameters to not be possible in a
1331         // mix-up at the user's request, if they enabled this heuristic.
1332         LLVM_DEBUG(llvm::dbgs() << "Parameters #" << I << " and #" << J
1333                                 << " deemed related, ignoring...\n");
1334 
1335         // If the parameter #I and #J mixes, then I is mixable with something
1336         // in the current range, so the range has to be broken and I not
1337         // included.
1338         MixesOfIth.clear();
1339         break;
1340       }
1341 
1342       Mix M{Jth, Ith,
1343             calculateMixability(Check, Jth->getType(), Ith->getType(), Ctx,
1344                                 Check.ModelImplicitConversions ? ICMM_All
1345                                                                : ICMM_None)};
1346       LLVM_DEBUG(llvm::dbgs() << "Mix flags (raw)           : "
1347                               << formatMixFlags(M.flags()) << '\n');
1348       M.sanitize();
1349       LLVM_DEBUG(llvm::dbgs() << "Mix flags (after sanitize): "
1350                               << formatMixFlags(M.flags()) << '\n');
1351 
1352       assert(M.flagsValid() && "All flags decayed!");
1353 
1354       if (M.mixable())
1355         MixesOfIth.emplace_back(std::move(M));
1356     }
1357 
1358     if (MixesOfIth.empty()) {
1359       // If there weren't any new mixes stored for Ith, the range is
1360       // [Start, ..., I].
1361       LLVM_DEBUG(llvm::dbgs()
1362                  << "Param #" << I
1363                  << " does not mix with any in the current range. Break!\n");
1364       break;
1365     }
1366 
1367     Ret.Mixes.insert(Ret.Mixes.end(), MixesOfIth.begin(), MixesOfIth.end());
1368     ++Ret.NumParamsChecked; // Otherwise a new param was iterated.
1369   }
1370 
1371   return Ret;
1372 }
1373 
1374 } // namespace model
1375 
1376 /// Matches DeclRefExprs and their ignorable wrappers to ParmVarDecls.
1377 AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher<Stmt>, paramRefExpr) {
1378   return expr(ignoringParenImpCasts(ignoringElidableConstructorCall(
1379       declRefExpr(to(parmVarDecl().bind("param"))))));
1380 }
1381 
1382 namespace filter {
1383 
1384 /// Returns whether the parameter's name or the parameter's type's name is
1385 /// configured by the user to be ignored from analysis and diagnostic.
1386 static bool isIgnoredParameter(const TheCheck &Check, const ParmVarDecl *Node) {
1387   LLVM_DEBUG(llvm::dbgs() << "Checking if '" << Node->getName()
1388                           << "' is ignored.\n");
1389 
1390   if (!Node->getIdentifier())
1391     return llvm::find(Check.IgnoredParameterNames, "\"\"") !=
1392            Check.IgnoredParameterNames.end();
1393 
1394   StringRef NodeName = Node->getName();
1395   if (llvm::find(Check.IgnoredParameterNames, NodeName) !=
1396       Check.IgnoredParameterNames.end()) {
1397     LLVM_DEBUG(llvm::dbgs() << "\tName ignored.\n");
1398     return true;
1399   }
1400 
1401   StringRef NodeTypeName = [Node] {
1402     const ASTContext &Ctx = Node->getASTContext();
1403     const SourceManager &SM = Ctx.getSourceManager();
1404     SourceLocation B = Node->getTypeSpecStartLoc();
1405     SourceLocation E = Node->getTypeSpecEndLoc();
1406     LangOptions LO;
1407 
1408     LLVM_DEBUG(llvm::dbgs() << "\tType name code is '"
1409                             << Lexer::getSourceText(
1410                                    CharSourceRange::getTokenRange(B, E), SM, LO)
1411                             << "'...\n");
1412     if (B.isMacroID()) {
1413       LLVM_DEBUG(llvm::dbgs() << "\t\tBeginning is macro.\n");
1414       B = SM.getTopMacroCallerLoc(B);
1415     }
1416     if (E.isMacroID()) {
1417       LLVM_DEBUG(llvm::dbgs() << "\t\tEnding is macro.\n");
1418       E = Lexer::getLocForEndOfToken(SM.getTopMacroCallerLoc(E), 0, SM, LO);
1419     }
1420     LLVM_DEBUG(llvm::dbgs() << "\tType name code is '"
1421                             << Lexer::getSourceText(
1422                                    CharSourceRange::getTokenRange(B, E), SM, LO)
1423                             << "'...\n");
1424 
1425     return Lexer::getSourceText(CharSourceRange::getTokenRange(B, E), SM, LO);
1426   }();
1427 
1428   LLVM_DEBUG(llvm::dbgs() << "\tType name is '" << NodeTypeName << "'\n");
1429   if (!NodeTypeName.empty()) {
1430     if (llvm::any_of(Check.IgnoredParameterTypeSuffixes,
1431                      [NodeTypeName](const std::string &E) {
1432                        return !E.empty() && NodeTypeName.endswith(E);
1433                      })) {
1434       LLVM_DEBUG(llvm::dbgs() << "\tType suffix ignored.\n");
1435       return true;
1436     }
1437   }
1438 
1439   return false;
1440 }
1441 
1442 /// This namespace contains the implementations for the suppression of
1443 /// diagnostics from similaly used ("related") parameters.
1444 namespace relatedness_heuristic {
1445 
1446 static constexpr std::size_t SmallDataStructureSize = 4;
1447 
1448 template <typename T, std::size_t N = SmallDataStructureSize>
1449 using ParamToSmallSetMap =
1450     llvm::DenseMap<const ParmVarDecl *, llvm::SmallSet<T, N>>;
1451 
1452 /// Returns whether the sets mapped to the two elements in the map have at
1453 /// least one element in common.
1454 template <typename MapTy, typename ElemTy>
1455 bool lazyMapOfSetsIntersectionExists(const MapTy &Map, const ElemTy &E1,
1456                                      const ElemTy &E2) {
1457   auto E1Iterator = Map.find(E1);
1458   auto E2Iterator = Map.find(E2);
1459   if (E1Iterator == Map.end() || E2Iterator == Map.end())
1460     return false;
1461 
1462   for (const auto &E1SetElem : E1Iterator->second)
1463     if (llvm::find(E2Iterator->second, E1SetElem) != E2Iterator->second.end())
1464       return true;
1465 
1466   return false;
1467 }
1468 
1469 /// Implements the heuristic that marks two parameters related if there is
1470 /// a usage for both in the same strict expression subtree. A strict
1471 /// expression subtree is a tree which only includes Expr nodes, i.e. no
1472 /// Stmts and no Decls.
1473 class AppearsInSameExpr : public RecursiveASTVisitor<AppearsInSameExpr> {
1474   using Base = RecursiveASTVisitor<AppearsInSameExpr>;
1475 
1476   const FunctionDecl *FD;
1477   const Expr *CurrentExprOnlyTreeRoot = nullptr;
1478   llvm::DenseMap<const ParmVarDecl *,
1479                  llvm::SmallPtrSet<const Expr *, SmallDataStructureSize>>
1480       ParentExprsForParamRefs;
1481 
1482 public:
1483   void setup(const FunctionDecl *FD) {
1484     this->FD = FD;
1485     TraverseFunctionDecl(const_cast<FunctionDecl *>(FD));
1486   }
1487 
1488   bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const {
1489     return lazyMapOfSetsIntersectionExists(ParentExprsForParamRefs, Param1,
1490                                            Param2);
1491   }
1492 
1493   bool TraverseDecl(Decl *D) {
1494     CurrentExprOnlyTreeRoot = nullptr;
1495     return Base::TraverseDecl(D);
1496   }
1497 
1498   bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue = nullptr) {
1499     if (auto *E = dyn_cast_or_null<Expr>(S)) {
1500       bool RootSetInCurrentStackFrame = false;
1501       if (!CurrentExprOnlyTreeRoot) {
1502         CurrentExprOnlyTreeRoot = E;
1503         RootSetInCurrentStackFrame = true;
1504       }
1505 
1506       bool Ret = Base::TraverseStmt(S);
1507 
1508       if (RootSetInCurrentStackFrame)
1509         CurrentExprOnlyTreeRoot = nullptr;
1510 
1511       return Ret;
1512     }
1513 
1514     // A Stmt breaks the strictly Expr subtree.
1515     CurrentExprOnlyTreeRoot = nullptr;
1516     return Base::TraverseStmt(S);
1517   }
1518 
1519   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1520     if (!CurrentExprOnlyTreeRoot)
1521       return true;
1522 
1523     if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1524       if (llvm::find(FD->parameters(), PVD))
1525         ParentExprsForParamRefs[PVD].insert(CurrentExprOnlyTreeRoot);
1526 
1527     return true;
1528   }
1529 };
1530 
1531 /// Implements the heuristic that marks two parameters related if there are
1532 /// two separate calls to the same function (overload) and the parameters are
1533 /// passed to the same index in both calls, i.e f(a, b) and f(a, c) passes
1534 /// b and c to the same index (2) of f(), marking them related.
1535 class PassedToSameFunction {
1536   ParamToSmallSetMap<std::pair<const FunctionDecl *, unsigned>> TargetParams;
1537 
1538 public:
1539   void setup(const FunctionDecl *FD) {
1540     auto ParamsAsArgsInFnCalls =
1541         match(functionDecl(forEachDescendant(
1542                   callExpr(forEachArgumentWithParam(
1543                                paramRefExpr(), parmVarDecl().bind("passed-to")))
1544                       .bind("call-expr"))),
1545               *FD, FD->getASTContext());
1546     for (const auto &Match : ParamsAsArgsInFnCalls) {
1547       const auto *PassedParamOfThisFn = Match.getNodeAs<ParmVarDecl>("param");
1548       const auto *CE = Match.getNodeAs<CallExpr>("call-expr");
1549       const auto *PassedToParam = Match.getNodeAs<ParmVarDecl>("passed-to");
1550       assert(PassedParamOfThisFn && CE && PassedToParam);
1551 
1552       const FunctionDecl *CalledFn = CE->getDirectCallee();
1553       if (!CalledFn)
1554         continue;
1555 
1556       llvm::Optional<unsigned> TargetIdx;
1557       unsigned NumFnParams = CalledFn->getNumParams();
1558       for (unsigned Idx = 0; Idx < NumFnParams; ++Idx)
1559         if (CalledFn->getParamDecl(Idx) == PassedToParam)
1560           TargetIdx.emplace(Idx);
1561 
1562       assert(TargetIdx.hasValue() && "Matched, but didn't find index?");
1563       TargetParams[PassedParamOfThisFn].insert(
1564           {CalledFn->getCanonicalDecl(), *TargetIdx});
1565     }
1566   }
1567 
1568   bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const {
1569     return lazyMapOfSetsIntersectionExists(TargetParams, Param1, Param2);
1570   }
1571 };
1572 
1573 /// Implements the heuristic that marks two parameters related if the same
1574 /// member is accessed (referred to) inside the current function's body.
1575 class AccessedSameMemberOf {
1576   ParamToSmallSetMap<const Decl *> AccessedMembers;
1577 
1578 public:
1579   void setup(const FunctionDecl *FD) {
1580     auto MembersCalledOnParams = match(
1581         functionDecl(forEachDescendant(
1582             memberExpr(hasObjectExpression(paramRefExpr())).bind("mem-expr"))),
1583         *FD, FD->getASTContext());
1584 
1585     for (const auto &Match : MembersCalledOnParams) {
1586       const auto *AccessedParam = Match.getNodeAs<ParmVarDecl>("param");
1587       const auto *ME = Match.getNodeAs<MemberExpr>("mem-expr");
1588       assert(AccessedParam && ME);
1589       AccessedMembers[AccessedParam].insert(
1590           ME->getMemberDecl()->getCanonicalDecl());
1591     }
1592   }
1593 
1594   bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const {
1595     return lazyMapOfSetsIntersectionExists(AccessedMembers, Param1, Param2);
1596   }
1597 };
1598 
1599 /// Implements the heuristic that marks two parameters related if different
1600 /// ReturnStmts return them from the function.
1601 class Returned {
1602   llvm::SmallVector<const ParmVarDecl *, SmallDataStructureSize> ReturnedParams;
1603 
1604 public:
1605   void setup(const FunctionDecl *FD) {
1606     // TODO: Handle co_return.
1607     auto ParamReturns = match(functionDecl(forEachDescendant(
1608                                   returnStmt(hasReturnValue(paramRefExpr())))),
1609                               *FD, FD->getASTContext());
1610     for (const auto &Match : ParamReturns) {
1611       const auto *ReturnedParam = Match.getNodeAs<ParmVarDecl>("param");
1612       assert(ReturnedParam);
1613 
1614       if (find(FD->parameters(), ReturnedParam) == FD->param_end())
1615         // Inside the subtree of a FunctionDecl there might be ReturnStmts of
1616         // a parameter that isn't the parameter of the function, e.g. in the
1617         // case of lambdas.
1618         continue;
1619 
1620       ReturnedParams.emplace_back(ReturnedParam);
1621     }
1622   }
1623 
1624   bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const {
1625     return llvm::find(ReturnedParams, Param1) != ReturnedParams.end() &&
1626            llvm::find(ReturnedParams, Param2) != ReturnedParams.end();
1627   }
1628 };
1629 
1630 } // namespace relatedness_heuristic
1631 
1632 /// Helper class that is used to detect if two parameters of the same function
1633 /// are used in a similar fashion, to suppress the result.
1634 class SimilarlyUsedParameterPairSuppressor {
1635   const bool Enabled;
1636   relatedness_heuristic::AppearsInSameExpr SameExpr;
1637   relatedness_heuristic::PassedToSameFunction PassToFun;
1638   relatedness_heuristic::AccessedSameMemberOf SameMember;
1639   relatedness_heuristic::Returned Returns;
1640 
1641 public:
1642   SimilarlyUsedParameterPairSuppressor(const FunctionDecl *FD, bool Enable)
1643       : Enabled(Enable) {
1644     if (!Enable)
1645       return;
1646 
1647     SameExpr.setup(FD);
1648     PassToFun.setup(FD);
1649     SameMember.setup(FD);
1650     Returns.setup(FD);
1651   }
1652 
1653   /// Returns whether the specified two parameters are deemed similarly used
1654   /// or related by the heuristics.
1655   bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const {
1656     if (!Enabled)
1657       return false;
1658 
1659     LLVM_DEBUG(llvm::dbgs()
1660                << "::: Matching similar usage / relatedness heuristic...\n");
1661 
1662     if (SameExpr(Param1, Param2)) {
1663       LLVM_DEBUG(llvm::dbgs() << "::: Used in the same expression.\n");
1664       return true;
1665     }
1666 
1667     if (PassToFun(Param1, Param2)) {
1668       LLVM_DEBUG(llvm::dbgs()
1669                  << "::: Passed to same function in different calls.\n");
1670       return true;
1671     }
1672 
1673     if (SameMember(Param1, Param2)) {
1674       LLVM_DEBUG(llvm::dbgs()
1675                  << "::: Same member field access or method called.\n");
1676       return true;
1677     }
1678 
1679     if (Returns(Param1, Param2)) {
1680       LLVM_DEBUG(llvm::dbgs() << "::: Both parameter returned.\n");
1681       return true;
1682     }
1683 
1684     LLVM_DEBUG(llvm::dbgs() << "::: None.\n");
1685     return false;
1686   }
1687 };
1688 
1689 // (This function hoists the call to operator() of the wrapper, so we do not
1690 // need to define the previous class at the top of the file.)
1691 static inline bool
1692 isSimilarlyUsedParameter(const SimilarlyUsedParameterPairSuppressor &Suppressor,
1693                          const ParmVarDecl *Param1, const ParmVarDecl *Param2) {
1694   return Suppressor(Param1, Param2);
1695 }
1696 
1697 static void padStringAtEnd(SmallVectorImpl<char> &Str, std::size_t ToLen) {
1698   while (Str.size() < ToLen)
1699     Str.emplace_back('\0');
1700 }
1701 
1702 static void padStringAtBegin(SmallVectorImpl<char> &Str, std::size_t ToLen) {
1703   while (Str.size() < ToLen)
1704     Str.insert(Str.begin(), '\0');
1705 }
1706 
1707 static bool isCommonPrefixWithoutSomeCharacters(std::size_t N, StringRef S1,
1708                                                 StringRef S2) {
1709   assert(S1.size() >= N && S2.size() >= N);
1710   StringRef S1Prefix = S1.take_front(S1.size() - N),
1711             S2Prefix = S2.take_front(S2.size() - N);
1712   return S1Prefix == S2Prefix && !S1Prefix.empty();
1713 }
1714 
1715 static bool isCommonSuffixWithoutSomeCharacters(std::size_t N, StringRef S1,
1716                                                 StringRef S2) {
1717   assert(S1.size() >= N && S2.size() >= N);
1718   StringRef S1Suffix = S1.take_back(S1.size() - N),
1719             S2Suffix = S2.take_back(S2.size() - N);
1720   return S1Suffix == S2Suffix && !S1Suffix.empty();
1721 }
1722 
1723 /// Returns whether the two strings are prefixes or suffixes of each other with
1724 /// at most Threshold characters differing on the non-common end.
1725 static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold,
1726                                             StringRef Str1, StringRef Str2) {
1727   if (Threshold == 0)
1728     return false;
1729 
1730   // Pad the two strings to the longer length.
1731   std::size_t BiggerLength = std::max(Str1.size(), Str2.size());
1732 
1733   if (BiggerLength <= Threshold)
1734     // If the length of the strings is still smaller than the threshold, they
1735     // would be covered by an empty prefix/suffix with the rest differing.
1736     // (E.g. "A" and "X" with Threshold = 1 would mean we think they are
1737     // similar and do not warn about them, which is a too eager assumption.)
1738     return false;
1739 
1740   SmallString<32> S1PadE{Str1}, S2PadE{Str2};
1741   padStringAtEnd(S1PadE, BiggerLength);
1742   padStringAtEnd(S2PadE, BiggerLength);
1743 
1744   if (isCommonPrefixWithoutSomeCharacters(
1745           Threshold, StringRef{S1PadE.begin(), BiggerLength},
1746           StringRef{S2PadE.begin(), BiggerLength}))
1747     return true;
1748 
1749   SmallString<32> S1PadB{Str1}, S2PadB{Str2};
1750   padStringAtBegin(S1PadB, BiggerLength);
1751   padStringAtBegin(S2PadB, BiggerLength);
1752 
1753   if (isCommonSuffixWithoutSomeCharacters(
1754           Threshold, StringRef{S1PadB.begin(), BiggerLength},
1755           StringRef{S2PadB.begin(), BiggerLength}))
1756     return true;
1757 
1758   return false;
1759 }
1760 
1761 } // namespace filter
1762 
1763 /// Matches functions that have at least the specified amount of parameters.
1764 AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N) {
1765   return Node.getNumParams() >= N;
1766 }
1767 
1768 /// Matches *any* overloaded unary and binary operators.
1769 AST_MATCHER(FunctionDecl, isOverloadedUnaryOrBinaryOperator) {
1770   switch (Node.getOverloadedOperator()) {
1771   case OO_None:
1772   case OO_New:
1773   case OO_Delete:
1774   case OO_Array_New:
1775   case OO_Array_Delete:
1776   case OO_Conditional:
1777   case OO_Coawait:
1778     return false;
1779 
1780   default:
1781     return Node.getNumParams() <= 2;
1782   }
1783 }
1784 
1785 /// Returns the DefaultMinimumLength if the Value of requested minimum length
1786 /// is less than 2. Minimum lengths of 0 or 1 are not accepted.
1787 static inline unsigned clampMinimumLength(const unsigned Value) {
1788   return Value < 2 ? DefaultMinimumLength : Value;
1789 }
1790 
1791 // FIXME: Maybe unneeded, getNameForDiagnostic() is expected to change to return
1792 // a crafted location when the node itself is unnamed. (See D84658, D85033.)
1793 /// Returns the diagnostic-friendly name of the node, or empty string.
1794 static SmallString<64> getName(const NamedDecl *ND) {
1795   SmallString<64> Name;
1796   llvm::raw_svector_ostream OS{Name};
1797   ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), false);
1798   return Name;
1799 }
1800 
1801 /// Returns the diagnostic-friendly name of the node, or a constant value.
1802 static SmallString<64> getNameOrUnnamed(const NamedDecl *ND) {
1803   auto Name = getName(ND);
1804   if (Name.empty())
1805     Name = "<unnamed>";
1806   return Name;
1807 }
1808 
1809 /// Returns whether a particular Mix between two parameters should have the
1810 /// types involved diagnosed to the user. This is only a flag check.
1811 static inline bool needsToPrintTypeInDiagnostic(const model::Mix &M) {
1812   using namespace model;
1813   return static_cast<bool>(
1814       M.flags() &
1815       (MixFlags::TypeAlias | MixFlags::ReferenceBind | MixFlags::Qualifiers));
1816 }
1817 
1818 /// Returns whether a particular Mix between the two parameters should have
1819 /// implicit conversions elaborated.
1820 static inline bool needsToElaborateImplicitConversion(const model::Mix &M) {
1821   return hasFlag(M.flags(), model::MixFlags::ImplicitConversion);
1822 }
1823 
1824 namespace {
1825 
1826 /// This class formats a conversion sequence into a "Ty1 -> Ty2 -> Ty3" line
1827 /// that can be used in diagnostics.
1828 struct FormattedConversionSequence {
1829   std::string DiagnosticText;
1830 
1831   /// The formatted sequence is trivial if it is "Ty1 -> Ty2", but Ty1 and
1832   /// Ty2 are the types that are shown in the code. A trivial diagnostic
1833   /// does not need to be printed.
1834   bool Trivial;
1835 
1836   FormattedConversionSequence(const PrintingPolicy &PP,
1837                               StringRef StartTypeAsDiagnosed,
1838                               const model::ConversionSequence &Conv,
1839                               StringRef DestinationTypeAsDiagnosed) {
1840     Trivial = true;
1841     llvm::raw_string_ostream OS{DiagnosticText};
1842 
1843     // Print the type name as it is printed in other places in the diagnostic.
1844     OS << '\'' << StartTypeAsDiagnosed << '\'';
1845     std::string LastAddedType = StartTypeAsDiagnosed.str();
1846     std::size_t NumElementsAdded = 1;
1847 
1848     // However, the parameter's defined type might not be what the implicit
1849     // conversion started with, e.g. if a typedef is found to convert.
1850     std::string SeqBeginTypeStr = Conv.Begin.getAsString(PP);
1851     std::string SeqEndTypeStr = Conv.End.getAsString(PP);
1852     if (StartTypeAsDiagnosed != SeqBeginTypeStr) {
1853       OS << " (as '" << SeqBeginTypeStr << "')";
1854       LastAddedType = SeqBeginTypeStr;
1855       Trivial = false;
1856     }
1857 
1858     auto AddType = [&](StringRef ToAdd) {
1859       if (LastAddedType != ToAdd && ToAdd != SeqEndTypeStr) {
1860         OS << " -> '" << ToAdd << "'";
1861         LastAddedType = ToAdd.str();
1862         ++NumElementsAdded;
1863       }
1864     };
1865     for (QualType InvolvedType : Conv.getInvolvedTypesInSequence())
1866       // Print every type that's unique in the sequence into the diagnosis.
1867       AddType(InvolvedType.getAsString(PP));
1868 
1869     if (LastAddedType != DestinationTypeAsDiagnosed) {
1870       OS << " -> '" << DestinationTypeAsDiagnosed << "'";
1871       LastAddedType = DestinationTypeAsDiagnosed.str();
1872       ++NumElementsAdded;
1873     }
1874 
1875     // Same reasoning as with the Begin, e.g. if the converted-to type is a
1876     // typedef, it will not be the same inside the conversion sequence (where
1877     // the model already tore off typedefs) as in the code.
1878     if (DestinationTypeAsDiagnosed != SeqEndTypeStr) {
1879       OS << " (as '" << SeqEndTypeStr << "')";
1880       LastAddedType = SeqEndTypeStr;
1881       Trivial = false;
1882     }
1883 
1884     if (Trivial && NumElementsAdded > 2)
1885       // If the thing is still marked trivial but we have more than the
1886       // from and to types added, it should not be trivial, and elaborated
1887       // when printing the diagnostic.
1888       Trivial = false;
1889   }
1890 };
1891 
1892 /// Retains the elements called with and returns whether the call is done with
1893 /// a new element.
1894 template <typename E, std::size_t N> class InsertOnce {
1895   llvm::SmallSet<E, N> CalledWith;
1896 
1897 public:
1898   bool operator()(E El) { return CalledWith.insert(std::move(El)).second; }
1899 
1900   bool calledWith(const E &El) const { return CalledWith.contains(El); }
1901 };
1902 
1903 struct SwappedEqualQualTypePair {
1904   QualType LHSType, RHSType;
1905 
1906   bool operator==(const SwappedEqualQualTypePair &Other) const {
1907     return (LHSType == Other.LHSType && RHSType == Other.RHSType) ||
1908            (LHSType == Other.RHSType && RHSType == Other.LHSType);
1909   }
1910 
1911   bool operator<(const SwappedEqualQualTypePair &Other) const {
1912     return LHSType < Other.LHSType && RHSType < Other.RHSType;
1913   }
1914 };
1915 
1916 struct TypeAliasDiagnosticTuple {
1917   QualType LHSType, RHSType, CommonType;
1918 
1919   bool operator==(const TypeAliasDiagnosticTuple &Other) const {
1920     return CommonType == Other.CommonType &&
1921            ((LHSType == Other.LHSType && RHSType == Other.RHSType) ||
1922             (LHSType == Other.RHSType && RHSType == Other.LHSType));
1923   }
1924 
1925   bool operator<(const TypeAliasDiagnosticTuple &Other) const {
1926     return CommonType < Other.CommonType && LHSType < Other.LHSType &&
1927            RHSType < Other.RHSType;
1928   }
1929 };
1930 
1931 /// Helper class to only emit a diagnostic related to MixFlags::TypeAlias once.
1932 class UniqueTypeAliasDiagnosticHelper
1933     : public InsertOnce<TypeAliasDiagnosticTuple, 8> {
1934   using Base = InsertOnce<TypeAliasDiagnosticTuple, 8>;
1935 
1936 public:
1937   /// Returns whether the diagnostic for LHSType and RHSType which are both
1938   /// referring to CommonType being the same has not been emitted already.
1939   bool operator()(QualType LHSType, QualType RHSType, QualType CommonType) {
1940     if (CommonType.isNull() || CommonType == LHSType || CommonType == RHSType)
1941       return Base::operator()({LHSType, RHSType, {}});
1942 
1943     TypeAliasDiagnosticTuple ThreeTuple{LHSType, RHSType, CommonType};
1944     if (!Base::operator()(ThreeTuple))
1945       return false;
1946 
1947     bool AlreadySaidLHSAndCommonIsSame = calledWith({LHSType, CommonType, {}});
1948     bool AlreadySaidRHSAndCommonIsSame = calledWith({RHSType, CommonType, {}});
1949     if (AlreadySaidLHSAndCommonIsSame && AlreadySaidRHSAndCommonIsSame) {
1950       // "SomeInt == int" && "SomeOtherInt == int" => "Common(SomeInt,
1951       // SomeOtherInt) == int", no need to diagnose it. Save the 3-tuple only
1952       // for shortcut if it ever appears again.
1953       return false;
1954     }
1955 
1956     return true;
1957   }
1958 };
1959 
1960 } // namespace
1961 
1962 EasilySwappableParametersCheck::EasilySwappableParametersCheck(
1963     StringRef Name, ClangTidyContext *Context)
1964     : ClangTidyCheck(Name, Context),
1965       MinimumLength(clampMinimumLength(
1966           Options.get("MinimumLength", DefaultMinimumLength))),
1967       IgnoredParameterNames(optutils::parseStringList(
1968           Options.get("IgnoredParameterNames", DefaultIgnoredParameterNames))),
1969       IgnoredParameterTypeSuffixes(optutils::parseStringList(
1970           Options.get("IgnoredParameterTypeSuffixes",
1971                       DefaultIgnoredParameterTypeSuffixes))),
1972       QualifiersMix(Options.get("QualifiersMix", DefaultQualifiersMix)),
1973       ModelImplicitConversions(Options.get("ModelImplicitConversions",
1974                                            DefaultModelImplicitConversions)),
1975       SuppressParametersUsedTogether(
1976           Options.get("SuppressParametersUsedTogether",
1977                       DefaultSuppressParametersUsedTogether)),
1978       NamePrefixSuffixSilenceDissimilarityTreshold(
1979           Options.get("NamePrefixSuffixSilenceDissimilarityTreshold",
1980                       DefaultNamePrefixSuffixSilenceDissimilarityTreshold)) {}
1981 
1982 void EasilySwappableParametersCheck::storeOptions(
1983     ClangTidyOptions::OptionMap &Opts) {
1984   Options.store(Opts, "MinimumLength", MinimumLength);
1985   Options.store(Opts, "IgnoredParameterNames",
1986                 optutils::serializeStringList(IgnoredParameterNames));
1987   Options.store(Opts, "IgnoredParameterTypeSuffixes",
1988                 optutils::serializeStringList(IgnoredParameterTypeSuffixes));
1989   Options.store(Opts, "QualifiersMix", QualifiersMix);
1990   Options.store(Opts, "ModelImplicitConversions", ModelImplicitConversions);
1991   Options.store(Opts, "SuppressParametersUsedTogether",
1992                 SuppressParametersUsedTogether);
1993   Options.store(Opts, "NamePrefixSuffixSilenceDissimilarityTreshold",
1994                 NamePrefixSuffixSilenceDissimilarityTreshold);
1995 }
1996 
1997 void EasilySwappableParametersCheck::registerMatchers(MatchFinder *Finder) {
1998   const auto BaseConstraints = functionDecl(
1999       // Only report for definition nodes, as fixing the issues reported
2000       // requires the user to be able to change code.
2001       isDefinition(), parameterCountGE(MinimumLength),
2002       unless(isOverloadedUnaryOrBinaryOperator()));
2003 
2004   Finder->addMatcher(
2005       functionDecl(BaseConstraints,
2006                    unless(ast_matchers::isTemplateInstantiation()))
2007           .bind("func"),
2008       this);
2009   Finder->addMatcher(
2010       functionDecl(BaseConstraints, isExplicitTemplateSpecialization())
2011           .bind("func"),
2012       this);
2013 }
2014 
2015 void EasilySwappableParametersCheck::check(
2016     const MatchFinder::MatchResult &Result) {
2017   using namespace model;
2018   using namespace filter;
2019 
2020   const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
2021   assert(FD);
2022 
2023   const PrintingPolicy &PP = FD->getASTContext().getPrintingPolicy();
2024   std::size_t NumParams = FD->getNumParams();
2025   std::size_t MixableRangeStartIndex = 0;
2026 
2027   // Spawn one suppressor and if the user requested, gather information from
2028   // the AST for the parameters' usages.
2029   filter::SimilarlyUsedParameterPairSuppressor UsageBasedSuppressor{
2030       FD, SuppressParametersUsedTogether};
2031 
2032   LLVM_DEBUG(llvm::dbgs() << "Begin analysis of " << getName(FD) << " with "
2033                           << NumParams << " parameters...\n");
2034   while (MixableRangeStartIndex < NumParams) {
2035     if (isIgnoredParameter(*this, FD->getParamDecl(MixableRangeStartIndex))) {
2036       LLVM_DEBUG(llvm::dbgs()
2037                  << "Parameter #" << MixableRangeStartIndex << " ignored.\n");
2038       ++MixableRangeStartIndex;
2039       continue;
2040     }
2041 
2042     MixableParameterRange R = modelMixingRange(
2043         *this, FD, MixableRangeStartIndex, UsageBasedSuppressor);
2044     assert(R.NumParamsChecked > 0 && "Ensure forward progress!");
2045     MixableRangeStartIndex += R.NumParamsChecked;
2046     if (R.NumParamsChecked < MinimumLength) {
2047       LLVM_DEBUG(llvm::dbgs() << "Ignoring range of " << R.NumParamsChecked
2048                               << " lower than limit.\n");
2049       continue;
2050     }
2051 
2052     bool NeedsAnyTypeNote = llvm::any_of(R.Mixes, needsToPrintTypeInDiagnostic);
2053     bool HasAnyImplicits =
2054         llvm::any_of(R.Mixes, needsToElaborateImplicitConversion);
2055     const ParmVarDecl *First = R.getFirstParam(), *Last = R.getLastParam();
2056     std::string FirstParamTypeAsWritten = First->getType().getAsString(PP);
2057     {
2058       StringRef DiagText;
2059 
2060       if (HasAnyImplicits)
2061         DiagText = "%0 adjacent parameters of %1 of convertible types are "
2062                    "easily swapped by mistake";
2063       else if (NeedsAnyTypeNote)
2064         DiagText = "%0 adjacent parameters of %1 of similar type are easily "
2065                    "swapped by mistake";
2066       else
2067         DiagText = "%0 adjacent parameters of %1 of similar type ('%2') are "
2068                    "easily swapped by mistake";
2069 
2070       auto Diag = diag(First->getOuterLocStart(), DiagText)
2071                   << static_cast<unsigned>(R.NumParamsChecked) << FD;
2072       if (!NeedsAnyTypeNote)
2073         Diag << FirstParamTypeAsWritten;
2074 
2075       CharSourceRange HighlightRange = CharSourceRange::getTokenRange(
2076           First->getBeginLoc(), Last->getEndLoc());
2077       Diag << HighlightRange;
2078     }
2079 
2080     // There is a chance that the previous highlight did not succeed, e.g. when
2081     // the two parameters are on different lines. For clarity, show the user
2082     // the involved variable explicitly.
2083     diag(First->getLocation(), "the first parameter in the range is '%0'",
2084          DiagnosticIDs::Note)
2085         << getNameOrUnnamed(First)
2086         << CharSourceRange::getTokenRange(First->getLocation(),
2087                                           First->getLocation());
2088     diag(Last->getLocation(), "the last parameter in the range is '%0'",
2089          DiagnosticIDs::Note)
2090         << getNameOrUnnamed(Last)
2091         << CharSourceRange::getTokenRange(Last->getLocation(),
2092                                           Last->getLocation());
2093 
2094     // Helper classes to silence elaborative diagnostic notes that would be
2095     // too verbose.
2096     UniqueTypeAliasDiagnosticHelper UniqueTypeAlias;
2097     InsertOnce<SwappedEqualQualTypePair, 8> UniqueBindPower;
2098     InsertOnce<SwappedEqualQualTypePair, 8> UniqueImplicitConversion;
2099 
2100     for (const model::Mix &M : R.Mixes) {
2101       assert(M.mixable() && "Sentinel or false mix in result.");
2102       if (!needsToPrintTypeInDiagnostic(M) &&
2103           !needsToElaborateImplicitConversion(M))
2104         continue;
2105 
2106       // Typedefs might result in the type of the variable needing to be
2107       // emitted to a note diagnostic, so prepare it.
2108       const ParmVarDecl *LVar = M.First;
2109       const ParmVarDecl *RVar = M.Second;
2110       QualType LType = LVar->getType();
2111       QualType RType = RVar->getType();
2112       QualType CommonType = M.commonUnderlyingType();
2113       std::string LTypeStr = LType.getAsString(PP);
2114       std::string RTypeStr = RType.getAsString(PP);
2115       std::string CommonTypeStr = CommonType.getAsString(PP);
2116 
2117       if (hasFlag(M.flags(), MixFlags::TypeAlias) &&
2118           UniqueTypeAlias(LType, RType, CommonType)) {
2119         StringRef DiagText;
2120         bool ExplicitlyPrintCommonType = false;
2121         if (LTypeStr == CommonTypeStr || RTypeStr == CommonTypeStr)
2122           if (hasFlag(M.flags(), MixFlags::Qualifiers))
2123             DiagText = "after resolving type aliases, '%0' and '%1' share a "
2124                        "common type";
2125           else
2126             DiagText =
2127                 "after resolving type aliases, '%0' and '%1' are the same";
2128         else if (!CommonType.isNull()) {
2129           DiagText = "after resolving type aliases, the common type of '%0' "
2130                      "and '%1' is '%2'";
2131           ExplicitlyPrintCommonType = true;
2132         }
2133 
2134         auto Diag =
2135             diag(LVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note)
2136             << LTypeStr << RTypeStr;
2137         if (ExplicitlyPrintCommonType)
2138           Diag << CommonTypeStr;
2139       }
2140 
2141       if ((hasFlag(M.flags(), MixFlags::ReferenceBind) ||
2142            hasFlag(M.flags(), MixFlags::Qualifiers)) &&
2143           UniqueBindPower({LType, RType})) {
2144         StringRef DiagText = "'%0' and '%1' parameters accept and bind the "
2145                              "same kind of values";
2146         diag(RVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note)
2147             << LTypeStr << RTypeStr;
2148       }
2149 
2150       if (needsToElaborateImplicitConversion(M) &&
2151           UniqueImplicitConversion({LType, RType})) {
2152         const model::ConversionSequence &LTR =
2153             M.leftToRightConversionSequence();
2154         const model::ConversionSequence &RTL =
2155             M.rightToLeftConversionSequence();
2156         FormattedConversionSequence LTRFmt{PP, LTypeStr, LTR, RTypeStr};
2157         FormattedConversionSequence RTLFmt{PP, RTypeStr, RTL, LTypeStr};
2158 
2159         StringRef DiagText = "'%0' and '%1' may be implicitly converted";
2160         if (!LTRFmt.Trivial || !RTLFmt.Trivial)
2161           DiagText = "'%0' and '%1' may be implicitly converted: %2, %3";
2162 
2163         {
2164           auto Diag =
2165               diag(RVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note)
2166               << LTypeStr << RTypeStr;
2167 
2168           if (!LTRFmt.Trivial || !RTLFmt.Trivial)
2169             Diag << LTRFmt.DiagnosticText << RTLFmt.DiagnosticText;
2170         }
2171 
2172         StringRef ConversionFunctionDiagText =
2173             "the implicit conversion involves the "
2174             "%select{|converting constructor|conversion operator}0 "
2175             "declared here";
2176         if (const FunctionDecl *LFD = LTR.getUserDefinedConversionFunction())
2177           diag(LFD->getLocation(), ConversionFunctionDiagText,
2178                DiagnosticIDs::Note)
2179               << static_cast<unsigned>(LTR.UDConvKind)
2180               << LTR.getUserDefinedConversionHighlight();
2181         if (const FunctionDecl *RFD = RTL.getUserDefinedConversionFunction())
2182           diag(RFD->getLocation(), ConversionFunctionDiagText,
2183                DiagnosticIDs::Note)
2184               << static_cast<unsigned>(RTL.UDConvKind)
2185               << RTL.getUserDefinedConversionHighlight();
2186       }
2187     }
2188   }
2189 }
2190 
2191 } // namespace bugprone
2192 } // namespace tidy
2193 } // namespace clang
2194