File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaOverload.cpp |
Warning: | line 9861, column 44 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// | |||
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 | // This file provides Sema routines for C++ overloading. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "clang/AST/ASTContext.h" | |||
14 | #include "clang/AST/CXXInheritance.h" | |||
15 | #include "clang/AST/DeclObjC.h" | |||
16 | #include "clang/AST/DependenceFlags.h" | |||
17 | #include "clang/AST/Expr.h" | |||
18 | #include "clang/AST/ExprCXX.h" | |||
19 | #include "clang/AST/ExprObjC.h" | |||
20 | #include "clang/AST/TypeOrdering.h" | |||
21 | #include "clang/Basic/Diagnostic.h" | |||
22 | #include "clang/Basic/DiagnosticOptions.h" | |||
23 | #include "clang/Basic/PartialDiagnostic.h" | |||
24 | #include "clang/Basic/SourceManager.h" | |||
25 | #include "clang/Basic/TargetInfo.h" | |||
26 | #include "clang/Sema/Initialization.h" | |||
27 | #include "clang/Sema/Lookup.h" | |||
28 | #include "clang/Sema/Overload.h" | |||
29 | #include "clang/Sema/SemaInternal.h" | |||
30 | #include "clang/Sema/Template.h" | |||
31 | #include "clang/Sema/TemplateDeduction.h" | |||
32 | #include "llvm/ADT/DenseSet.h" | |||
33 | #include "llvm/ADT/Optional.h" | |||
34 | #include "llvm/ADT/STLExtras.h" | |||
35 | #include "llvm/ADT/SmallPtrSet.h" | |||
36 | #include "llvm/ADT/SmallString.h" | |||
37 | #include <algorithm> | |||
38 | #include <cstdlib> | |||
39 | ||||
40 | using namespace clang; | |||
41 | using namespace sema; | |||
42 | ||||
43 | using AllowedExplicit = Sema::AllowedExplicit; | |||
44 | ||||
45 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { | |||
46 | return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { | |||
47 | return P->hasAttr<PassObjectSizeAttr>(); | |||
48 | }); | |||
49 | } | |||
50 | ||||
51 | /// A convenience routine for creating a decayed reference to a function. | |||
52 | static ExprResult CreateFunctionRefExpr( | |||
53 | Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, | |||
54 | bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), | |||
55 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { | |||
56 | if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) | |||
57 | return ExprError(); | |||
58 | // If FoundDecl is different from Fn (such as if one is a template | |||
59 | // and the other a specialization), make sure DiagnoseUseOfDecl is | |||
60 | // called on both. | |||
61 | // FIXME: This would be more comprehensively addressed by modifying | |||
62 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl | |||
63 | // being used. | |||
64 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) | |||
65 | return ExprError(); | |||
66 | DeclRefExpr *DRE = new (S.Context) | |||
67 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); | |||
68 | if (HadMultipleCandidates) | |||
69 | DRE->setHadMultipleCandidates(true); | |||
70 | ||||
71 | S.MarkDeclRefReferenced(DRE, Base); | |||
72 | if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { | |||
73 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { | |||
74 | S.ResolveExceptionSpec(Loc, FPT); | |||
75 | DRE->setType(Fn->getType()); | |||
76 | } | |||
77 | } | |||
78 | return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), | |||
79 | CK_FunctionToPointerDecay); | |||
80 | } | |||
81 | ||||
82 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, | |||
83 | bool InOverloadResolution, | |||
84 | StandardConversionSequence &SCS, | |||
85 | bool CStyle, | |||
86 | bool AllowObjCWritebackConversion); | |||
87 | ||||
88 | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, | |||
89 | QualType &ToType, | |||
90 | bool InOverloadResolution, | |||
91 | StandardConversionSequence &SCS, | |||
92 | bool CStyle); | |||
93 | static OverloadingResult | |||
94 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
95 | UserDefinedConversionSequence& User, | |||
96 | OverloadCandidateSet& Conversions, | |||
97 | AllowedExplicit AllowExplicit, | |||
98 | bool AllowObjCConversionOnExplicit); | |||
99 | ||||
100 | static ImplicitConversionSequence::CompareKind | |||
101 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, | |||
102 | const StandardConversionSequence& SCS1, | |||
103 | const StandardConversionSequence& SCS2); | |||
104 | ||||
105 | static ImplicitConversionSequence::CompareKind | |||
106 | CompareQualificationConversions(Sema &S, | |||
107 | const StandardConversionSequence& SCS1, | |||
108 | const StandardConversionSequence& SCS2); | |||
109 | ||||
110 | static ImplicitConversionSequence::CompareKind | |||
111 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, | |||
112 | const StandardConversionSequence& SCS1, | |||
113 | const StandardConversionSequence& SCS2); | |||
114 | ||||
115 | /// GetConversionRank - Retrieve the implicit conversion rank | |||
116 | /// corresponding to the given implicit conversion kind. | |||
117 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { | |||
118 | static const ImplicitConversionRank | |||
119 | Rank[(int)ICK_Num_Conversion_Kinds] = { | |||
120 | ICR_Exact_Match, | |||
121 | ICR_Exact_Match, | |||
122 | ICR_Exact_Match, | |||
123 | ICR_Exact_Match, | |||
124 | ICR_Exact_Match, | |||
125 | ICR_Exact_Match, | |||
126 | ICR_Promotion, | |||
127 | ICR_Promotion, | |||
128 | ICR_Promotion, | |||
129 | ICR_Conversion, | |||
130 | ICR_Conversion, | |||
131 | ICR_Conversion, | |||
132 | ICR_Conversion, | |||
133 | ICR_Conversion, | |||
134 | ICR_Conversion, | |||
135 | ICR_Conversion, | |||
136 | ICR_Conversion, | |||
137 | ICR_Conversion, | |||
138 | ICR_Conversion, | |||
139 | ICR_Conversion, | |||
140 | ICR_OCL_Scalar_Widening, | |||
141 | ICR_Complex_Real_Conversion, | |||
142 | ICR_Conversion, | |||
143 | ICR_Conversion, | |||
144 | ICR_Writeback_Conversion, | |||
145 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- | |||
146 | // it was omitted by the patch that added | |||
147 | // ICK_Zero_Event_Conversion | |||
148 | ICR_C_Conversion, | |||
149 | ICR_C_Conversion_Extension | |||
150 | }; | |||
151 | return Rank[(int)Kind]; | |||
152 | } | |||
153 | ||||
154 | /// GetImplicitConversionName - Return the name of this kind of | |||
155 | /// implicit conversion. | |||
156 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { | |||
157 | static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { | |||
158 | "No conversion", | |||
159 | "Lvalue-to-rvalue", | |||
160 | "Array-to-pointer", | |||
161 | "Function-to-pointer", | |||
162 | "Function pointer conversion", | |||
163 | "Qualification", | |||
164 | "Integral promotion", | |||
165 | "Floating point promotion", | |||
166 | "Complex promotion", | |||
167 | "Integral conversion", | |||
168 | "Floating conversion", | |||
169 | "Complex conversion", | |||
170 | "Floating-integral conversion", | |||
171 | "Pointer conversion", | |||
172 | "Pointer-to-member conversion", | |||
173 | "Boolean conversion", | |||
174 | "Compatible-types conversion", | |||
175 | "Derived-to-base conversion", | |||
176 | "Vector conversion", | |||
177 | "SVE Vector conversion", | |||
178 | "Vector splat", | |||
179 | "Complex-real conversion", | |||
180 | "Block Pointer conversion", | |||
181 | "Transparent Union Conversion", | |||
182 | "Writeback conversion", | |||
183 | "OpenCL Zero Event Conversion", | |||
184 | "C specific type conversion", | |||
185 | "Incompatible pointer conversion" | |||
186 | }; | |||
187 | return Name[Kind]; | |||
188 | } | |||
189 | ||||
190 | /// StandardConversionSequence - Set the standard conversion | |||
191 | /// sequence to the identity conversion. | |||
192 | void StandardConversionSequence::setAsIdentityConversion() { | |||
193 | First = ICK_Identity; | |||
194 | Second = ICK_Identity; | |||
195 | Third = ICK_Identity; | |||
196 | DeprecatedStringLiteralToCharPtr = false; | |||
197 | QualificationIncludesObjCLifetime = false; | |||
198 | ReferenceBinding = false; | |||
199 | DirectBinding = false; | |||
200 | IsLvalueReference = true; | |||
201 | BindsToFunctionLvalue = false; | |||
202 | BindsToRvalue = false; | |||
203 | BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
204 | ObjCLifetimeConversionBinding = false; | |||
205 | CopyConstructor = nullptr; | |||
206 | } | |||
207 | ||||
208 | /// getRank - Retrieve the rank of this standard conversion sequence | |||
209 | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the | |||
210 | /// implicit conversions. | |||
211 | ImplicitConversionRank StandardConversionSequence::getRank() const { | |||
212 | ImplicitConversionRank Rank = ICR_Exact_Match; | |||
213 | if (GetConversionRank(First) > Rank) | |||
214 | Rank = GetConversionRank(First); | |||
215 | if (GetConversionRank(Second) > Rank) | |||
216 | Rank = GetConversionRank(Second); | |||
217 | if (GetConversionRank(Third) > Rank) | |||
218 | Rank = GetConversionRank(Third); | |||
219 | return Rank; | |||
220 | } | |||
221 | ||||
222 | /// isPointerConversionToBool - Determines whether this conversion is | |||
223 | /// a conversion of a pointer or pointer-to-member to bool. This is | |||
224 | /// used as part of the ranking of standard conversion sequences | |||
225 | /// (C++ 13.3.3.2p4). | |||
226 | bool StandardConversionSequence::isPointerConversionToBool() const { | |||
227 | // Note that FromType has not necessarily been transformed by the | |||
228 | // array-to-pointer or function-to-pointer implicit conversions, so | |||
229 | // check for their presence as well as checking whether FromType is | |||
230 | // a pointer. | |||
231 | if (getToType(1)->isBooleanType() && | |||
232 | (getFromType()->isPointerType() || | |||
233 | getFromType()->isMemberPointerType() || | |||
234 | getFromType()->isObjCObjectPointerType() || | |||
235 | getFromType()->isBlockPointerType() || | |||
236 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) | |||
237 | return true; | |||
238 | ||||
239 | return false; | |||
240 | } | |||
241 | ||||
242 | /// isPointerConversionToVoidPointer - Determines whether this | |||
243 | /// conversion is a conversion of a pointer to a void pointer. This is | |||
244 | /// used as part of the ranking of standard conversion sequences (C++ | |||
245 | /// 13.3.3.2p4). | |||
246 | bool | |||
247 | StandardConversionSequence:: | |||
248 | isPointerConversionToVoidPointer(ASTContext& Context) const { | |||
249 | QualType FromType = getFromType(); | |||
250 | QualType ToType = getToType(1); | |||
251 | ||||
252 | // Note that FromType has not necessarily been transformed by the | |||
253 | // array-to-pointer implicit conversion, so check for its presence | |||
254 | // and redo the conversion to get a pointer. | |||
255 | if (First == ICK_Array_To_Pointer) | |||
256 | FromType = Context.getArrayDecayedType(FromType); | |||
257 | ||||
258 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) | |||
259 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) | |||
260 | return ToPtrType->getPointeeType()->isVoidType(); | |||
261 | ||||
262 | return false; | |||
263 | } | |||
264 | ||||
265 | /// Skip any implicit casts which could be either part of a narrowing conversion | |||
266 | /// or after one in an implicit conversion. | |||
267 | static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, | |||
268 | const Expr *Converted) { | |||
269 | // We can have cleanups wrapping the converted expression; these need to be | |||
270 | // preserved so that destructors run if necessary. | |||
271 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { | |||
272 | Expr *Inner = | |||
273 | const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); | |||
274 | return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), | |||
275 | EWC->getObjects()); | |||
276 | } | |||
277 | ||||
278 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { | |||
279 | switch (ICE->getCastKind()) { | |||
280 | case CK_NoOp: | |||
281 | case CK_IntegralCast: | |||
282 | case CK_IntegralToBoolean: | |||
283 | case CK_IntegralToFloating: | |||
284 | case CK_BooleanToSignedIntegral: | |||
285 | case CK_FloatingToIntegral: | |||
286 | case CK_FloatingToBoolean: | |||
287 | case CK_FloatingCast: | |||
288 | Converted = ICE->getSubExpr(); | |||
289 | continue; | |||
290 | ||||
291 | default: | |||
292 | return Converted; | |||
293 | } | |||
294 | } | |||
295 | ||||
296 | return Converted; | |||
297 | } | |||
298 | ||||
299 | /// Check if this standard conversion sequence represents a narrowing | |||
300 | /// conversion, according to C++11 [dcl.init.list]p7. | |||
301 | /// | |||
302 | /// \param Ctx The AST context. | |||
303 | /// \param Converted The result of applying this standard conversion sequence. | |||
304 | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the | |||
305 | /// value of the expression prior to the narrowing conversion. | |||
306 | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the | |||
307 | /// type of the expression prior to the narrowing conversion. | |||
308 | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions | |||
309 | /// from floating point types to integral types should be ignored. | |||
310 | NarrowingKind StandardConversionSequence::getNarrowingKind( | |||
311 | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, | |||
312 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { | |||
313 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\"" , "clang/lib/Sema/SemaOverload.cpp", 313, __extension__ __PRETTY_FUNCTION__ )); | |||
314 | ||||
315 | // C++11 [dcl.init.list]p7: | |||
316 | // A narrowing conversion is an implicit conversion ... | |||
317 | QualType FromType = getToType(0); | |||
318 | QualType ToType = getToType(1); | |||
319 | ||||
320 | // A conversion to an enumeration type is narrowing if the conversion to | |||
321 | // the underlying type is narrowing. This only arises for expressions of | |||
322 | // the form 'Enum{init}'. | |||
323 | if (auto *ET = ToType->getAs<EnumType>()) | |||
324 | ToType = ET->getDecl()->getIntegerType(); | |||
325 | ||||
326 | switch (Second) { | |||
327 | // 'bool' is an integral type; dispatch to the right place to handle it. | |||
328 | case ICK_Boolean_Conversion: | |||
329 | if (FromType->isRealFloatingType()) | |||
330 | goto FloatingIntegralConversion; | |||
331 | if (FromType->isIntegralOrUnscopedEnumerationType()) | |||
332 | goto IntegralConversion; | |||
333 | // -- from a pointer type or pointer-to-member type to bool, or | |||
334 | return NK_Type_Narrowing; | |||
335 | ||||
336 | // -- from a floating-point type to an integer type, or | |||
337 | // | |||
338 | // -- from an integer type or unscoped enumeration type to a floating-point | |||
339 | // type, except where the source is a constant expression and the actual | |||
340 | // value after conversion will fit into the target type and will produce | |||
341 | // the original value when converted back to the original type, or | |||
342 | case ICK_Floating_Integral: | |||
343 | FloatingIntegralConversion: | |||
344 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { | |||
345 | return NK_Type_Narrowing; | |||
346 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && | |||
347 | ToType->isRealFloatingType()) { | |||
348 | if (IgnoreFloatToIntegralConversion) | |||
349 | return NK_Not_Narrowing; | |||
350 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); | |||
351 | assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression" ) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\"" , "clang/lib/Sema/SemaOverload.cpp", 351, __extension__ __PRETTY_FUNCTION__ )); | |||
352 | ||||
353 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
354 | if (Initializer->isValueDependent()) | |||
355 | return NK_Dependent_Narrowing; | |||
356 | ||||
357 | if (Optional<llvm::APSInt> IntConstantValue = | |||
358 | Initializer->getIntegerConstantExpr(Ctx)) { | |||
359 | // Convert the integer to the floating type. | |||
360 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); | |||
361 | Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), | |||
362 | llvm::APFloat::rmNearestTiesToEven); | |||
363 | // And back. | |||
364 | llvm::APSInt ConvertedValue = *IntConstantValue; | |||
365 | bool ignored; | |||
366 | Result.convertToInteger(ConvertedValue, | |||
367 | llvm::APFloat::rmTowardZero, &ignored); | |||
368 | // If the resulting value is different, this was a narrowing conversion. | |||
369 | if (*IntConstantValue != ConvertedValue) { | |||
370 | ConstantValue = APValue(*IntConstantValue); | |||
371 | ConstantType = Initializer->getType(); | |||
372 | return NK_Constant_Narrowing; | |||
373 | } | |||
374 | } else { | |||
375 | // Variables are always narrowings. | |||
376 | return NK_Variable_Narrowing; | |||
377 | } | |||
378 | } | |||
379 | return NK_Not_Narrowing; | |||
380 | ||||
381 | // -- from long double to double or float, or from double to float, except | |||
382 | // where the source is a constant expression and the actual value after | |||
383 | // conversion is within the range of values that can be represented (even | |||
384 | // if it cannot be represented exactly), or | |||
385 | case ICK_Floating_Conversion: | |||
386 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && | |||
387 | Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { | |||
388 | // FromType is larger than ToType. | |||
389 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); | |||
390 | ||||
391 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
392 | if (Initializer->isValueDependent()) | |||
393 | return NK_Dependent_Narrowing; | |||
394 | ||||
395 | if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { | |||
396 | // Constant! | |||
397 | assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0 ) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp" , 397, __extension__ __PRETTY_FUNCTION__)); | |||
398 | llvm::APFloat FloatVal = ConstantValue.getFloat(); | |||
399 | // Convert the source value into the target type. | |||
400 | bool ignored; | |||
401 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( | |||
402 | Ctx.getFloatTypeSemantics(ToType), | |||
403 | llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
404 | // If there was no overflow, the source value is within the range of | |||
405 | // values that can be represented. | |||
406 | if (ConvertStatus & llvm::APFloat::opOverflow) { | |||
407 | ConstantType = Initializer->getType(); | |||
408 | return NK_Constant_Narrowing; | |||
409 | } | |||
410 | } else { | |||
411 | return NK_Variable_Narrowing; | |||
412 | } | |||
413 | } | |||
414 | return NK_Not_Narrowing; | |||
415 | ||||
416 | // -- from an integer type or unscoped enumeration type to an integer type | |||
417 | // that cannot represent all the values of the original type, except where | |||
418 | // the source is a constant expression and the actual value after | |||
419 | // conversion will fit into the target type and will produce the original | |||
420 | // value when converted back to the original type. | |||
421 | case ICK_Integral_Conversion: | |||
422 | IntegralConversion: { | |||
423 | assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType ()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()" , "clang/lib/Sema/SemaOverload.cpp", 423, __extension__ __PRETTY_FUNCTION__ )); | |||
424 | assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType ()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()" , "clang/lib/Sema/SemaOverload.cpp", 424, __extension__ __PRETTY_FUNCTION__ )); | |||
425 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); | |||
426 | const unsigned FromWidth = Ctx.getIntWidth(FromType); | |||
427 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); | |||
428 | const unsigned ToWidth = Ctx.getIntWidth(ToType); | |||
429 | ||||
430 | if (FromWidth > ToWidth || | |||
431 | (FromWidth == ToWidth && FromSigned != ToSigned) || | |||
432 | (FromSigned && !ToSigned)) { | |||
433 | // Not all values of FromType can be represented in ToType. | |||
434 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); | |||
435 | ||||
436 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
437 | if (Initializer->isValueDependent()) | |||
438 | return NK_Dependent_Narrowing; | |||
439 | ||||
440 | Optional<llvm::APSInt> OptInitializerValue; | |||
441 | if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { | |||
442 | // Such conversions on variables are always narrowing. | |||
443 | return NK_Variable_Narrowing; | |||
444 | } | |||
445 | llvm::APSInt &InitializerValue = *OptInitializerValue; | |||
446 | bool Narrowing = false; | |||
447 | if (FromWidth < ToWidth) { | |||
448 | // Negative -> unsigned is narrowing. Otherwise, more bits is never | |||
449 | // narrowing. | |||
450 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) | |||
451 | Narrowing = true; | |||
452 | } else { | |||
453 | // Add a bit to the InitializerValue so we don't have to worry about | |||
454 | // signed vs. unsigned comparisons. | |||
455 | InitializerValue = InitializerValue.extend( | |||
456 | InitializerValue.getBitWidth() + 1); | |||
457 | // Convert the initializer to and from the target width and signed-ness. | |||
458 | llvm::APSInt ConvertedValue = InitializerValue; | |||
459 | ConvertedValue = ConvertedValue.trunc(ToWidth); | |||
460 | ConvertedValue.setIsSigned(ToSigned); | |||
461 | ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); | |||
462 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); | |||
463 | // If the result is different, this was a narrowing conversion. | |||
464 | if (ConvertedValue != InitializerValue) | |||
465 | Narrowing = true; | |||
466 | } | |||
467 | if (Narrowing) { | |||
468 | ConstantType = Initializer->getType(); | |||
469 | ConstantValue = APValue(InitializerValue); | |||
470 | return NK_Constant_Narrowing; | |||
471 | } | |||
472 | } | |||
473 | return NK_Not_Narrowing; | |||
474 | } | |||
475 | ||||
476 | default: | |||
477 | // Other kinds of conversions are not narrowings. | |||
478 | return NK_Not_Narrowing; | |||
479 | } | |||
480 | } | |||
481 | ||||
482 | /// dump - Print this standard conversion sequence to standard | |||
483 | /// error. Useful for debugging overloading issues. | |||
484 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const { | |||
485 | raw_ostream &OS = llvm::errs(); | |||
486 | bool PrintedSomething = false; | |||
487 | if (First != ICK_Identity) { | |||
488 | OS << GetImplicitConversionName(First); | |||
489 | PrintedSomething = true; | |||
490 | } | |||
491 | ||||
492 | if (Second != ICK_Identity) { | |||
493 | if (PrintedSomething) { | |||
494 | OS << " -> "; | |||
495 | } | |||
496 | OS << GetImplicitConversionName(Second); | |||
497 | ||||
498 | if (CopyConstructor) { | |||
499 | OS << " (by copy constructor)"; | |||
500 | } else if (DirectBinding) { | |||
501 | OS << " (direct reference binding)"; | |||
502 | } else if (ReferenceBinding) { | |||
503 | OS << " (reference binding)"; | |||
504 | } | |||
505 | PrintedSomething = true; | |||
506 | } | |||
507 | ||||
508 | if (Third != ICK_Identity) { | |||
509 | if (PrintedSomething) { | |||
510 | OS << " -> "; | |||
511 | } | |||
512 | OS << GetImplicitConversionName(Third); | |||
513 | PrintedSomething = true; | |||
514 | } | |||
515 | ||||
516 | if (!PrintedSomething) { | |||
517 | OS << "No conversions required"; | |||
518 | } | |||
519 | } | |||
520 | ||||
521 | /// dump - Print this user-defined conversion sequence to standard | |||
522 | /// error. Useful for debugging overloading issues. | |||
523 | void UserDefinedConversionSequence::dump() const { | |||
524 | raw_ostream &OS = llvm::errs(); | |||
525 | if (Before.First || Before.Second || Before.Third) { | |||
526 | Before.dump(); | |||
527 | OS << " -> "; | |||
528 | } | |||
529 | if (ConversionFunction) | |||
530 | OS << '\'' << *ConversionFunction << '\''; | |||
531 | else | |||
532 | OS << "aggregate initialization"; | |||
533 | if (After.First || After.Second || After.Third) { | |||
534 | OS << " -> "; | |||
535 | After.dump(); | |||
536 | } | |||
537 | } | |||
538 | ||||
539 | /// dump - Print this implicit conversion sequence to standard | |||
540 | /// error. Useful for debugging overloading issues. | |||
541 | void ImplicitConversionSequence::dump() const { | |||
542 | raw_ostream &OS = llvm::errs(); | |||
543 | if (hasInitializerListContainerType()) | |||
544 | OS << "Worst list element conversion: "; | |||
545 | switch (ConversionKind) { | |||
546 | case StandardConversion: | |||
547 | OS << "Standard conversion: "; | |||
548 | Standard.dump(); | |||
549 | break; | |||
550 | case UserDefinedConversion: | |||
551 | OS << "User-defined conversion: "; | |||
552 | UserDefined.dump(); | |||
553 | break; | |||
554 | case EllipsisConversion: | |||
555 | OS << "Ellipsis conversion"; | |||
556 | break; | |||
557 | case AmbiguousConversion: | |||
558 | OS << "Ambiguous conversion"; | |||
559 | break; | |||
560 | case BadConversion: | |||
561 | OS << "Bad conversion"; | |||
562 | break; | |||
563 | } | |||
564 | ||||
565 | OS << "\n"; | |||
566 | } | |||
567 | ||||
568 | void AmbiguousConversionSequence::construct() { | |||
569 | new (&conversions()) ConversionSet(); | |||
570 | } | |||
571 | ||||
572 | void AmbiguousConversionSequence::destruct() { | |||
573 | conversions().~ConversionSet(); | |||
574 | } | |||
575 | ||||
576 | void | |||
577 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { | |||
578 | FromTypePtr = O.FromTypePtr; | |||
579 | ToTypePtr = O.ToTypePtr; | |||
580 | new (&conversions()) ConversionSet(O.conversions()); | |||
581 | } | |||
582 | ||||
583 | namespace { | |||
584 | // Structure used by DeductionFailureInfo to store | |||
585 | // template argument information. | |||
586 | struct DFIArguments { | |||
587 | TemplateArgument FirstArg; | |||
588 | TemplateArgument SecondArg; | |||
589 | }; | |||
590 | // Structure used by DeductionFailureInfo to store | |||
591 | // template parameter and template argument information. | |||
592 | struct DFIParamWithArguments : DFIArguments { | |||
593 | TemplateParameter Param; | |||
594 | }; | |||
595 | // Structure used by DeductionFailureInfo to store template argument | |||
596 | // information and the index of the problematic call argument. | |||
597 | struct DFIDeducedMismatchArgs : DFIArguments { | |||
598 | TemplateArgumentList *TemplateArgs; | |||
599 | unsigned CallArgIndex; | |||
600 | }; | |||
601 | // Structure used by DeductionFailureInfo to store information about | |||
602 | // unsatisfied constraints. | |||
603 | struct CNSInfo { | |||
604 | TemplateArgumentList *TemplateArgs; | |||
605 | ConstraintSatisfaction Satisfaction; | |||
606 | }; | |||
607 | } | |||
608 | ||||
609 | /// Convert from Sema's representation of template deduction information | |||
610 | /// to the form used in overload-candidate information. | |||
611 | DeductionFailureInfo | |||
612 | clang::MakeDeductionFailureInfo(ASTContext &Context, | |||
613 | Sema::TemplateDeductionResult TDK, | |||
614 | TemplateDeductionInfo &Info) { | |||
615 | DeductionFailureInfo Result; | |||
616 | Result.Result = static_cast<unsigned>(TDK); | |||
617 | Result.HasDiagnostic = false; | |||
618 | switch (TDK) { | |||
619 | case Sema::TDK_Invalid: | |||
620 | case Sema::TDK_InstantiationDepth: | |||
621 | case Sema::TDK_TooManyArguments: | |||
622 | case Sema::TDK_TooFewArguments: | |||
623 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
624 | case Sema::TDK_CUDATargetMismatch: | |||
625 | Result.Data = nullptr; | |||
626 | break; | |||
627 | ||||
628 | case Sema::TDK_Incomplete: | |||
629 | case Sema::TDK_InvalidExplicitArguments: | |||
630 | Result.Data = Info.Param.getOpaqueValue(); | |||
631 | break; | |||
632 | ||||
633 | case Sema::TDK_DeducedMismatch: | |||
634 | case Sema::TDK_DeducedMismatchNested: { | |||
635 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
636 | auto *Saved = new (Context) DFIDeducedMismatchArgs; | |||
637 | Saved->FirstArg = Info.FirstArg; | |||
638 | Saved->SecondArg = Info.SecondArg; | |||
639 | Saved->TemplateArgs = Info.take(); | |||
640 | Saved->CallArgIndex = Info.CallArgIndex; | |||
641 | Result.Data = Saved; | |||
642 | break; | |||
643 | } | |||
644 | ||||
645 | case Sema::TDK_NonDeducedMismatch: { | |||
646 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
647 | DFIArguments *Saved = new (Context) DFIArguments; | |||
648 | Saved->FirstArg = Info.FirstArg; | |||
649 | Saved->SecondArg = Info.SecondArg; | |||
650 | Result.Data = Saved; | |||
651 | break; | |||
652 | } | |||
653 | ||||
654 | case Sema::TDK_IncompletePack: | |||
655 | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. | |||
656 | case Sema::TDK_Inconsistent: | |||
657 | case Sema::TDK_Underqualified: { | |||
658 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
659 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; | |||
660 | Saved->Param = Info.Param; | |||
661 | Saved->FirstArg = Info.FirstArg; | |||
662 | Saved->SecondArg = Info.SecondArg; | |||
663 | Result.Data = Saved; | |||
664 | break; | |||
665 | } | |||
666 | ||||
667 | case Sema::TDK_SubstitutionFailure: | |||
668 | Result.Data = Info.take(); | |||
669 | if (Info.hasSFINAEDiagnostic()) { | |||
670 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( | |||
671 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); | |||
672 | Info.takeSFINAEDiagnostic(*Diag); | |||
673 | Result.HasDiagnostic = true; | |||
674 | } | |||
675 | break; | |||
676 | ||||
677 | case Sema::TDK_ConstraintsNotSatisfied: { | |||
678 | CNSInfo *Saved = new (Context) CNSInfo; | |||
679 | Saved->TemplateArgs = Info.take(); | |||
680 | Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; | |||
681 | Result.Data = Saved; | |||
682 | break; | |||
683 | } | |||
684 | ||||
685 | case Sema::TDK_Success: | |||
686 | case Sema::TDK_NonDependentConversionFailure: | |||
687 | llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "clang/lib/Sema/SemaOverload.cpp" , 687); | |||
688 | } | |||
689 | ||||
690 | return Result; | |||
691 | } | |||
692 | ||||
693 | void DeductionFailureInfo::Destroy() { | |||
694 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
695 | case Sema::TDK_Success: | |||
696 | case Sema::TDK_Invalid: | |||
697 | case Sema::TDK_InstantiationDepth: | |||
698 | case Sema::TDK_Incomplete: | |||
699 | case Sema::TDK_TooManyArguments: | |||
700 | case Sema::TDK_TooFewArguments: | |||
701 | case Sema::TDK_InvalidExplicitArguments: | |||
702 | case Sema::TDK_CUDATargetMismatch: | |||
703 | case Sema::TDK_NonDependentConversionFailure: | |||
704 | break; | |||
705 | ||||
706 | case Sema::TDK_IncompletePack: | |||
707 | case Sema::TDK_Inconsistent: | |||
708 | case Sema::TDK_Underqualified: | |||
709 | case Sema::TDK_DeducedMismatch: | |||
710 | case Sema::TDK_DeducedMismatchNested: | |||
711 | case Sema::TDK_NonDeducedMismatch: | |||
712 | // FIXME: Destroy the data? | |||
713 | Data = nullptr; | |||
714 | break; | |||
715 | ||||
716 | case Sema::TDK_SubstitutionFailure: | |||
717 | // FIXME: Destroy the template argument list? | |||
718 | Data = nullptr; | |||
719 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { | |||
720 | Diag->~PartialDiagnosticAt(); | |||
721 | HasDiagnostic = false; | |||
722 | } | |||
723 | break; | |||
724 | ||||
725 | case Sema::TDK_ConstraintsNotSatisfied: | |||
726 | // FIXME: Destroy the template argument list? | |||
727 | Data = nullptr; | |||
728 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { | |||
729 | Diag->~PartialDiagnosticAt(); | |||
730 | HasDiagnostic = false; | |||
731 | } | |||
732 | break; | |||
733 | ||||
734 | // Unhandled | |||
735 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
736 | break; | |||
737 | } | |||
738 | } | |||
739 | ||||
740 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { | |||
741 | if (HasDiagnostic) | |||
742 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); | |||
743 | return nullptr; | |||
744 | } | |||
745 | ||||
746 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { | |||
747 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
748 | case Sema::TDK_Success: | |||
749 | case Sema::TDK_Invalid: | |||
750 | case Sema::TDK_InstantiationDepth: | |||
751 | case Sema::TDK_TooManyArguments: | |||
752 | case Sema::TDK_TooFewArguments: | |||
753 | case Sema::TDK_SubstitutionFailure: | |||
754 | case Sema::TDK_DeducedMismatch: | |||
755 | case Sema::TDK_DeducedMismatchNested: | |||
756 | case Sema::TDK_NonDeducedMismatch: | |||
757 | case Sema::TDK_CUDATargetMismatch: | |||
758 | case Sema::TDK_NonDependentConversionFailure: | |||
759 | case Sema::TDK_ConstraintsNotSatisfied: | |||
760 | return TemplateParameter(); | |||
761 | ||||
762 | case Sema::TDK_Incomplete: | |||
763 | case Sema::TDK_InvalidExplicitArguments: | |||
764 | return TemplateParameter::getFromOpaqueValue(Data); | |||
765 | ||||
766 | case Sema::TDK_IncompletePack: | |||
767 | case Sema::TDK_Inconsistent: | |||
768 | case Sema::TDK_Underqualified: | |||
769 | return static_cast<DFIParamWithArguments*>(Data)->Param; | |||
770 | ||||
771 | // Unhandled | |||
772 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
773 | break; | |||
774 | } | |||
775 | ||||
776 | return TemplateParameter(); | |||
777 | } | |||
778 | ||||
779 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { | |||
780 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
781 | case Sema::TDK_Success: | |||
782 | case Sema::TDK_Invalid: | |||
783 | case Sema::TDK_InstantiationDepth: | |||
784 | case Sema::TDK_TooManyArguments: | |||
785 | case Sema::TDK_TooFewArguments: | |||
786 | case Sema::TDK_Incomplete: | |||
787 | case Sema::TDK_IncompletePack: | |||
788 | case Sema::TDK_InvalidExplicitArguments: | |||
789 | case Sema::TDK_Inconsistent: | |||
790 | case Sema::TDK_Underqualified: | |||
791 | case Sema::TDK_NonDeducedMismatch: | |||
792 | case Sema::TDK_CUDATargetMismatch: | |||
793 | case Sema::TDK_NonDependentConversionFailure: | |||
794 | return nullptr; | |||
795 | ||||
796 | case Sema::TDK_DeducedMismatch: | |||
797 | case Sema::TDK_DeducedMismatchNested: | |||
798 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; | |||
799 | ||||
800 | case Sema::TDK_SubstitutionFailure: | |||
801 | return static_cast<TemplateArgumentList*>(Data); | |||
802 | ||||
803 | case Sema::TDK_ConstraintsNotSatisfied: | |||
804 | return static_cast<CNSInfo*>(Data)->TemplateArgs; | |||
805 | ||||
806 | // Unhandled | |||
807 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
808 | break; | |||
809 | } | |||
810 | ||||
811 | return nullptr; | |||
812 | } | |||
813 | ||||
814 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { | |||
815 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
816 | case Sema::TDK_Success: | |||
817 | case Sema::TDK_Invalid: | |||
818 | case Sema::TDK_InstantiationDepth: | |||
819 | case Sema::TDK_Incomplete: | |||
820 | case Sema::TDK_TooManyArguments: | |||
821 | case Sema::TDK_TooFewArguments: | |||
822 | case Sema::TDK_InvalidExplicitArguments: | |||
823 | case Sema::TDK_SubstitutionFailure: | |||
824 | case Sema::TDK_CUDATargetMismatch: | |||
825 | case Sema::TDK_NonDependentConversionFailure: | |||
826 | case Sema::TDK_ConstraintsNotSatisfied: | |||
827 | return nullptr; | |||
828 | ||||
829 | case Sema::TDK_IncompletePack: | |||
830 | case Sema::TDK_Inconsistent: | |||
831 | case Sema::TDK_Underqualified: | |||
832 | case Sema::TDK_DeducedMismatch: | |||
833 | case Sema::TDK_DeducedMismatchNested: | |||
834 | case Sema::TDK_NonDeducedMismatch: | |||
835 | return &static_cast<DFIArguments*>(Data)->FirstArg; | |||
836 | ||||
837 | // Unhandled | |||
838 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
839 | break; | |||
840 | } | |||
841 | ||||
842 | return nullptr; | |||
843 | } | |||
844 | ||||
845 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { | |||
846 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
847 | case Sema::TDK_Success: | |||
848 | case Sema::TDK_Invalid: | |||
849 | case Sema::TDK_InstantiationDepth: | |||
850 | case Sema::TDK_Incomplete: | |||
851 | case Sema::TDK_IncompletePack: | |||
852 | case Sema::TDK_TooManyArguments: | |||
853 | case Sema::TDK_TooFewArguments: | |||
854 | case Sema::TDK_InvalidExplicitArguments: | |||
855 | case Sema::TDK_SubstitutionFailure: | |||
856 | case Sema::TDK_CUDATargetMismatch: | |||
857 | case Sema::TDK_NonDependentConversionFailure: | |||
858 | case Sema::TDK_ConstraintsNotSatisfied: | |||
859 | return nullptr; | |||
860 | ||||
861 | case Sema::TDK_Inconsistent: | |||
862 | case Sema::TDK_Underqualified: | |||
863 | case Sema::TDK_DeducedMismatch: | |||
864 | case Sema::TDK_DeducedMismatchNested: | |||
865 | case Sema::TDK_NonDeducedMismatch: | |||
866 | return &static_cast<DFIArguments*>(Data)->SecondArg; | |||
867 | ||||
868 | // Unhandled | |||
869 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
870 | break; | |||
871 | } | |||
872 | ||||
873 | return nullptr; | |||
874 | } | |||
875 | ||||
876 | llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { | |||
877 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
878 | case Sema::TDK_DeducedMismatch: | |||
879 | case Sema::TDK_DeducedMismatchNested: | |||
880 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; | |||
881 | ||||
882 | default: | |||
883 | return llvm::None; | |||
884 | } | |||
885 | } | |||
886 | ||||
887 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( | |||
888 | OverloadedOperatorKind Op) { | |||
889 | if (!AllowRewrittenCandidates) | |||
890 | return false; | |||
891 | return Op == OO_EqualEqual || Op == OO_Spaceship; | |||
892 | } | |||
893 | ||||
894 | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( | |||
895 | ASTContext &Ctx, const FunctionDecl *FD) { | |||
896 | if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) | |||
897 | return false; | |||
898 | // Don't bother adding a reversed candidate that can never be a better | |||
899 | // match than the non-reversed version. | |||
900 | return FD->getNumParams() != 2 || | |||
901 | !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), | |||
902 | FD->getParamDecl(1)->getType()) || | |||
903 | FD->hasAttr<EnableIfAttr>(); | |||
904 | } | |||
905 | ||||
906 | void OverloadCandidateSet::destroyCandidates() { | |||
907 | for (iterator i = begin(), e = end(); i != e; ++i) { | |||
908 | for (auto &C : i->Conversions) | |||
909 | C.~ImplicitConversionSequence(); | |||
910 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) | |||
911 | i->DeductionFailure.Destroy(); | |||
912 | } | |||
913 | } | |||
914 | ||||
915 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { | |||
916 | destroyCandidates(); | |||
917 | SlabAllocator.Reset(); | |||
918 | NumInlineBytesUsed = 0; | |||
919 | Candidates.clear(); | |||
920 | Functions.clear(); | |||
921 | Kind = CSK; | |||
922 | } | |||
923 | ||||
924 | namespace { | |||
925 | class UnbridgedCastsSet { | |||
926 | struct Entry { | |||
927 | Expr **Addr; | |||
928 | Expr *Saved; | |||
929 | }; | |||
930 | SmallVector<Entry, 2> Entries; | |||
931 | ||||
932 | public: | |||
933 | void save(Sema &S, Expr *&E) { | |||
934 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType ::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)" , "clang/lib/Sema/SemaOverload.cpp", 934, __extension__ __PRETTY_FUNCTION__ )); | |||
935 | Entry entry = { &E, E }; | |||
936 | Entries.push_back(entry); | |||
937 | E = S.stripARCUnbridgedCast(E); | |||
938 | } | |||
939 | ||||
940 | void restore() { | |||
941 | for (SmallVectorImpl<Entry>::iterator | |||
942 | i = Entries.begin(), e = Entries.end(); i != e; ++i) | |||
943 | *i->Addr = i->Saved; | |||
944 | } | |||
945 | }; | |||
946 | } | |||
947 | ||||
948 | /// checkPlaceholderForOverload - Do any interesting placeholder-like | |||
949 | /// preprocessing on the given expression. | |||
950 | /// | |||
951 | /// \param unbridgedCasts a collection to which to add unbridged casts; | |||
952 | /// without this, they will be immediately diagnosed as errors | |||
953 | /// | |||
954 | /// Return true on unrecoverable error. | |||
955 | static bool | |||
956 | checkPlaceholderForOverload(Sema &S, Expr *&E, | |||
957 | UnbridgedCastsSet *unbridgedCasts = nullptr) { | |||
958 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { | |||
959 | // We can't handle overloaded expressions here because overload | |||
960 | // resolution might reasonably tweak them. | |||
961 | if (placeholder->getKind() == BuiltinType::Overload) return false; | |||
962 | ||||
963 | // If the context potentially accepts unbridged ARC casts, strip | |||
964 | // the unbridged cast and add it to the collection for later restoration. | |||
965 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && | |||
966 | unbridgedCasts) { | |||
967 | unbridgedCasts->save(S, E); | |||
968 | return false; | |||
969 | } | |||
970 | ||||
971 | // Go ahead and check everything else. | |||
972 | ExprResult result = S.CheckPlaceholderExpr(E); | |||
973 | if (result.isInvalid()) | |||
974 | return true; | |||
975 | ||||
976 | E = result.get(); | |||
977 | return false; | |||
978 | } | |||
979 | ||||
980 | // Nothing to do. | |||
981 | return false; | |||
982 | } | |||
983 | ||||
984 | /// checkArgPlaceholdersForOverload - Check a set of call operands for | |||
985 | /// placeholders. | |||
986 | static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, | |||
987 | UnbridgedCastsSet &unbridged) { | |||
988 | for (unsigned i = 0, e = Args.size(); i != e; ++i) | |||
989 | if (checkPlaceholderForOverload(S, Args[i], &unbridged)) | |||
990 | return true; | |||
991 | ||||
992 | return false; | |||
993 | } | |||
994 | ||||
995 | /// Determine whether the given New declaration is an overload of the | |||
996 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if | |||
997 | /// New and Old cannot be overloaded, e.g., if New has the same signature as | |||
998 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't | |||
999 | /// functions (or function templates) at all. When it does return Ovl_Match or | |||
1000 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be | |||
1001 | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying | |||
1002 | /// declaration. | |||
1003 | /// | |||
1004 | /// Example: Given the following input: | |||
1005 | /// | |||
1006 | /// void f(int, float); // #1 | |||
1007 | /// void f(int, int); // #2 | |||
1008 | /// int f(int, int); // #3 | |||
1009 | /// | |||
1010 | /// When we process #1, there is no previous declaration of "f", so IsOverload | |||
1011 | /// will not be used. | |||
1012 | /// | |||
1013 | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing | |||
1014 | /// the parameter types, we see that #1 and #2 are overloaded (since they have | |||
1015 | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is | |||
1016 | /// unchanged. | |||
1017 | /// | |||
1018 | /// When we process #3, Old is an overload set containing #1 and #2. We compare | |||
1019 | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then | |||
1020 | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of | |||
1021 | /// functions are not part of the signature), IsOverload returns Ovl_Match and | |||
1022 | /// MatchedDecl will be set to point to the FunctionDecl for #2. | |||
1023 | /// | |||
1024 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class | |||
1025 | /// by a using declaration. The rules for whether to hide shadow declarations | |||
1026 | /// ignore some properties which otherwise figure into a function template's | |||
1027 | /// signature. | |||
1028 | Sema::OverloadKind | |||
1029 | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, | |||
1030 | NamedDecl *&Match, bool NewIsUsingDecl) { | |||
1031 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); | |||
1032 | I != E; ++I) { | |||
1033 | NamedDecl *OldD = *I; | |||
1034 | ||||
1035 | bool OldIsUsingDecl = false; | |||
1036 | if (isa<UsingShadowDecl>(OldD)) { | |||
1037 | OldIsUsingDecl = true; | |||
1038 | ||||
1039 | // We can always introduce two using declarations into the same | |||
1040 | // context, even if they have identical signatures. | |||
1041 | if (NewIsUsingDecl) continue; | |||
1042 | ||||
1043 | OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); | |||
1044 | } | |||
1045 | ||||
1046 | // A using-declaration does not conflict with another declaration | |||
1047 | // if one of them is hidden. | |||
1048 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) | |||
1049 | continue; | |||
1050 | ||||
1051 | // If either declaration was introduced by a using declaration, | |||
1052 | // we'll need to use slightly different rules for matching. | |||
1053 | // Essentially, these rules are the normal rules, except that | |||
1054 | // function templates hide function templates with different | |||
1055 | // return types or template parameter lists. | |||
1056 | bool UseMemberUsingDeclRules = | |||
1057 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && | |||
1058 | !New->getFriendObjectKind(); | |||
1059 | ||||
1060 | if (FunctionDecl *OldF = OldD->getAsFunction()) { | |||
1061 | if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { | |||
1062 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { | |||
1063 | HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); | |||
1064 | continue; | |||
1065 | } | |||
1066 | ||||
1067 | if (!isa<FunctionTemplateDecl>(OldD) && | |||
1068 | !shouldLinkPossiblyHiddenDecl(*I, New)) | |||
1069 | continue; | |||
1070 | ||||
1071 | Match = *I; | |||
1072 | return Ovl_Match; | |||
1073 | } | |||
1074 | ||||
1075 | // Builtins that have custom typechecking or have a reference should | |||
1076 | // not be overloadable or redeclarable. | |||
1077 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { | |||
1078 | Match = *I; | |||
1079 | return Ovl_NonFunction; | |||
1080 | } | |||
1081 | } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { | |||
1082 | // We can overload with these, which can show up when doing | |||
1083 | // redeclaration checks for UsingDecls. | |||
1084 | assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName ) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName" , "clang/lib/Sema/SemaOverload.cpp", 1084, __extension__ __PRETTY_FUNCTION__ )); | |||
1085 | } else if (isa<TagDecl>(OldD)) { | |||
1086 | // We can always overload with tags by hiding them. | |||
1087 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { | |||
1088 | // Optimistically assume that an unresolved using decl will | |||
1089 | // overload; if it doesn't, we'll have to diagnose during | |||
1090 | // template instantiation. | |||
1091 | // | |||
1092 | // Exception: if the scope is dependent and this is not a class | |||
1093 | // member, the using declaration can only introduce an enumerator. | |||
1094 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { | |||
1095 | Match = *I; | |||
1096 | return Ovl_NonFunction; | |||
1097 | } | |||
1098 | } else { | |||
1099 | // (C++ 13p1): | |||
1100 | // Only function declarations can be overloaded; object and type | |||
1101 | // declarations cannot be overloaded. | |||
1102 | Match = *I; | |||
1103 | return Ovl_NonFunction; | |||
1104 | } | |||
1105 | } | |||
1106 | ||||
1107 | // C++ [temp.friend]p1: | |||
1108 | // For a friend function declaration that is not a template declaration: | |||
1109 | // -- if the name of the friend is a qualified or unqualified template-id, | |||
1110 | // [...], otherwise | |||
1111 | // -- if the name of the friend is a qualified-id and a matching | |||
1112 | // non-template function is found in the specified class or namespace, | |||
1113 | // the friend declaration refers to that function, otherwise, | |||
1114 | // -- if the name of the friend is a qualified-id and a matching function | |||
1115 | // template is found in the specified class or namespace, the friend | |||
1116 | // declaration refers to the deduced specialization of that function | |||
1117 | // template, otherwise | |||
1118 | // -- the name shall be an unqualified-id [...] | |||
1119 | // If we get here for a qualified friend declaration, we've just reached the | |||
1120 | // third bullet. If the type of the friend is dependent, skip this lookup | |||
1121 | // until instantiation. | |||
1122 | if (New->getFriendObjectKind() && New->getQualifier() && | |||
1123 | !New->getDescribedFunctionTemplate() && | |||
1124 | !New->getDependentSpecializationInfo() && | |||
1125 | !New->getType()->isDependentType()) { | |||
1126 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); | |||
1127 | TemplateSpecResult.addAllDecls(Old); | |||
1128 | if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, | |||
1129 | /*QualifiedFriend*/true)) { | |||
1130 | New->setInvalidDecl(); | |||
1131 | return Ovl_Overload; | |||
1132 | } | |||
1133 | ||||
1134 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); | |||
1135 | return Ovl_Match; | |||
1136 | } | |||
1137 | ||||
1138 | return Ovl_Overload; | |||
1139 | } | |||
1140 | ||||
1141 | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, | |||
1142 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, | |||
1143 | bool ConsiderRequiresClauses) { | |||
1144 | // C++ [basic.start.main]p2: This function shall not be overloaded. | |||
1145 | if (New->isMain()) | |||
1146 | return false; | |||
1147 | ||||
1148 | // MSVCRT user defined entry points cannot be overloaded. | |||
1149 | if (New->isMSVCRTEntryPoint()) | |||
1150 | return false; | |||
1151 | ||||
1152 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); | |||
1153 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); | |||
1154 | ||||
1155 | // C++ [temp.fct]p2: | |||
1156 | // A function template can be overloaded with other function templates | |||
1157 | // and with normal (non-template) functions. | |||
1158 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) | |||
1159 | return true; | |||
1160 | ||||
1161 | // Is the function New an overload of the function Old? | |||
1162 | QualType OldQType = Context.getCanonicalType(Old->getType()); | |||
1163 | QualType NewQType = Context.getCanonicalType(New->getType()); | |||
1164 | ||||
1165 | // Compare the signatures (C++ 1.3.10) of the two functions to | |||
1166 | // determine whether they are overloads. If we find any mismatch | |||
1167 | // in the signature, they are overloads. | |||
1168 | ||||
1169 | // If either of these functions is a K&R-style function (no | |||
1170 | // prototype), then we consider them to have matching signatures. | |||
1171 | if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || | |||
1172 | isa<FunctionNoProtoType>(NewQType.getTypePtr())) | |||
1173 | return false; | |||
1174 | ||||
1175 | const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); | |||
1176 | const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); | |||
1177 | ||||
1178 | // The signature of a function includes the types of its | |||
1179 | // parameters (C++ 1.3.10), which includes the presence or absence | |||
1180 | // of the ellipsis; see C++ DR 357). | |||
1181 | if (OldQType != NewQType && | |||
1182 | (OldType->getNumParams() != NewType->getNumParams() || | |||
1183 | OldType->isVariadic() != NewType->isVariadic() || | |||
1184 | !FunctionParamTypesAreEqual(OldType, NewType))) | |||
1185 | return true; | |||
1186 | ||||
1187 | // C++ [temp.over.link]p4: | |||
1188 | // The signature of a function template consists of its function | |||
1189 | // signature, its return type and its template parameter list. The names | |||
1190 | // of the template parameters are significant only for establishing the | |||
1191 | // relationship between the template parameters and the rest of the | |||
1192 | // signature. | |||
1193 | // | |||
1194 | // We check the return type and template parameter lists for function | |||
1195 | // templates first; the remaining checks follow. | |||
1196 | // | |||
1197 | // However, we don't consider either of these when deciding whether | |||
1198 | // a member introduced by a shadow declaration is hidden. | |||
1199 | if (!UseMemberUsingDeclRules && NewTemplate && | |||
1200 | (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | |||
1201 | OldTemplate->getTemplateParameters(), | |||
1202 | false, TPL_TemplateMatch) || | |||
1203 | !Context.hasSameType(Old->getDeclaredReturnType(), | |||
1204 | New->getDeclaredReturnType()))) | |||
1205 | return true; | |||
1206 | ||||
1207 | // If the function is a class member, its signature includes the | |||
1208 | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. | |||
1209 | // | |||
1210 | // As part of this, also check whether one of the member functions | |||
1211 | // is static, in which case they are not overloads (C++ | |||
1212 | // 13.1p2). While not part of the definition of the signature, | |||
1213 | // this check is important to determine whether these functions | |||
1214 | // can be overloaded. | |||
1215 | CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | |||
1216 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | |||
1217 | if (OldMethod && NewMethod && | |||
1218 | !OldMethod->isStatic() && !NewMethod->isStatic()) { | |||
1219 | if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { | |||
1220 | if (!UseMemberUsingDeclRules && | |||
1221 | (OldMethod->getRefQualifier() == RQ_None || | |||
1222 | NewMethod->getRefQualifier() == RQ_None)) { | |||
1223 | // C++0x [over.load]p2: | |||
1224 | // - Member function declarations with the same name and the same | |||
1225 | // parameter-type-list as well as member function template | |||
1226 | // declarations with the same name, the same parameter-type-list, and | |||
1227 | // the same template parameter lists cannot be overloaded if any of | |||
1228 | // them, but not all, have a ref-qualifier (8.3.5). | |||
1229 | Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) | |||
1230 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); | |||
1231 | Diag(OldMethod->getLocation(), diag::note_previous_declaration); | |||
1232 | } | |||
1233 | return true; | |||
1234 | } | |||
1235 | ||||
1236 | // We may not have applied the implicit const for a constexpr member | |||
1237 | // function yet (because we haven't yet resolved whether this is a static | |||
1238 | // or non-static member function). Add it now, on the assumption that this | |||
1239 | // is a redeclaration of OldMethod. | |||
1240 | auto OldQuals = OldMethod->getMethodQualifiers(); | |||
1241 | auto NewQuals = NewMethod->getMethodQualifiers(); | |||
1242 | if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && | |||
1243 | !isa<CXXConstructorDecl>(NewMethod)) | |||
1244 | NewQuals.addConst(); | |||
1245 | // We do not allow overloading based off of '__restrict'. | |||
1246 | OldQuals.removeRestrict(); | |||
1247 | NewQuals.removeRestrict(); | |||
1248 | if (OldQuals != NewQuals) | |||
1249 | return true; | |||
1250 | } | |||
1251 | ||||
1252 | // Though pass_object_size is placed on parameters and takes an argument, we | |||
1253 | // consider it to be a function-level modifier for the sake of function | |||
1254 | // identity. Either the function has one or more parameters with | |||
1255 | // pass_object_size or it doesn't. | |||
1256 | if (functionHasPassObjectSizeParams(New) != | |||
1257 | functionHasPassObjectSizeParams(Old)) | |||
1258 | return true; | |||
1259 | ||||
1260 | // enable_if attributes are an order-sensitive part of the signature. | |||
1261 | for (specific_attr_iterator<EnableIfAttr> | |||
1262 | NewI = New->specific_attr_begin<EnableIfAttr>(), | |||
1263 | NewE = New->specific_attr_end<EnableIfAttr>(), | |||
1264 | OldI = Old->specific_attr_begin<EnableIfAttr>(), | |||
1265 | OldE = Old->specific_attr_end<EnableIfAttr>(); | |||
1266 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { | |||
1267 | if (NewI == NewE || OldI == OldE) | |||
1268 | return true; | |||
1269 | llvm::FoldingSetNodeID NewID, OldID; | |||
1270 | NewI->getCond()->Profile(NewID, Context, true); | |||
1271 | OldI->getCond()->Profile(OldID, Context, true); | |||
1272 | if (NewID != OldID) | |||
1273 | return true; | |||
1274 | } | |||
1275 | ||||
1276 | if (getLangOpts().CUDA && ConsiderCudaAttrs) { | |||
1277 | // Don't allow overloading of destructors. (In theory we could, but it | |||
1278 | // would be a giant change to clang.) | |||
1279 | if (!isa<CXXDestructorDecl>(New)) { | |||
1280 | CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), | |||
1281 | OldTarget = IdentifyCUDATarget(Old); | |||
1282 | if (NewTarget != CFT_InvalidTarget) { | |||
1283 | assert((OldTarget != CFT_InvalidTarget) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "clang/lib/Sema/SemaOverload.cpp", 1284, __extension__ __PRETTY_FUNCTION__ )) | |||
1284 | "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "clang/lib/Sema/SemaOverload.cpp", 1284, __extension__ __PRETTY_FUNCTION__ )); | |||
1285 | ||||
1286 | // Allow overloading of functions with same signature and different CUDA | |||
1287 | // target attributes. | |||
1288 | if (NewTarget != OldTarget) | |||
1289 | return true; | |||
1290 | } | |||
1291 | } | |||
1292 | } | |||
1293 | ||||
1294 | if (ConsiderRequiresClauses) { | |||
1295 | Expr *NewRC = New->getTrailingRequiresClause(), | |||
1296 | *OldRC = Old->getTrailingRequiresClause(); | |||
1297 | if ((NewRC != nullptr) != (OldRC != nullptr)) | |||
1298 | // RC are most certainly different - these are overloads. | |||
1299 | return true; | |||
1300 | ||||
1301 | if (NewRC) { | |||
1302 | llvm::FoldingSetNodeID NewID, OldID; | |||
1303 | NewRC->Profile(NewID, Context, /*Canonical=*/true); | |||
1304 | OldRC->Profile(OldID, Context, /*Canonical=*/true); | |||
1305 | if (NewID != OldID) | |||
1306 | // RCs are not equivalent - these are overloads. | |||
1307 | return true; | |||
1308 | } | |||
1309 | } | |||
1310 | ||||
1311 | // The signatures match; this is not an overload. | |||
1312 | return false; | |||
1313 | } | |||
1314 | ||||
1315 | /// Tries a user-defined conversion from From to ToType. | |||
1316 | /// | |||
1317 | /// Produces an implicit conversion sequence for when a standard conversion | |||
1318 | /// is not an option. See TryImplicitConversion for more information. | |||
1319 | static ImplicitConversionSequence | |||
1320 | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
1321 | bool SuppressUserConversions, | |||
1322 | AllowedExplicit AllowExplicit, | |||
1323 | bool InOverloadResolution, | |||
1324 | bool CStyle, | |||
1325 | bool AllowObjCWritebackConversion, | |||
1326 | bool AllowObjCConversionOnExplicit) { | |||
1327 | ImplicitConversionSequence ICS; | |||
1328 | ||||
1329 | if (SuppressUserConversions) { | |||
1330 | // We're not in the case above, so there is no conversion that | |||
1331 | // we can perform. | |||
1332 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1333 | return ICS; | |||
1334 | } | |||
1335 | ||||
1336 | // Attempt user-defined conversion. | |||
1337 | OverloadCandidateSet Conversions(From->getExprLoc(), | |||
1338 | OverloadCandidateSet::CSK_Normal); | |||
1339 | switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, | |||
1340 | Conversions, AllowExplicit, | |||
1341 | AllowObjCConversionOnExplicit)) { | |||
1342 | case OR_Success: | |||
1343 | case OR_Deleted: | |||
1344 | ICS.setUserDefined(); | |||
1345 | // C++ [over.ics.user]p4: | |||
1346 | // A conversion of an expression of class type to the same class | |||
1347 | // type is given Exact Match rank, and a conversion of an | |||
1348 | // expression of class type to a base class of that type is | |||
1349 | // given Conversion rank, in spite of the fact that a copy | |||
1350 | // constructor (i.e., a user-defined conversion function) is | |||
1351 | // called for those cases. | |||
1352 | if (CXXConstructorDecl *Constructor | |||
1353 | = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { | |||
1354 | QualType FromCanon | |||
1355 | = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); | |||
1356 | QualType ToCanon | |||
1357 | = S.Context.getCanonicalType(ToType).getUnqualifiedType(); | |||
1358 | if (Constructor->isCopyConstructor() && | |||
1359 | (FromCanon == ToCanon || | |||
1360 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { | |||
1361 | // Turn this into a "standard" conversion sequence, so that it | |||
1362 | // gets ranked with standard conversion sequences. | |||
1363 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; | |||
1364 | ICS.setStandard(); | |||
1365 | ICS.Standard.setAsIdentityConversion(); | |||
1366 | ICS.Standard.setFromType(From->getType()); | |||
1367 | ICS.Standard.setAllToTypes(ToType); | |||
1368 | ICS.Standard.CopyConstructor = Constructor; | |||
1369 | ICS.Standard.FoundCopyConstructor = Found; | |||
1370 | if (ToCanon != FromCanon) | |||
1371 | ICS.Standard.Second = ICK_Derived_To_Base; | |||
1372 | } | |||
1373 | } | |||
1374 | break; | |||
1375 | ||||
1376 | case OR_Ambiguous: | |||
1377 | ICS.setAmbiguous(); | |||
1378 | ICS.Ambiguous.setFromType(From->getType()); | |||
1379 | ICS.Ambiguous.setToType(ToType); | |||
1380 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); | |||
1381 | Cand != Conversions.end(); ++Cand) | |||
1382 | if (Cand->Best) | |||
1383 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); | |||
1384 | break; | |||
1385 | ||||
1386 | // Fall through. | |||
1387 | case OR_No_Viable_Function: | |||
1388 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1389 | break; | |||
1390 | } | |||
1391 | ||||
1392 | return ICS; | |||
1393 | } | |||
1394 | ||||
1395 | /// TryImplicitConversion - Attempt to perform an implicit conversion | |||
1396 | /// from the given expression (Expr) to the given type (ToType). This | |||
1397 | /// function returns an implicit conversion sequence that can be used | |||
1398 | /// to perform the initialization. Given | |||
1399 | /// | |||
1400 | /// void f(float f); | |||
1401 | /// void g(int i) { f(i); } | |||
1402 | /// | |||
1403 | /// this routine would produce an implicit conversion sequence to | |||
1404 | /// describe the initialization of f from i, which will be a standard | |||
1405 | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ | |||
1406 | /// 4.1) followed by a floating-integral conversion (C++ 4.9). | |||
1407 | // | |||
1408 | /// Note that this routine only determines how the conversion can be | |||
1409 | /// performed; it does not actually perform the conversion. As such, | |||
1410 | /// it will not produce any diagnostics if no conversion is available, | |||
1411 | /// but will instead return an implicit conversion sequence of kind | |||
1412 | /// "BadConversion". | |||
1413 | /// | |||
1414 | /// If @p SuppressUserConversions, then user-defined conversions are | |||
1415 | /// not permitted. | |||
1416 | /// If @p AllowExplicit, then explicit user-defined conversions are | |||
1417 | /// permitted. | |||
1418 | /// | |||
1419 | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C | |||
1420 | /// writeback conversion, which allows __autoreleasing id* parameters to | |||
1421 | /// be initialized with __strong id* or __weak id* arguments. | |||
1422 | static ImplicitConversionSequence | |||
1423 | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, | |||
1424 | bool SuppressUserConversions, | |||
1425 | AllowedExplicit AllowExplicit, | |||
1426 | bool InOverloadResolution, | |||
1427 | bool CStyle, | |||
1428 | bool AllowObjCWritebackConversion, | |||
1429 | bool AllowObjCConversionOnExplicit) { | |||
1430 | ImplicitConversionSequence ICS; | |||
1431 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, | |||
1432 | ICS.Standard, CStyle, AllowObjCWritebackConversion)){ | |||
1433 | ICS.setStandard(); | |||
1434 | return ICS; | |||
1435 | } | |||
1436 | ||||
1437 | if (!S.getLangOpts().CPlusPlus) { | |||
1438 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1439 | return ICS; | |||
1440 | } | |||
1441 | ||||
1442 | // C++ [over.ics.user]p4: | |||
1443 | // A conversion of an expression of class type to the same class | |||
1444 | // type is given Exact Match rank, and a conversion of an | |||
1445 | // expression of class type to a base class of that type is | |||
1446 | // given Conversion rank, in spite of the fact that a copy/move | |||
1447 | // constructor (i.e., a user-defined conversion function) is | |||
1448 | // called for those cases. | |||
1449 | QualType FromType = From->getType(); | |||
1450 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && | |||
1451 | (S.Context.hasSameUnqualifiedType(FromType, ToType) || | |||
1452 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { | |||
1453 | ICS.setStandard(); | |||
1454 | ICS.Standard.setAsIdentityConversion(); | |||
1455 | ICS.Standard.setFromType(FromType); | |||
1456 | ICS.Standard.setAllToTypes(ToType); | |||
1457 | ||||
1458 | // We don't actually check at this point whether there is a valid | |||
1459 | // copy/move constructor, since overloading just assumes that it | |||
1460 | // exists. When we actually perform initialization, we'll find the | |||
1461 | // appropriate constructor to copy the returned object, if needed. | |||
1462 | ICS.Standard.CopyConstructor = nullptr; | |||
1463 | ||||
1464 | // Determine whether this is considered a derived-to-base conversion. | |||
1465 | if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1466 | ICS.Standard.Second = ICK_Derived_To_Base; | |||
1467 | ||||
1468 | return ICS; | |||
1469 | } | |||
1470 | ||||
1471 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, | |||
1472 | AllowExplicit, InOverloadResolution, CStyle, | |||
1473 | AllowObjCWritebackConversion, | |||
1474 | AllowObjCConversionOnExplicit); | |||
1475 | } | |||
1476 | ||||
1477 | ImplicitConversionSequence | |||
1478 | Sema::TryImplicitConversion(Expr *From, QualType ToType, | |||
1479 | bool SuppressUserConversions, | |||
1480 | AllowedExplicit AllowExplicit, | |||
1481 | bool InOverloadResolution, | |||
1482 | bool CStyle, | |||
1483 | bool AllowObjCWritebackConversion) { | |||
1484 | return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, | |||
1485 | AllowExplicit, InOverloadResolution, CStyle, | |||
1486 | AllowObjCWritebackConversion, | |||
1487 | /*AllowObjCConversionOnExplicit=*/false); | |||
1488 | } | |||
1489 | ||||
1490 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
1491 | /// expression From to the type ToType. Returns the | |||
1492 | /// converted expression. Flavor is the kind of conversion we're | |||
1493 | /// performing, used in the error message. If @p AllowExplicit, | |||
1494 | /// explicit user-defined conversions are permitted. | |||
1495 | ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
1496 | AssignmentAction Action, | |||
1497 | bool AllowExplicit) { | |||
1498 | if (checkPlaceholderForOverload(*this, From)) | |||
1499 | return ExprError(); | |||
1500 | ||||
1501 | // Objective-C ARC: Determine whether we will allow the writeback conversion. | |||
1502 | bool AllowObjCWritebackConversion | |||
1503 | = getLangOpts().ObjCAutoRefCount && | |||
1504 | (Action == AA_Passing || Action == AA_Sending); | |||
1505 | if (getLangOpts().ObjC) | |||
1506 | CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, | |||
1507 | From->getType(), From); | |||
1508 | ImplicitConversionSequence ICS = ::TryImplicitConversion( | |||
1509 | *this, From, ToType, | |||
1510 | /*SuppressUserConversions=*/false, | |||
1511 | AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, | |||
1512 | /*InOverloadResolution=*/false, | |||
1513 | /*CStyle=*/false, AllowObjCWritebackConversion, | |||
1514 | /*AllowObjCConversionOnExplicit=*/false); | |||
1515 | return PerformImplicitConversion(From, ToType, ICS, Action); | |||
1516 | } | |||
1517 | ||||
1518 | /// Determine whether the conversion from FromType to ToType is a valid | |||
1519 | /// conversion that strips "noexcept" or "noreturn" off the nested function | |||
1520 | /// type. | |||
1521 | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, | |||
1522 | QualType &ResultTy) { | |||
1523 | if (Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1524 | return false; | |||
1525 | ||||
1526 | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) | |||
1527 | // or F(t noexcept) -> F(t) | |||
1528 | // where F adds one of the following at most once: | |||
1529 | // - a pointer | |||
1530 | // - a member pointer | |||
1531 | // - a block pointer | |||
1532 | // Changes here need matching changes in FindCompositePointerType. | |||
1533 | CanQualType CanTo = Context.getCanonicalType(ToType); | |||
1534 | CanQualType CanFrom = Context.getCanonicalType(FromType); | |||
1535 | Type::TypeClass TyClass = CanTo->getTypeClass(); | |||
1536 | if (TyClass != CanFrom->getTypeClass()) return false; | |||
1537 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { | |||
1538 | if (TyClass == Type::Pointer) { | |||
1539 | CanTo = CanTo.castAs<PointerType>()->getPointeeType(); | |||
1540 | CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); | |||
1541 | } else if (TyClass == Type::BlockPointer) { | |||
1542 | CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); | |||
1543 | CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); | |||
1544 | } else if (TyClass == Type::MemberPointer) { | |||
1545 | auto ToMPT = CanTo.castAs<MemberPointerType>(); | |||
1546 | auto FromMPT = CanFrom.castAs<MemberPointerType>(); | |||
1547 | // A function pointer conversion cannot change the class of the function. | |||
1548 | if (ToMPT->getClass() != FromMPT->getClass()) | |||
1549 | return false; | |||
1550 | CanTo = ToMPT->getPointeeType(); | |||
1551 | CanFrom = FromMPT->getPointeeType(); | |||
1552 | } else { | |||
1553 | return false; | |||
1554 | } | |||
1555 | ||||
1556 | TyClass = CanTo->getTypeClass(); | |||
1557 | if (TyClass != CanFrom->getTypeClass()) return false; | |||
1558 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) | |||
1559 | return false; | |||
1560 | } | |||
1561 | ||||
1562 | const auto *FromFn = cast<FunctionType>(CanFrom); | |||
1563 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | |||
1564 | ||||
1565 | const auto *ToFn = cast<FunctionType>(CanTo); | |||
1566 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | |||
1567 | ||||
1568 | bool Changed = false; | |||
1569 | ||||
1570 | // Drop 'noreturn' if not present in target type. | |||
1571 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { | |||
1572 | FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); | |||
1573 | Changed = true; | |||
1574 | } | |||
1575 | ||||
1576 | // Drop 'noexcept' if not present in target type. | |||
1577 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { | |||
1578 | const auto *ToFPT = cast<FunctionProtoType>(ToFn); | |||
1579 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { | |||
1580 | FromFn = cast<FunctionType>( | |||
1581 | Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), | |||
1582 | EST_None) | |||
1583 | .getTypePtr()); | |||
1584 | Changed = true; | |||
1585 | } | |||
1586 | ||||
1587 | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid | |||
1588 | // only if the ExtParameterInfo lists of the two function prototypes can be | |||
1589 | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. | |||
1590 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; | |||
1591 | bool CanUseToFPT, CanUseFromFPT; | |||
1592 | if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, | |||
1593 | CanUseFromFPT, NewParamInfos) && | |||
1594 | CanUseToFPT && !CanUseFromFPT) { | |||
1595 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); | |||
1596 | ExtInfo.ExtParameterInfos = | |||
1597 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); | |||
1598 | QualType QT = Context.getFunctionType(FromFPT->getReturnType(), | |||
1599 | FromFPT->getParamTypes(), ExtInfo); | |||
1600 | FromFn = QT->getAs<FunctionType>(); | |||
1601 | Changed = true; | |||
1602 | } | |||
1603 | } | |||
1604 | ||||
1605 | if (!Changed) | |||
1606 | return false; | |||
1607 | ||||
1608 | assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical()) ? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()" , "clang/lib/Sema/SemaOverload.cpp", 1608, __extension__ __PRETTY_FUNCTION__ )); | |||
1609 | if (QualType(FromFn, 0) != CanTo) return false; | |||
1610 | ||||
1611 | ResultTy = ToType; | |||
1612 | return true; | |||
1613 | } | |||
1614 | ||||
1615 | /// Determine whether the conversion from FromType to ToType is a valid | |||
1616 | /// vector conversion. | |||
1617 | /// | |||
1618 | /// \param ICK Will be set to the vector conversion kind, if this is a vector | |||
1619 | /// conversion. | |||
1620 | static bool IsVectorConversion(Sema &S, QualType FromType, | |||
1621 | QualType ToType, ImplicitConversionKind &ICK) { | |||
1622 | // We need at least one of these types to be a vector type to have a vector | |||
1623 | // conversion. | |||
1624 | if (!ToType->isVectorType() && !FromType->isVectorType()) | |||
1625 | return false; | |||
1626 | ||||
1627 | // Identical types require no conversions. | |||
1628 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1629 | return false; | |||
1630 | ||||
1631 | // There are no conversions between extended vector types, only identity. | |||
1632 | if (ToType->isExtVectorType()) { | |||
1633 | // There are no conversions between extended vector types other than the | |||
1634 | // identity conversion. | |||
1635 | if (FromType->isExtVectorType()) | |||
1636 | return false; | |||
1637 | ||||
1638 | // Vector splat from any arithmetic type to a vector. | |||
1639 | if (FromType->isArithmeticType()) { | |||
1640 | ICK = ICK_Vector_Splat; | |||
1641 | return true; | |||
1642 | } | |||
1643 | } | |||
1644 | ||||
1645 | if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) | |||
1646 | if (S.Context.areCompatibleSveTypes(FromType, ToType) || | |||
1647 | S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { | |||
1648 | ICK = ICK_SVE_Vector_Conversion; | |||
1649 | return true; | |||
1650 | } | |||
1651 | ||||
1652 | // We can perform the conversion between vector types in the following cases: | |||
1653 | // 1)vector types are equivalent AltiVec and GCC vector types | |||
1654 | // 2)lax vector conversions are permitted and the vector types are of the | |||
1655 | // same size | |||
1656 | // 3)the destination type does not have the ARM MVE strict-polymorphism | |||
1657 | // attribute, which inhibits lax vector conversion for overload resolution | |||
1658 | // only | |||
1659 | if (ToType->isVectorType() && FromType->isVectorType()) { | |||
1660 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || | |||
1661 | (S.isLaxVectorConversion(FromType, ToType) && | |||
1662 | !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { | |||
1663 | ICK = ICK_Vector_Conversion; | |||
1664 | return true; | |||
1665 | } | |||
1666 | } | |||
1667 | ||||
1668 | return false; | |||
1669 | } | |||
1670 | ||||
1671 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, | |||
1672 | bool InOverloadResolution, | |||
1673 | StandardConversionSequence &SCS, | |||
1674 | bool CStyle); | |||
1675 | ||||
1676 | /// IsStandardConversion - Determines whether there is a standard | |||
1677 | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the | |||
1678 | /// expression From to the type ToType. Standard conversion sequences | |||
1679 | /// only consider non-class types; for conversions that involve class | |||
1680 | /// types, use TryImplicitConversion. If a conversion exists, SCS will | |||
1681 | /// contain the standard conversion sequence required to perform this | |||
1682 | /// conversion and this routine will return true. Otherwise, this | |||
1683 | /// routine will return false and the value of SCS is unspecified. | |||
1684 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, | |||
1685 | bool InOverloadResolution, | |||
1686 | StandardConversionSequence &SCS, | |||
1687 | bool CStyle, | |||
1688 | bool AllowObjCWritebackConversion) { | |||
1689 | QualType FromType = From->getType(); | |||
1690 | ||||
1691 | // Standard conversions (C++ [conv]) | |||
1692 | SCS.setAsIdentityConversion(); | |||
1693 | SCS.IncompatibleObjC = false; | |||
1694 | SCS.setFromType(FromType); | |||
1695 | SCS.CopyConstructor = nullptr; | |||
1696 | ||||
1697 | // There are no standard conversions for class types in C++, so | |||
1698 | // abort early. When overloading in C, however, we do permit them. | |||
1699 | if (S.getLangOpts().CPlusPlus && | |||
1700 | (FromType->isRecordType() || ToType->isRecordType())) | |||
1701 | return false; | |||
1702 | ||||
1703 | // The first conversion can be an lvalue-to-rvalue conversion, | |||
1704 | // array-to-pointer conversion, or function-to-pointer conversion | |||
1705 | // (C++ 4p1). | |||
1706 | ||||
1707 | if (FromType == S.Context.OverloadTy) { | |||
1708 | DeclAccessPair AccessPair; | |||
1709 | if (FunctionDecl *Fn | |||
1710 | = S.ResolveAddressOfOverloadedFunction(From, ToType, false, | |||
1711 | AccessPair)) { | |||
1712 | // We were able to resolve the address of the overloaded function, | |||
1713 | // so we can convert to the type of that function. | |||
1714 | FromType = Fn->getType(); | |||
1715 | SCS.setFromType(FromType); | |||
1716 | ||||
1717 | // we can sometimes resolve &foo<int> regardless of ToType, so check | |||
1718 | // if the type matches (identity) or we are converting to bool | |||
1719 | if (!S.Context.hasSameUnqualifiedType( | |||
1720 | S.ExtractUnqualifiedFunctionType(ToType), FromType)) { | |||
1721 | QualType resultTy; | |||
1722 | // if the function type matches except for [[noreturn]], it's ok | |||
1723 | if (!S.IsFunctionConversion(FromType, | |||
1724 | S.ExtractUnqualifiedFunctionType(ToType), resultTy)) | |||
1725 | // otherwise, only a boolean conversion is standard | |||
1726 | if (!ToType->isBooleanType()) | |||
1727 | return false; | |||
1728 | } | |||
1729 | ||||
1730 | // Check if the "from" expression is taking the address of an overloaded | |||
1731 | // function and recompute the FromType accordingly. Take advantage of the | |||
1732 | // fact that non-static member functions *must* have such an address-of | |||
1733 | // expression. | |||
1734 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); | |||
1735 | if (Method && !Method->isStatic()) { | |||
1736 | assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From-> IgnoreParens()) && "Non-unary operator on non-static member address" ) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1737, __extension__ __PRETTY_FUNCTION__ )) | |||
1737 | "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From-> IgnoreParens()) && "Non-unary operator on non-static member address" ) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1737, __extension__ __PRETTY_FUNCTION__ )); | |||
1738 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1740, __extension__ __PRETTY_FUNCTION__ )) | |||
1739 | == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1740, __extension__ __PRETTY_FUNCTION__ )) | |||
1740 | "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "clang/lib/Sema/SemaOverload.cpp", 1740, __extension__ __PRETTY_FUNCTION__ )); | |||
1741 | const Type *ClassType | |||
1742 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); | |||
1743 | FromType = S.Context.getMemberPointerType(FromType, ClassType); | |||
1744 | } else if (isa<UnaryOperator>(From->IgnoreParens())) { | |||
1745 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1747, __extension__ __PRETTY_FUNCTION__ )) | |||
1746 | UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1747, __extension__ __PRETTY_FUNCTION__ )) | |||
1747 | "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From-> IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "clang/lib/Sema/SemaOverload.cpp", 1747, __extension__ __PRETTY_FUNCTION__ )); | |||
1748 | FromType = S.Context.getPointerType(FromType); | |||
1749 | } | |||
1750 | } else { | |||
1751 | return false; | |||
1752 | } | |||
1753 | } | |||
1754 | // Lvalue-to-rvalue conversion (C++11 4.1): | |||
1755 | // A glvalue (3.10) of a non-function, non-array type T can | |||
1756 | // be converted to a prvalue. | |||
1757 | bool argIsLValue = From->isGLValue(); | |||
1758 | if (argIsLValue && | |||
1759 | !FromType->isFunctionType() && !FromType->isArrayType() && | |||
1760 | S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { | |||
1761 | SCS.First = ICK_Lvalue_To_Rvalue; | |||
1762 | ||||
1763 | // C11 6.3.2.1p2: | |||
1764 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
1765 | // of the type of the lvalue ... | |||
1766 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) | |||
1767 | FromType = Atomic->getValueType(); | |||
1768 | ||||
1769 | // If T is a non-class type, the type of the rvalue is the | |||
1770 | // cv-unqualified version of T. Otherwise, the type of the rvalue | |||
1771 | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we | |||
1772 | // just strip the qualifiers because they don't matter. | |||
1773 | FromType = FromType.getUnqualifiedType(); | |||
1774 | } else if (FromType->isArrayType()) { | |||
1775 | // Array-to-pointer conversion (C++ 4.2) | |||
1776 | SCS.First = ICK_Array_To_Pointer; | |||
1777 | ||||
1778 | // An lvalue or rvalue of type "array of N T" or "array of unknown | |||
1779 | // bound of T" can be converted to an rvalue of type "pointer to | |||
1780 | // T" (C++ 4.2p1). | |||
1781 | FromType = S.Context.getArrayDecayedType(FromType); | |||
1782 | ||||
1783 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { | |||
1784 | // This conversion is deprecated in C++03 (D.4) | |||
1785 | SCS.DeprecatedStringLiteralToCharPtr = true; | |||
1786 | ||||
1787 | // For the purpose of ranking in overload resolution | |||
1788 | // (13.3.3.1.1), this conversion is considered an | |||
1789 | // array-to-pointer conversion followed by a qualification | |||
1790 | // conversion (4.4). (C++ 4.2p2) | |||
1791 | SCS.Second = ICK_Identity; | |||
1792 | SCS.Third = ICK_Qualification; | |||
1793 | SCS.QualificationIncludesObjCLifetime = false; | |||
1794 | SCS.setAllToTypes(FromType); | |||
1795 | return true; | |||
1796 | } | |||
1797 | } else if (FromType->isFunctionType() && argIsLValue) { | |||
1798 | // Function-to-pointer conversion (C++ 4.3). | |||
1799 | SCS.First = ICK_Function_To_Pointer; | |||
1800 | ||||
1801 | if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) | |||
1802 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
1803 | if (!S.checkAddressOfFunctionIsAvailable(FD)) | |||
1804 | return false; | |||
1805 | ||||
1806 | // An lvalue of function type T can be converted to an rvalue of | |||
1807 | // type "pointer to T." The result is a pointer to the | |||
1808 | // function. (C++ 4.3p1). | |||
1809 | FromType = S.Context.getPointerType(FromType); | |||
1810 | } else { | |||
1811 | // We don't require any conversions for the first step. | |||
1812 | SCS.First = ICK_Identity; | |||
1813 | } | |||
1814 | SCS.setToType(0, FromType); | |||
1815 | ||||
1816 | // The second conversion can be an integral promotion, floating | |||
1817 | // point promotion, integral conversion, floating point conversion, | |||
1818 | // floating-integral conversion, pointer conversion, | |||
1819 | // pointer-to-member conversion, or boolean conversion (C++ 4p1). | |||
1820 | // For overloading in C, this can also be a "compatible-type" | |||
1821 | // conversion. | |||
1822 | bool IncompatibleObjC = false; | |||
1823 | ImplicitConversionKind SecondICK = ICK_Identity; | |||
1824 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { | |||
1825 | // The unqualified versions of the types are the same: there's no | |||
1826 | // conversion to do. | |||
1827 | SCS.Second = ICK_Identity; | |||
1828 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { | |||
1829 | // Integral promotion (C++ 4.5). | |||
1830 | SCS.Second = ICK_Integral_Promotion; | |||
1831 | FromType = ToType.getUnqualifiedType(); | |||
1832 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { | |||
1833 | // Floating point promotion (C++ 4.6). | |||
1834 | SCS.Second = ICK_Floating_Promotion; | |||
1835 | FromType = ToType.getUnqualifiedType(); | |||
1836 | } else if (S.IsComplexPromotion(FromType, ToType)) { | |||
1837 | // Complex promotion (Clang extension) | |||
1838 | SCS.Second = ICK_Complex_Promotion; | |||
1839 | FromType = ToType.getUnqualifiedType(); | |||
1840 | } else if (ToType->isBooleanType() && | |||
1841 | (FromType->isArithmeticType() || | |||
1842 | FromType->isAnyPointerType() || | |||
1843 | FromType->isBlockPointerType() || | |||
1844 | FromType->isMemberPointerType())) { | |||
1845 | // Boolean conversions (C++ 4.12). | |||
1846 | SCS.Second = ICK_Boolean_Conversion; | |||
1847 | FromType = S.Context.BoolTy; | |||
1848 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && | |||
1849 | ToType->isIntegralType(S.Context)) { | |||
1850 | // Integral conversions (C++ 4.7). | |||
1851 | SCS.Second = ICK_Integral_Conversion; | |||
1852 | FromType = ToType.getUnqualifiedType(); | |||
1853 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { | |||
1854 | // Complex conversions (C99 6.3.1.6) | |||
1855 | SCS.Second = ICK_Complex_Conversion; | |||
1856 | FromType = ToType.getUnqualifiedType(); | |||
1857 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || | |||
1858 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { | |||
1859 | // Complex-real conversions (C99 6.3.1.7) | |||
1860 | SCS.Second = ICK_Complex_Real; | |||
1861 | FromType = ToType.getUnqualifiedType(); | |||
1862 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { | |||
1863 | // FIXME: disable conversions between long double, __ibm128 and __float128 | |||
1864 | // if their representation is different until there is back end support | |||
1865 | // We of course allow this conversion if long double is really double. | |||
1866 | ||||
1867 | // Conversions between bfloat and other floats are not permitted. | |||
1868 | if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) | |||
1869 | return false; | |||
1870 | ||||
1871 | // Conversions between IEEE-quad and IBM-extended semantics are not | |||
1872 | // permitted. | |||
1873 | const llvm::fltSemantics &FromSem = | |||
1874 | S.Context.getFloatTypeSemantics(FromType); | |||
1875 | const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); | |||
1876 | if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && | |||
1877 | &ToSem == &llvm::APFloat::IEEEquad()) || | |||
1878 | (&FromSem == &llvm::APFloat::IEEEquad() && | |||
1879 | &ToSem == &llvm::APFloat::PPCDoubleDouble())) | |||
1880 | return false; | |||
1881 | ||||
1882 | // Floating point conversions (C++ 4.8). | |||
1883 | SCS.Second = ICK_Floating_Conversion; | |||
1884 | FromType = ToType.getUnqualifiedType(); | |||
1885 | } else if ((FromType->isRealFloatingType() && | |||
1886 | ToType->isIntegralType(S.Context)) || | |||
1887 | (FromType->isIntegralOrUnscopedEnumerationType() && | |||
1888 | ToType->isRealFloatingType())) { | |||
1889 | // Conversions between bfloat and int are not permitted. | |||
1890 | if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) | |||
1891 | return false; | |||
1892 | ||||
1893 | // Floating-integral conversions (C++ 4.9). | |||
1894 | SCS.Second = ICK_Floating_Integral; | |||
1895 | FromType = ToType.getUnqualifiedType(); | |||
1896 | } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { | |||
1897 | SCS.Second = ICK_Block_Pointer_Conversion; | |||
1898 | } else if (AllowObjCWritebackConversion && | |||
1899 | S.isObjCWritebackConversion(FromType, ToType, FromType)) { | |||
1900 | SCS.Second = ICK_Writeback_Conversion; | |||
1901 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, | |||
1902 | FromType, IncompatibleObjC)) { | |||
1903 | // Pointer conversions (C++ 4.10). | |||
1904 | SCS.Second = ICK_Pointer_Conversion; | |||
1905 | SCS.IncompatibleObjC = IncompatibleObjC; | |||
1906 | FromType = FromType.getUnqualifiedType(); | |||
1907 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, | |||
1908 | InOverloadResolution, FromType)) { | |||
1909 | // Pointer to member conversions (4.11). | |||
1910 | SCS.Second = ICK_Pointer_Member; | |||
1911 | } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { | |||
1912 | SCS.Second = SecondICK; | |||
1913 | FromType = ToType.getUnqualifiedType(); | |||
1914 | } else if (!S.getLangOpts().CPlusPlus && | |||
1915 | S.Context.typesAreCompatible(ToType, FromType)) { | |||
1916 | // Compatible conversions (Clang extension for C function overloading) | |||
1917 | SCS.Second = ICK_Compatible_Conversion; | |||
1918 | FromType = ToType.getUnqualifiedType(); | |||
1919 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, | |||
1920 | InOverloadResolution, | |||
1921 | SCS, CStyle)) { | |||
1922 | SCS.Second = ICK_TransparentUnionConversion; | |||
1923 | FromType = ToType; | |||
1924 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, | |||
1925 | CStyle)) { | |||
1926 | // tryAtomicConversion has updated the standard conversion sequence | |||
1927 | // appropriately. | |||
1928 | return true; | |||
1929 | } else if (ToType->isEventT() && | |||
1930 | From->isIntegerConstantExpr(S.getASTContext()) && | |||
1931 | From->EvaluateKnownConstInt(S.getASTContext()) == 0) { | |||
1932 | SCS.Second = ICK_Zero_Event_Conversion; | |||
1933 | FromType = ToType; | |||
1934 | } else if (ToType->isQueueT() && | |||
1935 | From->isIntegerConstantExpr(S.getASTContext()) && | |||
1936 | (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { | |||
1937 | SCS.Second = ICK_Zero_Queue_Conversion; | |||
1938 | FromType = ToType; | |||
1939 | } else if (ToType->isSamplerT() && | |||
1940 | From->isIntegerConstantExpr(S.getASTContext())) { | |||
1941 | SCS.Second = ICK_Compatible_Conversion; | |||
1942 | FromType = ToType; | |||
1943 | } else { | |||
1944 | // No second conversion required. | |||
1945 | SCS.Second = ICK_Identity; | |||
1946 | } | |||
1947 | SCS.setToType(1, FromType); | |||
1948 | ||||
1949 | // The third conversion can be a function pointer conversion or a | |||
1950 | // qualification conversion (C++ [conv.fctptr], [conv.qual]). | |||
1951 | bool ObjCLifetimeConversion; | |||
1952 | if (S.IsFunctionConversion(FromType, ToType, FromType)) { | |||
1953 | // Function pointer conversions (removing 'noexcept') including removal of | |||
1954 | // 'noreturn' (Clang extension). | |||
1955 | SCS.Third = ICK_Function_Conversion; | |||
1956 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, | |||
1957 | ObjCLifetimeConversion)) { | |||
1958 | SCS.Third = ICK_Qualification; | |||
1959 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; | |||
1960 | FromType = ToType; | |||
1961 | } else { | |||
1962 | // No conversion required | |||
1963 | SCS.Third = ICK_Identity; | |||
1964 | } | |||
1965 | ||||
1966 | // C++ [over.best.ics]p6: | |||
1967 | // [...] Any difference in top-level cv-qualification is | |||
1968 | // subsumed by the initialization itself and does not constitute | |||
1969 | // a conversion. [...] | |||
1970 | QualType CanonFrom = S.Context.getCanonicalType(FromType); | |||
1971 | QualType CanonTo = S.Context.getCanonicalType(ToType); | |||
1972 | if (CanonFrom.getLocalUnqualifiedType() | |||
1973 | == CanonTo.getLocalUnqualifiedType() && | |||
1974 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { | |||
1975 | FromType = ToType; | |||
1976 | CanonFrom = CanonTo; | |||
1977 | } | |||
1978 | ||||
1979 | SCS.setToType(2, FromType); | |||
1980 | ||||
1981 | if (CanonFrom == CanonTo) | |||
1982 | return true; | |||
1983 | ||||
1984 | // If we have not converted the argument type to the parameter type, | |||
1985 | // this is a bad conversion sequence, unless we're resolving an overload in C. | |||
1986 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) | |||
1987 | return false; | |||
1988 | ||||
1989 | ExprResult ER = ExprResult{From}; | |||
1990 | Sema::AssignConvertType Conv = | |||
1991 | S.CheckSingleAssignmentConstraints(ToType, ER, | |||
1992 | /*Diagnose=*/false, | |||
1993 | /*DiagnoseCFAudited=*/false, | |||
1994 | /*ConvertRHS=*/false); | |||
1995 | ImplicitConversionKind SecondConv; | |||
1996 | switch (Conv) { | |||
1997 | case Sema::Compatible: | |||
1998 | SecondConv = ICK_C_Only_Conversion; | |||
1999 | break; | |||
2000 | // For our purposes, discarding qualifiers is just as bad as using an | |||
2001 | // incompatible pointer. Note that an IncompatiblePointer conversion can drop | |||
2002 | // qualifiers, as well. | |||
2003 | case Sema::CompatiblePointerDiscardsQualifiers: | |||
2004 | case Sema::IncompatiblePointer: | |||
2005 | case Sema::IncompatiblePointerSign: | |||
2006 | SecondConv = ICK_Incompatible_Pointer_Conversion; | |||
2007 | break; | |||
2008 | default: | |||
2009 | return false; | |||
2010 | } | |||
2011 | ||||
2012 | // First can only be an lvalue conversion, so we pretend that this was the | |||
2013 | // second conversion. First should already be valid from earlier in the | |||
2014 | // function. | |||
2015 | SCS.Second = SecondConv; | |||
2016 | SCS.setToType(1, ToType); | |||
2017 | ||||
2018 | // Third is Identity, because Second should rank us worse than any other | |||
2019 | // conversion. This could also be ICK_Qualification, but it's simpler to just | |||
2020 | // lump everything in with the second conversion, and we don't gain anything | |||
2021 | // from making this ICK_Qualification. | |||
2022 | SCS.Third = ICK_Identity; | |||
2023 | SCS.setToType(2, ToType); | |||
2024 | return true; | |||
2025 | } | |||
2026 | ||||
2027 | static bool | |||
2028 | IsTransparentUnionStandardConversion(Sema &S, Expr* From, | |||
2029 | QualType &ToType, | |||
2030 | bool InOverloadResolution, | |||
2031 | StandardConversionSequence &SCS, | |||
2032 | bool CStyle) { | |||
2033 | ||||
2034 | const RecordType *UT = ToType->getAsUnionType(); | |||
2035 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
2036 | return false; | |||
2037 | // The field to initialize within the transparent union. | |||
2038 | RecordDecl *UD = UT->getDecl(); | |||
2039 | // It's compatible if the expression matches any of the fields. | |||
2040 | for (const auto *it : UD->fields()) { | |||
2041 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, | |||
2042 | CStyle, /*AllowObjCWritebackConversion=*/false)) { | |||
2043 | ToType = it->getType(); | |||
2044 | return true; | |||
2045 | } | |||
2046 | } | |||
2047 | return false; | |||
2048 | } | |||
2049 | ||||
2050 | /// IsIntegralPromotion - Determines whether the conversion from the | |||
2051 | /// expression From (whose potentially-adjusted type is FromType) to | |||
2052 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and | |||
2053 | /// sets PromotedType to the promoted type. | |||
2054 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { | |||
2055 | const BuiltinType *To = ToType->getAs<BuiltinType>(); | |||
2056 | // All integers are built-in. | |||
2057 | if (!To) { | |||
2058 | return false; | |||
2059 | } | |||
2060 | ||||
2061 | // An rvalue of type char, signed char, unsigned char, short int, or | |||
2062 | // unsigned short int can be converted to an rvalue of type int if | |||
2063 | // int can represent all the values of the source type; otherwise, | |||
2064 | // the source rvalue can be converted to an rvalue of type unsigned | |||
2065 | // int (C++ 4.5p1). | |||
2066 | if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && | |||
2067 | !FromType->isEnumeralType()) { | |||
2068 | if (// We can promote any signed, promotable integer type to an int | |||
2069 | (FromType->isSignedIntegerType() || | |||
2070 | // We can promote any unsigned integer type whose size is | |||
2071 | // less than int to an int. | |||
2072 | Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { | |||
2073 | return To->getKind() == BuiltinType::Int; | |||
2074 | } | |||
2075 | ||||
2076 | return To->getKind() == BuiltinType::UInt; | |||
2077 | } | |||
2078 | ||||
2079 | // C++11 [conv.prom]p3: | |||
2080 | // A prvalue of an unscoped enumeration type whose underlying type is not | |||
2081 | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the | |||
2082 | // following types that can represent all the values of the enumeration | |||
2083 | // (i.e., the values in the range bmin to bmax as described in 7.2): int, | |||
2084 | // unsigned int, long int, unsigned long int, long long int, or unsigned | |||
2085 | // long long int. If none of the types in that list can represent all the | |||
2086 | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration | |||
2087 | // type can be converted to an rvalue a prvalue of the extended integer type | |||
2088 | // with lowest integer conversion rank (4.13) greater than the rank of long | |||
2089 | // long in which all the values of the enumeration can be represented. If | |||
2090 | // there are two such extended types, the signed one is chosen. | |||
2091 | // C++11 [conv.prom]p4: | |||
2092 | // A prvalue of an unscoped enumeration type whose underlying type is fixed | |||
2093 | // can be converted to a prvalue of its underlying type. Moreover, if | |||
2094 | // integral promotion can be applied to its underlying type, a prvalue of an | |||
2095 | // unscoped enumeration type whose underlying type is fixed can also be | |||
2096 | // converted to a prvalue of the promoted underlying type. | |||
2097 | if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { | |||
2098 | // C++0x 7.2p9: Note that this implicit enum to int conversion is not | |||
2099 | // provided for a scoped enumeration. | |||
2100 | if (FromEnumType->getDecl()->isScoped()) | |||
2101 | return false; | |||
2102 | ||||
2103 | // We can perform an integral promotion to the underlying type of the enum, | |||
2104 | // even if that's not the promoted type. Note that the check for promoting | |||
2105 | // the underlying type is based on the type alone, and does not consider | |||
2106 | // the bitfield-ness of the actual source expression. | |||
2107 | if (FromEnumType->getDecl()->isFixed()) { | |||
2108 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); | |||
2109 | return Context.hasSameUnqualifiedType(Underlying, ToType) || | |||
2110 | IsIntegralPromotion(nullptr, Underlying, ToType); | |||
2111 | } | |||
2112 | ||||
2113 | // We have already pre-calculated the promotion type, so this is trivial. | |||
2114 | if (ToType->isIntegerType() && | |||
2115 | isCompleteType(From->getBeginLoc(), FromType)) | |||
2116 | return Context.hasSameUnqualifiedType( | |||
2117 | ToType, FromEnumType->getDecl()->getPromotionType()); | |||
2118 | ||||
2119 | // C++ [conv.prom]p5: | |||
2120 | // If the bit-field has an enumerated type, it is treated as any other | |||
2121 | // value of that type for promotion purposes. | |||
2122 | // | |||
2123 | // ... so do not fall through into the bit-field checks below in C++. | |||
2124 | if (getLangOpts().CPlusPlus) | |||
2125 | return false; | |||
2126 | } | |||
2127 | ||||
2128 | // C++0x [conv.prom]p2: | |||
2129 | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted | |||
2130 | // to an rvalue a prvalue of the first of the following types that can | |||
2131 | // represent all the values of its underlying type: int, unsigned int, | |||
2132 | // long int, unsigned long int, long long int, or unsigned long long int. | |||
2133 | // If none of the types in that list can represent all the values of its | |||
2134 | // underlying type, an rvalue a prvalue of type char16_t, char32_t, | |||
2135 | // or wchar_t can be converted to an rvalue a prvalue of its underlying | |||
2136 | // type. | |||
2137 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && | |||
2138 | ToType->isIntegerType()) { | |||
2139 | // Determine whether the type we're converting from is signed or | |||
2140 | // unsigned. | |||
2141 | bool FromIsSigned = FromType->isSignedIntegerType(); | |||
2142 | uint64_t FromSize = Context.getTypeSize(FromType); | |||
2143 | ||||
2144 | // The types we'll try to promote to, in the appropriate | |||
2145 | // order. Try each of these types. | |||
2146 | QualType PromoteTypes[6] = { | |||
2147 | Context.IntTy, Context.UnsignedIntTy, | |||
2148 | Context.LongTy, Context.UnsignedLongTy , | |||
2149 | Context.LongLongTy, Context.UnsignedLongLongTy | |||
2150 | }; | |||
2151 | for (int Idx = 0; Idx < 6; ++Idx) { | |||
2152 | uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); | |||
2153 | if (FromSize < ToSize || | |||
2154 | (FromSize == ToSize && | |||
2155 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { | |||
2156 | // We found the type that we can promote to. If this is the | |||
2157 | // type we wanted, we have a promotion. Otherwise, no | |||
2158 | // promotion. | |||
2159 | return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); | |||
2160 | } | |||
2161 | } | |||
2162 | } | |||
2163 | ||||
2164 | // An rvalue for an integral bit-field (9.6) can be converted to an | |||
2165 | // rvalue of type int if int can represent all the values of the | |||
2166 | // bit-field; otherwise, it can be converted to unsigned int if | |||
2167 | // unsigned int can represent all the values of the bit-field. If | |||
2168 | // the bit-field is larger yet, no integral promotion applies to | |||
2169 | // it. If the bit-field has an enumerated type, it is treated as any | |||
2170 | // other value of that type for promotion purposes (C++ 4.5p3). | |||
2171 | // FIXME: We should delay checking of bit-fields until we actually perform the | |||
2172 | // conversion. | |||
2173 | // | |||
2174 | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be | |||
2175 | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum | |||
2176 | // bit-fields and those whose underlying type is larger than int) for GCC | |||
2177 | // compatibility. | |||
2178 | if (From) { | |||
2179 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { | |||
2180 | Optional<llvm::APSInt> BitWidth; | |||
2181 | if (FromType->isIntegralType(Context) && | |||
2182 | (BitWidth = | |||
2183 | MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { | |||
2184 | llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); | |||
2185 | ToSize = Context.getTypeSize(ToType); | |||
2186 | ||||
2187 | // Are we promoting to an int from a bitfield that fits in an int? | |||
2188 | if (*BitWidth < ToSize || | |||
2189 | (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { | |||
2190 | return To->getKind() == BuiltinType::Int; | |||
2191 | } | |||
2192 | ||||
2193 | // Are we promoting to an unsigned int from an unsigned bitfield | |||
2194 | // that fits into an unsigned int? | |||
2195 | if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { | |||
2196 | return To->getKind() == BuiltinType::UInt; | |||
2197 | } | |||
2198 | ||||
2199 | return false; | |||
2200 | } | |||
2201 | } | |||
2202 | } | |||
2203 | ||||
2204 | // An rvalue of type bool can be converted to an rvalue of type int, | |||
2205 | // with false becoming zero and true becoming one (C++ 4.5p4). | |||
2206 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { | |||
2207 | return true; | |||
2208 | } | |||
2209 | ||||
2210 | return false; | |||
2211 | } | |||
2212 | ||||
2213 | /// IsFloatingPointPromotion - Determines whether the conversion from | |||
2214 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, | |||
2215 | /// returns true and sets PromotedType to the promoted type. | |||
2216 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { | |||
2217 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) | |||
2218 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { | |||
2219 | /// An rvalue of type float can be converted to an rvalue of type | |||
2220 | /// double. (C++ 4.6p1). | |||
2221 | if (FromBuiltin->getKind() == BuiltinType::Float && | |||
2222 | ToBuiltin->getKind() == BuiltinType::Double) | |||
2223 | return true; | |||
2224 | ||||
2225 | // C99 6.3.1.5p1: | |||
2226 | // When a float is promoted to double or long double, or a | |||
2227 | // double is promoted to long double [...]. | |||
2228 | if (!getLangOpts().CPlusPlus && | |||
2229 | (FromBuiltin->getKind() == BuiltinType::Float || | |||
2230 | FromBuiltin->getKind() == BuiltinType::Double) && | |||
2231 | (ToBuiltin->getKind() == BuiltinType::LongDouble || | |||
2232 | ToBuiltin->getKind() == BuiltinType::Float128 || | |||
2233 | ToBuiltin->getKind() == BuiltinType::Ibm128)) | |||
2234 | return true; | |||
2235 | ||||
2236 | // Half can be promoted to float. | |||
2237 | if (!getLangOpts().NativeHalfType && | |||
2238 | FromBuiltin->getKind() == BuiltinType::Half && | |||
2239 | ToBuiltin->getKind() == BuiltinType::Float) | |||
2240 | return true; | |||
2241 | } | |||
2242 | ||||
2243 | return false; | |||
2244 | } | |||
2245 | ||||
2246 | /// Determine if a conversion is a complex promotion. | |||
2247 | /// | |||
2248 | /// A complex promotion is defined as a complex -> complex conversion | |||
2249 | /// where the conversion between the underlying real types is a | |||
2250 | /// floating-point or integral promotion. | |||
2251 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { | |||
2252 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); | |||
2253 | if (!FromComplex) | |||
2254 | return false; | |||
2255 | ||||
2256 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); | |||
2257 | if (!ToComplex) | |||
2258 | return false; | |||
2259 | ||||
2260 | return IsFloatingPointPromotion(FromComplex->getElementType(), | |||
2261 | ToComplex->getElementType()) || | |||
2262 | IsIntegralPromotion(nullptr, FromComplex->getElementType(), | |||
2263 | ToComplex->getElementType()); | |||
2264 | } | |||
2265 | ||||
2266 | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from | |||
2267 | /// the pointer type FromPtr to a pointer to type ToPointee, with the | |||
2268 | /// same type qualifiers as FromPtr has on its pointee type. ToType, | |||
2269 | /// if non-empty, will be a pointer to ToType that may or may not have | |||
2270 | /// the right set of qualifiers on its pointee. | |||
2271 | /// | |||
2272 | static QualType | |||
2273 | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, | |||
2274 | QualType ToPointee, QualType ToType, | |||
2275 | ASTContext &Context, | |||
2276 | bool StripObjCLifetime = false) { | |||
2277 | assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2279, __extension__ __PRETTY_FUNCTION__ )) | |||
2278 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2279, __extension__ __PRETTY_FUNCTION__ )) | |||
2279 | "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type ::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer ) && "Invalid similarly-qualified pointer type") ? void (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "clang/lib/Sema/SemaOverload.cpp", 2279, __extension__ __PRETTY_FUNCTION__ )); | |||
2280 | ||||
2281 | /// Conversions to 'id' subsume cv-qualifier conversions. | |||
2282 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) | |||
2283 | return ToType.getUnqualifiedType(); | |||
2284 | ||||
2285 | QualType CanonFromPointee | |||
2286 | = Context.getCanonicalType(FromPtr->getPointeeType()); | |||
2287 | QualType CanonToPointee = Context.getCanonicalType(ToPointee); | |||
2288 | Qualifiers Quals = CanonFromPointee.getQualifiers(); | |||
2289 | ||||
2290 | if (StripObjCLifetime) | |||
2291 | Quals.removeObjCLifetime(); | |||
2292 | ||||
2293 | // Exact qualifier match -> return the pointer type we're converting to. | |||
2294 | if (CanonToPointee.getLocalQualifiers() == Quals) { | |||
2295 | // ToType is exactly what we need. Return it. | |||
2296 | if (!ToType.isNull()) | |||
2297 | return ToType.getUnqualifiedType(); | |||
2298 | ||||
2299 | // Build a pointer to ToPointee. It has the right qualifiers | |||
2300 | // already. | |||
2301 | if (isa<ObjCObjectPointerType>(ToType)) | |||
2302 | return Context.getObjCObjectPointerType(ToPointee); | |||
2303 | return Context.getPointerType(ToPointee); | |||
2304 | } | |||
2305 | ||||
2306 | // Just build a canonical type that has the right qualifiers. | |||
2307 | QualType QualifiedCanonToPointee | |||
2308 | = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); | |||
2309 | ||||
2310 | if (isa<ObjCObjectPointerType>(ToType)) | |||
2311 | return Context.getObjCObjectPointerType(QualifiedCanonToPointee); | |||
2312 | return Context.getPointerType(QualifiedCanonToPointee); | |||
2313 | } | |||
2314 | ||||
2315 | static bool isNullPointerConstantForConversion(Expr *Expr, | |||
2316 | bool InOverloadResolution, | |||
2317 | ASTContext &Context) { | |||
2318 | // Handle value-dependent integral null pointer constants correctly. | |||
2319 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 | |||
2320 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && | |||
2321 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) | |||
2322 | return !InOverloadResolution; | |||
2323 | ||||
2324 | return Expr->isNullPointerConstant(Context, | |||
2325 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull | |||
2326 | : Expr::NPC_ValueDependentIsNull); | |||
2327 | } | |||
2328 | ||||
2329 | /// IsPointerConversion - Determines whether the conversion of the | |||
2330 | /// expression From, which has the (possibly adjusted) type FromType, | |||
2331 | /// can be converted to the type ToType via a pointer conversion (C++ | |||
2332 | /// 4.10). If so, returns true and places the converted type (that | |||
2333 | /// might differ from ToType in its cv-qualifiers at some level) into | |||
2334 | /// ConvertedType. | |||
2335 | /// | |||
2336 | /// This routine also supports conversions to and from block pointers | |||
2337 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and | |||
2338 | /// pointers to interfaces. FIXME: Once we've determined the | |||
2339 | /// appropriate overloading rules for Objective-C, we may want to | |||
2340 | /// split the Objective-C checks into a different routine; however, | |||
2341 | /// GCC seems to consider all of these conversions to be pointer | |||
2342 | /// conversions, so for now they live here. IncompatibleObjC will be | |||
2343 | /// set if the conversion is an allowed Objective-C conversion that | |||
2344 | /// should result in a warning. | |||
2345 | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, | |||
2346 | bool InOverloadResolution, | |||
2347 | QualType& ConvertedType, | |||
2348 | bool &IncompatibleObjC) { | |||
2349 | IncompatibleObjC = false; | |||
2350 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, | |||
2351 | IncompatibleObjC)) | |||
2352 | return true; | |||
2353 | ||||
2354 | // Conversion from a null pointer constant to any Objective-C pointer type. | |||
2355 | if (ToType->isObjCObjectPointerType() && | |||
2356 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2357 | ConvertedType = ToType; | |||
2358 | return true; | |||
2359 | } | |||
2360 | ||||
2361 | // Blocks: Block pointers can be converted to void*. | |||
2362 | if (FromType->isBlockPointerType() && ToType->isPointerType() && | |||
2363 | ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { | |||
2364 | ConvertedType = ToType; | |||
2365 | return true; | |||
2366 | } | |||
2367 | // Blocks: A null pointer constant can be converted to a block | |||
2368 | // pointer type. | |||
2369 | if (ToType->isBlockPointerType() && | |||
2370 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2371 | ConvertedType = ToType; | |||
2372 | return true; | |||
2373 | } | |||
2374 | ||||
2375 | // If the left-hand-side is nullptr_t, the right side can be a null | |||
2376 | // pointer constant. | |||
2377 | if (ToType->isNullPtrType() && | |||
2378 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2379 | ConvertedType = ToType; | |||
2380 | return true; | |||
2381 | } | |||
2382 | ||||
2383 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); | |||
2384 | if (!ToTypePtr) | |||
2385 | return false; | |||
2386 | ||||
2387 | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). | |||
2388 | if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2389 | ConvertedType = ToType; | |||
2390 | return true; | |||
2391 | } | |||
2392 | ||||
2393 | // Beyond this point, both types need to be pointers | |||
2394 | // , including objective-c pointers. | |||
2395 | QualType ToPointeeType = ToTypePtr->getPointeeType(); | |||
2396 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && | |||
2397 | !getLangOpts().ObjCAutoRefCount) { | |||
2398 | ConvertedType = BuildSimilarlyQualifiedPointerType( | |||
2399 | FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, | |||
2400 | Context); | |||
2401 | return true; | |||
2402 | } | |||
2403 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); | |||
2404 | if (!FromTypePtr) | |||
2405 | return false; | |||
2406 | ||||
2407 | QualType FromPointeeType = FromTypePtr->getPointeeType(); | |||
2408 | ||||
2409 | // If the unqualified pointee types are the same, this can't be a | |||
2410 | // pointer conversion, so don't do all of the work below. | |||
2411 | if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) | |||
2412 | return false; | |||
2413 | ||||
2414 | // An rvalue of type "pointer to cv T," where T is an object type, | |||
2415 | // can be converted to an rvalue of type "pointer to cv void" (C++ | |||
2416 | // 4.10p2). | |||
2417 | if (FromPointeeType->isIncompleteOrObjectType() && | |||
2418 | ToPointeeType->isVoidType()) { | |||
2419 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2420 | ToPointeeType, | |||
2421 | ToType, Context, | |||
2422 | /*StripObjCLifetime=*/true); | |||
2423 | return true; | |||
2424 | } | |||
2425 | ||||
2426 | // MSVC allows implicit function to void* type conversion. | |||
2427 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && | |||
2428 | ToPointeeType->isVoidType()) { | |||
2429 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2430 | ToPointeeType, | |||
2431 | ToType, Context); | |||
2432 | return true; | |||
2433 | } | |||
2434 | ||||
2435 | // When we're overloading in C, we allow a special kind of pointer | |||
2436 | // conversion for compatible-but-not-identical pointee types. | |||
2437 | if (!getLangOpts().CPlusPlus && | |||
2438 | Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { | |||
2439 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2440 | ToPointeeType, | |||
2441 | ToType, Context); | |||
2442 | return true; | |||
2443 | } | |||
2444 | ||||
2445 | // C++ [conv.ptr]p3: | |||
2446 | // | |||
2447 | // An rvalue of type "pointer to cv D," where D is a class type, | |||
2448 | // can be converted to an rvalue of type "pointer to cv B," where | |||
2449 | // B is a base class (clause 10) of D. If B is an inaccessible | |||
2450 | // (clause 11) or ambiguous (10.2) base class of D, a program that | |||
2451 | // necessitates this conversion is ill-formed. The result of the | |||
2452 | // conversion is a pointer to the base class sub-object of the | |||
2453 | // derived class object. The null pointer value is converted to | |||
2454 | // the null pointer value of the destination type. | |||
2455 | // | |||
2456 | // Note that we do not check for ambiguity or inaccessibility | |||
2457 | // here. That is handled by CheckPointerConversion. | |||
2458 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && | |||
2459 | ToPointeeType->isRecordType() && | |||
2460 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && | |||
2461 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { | |||
2462 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2463 | ToPointeeType, | |||
2464 | ToType, Context); | |||
2465 | return true; | |||
2466 | } | |||
2467 | ||||
2468 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && | |||
2469 | Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { | |||
2470 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2471 | ToPointeeType, | |||
2472 | ToType, Context); | |||
2473 | return true; | |||
2474 | } | |||
2475 | ||||
2476 | return false; | |||
2477 | } | |||
2478 | ||||
2479 | /// Adopt the given qualifiers for the given type. | |||
2480 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ | |||
2481 | Qualifiers TQs = T.getQualifiers(); | |||
2482 | ||||
2483 | // Check whether qualifiers already match. | |||
2484 | if (TQs == Qs) | |||
2485 | return T; | |||
2486 | ||||
2487 | if (Qs.compatiblyIncludes(TQs)) | |||
2488 | return Context.getQualifiedType(T, Qs); | |||
2489 | ||||
2490 | return Context.getQualifiedType(T.getUnqualifiedType(), Qs); | |||
2491 | } | |||
2492 | ||||
2493 | /// isObjCPointerConversion - Determines whether this is an | |||
2494 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, | |||
2495 | /// with the same arguments and return values. | |||
2496 | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, | |||
2497 | QualType& ConvertedType, | |||
2498 | bool &IncompatibleObjC) { | |||
2499 | if (!getLangOpts().ObjC) | |||
2500 | return false; | |||
2501 | ||||
2502 | // The set of qualifiers on the type we're converting from. | |||
2503 | Qualifiers FromQualifiers = FromType.getQualifiers(); | |||
2504 | ||||
2505 | // First, we handle all conversions on ObjC object pointer types. | |||
2506 | const ObjCObjectPointerType* ToObjCPtr = | |||
2507 | ToType->getAs<ObjCObjectPointerType>(); | |||
2508 | const ObjCObjectPointerType *FromObjCPtr = | |||
2509 | FromType->getAs<ObjCObjectPointerType>(); | |||
2510 | ||||
2511 | if (ToObjCPtr && FromObjCPtr) { | |||
2512 | // If the pointee types are the same (ignoring qualifications), | |||
2513 | // then this is not a pointer conversion. | |||
2514 | if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), | |||
2515 | FromObjCPtr->getPointeeType())) | |||
2516 | return false; | |||
2517 | ||||
2518 | // Conversion between Objective-C pointers. | |||
2519 | if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { | |||
2520 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); | |||
2521 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); | |||
2522 | if (getLangOpts().CPlusPlus && LHS && RHS && | |||
2523 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( | |||
2524 | FromObjCPtr->getPointeeType())) | |||
2525 | return false; | |||
2526 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, | |||
2527 | ToObjCPtr->getPointeeType(), | |||
2528 | ToType, Context); | |||
2529 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2530 | return true; | |||
2531 | } | |||
2532 | ||||
2533 | if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { | |||
2534 | // Okay: this is some kind of implicit downcast of Objective-C | |||
2535 | // interfaces, which is permitted. However, we're going to | |||
2536 | // complain about it. | |||
2537 | IncompatibleObjC = true; | |||
2538 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, | |||
2539 | ToObjCPtr->getPointeeType(), | |||
2540 | ToType, Context); | |||
2541 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2542 | return true; | |||
2543 | } | |||
2544 | } | |||
2545 | // Beyond this point, both types need to be C pointers or block pointers. | |||
2546 | QualType ToPointeeType; | |||
2547 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) | |||
2548 | ToPointeeType = ToCPtr->getPointeeType(); | |||
2549 | else if (const BlockPointerType *ToBlockPtr = | |||
2550 | ToType->getAs<BlockPointerType>()) { | |||
2551 | // Objective C++: We're able to convert from a pointer to any object | |||
2552 | // to a block pointer type. | |||
2553 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { | |||
2554 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2555 | return true; | |||
2556 | } | |||
2557 | ToPointeeType = ToBlockPtr->getPointeeType(); | |||
2558 | } | |||
2559 | else if (FromType->getAs<BlockPointerType>() && | |||
2560 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { | |||
2561 | // Objective C++: We're able to convert from a block pointer type to a | |||
2562 | // pointer to any object. | |||
2563 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2564 | return true; | |||
2565 | } | |||
2566 | else | |||
2567 | return false; | |||
2568 | ||||
2569 | QualType FromPointeeType; | |||
2570 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) | |||
2571 | FromPointeeType = FromCPtr->getPointeeType(); | |||
2572 | else if (const BlockPointerType *FromBlockPtr = | |||
2573 | FromType->getAs<BlockPointerType>()) | |||
2574 | FromPointeeType = FromBlockPtr->getPointeeType(); | |||
2575 | else | |||
2576 | return false; | |||
2577 | ||||
2578 | // If we have pointers to pointers, recursively check whether this | |||
2579 | // is an Objective-C conversion. | |||
2580 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && | |||
2581 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, | |||
2582 | IncompatibleObjC)) { | |||
2583 | // We always complain about this conversion. | |||
2584 | IncompatibleObjC = true; | |||
2585 | ConvertedType = Context.getPointerType(ConvertedType); | |||
2586 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2587 | return true; | |||
2588 | } | |||
2589 | // Allow conversion of pointee being objective-c pointer to another one; | |||
2590 | // as in I* to id. | |||
2591 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && | |||
2592 | ToPointeeType->getAs<ObjCObjectPointerType>() && | |||
2593 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, | |||
2594 | IncompatibleObjC)) { | |||
2595 | ||||
2596 | ConvertedType = Context.getPointerType(ConvertedType); | |||
2597 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2598 | return true; | |||
2599 | } | |||
2600 | ||||
2601 | // If we have pointers to functions or blocks, check whether the only | |||
2602 | // differences in the argument and result types are in Objective-C | |||
2603 | // pointer conversions. If so, we permit the conversion (but | |||
2604 | // complain about it). | |||
2605 | const FunctionProtoType *FromFunctionType | |||
2606 | = FromPointeeType->getAs<FunctionProtoType>(); | |||
2607 | const FunctionProtoType *ToFunctionType | |||
2608 | = ToPointeeType->getAs<FunctionProtoType>(); | |||
2609 | if (FromFunctionType && ToFunctionType) { | |||
2610 | // If the function types are exactly the same, this isn't an | |||
2611 | // Objective-C pointer conversion. | |||
2612 | if (Context.getCanonicalType(FromPointeeType) | |||
2613 | == Context.getCanonicalType(ToPointeeType)) | |||
2614 | return false; | |||
2615 | ||||
2616 | // Perform the quick checks that will tell us whether these | |||
2617 | // function types are obviously different. | |||
2618 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || | |||
2619 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || | |||
2620 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) | |||
2621 | return false; | |||
2622 | ||||
2623 | bool HasObjCConversion = false; | |||
2624 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == | |||
2625 | Context.getCanonicalType(ToFunctionType->getReturnType())) { | |||
2626 | // Okay, the types match exactly. Nothing to do. | |||
2627 | } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), | |||
2628 | ToFunctionType->getReturnType(), | |||
2629 | ConvertedType, IncompatibleObjC)) { | |||
2630 | // Okay, we have an Objective-C pointer conversion. | |||
2631 | HasObjCConversion = true; | |||
2632 | } else { | |||
2633 | // Function types are too different. Abort. | |||
2634 | return false; | |||
2635 | } | |||
2636 | ||||
2637 | // Check argument types. | |||
2638 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); | |||
2639 | ArgIdx != NumArgs; ++ArgIdx) { | |||
2640 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); | |||
2641 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); | |||
2642 | if (Context.getCanonicalType(FromArgType) | |||
2643 | == Context.getCanonicalType(ToArgType)) { | |||
2644 | // Okay, the types match exactly. Nothing to do. | |||
2645 | } else if (isObjCPointerConversion(FromArgType, ToArgType, | |||
2646 | ConvertedType, IncompatibleObjC)) { | |||
2647 | // Okay, we have an Objective-C pointer conversion. | |||
2648 | HasObjCConversion = true; | |||
2649 | } else { | |||
2650 | // Argument types are too different. Abort. | |||
2651 | return false; | |||
2652 | } | |||
2653 | } | |||
2654 | ||||
2655 | if (HasObjCConversion) { | |||
2656 | // We had an Objective-C conversion. Allow this pointer | |||
2657 | // conversion, but complain about it. | |||
2658 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2659 | IncompatibleObjC = true; | |||
2660 | return true; | |||
2661 | } | |||
2662 | } | |||
2663 | ||||
2664 | return false; | |||
2665 | } | |||
2666 | ||||
2667 | /// Determine whether this is an Objective-C writeback conversion, | |||
2668 | /// used for parameter passing when performing automatic reference counting. | |||
2669 | /// | |||
2670 | /// \param FromType The type we're converting form. | |||
2671 | /// | |||
2672 | /// \param ToType The type we're converting to. | |||
2673 | /// | |||
2674 | /// \param ConvertedType The type that will be produced after applying | |||
2675 | /// this conversion. | |||
2676 | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, | |||
2677 | QualType &ConvertedType) { | |||
2678 | if (!getLangOpts().ObjCAutoRefCount || | |||
2679 | Context.hasSameUnqualifiedType(FromType, ToType)) | |||
2680 | return false; | |||
2681 | ||||
2682 | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). | |||
2683 | QualType ToPointee; | |||
2684 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) | |||
2685 | ToPointee = ToPointer->getPointeeType(); | |||
2686 | else | |||
2687 | return false; | |||
2688 | ||||
2689 | Qualifiers ToQuals = ToPointee.getQualifiers(); | |||
2690 | if (!ToPointee->isObjCLifetimeType() || | |||
2691 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || | |||
2692 | !ToQuals.withoutObjCLifetime().empty()) | |||
2693 | return false; | |||
2694 | ||||
2695 | // Argument must be a pointer to __strong to __weak. | |||
2696 | QualType FromPointee; | |||
2697 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) | |||
2698 | FromPointee = FromPointer->getPointeeType(); | |||
2699 | else | |||
2700 | return false; | |||
2701 | ||||
2702 | Qualifiers FromQuals = FromPointee.getQualifiers(); | |||
2703 | if (!FromPointee->isObjCLifetimeType() || | |||
2704 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && | |||
2705 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) | |||
2706 | return false; | |||
2707 | ||||
2708 | // Make sure that we have compatible qualifiers. | |||
2709 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
2710 | if (!ToQuals.compatiblyIncludes(FromQuals)) | |||
2711 | return false; | |||
2712 | ||||
2713 | // Remove qualifiers from the pointee type we're converting from; they | |||
2714 | // aren't used in the compatibility check belong, and we'll be adding back | |||
2715 | // qualifiers (with __autoreleasing) if the compatibility check succeeds. | |||
2716 | FromPointee = FromPointee.getUnqualifiedType(); | |||
2717 | ||||
2718 | // The unqualified form of the pointee types must be compatible. | |||
2719 | ToPointee = ToPointee.getUnqualifiedType(); | |||
2720 | bool IncompatibleObjC; | |||
2721 | if (Context.typesAreCompatible(FromPointee, ToPointee)) | |||
2722 | FromPointee = ToPointee; | |||
2723 | else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, | |||
2724 | IncompatibleObjC)) | |||
2725 | return false; | |||
2726 | ||||
2727 | /// Construct the type we're converting to, which is a pointer to | |||
2728 | /// __autoreleasing pointee. | |||
2729 | FromPointee = Context.getQualifiedType(FromPointee, FromQuals); | |||
2730 | ConvertedType = Context.getPointerType(FromPointee); | |||
2731 | return true; | |||
2732 | } | |||
2733 | ||||
2734 | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, | |||
2735 | QualType& ConvertedType) { | |||
2736 | QualType ToPointeeType; | |||
2737 | if (const BlockPointerType *ToBlockPtr = | |||
2738 | ToType->getAs<BlockPointerType>()) | |||
2739 | ToPointeeType = ToBlockPtr->getPointeeType(); | |||
2740 | else | |||
2741 | return false; | |||
2742 | ||||
2743 | QualType FromPointeeType; | |||
2744 | if (const BlockPointerType *FromBlockPtr = | |||
2745 | FromType->getAs<BlockPointerType>()) | |||
2746 | FromPointeeType = FromBlockPtr->getPointeeType(); | |||
2747 | else | |||
2748 | return false; | |||
2749 | // We have pointer to blocks, check whether the only | |||
2750 | // differences in the argument and result types are in Objective-C | |||
2751 | // pointer conversions. If so, we permit the conversion. | |||
2752 | ||||
2753 | const FunctionProtoType *FromFunctionType | |||
2754 | = FromPointeeType->getAs<FunctionProtoType>(); | |||
2755 | const FunctionProtoType *ToFunctionType | |||
2756 | = ToPointeeType->getAs<FunctionProtoType>(); | |||
2757 | ||||
2758 | if (!FromFunctionType || !ToFunctionType) | |||
2759 | return false; | |||
2760 | ||||
2761 | if (Context.hasSameType(FromPointeeType, ToPointeeType)) | |||
2762 | return true; | |||
2763 | ||||
2764 | // Perform the quick checks that will tell us whether these | |||
2765 | // function types are obviously different. | |||
2766 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || | |||
2767 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) | |||
2768 | return false; | |||
2769 | ||||
2770 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); | |||
2771 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); | |||
2772 | if (FromEInfo != ToEInfo) | |||
2773 | return false; | |||
2774 | ||||
2775 | bool IncompatibleObjC = false; | |||
2776 | if (Context.hasSameType(FromFunctionType->getReturnType(), | |||
2777 | ToFunctionType->getReturnType())) { | |||
2778 | // Okay, the types match exactly. Nothing to do. | |||
2779 | } else { | |||
2780 | QualType RHS = FromFunctionType->getReturnType(); | |||
2781 | QualType LHS = ToFunctionType->getReturnType(); | |||
2782 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && | |||
2783 | !RHS.hasQualifiers() && LHS.hasQualifiers()) | |||
2784 | LHS = LHS.getUnqualifiedType(); | |||
2785 | ||||
2786 | if (Context.hasSameType(RHS,LHS)) { | |||
2787 | // OK exact match. | |||
2788 | } else if (isObjCPointerConversion(RHS, LHS, | |||
2789 | ConvertedType, IncompatibleObjC)) { | |||
2790 | if (IncompatibleObjC) | |||
2791 | return false; | |||
2792 | // Okay, we have an Objective-C pointer conversion. | |||
2793 | } | |||
2794 | else | |||
2795 | return false; | |||
2796 | } | |||
2797 | ||||
2798 | // Check argument types. | |||
2799 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); | |||
2800 | ArgIdx != NumArgs; ++ArgIdx) { | |||
2801 | IncompatibleObjC = false; | |||
2802 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); | |||
2803 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); | |||
2804 | if (Context.hasSameType(FromArgType, ToArgType)) { | |||
2805 | // Okay, the types match exactly. Nothing to do. | |||
2806 | } else if (isObjCPointerConversion(ToArgType, FromArgType, | |||
2807 | ConvertedType, IncompatibleObjC)) { | |||
2808 | if (IncompatibleObjC) | |||
2809 | return false; | |||
2810 | // Okay, we have an Objective-C pointer conversion. | |||
2811 | } else | |||
2812 | // Argument types are too different. Abort. | |||
2813 | return false; | |||
2814 | } | |||
2815 | ||||
2816 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; | |||
2817 | bool CanUseToFPT, CanUseFromFPT; | |||
2818 | if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, | |||
2819 | CanUseToFPT, CanUseFromFPT, | |||
2820 | NewParamInfos)) | |||
2821 | return false; | |||
2822 | ||||
2823 | ConvertedType = ToType; | |||
2824 | return true; | |||
2825 | } | |||
2826 | ||||
2827 | enum { | |||
2828 | ft_default, | |||
2829 | ft_different_class, | |||
2830 | ft_parameter_arity, | |||
2831 | ft_parameter_mismatch, | |||
2832 | ft_return_type, | |||
2833 | ft_qualifer_mismatch, | |||
2834 | ft_noexcept | |||
2835 | }; | |||
2836 | ||||
2837 | /// Attempts to get the FunctionProtoType from a Type. Handles | |||
2838 | /// MemberFunctionPointers properly. | |||
2839 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { | |||
2840 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) | |||
2841 | return FPT; | |||
2842 | ||||
2843 | if (auto *MPT = FromType->getAs<MemberPointerType>()) | |||
2844 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); | |||
2845 | ||||
2846 | return nullptr; | |||
2847 | } | |||
2848 | ||||
2849 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing | |||
2850 | /// function types. Catches different number of parameter, mismatch in | |||
2851 | /// parameter types, and different return types. | |||
2852 | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, | |||
2853 | QualType FromType, QualType ToType) { | |||
2854 | // If either type is not valid, include no extra info. | |||
2855 | if (FromType.isNull() || ToType.isNull()) { | |||
2856 | PDiag << ft_default; | |||
2857 | return; | |||
2858 | } | |||
2859 | ||||
2860 | // Get the function type from the pointers. | |||
2861 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { | |||
2862 | const auto *FromMember = FromType->castAs<MemberPointerType>(), | |||
2863 | *ToMember = ToType->castAs<MemberPointerType>(); | |||
2864 | if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { | |||
2865 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) | |||
2866 | << QualType(FromMember->getClass(), 0); | |||
2867 | return; | |||
2868 | } | |||
2869 | FromType = FromMember->getPointeeType(); | |||
2870 | ToType = ToMember->getPointeeType(); | |||
2871 | } | |||
2872 | ||||
2873 | if (FromType->isPointerType()) | |||
2874 | FromType = FromType->getPointeeType(); | |||
2875 | if (ToType->isPointerType()) | |||
2876 | ToType = ToType->getPointeeType(); | |||
2877 | ||||
2878 | // Remove references. | |||
2879 | FromType = FromType.getNonReferenceType(); | |||
2880 | ToType = ToType.getNonReferenceType(); | |||
2881 | ||||
2882 | // Don't print extra info for non-specialized template functions. | |||
2883 | if (FromType->isInstantiationDependentType() && | |||
2884 | !FromType->getAs<TemplateSpecializationType>()) { | |||
2885 | PDiag << ft_default; | |||
2886 | return; | |||
2887 | } | |||
2888 | ||||
2889 | // No extra info for same types. | |||
2890 | if (Context.hasSameType(FromType, ToType)) { | |||
2891 | PDiag << ft_default; | |||
2892 | return; | |||
2893 | } | |||
2894 | ||||
2895 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), | |||
2896 | *ToFunction = tryGetFunctionProtoType(ToType); | |||
2897 | ||||
2898 | // Both types need to be function types. | |||
2899 | if (!FromFunction || !ToFunction) { | |||
2900 | PDiag << ft_default; | |||
2901 | return; | |||
2902 | } | |||
2903 | ||||
2904 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { | |||
2905 | PDiag << ft_parameter_arity << ToFunction->getNumParams() | |||
2906 | << FromFunction->getNumParams(); | |||
2907 | return; | |||
2908 | } | |||
2909 | ||||
2910 | // Handle different parameter types. | |||
2911 | unsigned ArgPos; | |||
2912 | if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { | |||
2913 | PDiag << ft_parameter_mismatch << ArgPos + 1 | |||
2914 | << ToFunction->getParamType(ArgPos) | |||
2915 | << FromFunction->getParamType(ArgPos); | |||
2916 | return; | |||
2917 | } | |||
2918 | ||||
2919 | // Handle different return type. | |||
2920 | if (!Context.hasSameType(FromFunction->getReturnType(), | |||
2921 | ToFunction->getReturnType())) { | |||
2922 | PDiag << ft_return_type << ToFunction->getReturnType() | |||
2923 | << FromFunction->getReturnType(); | |||
2924 | return; | |||
2925 | } | |||
2926 | ||||
2927 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { | |||
2928 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() | |||
2929 | << FromFunction->getMethodQuals(); | |||
2930 | return; | |||
2931 | } | |||
2932 | ||||
2933 | // Handle exception specification differences on canonical type (in C++17 | |||
2934 | // onwards). | |||
2935 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) | |||
2936 | ->isNothrow() != | |||
2937 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) | |||
2938 | ->isNothrow()) { | |||
2939 | PDiag << ft_noexcept; | |||
2940 | return; | |||
2941 | } | |||
2942 | ||||
2943 | // Unable to find a difference, so add no extra info. | |||
2944 | PDiag << ft_default; | |||
2945 | } | |||
2946 | ||||
2947 | /// FunctionParamTypesAreEqual - This routine checks two function proto types | |||
2948 | /// for equality of their argument types. Caller has already checked that | |||
2949 | /// they have same number of arguments. If the parameters are different, | |||
2950 | /// ArgPos will have the parameter index of the first different parameter. | |||
2951 | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, | |||
2952 | const FunctionProtoType *NewType, | |||
2953 | unsigned *ArgPos) { | |||
2954 | for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), | |||
2955 | N = NewType->param_type_begin(), | |||
2956 | E = OldType->param_type_end(); | |||
2957 | O && (O != E); ++O, ++N) { | |||
2958 | // Ignore address spaces in pointee type. This is to disallow overloading | |||
2959 | // on __ptr32/__ptr64 address spaces. | |||
2960 | QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); | |||
2961 | QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); | |||
2962 | ||||
2963 | if (!Context.hasSameType(Old, New)) { | |||
2964 | if (ArgPos) | |||
2965 | *ArgPos = O - OldType->param_type_begin(); | |||
2966 | return false; | |||
2967 | } | |||
2968 | } | |||
2969 | return true; | |||
2970 | } | |||
2971 | ||||
2972 | /// CheckPointerConversion - Check the pointer conversion from the | |||
2973 | /// expression From to the type ToType. This routine checks for | |||
2974 | /// ambiguous or inaccessible derived-to-base pointer | |||
2975 | /// conversions for which IsPointerConversion has already returned | |||
2976 | /// true. It returns true and produces a diagnostic if there was an | |||
2977 | /// error, or returns false otherwise. | |||
2978 | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, | |||
2979 | CastKind &Kind, | |||
2980 | CXXCastPath& BasePath, | |||
2981 | bool IgnoreBaseAccess, | |||
2982 | bool Diagnose) { | |||
2983 | QualType FromType = From->getType(); | |||
2984 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; | |||
2985 | ||||
2986 | Kind = CK_BitCast; | |||
2987 | ||||
2988 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && | |||
2989 | From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == | |||
2990 | Expr::NPCK_ZeroExpression) { | |||
2991 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) | |||
2992 | DiagRuntimeBehavior(From->getExprLoc(), From, | |||
2993 | PDiag(diag::warn_impcast_bool_to_null_pointer) | |||
2994 | << ToType << From->getSourceRange()); | |||
2995 | else if (!isUnevaluatedContext()) | |||
2996 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) | |||
2997 | << ToType << From->getSourceRange(); | |||
2998 | } | |||
2999 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { | |||
3000 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { | |||
3001 | QualType FromPointeeType = FromPtrType->getPointeeType(), | |||
3002 | ToPointeeType = ToPtrType->getPointeeType(); | |||
3003 | ||||
3004 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && | |||
3005 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { | |||
3006 | // We must have a derived-to-base conversion. Check an | |||
3007 | // ambiguous or inaccessible conversion. | |||
3008 | unsigned InaccessibleID = 0; | |||
3009 | unsigned AmbiguousID = 0; | |||
3010 | if (Diagnose) { | |||
3011 | InaccessibleID = diag::err_upcast_to_inaccessible_base; | |||
3012 | AmbiguousID = diag::err_ambiguous_derived_to_base_conv; | |||
3013 | } | |||
3014 | if (CheckDerivedToBaseConversion( | |||
3015 | FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, | |||
3016 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), | |||
3017 | &BasePath, IgnoreBaseAccess)) | |||
3018 | return true; | |||
3019 | ||||
3020 | // The conversion was successful. | |||
3021 | Kind = CK_DerivedToBase; | |||
3022 | } | |||
3023 | ||||
3024 | if (Diagnose && !IsCStyleOrFunctionalCast && | |||
3025 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { | |||
3026 | assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "clang/lib/Sema/SemaOverload.cpp", 3027, __extension__ __PRETTY_FUNCTION__ )) | |||
3027 | "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "clang/lib/Sema/SemaOverload.cpp", 3027, __extension__ __PRETTY_FUNCTION__ )); | |||
3028 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) | |||
3029 | << From->getSourceRange(); | |||
3030 | } | |||
3031 | } | |||
3032 | } else if (const ObjCObjectPointerType *ToPtrType = | |||
3033 | ToType->getAs<ObjCObjectPointerType>()) { | |||
3034 | if (const ObjCObjectPointerType *FromPtrType = | |||
3035 | FromType->getAs<ObjCObjectPointerType>()) { | |||
3036 | // Objective-C++ conversions are always okay. | |||
3037 | // FIXME: We should have a different class of conversions for the | |||
3038 | // Objective-C++ implicit conversions. | |||
3039 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) | |||
3040 | return false; | |||
3041 | } else if (FromType->isBlockPointerType()) { | |||
3042 | Kind = CK_BlockPointerToObjCPointerCast; | |||
3043 | } else { | |||
3044 | Kind = CK_CPointerToObjCPointerCast; | |||
3045 | } | |||
3046 | } else if (ToType->isBlockPointerType()) { | |||
3047 | if (!FromType->isBlockPointerType()) | |||
3048 | Kind = CK_AnyPointerToBlockPointerCast; | |||
3049 | } | |||
3050 | ||||
3051 | // We shouldn't fall into this case unless it's valid for other | |||
3052 | // reasons. | |||
3053 | if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) | |||
3054 | Kind = CK_NullToPointer; | |||
3055 | ||||
3056 | return false; | |||
3057 | } | |||
3058 | ||||
3059 | /// IsMemberPointerConversion - Determines whether the conversion of the | |||
3060 | /// expression From, which has the (possibly adjusted) type FromType, can be | |||
3061 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). | |||
3062 | /// If so, returns true and places the converted type (that might differ from | |||
3063 | /// ToType in its cv-qualifiers at some level) into ConvertedType. | |||
3064 | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, | |||
3065 | QualType ToType, | |||
3066 | bool InOverloadResolution, | |||
3067 | QualType &ConvertedType) { | |||
3068 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); | |||
3069 | if (!ToTypePtr) | |||
3070 | return false; | |||
3071 | ||||
3072 | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) | |||
3073 | if (From->isNullPointerConstant(Context, | |||
3074 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull | |||
3075 | : Expr::NPC_ValueDependentIsNull)) { | |||
3076 | ConvertedType = ToType; | |||
3077 | return true; | |||
3078 | } | |||
3079 | ||||
3080 | // Otherwise, both types have to be member pointers. | |||
3081 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); | |||
3082 | if (!FromTypePtr) | |||
3083 | return false; | |||
3084 | ||||
3085 | // A pointer to member of B can be converted to a pointer to member of D, | |||
3086 | // where D is derived from B (C++ 4.11p2). | |||
3087 | QualType FromClass(FromTypePtr->getClass(), 0); | |||
3088 | QualType ToClass(ToTypePtr->getClass(), 0); | |||
3089 | ||||
3090 | if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && | |||
3091 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { | |||
3092 | ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), | |||
3093 | ToClass.getTypePtr()); | |||
3094 | return true; | |||
3095 | } | |||
3096 | ||||
3097 | return false; | |||
3098 | } | |||
3099 | ||||
3100 | /// CheckMemberPointerConversion - Check the member pointer conversion from the | |||
3101 | /// expression From to the type ToType. This routine checks for ambiguous or | |||
3102 | /// virtual or inaccessible base-to-derived member pointer conversions | |||
3103 | /// for which IsMemberPointerConversion has already returned true. It returns | |||
3104 | /// true and produces a diagnostic if there was an error, or returns false | |||
3105 | /// otherwise. | |||
3106 | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, | |||
3107 | CastKind &Kind, | |||
3108 | CXXCastPath &BasePath, | |||
3109 | bool IgnoreBaseAccess) { | |||
3110 | QualType FromType = From->getType(); | |||
3111 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); | |||
3112 | if (!FromPtrType) { | |||
3113 | // This must be a null pointer to member pointer conversion | |||
3114 | assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3116, __extension__ __PRETTY_FUNCTION__ )) | |||
3115 | Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3116, __extension__ __PRETTY_FUNCTION__ )) | |||
3116 | "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context , Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!" ) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "clang/lib/Sema/SemaOverload.cpp", 3116, __extension__ __PRETTY_FUNCTION__ )); | |||
3117 | Kind = CK_NullToMemberPointer; | |||
3118 | return false; | |||
3119 | } | |||
3120 | ||||
3121 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); | |||
3122 | assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? void (0) : __assert_fail ( "ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "clang/lib/Sema/SemaOverload.cpp", 3123, __extension__ __PRETTY_FUNCTION__ )) | |||
3123 | "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? void (0) : __assert_fail ( "ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "clang/lib/Sema/SemaOverload.cpp", 3123, __extension__ __PRETTY_FUNCTION__ )); | |||
3124 | ||||
3125 | QualType FromClass = QualType(FromPtrType->getClass(), 0); | |||
3126 | QualType ToClass = QualType(ToPtrType->getClass(), 0); | |||
3127 | ||||
3128 | // FIXME: What about dependent types? | |||
3129 | assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() && "Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\"" , "clang/lib/Sema/SemaOverload.cpp", 3129, __extension__ __PRETTY_FUNCTION__ )); | |||
3130 | assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() && "Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\"" , "clang/lib/Sema/SemaOverload.cpp", 3130, __extension__ __PRETTY_FUNCTION__ )); | |||
3131 | ||||
3132 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3133 | /*DetectVirtual=*/true); | |||
3134 | bool DerivationOkay = | |||
3135 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); | |||
3136 | assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK." ) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "clang/lib/Sema/SemaOverload.cpp", 3137, __extension__ __PRETTY_FUNCTION__ )) | |||
3137 | "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK." ) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "clang/lib/Sema/SemaOverload.cpp", 3137, __extension__ __PRETTY_FUNCTION__ )); | |||
3138 | (void)DerivationOkay; | |||
3139 | ||||
3140 | if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). | |||
3141 | getUnqualifiedType())) { | |||
3142 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); | |||
3143 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) | |||
3144 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); | |||
3145 | return true; | |||
3146 | } | |||
3147 | ||||
3148 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { | |||
3149 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) | |||
3150 | << FromClass << ToClass << QualType(VBase, 0) | |||
3151 | << From->getSourceRange(); | |||
3152 | return true; | |||
3153 | } | |||
3154 | ||||
3155 | if (!IgnoreBaseAccess) | |||
3156 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, | |||
3157 | Paths.front(), | |||
3158 | diag::err_downcast_from_inaccessible_base); | |||
3159 | ||||
3160 | // Must be a base to derived member conversion. | |||
3161 | BuildBasePathArray(Paths, BasePath); | |||
3162 | Kind = CK_BaseToDerivedMemberPointer; | |||
3163 | return false; | |||
3164 | } | |||
3165 | ||||
3166 | /// Determine whether the lifetime conversion between the two given | |||
3167 | /// qualifiers sets is nontrivial. | |||
3168 | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, | |||
3169 | Qualifiers ToQuals) { | |||
3170 | // Converting anything to const __unsafe_unretained is trivial. | |||
3171 | if (ToQuals.hasConst() && | |||
3172 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) | |||
3173 | return false; | |||
3174 | ||||
3175 | return true; | |||
3176 | } | |||
3177 | ||||
3178 | /// Perform a single iteration of the loop for checking if a qualification | |||
3179 | /// conversion is valid. | |||
3180 | /// | |||
3181 | /// Specifically, check whether any change between the qualifiers of \p | |||
3182 | /// FromType and \p ToType is permissible, given knowledge about whether every | |||
3183 | /// outer layer is const-qualified. | |||
3184 | static bool isQualificationConversionStep(QualType FromType, QualType ToType, | |||
3185 | bool CStyle, bool IsTopLevel, | |||
3186 | bool &PreviousToQualsIncludeConst, | |||
3187 | bool &ObjCLifetimeConversion) { | |||
3188 | Qualifiers FromQuals = FromType.getQualifiers(); | |||
3189 | Qualifiers ToQuals = ToType.getQualifiers(); | |||
3190 | ||||
3191 | // Ignore __unaligned qualifier. | |||
3192 | FromQuals.removeUnaligned(); | |||
3193 | ||||
3194 | // Objective-C ARC: | |||
3195 | // Check Objective-C lifetime conversions. | |||
3196 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { | |||
3197 | if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { | |||
3198 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) | |||
3199 | ObjCLifetimeConversion = true; | |||
3200 | FromQuals.removeObjCLifetime(); | |||
3201 | ToQuals.removeObjCLifetime(); | |||
3202 | } else { | |||
3203 | // Qualification conversions cannot cast between different | |||
3204 | // Objective-C lifetime qualifiers. | |||
3205 | return false; | |||
3206 | } | |||
3207 | } | |||
3208 | ||||
3209 | // Allow addition/removal of GC attributes but not changing GC attributes. | |||
3210 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && | |||
3211 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { | |||
3212 | FromQuals.removeObjCGCAttr(); | |||
3213 | ToQuals.removeObjCGCAttr(); | |||
3214 | } | |||
3215 | ||||
3216 | // -- for every j > 0, if const is in cv 1,j then const is in cv | |||
3217 | // 2,j, and similarly for volatile. | |||
3218 | if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) | |||
3219 | return false; | |||
3220 | ||||
3221 | // If address spaces mismatch: | |||
3222 | // - in top level it is only valid to convert to addr space that is a | |||
3223 | // superset in all cases apart from C-style casts where we allow | |||
3224 | // conversions between overlapping address spaces. | |||
3225 | // - in non-top levels it is not a valid conversion. | |||
3226 | if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && | |||
3227 | (!IsTopLevel || | |||
3228 | !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || | |||
3229 | (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) | |||
3230 | return false; | |||
3231 | ||||
3232 | // -- if the cv 1,j and cv 2,j are different, then const is in | |||
3233 | // every cv for 0 < k < j. | |||
3234 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && | |||
3235 | !PreviousToQualsIncludeConst) | |||
3236 | return false; | |||
3237 | ||||
3238 | // The following wording is from C++20, where the result of the conversion | |||
3239 | // is T3, not T2. | |||
3240 | // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is | |||
3241 | // "array of unknown bound of" | |||
3242 | if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) | |||
3243 | return false; | |||
3244 | ||||
3245 | // -- if the resulting P3,i is different from P1,i [...], then const is | |||
3246 | // added to every cv 3_k for 0 < k < i. | |||
3247 | if (!CStyle && FromType->isConstantArrayType() && | |||
3248 | ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) | |||
3249 | return false; | |||
3250 | ||||
3251 | // Keep track of whether all prior cv-qualifiers in the "to" type | |||
3252 | // include const. | |||
3253 | PreviousToQualsIncludeConst = | |||
3254 | PreviousToQualsIncludeConst && ToQuals.hasConst(); | |||
3255 | return true; | |||
3256 | } | |||
3257 | ||||
3258 | /// IsQualificationConversion - Determines whether the conversion from | |||
3259 | /// an rvalue of type FromType to ToType is a qualification conversion | |||
3260 | /// (C++ 4.4). | |||
3261 | /// | |||
3262 | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate | |||
3263 | /// when the qualification conversion involves a change in the Objective-C | |||
3264 | /// object lifetime. | |||
3265 | bool | |||
3266 | Sema::IsQualificationConversion(QualType FromType, QualType ToType, | |||
3267 | bool CStyle, bool &ObjCLifetimeConversion) { | |||
3268 | FromType = Context.getCanonicalType(FromType); | |||
3269 | ToType = Context.getCanonicalType(ToType); | |||
3270 | ObjCLifetimeConversion = false; | |||
3271 | ||||
3272 | // If FromType and ToType are the same type, this is not a | |||
3273 | // qualification conversion. | |||
3274 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) | |||
3275 | return false; | |||
3276 | ||||
3277 | // (C++ 4.4p4): | |||
3278 | // A conversion can add cv-qualifiers at levels other than the first | |||
3279 | // in multi-level pointers, subject to the following rules: [...] | |||
3280 | bool PreviousToQualsIncludeConst = true; | |||
3281 | bool UnwrappedAnyPointer = false; | |||
3282 | while (Context.UnwrapSimilarTypes(FromType, ToType)) { | |||
3283 | if (!isQualificationConversionStep( | |||
3284 | FromType, ToType, CStyle, !UnwrappedAnyPointer, | |||
3285 | PreviousToQualsIncludeConst, ObjCLifetimeConversion)) | |||
3286 | return false; | |||
3287 | UnwrappedAnyPointer = true; | |||
3288 | } | |||
3289 | ||||
3290 | // We are left with FromType and ToType being the pointee types | |||
3291 | // after unwrapping the original FromType and ToType the same number | |||
3292 | // of times. If we unwrapped any pointers, and if FromType and | |||
3293 | // ToType have the same unqualified type (since we checked | |||
3294 | // qualifiers above), then this is a qualification conversion. | |||
3295 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); | |||
3296 | } | |||
3297 | ||||
3298 | /// - Determine whether this is a conversion from a scalar type to an | |||
3299 | /// atomic type. | |||
3300 | /// | |||
3301 | /// If successful, updates \c SCS's second and third steps in the conversion | |||
3302 | /// sequence to finish the conversion. | |||
3303 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, | |||
3304 | bool InOverloadResolution, | |||
3305 | StandardConversionSequence &SCS, | |||
3306 | bool CStyle) { | |||
3307 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); | |||
3308 | if (!ToAtomic) | |||
3309 | return false; | |||
3310 | ||||
3311 | StandardConversionSequence InnerSCS; | |||
3312 | if (!IsStandardConversion(S, From, ToAtomic->getValueType(), | |||
3313 | InOverloadResolution, InnerSCS, | |||
3314 | CStyle, /*AllowObjCWritebackConversion=*/false)) | |||
3315 | return false; | |||
3316 | ||||
3317 | SCS.Second = InnerSCS.Second; | |||
3318 | SCS.setToType(1, InnerSCS.getToType(1)); | |||
3319 | SCS.Third = InnerSCS.Third; | |||
3320 | SCS.QualificationIncludesObjCLifetime | |||
3321 | = InnerSCS.QualificationIncludesObjCLifetime; | |||
3322 | SCS.setToType(2, InnerSCS.getToType(2)); | |||
3323 | return true; | |||
3324 | } | |||
3325 | ||||
3326 | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, | |||
3327 | CXXConstructorDecl *Constructor, | |||
3328 | QualType Type) { | |||
3329 | const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); | |||
3330 | if (CtorType->getNumParams() > 0) { | |||
3331 | QualType FirstArg = CtorType->getParamType(0); | |||
3332 | if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) | |||
3333 | return true; | |||
3334 | } | |||
3335 | return false; | |||
3336 | } | |||
3337 | ||||
3338 | static OverloadingResult | |||
3339 | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, | |||
3340 | CXXRecordDecl *To, | |||
3341 | UserDefinedConversionSequence &User, | |||
3342 | OverloadCandidateSet &CandidateSet, | |||
3343 | bool AllowExplicit) { | |||
3344 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3345 | for (auto *D : S.LookupConstructors(To)) { | |||
3346 | auto Info = getConstructorInfo(D); | |||
3347 | if (!Info) | |||
3348 | continue; | |||
3349 | ||||
3350 | bool Usable = !Info.Constructor->isInvalidDecl() && | |||
3351 | S.isInitListConstructor(Info.Constructor); | |||
3352 | if (Usable) { | |||
3353 | bool SuppressUserConversions = false; | |||
3354 | if (Info.ConstructorTmpl) | |||
3355 | S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, | |||
3356 | /*ExplicitArgs*/ nullptr, From, | |||
3357 | CandidateSet, SuppressUserConversions, | |||
3358 | /*PartialOverloading*/ false, | |||
3359 | AllowExplicit); | |||
3360 | else | |||
3361 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, | |||
3362 | CandidateSet, SuppressUserConversions, | |||
3363 | /*PartialOverloading*/ false, AllowExplicit); | |||
3364 | } | |||
3365 | } | |||
3366 | ||||
3367 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
3368 | ||||
3369 | OverloadCandidateSet::iterator Best; | |||
3370 | switch (auto Result = | |||
3371 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { | |||
3372 | case OR_Deleted: | |||
3373 | case OR_Success: { | |||
3374 | // Record the standard conversion we used and the conversion function. | |||
3375 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | |||
3376 | QualType ThisType = Constructor->getThisType(); | |||
3377 | // Initializer lists don't have conversions as such. | |||
3378 | User.Before.setAsIdentityConversion(); | |||
3379 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3380 | User.ConversionFunction = Constructor; | |||
3381 | User.FoundConversionFunction = Best->FoundDecl; | |||
3382 | User.After.setAsIdentityConversion(); | |||
3383 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); | |||
3384 | User.After.setAllToTypes(ToType); | |||
3385 | return Result; | |||
3386 | } | |||
3387 | ||||
3388 | case OR_No_Viable_Function: | |||
3389 | return OR_No_Viable_Function; | |||
3390 | case OR_Ambiguous: | |||
3391 | return OR_Ambiguous; | |||
3392 | } | |||
3393 | ||||
3394 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 3394); | |||
3395 | } | |||
3396 | ||||
3397 | /// Determines whether there is a user-defined conversion sequence | |||
3398 | /// (C++ [over.ics.user]) that converts expression From to the type | |||
3399 | /// ToType. If such a conversion exists, User will contain the | |||
3400 | /// user-defined conversion sequence that performs such a conversion | |||
3401 | /// and this routine will return true. Otherwise, this routine returns | |||
3402 | /// false and User is unspecified. | |||
3403 | /// | |||
3404 | /// \param AllowExplicit true if the conversion should consider C++0x | |||
3405 | /// "explicit" conversion functions as well as non-explicit conversion | |||
3406 | /// functions (C++0x [class.conv.fct]p2). | |||
3407 | /// | |||
3408 | /// \param AllowObjCConversionOnExplicit true if the conversion should | |||
3409 | /// allow an extra Objective-C pointer conversion on uses of explicit | |||
3410 | /// constructors. Requires \c AllowExplicit to also be set. | |||
3411 | static OverloadingResult | |||
3412 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
3413 | UserDefinedConversionSequence &User, | |||
3414 | OverloadCandidateSet &CandidateSet, | |||
3415 | AllowedExplicit AllowExplicit, | |||
3416 | bool AllowObjCConversionOnExplicit) { | |||
3417 | assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit:: None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit" , "clang/lib/Sema/SemaOverload.cpp", 3418, __extension__ __PRETTY_FUNCTION__ )) | |||
3418 | !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit:: None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit" , "clang/lib/Sema/SemaOverload.cpp", 3418, __extension__ __PRETTY_FUNCTION__ )); | |||
3419 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3420 | ||||
3421 | // Whether we will only visit constructors. | |||
3422 | bool ConstructorsOnly = false; | |||
3423 | ||||
3424 | // If the type we are conversion to is a class type, enumerate its | |||
3425 | // constructors. | |||
3426 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { | |||
3427 | // C++ [over.match.ctor]p1: | |||
3428 | // When objects of class type are direct-initialized (8.5), or | |||
3429 | // copy-initialized from an expression of the same or a | |||
3430 | // derived class type (8.5), overload resolution selects the | |||
3431 | // constructor. [...] For copy-initialization, the candidate | |||
3432 | // functions are all the converting constructors (12.3.1) of | |||
3433 | // that class. The argument list is the expression-list within | |||
3434 | // the parentheses of the initializer. | |||
3435 | if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || | |||
3436 | (From->getType()->getAs<RecordType>() && | |||
3437 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) | |||
3438 | ConstructorsOnly = true; | |||
3439 | ||||
3440 | if (!S.isCompleteType(From->getExprLoc(), ToType)) { | |||
3441 | // We're not going to find any constructors. | |||
3442 | } else if (CXXRecordDecl *ToRecordDecl | |||
3443 | = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { | |||
3444 | ||||
3445 | Expr **Args = &From; | |||
3446 | unsigned NumArgs = 1; | |||
3447 | bool ListInitializing = false; | |||
3448 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { | |||
3449 | // But first, see if there is an init-list-constructor that will work. | |||
3450 | OverloadingResult Result = IsInitializerListConstructorConversion( | |||
3451 | S, From, ToType, ToRecordDecl, User, CandidateSet, | |||
3452 | AllowExplicit == AllowedExplicit::All); | |||
3453 | if (Result != OR_No_Viable_Function) | |||
3454 | return Result; | |||
3455 | // Never mind. | |||
3456 | CandidateSet.clear( | |||
3457 | OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3458 | ||||
3459 | // If we're list-initializing, we pass the individual elements as | |||
3460 | // arguments, not the entire list. | |||
3461 | Args = InitList->getInits(); | |||
3462 | NumArgs = InitList->getNumInits(); | |||
3463 | ListInitializing = true; | |||
3464 | } | |||
3465 | ||||
3466 | for (auto *D : S.LookupConstructors(ToRecordDecl)) { | |||
3467 | auto Info = getConstructorInfo(D); | |||
3468 | if (!Info) | |||
3469 | continue; | |||
3470 | ||||
3471 | bool Usable = !Info.Constructor->isInvalidDecl(); | |||
3472 | if (!ListInitializing) | |||
3473 | Usable = Usable && Info.Constructor->isConvertingConstructor( | |||
3474 | /*AllowExplicit*/ true); | |||
3475 | if (Usable) { | |||
3476 | bool SuppressUserConversions = !ConstructorsOnly; | |||
3477 | // C++20 [over.best.ics.general]/4.5: | |||
3478 | // if the target is the first parameter of a constructor [of class | |||
3479 | // X] and the constructor [...] is a candidate by [...] the second | |||
3480 | // phase of [over.match.list] when the initializer list has exactly | |||
3481 | // one element that is itself an initializer list, [...] and the | |||
3482 | // conversion is to X or reference to cv X, user-defined conversion | |||
3483 | // sequences are not cnosidered. | |||
3484 | if (SuppressUserConversions && ListInitializing) { | |||
3485 | SuppressUserConversions = | |||
3486 | NumArgs == 1 && isa<InitListExpr>(Args[0]) && | |||
3487 | isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, | |||
3488 | ToType); | |||
3489 | } | |||
3490 | if (Info.ConstructorTmpl) | |||
3491 | S.AddTemplateOverloadCandidate( | |||
3492 | Info.ConstructorTmpl, Info.FoundDecl, | |||
3493 | /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), | |||
3494 | CandidateSet, SuppressUserConversions, | |||
3495 | /*PartialOverloading*/ false, | |||
3496 | AllowExplicit == AllowedExplicit::All); | |||
3497 | else | |||
3498 | // Allow one user-defined conversion when user specifies a | |||
3499 | // From->ToType conversion via an static cast (c-style, etc). | |||
3500 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | |||
3501 | llvm::makeArrayRef(Args, NumArgs), | |||
3502 | CandidateSet, SuppressUserConversions, | |||
3503 | /*PartialOverloading*/ false, | |||
3504 | AllowExplicit == AllowedExplicit::All); | |||
3505 | } | |||
3506 | } | |||
3507 | } | |||
3508 | } | |||
3509 | ||||
3510 | // Enumerate conversion functions, if we're allowed to. | |||
3511 | if (ConstructorsOnly || isa<InitListExpr>(From)) { | |||
3512 | } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { | |||
3513 | // No conversion functions from incomplete types. | |||
3514 | } else if (const RecordType *FromRecordType = | |||
3515 | From->getType()->getAs<RecordType>()) { | |||
3516 | if (CXXRecordDecl *FromRecordDecl | |||
3517 | = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { | |||
3518 | // Add all of the conversion functions as candidates. | |||
3519 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); | |||
3520 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
3521 | DeclAccessPair FoundDecl = I.getPair(); | |||
3522 | NamedDecl *D = FoundDecl.getDecl(); | |||
3523 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
3524 | if (isa<UsingShadowDecl>(D)) | |||
3525 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
3526 | ||||
3527 | CXXConversionDecl *Conv; | |||
3528 | FunctionTemplateDecl *ConvTemplate; | |||
3529 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) | |||
3530 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
3531 | else | |||
3532 | Conv = cast<CXXConversionDecl>(D); | |||
3533 | ||||
3534 | if (ConvTemplate) | |||
3535 | S.AddTemplateConversionCandidate( | |||
3536 | ConvTemplate, FoundDecl, ActingContext, From, ToType, | |||
3537 | CandidateSet, AllowObjCConversionOnExplicit, | |||
3538 | AllowExplicit != AllowedExplicit::None); | |||
3539 | else | |||
3540 | S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, | |||
3541 | CandidateSet, AllowObjCConversionOnExplicit, | |||
3542 | AllowExplicit != AllowedExplicit::None); | |||
3543 | } | |||
3544 | } | |||
3545 | } | |||
3546 | ||||
3547 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
3548 | ||||
3549 | OverloadCandidateSet::iterator Best; | |||
3550 | switch (auto Result = | |||
3551 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { | |||
3552 | case OR_Success: | |||
3553 | case OR_Deleted: | |||
3554 | // Record the standard conversion we used and the conversion function. | |||
3555 | if (CXXConstructorDecl *Constructor | |||
3556 | = dyn_cast<CXXConstructorDecl>(Best->Function)) { | |||
3557 | // C++ [over.ics.user]p1: | |||
3558 | // If the user-defined conversion is specified by a | |||
3559 | // constructor (12.3.1), the initial standard conversion | |||
3560 | // sequence converts the source type to the type required by | |||
3561 | // the argument of the constructor. | |||
3562 | // | |||
3563 | QualType ThisType = Constructor->getThisType(); | |||
3564 | if (isa<InitListExpr>(From)) { | |||
3565 | // Initializer lists don't have conversions as such. | |||
3566 | User.Before.setAsIdentityConversion(); | |||
3567 | } else { | |||
3568 | if (Best->Conversions[0].isEllipsis()) | |||
3569 | User.EllipsisConversion = true; | |||
3570 | else { | |||
3571 | User.Before = Best->Conversions[0].Standard; | |||
3572 | User.EllipsisConversion = false; | |||
3573 | } | |||
3574 | } | |||
3575 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3576 | User.ConversionFunction = Constructor; | |||
3577 | User.FoundConversionFunction = Best->FoundDecl; | |||
3578 | User.After.setAsIdentityConversion(); | |||
3579 | User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); | |||
3580 | User.After.setAllToTypes(ToType); | |||
3581 | return Result; | |||
3582 | } | |||
3583 | if (CXXConversionDecl *Conversion | |||
3584 | = dyn_cast<CXXConversionDecl>(Best->Function)) { | |||
3585 | // C++ [over.ics.user]p1: | |||
3586 | // | |||
3587 | // [...] If the user-defined conversion is specified by a | |||
3588 | // conversion function (12.3.2), the initial standard | |||
3589 | // conversion sequence converts the source type to the | |||
3590 | // implicit object parameter of the conversion function. | |||
3591 | User.Before = Best->Conversions[0].Standard; | |||
3592 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3593 | User.ConversionFunction = Conversion; | |||
3594 | User.FoundConversionFunction = Best->FoundDecl; | |||
3595 | User.EllipsisConversion = false; | |||
3596 | ||||
3597 | // C++ [over.ics.user]p2: | |||
3598 | // The second standard conversion sequence converts the | |||
3599 | // result of the user-defined conversion to the target type | |||
3600 | // for the sequence. Since an implicit conversion sequence | |||
3601 | // is an initialization, the special rules for | |||
3602 | // initialization by user-defined conversion apply when | |||
3603 | // selecting the best user-defined conversion for a | |||
3604 | // user-defined conversion sequence (see 13.3.3 and | |||
3605 | // 13.3.3.1). | |||
3606 | User.After = Best->FinalConversion; | |||
3607 | return Result; | |||
3608 | } | |||
3609 | llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?" , "clang/lib/Sema/SemaOverload.cpp", 3609); | |||
3610 | ||||
3611 | case OR_No_Viable_Function: | |||
3612 | return OR_No_Viable_Function; | |||
3613 | ||||
3614 | case OR_Ambiguous: | |||
3615 | return OR_Ambiguous; | |||
3616 | } | |||
3617 | ||||
3618 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 3618); | |||
3619 | } | |||
3620 | ||||
3621 | bool | |||
3622 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { | |||
3623 | ImplicitConversionSequence ICS; | |||
3624 | OverloadCandidateSet CandidateSet(From->getExprLoc(), | |||
3625 | OverloadCandidateSet::CSK_Normal); | |||
3626 | OverloadingResult OvResult = | |||
3627 | IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, | |||
3628 | CandidateSet, AllowedExplicit::None, false); | |||
3629 | ||||
3630 | if (!(OvResult == OR_Ambiguous || | |||
3631 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) | |||
3632 | return false; | |||
3633 | ||||
3634 | auto Cands = CandidateSet.CompleteCandidates( | |||
3635 | *this, | |||
3636 | OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, | |||
3637 | From); | |||
3638 | if (OvResult == OR_Ambiguous) | |||
3639 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) | |||
3640 | << From->getType() << ToType << From->getSourceRange(); | |||
3641 | else { // OR_No_Viable_Function && !CandidateSet.empty() | |||
3642 | if (!RequireCompleteType(From->getBeginLoc(), ToType, | |||
3643 | diag::err_typecheck_nonviable_condition_incomplete, | |||
3644 | From->getType(), From->getSourceRange())) | |||
3645 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) | |||
3646 | << false << From->getType() << From->getSourceRange() << ToType; | |||
3647 | } | |||
3648 | ||||
3649 | CandidateSet.NoteCandidates( | |||
3650 | *this, From, Cands); | |||
3651 | return true; | |||
3652 | } | |||
3653 | ||||
3654 | // Helper for compareConversionFunctions that gets the FunctionType that the | |||
3655 | // conversion-operator return value 'points' to, or nullptr. | |||
3656 | static const FunctionType * | |||
3657 | getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { | |||
3658 | const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); | |||
3659 | const PointerType *RetPtrTy = | |||
3660 | ConvFuncTy->getReturnType()->getAs<PointerType>(); | |||
3661 | ||||
3662 | if (!RetPtrTy) | |||
3663 | return nullptr; | |||
3664 | ||||
3665 | return RetPtrTy->getPointeeType()->getAs<FunctionType>(); | |||
3666 | } | |||
3667 | ||||
3668 | /// Compare the user-defined conversion functions or constructors | |||
3669 | /// of two user-defined conversion sequences to determine whether any ordering | |||
3670 | /// is possible. | |||
3671 | static ImplicitConversionSequence::CompareKind | |||
3672 | compareConversionFunctions(Sema &S, FunctionDecl *Function1, | |||
3673 | FunctionDecl *Function2) { | |||
3674 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); | |||
3675 | CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); | |||
3676 | if (!Conv1 || !Conv2) | |||
3677 | return ImplicitConversionSequence::Indistinguishable; | |||
3678 | ||||
3679 | if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) | |||
3680 | return ImplicitConversionSequence::Indistinguishable; | |||
3681 | ||||
3682 | // Objective-C++: | |||
3683 | // If both conversion functions are implicitly-declared conversions from | |||
3684 | // a lambda closure type to a function pointer and a block pointer, | |||
3685 | // respectively, always prefer the conversion to a function pointer, | |||
3686 | // because the function pointer is more lightweight and is more likely | |||
3687 | // to keep code working. | |||
3688 | if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { | |||
3689 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); | |||
3690 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); | |||
3691 | if (Block1 != Block2) | |||
3692 | return Block1 ? ImplicitConversionSequence::Worse | |||
3693 | : ImplicitConversionSequence::Better; | |||
3694 | } | |||
3695 | ||||
3696 | // In order to support multiple calling conventions for the lambda conversion | |||
3697 | // operator (such as when the free and member function calling convention is | |||
3698 | // different), prefer the 'free' mechanism, followed by the calling-convention | |||
3699 | // of operator(). The latter is in place to support the MSVC-like solution of | |||
3700 | // defining ALL of the possible conversions in regards to calling-convention. | |||
3701 | const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); | |||
3702 | const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); | |||
3703 | ||||
3704 | if (Conv1FuncRet && Conv2FuncRet && | |||
3705 | Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { | |||
3706 | CallingConv Conv1CC = Conv1FuncRet->getCallConv(); | |||
3707 | CallingConv Conv2CC = Conv2FuncRet->getCallConv(); | |||
3708 | ||||
3709 | CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); | |||
3710 | const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); | |||
3711 | ||||
3712 | CallingConv CallOpCC = | |||
3713 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); | |||
3714 | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( | |||
3715 | CallOpProto->isVariadic(), /*IsCXXMethod=*/false); | |||
3716 | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( | |||
3717 | CallOpProto->isVariadic(), /*IsCXXMethod=*/true); | |||
3718 | ||||
3719 | CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; | |||
3720 | for (CallingConv CC : PrefOrder) { | |||
3721 | if (Conv1CC == CC) | |||
3722 | return ImplicitConversionSequence::Better; | |||
3723 | if (Conv2CC == CC) | |||
3724 | return ImplicitConversionSequence::Worse; | |||
3725 | } | |||
3726 | } | |||
3727 | ||||
3728 | return ImplicitConversionSequence::Indistinguishable; | |||
3729 | } | |||
3730 | ||||
3731 | static bool hasDeprecatedStringLiteralToCharPtrConversion( | |||
3732 | const ImplicitConversionSequence &ICS) { | |||
3733 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || | |||
3734 | (ICS.isUserDefined() && | |||
3735 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); | |||
3736 | } | |||
3737 | ||||
3738 | /// CompareImplicitConversionSequences - Compare two implicit | |||
3739 | /// conversion sequences to determine whether one is better than the | |||
3740 | /// other or if they are indistinguishable (C++ 13.3.3.2). | |||
3741 | static ImplicitConversionSequence::CompareKind | |||
3742 | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, | |||
3743 | const ImplicitConversionSequence& ICS1, | |||
3744 | const ImplicitConversionSequence& ICS2) | |||
3745 | { | |||
3746 | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit | |||
3747 | // conversion sequences (as defined in 13.3.3.1) | |||
3748 | // -- a standard conversion sequence (13.3.3.1.1) is a better | |||
3749 | // conversion sequence than a user-defined conversion sequence or | |||
3750 | // an ellipsis conversion sequence, and | |||
3751 | // -- a user-defined conversion sequence (13.3.3.1.2) is a better | |||
3752 | // conversion sequence than an ellipsis conversion sequence | |||
3753 | // (13.3.3.1.3). | |||
3754 | // | |||
3755 | // C++0x [over.best.ics]p10: | |||
3756 | // For the purpose of ranking implicit conversion sequences as | |||
3757 | // described in 13.3.3.2, the ambiguous conversion sequence is | |||
3758 | // treated as a user-defined sequence that is indistinguishable | |||
3759 | // from any other user-defined conversion sequence. | |||
3760 | ||||
3761 | // String literal to 'char *' conversion has been deprecated in C++03. It has | |||
3762 | // been removed from C++11. We still accept this conversion, if it happens at | |||
3763 | // the best viable function. Otherwise, this conversion is considered worse | |||
3764 | // than ellipsis conversion. Consider this as an extension; this is not in the | |||
3765 | // standard. For example: | |||
3766 | // | |||
3767 | // int &f(...); // #1 | |||
3768 | // void f(char*); // #2 | |||
3769 | // void g() { int &r = f("foo"); } | |||
3770 | // | |||
3771 | // In C++03, we pick #2 as the best viable function. | |||
3772 | // In C++11, we pick #1 as the best viable function, because ellipsis | |||
3773 | // conversion is better than string-literal to char* conversion (since there | |||
3774 | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't | |||
3775 | // convert arguments, #2 would be the best viable function in C++11. | |||
3776 | // If the best viable function has this conversion, a warning will be issued | |||
3777 | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. | |||
3778 | ||||
3779 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && | |||
3780 | hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != | |||
3781 | hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && | |||
3782 | // Ill-formedness must not differ | |||
3783 | ICS1.isBad() == ICS2.isBad()) | |||
3784 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) | |||
3785 | ? ImplicitConversionSequence::Worse | |||
3786 | : ImplicitConversionSequence::Better; | |||
3787 | ||||
3788 | if (ICS1.getKindRank() < ICS2.getKindRank()) | |||
3789 | return ImplicitConversionSequence::Better; | |||
3790 | if (ICS2.getKindRank() < ICS1.getKindRank()) | |||
3791 | return ImplicitConversionSequence::Worse; | |||
3792 | ||||
3793 | // The following checks require both conversion sequences to be of | |||
3794 | // the same kind. | |||
3795 | if (ICS1.getKind() != ICS2.getKind()) | |||
3796 | return ImplicitConversionSequence::Indistinguishable; | |||
3797 | ||||
3798 | ImplicitConversionSequence::CompareKind Result = | |||
3799 | ImplicitConversionSequence::Indistinguishable; | |||
3800 | ||||
3801 | // Two implicit conversion sequences of the same form are | |||
3802 | // indistinguishable conversion sequences unless one of the | |||
3803 | // following rules apply: (C++ 13.3.3.2p3): | |||
3804 | ||||
3805 | // List-initialization sequence L1 is a better conversion sequence than | |||
3806 | // list-initialization sequence L2 if: | |||
3807 | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, | |||
3808 | // if not that, | |||
3809 | // — L1 and L2 convert to arrays of the same element type, and either the | |||
3810 | // number of elements n_1 initialized by L1 is less than the number of | |||
3811 | // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to | |||
3812 | // an array of unknown bound and L1 does not, | |||
3813 | // even if one of the other rules in this paragraph would otherwise apply. | |||
3814 | if (!ICS1.isBad()) { | |||
3815 | bool StdInit1 = false, StdInit2 = false; | |||
3816 | if (ICS1.hasInitializerListContainerType()) | |||
3817 | StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), | |||
3818 | nullptr); | |||
3819 | if (ICS2.hasInitializerListContainerType()) | |||
3820 | StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), | |||
3821 | nullptr); | |||
3822 | if (StdInit1 != StdInit2) | |||
3823 | return StdInit1 ? ImplicitConversionSequence::Better | |||
3824 | : ImplicitConversionSequence::Worse; | |||
3825 | ||||
3826 | if (ICS1.hasInitializerListContainerType() && | |||
3827 | ICS2.hasInitializerListContainerType()) | |||
3828 | if (auto *CAT1 = S.Context.getAsConstantArrayType( | |||
3829 | ICS1.getInitializerListContainerType())) | |||
3830 | if (auto *CAT2 = S.Context.getAsConstantArrayType( | |||
3831 | ICS2.getInitializerListContainerType())) { | |||
3832 | if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), | |||
3833 | CAT2->getElementType())) { | |||
3834 | // Both to arrays of the same element type | |||
3835 | if (CAT1->getSize() != CAT2->getSize()) | |||
3836 | // Different sized, the smaller wins | |||
3837 | return CAT1->getSize().ult(CAT2->getSize()) | |||
3838 | ? ImplicitConversionSequence::Better | |||
3839 | : ImplicitConversionSequence::Worse; | |||
3840 | if (ICS1.isInitializerListOfIncompleteArray() != | |||
3841 | ICS2.isInitializerListOfIncompleteArray()) | |||
3842 | // One is incomplete, it loses | |||
3843 | return ICS2.isInitializerListOfIncompleteArray() | |||
3844 | ? ImplicitConversionSequence::Better | |||
3845 | : ImplicitConversionSequence::Worse; | |||
3846 | } | |||
3847 | } | |||
3848 | } | |||
3849 | ||||
3850 | if (ICS1.isStandard()) | |||
3851 | // Standard conversion sequence S1 is a better conversion sequence than | |||
3852 | // standard conversion sequence S2 if [...] | |||
3853 | Result = CompareStandardConversionSequences(S, Loc, | |||
3854 | ICS1.Standard, ICS2.Standard); | |||
3855 | else if (ICS1.isUserDefined()) { | |||
3856 | // User-defined conversion sequence U1 is a better conversion | |||
3857 | // sequence than another user-defined conversion sequence U2 if | |||
3858 | // they contain the same user-defined conversion function or | |||
3859 | // constructor and if the second standard conversion sequence of | |||
3860 | // U1 is better than the second standard conversion sequence of | |||
3861 | // U2 (C++ 13.3.3.2p3). | |||
3862 | if (ICS1.UserDefined.ConversionFunction == | |||
3863 | ICS2.UserDefined.ConversionFunction) | |||
3864 | Result = CompareStandardConversionSequences(S, Loc, | |||
3865 | ICS1.UserDefined.After, | |||
3866 | ICS2.UserDefined.After); | |||
3867 | else | |||
3868 | Result = compareConversionFunctions(S, | |||
3869 | ICS1.UserDefined.ConversionFunction, | |||
3870 | ICS2.UserDefined.ConversionFunction); | |||
3871 | } | |||
3872 | ||||
3873 | return Result; | |||
3874 | } | |||
3875 | ||||
3876 | // Per 13.3.3.2p3, compare the given standard conversion sequences to | |||
3877 | // determine if one is a proper subset of the other. | |||
3878 | static ImplicitConversionSequence::CompareKind | |||
3879 | compareStandardConversionSubsets(ASTContext &Context, | |||
3880 | const StandardConversionSequence& SCS1, | |||
3881 | const StandardConversionSequence& SCS2) { | |||
3882 | ImplicitConversionSequence::CompareKind Result | |||
3883 | = ImplicitConversionSequence::Indistinguishable; | |||
3884 | ||||
3885 | // the identity conversion sequence is considered to be a subsequence of | |||
3886 | // any non-identity conversion sequence | |||
3887 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) | |||
3888 | return ImplicitConversionSequence::Better; | |||
3889 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) | |||
3890 | return ImplicitConversionSequence::Worse; | |||
3891 | ||||
3892 | if (SCS1.Second != SCS2.Second) { | |||
3893 | if (SCS1.Second == ICK_Identity) | |||
3894 | Result = ImplicitConversionSequence::Better; | |||
3895 | else if (SCS2.Second == ICK_Identity) | |||
3896 | Result = ImplicitConversionSequence::Worse; | |||
3897 | else | |||
3898 | return ImplicitConversionSequence::Indistinguishable; | |||
3899 | } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) | |||
3900 | return ImplicitConversionSequence::Indistinguishable; | |||
3901 | ||||
3902 | if (SCS1.Third == SCS2.Third) { | |||
3903 | return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result | |||
3904 | : ImplicitConversionSequence::Indistinguishable; | |||
3905 | } | |||
3906 | ||||
3907 | if (SCS1.Third == ICK_Identity) | |||
3908 | return Result == ImplicitConversionSequence::Worse | |||
3909 | ? ImplicitConversionSequence::Indistinguishable | |||
3910 | : ImplicitConversionSequence::Better; | |||
3911 | ||||
3912 | if (SCS2.Third == ICK_Identity) | |||
3913 | return Result == ImplicitConversionSequence::Better | |||
3914 | ? ImplicitConversionSequence::Indistinguishable | |||
3915 | : ImplicitConversionSequence::Worse; | |||
3916 | ||||
3917 | return ImplicitConversionSequence::Indistinguishable; | |||
3918 | } | |||
3919 | ||||
3920 | /// Determine whether one of the given reference bindings is better | |||
3921 | /// than the other based on what kind of bindings they are. | |||
3922 | static bool | |||
3923 | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, | |||
3924 | const StandardConversionSequence &SCS2) { | |||
3925 | // C++0x [over.ics.rank]p3b4: | |||
3926 | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an | |||
3927 | // implicit object parameter of a non-static member function declared | |||
3928 | // without a ref-qualifier, and *either* S1 binds an rvalue reference | |||
3929 | // to an rvalue and S2 binds an lvalue reference *or S1 binds an | |||
3930 | // lvalue reference to a function lvalue and S2 binds an rvalue | |||
3931 | // reference*. | |||
3932 | // | |||
3933 | // FIXME: Rvalue references. We're going rogue with the above edits, | |||
3934 | // because the semantics in the current C++0x working paper (N3225 at the | |||
3935 | // time of this writing) break the standard definition of std::forward | |||
3936 | // and std::reference_wrapper when dealing with references to functions. | |||
3937 | // Proposed wording changes submitted to CWG for consideration. | |||
3938 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || | |||
3939 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) | |||
3940 | return false; | |||
3941 | ||||
3942 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && | |||
3943 | SCS2.IsLvalueReference) || | |||
3944 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && | |||
3945 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); | |||
3946 | } | |||
3947 | ||||
3948 | enum class FixedEnumPromotion { | |||
3949 | None, | |||
3950 | ToUnderlyingType, | |||
3951 | ToPromotedUnderlyingType | |||
3952 | }; | |||
3953 | ||||
3954 | /// Returns kind of fixed enum promotion the \a SCS uses. | |||
3955 | static FixedEnumPromotion | |||
3956 | getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { | |||
3957 | ||||
3958 | if (SCS.Second != ICK_Integral_Promotion) | |||
3959 | return FixedEnumPromotion::None; | |||
3960 | ||||
3961 | QualType FromType = SCS.getFromType(); | |||
3962 | if (!FromType->isEnumeralType()) | |||
3963 | return FixedEnumPromotion::None; | |||
3964 | ||||
3965 | EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); | |||
3966 | if (!Enum->isFixed()) | |||
3967 | return FixedEnumPromotion::None; | |||
3968 | ||||
3969 | QualType UnderlyingType = Enum->getIntegerType(); | |||
3970 | if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) | |||
3971 | return FixedEnumPromotion::ToUnderlyingType; | |||
3972 | ||||
3973 | return FixedEnumPromotion::ToPromotedUnderlyingType; | |||
3974 | } | |||
3975 | ||||
3976 | /// CompareStandardConversionSequences - Compare two standard | |||
3977 | /// conversion sequences to determine whether one is better than the | |||
3978 | /// other or if they are indistinguishable (C++ 13.3.3.2p3). | |||
3979 | static ImplicitConversionSequence::CompareKind | |||
3980 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, | |||
3981 | const StandardConversionSequence& SCS1, | |||
3982 | const StandardConversionSequence& SCS2) | |||
3983 | { | |||
3984 | // Standard conversion sequence S1 is a better conversion sequence | |||
3985 | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): | |||
3986 | ||||
3987 | // -- S1 is a proper subsequence of S2 (comparing the conversion | |||
3988 | // sequences in the canonical form defined by 13.3.3.1.1, | |||
3989 | // excluding any Lvalue Transformation; the identity conversion | |||
3990 | // sequence is considered to be a subsequence of any | |||
3991 | // non-identity conversion sequence) or, if not that, | |||
3992 | if (ImplicitConversionSequence::CompareKind CK | |||
3993 | = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) | |||
3994 | return CK; | |||
3995 | ||||
3996 | // -- the rank of S1 is better than the rank of S2 (by the rules | |||
3997 | // defined below), or, if not that, | |||
3998 | ImplicitConversionRank Rank1 = SCS1.getRank(); | |||
3999 | ImplicitConversionRank Rank2 = SCS2.getRank(); | |||
4000 | if (Rank1 < Rank2) | |||
4001 | return ImplicitConversionSequence::Better; | |||
4002 | else if (Rank2 < Rank1) | |||
4003 | return ImplicitConversionSequence::Worse; | |||
4004 | ||||
4005 | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank | |||
4006 | // are indistinguishable unless one of the following rules | |||
4007 | // applies: | |||
4008 | ||||
4009 | // A conversion that is not a conversion of a pointer, or | |||
4010 | // pointer to member, to bool is better than another conversion | |||
4011 | // that is such a conversion. | |||
4012 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) | |||
4013 | return SCS2.isPointerConversionToBool() | |||
4014 | ? ImplicitConversionSequence::Better | |||
4015 | : ImplicitConversionSequence::Worse; | |||
4016 | ||||
4017 | // C++14 [over.ics.rank]p4b2: | |||
4018 | // This is retroactively applied to C++11 by CWG 1601. | |||
4019 | // | |||
4020 | // A conversion that promotes an enumeration whose underlying type is fixed | |||
4021 | // to its underlying type is better than one that promotes to the promoted | |||
4022 | // underlying type, if the two are different. | |||
4023 | FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); | |||
4024 | FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); | |||
4025 | if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && | |||
4026 | FEP1 != FEP2) | |||
4027 | return FEP1 == FixedEnumPromotion::ToUnderlyingType | |||
4028 | ? ImplicitConversionSequence::Better | |||
4029 | : ImplicitConversionSequence::Worse; | |||
4030 | ||||
4031 | // C++ [over.ics.rank]p4b2: | |||
4032 | // | |||
4033 | // If class B is derived directly or indirectly from class A, | |||
4034 | // conversion of B* to A* is better than conversion of B* to | |||
4035 | // void*, and conversion of A* to void* is better than conversion | |||
4036 | // of B* to void*. | |||
4037 | bool SCS1ConvertsToVoid | |||
4038 | = SCS1.isPointerConversionToVoidPointer(S.Context); | |||
4039 | bool SCS2ConvertsToVoid | |||
4040 | = SCS2.isPointerConversionToVoidPointer(S.Context); | |||
4041 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { | |||
4042 | // Exactly one of the conversion sequences is a conversion to | |||
4043 | // a void pointer; it's the worse conversion. | |||
4044 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better | |||
4045 | : ImplicitConversionSequence::Worse; | |||
4046 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { | |||
4047 | // Neither conversion sequence converts to a void pointer; compare | |||
4048 | // their derived-to-base conversions. | |||
4049 | if (ImplicitConversionSequence::CompareKind DerivedCK | |||
4050 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) | |||
4051 | return DerivedCK; | |||
4052 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && | |||
4053 | !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { | |||
4054 | // Both conversion sequences are conversions to void | |||
4055 | // pointers. Compare the source types to determine if there's an | |||
4056 | // inheritance relationship in their sources. | |||
4057 | QualType FromType1 = SCS1.getFromType(); | |||
4058 | QualType FromType2 = SCS2.getFromType(); | |||
4059 | ||||
4060 | // Adjust the types we're converting from via the array-to-pointer | |||
4061 | // conversion, if we need to. | |||
4062 | if (SCS1.First == ICK_Array_To_Pointer) | |||
4063 | FromType1 = S.Context.getArrayDecayedType(FromType1); | |||
4064 | if (SCS2.First == ICK_Array_To_Pointer) | |||
4065 | FromType2 = S.Context.getArrayDecayedType(FromType2); | |||
4066 | ||||
4067 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); | |||
4068 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); | |||
4069 | ||||
4070 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
4071 | return ImplicitConversionSequence::Better; | |||
4072 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
4073 | return ImplicitConversionSequence::Worse; | |||
4074 | ||||
4075 | // Objective-C++: If one interface is more specific than the | |||
4076 | // other, it is the better one. | |||
4077 | const ObjCObjectPointerType* FromObjCPtr1 | |||
4078 | = FromType1->getAs<ObjCObjectPointerType>(); | |||
4079 | const ObjCObjectPointerType* FromObjCPtr2 | |||
4080 | = FromType2->getAs<ObjCObjectPointerType>(); | |||
4081 | if (FromObjCPtr1 && FromObjCPtr2) { | |||
4082 | bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, | |||
4083 | FromObjCPtr2); | |||
4084 | bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, | |||
4085 | FromObjCPtr1); | |||
4086 | if (AssignLeft != AssignRight) { | |||
4087 | return AssignLeft? ImplicitConversionSequence::Better | |||
4088 | : ImplicitConversionSequence::Worse; | |||
4089 | } | |||
4090 | } | |||
4091 | } | |||
4092 | ||||
4093 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { | |||
4094 | // Check for a better reference binding based on the kind of bindings. | |||
4095 | if (isBetterReferenceBindingKind(SCS1, SCS2)) | |||
4096 | return ImplicitConversionSequence::Better; | |||
4097 | else if (isBetterReferenceBindingKind(SCS2, SCS1)) | |||
4098 | return ImplicitConversionSequence::Worse; | |||
4099 | } | |||
4100 | ||||
4101 | // Compare based on qualification conversions (C++ 13.3.3.2p3, | |||
4102 | // bullet 3). | |||
4103 | if (ImplicitConversionSequence::CompareKind QualCK | |||
4104 | = CompareQualificationConversions(S, SCS1, SCS2)) | |||
4105 | return QualCK; | |||
4106 | ||||
4107 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { | |||
4108 | // C++ [over.ics.rank]p3b4: | |||
4109 | // -- S1 and S2 are reference bindings (8.5.3), and the types to | |||
4110 | // which the references refer are the same type except for | |||
4111 | // top-level cv-qualifiers, and the type to which the reference | |||
4112 | // initialized by S2 refers is more cv-qualified than the type | |||
4113 | // to which the reference initialized by S1 refers. | |||
4114 | QualType T1 = SCS1.getToType(2); | |||
4115 | QualType T2 = SCS2.getToType(2); | |||
4116 | T1 = S.Context.getCanonicalType(T1); | |||
4117 | T2 = S.Context.getCanonicalType(T2); | |||
4118 | Qualifiers T1Quals, T2Quals; | |||
4119 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); | |||
4120 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); | |||
4121 | if (UnqualT1 == UnqualT2) { | |||
4122 | // Objective-C++ ARC: If the references refer to objects with different | |||
4123 | // lifetimes, prefer bindings that don't change lifetime. | |||
4124 | if (SCS1.ObjCLifetimeConversionBinding != | |||
4125 | SCS2.ObjCLifetimeConversionBinding) { | |||
4126 | return SCS1.ObjCLifetimeConversionBinding | |||
4127 | ? ImplicitConversionSequence::Worse | |||
4128 | : ImplicitConversionSequence::Better; | |||
4129 | } | |||
4130 | ||||
4131 | // If the type is an array type, promote the element qualifiers to the | |||
4132 | // type for comparison. | |||
4133 | if (isa<ArrayType>(T1) && T1Quals) | |||
4134 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); | |||
4135 | if (isa<ArrayType>(T2) && T2Quals) | |||
4136 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); | |||
4137 | if (T2.isMoreQualifiedThan(T1)) | |||
4138 | return ImplicitConversionSequence::Better; | |||
4139 | if (T1.isMoreQualifiedThan(T2)) | |||
4140 | return ImplicitConversionSequence::Worse; | |||
4141 | } | |||
4142 | } | |||
4143 | ||||
4144 | // In Microsoft mode (below 19.28), prefer an integral conversion to a | |||
4145 | // floating-to-integral conversion if the integral conversion | |||
4146 | // is between types of the same size. | |||
4147 | // For example: | |||
4148 | // void f(float); | |||
4149 | // void f(int); | |||
4150 | // int main { | |||
4151 | // long a; | |||
4152 | // f(a); | |||
4153 | // } | |||
4154 | // Here, MSVC will call f(int) instead of generating a compile error | |||
4155 | // as clang will do in standard mode. | |||
4156 | if (S.getLangOpts().MSVCCompat && | |||
4157 | !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && | |||
4158 | SCS1.Second == ICK_Integral_Conversion && | |||
4159 | SCS2.Second == ICK_Floating_Integral && | |||
4160 | S.Context.getTypeSize(SCS1.getFromType()) == | |||
4161 | S.Context.getTypeSize(SCS1.getToType(2))) | |||
4162 | return ImplicitConversionSequence::Better; | |||
4163 | ||||
4164 | // Prefer a compatible vector conversion over a lax vector conversion | |||
4165 | // For example: | |||
4166 | // | |||
4167 | // typedef float __v4sf __attribute__((__vector_size__(16))); | |||
4168 | // void f(vector float); | |||
4169 | // void f(vector signed int); | |||
4170 | // int main() { | |||
4171 | // __v4sf a; | |||
4172 | // f(a); | |||
4173 | // } | |||
4174 | // Here, we'd like to choose f(vector float) and not | |||
4175 | // report an ambiguous call error | |||
4176 | if (SCS1.Second == ICK_Vector_Conversion && | |||
4177 | SCS2.Second == ICK_Vector_Conversion) { | |||
4178 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( | |||
4179 | SCS1.getFromType(), SCS1.getToType(2)); | |||
4180 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( | |||
4181 | SCS2.getFromType(), SCS2.getToType(2)); | |||
4182 | ||||
4183 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) | |||
4184 | return SCS1IsCompatibleVectorConversion | |||
4185 | ? ImplicitConversionSequence::Better | |||
4186 | : ImplicitConversionSequence::Worse; | |||
4187 | } | |||
4188 | ||||
4189 | if (SCS1.Second == ICK_SVE_Vector_Conversion && | |||
4190 | SCS2.Second == ICK_SVE_Vector_Conversion) { | |||
4191 | bool SCS1IsCompatibleSVEVectorConversion = | |||
4192 | S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); | |||
4193 | bool SCS2IsCompatibleSVEVectorConversion = | |||
4194 | S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); | |||
4195 | ||||
4196 | if (SCS1IsCompatibleSVEVectorConversion != | |||
4197 | SCS2IsCompatibleSVEVectorConversion) | |||
4198 | return SCS1IsCompatibleSVEVectorConversion | |||
4199 | ? ImplicitConversionSequence::Better | |||
4200 | : ImplicitConversionSequence::Worse; | |||
4201 | } | |||
4202 | ||||
4203 | return ImplicitConversionSequence::Indistinguishable; | |||
4204 | } | |||
4205 | ||||
4206 | /// CompareQualificationConversions - Compares two standard conversion | |||
4207 | /// sequences to determine whether they can be ranked based on their | |||
4208 | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). | |||
4209 | static ImplicitConversionSequence::CompareKind | |||
4210 | CompareQualificationConversions(Sema &S, | |||
4211 | const StandardConversionSequence& SCS1, | |||
4212 | const StandardConversionSequence& SCS2) { | |||
4213 | // C++ [over.ics.rank]p3: | |||
4214 | // -- S1 and S2 differ only in their qualification conversion and | |||
4215 | // yield similar types T1 and T2 (C++ 4.4), respectively, [...] | |||
4216 | // [C++98] | |||
4217 | // [...] and the cv-qualification signature of type T1 is a proper subset | |||
4218 | // of the cv-qualification signature of type T2, and S1 is not the | |||
4219 | // deprecated string literal array-to-pointer conversion (4.2). | |||
4220 | // [C++2a] | |||
4221 | // [...] where T1 can be converted to T2 by a qualification conversion. | |||
4222 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || | |||
4223 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) | |||
4224 | return ImplicitConversionSequence::Indistinguishable; | |||
4225 | ||||
4226 | // FIXME: the example in the standard doesn't use a qualification | |||
4227 | // conversion (!) | |||
4228 | QualType T1 = SCS1.getToType(2); | |||
4229 | QualType T2 = SCS2.getToType(2); | |||
4230 | T1 = S.Context.getCanonicalType(T1); | |||
4231 | T2 = S.Context.getCanonicalType(T2); | |||
4232 | assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() && !T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()" , "clang/lib/Sema/SemaOverload.cpp", 4232, __extension__ __PRETTY_FUNCTION__ )); | |||
4233 | Qualifiers T1Quals, T2Quals; | |||
4234 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); | |||
4235 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); | |||
4236 | ||||
4237 | // If the types are the same, we won't learn anything by unwrapping | |||
4238 | // them. | |||
4239 | if (UnqualT1 == UnqualT2) | |||
4240 | return ImplicitConversionSequence::Indistinguishable; | |||
4241 | ||||
4242 | // Don't ever prefer a standard conversion sequence that uses the deprecated | |||
4243 | // string literal array to pointer conversion. | |||
4244 | bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; | |||
4245 | bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; | |||
4246 | ||||
4247 | // Objective-C++ ARC: | |||
4248 | // Prefer qualification conversions not involving a change in lifetime | |||
4249 | // to qualification conversions that do change lifetime. | |||
4250 | if (SCS1.QualificationIncludesObjCLifetime && | |||
4251 | !SCS2.QualificationIncludesObjCLifetime) | |||
4252 | CanPick1 = false; | |||
4253 | if (SCS2.QualificationIncludesObjCLifetime && | |||
4254 | !SCS1.QualificationIncludesObjCLifetime) | |||
4255 | CanPick2 = false; | |||
4256 | ||||
4257 | bool ObjCLifetimeConversion; | |||
4258 | if (CanPick1 && | |||
4259 | !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) | |||
4260 | CanPick1 = false; | |||
4261 | // FIXME: In Objective-C ARC, we can have qualification conversions in both | |||
4262 | // directions, so we can't short-cut this second check in general. | |||
4263 | if (CanPick2 && | |||
4264 | !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) | |||
4265 | CanPick2 = false; | |||
4266 | ||||
4267 | if (CanPick1 != CanPick2) | |||
4268 | return CanPick1 ? ImplicitConversionSequence::Better | |||
4269 | : ImplicitConversionSequence::Worse; | |||
4270 | return ImplicitConversionSequence::Indistinguishable; | |||
4271 | } | |||
4272 | ||||
4273 | /// CompareDerivedToBaseConversions - Compares two standard conversion | |||
4274 | /// sequences to determine whether they can be ranked based on their | |||
4275 | /// various kinds of derived-to-base conversions (C++ | |||
4276 | /// [over.ics.rank]p4b3). As part of these checks, we also look at | |||
4277 | /// conversions between Objective-C interface types. | |||
4278 | static ImplicitConversionSequence::CompareKind | |||
4279 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, | |||
4280 | const StandardConversionSequence& SCS1, | |||
4281 | const StandardConversionSequence& SCS2) { | |||
4282 | QualType FromType1 = SCS1.getFromType(); | |||
4283 | QualType ToType1 = SCS1.getToType(1); | |||
4284 | QualType FromType2 = SCS2.getFromType(); | |||
4285 | QualType ToType2 = SCS2.getToType(1); | |||
4286 | ||||
4287 | // Adjust the types we're converting from via the array-to-pointer | |||
4288 | // conversion, if we need to. | |||
4289 | if (SCS1.First == ICK_Array_To_Pointer) | |||
4290 | FromType1 = S.Context.getArrayDecayedType(FromType1); | |||
4291 | if (SCS2.First == ICK_Array_To_Pointer) | |||
4292 | FromType2 = S.Context.getArrayDecayedType(FromType2); | |||
4293 | ||||
4294 | // Canonicalize all of the types. | |||
4295 | FromType1 = S.Context.getCanonicalType(FromType1); | |||
4296 | ToType1 = S.Context.getCanonicalType(ToType1); | |||
4297 | FromType2 = S.Context.getCanonicalType(FromType2); | |||
4298 | ToType2 = S.Context.getCanonicalType(ToType2); | |||
4299 | ||||
4300 | // C++ [over.ics.rank]p4b3: | |||
4301 | // | |||
4302 | // If class B is derived directly or indirectly from class A and | |||
4303 | // class C is derived directly or indirectly from B, | |||
4304 | // | |||
4305 | // Compare based on pointer conversions. | |||
4306 | if (SCS1.Second == ICK_Pointer_Conversion && | |||
4307 | SCS2.Second == ICK_Pointer_Conversion && | |||
4308 | /*FIXME: Remove if Objective-C id conversions get their own rank*/ | |||
4309 | FromType1->isPointerType() && FromType2->isPointerType() && | |||
4310 | ToType1->isPointerType() && ToType2->isPointerType()) { | |||
4311 | QualType FromPointee1 = | |||
4312 | FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4313 | QualType ToPointee1 = | |||
4314 | ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4315 | QualType FromPointee2 = | |||
4316 | FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4317 | QualType ToPointee2 = | |||
4318 | ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4319 | ||||
4320 | // -- conversion of C* to B* is better than conversion of C* to A*, | |||
4321 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { | |||
4322 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) | |||
4323 | return ImplicitConversionSequence::Better; | |||
4324 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) | |||
4325 | return ImplicitConversionSequence::Worse; | |||
4326 | } | |||
4327 | ||||
4328 | // -- conversion of B* to A* is better than conversion of C* to A*, | |||
4329 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { | |||
4330 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
4331 | return ImplicitConversionSequence::Better; | |||
4332 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
4333 | return ImplicitConversionSequence::Worse; | |||
4334 | } | |||
4335 | } else if (SCS1.Second == ICK_Pointer_Conversion && | |||
4336 | SCS2.Second == ICK_Pointer_Conversion) { | |||
4337 | const ObjCObjectPointerType *FromPtr1 | |||
4338 | = FromType1->getAs<ObjCObjectPointerType>(); | |||
4339 | const ObjCObjectPointerType *FromPtr2 | |||
4340 | = FromType2->getAs<ObjCObjectPointerType>(); | |||
4341 | const ObjCObjectPointerType *ToPtr1 | |||
4342 | = ToType1->getAs<ObjCObjectPointerType>(); | |||
4343 | const ObjCObjectPointerType *ToPtr2 | |||
4344 | = ToType2->getAs<ObjCObjectPointerType>(); | |||
4345 | ||||
4346 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { | |||
4347 | // Apply the same conversion ranking rules for Objective-C pointer types | |||
4348 | // that we do for C++ pointers to class types. However, we employ the | |||
4349 | // Objective-C pseudo-subtyping relationship used for assignment of | |||
4350 | // Objective-C pointer types. | |||
4351 | bool FromAssignLeft | |||
4352 | = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); | |||
4353 | bool FromAssignRight | |||
4354 | = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); | |||
4355 | bool ToAssignLeft | |||
4356 | = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); | |||
4357 | bool ToAssignRight | |||
4358 | = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); | |||
4359 | ||||
4360 | // A conversion to an a non-id object pointer type or qualified 'id' | |||
4361 | // type is better than a conversion to 'id'. | |||
4362 | if (ToPtr1->isObjCIdType() && | |||
4363 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) | |||
4364 | return ImplicitConversionSequence::Worse; | |||
4365 | if (ToPtr2->isObjCIdType() && | |||
4366 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) | |||
4367 | return ImplicitConversionSequence::Better; | |||
4368 | ||||
4369 | // A conversion to a non-id object pointer type is better than a | |||
4370 | // conversion to a qualified 'id' type | |||
4371 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) | |||
4372 | return ImplicitConversionSequence::Worse; | |||
4373 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) | |||
4374 | return ImplicitConversionSequence::Better; | |||
4375 | ||||
4376 | // A conversion to an a non-Class object pointer type or qualified 'Class' | |||
4377 | // type is better than a conversion to 'Class'. | |||
4378 | if (ToPtr1->isObjCClassType() && | |||
4379 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) | |||
4380 | return ImplicitConversionSequence::Worse; | |||
4381 | if (ToPtr2->isObjCClassType() && | |||
4382 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) | |||
4383 | return ImplicitConversionSequence::Better; | |||
4384 | ||||
4385 | // A conversion to a non-Class object pointer type is better than a | |||
4386 | // conversion to a qualified 'Class' type. | |||
4387 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) | |||
4388 | return ImplicitConversionSequence::Worse; | |||
4389 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) | |||
4390 | return ImplicitConversionSequence::Better; | |||
4391 | ||||
4392 | // -- "conversion of C* to B* is better than conversion of C* to A*," | |||
4393 | if (S.Context.hasSameType(FromType1, FromType2) && | |||
4394 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && | |||
4395 | (ToAssignLeft != ToAssignRight)) { | |||
4396 | if (FromPtr1->isSpecialized()) { | |||
4397 | // "conversion of B<A> * to B * is better than conversion of B * to | |||
4398 | // C *. | |||
4399 | bool IsFirstSame = | |||
4400 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); | |||
4401 | bool IsSecondSame = | |||
4402 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); | |||
4403 | if (IsFirstSame) { | |||
4404 | if (!IsSecondSame) | |||
4405 | return ImplicitConversionSequence::Better; | |||
4406 | } else if (IsSecondSame) | |||
4407 | return ImplicitConversionSequence::Worse; | |||
4408 | } | |||
4409 | return ToAssignLeft? ImplicitConversionSequence::Worse | |||
4410 | : ImplicitConversionSequence::Better; | |||
4411 | } | |||
4412 | ||||
4413 | // -- "conversion of B* to A* is better than conversion of C* to A*," | |||
4414 | if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && | |||
4415 | (FromAssignLeft != FromAssignRight)) | |||
4416 | return FromAssignLeft? ImplicitConversionSequence::Better | |||
4417 | : ImplicitConversionSequence::Worse; | |||
4418 | } | |||
4419 | } | |||
4420 | ||||
4421 | // Ranking of member-pointer types. | |||
4422 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && | |||
4423 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && | |||
4424 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { | |||
4425 | const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); | |||
4426 | const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); | |||
4427 | const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); | |||
4428 | const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); | |||
4429 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); | |||
4430 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); | |||
4431 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); | |||
4432 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); | |||
4433 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); | |||
4434 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); | |||
4435 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); | |||
4436 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); | |||
4437 | // conversion of A::* to B::* is better than conversion of A::* to C::*, | |||
4438 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { | |||
4439 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) | |||
4440 | return ImplicitConversionSequence::Worse; | |||
4441 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) | |||
4442 | return ImplicitConversionSequence::Better; | |||
4443 | } | |||
4444 | // conversion of B::* to C::* is better than conversion of A::* to C::* | |||
4445 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { | |||
4446 | if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
4447 | return ImplicitConversionSequence::Better; | |||
4448 | else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
4449 | return ImplicitConversionSequence::Worse; | |||
4450 | } | |||
4451 | } | |||
4452 | ||||
4453 | if (SCS1.Second == ICK_Derived_To_Base) { | |||
4454 | // -- conversion of C to B is better than conversion of C to A, | |||
4455 | // -- binding of an expression of type C to a reference of type | |||
4456 | // B& is better than binding an expression of type C to a | |||
4457 | // reference of type A&, | |||
4458 | if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && | |||
4459 | !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { | |||
4460 | if (S.IsDerivedFrom(Loc, ToType1, ToType2)) | |||
4461 | return ImplicitConversionSequence::Better; | |||
4462 | else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) | |||
4463 | return ImplicitConversionSequence::Worse; | |||
4464 | } | |||
4465 | ||||
4466 | // -- conversion of B to A is better than conversion of C to A. | |||
4467 | // -- binding of an expression of type B to a reference of type | |||
4468 | // A& is better than binding an expression of type C to a | |||
4469 | // reference of type A&, | |||
4470 | if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && | |||
4471 | S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { | |||
4472 | if (S.IsDerivedFrom(Loc, FromType2, FromType1)) | |||
4473 | return ImplicitConversionSequence::Better; | |||
4474 | else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) | |||
4475 | return ImplicitConversionSequence::Worse; | |||
4476 | } | |||
4477 | } | |||
4478 | ||||
4479 | return ImplicitConversionSequence::Indistinguishable; | |||
4480 | } | |||
4481 | ||||
4482 | /// Determine whether the given type is valid, e.g., it is not an invalid | |||
4483 | /// C++ class. | |||
4484 | static bool isTypeValid(QualType T) { | |||
4485 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) | |||
4486 | return !Record->isInvalidDecl(); | |||
4487 | ||||
4488 | return true; | |||
4489 | } | |||
4490 | ||||
4491 | static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { | |||
4492 | if (!T.getQualifiers().hasUnaligned()) | |||
4493 | return T; | |||
4494 | ||||
4495 | Qualifiers Q; | |||
4496 | T = Ctx.getUnqualifiedArrayType(T, Q); | |||
4497 | Q.removeUnaligned(); | |||
4498 | return Ctx.getQualifiedType(T, Q); | |||
4499 | } | |||
4500 | ||||
4501 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to | |||
4502 | /// determine whether they are reference-compatible, | |||
4503 | /// reference-related, or incompatible, for use in C++ initialization by | |||
4504 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference | |||
4505 | /// type, and the first type (T1) is the pointee type of the reference | |||
4506 | /// type being initialized. | |||
4507 | Sema::ReferenceCompareResult | |||
4508 | Sema::CompareReferenceRelationship(SourceLocation Loc, | |||
4509 | QualType OrigT1, QualType OrigT2, | |||
4510 | ReferenceConversions *ConvOut) { | |||
4511 | assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type") ? void ( 0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4512, __extension__ __PRETTY_FUNCTION__ )) | |||
4512 | "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type") ? void ( 0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4512, __extension__ __PRETTY_FUNCTION__ )); | |||
4513 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() && "T2 cannot be a reference type") ? void (0) : __assert_fail ( "!OrigT2->isReferenceType() && \"T2 cannot be a reference type\"" , "clang/lib/Sema/SemaOverload.cpp", 4513, __extension__ __PRETTY_FUNCTION__ )); | |||
4514 | ||||
4515 | QualType T1 = Context.getCanonicalType(OrigT1); | |||
4516 | QualType T2 = Context.getCanonicalType(OrigT2); | |||
4517 | Qualifiers T1Quals, T2Quals; | |||
4518 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); | |||
4519 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); | |||
4520 | ||||
4521 | ReferenceConversions ConvTmp; | |||
4522 | ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; | |||
4523 | Conv = ReferenceConversions(); | |||
4524 | ||||
4525 | // C++2a [dcl.init.ref]p4: | |||
4526 | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is | |||
4527 | // reference-related to "cv2 T2" if T1 is similar to T2, or | |||
4528 | // T1 is a base class of T2. | |||
4529 | // "cv1 T1" is reference-compatible with "cv2 T2" if | |||
4530 | // a prvalue of type "pointer to cv2 T2" can be converted to the type | |||
4531 | // "pointer to cv1 T1" via a standard conversion sequence. | |||
4532 | ||||
4533 | // Check for standard conversions we can apply to pointers: derived-to-base | |||
4534 | // conversions, ObjC pointer conversions, and function pointer conversions. | |||
4535 | // (Qualification conversions are checked last.) | |||
4536 | QualType ConvertedT2; | |||
4537 | if (UnqualT1 == UnqualT2) { | |||
4538 | // Nothing to do. | |||
4539 | } else if (isCompleteType(Loc, OrigT2) && | |||
4540 | isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && | |||
4541 | IsDerivedFrom(Loc, UnqualT2, UnqualT1)) | |||
4542 | Conv |= ReferenceConversions::DerivedToBase; | |||
4543 | else if (UnqualT1->isObjCObjectOrInterfaceType() && | |||
4544 | UnqualT2->isObjCObjectOrInterfaceType() && | |||
4545 | Context.canBindObjCObjectType(UnqualT1, UnqualT2)) | |||
4546 | Conv |= ReferenceConversions::ObjC; | |||
4547 | else if (UnqualT2->isFunctionType() && | |||
4548 | IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { | |||
4549 | Conv |= ReferenceConversions::Function; | |||
4550 | // No need to check qualifiers; function types don't have them. | |||
4551 | return Ref_Compatible; | |||
4552 | } | |||
4553 | bool ConvertedReferent = Conv != 0; | |||
4554 | ||||
4555 | // We can have a qualification conversion. Compute whether the types are | |||
4556 | // similar at the same time. | |||
4557 | bool PreviousToQualsIncludeConst = true; | |||
4558 | bool TopLevel = true; | |||
4559 | do { | |||
4560 | if (T1 == T2) | |||
4561 | break; | |||
4562 | ||||
4563 | // We will need a qualification conversion. | |||
4564 | Conv |= ReferenceConversions::Qualification; | |||
4565 | ||||
4566 | // Track whether we performed a qualification conversion anywhere other | |||
4567 | // than the top level. This matters for ranking reference bindings in | |||
4568 | // overload resolution. | |||
4569 | if (!TopLevel) | |||
4570 | Conv |= ReferenceConversions::NestedQualification; | |||
4571 | ||||
4572 | // MS compiler ignores __unaligned qualifier for references; do the same. | |||
4573 | T1 = withoutUnaligned(Context, T1); | |||
4574 | T2 = withoutUnaligned(Context, T2); | |||
4575 | ||||
4576 | // If we find a qualifier mismatch, the types are not reference-compatible, | |||
4577 | // but are still be reference-related if they're similar. | |||
4578 | bool ObjCLifetimeConversion = false; | |||
4579 | if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, | |||
4580 | PreviousToQualsIncludeConst, | |||
4581 | ObjCLifetimeConversion)) | |||
4582 | return (ConvertedReferent || Context.hasSimilarType(T1, T2)) | |||
4583 | ? Ref_Related | |||
4584 | : Ref_Incompatible; | |||
4585 | ||||
4586 | // FIXME: Should we track this for any level other than the first? | |||
4587 | if (ObjCLifetimeConversion) | |||
4588 | Conv |= ReferenceConversions::ObjCLifetime; | |||
4589 | ||||
4590 | TopLevel = false; | |||
4591 | } while (Context.UnwrapSimilarTypes(T1, T2)); | |||
4592 | ||||
4593 | // At this point, if the types are reference-related, we must either have the | |||
4594 | // same inner type (ignoring qualifiers), or must have already worked out how | |||
4595 | // to convert the referent. | |||
4596 | return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) | |||
4597 | ? Ref_Compatible | |||
4598 | : Ref_Incompatible; | |||
4599 | } | |||
4600 | ||||
4601 | /// Look for a user-defined conversion to a value reference-compatible | |||
4602 | /// with DeclType. Return true if something definite is found. | |||
4603 | static bool | |||
4604 | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, | |||
4605 | QualType DeclType, SourceLocation DeclLoc, | |||
4606 | Expr *Init, QualType T2, bool AllowRvalues, | |||
4607 | bool AllowExplicit) { | |||
4608 | assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types." ) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\"" , "clang/lib/Sema/SemaOverload.cpp", 4608, __extension__ __PRETTY_FUNCTION__ )); | |||
4609 | auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); | |||
4610 | ||||
4611 | OverloadCandidateSet CandidateSet( | |||
4612 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
4613 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | |||
4614 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
4615 | NamedDecl *D = *I; | |||
4616 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
4617 | if (isa<UsingShadowDecl>(D)) | |||
4618 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
4619 | ||||
4620 | FunctionTemplateDecl *ConvTemplate | |||
4621 | = dyn_cast<FunctionTemplateDecl>(D); | |||
4622 | CXXConversionDecl *Conv; | |||
4623 | if (ConvTemplate) | |||
4624 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
4625 | else | |||
4626 | Conv = cast<CXXConversionDecl>(D); | |||
4627 | ||||
4628 | if (AllowRvalues) { | |||
4629 | // If we are initializing an rvalue reference, don't permit conversion | |||
4630 | // functions that return lvalues. | |||
4631 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { | |||
4632 | const ReferenceType *RefType | |||
4633 | = Conv->getConversionType()->getAs<LValueReferenceType>(); | |||
4634 | if (RefType && !RefType->getPointeeType()->isFunctionType()) | |||
4635 | continue; | |||
4636 | } | |||
4637 | ||||
4638 | if (!ConvTemplate && | |||
4639 | S.CompareReferenceRelationship( | |||
4640 | DeclLoc, | |||
4641 | Conv->getConversionType() | |||
4642 | .getNonReferenceType() | |||
4643 | .getUnqualifiedType(), | |||
4644 | DeclType.getNonReferenceType().getUnqualifiedType()) == | |||
4645 | Sema::Ref_Incompatible) | |||
4646 | continue; | |||
4647 | } else { | |||
4648 | // If the conversion function doesn't return a reference type, | |||
4649 | // it can't be considered for this conversion. An rvalue reference | |||
4650 | // is only acceptable if its referencee is a function type. | |||
4651 | ||||
4652 | const ReferenceType *RefType = | |||
4653 | Conv->getConversionType()->getAs<ReferenceType>(); | |||
4654 | if (!RefType || | |||
4655 | (!RefType->isLValueReferenceType() && | |||
4656 | !RefType->getPointeeType()->isFunctionType())) | |||
4657 | continue; | |||
4658 | } | |||
4659 | ||||
4660 | if (ConvTemplate) | |||
4661 | S.AddTemplateConversionCandidate( | |||
4662 | ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, | |||
4663 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); | |||
4664 | else | |||
4665 | S.AddConversionCandidate( | |||
4666 | Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, | |||
4667 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); | |||
4668 | } | |||
4669 | ||||
4670 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
4671 | ||||
4672 | OverloadCandidateSet::iterator Best; | |||
4673 | switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | |||
4674 | case OR_Success: | |||
4675 | // C++ [over.ics.ref]p1: | |||
4676 | // | |||
4677 | // [...] If the parameter binds directly to the result of | |||
4678 | // applying a conversion function to the argument | |||
4679 | // expression, the implicit conversion sequence is a | |||
4680 | // user-defined conversion sequence (13.3.3.1.2), with the | |||
4681 | // second standard conversion sequence either an identity | |||
4682 | // conversion or, if the conversion function returns an | |||
4683 | // entity of a type that is a derived class of the parameter | |||
4684 | // type, a derived-to-base Conversion. | |||
4685 | if (!Best->FinalConversion.DirectBinding) | |||
4686 | return false; | |||
4687 | ||||
4688 | ICS.setUserDefined(); | |||
4689 | ICS.UserDefined.Before = Best->Conversions[0].Standard; | |||
4690 | ICS.UserDefined.After = Best->FinalConversion; | |||
4691 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; | |||
4692 | ICS.UserDefined.ConversionFunction = Best->Function; | |||
4693 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; | |||
4694 | ICS.UserDefined.EllipsisConversion = false; | |||
4695 | assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4697, __extension__ __PRETTY_FUNCTION__ )) | |||
4696 | ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4697, __extension__ __PRETTY_FUNCTION__ )) | |||
4697 | "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!" ) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "clang/lib/Sema/SemaOverload.cpp", 4697, __extension__ __PRETTY_FUNCTION__ )); | |||
4698 | return true; | |||
4699 | ||||
4700 | case OR_Ambiguous: | |||
4701 | ICS.setAmbiguous(); | |||
4702 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); | |||
4703 | Cand != CandidateSet.end(); ++Cand) | |||
4704 | if (Cand->Best) | |||
4705 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); | |||
4706 | return true; | |||
4707 | ||||
4708 | case OR_No_Viable_Function: | |||
4709 | case OR_Deleted: | |||
4710 | // There was no suitable conversion, or we found a deleted | |||
4711 | // conversion; continue with other checks. | |||
4712 | return false; | |||
4713 | } | |||
4714 | ||||
4715 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp" , 4715); | |||
4716 | } | |||
4717 | ||||
4718 | /// Compute an implicit conversion sequence for reference | |||
4719 | /// initialization. | |||
4720 | static ImplicitConversionSequence | |||
4721 | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, | |||
4722 | SourceLocation DeclLoc, | |||
4723 | bool SuppressUserConversions, | |||
4724 | bool AllowExplicit) { | |||
4725 | assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() && "Reference init needs a reference") ? void (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\"" , "clang/lib/Sema/SemaOverload.cpp", 4725, __extension__ __PRETTY_FUNCTION__ )); | |||
4726 | ||||
4727 | // Most paths end in a failed conversion. | |||
4728 | ImplicitConversionSequence ICS; | |||
4729 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); | |||
4730 | ||||
4731 | QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); | |||
4732 | QualType T2 = Init->getType(); | |||
4733 | ||||
4734 | // If the initializer is the address of an overloaded function, try | |||
4735 | // to resolve the overloaded function. If all goes well, T2 is the | |||
4736 | // type of the resulting function. | |||
4737 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { | |||
4738 | DeclAccessPair Found; | |||
4739 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, | |||
4740 | false, Found)) | |||
4741 | T2 = Fn->getType(); | |||
4742 | } | |||
4743 | ||||
4744 | // Compute some basic properties of the types and the initializer. | |||
4745 | bool isRValRef = DeclType->isRValueReferenceType(); | |||
4746 | Expr::Classification InitCategory = Init->Classify(S.Context); | |||
4747 | ||||
4748 | Sema::ReferenceConversions RefConv; | |||
4749 | Sema::ReferenceCompareResult RefRelationship = | |||
4750 | S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); | |||
4751 | ||||
4752 | auto SetAsReferenceBinding = [&](bool BindsDirectly) { | |||
4753 | ICS.setStandard(); | |||
4754 | ICS.Standard.First = ICK_Identity; | |||
4755 | // FIXME: A reference binding can be a function conversion too. We should | |||
4756 | // consider that when ordering reference-to-function bindings. | |||
4757 | ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
4758 | ? ICK_Derived_To_Base | |||
4759 | : (RefConv & Sema::ReferenceConversions::ObjC) | |||
4760 | ? ICK_Compatible_Conversion | |||
4761 | : ICK_Identity; | |||
4762 | // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank | |||
4763 | // a reference binding that performs a non-top-level qualification | |||
4764 | // conversion as a qualification conversion, not as an identity conversion. | |||
4765 | ICS.Standard.Third = (RefConv & | |||
4766 | Sema::ReferenceConversions::NestedQualification) | |||
4767 | ? ICK_Qualification | |||
4768 | : ICK_Identity; | |||
4769 | ICS.Standard.setFromType(T2); | |||
4770 | ICS.Standard.setToType(0, T2); | |||
4771 | ICS.Standard.setToType(1, T1); | |||
4772 | ICS.Standard.setToType(2, T1); | |||
4773 | ICS.Standard.ReferenceBinding = true; | |||
4774 | ICS.Standard.DirectBinding = BindsDirectly; | |||
4775 | ICS.Standard.IsLvalueReference = !isRValRef; | |||
4776 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); | |||
4777 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); | |||
4778 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4779 | ICS.Standard.ObjCLifetimeConversionBinding = | |||
4780 | (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; | |||
4781 | ICS.Standard.CopyConstructor = nullptr; | |||
4782 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; | |||
4783 | }; | |||
4784 | ||||
4785 | // C++0x [dcl.init.ref]p5: | |||
4786 | // A reference to type "cv1 T1" is initialized by an expression | |||
4787 | // of type "cv2 T2" as follows: | |||
4788 | ||||
4789 | // -- If reference is an lvalue reference and the initializer expression | |||
4790 | if (!isRValRef) { | |||
4791 | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is | |||
4792 | // reference-compatible with "cv2 T2," or | |||
4793 | // | |||
4794 | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. | |||
4795 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { | |||
4796 | // C++ [over.ics.ref]p1: | |||
4797 | // When a parameter of reference type binds directly (8.5.3) | |||
4798 | // to an argument expression, the implicit conversion sequence | |||
4799 | // is the identity conversion, unless the argument expression | |||
4800 | // has a type that is a derived class of the parameter type, | |||
4801 | // in which case the implicit conversion sequence is a | |||
4802 | // derived-to-base Conversion (13.3.3.1). | |||
4803 | SetAsReferenceBinding(/*BindsDirectly=*/true); | |||
4804 | ||||
4805 | // Nothing more to do: the inaccessibility/ambiguity check for | |||
4806 | // derived-to-base conversions is suppressed when we're | |||
4807 | // computing the implicit conversion sequence (C++ | |||
4808 | // [over.best.ics]p2). | |||
4809 | return ICS; | |||
4810 | } | |||
4811 | ||||
4812 | // -- has a class type (i.e., T2 is a class type), where T1 is | |||
4813 | // not reference-related to T2, and can be implicitly | |||
4814 | // converted to an lvalue of type "cv3 T3," where "cv1 T1" | |||
4815 | // is reference-compatible with "cv3 T3" 92) (this | |||
4816 | // conversion is selected by enumerating the applicable | |||
4817 | // conversion functions (13.3.1.6) and choosing the best | |||
4818 | // one through overload resolution (13.3)), | |||
4819 | if (!SuppressUserConversions && T2->isRecordType() && | |||
4820 | S.isCompleteType(DeclLoc, T2) && | |||
4821 | RefRelationship == Sema::Ref_Incompatible) { | |||
4822 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, | |||
4823 | Init, T2, /*AllowRvalues=*/false, | |||
4824 | AllowExplicit)) | |||
4825 | return ICS; | |||
4826 | } | |||
4827 | } | |||
4828 | ||||
4829 | // -- Otherwise, the reference shall be an lvalue reference to a | |||
4830 | // non-volatile const type (i.e., cv1 shall be const), or the reference | |||
4831 | // shall be an rvalue reference. | |||
4832 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { | |||
4833 | if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) | |||
4834 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); | |||
4835 | return ICS; | |||
4836 | } | |||
4837 | ||||
4838 | // -- If the initializer expression | |||
4839 | // | |||
4840 | // -- is an xvalue, class prvalue, array prvalue or function | |||
4841 | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or | |||
4842 | if (RefRelationship == Sema::Ref_Compatible && | |||
4843 | (InitCategory.isXValue() || | |||
4844 | (InitCategory.isPRValue() && | |||
4845 | (T2->isRecordType() || T2->isArrayType())) || | |||
4846 | (InitCategory.isLValue() && T2->isFunctionType()))) { | |||
4847 | // In C++11, this is always a direct binding. In C++98/03, it's a direct | |||
4848 | // binding unless we're binding to a class prvalue. | |||
4849 | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we | |||
4850 | // allow the use of rvalue references in C++98/03 for the benefit of | |||
4851 | // standard library implementors; therefore, we need the xvalue check here. | |||
4852 | SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || | |||
4853 | !(InitCategory.isPRValue() || T2->isRecordType())); | |||
4854 | return ICS; | |||
4855 | } | |||
4856 | ||||
4857 | // -- has a class type (i.e., T2 is a class type), where T1 is not | |||
4858 | // reference-related to T2, and can be implicitly converted to | |||
4859 | // an xvalue, class prvalue, or function lvalue of type | |||
4860 | // "cv3 T3", where "cv1 T1" is reference-compatible with | |||
4861 | // "cv3 T3", | |||
4862 | // | |||
4863 | // then the reference is bound to the value of the initializer | |||
4864 | // expression in the first case and to the result of the conversion | |||
4865 | // in the second case (or, in either case, to an appropriate base | |||
4866 | // class subobject). | |||
4867 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && | |||
4868 | T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && | |||
4869 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, | |||
4870 | Init, T2, /*AllowRvalues=*/true, | |||
4871 | AllowExplicit)) { | |||
4872 | // In the second case, if the reference is an rvalue reference | |||
4873 | // and the second standard conversion sequence of the | |||
4874 | // user-defined conversion sequence includes an lvalue-to-rvalue | |||
4875 | // conversion, the program is ill-formed. | |||
4876 | if (ICS.isUserDefined() && isRValRef && | |||
4877 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) | |||
4878 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); | |||
4879 | ||||
4880 | return ICS; | |||
4881 | } | |||
4882 | ||||
4883 | // A temporary of function type cannot be created; don't even try. | |||
4884 | if (T1->isFunctionType()) | |||
4885 | return ICS; | |||
4886 | ||||
4887 | // -- Otherwise, a temporary of type "cv1 T1" is created and | |||
4888 | // initialized from the initializer expression using the | |||
4889 | // rules for a non-reference copy initialization (8.5). The | |||
4890 | // reference is then bound to the temporary. If T1 is | |||
4891 | // reference-related to T2, cv1 must be the same | |||
4892 | // cv-qualification as, or greater cv-qualification than, | |||
4893 | // cv2; otherwise, the program is ill-formed. | |||
4894 | if (RefRelationship == Sema::Ref_Related) { | |||
4895 | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then | |||
4896 | // we would be reference-compatible or reference-compatible with | |||
4897 | // added qualification. But that wasn't the case, so the reference | |||
4898 | // initialization fails. | |||
4899 | // | |||
4900 | // Note that we only want to check address spaces and cvr-qualifiers here. | |||
4901 | // ObjC GC, lifetime and unaligned qualifiers aren't important. | |||
4902 | Qualifiers T1Quals = T1.getQualifiers(); | |||
4903 | Qualifiers T2Quals = T2.getQualifiers(); | |||
4904 | T1Quals.removeObjCGCAttr(); | |||
4905 | T1Quals.removeObjCLifetime(); | |||
4906 | T2Quals.removeObjCGCAttr(); | |||
4907 | T2Quals.removeObjCLifetime(); | |||
4908 | // MS compiler ignores __unaligned qualifier for references; do the same. | |||
4909 | T1Quals.removeUnaligned(); | |||
4910 | T2Quals.removeUnaligned(); | |||
4911 | if (!T1Quals.compatiblyIncludes(T2Quals)) | |||
4912 | return ICS; | |||
4913 | } | |||
4914 | ||||
4915 | // If at least one of the types is a class type, the types are not | |||
4916 | // related, and we aren't allowed any user conversions, the | |||
4917 | // reference binding fails. This case is important for breaking | |||
4918 | // recursion, since TryImplicitConversion below will attempt to | |||
4919 | // create a temporary through the use of a copy constructor. | |||
4920 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && | |||
4921 | (T1->isRecordType() || T2->isRecordType())) | |||
4922 | return ICS; | |||
4923 | ||||
4924 | // If T1 is reference-related to T2 and the reference is an rvalue | |||
4925 | // reference, the initializer expression shall not be an lvalue. | |||
4926 | if (RefRelationship >= Sema::Ref_Related && isRValRef && | |||
4927 | Init->Classify(S.Context).isLValue()) { | |||
4928 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); | |||
4929 | return ICS; | |||
4930 | } | |||
4931 | ||||
4932 | // C++ [over.ics.ref]p2: | |||
4933 | // When a parameter of reference type is not bound directly to | |||
4934 | // an argument expression, the conversion sequence is the one | |||
4935 | // required to convert the argument expression to the | |||
4936 | // underlying type of the reference according to | |||
4937 | // 13.3.3.1. Conceptually, this conversion sequence corresponds | |||
4938 | // to copy-initializing a temporary of the underlying type with | |||
4939 | // the argument expression. Any difference in top-level | |||
4940 | // cv-qualification is subsumed by the initialization itself | |||
4941 | // and does not constitute a conversion. | |||
4942 | ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, | |||
4943 | AllowedExplicit::None, | |||
4944 | /*InOverloadResolution=*/false, | |||
4945 | /*CStyle=*/false, | |||
4946 | /*AllowObjCWritebackConversion=*/false, | |||
4947 | /*AllowObjCConversionOnExplicit=*/false); | |||
4948 | ||||
4949 | // Of course, that's still a reference binding. | |||
4950 | if (ICS.isStandard()) { | |||
4951 | ICS.Standard.ReferenceBinding = true; | |||
4952 | ICS.Standard.IsLvalueReference = !isRValRef; | |||
4953 | ICS.Standard.BindsToFunctionLvalue = false; | |||
4954 | ICS.Standard.BindsToRvalue = true; | |||
4955 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4956 | ICS.Standard.ObjCLifetimeConversionBinding = false; | |||
4957 | } else if (ICS.isUserDefined()) { | |||
4958 | const ReferenceType *LValRefType = | |||
4959 | ICS.UserDefined.ConversionFunction->getReturnType() | |||
4960 | ->getAs<LValueReferenceType>(); | |||
4961 | ||||
4962 | // C++ [over.ics.ref]p3: | |||
4963 | // Except for an implicit object parameter, for which see 13.3.1, a | |||
4964 | // standard conversion sequence cannot be formed if it requires [...] | |||
4965 | // binding an rvalue reference to an lvalue other than a function | |||
4966 | // lvalue. | |||
4967 | // Note that the function case is not possible here. | |||
4968 | if (isRValRef && LValRefType) { | |||
4969 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); | |||
4970 | return ICS; | |||
4971 | } | |||
4972 | ||||
4973 | ICS.UserDefined.After.ReferenceBinding = true; | |||
4974 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; | |||
4975 | ICS.UserDefined.After.BindsToFunctionLvalue = false; | |||
4976 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; | |||
4977 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4978 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; | |||
4979 | } | |||
4980 | ||||
4981 | return ICS; | |||
4982 | } | |||
4983 | ||||
4984 | static ImplicitConversionSequence | |||
4985 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, | |||
4986 | bool SuppressUserConversions, | |||
4987 | bool InOverloadResolution, | |||
4988 | bool AllowObjCWritebackConversion, | |||
4989 | bool AllowExplicit = false); | |||
4990 | ||||
4991 | /// TryListConversion - Try to copy-initialize a value of type ToType from the | |||
4992 | /// initializer list From. | |||
4993 | static ImplicitConversionSequence | |||
4994 | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, | |||
4995 | bool SuppressUserConversions, | |||
4996 | bool InOverloadResolution, | |||
4997 | bool AllowObjCWritebackConversion) { | |||
4998 | // C++11 [over.ics.list]p1: | |||
4999 | // When an argument is an initializer list, it is not an expression and | |||
5000 | // special rules apply for converting it to a parameter type. | |||
5001 | ||||
5002 | ImplicitConversionSequence Result; | |||
5003 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
5004 | ||||
5005 | // We need a complete type for what follows. With one C++20 exception, | |||
5006 | // incomplete types can never be initialized from init lists. | |||
5007 | QualType InitTy = ToType; | |||
5008 | const ArrayType *AT = S.Context.getAsArrayType(ToType); | |||
5009 | if (AT && S.getLangOpts().CPlusPlus20) | |||
5010 | if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) | |||
5011 | // C++20 allows list initialization of an incomplete array type. | |||
5012 | InitTy = IAT->getElementType(); | |||
5013 | if (!S.isCompleteType(From->getBeginLoc(), InitTy)) | |||
5014 | return Result; | |||
5015 | ||||
5016 | // Per DR1467: | |||
5017 | // If the parameter type is a class X and the initializer list has a single | |||
5018 | // element of type cv U, where U is X or a class derived from X, the | |||
5019 | // implicit conversion sequence is the one required to convert the element | |||
5020 | // to the parameter type. | |||
5021 | // | |||
5022 | // Otherwise, if the parameter type is a character array [... ] | |||
5023 | // and the initializer list has a single element that is an | |||
5024 | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the | |||
5025 | // implicit conversion sequence is the identity conversion. | |||
5026 | if (From->getNumInits() == 1) { | |||
5027 | if (ToType->isRecordType()) { | |||
5028 | QualType InitType = From->getInit(0)->getType(); | |||
5029 | if (S.Context.hasSameUnqualifiedType(InitType, ToType) || | |||
5030 | S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) | |||
5031 | return TryCopyInitialization(S, From->getInit(0), ToType, | |||
5032 | SuppressUserConversions, | |||
5033 | InOverloadResolution, | |||
5034 | AllowObjCWritebackConversion); | |||
5035 | } | |||
5036 | ||||
5037 | if (AT && S.IsStringInit(From->getInit(0), AT)) { | |||
5038 | InitializedEntity Entity = | |||
5039 | InitializedEntity::InitializeParameter(S.Context, ToType, | |||
5040 | /*Consumed=*/false); | |||
5041 | if (S.CanPerformCopyInitialization(Entity, From)) { | |||
5042 | Result.setStandard(); | |||
5043 | Result.Standard.setAsIdentityConversion(); | |||
5044 | Result.Standard.setFromType(ToType); | |||
5045 | Result.Standard.setAllToTypes(ToType); | |||
5046 | return Result; | |||
5047 | } | |||
5048 | } | |||
5049 | } | |||
5050 | ||||
5051 | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). | |||
5052 | // C++11 [over.ics.list]p2: | |||
5053 | // If the parameter type is std::initializer_list<X> or "array of X" and | |||
5054 | // all the elements can be implicitly converted to X, the implicit | |||
5055 | // conversion sequence is the worst conversion necessary to convert an | |||
5056 | // element of the list to X. | |||
5057 | // | |||
5058 | // C++14 [over.ics.list]p3: | |||
5059 | // Otherwise, if the parameter type is "array of N X", if the initializer | |||
5060 | // list has exactly N elements or if it has fewer than N elements and X is | |||
5061 | // default-constructible, and if all the elements of the initializer list | |||
5062 | // can be implicitly converted to X, the implicit conversion sequence is | |||
5063 | // the worst conversion necessary to convert an element of the list to X. | |||
5064 | if (AT || S.isStdInitializerList(ToType, &InitTy)) { | |||
5065 | unsigned e = From->getNumInits(); | |||
5066 | ImplicitConversionSequence DfltElt; | |||
5067 | DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), | |||
5068 | QualType()); | |||
5069 | QualType ContTy = ToType; | |||
5070 | bool IsUnbounded = false; | |||
5071 | if (AT) { | |||
5072 | InitTy = AT->getElementType(); | |||
5073 | if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { | |||
5074 | if (CT->getSize().ult(e)) { | |||
5075 | // Too many inits, fatally bad | |||
5076 | Result.setBad(BadConversionSequence::too_many_initializers, From, | |||
5077 | ToType); | |||
5078 | Result.setInitializerListContainerType(ContTy, IsUnbounded); | |||
5079 | return Result; | |||
5080 | } | |||
5081 | if (CT->getSize().ugt(e)) { | |||
5082 | // Need an init from empty {}, is there one? | |||
5083 | InitListExpr EmptyList(S.Context, From->getEndLoc(), None, | |||
5084 | From->getEndLoc()); | |||
5085 | EmptyList.setType(S.Context.VoidTy); | |||
5086 | DfltElt = TryListConversion( | |||
5087 | S, &EmptyList, InitTy, SuppressUserConversions, | |||
5088 | InOverloadResolution, AllowObjCWritebackConversion); | |||
5089 | if (DfltElt.isBad()) { | |||
5090 | // No {} init, fatally bad | |||
5091 | Result.setBad(BadConversionSequence::too_few_initializers, From, | |||
5092 | ToType); | |||
5093 | Result.setInitializerListContainerType(ContTy, IsUnbounded); | |||
5094 | return Result; | |||
5095 | } | |||
5096 | } | |||
5097 | } else { | |||
5098 | assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT) && "Expected incomplete array") ? void (0) : __assert_fail ("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\"" , "clang/lib/Sema/SemaOverload.cpp", 5098, __extension__ __PRETTY_FUNCTION__ )); | |||
5099 | IsUnbounded = true; | |||
5100 | if (!e) { | |||
5101 | // Cannot convert to zero-sized. | |||
5102 | Result.setBad(BadConversionSequence::too_few_initializers, From, | |||
5103 | ToType); | |||
5104 | Result.setInitializerListContainerType(ContTy, IsUnbounded); | |||
5105 | return Result; | |||
5106 | } | |||
5107 | llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); | |||
5108 | ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, | |||
5109 | ArrayType::Normal, 0); | |||
5110 | } | |||
5111 | } | |||
5112 | ||||
5113 | Result.setStandard(); | |||
5114 | Result.Standard.setAsIdentityConversion(); | |||
5115 | Result.Standard.setFromType(InitTy); | |||
5116 | Result.Standard.setAllToTypes(InitTy); | |||
5117 | for (unsigned i = 0; i < e; ++i) { | |||
5118 | Expr *Init = From->getInit(i); | |||
5119 | ImplicitConversionSequence ICS = TryCopyInitialization( | |||
5120 | S, Init, InitTy, SuppressUserConversions, InOverloadResolution, | |||
5121 | AllowObjCWritebackConversion); | |||
5122 | ||||
5123 | // Keep the worse conversion seen so far. | |||
5124 | // FIXME: Sequences are not totally ordered, so 'worse' can be | |||
5125 | // ambiguous. CWG has been informed. | |||
5126 | if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, | |||
5127 | Result) == | |||
5128 | ImplicitConversionSequence::Worse) { | |||
5129 | Result = ICS; | |||
5130 | // Bail as soon as we find something unconvertible. | |||
5131 | if (Result.isBad()) { | |||
5132 | Result.setInitializerListContainerType(ContTy, IsUnbounded); | |||
5133 | return Result; | |||
5134 | } | |||
5135 | } | |||
5136 | } | |||
5137 | ||||
5138 | // If we needed any implicit {} initialization, compare that now. | |||
5139 | // over.ics.list/6 indicates we should compare that conversion. Again CWG | |||
5140 | // has been informed that this might not be the best thing. | |||
5141 | if (!DfltElt.isBad() && CompareImplicitConversionSequences( | |||
5142 | S, From->getEndLoc(), DfltElt, Result) == | |||
5143 | ImplicitConversionSequence::Worse) | |||
5144 | Result = DfltElt; | |||
5145 | // Record the type being initialized so that we may compare sequences | |||
5146 | Result.setInitializerListContainerType(ContTy, IsUnbounded); | |||
5147 | return Result; | |||
5148 | } | |||
5149 | ||||
5150 | // C++14 [over.ics.list]p4: | |||
5151 | // C++11 [over.ics.list]p3: | |||
5152 | // Otherwise, if the parameter is a non-aggregate class X and overload | |||
5153 | // resolution chooses a single best constructor [...] the implicit | |||
5154 | // conversion sequence is a user-defined conversion sequence. If multiple | |||
5155 | // constructors are viable but none is better than the others, the | |||
5156 | // implicit conversion sequence is a user-defined conversion sequence. | |||
5157 | if (ToType->isRecordType() && !ToType->isAggregateType()) { | |||
5158 | // This function can deal with initializer lists. | |||
5159 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, | |||
5160 | AllowedExplicit::None, | |||
5161 | InOverloadResolution, /*CStyle=*/false, | |||
5162 | AllowObjCWritebackConversion, | |||
5163 | /*AllowObjCConversionOnExplicit=*/false); | |||
5164 | } | |||
5165 | ||||
5166 | // C++14 [over.ics.list]p5: | |||
5167 | // C++11 [over.ics.list]p4: | |||
5168 | // Otherwise, if the parameter has an aggregate type which can be | |||
5169 | // initialized from the initializer list [...] the implicit conversion | |||
5170 | // sequence is a user-defined conversion sequence. | |||
5171 | if (ToType->isAggregateType()) { | |||
5172 | // Type is an aggregate, argument is an init list. At this point it comes | |||
5173 | // down to checking whether the initialization works. | |||
5174 | // FIXME: Find out whether this parameter is consumed or not. | |||
5175 | InitializedEntity Entity = | |||
5176 | InitializedEntity::InitializeParameter(S.Context, ToType, | |||
5177 | /*Consumed=*/false); | |||
5178 | if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, | |||
5179 | From)) { | |||
5180 | Result.setUserDefined(); | |||
5181 | Result.UserDefined.Before.setAsIdentityConversion(); | |||
5182 | // Initializer lists don't have a type. | |||
5183 | Result.UserDefined.Before.setFromType(QualType()); | |||
5184 | Result.UserDefined.Before.setAllToTypes(QualType()); | |||
5185 | ||||
5186 | Result.UserDefined.After.setAsIdentityConversion(); | |||
5187 | Result.UserDefined.After.setFromType(ToType); | |||
5188 | Result.UserDefined.After.setAllToTypes(ToType); | |||
5189 | Result.UserDefined.ConversionFunction = nullptr; | |||
5190 | } | |||
5191 | return Result; | |||
5192 | } | |||
5193 | ||||
5194 | // C++14 [over.ics.list]p6: | |||
5195 | // C++11 [over.ics.list]p5: | |||
5196 | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. | |||
5197 | if (ToType->isReferenceType()) { | |||
5198 | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't | |||
5199 | // mention initializer lists in any way. So we go by what list- | |||
5200 | // initialization would do and try to extrapolate from that. | |||
5201 | ||||
5202 | QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); | |||
5203 | ||||
5204 | // If the initializer list has a single element that is reference-related | |||
5205 | // to the parameter type, we initialize the reference from that. | |||
5206 | if (From->getNumInits() == 1) { | |||
5207 | Expr *Init = From->getInit(0); | |||
5208 | ||||
5209 | QualType T2 = Init->getType(); | |||
5210 | ||||
5211 | // If the initializer is the address of an overloaded function, try | |||
5212 | // to resolve the overloaded function. If all goes well, T2 is the | |||
5213 | // type of the resulting function. | |||
5214 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { | |||
5215 | DeclAccessPair Found; | |||
5216 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( | |||
5217 | Init, ToType, false, Found)) | |||
5218 | T2 = Fn->getType(); | |||
5219 | } | |||
5220 | ||||
5221 | // Compute some basic properties of the types and the initializer. | |||
5222 | Sema::ReferenceCompareResult RefRelationship = | |||
5223 | S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); | |||
5224 | ||||
5225 | if (RefRelationship >= Sema::Ref_Related) { | |||
5226 | return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), | |||
5227 | SuppressUserConversions, | |||
5228 | /*AllowExplicit=*/false); | |||
5229 | } | |||
5230 | } | |||
5231 | ||||
5232 | // Otherwise, we bind the reference to a temporary created from the | |||
5233 | // initializer list. | |||
5234 | Result = TryListConversion(S, From, T1, SuppressUserConversions, | |||
5235 | InOverloadResolution, | |||
5236 | AllowObjCWritebackConversion); | |||
5237 | if (Result.isFailure()) | |||
5238 | return Result; | |||
5239 | assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "clang/lib/Sema/SemaOverload.cpp", 5240, __extension__ __PRETTY_FUNCTION__ )) | |||
5240 | "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "clang/lib/Sema/SemaOverload.cpp", 5240, __extension__ __PRETTY_FUNCTION__ )); | |||
5241 | ||||
5242 | // Can we even bind to a temporary? | |||
5243 | if (ToType->isRValueReferenceType() || | |||
5244 | (T1.isConstQualified() && !T1.isVolatileQualified())) { | |||
5245 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : | |||
5246 | Result.UserDefined.After; | |||
5247 | SCS.ReferenceBinding = true; | |||
5248 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); | |||
5249 | SCS.BindsToRvalue = true; | |||
5250 | SCS.BindsToFunctionLvalue = false; | |||
5251 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
5252 | SCS.ObjCLifetimeConversionBinding = false; | |||
5253 | } else | |||
5254 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, | |||
5255 | From, ToType); | |||
5256 | return Result; | |||
5257 | } | |||
5258 | ||||
5259 | // C++14 [over.ics.list]p7: | |||
5260 | // C++11 [over.ics.list]p6: | |||
5261 | // Otherwise, if the parameter type is not a class: | |||
5262 | if (!ToType->isRecordType()) { | |||
5263 | // - if the initializer list has one element that is not itself an | |||
5264 | // initializer list, the implicit conversion sequence is the one | |||
5265 | // required to convert the element to the parameter type. | |||
5266 | unsigned NumInits = From->getNumInits(); | |||
5267 | if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) | |||
5268 | Result = TryCopyInitialization(S, From->getInit(0), ToType, | |||
5269 | SuppressUserConversions, | |||
5270 | InOverloadResolution, | |||
5271 | AllowObjCWritebackConversion); | |||
5272 | // - if the initializer list has no elements, the implicit conversion | |||
5273 | // sequence is the identity conversion. | |||
5274 | else if (NumInits == 0) { | |||
5275 | Result.setStandard(); | |||
5276 | Result.Standard.setAsIdentityConversion(); | |||
5277 | Result.Standard.setFromType(ToType); | |||
5278 | Result.Standard.setAllToTypes(ToType); | |||
5279 | } | |||
5280 | return Result; | |||
5281 | } | |||
5282 | ||||
5283 | // C++14 [over.ics.list]p8: | |||
5284 | // C++11 [over.ics.list]p7: | |||
5285 | // In all cases other than those enumerated above, no conversion is possible | |||
5286 | return Result; | |||
5287 | } | |||
5288 | ||||
5289 | /// TryCopyInitialization - Try to copy-initialize a value of type | |||
5290 | /// ToType from the expression From. Return the implicit conversion | |||
5291 | /// sequence required to pass this argument, which may be a bad | |||
5292 | /// conversion sequence (meaning that the argument cannot be passed to | |||
5293 | /// a parameter of this type). If @p SuppressUserConversions, then we | |||
5294 | /// do not permit any user-defined conversion sequences. | |||
5295 | static ImplicitConversionSequence | |||
5296 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, | |||
5297 | bool SuppressUserConversions, | |||
5298 | bool InOverloadResolution, | |||
5299 | bool AllowObjCWritebackConversion, | |||
5300 | bool AllowExplicit) { | |||
5301 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) | |||
5302 | return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, | |||
5303 | InOverloadResolution,AllowObjCWritebackConversion); | |||
5304 | ||||
5305 | if (ToType->isReferenceType()) | |||
5306 | return TryReferenceInit(S, From, ToType, | |||
5307 | /*FIXME:*/ From->getBeginLoc(), | |||
5308 | SuppressUserConversions, AllowExplicit); | |||
5309 | ||||
5310 | return TryImplicitConversion(S, From, ToType, | |||
5311 | SuppressUserConversions, | |||
5312 | AllowedExplicit::None, | |||
5313 | InOverloadResolution, | |||
5314 | /*CStyle=*/false, | |||
5315 | AllowObjCWritebackConversion, | |||
5316 | /*AllowObjCConversionOnExplicit=*/false); | |||
5317 | } | |||
5318 | ||||
5319 | static bool TryCopyInitialization(const CanQualType FromQTy, | |||
5320 | const CanQualType ToQTy, | |||
5321 | Sema &S, | |||
5322 | SourceLocation Loc, | |||
5323 | ExprValueKind FromVK) { | |||
5324 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); | |||
5325 | ImplicitConversionSequence ICS = | |||
5326 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); | |||
5327 | ||||
5328 | return !ICS.isBad(); | |||
5329 | } | |||
5330 | ||||
5331 | /// TryObjectArgumentInitialization - Try to initialize the object | |||
5332 | /// parameter of the given member function (@c Method) from the | |||
5333 | /// expression @p From. | |||
5334 | static ImplicitConversionSequence | |||
5335 | TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, | |||
5336 | Expr::Classification FromClassification, | |||
5337 | CXXMethodDecl *Method, | |||
5338 | CXXRecordDecl *ActingContext) { | |||
5339 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); | |||
5340 | // [class.dtor]p2: A destructor can be invoked for a const, volatile or | |||
5341 | // const volatile object. | |||
5342 | Qualifiers Quals = Method->getMethodQualifiers(); | |||
5343 | if (isa<CXXDestructorDecl>(Method)) { | |||
5344 | Quals.addConst(); | |||
5345 | Quals.addVolatile(); | |||
5346 | } | |||
5347 | ||||
5348 | QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); | |||
5349 | ||||
5350 | // Set up the conversion sequence as a "bad" conversion, to allow us | |||
5351 | // to exit early. | |||
5352 | ImplicitConversionSequence ICS; | |||
5353 | ||||
5354 | // We need to have an object of class type. | |||
5355 | if (const PointerType *PT = FromType->getAs<PointerType>()) { | |||
5356 | FromType = PT->getPointeeType(); | |||
5357 | ||||
5358 | // When we had a pointer, it's implicitly dereferenced, so we | |||
5359 | // better have an lvalue. | |||
5360 | assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void (0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp" , 5360, __extension__ __PRETTY_FUNCTION__)); | |||
5361 | } | |||
5362 | ||||
5363 | assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void (0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp" , 5363, __extension__ __PRETTY_FUNCTION__)); | |||
5364 | ||||
5365 | // C++0x [over.match.funcs]p4: | |||
5366 | // For non-static member functions, the type of the implicit object | |||
5367 | // parameter is | |||
5368 | // | |||
5369 | // - "lvalue reference to cv X" for functions declared without a | |||
5370 | // ref-qualifier or with the & ref-qualifier | |||
5371 | // - "rvalue reference to cv X" for functions declared with the && | |||
5372 | // ref-qualifier | |||
5373 | // | |||
5374 | // where X is the class of which the function is a member and cv is the | |||
5375 | // cv-qualification on the member function declaration. | |||
5376 | // | |||
5377 | // However, when finding an implicit conversion sequence for the argument, we | |||
5378 | // are not allowed to perform user-defined conversions | |||
5379 | // (C++ [over.match.funcs]p5). We perform a simplified version of | |||
5380 | // reference binding here, that allows class rvalues to bind to | |||
5381 | // non-constant references. | |||
5382 | ||||
5383 | // First check the qualifiers. | |||
5384 | QualType FromTypeCanon = S.Context.getCanonicalType(FromType); | |||
5385 | if (ImplicitParamType.getCVRQualifiers() | |||
5386 | != FromTypeCanon.getLocalCVRQualifiers() && | |||
5387 | !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { | |||
5388 | ICS.setBad(BadConversionSequence::bad_qualifiers, | |||
5389 | FromType, ImplicitParamType); | |||
5390 | return ICS; | |||
5391 | } | |||
5392 | ||||
5393 | if (FromTypeCanon.hasAddressSpace()) { | |||
5394 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); | |||
5395 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); | |||
5396 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { | |||
5397 | ICS.setBad(BadConversionSequence::bad_qualifiers, | |||
5398 | FromType, ImplicitParamType); | |||
5399 | return ICS; | |||
5400 | } | |||
5401 | } | |||
5402 | ||||
5403 | // Check that we have either the same type or a derived type. It | |||
5404 | // affects the conversion rank. | |||
5405 | QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); | |||
5406 | ImplicitConversionKind SecondKind; | |||
5407 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { | |||
5408 | SecondKind = ICK_Identity; | |||
5409 | } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) | |||
5410 | SecondKind = ICK_Derived_To_Base; | |||
5411 | else { | |||
5412 | ICS.setBad(BadConversionSequence::unrelated_class, | |||
5413 | FromType, ImplicitParamType); | |||
5414 | return ICS; | |||
5415 | } | |||
5416 | ||||
5417 | // Check the ref-qualifier. | |||
5418 | switch (Method->getRefQualifier()) { | |||
5419 | case RQ_None: | |||
5420 | // Do nothing; we don't care about lvalueness or rvalueness. | |||
5421 | break; | |||
5422 | ||||
5423 | case RQ_LValue: | |||
5424 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { | |||
5425 | // non-const lvalue reference cannot bind to an rvalue | |||
5426 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, | |||
5427 | ImplicitParamType); | |||
5428 | return ICS; | |||
5429 | } | |||
5430 | break; | |||
5431 | ||||
5432 | case RQ_RValue: | |||
5433 | if (!FromClassification.isRValue()) { | |||
5434 | // rvalue reference cannot bind to an lvalue | |||
5435 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, | |||
5436 | ImplicitParamType); | |||
5437 | return ICS; | |||
5438 | } | |||
5439 | break; | |||
5440 | } | |||
5441 | ||||
5442 | // Success. Mark this as a reference binding. | |||
5443 | ICS.setStandard(); | |||
5444 | ICS.Standard.setAsIdentityConversion(); | |||
5445 | ICS.Standard.Second = SecondKind; | |||
5446 | ICS.Standard.setFromType(FromType); | |||
5447 | ICS.Standard.setAllToTypes(ImplicitParamType); | |||
5448 | ICS.Standard.ReferenceBinding = true; | |||
5449 | ICS.Standard.DirectBinding = true; | |||
5450 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; | |||
5451 | ICS.Standard.BindsToFunctionLvalue = false; | |||
5452 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); | |||
5453 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier | |||
5454 | = (Method->getRefQualifier() == RQ_None); | |||
5455 | return ICS; | |||
5456 | } | |||
5457 | ||||
5458 | /// PerformObjectArgumentInitialization - Perform initialization of | |||
5459 | /// the implicit object parameter for the given Method with the given | |||
5460 | /// expression. | |||
5461 | ExprResult | |||
5462 | Sema::PerformObjectArgumentInitialization(Expr *From, | |||
5463 | NestedNameSpecifier *Qualifier, | |||
5464 | NamedDecl *FoundDecl, | |||
5465 | CXXMethodDecl *Method) { | |||
5466 | QualType FromRecordType, DestType; | |||
5467 | QualType ImplicitParamRecordType = | |||
5468 | Method->getThisType()->castAs<PointerType>()->getPointeeType(); | |||
5469 | ||||
5470 | Expr::Classification FromClassification; | |||
5471 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { | |||
5472 | FromRecordType = PT->getPointeeType(); | |||
5473 | DestType = Method->getThisType(); | |||
5474 | FromClassification = Expr::Classification::makeSimpleLValue(); | |||
5475 | } else { | |||
5476 | FromRecordType = From->getType(); | |||
5477 | DestType = ImplicitParamRecordType; | |||
5478 | FromClassification = From->Classify(Context); | |||
5479 | ||||
5480 | // When performing member access on a prvalue, materialize a temporary. | |||
5481 | if (From->isPRValue()) { | |||
5482 | From = CreateMaterializeTemporaryExpr(FromRecordType, From, | |||
5483 | Method->getRefQualifier() != | |||
5484 | RefQualifierKind::RQ_RValue); | |||
5485 | } | |||
5486 | } | |||
5487 | ||||
5488 | // Note that we always use the true parent context when performing | |||
5489 | // the actual argument initialization. | |||
5490 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( | |||
5491 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, | |||
5492 | Method->getParent()); | |||
5493 | if (ICS.isBad()) { | |||
5494 | switch (ICS.Bad.Kind) { | |||
5495 | case BadConversionSequence::bad_qualifiers: { | |||
5496 | Qualifiers FromQs = FromRecordType.getQualifiers(); | |||
5497 | Qualifiers ToQs = DestType.getQualifiers(); | |||
5498 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); | |||
5499 | if (CVR) { | |||
5500 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) | |||
5501 | << Method->getDeclName() << FromRecordType << (CVR - 1) | |||
5502 | << From->getSourceRange(); | |||
5503 | Diag(Method->getLocation(), diag::note_previous_decl) | |||
5504 | << Method->getDeclName(); | |||
5505 | return ExprError(); | |||
5506 | } | |||
5507 | break; | |||
5508 | } | |||
5509 | ||||
5510 | case BadConversionSequence::lvalue_ref_to_rvalue: | |||
5511 | case BadConversionSequence::rvalue_ref_to_lvalue: { | |||
5512 | bool IsRValueQualified = | |||
5513 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; | |||
5514 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) | |||
5515 | << Method->getDeclName() << FromClassification.isRValue() | |||
5516 | << IsRValueQualified; | |||
5517 | Diag(Method->getLocation(), diag::note_previous_decl) | |||
5518 | << Method->getDeclName(); | |||
5519 | return ExprError(); | |||
5520 | } | |||
5521 | ||||
5522 | case BadConversionSequence::no_conversion: | |||
5523 | case BadConversionSequence::unrelated_class: | |||
5524 | break; | |||
5525 | ||||
5526 | case BadConversionSequence::too_few_initializers: | |||
5527 | case BadConversionSequence::too_many_initializers: | |||
5528 | llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp" , 5528); | |||
5529 | } | |||
5530 | ||||
5531 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) | |||
5532 | << ImplicitParamRecordType << FromRecordType | |||
5533 | << From->getSourceRange(); | |||
5534 | } | |||
5535 | ||||
5536 | if (ICS.Standard.Second == ICK_Derived_To_Base) { | |||
5537 | ExprResult FromRes = | |||
5538 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); | |||
5539 | if (FromRes.isInvalid()) | |||
5540 | return ExprError(); | |||
5541 | From = FromRes.get(); | |||
5542 | } | |||
5543 | ||||
5544 | if (!Context.hasSameType(From->getType(), DestType)) { | |||
5545 | CastKind CK; | |||
5546 | QualType PteeTy = DestType->getPointeeType(); | |||
5547 | LangAS DestAS = | |||
5548 | PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); | |||
5549 | if (FromRecordType.getAddressSpace() != DestAS) | |||
5550 | CK = CK_AddressSpaceConversion; | |||
5551 | else | |||
5552 | CK = CK_NoOp; | |||
5553 | From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); | |||
5554 | } | |||
5555 | return From; | |||
5556 | } | |||
5557 | ||||
5558 | /// TryContextuallyConvertToBool - Attempt to contextually convert the | |||
5559 | /// expression From to bool (C++0x [conv]p3). | |||
5560 | static ImplicitConversionSequence | |||
5561 | TryContextuallyConvertToBool(Sema &S, Expr *From) { | |||
5562 | // C++ [dcl.init]/17.8: | |||
5563 | // - Otherwise, if the initialization is direct-initialization, the source | |||
5564 | // type is std::nullptr_t, and the destination type is bool, the initial | |||
5565 | // value of the object being initialized is false. | |||
5566 | if (From->getType()->isNullPtrType()) | |||
5567 | return ImplicitConversionSequence::getNullptrToBool(From->getType(), | |||
5568 | S.Context.BoolTy, | |||
5569 | From->isGLValue()); | |||
5570 | ||||
5571 | // All other direct-initialization of bool is equivalent to an implicit | |||
5572 | // conversion to bool in which explicit conversions are permitted. | |||
5573 | return TryImplicitConversion(S, From, S.Context.BoolTy, | |||
5574 | /*SuppressUserConversions=*/false, | |||
5575 | AllowedExplicit::Conversions, | |||
5576 | /*InOverloadResolution=*/false, | |||
5577 | /*CStyle=*/false, | |||
5578 | /*AllowObjCWritebackConversion=*/false, | |||
5579 | /*AllowObjCConversionOnExplicit=*/false); | |||
5580 | } | |||
5581 | ||||
5582 | /// PerformContextuallyConvertToBool - Perform a contextual conversion | |||
5583 | /// of the expression From to bool (C++0x [conv]p3). | |||
5584 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { | |||
5585 | if (checkPlaceholderForOverload(*this, From)) | |||
5586 | return ExprError(); | |||
5587 | ||||
5588 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); | |||
5589 | if (!ICS.isBad()) | |||
5590 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); | |||
5591 | ||||
5592 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) | |||
5593 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) | |||
5594 | << From->getType() << From->getSourceRange(); | |||
5595 | return ExprError(); | |||
5596 | } | |||
5597 | ||||
5598 | /// Check that the specified conversion is permitted in a converted constant | |||
5599 | /// expression, according to C++11 [expr.const]p3. Return true if the conversion | |||
5600 | /// is acceptable. | |||
5601 | static bool CheckConvertedConstantConversions(Sema &S, | |||
5602 | StandardConversionSequence &SCS) { | |||
5603 | // Since we know that the target type is an integral or unscoped enumeration | |||
5604 | // type, most conversion kinds are impossible. All possible First and Third | |||
5605 | // conversions are fine. | |||
5606 | switch (SCS.Second) { | |||
5607 | case ICK_Identity: | |||
5608 | case ICK_Integral_Promotion: | |||
5609 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. | |||
5610 | case ICK_Zero_Queue_Conversion: | |||
5611 | return true; | |||
5612 | ||||
5613 | case ICK_Boolean_Conversion: | |||
5614 | // Conversion from an integral or unscoped enumeration type to bool is | |||
5615 | // classified as ICK_Boolean_Conversion, but it's also arguably an integral | |||
5616 | // conversion, so we allow it in a converted constant expression. | |||
5617 | // | |||
5618 | // FIXME: Per core issue 1407, we should not allow this, but that breaks | |||
5619 | // a lot of popular code. We should at least add a warning for this | |||
5620 | // (non-conforming) extension. | |||
5621 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && | |||
5622 | SCS.getToType(2)->isBooleanType(); | |||
5623 | ||||
5624 | case ICK_Pointer_Conversion: | |||
5625 | case ICK_Pointer_Member: | |||
5626 | // C++1z: null pointer conversions and null member pointer conversions are | |||
5627 | // only permitted if the source type is std::nullptr_t. | |||
5628 | return SCS.getFromType()->isNullPtrType(); | |||
5629 | ||||
5630 | case ICK_Floating_Promotion: | |||
5631 | case ICK_Complex_Promotion: | |||
5632 | case ICK_Floating_Conversion: | |||
5633 | case ICK_Complex_Conversion: | |||
5634 | case ICK_Floating_Integral: | |||
5635 | case ICK_Compatible_Conversion: | |||
5636 | case ICK_Derived_To_Base: | |||
5637 | case ICK_Vector_Conversion: | |||
5638 | case ICK_SVE_Vector_Conversion: | |||
5639 | case ICK_Vector_Splat: | |||
5640 | case ICK_Complex_Real: | |||
5641 | case ICK_Block_Pointer_Conversion: | |||
5642 | case ICK_TransparentUnionConversion: | |||
5643 | case ICK_Writeback_Conversion: | |||
5644 | case ICK_Zero_Event_Conversion: | |||
5645 | case ICK_C_Only_Conversion: | |||
5646 | case ICK_Incompatible_Pointer_Conversion: | |||
5647 | return false; | |||
5648 | ||||
5649 | case ICK_Lvalue_To_Rvalue: | |||
5650 | case ICK_Array_To_Pointer: | |||
5651 | case ICK_Function_To_Pointer: | |||
5652 | llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second" , "clang/lib/Sema/SemaOverload.cpp", 5652); | |||
5653 | ||||
5654 | case ICK_Function_Conversion: | |||
5655 | case ICK_Qualification: | |||
5656 | llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second" , "clang/lib/Sema/SemaOverload.cpp", 5656); | |||
5657 | ||||
5658 | case ICK_Num_Conversion_Kinds: | |||
5659 | break; | |||
5660 | } | |||
5661 | ||||
5662 | llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp" , 5662); | |||
5663 | } | |||
5664 | ||||
5665 | /// CheckConvertedConstantExpression - Check that the expression From is a | |||
5666 | /// converted constant expression of type T, perform the conversion and produce | |||
5667 | /// the converted expression, per C++11 [expr.const]p3. | |||
5668 | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, | |||
5669 | QualType T, APValue &Value, | |||
5670 | Sema::CCEKind CCE, | |||
5671 | bool RequireInt, | |||
5672 | NamedDecl *Dest) { | |||
5673 | assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "clang/lib/Sema/SemaOverload.cpp", 5674, __extension__ __PRETTY_FUNCTION__ )) | |||
5674 | "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "clang/lib/Sema/SemaOverload.cpp", 5674, __extension__ __PRETTY_FUNCTION__ )); | |||
5675 | ||||
5676 | if (checkPlaceholderForOverload(S, From)) | |||
5677 | return ExprError(); | |||
5678 | ||||
5679 | // C++1z [expr.const]p3: | |||
5680 | // A converted constant expression of type T is an expression, | |||
5681 | // implicitly converted to type T, where the converted | |||
5682 | // expression is a constant expression and the implicit conversion | |||
5683 | // sequence contains only [... list of conversions ...]. | |||
5684 | ImplicitConversionSequence ICS = | |||
5685 | (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) | |||
5686 | ? TryContextuallyConvertToBool(S, From) | |||
5687 | : TryCopyInitialization(S, From, T, | |||
5688 | /*SuppressUserConversions=*/false, | |||
5689 | /*InOverloadResolution=*/false, | |||
5690 | /*AllowObjCWritebackConversion=*/false, | |||
5691 | /*AllowExplicit=*/false); | |||
5692 | StandardConversionSequence *SCS = nullptr; | |||
5693 | switch (ICS.getKind()) { | |||
5694 | case ImplicitConversionSequence::StandardConversion: | |||
5695 | SCS = &ICS.Standard; | |||
5696 | break; | |||
5697 | case ImplicitConversionSequence::UserDefinedConversion: | |||
5698 | if (T->isRecordType()) | |||
5699 | SCS = &ICS.UserDefined.Before; | |||
5700 | else | |||
5701 | SCS = &ICS.UserDefined.After; | |||
5702 | break; | |||
5703 | case ImplicitConversionSequence::AmbiguousConversion: | |||
5704 | case ImplicitConversionSequence::BadConversion: | |||
5705 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) | |||
5706 | return S.Diag(From->getBeginLoc(), | |||
5707 | diag::err_typecheck_converted_constant_expression) | |||
5708 | << From->getType() << From->getSourceRange() << T; | |||
5709 | return ExprError(); | |||
5710 | ||||
5711 | case ImplicitConversionSequence::EllipsisConversion: | |||
5712 | llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression" , "clang/lib/Sema/SemaOverload.cpp", 5712); | |||
5713 | } | |||
5714 | ||||
5715 | // Check that we would only use permitted conversions. | |||
5716 | if (!CheckConvertedConstantConversions(S, *SCS)) { | |||
5717 | return S.Diag(From->getBeginLoc(), | |||
5718 | diag::err_typecheck_converted_constant_expression_disallowed) | |||
5719 | << From->getType() << From->getSourceRange() << T; | |||
5720 | } | |||
5721 | // [...] and where the reference binding (if any) binds directly. | |||
5722 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { | |||
5723 | return S.Diag(From->getBeginLoc(), | |||
5724 | diag::err_typecheck_converted_constant_expression_indirect) | |||
5725 | << From->getType() << From->getSourceRange() << T; | |||
5726 | } | |||
5727 | ||||
5728 | // Usually we can simply apply the ImplicitConversionSequence we formed | |||
5729 | // earlier, but that's not guaranteed to work when initializing an object of | |||
5730 | // class type. | |||
5731 | ExprResult Result; | |||
5732 | if (T->isRecordType()) { | |||
5733 | assert(CCE == Sema::CCEK_TemplateArg &&(static_cast <bool> (CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr") ? void (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\"" , "clang/lib/Sema/SemaOverload.cpp", 5734, __extension__ __PRETTY_FUNCTION__ )) | |||
5734 | "unexpected class type converted constant expr")(static_cast <bool> (CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr") ? void (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\"" , "clang/lib/Sema/SemaOverload.cpp", 5734, __extension__ __PRETTY_FUNCTION__ )); | |||
5735 | Result = S.PerformCopyInitialization( | |||
5736 | InitializedEntity::InitializeTemplateParameter( | |||
5737 | T, cast<NonTypeTemplateParmDecl>(Dest)), | |||
5738 | SourceLocation(), From); | |||
5739 | } else { | |||
5740 | Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); | |||
5741 | } | |||
5742 | if (Result.isInvalid()) | |||
5743 | return Result; | |||
5744 | ||||
5745 | // C++2a [intro.execution]p5: | |||
5746 | // A full-expression is [...] a constant-expression [...] | |||
5747 | Result = | |||
5748 | S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), | |||
5749 | /*DiscardedValue=*/false, /*IsConstexpr=*/true); | |||
5750 | if (Result.isInvalid()) | |||
5751 | return Result; | |||
5752 | ||||
5753 | // Check for a narrowing implicit conversion. | |||
5754 | bool ReturnPreNarrowingValue = false; | |||
5755 | APValue PreNarrowingValue; | |||
5756 | QualType PreNarrowingType; | |||
5757 | switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, | |||
5758 | PreNarrowingType)) { | |||
5759 | case NK_Dependent_Narrowing: | |||
5760 | // Implicit conversion to a narrower type, but the expression is | |||
5761 | // value-dependent so we can't tell whether it's actually narrowing. | |||
5762 | case NK_Variable_Narrowing: | |||
5763 | // Implicit conversion to a narrower type, and the value is not a constant | |||
5764 | // expression. We'll diagnose this in a moment. | |||
5765 | case NK_Not_Narrowing: | |||
5766 | break; | |||
5767 | ||||
5768 | case NK_Constant_Narrowing: | |||
5769 | if (CCE == Sema::CCEK_ArrayBound && | |||
5770 | PreNarrowingType->isIntegralOrEnumerationType() && | |||
5771 | PreNarrowingValue.isInt()) { | |||
5772 | // Don't diagnose array bound narrowing here; we produce more precise | |||
5773 | // errors by allowing the un-narrowed value through. | |||
5774 | ReturnPreNarrowingValue = true; | |||
5775 | break; | |||
5776 | } | |||
5777 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) | |||
5778 | << CCE << /*Constant*/ 1 | |||
5779 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; | |||
5780 | break; | |||
5781 | ||||
5782 | case NK_Type_Narrowing: | |||
5783 | // FIXME: It would be better to diagnose that the expression is not a | |||
5784 | // constant expression. | |||
5785 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) | |||
5786 | << CCE << /*Constant*/ 0 << From->getType() << T; | |||
5787 | break; | |||
5788 | } | |||
5789 | ||||
5790 | if (Result.get()->isValueDependent()) { | |||
5791 | Value = APValue(); | |||
5792 | return Result; | |||
5793 | } | |||
5794 | ||||
5795 | // Check the expression is a constant expression. | |||
5796 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
5797 | Expr::EvalResult Eval; | |||
5798 | Eval.Diag = &Notes; | |||
5799 | ||||
5800 | ConstantExprKind Kind; | |||
5801 | if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) | |||
5802 | Kind = ConstantExprKind::ClassTemplateArgument; | |||
5803 | else if (CCE == Sema::CCEK_TemplateArg) | |||
5804 | Kind = ConstantExprKind::NonClassTemplateArgument; | |||
5805 | else | |||
5806 | Kind = ConstantExprKind::Normal; | |||
5807 | ||||
5808 | if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || | |||
5809 | (RequireInt && !Eval.Val.isInt())) { | |||
5810 | // The expression can't be folded, so we can't keep it at this position in | |||
5811 | // the AST. | |||
5812 | Result = ExprError(); | |||
5813 | } else { | |||
5814 | Value = Eval.Val; | |||
5815 | ||||
5816 | if (Notes.empty()) { | |||
5817 | // It's a constant expression. | |||
5818 | Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); | |||
5819 | if (ReturnPreNarrowingValue) | |||
5820 | Value = std::move(PreNarrowingValue); | |||
5821 | return E; | |||
5822 | } | |||
5823 | } | |||
5824 | ||||
5825 | // It's not a constant expression. Produce an appropriate diagnostic. | |||
5826 | if (Notes.size() == 1 && | |||
5827 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { | |||
5828 | S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; | |||
5829 | } else if (!Notes.empty() && Notes[0].second.getDiagID() == | |||
5830 | diag::note_constexpr_invalid_template_arg) { | |||
5831 | Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); | |||
5832 | for (unsigned I = 0; I < Notes.size(); ++I) | |||
5833 | S.Diag(Notes[I].first, Notes[I].second); | |||
5834 | } else { | |||
5835 | S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) | |||
5836 | << CCE << From->getSourceRange(); | |||
5837 | for (unsigned I = 0; I < Notes.size(); ++I) | |||
5838 | S.Diag(Notes[I].first, Notes[I].second); | |||
5839 | } | |||
5840 | return ExprError(); | |||
5841 | } | |||
5842 | ||||
5843 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, | |||
5844 | APValue &Value, CCEKind CCE, | |||
5845 | NamedDecl *Dest) { | |||
5846 | return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, | |||
5847 | Dest); | |||
5848 | } | |||
5849 | ||||
5850 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, | |||
5851 | llvm::APSInt &Value, | |||
5852 | CCEKind CCE) { | |||
5853 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType( ) && "unexpected converted const type") ? void (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\"" , "clang/lib/Sema/SemaOverload.cpp", 5853, __extension__ __PRETTY_FUNCTION__ )); | |||
5854 | ||||
5855 | APValue V; | |||
5856 | auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, | |||
5857 | /*Dest=*/nullptr); | |||
5858 | if (!R.isInvalid() && !R.get()->isValueDependent()) | |||
5859 | Value = V.getInt(); | |||
5860 | return R; | |||
5861 | } | |||
5862 | ||||
5863 | ||||
5864 | /// dropPointerConversions - If the given standard conversion sequence | |||
5865 | /// involves any pointer conversions, remove them. This may change | |||
5866 | /// the result type of the conversion sequence. | |||
5867 | static void dropPointerConversion(StandardConversionSequence &SCS) { | |||
5868 | if (SCS.Second == ICK_Pointer_Conversion) { | |||
5869 | SCS.Second = ICK_Identity; | |||
5870 | SCS.Third = ICK_Identity; | |||
5871 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; | |||
5872 | } | |||
5873 | } | |||
5874 | ||||
5875 | /// TryContextuallyConvertToObjCPointer - Attempt to contextually | |||
5876 | /// convert the expression From to an Objective-C pointer type. | |||
5877 | static ImplicitConversionSequence | |||
5878 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { | |||
5879 | // Do an implicit conversion to 'id'. | |||
5880 | QualType Ty = S.Context.getObjCIdType(); | |||
5881 | ImplicitConversionSequence ICS | |||
5882 | = TryImplicitConversion(S, From, Ty, | |||
5883 | // FIXME: Are these flags correct? | |||
5884 | /*SuppressUserConversions=*/false, | |||
5885 | AllowedExplicit::Conversions, | |||
5886 | /*InOverloadResolution=*/false, | |||
5887 | /*CStyle=*/false, | |||
5888 | /*AllowObjCWritebackConversion=*/false, | |||
5889 | /*AllowObjCConversionOnExplicit=*/true); | |||
5890 | ||||
5891 | // Strip off any final conversions to 'id'. | |||
5892 | switch (ICS.getKind()) { | |||
5893 | case ImplicitConversionSequence::BadConversion: | |||
5894 | case ImplicitConversionSequence::AmbiguousConversion: | |||
5895 | case ImplicitConversionSequence::EllipsisConversion: | |||
5896 | break; | |||
5897 | ||||
5898 | case ImplicitConversionSequence::UserDefinedConversion: | |||
5899 | dropPointerConversion(ICS.UserDefined.After); | |||
5900 | break; | |||
5901 | ||||
5902 | case ImplicitConversionSequence::StandardConversion: | |||
5903 | dropPointerConversion(ICS.Standard); | |||
5904 | break; | |||
5905 | } | |||
5906 | ||||
5907 | return ICS; | |||
5908 | } | |||
5909 | ||||
5910 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual | |||
5911 | /// conversion of the expression From to an Objective-C pointer type. | |||
5912 | /// Returns a valid but null ExprResult if no conversion sequence exists. | |||
5913 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { | |||
5914 | if (checkPlaceholderForOverload(*this, From)) | |||
5915 | return ExprError(); | |||
5916 | ||||
5917 | QualType Ty = Context.getObjCIdType(); | |||
5918 | ImplicitConversionSequence ICS = | |||
5919 | TryContextuallyConvertToObjCPointer(*this, From); | |||
5920 | if (!ICS.isBad()) | |||
5921 | return PerformImplicitConversion(From, Ty, ICS, AA_Converting); | |||
5922 | return ExprResult(); | |||
5923 | } | |||
5924 | ||||
5925 | /// Determine whether the provided type is an integral type, or an enumeration | |||
5926 | /// type of a permitted flavor. | |||
5927 | bool Sema::ICEConvertDiagnoser::match(QualType T) { | |||
5928 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() | |||
5929 | : T->isIntegralOrUnscopedEnumerationType(); | |||
5930 | } | |||
5931 | ||||
5932 | static ExprResult | |||
5933 | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, | |||
5934 | Sema::ContextualImplicitConverter &Converter, | |||
5935 | QualType T, UnresolvedSetImpl &ViableConversions) { | |||
5936 | ||||
5937 | if (Converter.Suppress) | |||
5938 | return ExprError(); | |||
5939 | ||||
5940 | Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); | |||
5941 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { | |||
5942 | CXXConversionDecl *Conv = | |||
5943 | cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); | |||
5944 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); | |||
5945 | Converter.noteAmbiguous(SemaRef, Conv, ConvTy); | |||
5946 | } | |||
5947 | return From; | |||
5948 | } | |||
5949 | ||||
5950 | static bool | |||
5951 | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, | |||
5952 | Sema::ContextualImplicitConverter &Converter, | |||
5953 | QualType T, bool HadMultipleCandidates, | |||
5954 | UnresolvedSetImpl &ExplicitConversions) { | |||
5955 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { | |||
5956 | DeclAccessPair Found = ExplicitConversions[0]; | |||
5957 | CXXConversionDecl *Conversion = | |||
5958 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); | |||
5959 | ||||
5960 | // The user probably meant to invoke the given explicit | |||
5961 | // conversion; use it. | |||
5962 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); | |||
5963 | std::string TypeStr; | |||
5964 | ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); | |||
5965 | ||||
5966 | Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) | |||
5967 | << FixItHint::CreateInsertion(From->getBeginLoc(), | |||
5968 | "static_cast<" + TypeStr + ">(") | |||
5969 | << FixItHint::CreateInsertion( | |||
5970 | SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); | |||
5971 | Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); | |||
5972 | ||||
5973 | // If we aren't in a SFINAE context, build a call to the | |||
5974 | // explicit conversion function. | |||
5975 | if (SemaRef.isSFINAEContext()) | |||
5976 | return true; | |||
5977 | ||||
5978 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); | |||
5979 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, | |||
5980 | HadMultipleCandidates); | |||
5981 | if (Result.isInvalid()) | |||
5982 | return true; | |||
5983 | // Record usage of conversion in an implicit cast. | |||
5984 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), | |||
5985 | CK_UserDefinedConversion, Result.get(), | |||
5986 | nullptr, Result.get()->getValueKind(), | |||
5987 | SemaRef.CurFPFeatureOverrides()); | |||
5988 | } | |||
5989 | return false; | |||
5990 | } | |||
5991 | ||||
5992 | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, | |||
5993 | Sema::ContextualImplicitConverter &Converter, | |||
5994 | QualType T, bool HadMultipleCandidates, | |||
5995 | DeclAccessPair &Found) { | |||
5996 | CXXConversionDecl *Conversion = | |||
5997 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); | |||
5998 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); | |||
5999 | ||||
6000 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); | |||
6001 | if (!Converter.SuppressConversion) { | |||
6002 | if (SemaRef.isSFINAEContext()) | |||
6003 | return true; | |||
6004 | ||||
6005 | Converter.diagnoseConversion(SemaRef, Loc, T, ToType) | |||
6006 | << From->getSourceRange(); | |||
6007 | } | |||
6008 | ||||
6009 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, | |||
6010 | HadMultipleCandidates); | |||
6011 | if (Result.isInvalid()) | |||
6012 | return true; | |||
6013 | // Record usage of conversion in an implicit cast. | |||
6014 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), | |||
6015 | CK_UserDefinedConversion, Result.get(), | |||
6016 | nullptr, Result.get()->getValueKind(), | |||
6017 | SemaRef.CurFPFeatureOverrides()); | |||
6018 | return false; | |||
6019 | } | |||
6020 | ||||
6021 | static ExprResult finishContextualImplicitConversion( | |||
6022 | Sema &SemaRef, SourceLocation Loc, Expr *From, | |||
6023 | Sema::ContextualImplicitConverter &Converter) { | |||
6024 | if (!Converter.match(From->getType()) && !Converter.Suppress) | |||
6025 | Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) | |||
6026 | << From->getSourceRange(); | |||
6027 | ||||
6028 | return SemaRef.DefaultLvalueConversion(From); | |||
6029 | } | |||
6030 | ||||
6031 | static void | |||
6032 | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, | |||
6033 | UnresolvedSetImpl &ViableConversions, | |||
6034 | OverloadCandidateSet &CandidateSet) { | |||
6035 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { | |||
6036 | DeclAccessPair FoundDecl = ViableConversions[I]; | |||
6037 | NamedDecl *D = FoundDecl.getDecl(); | |||
6038 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
6039 | if (isa<UsingShadowDecl>(D)) | |||
6040 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
6041 | ||||
6042 | CXXConversionDecl *Conv; | |||
6043 | FunctionTemplateDecl *ConvTemplate; | |||
6044 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) | |||
6045 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
6046 | else | |||
6047 | Conv = cast<CXXConversionDecl>(D); | |||
6048 | ||||
6049 | if (ConvTemplate) | |||
6050 | SemaRef.AddTemplateConversionCandidate( | |||
6051 | ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, | |||
6052 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); | |||
6053 | else | |||
6054 | SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, | |||
6055 | ToType, CandidateSet, | |||
6056 | /*AllowObjCConversionOnExplicit=*/false, | |||
6057 | /*AllowExplicit*/ true); | |||
6058 | } | |||
6059 | } | |||
6060 | ||||
6061 | /// Attempt to convert the given expression to a type which is accepted | |||
6062 | /// by the given converter. | |||
6063 | /// | |||
6064 | /// This routine will attempt to convert an expression of class type to a | |||
6065 | /// type accepted by the specified converter. In C++11 and before, the class | |||
6066 | /// must have a single non-explicit conversion function converting to a matching | |||
6067 | /// type. In C++1y, there can be multiple such conversion functions, but only | |||
6068 | /// one target type. | |||
6069 | /// | |||
6070 | /// \param Loc The source location of the construct that requires the | |||
6071 | /// conversion. | |||
6072 | /// | |||
6073 | /// \param From The expression we're converting from. | |||
6074 | /// | |||
6075 | /// \param Converter Used to control and diagnose the conversion process. | |||
6076 | /// | |||
6077 | /// \returns The expression, converted to an integral or enumeration type if | |||
6078 | /// successful. | |||
6079 | ExprResult Sema::PerformContextualImplicitConversion( | |||
6080 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { | |||
6081 | // We can't perform any more checking for type-dependent expressions. | |||
6082 | if (From->isTypeDependent()) | |||
6083 | return From; | |||
6084 | ||||
6085 | // Process placeholders immediately. | |||
6086 | if (From->hasPlaceholderType()) { | |||
6087 | ExprResult result = CheckPlaceholderExpr(From); | |||
6088 | if (result.isInvalid()) | |||
6089 | return result; | |||
6090 | From = result.get(); | |||
6091 | } | |||
6092 | ||||
6093 | // If the expression already has a matching type, we're golden. | |||
6094 | QualType T = From->getType(); | |||
6095 | if (Converter.match(T)) | |||
6096 | return DefaultLvalueConversion(From); | |||
6097 | ||||
6098 | // FIXME: Check for missing '()' if T is a function type? | |||
6099 | ||||
6100 | // We can only perform contextual implicit conversions on objects of class | |||
6101 | // type. | |||
6102 | const RecordType *RecordTy = T->getAs<RecordType>(); | |||
6103 | if (!RecordTy || !getLangOpts().CPlusPlus) { | |||
6104 | if (!Converter.Suppress) | |||
6105 | Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); | |||
6106 | return From; | |||
6107 | } | |||
6108 | ||||
6109 | // We must have a complete class type. | |||
6110 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { | |||
6111 | ContextualImplicitConverter &Converter; | |||
6112 | Expr *From; | |||
6113 | ||||
6114 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) | |||
6115 | : Converter(Converter), From(From) {} | |||
6116 | ||||
6117 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
6118 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); | |||
6119 | } | |||
6120 | } IncompleteDiagnoser(Converter, From); | |||
6121 | ||||
6122 | if (Converter.Suppress ? !isCompleteType(Loc, T) | |||
6123 | : RequireCompleteType(Loc, T, IncompleteDiagnoser)) | |||
6124 | return From; | |||
6125 | ||||
6126 | // Look for a conversion to an integral or enumeration type. | |||
6127 | UnresolvedSet<4> | |||
6128 | ViableConversions; // These are *potentially* viable in C++1y. | |||
6129 | UnresolvedSet<4> ExplicitConversions; | |||
6130 | const auto &Conversions = | |||
6131 | cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); | |||
6132 | ||||
6133 | bool HadMultipleCandidates = | |||
6134 | (std::distance(Conversions.begin(), Conversions.end()) > 1); | |||
6135 | ||||
6136 | // To check that there is only one target type, in C++1y: | |||
6137 | QualType ToType; | |||
6138 | bool HasUniqueTargetType = true; | |||
6139 | ||||
6140 | // Collect explicit or viable (potentially in C++1y) conversions. | |||
6141 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
6142 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
6143 | CXXConversionDecl *Conversion; | |||
6144 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
6145 | if (ConvTemplate) { | |||
6146 | if (getLangOpts().CPlusPlus14) | |||
6147 | Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
6148 | else | |||
6149 | continue; // C++11 does not consider conversion operator templates(?). | |||
6150 | } else | |||
6151 | Conversion = cast<CXXConversionDecl>(D); | |||
6152 | ||||
6153 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6155, __extension__ __PRETTY_FUNCTION__ )) | |||
6154 | "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6155, __extension__ __PRETTY_FUNCTION__ )) | |||
6155 | "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14 ) && "Conversion operator templates are considered potentially " "viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "clang/lib/Sema/SemaOverload.cpp", 6155, __extension__ __PRETTY_FUNCTION__ )); | |||
6156 | ||||
6157 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); | |||
6158 | if (Converter.match(CurToType) || ConvTemplate) { | |||
6159 | ||||
6160 | if (Conversion->isExplicit()) { | |||
6161 | // FIXME: For C++1y, do we need this restriction? | |||
6162 | // cf. diagnoseNoViableConversion() | |||
6163 | if (!ConvTemplate) | |||
6164 | ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); | |||
6165 | } else { | |||
6166 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { | |||
6167 | if (ToType.isNull()) | |||
6168 | ToType = CurToType.getUnqualifiedType(); | |||
6169 | else if (HasUniqueTargetType && | |||
6170 | (CurToType.getUnqualifiedType() != ToType)) | |||
6171 | HasUniqueTargetType = false; | |||
6172 | } | |||
6173 | ViableConversions.addDecl(I.getDecl(), I.getAccess()); | |||
6174 | } | |||
6175 | } | |||
6176 | } | |||
6177 | ||||
6178 | if (getLangOpts().CPlusPlus14) { | |||
6179 | // C++1y [conv]p6: | |||
6180 | // ... An expression e of class type E appearing in such a context | |||
6181 | // is said to be contextually implicitly converted to a specified | |||
6182 | // type T and is well-formed if and only if e can be implicitly | |||
6183 | // converted to a type T that is determined as follows: E is searched | |||
6184 | // for conversion functions whose return type is cv T or reference to | |||
6185 | // cv T such that T is allowed by the context. There shall be | |||
6186 | // exactly one such T. | |||
6187 | ||||
6188 | // If no unique T is found: | |||
6189 | if (ToType.isNull()) { | |||
6190 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
6191 | HadMultipleCandidates, | |||
6192 | ExplicitConversions)) | |||
6193 | return ExprError(); | |||
6194 | return finishContextualImplicitConversion(*this, Loc, From, Converter); | |||
6195 | } | |||
6196 | ||||
6197 | // If more than one unique Ts are found: | |||
6198 | if (!HasUniqueTargetType) | |||
6199 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
6200 | ViableConversions); | |||
6201 | ||||
6202 | // If one unique T is found: | |||
6203 | // First, build a candidate set from the previously recorded | |||
6204 | // potentially viable conversions. | |||
6205 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
6206 | collectViableConversionCandidates(*this, From, ToType, ViableConversions, | |||
6207 | CandidateSet); | |||
6208 | ||||
6209 | // Then, perform overload resolution over the candidate set. | |||
6210 | OverloadCandidateSet::iterator Best; | |||
6211 | switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { | |||
6212 | case OR_Success: { | |||
6213 | // Apply this conversion. | |||
6214 | DeclAccessPair Found = | |||
6215 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); | |||
6216 | if (recordConversion(*this, Loc, From, Converter, T, | |||
6217 | HadMultipleCandidates, Found)) | |||
6218 | return ExprError(); | |||
6219 | break; | |||
6220 | } | |||
6221 | case OR_Ambiguous: | |||
6222 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
6223 | ViableConversions); | |||
6224 | case OR_No_Viable_Function: | |||
6225 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
6226 | HadMultipleCandidates, | |||
6227 | ExplicitConversions)) | |||
6228 | return ExprError(); | |||
6229 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
6230 | case OR_Deleted: | |||
6231 | // We'll complain below about a non-integral condition type. | |||
6232 | break; | |||
6233 | } | |||
6234 | } else { | |||
6235 | switch (ViableConversions.size()) { | |||
6236 | case 0: { | |||
6237 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
6238 | HadMultipleCandidates, | |||
6239 | ExplicitConversions)) | |||
6240 | return ExprError(); | |||
6241 | ||||
6242 | // We'll complain below about a non-integral condition type. | |||
6243 | break; | |||
6244 | } | |||
6245 | case 1: { | |||
6246 | // Apply this conversion. | |||
6247 | DeclAccessPair Found = ViableConversions[0]; | |||
6248 | if (recordConversion(*this, Loc, From, Converter, T, | |||
6249 | HadMultipleCandidates, Found)) | |||
6250 | return ExprError(); | |||
6251 | break; | |||
6252 | } | |||
6253 | default: | |||
6254 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
6255 | ViableConversions); | |||
6256 | } | |||
6257 | } | |||
6258 | ||||
6259 | return finishContextualImplicitConversion(*this, Loc, From, Converter); | |||
6260 | } | |||
6261 | ||||
6262 | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is | |||
6263 | /// an acceptable non-member overloaded operator for a call whose | |||
6264 | /// arguments have types T1 (and, if non-empty, T2). This routine | |||
6265 | /// implements the check in C++ [over.match.oper]p3b2 concerning | |||
6266 | /// enumeration types. | |||
6267 | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, | |||
6268 | FunctionDecl *Fn, | |||
6269 | ArrayRef<Expr *> Args) { | |||
6270 | QualType T1 = Args[0]->getType(); | |||
6271 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); | |||
6272 | ||||
6273 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) | |||
6274 | return true; | |||
6275 | ||||
6276 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) | |||
6277 | return true; | |||
6278 | ||||
6279 | const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); | |||
6280 | if (Proto->getNumParams() < 1) | |||
6281 | return false; | |||
6282 | ||||
6283 | if (T1->isEnumeralType()) { | |||
6284 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); | |||
6285 | if (Context.hasSameUnqualifiedType(T1, ArgType)) | |||
6286 | return true; | |||
6287 | } | |||
6288 | ||||
6289 | if (Proto->getNumParams() < 2) | |||
6290 | return false; | |||
6291 | ||||
6292 | if (!T2.isNull() && T2->isEnumeralType()) { | |||
6293 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); | |||
6294 | if (Context.hasSameUnqualifiedType(T2, ArgType)) | |||
6295 | return true; | |||
6296 | } | |||
6297 | ||||
6298 | return false; | |||
6299 | } | |||
6300 | ||||
6301 | /// AddOverloadCandidate - Adds the given function to the set of | |||
6302 | /// candidate functions, using the given function call arguments. If | |||
6303 | /// @p SuppressUserConversions, then don't allow user-defined | |||
6304 | /// conversions via constructors or conversion operators. | |||
6305 | /// | |||
6306 | /// \param PartialOverloading true if we are performing "partial" overloading | |||
6307 | /// based on an incomplete set of function arguments. This feature is used by | |||
6308 | /// code completion. | |||
6309 | void Sema::AddOverloadCandidate( | |||
6310 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, | |||
6311 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, | |||
6312 | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, | |||
6313 | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, | |||
6314 | OverloadCandidateParamOrder PO) { | |||
6315 | const FunctionProtoType *Proto | |||
6316 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); | |||
6317 | assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded" ) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\"" , "clang/lib/Sema/SemaOverload.cpp", 6317, __extension__ __PRETTY_FUNCTION__ )); | |||
6318 | assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate () && "Use AddTemplateOverloadCandidate for function templates" ) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "clang/lib/Sema/SemaOverload.cpp", 6319, __extension__ __PRETTY_FUNCTION__ )) | |||
6319 | "Use AddTemplateOverloadCandidate for function templates")(static_cast <bool> (!Function->getDescribedFunctionTemplate () && "Use AddTemplateOverloadCandidate for function templates" ) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "clang/lib/Sema/SemaOverload.cpp", 6319, __extension__ __PRETTY_FUNCTION__ )); | |||
6320 | ||||
6321 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { | |||
6322 | if (!isa<CXXConstructorDecl>(Method)) { | |||
6323 | // If we get here, it's because we're calling a member function | |||
6324 | // that is named without a member access expression (e.g., | |||
6325 | // "this->f") that was either written explicitly or created | |||
6326 | // implicitly. This can happen with a qualified call to a member | |||
6327 | // function, e.g., X::f(). We use an empty type for the implied | |||
6328 | // object argument (C++ [over.call.func]p3), and the acting context | |||
6329 | // is irrelevant. | |||
6330 | AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), | |||
6331 | Expr::Classification::makeSimpleLValue(), Args, | |||
6332 | CandidateSet, SuppressUserConversions, | |||
6333 | PartialOverloading, EarlyConversions, PO); | |||
6334 | return; | |||
6335 | } | |||
6336 | // We treat a constructor like a non-member function, since its object | |||
6337 | // argument doesn't participate in overload resolution. | |||
6338 | } | |||
6339 | ||||
6340 | if (!CandidateSet.isNewCandidate(Function, PO)) | |||
6341 | return; | |||
6342 | ||||
6343 | // C++11 [class.copy]p11: [DR1402] | |||
6344 | // A defaulted move constructor that is defined as deleted is ignored by | |||
6345 | // overload resolution. | |||
6346 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); | |||
6347 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && | |||
6348 | Constructor->isMoveConstructor()) | |||
6349 | return; | |||
6350 | ||||
6351 | // Overload resolution is always an unevaluated context. | |||
6352 | EnterExpressionEvaluationContext Unevaluated( | |||
6353 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6354 | ||||
6355 | // C++ [over.match.oper]p3: | |||
6356 | // if no operand has a class type, only those non-member functions in the | |||
6357 | // lookup set that have a first parameter of type T1 or "reference to | |||
6358 | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there | |||
6359 | // is a right operand) a second parameter of type T2 or "reference to | |||
6360 | // (possibly cv-qualified) T2", when T2 is an enumeration type, are | |||
6361 | // candidate functions. | |||
6362 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && | |||
6363 | !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) | |||
6364 | return; | |||
6365 | ||||
6366 | // Add this candidate | |||
6367 | OverloadCandidate &Candidate = | |||
6368 | CandidateSet.addCandidate(Args.size(), EarlyConversions); | |||
6369 | Candidate.FoundDecl = FoundDecl; | |||
6370 | Candidate.Function = Function; | |||
6371 | Candidate.Viable = true; | |||
6372 | Candidate.RewriteKind = | |||
6373 | CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); | |||
6374 | Candidate.IsSurrogate = false; | |||
6375 | Candidate.IsADLCandidate = IsADLCandidate; | |||
6376 | Candidate.IgnoreObjectArgument = false; | |||
6377 | Candidate.ExplicitCallArguments = Args.size(); | |||
6378 | ||||
6379 | // Explicit functions are not actually candidates at all if we're not | |||
6380 | // allowing them in this context, but keep them around so we can point | |||
6381 | // to them in diagnostics. | |||
6382 | if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { | |||
6383 | Candidate.Viable = false; | |||
6384 | Candidate.FailureKind = ovl_fail_explicit; | |||
6385 | return; | |||
6386 | } | |||
6387 | ||||
6388 | if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && | |||
6389 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
6390 | Candidate.Viable = false; | |||
6391 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
6392 | return; | |||
6393 | } | |||
6394 | ||||
6395 | if (Constructor) { | |||
6396 | // C++ [class.copy]p3: | |||
6397 | // A member function template is never instantiated to perform the copy | |||
6398 | // of a class object to an object of its class type. | |||
6399 | QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); | |||
6400 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && | |||
6401 | (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || | |||
6402 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), | |||
6403 | ClassType))) { | |||
6404 | Candidate.Viable = false; | |||
6405 | Candidate.FailureKind = ovl_fail_illegal_constructor; | |||
6406 | return; | |||
6407 | } | |||
6408 | ||||
6409 | // C++ [over.match.funcs]p8: (proposed DR resolution) | |||
6410 | // A constructor inherited from class type C that has a first parameter | |||
6411 | // of type "reference to P" (including such a constructor instantiated | |||
6412 | // from a template) is excluded from the set of candidate functions when | |||
6413 | // constructing an object of type cv D if the argument list has exactly | |||
6414 | // one argument and D is reference-related to P and P is reference-related | |||
6415 | // to C. | |||
6416 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); | |||
6417 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && | |||
6418 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { | |||
6419 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); | |||
6420 | QualType C = Context.getRecordType(Constructor->getParent()); | |||
6421 | QualType D = Context.getRecordType(Shadow->getParent()); | |||
6422 | SourceLocation Loc = Args.front()->getExprLoc(); | |||
6423 | if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && | |||
6424 | (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { | |||
6425 | Candidate.Viable = false; | |||
6426 | Candidate.FailureKind = ovl_fail_inhctor_slice; | |||
6427 | return; | |||
6428 | } | |||
6429 | } | |||
6430 | ||||
6431 | // Check that the constructor is capable of constructing an object in the | |||
6432 | // destination address space. | |||
6433 | if (!Qualifiers::isAddressSpaceSupersetOf( | |||
6434 | Constructor->getMethodQualifiers().getAddressSpace(), | |||
6435 | CandidateSet.getDestAS())) { | |||
6436 | Candidate.Viable = false; | |||
6437 | Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; | |||
6438 | } | |||
6439 | } | |||
6440 | ||||
6441 | unsigned NumParams = Proto->getNumParams(); | |||
6442 | ||||
6443 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
6444 | // parameters is viable only if it has an ellipsis in its parameter | |||
6445 | // list (8.3.5). | |||
6446 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && | |||
6447 | !Proto->isVariadic() && | |||
6448 | shouldEnforceArgLimit(PartialOverloading, Function)) { | |||
6449 | Candidate.Viable = false; | |||
6450 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
6451 | return; | |||
6452 | } | |||
6453 | ||||
6454 | // (C++ 13.3.2p2): A candidate function having more than m parameters | |||
6455 | // is viable only if the (m+1)st parameter has a default argument | |||
6456 | // (8.3.6). For the purposes of overload resolution, the | |||
6457 | // parameter list is truncated on the right, so that there are | |||
6458 | // exactly m parameters. | |||
6459 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); | |||
6460 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { | |||
6461 | // Not enough arguments. | |||
6462 | Candidate.Viable = false; | |||
6463 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
6464 | return; | |||
6465 | } | |||
6466 | ||||
6467 | // (CUDA B.1): Check for invalid calls between targets. | |||
6468 | if (getLangOpts().CUDA) | |||
6469 | if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) | |||
6470 | // Skip the check for callers that are implicit members, because in this | |||
6471 | // case we may not yet know what the member's target is; the target is | |||
6472 | // inferred for the member automatically, based on the bases and fields of | |||
6473 | // the class. | |||
6474 | if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { | |||
6475 | Candidate.Viable = false; | |||
6476 | Candidate.FailureKind = ovl_fail_bad_target; | |||
6477 | return; | |||
6478 | } | |||
6479 | ||||
6480 | if (Function->getTrailingRequiresClause()) { | |||
6481 | ConstraintSatisfaction Satisfaction; | |||
6482 | if (CheckFunctionConstraints(Function, Satisfaction) || | |||
6483 | !Satisfaction.IsSatisfied) { | |||
6484 | Candidate.Viable = false; | |||
6485 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; | |||
6486 | return; | |||
6487 | } | |||
6488 | } | |||
6489 | ||||
6490 | // Determine the implicit conversion sequences for each of the | |||
6491 | // arguments. | |||
6492 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { | |||
6493 | unsigned ConvIdx = | |||
6494 | PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; | |||
6495 | if (Candidate.Conversions[ConvIdx].isInitialized()) { | |||
6496 | // We already formed a conversion sequence for this parameter during | |||
6497 | // template argument deduction. | |||
6498 | } else if (ArgIdx < NumParams) { | |||
6499 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
6500 | // exist for each argument an implicit conversion sequence | |||
6501 | // (13.3.3.1) that converts that argument to the corresponding | |||
6502 | // parameter of F. | |||
6503 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
6504 | Candidate.Conversions[ConvIdx] = TryCopyInitialization( | |||
6505 | *this, Args[ArgIdx], ParamType, SuppressUserConversions, | |||
6506 | /*InOverloadResolution=*/true, | |||
6507 | /*AllowObjCWritebackConversion=*/ | |||
6508 | getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); | |||
6509 | if (Candidate.Conversions[ConvIdx].isBad()) { | |||
6510 | Candidate.Viable = false; | |||
6511 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6512 | return; | |||
6513 | } | |||
6514 | } else { | |||
6515 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
6516 | // argument for which there is no corresponding parameter is | |||
6517 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). | |||
6518 | Candidate.Conversions[ConvIdx].setEllipsis(); | |||
6519 | } | |||
6520 | } | |||
6521 | ||||
6522 | if (EnableIfAttr *FailedAttr = | |||
6523 | CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { | |||
6524 | Candidate.Viable = false; | |||
6525 | Candidate.FailureKind = ovl_fail_enable_if; | |||
6526 | Candidate.DeductionFailure.Data = FailedAttr; | |||
6527 | return; | |||
6528 | } | |||
6529 | } | |||
6530 | ||||
6531 | ObjCMethodDecl * | |||
6532 | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, | |||
6533 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { | |||
6534 | if (Methods.size() <= 1) | |||
6535 | return nullptr; | |||
6536 | ||||
6537 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { | |||
6538 | bool Match = true; | |||
6539 | ObjCMethodDecl *Method = Methods[b]; | |||
6540 | unsigned NumNamedArgs = Sel.getNumArgs(); | |||
6541 | // Method might have more arguments than selector indicates. This is due | |||
6542 | // to addition of c-style arguments in method. | |||
6543 | if (Method->param_size() > NumNamedArgs) | |||
6544 | NumNamedArgs = Method->param_size(); | |||
6545 | if (Args.size() < NumNamedArgs) | |||
6546 | continue; | |||
6547 | ||||
6548 | for (unsigned i = 0; i < NumNamedArgs; i++) { | |||
6549 | // We can't do any type-checking on a type-dependent argument. | |||
6550 | if (Args[i]->isTypeDependent()) { | |||
6551 | Match = false; | |||
6552 | break; | |||
6553 | } | |||
6554 | ||||
6555 | ParmVarDecl *param = Method->parameters()[i]; | |||
6556 | Expr *argExpr = Args[i]; | |||
6557 | assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression" ) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\"" , "clang/lib/Sema/SemaOverload.cpp", 6557, __extension__ __PRETTY_FUNCTION__ )); | |||
6558 | ||||
6559 | // Strip the unbridged-cast placeholder expression off unless it's | |||
6560 | // a consumed argument. | |||
6561 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && | |||
6562 | !param->hasAttr<CFConsumedAttr>()) | |||
6563 | argExpr = stripARCUnbridgedCast(argExpr); | |||
6564 | ||||
6565 | // If the parameter is __unknown_anytype, move on to the next method. | |||
6566 | if (param->getType() == Context.UnknownAnyTy) { | |||
6567 | Match = false; | |||
6568 | break; | |||
6569 | } | |||
6570 | ||||
6571 | ImplicitConversionSequence ConversionState | |||
6572 | = TryCopyInitialization(*this, argExpr, param->getType(), | |||
6573 | /*SuppressUserConversions*/false, | |||
6574 | /*InOverloadResolution=*/true, | |||
6575 | /*AllowObjCWritebackConversion=*/ | |||
6576 | getLangOpts().ObjCAutoRefCount, | |||
6577 | /*AllowExplicit*/false); | |||
6578 | // This function looks for a reasonably-exact match, so we consider | |||
6579 | // incompatible pointer conversions to be a failure here. | |||
6580 | if (ConversionState.isBad() || | |||
6581 | (ConversionState.isStandard() && | |||
6582 | ConversionState.Standard.Second == | |||
6583 | ICK_Incompatible_Pointer_Conversion)) { | |||
6584 | Match = false; | |||
6585 | break; | |||
6586 | } | |||
6587 | } | |||
6588 | // Promote additional arguments to variadic methods. | |||
6589 | if (Match && Method->isVariadic()) { | |||
6590 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { | |||
6591 | if (Args[i]->isTypeDependent()) { | |||
6592 | Match = false; | |||
6593 | break; | |||
6594 | } | |||
6595 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, | |||
6596 | nullptr); | |||
6597 | if (Arg.isInvalid()) { | |||
6598 | Match = false; | |||
6599 | break; | |||
6600 | } | |||
6601 | } | |||
6602 | } else { | |||
6603 | // Check for extra arguments to non-variadic methods. | |||
6604 | if (Args.size() != NumNamedArgs) | |||
6605 | Match = false; | |||
6606 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { | |||
6607 | // Special case when selectors have no argument. In this case, select | |||
6608 | // one with the most general result type of 'id'. | |||
6609 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { | |||
6610 | QualType ReturnT = Methods[b]->getReturnType(); | |||
6611 | if (ReturnT->isObjCIdType()) | |||
6612 | return Methods[b]; | |||
6613 | } | |||
6614 | } | |||
6615 | } | |||
6616 | ||||
6617 | if (Match) | |||
6618 | return Method; | |||
6619 | } | |||
6620 | return nullptr; | |||
6621 | } | |||
6622 | ||||
6623 | static bool convertArgsForAvailabilityChecks( | |||
6624 | Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, | |||
6625 | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, | |||
6626 | Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { | |||
6627 | if (ThisArg) { | |||
6628 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); | |||
6629 | assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Shouldn't have `this` for ctors!") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "clang/lib/Sema/SemaOverload.cpp", 6630, __extension__ __PRETTY_FUNCTION__ )) | |||
6630 | "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Shouldn't have `this` for ctors!") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "clang/lib/Sema/SemaOverload.cpp", 6630, __extension__ __PRETTY_FUNCTION__ )); | |||
6631 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!" ) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\"" , "clang/lib/Sema/SemaOverload.cpp", 6631, __extension__ __PRETTY_FUNCTION__ )); | |||
6632 | ExprResult R = S.PerformObjectArgumentInitialization( | |||
6633 | ThisArg, /*Qualifier=*/nullptr, Method, Method); | |||
6634 | if (R.isInvalid()) | |||
6635 | return false; | |||
6636 | ConvertedThis = R.get(); | |||
6637 | } else { | |||
6638 | if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { | |||
6639 | (void)MD; | |||
6640 | assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )) | |||
6641 | isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )) | |||
6642 | "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic () || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods" ) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "clang/lib/Sema/SemaOverload.cpp", 6642, __extension__ __PRETTY_FUNCTION__ )); | |||
6643 | } | |||
6644 | ConvertedThis = nullptr; | |||
6645 | } | |||
6646 | ||||
6647 | // Ignore any variadic arguments. Converting them is pointless, since the | |||
6648 | // user can't refer to them in the function condition. | |||
6649 | unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); | |||
6650 | ||||
6651 | // Convert the arguments. | |||
6652 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { | |||
6653 | ExprResult R; | |||
6654 | R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
6655 | S.Context, Function->getParamDecl(I)), | |||
6656 | SourceLocation(), Args[I]); | |||
6657 | ||||
6658 | if (R.isInvalid()) | |||
6659 | return false; | |||
6660 | ||||
6661 | ConvertedArgs.push_back(R.get()); | |||
6662 | } | |||
6663 | ||||
6664 | if (Trap.hasErrorOccurred()) | |||
6665 | return false; | |||
6666 | ||||
6667 | // Push default arguments if needed. | |||
6668 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { | |||
6669 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { | |||
6670 | ParmVarDecl *P = Function->getParamDecl(i); | |||
6671 | if (!P->hasDefaultArg()) | |||
6672 | return false; | |||
6673 | ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); | |||
6674 | if (R.isInvalid()) | |||
6675 | return false; | |||
6676 | ConvertedArgs.push_back(R.get()); | |||
6677 | } | |||
6678 | ||||
6679 | if (Trap.hasErrorOccurred()) | |||
6680 | return false; | |||
6681 | } | |||
6682 | return true; | |||
6683 | } | |||
6684 | ||||
6685 | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, | |||
6686 | SourceLocation CallLoc, | |||
6687 | ArrayRef<Expr *> Args, | |||
6688 | bool MissingImplicitThis) { | |||
6689 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); | |||
6690 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) | |||
6691 | return nullptr; | |||
6692 | ||||
6693 | SFINAETrap Trap(*this); | |||
6694 | SmallVector<Expr *, 16> ConvertedArgs; | |||
6695 | // FIXME: We should look into making enable_if late-parsed. | |||
6696 | Expr *DiscardedThis; | |||
6697 | if (!convertArgsForAvailabilityChecks( | |||
6698 | *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, | |||
6699 | /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) | |||
6700 | return *EnableIfAttrs.begin(); | |||
6701 | ||||
6702 | for (auto *EIA : EnableIfAttrs) { | |||
6703 | APValue Result; | |||
6704 | // FIXME: This doesn't consider value-dependent cases, because doing so is | |||
6705 | // very difficult. Ideally, we should handle them more gracefully. | |||
6706 | if (EIA->getCond()->isValueDependent() || | |||
6707 | !EIA->getCond()->EvaluateWithSubstitution( | |||
6708 | Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) | |||
6709 | return EIA; | |||
6710 | ||||
6711 | if (!Result.isInt() || !Result.getInt().getBoolValue()) | |||
6712 | return EIA; | |||
6713 | } | |||
6714 | return nullptr; | |||
6715 | } | |||
6716 | ||||
6717 | template <typename CheckFn> | |||
6718 | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, | |||
6719 | bool ArgDependent, SourceLocation Loc, | |||
6720 | CheckFn &&IsSuccessful) { | |||
6721 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; | |||
6722 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { | |||
6723 | if (ArgDependent == DIA->getArgDependent()) | |||
6724 | Attrs.push_back(DIA); | |||
6725 | } | |||
6726 | ||||
6727 | // Common case: No diagnose_if attributes, so we can quit early. | |||
6728 | if (Attrs.empty()) | |||
6729 | return false; | |||
6730 | ||||
6731 | auto WarningBegin = std::stable_partition( | |||
6732 | Attrs.begin(), Attrs.end(), | |||
6733 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); | |||
6734 | ||||
6735 | // Note that diagnose_if attributes are late-parsed, so they appear in the | |||
6736 | // correct order (unlike enable_if attributes). | |||
6737 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), | |||
6738 | IsSuccessful); | |||
6739 | if (ErrAttr != WarningBegin) { | |||
6740 | const DiagnoseIfAttr *DIA = *ErrAttr; | |||
6741 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); | |||
6742 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | |||
6743 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | |||
6744 | return true; | |||
6745 | } | |||
6746 | ||||
6747 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) | |||
6748 | if (IsSuccessful(DIA)) { | |||
6749 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); | |||
6750 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | |||
6751 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | |||
6752 | } | |||
6753 | ||||
6754 | return false; | |||
6755 | } | |||
6756 | ||||
6757 | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, | |||
6758 | const Expr *ThisArg, | |||
6759 | ArrayRef<const Expr *> Args, | |||
6760 | SourceLocation Loc) { | |||
6761 | return diagnoseDiagnoseIfAttrsWith( | |||
6762 | *this, Function, /*ArgDependent=*/true, Loc, | |||
6763 | [&](const DiagnoseIfAttr *DIA) { | |||
6764 | APValue Result; | |||
6765 | // It's sane to use the same Args for any redecl of this function, since | |||
6766 | // EvaluateWithSubstitution only cares about the position of each | |||
6767 | // argument in the arg list, not the ParmVarDecl* it maps to. | |||
6768 | if (!DIA->getCond()->EvaluateWithSubstitution( | |||
6769 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) | |||
6770 | return false; | |||
6771 | return Result.isInt() && Result.getInt().getBoolValue(); | |||
6772 | }); | |||
6773 | } | |||
6774 | ||||
6775 | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, | |||
6776 | SourceLocation Loc) { | |||
6777 | return diagnoseDiagnoseIfAttrsWith( | |||
6778 | *this, ND, /*ArgDependent=*/false, Loc, | |||
6779 | [&](const DiagnoseIfAttr *DIA) { | |||
6780 | bool Result; | |||
6781 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && | |||
6782 | Result; | |||
6783 | }); | |||
6784 | } | |||
6785 | ||||
6786 | /// Add all of the function declarations in the given function set to | |||
6787 | /// the overload candidate set. | |||
6788 | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, | |||
6789 | ArrayRef<Expr *> Args, | |||
6790 | OverloadCandidateSet &CandidateSet, | |||
6791 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
6792 | bool SuppressUserConversions, | |||
6793 | bool PartialOverloading, | |||
6794 | bool FirstArgumentIsBase) { | |||
6795 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { | |||
6796 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); | |||
6797 | ArrayRef<Expr *> FunctionArgs = Args; | |||
6798 | ||||
6799 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); | |||
6800 | FunctionDecl *FD = | |||
6801 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); | |||
6802 | ||||
6803 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { | |||
6804 | QualType ObjectType; | |||
6805 | Expr::Classification ObjectClassification; | |||
6806 | if (Args.size() > 0) { | |||
6807 | if (Expr *E = Args[0]) { | |||
6808 | // Use the explicit base to restrict the lookup: | |||
6809 | ObjectType = E->getType(); | |||
6810 | // Pointers in the object arguments are implicitly dereferenced, so we | |||
6811 | // always classify them as l-values. | |||
6812 | if (!ObjectType.isNull() && ObjectType->isPointerType()) | |||
6813 | ObjectClassification = Expr::Classification::makeSimpleLValue(); | |||
6814 | else | |||
6815 | ObjectClassification = E->Classify(Context); | |||
6816 | } // .. else there is an implicit base. | |||
6817 | FunctionArgs = Args.slice(1); | |||
6818 | } | |||
6819 | if (FunTmpl) { | |||
6820 | AddMethodTemplateCandidate( | |||
6821 | FunTmpl, F.getPair(), | |||
6822 | cast<CXXRecordDecl>(FunTmpl->getDeclContext()), | |||
6823 | ExplicitTemplateArgs, ObjectType, ObjectClassification, | |||
6824 | FunctionArgs, CandidateSet, SuppressUserConversions, | |||
6825 | PartialOverloading); | |||
6826 | } else { | |||
6827 | AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), | |||
6828 | cast<CXXMethodDecl>(FD)->getParent(), ObjectType, | |||
6829 | ObjectClassification, FunctionArgs, CandidateSet, | |||
6830 | SuppressUserConversions, PartialOverloading); | |||
6831 | } | |||
6832 | } else { | |||
6833 | // This branch handles both standalone functions and static methods. | |||
6834 | ||||
6835 | // Slice the first argument (which is the base) when we access | |||
6836 | // static method as non-static. | |||
6837 | if (Args.size() > 0 && | |||
6838 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && | |||
6839 | !isa<CXXConstructorDecl>(FD)))) { | |||
6840 | assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)-> isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()" , "clang/lib/Sema/SemaOverload.cpp", 6840, __extension__ __PRETTY_FUNCTION__ )); | |||
6841 | FunctionArgs = Args.slice(1); | |||
6842 | } | |||
6843 | if (FunTmpl) { | |||
6844 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), | |||
6845 | ExplicitTemplateArgs, FunctionArgs, | |||
6846 | CandidateSet, SuppressUserConversions, | |||
6847 | PartialOverloading); | |||
6848 | } else { | |||
6849 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, | |||
6850 | SuppressUserConversions, PartialOverloading); | |||
6851 | } | |||
6852 | } | |||
6853 | } | |||
6854 | } | |||
6855 | ||||
6856 | /// AddMethodCandidate - Adds a named decl (which is some kind of | |||
6857 | /// method) as a method candidate to the given overload set. | |||
6858 | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, | |||
6859 | Expr::Classification ObjectClassification, | |||
6860 | ArrayRef<Expr *> Args, | |||
6861 | OverloadCandidateSet &CandidateSet, | |||
6862 | bool SuppressUserConversions, | |||
6863 | OverloadCandidateParamOrder PO) { | |||
6864 | NamedDecl *Decl = FoundDecl.getDecl(); | |||
6865 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); | |||
6866 | ||||
6867 | if (isa<UsingShadowDecl>(Decl)) | |||
6868 | Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); | |||
6869 | ||||
6870 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { | |||
6871 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl ()) && "Expected a member function template") ? void ( 0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "clang/lib/Sema/SemaOverload.cpp", 6872, __extension__ __PRETTY_FUNCTION__ )) | |||
6872 | "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl ()) && "Expected a member function template") ? void ( 0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "clang/lib/Sema/SemaOverload.cpp", 6872, __extension__ __PRETTY_FUNCTION__ )); | |||
6873 | AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, | |||
6874 | /*ExplicitArgs*/ nullptr, ObjectType, | |||
6875 | ObjectClassification, Args, CandidateSet, | |||
6876 | SuppressUserConversions, false, PO); | |||
6877 | } else { | |||
6878 | AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, | |||
6879 | ObjectType, ObjectClassification, Args, CandidateSet, | |||
6880 | SuppressUserConversions, false, None, PO); | |||
6881 | } | |||
6882 | } | |||
6883 | ||||
6884 | /// AddMethodCandidate - Adds the given C++ member function to the set | |||
6885 | /// of candidate functions, using the given function call arguments | |||
6886 | /// and the object argument (@c Object). For example, in a call | |||
6887 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain | |||
6888 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't | |||
6889 | /// allow user-defined conversions via constructors or conversion | |||
6890 | /// operators. | |||
6891 | void | |||
6892 | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, | |||
6893 | CXXRecordDecl *ActingContext, QualType ObjectType, | |||
6894 | Expr::Classification ObjectClassification, | |||
6895 | ArrayRef<Expr *> Args, | |||
6896 | OverloadCandidateSet &CandidateSet, | |||
6897 | bool SuppressUserConversions, | |||
6898 | bool PartialOverloading, | |||
6899 | ConversionSequenceList EarlyConversions, | |||
6900 | OverloadCandidateParamOrder PO) { | |||
6901 | const FunctionProtoType *Proto | |||
6902 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); | |||
6903 | assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded" ) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\"" , "clang/lib/Sema/SemaOverload.cpp", 6903, __extension__ __PRETTY_FUNCTION__ )); | |||
6904 | assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Use AddOverloadCandidate for constructors") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "clang/lib/Sema/SemaOverload.cpp", 6905, __extension__ __PRETTY_FUNCTION__ )) | |||
6905 | "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method ) && "Use AddOverloadCandidate for constructors") ? void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "clang/lib/Sema/SemaOverload.cpp", 6905, __extension__ __PRETTY_FUNCTION__ )); | |||
6906 | ||||
6907 | if (!CandidateSet.isNewCandidate(Method, PO)) | |||
6908 | return; | |||
6909 | ||||
6910 | // C++11 [class.copy]p23: [DR1402] | |||
6911 | // A defaulted move assignment operator that is defined as deleted is | |||
6912 | // ignored by overload resolution. | |||
6913 | if (Method->isDefaulted() && Method->isDeleted() && | |||
6914 | Method->isMoveAssignmentOperator()) | |||
6915 | return; | |||
6916 | ||||
6917 | // Overload resolution is always an unevaluated context. | |||
6918 | EnterExpressionEvaluationContext Unevaluated( | |||
6919 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6920 | ||||
6921 | // Add this candidate | |||
6922 | OverloadCandidate &Candidate = | |||
6923 | CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); | |||
6924 | Candidate.FoundDecl = FoundDecl; | |||
6925 | Candidate.Function = Method; | |||
6926 | Candidate.RewriteKind = | |||
6927 | CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); | |||
6928 | Candidate.IsSurrogate = false; | |||
6929 | Candidate.IgnoreObjectArgument = false; | |||
6930 | Candidate.ExplicitCallArguments = Args.size(); | |||
6931 | ||||
6932 | unsigned NumParams = Proto->getNumParams(); | |||
6933 | ||||
6934 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
6935 | // parameters is viable only if it has an ellipsis in its parameter | |||
6936 | // list (8.3.5). | |||
6937 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && | |||
6938 | !Proto->isVariadic() && | |||
6939 | shouldEnforceArgLimit(PartialOverloading, Method)) { | |||
6940 | Candidate.Viable = false; | |||
6941 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
6942 | return; | |||
6943 | } | |||
6944 | ||||
6945 | // (C++ 13.3.2p2): A candidate function having more than m parameters | |||
6946 | // is viable only if the (m+1)st parameter has a default argument | |||
6947 | // (8.3.6). For the purposes of overload resolution, the | |||
6948 | // parameter list is truncated on the right, so that there are | |||
6949 | // exactly m parameters. | |||
6950 | unsigned MinRequiredArgs = Method->getMinRequiredArguments(); | |||
6951 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { | |||
6952 | // Not enough arguments. | |||
6953 | Candidate.Viable = false; | |||
6954 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
6955 | return; | |||
6956 | } | |||
6957 | ||||
6958 | Candidate.Viable = true; | |||
6959 | ||||
6960 | if (Method->isStatic() || ObjectType.isNull()) | |||
6961 | // The implicit object argument is ignored. | |||
6962 | Candidate.IgnoreObjectArgument = true; | |||
6963 | else { | |||
6964 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; | |||
6965 | // Determine the implicit conversion sequence for the object | |||
6966 | // parameter. | |||
6967 | Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( | |||
6968 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, | |||
6969 | Method, ActingContext); | |||
6970 | if (Candidate.Conversions[ConvIdx].isBad()) { | |||
6971 | Candidate.Viable = false; | |||
6972 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6973 | return; | |||
6974 | } | |||
6975 | } | |||
6976 | ||||
6977 | // (CUDA B.1): Check for invalid calls between targets. | |||
6978 | if (getLangOpts().CUDA) | |||
6979 | if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) | |||
6980 | if (!IsAllowedCUDACall(Caller, Method)) { | |||
6981 | Candidate.Viable = false; | |||
6982 | Candidate.FailureKind = ovl_fail_bad_target; | |||
6983 | return; | |||
6984 | } | |||
6985 | ||||
6986 | if (Method->getTrailingRequiresClause()) { | |||
6987 | ConstraintSatisfaction Satisfaction; | |||
6988 | if (CheckFunctionConstraints(Method, Satisfaction) || | |||
6989 | !Satisfaction.IsSatisfied) { | |||
6990 | Candidate.Viable = false; | |||
6991 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; | |||
6992 | return; | |||
6993 | } | |||
6994 | } | |||
6995 | ||||
6996 | // Determine the implicit conversion sequences for each of the | |||
6997 | // arguments. | |||
6998 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { | |||
6999 | unsigned ConvIdx = | |||
7000 | PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); | |||
7001 | if (Candidate.Conversions[ConvIdx].isInitialized()) { | |||
7002 | // We already formed a conversion sequence for this parameter during | |||
7003 | // template argument deduction. | |||
7004 | } else if (ArgIdx < NumParams) { | |||
7005 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
7006 | // exist for each argument an implicit conversion sequence | |||
7007 | // (13.3.3.1) that converts that argument to the corresponding | |||
7008 | // parameter of F. | |||
7009 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
7010 | Candidate.Conversions[ConvIdx] | |||
7011 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, | |||
7012 | SuppressUserConversions, | |||
7013 | /*InOverloadResolution=*/true, | |||
7014 | /*AllowObjCWritebackConversion=*/ | |||
7015 | getLangOpts().ObjCAutoRefCount); | |||
7016 | if (Candidate.Conversions[ConvIdx].isBad()) { | |||
7017 | Candidate.Viable = false; | |||
7018 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7019 | return; | |||
7020 | } | |||
7021 | } else { | |||
7022 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
7023 | // argument for which there is no corresponding parameter is | |||
7024 | // considered to "match the ellipsis" (C+ 13.3.3.1.3). | |||
7025 | Candidate.Conversions[ConvIdx].setEllipsis(); | |||
7026 | } | |||
7027 | } | |||
7028 | ||||
7029 | if (EnableIfAttr *FailedAttr = | |||
7030 | CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { | |||
7031 | Candidate.Viable = false; | |||
7032 | Candidate.FailureKind = ovl_fail_enable_if; | |||
7033 | Candidate.DeductionFailure.Data = FailedAttr; | |||
7034 | return; | |||
7035 | } | |||
7036 | ||||
7037 | if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && | |||
7038 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
7039 | Candidate.Viable = false; | |||
7040 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
7041 | } | |||
7042 | } | |||
7043 | ||||
7044 | /// Add a C++ member function template as a candidate to the candidate | |||
7045 | /// set, using template argument deduction to produce an appropriate member | |||
7046 | /// function template specialization. | |||
7047 | void Sema::AddMethodTemplateCandidate( | |||
7048 | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, | |||
7049 | CXXRecordDecl *ActingContext, | |||
7050 | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, | |||
7051 | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, | |||
7052 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, | |||
7053 | bool PartialOverloading, OverloadCandidateParamOrder PO) { | |||
7054 | if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) | |||
7055 | return; | |||
7056 | ||||
7057 | // C++ [over.match.funcs]p7: | |||
7058 | // In each case where a candidate is a function template, candidate | |||
7059 | // function template specializations are generated using template argument | |||
7060 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as | |||
7061 | // candidate functions in the usual way.113) A given name can refer to one | |||
7062 | // or more function templates and also to a set of overloaded non-template | |||
7063 | // functions. In such a case, the candidate functions generated from each | |||
7064 | // function template are combined with the set of non-template candidate | |||
7065 | // functions. | |||
7066 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
7067 | FunctionDecl *Specialization = nullptr; | |||
7068 | ConversionSequenceList Conversions; | |||
7069 | if (TemplateDeductionResult Result = DeduceTemplateArguments( | |||
7070 | MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, | |||
7071 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { | |||
7072 | return CheckNonDependentConversions( | |||
7073 | MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, | |||
7074 | SuppressUserConversions, ActingContext, ObjectType, | |||
7075 | ObjectClassification, PO); | |||
7076 | })) { | |||
7077 | OverloadCandidate &Candidate = | |||
7078 | CandidateSet.addCandidate(Conversions.size(), Conversions); | |||
7079 | Candidate.FoundDecl = FoundDecl; | |||
7080 | Candidate.Function = MethodTmpl->getTemplatedDecl(); | |||
7081 | Candidate.Viable = false; | |||
7082 | Candidate.RewriteKind = | |||
7083 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); | |||
7084 | Candidate.IsSurrogate = false; | |||
7085 | Candidate.IgnoreObjectArgument = | |||
7086 | cast<CXXMethodDecl>(Candidate.Function)->isStatic() || | |||
7087 | ObjectType.isNull(); | |||
7088 | Candidate.ExplicitCallArguments = Args.size(); | |||
7089 | if (Result == TDK_NonDependentConversionFailure) | |||
7090 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7091 | else { | |||
7092 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
7093 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
7094 | Info); | |||
7095 | } | |||
7096 | return; | |||
7097 | } | |||
7098 | ||||
7099 | // Add the function template specialization produced by template argument | |||
7100 | // deduction as a candidate. | |||
7101 | assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7101, __extension__ __PRETTY_FUNCTION__ )); | |||
7102 | assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization ) && "Specialization is not a member function?") ? void (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "clang/lib/Sema/SemaOverload.cpp", 7103, __extension__ __PRETTY_FUNCTION__ )) | |||
7103 | "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization ) && "Specialization is not a member function?") ? void (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "clang/lib/Sema/SemaOverload.cpp", 7103, __extension__ __PRETTY_FUNCTION__ )); | |||
7104 | AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, | |||
7105 | ActingContext, ObjectType, ObjectClassification, Args, | |||
7106 | CandidateSet, SuppressUserConversions, PartialOverloading, | |||
7107 | Conversions, PO); | |||
7108 | } | |||
7109 | ||||
7110 | /// Determine whether a given function template has a simple explicit specifier | |||
7111 | /// or a non-value-dependent explicit-specification that evaluates to true. | |||
7112 | static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { | |||
7113 | return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); | |||
7114 | } | |||
7115 | ||||
7116 | /// Add a C++ function template specialization as a candidate | |||
7117 | /// in the candidate set, using template argument deduction to produce | |||
7118 | /// an appropriate function template specialization. | |||
7119 | void Sema::AddTemplateOverloadCandidate( | |||
7120 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
7121 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, | |||
7122 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, | |||
7123 | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, | |||
7124 | OverloadCandidateParamOrder PO) { | |||
7125 | if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) | |||
7126 | return; | |||
7127 | ||||
7128 | // If the function template has a non-dependent explicit specification, | |||
7129 | // exclude it now if appropriate; we are not permitted to perform deduction | |||
7130 | // and substitution in this case. | |||
7131 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { | |||
7132 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); | |||
7133 | Candidate.FoundDecl = FoundDecl; | |||
7134 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
7135 | Candidate.Viable = false; | |||
7136 | Candidate.FailureKind = ovl_fail_explicit; | |||
7137 | return; | |||
7138 | } | |||
7139 | ||||
7140 | // C++ [over.match.funcs]p7: | |||
7141 | // In each case where a candidate is a function template, candidate | |||
7142 | // function template specializations are generated using template argument | |||
7143 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as | |||
7144 | // candidate functions in the usual way.113) A given name can refer to one | |||
7145 | // or more function templates and also to a set of overloaded non-template | |||
7146 | // functions. In such a case, the candidate functions generated from each | |||
7147 | // function template are combined with the set of non-template candidate | |||
7148 | // functions. | |||
7149 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
7150 | FunctionDecl *Specialization = nullptr; | |||
7151 | ConversionSequenceList Conversions; | |||
7152 | if (TemplateDeductionResult Result = DeduceTemplateArguments( | |||
7153 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, | |||
7154 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { | |||
7155 | return CheckNonDependentConversions( | |||
7156 | FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, | |||
7157 | SuppressUserConversions, nullptr, QualType(), {}, PO); | |||
7158 | })) { | |||
7159 | OverloadCandidate &Candidate = | |||
7160 | CandidateSet.addCandidate(Conversions.size(), Conversions); | |||
7161 | Candidate.FoundDecl = FoundDecl; | |||
7162 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
7163 | Candidate.Viable = false; | |||
7164 | Candidate.RewriteKind = | |||
7165 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); | |||
7166 | Candidate.IsSurrogate = false; | |||
7167 | Candidate.IsADLCandidate = IsADLCandidate; | |||
7168 | // Ignore the object argument if there is one, since we don't have an object | |||
7169 | // type. | |||
7170 | Candidate.IgnoreObjectArgument = | |||
7171 | isa<CXXMethodDecl>(Candidate.Function) && | |||
7172 | !isa<CXXConstructorDecl>(Candidate.Function); | |||
7173 | Candidate.ExplicitCallArguments = Args.size(); | |||
7174 | if (Result == TDK_NonDependentConversionFailure) | |||
7175 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7176 | else { | |||
7177 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
7178 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
7179 | Info); | |||
7180 | } | |||
7181 | return; | |||
7182 | } | |||
7183 | ||||
7184 | // Add the function template specialization produced by template argument | |||
7185 | // deduction as a candidate. | |||
7186 | assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7186, __extension__ __PRETTY_FUNCTION__ )); | |||
7187 | AddOverloadCandidate( | |||
7188 | Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, | |||
7189 | PartialOverloading, AllowExplicit, | |||
7190 | /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); | |||
7191 | } | |||
7192 | ||||
7193 | /// Check that implicit conversion sequences can be formed for each argument | |||
7194 | /// whose corresponding parameter has a non-dependent type, per DR1391's | |||
7195 | /// [temp.deduct.call]p10. | |||
7196 | bool Sema::CheckNonDependentConversions( | |||
7197 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, | |||
7198 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, | |||
7199 | ConversionSequenceList &Conversions, bool SuppressUserConversions, | |||
7200 | CXXRecordDecl *ActingContext, QualType ObjectType, | |||
7201 | Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { | |||
7202 | // FIXME: The cases in which we allow explicit conversions for constructor | |||
7203 | // arguments never consider calling a constructor template. It's not clear | |||
7204 | // that is correct. | |||
7205 | const bool AllowExplicit = false; | |||
7206 | ||||
7207 | auto *FD = FunctionTemplate->getTemplatedDecl(); | |||
7208 | auto *Method = dyn_cast<CXXMethodDecl>(FD); | |||
7209 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); | |||
7210 | unsigned ThisConversions = HasThisConversion ? 1 : 0; | |||
7211 | ||||
7212 | Conversions = | |||
7213 | CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); | |||
7214 | ||||
7215 | // Overload resolution is always an unevaluated context. | |||
7216 | EnterExpressionEvaluationContext Unevaluated( | |||
7217 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7218 | ||||
7219 | // For a method call, check the 'this' conversion here too. DR1391 doesn't | |||
7220 | // require that, but this check should never result in a hard error, and | |||
7221 | // overload resolution is permitted to sidestep instantiations. | |||
7222 | if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && | |||
7223 | !ObjectType.isNull()) { | |||
7224 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; | |||
7225 | Conversions[ConvIdx] = TryObjectArgumentInitialization( | |||
7226 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, | |||
7227 | Method, ActingContext); | |||
7228 | if (Conversions[ConvIdx].isBad()) | |||
7229 | return true; | |||
7230 | } | |||
7231 | ||||
7232 | for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; | |||
7233 | ++I) { | |||
7234 | QualType ParamType = ParamTypes[I]; | |||
7235 | if (!ParamType->isDependentType()) { | |||
7236 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed | |||
7237 | ? 0 | |||
7238 | : (ThisConversions + I); | |||
7239 | Conversions[ConvIdx] | |||
7240 | = TryCopyInitialization(*this, Args[I], ParamType, | |||
7241 | SuppressUserConversions, | |||
7242 | /*InOverloadResolution=*/true, | |||
7243 | /*AllowObjCWritebackConversion=*/ | |||
7244 | getLangOpts().ObjCAutoRefCount, | |||
7245 | AllowExplicit); | |||
7246 | if (Conversions[ConvIdx].isBad()) | |||
7247 | return true; | |||
7248 | } | |||
7249 | } | |||
7250 | ||||
7251 | return false; | |||
7252 | } | |||
7253 | ||||
7254 | /// Determine whether this is an allowable conversion from the result | |||
7255 | /// of an explicit conversion operator to the expected type, per C++ | |||
7256 | /// [over.match.conv]p1 and [over.match.ref]p1. | |||
7257 | /// | |||
7258 | /// \param ConvType The return type of the conversion function. | |||
7259 | /// | |||
7260 | /// \param ToType The type we are converting to. | |||
7261 | /// | |||
7262 | /// \param AllowObjCPointerConversion Allow a conversion from one | |||
7263 | /// Objective-C pointer to another. | |||
7264 | /// | |||
7265 | /// \returns true if the conversion is allowable, false otherwise. | |||
7266 | static bool isAllowableExplicitConversion(Sema &S, | |||
7267 | QualType ConvType, QualType ToType, | |||
7268 | bool AllowObjCPointerConversion) { | |||
7269 | QualType ToNonRefType = ToType.getNonReferenceType(); | |||
7270 | ||||
7271 | // Easy case: the types are the same. | |||
7272 | if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) | |||
7273 | return true; | |||
7274 | ||||
7275 | // Allow qualification conversions. | |||
7276 | bool ObjCLifetimeConversion; | |||
7277 | if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, | |||
7278 | ObjCLifetimeConversion)) | |||
7279 | return true; | |||
7280 | ||||
7281 | // If we're not allowed to consider Objective-C pointer conversions, | |||
7282 | // we're done. | |||
7283 | if (!AllowObjCPointerConversion) | |||
7284 | return false; | |||
7285 | ||||
7286 | // Is this an Objective-C pointer conversion? | |||
7287 | bool IncompatibleObjC = false; | |||
7288 | QualType ConvertedType; | |||
7289 | return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, | |||
7290 | IncompatibleObjC); | |||
7291 | } | |||
7292 | ||||
7293 | /// AddConversionCandidate - Add a C++ conversion function as a | |||
7294 | /// candidate in the candidate set (C++ [over.match.conv], | |||
7295 | /// C++ [over.match.copy]). From is the expression we're converting from, | |||
7296 | /// and ToType is the type that we're eventually trying to convert to | |||
7297 | /// (which may or may not be the same type as the type that the | |||
7298 | /// conversion function produces). | |||
7299 | void Sema::AddConversionCandidate( | |||
7300 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, | |||
7301 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, | |||
7302 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
7303 | bool AllowExplicit, bool AllowResultConversion) { | |||
7304 | assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate () && "Conversion function templates use AddTemplateConversionCandidate" ) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "clang/lib/Sema/SemaOverload.cpp", 7305, __extension__ __PRETTY_FUNCTION__ )) | |||
7305 | "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate () && "Conversion function templates use AddTemplateConversionCandidate" ) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "clang/lib/Sema/SemaOverload.cpp", 7305, __extension__ __PRETTY_FUNCTION__ )); | |||
7306 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); | |||
7307 | if (!CandidateSet.isNewCandidate(Conversion)) | |||
7308 | return; | |||
7309 | ||||
7310 | // If the conversion function has an undeduced return type, trigger its | |||
7311 | // deduction now. | |||
7312 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { | |||
7313 | if (DeduceReturnType(Conversion, From->getExprLoc())) | |||
7314 | return; | |||
7315 | ConvType = Conversion->getConversionType().getNonReferenceType(); | |||
7316 | } | |||
7317 | ||||
7318 | // If we don't allow any conversion of the result type, ignore conversion | |||
7319 | // functions that don't convert to exactly (possibly cv-qualified) T. | |||
7320 | if (!AllowResultConversion && | |||
7321 | !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) | |||
7322 | return; | |||
7323 | ||||
7324 | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion | |||
7325 | // operator is only a candidate if its return type is the target type or | |||
7326 | // can be converted to the target type with a qualification conversion. | |||
7327 | // | |||
7328 | // FIXME: Include such functions in the candidate list and explain why we | |||
7329 | // can't select them. | |||
7330 | if (Conversion->isExplicit() && | |||
7331 | !isAllowableExplicitConversion(*this, ConvType, ToType, | |||
7332 | AllowObjCConversionOnExplicit)) | |||
7333 | return; | |||
7334 | ||||
7335 | // Overload resolution is always an unevaluated context. | |||
7336 | EnterExpressionEvaluationContext Unevaluated( | |||
7337 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7338 | ||||
7339 | // Add this candidate | |||
7340 | OverloadCandidate &Candidate = CandidateSet.addCandidate(1); | |||
7341 | Candidate.FoundDecl = FoundDecl; | |||
7342 | Candidate.Function = Conversion; | |||
7343 | Candidate.IsSurrogate = false; | |||
7344 | Candidate.IgnoreObjectArgument = false; | |||
7345 | Candidate.FinalConversion.setAsIdentityConversion(); | |||
7346 | Candidate.FinalConversion.setFromType(ConvType); | |||
7347 | Candidate.FinalConversion.setAllToTypes(ToType); | |||
7348 | Candidate.Viable = true; | |||
7349 | Candidate.ExplicitCallArguments = 1; | |||
7350 | ||||
7351 | // Explicit functions are not actually candidates at all if we're not | |||
7352 | // allowing them in this context, but keep them around so we can point | |||
7353 | // to them in diagnostics. | |||
7354 | if (!AllowExplicit && Conversion->isExplicit()) { | |||
7355 | Candidate.Viable = false; | |||
7356 | Candidate.FailureKind = ovl_fail_explicit; | |||
7357 | return; | |||
7358 | } | |||
7359 | ||||
7360 | // C++ [over.match.funcs]p4: | |||
7361 | // For conversion functions, the function is considered to be a member of | |||
7362 | // the class of the implicit implied object argument for the purpose of | |||
7363 | // defining the type of the implicit object parameter. | |||
7364 | // | |||
7365 | // Determine the implicit conversion sequence for the implicit | |||
7366 | // object parameter. | |||
7367 | QualType ImplicitParamType = From->getType(); | |||
7368 | if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) | |||
7369 | ImplicitParamType = FromPtrType->getPointeeType(); | |||
7370 | CXXRecordDecl *ConversionContext | |||
7371 | = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); | |||
7372 | ||||
7373 | Candidate.Conversions[0] = TryObjectArgumentInitialization( | |||
7374 | *this, CandidateSet.getLocation(), From->getType(), | |||
7375 | From->Classify(Context), Conversion, ConversionContext); | |||
7376 | ||||
7377 | if (Candidate.Conversions[0].isBad()) { | |||
7378 | Candidate.Viable = false; | |||
7379 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7380 | return; | |||
7381 | } | |||
7382 | ||||
7383 | if (Conversion->getTrailingRequiresClause()) { | |||
7384 | ConstraintSatisfaction Satisfaction; | |||
7385 | if (CheckFunctionConstraints(Conversion, Satisfaction) || | |||
7386 | !Satisfaction.IsSatisfied) { | |||
7387 | Candidate.Viable = false; | |||
7388 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; | |||
7389 | return; | |||
7390 | } | |||
7391 | } | |||
7392 | ||||
7393 | // We won't go through a user-defined type conversion function to convert a | |||
7394 | // derived to base as such conversions are given Conversion Rank. They only | |||
7395 | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] | |||
7396 | QualType FromCanon | |||
7397 | = Context.getCanonicalType(From->getType().getUnqualifiedType()); | |||
7398 | QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); | |||
7399 | if (FromCanon == ToCanon || | |||
7400 | IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { | |||
7401 | Candidate.Viable = false; | |||
7402 | Candidate.FailureKind = ovl_fail_trivial_conversion; | |||
7403 | return; | |||
7404 | } | |||
7405 | ||||
7406 | // To determine what the conversion from the result of calling the | |||
7407 | // conversion function to the type we're eventually trying to | |||
7408 | // convert to (ToType), we need to synthesize a call to the | |||
7409 | // conversion function and attempt copy initialization from it. This | |||
7410 | // makes sure that we get the right semantics with respect to | |||
7411 | // lvalues/rvalues and the type. Fortunately, we can allocate this | |||
7412 | // call on the stack and we don't need its arguments to be | |||
7413 | // well-formed. | |||
7414 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), | |||
7415 | VK_LValue, From->getBeginLoc()); | |||
7416 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, | |||
7417 | Context.getPointerType(Conversion->getType()), | |||
7418 | CK_FunctionToPointerDecay, &ConversionRef, | |||
7419 | VK_PRValue, FPOptionsOverride()); | |||
7420 | ||||
7421 | QualType ConversionType = Conversion->getConversionType(); | |||
7422 | if (!isCompleteType(From->getBeginLoc(), ConversionType)) { | |||
7423 | Candidate.Viable = false; | |||
7424 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7425 | return; | |||
7426 | } | |||
7427 | ||||
7428 | ExprValueKind VK = Expr::getValueKindForType(ConversionType); | |||
7429 | ||||
7430 | // Note that it is safe to allocate CallExpr on the stack here because | |||
7431 | // there are 0 arguments (i.e., nothing is allocated using ASTContext's | |||
7432 | // allocator). | |||
7433 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); | |||
7434 | ||||
7435 | alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; | |||
7436 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( | |||
7437 | Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); | |||
7438 | ||||
7439 | ImplicitConversionSequence ICS = | |||
7440 | TryCopyInitialization(*this, TheTemporaryCall, ToType, | |||
7441 | /*SuppressUserConversions=*/true, | |||
7442 | /*InOverloadResolution=*/false, | |||
7443 | /*AllowObjCWritebackConversion=*/false); | |||
7444 | ||||
7445 | switch (ICS.getKind()) { | |||
7446 | case ImplicitConversionSequence::StandardConversion: | |||
7447 | Candidate.FinalConversion = ICS.Standard; | |||
7448 | ||||
7449 | // C++ [over.ics.user]p3: | |||
7450 | // If the user-defined conversion is specified by a specialization of a | |||
7451 | // conversion function template, the second standard conversion sequence | |||
7452 | // shall have exact match rank. | |||
7453 | if (Conversion->getPrimaryTemplate() && | |||
7454 | GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { | |||
7455 | Candidate.Viable = false; | |||
7456 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; | |||
7457 | return; | |||
7458 | } | |||
7459 | ||||
7460 | // C++0x [dcl.init.ref]p5: | |||
7461 | // In the second case, if the reference is an rvalue reference and | |||
7462 | // the second standard conversion sequence of the user-defined | |||
7463 | // conversion sequence includes an lvalue-to-rvalue conversion, the | |||
7464 | // program is ill-formed. | |||
7465 | if (ToType->isRValueReferenceType() && | |||
7466 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | |||
7467 | Candidate.Viable = false; | |||
7468 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7469 | return; | |||
7470 | } | |||
7471 | break; | |||
7472 | ||||
7473 | case ImplicitConversionSequence::BadConversion: | |||
7474 | Candidate.Viable = false; | |||
7475 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7476 | return; | |||
7477 | ||||
7478 | default: | |||
7479 | llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "clang/lib/Sema/SemaOverload.cpp", 7480) | |||
7480 | "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "clang/lib/Sema/SemaOverload.cpp", 7480); | |||
7481 | } | |||
7482 | ||||
7483 | if (EnableIfAttr *FailedAttr = | |||
7484 | CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { | |||
7485 | Candidate.Viable = false; | |||
7486 | Candidate.FailureKind = ovl_fail_enable_if; | |||
7487 | Candidate.DeductionFailure.Data = FailedAttr; | |||
7488 | return; | |||
7489 | } | |||
7490 | ||||
7491 | if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && | |||
7492 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
7493 | Candidate.Viable = false; | |||
7494 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
7495 | } | |||
7496 | } | |||
7497 | ||||
7498 | /// Adds a conversion function template specialization | |||
7499 | /// candidate to the overload set, using template argument deduction | |||
7500 | /// to deduce the template arguments of the conversion function | |||
7501 | /// template from the type that we are converting to (C++ | |||
7502 | /// [temp.deduct.conv]). | |||
7503 | void Sema::AddTemplateConversionCandidate( | |||
7504 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
7505 | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, | |||
7506 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
7507 | bool AllowExplicit, bool AllowResultConversion) { | |||
7508 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate ->getTemplatedDecl()) && "Only conversion function templates permitted here" ) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "clang/lib/Sema/SemaOverload.cpp", 7509, __extension__ __PRETTY_FUNCTION__ )) | |||
7509 | "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate ->getTemplatedDecl()) && "Only conversion function templates permitted here" ) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "clang/lib/Sema/SemaOverload.cpp", 7509, __extension__ __PRETTY_FUNCTION__ )); | |||
7510 | ||||
7511 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) | |||
7512 | return; | |||
7513 | ||||
7514 | // If the function template has a non-dependent explicit specification, | |||
7515 | // exclude it now if appropriate; we are not permitted to perform deduction | |||
7516 | // and substitution in this case. | |||
7517 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { | |||
7518 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); | |||
7519 | Candidate.FoundDecl = FoundDecl; | |||
7520 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
7521 | Candidate.Viable = false; | |||
7522 | Candidate.FailureKind = ovl_fail_explicit; | |||
7523 | return; | |||
7524 | } | |||
7525 | ||||
7526 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
7527 | CXXConversionDecl *Specialization = nullptr; | |||
7528 | if (TemplateDeductionResult Result | |||
7529 | = DeduceTemplateArguments(FunctionTemplate, ToType, | |||
7530 | Specialization, Info)) { | |||
7531 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); | |||
7532 | Candidate.FoundDecl = FoundDecl; | |||
7533 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
7534 | Candidate.Viable = false; | |||
7535 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
7536 | Candidate.IsSurrogate = false; | |||
7537 | Candidate.IgnoreObjectArgument = false; | |||
7538 | Candidate.ExplicitCallArguments = 1; | |||
7539 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
7540 | Info); | |||
7541 | return; | |||
7542 | } | |||
7543 | ||||
7544 | // Add the conversion function template specialization produced by | |||
7545 | // template argument deduction as a candidate. | |||
7546 | assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?" ) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "clang/lib/Sema/SemaOverload.cpp", 7546, __extension__ __PRETTY_FUNCTION__ )); | |||
7547 | AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, | |||
7548 | CandidateSet, AllowObjCConversionOnExplicit, | |||
7549 | AllowExplicit, AllowResultConversion); | |||
7550 | } | |||
7551 | ||||
7552 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that | |||
7553 | /// converts the given @c Object to a function pointer via the | |||
7554 | /// conversion function @c Conversion, and then attempts to call it | |||
7555 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is | |||
7556 | /// the type of function that we'll eventually be calling. | |||
7557 | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, | |||
7558 | DeclAccessPair FoundDecl, | |||
7559 | CXXRecordDecl *ActingContext, | |||
7560 | const FunctionProtoType *Proto, | |||
7561 | Expr *Object, | |||
7562 | ArrayRef<Expr *> Args, | |||
7563 | OverloadCandidateSet& CandidateSet) { | |||
7564 | if (!CandidateSet.isNewCandidate(Conversion)) | |||
7565 | return; | |||
7566 | ||||
7567 | // Overload resolution is always an unevaluated context. | |||
7568 | EnterExpressionEvaluationContext Unevaluated( | |||
7569 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7570 | ||||
7571 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); | |||
7572 | Candidate.FoundDecl = FoundDecl; | |||
7573 | Candidate.Function = nullptr; | |||
7574 | Candidate.Surrogate = Conversion; | |||
7575 | Candidate.Viable = true; | |||
7576 | Candidate.IsSurrogate = true; | |||
7577 | Candidate.IgnoreObjectArgument = false; | |||
7578 | Candidate.ExplicitCallArguments = Args.size(); | |||
7579 | ||||
7580 | // Determine the implicit conversion sequence for the implicit | |||
7581 | // object parameter. | |||
7582 | ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( | |||
7583 | *this, CandidateSet.getLocation(), Object->getType(), | |||
7584 | Object->Classify(Context), Conversion, ActingContext); | |||
7585 | if (ObjectInit.isBad()) { | |||
7586 | Candidate.Viable = false; | |||
7587 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7588 | Candidate.Conversions[0] = ObjectInit; | |||
7589 | return; | |||
7590 | } | |||
7591 | ||||
7592 | // The first conversion is actually a user-defined conversion whose | |||
7593 | // first conversion is ObjectInit's standard conversion (which is | |||
7594 | // effectively a reference binding). Record it as such. | |||
7595 | Candidate.Conversions[0].setUserDefined(); | |||
7596 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; | |||
7597 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; | |||
7598 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; | |||
7599 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; | |||
7600 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; | |||
7601 | Candidate.Conversions[0].UserDefined.After | |||
7602 | = Candidate.Conversions[0].UserDefined.Before; | |||
7603 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); | |||
7604 | ||||
7605 | // Find the | |||
7606 | unsigned NumParams = Proto->getNumParams(); | |||
7607 | ||||
7608 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
7609 | // parameters is viable only if it has an ellipsis in its parameter | |||
7610 | // list (8.3.5). | |||
7611 | if (Args.size() > NumParams && !Proto->isVariadic()) { | |||
7612 | Candidate.Viable = false; | |||
7613 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
7614 | return; | |||
7615 | } | |||
7616 | ||||
7617 | // Function types don't have any default arguments, so just check if | |||
7618 | // we have enough arguments. | |||
7619 | if (Args.size() < NumParams) { | |||
7620 | // Not enough arguments. | |||
7621 | Candidate.Viable = false; | |||
7622 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
7623 | return; | |||
7624 | } | |||
7625 | ||||
7626 | // Determine the implicit conversion sequences for each of the | |||
7627 | // arguments. | |||
7628 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
7629 | if (ArgIdx < NumParams) { | |||
7630 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
7631 | // exist for each argument an implicit conversion sequence | |||
7632 | // (13.3.3.1) that converts that argument to the corresponding | |||
7633 | // parameter of F. | |||
7634 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
7635 | Candidate.Conversions[ArgIdx + 1] | |||
7636 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, | |||
7637 | /*SuppressUserConversions=*/false, | |||
7638 | /*InOverloadResolution=*/false, | |||
7639 | /*AllowObjCWritebackConversion=*/ | |||
7640 | getLangOpts().ObjCAutoRefCount); | |||
7641 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { | |||
7642 | Candidate.Viable = false; | |||
7643 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7644 | return; | |||
7645 | } | |||
7646 | } else { | |||
7647 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
7648 | // argument for which there is no corresponding parameter is | |||
7649 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). | |||
7650 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); | |||
7651 | } | |||
7652 | } | |||
7653 | ||||
7654 | if (EnableIfAttr *FailedAttr = | |||
7655 | CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { | |||
7656 | Candidate.Viable = false; | |||
7657 | Candidate.FailureKind = ovl_fail_enable_if; | |||
7658 | Candidate.DeductionFailure.Data = FailedAttr; | |||
7659 | return; | |||
7660 | } | |||
7661 | } | |||
7662 | ||||
7663 | /// Add all of the non-member operator function declarations in the given | |||
7664 | /// function set to the overload candidate set. | |||
7665 | void Sema::AddNonMemberOperatorCandidates( | |||
7666 | const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, | |||
7667 | OverloadCandidateSet &CandidateSet, | |||
7668 | TemplateArgumentListInfo *ExplicitTemplateArgs) { | |||
7669 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { | |||
7670 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); | |||
7671 | ArrayRef<Expr *> FunctionArgs = Args; | |||
7672 | ||||
7673 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); | |||
7674 | FunctionDecl *FD = | |||
7675 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); | |||
7676 | ||||
7677 | // Don't consider rewritten functions if we're not rewriting. | |||
7678 | if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) | |||
7679 | continue; | |||
7680 | ||||
7681 | assert(!isa<CXXMethodDecl>(FD) &&(static_cast <bool> (!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function") ? void (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "clang/lib/Sema/SemaOverload.cpp", 7682, __extension__ __PRETTY_FUNCTION__ )) | |||
7682 | "unqualified operator lookup found a member function")(static_cast <bool> (!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function") ? void (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\"" , "clang/lib/Sema/SemaOverload.cpp", 7682, __extension__ __PRETTY_FUNCTION__ )); | |||
7683 | ||||
7684 | if (FunTmpl) { | |||
7685 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, | |||
7686 | FunctionArgs, CandidateSet); | |||
7687 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) | |||
7688 | AddTemplateOverloadCandidate( | |||
7689 | FunTmpl, F.getPair(), ExplicitTemplateArgs, | |||
7690 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, | |||
7691 | true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); | |||
7692 | } else { | |||
7693 | if (ExplicitTemplateArgs) | |||
7694 | continue; | |||
7695 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); | |||
7696 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) | |||
7697 | AddOverloadCandidate(FD, F.getPair(), | |||
7698 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, | |||
7699 | false, false, true, false, ADLCallKind::NotADL, | |||
7700 | None, OverloadCandidateParamOrder::Reversed); | |||
7701 | } | |||
7702 | } | |||
7703 | } | |||
7704 | ||||
7705 | /// Add overload candidates for overloaded operators that are | |||
7706 | /// member functions. | |||
7707 | /// | |||
7708 | /// Add the overloaded operator candidates that are member functions | |||
7709 | /// for the operator Op that was used in an operator expression such | |||
7710 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and | |||
7711 | /// CandidateSet will store the added overload candidates. (C++ | |||
7712 | /// [over.match.oper]). | |||
7713 | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, | |||
7714 | SourceLocation OpLoc, | |||
7715 | ArrayRef<Expr *> Args, | |||
7716 | OverloadCandidateSet &CandidateSet, | |||
7717 | OverloadCandidateParamOrder PO) { | |||
7718 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
7719 | ||||
7720 | // C++ [over.match.oper]p3: | |||
7721 | // For a unary operator @ with an operand of a type whose | |||
7722 | // cv-unqualified version is T1, and for a binary operator @ with | |||
7723 | // a left operand of a type whose cv-unqualified version is T1 and | |||
7724 | // a right operand of a type whose cv-unqualified version is T2, | |||
7725 | // three sets of candidate functions, designated member | |||
7726 | // candidates, non-member candidates and built-in candidates, are | |||
7727 | // constructed as follows: | |||
7728 | QualType T1 = Args[0]->getType(); | |||
7729 | ||||
7730 | // -- If T1 is a complete class type or a class currently being | |||
7731 | // defined, the set of member candidates is the result of the | |||
7732 | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, | |||
7733 | // the set of member candidates is empty. | |||
7734 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { | |||
7735 | // Complete the type if it can be completed. | |||
7736 | if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) | |||
7737 | return; | |||
7738 | // If the type is neither complete nor being defined, bail out now. | |||
7739 | if (!T1Rec->getDecl()->getDefinition()) | |||
7740 | return; | |||
7741 | ||||
7742 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); | |||
7743 | LookupQualifiedName(Operators, T1Rec->getDecl()); | |||
7744 | Operators.suppressDiagnostics(); | |||
7745 | ||||
7746 | for (LookupResult::iterator Oper = Operators.begin(), | |||
7747 | OperEnd = Operators.end(); | |||
7748 | Oper != OperEnd; | |||
7749 | ++Oper) | |||
7750 | AddMethodCandidate(Oper.getPair(), Args[0]->getType(), | |||
7751 | Args[0]->Classify(Context), Args.slice(1), | |||
7752 | CandidateSet, /*SuppressUserConversion=*/false, PO); | |||
7753 | } | |||
7754 | } | |||
7755 | ||||
7756 | /// AddBuiltinCandidate - Add a candidate for a built-in | |||
7757 | /// operator. ResultTy and ParamTys are the result and parameter types | |||
7758 | /// of the built-in candidate, respectively. Args and NumArgs are the | |||
7759 | /// arguments being passed to the candidate. IsAssignmentOperator | |||
7760 | /// should be true when this built-in candidate is an assignment | |||
7761 | /// operator. NumContextualBoolArguments is the number of arguments | |||
7762 | /// (at the beginning of the argument list) that will be contextually | |||
7763 | /// converted to bool. | |||
7764 | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, | |||
7765 | OverloadCandidateSet& CandidateSet, | |||
7766 | bool IsAssignmentOperator, | |||
7767 | unsigned NumContextualBoolArguments) { | |||
7768 | // Overload resolution is always an unevaluated context. | |||
7769 | EnterExpressionEvaluationContext Unevaluated( | |||
7770 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7771 | ||||
7772 | // Add this candidate | |||
7773 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); | |||
7774 | Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); | |||
7775 | Candidate.Function = nullptr; | |||
7776 | Candidate.IsSurrogate = false; | |||
7777 | Candidate.IgnoreObjectArgument = false; | |||
7778 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); | |||
7779 | ||||
7780 | // Determine the implicit conversion sequences for each of the | |||
7781 | // arguments. | |||
7782 | Candidate.Viable = true; | |||
7783 | Candidate.ExplicitCallArguments = Args.size(); | |||
7784 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
7785 | // C++ [over.match.oper]p4: | |||
7786 | // For the built-in assignment operators, conversions of the | |||
7787 | // left operand are restricted as follows: | |||
7788 | // -- no temporaries are introduced to hold the left operand, and | |||
7789 | // -- no user-defined conversions are applied to the left | |||
7790 | // operand to achieve a type match with the left-most | |||
7791 | // parameter of a built-in candidate. | |||
7792 | // | |||
7793 | // We block these conversions by turning off user-defined | |||
7794 | // conversions, since that is the only way that initialization of | |||
7795 | // a reference to a non-class type can occur from something that | |||
7796 | // is not of the same type. | |||
7797 | if (ArgIdx < NumContextualBoolArguments) { | |||
7798 | assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "clang/lib/Sema/SemaOverload.cpp", 7799, __extension__ __PRETTY_FUNCTION__ )) | |||
7799 | "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "clang/lib/Sema/SemaOverload.cpp", 7799, __extension__ __PRETTY_FUNCTION__ )); | |||
7800 | Candidate.Conversions[ArgIdx] | |||
7801 | = TryContextuallyConvertToBool(*this, Args[ArgIdx]); | |||
7802 | } else { | |||
7803 | Candidate.Conversions[ArgIdx] | |||
7804 | = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], | |||
7805 | ArgIdx == 0 && IsAssignmentOperator, | |||
7806 | /*InOverloadResolution=*/false, | |||
7807 | /*AllowObjCWritebackConversion=*/ | |||
7808 | getLangOpts().ObjCAutoRefCount); | |||
7809 | } | |||
7810 | if (Candidate.Conversions[ArgIdx].isBad()) { | |||
7811 | Candidate.Viable = false; | |||
7812 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7813 | break; | |||
7814 | } | |||
7815 | } | |||
7816 | } | |||
7817 | ||||
7818 | namespace { | |||
7819 | ||||
7820 | /// BuiltinCandidateTypeSet - A set of types that will be used for the | |||
7821 | /// candidate operator functions for built-in operators (C++ | |||
7822 | /// [over.built]). The types are separated into pointer types and | |||
7823 | /// enumeration types. | |||
7824 | class BuiltinCandidateTypeSet { | |||
7825 | /// TypeSet - A set of types. | |||
7826 | typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, | |||
7827 | llvm::SmallPtrSet<QualType, 8>> TypeSet; | |||
7828 | ||||
7829 | /// PointerTypes - The set of pointer types that will be used in the | |||
7830 | /// built-in candidates. | |||
7831 | TypeSet PointerTypes; | |||
7832 | ||||
7833 | /// MemberPointerTypes - The set of member pointer types that will be | |||
7834 | /// used in the built-in candidates. | |||
7835 | TypeSet MemberPointerTypes; | |||
7836 | ||||
7837 | /// EnumerationTypes - The set of enumeration types that will be | |||
7838 | /// used in the built-in candidates. | |||
7839 | TypeSet EnumerationTypes; | |||
7840 | ||||
7841 | /// The set of vector types that will be used in the built-in | |||
7842 | /// candidates. | |||
7843 | TypeSet VectorTypes; | |||
7844 | ||||
7845 | /// The set of matrix types that will be used in the built-in | |||
7846 | /// candidates. | |||
7847 | TypeSet MatrixTypes; | |||
7848 | ||||
7849 | /// A flag indicating non-record types are viable candidates | |||
7850 | bool HasNonRecordTypes; | |||
7851 | ||||
7852 | /// A flag indicating whether either arithmetic or enumeration types | |||
7853 | /// were present in the candidate set. | |||
7854 | bool HasArithmeticOrEnumeralTypes; | |||
7855 | ||||
7856 | /// A flag indicating whether the nullptr type was present in the | |||
7857 | /// candidate set. | |||
7858 | bool HasNullPtrType; | |||
7859 | ||||
7860 | /// Sema - The semantic analysis instance where we are building the | |||
7861 | /// candidate type set. | |||
7862 | Sema &SemaRef; | |||
7863 | ||||
7864 | /// Context - The AST context in which we will build the type sets. | |||
7865 | ASTContext &Context; | |||
7866 | ||||
7867 | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, | |||
7868 | const Qualifiers &VisibleQuals); | |||
7869 | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); | |||
7870 | ||||
7871 | public: | |||
7872 | /// iterator - Iterates through the types that are part of the set. | |||
7873 | typedef TypeSet::iterator iterator; | |||
7874 | ||||
7875 | BuiltinCandidateTypeSet(Sema &SemaRef) | |||
7876 | : HasNonRecordTypes(false), | |||
7877 | HasArithmeticOrEnumeralTypes(false), | |||
7878 | HasNullPtrType(false), | |||
7879 | SemaRef(SemaRef), | |||
7880 | Context(SemaRef.Context) { } | |||
7881 | ||||
7882 | void AddTypesConvertedFrom(QualType Ty, | |||
7883 | SourceLocation Loc, | |||
7884 | bool AllowUserConversions, | |||
7885 | bool AllowExplicitConversions, | |||
7886 | const Qualifiers &VisibleTypeConversionsQuals); | |||
7887 | ||||
7888 | llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } | |||
7889 | llvm::iterator_range<iterator> member_pointer_types() { | |||
7890 | return MemberPointerTypes; | |||
7891 | } | |||
7892 | llvm::iterator_range<iterator> enumeration_types() { | |||
7893 | return EnumerationTypes; | |||
7894 | } | |||
7895 | llvm::iterator_range<iterator> vector_types() { return VectorTypes; } | |||
7896 | llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } | |||
7897 | ||||
7898 | bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } | |||
7899 | bool hasNonRecordTypes() { return HasNonRecordTypes; } | |||
7900 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } | |||
7901 | bool hasNullPtrType() const { return HasNullPtrType; } | |||
7902 | }; | |||
7903 | ||||
7904 | } // end anonymous namespace | |||
7905 | ||||
7906 | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to | |||
7907 | /// the set of pointer types along with any more-qualified variants of | |||
7908 | /// that type. For example, if @p Ty is "int const *", this routine | |||
7909 | /// will add "int const *", "int const volatile *", "int const | |||
7910 | /// restrict *", and "int const volatile restrict *" to the set of | |||
7911 | /// pointer types. Returns true if the add of @p Ty itself succeeded, | |||
7912 | /// false otherwise. | |||
7913 | /// | |||
7914 | /// FIXME: what to do about extended qualifiers? | |||
7915 | bool | |||
7916 | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, | |||
7917 | const Qualifiers &VisibleQuals) { | |||
7918 | ||||
7919 | // Insert this type. | |||
7920 | if (!PointerTypes.insert(Ty)) | |||
7921 | return false; | |||
7922 | ||||
7923 | QualType PointeeTy; | |||
7924 | const PointerType *PointerTy = Ty->getAs<PointerType>(); | |||
7925 | bool buildObjCPtr = false; | |||
7926 | if (!PointerTy) { | |||
7927 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); | |||
7928 | PointeeTy = PTy->getPointeeType(); | |||
7929 | buildObjCPtr = true; | |||
7930 | } else { | |||
7931 | PointeeTy = PointerTy->getPointeeType(); | |||
7932 | } | |||
7933 | ||||
7934 | // Don't add qualified variants of arrays. For one, they're not allowed | |||
7935 | // (the qualifier would sink to the element type), and for another, the | |||
7936 | // only overload situation where it matters is subscript or pointer +- int, | |||
7937 | // and those shouldn't have qualifier variants anyway. | |||
7938 | if (PointeeTy->isArrayType()) | |||
7939 | return true; | |||
7940 | ||||
7941 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); | |||
7942 | bool hasVolatile = VisibleQuals.hasVolatile(); | |||
7943 | bool hasRestrict = VisibleQuals.hasRestrict(); | |||
7944 | ||||
7945 | // Iterate through all strict supersets of BaseCVR. | |||
7946 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { | |||
7947 | if ((CVR | BaseCVR) != CVR) continue; | |||
7948 | // Skip over volatile if no volatile found anywhere in the types. | |||
7949 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; | |||
7950 | ||||
7951 | // Skip over restrict if no restrict found anywhere in the types, or if | |||
7952 | // the type cannot be restrict-qualified. | |||
7953 | if ((CVR & Qualifiers::Restrict) && | |||
7954 | (!hasRestrict || | |||
7955 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) | |||
7956 | continue; | |||
7957 | ||||
7958 | // Build qualified pointee type. | |||
7959 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); | |||
7960 | ||||
7961 | // Build qualified pointer type. | |||
7962 | QualType QPointerTy; | |||
7963 | if (!buildObjCPtr) | |||
7964 | QPointerTy = Context.getPointerType(QPointeeTy); | |||
7965 | else | |||
7966 | QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); | |||
7967 | ||||
7968 | // Insert qualified pointer type. | |||
7969 | PointerTypes.insert(QPointerTy); | |||
7970 | } | |||
7971 | ||||
7972 | return true; | |||
7973 | } | |||
7974 | ||||
7975 | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty | |||
7976 | /// to the set of pointer types along with any more-qualified variants of | |||
7977 | /// that type. For example, if @p Ty is "int const *", this routine | |||
7978 | /// will add "int const *", "int const volatile *", "int const | |||
7979 | /// restrict *", and "int const volatile restrict *" to the set of | |||
7980 | /// pointer types. Returns true if the add of @p Ty itself succeeded, | |||
7981 | /// false otherwise. | |||
7982 | /// | |||
7983 | /// FIXME: what to do about extended qualifiers? | |||
7984 | bool | |||
7985 | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( | |||
7986 | QualType Ty) { | |||
7987 | // Insert this type. | |||
7988 | if (!MemberPointerTypes.insert(Ty)) | |||
7989 | return false; | |||
7990 | ||||
7991 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); | |||
7992 | assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!" ) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\"" , "clang/lib/Sema/SemaOverload.cpp", 7992, __extension__ __PRETTY_FUNCTION__ )); | |||
7993 | ||||
7994 | QualType PointeeTy = PointerTy->getPointeeType(); | |||
7995 | // Don't add qualified variants of arrays. For one, they're not allowed | |||
7996 | // (the qualifier would sink to the element type), and for another, the | |||
7997 | // only overload situation where it matters is subscript or pointer +- int, | |||
7998 | // and those shouldn't have qualifier variants anyway. | |||
7999 | if (PointeeTy->isArrayType()) | |||
8000 | return true; | |||
8001 | const Type *ClassTy = PointerTy->getClass(); | |||
8002 | ||||
8003 | // Iterate through all strict supersets of the pointee type's CVR | |||
8004 | // qualifiers. | |||
8005 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); | |||
8006 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { | |||
8007 | if ((CVR | BaseCVR) != CVR) continue; | |||
8008 | ||||
8009 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); | |||
8010 | MemberPointerTypes.insert( | |||
8011 | Context.getMemberPointerType(QPointeeTy, ClassTy)); | |||
8012 | } | |||
8013 | ||||
8014 | return true; | |||
8015 | } | |||
8016 | ||||
8017 | /// AddTypesConvertedFrom - Add each of the types to which the type @p | |||
8018 | /// Ty can be implicit converted to the given set of @p Types. We're | |||
8019 | /// primarily interested in pointer types and enumeration types. We also | |||
8020 | /// take member pointer types, for the conditional operator. | |||
8021 | /// AllowUserConversions is true if we should look at the conversion | |||
8022 | /// functions of a class type, and AllowExplicitConversions if we | |||
8023 | /// should also include the explicit conversion functions of a class | |||
8024 | /// type. | |||
8025 | void | |||
8026 | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, | |||
8027 | SourceLocation Loc, | |||
8028 | bool AllowUserConversions, | |||
8029 | bool AllowExplicitConversions, | |||
8030 | const Qualifiers &VisibleQuals) { | |||
8031 | // Only deal with canonical types. | |||
8032 | Ty = Context.getCanonicalType(Ty); | |||
8033 | ||||
8034 | // Look through reference types; they aren't part of the type of an | |||
8035 | // expression for the purposes of conversions. | |||
8036 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) | |||
8037 | Ty = RefTy->getPointeeType(); | |||
8038 | ||||
8039 | // If we're dealing with an array type, decay to the pointer. | |||
8040 | if (Ty->isArrayType()) | |||
8041 | Ty = SemaRef.Context.getArrayDecayedType(Ty); | |||
8042 | ||||
8043 | // Otherwise, we don't care about qualifiers on the type. | |||
8044 | Ty = Ty.getLocalUnqualifiedType(); | |||
8045 | ||||
8046 | // Flag if we ever add a non-record type. | |||
8047 | const RecordType *TyRec = Ty->getAs<RecordType>(); | |||
8048 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; | |||
8049 | ||||
8050 | // Flag if we encounter an arithmetic type. | |||
8051 | HasArithmeticOrEnumeralTypes = | |||
8052 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); | |||
8053 | ||||
8054 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) | |||
8055 | PointerTypes.insert(Ty); | |||
8056 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { | |||
8057 | // Insert our type, and its more-qualified variants, into the set | |||
8058 | // of types. | |||
8059 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) | |||
8060 | return; | |||
8061 | } else if (Ty->isMemberPointerType()) { | |||
8062 | // Member pointers are far easier, since the pointee can't be converted. | |||
8063 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) | |||
8064 | return; | |||
8065 | } else if (Ty->isEnumeralType()) { | |||
8066 | HasArithmeticOrEnumeralTypes = true; | |||
8067 | EnumerationTypes.insert(Ty); | |||
8068 | } else if (Ty->isVectorType()) { | |||
8069 | // We treat vector types as arithmetic types in many contexts as an | |||
8070 | // extension. | |||
8071 | HasArithmeticOrEnumeralTypes = true; | |||
8072 | VectorTypes.insert(Ty); | |||
8073 | } else if (Ty->isMatrixType()) { | |||
8074 | // Similar to vector types, we treat vector types as arithmetic types in | |||
8075 | // many contexts as an extension. | |||
8076 | HasArithmeticOrEnumeralTypes = true; | |||
8077 | MatrixTypes.insert(Ty); | |||
8078 | } else if (Ty->isNullPtrType()) { | |||
8079 | HasNullPtrType = true; | |||
8080 | } else if (AllowUserConversions && TyRec) { | |||
8081 | // No conversion functions in incomplete types. | |||
8082 | if (!SemaRef.isCompleteType(Loc, Ty)) | |||
8083 | return; | |||
8084 | ||||
8085 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); | |||
8086 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { | |||
8087 | if (isa<UsingShadowDecl>(D)) | |||
8088 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
8089 | ||||
8090 | // Skip conversion function templates; they don't tell us anything | |||
8091 | // about which builtin types we can convert to. | |||
8092 | if (isa<FunctionTemplateDecl>(D)) | |||
8093 | continue; | |||
8094 | ||||
8095 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); | |||
8096 | if (AllowExplicitConversions || !Conv->isExplicit()) { | |||
8097 | AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, | |||
8098 | VisibleQuals); | |||
8099 | } | |||
8100 | } | |||
8101 | } | |||
8102 | } | |||
8103 | /// Helper function for adjusting address spaces for the pointer or reference | |||
8104 | /// operands of builtin operators depending on the argument. | |||
8105 | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, | |||
8106 | Expr *Arg) { | |||
8107 | return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); | |||
8108 | } | |||
8109 | ||||
8110 | /// Helper function for AddBuiltinOperatorCandidates() that adds | |||
8111 | /// the volatile- and non-volatile-qualified assignment operators for the | |||
8112 | /// given type to the candidate set. | |||
8113 | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, | |||
8114 | QualType T, | |||
8115 | ArrayRef<Expr *> Args, | |||
8116 | OverloadCandidateSet &CandidateSet) { | |||
8117 | QualType ParamTypes[2]; | |||
8118 | ||||
8119 | // T& operator=(T&, T) | |||
8120 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
8121 | AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); | |||
8122 | ParamTypes[1] = T; | |||
8123 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8124 | /*IsAssignmentOperator=*/true); | |||
8125 | ||||
8126 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { | |||
8127 | // volatile T& operator=(volatile T&, T) | |||
8128 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
8129 | AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), | |||
8130 | Args[0])); | |||
8131 | ParamTypes[1] = T; | |||
8132 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8133 | /*IsAssignmentOperator=*/true); | |||
8134 | } | |||
8135 | } | |||
8136 | ||||
8137 | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, | |||
8138 | /// if any, found in visible type conversion functions found in ArgExpr's type. | |||
8139 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { | |||
8140 | Qualifiers VRQuals; | |||
8141 | const RecordType *TyRec; | |||
8142 | if (const MemberPointerType *RHSMPType = | |||
8143 | ArgExpr->getType()->getAs<MemberPointerType>()) | |||
8144 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); | |||
8145 | else | |||
8146 | TyRec = ArgExpr->getType()->getAs<RecordType>(); | |||
8147 | if (!TyRec) { | |||
8148 | // Just to be safe, assume the worst case. | |||
8149 | VRQuals.addVolatile(); | |||
8150 | VRQuals.addRestrict(); | |||
8151 | return VRQuals; | |||
8152 | } | |||
8153 | ||||
8154 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); | |||
8155 | if (!ClassDecl->hasDefinition()) | |||
8156 | return VRQuals; | |||
8157 | ||||
8158 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { | |||
8159 | if (isa<UsingShadowDecl>(D)) | |||
8160 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
8161 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { | |||
8162 | QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); | |||
8163 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) | |||
8164 | CanTy = ResTypeRef->getPointeeType(); | |||
8165 | // Need to go down the pointer/mempointer chain and add qualifiers | |||
8166 | // as see them. | |||
8167 | bool done = false; | |||
8168 | while (!done) { | |||
8169 | if (CanTy.isRestrictQualified()) | |||
8170 | VRQuals.addRestrict(); | |||
8171 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) | |||
8172 | CanTy = ResTypePtr->getPointeeType(); | |||
8173 | else if (const MemberPointerType *ResTypeMPtr = | |||
8174 | CanTy->getAs<MemberPointerType>()) | |||
8175 | CanTy = ResTypeMPtr->getPointeeType(); | |||
8176 | else | |||
8177 | done = true; | |||
8178 | if (CanTy.isVolatileQualified()) | |||
8179 | VRQuals.addVolatile(); | |||
8180 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) | |||
8181 | return VRQuals; | |||
8182 | } | |||
8183 | } | |||
8184 | } | |||
8185 | return VRQuals; | |||
8186 | } | |||
8187 | ||||
8188 | namespace { | |||
8189 | ||||
8190 | /// Helper class to manage the addition of builtin operator overload | |||
8191 | /// candidates. It provides shared state and utility methods used throughout | |||
8192 | /// the process, as well as a helper method to add each group of builtin | |||
8193 | /// operator overloads from the standard to a candidate set. | |||
8194 | class BuiltinOperatorOverloadBuilder { | |||
8195 | // Common instance state available to all overload candidate addition methods. | |||
8196 | Sema &S; | |||
8197 | ArrayRef<Expr *> Args; | |||
8198 | Qualifiers VisibleTypeConversionsQuals; | |||
8199 | bool HasArithmeticOrEnumeralCandidateType; | |||
8200 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; | |||
8201 | OverloadCandidateSet &CandidateSet; | |||
8202 | ||||
8203 | static constexpr int ArithmeticTypesCap = 24; | |||
8204 | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; | |||
8205 | ||||
8206 | // Define some indices used to iterate over the arithmetic types in | |||
8207 | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic | |||
8208 | // types are that preserved by promotion (C++ [over.built]p2). | |||
8209 | unsigned FirstIntegralType, | |||
8210 | LastIntegralType; | |||
8211 | unsigned FirstPromotedIntegralType, | |||
8212 | LastPromotedIntegralType; | |||
8213 | unsigned FirstPromotedArithmeticType, | |||
8214 | LastPromotedArithmeticType; | |||
8215 | unsigned NumArithmeticTypes; | |||
8216 | ||||
8217 | void InitArithmeticTypes() { | |||
8218 | // Start of promoted types. | |||
8219 | FirstPromotedArithmeticType = 0; | |||
8220 | ArithmeticTypes.push_back(S.Context.FloatTy); | |||
8221 | ArithmeticTypes.push_back(S.Context.DoubleTy); | |||
8222 | ArithmeticTypes.push_back(S.Context.LongDoubleTy); | |||
8223 | if (S.Context.getTargetInfo().hasFloat128Type()) | |||
8224 | ArithmeticTypes.push_back(S.Context.Float128Ty); | |||
8225 | if (S.Context.getTargetInfo().hasIbm128Type()) | |||
8226 | ArithmeticTypes.push_back(S.Context.Ibm128Ty); | |||
8227 | ||||
8228 | // Start of integral types. | |||
8229 | FirstIntegralType = ArithmeticTypes.size(); | |||
8230 | FirstPromotedIntegralType = ArithmeticTypes.size(); | |||
8231 | ArithmeticTypes.push_back(S.Context.IntTy); | |||
8232 | ArithmeticTypes.push_back(S.Context.LongTy); | |||
8233 | ArithmeticTypes.push_back(S.Context.LongLongTy); | |||
8234 | if (S.Context.getTargetInfo().hasInt128Type() || | |||
8235 | (S.Context.getAuxTargetInfo() && | |||
8236 | S.Context.getAuxTargetInfo()->hasInt128Type())) | |||
8237 | ArithmeticTypes.push_back(S.Context.Int128Ty); | |||
8238 | ArithmeticTypes.push_back(S.Context.UnsignedIntTy); | |||
8239 | ArithmeticTypes.push_back(S.Context.UnsignedLongTy); | |||
8240 | ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); | |||
8241 | if (S.Context.getTargetInfo().hasInt128Type() || | |||
8242 | (S.Context.getAuxTargetInfo() && | |||
8243 | S.Context.getAuxTargetInfo()->hasInt128Type())) | |||
8244 | ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); | |||
8245 | LastPromotedIntegralType = ArithmeticTypes.size(); | |||
8246 | LastPromotedArithmeticType = ArithmeticTypes.size(); | |||
8247 | // End of promoted types. | |||
8248 | ||||
8249 | ArithmeticTypes.push_back(S.Context.BoolTy); | |||
8250 | ArithmeticTypes.push_back(S.Context.CharTy); | |||
8251 | ArithmeticTypes.push_back(S.Context.WCharTy); | |||
8252 | if (S.Context.getLangOpts().Char8) | |||
8253 | ArithmeticTypes.push_back(S.Context.Char8Ty); | |||
8254 | ArithmeticTypes.push_back(S.Context.Char16Ty); | |||
8255 | ArithmeticTypes.push_back(S.Context.Char32Ty); | |||
8256 | ArithmeticTypes.push_back(S.Context.SignedCharTy); | |||
8257 | ArithmeticTypes.push_back(S.Context.ShortTy); | |||
8258 | ArithmeticTypes.push_back(S.Context.UnsignedCharTy); | |||
8259 | ArithmeticTypes.push_back(S.Context.UnsignedShortTy); | |||
8260 | LastIntegralType = ArithmeticTypes.size(); | |||
8261 | NumArithmeticTypes = ArithmeticTypes.size(); | |||
8262 | // End of integral types. | |||
8263 | // FIXME: What about complex? What about half? | |||
8264 | ||||
8265 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "clang/lib/Sema/SemaOverload.cpp", 8266, __extension__ __PRETTY_FUNCTION__ )) | |||
8266 | "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "clang/lib/Sema/SemaOverload.cpp", 8266, __extension__ __PRETTY_FUNCTION__ )); | |||
8267 | } | |||
8268 | ||||
8269 | /// Helper method to factor out the common pattern of adding overloads | |||
8270 | /// for '++' and '--' builtin operators. | |||
8271 | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, | |||
8272 | bool HasVolatile, | |||
8273 | bool HasRestrict) { | |||
8274 | QualType ParamTypes[2] = { | |||
8275 | S.Context.getLValueReferenceType(CandidateTy), | |||
8276 | S.Context.IntTy | |||
8277 | }; | |||
8278 | ||||
8279 | // Non-volatile version. | |||
8280 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8281 | ||||
8282 | // Use a heuristic to reduce number of builtin candidates in the set: | |||
8283 | // add volatile version only if there are conversions to a volatile type. | |||
8284 | if (HasVolatile) { | |||
8285 | ParamTypes[0] = | |||
8286 | S.Context.getLValueReferenceType( | |||
8287 | S.Context.getVolatileType(CandidateTy)); | |||
8288 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8289 | } | |||
8290 | ||||
8291 | // Add restrict version only if there are conversions to a restrict type | |||
8292 | // and our candidate type is a non-restrict-qualified pointer. | |||
8293 | if (HasRestrict && CandidateTy->isAnyPointerType() && | |||
8294 | !CandidateTy.isRestrictQualified()) { | |||
8295 | ParamTypes[0] | |||
8296 | = S.Context.getLValueReferenceType( | |||
8297 | S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); | |||
8298 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8299 | ||||
8300 | if (HasVolatile) { | |||
8301 | ParamTypes[0] | |||
8302 | = S.Context.getLValueReferenceType( | |||
8303 | S.Context.getCVRQualifiedType(CandidateTy, | |||
8304 | (Qualifiers::Volatile | | |||
8305 | Qualifiers::Restrict))); | |||
8306 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8307 | } | |||
8308 | } | |||
8309 | ||||
8310 | } | |||
8311 | ||||
8312 | /// Helper to add an overload candidate for a binary builtin with types \p L | |||
8313 | /// and \p R. | |||
8314 | void AddCandidate(QualType L, QualType R) { | |||
8315 | QualType LandR[2] = {L, R}; | |||
8316 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8317 | } | |||
8318 | ||||
8319 | public: | |||
8320 | BuiltinOperatorOverloadBuilder( | |||
8321 | Sema &S, ArrayRef<Expr *> Args, | |||
8322 | Qualifiers VisibleTypeConversionsQuals, | |||
8323 | bool HasArithmeticOrEnumeralCandidateType, | |||
8324 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, | |||
8325 | OverloadCandidateSet &CandidateSet) | |||
8326 | : S(S), Args(Args), | |||
8327 | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), | |||
8328 | HasArithmeticOrEnumeralCandidateType( | |||
8329 | HasArithmeticOrEnumeralCandidateType), | |||
8330 | CandidateTypes(CandidateTypes), | |||
8331 | CandidateSet(CandidateSet) { | |||
8332 | ||||
8333 | InitArithmeticTypes(); | |||
8334 | } | |||
8335 | ||||
8336 | // Increment is deprecated for bool since C++17. | |||
8337 | // | |||
8338 | // C++ [over.built]p3: | |||
8339 | // | |||
8340 | // For every pair (T, VQ), where T is an arithmetic type other | |||
8341 | // than bool, and VQ is either volatile or empty, there exist | |||
8342 | // candidate operator functions of the form | |||
8343 | // | |||
8344 | // VQ T& operator++(VQ T&); | |||
8345 | // T operator++(VQ T&, int); | |||
8346 | // | |||
8347 | // C++ [over.built]p4: | |||
8348 | // | |||
8349 | // For every pair (T, VQ), where T is an arithmetic type other | |||
8350 | // than bool, and VQ is either volatile or empty, there exist | |||
8351 | // candidate operator functions of the form | |||
8352 | // | |||
8353 | // VQ T& operator--(VQ T&); | |||
8354 | // T operator--(VQ T&, int); | |||
8355 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { | |||
8356 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8357 | return; | |||
8358 | ||||
8359 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { | |||
8360 | const auto TypeOfT = ArithmeticTypes[Arith]; | |||
8361 | if (TypeOfT == S.Context.BoolTy) { | |||
8362 | if (Op == OO_MinusMinus) | |||
8363 | continue; | |||
8364 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) | |||
8365 | continue; | |||
8366 | } | |||
8367 | addPlusPlusMinusMinusStyleOverloads( | |||
8368 | TypeOfT, | |||
8369 | VisibleTypeConversionsQuals.hasVolatile(), | |||
8370 | VisibleTypeConversionsQuals.hasRestrict()); | |||
8371 | } | |||
8372 | } | |||
8373 | ||||
8374 | // C++ [over.built]p5: | |||
8375 | // | |||
8376 | // For every pair (T, VQ), where T is a cv-qualified or | |||
8377 | // cv-unqualified object type, and VQ is either volatile or | |||
8378 | // empty, there exist candidate operator functions of the form | |||
8379 | // | |||
8380 | // T*VQ& operator++(T*VQ&); | |||
8381 | // T*VQ& operator--(T*VQ&); | |||
8382 | // T* operator++(T*VQ&, int); | |||
8383 | // T* operator--(T*VQ&, int); | |||
8384 | void addPlusPlusMinusMinusPointerOverloads() { | |||
8385 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { | |||
8386 | // Skip pointer types that aren't pointers to object types. | |||
8387 | if (!PtrTy->getPointeeType()->isObjectType()) | |||
8388 | continue; | |||
8389 | ||||
8390 | addPlusPlusMinusMinusStyleOverloads( | |||
8391 | PtrTy, | |||
8392 | (!PtrTy.isVolatileQualified() && | |||
8393 | VisibleTypeConversionsQuals.hasVolatile()), | |||
8394 | (!PtrTy.isRestrictQualified() && | |||
8395 | VisibleTypeConversionsQuals.hasRestrict())); | |||
8396 | } | |||
8397 | } | |||
8398 | ||||
8399 | // C++ [over.built]p6: | |||
8400 | // For every cv-qualified or cv-unqualified object type T, there | |||
8401 | // exist candidate operator functions of the form | |||
8402 | // | |||
8403 | // T& operator*(T*); | |||
8404 | // | |||
8405 | // C++ [over.built]p7: | |||
8406 | // For every function type T that does not have cv-qualifiers or a | |||
8407 | // ref-qualifier, there exist candidate operator functions of the form | |||
8408 | // T& operator*(T*); | |||
8409 | void addUnaryStarPointerOverloads() { | |||
8410 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) { | |||
8411 | QualType PointeeTy = ParamTy->getPointeeType(); | |||
8412 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) | |||
8413 | continue; | |||
8414 | ||||
8415 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) | |||
8416 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) | |||
8417 | continue; | |||
8418 | ||||
8419 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); | |||
8420 | } | |||
8421 | } | |||
8422 | ||||
8423 | // C++ [over.built]p9: | |||
8424 | // For every promoted arithmetic type T, there exist candidate | |||
8425 | // operator functions of the form | |||
8426 | // | |||
8427 | // T operator+(T); | |||
8428 | // T operator-(T); | |||
8429 | void addUnaryPlusOrMinusArithmeticOverloads() { | |||
8430 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8431 | return; | |||
8432 | ||||
8433 | for (unsigned Arith = FirstPromotedArithmeticType; | |||
8434 | Arith < LastPromotedArithmeticType; ++Arith) { | |||
8435 | QualType ArithTy = ArithmeticTypes[Arith]; | |||
8436 | S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); | |||
8437 | } | |||
8438 | ||||
8439 | // Extension: We also add these operators for vector types. | |||
8440 | for (QualType VecTy : CandidateTypes[0].vector_types()) | |||
8441 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); | |||
8442 | } | |||
8443 | ||||
8444 | // C++ [over.built]p8: | |||
8445 | // For every type T, there exist candidate operator functions of | |||
8446 | // the form | |||
8447 | // | |||
8448 | // T* operator+(T*); | |||
8449 | void addUnaryPlusPointerOverloads() { | |||
8450 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) | |||
8451 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); | |||
8452 | } | |||
8453 | ||||
8454 | // C++ [over.built]p10: | |||
8455 | // For every promoted integral type T, there exist candidate | |||
8456 | // operator functions of the form | |||
8457 | // | |||
8458 | // T operator~(T); | |||
8459 | void addUnaryTildePromotedIntegralOverloads() { | |||
8460 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8461 | return; | |||
8462 | ||||
8463 | for (unsigned Int = FirstPromotedIntegralType; | |||
8464 | Int < LastPromotedIntegralType; ++Int) { | |||
8465 | QualType IntTy = ArithmeticTypes[Int]; | |||
8466 | S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); | |||
8467 | } | |||
8468 | ||||
8469 | // Extension: We also add this operator for vector types. | |||
8470 | for (QualType VecTy : CandidateTypes[0].vector_types()) | |||
8471 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); | |||
8472 | } | |||
8473 | ||||
8474 | // C++ [over.match.oper]p16: | |||
8475 | // For every pointer to member type T or type std::nullptr_t, there | |||
8476 | // exist candidate operator functions of the form | |||
8477 | // | |||
8478 | // bool operator==(T,T); | |||
8479 | // bool operator!=(T,T); | |||
8480 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { | |||
8481 | /// Set of (canonical) types that we've already handled. | |||
8482 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8483 | ||||
8484 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8485 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { | |||
8486 | // Don't add the same builtin candidate twice. | |||
8487 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) | |||
8488 | continue; | |||
8489 | ||||
8490 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; | |||
8491 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8492 | } | |||
8493 | ||||
8494 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { | |||
8495 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); | |||
8496 | if (AddedTypes.insert(NullPtrTy).second) { | |||
8497 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; | |||
8498 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8499 | } | |||
8500 | } | |||
8501 | } | |||
8502 | } | |||
8503 | ||||
8504 | // C++ [over.built]p15: | |||
8505 | // | |||
8506 | // For every T, where T is an enumeration type or a pointer type, | |||
8507 | // there exist candidate operator functions of the form | |||
8508 | // | |||
8509 | // bool operator<(T, T); | |||
8510 | // bool operator>(T, T); | |||
8511 | // bool operator<=(T, T); | |||
8512 | // bool operator>=(T, T); | |||
8513 | // bool operator==(T, T); | |||
8514 | // bool operator!=(T, T); | |||
8515 | // R operator<=>(T, T) | |||
8516 | void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { | |||
8517 | // C++ [over.match.oper]p3: | |||
8518 | // [...]the built-in candidates include all of the candidate operator | |||
8519 | // functions defined in 13.6 that, compared to the given operator, [...] | |||
8520 | // do not have the same parameter-type-list as any non-template non-member | |||
8521 | // candidate. | |||
8522 | // | |||
8523 | // Note that in practice, this only affects enumeration types because there | |||
8524 | // aren't any built-in candidates of record type, and a user-defined operator | |||
8525 | // must have an operand of record or enumeration type. Also, the only other | |||
8526 | // overloaded operator with enumeration arguments, operator=, | |||
8527 | // cannot be overloaded for enumeration types, so this is the only place | |||
8528 | // where we must suppress candidates like this. | |||
8529 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > | |||
8530 | UserDefinedBinaryOperators; | |||
8531 | ||||
8532 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8533 | if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { | |||
8534 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), | |||
8535 | CEnd = CandidateSet.end(); | |||
8536 | C != CEnd; ++C) { | |||
8537 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) | |||
8538 | continue; | |||
8539 | ||||
8540 | if (C->Function->isFunctionTemplateSpecialization()) | |||
8541 | continue; | |||
8542 | ||||
8543 | // We interpret "same parameter-type-list" as applying to the | |||
8544 | // "synthesized candidate, with the order of the two parameters | |||
8545 | // reversed", not to the original function. | |||
8546 | bool Reversed = C->isReversed(); | |||
8547 | QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) | |||
8548 | ->getType() | |||
8549 | .getUnqualifiedType(); | |||
8550 | QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) | |||
8551 | ->getType() | |||
8552 | .getUnqualifiedType(); | |||
8553 | ||||
8554 | // Skip if either parameter isn't of enumeral type. | |||
8555 | if (!FirstParamType->isEnumeralType() || | |||
8556 | !SecondParamType->isEnumeralType()) | |||
8557 | continue; | |||
8558 | ||||
8559 | // Add this operator to the set of known user-defined operators. | |||
8560 | UserDefinedBinaryOperators.insert( | |||
8561 | std::make_pair(S.Context.getCanonicalType(FirstParamType), | |||
8562 | S.Context.getCanonicalType(SecondParamType))); | |||
8563 | } | |||
8564 | } | |||
8565 | } | |||
8566 | ||||
8567 | /// Set of (canonical) types that we've already handled. | |||
8568 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8569 | ||||
8570 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8571 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { | |||
8572 | // Don't add the same builtin candidate twice. | |||
8573 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) | |||
8574 | continue; | |||
8575 | if (IsSpaceship && PtrTy->isFunctionPointerType()) | |||
8576 | continue; | |||
8577 | ||||
8578 | QualType ParamTypes[2] = {PtrTy, PtrTy}; | |||
8579 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8580 | } | |||
8581 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { | |||
8582 | CanQualType CanonType = S.Context.getCanonicalType(EnumTy); | |||
8583 | ||||
8584 | // Don't add the same builtin candidate twice, or if a user defined | |||
8585 | // candidate exists. | |||
8586 | if (!AddedTypes.insert(CanonType).second || | |||
8587 | UserDefinedBinaryOperators.count(std::make_pair(CanonType, | |||
8588 | CanonType))) | |||
8589 | continue; | |||
8590 | QualType ParamTypes[2] = {EnumTy, EnumTy}; | |||
8591 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8592 | } | |||
8593 | } | |||
8594 | } | |||
8595 | ||||
8596 | // C++ [over.built]p13: | |||
8597 | // | |||
8598 | // For every cv-qualified or cv-unqualified object type T | |||
8599 | // there exist candidate operator functions of the form | |||
8600 | // | |||
8601 | // T* operator+(T*, ptrdiff_t); | |||
8602 | // T& operator[](T*, ptrdiff_t); [BELOW] | |||
8603 | // T* operator-(T*, ptrdiff_t); | |||
8604 | // T* operator+(ptrdiff_t, T*); | |||
8605 | // T& operator[](ptrdiff_t, T*); [BELOW] | |||
8606 | // | |||
8607 | // C++ [over.built]p14: | |||
8608 | // | |||
8609 | // For every T, where T is a pointer to object type, there | |||
8610 | // exist candidate operator functions of the form | |||
8611 | // | |||
8612 | // ptrdiff_t operator-(T, T); | |||
8613 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { | |||
8614 | /// Set of (canonical) types that we've already handled. | |||
8615 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8616 | ||||
8617 | for (int Arg = 0; Arg < 2; ++Arg) { | |||
8618 | QualType AsymmetricParamTypes[2] = { | |||
8619 | S.Context.getPointerDiffType(), | |||
8620 | S.Context.getPointerDiffType(), | |||
8621 | }; | |||
8622 | for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { | |||
8623 | QualType PointeeTy = PtrTy->getPointeeType(); | |||
8624 | if (!PointeeTy->isObjectType()) | |||
8625 | continue; | |||
8626 | ||||
8627 | AsymmetricParamTypes[Arg] = PtrTy; | |||
8628 | if (Arg == 0 || Op == OO_Plus) { | |||
8629 | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) | |||
8630 | // T* operator+(ptrdiff_t, T*); | |||
8631 | S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); | |||
8632 | } | |||
8633 | if (Op == OO_Minus) { | |||
8634 | // ptrdiff_t operator-(T, T); | |||
8635 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) | |||
8636 | continue; | |||
8637 | ||||
8638 | QualType ParamTypes[2] = {PtrTy, PtrTy}; | |||
8639 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8640 | } | |||
8641 | } | |||
8642 | } | |||
8643 | } | |||
8644 | ||||
8645 | // C++ [over.built]p12: | |||
8646 | // | |||
8647 | // For every pair of promoted arithmetic types L and R, there | |||
8648 | // exist candidate operator functions of the form | |||
8649 | // | |||
8650 | // LR operator*(L, R); | |||
8651 | // LR operator/(L, R); | |||
8652 | // LR operator+(L, R); | |||
8653 | // LR operator-(L, R); | |||
8654 | // bool operator<(L, R); | |||
8655 | // bool operator>(L, R); | |||
8656 | // bool operator<=(L, R); | |||
8657 | // bool operator>=(L, R); | |||
8658 | // bool operator==(L, R); | |||
8659 | // bool operator!=(L, R); | |||
8660 | // | |||
8661 | // where LR is the result of the usual arithmetic conversions | |||
8662 | // between types L and R. | |||
8663 | // | |||
8664 | // C++ [over.built]p24: | |||
8665 | // | |||
8666 | // For every pair of promoted arithmetic types L and R, there exist | |||
8667 | // candidate operator functions of the form | |||
8668 | // | |||
8669 | // LR operator?(bool, L, R); | |||
8670 | // | |||
8671 | // where LR is the result of the usual arithmetic conversions | |||
8672 | // between types L and R. | |||
8673 | // Our candidates ignore the first parameter. | |||
8674 | void addGenericBinaryArithmeticOverloads() { | |||
8675 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8676 | return; | |||
8677 | ||||
8678 | for (unsigned Left = FirstPromotedArithmeticType; | |||
8679 | Left < LastPromotedArithmeticType; ++Left) { | |||
8680 | for (unsigned Right = FirstPromotedArithmeticType; | |||
8681 | Right < LastPromotedArithmeticType; ++Right) { | |||
8682 | QualType LandR[2] = { ArithmeticTypes[Left], | |||
8683 | ArithmeticTypes[Right] }; | |||
8684 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8685 | } | |||
8686 | } | |||
8687 | ||||
8688 | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the | |||
8689 | // conditional operator for vector types. | |||
8690 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) | |||
8691 | for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { | |||
8692 | QualType LandR[2] = {Vec1Ty, Vec2Ty}; | |||
8693 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8694 | } | |||
8695 | } | |||
8696 | ||||
8697 | /// Add binary operator overloads for each candidate matrix type M1, M2: | |||
8698 | /// * (M1, M1) -> M1 | |||
8699 | /// * (M1, M1.getElementType()) -> M1 | |||
8700 | /// * (M2.getElementType(), M2) -> M2 | |||
8701 | /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. | |||
8702 | void addMatrixBinaryArithmeticOverloads() { | |||
8703 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8704 | return; | |||
8705 | ||||
8706 | for (QualType M1 : CandidateTypes[0].matrix_types()) { | |||
8707 | AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); | |||
8708 | AddCandidate(M1, M1); | |||
8709 | } | |||
8710 | ||||
8711 | for (QualType M2 : CandidateTypes[1].matrix_types()) { | |||
8712 | AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); | |||
8713 | if (!CandidateTypes[0].containsMatrixType(M2)) | |||
8714 | AddCandidate(M2, M2); | |||
8715 | } | |||
8716 | } | |||
8717 | ||||
8718 | // C++2a [over.built]p14: | |||
8719 | // | |||
8720 | // For every integral type T there exists a candidate operator function | |||
8721 | // of the form | |||
8722 | // | |||
8723 | // std::strong_ordering operator<=>(T, T) | |||
8724 | // | |||
8725 | // C++2a [over.built]p15: | |||
8726 | // | |||
8727 | // For every pair of floating-point types L and R, there exists a candidate | |||
8728 | // operator function of the form | |||
8729 | // | |||
8730 | // std::partial_ordering operator<=>(L, R); | |||
8731 | // | |||
8732 | // FIXME: The current specification for integral types doesn't play nice with | |||
8733 | // the direction of p0946r0, which allows mixed integral and unscoped-enum | |||
8734 | // comparisons. Under the current spec this can lead to ambiguity during | |||
8735 | // overload resolution. For example: | |||
8736 | // | |||
8737 | // enum A : int {a}; | |||
8738 | // auto x = (a <=> (long)42); | |||
8739 | // | |||
8740 | // error: call is ambiguous for arguments 'A' and 'long'. | |||
8741 | // note: candidate operator<=>(int, int) | |||
8742 | // note: candidate operator<=>(long, long) | |||
8743 | // | |||
8744 | // To avoid this error, this function deviates from the specification and adds | |||
8745 | // the mixed overloads `operator<=>(L, R)` where L and R are promoted | |||
8746 | // arithmetic types (the same as the generic relational overloads). | |||
8747 | // | |||
8748 | // For now this function acts as a placeholder. | |||
8749 | void addThreeWayArithmeticOverloads() { | |||
8750 | addGenericBinaryArithmeticOverloads(); | |||
8751 | } | |||
8752 | ||||
8753 | // C++ [over.built]p17: | |||
8754 | // | |||
8755 | // For every pair of promoted integral types L and R, there | |||
8756 | // exist candidate operator functions of the form | |||
8757 | // | |||
8758 | // LR operator%(L, R); | |||
8759 | // LR operator&(L, R); | |||
8760 | // LR operator^(L, R); | |||
8761 | // LR operator|(L, R); | |||
8762 | // L operator<<(L, R); | |||
8763 | // L operator>>(L, R); | |||
8764 | // | |||
8765 | // where LR is the result of the usual arithmetic conversions | |||
8766 | // between types L and R. | |||
8767 | void addBinaryBitwiseArithmeticOverloads() { | |||
8768 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8769 | return; | |||
8770 | ||||
8771 | for (unsigned Left = FirstPromotedIntegralType; | |||
8772 | Left < LastPromotedIntegralType; ++Left) { | |||
8773 | for (unsigned Right = FirstPromotedIntegralType; | |||
8774 | Right < LastPromotedIntegralType; ++Right) { | |||
8775 | QualType LandR[2] = { ArithmeticTypes[Left], | |||
8776 | ArithmeticTypes[Right] }; | |||
8777 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8778 | } | |||
8779 | } | |||
8780 | } | |||
8781 | ||||
8782 | // C++ [over.built]p20: | |||
8783 | // | |||
8784 | // For every pair (T, VQ), where T is an enumeration or | |||
8785 | // pointer to member type and VQ is either volatile or | |||
8786 | // empty, there exist candidate operator functions of the form | |||
8787 | // | |||
8788 | // VQ T& operator=(VQ T&, T); | |||
8789 | void addAssignmentMemberPointerOrEnumeralOverloads() { | |||
8790 | /// Set of (canonical) types that we've already handled. | |||
8791 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8792 | ||||
8793 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { | |||
8794 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { | |||
8795 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) | |||
8796 | continue; | |||
8797 | ||||
8798 | AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); | |||
8799 | } | |||
8800 | ||||
8801 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { | |||
8802 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) | |||
8803 | continue; | |||
8804 | ||||
8805 | AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); | |||
8806 | } | |||
8807 | } | |||
8808 | } | |||
8809 | ||||
8810 | // C++ [over.built]p19: | |||
8811 | // | |||
8812 | // For every pair (T, VQ), where T is any type and VQ is either | |||
8813 | // volatile or empty, there exist candidate operator functions | |||
8814 | // of the form | |||
8815 | // | |||
8816 | // T*VQ& operator=(T*VQ&, T*); | |||
8817 | // | |||
8818 | // C++ [over.built]p21: | |||
8819 | // | |||
8820 | // For every pair (T, VQ), where T is a cv-qualified or | |||
8821 | // cv-unqualified object type and VQ is either volatile or | |||
8822 | // empty, there exist candidate operator functions of the form | |||
8823 | // | |||
8824 | // T*VQ& operator+=(T*VQ&, ptrdiff_t); | |||
8825 | // T*VQ& operator-=(T*VQ&, ptrdiff_t); | |||
8826 | void addAssignmentPointerOverloads(bool isEqualOp) { | |||
8827 | /// Set of (canonical) types that we've already handled. | |||
8828 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8829 | ||||
8830 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { | |||
8831 | // If this is operator=, keep track of the builtin candidates we added. | |||
8832 | if (isEqualOp) | |||
8833 | AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); | |||
8834 | else if (!PtrTy->getPointeeType()->isObjectType()) | |||
8835 | continue; | |||
8836 | ||||
8837 | // non-volatile version | |||
8838 | QualType ParamTypes[2] = { | |||
8839 | S.Context.getLValueReferenceType(PtrTy), | |||
8840 | isEqualOp ? PtrTy : S.Context.getPointerDiffType(), | |||
8841 | }; | |||
8842 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8843 | /*IsAssignmentOperator=*/ isEqualOp); | |||
8844 | ||||
8845 | bool NeedVolatile = !PtrTy.isVolatileQualified() && | |||
8846 | VisibleTypeConversionsQuals.hasVolatile(); | |||
8847 | if (NeedVolatile) { | |||
8848 | // volatile version | |||
8849 | ParamTypes[0] = | |||
8850 | S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); | |||
8851 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8852 | /*IsAssignmentOperator=*/isEqualOp); | |||
8853 | } | |||
8854 | ||||
8855 | if (!PtrTy.isRestrictQualified() && | |||
8856 | VisibleTypeConversionsQuals.hasRestrict()) { | |||
8857 | // restrict version | |||
8858 | ParamTypes[0] = | |||
8859 | S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); | |||
8860 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8861 | /*IsAssignmentOperator=*/isEqualOp); | |||
8862 | ||||
8863 | if (NeedVolatile) { | |||
8864 | // volatile restrict version | |||
8865 | ParamTypes[0] = | |||
8866 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( | |||
8867 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); | |||
8868 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8869 | /*IsAssignmentOperator=*/isEqualOp); | |||
8870 | } | |||
8871 | } | |||
8872 | } | |||
8873 | ||||
8874 | if (isEqualOp) { | |||
8875 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { | |||
8876 | // Make sure we don't add the same candidate twice. | |||
8877 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) | |||
8878 | continue; | |||
8879 | ||||
8880 | QualType ParamTypes[2] = { | |||
8881 | S.Context.getLValueReferenceType(PtrTy), | |||
8882 | PtrTy, | |||
8883 | }; | |||
8884 | ||||
8885 | // non-volatile version | |||
8886 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8887 | /*IsAssignmentOperator=*/true); | |||
8888 | ||||
8889 | bool NeedVolatile = !PtrTy.isVolatileQualified() && | |||
8890 | VisibleTypeConversionsQuals.hasVolatile(); | |||
8891 | if (NeedVolatile) { | |||
8892 | // volatile version | |||
8893 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
8894 | S.Context.getVolatileType(PtrTy)); | |||
8895 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8896 | /*IsAssignmentOperator=*/true); | |||
8897 | } | |||
8898 | ||||
8899 | if (!PtrTy.isRestrictQualified() && | |||
8900 | VisibleTypeConversionsQuals.hasRestrict()) { | |||
8901 | // restrict version | |||
8902 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
8903 | S.Context.getRestrictType(PtrTy)); | |||
8904 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8905 | /*IsAssignmentOperator=*/true); | |||
8906 | ||||
8907 | if (NeedVolatile) { | |||
8908 | // volatile restrict version | |||
8909 | ParamTypes[0] = | |||
8910 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( | |||
8911 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); | |||
8912 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8913 | /*IsAssignmentOperator=*/true); | |||
8914 | } | |||
8915 | } | |||
8916 | } | |||
8917 | } | |||
8918 | } | |||
8919 | ||||
8920 | // C++ [over.built]p18: | |||
8921 | // | |||
8922 | // For every triple (L, VQ, R), where L is an arithmetic type, | |||
8923 | // VQ is either volatile or empty, and R is a promoted | |||
8924 | // arithmetic type, there exist candidate operator functions of | |||
8925 | // the form | |||
8926 | // | |||
8927 | // VQ L& operator=(VQ L&, R); | |||
8928 | // VQ L& operator*=(VQ L&, R); | |||
8929 | // VQ L& operator/=(VQ L&, R); | |||
8930 | // VQ L& operator+=(VQ L&, R); | |||
8931 | // VQ L& operator-=(VQ L&, R); | |||
8932 | void addAssignmentArithmeticOverloads(bool isEqualOp) { | |||
8933 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8934 | return; | |||
8935 | ||||
8936 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { | |||
8937 | for (unsigned Right = FirstPromotedArithmeticType; | |||
8938 | Right < LastPromotedArithmeticType; ++Right) { | |||
8939 | QualType ParamTypes[2]; | |||
8940 | ParamTypes[1] = ArithmeticTypes[Right]; | |||
8941 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( | |||
8942 | S, ArithmeticTypes[Left], Args[0]); | |||
8943 | // Add this built-in operator as a candidate (VQ is empty). | |||
8944 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); | |||
8945 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8946 | /*IsAssignmentOperator=*/isEqualOp); | |||
8947 | ||||
8948 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
8949 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
8950 | ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); | |||
8951 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
8952 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8953 | /*IsAssignmentOperator=*/isEqualOp); | |||
8954 | } | |||
8955 | } | |||
8956 | } | |||
8957 | ||||
8958 | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. | |||
8959 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) | |||
8960 | for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { | |||
8961 | QualType ParamTypes[2]; | |||
8962 | ParamTypes[1] = Vec2Ty; | |||
8963 | // Add this built-in operator as a candidate (VQ is empty). | |||
8964 | ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); | |||
8965 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8966 | /*IsAssignmentOperator=*/isEqualOp); | |||
8967 | ||||
8968 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
8969 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
8970 | ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); | |||
8971 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
8972 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8973 | /*IsAssignmentOperator=*/isEqualOp); | |||
8974 | } | |||
8975 | } | |||
8976 | } | |||
8977 | ||||
8978 | // C++ [over.built]p22: | |||
8979 | // | |||
8980 | // For every triple (L, VQ, R), where L is an integral type, VQ | |||
8981 | // is either volatile or empty, and R is a promoted integral | |||
8982 | // type, there exist candidate operator functions of the form | |||
8983 | // | |||
8984 | // VQ L& operator%=(VQ L&, R); | |||
8985 | // VQ L& operator<<=(VQ L&, R); | |||
8986 | // VQ L& operator>>=(VQ L&, R); | |||
8987 | // VQ L& operator&=(VQ L&, R); | |||
8988 | // VQ L& operator^=(VQ L&, R); | |||
8989 | // VQ L& operator|=(VQ L&, R); | |||
8990 | void addAssignmentIntegralOverloads() { | |||
8991 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8992 | return; | |||
8993 | ||||
8994 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { | |||
8995 | for (unsigned Right = FirstPromotedIntegralType; | |||
8996 | Right < LastPromotedIntegralType; ++Right) { | |||
8997 | QualType ParamTypes[2]; | |||
8998 | ParamTypes[1] = ArithmeticTypes[Right]; | |||
8999 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( | |||
9000 | S, ArithmeticTypes[Left], Args[0]); | |||
9001 | // Add this built-in operator as a candidate (VQ is empty). | |||
9002 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); | |||
9003 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9004 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
9005 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
9006 | ParamTypes[0] = LeftBaseTy; | |||
9007 | ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); | |||
9008 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
9009 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9010 | } | |||
9011 | } | |||
9012 | } | |||
9013 | } | |||
9014 | ||||
9015 | // C++ [over.operator]p23: | |||
9016 | // | |||
9017 | // There also exist candidate operator functions of the form | |||
9018 | // | |||
9019 | // bool operator!(bool); | |||
9020 | // bool operator&&(bool, bool); | |||
9021 | // bool operator||(bool, bool); | |||
9022 | void addExclaimOverload() { | |||
9023 | QualType ParamTy = S.Context.BoolTy; | |||
9024 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, | |||
9025 | /*IsAssignmentOperator=*/false, | |||
9026 | /*NumContextualBoolArguments=*/1); | |||
9027 | } | |||
9028 | void addAmpAmpOrPipePipeOverload() { | |||
9029 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; | |||
9030 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
9031 | /*IsAssignmentOperator=*/false, | |||
9032 | /*NumContextualBoolArguments=*/2); | |||
9033 | } | |||
9034 | ||||
9035 | // C++ [over.built]p13: | |||
9036 | // | |||
9037 | // For every cv-qualified or cv-unqualified object type T there | |||
9038 | // exist candidate operator functions of the form | |||
9039 | // | |||
9040 | // T* operator+(T*, ptrdiff_t); [ABOVE] | |||
9041 | // T& operator[](T*, ptrdiff_t); | |||
9042 | // T* operator-(T*, ptrdiff_t); [ABOVE] | |||
9043 | // T* operator+(ptrdiff_t, T*); [ABOVE] | |||
9044 | // T& operator[](ptrdiff_t, T*); | |||
9045 | void addSubscriptOverloads() { | |||
9046 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { | |||
9047 | QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; | |||
9048 | QualType PointeeType = PtrTy->getPointeeType(); | |||
9049 | if (!PointeeType->isObjectType()) | |||
9050 | continue; | |||
9051 | ||||
9052 | // T& operator[](T*, ptrdiff_t) | |||
9053 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9054 | } | |||
9055 | ||||
9056 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { | |||
9057 | QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; | |||
9058 | QualType PointeeType = PtrTy->getPointeeType(); | |||
9059 | if (!PointeeType->isObjectType()) | |||
9060 | continue; | |||
9061 | ||||
9062 | // T& operator[](ptrdiff_t, T*) | |||
9063 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9064 | } | |||
9065 | } | |||
9066 | ||||
9067 | // C++ [over.built]p11: | |||
9068 | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, | |||
9069 | // C1 is the same type as C2 or is a derived class of C2, T is an object | |||
9070 | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, | |||
9071 | // there exist candidate operator functions of the form | |||
9072 | // | |||
9073 | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); | |||
9074 | // | |||
9075 | // where CV12 is the union of CV1 and CV2. | |||
9076 | void addArrowStarOverloads() { | |||
9077 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { | |||
9078 | QualType C1Ty = PtrTy; | |||
9079 | QualType C1; | |||
9080 | QualifierCollector Q1; | |||
9081 | C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); | |||
9082 | if (!isa<RecordType>(C1)) | |||
9083 | continue; | |||
9084 | // heuristic to reduce number of builtin candidates in the set. | |||
9085 | // Add volatile/restrict version only if there are conversions to a | |||
9086 | // volatile/restrict type. | |||
9087 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) | |||
9088 | continue; | |||
9089 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) | |||
9090 | continue; | |||
9091 | for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { | |||
9092 | const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); | |||
9093 | QualType C2 = QualType(mptr->getClass(), 0); | |||
9094 | C2 = C2.getUnqualifiedType(); | |||
9095 | if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) | |||
9096 | break; | |||
9097 | QualType ParamTypes[2] = {PtrTy, MemPtrTy}; | |||
9098 | // build CV12 T& | |||
9099 | QualType T = mptr->getPointeeType(); | |||
9100 | if (!VisibleTypeConversionsQuals.hasVolatile() && | |||
9101 | T.isVolatileQualified()) | |||
9102 | continue; | |||
9103 | if (!VisibleTypeConversionsQuals.hasRestrict() && | |||
9104 | T.isRestrictQualified()) | |||
9105 | continue; | |||
9106 | T = Q1.apply(S.Context, T); | |||
9107 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9108 | } | |||
9109 | } | |||
9110 | } | |||
9111 | ||||
9112 | // Note that we don't consider the first argument, since it has been | |||
9113 | // contextually converted to bool long ago. The candidates below are | |||
9114 | // therefore added as binary. | |||
9115 | // | |||
9116 | // C++ [over.built]p25: | |||
9117 | // For every type T, where T is a pointer, pointer-to-member, or scoped | |||
9118 | // enumeration type, there exist candidate operator functions of the form | |||
9119 | // | |||
9120 | // T operator?(bool, T, T); | |||
9121 | // | |||
9122 | void addConditionalOperatorOverloads() { | |||
9123 | /// Set of (canonical) types that we've already handled. | |||
9124 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
9125 | ||||
9126 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { | |||
9127 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { | |||
9128 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) | |||
9129 | continue; | |||
9130 | ||||
9131 | QualType ParamTypes[2] = {PtrTy, PtrTy}; | |||
9132 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9133 | } | |||
9134 | ||||
9135 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { | |||
9136 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) | |||
9137 | continue; | |||
9138 | ||||
9139 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; | |||
9140 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9141 | } | |||
9142 | ||||
9143 | if (S.getLangOpts().CPlusPlus11) { | |||
9144 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { | |||
9145 | if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) | |||
9146 | continue; | |||
9147 | ||||
9148 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) | |||
9149 | continue; | |||
9150 | ||||
9151 | QualType ParamTypes[2] = {EnumTy, EnumTy}; | |||
9152 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
9153 | } | |||
9154 | } | |||
9155 | } | |||
9156 | } | |||
9157 | }; | |||
9158 | ||||
9159 | } // end anonymous namespace | |||
9160 | ||||
9161 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in | |||
9162 | /// operator overloads to the candidate set (C++ [over.built]), based | |||
9163 | /// on the operator @p Op and the arguments given. For example, if the | |||
9164 | /// operator is a binary '+', this routine might add "int | |||
9165 | /// operator+(int, int)" to cover integer addition. | |||
9166 | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, | |||
9167 | SourceLocation OpLoc, | |||
9168 | ArrayRef<Expr *> Args, | |||
9169 | OverloadCandidateSet &CandidateSet) { | |||
9170 | // Find all of the types that the arguments can convert to, but only | |||
9171 | // if the operator we're looking at has built-in operator candidates | |||
9172 | // that make use of these types. Also record whether we encounter non-record | |||
9173 | // candidate types or either arithmetic or enumeral candidate types. | |||
9174 | Qualifiers VisibleTypeConversionsQuals; | |||
9175 | VisibleTypeConversionsQuals.addConst(); | |||
9176 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) | |||
9177 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); | |||
9178 | ||||
9179 | bool HasNonRecordCandidateType = false; | |||
9180 | bool HasArithmeticOrEnumeralCandidateType = false; | |||
9181 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; | |||
9182 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
9183 | CandidateTypes.emplace_back(*this); | |||
9184 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), | |||
9185 | OpLoc, | |||
9186 | true, | |||
9187 | (Op == OO_Exclaim || | |||
9188 | Op == OO_AmpAmp || | |||
9189 | Op == OO_PipePipe), | |||
9190 | VisibleTypeConversionsQuals); | |||
9191 | HasNonRecordCandidateType = HasNonRecordCandidateType || | |||
9192 | CandidateTypes[ArgIdx].hasNonRecordTypes(); | |||
9193 | HasArithmeticOrEnumeralCandidateType = | |||
9194 | HasArithmeticOrEnumeralCandidateType || | |||
9195 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); | |||
9196 | } | |||
9197 | ||||
9198 | // Exit early when no non-record types have been added to the candidate set | |||
9199 | // for any of the arguments to the operator. | |||
9200 | // | |||
9201 | // We can't exit early for !, ||, or &&, since there we have always have | |||
9202 | // 'bool' overloads. | |||
9203 | if (!HasNonRecordCandidateType && | |||
9204 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) | |||
9205 | return; | |||
9206 | ||||
9207 | // Setup an object to manage the common state for building overloads. | |||
9208 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, | |||
9209 | VisibleTypeConversionsQuals, | |||
9210 | HasArithmeticOrEnumeralCandidateType, | |||
9211 | CandidateTypes, CandidateSet); | |||
9212 | ||||
9213 | // Dispatch over the operation to add in only those overloads which apply. | |||
9214 | switch (Op) { | |||
9215 | case OO_None: | |||
9216 | case NUM_OVERLOADED_OPERATORS: | |||
9217 | llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator" , "clang/lib/Sema/SemaOverload.cpp", 9217); | |||
9218 | ||||
9219 | case OO_New: | |||
9220 | case OO_Delete: | |||
9221 | case OO_Array_New: | |||
9222 | case OO_Array_Delete: | |||
9223 | case OO_Call: | |||
9224 | llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "clang/lib/Sema/SemaOverload.cpp", 9225) | |||
9225 | "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "clang/lib/Sema/SemaOverload.cpp", 9225); | |||
9226 | ||||
9227 | case OO_Comma: | |||
9228 | case OO_Arrow: | |||
9229 | case OO_Coawait: | |||
9230 | // C++ [over.match.oper]p3: | |||
9231 | // -- For the operator ',', the unary operator '&', the | |||
9232 | // operator '->', or the operator 'co_await', the | |||
9233 | // built-in candidates set is empty. | |||
9234 | break; | |||
9235 | ||||
9236 | case OO_Plus: // '+' is either unary or binary | |||
9237 | if (Args.size() == 1) | |||
9238 | OpBuilder.addUnaryPlusPointerOverloads(); | |||
9239 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
9240 | ||||
9241 | case OO_Minus: // '-' is either unary or binary | |||
9242 | if (Args.size() == 1) { | |||
9243 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); | |||
9244 | } else { | |||
9245 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); | |||
9246 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9247 | OpBuilder.addMatrixBinaryArithmeticOverloads(); | |||
9248 | } | |||
9249 | break; | |||
9250 | ||||
9251 | case OO_Star: // '*' is either unary or binary | |||
9252 | if (Args.size() == 1) | |||
9253 | OpBuilder.addUnaryStarPointerOverloads(); | |||
9254 | else { | |||
9255 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9256 | OpBuilder.addMatrixBinaryArithmeticOverloads(); | |||
9257 | } | |||
9258 | break; | |||
9259 | ||||
9260 | case OO_Slash: | |||
9261 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9262 | break; | |||
9263 | ||||
9264 | case OO_PlusPlus: | |||
9265 | case OO_MinusMinus: | |||
9266 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); | |||
9267 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); | |||
9268 | break; | |||
9269 | ||||
9270 | case OO_EqualEqual: | |||
9271 | case OO_ExclaimEqual: | |||
9272 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); | |||
9273 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); | |||
9274 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9275 | break; | |||
9276 | ||||
9277 | case OO_Less: | |||
9278 | case OO_Greater: | |||
9279 | case OO_LessEqual: | |||
9280 | case OO_GreaterEqual: | |||
9281 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); | |||
9282 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9283 | break; | |||
9284 | ||||
9285 | case OO_Spaceship: | |||
9286 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); | |||
9287 | OpBuilder.addThreeWayArithmeticOverloads(); | |||
9288 | break; | |||
9289 | ||||
9290 | case OO_Percent: | |||
9291 | case OO_Caret: | |||
9292 | case OO_Pipe: | |||
9293 | case OO_LessLess: | |||
9294 | case OO_GreaterGreater: | |||
9295 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); | |||
9296 | break; | |||
9297 | ||||
9298 | case OO_Amp: // '&' is either unary or binary | |||
9299 | if (Args.size() == 1) | |||
9300 | // C++ [over.match.oper]p3: | |||
9301 | // -- For the operator ',', the unary operator '&', or the | |||
9302 | // operator '->', the built-in candidates set is empty. | |||
9303 | break; | |||
9304 | ||||
9305 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); | |||
9306 | break; | |||
9307 | ||||
9308 | case OO_Tilde: | |||
9309 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); | |||
9310 | break; | |||
9311 | ||||
9312 | case OO_Equal: | |||
9313 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); | |||
9314 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
9315 | ||||
9316 | case OO_PlusEqual: | |||
9317 | case OO_MinusEqual: | |||
9318 | OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); | |||
9319 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
9320 | ||||
9321 | case OO_StarEqual: | |||
9322 | case OO_SlashEqual: | |||
9323 | OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); | |||
9324 | break; | |||
9325 | ||||
9326 | case OO_PercentEqual: | |||
9327 | case OO_LessLessEqual: | |||
9328 | case OO_GreaterGreaterEqual: | |||
9329 | case OO_AmpEqual: | |||
9330 | case OO_CaretEqual: | |||
9331 | case OO_PipeEqual: | |||
9332 | OpBuilder.addAssignmentIntegralOverloads(); | |||
9333 | break; | |||
9334 | ||||
9335 | case OO_Exclaim: | |||
9336 | OpBuilder.addExclaimOverload(); | |||
9337 | break; | |||
9338 | ||||
9339 | case OO_AmpAmp: | |||
9340 | case OO_PipePipe: | |||
9341 | OpBuilder.addAmpAmpOrPipePipeOverload(); | |||
9342 | break; | |||
9343 | ||||
9344 | case OO_Subscript: | |||
9345 | if (Args.size() == 2) | |||
9346 | OpBuilder.addSubscriptOverloads(); | |||
9347 | break; | |||
9348 | ||||
9349 | case OO_ArrowStar: | |||
9350 | OpBuilder.addArrowStarOverloads(); | |||
9351 | break; | |||
9352 | ||||
9353 | case OO_Conditional: | |||
9354 | OpBuilder.addConditionalOperatorOverloads(); | |||
9355 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
9356 | break; | |||
9357 | } | |||
9358 | } | |||
9359 | ||||
9360 | /// Add function candidates found via argument-dependent lookup | |||
9361 | /// to the set of overloading candidates. | |||
9362 | /// | |||
9363 | /// This routine performs argument-dependent name lookup based on the | |||
9364 | /// given function name (which may also be an operator name) and adds | |||
9365 | /// all of the overload candidates found by ADL to the overload | |||
9366 | /// candidate set (C++ [basic.lookup.argdep]). | |||
9367 | void | |||
9368 | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, | |||
9369 | SourceLocation Loc, | |||
9370 | ArrayRef<Expr *> Args, | |||
9371 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
9372 | OverloadCandidateSet& CandidateSet, | |||
9373 | bool PartialOverloading) { | |||
9374 | ADLResult Fns; | |||
9375 | ||||
9376 | // FIXME: This approach for uniquing ADL results (and removing | |||
9377 | // redundant candidates from the set) relies on pointer-equality, | |||
9378 | // which means we need to key off the canonical decl. However, | |||
9379 | // always going back to the canonical decl might not get us the | |||
9380 | // right set of default arguments. What default arguments are | |||
9381 | // we supposed to consider on ADL candidates, anyway? | |||
9382 | ||||
9383 | // FIXME: Pass in the explicit template arguments? | |||
9384 | ArgumentDependentLookup(Name, Loc, Args, Fns); | |||
9385 | ||||
9386 | // Erase all of the candidates we already knew about. | |||
9387 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), | |||
9388 | CandEnd = CandidateSet.end(); | |||
9389 | Cand != CandEnd; ++Cand) | |||
9390 | if (Cand->Function) { | |||
9391 | Fns.erase(Cand->Function); | |||
9392 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) | |||
9393 | Fns.erase(FunTmpl); | |||
9394 | } | |||
9395 | ||||
9396 | // For each of the ADL candidates we found, add it to the overload | |||
9397 | // set. | |||
9398 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { | |||
9399 | DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); | |||
9400 | ||||
9401 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { | |||
9402 | if (ExplicitTemplateArgs) | |||
9403 | continue; | |||
9404 | ||||
9405 | AddOverloadCandidate( | |||
9406 | FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, | |||
9407 | PartialOverloading, /*AllowExplicit=*/true, | |||
9408 | /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); | |||
9409 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { | |||
9410 | AddOverloadCandidate( | |||
9411 | FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, | |||
9412 | /*SuppressUserConversions=*/false, PartialOverloading, | |||
9413 | /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, | |||
9414 | ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); | |||
9415 | } | |||
9416 | } else { | |||
9417 | auto *FTD = cast<FunctionTemplateDecl>(*I); | |||
9418 | AddTemplateOverloadCandidate( | |||
9419 | FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, | |||
9420 | /*SuppressUserConversions=*/false, PartialOverloading, | |||
9421 | /*AllowExplicit=*/true, ADLCallKind::UsesADL); | |||
9422 | if (CandidateSet.getRewriteInfo().shouldAddReversed( | |||
9423 | Context, FTD->getTemplatedDecl())) { | |||
9424 | AddTemplateOverloadCandidate( | |||
9425 | FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, | |||
9426 | CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, | |||
9427 | /*AllowExplicit=*/true, ADLCallKind::UsesADL, | |||
9428 | OverloadCandidateParamOrder::Reversed); | |||
9429 | } | |||
9430 | } | |||
9431 | } | |||
9432 | } | |||
9433 | ||||
9434 | namespace { | |||
9435 | enum class Comparison { Equal, Better, Worse }; | |||
9436 | } | |||
9437 | ||||
9438 | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of | |||
9439 | /// overload resolution. | |||
9440 | /// | |||
9441 | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff | |||
9442 | /// Cand1's first N enable_if attributes have precisely the same conditions as | |||
9443 | /// Cand2's first N enable_if attributes (where N = the number of enable_if | |||
9444 | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. | |||
9445 | /// | |||
9446 | /// Note that you can have a pair of candidates such that Cand1's enable_if | |||
9447 | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are | |||
9448 | /// worse than Cand1's. | |||
9449 | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, | |||
9450 | const FunctionDecl *Cand2) { | |||
9451 | // Common case: One (or both) decls don't have enable_if attrs. | |||
9452 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); | |||
9453 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); | |||
9454 | if (!Cand1Attr || !Cand2Attr) { | |||
9455 | if (Cand1Attr == Cand2Attr) | |||
9456 | return Comparison::Equal; | |||
9457 | return Cand1Attr ? Comparison::Better : Comparison::Worse; | |||
9458 | } | |||
9459 | ||||
9460 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); | |||
9461 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); | |||
9462 | ||||
9463 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; | |||
9464 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { | |||
9465 | Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); | |||
9466 | Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); | |||
9467 | ||||
9468 | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 | |||
9469 | // has fewer enable_if attributes than Cand2, and vice versa. | |||
9470 | if (!Cand1A) | |||
9471 | return Comparison::Worse; | |||
9472 | if (!Cand2A) | |||
9473 | return Comparison::Better; | |||
9474 | ||||
9475 | Cand1ID.clear(); | |||
9476 | Cand2ID.clear(); | |||
9477 | ||||
9478 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); | |||
9479 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); | |||
9480 | if (Cand1ID != Cand2ID) | |||
9481 | return Comparison::Worse; | |||
9482 | } | |||
9483 | ||||
9484 | return Comparison::Equal; | |||
9485 | } | |||
9486 | ||||
9487 | static Comparison | |||
9488 | isBetterMultiversionCandidate(const OverloadCandidate &Cand1, | |||
9489 | const OverloadCandidate &Cand2) { | |||
9490 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || | |||
9491 | !Cand2.Function->isMultiVersion()) | |||
9492 | return Comparison::Equal; | |||
9493 | ||||
9494 | // If both are invalid, they are equal. If one of them is invalid, the other | |||
9495 | // is better. | |||
9496 | if (Cand1.Function->isInvalidDecl()) { | |||
9497 | if (Cand2.Function->isInvalidDecl()) | |||
9498 | return Comparison::Equal; | |||
9499 | return Comparison::Worse; | |||
9500 | } | |||
9501 | if (Cand2.Function->isInvalidDecl()) | |||
9502 | return Comparison::Better; | |||
9503 | ||||
9504 | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer | |||
9505 | // cpu_dispatch, else arbitrarily based on the identifiers. | |||
9506 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); | |||
9507 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); | |||
9508 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); | |||
9509 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); | |||
9510 | ||||
9511 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) | |||
9512 | return Comparison::Equal; | |||
9513 | ||||
9514 | if (Cand1CPUDisp && !Cand2CPUDisp) | |||
9515 | return Comparison::Better; | |||
9516 | if (Cand2CPUDisp && !Cand1CPUDisp) | |||
9517 | return Comparison::Worse; | |||
9518 | ||||
9519 | if (Cand1CPUSpec && Cand2CPUSpec) { | |||
9520 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) | |||
9521 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() | |||
9522 | ? Comparison::Better | |||
9523 | : Comparison::Worse; | |||
9524 | ||||
9525 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> | |||
9526 | FirstDiff = std::mismatch( | |||
9527 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), | |||
9528 | Cand2CPUSpec->cpus_begin(), | |||
9529 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { | |||
9530 | return LHS->getName() == RHS->getName(); | |||
9531 | }); | |||
9532 | ||||
9533 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9535, __extension__ __PRETTY_FUNCTION__ )) | |||
9534 | "Two different cpu-specific versions should not have the same "(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9535, __extension__ __PRETTY_FUNCTION__ )) | |||
9535 | "identifier list, otherwise they'd be the same decl!")(static_cast <bool> (FirstDiff.first != Cand1CPUSpec-> cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? void (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "clang/lib/Sema/SemaOverload.cpp", 9535, __extension__ __PRETTY_FUNCTION__ )); | |||
9536 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() | |||
9537 | ? Comparison::Better | |||
9538 | : Comparison::Worse; | |||
9539 | } | |||
9540 | llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch" , "clang/lib/Sema/SemaOverload.cpp", 9540); | |||
9541 | } | |||
9542 | ||||
9543 | /// Compute the type of the implicit object parameter for the given function, | |||
9544 | /// if any. Returns None if there is no implicit object parameter, and a null | |||
9545 | /// QualType if there is a 'matches anything' implicit object parameter. | |||
9546 | static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, | |||
9547 | const FunctionDecl *F) { | |||
9548 | if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) | |||
9549 | return llvm::None; | |||
9550 | ||||
9551 | auto *M = cast<CXXMethodDecl>(F); | |||
9552 | // Static member functions' object parameters match all types. | |||
9553 | if (M->isStatic()) | |||
9554 | return QualType(); | |||
9555 | ||||
9556 | QualType T = M->getThisObjectType(); | |||
9557 | if (M->getRefQualifier() == RQ_RValue) | |||
9558 | return Context.getRValueReferenceType(T); | |||
9559 | return Context.getLValueReferenceType(T); | |||
9560 | } | |||
9561 | ||||
9562 | static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, | |||
9563 | const FunctionDecl *F2, unsigned NumParams) { | |||
9564 | if (declaresSameEntity(F1, F2)) | |||
9565 | return true; | |||
9566 | ||||
9567 | auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { | |||
9568 | if (First) { | |||
9569 | if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) | |||
9570 | return *T; | |||
9571 | } | |||
9572 | assert(I < F->getNumParams())(static_cast <bool> (I < F->getNumParams()) ? void (0) : __assert_fail ("I < F->getNumParams()", "clang/lib/Sema/SemaOverload.cpp" , 9572, __extension__ __PRETTY_FUNCTION__)); | |||
9573 | return F->getParamDecl(I++)->getType(); | |||
9574 | }; | |||
9575 | ||||
9576 | unsigned I1 = 0, I2 = 0; | |||
9577 | for (unsigned I = 0; I != NumParams; ++I) { | |||
9578 | QualType T1 = NextParam(F1, I1, I == 0); | |||
9579 | QualType T2 = NextParam(F2, I2, I == 0); | |||
9580 | assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types")(static_cast <bool> (!T1.isNull() && !T2.isNull () && "Unexpected null param types") ? void (0) : __assert_fail ("!T1.isNull() && !T2.isNull() && \"Unexpected null param types\"" , "clang/lib/Sema/SemaOverload.cpp", 9580, __extension__ __PRETTY_FUNCTION__ )); | |||
9581 | if (!Context.hasSameUnqualifiedType(T1, T2)) | |||
9582 | return false; | |||
9583 | } | |||
9584 | return true; | |||
9585 | } | |||
9586 | ||||
9587 | /// isBetterOverloadCandidate - Determines whether the first overload | |||
9588 | /// candidate is a better candidate than the second (C++ 13.3.3p1). | |||
9589 | bool clang::isBetterOverloadCandidate( | |||
9590 | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, | |||
9591 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { | |||
9592 | // Define viable functions to be better candidates than non-viable | |||
9593 | // functions. | |||
9594 | if (!Cand2.Viable) | |||
| ||||
9595 | return Cand1.Viable; | |||
9596 | else if (!Cand1.Viable) | |||
9597 | return false; | |||
9598 | ||||
9599 | // [CUDA] A function with 'never' preference is marked not viable, therefore | |||
9600 | // is never shown up here. The worst preference shown up here is 'wrong side', | |||
9601 | // e.g. an H function called by a HD function in device compilation. This is | |||
9602 | // valid AST as long as the HD function is not emitted, e.g. it is an inline | |||
9603 | // function which is called only by an H function. A deferred diagnostic will | |||
9604 | // be triggered if it is emitted. However a wrong-sided function is still | |||
9605 | // a viable candidate here. | |||
9606 | // | |||
9607 | // If Cand1 can be emitted and Cand2 cannot be emitted in the current | |||
9608 | // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 | |||
9609 | // can be emitted, Cand1 is not better than Cand2. This rule should have | |||
9610 | // precedence over other rules. | |||
9611 | // | |||
9612 | // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then | |||
9613 | // other rules should be used to determine which is better. This is because | |||
9614 | // host/device based overloading resolution is mostly for determining | |||
9615 | // viability of a function. If two functions are both viable, other factors | |||
9616 | // should take precedence in preference, e.g. the standard-defined preferences | |||
9617 | // like argument conversion ranks or enable_if partial-ordering. The | |||
9618 | // preference for pass-object-size parameters is probably most similar to a | |||
9619 | // type-based-overloading decision and so should take priority. | |||
9620 | // | |||
9621 | // If other rules cannot determine which is better, CUDA preference will be | |||
9622 | // used again to determine which is better. | |||
9623 | // | |||
9624 | // TODO: Currently IdentifyCUDAPreference does not return correct values | |||
9625 | // for functions called in global variable initializers due to missing | |||
9626 | // correct context about device/host. Therefore we can only enforce this | |||
9627 | // rule when there is a caller. We should enforce this rule for functions | |||
9628 | // in global variable initializers once proper context is added. | |||
9629 | // | |||
9630 | // TODO: We can only enable the hostness based overloading resolution when | |||
9631 | // -fgpu-exclude-wrong-side-overloads is on since this requires deferring | |||
9632 | // overloading resolution diagnostics. | |||
9633 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && | |||
9634 | S.getLangOpts().GPUExcludeWrongSideOverloads) { | |||
9635 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { | |||
9636 | bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); | |||
9637 | bool IsCand1ImplicitHD = | |||
9638 | Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); | |||
9639 | bool IsCand2ImplicitHD = | |||
9640 | Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); | |||
9641 | auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); | |||
9642 | auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); | |||
9643 | assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)(static_cast <bool> (P1 != Sema::CFP_Never && P2 != Sema::CFP_Never) ? void (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never" , "clang/lib/Sema/SemaOverload.cpp", 9643, __extension__ __PRETTY_FUNCTION__ )); | |||
9644 | // The implicit HD function may be a function in a system header which | |||
9645 | // is forced by pragma. In device compilation, if we prefer HD candidates | |||
9646 | // over wrong-sided candidates, overloading resolution may change, which | |||
9647 | // may result in non-deferrable diagnostics. As a workaround, we let | |||
9648 | // implicit HD candidates take equal preference as wrong-sided candidates. | |||
9649 | // This will preserve the overloading resolution. | |||
9650 | // TODO: We still need special handling of implicit HD functions since | |||
9651 | // they may incur other diagnostics to be deferred. We should make all | |||
9652 | // host/device related diagnostics deferrable and remove special handling | |||
9653 | // of implicit HD functions. | |||
9654 | auto EmitThreshold = | |||
9655 | (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && | |||
9656 | (IsCand1ImplicitHD || IsCand2ImplicitHD)) | |||
9657 | ? Sema::CFP_Never | |||
9658 | : Sema::CFP_WrongSide; | |||
9659 | auto Cand1Emittable = P1 > EmitThreshold; | |||
9660 | auto Cand2Emittable = P2 > EmitThreshold; | |||
9661 | if (Cand1Emittable && !Cand2Emittable) | |||
9662 | return true; | |||
9663 | if (!Cand1Emittable && Cand2Emittable) | |||
9664 | return false; | |||
9665 | } | |||
9666 | } | |||
9667 | ||||
9668 | // C++ [over.match.best]p1: | |||
9669 | // | |||
9670 | // -- if F is a static member function, ICS1(F) is defined such | |||
9671 | // that ICS1(F) is neither better nor worse than ICS1(G) for | |||
9672 | // any function G, and, symmetrically, ICS1(G) is neither | |||
9673 | // better nor worse than ICS1(F). | |||
9674 | unsigned StartArg = 0; | |||
9675 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) | |||
9676 | StartArg = 1; | |||
9677 | ||||
9678 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { | |||
9679 | // We don't allow incompatible pointer conversions in C++. | |||
9680 | if (!S.getLangOpts().CPlusPlus) | |||
9681 | return ICS.isStandard() && | |||
9682 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; | |||
9683 | ||||
9684 | // The only ill-formed conversion we allow in C++ is the string literal to | |||
9685 | // char* conversion, which is only considered ill-formed after C++11. | |||
9686 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && | |||
9687 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); | |||
9688 | }; | |||
9689 | ||||
9690 | // Define functions that don't require ill-formed conversions for a given | |||
9691 | // argument to be better candidates than functions that do. | |||
9692 | unsigned NumArgs = Cand1.Conversions.size(); | |||
9693 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast <bool> (Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch") ? void (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\"" , "clang/lib/Sema/SemaOverload.cpp", 9693, __extension__ __PRETTY_FUNCTION__ )); | |||
9694 | bool HasBetterConversion = false; | |||
9695 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { | |||
9696 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); | |||
9697 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); | |||
9698 | if (Cand1Bad != Cand2Bad) { | |||
9699 | if (Cand1Bad) | |||
9700 | return false; | |||
9701 | HasBetterConversion = true; | |||
9702 | } | |||
9703 | } | |||
9704 | ||||
9705 | if (HasBetterConversion
| |||
9706 | return true; | |||
9707 | ||||
9708 | // C++ [over.match.best]p1: | |||
9709 | // A viable function F1 is defined to be a better function than another | |||
9710 | // viable function F2 if for all arguments i, ICSi(F1) is not a worse | |||
9711 | // conversion sequence than ICSi(F2), and then... | |||
9712 | bool HasWorseConversion = false; | |||
9713 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { | |||
9714 | switch (CompareImplicitConversionSequences(S, Loc, | |||
9715 | Cand1.Conversions[ArgIdx], | |||
9716 | Cand2.Conversions[ArgIdx])) { | |||
9717 | case ImplicitConversionSequence::Better: | |||
9718 | // Cand1 has a better conversion sequence. | |||
9719 | HasBetterConversion = true; | |||
9720 | break; | |||
9721 | ||||
9722 | case ImplicitConversionSequence::Worse: | |||
9723 | if (Cand1.Function && Cand2.Function && | |||
9724 | Cand1.isReversed() != Cand2.isReversed() && | |||
9725 | haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, | |||
9726 | NumArgs)) { | |||
9727 | // Work around large-scale breakage caused by considering reversed | |||
9728 | // forms of operator== in C++20: | |||
9729 | // | |||
9730 | // When comparing a function against a reversed function with the same | |||
9731 | // parameter types, if we have a better conversion for one argument and | |||
9732 | // a worse conversion for the other, the implicit conversion sequences | |||
9733 | // are treated as being equally good. | |||
9734 | // | |||
9735 | // This prevents a comparison function from being considered ambiguous | |||
9736 | // with a reversed form that is written in the same way. | |||
9737 | // | |||
9738 | // We diagnose this as an extension from CreateOverloadedBinOp. | |||
9739 | HasWorseConversion = true; | |||
9740 | break; | |||
9741 | } | |||
9742 | ||||
9743 | // Cand1 can't be better than Cand2. | |||
9744 | return false; | |||
9745 | ||||
9746 | case ImplicitConversionSequence::Indistinguishable: | |||
9747 | // Do nothing. | |||
9748 | break; | |||
9749 | } | |||
9750 | } | |||
9751 | ||||
9752 | // -- for some argument j, ICSj(F1) is a better conversion sequence than | |||
9753 | // ICSj(F2), or, if not that, | |||
9754 | if (HasBetterConversion
| |||
9755 | return true; | |||
9756 | ||||
9757 | // -- the context is an initialization by user-defined conversion | |||
9758 | // (see 8.5, 13.3.1.5) and the standard conversion sequence | |||
9759 | // from the return type of F1 to the destination type (i.e., | |||
9760 | // the type of the entity being initialized) is a better | |||
9761 | // conversion sequence than the standard conversion sequence | |||
9762 | // from the return type of F2 to the destination type. | |||
9763 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && | |||
9764 | Cand1.Function && Cand2.Function && | |||
9765 | isa<CXXConversionDecl>(Cand1.Function) && | |||
9766 | isa<CXXConversionDecl>(Cand2.Function)) { | |||
9767 | // First check whether we prefer one of the conversion functions over the | |||
9768 | // other. This only distinguishes the results in non-standard, extension | |||
9769 | // cases such as the conversion from a lambda closure type to a function | |||
9770 | // pointer or block. | |||
9771 | ImplicitConversionSequence::CompareKind Result = | |||
9772 | compareConversionFunctions(S, Cand1.Function, Cand2.Function); | |||
9773 | if (Result == ImplicitConversionSequence::Indistinguishable) | |||
9774 | Result = CompareStandardConversionSequences(S, Loc, | |||
9775 | Cand1.FinalConversion, | |||
9776 | Cand2.FinalConversion); | |||
9777 | ||||
9778 | if (Result != ImplicitConversionSequence::Indistinguishable) | |||
9779 | return Result == ImplicitConversionSequence::Better; | |||
9780 | ||||
9781 | // FIXME: Compare kind of reference binding if conversion functions | |||
9782 | // convert to a reference type used in direct reference binding, per | |||
9783 | // C++14 [over.match.best]p1 section 2 bullet 3. | |||
9784 | } | |||
9785 | ||||
9786 | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, | |||
9787 | // as combined with the resolution to CWG issue 243. | |||
9788 | // | |||
9789 | // When the context is initialization by constructor ([over.match.ctor] or | |||
9790 | // either phase of [over.match.list]), a constructor is preferred over | |||
9791 | // a conversion function. | |||
9792 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && | |||
9793 | Cand1.Function && Cand2.Function && | |||
9794 | isa<CXXConstructorDecl>(Cand1.Function) != | |||
9795 | isa<CXXConstructorDecl>(Cand2.Function)) | |||
9796 | return isa<CXXConstructorDecl>(Cand1.Function); | |||
9797 | ||||
9798 | // -- F1 is a non-template function and F2 is a function template | |||
9799 | // specialization, or, if not that, | |||
9800 | bool Cand1IsSpecialization = Cand1.Function && | |||
9801 | Cand1.Function->getPrimaryTemplate(); | |||
9802 | bool Cand2IsSpecialization = Cand2.Function && | |||
9803 | Cand2.Function->getPrimaryTemplate(); | |||
9804 | if (Cand1IsSpecialization
| |||
9805 | return Cand2IsSpecialization; | |||
9806 | ||||
9807 | // -- F1 and F2 are function template specializations, and the function | |||
9808 | // template for F1 is more specialized than the template for F2 | |||
9809 | // according to the partial ordering rules described in 14.5.5.2, or, | |||
9810 | // if not that, | |||
9811 | if (Cand1IsSpecialization
| |||
9812 | if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( | |||
9813 | Cand1.Function->getPrimaryTemplate(), | |||
9814 | Cand2.Function->getPrimaryTemplate(), Loc, | |||
9815 | isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion | |||
9816 | : TPOC_Call, | |||
9817 | Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, | |||
9818 | Cand1.isReversed() ^ Cand2.isReversed())) | |||
9819 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); | |||
9820 | } | |||
9821 | ||||
9822 | // -— F1 and F2 are non-template functions with the same | |||
9823 | // parameter-type-lists, and F1 is more constrained than F2 [...], | |||
9824 | if (Cand1.Function
| |||
9825 | !Cand2IsSpecialization && Cand1.Function->hasPrototype() && | |||
9826 | Cand2.Function->hasPrototype()) { | |||
9827 | auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); | |||
9828 | auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); | |||
9829 | if (PT1->getNumParams() == PT2->getNumParams() && | |||
9830 | PT1->isVariadic() == PT2->isVariadic() && | |||
9831 | S.FunctionParamTypesAreEqual(PT1, PT2)) { | |||
9832 | Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); | |||
9833 | Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); | |||
9834 | if (RC1 && RC2) { | |||
9835 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; | |||
9836 | if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, | |||
9837 | {RC2}, AtLeastAsConstrained1) || | |||
9838 | S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, | |||
9839 | {RC1}, AtLeastAsConstrained2)) | |||
9840 | return false; | |||
9841 | if (AtLeastAsConstrained1 != AtLeastAsConstrained2) | |||
9842 | return AtLeastAsConstrained1; | |||
9843 | } else if (RC1 || RC2) { | |||
9844 | return RC1 != nullptr; | |||
9845 | } | |||
9846 | } | |||
9847 | } | |||
9848 | ||||
9849 | // -- F1 is a constructor for a class D, F2 is a constructor for a base | |||
9850 | // class B of D, and for all arguments the corresponding parameters of | |||
9851 | // F1 and F2 have the same type. | |||
9852 | // FIXME: Implement the "all parameters have the same type" check. | |||
9853 | bool Cand1IsInherited = | |||
9854 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); | |||
9855 | bool Cand2IsInherited = | |||
9856 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); | |||
9857 | if (Cand1IsInherited
| |||
9858 | return Cand2IsInherited; | |||
9859 | else if (Cand1IsInherited
| |||
9860 | assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail ("Cand2IsInherited", "clang/lib/Sema/SemaOverload.cpp", 9860 , __extension__ __PRETTY_FUNCTION__)); | |||
9861 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); | |||
| ||||
9862 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); | |||
9863 | if (Cand1Class->isDerivedFrom(Cand2Class)) | |||
9864 | return true; | |||
9865 | if (Cand2Class->isDerivedFrom(Cand1Class)) | |||
9866 | return false; | |||
9867 | // Inherited from sibling base classes: still ambiguous. | |||
9868 | } | |||
9869 | ||||
9870 | // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not | |||
9871 | // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate | |||
9872 | // with reversed order of parameters and F1 is not | |||
9873 | // | |||
9874 | // We rank reversed + different operator as worse than just reversed, but | |||
9875 | // that comparison can never happen, because we only consider reversing for | |||
9876 | // the maximally-rewritten operator (== or <=>). | |||
9877 | if (Cand1.RewriteKind != Cand2.RewriteKind) | |||
9878 | return Cand1.RewriteKind < Cand2.RewriteKind; | |||
9879 | ||||
9880 | // Check C++17 tie-breakers for deduction guides. | |||
9881 | { | |||
9882 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); | |||
9883 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); | |||
9884 | if (Guide1 && Guide2) { | |||
9885 | // -- F1 is generated from a deduction-guide and F2 is not | |||
9886 | if (Guide1->isImplicit() != Guide2->isImplicit()) | |||
9887 | return Guide2->isImplicit(); | |||
9888 | ||||
9889 | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not | |||
9890 | if (Guide1->isCopyDeductionCandidate()) | |||
9891 | return true; | |||
9892 | } | |||
9893 | } | |||
9894 | ||||
9895 | // Check for enable_if value-based overload resolution. | |||
9896 | if (Cand1.Function && Cand2.Function) { | |||
9897 | Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); | |||
9898 | if (Cmp != Comparison::Equal) | |||
9899 | return Cmp == Comparison::Better; | |||
9900 | } | |||
9901 | ||||
9902 | bool HasPS1 = Cand1.Function != nullptr && | |||
9903 | functionHasPassObjectSizeParams(Cand1.Function); | |||
9904 | bool HasPS2 = Cand2.Function != nullptr && | |||
9905 | functionHasPassObjectSizeParams(Cand2.Function); | |||
9906 | if (HasPS1 != HasPS2 && HasPS1) | |||
9907 | return true; | |||
9908 | ||||
9909 | auto MV = isBetterMultiversionCandidate(Cand1, Cand2); | |||
9910 | if (MV == Comparison::Better) | |||
9911 | return true; | |||
9912 | if (MV == Comparison::Worse) | |||
9913 | return false; | |||
9914 | ||||
9915 | // If other rules cannot determine which is better, CUDA preference is used | |||
9916 | // to determine which is better. | |||
9917 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { | |||
9918 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); | |||
9919 | return S.IdentifyCUDAPreference(Caller, Cand1.Function) > | |||
9920 | S.IdentifyCUDAPreference(Caller, Cand2.Function); | |||
9921 | } | |||
9922 | ||||
9923 | // General member function overloading is handled above, so this only handles | |||
9924 | // constructors with address spaces. | |||
9925 | // This only handles address spaces since C++ has no other | |||
9926 | // qualifier that can be used with constructors. | |||
9927 | const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); | |||
9928 | const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); | |||
9929 | if (CD1 && CD2) { | |||
9930 | LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); | |||
9931 | LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); | |||
9932 | if (AS1 != AS2) { | |||
9933 | if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) | |||
9934 | return true; | |||
9935 | if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) | |||
9936 | return false; | |||
9937 | } | |||
9938 | } | |||
9939 | ||||
9940 | return false; | |||
9941 | } | |||
9942 | ||||
9943 | /// Determine whether two declarations are "equivalent" for the purposes of | |||
9944 | /// name lookup and overload resolution. This applies when the same internal/no | |||
9945 | /// linkage entity is defined by two modules (probably by textually including | |||
9946 | /// the same header). In such a case, we don't consider the declarations to | |||
9947 | /// declare the same entity, but we also don't want lookups with both | |||
9948 | /// declarations visible to be ambiguous in some cases (this happens when using | |||
9949 | /// a modularized libstdc++). | |||
9950 | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, | |||
9951 | const NamedDecl *B) { | |||
9952 | auto *VA = dyn_cast_or_null<ValueDecl>(A); | |||
9953 | auto *VB = dyn_cast_or_null<ValueDecl>(B); | |||
9954 | if (!VA || !VB) | |||
9955 | return false; | |||
9956 | ||||
9957 | // The declarations must be declaring the same name as an internal linkage | |||
9958 | // entity in different modules. | |||
9959 | if (!VA->getDeclContext()->getRedeclContext()->Equals( | |||
9960 | VB->getDeclContext()->getRedeclContext()) || | |||
9961 | getOwningModule(VA) == getOwningModule(VB) || | |||
9962 | VA->isExternallyVisible() || VB->isExternallyVisible()) | |||
9963 | return false; | |||
9964 | ||||
9965 | // Check that the declarations appear to be equivalent. | |||
9966 | // | |||
9967 | // FIXME: Checking the type isn't really enough to resolve the ambiguity. | |||
9968 | // For constants and functions, we should check the initializer or body is | |||
9969 | // the same. For non-constant variables, we shouldn't allow it at all. | |||
9970 | if (Context.hasSameType(VA->getType(), VB->getType())) | |||
9971 | return true; | |||
9972 | ||||
9973 | // Enum constants within unnamed enumerations will have different types, but | |||
9974 | // may still be similar enough to be interchangeable for our purposes. | |||
9975 | if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { | |||
9976 | if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { | |||
9977 | // Only handle anonymous enums. If the enumerations were named and | |||
9978 | // equivalent, they would have been merged to the same type. | |||
9979 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); | |||
9980 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); | |||
9981 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || | |||
9982 | !Context.hasSameType(EnumA->getIntegerType(), | |||
9983 | EnumB->getIntegerType())) | |||
9984 | return false; | |||
9985 | // Allow this only if the value is the same for both enumerators. | |||
9986 | return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); | |||
9987 | } | |||
9988 | } | |||
9989 | ||||
9990 | // Nothing else is sufficiently similar. | |||
9991 | return false; | |||
9992 | } | |||
9993 | ||||
9994 | void Sema::diagnoseEquivalentInternalLinkageDeclarations( | |||
9995 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { | |||
9996 | assert(D && "Unknown declaration")(static_cast <bool> (D && "Unknown declaration" ) ? void (0) : __assert_fail ("D && \"Unknown declaration\"" , "clang/lib/Sema/SemaOverload.cpp", 9996, __extension__ __PRETTY_FUNCTION__ )); | |||
9997 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; | |||
9998 | ||||
9999 | Module *M = getOwningModule(D); | |||
10000 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) | |||
10001 | << !M << (M ? M->getFullModuleName() : ""); | |||
10002 | ||||
10003 | for (auto *E : Equiv) { | |||
10004 | Module *M = getOwningModule(E); | |||
10005 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) | |||
10006 | << !M << (M ? M->getFullModuleName() : ""); | |||
10007 | } | |||
10008 | } | |||
10009 | ||||
10010 | /// Computes the best viable function (C++ 13.3.3) | |||
10011 | /// within an overload candidate set. | |||
10012 | /// | |||
10013 | /// \param Loc The location of the function name (or operator symbol) for | |||
10014 | /// which overload resolution occurs. | |||
10015 | /// | |||
10016 | /// \param Best If overload resolution was successful or found a deleted | |||
10017 | /// function, \p Best points to the candidate function found. | |||
10018 | /// | |||
10019 | /// \returns The result of overload resolution. | |||
10020 | OverloadingResult | |||
10021 | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, | |||
10022 | iterator &Best) { | |||
10023 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; | |||
10024 | std::transform(begin(), end(), std::back_inserter(Candidates), | |||
10025 | [](OverloadCandidate &Cand) { return &Cand; }); | |||
10026 | ||||
10027 | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but | |||
10028 | // are accepted by both clang and NVCC. However, during a particular | |||
10029 | // compilation mode only one call variant is viable. We need to | |||
10030 | // exclude non-viable overload candidates from consideration based | |||
10031 | // only on their host/device attributes. Specifically, if one | |||
10032 | // candidate call is WrongSide and the other is SameSide, we ignore | |||
10033 | // the WrongSide candidate. | |||
10034 | // We only need to remove wrong-sided candidates here if | |||
10035 | // -fgpu-exclude-wrong-side-overloads is off. When | |||
10036 | // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared | |||
10037 | // uniformly in isBetterOverloadCandidate. | |||
10038 | if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { | |||
10039 | const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); | |||
10040 | bool ContainsSameSideCandidate = | |||
10041 | llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { | |||
10042 | // Check viable function only. | |||
10043 | return Cand->Viable && Cand->Function && | |||
10044 | S.IdentifyCUDAPreference(Caller, Cand->Function) == | |||
10045 | Sema::CFP_SameSide; | |||
10046 | }); | |||
10047 | if (ContainsSameSideCandidate) { | |||
10048 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { | |||
10049 | // Check viable function only to avoid unnecessary data copying/moving. | |||
10050 | return Cand->Viable && Cand->Function && | |||
10051 | S.IdentifyCUDAPreference(Caller, Cand->Function) == | |||
10052 | Sema::CFP_WrongSide; | |||
10053 | }; | |||
10054 | llvm::erase_if(Candidates, IsWrongSideCandidate); | |||
10055 | } | |||
10056 | } | |||
10057 | ||||
10058 | // Find the best viable function. | |||
10059 | Best = end(); | |||
10060 | for (auto *Cand : Candidates) { | |||
10061 | Cand->Best = false; | |||
10062 | if (Cand->Viable) | |||
10063 | if (Best == end() || | |||
10064 | isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) | |||
10065 | Best = Cand; | |||
10066 | } | |||
10067 | ||||
10068 | // If we didn't find any viable functions, abort. | |||
10069 | if (Best == end()) | |||
10070 | return OR_No_Viable_Function; | |||
10071 | ||||
10072 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; | |||
10073 | ||||
10074 | llvm::SmallVector<OverloadCandidate*, 4> PendingBest; | |||
10075 | PendingBest.push_back(&*Best); | |||
10076 | Best->Best = true; | |||
10077 | ||||
10078 | // Make sure that this function is better than every other viable | |||
10079 | // function. If not, we have an ambiguity. | |||
10080 | while (!PendingBest.empty()) { | |||
10081 | auto *Curr = PendingBest.pop_back_val(); | |||
10082 | for (auto *Cand : Candidates) { | |||
10083 | if (Cand->Viable && !Cand->Best && | |||
10084 | !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { | |||
10085 | PendingBest.push_back(Cand); | |||
10086 | Cand->Best = true; | |||
10087 | ||||
10088 | if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, | |||
10089 | Curr->Function)) | |||
10090 | EquivalentCands.push_back(Cand->Function); | |||
10091 | else | |||
10092 | Best = end(); | |||
10093 | } | |||
10094 | } | |||
10095 | } | |||
10096 | ||||
10097 | // If we found more than one best candidate, this is ambiguous. | |||
10098 | if (Best == end()) | |||
10099 | return OR_Ambiguous; | |||
10100 | ||||
10101 | // Best is the best viable function. | |||
10102 | if (Best->Function && Best->Function->isDeleted()) | |||
10103 | return OR_Deleted; | |||
10104 | ||||
10105 | if (!EquivalentCands.empty()) | |||
10106 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, | |||
10107 | EquivalentCands); | |||
10108 | ||||
10109 | return OR_Success; | |||
10110 | } | |||
10111 | ||||
10112 | namespace { | |||
10113 | ||||
10114 | enum OverloadCandidateKind { | |||
10115 | oc_function, | |||
10116 | oc_method, | |||
10117 | oc_reversed_binary_operator, | |||
10118 | oc_constructor, | |||
10119 | oc_implicit_default_constructor, | |||
10120 | oc_implicit_copy_constructor, | |||
10121 | oc_implicit_move_constructor, | |||
10122 | oc_implicit_copy_assignment, | |||
10123 | oc_implicit_move_assignment, | |||
10124 | oc_implicit_equality_comparison, | |||
10125 | oc_inherited_constructor | |||
10126 | }; | |||
10127 | ||||
10128 | enum OverloadCandidateSelect { | |||
10129 | ocs_non_template, | |||
10130 | ocs_template, | |||
10131 | ocs_described_template, | |||
10132 | }; | |||
10133 | ||||
10134 | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> | |||
10135 | ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, | |||
10136 | OverloadCandidateRewriteKind CRK, | |||
10137 | std::string &Description) { | |||
10138 | ||||
10139 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); | |||
10140 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { | |||
10141 | isTemplate = true; | |||
10142 | Description = S.getTemplateArgumentBindingsText( | |||
10143 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); | |||
10144 | } | |||
10145 | ||||
10146 | OverloadCandidateSelect Select = [&]() { | |||
10147 | if (!Description.empty()) | |||
10148 | return ocs_described_template; | |||
10149 | return isTemplate ? ocs_template : ocs_non_template; | |||
10150 | }(); | |||
10151 | ||||
10152 | OverloadCandidateKind Kind = [&]() { | |||
10153 | if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) | |||
10154 | return oc_implicit_equality_comparison; | |||
10155 | ||||
10156 | if (CRK & CRK_Reversed) | |||
10157 | return oc_reversed_binary_operator; | |||
10158 | ||||
10159 | if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { | |||
10160 | if (!Ctor->isImplicit()) { | |||
10161 | if (isa<ConstructorUsingShadowDecl>(Found)) | |||
10162 | return oc_inherited_constructor; | |||
10163 | else | |||
10164 | return oc_constructor; | |||
10165 | } | |||
10166 | ||||
10167 | if (Ctor->isDefaultConstructor()) | |||
10168 | return oc_implicit_default_constructor; | |||
10169 | ||||
10170 | if (Ctor->isMoveConstructor()) | |||
10171 | return oc_implicit_move_constructor; | |||
10172 | ||||
10173 | assert(Ctor->isCopyConstructor() &&(static_cast <bool> (Ctor->isCopyConstructor() && "unexpected sort of implicit constructor") ? void (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "clang/lib/Sema/SemaOverload.cpp", 10174, __extension__ __PRETTY_FUNCTION__ )) | |||
10174 | "unexpected sort of implicit constructor")(static_cast <bool> (Ctor->isCopyConstructor() && "unexpected sort of implicit constructor") ? void (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "clang/lib/Sema/SemaOverload.cpp", 10174, __extension__ __PRETTY_FUNCTION__ )); | |||
10175 | return oc_implicit_copy_constructor; | |||
10176 | } | |||
10177 | ||||
10178 | if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { | |||
10179 | // This actually gets spelled 'candidate function' for now, but | |||
10180 | // it doesn't hurt to split it out. | |||
10181 | if (!Meth->isImplicit()) | |||
10182 | return oc_method; | |||
10183 | ||||
10184 | if (Meth->isMoveAssignmentOperator()) | |||
10185 | return oc_implicit_move_assignment; | |||
10186 | ||||
10187 | if (Meth->isCopyAssignmentOperator()) | |||
10188 | return oc_implicit_copy_assignment; | |||
10189 | ||||
10190 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast <bool> (isa<CXXConversionDecl>(Meth) && "expected conversion") ? void (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\"" , "clang/lib/Sema/SemaOverload.cpp", 10190, __extension__ __PRETTY_FUNCTION__ )); | |||
10191 | return oc_method; | |||
10192 | } | |||
10193 | ||||
10194 | return oc_function; | |||
10195 | }(); | |||
10196 | ||||
10197 | return std::make_pair(Kind, Select); | |||
10198 | } | |||
10199 | ||||
10200 | void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { | |||
10201 | // FIXME: It'd be nice to only emit a note once per using-decl per overload | |||
10202 | // set. | |||
10203 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) | |||
10204 | S.Diag(FoundDecl->getLocation(), | |||
10205 | diag::note_ovl_candidate_inherited_constructor) | |||
10206 | << Shadow->getNominatedBaseClass(); | |||
10207 | } | |||
10208 | ||||
10209 | } // end anonymous namespace | |||
10210 | ||||
10211 | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, | |||
10212 | const FunctionDecl *FD) { | |||
10213 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { | |||
10214 | bool AlwaysTrue; | |||
10215 | if (EnableIf->getCond()->isValueDependent() || | |||
10216 | !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) | |||
10217 | return false; | |||
10218 | if (!AlwaysTrue) | |||
10219 | return false; | |||
10220 | } | |||
10221 | return true; | |||
10222 | } | |||
10223 | ||||
10224 | /// Returns true if we can take the address of the function. | |||
10225 | /// | |||
10226 | /// \param Complain - If true, we'll emit a diagnostic | |||
10227 | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are | |||
10228 | /// we in overload resolution? | |||
10229 | /// \param Loc - The location of the statement we're complaining about. Ignored | |||
10230 | /// if we're not complaining, or if we're in overload resolution. | |||
10231 | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, | |||
10232 | bool Complain, | |||
10233 | bool InOverloadResolution, | |||
10234 | SourceLocation Loc) { | |||
10235 | if (!isFunctionAlwaysEnabled(S.Context, FD)) { | |||
10236 | if (Complain) { | |||
10237 | if (InOverloadResolution) | |||
10238 | S.Diag(FD->getBeginLoc(), | |||
10239 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); | |||
10240 | else | |||
10241 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; | |||
10242 | } | |||
10243 | return false; | |||
10244 | } | |||
10245 | ||||
10246 | if (FD->getTrailingRequiresClause()) { | |||
10247 | ConstraintSatisfaction Satisfaction; | |||
10248 | if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) | |||
10249 | return false; | |||
10250 | if (!Satisfaction.IsSatisfied) { | |||
10251 | if (Complain) { | |||
10252 | if (InOverloadResolution) { | |||
10253 | SmallString<128> TemplateArgString; | |||
10254 | if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { | |||
10255 | TemplateArgString += " "; | |||
10256 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10257 | FunTmpl->getTemplateParameters(), | |||
10258 | *FD->getTemplateSpecializationArgs()); | |||
10259 | } | |||
10260 | ||||
10261 | S.Diag(FD->getBeginLoc(), | |||
10262 | diag::note_ovl_candidate_unsatisfied_constraints) | |||
10263 | << TemplateArgString; | |||
10264 | } else | |||
10265 | S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) | |||
10266 | << FD; | |||
10267 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); | |||
10268 | } | |||
10269 | return false; | |||
10270 | } | |||
10271 | } | |||
10272 | ||||
10273 | auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { | |||
10274 | return P->hasAttr<PassObjectSizeAttr>(); | |||
10275 | }); | |||
10276 | if (I == FD->param_end()) | |||
10277 | return true; | |||
10278 | ||||
10279 | if (Complain) { | |||
10280 | // Add one to ParamNo because it's user-facing | |||
10281 | unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; | |||
10282 | if (InOverloadResolution) | |||
10283 | S.Diag(FD->getLocation(), | |||
10284 | diag::note_ovl_candidate_has_pass_object_size_params) | |||
10285 | << ParamNo; | |||
10286 | else | |||
10287 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) | |||
10288 | << FD << ParamNo; | |||
10289 | } | |||
10290 | return false; | |||
10291 | } | |||
10292 | ||||
10293 | static bool checkAddressOfCandidateIsAvailable(Sema &S, | |||
10294 | const FunctionDecl *FD) { | |||
10295 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, | |||
10296 | /*InOverloadResolution=*/true, | |||
10297 | /*Loc=*/SourceLocation()); | |||
10298 | } | |||
10299 | ||||
10300 | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, | |||
10301 | bool Complain, | |||
10302 | SourceLocation Loc) { | |||
10303 | return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, | |||
10304 | /*InOverloadResolution=*/false, | |||
10305 | Loc); | |||
10306 | } | |||
10307 | ||||
10308 | // Don't print candidates other than the one that matches the calling | |||
10309 | // convention of the call operator, since that is guaranteed to exist. | |||
10310 | static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { | |||
10311 | const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); | |||
10312 | ||||
10313 | if (!ConvD) | |||
10314 | return false; | |||
10315 | const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); | |||
10316 | if (!RD->isLambda()) | |||
10317 | return false; | |||
10318 | ||||
10319 | CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); | |||
10320 | CallingConv CallOpCC = | |||
10321 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); | |||
10322 | QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); | |||
10323 | CallingConv ConvToCC = | |||
10324 | ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); | |||
10325 | ||||
10326 | return ConvToCC != CallOpCC; | |||
10327 | } | |||
10328 | ||||
10329 | // Notes the location of an overload candidate. | |||
10330 | void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, | |||
10331 | OverloadCandidateRewriteKind RewriteKind, | |||
10332 | QualType DestType, bool TakingAddress) { | |||
10333 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) | |||
10334 | return; | |||
10335 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && | |||
10336 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) | |||
10337 | return; | |||
10338 | if (shouldSkipNotingLambdaConversionDecl(Fn)) | |||
10339 | return; | |||
10340 | ||||
10341 | std::string FnDesc; | |||
10342 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = | |||
10343 | ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); | |||
10344 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) | |||
10345 | << (unsigned)KSPair.first << (unsigned)KSPair.second | |||
10346 | << Fn << FnDesc; | |||
10347 | ||||
10348 | HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); | |||
10349 | Diag(Fn->getLocation(), PD); | |||
10350 | MaybeEmitInheritedConstructorNote(*this, Found); | |||
10351 | } | |||
10352 | ||||
10353 | static void | |||
10354 | MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { | |||
10355 | // Perhaps the ambiguity was caused by two atomic constraints that are | |||
10356 | // 'identical' but not equivalent: | |||
10357 | // | |||
10358 | // void foo() requires (sizeof(T) > 4) { } // #1 | |||
10359 | // void foo() requires (sizeof(T) > 4) && T::value { } // #2 | |||
10360 | // | |||
10361 | // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause | |||
10362 | // #2 to subsume #1, but these constraint are not considered equivalent | |||
10363 | // according to the subsumption rules because they are not the same | |||
10364 | // source-level construct. This behavior is quite confusing and we should try | |||
10365 | // to help the user figure out what happened. | |||
10366 | ||||
10367 | SmallVector<const Expr *, 3> FirstAC, SecondAC; | |||
10368 | FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; | |||
10369 | for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { | |||
10370 | if (!I->Function) | |||
10371 | continue; | |||
10372 | SmallVector<const Expr *, 3> AC; | |||
10373 | if (auto *Template = I->Function->getPrimaryTemplate()) | |||
10374 | Template->getAssociatedConstraints(AC); | |||
10375 | else | |||
10376 | I->Function->getAssociatedConstraints(AC); | |||
10377 | if (AC.empty()) | |||
10378 | continue; | |||
10379 | if (FirstCand == nullptr) { | |||
10380 | FirstCand = I->Function; | |||
10381 | FirstAC = AC; | |||
10382 | } else if (SecondCand == nullptr) { | |||
10383 | SecondCand = I->Function; | |||
10384 | SecondAC = AC; | |||
10385 | } else { | |||
10386 | // We have more than one pair of constrained functions - this check is | |||
10387 | // expensive and we'd rather not try to diagnose it. | |||
10388 | return; | |||
10389 | } | |||
10390 | } | |||
10391 | if (!SecondCand) | |||
10392 | return; | |||
10393 | // The diagnostic can only happen if there are associated constraints on | |||
10394 | // both sides (there needs to be some identical atomic constraint). | |||
10395 | if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, | |||
10396 | SecondCand, SecondAC)) | |||
10397 | // Just show the user one diagnostic, they'll probably figure it out | |||
10398 | // from here. | |||
10399 | return; | |||
10400 | } | |||
10401 | ||||
10402 | // Notes the location of all overload candidates designated through | |||
10403 | // OverloadedExpr | |||
10404 | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, | |||
10405 | bool TakingAddress) { | |||
10406 | assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast <bool> (OverloadedExpr->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 10406, __extension__ __PRETTY_FUNCTION__ )); | |||
10407 | ||||
10408 | OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); | |||
10409 | OverloadExpr *OvlExpr = Ovl.Expression; | |||
10410 | ||||
10411 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
10412 | IEnd = OvlExpr->decls_end(); | |||
10413 | I != IEnd; ++I) { | |||
10414 | if (FunctionTemplateDecl *FunTmpl = | |||
10415 | dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { | |||
10416 | NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, | |||
10417 | TakingAddress); | |||
10418 | } else if (FunctionDecl *Fun | |||
10419 | = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { | |||
10420 | NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); | |||
10421 | } | |||
10422 | } | |||
10423 | } | |||
10424 | ||||
10425 | /// Diagnoses an ambiguous conversion. The partial diagnostic is the | |||
10426 | /// "lead" diagnostic; it will be given two arguments, the source and | |||
10427 | /// target types of the conversion. | |||
10428 | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( | |||
10429 | Sema &S, | |||
10430 | SourceLocation CaretLoc, | |||
10431 | const PartialDiagnostic &PDiag) const { | |||
10432 | S.Diag(CaretLoc, PDiag) | |||
10433 | << Ambiguous.getFromType() << Ambiguous.getToType(); | |||
10434 | unsigned CandsShown = 0; | |||
10435 | AmbiguousConversionSequence::const_iterator I, E; | |||
10436 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { | |||
10437 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) | |||
10438 | break; | |||
10439 | ++CandsShown; | |||
10440 | S.NoteOverloadCandidate(I->first, I->second); | |||
10441 | } | |||
10442 | S.Diags.overloadCandidatesShown(CandsShown); | |||
10443 | if (I != E) | |||
10444 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); | |||
10445 | } | |||
10446 | ||||
10447 | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, | |||
10448 | unsigned I, bool TakingCandidateAddress) { | |||
10449 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; | |||
10450 | assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail ("Conv.isBad()", "clang/lib/Sema/SemaOverload.cpp", 10450, __extension__ __PRETTY_FUNCTION__)); | |||
10451 | assert(Cand->Function && "for now, candidate must be a function")(static_cast <bool> (Cand->Function && "for now, candidate must be a function" ) ? void (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\"" , "clang/lib/Sema/SemaOverload.cpp", 10451, __extension__ __PRETTY_FUNCTION__ )); | |||
10452 | FunctionDecl *Fn = Cand->Function; | |||
10453 | ||||
10454 | // There's a conversion slot for the object argument if this is a | |||
10455 | // non-constructor method. Note that 'I' corresponds the | |||
10456 | // conversion-slot index. | |||
10457 | bool isObjectArgument = false; | |||
10458 | if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { | |||
10459 | if (I == 0) | |||
10460 | isObjectArgument = true; | |||
10461 | else | |||
10462 | I--; | |||
10463 | } | |||
10464 | ||||
10465 | std::string FnDesc; | |||
10466 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
10467 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), | |||
10468 | FnDesc); | |||
10469 | ||||
10470 | Expr *FromExpr = Conv.Bad.FromExpr; | |||
10471 | QualType FromTy = Conv.Bad.getFromType(); | |||
10472 | QualType ToTy = Conv.Bad.getToType(); | |||
10473 | ||||
10474 | if (FromTy == S.Context.OverloadTy) { | |||
10475 | assert(FromExpr && "overload set argument came from implicit argument?")(static_cast <bool> (FromExpr && "overload set argument came from implicit argument?" ) ? void (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\"" , "clang/lib/Sema/SemaOverload.cpp", 10475, __extension__ __PRETTY_FUNCTION__ )); | |||
10476 | Expr *E = FromExpr->IgnoreParens(); | |||
10477 | if (isa<UnaryOperator>(E)) | |||
10478 | E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); | |||
10479 | DeclarationName Name = cast<OverloadExpr>(E)->getName(); | |||
10480 | ||||
10481 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) | |||
10482 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10483 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy | |||
10484 | << Name << I + 1; | |||
10485 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10486 | return; | |||
10487 | } | |||
10488 | ||||
10489 | // Do some hand-waving analysis to see if the non-viability is due | |||
10490 | // to a qualifier mismatch. | |||
10491 | CanQualType CFromTy = S.Context.getCanonicalType(FromTy); | |||
10492 | CanQualType CToTy = S.Context.getCanonicalType(ToTy); | |||
10493 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) | |||
10494 | CToTy = RT->getPointeeType(); | |||
10495 | else { | |||
10496 | // TODO: detect and diagnose the full richness of const mismatches. | |||
10497 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) | |||
10498 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { | |||
10499 | CFromTy = FromPT->getPointeeType(); | |||
10500 | CToTy = ToPT->getPointeeType(); | |||
10501 | } | |||
10502 | } | |||
10503 | ||||
10504 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && | |||
10505 | !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { | |||
10506 | Qualifiers FromQs = CFromTy.getQualifiers(); | |||
10507 | Qualifiers ToQs = CToTy.getQualifiers(); | |||
10508 | ||||
10509 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { | |||
10510 | if (isObjectArgument) | |||
10511 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) | |||
10512 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
10513 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
10514 | << FromQs.getAddressSpace() << ToQs.getAddressSpace(); | |||
10515 | else | |||
10516 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) | |||
10517 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
10518 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
10519 | << FromQs.getAddressSpace() << ToQs.getAddressSpace() | |||
10520 | << ToTy->isReferenceType() << I + 1; | |||
10521 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10522 | return; | |||
10523 | } | |||
10524 | ||||
10525 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { | |||
10526 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) | |||
10527 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10528 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10529 | << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() | |||
10530 | << (unsigned)isObjectArgument << I + 1; | |||
10531 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10532 | return; | |||
10533 | } | |||
10534 | ||||
10535 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { | |||
10536 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) | |||
10537 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10538 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10539 | << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() | |||
10540 | << (unsigned)isObjectArgument << I + 1; | |||
10541 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10542 | return; | |||
10543 | } | |||
10544 | ||||
10545 | if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { | |||
10546 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) | |||
10547 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10548 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10549 | << FromQs.hasUnaligned() << I + 1; | |||
10550 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10551 | return; | |||
10552 | } | |||
10553 | ||||
10554 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); | |||
10555 | assert(CVR && "expected qualifiers mismatch")(static_cast <bool> (CVR && "expected qualifiers mismatch" ) ? void (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\"" , "clang/lib/Sema/SemaOverload.cpp", 10555, __extension__ __PRETTY_FUNCTION__ )); | |||
10556 | ||||
10557 | if (isObjectArgument) { | |||
10558 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) | |||
10559 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10560 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10561 | << (CVR - 1); | |||
10562 | } else { | |||
10563 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) | |||
10564 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10565 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10566 | << (CVR - 1) << I + 1; | |||
10567 | } | |||
10568 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10569 | return; | |||
10570 | } | |||
10571 | ||||
10572 | if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || | |||
10573 | Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { | |||
10574 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) | |||
10575 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10576 | << (unsigned)isObjectArgument << I + 1 | |||
10577 | << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) | |||
10578 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); | |||
10579 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10580 | return; | |||
10581 | } | |||
10582 | ||||
10583 | // Special diagnostic for failure to convert an initializer list, since | |||
10584 | // telling the user that it has type void is not useful. | |||
10585 | if (FromExpr && isa<InitListExpr>(FromExpr)) { | |||
10586 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) | |||
10587 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10588 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10589 | << ToTy << (unsigned)isObjectArgument << I + 1 | |||
10590 | << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 | |||
10591 | : Conv.Bad.Kind == BadConversionSequence::too_many_initializers | |||
10592 | ? 2 | |||
10593 | : 0); | |||
10594 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10595 | return; | |||
10596 | } | |||
10597 | ||||
10598 | // Diagnose references or pointers to incomplete types differently, | |||
10599 | // since it's far from impossible that the incompleteness triggered | |||
10600 | // the failure. | |||
10601 | QualType TempFromTy = FromTy.getNonReferenceType(); | |||
10602 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) | |||
10603 | TempFromTy = PTy->getPointeeType(); | |||
10604 | if (TempFromTy->isIncompleteType()) { | |||
10605 | // Emit the generic diagnostic and, optionally, add the hints to it. | |||
10606 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) | |||
10607 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10608 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10609 | << ToTy << (unsigned)isObjectArgument << I + 1 | |||
10610 | << (unsigned)(Cand->Fix.Kind); | |||
10611 | ||||
10612 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10613 | return; | |||
10614 | } | |||
10615 | ||||
10616 | // Diagnose base -> derived pointer conversions. | |||
10617 | unsigned BaseToDerivedConversion = 0; | |||
10618 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { | |||
10619 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { | |||
10620 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( | |||
10621 | FromPtrTy->getPointeeType()) && | |||
10622 | !FromPtrTy->getPointeeType()->isIncompleteType() && | |||
10623 | !ToPtrTy->getPointeeType()->isIncompleteType() && | |||
10624 | S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), | |||
10625 | FromPtrTy->getPointeeType())) | |||
10626 | BaseToDerivedConversion = 1; | |||
10627 | } | |||
10628 | } else if (const ObjCObjectPointerType *FromPtrTy | |||
10629 | = FromTy->getAs<ObjCObjectPointerType>()) { | |||
10630 | if (const ObjCObjectPointerType *ToPtrTy | |||
10631 | = ToTy->getAs<ObjCObjectPointerType>()) | |||
10632 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) | |||
10633 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) | |||
10634 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( | |||
10635 | FromPtrTy->getPointeeType()) && | |||
10636 | FromIface->isSuperClassOf(ToIface)) | |||
10637 | BaseToDerivedConversion = 2; | |||
10638 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { | |||
10639 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && | |||
10640 | !FromTy->isIncompleteType() && | |||
10641 | !ToRefTy->getPointeeType()->isIncompleteType() && | |||
10642 | S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { | |||
10643 | BaseToDerivedConversion = 3; | |||
10644 | } | |||
10645 | } | |||
10646 | ||||
10647 | if (BaseToDerivedConversion) { | |||
10648 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) | |||
10649 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10650 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
10651 | << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; | |||
10652 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10653 | return; | |||
10654 | } | |||
10655 | ||||
10656 | if (isa<ObjCObjectPointerType>(CFromTy) && | |||
10657 | isa<PointerType>(CToTy)) { | |||
10658 | Qualifiers FromQs = CFromTy.getQualifiers(); | |||
10659 | Qualifiers ToQs = CToTy.getQualifiers(); | |||
10660 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { | |||
10661 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) | |||
10662 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
10663 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
10664 | << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; | |||
10665 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10666 | return; | |||
10667 | } | |||
10668 | } | |||
10669 | ||||
10670 | if (TakingCandidateAddress && | |||
10671 | !checkAddressOfCandidateIsAvailable(S, Cand->Function)) | |||
10672 | return; | |||
10673 | ||||
10674 | // Emit the generic diagnostic and, optionally, add the hints to it. | |||
10675 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); | |||
10676 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10677 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
10678 | << ToTy << (unsigned)isObjectArgument << I + 1 | |||
10679 | << (unsigned)(Cand->Fix.Kind); | |||
10680 | ||||
10681 | // If we can fix the conversion, suggest the FixIts. | |||
10682 | for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), | |||
10683 | HE = Cand->Fix.Hints.end(); HI != HE; ++HI) | |||
10684 | FDiag << *HI; | |||
10685 | S.Diag(Fn->getLocation(), FDiag); | |||
10686 | ||||
10687 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10688 | } | |||
10689 | ||||
10690 | /// Additional arity mismatch diagnosis specific to a function overload | |||
10691 | /// candidates. This is not covered by the more general DiagnoseArityMismatch() | |||
10692 | /// over a candidate in any candidate set. | |||
10693 | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, | |||
10694 | unsigned NumArgs) { | |||
10695 | FunctionDecl *Fn = Cand->Function; | |||
10696 | unsigned MinParams = Fn->getMinRequiredArguments(); | |||
10697 | ||||
10698 | // With invalid overloaded operators, it's possible that we think we | |||
10699 | // have an arity mismatch when in fact it looks like we have the | |||
10700 | // right number of arguments, because only overloaded operators have | |||
10701 | // the weird behavior of overloading member and non-member functions. | |||
10702 | // Just don't report anything. | |||
10703 | if (Fn->isInvalidDecl() && | |||
10704 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) | |||
10705 | return true; | |||
10706 | ||||
10707 | if (NumArgs < MinParams) { | |||
10708 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10710, __extension__ __PRETTY_FUNCTION__ )) | |||
10709 | (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10710, __extension__ __PRETTY_FUNCTION__ )) | |||
10710 | Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10710, __extension__ __PRETTY_FUNCTION__ )); | |||
10711 | } else { | |||
10712 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10714, __extension__ __PRETTY_FUNCTION__ )) | |||
10713 | (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10714, __extension__ __PRETTY_FUNCTION__ )) | |||
10714 | Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments ) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments )) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "clang/lib/Sema/SemaOverload.cpp", 10714, __extension__ __PRETTY_FUNCTION__ )); | |||
10715 | } | |||
10716 | ||||
10717 | return false; | |||
10718 | } | |||
10719 | ||||
10720 | /// General arity mismatch diagnosis over a candidate in a candidate set. | |||
10721 | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, | |||
10722 | unsigned NumFormalArgs) { | |||
10723 | assert(isa<FunctionDecl>(D) &&(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 10726, __extension__ __PRETTY_FUNCTION__ )) | |||
10724 | "The templated declaration should at least be a function"(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 10726, __extension__ __PRETTY_FUNCTION__ )) | |||
10725 | " when diagnosing bad template argument deduction due to too many"(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 10726, __extension__ __PRETTY_FUNCTION__ )) | |||
10726 | " or too few arguments")(static_cast <bool> (isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 10726, __extension__ __PRETTY_FUNCTION__ )); | |||
10727 | ||||
10728 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
10729 | ||||
10730 | // TODO: treat calls to a missing default constructor as a special case | |||
10731 | const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); | |||
10732 | unsigned MinParams = Fn->getMinRequiredArguments(); | |||
10733 | ||||
10734 | // at least / at most / exactly | |||
10735 | unsigned mode, modeCount; | |||
10736 | if (NumFormalArgs < MinParams) { | |||
10737 | if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || | |||
10738 | FnTy->isTemplateVariadic()) | |||
10739 | mode = 0; // "at least" | |||
10740 | else | |||
10741 | mode = 2; // "exactly" | |||
10742 | modeCount = MinParams; | |||
10743 | } else { | |||
10744 | if (MinParams != FnTy->getNumParams()) | |||
10745 | mode = 1; // "at most" | |||
10746 | else | |||
10747 | mode = 2; // "exactly" | |||
10748 | modeCount = FnTy->getNumParams(); | |||
10749 | } | |||
10750 | ||||
10751 | std::string Description; | |||
10752 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
10753 | ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); | |||
10754 | ||||
10755 | if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) | |||
10756 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) | |||
10757 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
10758 | << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; | |||
10759 | else | |||
10760 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) | |||
10761 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
10762 | << Description << mode << modeCount << NumFormalArgs; | |||
10763 | ||||
10764 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10765 | } | |||
10766 | ||||
10767 | /// Arity mismatch diagnosis specific to a function overload candidate. | |||
10768 | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, | |||
10769 | unsigned NumFormalArgs) { | |||
10770 | if (!CheckArityMismatch(S, Cand, NumFormalArgs)) | |||
10771 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); | |||
10772 | } | |||
10773 | ||||
10774 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { | |||
10775 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) | |||
10776 | return TD; | |||
10777 | llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp" , 10778) | |||
10778 | " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp" , 10778); | |||
10779 | } | |||
10780 | ||||
10781 | /// Diagnose a failed template-argument deduction. | |||
10782 | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, | |||
10783 | DeductionFailureInfo &DeductionFailure, | |||
10784 | unsigned NumArgs, | |||
10785 | bool TakingCandidateAddress) { | |||
10786 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); | |||
10787 | NamedDecl *ParamD; | |||
10788 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || | |||
10789 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || | |||
10790 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); | |||
10791 | switch (DeductionFailure.Result) { | |||
10792 | case Sema::TDK_Success: | |||
10793 | llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction" , "clang/lib/Sema/SemaOverload.cpp", 10793); | |||
10794 | ||||
10795 | case Sema::TDK_Incomplete: { | |||
10796 | assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 10796, __extension__ __PRETTY_FUNCTION__ )); | |||
10797 | S.Diag(Templated->getLocation(), | |||
10798 | diag::note_ovl_candidate_incomplete_deduction) | |||
10799 | << ParamD->getDeclName(); | |||
10800 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10801 | return; | |||
10802 | } | |||
10803 | ||||
10804 | case Sema::TDK_IncompletePack: { | |||
10805 | assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 10805, __extension__ __PRETTY_FUNCTION__ )); | |||
10806 | S.Diag(Templated->getLocation(), | |||
10807 | diag::note_ovl_candidate_incomplete_deduction_pack) | |||
10808 | << ParamD->getDeclName() | |||
10809 | << (DeductionFailure.getFirstArg()->pack_size() + 1) | |||
10810 | << *DeductionFailure.getFirstArg(); | |||
10811 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10812 | return; | |||
10813 | } | |||
10814 | ||||
10815 | case Sema::TDK_Underqualified: { | |||
10816 | assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast <bool> (ParamD && "no parameter found for bad qualifiers deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 10816, __extension__ __PRETTY_FUNCTION__ )); | |||
10817 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); | |||
10818 | ||||
10819 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); | |||
10820 | ||||
10821 | // Param will have been canonicalized, but it should just be a | |||
10822 | // qualified version of ParamD, so move the qualifiers to that. | |||
10823 | QualifierCollector Qs; | |||
10824 | Qs.strip(Param); | |||
10825 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); | |||
10826 | assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast <bool> (S.Context.hasSameType(Param, NonCanonParam )) ? void (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)" , "clang/lib/Sema/SemaOverload.cpp", 10826, __extension__ __PRETTY_FUNCTION__ )); | |||
10827 | ||||
10828 | // Arg has also been canonicalized, but there's nothing we can do | |||
10829 | // about that. It also doesn't matter as much, because it won't | |||
10830 | // have any template parameters in it (because deduction isn't | |||
10831 | // done on dependent types). | |||
10832 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); | |||
10833 | ||||
10834 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) | |||
10835 | << ParamD->getDeclName() << Arg << NonCanonParam; | |||
10836 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10837 | return; | |||
10838 | } | |||
10839 | ||||
10840 | case Sema::TDK_Inconsistent: { | |||
10841 | assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast <bool> (ParamD && "no parameter found for inconsistent deduction result" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\"" , "clang/lib/Sema/SemaOverload.cpp", 10841, __extension__ __PRETTY_FUNCTION__ )); | |||
10842 | int which = 0; | |||
10843 | if (isa<TemplateTypeParmDecl>(ParamD)) | |||
10844 | which = 0; | |||
10845 | else if (isa<NonTypeTemplateParmDecl>(ParamD)) { | |||
10846 | // Deduction might have failed because we deduced arguments of two | |||
10847 | // different types for a non-type template parameter. | |||
10848 | // FIXME: Use a different TDK value for this. | |||
10849 | QualType T1 = | |||
10850 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); | |||
10851 | QualType T2 = | |||
10852 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); | |||
10853 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { | |||
10854 | S.Diag(Templated->getLocation(), | |||
10855 | diag::note_ovl_candidate_inconsistent_deduction_types) | |||
10856 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 | |||
10857 | << *DeductionFailure.getSecondArg() << T2; | |||
10858 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10859 | return; | |||
10860 | } | |||
10861 | ||||
10862 | which = 1; | |||
10863 | } else { | |||
10864 | which = 2; | |||
10865 | } | |||
10866 | ||||
10867 | // Tweak the diagnostic if the problem is that we deduced packs of | |||
10868 | // different arities. We'll print the actual packs anyway in case that | |||
10869 | // includes additional useful information. | |||
10870 | if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && | |||
10871 | DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && | |||
10872 | DeductionFailure.getFirstArg()->pack_size() != | |||
10873 | DeductionFailure.getSecondArg()->pack_size()) { | |||
10874 | which = 3; | |||
10875 | } | |||
10876 | ||||
10877 | S.Diag(Templated->getLocation(), | |||
10878 | diag::note_ovl_candidate_inconsistent_deduction) | |||
10879 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() | |||
10880 | << *DeductionFailure.getSecondArg(); | |||
10881 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10882 | return; | |||
10883 | } | |||
10884 | ||||
10885 | case Sema::TDK_InvalidExplicitArguments: | |||
10886 | assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast <bool> (ParamD && "no parameter found for invalid explicit arguments" ) ? void (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\"" , "clang/lib/Sema/SemaOverload.cpp", 10886, __extension__ __PRETTY_FUNCTION__ )); | |||
10887 | if (ParamD->getDeclName()) | |||
10888 | S.Diag(Templated->getLocation(), | |||
10889 | diag::note_ovl_candidate_explicit_arg_mismatch_named) | |||
10890 | << ParamD->getDeclName(); | |||
10891 | else { | |||
10892 | int index = 0; | |||
10893 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) | |||
10894 | index = TTP->getIndex(); | |||
10895 | else if (NonTypeTemplateParmDecl *NTTP | |||
10896 | = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) | |||
10897 | index = NTTP->getIndex(); | |||
10898 | else | |||
10899 | index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); | |||
10900 | S.Diag(Templated->getLocation(), | |||
10901 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) | |||
10902 | << (index + 1); | |||
10903 | } | |||
10904 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10905 | return; | |||
10906 | ||||
10907 | case Sema::TDK_ConstraintsNotSatisfied: { | |||
10908 | // Format the template argument list into the argument string. | |||
10909 | SmallString<128> TemplateArgString; | |||
10910 | TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); | |||
10911 | TemplateArgString = " "; | |||
10912 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10913 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); | |||
10914 | if (TemplateArgString.size() == 1) | |||
10915 | TemplateArgString.clear(); | |||
10916 | S.Diag(Templated->getLocation(), | |||
10917 | diag::note_ovl_candidate_unsatisfied_constraints) | |||
10918 | << TemplateArgString; | |||
10919 | ||||
10920 | S.DiagnoseUnsatisfiedConstraint( | |||
10921 | static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); | |||
10922 | return; | |||
10923 | } | |||
10924 | case Sema::TDK_TooManyArguments: | |||
10925 | case Sema::TDK_TooFewArguments: | |||
10926 | DiagnoseArityMismatch(S, Found, Templated, NumArgs); | |||
10927 | return; | |||
10928 | ||||
10929 | case Sema::TDK_InstantiationDepth: | |||
10930 | S.Diag(Templated->getLocation(), | |||
10931 | diag::note_ovl_candidate_instantiation_depth); | |||
10932 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10933 | return; | |||
10934 | ||||
10935 | case Sema::TDK_SubstitutionFailure: { | |||
10936 | // Format the template argument list into the argument string. | |||
10937 | SmallString<128> TemplateArgString; | |||
10938 | if (TemplateArgumentList *Args = | |||
10939 | DeductionFailure.getTemplateArgumentList()) { | |||
10940 | TemplateArgString = " "; | |||
10941 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10942 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); | |||
10943 | if (TemplateArgString.size() == 1) | |||
10944 | TemplateArgString.clear(); | |||
10945 | } | |||
10946 | ||||
10947 | // If this candidate was disabled by enable_if, say so. | |||
10948 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); | |||
10949 | if (PDiag && PDiag->second.getDiagID() == | |||
10950 | diag::err_typename_nested_not_found_enable_if) { | |||
10951 | // FIXME: Use the source range of the condition, and the fully-qualified | |||
10952 | // name of the enable_if template. These are both present in PDiag. | |||
10953 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) | |||
10954 | << "'enable_if'" << TemplateArgString; | |||
10955 | return; | |||
10956 | } | |||
10957 | ||||
10958 | // We found a specific requirement that disabled the enable_if. | |||
10959 | if (PDiag && PDiag->second.getDiagID() == | |||
10960 | diag::err_typename_nested_not_found_requirement) { | |||
10961 | S.Diag(Templated->getLocation(), | |||
10962 | diag::note_ovl_candidate_disabled_by_requirement) | |||
10963 | << PDiag->second.getStringArg(0) << TemplateArgString; | |||
10964 | return; | |||
10965 | } | |||
10966 | ||||
10967 | // Format the SFINAE diagnostic into the argument string. | |||
10968 | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s | |||
10969 | // formatted message in another diagnostic. | |||
10970 | SmallString<128> SFINAEArgString; | |||
10971 | SourceRange R; | |||
10972 | if (PDiag) { | |||
10973 | SFINAEArgString = ": "; | |||
10974 | R = SourceRange(PDiag->first, PDiag->first); | |||
10975 | PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); | |||
10976 | } | |||
10977 | ||||
10978 | S.Diag(Templated->getLocation(), | |||
10979 | diag::note_ovl_candidate_substitution_failure) | |||
10980 | << TemplateArgString << SFINAEArgString << R; | |||
10981 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10982 | return; | |||
10983 | } | |||
10984 | ||||
10985 | case Sema::TDK_DeducedMismatch: | |||
10986 | case Sema::TDK_DeducedMismatchNested: { | |||
10987 | // Format the template argument list into the argument string. | |||
10988 | SmallString<128> TemplateArgString; | |||
10989 | if (TemplateArgumentList *Args = | |||
10990 | DeductionFailure.getTemplateArgumentList()) { | |||
10991 | TemplateArgString = " "; | |||
10992 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10993 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); | |||
10994 | if (TemplateArgString.size() == 1) | |||
10995 | TemplateArgString.clear(); | |||
10996 | } | |||
10997 | ||||
10998 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) | |||
10999 | << (*DeductionFailure.getCallArgIndex() + 1) | |||
11000 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() | |||
11001 | << TemplateArgString | |||
11002 | << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); | |||
11003 | break; | |||
11004 | } | |||
11005 | ||||
11006 | case Sema::TDK_NonDeducedMismatch: { | |||
11007 | // FIXME: Provide a source location to indicate what we couldn't match. | |||
11008 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); | |||
11009 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); | |||
11010 | if (FirstTA.getKind() == TemplateArgument::Template && | |||
11011 | SecondTA.getKind() == TemplateArgument::Template) { | |||
11012 | TemplateName FirstTN = FirstTA.getAsTemplate(); | |||
11013 | TemplateName SecondTN = SecondTA.getAsTemplate(); | |||
11014 | if (FirstTN.getKind() == TemplateName::Template && | |||
11015 | SecondTN.getKind() == TemplateName::Template) { | |||
11016 | if (FirstTN.getAsTemplateDecl()->getName() == | |||
11017 | SecondTN.getAsTemplateDecl()->getName()) { | |||
11018 | // FIXME: This fixes a bad diagnostic where both templates are named | |||
11019 | // the same. This particular case is a bit difficult since: | |||
11020 | // 1) It is passed as a string to the diagnostic printer. | |||
11021 | // 2) The diagnostic printer only attempts to find a better | |||
11022 | // name for types, not decls. | |||
11023 | // Ideally, this should folded into the diagnostic printer. | |||
11024 | S.Diag(Templated->getLocation(), | |||
11025 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) | |||
11026 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); | |||
11027 | return; | |||
11028 | } | |||
11029 | } | |||
11030 | } | |||
11031 | ||||
11032 | if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && | |||
11033 | !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) | |||
11034 | return; | |||
11035 | ||||
11036 | // FIXME: For generic lambda parameters, check if the function is a lambda | |||
11037 | // call operator, and if so, emit a prettier and more informative | |||
11038 | // diagnostic that mentions 'auto' and lambda in addition to | |||
11039 | // (or instead of?) the canonical template type parameters. | |||
11040 | S.Diag(Templated->getLocation(), | |||
11041 | diag::note_ovl_candidate_non_deduced_mismatch) | |||
11042 | << FirstTA << SecondTA; | |||
11043 | return; | |||
11044 | } | |||
11045 | // TODO: diagnose these individually, then kill off | |||
11046 | // note_ovl_candidate_bad_deduction, which is uselessly vague. | |||
11047 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
11048 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); | |||
11049 | MaybeEmitInheritedConstructorNote(S, Found); | |||
11050 | return; | |||
11051 | case Sema::TDK_CUDATargetMismatch: | |||
11052 | S.Diag(Templated->getLocation(), | |||
11053 | diag::note_cuda_ovl_candidate_target_mismatch); | |||
11054 | return; | |||
11055 | } | |||
11056 | } | |||
11057 | ||||
11058 | /// Diagnose a failed template-argument deduction, for function calls. | |||
11059 | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, | |||
11060 | unsigned NumArgs, | |||
11061 | bool TakingCandidateAddress) { | |||
11062 | unsigned TDK = Cand->DeductionFailure.Result; | |||
11063 | if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { | |||
11064 | if (CheckArityMismatch(S, Cand, NumArgs)) | |||
11065 | return; | |||
11066 | } | |||
11067 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern | |||
11068 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); | |||
11069 | } | |||
11070 | ||||
11071 | /// CUDA: diagnose an invalid call across targets. | |||
11072 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { | |||
11073 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); | |||
11074 | FunctionDecl *Callee = Cand->Function; | |||
11075 | ||||
11076 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), | |||
11077 | CalleeTarget = S.IdentifyCUDATarget(Callee); | |||
11078 | ||||
11079 | std::string FnDesc; | |||
11080 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
11081 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, | |||
11082 | Cand->getRewriteKind(), FnDesc); | |||
11083 | ||||
11084 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) | |||
11085 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template | |||
11086 | << FnDesc /* Ignored */ | |||
11087 | << CalleeTarget << CallerTarget; | |||
11088 | ||||
11089 | // This could be an implicit constructor for which we could not infer the | |||
11090 | // target due to a collsion. Diagnose that case. | |||
11091 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); | |||
11092 | if (Meth != nullptr && Meth->isImplicit()) { | |||
11093 | CXXRecordDecl *ParentClass = Meth->getParent(); | |||
11094 | Sema::CXXSpecialMember CSM; | |||
11095 | ||||
11096 | switch (FnKindPair.first) { | |||
11097 | default: | |||
11098 | return; | |||
11099 | case oc_implicit_default_constructor: | |||
11100 | CSM = Sema::CXXDefaultConstructor; | |||
11101 | break; | |||
11102 | case oc_implicit_copy_constructor: | |||
11103 | CSM = Sema::CXXCopyConstructor; | |||
11104 | break; | |||
11105 | case oc_implicit_move_constructor: | |||
11106 | CSM = Sema::CXXMoveConstructor; | |||
11107 | break; | |||
11108 | case oc_implicit_copy_assignment: | |||
11109 | CSM = Sema::CXXCopyAssignment; | |||
11110 | break; | |||
11111 | case oc_implicit_move_assignment: | |||
11112 | CSM = Sema::CXXMoveAssignment; | |||
11113 | break; | |||
11114 | }; | |||
11115 | ||||
11116 | bool ConstRHS = false; | |||
11117 | if (Meth->getNumParams()) { | |||
11118 | if (const ReferenceType *RT = | |||
11119 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { | |||
11120 | ConstRHS = RT->getPointeeType().isConstQualified(); | |||
11121 | } | |||
11122 | } | |||
11123 | ||||
11124 | S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, | |||
11125 | /* ConstRHS */ ConstRHS, | |||
11126 | /* Diagnose */ true); | |||
11127 | } | |||
11128 | } | |||
11129 | ||||
11130 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { | |||
11131 | FunctionDecl *Callee = Cand->Function; | |||
11132 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); | |||
11133 | ||||
11134 | S.Diag(Callee->getLocation(), | |||
11135 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
11136 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
11137 | } | |||
11138 | ||||
11139 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { | |||
11140 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); | |||
11141 | assert(ES.isExplicit() && "not an explicit candidate")(static_cast <bool> (ES.isExplicit() && "not an explicit candidate" ) ? void (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 11141, __extension__ __PRETTY_FUNCTION__ )); | |||
11142 | ||||
11143 | unsigned Kind; | |||
11144 | switch (Cand->Function->getDeclKind()) { | |||
11145 | case Decl::Kind::CXXConstructor: | |||
11146 | Kind = 0; | |||
11147 | break; | |||
11148 | case Decl::Kind::CXXConversion: | |||
11149 | Kind = 1; | |||
11150 | break; | |||
11151 | case Decl::Kind::CXXDeductionGuide: | |||
11152 | Kind = Cand->Function->isImplicit() ? 0 : 2; | |||
11153 | break; | |||
11154 | default: | |||
11155 | llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "clang/lib/Sema/SemaOverload.cpp" , 11155); | |||
11156 | } | |||
11157 | ||||
11158 | // Note the location of the first (in-class) declaration; a redeclaration | |||
11159 | // (particularly an out-of-class definition) will typically lack the | |||
11160 | // 'explicit' specifier. | |||
11161 | // FIXME: This is probably a good thing to do for all 'candidate' notes. | |||
11162 | FunctionDecl *First = Cand->Function->getFirstDecl(); | |||
11163 | if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) | |||
11164 | First = Pattern->getFirstDecl(); | |||
11165 | ||||
11166 | S.Diag(First->getLocation(), | |||
11167 | diag::note_ovl_candidate_explicit) | |||
11168 | << Kind << (ES.getExpr() ? 1 : 0) | |||
11169 | << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); | |||
11170 | } | |||
11171 | ||||
11172 | /// Generates a 'note' diagnostic for an overload candidate. We've | |||
11173 | /// already generated a primary error at the call site. | |||
11174 | /// | |||
11175 | /// It really does need to be a single diagnostic with its caret | |||
11176 | /// pointed at the candidate declaration. Yes, this creates some | |||
11177 | /// major challenges of technical writing. Yes, this makes pointing | |||
11178 | /// out problems with specific arguments quite awkward. It's still | |||
11179 | /// better than generating twenty screens of text for every failed | |||
11180 | /// overload. | |||
11181 | /// | |||
11182 | /// It would be great to be able to express per-candidate problems | |||
11183 | /// more richly for those diagnostic clients that cared, but we'd | |||
11184 | /// still have to be just as careful with the default diagnostics. | |||
11185 | /// \param CtorDestAS Addr space of object being constructed (for ctor | |||
11186 | /// candidates only). | |||
11187 | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, | |||
11188 | unsigned NumArgs, | |||
11189 | bool TakingCandidateAddress, | |||
11190 | LangAS CtorDestAS = LangAS::Default) { | |||
11191 | FunctionDecl *Fn = Cand->Function; | |||
11192 | if (shouldSkipNotingLambdaConversionDecl(Fn)) | |||
11193 | return; | |||
11194 | ||||
11195 | // Note deleted candidates, but only if they're viable. | |||
11196 | if (Cand->Viable) { | |||
11197 | if (Fn->isDeleted()) { | |||
11198 | std::string FnDesc; | |||
11199 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
11200 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, | |||
11201 | Cand->getRewriteKind(), FnDesc); | |||
11202 | ||||
11203 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) | |||
11204 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
11205 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); | |||
11206 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
11207 | return; | |||
11208 | } | |||
11209 | ||||
11210 | // We don't really have anything else to say about viable candidates. | |||
11211 | S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); | |||
11212 | return; | |||
11213 | } | |||
11214 | ||||
11215 | switch (Cand->FailureKind) { | |||
11216 | case ovl_fail_too_many_arguments: | |||
11217 | case ovl_fail_too_few_arguments: | |||
11218 | return DiagnoseArityMismatch(S, Cand, NumArgs); | |||
11219 | ||||
11220 | case ovl_fail_bad_deduction: | |||
11221 | return DiagnoseBadDeduction(S, Cand, NumArgs, | |||
11222 | TakingCandidateAddress); | |||
11223 | ||||
11224 | case ovl_fail_illegal_constructor: { | |||
11225 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) | |||
11226 | << (Fn->getPrimaryTemplate() ? 1 : 0); | |||
11227 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
11228 | return; | |||
11229 | } | |||
11230 | ||||
11231 | case ovl_fail_object_addrspace_mismatch: { | |||
11232 | Qualifiers QualsForPrinting; | |||
11233 | QualsForPrinting.setAddressSpace(CtorDestAS); | |||
11234 | S.Diag(Fn->getLocation(), | |||
11235 | diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) | |||
11236 | << QualsForPrinting; | |||
11237 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
11238 | return; | |||
11239 | } | |||
11240 | ||||
11241 | case ovl_fail_trivial_conversion: | |||
11242 | case ovl_fail_bad_final_conversion: | |||
11243 | case ovl_fail_final_conversion_not_exact: | |||
11244 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); | |||
11245 | ||||
11246 | case ovl_fail_bad_conversion: { | |||
11247 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); | |||
11248 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) | |||
11249 | if (Cand->Conversions[I].isBad()) | |||
11250 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); | |||
11251 | ||||
11252 | // FIXME: this currently happens when we're called from SemaInit | |||
11253 | // when user-conversion overload fails. Figure out how to handle | |||
11254 | // those conditions and diagnose them well. | |||
11255 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); | |||
11256 | } | |||
11257 | ||||
11258 | case ovl_fail_bad_target: | |||
11259 | return DiagnoseBadTarget(S, Cand); | |||
11260 | ||||
11261 | case ovl_fail_enable_if: | |||
11262 | return DiagnoseFailedEnableIfAttr(S, Cand); | |||
11263 | ||||
11264 | case ovl_fail_explicit: | |||
11265 | return DiagnoseFailedExplicitSpec(S, Cand); | |||
11266 | ||||
11267 | case ovl_fail_inhctor_slice: | |||
11268 | // It's generally not interesting to note copy/move constructors here. | |||
11269 | if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) | |||
11270 | return; | |||
11271 | S.Diag(Fn->getLocation(), | |||
11272 | diag::note_ovl_candidate_inherited_constructor_slice) | |||
11273 | << (Fn->getPrimaryTemplate() ? 1 : 0) | |||
11274 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); | |||
11275 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
11276 | return; | |||
11277 | ||||
11278 | case ovl_fail_addr_not_available: { | |||
11279 | bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); | |||
11280 | (void)Available; | |||
11281 | assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail ("!Available", "clang/lib/Sema/SemaOverload.cpp", 11281, __extension__ __PRETTY_FUNCTION__)); | |||
11282 | break; | |||
11283 | } | |||
11284 | case ovl_non_default_multiversion_function: | |||
11285 | // Do nothing, these should simply be ignored. | |||
11286 | break; | |||
11287 | ||||
11288 | case ovl_fail_constraints_not_satisfied: { | |||
11289 | std::string FnDesc; | |||
11290 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
11291 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, | |||
11292 | Cand->getRewriteKind(), FnDesc); | |||
11293 | ||||
11294 | S.Diag(Fn->getLocation(), | |||
11295 | diag::note_ovl_candidate_constraints_not_satisfied) | |||
11296 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template | |||
11297 | << FnDesc /* Ignored */; | |||
11298 | ConstraintSatisfaction Satisfaction; | |||
11299 | if (S.CheckFunctionConstraints(Fn, Satisfaction)) | |||
11300 | break; | |||
11301 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); | |||
11302 | } | |||
11303 | } | |||
11304 | } | |||
11305 | ||||
11306 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { | |||
11307 | if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) | |||
11308 | return; | |||
11309 | ||||
11310 | // Desugar the type of the surrogate down to a function type, | |||
11311 | // retaining as many typedefs as possible while still showing | |||
11312 | // the function type (and, therefore, its parameter types). | |||
11313 | QualType FnType = Cand->Surrogate->getConversionType(); | |||
11314 | bool isLValueReference = false; | |||
11315 | bool isRValueReference = false; | |||
11316 | bool isPointer = false; | |||
11317 | if (const LValueReferenceType *FnTypeRef = | |||
11318 | FnType->getAs<LValueReferenceType>()) { | |||
11319 | FnType = FnTypeRef->getPointeeType(); | |||
11320 | isLValueReference = true; | |||
11321 | } else if (const RValueReferenceType *FnTypeRef = | |||
11322 | FnType->getAs<RValueReferenceType>()) { | |||
11323 | FnType = FnTypeRef->getPointeeType(); | |||
11324 | isRValueReference = true; | |||
11325 | } | |||
11326 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { | |||
11327 | FnType = FnTypePtr->getPointeeType(); | |||
11328 | isPointer = true; | |||
11329 | } | |||
11330 | // Desugar down to a function type. | |||
11331 | FnType = QualType(FnType->getAs<FunctionType>(), 0); | |||
11332 | // Reconstruct the pointer/reference as appropriate. | |||
11333 | if (isPointer) FnType = S.Context.getPointerType(FnType); | |||
11334 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); | |||
11335 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); | |||
11336 | ||||
11337 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) | |||
11338 | << FnType; | |||
11339 | } | |||
11340 | ||||
11341 | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, | |||
11342 | SourceLocation OpLoc, | |||
11343 | OverloadCandidate *Cand) { | |||
11344 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast <bool> (Cand->Conversions.size() <= 2 && "builtin operator is not binary") ? void (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\"" , "clang/lib/Sema/SemaOverload.cpp", 11344, __extension__ __PRETTY_FUNCTION__ )); | |||
11345 | std::string TypeStr("operator"); | |||
11346 | TypeStr += Opc; | |||
11347 | TypeStr += "("; | |||
11348 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); | |||
11349 | if (Cand->Conversions.size() == 1) { | |||
11350 | TypeStr += ")"; | |||
11351 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; | |||
11352 | } else { | |||
11353 | TypeStr += ", "; | |||
11354 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); | |||
11355 | TypeStr += ")"; | |||
11356 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; | |||
11357 | } | |||
11358 | } | |||
11359 | ||||
11360 | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, | |||
11361 | OverloadCandidate *Cand) { | |||
11362 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { | |||
11363 | if (ICS.isBad()) break; // all meaningless after first invalid | |||
11364 | if (!ICS.isAmbiguous()) continue; | |||
11365 | ||||
11366 | ICS.DiagnoseAmbiguousConversion( | |||
11367 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); | |||
11368 | } | |||
11369 | } | |||
11370 | ||||
11371 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { | |||
11372 | if (Cand->Function) | |||
11373 | return Cand->Function->getLocation(); | |||
11374 | if (Cand->IsSurrogate) | |||
11375 | return Cand->Surrogate->getLocation(); | |||
11376 | return SourceLocation(); | |||
11377 | } | |||
11378 | ||||
11379 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { | |||
11380 | switch ((Sema::TemplateDeductionResult)DFI.Result) { | |||
11381 | case Sema::TDK_Success: | |||
11382 | case Sema::TDK_NonDependentConversionFailure: | |||
11383 | llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction" , "clang/lib/Sema/SemaOverload.cpp", 11383); | |||
11384 | ||||
11385 | case Sema::TDK_Invalid: | |||
11386 | case Sema::TDK_Incomplete: | |||
11387 | case Sema::TDK_IncompletePack: | |||
11388 | return 1; | |||
11389 | ||||
11390 | case Sema::TDK_Underqualified: | |||
11391 | case Sema::TDK_Inconsistent: | |||
11392 | return 2; | |||
11393 | ||||
11394 | case Sema::TDK_SubstitutionFailure: | |||
11395 | case Sema::TDK_DeducedMismatch: | |||
11396 | case Sema::TDK_ConstraintsNotSatisfied: | |||
11397 | case Sema::TDK_DeducedMismatchNested: | |||
11398 | case Sema::TDK_NonDeducedMismatch: | |||
11399 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
11400 | case Sema::TDK_CUDATargetMismatch: | |||
11401 | return 3; | |||
11402 | ||||
11403 | case Sema::TDK_InstantiationDepth: | |||
11404 | return 4; | |||
11405 | ||||
11406 | case Sema::TDK_InvalidExplicitArguments: | |||
11407 | return 5; | |||
11408 | ||||
11409 | case Sema::TDK_TooManyArguments: | |||
11410 | case Sema::TDK_TooFewArguments: | |||
11411 | return 6; | |||
11412 | } | |||
11413 | llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result" , "clang/lib/Sema/SemaOverload.cpp", 11413); | |||
11414 | } | |||
11415 | ||||
11416 | namespace { | |||
11417 | struct CompareOverloadCandidatesForDisplay { | |||
11418 | Sema &S; | |||
11419 | SourceLocation Loc; | |||
11420 | size_t NumArgs; | |||
11421 | OverloadCandidateSet::CandidateSetKind CSK; | |||
11422 | ||||
11423 | CompareOverloadCandidatesForDisplay( | |||
11424 | Sema &S, SourceLocation Loc, size_t NArgs, | |||
11425 | OverloadCandidateSet::CandidateSetKind CSK) | |||
11426 | : S(S), NumArgs(NArgs), CSK(CSK) {} | |||
11427 | ||||
11428 | OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { | |||
11429 | // If there are too many or too few arguments, that's the high-order bit we | |||
11430 | // want to sort by, even if the immediate failure kind was something else. | |||
11431 | if (C->FailureKind == ovl_fail_too_many_arguments || | |||
11432 | C->FailureKind == ovl_fail_too_few_arguments) | |||
11433 | return static_cast<OverloadFailureKind>(C->FailureKind); | |||
11434 | ||||
11435 | if (C->Function) { | |||
11436 | if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) | |||
11437 | return ovl_fail_too_many_arguments; | |||
11438 | if (NumArgs < C->Function->getMinRequiredArguments()) | |||
11439 | return ovl_fail_too_few_arguments; | |||
11440 | } | |||
11441 | ||||
11442 | return static_cast<OverloadFailureKind>(C->FailureKind); | |||
11443 | } | |||
11444 | ||||
11445 | bool operator()(const OverloadCandidate *L, | |||
11446 | const OverloadCandidate *R) { | |||
11447 | // Fast-path this check. | |||
11448 | if (L == R) return false; | |||
11449 | ||||
11450 | // Order first by viability. | |||
11451 | if (L->Viable) { | |||
11452 | if (!R->Viable) return true; | |||
11453 | ||||
11454 | // TODO: introduce a tri-valued comparison for overload | |||
11455 | // candidates. Would be more worthwhile if we had a sort | |||
11456 | // that could exploit it. | |||
11457 | if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) | |||
11458 | return true; | |||
11459 | if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) | |||
11460 | return false; | |||
11461 | } else if (R->Viable) | |||
11462 | return false; | |||
11463 | ||||
11464 | assert(L->Viable == R->Viable)(static_cast <bool> (L->Viable == R->Viable) ? void (0) : __assert_fail ("L->Viable == R->Viable", "clang/lib/Sema/SemaOverload.cpp" , 11464, __extension__ __PRETTY_FUNCTION__)); | |||
11465 | ||||
11466 | // Criteria by which we can sort non-viable candidates: | |||
11467 | if (!L->Viable) { | |||
11468 | OverloadFailureKind LFailureKind = EffectiveFailureKind(L); | |||
11469 | OverloadFailureKind RFailureKind = EffectiveFailureKind(R); | |||
11470 | ||||
11471 | // 1. Arity mismatches come after other candidates. | |||
11472 | if (LFailureKind == ovl_fail_too_many_arguments || | |||
11473 | LFailureKind == ovl_fail_too_few_arguments) { | |||
11474 | if (RFailureKind == ovl_fail_too_many_arguments || | |||
11475 | RFailureKind == ovl_fail_too_few_arguments) { | |||
11476 | int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); | |||
11477 | int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); | |||
11478 | if (LDist == RDist) { | |||
11479 | if (LFailureKind == RFailureKind) | |||
11480 | // Sort non-surrogates before surrogates. | |||
11481 | return !L->IsSurrogate && R->IsSurrogate; | |||
11482 | // Sort candidates requiring fewer parameters than there were | |||
11483 | // arguments given after candidates requiring more parameters | |||
11484 | // than there were arguments given. | |||
11485 | return LFailureKind == ovl_fail_too_many_arguments; | |||
11486 | } | |||
11487 | return LDist < RDist; | |||
11488 | } | |||
11489 | return false; | |||
11490 | } | |||
11491 | if (RFailureKind == ovl_fail_too_many_arguments || | |||
11492 | RFailureKind == ovl_fail_too_few_arguments) | |||
11493 | return true; | |||
11494 | ||||
11495 | // 2. Bad conversions come first and are ordered by the number | |||
11496 | // of bad conversions and quality of good conversions. | |||
11497 | if (LFailureKind == ovl_fail_bad_conversion) { | |||
11498 | if (RFailureKind != ovl_fail_bad_conversion) | |||
11499 | return true; | |||
11500 | ||||
11501 | // The conversion that can be fixed with a smaller number of changes, | |||
11502 | // comes first. | |||
11503 | unsigned numLFixes = L->Fix.NumConversionsFixed; | |||
11504 | unsigned numRFixes = R->Fix.NumConversionsFixed; | |||
11505 | numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; | |||
11506 | numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; | |||
11507 | if (numLFixes != numRFixes) { | |||
11508 | return numLFixes < numRFixes; | |||
11509 | } | |||
11510 | ||||
11511 | // If there's any ordering between the defined conversions... | |||
11512 | // FIXME: this might not be transitive. | |||
11513 | assert(L->Conversions.size() == R->Conversions.size())(static_cast <bool> (L->Conversions.size() == R-> Conversions.size()) ? void (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()" , "clang/lib/Sema/SemaOverload.cpp", 11513, __extension__ __PRETTY_FUNCTION__ )); | |||
11514 | ||||
11515 | int leftBetter = 0; | |||
11516 | unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); | |||
11517 | for (unsigned E = L->Conversions.size(); I != E; ++I) { | |||
11518 | switch (CompareImplicitConversionSequences(S, Loc, | |||
11519 | L->Conversions[I], | |||
11520 | R->Conversions[I])) { | |||
11521 | case ImplicitConversionSequence::Better: | |||
11522 | leftBetter++; | |||
11523 | break; | |||
11524 | ||||
11525 | case ImplicitConversionSequence::Worse: | |||
11526 | leftBetter--; | |||
11527 | break; | |||
11528 | ||||
11529 | case ImplicitConversionSequence::Indistinguishable: | |||
11530 | break; | |||
11531 | } | |||
11532 | } | |||
11533 | if (leftBetter > 0) return true; | |||
11534 | if (leftBetter < 0) return false; | |||
11535 | ||||
11536 | } else if (RFailureKind == ovl_fail_bad_conversion) | |||
11537 | return false; | |||
11538 | ||||
11539 | if (LFailureKind == ovl_fail_bad_deduction) { | |||
11540 | if (RFailureKind != ovl_fail_bad_deduction) | |||
11541 | return true; | |||
11542 | ||||
11543 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) | |||
11544 | return RankDeductionFailure(L->DeductionFailure) | |||
11545 | < RankDeductionFailure(R->DeductionFailure); | |||
11546 | } else if (RFailureKind == ovl_fail_bad_deduction) | |||
11547 | return false; | |||
11548 | ||||
11549 | // TODO: others? | |||
11550 | } | |||
11551 | ||||
11552 | // Sort everything else by location. | |||
11553 | SourceLocation LLoc = GetLocationForCandidate(L); | |||
11554 | SourceLocation RLoc = GetLocationForCandidate(R); | |||
11555 | ||||
11556 | // Put candidates without locations (e.g. builtins) at the end. | |||
11557 | if (LLoc.isInvalid()) return false; | |||
11558 | if (RLoc.isInvalid()) return true; | |||
11559 | ||||
11560 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); | |||
11561 | } | |||
11562 | }; | |||
11563 | } | |||
11564 | ||||
11565 | /// CompleteNonViableCandidate - Normally, overload resolution only | |||
11566 | /// computes up to the first bad conversion. Produces the FixIt set if | |||
11567 | /// possible. | |||
11568 | static void | |||
11569 | CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, | |||
11570 | ArrayRef<Expr *> Args, | |||
11571 | OverloadCandidateSet::CandidateSetKind CSK) { | |||
11572 | assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail ("!Cand->Viable", "clang/lib/Sema/SemaOverload.cpp", 11572 , __extension__ __PRETTY_FUNCTION__)); | |||
11573 | ||||
11574 | // Don't do anything on failures other than bad conversion. | |||
11575 | if (Cand->FailureKind != ovl_fail_bad_conversion) | |||
11576 | return; | |||
11577 | ||||
11578 | // We only want the FixIts if all the arguments can be corrected. | |||
11579 | bool Unfixable = false; | |||
11580 | // Use a implicit copy initialization to check conversion fixes. | |||
11581 | Cand->Fix.setConversionChecker(TryCopyInitialization); | |||
11582 | ||||
11583 | // Attempt to fix the bad conversion. | |||
11584 | unsigned ConvCount = Cand->Conversions.size(); | |||
11585 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; | |||
11586 | ++ConvIdx) { | |||
11587 | assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast <bool> (ConvIdx != ConvCount && "no bad conversion in candidate" ) ? void (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 11587, __extension__ __PRETTY_FUNCTION__ )); | |||
11588 | if (Cand->Conversions[ConvIdx].isInitialized() && | |||
11589 | Cand->Conversions[ConvIdx].isBad()) { | |||
11590 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); | |||
11591 | break; | |||
11592 | } | |||
11593 | } | |||
11594 | ||||
11595 | // FIXME: this should probably be preserved from the overload | |||
11596 | // operation somehow. | |||
11597 | bool SuppressUserConversions = false; | |||
11598 | ||||
11599 | unsigned ConvIdx = 0; | |||
11600 | unsigned ArgIdx = 0; | |||
11601 | ArrayRef<QualType> ParamTypes; | |||
11602 | bool Reversed = Cand->isReversed(); | |||
11603 | ||||
11604 | if (Cand->IsSurrogate) { | |||
11605 | QualType ConvType | |||
11606 | = Cand->Surrogate->getConversionType().getNonReferenceType(); | |||
11607 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
11608 | ConvType = ConvPtrType->getPointeeType(); | |||
11609 | ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); | |||
11610 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. | |||
11611 | ConvIdx = 1; | |||
11612 | } else if (Cand->Function) { | |||
11613 | ParamTypes = | |||
11614 | Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); | |||
11615 | if (isa<CXXMethodDecl>(Cand->Function) && | |||
11616 | !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { | |||
11617 | // Conversion 0 is 'this', which doesn't have a corresponding parameter. | |||
11618 | ConvIdx = 1; | |||
11619 | if (CSK == OverloadCandidateSet::CSK_Operator && | |||
11620 | Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && | |||
11621 | Cand->Function->getDeclName().getCXXOverloadedOperator() != | |||
11622 | OO_Subscript) | |||
11623 | // Argument 0 is 'this', which doesn't have a corresponding parameter. | |||
11624 | ArgIdx = 1; | |||
11625 | } | |||
11626 | } else { | |||
11627 | // Builtin operator. | |||
11628 | assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail ("ConvCount <= 3", "clang/lib/Sema/SemaOverload.cpp", 11628 , __extension__ __PRETTY_FUNCTION__)); | |||
11629 | ParamTypes = Cand->BuiltinParamTypes; | |||
11630 | } | |||
11631 | ||||
11632 | // Fill in the rest of the conversions. | |||
11633 | for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; | |||
11634 | ConvIdx != ConvCount; | |||
11635 | ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { | |||
11636 | assert(ArgIdx < Args.size() && "no argument for this arg conversion")(static_cast <bool> (ArgIdx < Args.size() && "no argument for this arg conversion") ? void (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\"" , "clang/lib/Sema/SemaOverload.cpp", 11636, __extension__ __PRETTY_FUNCTION__ )); | |||
11637 | if (Cand->Conversions[ConvIdx].isInitialized()) { | |||
11638 | // We've already checked this conversion. | |||
11639 | } else if (ParamIdx < ParamTypes.size()) { | |||
11640 | if (ParamTypes[ParamIdx]->isDependentType()) | |||
11641 | Cand->Conversions[ConvIdx].setAsIdentityConversion( | |||
11642 | Args[ArgIdx]->getType()); | |||
11643 | else { | |||
11644 | Cand->Conversions[ConvIdx] = | |||
11645 | TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], | |||
11646 | SuppressUserConversions, | |||
11647 | /*InOverloadResolution=*/true, | |||
11648 | /*AllowObjCWritebackConversion=*/ | |||
11649 | S.getLangOpts().ObjCAutoRefCount); | |||
11650 | // Store the FixIt in the candidate if it exists. | |||
11651 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) | |||
11652 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); | |||
11653 | } | |||
11654 | } else | |||
11655 | Cand->Conversions[ConvIdx].setEllipsis(); | |||
11656 | } | |||
11657 | } | |||
11658 | ||||
11659 | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( | |||
11660 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, | |||
11661 | SourceLocation OpLoc, | |||
11662 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { | |||
11663 | // Sort the candidates by viability and position. Sorting directly would | |||
11664 | // be prohibitive, so we make a set of pointers and sort those. | |||
11665 | SmallVector<OverloadCandidate*, 32> Cands; | |||
11666 | if (OCD == OCD_AllCandidates) Cands.reserve(size()); | |||
11667 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { | |||
11668 | if (!Filter(*Cand)) | |||
11669 | continue; | |||
11670 | switch (OCD) { | |||
11671 | case OCD_AllCandidates: | |||
11672 | if (!Cand->Viable) { | |||
11673 | if (!Cand->Function && !Cand->IsSurrogate) { | |||
11674 | // This a non-viable builtin candidate. We do not, in general, | |||
11675 | // want to list every possible builtin candidate. | |||
11676 | continue; | |||
11677 | } | |||
11678 | CompleteNonViableCandidate(S, Cand, Args, Kind); | |||
11679 | } | |||
11680 | break; | |||
11681 | ||||
11682 | case OCD_ViableCandidates: | |||
11683 | if (!Cand->Viable) | |||
11684 | continue; | |||
11685 | break; | |||
11686 | ||||
11687 | case OCD_AmbiguousCandidates: | |||
11688 | if (!Cand->Best) | |||
11689 | continue; | |||
11690 | break; | |||
11691 | } | |||
11692 | ||||
11693 | Cands.push_back(Cand); | |||
11694 | } | |||
11695 | ||||
11696 | llvm::stable_sort( | |||
11697 | Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); | |||
11698 | ||||
11699 | return Cands; | |||
11700 | } | |||
11701 | ||||
11702 | bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, | |||
11703 | SourceLocation OpLoc) { | |||
11704 | bool DeferHint = false; | |||
11705 | if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { | |||
11706 | // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or | |||
11707 | // host device candidates. | |||
11708 | auto WrongSidedCands = | |||
11709 | CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { | |||
11710 | return (Cand.Viable == false && | |||
11711 | Cand.FailureKind == ovl_fail_bad_target) || | |||
11712 | (Cand.Function && | |||
11713 | Cand.Function->template hasAttr<CUDAHostAttr>() && | |||
11714 | Cand.Function->template hasAttr<CUDADeviceAttr>()); | |||
11715 | }); | |||
11716 | DeferHint = !WrongSidedCands.empty(); | |||
11717 | } | |||
11718 | return DeferHint; | |||
11719 | } | |||
11720 | ||||
11721 | /// When overload resolution fails, prints diagnostic messages containing the | |||
11722 | /// candidates in the candidate set. | |||
11723 | void OverloadCandidateSet::NoteCandidates( | |||
11724 | PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, | |||
11725 | ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, | |||
11726 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { | |||
11727 | ||||
11728 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); | |||
11729 | ||||
11730 | S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); | |||
11731 | ||||
11732 | NoteCandidates(S, Args, Cands, Opc, OpLoc); | |||
11733 | ||||
11734 | if (OCD == OCD_AmbiguousCandidates) | |||
11735 | MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); | |||
11736 | } | |||
11737 | ||||
11738 | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, | |||
11739 | ArrayRef<OverloadCandidate *> Cands, | |||
11740 | StringRef Opc, SourceLocation OpLoc) { | |||
11741 | bool ReportedAmbiguousConversions = false; | |||
11742 | ||||
11743 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); | |||
11744 | unsigned CandsShown = 0; | |||
11745 | auto I = Cands.begin(), E = Cands.end(); | |||
11746 | for (; I != E; ++I) { | |||
11747 | OverloadCandidate *Cand = *I; | |||
11748 | ||||
11749 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && | |||
11750 | ShowOverloads == Ovl_Best) { | |||
11751 | break; | |||
11752 | } | |||
11753 | ++CandsShown; | |||
11754 | ||||
11755 | if (Cand->Function) | |||
11756 | NoteFunctionCandidate(S, Cand, Args.size(), | |||
11757 | /*TakingCandidateAddress=*/false, DestAS); | |||
11758 | else if (Cand->IsSurrogate) | |||
11759 | NoteSurrogateCandidate(S, Cand); | |||
11760 | else { | |||
11761 | assert(Cand->Viable &&(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 11762, __extension__ __PRETTY_FUNCTION__ )) | |||
11762 | "Non-viable built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 11762, __extension__ __PRETTY_FUNCTION__ )); | |||
11763 | // Generally we only see ambiguities including viable builtin | |||
11764 | // operators if overload resolution got screwed up by an | |||
11765 | // ambiguous user-defined conversion. | |||
11766 | // | |||
11767 | // FIXME: It's quite possible for different conversions to see | |||
11768 | // different ambiguities, though. | |||
11769 | if (!ReportedAmbiguousConversions) { | |||
11770 | NoteAmbiguousUserConversions(S, OpLoc, Cand); | |||
11771 | ReportedAmbiguousConversions = true; | |||
11772 | } | |||
11773 | ||||
11774 | // If this is a viable builtin, print it. | |||
11775 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); | |||
11776 | } | |||
11777 | } | |||
11778 | ||||
11779 | // Inform S.Diags that we've shown an overload set with N elements. This may | |||
11780 | // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). | |||
11781 | S.Diags.overloadCandidatesShown(CandsShown); | |||
11782 | ||||
11783 | if (I != E) | |||
11784 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates, | |||
11785 | shouldDeferDiags(S, Args, OpLoc)) | |||
11786 | << int(E - I); | |||
11787 | } | |||
11788 | ||||
11789 | static SourceLocation | |||
11790 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { | |||
11791 | return Cand->Specialization ? Cand->Specialization->getLocation() | |||
11792 | : SourceLocation(); | |||
11793 | } | |||
11794 | ||||
11795 | namespace { | |||
11796 | struct CompareTemplateSpecCandidatesForDisplay { | |||
11797 | Sema &S; | |||
11798 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} | |||
11799 | ||||
11800 | bool operator()(const TemplateSpecCandidate *L, | |||
11801 | const TemplateSpecCandidate *R) { | |||
11802 | // Fast-path this check. | |||
11803 | if (L == R) | |||
11804 | return false; | |||
11805 | ||||
11806 | // Assuming that both candidates are not matches... | |||
11807 | ||||
11808 | // Sort by the ranking of deduction failures. | |||
11809 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) | |||
11810 | return RankDeductionFailure(L->DeductionFailure) < | |||
11811 | RankDeductionFailure(R->DeductionFailure); | |||
11812 | ||||
11813 | // Sort everything else by location. | |||
11814 | SourceLocation LLoc = GetLocationForCandidate(L); | |||
11815 | SourceLocation RLoc = GetLocationForCandidate(R); | |||
11816 | ||||
11817 | // Put candidates without locations (e.g. builtins) at the end. | |||
11818 | if (LLoc.isInvalid()) | |||
11819 | return false; | |||
11820 | if (RLoc.isInvalid()) | |||
11821 | return true; | |||
11822 | ||||
11823 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); | |||
11824 | } | |||
11825 | }; | |||
11826 | } | |||
11827 | ||||
11828 | /// Diagnose a template argument deduction failure. | |||
11829 | /// We are treating these failures as overload failures due to bad | |||
11830 | /// deductions. | |||
11831 | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, | |||
11832 | bool ForTakingAddress) { | |||
11833 | DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern | |||
11834 | DeductionFailure, /*NumArgs=*/0, ForTakingAddress); | |||
11835 | } | |||
11836 | ||||
11837 | void TemplateSpecCandidateSet::destroyCandidates() { | |||
11838 | for (iterator i = begin(), e = end(); i != e; ++i) { | |||
11839 | i->DeductionFailure.Destroy(); | |||
11840 | } | |||
11841 | } | |||
11842 | ||||
11843 | void TemplateSpecCandidateSet::clear() { | |||
11844 | destroyCandidates(); | |||
11845 | Candidates.clear(); | |||
11846 | } | |||
11847 | ||||
11848 | /// NoteCandidates - When no template specialization match is found, prints | |||
11849 | /// diagnostic messages containing the non-matching specializations that form | |||
11850 | /// the candidate set. | |||
11851 | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with | |||
11852 | /// OCD == OCD_AllCandidates and Cand->Viable == false. | |||
11853 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { | |||
11854 | // Sort the candidates by position (assuming no candidate is a match). | |||
11855 | // Sorting directly would be prohibitive, so we make a set of pointers | |||
11856 | // and sort those. | |||
11857 | SmallVector<TemplateSpecCandidate *, 32> Cands; | |||
11858 | Cands.reserve(size()); | |||
11859 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { | |||
11860 | if (Cand->Specialization) | |||
11861 | Cands.push_back(Cand); | |||
11862 | // Otherwise, this is a non-matching builtin candidate. We do not, | |||
11863 | // in general, want to list every possible builtin candidate. | |||
11864 | } | |||
11865 | ||||
11866 | llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); | |||
11867 | ||||
11868 | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() | |||
11869 | // for generalization purposes (?). | |||
11870 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); | |||
11871 | ||||
11872 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; | |||
11873 | unsigned CandsShown = 0; | |||
11874 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { | |||
11875 | TemplateSpecCandidate *Cand = *I; | |||
11876 | ||||
11877 | // Set an arbitrary limit on the number of candidates we'll spam | |||
11878 | // the user with. FIXME: This limit should depend on details of the | |||
11879 | // candidate list. | |||
11880 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) | |||
11881 | break; | |||
11882 | ++CandsShown; | |||
11883 | ||||
11884 | assert(Cand->Specialization &&(static_cast <bool> (Cand->Specialization && "Non-matching built-in candidates are not added to Cands.") ? void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 11885, __extension__ __PRETTY_FUNCTION__ )) | |||
11885 | "Non-matching built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Specialization && "Non-matching built-in candidates are not added to Cands.") ? void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "clang/lib/Sema/SemaOverload.cpp", 11885, __extension__ __PRETTY_FUNCTION__ )); | |||
11886 | Cand->NoteDeductionFailure(S, ForTakingAddress); | |||
11887 | } | |||
11888 | ||||
11889 | if (I != E) | |||
11890 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); | |||
11891 | } | |||
11892 | ||||
11893 | // [PossiblyAFunctionType] --> [Return] | |||
11894 | // NonFunctionType --> NonFunctionType | |||
11895 | // R (A) --> R(A) | |||
11896 | // R (*)(A) --> R (A) | |||
11897 | // R (&)(A) --> R (A) | |||
11898 | // R (S::*)(A) --> R (A) | |||
11899 | QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { | |||
11900 | QualType Ret = PossiblyAFunctionType; | |||
11901 | if (const PointerType *ToTypePtr = | |||
11902 | PossiblyAFunctionType->getAs<PointerType>()) | |||
11903 | Ret = ToTypePtr->getPointeeType(); | |||
11904 | else if (const ReferenceType *ToTypeRef = | |||
11905 | PossiblyAFunctionType->getAs<ReferenceType>()) | |||
11906 | Ret = ToTypeRef->getPointeeType(); | |||
11907 | else if (const MemberPointerType *MemTypePtr = | |||
11908 | PossiblyAFunctionType->getAs<MemberPointerType>()) | |||
11909 | Ret = MemTypePtr->getPointeeType(); | |||
11910 | Ret = | |||
11911 | Context.getCanonicalType(Ret).getUnqualifiedType(); | |||
11912 | return Ret; | |||
11913 | } | |||
11914 | ||||
11915 | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, | |||
11916 | bool Complain = true) { | |||
11917 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
11918 | S.DeduceReturnType(FD, Loc, Complain)) | |||
11919 | return true; | |||
11920 | ||||
11921 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); | |||
11922 | if (S.getLangOpts().CPlusPlus17 && | |||
11923 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && | |||
11924 | !S.ResolveExceptionSpec(Loc, FPT)) | |||
11925 | return true; | |||
11926 | ||||
11927 | return false; | |||
11928 | } | |||
11929 | ||||
11930 | namespace { | |||
11931 | // A helper class to help with address of function resolution | |||
11932 | // - allows us to avoid passing around all those ugly parameters | |||
11933 | class AddressOfFunctionResolver { | |||
11934 | Sema& S; | |||
11935 | Expr* SourceExpr; | |||
11936 | const QualType& TargetType; | |||
11937 | QualType TargetFunctionType; // Extracted function type from target type | |||
11938 | ||||
11939 | bool Complain; | |||
11940 | //DeclAccessPair& ResultFunctionAccessPair; | |||
11941 | ASTContext& Context; | |||
11942 | ||||
11943 | bool TargetTypeIsNonStaticMemberFunction; | |||
11944 | bool FoundNonTemplateFunction; | |||
11945 | bool StaticMemberFunctionFromBoundPointer; | |||
11946 | bool HasComplained; | |||
11947 | ||||
11948 | OverloadExpr::FindResult OvlExprInfo; | |||
11949 | OverloadExpr *OvlExpr; | |||
11950 | TemplateArgumentListInfo OvlExplicitTemplateArgs; | |||
11951 | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; | |||
11952 | TemplateSpecCandidateSet FailedCandidates; | |||
11953 | ||||
11954 | public: | |||
11955 | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, | |||
11956 | const QualType &TargetType, bool Complain) | |||
11957 | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), | |||
11958 | Complain(Complain), Context(S.getASTContext()), | |||
11959 | TargetTypeIsNonStaticMemberFunction( | |||
11960 | !!TargetType->getAs<MemberPointerType>()), | |||
11961 | FoundNonTemplateFunction(false), | |||
11962 | StaticMemberFunctionFromBoundPointer(false), | |||
11963 | HasComplained(false), | |||
11964 | OvlExprInfo(OverloadExpr::find(SourceExpr)), | |||
11965 | OvlExpr(OvlExprInfo.Expression), | |||
11966 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { | |||
11967 | ExtractUnqualifiedFunctionTypeFromTargetType(); | |||
11968 | ||||
11969 | if (TargetFunctionType->isFunctionType()) { | |||
11970 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) | |||
11971 | if (!UME->isImplicitAccess() && | |||
11972 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) | |||
11973 | StaticMemberFunctionFromBoundPointer = true; | |||
11974 | } else if (OvlExpr->hasExplicitTemplateArgs()) { | |||
11975 | DeclAccessPair dap; | |||
11976 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( | |||
11977 | OvlExpr, false, &dap)) { | |||
11978 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) | |||
11979 | if (!Method->isStatic()) { | |||
11980 | // If the target type is a non-function type and the function found | |||
11981 | // is a non-static member function, pretend as if that was the | |||
11982 | // target, it's the only possible type to end up with. | |||
11983 | TargetTypeIsNonStaticMemberFunction = true; | |||
11984 | ||||
11985 | // And skip adding the function if its not in the proper form. | |||
11986 | // We'll diagnose this due to an empty set of functions. | |||
11987 | if (!OvlExprInfo.HasFormOfMemberPointer) | |||
11988 | return; | |||
11989 | } | |||
11990 | ||||
11991 | Matches.push_back(std::make_pair(dap, Fn)); | |||
11992 | } | |||
11993 | return; | |||
11994 | } | |||
11995 | ||||
11996 | if (OvlExpr->hasExplicitTemplateArgs()) | |||
11997 | OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); | |||
11998 | ||||
11999 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { | |||
12000 | // C++ [over.over]p4: | |||
12001 | // If more than one function is selected, [...] | |||
12002 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { | |||
12003 | if (FoundNonTemplateFunction) | |||
12004 | EliminateAllTemplateMatches(); | |||
12005 | else | |||
12006 | EliminateAllExceptMostSpecializedTemplate(); | |||
12007 | } | |||
12008 | } | |||
12009 | ||||
12010 | if (S.getLangOpts().CUDA && Matches.size() > 1) | |||
12011 | EliminateSuboptimalCudaMatches(); | |||
12012 | } | |||
12013 | ||||
12014 | bool hasComplained() const { return HasComplained; } | |||
12015 | ||||
12016 | private: | |||
12017 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { | |||
12018 | QualType Discard; | |||
12019 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || | |||
12020 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); | |||
12021 | } | |||
12022 | ||||
12023 | /// \return true if A is considered a better overload candidate for the | |||
12024 | /// desired type than B. | |||
12025 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { | |||
12026 | // If A doesn't have exactly the correct type, we don't want to classify it | |||
12027 | // as "better" than anything else. This way, the user is required to | |||
12028 | // disambiguate for us if there are multiple candidates and no exact match. | |||
12029 | return candidateHasExactlyCorrectType(A) && | |||
12030 | (!candidateHasExactlyCorrectType(B) || | |||
12031 | compareEnableIfAttrs(S, A, B) == Comparison::Better); | |||
12032 | } | |||
12033 | ||||
12034 | /// \return true if we were able to eliminate all but one overload candidate, | |||
12035 | /// false otherwise. | |||
12036 | bool eliminiateSuboptimalOverloadCandidates() { | |||
12037 | // Same algorithm as overload resolution -- one pass to pick the "best", | |||
12038 | // another pass to be sure that nothing is better than the best. | |||
12039 | auto Best = Matches.begin(); | |||
12040 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) | |||
12041 | if (isBetterCandidate(I->second, Best->second)) | |||
12042 | Best = I; | |||
12043 | ||||
12044 | const FunctionDecl *BestFn = Best->second; | |||
12045 | auto IsBestOrInferiorToBest = [this, BestFn]( | |||
12046 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { | |||
12047 | return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); | |||
12048 | }; | |||
12049 | ||||
12050 | // Note: We explicitly leave Matches unmodified if there isn't a clear best | |||
12051 | // option, so we can potentially give the user a better error | |||
12052 | if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) | |||
12053 | return false; | |||
12054 | Matches[0] = *Best; | |||
12055 | Matches.resize(1); | |||
12056 | return true; | |||
12057 | } | |||
12058 | ||||
12059 | bool isTargetTypeAFunction() const { | |||
12060 | return TargetFunctionType->isFunctionType(); | |||
12061 | } | |||
12062 | ||||
12063 | // [ToType] [Return] | |||
12064 | ||||
12065 | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false | |||
12066 | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false | |||
12067 | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true | |||
12068 | void inline ExtractUnqualifiedFunctionTypeFromTargetType() { | |||
12069 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); | |||
12070 | } | |||
12071 | ||||
12072 | // return true if any matching specializations were found | |||
12073 | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, | |||
12074 | const DeclAccessPair& CurAccessFunPair) { | |||
12075 | if (CXXMethodDecl *Method | |||
12076 | = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { | |||
12077 | // Skip non-static function templates when converting to pointer, and | |||
12078 | // static when converting to member pointer. | |||
12079 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) | |||
12080 | return false; | |||
12081 | } | |||
12082 | else if (TargetTypeIsNonStaticMemberFunction) | |||
12083 | return false; | |||
12084 | ||||
12085 | // C++ [over.over]p2: | |||
12086 | // If the name is a function template, template argument deduction is | |||
12087 | // done (14.8.2.2), and if the argument deduction succeeds, the | |||
12088 | // resulting template argument list is used to generate a single | |||
12089 | // function template specialization, which is added to the set of | |||
12090 | // overloaded functions considered. | |||
12091 | FunctionDecl *Specialization = nullptr; | |||
12092 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); | |||
12093 | if (Sema::TemplateDeductionResult Result | |||
12094 | = S.DeduceTemplateArguments(FunctionTemplate, | |||
12095 | &OvlExplicitTemplateArgs, | |||
12096 | TargetFunctionType, Specialization, | |||
12097 | Info, /*IsAddressOfFunction*/true)) { | |||
12098 | // Make a note of the failed deduction for diagnostics. | |||
12099 | FailedCandidates.addCandidate() | |||
12100 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), | |||
12101 | MakeDeductionFailureInfo(Context, Result, Info)); | |||
12102 | return false; | |||
12103 | } | |||
12104 | ||||
12105 | // Template argument deduction ensures that we have an exact match or | |||
12106 | // compatible pointer-to-function arguments that would be adjusted by ICS. | |||
12107 | // This function template specicalization works. | |||
12108 | assert(S.isSameOrCompatibleFunctionType((static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__ )) | |||
12109 | Context.getCanonicalType(Specialization->getType()),(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__ )) | |||
12110 | Context.getCanonicalType(TargetFunctionType)))(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context .getCanonicalType(Specialization->getType()), Context.getCanonicalType (TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__ )); | |||
12111 | ||||
12112 | if (!S.checkAddressOfFunctionIsAvailable(Specialization)) | |||
12113 | return false; | |||
12114 | ||||
12115 | Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); | |||
12116 | return true; | |||
12117 | } | |||
12118 | ||||
12119 | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, | |||
12120 | const DeclAccessPair& CurAccessFunPair) { | |||
12121 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { | |||
12122 | // Skip non-static functions when converting to pointer, and static | |||
12123 | // when converting to member pointer. | |||
12124 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) | |||
12125 | return false; | |||
12126 | } | |||
12127 | else if (TargetTypeIsNonStaticMemberFunction) | |||
12128 | return false; | |||
12129 | ||||
12130 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { | |||
12131 | if (S.getLangOpts().CUDA) | |||
12132 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) | |||
12133 | if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) | |||
12134 | return false; | |||
12135 | if (FunDecl->isMultiVersion()) { | |||
12136 | const auto *TA = FunDecl->getAttr<TargetAttr>(); | |||
12137 | if (TA && !TA->isDefaultVersion()) | |||
12138 | return false; | |||
12139 | } | |||
12140 | ||||
12141 | // If any candidate has a placeholder return type, trigger its deduction | |||
12142 | // now. | |||
12143 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), | |||
12144 | Complain)) { | |||
12145 | HasComplained |= Complain; | |||
12146 | return false; | |||
12147 | } | |||
12148 | ||||
12149 | if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) | |||
12150 | return false; | |||
12151 | ||||
12152 | // If we're in C, we need to support types that aren't exactly identical. | |||
12153 | if (!S.getLangOpts().CPlusPlus || | |||
12154 | candidateHasExactlyCorrectType(FunDecl)) { | |||
12155 | Matches.push_back(std::make_pair( | |||
12156 | CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); | |||
12157 | FoundNonTemplateFunction = true; | |||
12158 | return true; | |||
12159 | } | |||
12160 | } | |||
12161 | ||||
12162 | return false; | |||
12163 | } | |||
12164 | ||||
12165 | bool FindAllFunctionsThatMatchTargetTypeExactly() { | |||
12166 | bool Ret = false; | |||
12167 | ||||
12168 | // If the overload expression doesn't have the form of a pointer to | |||
12169 | // member, don't try to convert it to a pointer-to-member type. | |||
12170 | if (IsInvalidFormOfPointerToMemberFunction()) | |||
12171 | return false; | |||
12172 | ||||
12173 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
12174 | E = OvlExpr->decls_end(); | |||
12175 | I != E; ++I) { | |||
12176 | // Look through any using declarations to find the underlying function. | |||
12177 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); | |||
12178 | ||||
12179 | // C++ [over.over]p3: | |||
12180 | // Non-member functions and static member functions match | |||
12181 | // targets of type "pointer-to-function" or "reference-to-function." | |||
12182 | // Nonstatic member functions match targets of | |||
12183 | // type "pointer-to-member-function." | |||
12184 | // Note that according to DR 247, the containing class does not matter. | |||
12185 | if (FunctionTemplateDecl *FunctionTemplate | |||
12186 | = dyn_cast<FunctionTemplateDecl>(Fn)) { | |||
12187 | if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) | |||
12188 | Ret = true; | |||
12189 | } | |||
12190 | // If we have explicit template arguments supplied, skip non-templates. | |||
12191 | else if (!OvlExpr->hasExplicitTemplateArgs() && | |||
12192 | AddMatchingNonTemplateFunction(Fn, I.getPair())) | |||
12193 | Ret = true; | |||
12194 | } | |||
12195 | assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0) : __assert_fail ("Ret || Matches.empty()", "clang/lib/Sema/SemaOverload.cpp" , 12195, __extension__ __PRETTY_FUNCTION__)); | |||
12196 | return Ret; | |||
12197 | } | |||
12198 | ||||
12199 | void EliminateAllExceptMostSpecializedTemplate() { | |||
12200 | // [...] and any given function template specialization F1 is | |||
12201 | // eliminated if the set contains a second function template | |||
12202 | // specialization whose function template is more specialized | |||
12203 | // than the function template of F1 according to the partial | |||
12204 | // ordering rules of 14.5.5.2. | |||
12205 | ||||
12206 | // The algorithm specified above is quadratic. We instead use a | |||
12207 | // two-pass algorithm (similar to the one used to identify the | |||
12208 | // best viable function in an overload set) that identifies the | |||
12209 | // best function template (if it exists). | |||
12210 | ||||
12211 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! | |||
12212 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) | |||
12213 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); | |||
12214 | ||||
12215 | // TODO: It looks like FailedCandidates does not serve much purpose | |||
12216 | // here, since the no_viable diagnostic has index 0. | |||
12217 | UnresolvedSetIterator Result = S.getMostSpecialized( | |||
12218 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, | |||
12219 | SourceExpr->getBeginLoc(), S.PDiag(), | |||
12220 | S.PDiag(diag::err_addr_ovl_ambiguous) | |||
12221 | << Matches[0].second->getDeclName(), | |||
12222 | S.PDiag(diag::note_ovl_candidate) | |||
12223 | << (unsigned)oc_function << (unsigned)ocs_described_template, | |||
12224 | Complain, TargetFunctionType); | |||
12225 | ||||
12226 | if (Result != MatchesCopy.end()) { | |||
12227 | // Make it the first and only element | |||
12228 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; | |||
12229 | Matches[0].second = cast<FunctionDecl>(*Result); | |||
12230 | Matches.resize(1); | |||
12231 | } else | |||
12232 | HasComplained |= Complain; | |||
12233 | } | |||
12234 | ||||
12235 | void EliminateAllTemplateMatches() { | |||
12236 | // [...] any function template specializations in the set are | |||
12237 | // eliminated if the set also contains a non-template function, [...] | |||
12238 | for (unsigned I = 0, N = Matches.size(); I != N; ) { | |||
12239 | if (Matches[I].second->getPrimaryTemplate() == nullptr) | |||
12240 | ++I; | |||
12241 | else { | |||
12242 | Matches[I] = Matches[--N]; | |||
12243 | Matches.resize(N); | |||
12244 | } | |||
12245 | } | |||
12246 | } | |||
12247 | ||||
12248 | void EliminateSuboptimalCudaMatches() { | |||
12249 | S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), | |||
12250 | Matches); | |||
12251 | } | |||
12252 | ||||
12253 | public: | |||
12254 | void ComplainNoMatchesFound() const { | |||
12255 | assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail ("Matches.empty()", "clang/lib/Sema/SemaOverload.cpp", 12255 , __extension__ __PRETTY_FUNCTION__)); | |||
12256 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) | |||
12257 | << OvlExpr->getName() << TargetFunctionType | |||
12258 | << OvlExpr->getSourceRange(); | |||
12259 | if (FailedCandidates.empty()) | |||
12260 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, | |||
12261 | /*TakingAddress=*/true); | |||
12262 | else { | |||
12263 | // We have some deduction failure messages. Use them to diagnose | |||
12264 | // the function templates, and diagnose the non-template candidates | |||
12265 | // normally. | |||
12266 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
12267 | IEnd = OvlExpr->decls_end(); | |||
12268 | I != IEnd; ++I) | |||
12269 | if (FunctionDecl *Fun = | |||
12270 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) | |||
12271 | if (!functionHasPassObjectSizeParams(Fun)) | |||
12272 | S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, | |||
12273 | /*TakingAddress=*/true); | |||
12274 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); | |||
12275 | } | |||
12276 | } | |||
12277 | ||||
12278 | bool IsInvalidFormOfPointerToMemberFunction() const { | |||
12279 | return TargetTypeIsNonStaticMemberFunction && | |||
12280 | !OvlExprInfo.HasFormOfMemberPointer; | |||
12281 | } | |||
12282 | ||||
12283 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { | |||
12284 | // TODO: Should we condition this on whether any functions might | |||
12285 | // have matched, or is it more appropriate to do that in callers? | |||
12286 | // TODO: a fixit wouldn't hurt. | |||
12287 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) | |||
12288 | << TargetType << OvlExpr->getSourceRange(); | |||
12289 | } | |||
12290 | ||||
12291 | bool IsStaticMemberFunctionFromBoundPointer() const { | |||
12292 | return StaticMemberFunctionFromBoundPointer; | |||
12293 | } | |||
12294 | ||||
12295 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { | |||
12296 | S.Diag(OvlExpr->getBeginLoc(), | |||
12297 | diag::err_invalid_form_pointer_member_function) | |||
12298 | << OvlExpr->getSourceRange(); | |||
12299 | } | |||
12300 | ||||
12301 | void ComplainOfInvalidConversion() const { | |||
12302 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) | |||
12303 | << OvlExpr->getName() << TargetType; | |||
12304 | } | |||
12305 | ||||
12306 | void ComplainMultipleMatchesFound() const { | |||
12307 | assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) : __assert_fail ("Matches.size() > 1", "clang/lib/Sema/SemaOverload.cpp" , 12307, __extension__ __PRETTY_FUNCTION__)); | |||
12308 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) | |||
12309 | << OvlExpr->getName() << OvlExpr->getSourceRange(); | |||
12310 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, | |||
12311 | /*TakingAddress=*/true); | |||
12312 | } | |||
12313 | ||||
12314 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } | |||
12315 | ||||
12316 | int getNumMatches() const { return Matches.size(); } | |||
12317 | ||||
12318 | FunctionDecl* getMatchingFunctionDecl() const { | |||
12319 | if (Matches.size() != 1) return nullptr; | |||
12320 | return Matches[0].second; | |||
12321 | } | |||
12322 | ||||
12323 | const DeclAccessPair* getMatchingFunctionAccessPair() const { | |||
12324 | if (Matches.size() != 1) return nullptr; | |||
12325 | return &Matches[0].first; | |||
12326 | } | |||
12327 | }; | |||
12328 | } | |||
12329 | ||||
12330 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of | |||
12331 | /// an overloaded function (C++ [over.over]), where @p From is an | |||
12332 | /// expression with overloaded function type and @p ToType is the type | |||
12333 | /// we're trying to resolve to. For example: | |||
12334 | /// | |||
12335 | /// @code | |||
12336 | /// int f(double); | |||
12337 | /// int f(int); | |||
12338 | /// | |||
12339 | /// int (*pfd)(double) = f; // selects f(double) | |||
12340 | /// @endcode | |||
12341 | /// | |||
12342 | /// This routine returns the resulting FunctionDecl if it could be | |||
12343 | /// resolved, and NULL otherwise. When @p Complain is true, this | |||
12344 | /// routine will emit diagnostics if there is an error. | |||
12345 | FunctionDecl * | |||
12346 | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, | |||
12347 | QualType TargetType, | |||
12348 | bool Complain, | |||
12349 | DeclAccessPair &FoundResult, | |||
12350 | bool *pHadMultipleCandidates) { | |||
12351 | assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast <bool> (AddressOfExpr->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 12351, __extension__ __PRETTY_FUNCTION__ )); | |||
12352 | ||||
12353 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, | |||
12354 | Complain); | |||
12355 | int NumMatches = Resolver.getNumMatches(); | |||
12356 | FunctionDecl *Fn = nullptr; | |||
12357 | bool ShouldComplain = Complain && !Resolver.hasComplained(); | |||
12358 | if (NumMatches == 0 && ShouldComplain) { | |||
12359 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) | |||
12360 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); | |||
12361 | else | |||
12362 | Resolver.ComplainNoMatchesFound(); | |||
12363 | } | |||
12364 | else if (NumMatches > 1 && ShouldComplain) | |||
12365 | Resolver.ComplainMultipleMatchesFound(); | |||
12366 | else if (NumMatches == 1) { | |||
12367 | Fn = Resolver.getMatchingFunctionDecl(); | |||
12368 | assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn" , "clang/lib/Sema/SemaOverload.cpp", 12368, __extension__ __PRETTY_FUNCTION__ )); | |||
12369 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) | |||
12370 | ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); | |||
12371 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); | |||
12372 | if (Complain) { | |||
12373 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) | |||
12374 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); | |||
12375 | else | |||
12376 | CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); | |||
12377 | } | |||
12378 | } | |||
12379 | ||||
12380 | if (pHadMultipleCandidates) | |||
12381 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); | |||
12382 | return Fn; | |||
12383 | } | |||
12384 | ||||
12385 | /// Given an expression that refers to an overloaded function, try to | |||
12386 | /// resolve that function to a single function that can have its address taken. | |||
12387 | /// This will modify `Pair` iff it returns non-null. | |||
12388 | /// | |||
12389 | /// This routine can only succeed if from all of the candidates in the overload | |||
12390 | /// set for SrcExpr that can have their addresses taken, there is one candidate | |||
12391 | /// that is more constrained than the rest. | |||
12392 | FunctionDecl * | |||
12393 | Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { | |||
12394 | OverloadExpr::FindResult R = OverloadExpr::find(E); | |||
12395 | OverloadExpr *Ovl = R.Expression; | |||
12396 | bool IsResultAmbiguous = false; | |||
12397 | FunctionDecl *Result = nullptr; | |||
12398 | DeclAccessPair DAP; | |||
12399 | SmallVector<FunctionDecl *, 2> AmbiguousDecls; | |||
12400 | ||||
12401 | auto CheckMoreConstrained = | |||
12402 | [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { | |||
12403 | SmallVector<const Expr *, 1> AC1, AC2; | |||
12404 | FD1->getAssociatedConstraints(AC1); | |||
12405 | FD2->getAssociatedConstraints(AC2); | |||
12406 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; | |||
12407 | if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) | |||
12408 | return None; | |||
12409 | if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) | |||
12410 | return None; | |||
12411 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) | |||
12412 | return None; | |||
12413 | return AtLeastAsConstrained1; | |||
12414 | }; | |||
12415 | ||||
12416 | // Don't use the AddressOfResolver because we're specifically looking for | |||
12417 | // cases where we have one overload candidate that lacks | |||
12418 | // enable_if/pass_object_size/... | |||
12419 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { | |||
12420 | auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); | |||
12421 | if (!FD) | |||
12422 | return nullptr; | |||
12423 | ||||
12424 | if (!checkAddressOfFunctionIsAvailable(FD)) | |||
12425 | continue; | |||
12426 | ||||
12427 | // We have more than one result - see if it is more constrained than the | |||
12428 | // previous one. | |||
12429 | if (Result) { | |||
12430 | Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, | |||
12431 | Result); | |||
12432 | if (!MoreConstrainedThanPrevious) { | |||
12433 | IsResultAmbiguous = true; | |||
12434 | AmbiguousDecls.push_back(FD); | |||
12435 | continue; | |||
12436 | } | |||
12437 | if (!*MoreConstrainedThanPrevious) | |||
12438 | continue; | |||
12439 | // FD is more constrained - replace Result with it. | |||
12440 | } | |||
12441 | IsResultAmbiguous = false; | |||
12442 | DAP = I.getPair(); | |||
12443 | Result = FD; | |||
12444 | } | |||
12445 | ||||
12446 | if (IsResultAmbiguous) | |||
12447 | return nullptr; | |||
12448 | ||||
12449 | if (Result) { | |||
12450 | SmallVector<const Expr *, 1> ResultAC; | |||
12451 | // We skipped over some ambiguous declarations which might be ambiguous with | |||
12452 | // the selected result. | |||
12453 | for (FunctionDecl *Skipped : AmbiguousDecls) | |||
12454 | if (!CheckMoreConstrained(Skipped, Result).hasValue()) | |||
12455 | return nullptr; | |||
12456 | Pair = DAP; | |||
12457 | } | |||
12458 | return Result; | |||
12459 | } | |||
12460 | ||||
12461 | /// Given an overloaded function, tries to turn it into a non-overloaded | |||
12462 | /// function reference using resolveAddressOfSingleOverloadCandidate. This | |||
12463 | /// will perform access checks, diagnose the use of the resultant decl, and, if | |||
12464 | /// requested, potentially perform a function-to-pointer decay. | |||
12465 | /// | |||
12466 | /// Returns false if resolveAddressOfSingleOverloadCandidate fails. | |||
12467 | /// Otherwise, returns true. This may emit diagnostics and return true. | |||
12468 | bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( | |||
12469 | ExprResult &SrcExpr, bool DoFunctionPointerConverion) { | |||
12470 | Expr *E = SrcExpr.get(); | |||
12471 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast <bool> (E->getType() == Context.OverloadTy && "SrcExpr must be an overload") ? void (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\"" , "clang/lib/Sema/SemaOverload.cpp", 12471, __extension__ __PRETTY_FUNCTION__ )); | |||
12472 | ||||
12473 | DeclAccessPair DAP; | |||
12474 | FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); | |||
12475 | if (!Found || Found->isCPUDispatchMultiVersion() || | |||
12476 | Found->isCPUSpecificMultiVersion()) | |||
12477 | return false; | |||
12478 | ||||
12479 | // Emitting multiple diagnostics for a function that is both inaccessible and | |||
12480 | // unavailable is consistent with our behavior elsewhere. So, always check | |||
12481 | // for both. | |||
12482 | DiagnoseUseOfDecl(Found, E->getExprLoc()); | |||
12483 | CheckAddressOfMemberAccess(E, DAP); | |||
12484 | Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); | |||
12485 | if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) | |||
12486 | SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); | |||
12487 | else | |||
12488 | SrcExpr = Fixed; | |||
12489 | return true; | |||
12490 | } | |||
12491 | ||||
12492 | /// Given an expression that refers to an overloaded function, try to | |||
12493 | /// resolve that overloaded function expression down to a single function. | |||
12494 | /// | |||
12495 | /// This routine can only resolve template-ids that refer to a single function | |||
12496 | /// template, where that template-id refers to a single template whose template | |||
12497 | /// arguments are either provided by the template-id or have defaults, | |||
12498 | /// as described in C++0x [temp.arg.explicit]p3. | |||
12499 | /// | |||
12500 | /// If no template-ids are found, no diagnostics are emitted and NULL is | |||
12501 | /// returned. | |||
12502 | FunctionDecl * | |||
12503 | Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, | |||
12504 | bool Complain, | |||
12505 | DeclAccessPair *FoundResult) { | |||
12506 | // C++ [over.over]p1: | |||
12507 | // [...] [Note: any redundant set of parentheses surrounding the | |||
12508 | // overloaded function name is ignored (5.1). ] | |||
12509 | // C++ [over.over]p1: | |||
12510 | // [...] The overloaded function name can be preceded by the & | |||
12511 | // operator. | |||
12512 | ||||
12513 | // If we didn't actually find any template-ids, we're done. | |||
12514 | if (!ovl->hasExplicitTemplateArgs()) | |||
12515 | return nullptr; | |||
12516 | ||||
12517 | TemplateArgumentListInfo ExplicitTemplateArgs; | |||
12518 | ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); | |||
12519 | TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); | |||
12520 | ||||
12521 | // Look through all of the overloaded functions, searching for one | |||
12522 | // whose type matches exactly. | |||
12523 | FunctionDecl *Matched = nullptr; | |||
12524 | for (UnresolvedSetIterator I = ovl->decls_begin(), | |||
12525 | E = ovl->decls_end(); I != E; ++I) { | |||
12526 | // C++0x [temp.arg.explicit]p3: | |||
12527 | // [...] In contexts where deduction is done and fails, or in contexts | |||
12528 | // where deduction is not done, if a template argument list is | |||
12529 | // specified and it, along with any default template arguments, | |||
12530 | // identifies a single function template specialization, then the | |||
12531 | // template-id is an lvalue for the function template specialization. | |||
12532 | FunctionTemplateDecl *FunctionTemplate | |||
12533 | = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); | |||
12534 | ||||
12535 | // C++ [over.over]p2: | |||
12536 | // If the name is a function template, template argument deduction is | |||
12537 | // done (14.8.2.2), and if the argument deduction succeeds, the | |||
12538 | // resulting template argument list is used to generate a single | |||
12539 | // function template specialization, which is added to the set of | |||
12540 | // overloaded functions considered. | |||
12541 | FunctionDecl *Specialization = nullptr; | |||
12542 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); | |||
12543 | if (TemplateDeductionResult Result | |||
12544 | = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, | |||
12545 | Specialization, Info, | |||
12546 | /*IsAddressOfFunction*/true)) { | |||
12547 | // Make a note of the failed deduction for diagnostics. | |||
12548 | // TODO: Actually use the failed-deduction info? | |||
12549 | FailedCandidates.addCandidate() | |||
12550 | .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), | |||
12551 | MakeDeductionFailureInfo(Context, Result, Info)); | |||
12552 | continue; | |||
12553 | } | |||
12554 | ||||
12555 | assert(Specialization && "no specialization and no error?")(static_cast <bool> (Specialization && "no specialization and no error?" ) ? void (0) : __assert_fail ("Specialization && \"no specialization and no error?\"" , "clang/lib/Sema/SemaOverload.cpp", 12555, __extension__ __PRETTY_FUNCTION__ )); | |||
12556 | ||||
12557 | // Multiple matches; we can't resolve to a single declaration. | |||
12558 | if (Matched) { | |||
12559 | if (Complain) { | |||
12560 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) | |||
12561 | << ovl->getName(); | |||
12562 | NoteAllOverloadCandidates(ovl); | |||
12563 | } | |||
12564 | return nullptr; | |||
12565 | } | |||
12566 | ||||
12567 | Matched = Specialization; | |||
12568 | if (FoundResult) *FoundResult = I.getPair(); | |||
12569 | } | |||
12570 | ||||
12571 | if (Matched && | |||
12572 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) | |||
12573 | return nullptr; | |||
12574 | ||||
12575 | return Matched; | |||
12576 | } | |||
12577 | ||||
12578 | // Resolve and fix an overloaded expression that can be resolved | |||
12579 | // because it identifies a single function template specialization. | |||
12580 | // | |||
12581 | // Last three arguments should only be supplied if Complain = true | |||
12582 | // | |||
12583 | // Return true if it was logically possible to so resolve the | |||
12584 | // expression, regardless of whether or not it succeeded. Always | |||
12585 | // returns true if 'complain' is set. | |||
12586 | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( | |||
12587 | ExprResult &SrcExpr, bool doFunctionPointerConverion, | |||
12588 | bool complain, SourceRange OpRangeForComplaining, | |||
12589 | QualType DestTypeForComplaining, | |||
12590 | unsigned DiagIDForComplaining) { | |||
12591 | assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast <bool> (SrcExpr.get()->getType() == Context .OverloadTy) ? void (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 12591, __extension__ __PRETTY_FUNCTION__ )); | |||
12592 | ||||
12593 | OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); | |||
12594 | ||||
12595 | DeclAccessPair found; | |||
12596 | ExprResult SingleFunctionExpression; | |||
12597 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( | |||
12598 | ovl.Expression, /*complain*/ false, &found)) { | |||
12599 | if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { | |||
12600 | SrcExpr = ExprError(); | |||
12601 | return true; | |||
12602 | } | |||
12603 | ||||
12604 | // It is only correct to resolve to an instance method if we're | |||
12605 | // resolving a form that's permitted to be a pointer to member. | |||
12606 | // Otherwise we'll end up making a bound member expression, which | |||
12607 | // is illegal in all the contexts we resolve like this. | |||
12608 | if (!ovl.HasFormOfMemberPointer && | |||
12609 | isa<CXXMethodDecl>(fn) && | |||
12610 | cast<CXXMethodDecl>(fn)->isInstance()) { | |||
12611 | if (!complain) return false; | |||
12612 | ||||
12613 | Diag(ovl.Expression->getExprLoc(), | |||
12614 | diag::err_bound_member_function) | |||
12615 | << 0 << ovl.Expression->getSourceRange(); | |||
12616 | ||||
12617 | // TODO: I believe we only end up here if there's a mix of | |||
12618 | // static and non-static candidates (otherwise the expression | |||
12619 | // would have 'bound member' type, not 'overload' type). | |||
12620 | // Ideally we would note which candidate was chosen and why | |||
12621 | // the static candidates were rejected. | |||
12622 | SrcExpr = ExprError(); | |||
12623 | return true; | |||
12624 | } | |||
12625 | ||||
12626 | // Fix the expression to refer to 'fn'. | |||
12627 | SingleFunctionExpression = | |||
12628 | FixOverloadedFunctionReference(SrcExpr.get(), found, fn); | |||
12629 | ||||
12630 | // If desired, do function-to-pointer decay. | |||
12631 | if (doFunctionPointerConverion) { | |||
12632 | SingleFunctionExpression = | |||
12633 | DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); | |||
12634 | if (SingleFunctionExpression.isInvalid()) { | |||
12635 | SrcExpr = ExprError(); | |||
12636 | return true; | |||
12637 | } | |||
12638 | } | |||
12639 | } | |||
12640 | ||||
12641 | if (!SingleFunctionExpression.isUsable()) { | |||
12642 | if (complain) { | |||
12643 | Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) | |||
12644 | << ovl.Expression->getName() | |||
12645 | << DestTypeForComplaining | |||
12646 | << OpRangeForComplaining | |||
12647 | << ovl.Expression->getQualifierLoc().getSourceRange(); | |||
12648 | NoteAllOverloadCandidates(SrcExpr.get()); | |||
12649 | ||||
12650 | SrcExpr = ExprError(); | |||
12651 | return true; | |||
12652 | } | |||
12653 | ||||
12654 | return false; | |||
12655 | } | |||
12656 | ||||
12657 | SrcExpr = SingleFunctionExpression; | |||
12658 | return true; | |||
12659 | } | |||
12660 | ||||
12661 | /// Add a single candidate to the overload set. | |||
12662 | static void AddOverloadedCallCandidate(Sema &S, | |||
12663 | DeclAccessPair FoundDecl, | |||
12664 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
12665 | ArrayRef<Expr *> Args, | |||
12666 | OverloadCandidateSet &CandidateSet, | |||
12667 | bool PartialOverloading, | |||
12668 | bool KnownValid) { | |||
12669 | NamedDecl *Callee = FoundDecl.getDecl(); | |||
12670 | if (isa<UsingShadowDecl>(Callee)) | |||
12671 | Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); | |||
12672 | ||||
12673 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { | |||
12674 | if (ExplicitTemplateArgs) { | |||
12675 | assert(!KnownValid && "Explicit template arguments?")(static_cast <bool> (!KnownValid && "Explicit template arguments?" ) ? void (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\"" , "clang/lib/Sema/SemaOverload.cpp", 12675, __extension__ __PRETTY_FUNCTION__ )); | |||
12676 | return; | |||
12677 | } | |||
12678 | // Prevent ill-formed function decls to be added as overload candidates. | |||
12679 | if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) | |||
12680 | return; | |||
12681 | ||||
12682 | S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, | |||
12683 | /*SuppressUserConversions=*/false, | |||
12684 | PartialOverloading); | |||
12685 | return; | |||
12686 | } | |||
12687 | ||||
12688 | if (FunctionTemplateDecl *FuncTemplate | |||
12689 | = dyn_cast<FunctionTemplateDecl>(Callee)) { | |||
12690 | S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, | |||
12691 | ExplicitTemplateArgs, Args, CandidateSet, | |||
12692 | /*SuppressUserConversions=*/false, | |||
12693 | PartialOverloading); | |||
12694 | return; | |||
12695 | } | |||
12696 | ||||
12697 | assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast <bool> (!KnownValid && "unhandled case in overloaded call candidate" ) ? void (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\"" , "clang/lib/Sema/SemaOverload.cpp", 12697, __extension__ __PRETTY_FUNCTION__ )); | |||
12698 | } | |||
12699 | ||||
12700 | /// Add the overload candidates named by callee and/or found by argument | |||
12701 | /// dependent lookup to the given overload set. | |||
12702 | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, | |||
12703 | ArrayRef<Expr *> Args, | |||
12704 | OverloadCandidateSet &CandidateSet, | |||
12705 | bool PartialOverloading) { | |||
12706 | ||||
12707 | #ifndef NDEBUG | |||
12708 | // Verify that ArgumentDependentLookup is consistent with the rules | |||
12709 | // in C++0x [basic.lookup.argdep]p3: | |||
12710 | // | |||
12711 | // Let X be the lookup set produced by unqualified lookup (3.4.1) | |||
12712 | // and let Y be the lookup set produced by argument dependent | |||
12713 | // lookup (defined as follows). If X contains | |||
12714 | // | |||
12715 | // -- a declaration of a class member, or | |||
12716 | // | |||
12717 | // -- a block-scope function declaration that is not a | |||
12718 | // using-declaration, or | |||
12719 | // | |||
12720 | // -- a declaration that is neither a function or a function | |||
12721 | // template | |||
12722 | // | |||
12723 | // then Y is empty. | |||
12724 | ||||
12725 | if (ULE->requiresADL()) { | |||
12726 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), | |||
12727 | E = ULE->decls_end(); I != E; ++I) { | |||
12728 | assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord ()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()" , "clang/lib/Sema/SemaOverload.cpp", 12728, __extension__ __PRETTY_FUNCTION__ )); | |||
12729 | assert(isa<UsingShadowDecl>(*I) ||(static_cast <bool> (isa<UsingShadowDecl>(*I) || ! (*I)->getDeclContext()->isFunctionOrMethod()) ? void (0 ) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "clang/lib/Sema/SemaOverload.cpp", 12730, __extension__ __PRETTY_FUNCTION__ )) | |||
12730 | !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast <bool> (isa<UsingShadowDecl>(*I) || ! (*I)->getDeclContext()->isFunctionOrMethod()) ? void (0 ) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "clang/lib/Sema/SemaOverload.cpp", 12730, __extension__ __PRETTY_FUNCTION__ )); | |||
12731 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate ()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()" , "clang/lib/Sema/SemaOverload.cpp", 12731, __extension__ __PRETTY_FUNCTION__ )); | |||
12732 | } | |||
12733 | } | |||
12734 | #endif | |||
12735 | ||||
12736 | // It would be nice to avoid this copy. | |||
12737 | TemplateArgumentListInfo TABuffer; | |||
12738 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; | |||
12739 | if (ULE->hasExplicitTemplateArgs()) { | |||
12740 | ULE->copyTemplateArgumentsInto(TABuffer); | |||
12741 | ExplicitTemplateArgs = &TABuffer; | |||
12742 | } | |||
12743 | ||||
12744 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), | |||
12745 | E = ULE->decls_end(); I != E; ++I) | |||
12746 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, | |||
12747 | CandidateSet, PartialOverloading, | |||
12748 | /*KnownValid*/ true); | |||
12749 | ||||
12750 | if (ULE->requiresADL()) | |||
12751 | AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), | |||
12752 | Args, ExplicitTemplateArgs, | |||
12753 | CandidateSet, PartialOverloading); | |||
12754 | } | |||
12755 | ||||
12756 | /// Add the call candidates from the given set of lookup results to the given | |||
12757 | /// overload set. Non-function lookup results are ignored. | |||
12758 | void Sema::AddOverloadedCallCandidates( | |||
12759 | LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
12760 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { | |||
12761 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | |||
12762 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, | |||
12763 | CandidateSet, false, /*KnownValid*/ false); | |||
12764 | } | |||
12765 | ||||
12766 | /// Determine whether a declaration with the specified name could be moved into | |||
12767 | /// a different namespace. | |||
12768 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { | |||
12769 | switch (Name.getCXXOverloadedOperator()) { | |||
12770 | case OO_New: case OO_Array_New: | |||
12771 | case OO_Delete: case OO_Array_Delete: | |||
12772 | return false; | |||
12773 | ||||
12774 | default: | |||
12775 | return true; | |||
12776 | } | |||
12777 | } | |||
12778 | ||||
12779 | /// Attempt to recover from an ill-formed use of a non-dependent name in a | |||
12780 | /// template, where the non-dependent name was declared after the template | |||
12781 | /// was defined. This is common in code written for a compilers which do not | |||
12782 | /// correctly implement two-stage name lookup. | |||
12783 | /// | |||
12784 | /// Returns true if a viable candidate was found and a diagnostic was issued. | |||
12785 | static bool DiagnoseTwoPhaseLookup( | |||
12786 | Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, | |||
12787 | LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, | |||
12788 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, | |||
12789 | CXXRecordDecl **FoundInClass = nullptr) { | |||
12790 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) | |||
12791 | return false; | |||
12792 | ||||
12793 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { | |||
12794 | if (DC->isTransparentContext()) | |||
12795 | continue; | |||
12796 | ||||
12797 | SemaRef.LookupQualifiedName(R, DC); | |||
12798 | ||||
12799 | if (!R.empty()) { | |||
12800 | R.suppressDiagnostics(); | |||
12801 | ||||
12802 | OverloadCandidateSet Candidates(FnLoc, CSK); | |||
12803 | SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, | |||
12804 | Candidates); | |||
12805 | ||||
12806 | OverloadCandidateSet::iterator Best; | |||
12807 | OverloadingResult OR = | |||
12808 | Candidates.BestViableFunction(SemaRef, FnLoc, Best); | |||
12809 | ||||
12810 | if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { | |||
12811 | // We either found non-function declarations or a best viable function | |||
12812 | // at class scope. A class-scope lookup result disables ADL. Don't | |||
12813 | // look past this, but let the caller know that we found something that | |||
12814 | // either is, or might be, usable in this class. | |||
12815 | if (FoundInClass) { | |||
12816 | *FoundInClass = RD; | |||
12817 | if (OR == OR_Success) { | |||
12818 | R.clear(); | |||
12819 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); | |||
12820 | R.resolveKind(); | |||
12821 | } | |||
12822 | } | |||
12823 | return false; | |||
12824 | } | |||
12825 | ||||
12826 | if (OR != OR_Success) { | |||
12827 | // There wasn't a unique best function or function template. | |||
12828 | return false; | |||
12829 | } | |||
12830 | ||||
12831 | // Find the namespaces where ADL would have looked, and suggest | |||
12832 | // declaring the function there instead. | |||
12833 | Sema::AssociatedNamespaceSet AssociatedNamespaces; | |||
12834 | Sema::AssociatedClassSet AssociatedClasses; | |||
12835 | SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, | |||
12836 | AssociatedNamespaces, | |||
12837 | AssociatedClasses); | |||
12838 | Sema::AssociatedNamespaceSet SuggestedNamespaces; | |||
12839 | if (canBeDeclaredInNamespace(R.getLookupName())) { | |||
12840 | DeclContext *Std = SemaRef.getStdNamespace(); | |||
12841 | for (Sema::AssociatedNamespaceSet::iterator | |||
12842 | it = AssociatedNamespaces.begin(), | |||
12843 | end = AssociatedNamespaces.end(); it != end; ++it) { | |||
12844 | // Never suggest declaring a function within namespace 'std'. | |||
12845 | if (Std && Std->Encloses(*it)) | |||
12846 | continue; | |||
12847 | ||||
12848 | // Never suggest declaring a function within a namespace with a | |||
12849 | // reserved name, like __gnu_cxx. | |||
12850 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); | |||
12851 | if (NS && | |||
12852 | NS->getQualifiedNameAsString().find("__") != std::string::npos) | |||
12853 | continue; | |||
12854 | ||||
12855 | SuggestedNamespaces.insert(*it); | |||
12856 | } | |||
12857 | } | |||
12858 | ||||
12859 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) | |||
12860 | << R.getLookupName(); | |||
12861 | if (SuggestedNamespaces.empty()) { | |||
12862 | SemaRef.Diag(Best->Function->getLocation(), | |||
12863 | diag::note_not_found_by_two_phase_lookup) | |||
12864 | << R.getLookupName() << 0; | |||
12865 | } else if (SuggestedNamespaces.size() == 1) { | |||
12866 | SemaRef.Diag(Best->Function->getLocation(), | |||
12867 | diag::note_not_found_by_two_phase_lookup) | |||
12868 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); | |||
12869 | } else { | |||
12870 | // FIXME: It would be useful to list the associated namespaces here, | |||
12871 | // but the diagnostics infrastructure doesn't provide a way to produce | |||
12872 | // a localized representation of a list of items. | |||
12873 | SemaRef.Diag(Best->Function->getLocation(), | |||
12874 | diag::note_not_found_by_two_phase_lookup) | |||
12875 | << R.getLookupName() << 2; | |||
12876 | } | |||
12877 | ||||
12878 | // Try to recover by calling this function. | |||
12879 | return true; | |||
12880 | } | |||
12881 | ||||
12882 | R.clear(); | |||
12883 | } | |||
12884 | ||||
12885 | return false; | |||
12886 | } | |||
12887 | ||||
12888 | /// Attempt to recover from ill-formed use of a non-dependent operator in a | |||
12889 | /// template, where the non-dependent operator was declared after the template | |||
12890 | /// was defined. | |||
12891 | /// | |||
12892 | /// Returns true if a viable candidate was found and a diagnostic was issued. | |||
12893 | static bool | |||
12894 | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, | |||
12895 | SourceLocation OpLoc, | |||
12896 | ArrayRef<Expr *> Args) { | |||
12897 | DeclarationName OpName = | |||
12898 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); | |||
12899 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); | |||
12900 | return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, | |||
12901 | OverloadCandidateSet::CSK_Operator, | |||
12902 | /*ExplicitTemplateArgs=*/nullptr, Args); | |||
12903 | } | |||
12904 | ||||
12905 | namespace { | |||
12906 | class BuildRecoveryCallExprRAII { | |||
12907 | Sema &SemaRef; | |||
12908 | public: | |||
12909 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { | |||
12910 | assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr == false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false" , "clang/lib/Sema/SemaOverload.cpp", 12910, __extension__ __PRETTY_FUNCTION__ )); | |||
12911 | SemaRef.IsBuildingRecoveryCallExpr = true; | |||
12912 | } | |||
12913 | ||||
12914 | ~BuildRecoveryCallExprRAII() { | |||
12915 | SemaRef.IsBuildingRecoveryCallExpr = false; | |||
12916 | } | |||
12917 | }; | |||
12918 | ||||
12919 | } | |||
12920 | ||||
12921 | /// Attempts to recover from a call where no functions were found. | |||
12922 | /// | |||
12923 | /// This function will do one of three things: | |||
12924 | /// * Diagnose, recover, and return a recovery expression. | |||
12925 | /// * Diagnose, fail to recover, and return ExprError(). | |||
12926 | /// * Do not diagnose, do not recover, and return ExprResult(). The caller is | |||
12927 | /// expected to diagnose as appropriate. | |||
12928 | static ExprResult | |||
12929 | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, | |||
12930 | UnresolvedLookupExpr *ULE, | |||
12931 | SourceLocation LParenLoc, | |||
12932 | MutableArrayRef<Expr *> Args, | |||
12933 | SourceLocation RParenLoc, | |||
12934 | bool EmptyLookup, bool AllowTypoCorrection) { | |||
12935 | // Do not try to recover if it is already building a recovery call. | |||
12936 | // This stops infinite loops for template instantiations like | |||
12937 | // | |||
12938 | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} | |||
12939 | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} | |||
12940 | if (SemaRef.IsBuildingRecoveryCallExpr) | |||
12941 | return ExprResult(); | |||
12942 | BuildRecoveryCallExprRAII RCE(SemaRef); | |||
12943 | ||||
12944 | CXXScopeSpec SS; | |||
12945 | SS.Adopt(ULE->getQualifierLoc()); | |||
12946 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); | |||
12947 | ||||
12948 | TemplateArgumentListInfo TABuffer; | |||
12949 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; | |||
12950 | if (ULE->hasExplicitTemplateArgs()) { | |||
12951 | ULE->copyTemplateArgumentsInto(TABuffer); | |||
12952 | ExplicitTemplateArgs = &TABuffer; | |||
12953 | } | |||
12954 | ||||
12955 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), | |||
12956 | Sema::LookupOrdinaryName); | |||
12957 | CXXRecordDecl *FoundInClass = nullptr; | |||
12958 | if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, | |||
12959 | OverloadCandidateSet::CSK_Normal, | |||
12960 | ExplicitTemplateArgs, Args, &FoundInClass)) { | |||
12961 | // OK, diagnosed a two-phase lookup issue. | |||
12962 | } else if (EmptyLookup) { | |||
12963 | // Try to recover from an empty lookup with typo correction. | |||
12964 | R.clear(); | |||
12965 | NoTypoCorrectionCCC NoTypoValidator{}; | |||
12966 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), | |||
12967 | ExplicitTemplateArgs != nullptr, | |||
12968 | dyn_cast<MemberExpr>(Fn)); | |||
12969 | CorrectionCandidateCallback &Validator = | |||
12970 | AllowTypoCorrection | |||
12971 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) | |||
12972 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); | |||
12973 | if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, | |||
12974 | Args)) | |||
12975 | return ExprError(); | |||
12976 | } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { | |||
12977 | // We found a usable declaration of the name in a dependent base of some | |||
12978 | // enclosing class. | |||
12979 | // FIXME: We should also explain why the candidates found by name lookup | |||
12980 | // were not viable. | |||
12981 | if (SemaRef.DiagnoseDependentMemberLookup(R)) | |||
12982 | return ExprError(); | |||
12983 | } else { | |||
12984 | // We had viable candidates and couldn't recover; let the caller diagnose | |||
12985 | // this. | |||
12986 | return ExprResult(); | |||
12987 | } | |||
12988 | ||||
12989 | // If we get here, we should have issued a diagnostic and formed a recovery | |||
12990 | // lookup result. | |||
12991 | assert(!R.empty() && "lookup results empty despite recovery")(static_cast <bool> (!R.empty() && "lookup results empty despite recovery" ) ? void (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\"" , "clang/lib/Sema/SemaOverload.cpp", 12991, __extension__ __PRETTY_FUNCTION__ )); | |||
12992 | ||||
12993 | // If recovery created an ambiguity, just bail out. | |||
12994 | if (R.isAmbiguous()) { | |||
12995 | R.suppressDiagnostics(); | |||
12996 | return ExprError(); | |||
12997 | } | |||
12998 | ||||
12999 | // Build an implicit member call if appropriate. Just drop the | |||
13000 | // casts and such from the call, we don't really care. | |||
13001 | ExprResult NewFn = ExprError(); | |||
13002 | if ((*R.begin())->isCXXClassMember()) | |||
13003 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, | |||
13004 | ExplicitTemplateArgs, S); | |||
13005 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) | |||
13006 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, | |||
13007 | ExplicitTemplateArgs); | |||
13008 | else | |||
13009 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); | |||
13010 | ||||
13011 | if (NewFn.isInvalid()) | |||
13012 | return ExprError(); | |||
13013 | ||||
13014 | // This shouldn't cause an infinite loop because we're giving it | |||
13015 | // an expression with viable lookup results, which should never | |||
13016 | // end up here. | |||
13017 | return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, | |||
13018 | MultiExprArg(Args.data(), Args.size()), | |||
13019 | RParenLoc); | |||
13020 | } | |||
13021 | ||||
13022 | /// Constructs and populates an OverloadedCandidateSet from | |||
13023 | /// the given function. | |||
13024 | /// \returns true when an the ExprResult output parameter has been set. | |||
13025 | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, | |||
13026 | UnresolvedLookupExpr *ULE, | |||
13027 | MultiExprArg Args, | |||
13028 | SourceLocation RParenLoc, | |||
13029 | OverloadCandidateSet *CandidateSet, | |||
13030 | ExprResult *Result) { | |||
13031 | #ifndef NDEBUG | |||
13032 | if (ULE->requiresADL()) { | |||
13033 | // To do ADL, we must have found an unqualified name. | |||
13034 | assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast <bool> (!ULE->getQualifier() && "qualified name with ADL") ? void (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\"" , "clang/lib/Sema/SemaOverload.cpp", 13034, __extension__ __PRETTY_FUNCTION__ )); | |||
13035 | ||||
13036 | // We don't perform ADL for implicit declarations of builtins. | |||
13037 | // Verify that this was correctly set up. | |||
13038 | FunctionDecl *F; | |||
13039 | if (ULE->decls_begin() != ULE->decls_end() && | |||
13040 | ULE->decls_begin() + 1 == ULE->decls_end() && | |||
13041 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && | |||
13042 | F->getBuiltinID() && F->isImplicit()) | |||
13043 | llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin" , "clang/lib/Sema/SemaOverload.cpp", 13043); | |||
13044 | ||||
13045 | // We don't perform ADL in C. | |||
13046 | assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast <bool> (getLangOpts().CPlusPlus && "ADL enabled in C") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\"" , "clang/lib/Sema/SemaOverload.cpp", 13046, __extension__ __PRETTY_FUNCTION__ )); | |||
13047 | } | |||
13048 | #endif | |||
13049 | ||||
13050 | UnbridgedCastsSet UnbridgedCasts; | |||
13051 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { | |||
13052 | *Result = ExprError(); | |||
13053 | return true; | |||
13054 | } | |||
13055 | ||||
13056 | // Add the functions denoted by the callee to the set of candidate | |||
13057 | // functions, including those from argument-dependent lookup. | |||
13058 | AddOverloadedCallCandidates(ULE, Args, *CandidateSet); | |||
13059 | ||||
13060 | if (getLangOpts().MSVCCompat && | |||
13061 | CurContext->isDependentContext() && !isSFINAEContext() && | |||
13062 | (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { | |||
13063 | ||||
13064 | OverloadCandidateSet::iterator Best; | |||
13065 | if (CandidateSet->empty() || | |||
13066 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == | |||
13067 | OR_No_Viable_Function) { | |||
13068 | // In Microsoft mode, if we are inside a template class member function | |||
13069 | // then create a type dependent CallExpr. The goal is to postpone name | |||
13070 | // lookup to instantiation time to be able to search into type dependent | |||
13071 | // base classes. | |||
13072 | CallExpr *CE = | |||
13073 | CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, | |||
13074 | RParenLoc, CurFPFeatureOverrides()); | |||
13075 | CE->markDependentForPostponedNameLookup(); | |||
13076 | *Result = CE; | |||
13077 | return true; | |||
13078 | } | |||
13079 | } | |||
13080 | ||||
13081 | if (CandidateSet->empty()) | |||
13082 | return false; | |||
13083 | ||||
13084 | UnbridgedCasts.restore(); | |||
13085 | return false; | |||
13086 | } | |||
13087 | ||||
13088 | // Guess at what the return type for an unresolvable overload should be. | |||
13089 | static QualType chooseRecoveryType(OverloadCandidateSet &CS, | |||
13090 | OverloadCandidateSet::iterator *Best) { | |||
13091 | llvm::Optional<QualType> Result; | |||
13092 | // Adjust Type after seeing a candidate. | |||
13093 | auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { | |||
13094 | if (!Candidate.Function) | |||
13095 | return; | |||
13096 | if (Candidate.Function->isInvalidDecl()) | |||
13097 | return; | |||
13098 | QualType T = Candidate.Function->getReturnType(); | |||
13099 | if (T.isNull()) | |||
13100 | return; | |||
13101 | if (!Result) | |||
13102 | Result = T; | |||
13103 | else if (Result != T) | |||
13104 | Result = QualType(); | |||
13105 | }; | |||
13106 | ||||
13107 | // Look for an unambiguous type from a progressively larger subset. | |||
13108 | // e.g. if types disagree, but all *viable* overloads return int, choose int. | |||
13109 | // | |||
13110 | // First, consider only the best candidate. | |||
13111 | if (Best && *Best != CS.end()) | |||
13112 | ConsiderCandidate(**Best); | |||
13113 | // Next, consider only viable candidates. | |||
13114 | if (!Result) | |||
13115 | for (const auto &C : CS) | |||
13116 | if (C.Viable) | |||
13117 | ConsiderCandidate(C); | |||
13118 | // Finally, consider all candidates. | |||
13119 | if (!Result) | |||
13120 | for (const auto &C : CS) | |||
13121 | ConsiderCandidate(C); | |||
13122 | ||||
13123 | if (!Result) | |||
13124 | return QualType(); | |||
13125 | auto Value = Result.getValue(); | |||
13126 | if (Value.isNull() || Value->isUndeducedType()) | |||
13127 | return QualType(); | |||
13128 | return Value; | |||
13129 | } | |||
13130 | ||||
13131 | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns | |||
13132 | /// the completed call expression. If overload resolution fails, emits | |||
13133 | /// diagnostics and returns ExprError() | |||
13134 | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, | |||
13135 | UnresolvedLookupExpr *ULE, | |||
13136 | SourceLocation LParenLoc, | |||
13137 | MultiExprArg Args, | |||
13138 | SourceLocation RParenLoc, | |||
13139 | Expr *ExecConfig, | |||
13140 | OverloadCandidateSet *CandidateSet, | |||
13141 | OverloadCandidateSet::iterator *Best, | |||
13142 | OverloadingResult OverloadResult, | |||
13143 | bool AllowTypoCorrection) { | |||
13144 | switch (OverloadResult) { | |||
13145 | case OR_Success: { | |||
13146 | FunctionDecl *FDecl = (*Best)->Function; | |||
13147 | SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); | |||
13148 | if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) | |||
13149 | return ExprError(); | |||
13150 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); | |||
13151 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, | |||
13152 | ExecConfig, /*IsExecConfig=*/false, | |||
13153 | (*Best)->IsADLCandidate); | |||
13154 | } | |||
13155 | ||||
13156 | case OR_No_Viable_Function: { | |||
13157 | // Try to recover by looking for viable functions which the user might | |||
13158 | // have meant to call. | |||
13159 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, | |||
13160 | Args, RParenLoc, | |||
13161 | CandidateSet->empty(), | |||
13162 | AllowTypoCorrection); | |||
13163 | if (Recovery.isInvalid() || Recovery.isUsable()) | |||
13164 | return Recovery; | |||
13165 | ||||
13166 | // If the user passes in a function that we can't take the address of, we | |||
13167 | // generally end up emitting really bad error messages. Here, we attempt to | |||
13168 | // emit better ones. | |||
13169 | for (const Expr *Arg : Args) { | |||
13170 | if (!Arg->getType()->isFunctionType()) | |||
13171 | continue; | |||
13172 | if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { | |||
13173 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
13174 | if (FD && | |||
13175 | !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
13176 | Arg->getExprLoc())) | |||
13177 | return ExprError(); | |||
13178 | } | |||
13179 | } | |||
13180 | ||||
13181 | CandidateSet->NoteCandidates( | |||
13182 | PartialDiagnosticAt( | |||
13183 | Fn->getBeginLoc(), | |||
13184 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
13185 | << ULE->getName() << Fn->getSourceRange()), | |||
13186 | SemaRef, OCD_AllCandidates, Args); | |||
13187 | break; | |||
13188 | } | |||
13189 | ||||
13190 | case OR_Ambiguous: | |||
13191 | CandidateSet->NoteCandidates( | |||
13192 | PartialDiagnosticAt(Fn->getBeginLoc(), | |||
13193 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) | |||
13194 | << ULE->getName() << Fn->getSourceRange()), | |||
13195 | SemaRef, OCD_AmbiguousCandidates, Args); | |||
13196 | break; | |||
13197 | ||||
13198 | case OR_Deleted: { | |||
13199 | CandidateSet->NoteCandidates( | |||
13200 | PartialDiagnosticAt(Fn->getBeginLoc(), | |||
13201 | SemaRef.PDiag(diag::err_ovl_deleted_call) | |||
13202 | << ULE->getName() << Fn->getSourceRange()), | |||
13203 | SemaRef, OCD_AllCandidates, Args); | |||
13204 | ||||
13205 | // We emitted an error for the unavailable/deleted function call but keep | |||
13206 | // the call in the AST. | |||
13207 | FunctionDecl *FDecl = (*Best)->Function; | |||
13208 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); | |||
13209 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, | |||
13210 | ExecConfig, /*IsExecConfig=*/false, | |||
13211 | (*Best)->IsADLCandidate); | |||
13212 | } | |||
13213 | } | |||
13214 | ||||
13215 | // Overload resolution failed, try to recover. | |||
13216 | SmallVector<Expr *, 8> SubExprs = {Fn}; | |||
13217 | SubExprs.append(Args.begin(), Args.end()); | |||
13218 | return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, | |||
13219 | chooseRecoveryType(*CandidateSet, Best)); | |||
13220 | } | |||
13221 | ||||
13222 | static void markUnaddressableCandidatesUnviable(Sema &S, | |||
13223 | OverloadCandidateSet &CS) { | |||
13224 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { | |||
13225 | if (I->Viable && | |||
13226 | !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { | |||
13227 | I->Viable = false; | |||
13228 | I->FailureKind = ovl_fail_addr_not_available; | |||
13229 | } | |||
13230 | } | |||
13231 | } | |||
13232 | ||||
13233 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn | |||
13234 | /// (which eventually refers to the declaration Func) and the call | |||
13235 | /// arguments Args/NumArgs, attempt to resolve the function call down | |||
13236 | /// to a specific function. If overload resolution succeeds, returns | |||
13237 | /// the call expression produced by overload resolution. | |||
13238 | /// Otherwise, emits diagnostics and returns ExprError. | |||
13239 | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, | |||
13240 | UnresolvedLookupExpr *ULE, | |||
13241 | SourceLocation LParenLoc, | |||
13242 | MultiExprArg Args, | |||
13243 | SourceLocation RParenLoc, | |||
13244 | Expr *ExecConfig, | |||
13245 | bool AllowTypoCorrection, | |||
13246 | bool CalleesAddressIsTaken) { | |||
13247 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), | |||
13248 | OverloadCandidateSet::CSK_Normal); | |||
13249 | ExprResult result; | |||
13250 | ||||
13251 | if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, | |||
13252 | &result)) | |||
13253 | return result; | |||
13254 | ||||
13255 | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that | |||
13256 | // functions that aren't addressible are considered unviable. | |||
13257 | if (CalleesAddressIsTaken) | |||
13258 | markUnaddressableCandidatesUnviable(*this, CandidateSet); | |||
13259 | ||||
13260 | OverloadCandidateSet::iterator Best; | |||
13261 | OverloadingResult OverloadResult = | |||
13262 | CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); | |||
13263 | ||||
13264 | return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, | |||
13265 | ExecConfig, &CandidateSet, &Best, | |||
13266 | OverloadResult, AllowTypoCorrection); | |||
13267 | } | |||
13268 | ||||
13269 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { | |||
13270 | return Functions.size() > 1 || | |||
13271 | (Functions.size() == 1 && | |||
13272 | isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); | |||
13273 | } | |||
13274 | ||||
13275 | ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, | |||
13276 | NestedNameSpecifierLoc NNSLoc, | |||
13277 | DeclarationNameInfo DNI, | |||
13278 | const UnresolvedSetImpl &Fns, | |||
13279 | bool PerformADL) { | |||
13280 | return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, | |||
13281 | PerformADL, IsOverloaded(Fns), | |||
13282 | Fns.begin(), Fns.end()); | |||
13283 | } | |||
13284 | ||||
13285 | /// Create a unary operation that may resolve to an overloaded | |||
13286 | /// operator. | |||
13287 | /// | |||
13288 | /// \param OpLoc The location of the operator itself (e.g., '*'). | |||
13289 | /// | |||
13290 | /// \param Opc The UnaryOperatorKind that describes this operator. | |||
13291 | /// | |||
13292 | /// \param Fns The set of non-member functions that will be | |||
13293 | /// considered by overload resolution. The caller needs to build this | |||
13294 | /// set based on the context using, e.g., | |||
13295 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This | |||
13296 | /// set should not contain any member functions; those will be added | |||
13297 | /// by CreateOverloadedUnaryOp(). | |||
13298 | /// | |||
13299 | /// \param Input The input argument. | |||
13300 | ExprResult | |||
13301 | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, | |||
13302 | const UnresolvedSetImpl &Fns, | |||
13303 | Expr *Input, bool PerformADL) { | |||
13304 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); | |||
13305 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast <bool> (Op != OO_None && "Invalid opcode for overloaded unary operator" ) ? void (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\"" , "clang/lib/Sema/SemaOverload.cpp", 13305, __extension__ __PRETTY_FUNCTION__ )); | |||
13306 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
13307 | // TODO: provide better source location info. | |||
13308 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); | |||
13309 | ||||
13310 | if (checkPlaceholderForOverload(*this, Input)) | |||
13311 | return ExprError(); | |||
13312 | ||||
13313 | Expr *Args[2] = { Input, nullptr }; | |||
13314 | unsigned NumArgs = 1; | |||
13315 | ||||
13316 | // For post-increment and post-decrement, add the implicit '0' as | |||
13317 | // the second argument, so that we know this is a post-increment or | |||
13318 | // post-decrement. | |||
13319 | if (Opc == UO_PostInc || Opc == UO_PostDec) { | |||
13320 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); | |||
13321 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, | |||
13322 | SourceLocation()); | |||
13323 | NumArgs = 2; | |||
13324 | } | |||
13325 | ||||
13326 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); | |||
13327 | ||||
13328 | if (Input->isTypeDependent()) { | |||
13329 | if (Fns.empty()) | |||
13330 | return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, | |||
13331 | VK_PRValue, OK_Ordinary, OpLoc, false, | |||
13332 | CurFPFeatureOverrides()); | |||
13333 | ||||
13334 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
13335 | ExprResult Fn = CreateUnresolvedLookupExpr( | |||
13336 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); | |||
13337 | if (Fn.isInvalid()) | |||
13338 | return ExprError(); | |||
13339 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, | |||
13340 | Context.DependentTy, VK_PRValue, OpLoc, | |||
13341 | CurFPFeatureOverrides()); | |||
13342 | } | |||
13343 | ||||
13344 | // Build an empty overload set. | |||
13345 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); | |||
13346 | ||||
13347 | // Add the candidates from the given function set. | |||
13348 | AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); | |||
13349 | ||||
13350 | // Add operator candidates that are member functions. | |||
13351 | AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); | |||
13352 | ||||
13353 | // Add candidates from ADL. | |||
13354 | if (PerformADL) { | |||
13355 | AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, | |||
13356 | /*ExplicitTemplateArgs*/nullptr, | |||
13357 | CandidateSet); | |||
13358 | } | |||
13359 | ||||
13360 | // Add builtin operator candidates. | |||
13361 | AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); | |||
13362 | ||||
13363 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
13364 | ||||
13365 | // Perform overload resolution. | |||
13366 | OverloadCandidateSet::iterator Best; | |||
13367 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
13368 | case OR_Success: { | |||
13369 | // We found a built-in operator or an overloaded operator. | |||
13370 | FunctionDecl *FnDecl = Best->Function; | |||
13371 | ||||
13372 | if (FnDecl) { | |||
13373 | Expr *Base = nullptr; | |||
13374 | // We matched an overloaded operator. Build a call to that | |||
13375 | // operator. | |||
13376 | ||||
13377 | // Convert the arguments. | |||
13378 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
13379 | CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); | |||
13380 | ||||
13381 | ExprResult InputRes = | |||
13382 | PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, | |||
13383 | Best->FoundDecl, Method); | |||
13384 | if (InputRes.isInvalid()) | |||
13385 | return ExprError(); | |||
13386 | Base = Input = InputRes.get(); | |||
13387 | } else { | |||
13388 | // Convert the arguments. | |||
13389 | ExprResult InputInit | |||
13390 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
13391 | Context, | |||
13392 | FnDecl->getParamDecl(0)), | |||
13393 | SourceLocation(), | |||
13394 | Input); | |||
13395 | if (InputInit.isInvalid()) | |||
13396 | return ExprError(); | |||
13397 | Input = InputInit.get(); | |||
13398 | } | |||
13399 | ||||
13400 | // Build the actual expression node. | |||
13401 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, | |||
13402 | Base, HadMultipleCandidates, | |||
13403 | OpLoc); | |||
13404 | if (FnExpr.isInvalid()) | |||
13405 | return ExprError(); | |||
13406 | ||||
13407 | // Determine the result type. | |||
13408 | QualType ResultTy = FnDecl->getReturnType(); | |||
13409 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
13410 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
13411 | ||||
13412 | Args[0] = Input; | |||
13413 | CallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
13414 | Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, | |||
13415 | CurFPFeatureOverrides(), Best->IsADLCandidate); | |||
13416 | ||||
13417 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) | |||
13418 | return ExprError(); | |||
13419 | ||||
13420 | if (CheckFunctionCall(FnDecl, TheCall, | |||
13421 | FnDecl->getType()->castAs<FunctionProtoType>())) | |||
13422 | return ExprError(); | |||
13423 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); | |||
13424 | } else { | |||
13425 | // We matched a built-in operator. Convert the arguments, then | |||
13426 | // break out so that we will build the appropriate built-in | |||
13427 | // operator node. | |||
13428 | ExprResult InputRes = PerformImplicitConversion( | |||
13429 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, | |||
13430 | CCK_ForBuiltinOverloadedOp); | |||
13431 | if (InputRes.isInvalid()) | |||
13432 | return ExprError(); | |||
13433 | Input = InputRes.get(); | |||
13434 | break; | |||
13435 | } | |||
13436 | } | |||
13437 | ||||
13438 | case OR_No_Viable_Function: | |||
13439 | // This is an erroneous use of an operator which can be overloaded by | |||
13440 | // a non-member function. Check for non-member operators which were | |||
13441 | // defined too late to be candidates. | |||
13442 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) | |||
13443 | // FIXME: Recover by calling the found function. | |||
13444 | return ExprError(); | |||
13445 | ||||
13446 | // No viable function; fall through to handling this as a | |||
13447 | // built-in operator, which will produce an error message for us. | |||
13448 | break; | |||
13449 | ||||
13450 | case OR_Ambiguous: | |||
13451 | CandidateSet.NoteCandidates( | |||
13452 | PartialDiagnosticAt(OpLoc, | |||
13453 | PDiag(diag::err_ovl_ambiguous_oper_unary) | |||
13454 | << UnaryOperator::getOpcodeStr(Opc) | |||
13455 | << Input->getType() << Input->getSourceRange()), | |||
13456 | *this, OCD_AmbiguousCandidates, ArgsArray, | |||
13457 | UnaryOperator::getOpcodeStr(Opc), OpLoc); | |||
13458 | return ExprError(); | |||
13459 | ||||
13460 | case OR_Deleted: | |||
13461 | CandidateSet.NoteCandidates( | |||
13462 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
13463 | << UnaryOperator::getOpcodeStr(Opc) | |||
13464 | << Input->getSourceRange()), | |||
13465 | *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), | |||
13466 | OpLoc); | |||
13467 | return ExprError(); | |||
13468 | } | |||
13469 | ||||
13470 | // Either we found no viable overloaded operator or we matched a | |||
13471 | // built-in operator. In either case, fall through to trying to | |||
13472 | // build a built-in operation. | |||
13473 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
13474 | } | |||
13475 | ||||
13476 | /// Perform lookup for an overloaded binary operator. | |||
13477 | void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, | |||
13478 | OverloadedOperatorKind Op, | |||
13479 | const UnresolvedSetImpl &Fns, | |||
13480 | ArrayRef<Expr *> Args, bool PerformADL) { | |||
13481 | SourceLocation OpLoc = CandidateSet.getLocation(); | |||
13482 | ||||
13483 | OverloadedOperatorKind ExtraOp = | |||
13484 | CandidateSet.getRewriteInfo().AllowRewrittenCandidates | |||
13485 | ? getRewrittenOverloadedOperator(Op) | |||
13486 | : OO_None; | |||
13487 | ||||
13488 | // Add the candidates from the given function set. This also adds the | |||
13489 | // rewritten candidates using these functions if necessary. | |||
13490 | AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); | |||
13491 | ||||
13492 | // Add operator candidates that are member functions. | |||
13493 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); | |||
13494 | if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) | |||
13495 | AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, | |||
13496 | OverloadCandidateParamOrder::Reversed); | |||
13497 | ||||
13498 | // In C++20, also add any rewritten member candidates. | |||
13499 | if (ExtraOp) { | |||
13500 | AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); | |||
13501 | if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) | |||
13502 | AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, | |||
13503 | CandidateSet, | |||
13504 | OverloadCandidateParamOrder::Reversed); | |||
13505 | } | |||
13506 | ||||
13507 | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not | |||
13508 | // performed for an assignment operator (nor for operator[] nor operator->, | |||
13509 | // which don't get here). | |||
13510 | if (Op != OO_Equal && PerformADL) { | |||
13511 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
13512 | AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, | |||
13513 | /*ExplicitTemplateArgs*/ nullptr, | |||
13514 | CandidateSet); | |||
13515 | if (ExtraOp) { | |||
13516 | DeclarationName ExtraOpName = | |||
13517 | Context.DeclarationNames.getCXXOperatorName(ExtraOp); | |||
13518 | AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, | |||
13519 | /*ExplicitTemplateArgs*/ nullptr, | |||
13520 | CandidateSet); | |||
13521 | } | |||
13522 | } | |||
13523 | ||||
13524 | // Add builtin operator candidates. | |||
13525 | // | |||
13526 | // FIXME: We don't add any rewritten candidates here. This is strictly | |||
13527 | // incorrect; a builtin candidate could be hidden by a non-viable candidate, | |||
13528 | // resulting in our selecting a rewritten builtin candidate. For example: | |||
13529 | // | |||
13530 | // enum class E { e }; | |||
13531 | // bool operator!=(E, E) requires false; | |||
13532 | // bool k = E::e != E::e; | |||
13533 | // | |||
13534 | // ... should select the rewritten builtin candidate 'operator==(E, E)'. But | |||
13535 | // it seems unreasonable to consider rewritten builtin candidates. A core | |||
13536 | // issue has been filed proposing to removed this requirement. | |||
13537 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); | |||
13538 | } | |||
13539 | ||||
13540 | /// Create a binary operation that may resolve to an overloaded | |||
13541 | /// operator. | |||
13542 | /// | |||
13543 | /// \param OpLoc The location of the operator itself (e.g., '+'). | |||
13544 | /// | |||
13545 | /// \param Opc The BinaryOperatorKind that describes this operator. | |||
13546 | /// | |||
13547 | /// \param Fns The set of non-member functions that will be | |||
13548 | /// considered by overload resolution. The caller needs to build this | |||
13549 | /// set based on the context using, e.g., | |||
13550 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This | |||
13551 | /// set should not contain any member functions; those will be added | |||
13552 | /// by CreateOverloadedBinOp(). | |||
13553 | /// | |||
13554 | /// \param LHS Left-hand argument. | |||
13555 | /// \param RHS Right-hand argument. | |||
13556 | /// \param PerformADL Whether to consider operator candidates found by ADL. | |||
13557 | /// \param AllowRewrittenCandidates Whether to consider candidates found by | |||
13558 | /// C++20 operator rewrites. | |||
13559 | /// \param DefaultedFn If we are synthesizing a defaulted operator function, | |||
13560 | /// the function in question. Such a function is never a candidate in | |||
13561 | /// our overload resolution. This also enables synthesizing a three-way | |||
13562 | /// comparison from < and == as described in C++20 [class.spaceship]p1. | |||
13563 | ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, | |||
13564 | BinaryOperatorKind Opc, | |||
13565 | const UnresolvedSetImpl &Fns, Expr *LHS, | |||
13566 | Expr *RHS, bool PerformADL, | |||
13567 | bool AllowRewrittenCandidates, | |||
13568 | FunctionDecl *DefaultedFn) { | |||
13569 | Expr *Args[2] = { LHS, RHS }; | |||
13570 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple | |||
13571 | ||||
13572 | if (!getLangOpts().CPlusPlus20) | |||
13573 | AllowRewrittenCandidates = false; | |||
13574 | ||||
13575 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); | |||
13576 | ||||
13577 | // If either side is type-dependent, create an appropriate dependent | |||
13578 | // expression. | |||
13579 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { | |||
13580 | if (Fns.empty()) { | |||
13581 | // If there are no functions to store, just build a dependent | |||
13582 | // BinaryOperator or CompoundAssignment. | |||
13583 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) | |||
13584 | return CompoundAssignOperator::Create( | |||
13585 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, | |||
13586 | OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, | |||
13587 | Context.DependentTy); | |||
13588 | return BinaryOperator::Create( | |||
13589 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, | |||
13590 | OK_Ordinary, OpLoc, CurFPFeatureOverrides()); | |||
13591 | } | |||
13592 | ||||
13593 | // FIXME: save results of ADL from here? | |||
13594 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
13595 | // TODO: provide better source location info in DNLoc component. | |||
13596 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
13597 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); | |||
13598 | ExprResult Fn = CreateUnresolvedLookupExpr( | |||
13599 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); | |||
13600 | if (Fn.isInvalid()) | |||
13601 | return ExprError(); | |||
13602 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, | |||
13603 | Context.DependentTy, VK_PRValue, OpLoc, | |||
13604 | CurFPFeatureOverrides()); | |||
13605 | } | |||
13606 | ||||
13607 | // Always do placeholder-like conversions on the RHS. | |||
13608 | if (checkPlaceholderForOverload(*this, Args[1])) | |||
13609 | return ExprError(); | |||
13610 | ||||
13611 | // Do placeholder-like conversion on the LHS; note that we should | |||
13612 | // not get here with a PseudoObject LHS. | |||
13613 | assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (Args[0]->getObjectKind() != OK_ObjCProperty ) ? void (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty" , "clang/lib/Sema/SemaOverload.cpp", 13613, __extension__ __PRETTY_FUNCTION__ )); | |||
13614 | if (checkPlaceholderForOverload(*this, Args[0])) | |||
13615 | return ExprError(); | |||
13616 | ||||
13617 | // If this is the assignment operator, we only perform overload resolution | |||
13618 | // if the left-hand side is a class or enumeration type. This is actually | |||
13619 | // a hack. The standard requires that we do overload resolution between the | |||
13620 | // various built-in candidates, but as DR507 points out, this can lead to | |||
13621 | // problems. So we do it this way, which pretty much follows what GCC does. | |||
13622 | // Note that we go the traditional code path for compound assignment forms. | |||
13623 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) | |||
13624 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
13625 | ||||
13626 | // If this is the .* operator, which is not overloadable, just | |||
13627 | // create a built-in binary operator. | |||
13628 | if (Opc == BO_PtrMemD) | |||
13629 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
13630 | ||||
13631 | // Build the overload set. | |||
13632 | OverloadCandidateSet CandidateSet( | |||
13633 | OpLoc, OverloadCandidateSet::CSK_Operator, | |||
13634 | OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); | |||
13635 | if (DefaultedFn) | |||
13636 | CandidateSet.exclude(DefaultedFn); | |||
13637 | LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); | |||
13638 | ||||
13639 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
13640 | ||||
13641 | // Perform overload resolution. | |||
13642 | OverloadCandidateSet::iterator Best; | |||
13643 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
13644 | case OR_Success: { | |||
13645 | // We found a built-in operator or an overloaded operator. | |||
13646 | FunctionDecl *FnDecl = Best->Function; | |||
13647 | ||||
13648 | bool IsReversed = Best->isReversed(); | |||
13649 | if (IsReversed) | |||
13650 | std::swap(Args[0], Args[1]); | |||
13651 | ||||
13652 | if (FnDecl) { | |||
13653 | Expr *Base = nullptr; | |||
13654 | // We matched an overloaded operator. Build a call to that | |||
13655 | // operator. | |||
13656 | ||||
13657 | OverloadedOperatorKind ChosenOp = | |||
13658 | FnDecl->getDeclName().getCXXOverloadedOperator(); | |||
13659 | ||||
13660 | // C++2a [over.match.oper]p9: | |||
13661 | // If a rewritten operator== candidate is selected by overload | |||
13662 | // resolution for an operator@, its return type shall be cv bool | |||
13663 | if (Best->RewriteKind && ChosenOp == OO_EqualEqual && | |||
13664 | !FnDecl->getReturnType()->isBooleanType()) { | |||
13665 | bool IsExtension = | |||
13666 | FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); | |||
13667 | Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool | |||
13668 | : diag::err_ovl_rewrite_equalequal_not_bool) | |||
13669 | << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) | |||
13670 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
13671 | Diag(FnDecl->getLocation(), diag::note_declared_at); | |||
13672 | if (!IsExtension) | |||
13673 | return ExprError(); | |||
13674 | } | |||
13675 | ||||
13676 | if (AllowRewrittenCandidates && !IsReversed && | |||
13677 | CandidateSet.getRewriteInfo().isReversible()) { | |||
13678 | // We could have reversed this operator, but didn't. Check if some | |||
13679 | // reversed form was a viable candidate, and if so, if it had a | |||
13680 | // better conversion for either parameter. If so, this call is | |||
13681 | // formally ambiguous, and allowing it is an extension. | |||
13682 | llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; | |||
13683 | for (OverloadCandidate &Cand : CandidateSet) { | |||
13684 | if (Cand.Viable && Cand.Function && Cand.isReversed() && | |||
13685 | haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { | |||
13686 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { | |||
13687 | if (CompareImplicitConversionSequences( | |||
13688 | *this, OpLoc, Cand.Conversions[ArgIdx], | |||
13689 | Best->Conversions[ArgIdx]) == | |||
13690 | ImplicitConversionSequence::Better) { | |||
13691 | AmbiguousWith.push_back(Cand.Function); | |||
13692 | break; | |||
13693 | } | |||
13694 | } | |||
13695 | } | |||
13696 | } | |||
13697 | ||||
13698 | if (!AmbiguousWith.empty()) { | |||
13699 | bool AmbiguousWithSelf = | |||
13700 | AmbiguousWith.size() == 1 && | |||
13701 | declaresSameEntity(AmbiguousWith.front(), FnDecl); | |||
13702 | Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) | |||
13703 | << BinaryOperator::getOpcodeStr(Opc) | |||
13704 | << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf | |||
13705 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
13706 | if (AmbiguousWithSelf) { | |||
13707 | Diag(FnDecl->getLocation(), | |||
13708 | diag::note_ovl_ambiguous_oper_binary_reversed_self); | |||
13709 | } else { | |||
13710 | Diag(FnDecl->getLocation(), | |||
13711 | diag::note_ovl_ambiguous_oper_binary_selected_candidate); | |||
13712 | for (auto *F : AmbiguousWith) | |||
13713 | Diag(F->getLocation(), | |||
13714 | diag::note_ovl_ambiguous_oper_binary_reversed_candidate); | |||
13715 | } | |||
13716 | } | |||
13717 | } | |||
13718 | ||||
13719 | // Convert the arguments. | |||
13720 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
13721 | // Best->Access is only meaningful for class members. | |||
13722 | CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); | |||
13723 | ||||
13724 | ExprResult Arg1 = | |||
13725 | PerformCopyInitialization( | |||
13726 | InitializedEntity::InitializeParameter(Context, | |||
13727 | FnDecl->getParamDecl(0)), | |||
13728 | SourceLocation(), Args[1]); | |||
13729 | if (Arg1.isInvalid()) | |||
13730 | return ExprError(); | |||
13731 | ||||
13732 | ExprResult Arg0 = | |||
13733 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, | |||
13734 | Best->FoundDecl, Method); | |||
13735 | if (Arg0.isInvalid()) | |||
13736 | return ExprError(); | |||
13737 | Base = Args[0] = Arg0.getAs<Expr>(); | |||
13738 | Args[1] = RHS = Arg1.getAs<Expr>(); | |||
13739 | } else { | |||
13740 | // Convert the arguments. | |||
13741 | ExprResult Arg0 = PerformCopyInitialization( | |||
13742 | InitializedEntity::InitializeParameter(Context, | |||
13743 | FnDecl->getParamDecl(0)), | |||
13744 | SourceLocation(), Args[0]); | |||
13745 | if (Arg0.isInvalid()) | |||
13746 | return ExprError(); | |||
13747 | ||||
13748 | ExprResult Arg1 = | |||
13749 | PerformCopyInitialization( | |||
13750 | InitializedEntity::InitializeParameter(Context, | |||
13751 | FnDecl->getParamDecl(1)), | |||
13752 | SourceLocation(), Args[1]); | |||
13753 | if (Arg1.isInvalid()) | |||
13754 | return ExprError(); | |||
13755 | Args[0] = LHS = Arg0.getAs<Expr>(); | |||
13756 | Args[1] = RHS = Arg1.getAs<Expr>(); | |||
13757 | } | |||
13758 | ||||
13759 | // Build the actual expression node. | |||
13760 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, | |||
13761 | Best->FoundDecl, Base, | |||
13762 | HadMultipleCandidates, OpLoc); | |||
13763 | if (FnExpr.isInvalid()) | |||
13764 | return ExprError(); | |||
13765 | ||||
13766 | // Determine the result type. | |||
13767 | QualType ResultTy = FnDecl->getReturnType(); | |||
13768 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
13769 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
13770 | ||||
13771 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
13772 | Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, | |||
13773 | CurFPFeatureOverrides(), Best->IsADLCandidate); | |||
13774 | ||||
13775 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, | |||
13776 | FnDecl)) | |||
13777 | return ExprError(); | |||
13778 | ||||
13779 | ArrayRef<const Expr *> ArgsArray(Args, 2); | |||
13780 | const Expr *ImplicitThis = nullptr; | |||
13781 | // Cut off the implicit 'this'. | |||
13782 | if (isa<CXXMethodDecl>(FnDecl)) { | |||
13783 | ImplicitThis = ArgsArray[0]; | |||
13784 | ArgsArray = ArgsArray.slice(1); | |||
13785 | } | |||
13786 | ||||
13787 | // Check for a self move. | |||
13788 | if (Op == OO_Equal) | |||
13789 | DiagnoseSelfMove(Args[0], Args[1], OpLoc); | |||
13790 | ||||
13791 | if (ImplicitThis) { | |||
13792 | QualType ThisType = Context.getPointerType(ImplicitThis->getType()); | |||
13793 | QualType ThisTypeFromDecl = Context.getPointerType( | |||
13794 | cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); | |||
13795 | ||||
13796 | CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, | |||
13797 | ThisTypeFromDecl); | |||
13798 | } | |||
13799 | ||||
13800 | checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, | |||
13801 | isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), | |||
13802 | VariadicDoesNotApply); | |||
13803 | ||||
13804 | ExprResult R = MaybeBindToTemporary(TheCall); | |||
13805 | if (R.isInvalid()) | |||
13806 | return ExprError(); | |||
13807 | ||||
13808 | R = CheckForImmediateInvocation(R, FnDecl); | |||
13809 | if (R.isInvalid()) | |||
13810 | return ExprError(); | |||
13811 | ||||
13812 | // For a rewritten candidate, we've already reversed the arguments | |||
13813 | // if needed. Perform the rest of the rewrite now. | |||
13814 | if ((Best->RewriteKind & CRK_DifferentOperator) || | |||
13815 | (Op == OO_Spaceship && IsReversed)) { | |||
13816 | if (Op == OO_ExclaimEqual) { | |||
13817 | assert(ChosenOp == OO_EqualEqual && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_EqualEqual && "unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 13817, __extension__ __PRETTY_FUNCTION__ )); | |||
13818 | R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); | |||
13819 | } else { | |||
13820 | assert(ChosenOp == OO_Spaceship && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_Spaceship && "unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 13820, __extension__ __PRETTY_FUNCTION__ )); | |||
13821 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); | |||
13822 | Expr *ZeroLiteral = | |||
13823 | IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); | |||
13824 | ||||
13825 | Sema::CodeSynthesisContext Ctx; | |||
13826 | Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; | |||
13827 | Ctx.Entity = FnDecl; | |||
13828 | pushCodeSynthesisContext(Ctx); | |||
13829 | ||||
13830 | R = CreateOverloadedBinOp( | |||
13831 | OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), | |||
13832 | IsReversed ? R.get() : ZeroLiteral, PerformADL, | |||
13833 | /*AllowRewrittenCandidates=*/false); | |||
13834 | ||||
13835 | popCodeSynthesisContext(); | |||
13836 | } | |||
13837 | if (R.isInvalid()) | |||
13838 | return ExprError(); | |||
13839 | } else { | |||
13840 | assert(ChosenOp == Op && "unexpected operator name")(static_cast <bool> (ChosenOp == Op && "unexpected operator name" ) ? void (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\"" , "clang/lib/Sema/SemaOverload.cpp", 13840, __extension__ __PRETTY_FUNCTION__ )); | |||
13841 | } | |||
13842 | ||||
13843 | // Make a note in the AST if we did any rewriting. | |||
13844 | if (Best->RewriteKind != CRK_None) | |||
13845 | R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); | |||
13846 | ||||
13847 | return R; | |||
13848 | } else { | |||
13849 | // We matched a built-in operator. Convert the arguments, then | |||
13850 | // break out so that we will build the appropriate built-in | |||
13851 | // operator node. | |||
13852 | ExprResult ArgsRes0 = PerformImplicitConversion( | |||
13853 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
13854 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
13855 | if (ArgsRes0.isInvalid()) | |||
13856 | return ExprError(); | |||
13857 | Args[0] = ArgsRes0.get(); | |||
13858 | ||||
13859 | ExprResult ArgsRes1 = PerformImplicitConversion( | |||
13860 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
13861 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
13862 | if (ArgsRes1.isInvalid()) | |||
13863 | return ExprError(); | |||
13864 | Args[1] = ArgsRes1.get(); | |||
13865 | break; | |||
13866 | } | |||
13867 | } | |||
13868 | ||||
13869 | case OR_No_Viable_Function: { | |||
13870 | // C++ [over.match.oper]p9: | |||
13871 | // If the operator is the operator , [...] and there are no | |||
13872 | // viable functions, then the operator is assumed to be the | |||
13873 | // built-in operator and interpreted according to clause 5. | |||
13874 | if (Opc == BO_Comma) | |||
13875 | break; | |||
13876 | ||||
13877 | // When defaulting an 'operator<=>', we can try to synthesize a three-way | |||
13878 | // compare result using '==' and '<'. | |||
13879 | if (DefaultedFn && Opc == BO_Cmp) { | |||
13880 | ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], | |||
13881 | Args[1], DefaultedFn); | |||
13882 | if (E.isInvalid() || E.isUsable()) | |||
13883 | return E; | |||
13884 | } | |||
13885 | ||||
13886 | // For class as left operand for assignment or compound assignment | |||
13887 | // operator do not fall through to handling in built-in, but report that | |||
13888 | // no overloaded assignment operator found | |||
13889 | ExprResult Result = ExprError(); | |||
13890 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); | |||
13891 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, | |||
13892 | Args, OpLoc); | |||
13893 | DeferDiagsRAII DDR(*this, | |||
13894 | CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); | |||
13895 | if (Args[0]->getType()->isRecordType() && | |||
13896 | Opc >= BO_Assign && Opc <= BO_OrAssign) { | |||
13897 | Diag(OpLoc, diag::err_ovl_no_viable_oper) | |||
13898 | << BinaryOperator::getOpcodeStr(Opc) | |||
13899 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
13900 | if (Args[0]->getType()->isIncompleteType()) { | |||
13901 | Diag(OpLoc, diag::note_assign_lhs_incomplete) | |||
13902 | << Args[0]->getType() | |||
13903 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
13904 | } | |||
13905 | } else { | |||
13906 | // This is an erroneous use of an operator which can be overloaded by | |||
13907 | // a non-member function. Check for non-member operators which were | |||
13908 | // defined too late to be candidates. | |||
13909 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) | |||
13910 | // FIXME: Recover by calling the found function. | |||
13911 | return ExprError(); | |||
13912 | ||||
13913 | // No viable function; try to create a built-in operation, which will | |||
13914 | // produce an error. Then, show the non-viable candidates. | |||
13915 | Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
13916 | } | |||
13917 | assert(Result.isInvalid() &&(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "clang/lib/Sema/SemaOverload.cpp", 13918, __extension__ __PRETTY_FUNCTION__ )) | |||
13918 | "C++ binary operator overloading is missing candidates!")(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "clang/lib/Sema/SemaOverload.cpp", 13918, __extension__ __PRETTY_FUNCTION__ )); | |||
13919 | CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); | |||
13920 | return Result; | |||
13921 | } | |||
13922 | ||||
13923 | case OR_Ambiguous: | |||
13924 | CandidateSet.NoteCandidates( | |||
13925 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) | |||
13926 | << BinaryOperator::getOpcodeStr(Opc) | |||
13927 | << Args[0]->getType() | |||
13928 | << Args[1]->getType() | |||
13929 | << Args[0]->getSourceRange() | |||
13930 | << Args[1]->getSourceRange()), | |||
13931 | *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), | |||
13932 | OpLoc); | |||
13933 | return ExprError(); | |||
13934 | ||||
13935 | case OR_Deleted: | |||
13936 | if (isImplicitlyDeleted(Best->Function)) { | |||
13937 | FunctionDecl *DeletedFD = Best->Function; | |||
13938 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); | |||
13939 | if (DFK.isSpecialMember()) { | |||
13940 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) | |||
13941 | << Args[0]->getType() << DFK.asSpecialMember(); | |||
13942 | } else { | |||
13943 | assert(DFK.isComparison())(static_cast <bool> (DFK.isComparison()) ? void (0) : __assert_fail ("DFK.isComparison()", "clang/lib/Sema/SemaOverload.cpp", 13943 , __extension__ __PRETTY_FUNCTION__)); | |||
13944 | Diag(OpLoc, diag::err_ovl_deleted_comparison) | |||
13945 | << Args[0]->getType() << DeletedFD; | |||
13946 | } | |||
13947 | ||||
13948 | // The user probably meant to call this special member. Just | |||
13949 | // explain why it's deleted. | |||
13950 | NoteDeletedFunction(DeletedFD); | |||
13951 | return ExprError(); | |||
13952 | } | |||
13953 | CandidateSet.NoteCandidates( | |||
13954 | PartialDiagnosticAt( | |||
13955 | OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
13956 | << getOperatorSpelling(Best->Function->getDeclName() | |||
13957 | .getCXXOverloadedOperator()) | |||
13958 | << Args[0]->getSourceRange() | |||
13959 | << Args[1]->getSourceRange()), | |||
13960 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), | |||
13961 | OpLoc); | |||
13962 | return ExprError(); | |||
13963 | } | |||
13964 | ||||
13965 | // We matched a built-in operator; build it. | |||
13966 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
13967 | } | |||
13968 | ||||
13969 | ExprResult Sema::BuildSynthesizedThreeWayComparison( | |||
13970 | SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, | |||
13971 | FunctionDecl *DefaultedFn) { | |||
13972 | const ComparisonCategoryInfo *Info = | |||
13973 | Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); | |||
13974 | // If we're not producing a known comparison category type, we can't | |||
13975 | // synthesize a three-way comparison. Let the caller diagnose this. | |||
13976 | if (!Info) | |||
13977 | return ExprResult((Expr*)nullptr); | |||
13978 | ||||
13979 | // If we ever want to perform this synthesis more generally, we will need to | |||
13980 | // apply the temporary materialization conversion to the operands. | |||
13981 | assert(LHS->isGLValue() && RHS->isGLValue() &&(static_cast <bool> (LHS->isGLValue() && RHS ->isGLValue() && "cannot use prvalue expressions more than once" ) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\"" , "clang/lib/Sema/SemaOverload.cpp", 13982, __extension__ __PRETTY_FUNCTION__ )) | |||
13982 | "cannot use prvalue expressions more than once")(static_cast <bool> (LHS->isGLValue() && RHS ->isGLValue() && "cannot use prvalue expressions more than once" ) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\"" , "clang/lib/Sema/SemaOverload.cpp", 13982, __extension__ __PRETTY_FUNCTION__ )); | |||
13983 | Expr *OrigLHS = LHS; | |||
13984 | Expr *OrigRHS = RHS; | |||
13985 | ||||
13986 | // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to | |||
13987 | // each of them multiple times below. | |||
13988 | LHS = new (Context) | |||
13989 | OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), | |||
13990 | LHS->getObjectKind(), LHS); | |||
13991 | RHS = new (Context) | |||
13992 | OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), | |||
13993 | RHS->getObjectKind(), RHS); | |||
13994 | ||||
13995 | ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, | |||
13996 | DefaultedFn); | |||
13997 | if (Eq.isInvalid()) | |||
13998 | return ExprError(); | |||
13999 | ||||
14000 | ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, | |||
14001 | true, DefaultedFn); | |||
14002 | if (Less.isInvalid()) | |||
14003 | return ExprError(); | |||
14004 | ||||
14005 | ExprResult Greater; | |||
14006 | if (Info->isPartial()) { | |||
14007 | Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, | |||
14008 | DefaultedFn); | |||
14009 | if (Greater.isInvalid()) | |||
14010 | return ExprError(); | |||
14011 | } | |||
14012 | ||||
14013 | // Form the list of comparisons we're going to perform. | |||
14014 | struct Comparison { | |||
14015 | ExprResult Cmp; | |||
14016 | ComparisonCategoryResult Result; | |||
14017 | } Comparisons[4] = | |||
14018 | { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal | |||
14019 | : ComparisonCategoryResult::Equivalent}, | |||
14020 | {Less, ComparisonCategoryResult::Less}, | |||
14021 | {Greater, ComparisonCategoryResult::Greater}, | |||
14022 | {ExprResult(), ComparisonCategoryResult::Unordered}, | |||
14023 | }; | |||
14024 | ||||
14025 | int I = Info->isPartial() ? 3 : 2; | |||
14026 | ||||
14027 | // Combine the comparisons with suitable conditional expressions. | |||
14028 | ExprResult Result; | |||
14029 | for (; I >= 0; --I) { | |||
14030 | // Build a reference to the comparison category constant. | |||
14031 | auto *VI = Info->lookupValueInfo(Comparisons[I].Result); | |||
14032 | // FIXME: Missing a constant for a comparison category. Diagnose this? | |||
14033 | if (!VI) | |||
14034 | return ExprResult((Expr*)nullptr); | |||
14035 | ExprResult ThisResult = | |||
14036 | BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); | |||
14037 | if (ThisResult.isInvalid()) | |||
14038 | return ExprError(); | |||
14039 | ||||
14040 | // Build a conditional unless this is the final case. | |||
14041 | if (Result.get()) { | |||
14042 | Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), | |||
14043 | ThisResult.get(), Result.get()); | |||
14044 | if (Result.isInvalid()) | |||
14045 | return ExprError(); | |||
14046 | } else { | |||
14047 | Result = ThisResult; | |||
14048 | } | |||
14049 | } | |||
14050 | ||||
14051 | // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to | |||
14052 | // bind the OpaqueValueExprs before they're (repeatedly) used. | |||
14053 | Expr *SyntacticForm = BinaryOperator::Create( | |||
14054 | Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), | |||
14055 | Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, | |||
14056 | CurFPFeatureOverrides()); | |||
14057 | Expr *SemanticForm[] = {LHS, RHS, Result.get()}; | |||
14058 | return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); | |||
14059 | } | |||
14060 | ||||
14061 | static bool PrepareArgumentsForCallToObjectOfClassType( | |||
14062 | Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, | |||
14063 | MultiExprArg Args, SourceLocation LParenLoc) { | |||
14064 | ||||
14065 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); | |||
14066 | unsigned NumParams = Proto->getNumParams(); | |||
14067 | unsigned NumArgsSlots = | |||
14068 | MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); | |||
14069 | // Build the full argument list for the method call (the implicit object | |||
14070 | // parameter is placed at the beginning of the list). | |||
14071 | MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); | |||
14072 | bool IsError = false; | |||
14073 | // Initialize the implicit object parameter. | |||
14074 | // Check the argument types. | |||
14075 | for (unsigned i = 0; i != NumParams; i++) { | |||
14076 | Expr *Arg; | |||
14077 | if (i < Args.size()) { | |||
14078 | Arg = Args[i]; | |||
14079 | ExprResult InputInit = | |||
14080 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
14081 | S.Context, Method->getParamDecl(i)), | |||
14082 | SourceLocation(), Arg); | |||
14083 | IsError |= InputInit.isInvalid(); | |||
14084 | Arg = InputInit.getAs<Expr>(); | |||
14085 | } else { | |||
14086 | ExprResult DefArg = | |||
14087 | S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); | |||
14088 | if (DefArg.isInvalid()) { | |||
14089 | IsError = true; | |||
14090 | break; | |||
14091 | } | |||
14092 | Arg = DefArg.getAs<Expr>(); | |||
14093 | } | |||
14094 | ||||
14095 | MethodArgs.push_back(Arg); | |||
14096 | } | |||
14097 | return IsError; | |||
14098 | } | |||
14099 | ||||
14100 | ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, | |||
14101 | SourceLocation RLoc, | |||
14102 | Expr *Base, | |||
14103 | MultiExprArg ArgExpr) { | |||
14104 | SmallVector<Expr *, 2> Args; | |||
14105 | Args.push_back(Base); | |||
14106 | for (auto e : ArgExpr) { | |||
14107 | Args.push_back(e); | |||
14108 | } | |||
14109 | DeclarationName OpName = | |||
14110 | Context.DeclarationNames.getCXXOperatorName(OO_Subscript); | |||
14111 | ||||
14112 | SourceRange Range = ArgExpr.empty() | |||
14113 | ? SourceRange{} | |||
14114 | : SourceRange(ArgExpr.front()->getBeginLoc(), | |||
14115 | ArgExpr.back()->getEndLoc()); | |||
14116 | ||||
14117 | // If either side is type-dependent, create an appropriate dependent | |||
14118 | // expression. | |||
14119 | if (Expr::hasAnyTypeDependentArguments(Args)) { | |||
14120 | ||||
14121 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
14122 | // CHECKME: no 'operator' keyword? | |||
14123 | DeclarationNameInfo OpNameInfo(OpName, LLoc); | |||
14124 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); | |||
14125 | ExprResult Fn = CreateUnresolvedLookupExpr( | |||
14126 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); | |||
14127 | if (Fn.isInvalid()) | |||
14128 | return ExprError(); | |||
14129 | // Can't add any actual overloads yet | |||
14130 | ||||
14131 | return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, | |||
14132 | Context.DependentTy, VK_PRValue, RLoc, | |||
14133 | CurFPFeatureOverrides()); | |||
14134 | } | |||
14135 | ||||
14136 | // Handle placeholders | |||
14137 | UnbridgedCastsSet UnbridgedCasts; | |||
14138 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { | |||
14139 | return ExprError(); | |||
14140 | } | |||
14141 | // Build an empty overload set. | |||
14142 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); | |||
14143 | ||||
14144 | // Subscript can only be overloaded as a member function. | |||
14145 | ||||
14146 | // Add operator candidates that are member functions. | |||
14147 | AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); | |||
14148 | ||||
14149 | // Add builtin operator candidates. | |||
14150 | if (Args.size() == 2) | |||
14151 | AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); | |||
14152 | ||||
14153 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
14154 | ||||
14155 | // Perform overload resolution. | |||
14156 | OverloadCandidateSet::iterator Best; | |||
14157 | switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { | |||
14158 | case OR_Success: { | |||
14159 | // We found a built-in operator or an overloaded operator. | |||
14160 | FunctionDecl *FnDecl = Best->Function; | |||
14161 | ||||
14162 | if (FnDecl) { | |||
14163 | // We matched an overloaded operator. Build a call to that | |||
14164 | // operator. | |||
14165 | ||||
14166 | CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); | |||
14167 | ||||
14168 | // Convert the arguments. | |||
14169 | CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); | |||
14170 | SmallVector<Expr *, 2> MethodArgs; | |||
14171 | ExprResult Arg0 = PerformObjectArgumentInitialization( | |||
14172 | Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); | |||
14173 | if (Arg0.isInvalid()) | |||
14174 | return ExprError(); | |||
14175 | ||||
14176 | MethodArgs.push_back(Arg0.get()); | |||
14177 | bool IsError = PrepareArgumentsForCallToObjectOfClassType( | |||
14178 | *this, MethodArgs, Method, ArgExpr, LLoc); | |||
14179 | if (IsError) | |||
14180 | return ExprError(); | |||
14181 | ||||
14182 | // Build the actual expression node. | |||
14183 | DeclarationNameInfo OpLocInfo(OpName, LLoc); | |||
14184 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); | |||
14185 | ExprResult FnExpr = CreateFunctionRefExpr( | |||
14186 | *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, | |||
14187 | OpLocInfo.getLoc(), OpLocInfo.getInfo()); | |||
14188 | if (FnExpr.isInvalid()) | |||
14189 | return ExprError(); | |||
14190 | ||||
14191 | // Determine the result type | |||
14192 | QualType ResultTy = FnDecl->getReturnType(); | |||
14193 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
14194 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
14195 | ||||
14196 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
14197 | Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, | |||
14198 | CurFPFeatureOverrides()); | |||
14199 | if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) | |||
14200 | return ExprError(); | |||
14201 | ||||
14202 | if (CheckFunctionCall(Method, TheCall, | |||
14203 | Method->getType()->castAs<FunctionProtoType>())) | |||
14204 | return ExprError(); | |||
14205 | ||||
14206 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), | |||
14207 | FnDecl); | |||
14208 | } else { | |||
14209 | // We matched a built-in operator. Convert the arguments, then | |||
14210 | // break out so that we will build the appropriate built-in | |||
14211 | // operator node. | |||
14212 | ExprResult ArgsRes0 = PerformImplicitConversion( | |||
14213 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
14214 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
14215 | if (ArgsRes0.isInvalid()) | |||
14216 | return ExprError(); | |||
14217 | Args[0] = ArgsRes0.get(); | |||
14218 | ||||
14219 | ExprResult ArgsRes1 = PerformImplicitConversion( | |||
14220 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
14221 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
14222 | if (ArgsRes1.isInvalid()) | |||
14223 | return ExprError(); | |||
14224 | Args[1] = ArgsRes1.get(); | |||
14225 | ||||
14226 | break; | |||
14227 | } | |||
14228 | } | |||
14229 | ||||
14230 | case OR_No_Viable_Function: { | |||
14231 | PartialDiagnostic PD = | |||
14232 | CandidateSet.empty() | |||
14233 | ? (PDiag(diag::err_ovl_no_oper) | |||
14234 | << Args[0]->getType() << /*subscript*/ 0 | |||
14235 | << Args[0]->getSourceRange() << Range) | |||
14236 | : (PDiag(diag::err_ovl_no_viable_subscript) | |||
14237 | << Args[0]->getType() << Args[0]->getSourceRange() << Range); | |||
14238 | CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, | |||
14239 | OCD_AllCandidates, ArgExpr, "[]", LLoc); | |||
14240 | return ExprError(); | |||
14241 | } | |||
14242 | ||||
14243 | case OR_Ambiguous: | |||
14244 | if (Args.size() == 2) { | |||
14245 | CandidateSet.NoteCandidates( | |||
14246 | PartialDiagnosticAt( | |||
14247 | LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) | |||
14248 | << "[]" << Args[0]->getType() << Args[1]->getType() | |||
14249 | << Args[0]->getSourceRange() << Range), | |||
14250 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); | |||
14251 | } else { | |||
14252 | CandidateSet.NoteCandidates( | |||
14253 | PartialDiagnosticAt(LLoc, | |||
14254 | PDiag(diag::err_ovl_ambiguous_subscript_call) | |||
14255 | << Args[0]->getType() | |||
14256 | << Args[0]->getSourceRange() << Range), | |||
14257 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); | |||
14258 | } | |||
14259 | return ExprError(); | |||
14260 | ||||
14261 | case OR_Deleted: | |||
14262 | CandidateSet.NoteCandidates( | |||
14263 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) | |||
14264 | << "[]" << Args[0]->getSourceRange() | |||
14265 | << Range), | |||
14266 | *this, OCD_AllCandidates, Args, "[]", LLoc); | |||
14267 | return ExprError(); | |||
14268 | } | |||
14269 | ||||
14270 | // We matched a built-in operator; build it. | |||
14271 | return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); | |||
14272 | } | |||
14273 | ||||
14274 | /// BuildCallToMemberFunction - Build a call to a member | |||
14275 | /// function. MemExpr is the expression that refers to the member | |||
14276 | /// function (and includes the object parameter), Args/NumArgs are the | |||
14277 | /// arguments to the function call (not including the object | |||
14278 | /// parameter). The caller needs to validate that the member | |||
14279 | /// expression refers to a non-static member function or an overloaded | |||
14280 | /// member function. | |||
14281 | ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, | |||
14282 | SourceLocation LParenLoc, | |||
14283 | MultiExprArg Args, | |||
14284 | SourceLocation RParenLoc, | |||
14285 | Expr *ExecConfig, bool IsExecConfig, | |||
14286 | bool AllowRecovery) { | |||
14287 | assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast <bool> (MemExprE->getType() == Context. BoundMemberTy || MemExprE->getType() == Context.OverloadTy ) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 14288, __extension__ __PRETTY_FUNCTION__ )) | |||
14288 | MemExprE->getType() == Context.OverloadTy)(static_cast <bool> (MemExprE->getType() == Context. BoundMemberTy || MemExprE->getType() == Context.OverloadTy ) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "clang/lib/Sema/SemaOverload.cpp", 14288, __extension__ __PRETTY_FUNCTION__ )); | |||
14289 | ||||
14290 | // Dig out the member expression. This holds both the object | |||
14291 | // argument and the member function we're referring to. | |||
14292 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); | |||
14293 | ||||
14294 | // Determine whether this is a call to a pointer-to-member function. | |||
14295 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { | |||
14296 | assert(op->getType() == Context.BoundMemberTy)(static_cast <bool> (op->getType() == Context.BoundMemberTy ) ? void (0) : __assert_fail ("op->getType() == Context.BoundMemberTy" , "clang/lib/Sema/SemaOverload.cpp", 14296, __extension__ __PRETTY_FUNCTION__ )); | |||
14297 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast <bool> (op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI" , "clang/lib/Sema/SemaOverload.cpp", 14297, __extension__ __PRETTY_FUNCTION__ )); | |||
14298 | ||||
14299 | QualType fnType = | |||
14300 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); | |||
14301 | ||||
14302 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); | |||
14303 | QualType resultType = proto->getCallResultType(Context); | |||
14304 | ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); | |||
14305 | ||||
14306 | // Check that the object type isn't more qualified than the | |||
14307 | // member function we're calling. | |||
14308 | Qualifiers funcQuals = proto->getMethodQuals(); | |||
14309 | ||||
14310 | QualType objectType = op->getLHS()->getType(); | |||
14311 | if (op->getOpcode() == BO_PtrMemI) | |||
14312 | objectType = objectType->castAs<PointerType>()->getPointeeType(); | |||
14313 | Qualifiers objectQuals = objectType.getQualifiers(); | |||
14314 | ||||
14315 | Qualifiers difference = objectQuals - funcQuals; | |||
14316 | difference.removeObjCGCAttr(); | |||
14317 | difference.removeAddressSpace(); | |||
14318 | if (difference) { | |||
14319 | std::string qualsString = difference.getAsString(); | |||
14320 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) | |||
14321 | << fnType.getUnqualifiedType() | |||
14322 | << qualsString | |||
14323 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); | |||
14324 | } | |||
14325 | ||||
14326 | CXXMemberCallExpr *call = CXXMemberCallExpr::Create( | |||
14327 | Context, MemExprE, Args, resultType, valueKind, RParenLoc, | |||
14328 | CurFPFeatureOverrides(), proto->getNumParams()); | |||
14329 | ||||
14330 | if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), | |||
14331 | call, nullptr)) | |||
14332 | return ExprError(); | |||
14333 | ||||
14334 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) | |||
14335 | return ExprError(); | |||
14336 | ||||
14337 | if (CheckOtherCall(call, proto)) | |||
14338 | return ExprError(); | |||
14339 | ||||
14340 | return MaybeBindToTemporary(call); | |||
14341 | } | |||
14342 | ||||
14343 | // We only try to build a recovery expr at this level if we can preserve | |||
14344 | // the return type, otherwise we return ExprError() and let the caller | |||
14345 | // recover. | |||
14346 | auto BuildRecoveryExpr = [&](QualType Type) { | |||
14347 | if (!AllowRecovery) | |||
14348 | return ExprError(); | |||
14349 | std::vector<Expr *> SubExprs = {MemExprE}; | |||
14350 | llvm::append_range(SubExprs, Args); | |||
14351 | return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, | |||
14352 | Type); | |||
14353 | }; | |||
14354 | if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) | |||
14355 | return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, | |||
14356 | RParenLoc, CurFPFeatureOverrides()); | |||
14357 | ||||
14358 | UnbridgedCastsSet UnbridgedCasts; | |||
14359 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) | |||
14360 | return ExprError(); | |||
14361 | ||||
14362 | MemberExpr *MemExpr; | |||
14363 | CXXMethodDecl *Method = nullptr; | |||
14364 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); | |||
14365 | NestedNameSpecifier *Qualifier = nullptr; | |||
14366 | if (isa<MemberExpr>(NakedMemExpr)) { | |||
14367 | MemExpr = cast<MemberExpr>(NakedMemExpr); | |||
14368 | Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); | |||
14369 | FoundDecl = MemExpr->getFoundDecl(); | |||
14370 | Qualifier = MemExpr->getQualifier(); | |||
14371 | UnbridgedCasts.restore(); | |||
14372 | } else { | |||
14373 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); | |||
14374 | Qualifier = UnresExpr->getQualifier(); | |||
14375 | ||||
14376 | QualType ObjectType = UnresExpr->getBaseType(); | |||
14377 | Expr::Classification ObjectClassification | |||
14378 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() | |||
14379 | : UnresExpr->getBase()->Classify(Context); | |||
14380 | ||||
14381 | // Add overload candidates | |||
14382 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), | |||
14383 | OverloadCandidateSet::CSK_Normal); | |||
14384 | ||||
14385 | // FIXME: avoid copy. | |||
14386 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
14387 | if (UnresExpr->hasExplicitTemplateArgs()) { | |||
14388 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
14389 | TemplateArgs = &TemplateArgsBuffer; | |||
14390 | } | |||
14391 | ||||
14392 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), | |||
14393 | E = UnresExpr->decls_end(); I != E; ++I) { | |||
14394 | ||||
14395 | NamedDecl *Func = *I; | |||
14396 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); | |||
14397 | if (isa<UsingShadowDecl>(Func)) | |||
14398 | Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); | |||
14399 | ||||
14400 | ||||
14401 | // Microsoft supports direct constructor calls. | |||
14402 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { | |||
14403 | AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, | |||
14404 | CandidateSet, | |||
14405 | /*SuppressUserConversions*/ false); | |||
14406 | } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { | |||
14407 | // If explicit template arguments were provided, we can't call a | |||
14408 | // non-template member function. | |||
14409 | if (TemplateArgs) | |||
14410 | continue; | |||
14411 | ||||
14412 | AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, | |||
14413 | ObjectClassification, Args, CandidateSet, | |||
14414 | /*SuppressUserConversions=*/false); | |||
14415 | } else { | |||
14416 | AddMethodTemplateCandidate( | |||
14417 | cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, | |||
14418 | TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, | |||
14419 | /*SuppressUserConversions=*/false); | |||
14420 | } | |||
14421 | } | |||
14422 | ||||
14423 | DeclarationName DeclName = UnresExpr->getMemberName(); | |||
14424 | ||||
14425 | UnbridgedCasts.restore(); | |||
14426 | ||||
14427 | OverloadCandidateSet::iterator Best; | |||
14428 | bool Succeeded = false; | |||
14429 | switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), | |||
14430 | Best)) { | |||
14431 | case OR_Success: | |||
14432 | Method = cast<CXXMethodDecl>(Best->Function); | |||
14433 | FoundDecl = Best->FoundDecl; | |||
14434 | CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); | |||
14435 | if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) | |||
14436 | break; | |||
14437 | // If FoundDecl is different from Method (such as if one is a template | |||
14438 | // and the other a specialization), make sure DiagnoseUseOfDecl is | |||
14439 | // called on both. | |||
14440 | // FIXME: This would be more comprehensively addressed by modifying | |||
14441 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl | |||
14442 | // being used. | |||
14443 | if (Method != FoundDecl.getDecl() && | |||
14444 | DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) | |||
14445 | break; | |||
14446 | Succeeded = true; | |||
14447 | break; | |||
14448 | ||||
14449 | case OR_No_Viable_Function: | |||
14450 | CandidateSet.NoteCandidates( | |||
14451 | PartialDiagnosticAt( | |||
14452 | UnresExpr->getMemberLoc(), | |||
14453 | PDiag(diag::err_ovl_no_viable_member_function_in_call) | |||
14454 | << DeclName << MemExprE->getSourceRange()), | |||
14455 | *this, OCD_AllCandidates, Args); | |||
14456 | break; | |||
14457 | case OR_Ambiguous: | |||
14458 | CandidateSet.NoteCandidates( | |||
14459 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), | |||
14460 | PDiag(diag::err_ovl_ambiguous_member_call) | |||
14461 | << DeclName << MemExprE->getSourceRange()), | |||
14462 | *this, OCD_AmbiguousCandidates, Args); | |||
14463 | break; | |||
14464 | case OR_Deleted: | |||
14465 | CandidateSet.NoteCandidates( | |||
14466 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), | |||
14467 | PDiag(diag::err_ovl_deleted_member_call) | |||
14468 | << DeclName << MemExprE->getSourceRange()), | |||
14469 | *this, OCD_AllCandidates, Args); | |||
14470 | break; | |||
14471 | } | |||
14472 | // Overload resolution fails, try to recover. | |||
14473 | if (!Succeeded) | |||
14474 | return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); | |||
14475 | ||||
14476 | MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); | |||
14477 | ||||
14478 | // If overload resolution picked a static member, build a | |||
14479 | // non-member call based on that function. | |||
14480 | if (Method->isStatic()) { | |||
14481 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, | |||
14482 | ExecConfig, IsExecConfig); | |||
14483 | } | |||
14484 | ||||
14485 | MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); | |||
14486 | } | |||
14487 | ||||
14488 | QualType ResultType = Method->getReturnType(); | |||
14489 | ExprValueKind VK = Expr::getValueKindForType(ResultType); | |||
14490 | ResultType = ResultType.getNonLValueExprType(Context); | |||
14491 | ||||
14492 | assert(Method && "Member call to something that isn't a method?")(static_cast <bool> (Method && "Member call to something that isn't a method?" ) ? void (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\"" , "clang/lib/Sema/SemaOverload.cpp", 14492, __extension__ __PRETTY_FUNCTION__ )); | |||
14493 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); | |||
14494 | CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( | |||
14495 | Context, MemExprE, Args, ResultType, VK, RParenLoc, | |||
14496 | CurFPFeatureOverrides(), Proto->getNumParams()); | |||
14497 | ||||
14498 | // Check for a valid return type. | |||
14499 | if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), | |||
14500 | TheCall, Method)) | |||
14501 | return BuildRecoveryExpr(ResultType); | |||
14502 | ||||
14503 | // Convert the object argument (for a non-static member function call). | |||
14504 | // We only need to do this if there was actually an overload; otherwise | |||
14505 | // it was done at lookup. | |||
14506 | if (!Method->isStatic()) { | |||
14507 | ExprResult ObjectArg = | |||
14508 | PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, | |||
14509 | FoundDecl, Method); | |||
14510 | if (ObjectArg.isInvalid()) | |||
14511 | return ExprError(); | |||
14512 | MemExpr->setBase(ObjectArg.get()); | |||
14513 | } | |||
14514 | ||||
14515 | // Convert the rest of the arguments | |||
14516 | if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, | |||
14517 | RParenLoc)) | |||
14518 | return BuildRecoveryExpr(ResultType); | |||
14519 | ||||
14520 | DiagnoseSentinelCalls(Method, LParenLoc, Args); | |||
14521 | ||||
14522 | if (CheckFunctionCall(Method, TheCall, Proto)) | |||
14523 | return ExprError(); | |||
14524 | ||||
14525 | // In the case the method to call was not selected by the overloading | |||
14526 | // resolution process, we still need to handle the enable_if attribute. Do | |||
14527 | // that here, so it will not hide previous -- and more relevant -- errors. | |||
14528 | if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { | |||
14529 | if (const EnableIfAttr *Attr = | |||
14530 | CheckEnableIf(Method, LParenLoc, Args, true)) { | |||
14531 | Diag(MemE->getMemberLoc(), | |||
14532 | diag::err_ovl_no_viable_member_function_in_call) | |||
14533 | << Method << Method->getSourceRange(); | |||
14534 | Diag(Method->getLocation(), | |||
14535 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
14536 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
14537 | return ExprError(); | |||
14538 | } | |||
14539 | } | |||
14540 | ||||
14541 | if ((isa<CXXConstructorDecl>(CurContext) || | |||
14542 | isa<CXXDestructorDecl>(CurContext)) && | |||
14543 | TheCall->getMethodDecl()->isPure()) { | |||
14544 | const CXXMethodDecl *MD = TheCall->getMethodDecl(); | |||
14545 | ||||
14546 | if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && | |||
14547 | MemExpr->performsVirtualDispatch(getLangOpts())) { | |||
14548 | Diag(MemExpr->getBeginLoc(), | |||
14549 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) | |||
14550 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) | |||
14551 | << MD->getParent(); | |||
14552 | ||||
14553 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); | |||
14554 | if (getLangOpts().AppleKext) | |||
14555 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) | |||
14556 | << MD->getParent() << MD->getDeclName(); | |||
14557 | } | |||
14558 | } | |||
14559 | ||||
14560 | if (CXXDestructorDecl *DD = | |||
14561 | dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { | |||
14562 | // a->A::f() doesn't go through the vtable, except in AppleKext mode. | |||
14563 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; | |||
14564 | CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, | |||
14565 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, | |||
14566 | MemExpr->getMemberLoc()); | |||
14567 | } | |||
14568 | ||||
14569 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), | |||
14570 | TheCall->getMethodDecl()); | |||
14571 | } | |||
14572 | ||||
14573 | /// BuildCallToObjectOfClassType - Build a call to an object of class | |||
14574 | /// type (C++ [over.call.object]), which can end up invoking an | |||
14575 | /// overloaded function call operator (@c operator()) or performing a | |||
14576 | /// user-defined conversion on the object argument. | |||
14577 | ExprResult | |||
14578 | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, | |||
14579 | SourceLocation LParenLoc, | |||
14580 | MultiExprArg Args, | |||
14581 | SourceLocation RParenLoc) { | |||
14582 | if (checkPlaceholderForOverload(*this, Obj)) | |||
14583 | return ExprError(); | |||
14584 | ExprResult Object = Obj; | |||
14585 | ||||
14586 | UnbridgedCastsSet UnbridgedCasts; | |||
14587 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) | |||
14588 | return ExprError(); | |||
14589 | ||||
14590 | assert(Object.get()->getType()->isRecordType() &&(static_cast <bool> (Object.get()->getType()->isRecordType () && "Requires object type argument") ? void (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "clang/lib/Sema/SemaOverload.cpp", 14591, __extension__ __PRETTY_FUNCTION__ )) | |||
14591 | "Requires object type argument")(static_cast <bool> (Object.get()->getType()->isRecordType () && "Requires object type argument") ? void (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "clang/lib/Sema/SemaOverload.cpp", 14591, __extension__ __PRETTY_FUNCTION__ )); | |||
14592 | ||||
14593 | // C++ [over.call.object]p1: | |||
14594 | // If the primary-expression E in the function call syntax | |||
14595 | // evaluates to a class object of type "cv T", then the set of | |||
14596 | // candidate functions includes at least the function call | |||
14597 | // operators of T. The function call operators of T are obtained by | |||
14598 | // ordinary lookup of the name operator() in the context of | |||
14599 | // (E).operator(). | |||
14600 | OverloadCandidateSet CandidateSet(LParenLoc, | |||
14601 | OverloadCandidateSet::CSK_Operator); | |||
14602 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); | |||
14603 | ||||
14604 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), | |||
14605 | diag::err_incomplete_object_call, Object.get())) | |||
14606 | return true; | |||
14607 | ||||
14608 | const auto *Record = Object.get()->getType()->castAs<RecordType>(); | |||
14609 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); | |||
14610 | LookupQualifiedName(R, Record->getDecl()); | |||
14611 | R.suppressDiagnostics(); | |||
14612 | ||||
14613 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); | |||
14614 | Oper != OperEnd; ++Oper) { | |||
14615 | AddMethodCandidate(Oper.getPair(), Object.get()->getType(), | |||
14616 | Object.get()->Classify(Context), Args, CandidateSet, | |||
14617 | /*SuppressUserConversion=*/false); | |||
14618 | } | |||
14619 | ||||
14620 | // C++ [over.call.object]p2: | |||
14621 | // In addition, for each (non-explicit in C++0x) conversion function | |||
14622 | // declared in T of the form | |||
14623 | // | |||
14624 | // operator conversion-type-id () cv-qualifier; | |||
14625 | // | |||
14626 | // where cv-qualifier is the same cv-qualification as, or a | |||
14627 | // greater cv-qualification than, cv, and where conversion-type-id | |||
14628 | // denotes the type "pointer to function of (P1,...,Pn) returning | |||
14629 | // R", or the type "reference to pointer to function of | |||
14630 | // (P1,...,Pn) returning R", or the type "reference to function | |||
14631 | // of (P1,...,Pn) returning R", a surrogate call function [...] | |||
14632 | // is also considered as a candidate function. Similarly, | |||
14633 | // surrogate call functions are added to the set of candidate | |||
14634 | // functions for each conversion function declared in an | |||
14635 | // accessible base class provided the function is not hidden | |||
14636 | // within T by another intervening declaration. | |||
14637 | const auto &Conversions = | |||
14638 | cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); | |||
14639 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
14640 | NamedDecl *D = *I; | |||
14641 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
14642 | if (isa<UsingShadowDecl>(D)) | |||
14643 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
14644 | ||||
14645 | // Skip over templated conversion functions; they aren't | |||
14646 | // surrogates. | |||
14647 | if (isa<FunctionTemplateDecl>(D)) | |||
14648 | continue; | |||
14649 | ||||
14650 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); | |||
14651 | if (!Conv->isExplicit()) { | |||
14652 | // Strip the reference type (if any) and then the pointer type (if | |||
14653 | // any) to get down to what might be a function type. | |||
14654 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); | |||
14655 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
14656 | ConvType = ConvPtrType->getPointeeType(); | |||
14657 | ||||
14658 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) | |||
14659 | { | |||
14660 | AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, | |||
14661 | Object.get(), Args, CandidateSet); | |||
14662 | } | |||
14663 | } | |||
14664 | } | |||
14665 | ||||
14666 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
14667 | ||||
14668 | // Perform overload resolution. | |||
14669 | OverloadCandidateSet::iterator Best; | |||
14670 | switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), | |||
14671 | Best)) { | |||
14672 | case OR_Success: | |||
14673 | // Overload resolution succeeded; we'll build the appropriate call | |||
14674 | // below. | |||
14675 | break; | |||
14676 | ||||
14677 | case OR_No_Viable_Function: { | |||
14678 | PartialDiagnostic PD = | |||
14679 | CandidateSet.empty() | |||
14680 | ? (PDiag(diag::err_ovl_no_oper) | |||
14681 | << Object.get()->getType() << /*call*/ 1 | |||
14682 | << Object.get()->getSourceRange()) | |||
14683 | : (PDiag(diag::err_ovl_no_viable_object_call) | |||
14684 | << Object.get()->getType() << Object.get()->getSourceRange()); | |||
14685 | CandidateSet.NoteCandidates( | |||
14686 | PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, | |||
14687 | OCD_AllCandidates, Args); | |||
14688 | break; | |||
14689 | } | |||
14690 | case OR_Ambiguous: | |||
14691 | CandidateSet.NoteCandidates( | |||
14692 | PartialDiagnosticAt(Object.get()->getBeginLoc(), | |||
14693 | PDiag(diag::err_ovl_ambiguous_object_call) | |||
14694 | << Object.get()->getType() | |||
14695 | << Object.get()->getSourceRange()), | |||
14696 | *this, OCD_AmbiguousCandidates, Args); | |||
14697 | break; | |||
14698 | ||||
14699 | case OR_Deleted: | |||
14700 | CandidateSet.NoteCandidates( | |||
14701 | PartialDiagnosticAt(Object.get()->getBeginLoc(), | |||
14702 | PDiag(diag::err_ovl_deleted_object_call) | |||
14703 | << Object.get()->getType() | |||
14704 | << Object.get()->getSourceRange()), | |||
14705 | *this, OCD_AllCandidates, Args); | |||
14706 | break; | |||
14707 | } | |||
14708 | ||||
14709 | if (Best == CandidateSet.end()) | |||
14710 | return true; | |||
14711 | ||||
14712 | UnbridgedCasts.restore(); | |||
14713 | ||||
14714 | if (Best->Function == nullptr) { | |||
14715 | // Since there is no function declaration, this is one of the | |||
14716 | // surrogate candidates. Dig out the conversion function. | |||
14717 | CXXConversionDecl *Conv | |||
14718 | = cast<CXXConversionDecl>( | |||
14719 | Best->Conversions[0].UserDefined.ConversionFunction); | |||
14720 | ||||
14721 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, | |||
14722 | Best->FoundDecl); | |||
14723 | if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) | |||
14724 | return ExprError(); | |||
14725 | assert(Conv == Best->FoundDecl.getDecl() &&(static_cast <bool> (Conv == Best->FoundDecl.getDecl () && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "clang/lib/Sema/SemaOverload.cpp", 14726, __extension__ __PRETTY_FUNCTION__ )) | |||
14726 | "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast <bool> (Conv == Best->FoundDecl.getDecl () && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "clang/lib/Sema/SemaOverload.cpp", 14726, __extension__ __PRETTY_FUNCTION__ )); | |||
14727 | // We selected one of the surrogate functions that converts the | |||
14728 | // object parameter to a function pointer. Perform the conversion | |||
14729 | // on the object argument, then let BuildCallExpr finish the job. | |||
14730 | ||||
14731 | // Create an implicit member expr to refer to the conversion operator. | |||
14732 | // and then call it. | |||
14733 | ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, | |||
14734 | Conv, HadMultipleCandidates); | |||
14735 | if (Call.isInvalid()) | |||
14736 | return ExprError(); | |||
14737 | // Record usage of conversion in an implicit cast. | |||
14738 | Call = ImplicitCastExpr::Create( | |||
14739 | Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), | |||
14740 | nullptr, VK_PRValue, CurFPFeatureOverrides()); | |||
14741 | ||||
14742 | return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); | |||
14743 | } | |||
14744 | ||||
14745 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); | |||
14746 | ||||
14747 | // We found an overloaded operator(). Build a CXXOperatorCallExpr | |||
14748 | // that calls this method, using Object for the implicit object | |||
14749 | // parameter and passing along the remaining arguments. | |||
14750 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); | |||
14751 | ||||
14752 | // An error diagnostic has already been printed when parsing the declaration. | |||
14753 | if (Method->isInvalidDecl()) | |||
14754 | return ExprError(); | |||
14755 | ||||
14756 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); | |||
14757 | unsigned NumParams = Proto->getNumParams(); | |||
14758 | ||||
14759 | DeclarationNameInfo OpLocInfo( | |||
14760 | Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); | |||
14761 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); | |||
14762 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, | |||
14763 | Obj, HadMultipleCandidates, | |||
14764 | OpLocInfo.getLoc(), | |||
14765 | OpLocInfo.getInfo()); | |||
14766 | if (NewFn.isInvalid()) | |||
14767 | return true; | |||
14768 | ||||
14769 | SmallVector<Expr *, 8> MethodArgs; | |||
14770 | MethodArgs.reserve(NumParams + 1); | |||
14771 | ||||
14772 | bool IsError = false; | |||
14773 | ||||
14774 | // Initialize the implicit object parameter. | |||
14775 | ExprResult ObjRes = | |||
14776 | PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, | |||
14777 | Best->FoundDecl, Method); | |||
14778 | if (ObjRes.isInvalid()) | |||
14779 | IsError = true; | |||
14780 | else | |||
14781 | Object = ObjRes; | |||
14782 | MethodArgs.push_back(Object.get()); | |||
14783 | ||||
14784 | IsError |= PrepareArgumentsForCallToObjectOfClassType( | |||
14785 | *this, MethodArgs, Method, Args, LParenLoc); | |||
14786 | ||||
14787 | // If this is a variadic call, handle args passed through "...". | |||
14788 | if (Proto->isVariadic()) { | |||
14789 | // Promote the arguments (C99 6.5.2.2p7). | |||
14790 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { | |||
14791 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, | |||
14792 | nullptr); | |||
14793 | IsError |= Arg.isInvalid(); | |||
14794 | MethodArgs.push_back(Arg.get()); | |||
14795 | } | |||
14796 | } | |||
14797 | ||||
14798 | if (IsError) | |||
14799 | return true; | |||
14800 | ||||
14801 | DiagnoseSentinelCalls(Method, LParenLoc, Args); | |||
14802 | ||||
14803 | // Once we've built TheCall, all of the expressions are properly owned. | |||
14804 | QualType ResultTy = Method->getReturnType(); | |||
14805 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
14806 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
14807 | ||||
14808 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
14809 | Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, | |||
14810 | CurFPFeatureOverrides()); | |||
14811 | ||||
14812 | if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) | |||
14813 | return true; | |||
14814 | ||||
14815 | if (CheckFunctionCall(Method, TheCall, Proto)) | |||
14816 | return true; | |||
14817 | ||||
14818 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); | |||
14819 | } | |||
14820 | ||||
14821 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> | |||
14822 | /// (if one exists), where @c Base is an expression of class type and | |||
14823 | /// @c Member is the name of the member we're trying to find. | |||
14824 | ExprResult | |||
14825 | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, | |||
14826 | bool *NoArrowOperatorFound) { | |||
14827 | assert(Base->getType()->isRecordType() &&(static_cast <bool> (Base->getType()->isRecordType () && "left-hand side must have class type") ? void ( 0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "clang/lib/Sema/SemaOverload.cpp", 14828, __extension__ __PRETTY_FUNCTION__ )) | |||
14828 | "left-hand side must have class type")(static_cast <bool> (Base->getType()->isRecordType () && "left-hand side must have class type") ? void ( 0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "clang/lib/Sema/SemaOverload.cpp", 14828, __extension__ __PRETTY_FUNCTION__ )); | |||
14829 | ||||
14830 | if (checkPlaceholderForOverload(*this, Base)) | |||
14831 | return ExprError(); | |||
14832 | ||||
14833 | SourceLocation Loc = Base->getExprLoc(); | |||
14834 | ||||
14835 | // C++ [over.ref]p1: | |||
14836 | // | |||
14837 | // [...] An expression x->m is interpreted as (x.operator->())->m | |||
14838 | // for a class object x of type T if T::operator->() exists and if | |||
14839 | // the operator is selected as the best match function by the | |||
14840 | // overload resolution mechanism (13.3). | |||
14841 | DeclarationName OpName = | |||
14842 | Context.DeclarationNames.getCXXOperatorName(OO_Arrow); | |||
14843 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); | |||
14844 | ||||
14845 | if (RequireCompleteType(Loc, Base->getType(), | |||
14846 | diag::err_typecheck_incomplete_tag, Base)) | |||
14847 | return ExprError(); | |||
14848 | ||||
14849 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); | |||
14850 | LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); | |||
14851 | R.suppressDiagnostics(); | |||
14852 | ||||
14853 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); | |||
14854 | Oper != OperEnd; ++Oper) { | |||
14855 | AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), | |||
14856 | None, CandidateSet, /*SuppressUserConversion=*/false); | |||
14857 | } | |||
14858 | ||||
14859 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
14860 | ||||
14861 | // Perform overload resolution. | |||
14862 | OverloadCandidateSet::iterator Best; | |||
14863 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
14864 | case OR_Success: | |||
14865 | // Overload resolution succeeded; we'll build the call below. | |||
14866 | break; | |||
14867 | ||||
14868 | case OR_No_Viable_Function: { | |||
14869 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); | |||
14870 | if (CandidateSet.empty()) { | |||
14871 | QualType BaseType = Base->getType(); | |||
14872 | if (NoArrowOperatorFound) { | |||
14873 | // Report this specific error to the caller instead of emitting a | |||
14874 | // diagnostic, as requested. | |||
14875 | *NoArrowOperatorFound = true; | |||
14876 | return ExprError(); | |||
14877 | } | |||
14878 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) | |||
14879 | << BaseType << Base->getSourceRange(); | |||
14880 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { | |||
14881 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) | |||
14882 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
14883 | } | |||
14884 | } else | |||
14885 | Diag(OpLoc, diag::err_ovl_no_viable_oper) | |||
14886 | << "operator->" << Base->getSourceRange(); | |||
14887 | CandidateSet.NoteCandidates(*this, Base, Cands); | |||
14888 | return ExprError(); | |||
14889 | } | |||
14890 | case OR_Ambiguous: | |||
14891 | CandidateSet.NoteCandidates( | |||
14892 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) | |||
14893 | << "->" << Base->getType() | |||
14894 | << Base->getSourceRange()), | |||
14895 | *this, OCD_AmbiguousCandidates, Base); | |||
14896 | return ExprError(); | |||
14897 | ||||
14898 | case OR_Deleted: | |||
14899 | CandidateSet.NoteCandidates( | |||
14900 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
14901 | << "->" << Base->getSourceRange()), | |||
14902 | *this, OCD_AllCandidates, Base); | |||
14903 | return ExprError(); | |||
14904 | } | |||
14905 | ||||
14906 | CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); | |||
14907 | ||||
14908 | // Convert the object parameter. | |||
14909 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); | |||
14910 | ExprResult BaseResult = | |||
14911 | PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, | |||
14912 | Best->FoundDecl, Method); | |||
14913 | if (BaseResult.isInvalid()) | |||
14914 | return ExprError(); | |||
14915 | Base = BaseResult.get(); | |||
14916 | ||||
14917 | // Build the operator call. | |||
14918 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, | |||
14919 | Base, HadMultipleCandidates, OpLoc); | |||
14920 | if (FnExpr.isInvalid()) | |||
14921 | return ExprError(); | |||
14922 | ||||
14923 | QualType ResultTy = Method->getReturnType(); | |||
14924 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
14925 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
14926 | CXXOperatorCallExpr *TheCall = | |||
14927 | CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, | |||
14928 | ResultTy, VK, OpLoc, CurFPFeatureOverrides()); | |||
14929 | ||||
14930 | if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) | |||
14931 | return ExprError(); | |||
14932 | ||||
14933 | if (CheckFunctionCall(Method, TheCall, | |||
14934 | Method->getType()->castAs<FunctionProtoType>())) | |||
14935 | return ExprError(); | |||
14936 | ||||
14937 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); | |||
14938 | } | |||
14939 | ||||
14940 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to | |||
14941 | /// a literal operator described by the provided lookup results. | |||
14942 | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, | |||
14943 | DeclarationNameInfo &SuffixInfo, | |||
14944 | ArrayRef<Expr*> Args, | |||
14945 | SourceLocation LitEndLoc, | |||
14946 | TemplateArgumentListInfo *TemplateArgs) { | |||
14947 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); | |||
14948 | ||||
14949 | OverloadCandidateSet CandidateSet(UDSuffixLoc, | |||
14950 | OverloadCandidateSet::CSK_Normal); | |||
14951 | AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, | |||
14952 | TemplateArgs); | |||
14953 | ||||
14954 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
14955 | ||||
14956 | // Perform overload resolution. This will usually be trivial, but might need | |||
14957 | // to perform substitutions for a literal operator template. | |||
14958 | OverloadCandidateSet::iterator Best; | |||
14959 | switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { | |||
14960 | case OR_Success: | |||
14961 | case OR_Deleted: | |||
14962 | break; | |||
14963 | ||||
14964 | case OR_No_Viable_Function: | |||
14965 | CandidateSet.NoteCandidates( | |||
14966 | PartialDiagnosticAt(UDSuffixLoc, | |||
14967 | PDiag(diag::err_ovl_no_viable_function_in_call) | |||
14968 | << R.getLookupName()), | |||
14969 | *this, OCD_AllCandidates, Args); | |||
14970 | return ExprError(); | |||
14971 | ||||
14972 | case OR_Ambiguous: | |||
14973 | CandidateSet.NoteCandidates( | |||
14974 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) | |||
14975 | << R.getLookupName()), | |||
14976 | *this, OCD_AmbiguousCandidates, Args); | |||
14977 | return ExprError(); | |||
14978 | } | |||
14979 | ||||
14980 | FunctionDecl *FD = Best->Function; | |||
14981 | ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, | |||
14982 | nullptr, HadMultipleCandidates, | |||
14983 | SuffixInfo.getLoc(), | |||
14984 | SuffixInfo.getInfo()); | |||
14985 | if (Fn.isInvalid()) | |||
14986 | return true; | |||
14987 | ||||
14988 | // Check the argument types. This should almost always be a no-op, except | |||
14989 | // that array-to-pointer decay is applied to string literals. | |||
14990 | Expr *ConvArgs[2]; | |||
14991 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
14992 | ExprResult InputInit = PerformCopyInitialization( | |||
14993 | InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), | |||
14994 | SourceLocation(), Args[ArgIdx]); | |||
14995 | if (InputInit.isInvalid()) | |||
14996 | return true; | |||
14997 | ConvArgs[ArgIdx] = InputInit.get(); | |||
14998 | } | |||
14999 | ||||
15000 | QualType ResultTy = FD->getReturnType(); | |||
15001 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
15002 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
15003 | ||||
15004 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( | |||
15005 | Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, | |||
15006 | VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); | |||
15007 | ||||
15008 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) | |||
15009 | return ExprError(); | |||
15010 | ||||
15011 | if (CheckFunctionCall(FD, UDL, nullptr)) | |||
15012 | return ExprError(); | |||
15013 | ||||
15014 | return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); | |||
15015 | } | |||
15016 | ||||
15017 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the | |||
15018 | /// given LookupResult is non-empty, it is assumed to describe a member which | |||
15019 | /// will be invoked. Otherwise, the function will be found via argument | |||
15020 | /// dependent lookup. | |||
15021 | /// CallExpr is set to a valid expression and FRS_Success returned on success, | |||
15022 | /// otherwise CallExpr is set to ExprError() and some non-success value | |||
15023 | /// is returned. | |||
15024 | Sema::ForRangeStatus | |||
15025 | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, | |||
15026 | SourceLocation RangeLoc, | |||
15027 | const DeclarationNameInfo &NameInfo, | |||
15028 | LookupResult &MemberLookup, | |||
15029 | OverloadCandidateSet *CandidateSet, | |||
15030 | Expr *Range, ExprResult *CallExpr) { | |||
15031 | Scope *S = nullptr; | |||
15032 | ||||
15033 | CandidateSet->clear(OverloadCandidateSet::CSK_Normal); | |||
15034 | if (!MemberLookup.empty()) { | |||
15035 | ExprResult MemberRef = | |||
15036 | BuildMemberReferenceExpr(Range, Range->getType(), Loc, | |||
15037 | /*IsPtr=*/false, CXXScopeSpec(), | |||
15038 | /*TemplateKWLoc=*/SourceLocation(), | |||
15039 | /*FirstQualifierInScope=*/nullptr, | |||
15040 | MemberLookup, | |||
15041 | /*TemplateArgs=*/nullptr, S); | |||
15042 | if (MemberRef.isInvalid()) { | |||
15043 | *CallExpr = ExprError(); | |||
15044 | return FRS_DiagnosticIssued; | |||
15045 | } | |||
15046 | *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); | |||
15047 | if (CallExpr->isInvalid()) { | |||
15048 | *CallExpr = ExprError(); | |||
15049 | return FRS_DiagnosticIssued; | |||
15050 | } | |||
15051 | } else { | |||
15052 | ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, | |||
15053 | NestedNameSpecifierLoc(), | |||
15054 | NameInfo, UnresolvedSet<0>()); | |||
15055 | if (FnR.isInvalid()) | |||
15056 | return FRS_DiagnosticIssued; | |||
15057 | UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); | |||
15058 | ||||
15059 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, | |||
15060 | CandidateSet, CallExpr); | |||
15061 | if (CandidateSet->empty() || CandidateSetError) { | |||
15062 | *CallExpr = ExprError(); | |||
15063 | return FRS_NoViableFunction; | |||
15064 | } | |||
15065 | OverloadCandidateSet::iterator Best; | |||
15066 | OverloadingResult OverloadResult = | |||
15067 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); | |||
15068 | ||||
15069 | if (OverloadResult == OR_No_Viable_Function) { | |||
15070 | *CallExpr = ExprError(); | |||
15071 | return FRS_NoViableFunction; | |||
15072 | } | |||
15073 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, | |||
15074 | Loc, nullptr, CandidateSet, &Best, | |||
15075 | OverloadResult, | |||
15076 | /*AllowTypoCorrection=*/false); | |||
15077 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { | |||
15078 | *CallExpr = ExprError(); | |||
15079 | return FRS_DiagnosticIssued; | |||
15080 | } | |||
15081 | } | |||
15082 | return FRS_Success; | |||
15083 | } | |||
15084 | ||||
15085 | ||||
15086 | /// FixOverloadedFunctionReference - E is an expression that refers to | |||
15087 | /// a C++ overloaded function (possibly with some parentheses and | |||
15088 | /// perhaps a '&' around it). We have resolved the overloaded function | |||
15089 | /// to the function declaration Fn, so patch up the expression E to | |||
15090 | /// refer (possibly indirectly) to Fn. Returns the new expr. | |||
15091 | Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, | |||
15092 | FunctionDecl *Fn) { | |||
15093 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
15094 | Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), | |||
15095 | Found, Fn); | |||
15096 | if (SubExpr == PE->getSubExpr()) | |||
15097 | return PE; | |||
15098 | ||||
15099 | return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); | |||
15100 | } | |||
15101 | ||||
15102 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
15103 | Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), | |||
15104 | Found, Fn); | |||
15105 | assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15107, __extension__ __PRETTY_FUNCTION__ )) | |||
15106 | SubExpr->getType()) &&(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15107, __extension__ __PRETTY_FUNCTION__ )) | |||
15107 | "Implicit cast type cannot be determined from overload")(static_cast <bool> (Context.hasSameType(ICE->getSubExpr ()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload" ) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "clang/lib/Sema/SemaOverload.cpp", 15107, __extension__ __PRETTY_FUNCTION__ )); | |||
15108 | assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast <bool> (ICE->path_empty() && "fixing up hierarchy conversion?" ) ? void (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\"" , "clang/lib/Sema/SemaOverload.cpp", 15108, __extension__ __PRETTY_FUNCTION__ )); | |||
15109 | if (SubExpr == ICE->getSubExpr()) | |||
15110 | return ICE; | |||
15111 | ||||
15112 | return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), | |||
15113 | SubExpr, nullptr, ICE->getValueKind(), | |||
15114 | CurFPFeatureOverrides()); | |||
15115 | } | |||
15116 | ||||
15117 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
15118 | if (!GSE->isResultDependent()) { | |||
15119 | Expr *SubExpr = | |||
15120 | FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); | |||
15121 | if (SubExpr == GSE->getResultExpr()) | |||
15122 | return GSE; | |||
15123 | ||||
15124 | // Replace the resulting type information before rebuilding the generic | |||
15125 | // selection expression. | |||
15126 | ArrayRef<Expr *> A = GSE->getAssocExprs(); | |||
15127 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); | |||
15128 | unsigned ResultIdx = GSE->getResultIndex(); | |||
15129 | AssocExprs[ResultIdx] = SubExpr; | |||
15130 | ||||
15131 | return GenericSelectionExpr::Create( | |||
15132 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), | |||
15133 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), | |||
15134 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), | |||
15135 | ResultIdx); | |||
15136 | } | |||
15137 | // Rather than fall through to the unreachable, return the original generic | |||
15138 | // selection expression. | |||
15139 | return GSE; | |||
15140 | } | |||
15141 | ||||
15142 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { | |||
15143 | assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function") ? void (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "clang/lib/Sema/SemaOverload.cpp", 15144, __extension__ __PRETTY_FUNCTION__ )) | |||
15144 | "Can only take the address of an overloaded function")(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function") ? void (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "clang/lib/Sema/SemaOverload.cpp", 15144, __extension__ __PRETTY_FUNCTION__ )); | |||
15145 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { | |||
15146 | if (Method->isStatic()) { | |||
15147 | // Do nothing: static member functions aren't any different | |||
15148 | // from non-member functions. | |||
15149 | } else { | |||
15150 | // Fix the subexpression, which really has to be an | |||
15151 | // UnresolvedLookupExpr holding an overloaded member function | |||
15152 | // or template. | |||
15153 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), | |||
15154 | Found, Fn); | |||
15155 | if (SubExpr == UnOp->getSubExpr()) | |||
15156 | return UnOp; | |||
15157 | ||||
15158 | assert(isa<DeclRefExpr>(SubExpr)(static_cast <bool> (isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref") ? void (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "clang/lib/Sema/SemaOverload.cpp", 15159, __extension__ __PRETTY_FUNCTION__ )) | |||
15159 | && "fixed to something other than a decl ref")(static_cast <bool> (isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref") ? void (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "clang/lib/Sema/SemaOverload.cpp", 15159, __extension__ __PRETTY_FUNCTION__ )); | |||
15160 | assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast <bool> (cast<DeclRefExpr>(SubExpr)-> getQualifier() && "fixed to a member ref with no nested name qualifier" ) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "clang/lib/Sema/SemaOverload.cpp", 15161, __extension__ __PRETTY_FUNCTION__ )) | |||
15161 | && "fixed to a member ref with no nested name qualifier")(static_cast <bool> (cast<DeclRefExpr>(SubExpr)-> getQualifier() && "fixed to a member ref with no nested name qualifier" ) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "clang/lib/Sema/SemaOverload.cpp", 15161, __extension__ __PRETTY_FUNCTION__ )); | |||
15162 | ||||
15163 | // We have taken the address of a pointer to member | |||
15164 | // function. Perform the computation here so that we get the | |||
15165 | // appropriate pointer to member type. | |||
15166 | QualType ClassType | |||
15167 | = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); | |||
15168 | QualType MemPtrType | |||
15169 | = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); | |||
15170 | // Under the MS ABI, lock down the inheritance model now. | |||
15171 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
15172 | (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); | |||
15173 | ||||
15174 | return UnaryOperator::Create( | |||
15175 | Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, | |||
15176 | UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); | |||
15177 | } | |||
15178 | } | |||
15179 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), | |||
15180 | Found, Fn); | |||
15181 | if (SubExpr == UnOp->getSubExpr()) | |||
15182 | return UnOp; | |||
15183 | ||||
15184 | // FIXME: This can't currently fail, but in principle it could. | |||
15185 | return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr) | |||
15186 | .get(); | |||
15187 | } | |||
15188 | ||||
15189 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | |||
15190 | // FIXME: avoid copy. | |||
15191 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
15192 | if (ULE->hasExplicitTemplateArgs()) { | |||
15193 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
15194 | TemplateArgs = &TemplateArgsBuffer; | |||
15195 | } | |||
15196 | ||||
15197 | QualType Type = Fn->getType(); | |||
15198 | ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; | |||
15199 | ||||
15200 | // FIXME: Duplicated from BuildDeclarationNameExpr. | |||
15201 | if (unsigned BID = Fn->getBuiltinID()) { | |||
15202 | if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { | |||
15203 | Type = Context.BuiltinFnTy; | |||
15204 | ValueKind = VK_PRValue; | |||
15205 | } | |||
15206 | } | |||
15207 | ||||
15208 | DeclRefExpr *DRE = BuildDeclRefExpr( | |||
15209 | Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), | |||
15210 | Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); | |||
15211 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); | |||
15212 | return DRE; | |||
15213 | } | |||
15214 | ||||
15215 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { | |||
15216 | // FIXME: avoid copy. | |||
15217 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
15218 | if (MemExpr->hasExplicitTemplateArgs()) { | |||
15219 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
15220 | TemplateArgs = &TemplateArgsBuffer; | |||
15221 | } | |||
15222 | ||||
15223 | Expr *Base; | |||
15224 | ||||
15225 | // If we're filling in a static method where we used to have an | |||
15226 | // implicit member access, rewrite to a simple decl ref. | |||
15227 | if (MemExpr->isImplicitAccess()) { | |||
15228 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { | |||
15229 | DeclRefExpr *DRE = BuildDeclRefExpr( | |||
15230 | Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), | |||
15231 | MemExpr->getQualifierLoc(), Found.getDecl(), | |||
15232 | MemExpr->getTemplateKeywordLoc(), TemplateArgs); | |||
15233 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); | |||
15234 | return DRE; | |||
15235 | } else { | |||
15236 | SourceLocation Loc = MemExpr->getMemberLoc(); | |||
15237 | if (MemExpr->getQualifier()) | |||
15238 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); | |||
15239 | Base = | |||
15240 | BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); | |||
15241 | } | |||
15242 | } else | |||
15243 | Base = MemExpr->getBase(); | |||
15244 | ||||
15245 | ExprValueKind valueKind; | |||
15246 | QualType type; | |||
15247 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { | |||
15248 | valueKind = VK_LValue; | |||
15249 | type = Fn->getType(); | |||
15250 | } else { | |||
15251 | valueKind = VK_PRValue; | |||
15252 | type = Context.BoundMemberTy; | |||
15253 | } | |||
15254 | ||||
15255 | return BuildMemberExpr( | |||
15256 | Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), | |||
15257 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, | |||
15258 | /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), | |||
15259 | type, valueKind, OK_Ordinary, TemplateArgs); | |||
15260 | } | |||
15261 | ||||
15262 | llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function" , "clang/lib/Sema/SemaOverload.cpp", 15262); | |||
15263 | } | |||
15264 | ||||
15265 | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, | |||
15266 | DeclAccessPair Found, | |||
15267 | FunctionDecl *Fn) { | |||
15268 | return FixOverloadedFunctionReference(E.get(), Found, Fn); | |||
15269 | } | |||
15270 | ||||
15271 | bool clang::shouldEnforceArgLimit(bool PartialOverloading, | |||
15272 | FunctionDecl *Function) { | |||
15273 | if (!PartialOverloading || !Function) | |||
15274 | return true; | |||
15275 | if (Function->isVariadic()) | |||
15276 | return false; | |||
15277 | if (const auto *Proto = | |||
15278 | dyn_cast<FunctionProtoType>(Function->getFunctionType())) | |||
15279 | if (Proto->isTemplateVariadic()) | |||
15280 | return false; | |||
15281 | if (auto *Pattern = Function->getTemplateInstantiationPattern()) | |||
15282 | if (const auto *Proto = | |||
15283 | dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) | |||
15284 | if (Proto->isTemplateVariadic()) | |||
15285 | return false; | |||
15286 | return true; | |||
15287 | } |