Bug Summary

File:clang/lib/Sema/SemaOverload.cpp
Warning:line 10535, column 50
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp

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
40using namespace clang;
41using namespace sema;
42
43using AllowedExplicit = Sema::AllowedExplicit;
44
45static 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.
52static ExprResult
53CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54 const Expr *Base, bool HadMultipleCandidates,
55 SourceLocation Loc = SourceLocation(),
56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58 return ExprError();
59 // If FoundDecl is different from Fn (such as if one is a template
60 // and the other a specialization), make sure DiagnoseUseOfDecl is
61 // called on both.
62 // FIXME: This would be more comprehensively addressed by modifying
63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64 // being used.
65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66 return ExprError();
67 DeclRefExpr *DRE = new (S.Context)
68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69 if (HadMultipleCandidates)
70 DRE->setHadMultipleCandidates(true);
71
72 S.MarkDeclRefReferenced(DRE, Base);
73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75 S.ResolveExceptionSpec(Loc, FPT);
76 DRE->setType(Fn->getType());
77 }
78 }
79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80 CK_FunctionToPointerDecay);
81}
82
83static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle,
87 bool AllowObjCWritebackConversion);
88
89static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90 QualType &ToType,
91 bool InOverloadResolution,
92 StandardConversionSequence &SCS,
93 bool CStyle);
94static OverloadingResult
95IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96 UserDefinedConversionSequence& User,
97 OverloadCandidateSet& Conversions,
98 AllowedExplicit AllowExplicit,
99 bool AllowObjCConversionOnExplicit);
100
101static ImplicitConversionSequence::CompareKind
102CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
106static ImplicitConversionSequence::CompareKind
107CompareQualificationConversions(Sema &S,
108 const StandardConversionSequence& SCS1,
109 const StandardConversionSequence& SCS2);
110
111static ImplicitConversionSequence::CompareKind
112CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
116/// GetConversionRank - Retrieve the implicit conversion rank
117/// corresponding to the given implicit conversion kind.
118ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119 static const ImplicitConversionRank
120 Rank[(int)ICK_Num_Conversion_Kinds] = {
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Promotion,
128 ICR_Promotion,
129 ICR_Promotion,
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_Conversion,
141 ICR_OCL_Scalar_Widening,
142 ICR_Complex_Real_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Writeback_Conversion,
146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147 // it was omitted by the patch that added
148 // ICK_Zero_Event_Conversion
149 ICR_C_Conversion,
150 ICR_C_Conversion_Extension
151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
163 "Function pointer conversion",
164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
167 "Complex promotion",
168 "Integral conversion",
169 "Floating conversion",
170 "Complex conversion",
171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
174 "Boolean conversion",
175 "Compatible-types conversion",
176 "Derived-to-base conversion",
177 "Vector conversion",
178 "SVE Vector conversion",
179 "Vector splat",
180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion",
183 "Writeback conversion",
184 "OpenCL Zero Event Conversion",
185 "C specific type conversion",
186 "Incompatible pointer conversion"
187 };
188 return Name[Kind];
189}
190
191/// StandardConversionSequence - Set the standard conversion
192/// sequence to the identity conversion.
193void StandardConversionSequence::setAsIdentityConversion() {
194 First = ICK_Identity;
195 Second = ICK_Identity;
196 Third = ICK_Identity;
197 DeprecatedStringLiteralToCharPtr = false;
198 QualificationIncludesObjCLifetime = false;
199 ReferenceBinding = false;
200 DirectBinding = false;
201 IsLvalueReference = true;
202 BindsToFunctionLvalue = false;
203 BindsToRvalue = false;
204 BindsImplicitObjectArgumentWithoutRefQualifier = false;
205 ObjCLifetimeConversionBinding = false;
206 CopyConstructor = nullptr;
207}
208
209/// getRank - Retrieve the rank of this standard conversion sequence
210/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211/// implicit conversions.
212ImplicitConversionRank StandardConversionSequence::getRank() const {
213 ImplicitConversionRank Rank = ICR_Exact_Match;
214 if (GetConversionRank(First) > Rank)
215 Rank = GetConversionRank(First);
216 if (GetConversionRank(Second) > Rank)
217 Rank = GetConversionRank(Second);
218 if (GetConversionRank(Third) > Rank)
219 Rank = GetConversionRank(Third);
220 return Rank;
221}
222
223/// isPointerConversionToBool - Determines whether this conversion is
224/// a conversion of a pointer or pointer-to-member to bool. This is
225/// used as part of the ranking of standard conversion sequences
226/// (C++ 13.3.3.2p4).
227bool StandardConversionSequence::isPointerConversionToBool() const {
228 // Note that FromType has not necessarily been transformed by the
229 // array-to-pointer or function-to-pointer implicit conversions, so
230 // check for their presence as well as checking whether FromType is
231 // a pointer.
232 if (getToType(1)->isBooleanType() &&
233 (getFromType()->isPointerType() ||
234 getFromType()->isMemberPointerType() ||
235 getFromType()->isObjCObjectPointerType() ||
236 getFromType()->isBlockPointerType() ||
237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238 return true;
239
240 return false;
241}
242
243/// isPointerConversionToVoidPointer - Determines whether this
244/// conversion is a conversion of a pointer to a void pointer. This is
245/// used as part of the ranking of standard conversion sequences (C++
246/// 13.3.3.2p4).
247bool
248StandardConversionSequence::
249isPointerConversionToVoidPointer(ASTContext& Context) const {
250 QualType FromType = getFromType();
251 QualType ToType = getToType(1);
252
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer implicit conversion, so check for its presence
255 // and redo the conversion to get a pointer.
256 if (First == ICK_Array_To_Pointer)
257 FromType = Context.getArrayDecayedType(FromType);
258
259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261 return ToPtrType->getPointeeType()->isVoidType();
262
263 return false;
264}
265
266/// Skip any implicit casts which could be either part of a narrowing conversion
267/// or after one in an implicit conversion.
268static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269 const Expr *Converted) {
270 // We can have cleanups wrapping the converted expression; these need to be
271 // preserved so that destructors run if necessary.
272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273 Expr *Inner =
274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276 EWC->getObjects());
277 }
278
279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_BooleanToSignedIntegral:
286 case CK_FloatingToIntegral:
287 case CK_FloatingToBoolean:
288 case CK_FloatingCast:
289 Converted = ICE->getSubExpr();
290 continue;
291
292 default:
293 return Converted;
294 }
295 }
296
297 return Converted;
298}
299
300/// Check if this standard conversion sequence represents a narrowing
301/// conversion, according to C++11 [dcl.init.list]p7.
302///
303/// \param Ctx The AST context.
304/// \param Converted The result of applying this standard conversion sequence.
305/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
306/// value of the expression prior to the narrowing conversion.
307/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
308/// type of the expression prior to the narrowing conversion.
309/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310/// from floating point types to integral types should be ignored.
311NarrowingKind StandardConversionSequence::getNarrowingKind(
312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 314, __PRETTY_FUNCTION__))
;
315
316 // C++11 [dcl.init.list]p7:
317 // A narrowing conversion is an implicit conversion ...
318 QualType FromType = getToType(0);
319 QualType ToType = getToType(1);
320
321 // A conversion to an enumeration type is narrowing if the conversion to
322 // the underlying type is narrowing. This only arises for expressions of
323 // the form 'Enum{init}'.
324 if (auto *ET = ToType->getAs<EnumType>())
325 ToType = ET->getDecl()->getIntegerType();
326
327 switch (Second) {
328 // 'bool' is an integral type; dispatch to the right place to handle it.
329 case ICK_Boolean_Conversion:
330 if (FromType->isRealFloatingType())
331 goto FloatingIntegralConversion;
332 if (FromType->isIntegralOrUnscopedEnumerationType())
333 goto IntegralConversion;
334 // -- from a pointer type or pointer-to-member type to bool, or
335 return NK_Type_Narrowing;
336
337 // -- from a floating-point type to an integer type, or
338 //
339 // -- from an integer type or unscoped enumeration type to a floating-point
340 // type, except where the source is a constant expression and the actual
341 // value after conversion will fit into the target type and will produce
342 // the original value when converted back to the original type, or
343 case ICK_Floating_Integral:
344 FloatingIntegralConversion:
345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346 return NK_Type_Narrowing;
347 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348 ToType->isRealFloatingType()) {
349 if (IgnoreFloatToIntegralConversion)
350 return NK_Not_Narrowing;
351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 352, __PRETTY_FUNCTION__))
;
353
354 // If it's value-dependent, we can't tell whether it's narrowing.
355 if (Initializer->isValueDependent())
356 return NK_Dependent_Narrowing;
357
358 if (Optional<llvm::APSInt> IntConstantValue =
359 Initializer->getIntegerConstantExpr(Ctx)) {
360 // Convert the integer to the floating type.
361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363 llvm::APFloat::rmNearestTiesToEven);
364 // And back.
365 llvm::APSInt ConvertedValue = *IntConstantValue;
366 bool ignored;
367 Result.convertToInteger(ConvertedValue,
368 llvm::APFloat::rmTowardZero, &ignored);
369 // If the resulting value is different, this was a narrowing conversion.
370 if (*IntConstantValue != ConvertedValue) {
371 ConstantValue = APValue(*IntConstantValue);
372 ConstantType = Initializer->getType();
373 return NK_Constant_Narrowing;
374 }
375 } else {
376 // Variables are always narrowings.
377 return NK_Variable_Narrowing;
378 }
379 }
380 return NK_Not_Narrowing;
381
382 // -- from long double to double or float, or from double to float, except
383 // where the source is a constant expression and the actual value after
384 // conversion is within the range of values that can be represented (even
385 // if it cannot be represented exactly), or
386 case ICK_Floating_Conversion:
387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389 // FromType is larger than ToType.
390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391
392 // If it's value-dependent, we can't tell whether it's narrowing.
393 if (Initializer->isValueDependent())
394 return NK_Dependent_Narrowing;
395
396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397 // Constant!
398 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 398, __PRETTY_FUNCTION__))
;
399 llvm::APFloat FloatVal = ConstantValue.getFloat();
400 // Convert the source value into the target type.
401 bool ignored;
402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403 Ctx.getFloatTypeSemantics(ToType),
404 llvm::APFloat::rmNearestTiesToEven, &ignored);
405 // If there was no overflow, the source value is within the range of
406 // values that can be represented.
407 if (ConvertStatus & llvm::APFloat::opOverflow) {
408 ConstantType = Initializer->getType();
409 return NK_Constant_Narrowing;
410 }
411 } else {
412 return NK_Variable_Narrowing;
413 }
414 }
415 return NK_Not_Narrowing;
416
417 // -- from an integer type or unscoped enumeration type to an integer type
418 // that cannot represent all the values of the original type, except where
419 // the source is a constant expression and the actual value after
420 // conversion will fit into the target type and will produce the original
421 // value when converted back to the original type.
422 case ICK_Integral_Conversion:
423 IntegralConversion: {
424 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 424, __PRETTY_FUNCTION__))
;
425 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 425, __PRETTY_FUNCTION__))
;
426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427 const unsigned FromWidth = Ctx.getIntWidth(FromType);
428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429 const unsigned ToWidth = Ctx.getIntWidth(ToType);
430
431 if (FromWidth > ToWidth ||
432 (FromWidth == ToWidth && FromSigned != ToSigned) ||
433 (FromSigned && !ToSigned)) {
434 // Not all values of FromType can be represented in ToType.
435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436
437 // If it's value-dependent, we can't tell whether it's narrowing.
438 if (Initializer->isValueDependent())
439 return NK_Dependent_Narrowing;
440
441 Optional<llvm::APSInt> OptInitializerValue;
442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443 // Such conversions on variables are always narrowing.
444 return NK_Variable_Narrowing;
445 }
446 llvm::APSInt &InitializerValue = *OptInitializerValue;
447 bool Narrowing = false;
448 if (FromWidth < ToWidth) {
449 // Negative -> unsigned is narrowing. Otherwise, more bits is never
450 // narrowing.
451 if (InitializerValue.isSigned() && InitializerValue.isNegative())
452 Narrowing = true;
453 } else {
454 // Add a bit to the InitializerValue so we don't have to worry about
455 // signed vs. unsigned comparisons.
456 InitializerValue = InitializerValue.extend(
457 InitializerValue.getBitWidth() + 1);
458 // Convert the initializer to and from the target width and signed-ness.
459 llvm::APSInt ConvertedValue = InitializerValue;
460 ConvertedValue = ConvertedValue.trunc(ToWidth);
461 ConvertedValue.setIsSigned(ToSigned);
462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463 ConvertedValue.setIsSigned(InitializerValue.isSigned());
464 // If the result is different, this was a narrowing conversion.
465 if (ConvertedValue != InitializerValue)
466 Narrowing = true;
467 }
468 if (Narrowing) {
469 ConstantType = Initializer->getType();
470 ConstantValue = APValue(InitializerValue);
471 return NK_Constant_Narrowing;
472 }
473 }
474 return NK_Not_Narrowing;
475 }
476
477 default:
478 // Other kinds of conversions are not narrowings.
479 return NK_Not_Narrowing;
480 }
481}
482
483/// dump - Print this standard conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 bool PrintedSomething = false;
488 if (First != ICK_Identity) {
489 OS << GetImplicitConversionName(First);
490 PrintedSomething = true;
491 }
492
493 if (Second != ICK_Identity) {
494 if (PrintedSomething) {
495 OS << " -> ";
496 }
497 OS << GetImplicitConversionName(Second);
498
499 if (CopyConstructor) {
500 OS << " (by copy constructor)";
501 } else if (DirectBinding) {
502 OS << " (direct reference binding)";
503 } else if (ReferenceBinding) {
504 OS << " (reference binding)";
505 }
506 PrintedSomething = true;
507 }
508
509 if (Third != ICK_Identity) {
510 if (PrintedSomething) {
511 OS << " -> ";
512 }
513 OS << GetImplicitConversionName(Third);
514 PrintedSomething = true;
515 }
516
517 if (!PrintedSomething) {
518 OS << "No conversions required";
519 }
520}
521
522/// dump - Print this user-defined conversion sequence to standard
523/// error. Useful for debugging overloading issues.
524void UserDefinedConversionSequence::dump() const {
525 raw_ostream &OS = llvm::errs();
526 if (Before.First || Before.Second || Before.Third) {
527 Before.dump();
528 OS << " -> ";
529 }
530 if (ConversionFunction)
531 OS << '\'' << *ConversionFunction << '\'';
532 else
533 OS << "aggregate initialization";
534 if (After.First || After.Second || After.Third) {
535 OS << " -> ";
536 After.dump();
537 }
538}
539
540/// dump - Print this implicit conversion sequence to standard
541/// error. Useful for debugging overloading issues.
542void ImplicitConversionSequence::dump() const {
543 raw_ostream &OS = llvm::errs();
544 if (isStdInitializerListElement())
545 OS << "Worst std::initializer_list element conversion: ";
546 switch (ConversionKind) {
547 case StandardConversion:
548 OS << "Standard conversion: ";
549 Standard.dump();
550 break;
551 case UserDefinedConversion:
552 OS << "User-defined conversion: ";
553 UserDefined.dump();
554 break;
555 case EllipsisConversion:
556 OS << "Ellipsis conversion";
557 break;
558 case AmbiguousConversion:
559 OS << "Ambiguous conversion";
560 break;
561 case BadConversion:
562 OS << "Bad conversion";
563 break;
564 }
565
566 OS << "\n";
567}
568
569void AmbiguousConversionSequence::construct() {
570 new (&conversions()) ConversionSet();
571}
572
573void AmbiguousConversionSequence::destruct() {
574 conversions().~ConversionSet();
575}
576
577void
578AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579 FromTypePtr = O.FromTypePtr;
580 ToTypePtr = O.ToTypePtr;
581 new (&conversions()) ConversionSet(O.conversions());
582}
583
584namespace {
585 // Structure used by DeductionFailureInfo to store
586 // template argument information.
587 struct DFIArguments {
588 TemplateArgument FirstArg;
589 TemplateArgument SecondArg;
590 };
591 // Structure used by DeductionFailureInfo to store
592 // template parameter and template argument information.
593 struct DFIParamWithArguments : DFIArguments {
594 TemplateParameter Param;
595 };
596 // Structure used by DeductionFailureInfo to store template argument
597 // information and the index of the problematic call argument.
598 struct DFIDeducedMismatchArgs : DFIArguments {
599 TemplateArgumentList *TemplateArgs;
600 unsigned CallArgIndex;
601 };
602 // Structure used by DeductionFailureInfo to store information about
603 // unsatisfied constraints.
604 struct CNSInfo {
605 TemplateArgumentList *TemplateArgs;
606 ConstraintSatisfaction Satisfaction;
607 };
608}
609
610/// Convert from Sema's representation of template deduction information
611/// to the form used in overload-candidate information.
612DeductionFailureInfo
613clang::MakeDeductionFailureInfo(ASTContext &Context,
614 Sema::TemplateDeductionResult TDK,
615 TemplateDeductionInfo &Info) {
616 DeductionFailureInfo Result;
617 Result.Result = static_cast<unsigned>(TDK);
618 Result.HasDiagnostic = false;
619 switch (TDK) {
620 case Sema::TDK_Invalid:
621 case Sema::TDK_InstantiationDepth:
622 case Sema::TDK_TooManyArguments:
623 case Sema::TDK_TooFewArguments:
624 case Sema::TDK_MiscellaneousDeductionFailure:
625 case Sema::TDK_CUDATargetMismatch:
626 Result.Data = nullptr;
627 break;
628
629 case Sema::TDK_Incomplete:
630 case Sema::TDK_InvalidExplicitArguments:
631 Result.Data = Info.Param.getOpaqueValue();
632 break;
633
634 case Sema::TDK_DeducedMismatch:
635 case Sema::TDK_DeducedMismatchNested: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 auto *Saved = new (Context) DFIDeducedMismatchArgs;
638 Saved->FirstArg = Info.FirstArg;
639 Saved->SecondArg = Info.SecondArg;
640 Saved->TemplateArgs = Info.take();
641 Saved->CallArgIndex = Info.CallArgIndex;
642 Result.Data = Saved;
643 break;
644 }
645
646 case Sema::TDK_NonDeducedMismatch: {
647 // FIXME: Should allocate from normal heap so that we can free this later.
648 DFIArguments *Saved = new (Context) DFIArguments;
649 Saved->FirstArg = Info.FirstArg;
650 Saved->SecondArg = Info.SecondArg;
651 Result.Data = Saved;
652 break;
653 }
654
655 case Sema::TDK_IncompletePack:
656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657 case Sema::TDK_Inconsistent:
658 case Sema::TDK_Underqualified: {
659 // FIXME: Should allocate from normal heap so that we can free this later.
660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661 Saved->Param = Info.Param;
662 Saved->FirstArg = Info.FirstArg;
663 Saved->SecondArg = Info.SecondArg;
664 Result.Data = Saved;
665 break;
666 }
667
668 case Sema::TDK_SubstitutionFailure:
669 Result.Data = Info.take();
670 if (Info.hasSFINAEDiagnostic()) {
671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672 SourceLocation(), PartialDiagnostic::NullDiagnostic());
673 Info.takeSFINAEDiagnostic(*Diag);
674 Result.HasDiagnostic = true;
675 }
676 break;
677
678 case Sema::TDK_ConstraintsNotSatisfied: {
679 CNSInfo *Saved = new (Context) CNSInfo;
680 Saved->TemplateArgs = Info.take();
681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682 Result.Data = Saved;
683 break;
684 }
685
686 case Sema::TDK_Success:
687 case Sema::TDK_NonDependentConversionFailure:
688 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 688)
;
689 }
690
691 return Result;
692}
693
694void DeductionFailureInfo::Destroy() {
695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696 case Sema::TDK_Success:
697 case Sema::TDK_Invalid:
698 case Sema::TDK_InstantiationDepth:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_InvalidExplicitArguments:
703 case Sema::TDK_CUDATargetMismatch:
704 case Sema::TDK_NonDependentConversionFailure:
705 break;
706
707 case Sema::TDK_IncompletePack:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_DeducedMismatch:
711 case Sema::TDK_DeducedMismatchNested:
712 case Sema::TDK_NonDeducedMismatch:
713 // FIXME: Destroy the data?
714 Data = nullptr;
715 break;
716
717 case Sema::TDK_SubstitutionFailure:
718 // FIXME: Destroy the template argument list?
719 Data = nullptr;
720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721 Diag->~PartialDiagnosticAt();
722 HasDiagnostic = false;
723 }
724 break;
725
726 case Sema::TDK_ConstraintsNotSatisfied:
727 // FIXME: Destroy the template argument list?
728 Data = nullptr;
729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730 Diag->~PartialDiagnosticAt();
731 HasDiagnostic = false;
732 }
733 break;
734
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 break;
738 }
739}
740
741PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742 if (HasDiagnostic)
743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744 return nullptr;
745}
746
747TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749 case Sema::TDK_Success:
750 case Sema::TDK_Invalid:
751 case Sema::TDK_InstantiationDepth:
752 case Sema::TDK_TooManyArguments:
753 case Sema::TDK_TooFewArguments:
754 case Sema::TDK_SubstitutionFailure:
755 case Sema::TDK_DeducedMismatch:
756 case Sema::TDK_DeducedMismatchNested:
757 case Sema::TDK_NonDeducedMismatch:
758 case Sema::TDK_CUDATargetMismatch:
759 case Sema::TDK_NonDependentConversionFailure:
760 case Sema::TDK_ConstraintsNotSatisfied:
761 return TemplateParameter();
762
763 case Sema::TDK_Incomplete:
764 case Sema::TDK_InvalidExplicitArguments:
765 return TemplateParameter::getFromOpaqueValue(Data);
766
767 case Sema::TDK_IncompletePack:
768 case Sema::TDK_Inconsistent:
769 case Sema::TDK_Underqualified:
770 return static_cast<DFIParamWithArguments*>(Data)->Param;
771
772 // Unhandled
773 case Sema::TDK_MiscellaneousDeductionFailure:
774 break;
775 }
776
777 return TemplateParameter();
778}
779
780TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782 case Sema::TDK_Success:
783 case Sema::TDK_Invalid:
784 case Sema::TDK_InstantiationDepth:
785 case Sema::TDK_TooManyArguments:
786 case Sema::TDK_TooFewArguments:
787 case Sema::TDK_Incomplete:
788 case Sema::TDK_IncompletePack:
789 case Sema::TDK_InvalidExplicitArguments:
790 case Sema::TDK_Inconsistent:
791 case Sema::TDK_Underqualified:
792 case Sema::TDK_NonDeducedMismatch:
793 case Sema::TDK_CUDATargetMismatch:
794 case Sema::TDK_NonDependentConversionFailure:
795 return nullptr;
796
797 case Sema::TDK_DeducedMismatch:
798 case Sema::TDK_DeducedMismatchNested:
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800
801 case Sema::TDK_SubstitutionFailure:
802 return static_cast<TemplateArgumentList*>(Data);
803
804 case Sema::TDK_ConstraintsNotSatisfied:
805 return static_cast<CNSInfo*>(Data)->TemplateArgs;
806
807 // Unhandled
808 case Sema::TDK_MiscellaneousDeductionFailure:
809 break;
810 }
811
812 return nullptr;
813}
814
815const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817 case Sema::TDK_Success:
818 case Sema::TDK_Invalid:
819 case Sema::TDK_InstantiationDepth:
820 case Sema::TDK_Incomplete:
821 case Sema::TDK_TooManyArguments:
822 case Sema::TDK_TooFewArguments:
823 case Sema::TDK_InvalidExplicitArguments:
824 case Sema::TDK_SubstitutionFailure:
825 case Sema::TDK_CUDATargetMismatch:
826 case Sema::TDK_NonDependentConversionFailure:
827 case Sema::TDK_ConstraintsNotSatisfied:
828 return nullptr;
829
830 case Sema::TDK_IncompletePack:
831 case Sema::TDK_Inconsistent:
832 case Sema::TDK_Underqualified:
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 case Sema::TDK_NonDeducedMismatch:
836 return &static_cast<DFIArguments*>(Data)->FirstArg;
837
838 // Unhandled
839 case Sema::TDK_MiscellaneousDeductionFailure:
840 break;
841 }
842
843 return nullptr;
844}
845
846const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848 case Sema::TDK_Success:
849 case Sema::TDK_Invalid:
850 case Sema::TDK_InstantiationDepth:
851 case Sema::TDK_Incomplete:
852 case Sema::TDK_IncompletePack:
853 case Sema::TDK_TooManyArguments:
854 case Sema::TDK_TooFewArguments:
855 case Sema::TDK_InvalidExplicitArguments:
856 case Sema::TDK_SubstitutionFailure:
857 case Sema::TDK_CUDATargetMismatch:
858 case Sema::TDK_NonDependentConversionFailure:
859 case Sema::TDK_ConstraintsNotSatisfied:
860 return nullptr;
861
862 case Sema::TDK_Inconsistent:
863 case Sema::TDK_Underqualified:
864 case Sema::TDK_DeducedMismatch:
865 case Sema::TDK_DeducedMismatchNested:
866 case Sema::TDK_NonDeducedMismatch:
867 return &static_cast<DFIArguments*>(Data)->SecondArg;
868
869 // Unhandled
870 case Sema::TDK_MiscellaneousDeductionFailure:
871 break;
872 }
873
874 return nullptr;
875}
876
877llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879 case Sema::TDK_DeducedMismatch:
880 case Sema::TDK_DeducedMismatchNested:
881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882
883 default:
884 return llvm::None;
885 }
886}
887
888bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889 OverloadedOperatorKind Op) {
890 if (!AllowRewrittenCandidates)
891 return false;
892 return Op == OO_EqualEqual || Op == OO_Spaceship;
893}
894
895bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896 ASTContext &Ctx, const FunctionDecl *FD) {
897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898 return false;
899 // Don't bother adding a reversed candidate that can never be a better
900 // match than the non-reversed version.
901 return FD->getNumParams() != 2 ||
902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903 FD->getParamDecl(1)->getType()) ||
904 FD->hasAttr<EnableIfAttr>();
905}
906
907void OverloadCandidateSet::destroyCandidates() {
908 for (iterator i = begin(), e = end(); i != e; ++i) {
909 for (auto &C : i->Conversions)
910 C.~ImplicitConversionSequence();
911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912 i->DeductionFailure.Destroy();
913 }
914}
915
916void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917 destroyCandidates();
918 SlabAllocator.Reset();
919 NumInlineBytesUsed = 0;
920 Candidates.clear();
921 Functions.clear();
922 Kind = CSK;
923}
924
925namespace {
926 class UnbridgedCastsSet {
927 struct Entry {
928 Expr **Addr;
929 Expr *Saved;
930 };
931 SmallVector<Entry, 2> Entries;
932
933 public:
934 void save(Sema &S, Expr *&E) {
935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 935, __PRETTY_FUNCTION__))
;
936 Entry entry = { &E, E };
937 Entries.push_back(entry);
938 E = S.stripARCUnbridgedCast(E);
939 }
940
941 void restore() {
942 for (SmallVectorImpl<Entry>::iterator
943 i = Entries.begin(), e = Entries.end(); i != e; ++i)
944 *i->Addr = i->Saved;
945 }
946 };
947}
948
949/// checkPlaceholderForOverload - Do any interesting placeholder-like
950/// preprocessing on the given expression.
951///
952/// \param unbridgedCasts a collection to which to add unbridged casts;
953/// without this, they will be immediately diagnosed as errors
954///
955/// Return true on unrecoverable error.
956static bool
957checkPlaceholderForOverload(Sema &S, Expr *&E,
958 UnbridgedCastsSet *unbridgedCasts = nullptr) {
959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
960 // We can't handle overloaded expressions here because overload
961 // resolution might reasonably tweak them.
962 if (placeholder->getKind() == BuiltinType::Overload) return false;
963
964 // If the context potentially accepts unbridged ARC casts, strip
965 // the unbridged cast and add it to the collection for later restoration.
966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967 unbridgedCasts) {
968 unbridgedCasts->save(S, E);
969 return false;
970 }
971
972 // Go ahead and check everything else.
973 ExprResult result = S.CheckPlaceholderExpr(E);
974 if (result.isInvalid())
975 return true;
976
977 E = result.get();
978 return false;
979 }
980
981 // Nothing to do.
982 return false;
983}
984
985/// checkArgPlaceholdersForOverload - Check a set of call operands for
986/// placeholders.
987static bool checkArgPlaceholdersForOverload(Sema &S,
988 MultiExprArg Args,
989 UnbridgedCastsSet &unbridged) {
990 for (unsigned i = 0, e = Args.size(); i != e; ++i)
991 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992 return true;
993
994 return false;
995}
996
997/// Determine whether the given New declaration is an overload of the
998/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999/// New and Old cannot be overloaded, e.g., if New has the same signature as
1000/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001/// functions (or function templates) at all. When it does return Ovl_Match or
1002/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004/// declaration.
1005///
1006/// Example: Given the following input:
1007///
1008/// void f(int, float); // #1
1009/// void f(int, int); // #2
1010/// int f(int, int); // #3
1011///
1012/// When we process #1, there is no previous declaration of "f", so IsOverload
1013/// will not be used.
1014///
1015/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016/// the parameter types, we see that #1 and #2 are overloaded (since they have
1017/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018/// unchanged.
1019///
1020/// When we process #3, Old is an overload set containing #1 and #2. We compare
1021/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023/// functions are not part of the signature), IsOverload returns Ovl_Match and
1024/// MatchedDecl will be set to point to the FunctionDecl for #2.
1025///
1026/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027/// by a using declaration. The rules for whether to hide shadow declarations
1028/// ignore some properties which otherwise figure into a function template's
1029/// signature.
1030Sema::OverloadKind
1031Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032 NamedDecl *&Match, bool NewIsUsingDecl) {
1033 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034 I != E; ++I) {
1035 NamedDecl *OldD = *I;
1036
1037 bool OldIsUsingDecl = false;
1038 if (isa<UsingShadowDecl>(OldD)) {
1039 OldIsUsingDecl = true;
1040
1041 // We can always introduce two using declarations into the same
1042 // context, even if they have identical signatures.
1043 if (NewIsUsingDecl) continue;
1044
1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046 }
1047
1048 // A using-declaration does not conflict with another declaration
1049 // if one of them is hidden.
1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051 continue;
1052
1053 // If either declaration was introduced by a using declaration,
1054 // we'll need to use slightly different rules for matching.
1055 // Essentially, these rules are the normal rules, except that
1056 // function templates hide function templates with different
1057 // return types or template parameter lists.
1058 bool UseMemberUsingDeclRules =
1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060 !New->getFriendObjectKind();
1061
1062 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066 continue;
1067 }
1068
1069 if (!isa<FunctionTemplateDecl>(OldD) &&
1070 !shouldLinkPossiblyHiddenDecl(*I, New))
1071 continue;
1072
1073 Match = *I;
1074 return Ovl_Match;
1075 }
1076
1077 // Builtins that have custom typechecking or have a reference should
1078 // not be overloadable or redeclarable.
1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080 Match = *I;
1081 return Ovl_NonFunction;
1082 }
1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084 // We can overload with these, which can show up when doing
1085 // redeclaration checks for UsingDecls.
1086 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1086, __PRETTY_FUNCTION__))
;
1087 } else if (isa<TagDecl>(OldD)) {
1088 // We can always overload with tags by hiding them.
1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090 // Optimistically assume that an unresolved using decl will
1091 // overload; if it doesn't, we'll have to diagnose during
1092 // template instantiation.
1093 //
1094 // Exception: if the scope is dependent and this is not a class
1095 // member, the using declaration can only introduce an enumerator.
1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097 Match = *I;
1098 return Ovl_NonFunction;
1099 }
1100 } else {
1101 // (C++ 13p1):
1102 // Only function declarations can be overloaded; object and type
1103 // declarations cannot be overloaded.
1104 Match = *I;
1105 return Ovl_NonFunction;
1106 }
1107 }
1108
1109 // C++ [temp.friend]p1:
1110 // For a friend function declaration that is not a template declaration:
1111 // -- if the name of the friend is a qualified or unqualified template-id,
1112 // [...], otherwise
1113 // -- if the name of the friend is a qualified-id and a matching
1114 // non-template function is found in the specified class or namespace,
1115 // the friend declaration refers to that function, otherwise,
1116 // -- if the name of the friend is a qualified-id and a matching function
1117 // template is found in the specified class or namespace, the friend
1118 // declaration refers to the deduced specialization of that function
1119 // template, otherwise
1120 // -- the name shall be an unqualified-id [...]
1121 // If we get here for a qualified friend declaration, we've just reached the
1122 // third bullet. If the type of the friend is dependent, skip this lookup
1123 // until instantiation.
1124 if (New->getFriendObjectKind() && New->getQualifier() &&
1125 !New->getDescribedFunctionTemplate() &&
1126 !New->getDependentSpecializationInfo() &&
1127 !New->getType()->isDependentType()) {
1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129 TemplateSpecResult.addAllDecls(Old);
1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131 /*QualifiedFriend*/true)) {
1132 New->setInvalidDecl();
1133 return Ovl_Overload;
1134 }
1135
1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137 return Ovl_Match;
1138 }
1139
1140 return Ovl_Overload;
1141}
1142
1143bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145 bool ConsiderRequiresClauses) {
1146 // C++ [basic.start.main]p2: This function shall not be overloaded.
1147 if (New->isMain())
1148 return false;
1149
1150 // MSVCRT user defined entry points cannot be overloaded.
1151 if (New->isMSVCRTEntryPoint())
1152 return false;
1153
1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156
1157 // C++ [temp.fct]p2:
1158 // A function template can be overloaded with other function templates
1159 // and with normal (non-template) functions.
1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161 return true;
1162
1163 // Is the function New an overload of the function Old?
1164 QualType OldQType = Context.getCanonicalType(Old->getType());
1165 QualType NewQType = Context.getCanonicalType(New->getType());
1166
1167 // Compare the signatures (C++ 1.3.10) of the two functions to
1168 // determine whether they are overloads. If we find any mismatch
1169 // in the signature, they are overloads.
1170
1171 // If either of these functions is a K&R-style function (no
1172 // prototype), then we consider them to have matching signatures.
1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175 return false;
1176
1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179
1180 // The signature of a function includes the types of its
1181 // parameters (C++ 1.3.10), which includes the presence or absence
1182 // of the ellipsis; see C++ DR 357).
1183 if (OldQType != NewQType &&
1184 (OldType->getNumParams() != NewType->getNumParams() ||
1185 OldType->isVariadic() != NewType->isVariadic() ||
1186 !FunctionParamTypesAreEqual(OldType, NewType)))
1187 return true;
1188
1189 // C++ [temp.over.link]p4:
1190 // The signature of a function template consists of its function
1191 // signature, its return type and its template parameter list. The names
1192 // of the template parameters are significant only for establishing the
1193 // relationship between the template parameters and the rest of the
1194 // signature.
1195 //
1196 // We check the return type and template parameter lists for function
1197 // templates first; the remaining checks follow.
1198 //
1199 // However, we don't consider either of these when deciding whether
1200 // a member introduced by a shadow declaration is hidden.
1201 if (!UseMemberUsingDeclRules && NewTemplate &&
1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203 OldTemplate->getTemplateParameters(),
1204 false, TPL_TemplateMatch) ||
1205 !Context.hasSameType(Old->getDeclaredReturnType(),
1206 New->getDeclaredReturnType())))
1207 return true;
1208
1209 // If the function is a class member, its signature includes the
1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211 //
1212 // As part of this, also check whether one of the member functions
1213 // is static, in which case they are not overloads (C++
1214 // 13.1p2). While not part of the definition of the signature,
1215 // this check is important to determine whether these functions
1216 // can be overloaded.
1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219 if (OldMethod && NewMethod &&
1220 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222 if (!UseMemberUsingDeclRules &&
1223 (OldMethod->getRefQualifier() == RQ_None ||
1224 NewMethod->getRefQualifier() == RQ_None)) {
1225 // C++0x [over.load]p2:
1226 // - Member function declarations with the same name and the same
1227 // parameter-type-list as well as member function template
1228 // declarations with the same name, the same parameter-type-list, and
1229 // the same template parameter lists cannot be overloaded if any of
1230 // them, but not all, have a ref-qualifier (8.3.5).
1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234 }
1235 return true;
1236 }
1237
1238 // We may not have applied the implicit const for a constexpr member
1239 // function yet (because we haven't yet resolved whether this is a static
1240 // or non-static member function). Add it now, on the assumption that this
1241 // is a redeclaration of OldMethod.
1242 auto OldQuals = OldMethod->getMethodQualifiers();
1243 auto NewQuals = NewMethod->getMethodQualifiers();
1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245 !isa<CXXConstructorDecl>(NewMethod))
1246 NewQuals.addConst();
1247 // We do not allow overloading based off of '__restrict'.
1248 OldQuals.removeRestrict();
1249 NewQuals.removeRestrict();
1250 if (OldQuals != NewQuals)
1251 return true;
1252 }
1253
1254 // Though pass_object_size is placed on parameters and takes an argument, we
1255 // consider it to be a function-level modifier for the sake of function
1256 // identity. Either the function has one or more parameters with
1257 // pass_object_size or it doesn't.
1258 if (functionHasPassObjectSizeParams(New) !=
1259 functionHasPassObjectSizeParams(Old))
1260 return true;
1261
1262 // enable_if attributes are an order-sensitive part of the signature.
1263 for (specific_attr_iterator<EnableIfAttr>
1264 NewI = New->specific_attr_begin<EnableIfAttr>(),
1265 NewE = New->specific_attr_end<EnableIfAttr>(),
1266 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267 OldE = Old->specific_attr_end<EnableIfAttr>();
1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269 if (NewI == NewE || OldI == OldE)
1270 return true;
1271 llvm::FoldingSetNodeID NewID, OldID;
1272 NewI->getCond()->Profile(NewID, Context, true);
1273 OldI->getCond()->Profile(OldID, Context, true);
1274 if (NewID != OldID)
1275 return true;
1276 }
1277
1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279 // Don't allow overloading of destructors. (In theory we could, but it
1280 // would be a giant change to clang.)
1281 if (!isa<CXXDestructorDecl>(New)) {
1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283 OldTarget = IdentifyCUDATarget(Old);
1284 if (NewTarget != CFT_InvalidTarget) {
1285 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287
1288 // Allow overloading of functions with same signature and different CUDA
1289 // target attributes.
1290 if (NewTarget != OldTarget)
1291 return true;
1292 }
1293 }
1294 }
1295
1296 if (ConsiderRequiresClauses) {
1297 Expr *NewRC = New->getTrailingRequiresClause(),
1298 *OldRC = Old->getTrailingRequiresClause();
1299 if ((NewRC != nullptr) != (OldRC != nullptr))
1300 // RC are most certainly different - these are overloads.
1301 return true;
1302
1303 if (NewRC) {
1304 llvm::FoldingSetNodeID NewID, OldID;
1305 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307 if (NewID != OldID)
1308 // RCs are not equivalent - these are overloads.
1309 return true;
1310 }
1311 }
1312
1313 // The signatures match; this is not an overload.
1314 return false;
1315}
1316
1317/// Tries a user-defined conversion from From to ToType.
1318///
1319/// Produces an implicit conversion sequence for when a standard conversion
1320/// is not an option. See TryImplicitConversion for more information.
1321static ImplicitConversionSequence
1322TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323 bool SuppressUserConversions,
1324 AllowedExplicit AllowExplicit,
1325 bool InOverloadResolution,
1326 bool CStyle,
1327 bool AllowObjCWritebackConversion,
1328 bool AllowObjCConversionOnExplicit) {
1329 ImplicitConversionSequence ICS;
1330
1331 if (SuppressUserConversions) {
1332 // We're not in the case above, so there is no conversion that
1333 // we can perform.
1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335 return ICS;
1336 }
1337
1338 // Attempt user-defined conversion.
1339 OverloadCandidateSet Conversions(From->getExprLoc(),
1340 OverloadCandidateSet::CSK_Normal);
1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342 Conversions, AllowExplicit,
1343 AllowObjCConversionOnExplicit)) {
1344 case OR_Success:
1345 case OR_Deleted:
1346 ICS.setUserDefined();
1347 // C++ [over.ics.user]p4:
1348 // A conversion of an expression of class type to the same class
1349 // type is given Exact Match rank, and a conversion of an
1350 // expression of class type to a base class of that type is
1351 // given Conversion rank, in spite of the fact that a copy
1352 // constructor (i.e., a user-defined conversion function) is
1353 // called for those cases.
1354 if (CXXConstructorDecl *Constructor
1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356 QualType FromCanon
1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358 QualType ToCanon
1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360 if (Constructor->isCopyConstructor() &&
1361 (FromCanon == ToCanon ||
1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363 // Turn this into a "standard" conversion sequence, so that it
1364 // gets ranked with standard conversion sequences.
1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366 ICS.setStandard();
1367 ICS.Standard.setAsIdentityConversion();
1368 ICS.Standard.setFromType(From->getType());
1369 ICS.Standard.setAllToTypes(ToType);
1370 ICS.Standard.CopyConstructor = Constructor;
1371 ICS.Standard.FoundCopyConstructor = Found;
1372 if (ToCanon != FromCanon)
1373 ICS.Standard.Second = ICK_Derived_To_Base;
1374 }
1375 }
1376 break;
1377
1378 case OR_Ambiguous:
1379 ICS.setAmbiguous();
1380 ICS.Ambiguous.setFromType(From->getType());
1381 ICS.Ambiguous.setToType(ToType);
1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383 Cand != Conversions.end(); ++Cand)
1384 if (Cand->Best)
1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386 break;
1387
1388 // Fall through.
1389 case OR_No_Viable_Function:
1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391 break;
1392 }
1393
1394 return ICS;
1395}
1396
1397/// TryImplicitConversion - Attempt to perform an implicit conversion
1398/// from the given expression (Expr) to the given type (ToType). This
1399/// function returns an implicit conversion sequence that can be used
1400/// to perform the initialization. Given
1401///
1402/// void f(float f);
1403/// void g(int i) { f(i); }
1404///
1405/// this routine would produce an implicit conversion sequence to
1406/// describe the initialization of f from i, which will be a standard
1407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409//
1410/// Note that this routine only determines how the conversion can be
1411/// performed; it does not actually perform the conversion. As such,
1412/// it will not produce any diagnostics if no conversion is available,
1413/// but will instead return an implicit conversion sequence of kind
1414/// "BadConversion".
1415///
1416/// If @p SuppressUserConversions, then user-defined conversions are
1417/// not permitted.
1418/// If @p AllowExplicit, then explicit user-defined conversions are
1419/// permitted.
1420///
1421/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422/// writeback conversion, which allows __autoreleasing id* parameters to
1423/// be initialized with __strong id* or __weak id* arguments.
1424static ImplicitConversionSequence
1425TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426 bool SuppressUserConversions,
1427 AllowedExplicit AllowExplicit,
1428 bool InOverloadResolution,
1429 bool CStyle,
1430 bool AllowObjCWritebackConversion,
1431 bool AllowObjCConversionOnExplicit) {
1432 ImplicitConversionSequence ICS;
1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435 ICS.setStandard();
1436 return ICS;
1437 }
1438
1439 if (!S.getLangOpts().CPlusPlus) {
1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441 return ICS;
1442 }
1443
1444 // C++ [over.ics.user]p4:
1445 // A conversion of an expression of class type to the same class
1446 // type is given Exact Match rank, and a conversion of an
1447 // expression of class type to a base class of that type is
1448 // given Conversion rank, in spite of the fact that a copy/move
1449 // constructor (i.e., a user-defined conversion function) is
1450 // called for those cases.
1451 QualType FromType = From->getType();
1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455 ICS.setStandard();
1456 ICS.Standard.setAsIdentityConversion();
1457 ICS.Standard.setFromType(FromType);
1458 ICS.Standard.setAllToTypes(ToType);
1459
1460 // We don't actually check at this point whether there is a valid
1461 // copy/move constructor, since overloading just assumes that it
1462 // exists. When we actually perform initialization, we'll find the
1463 // appropriate constructor to copy the returned object, if needed.
1464 ICS.Standard.CopyConstructor = nullptr;
1465
1466 // Determine whether this is considered a derived-to-base conversion.
1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468 ICS.Standard.Second = ICK_Derived_To_Base;
1469
1470 return ICS;
1471 }
1472
1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474 AllowExplicit, InOverloadResolution, CStyle,
1475 AllowObjCWritebackConversion,
1476 AllowObjCConversionOnExplicit);
1477}
1478
1479ImplicitConversionSequence
1480Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481 bool SuppressUserConversions,
1482 AllowedExplicit AllowExplicit,
1483 bool InOverloadResolution,
1484 bool CStyle,
1485 bool AllowObjCWritebackConversion) {
1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487 AllowExplicit, InOverloadResolution, CStyle,
1488 AllowObjCWritebackConversion,
1489 /*AllowObjCConversionOnExplicit=*/false);
1490}
1491
1492/// PerformImplicitConversion - Perform an implicit conversion of the
1493/// expression From to the type ToType. Returns the
1494/// converted expression. Flavor is the kind of conversion we're
1495/// performing, used in the error message. If @p AllowExplicit,
1496/// explicit user-defined conversions are permitted.
1497ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498 AssignmentAction Action,
1499 bool AllowExplicit) {
1500 if (checkPlaceholderForOverload(*this, From))
1501 return ExprError();
1502
1503 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504 bool AllowObjCWritebackConversion
1505 = getLangOpts().ObjCAutoRefCount &&
1506 (Action == AA_Passing || Action == AA_Sending);
1507 if (getLangOpts().ObjC)
1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509 From->getType(), From);
1510 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511 *this, From, ToType,
1512 /*SuppressUserConversions=*/false,
1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514 /*InOverloadResolution=*/false,
1515 /*CStyle=*/false, AllowObjCWritebackConversion,
1516 /*AllowObjCConversionOnExplicit=*/false);
1517 return PerformImplicitConversion(From, ToType, ICS, Action);
1518}
1519
1520/// Determine whether the conversion from FromType to ToType is a valid
1521/// conversion that strips "noexcept" or "noreturn" off the nested function
1522/// type.
1523bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524 QualType &ResultTy) {
1525 if (Context.hasSameUnqualifiedType(FromType, ToType))
1526 return false;
1527
1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529 // or F(t noexcept) -> F(t)
1530 // where F adds one of the following at most once:
1531 // - a pointer
1532 // - a member pointer
1533 // - a block pointer
1534 // Changes here need matching changes in FindCompositePointerType.
1535 CanQualType CanTo = Context.getCanonicalType(ToType);
1536 CanQualType CanFrom = Context.getCanonicalType(FromType);
1537 Type::TypeClass TyClass = CanTo->getTypeClass();
1538 if (TyClass != CanFrom->getTypeClass()) return false;
1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540 if (TyClass == Type::Pointer) {
1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543 } else if (TyClass == Type::BlockPointer) {
1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546 } else if (TyClass == Type::MemberPointer) {
1547 auto ToMPT = CanTo.castAs<MemberPointerType>();
1548 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549 // A function pointer conversion cannot change the class of the function.
1550 if (ToMPT->getClass() != FromMPT->getClass())
1551 return false;
1552 CanTo = ToMPT->getPointeeType();
1553 CanFrom = FromMPT->getPointeeType();
1554 } else {
1555 return false;
1556 }
1557
1558 TyClass = CanTo->getTypeClass();
1559 if (TyClass != CanFrom->getTypeClass()) return false;
1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561 return false;
1562 }
1563
1564 const auto *FromFn = cast<FunctionType>(CanFrom);
1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566
1567 const auto *ToFn = cast<FunctionType>(CanTo);
1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569
1570 bool Changed = false;
1571
1572 // Drop 'noreturn' if not present in target type.
1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575 Changed = true;
1576 }
1577
1578 // Drop 'noexcept' if not present in target type.
1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582 FromFn = cast<FunctionType>(
1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584 EST_None)
1585 .getTypePtr());
1586 Changed = true;
1587 }
1588
1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590 // only if the ExtParameterInfo lists of the two function prototypes can be
1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593 bool CanUseToFPT, CanUseFromFPT;
1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595 CanUseFromFPT, NewParamInfos) &&
1596 CanUseToFPT && !CanUseFromFPT) {
1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598 ExtInfo.ExtParameterInfos =
1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601 FromFPT->getParamTypes(), ExtInfo);
1602 FromFn = QT->getAs<FunctionType>();
1603 Changed = true;
1604 }
1605 }
1606
1607 if (!Changed)
1608 return false;
1609
1610 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1610, __PRETTY_FUNCTION__))
;
1611 if (QualType(FromFn, 0) != CanTo) return false;
1612
1613 ResultTy = ToType;
1614 return true;
1615}
1616
1617/// Determine whether the conversion from FromType to ToType is a valid
1618/// vector conversion.
1619///
1620/// \param ICK Will be set to the vector conversion kind, if this is a vector
1621/// conversion.
1622static bool IsVectorConversion(Sema &S, QualType FromType,
1623 QualType ToType, ImplicitConversionKind &ICK) {
1624 // We need at least one of these types to be a vector type to have a vector
1625 // conversion.
1626 if (!ToType->isVectorType() && !FromType->isVectorType())
1627 return false;
1628
1629 // Identical types require no conversions.
1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631 return false;
1632
1633 // There are no conversions between extended vector types, only identity.
1634 if (ToType->isExtVectorType()) {
1635 // There are no conversions between extended vector types other than the
1636 // identity conversion.
1637 if (FromType->isExtVectorType())
1638 return false;
1639
1640 // Vector splat from any arithmetic type to a vector.
1641 if (FromType->isArithmeticType()) {
1642 ICK = ICK_Vector_Splat;
1643 return true;
1644 }
1645 }
1646
1647 if ((ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) &&
1648 S.Context.areCompatibleSveTypes(FromType, ToType)) {
1649 ICK = ICK_SVE_Vector_Conversion;
1650 return true;
1651 }
1652
1653 // We can perform the conversion between vector types in the following cases:
1654 // 1)vector types are equivalent AltiVec and GCC vector types
1655 // 2)lax vector conversions are permitted and the vector types are of the
1656 // same size
1657 // 3)the destination type does not have the ARM MVE strict-polymorphism
1658 // attribute, which inhibits lax vector conversion for overload resolution
1659 // only
1660 if (ToType->isVectorType() && FromType->isVectorType()) {
1661 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662 (S.isLaxVectorConversion(FromType, ToType) &&
1663 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664 ICK = ICK_Vector_Conversion;
1665 return true;
1666 }
1667 }
1668
1669 return false;
1670}
1671
1672static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1673 bool InOverloadResolution,
1674 StandardConversionSequence &SCS,
1675 bool CStyle);
1676
1677/// IsStandardConversion - Determines whether there is a standard
1678/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1679/// expression From to the type ToType. Standard conversion sequences
1680/// only consider non-class types; for conversions that involve class
1681/// types, use TryImplicitConversion. If a conversion exists, SCS will
1682/// contain the standard conversion sequence required to perform this
1683/// conversion and this routine will return true. Otherwise, this
1684/// routine will return false and the value of SCS is unspecified.
1685static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1686 bool InOverloadResolution,
1687 StandardConversionSequence &SCS,
1688 bool CStyle,
1689 bool AllowObjCWritebackConversion) {
1690 QualType FromType = From->getType();
1691
1692 // Standard conversions (C++ [conv])
1693 SCS.setAsIdentityConversion();
1694 SCS.IncompatibleObjC = false;
1695 SCS.setFromType(FromType);
1696 SCS.CopyConstructor = nullptr;
1697
1698 // There are no standard conversions for class types in C++, so
1699 // abort early. When overloading in C, however, we do permit them.
1700 if (S.getLangOpts().CPlusPlus &&
1701 (FromType->isRecordType() || ToType->isRecordType()))
1702 return false;
1703
1704 // The first conversion can be an lvalue-to-rvalue conversion,
1705 // array-to-pointer conversion, or function-to-pointer conversion
1706 // (C++ 4p1).
1707
1708 if (FromType == S.Context.OverloadTy) {
1709 DeclAccessPair AccessPair;
1710 if (FunctionDecl *Fn
1711 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1712 AccessPair)) {
1713 // We were able to resolve the address of the overloaded function,
1714 // so we can convert to the type of that function.
1715 FromType = Fn->getType();
1716 SCS.setFromType(FromType);
1717
1718 // we can sometimes resolve &foo<int> regardless of ToType, so check
1719 // if the type matches (identity) or we are converting to bool
1720 if (!S.Context.hasSameUnqualifiedType(
1721 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1722 QualType resultTy;
1723 // if the function type matches except for [[noreturn]], it's ok
1724 if (!S.IsFunctionConversion(FromType,
1725 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1726 // otherwise, only a boolean conversion is standard
1727 if (!ToType->isBooleanType())
1728 return false;
1729 }
1730
1731 // Check if the "from" expression is taking the address of an overloaded
1732 // function and recompute the FromType accordingly. Take advantage of the
1733 // fact that non-static member functions *must* have such an address-of
1734 // expression.
1735 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1736 if (Method && !Method->isStatic()) {
1737 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1738, __PRETTY_FUNCTION__))
1738 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1738, __PRETTY_FUNCTION__))
;
1739 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1741, __PRETTY_FUNCTION__))
1740 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1741, __PRETTY_FUNCTION__))
1741 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1741, __PRETTY_FUNCTION__))
;
1742 const Type *ClassType
1743 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1744 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1745 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1746 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1748, __PRETTY_FUNCTION__))
1747 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1748, __PRETTY_FUNCTION__))
1748 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1748, __PRETTY_FUNCTION__))
;
1749 FromType = S.Context.getPointerType(FromType);
1750 }
1751
1752 // Check that we've computed the proper type after overload resolution.
1753 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1754 // be calling it from within an NDEBUG block.
1755 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1757, __PRETTY_FUNCTION__))
1756 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1757, __PRETTY_FUNCTION__))
1757 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 1757, __PRETTY_FUNCTION__))
;
1758 } else {
1759 return false;
1760 }
1761 }
1762 // Lvalue-to-rvalue conversion (C++11 4.1):
1763 // A glvalue (3.10) of a non-function, non-array type T can
1764 // be converted to a prvalue.
1765 bool argIsLValue = From->isGLValue();
1766 if (argIsLValue &&
1767 !FromType->isFunctionType() && !FromType->isArrayType() &&
1768 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769 SCS.First = ICK_Lvalue_To_Rvalue;
1770
1771 // C11 6.3.2.1p2:
1772 // ... if the lvalue has atomic type, the value has the non-atomic version
1773 // of the type of the lvalue ...
1774 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775 FromType = Atomic->getValueType();
1776
1777 // If T is a non-class type, the type of the rvalue is the
1778 // cv-unqualified version of T. Otherwise, the type of the rvalue
1779 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780 // just strip the qualifiers because they don't matter.
1781 FromType = FromType.getUnqualifiedType();
1782 } else if (FromType->isArrayType()) {
1783 // Array-to-pointer conversion (C++ 4.2)
1784 SCS.First = ICK_Array_To_Pointer;
1785
1786 // An lvalue or rvalue of type "array of N T" or "array of unknown
1787 // bound of T" can be converted to an rvalue of type "pointer to
1788 // T" (C++ 4.2p1).
1789 FromType = S.Context.getArrayDecayedType(FromType);
1790
1791 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792 // This conversion is deprecated in C++03 (D.4)
1793 SCS.DeprecatedStringLiteralToCharPtr = true;
1794
1795 // For the purpose of ranking in overload resolution
1796 // (13.3.3.1.1), this conversion is considered an
1797 // array-to-pointer conversion followed by a qualification
1798 // conversion (4.4). (C++ 4.2p2)
1799 SCS.Second = ICK_Identity;
1800 SCS.Third = ICK_Qualification;
1801 SCS.QualificationIncludesObjCLifetime = false;
1802 SCS.setAllToTypes(FromType);
1803 return true;
1804 }
1805 } else if (FromType->isFunctionType() && argIsLValue) {
1806 // Function-to-pointer conversion (C++ 4.3).
1807 SCS.First = ICK_Function_To_Pointer;
1808
1809 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811 if (!S.checkAddressOfFunctionIsAvailable(FD))
1812 return false;
1813
1814 // An lvalue of function type T can be converted to an rvalue of
1815 // type "pointer to T." The result is a pointer to the
1816 // function. (C++ 4.3p1).
1817 FromType = S.Context.getPointerType(FromType);
1818 } else {
1819 // We don't require any conversions for the first step.
1820 SCS.First = ICK_Identity;
1821 }
1822 SCS.setToType(0, FromType);
1823
1824 // The second conversion can be an integral promotion, floating
1825 // point promotion, integral conversion, floating point conversion,
1826 // floating-integral conversion, pointer conversion,
1827 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828 // For overloading in C, this can also be a "compatible-type"
1829 // conversion.
1830 bool IncompatibleObjC = false;
1831 ImplicitConversionKind SecondICK = ICK_Identity;
1832 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833 // The unqualified versions of the types are the same: there's no
1834 // conversion to do.
1835 SCS.Second = ICK_Identity;
1836 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837 // Integral promotion (C++ 4.5).
1838 SCS.Second = ICK_Integral_Promotion;
1839 FromType = ToType.getUnqualifiedType();
1840 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841 // Floating point promotion (C++ 4.6).
1842 SCS.Second = ICK_Floating_Promotion;
1843 FromType = ToType.getUnqualifiedType();
1844 } else if (S.IsComplexPromotion(FromType, ToType)) {
1845 // Complex promotion (Clang extension)
1846 SCS.Second = ICK_Complex_Promotion;
1847 FromType = ToType.getUnqualifiedType();
1848 } else if (ToType->isBooleanType() &&
1849 (FromType->isArithmeticType() ||
1850 FromType->isAnyPointerType() ||
1851 FromType->isBlockPointerType() ||
1852 FromType->isMemberPointerType())) {
1853 // Boolean conversions (C++ 4.12).
1854 SCS.Second = ICK_Boolean_Conversion;
1855 FromType = S.Context.BoolTy;
1856 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857 ToType->isIntegralType(S.Context)) {
1858 // Integral conversions (C++ 4.7).
1859 SCS.Second = ICK_Integral_Conversion;
1860 FromType = ToType.getUnqualifiedType();
1861 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862 // Complex conversions (C99 6.3.1.6)
1863 SCS.Second = ICK_Complex_Conversion;
1864 FromType = ToType.getUnqualifiedType();
1865 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867 // Complex-real conversions (C99 6.3.1.7)
1868 SCS.Second = ICK_Complex_Real;
1869 FromType = ToType.getUnqualifiedType();
1870 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871 // FIXME: disable conversions between long double and __float128 if
1872 // their representation is different until there is back end support
1873 // We of course allow this conversion if long double is really double.
1874
1875 // Conversions between bfloat and other floats are not permitted.
1876 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877 return false;
1878 if (&S.Context.getFloatTypeSemantics(FromType) !=
1879 &S.Context.getFloatTypeSemantics(ToType)) {
1880 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1881 ToType == S.Context.LongDoubleTy) ||
1882 (FromType == S.Context.LongDoubleTy &&
1883 ToType == S.Context.Float128Ty));
1884 if (Float128AndLongDouble &&
1885 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1886 &llvm::APFloat::PPCDoubleDouble()))
1887 return false;
1888 }
1889 // Floating point conversions (C++ 4.8).
1890 SCS.Second = ICK_Floating_Conversion;
1891 FromType = ToType.getUnqualifiedType();
1892 } else if ((FromType->isRealFloatingType() &&
1893 ToType->isIntegralType(S.Context)) ||
1894 (FromType->isIntegralOrUnscopedEnumerationType() &&
1895 ToType->isRealFloatingType())) {
1896 // Conversions between bfloat and int are not permitted.
1897 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1898 return false;
1899
1900 // Floating-integral conversions (C++ 4.9).
1901 SCS.Second = ICK_Floating_Integral;
1902 FromType = ToType.getUnqualifiedType();
1903 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1904 SCS.Second = ICK_Block_Pointer_Conversion;
1905 } else if (AllowObjCWritebackConversion &&
1906 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1907 SCS.Second = ICK_Writeback_Conversion;
1908 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1909 FromType, IncompatibleObjC)) {
1910 // Pointer conversions (C++ 4.10).
1911 SCS.Second = ICK_Pointer_Conversion;
1912 SCS.IncompatibleObjC = IncompatibleObjC;
1913 FromType = FromType.getUnqualifiedType();
1914 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1915 InOverloadResolution, FromType)) {
1916 // Pointer to member conversions (4.11).
1917 SCS.Second = ICK_Pointer_Member;
1918 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1919 SCS.Second = SecondICK;
1920 FromType = ToType.getUnqualifiedType();
1921 } else if (!S.getLangOpts().CPlusPlus &&
1922 S.Context.typesAreCompatible(ToType, FromType)) {
1923 // Compatible conversions (Clang extension for C function overloading)
1924 SCS.Second = ICK_Compatible_Conversion;
1925 FromType = ToType.getUnqualifiedType();
1926 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1927 InOverloadResolution,
1928 SCS, CStyle)) {
1929 SCS.Second = ICK_TransparentUnionConversion;
1930 FromType = ToType;
1931 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1932 CStyle)) {
1933 // tryAtomicConversion has updated the standard conversion sequence
1934 // appropriately.
1935 return true;
1936 } else if (ToType->isEventT() &&
1937 From->isIntegerConstantExpr(S.getASTContext()) &&
1938 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1939 SCS.Second = ICK_Zero_Event_Conversion;
1940 FromType = ToType;
1941 } else if (ToType->isQueueT() &&
1942 From->isIntegerConstantExpr(S.getASTContext()) &&
1943 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1944 SCS.Second = ICK_Zero_Queue_Conversion;
1945 FromType = ToType;
1946 } else if (ToType->isSamplerT() &&
1947 From->isIntegerConstantExpr(S.getASTContext())) {
1948 SCS.Second = ICK_Compatible_Conversion;
1949 FromType = ToType;
1950 } else {
1951 // No second conversion required.
1952 SCS.Second = ICK_Identity;
1953 }
1954 SCS.setToType(1, FromType);
1955
1956 // The third conversion can be a function pointer conversion or a
1957 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1958 bool ObjCLifetimeConversion;
1959 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1960 // Function pointer conversions (removing 'noexcept') including removal of
1961 // 'noreturn' (Clang extension).
1962 SCS.Third = ICK_Function_Conversion;
1963 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1964 ObjCLifetimeConversion)) {
1965 SCS.Third = ICK_Qualification;
1966 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1967 FromType = ToType;
1968 } else {
1969 // No conversion required
1970 SCS.Third = ICK_Identity;
1971 }
1972
1973 // C++ [over.best.ics]p6:
1974 // [...] Any difference in top-level cv-qualification is
1975 // subsumed by the initialization itself and does not constitute
1976 // a conversion. [...]
1977 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1978 QualType CanonTo = S.Context.getCanonicalType(ToType);
1979 if (CanonFrom.getLocalUnqualifiedType()
1980 == CanonTo.getLocalUnqualifiedType() &&
1981 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1982 FromType = ToType;
1983 CanonFrom = CanonTo;
1984 }
1985
1986 SCS.setToType(2, FromType);
1987
1988 if (CanonFrom == CanonTo)
1989 return true;
1990
1991 // If we have not converted the argument type to the parameter type,
1992 // this is a bad conversion sequence, unless we're resolving an overload in C.
1993 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1994 return false;
1995
1996 ExprResult ER = ExprResult{From};
1997 Sema::AssignConvertType Conv =
1998 S.CheckSingleAssignmentConstraints(ToType, ER,
1999 /*Diagnose=*/false,
2000 /*DiagnoseCFAudited=*/false,
2001 /*ConvertRHS=*/false);
2002 ImplicitConversionKind SecondConv;
2003 switch (Conv) {
2004 case Sema::Compatible:
2005 SecondConv = ICK_C_Only_Conversion;
2006 break;
2007 // For our purposes, discarding qualifiers is just as bad as using an
2008 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2009 // qualifiers, as well.
2010 case Sema::CompatiblePointerDiscardsQualifiers:
2011 case Sema::IncompatiblePointer:
2012 case Sema::IncompatiblePointerSign:
2013 SecondConv = ICK_Incompatible_Pointer_Conversion;
2014 break;
2015 default:
2016 return false;
2017 }
2018
2019 // First can only be an lvalue conversion, so we pretend that this was the
2020 // second conversion. First should already be valid from earlier in the
2021 // function.
2022 SCS.Second = SecondConv;
2023 SCS.setToType(1, ToType);
2024
2025 // Third is Identity, because Second should rank us worse than any other
2026 // conversion. This could also be ICK_Qualification, but it's simpler to just
2027 // lump everything in with the second conversion, and we don't gain anything
2028 // from making this ICK_Qualification.
2029 SCS.Third = ICK_Identity;
2030 SCS.setToType(2, ToType);
2031 return true;
2032}
2033
2034static bool
2035IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2036 QualType &ToType,
2037 bool InOverloadResolution,
2038 StandardConversionSequence &SCS,
2039 bool CStyle) {
2040
2041 const RecordType *UT = ToType->getAsUnionType();
2042 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2043 return false;
2044 // The field to initialize within the transparent union.
2045 RecordDecl *UD = UT->getDecl();
2046 // It's compatible if the expression matches any of the fields.
2047 for (const auto *it : UD->fields()) {
2048 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2049 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2050 ToType = it->getType();
2051 return true;
2052 }
2053 }
2054 return false;
2055}
2056
2057/// IsIntegralPromotion - Determines whether the conversion from the
2058/// expression From (whose potentially-adjusted type is FromType) to
2059/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2060/// sets PromotedType to the promoted type.
2061bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2062 const BuiltinType *To = ToType->getAs<BuiltinType>();
2063 // All integers are built-in.
2064 if (!To) {
2065 return false;
2066 }
2067
2068 // An rvalue of type char, signed char, unsigned char, short int, or
2069 // unsigned short int can be converted to an rvalue of type int if
2070 // int can represent all the values of the source type; otherwise,
2071 // the source rvalue can be converted to an rvalue of type unsigned
2072 // int (C++ 4.5p1).
2073 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2074 !FromType->isEnumeralType()) {
2075 if (// We can promote any signed, promotable integer type to an int
2076 (FromType->isSignedIntegerType() ||
2077 // We can promote any unsigned integer type whose size is
2078 // less than int to an int.
2079 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2080 return To->getKind() == BuiltinType::Int;
2081 }
2082
2083 return To->getKind() == BuiltinType::UInt;
2084 }
2085
2086 // C++11 [conv.prom]p3:
2087 // A prvalue of an unscoped enumeration type whose underlying type is not
2088 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2089 // following types that can represent all the values of the enumeration
2090 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2091 // unsigned int, long int, unsigned long int, long long int, or unsigned
2092 // long long int. If none of the types in that list can represent all the
2093 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2094 // type can be converted to an rvalue a prvalue of the extended integer type
2095 // with lowest integer conversion rank (4.13) greater than the rank of long
2096 // long in which all the values of the enumeration can be represented. If
2097 // there are two such extended types, the signed one is chosen.
2098 // C++11 [conv.prom]p4:
2099 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2100 // can be converted to a prvalue of its underlying type. Moreover, if
2101 // integral promotion can be applied to its underlying type, a prvalue of an
2102 // unscoped enumeration type whose underlying type is fixed can also be
2103 // converted to a prvalue of the promoted underlying type.
2104 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2105 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2106 // provided for a scoped enumeration.
2107 if (FromEnumType->getDecl()->isScoped())
2108 return false;
2109
2110 // We can perform an integral promotion to the underlying type of the enum,
2111 // even if that's not the promoted type. Note that the check for promoting
2112 // the underlying type is based on the type alone, and does not consider
2113 // the bitfield-ness of the actual source expression.
2114 if (FromEnumType->getDecl()->isFixed()) {
2115 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2116 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2117 IsIntegralPromotion(nullptr, Underlying, ToType);
2118 }
2119
2120 // We have already pre-calculated the promotion type, so this is trivial.
2121 if (ToType->isIntegerType() &&
2122 isCompleteType(From->getBeginLoc(), FromType))
2123 return Context.hasSameUnqualifiedType(
2124 ToType, FromEnumType->getDecl()->getPromotionType());
2125
2126 // C++ [conv.prom]p5:
2127 // If the bit-field has an enumerated type, it is treated as any other
2128 // value of that type for promotion purposes.
2129 //
2130 // ... so do not fall through into the bit-field checks below in C++.
2131 if (getLangOpts().CPlusPlus)
2132 return false;
2133 }
2134
2135 // C++0x [conv.prom]p2:
2136 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2137 // to an rvalue a prvalue of the first of the following types that can
2138 // represent all the values of its underlying type: int, unsigned int,
2139 // long int, unsigned long int, long long int, or unsigned long long int.
2140 // If none of the types in that list can represent all the values of its
2141 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2142 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2143 // type.
2144 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2145 ToType->isIntegerType()) {
2146 // Determine whether the type we're converting from is signed or
2147 // unsigned.
2148 bool FromIsSigned = FromType->isSignedIntegerType();
2149 uint64_t FromSize = Context.getTypeSize(FromType);
2150
2151 // The types we'll try to promote to, in the appropriate
2152 // order. Try each of these types.
2153 QualType PromoteTypes[6] = {
2154 Context.IntTy, Context.UnsignedIntTy,
2155 Context.LongTy, Context.UnsignedLongTy ,
2156 Context.LongLongTy, Context.UnsignedLongLongTy
2157 };
2158 for (int Idx = 0; Idx < 6; ++Idx) {
2159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2160 if (FromSize < ToSize ||
2161 (FromSize == ToSize &&
2162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2163 // We found the type that we can promote to. If this is the
2164 // type we wanted, we have a promotion. Otherwise, no
2165 // promotion.
2166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2167 }
2168 }
2169 }
2170
2171 // An rvalue for an integral bit-field (9.6) can be converted to an
2172 // rvalue of type int if int can represent all the values of the
2173 // bit-field; otherwise, it can be converted to unsigned int if
2174 // unsigned int can represent all the values of the bit-field. If
2175 // the bit-field is larger yet, no integral promotion applies to
2176 // it. If the bit-field has an enumerated type, it is treated as any
2177 // other value of that type for promotion purposes (C++ 4.5p3).
2178 // FIXME: We should delay checking of bit-fields until we actually perform the
2179 // conversion.
2180 //
2181 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2182 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2183 // bit-fields and those whose underlying type is larger than int) for GCC
2184 // compatibility.
2185 if (From) {
2186 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2187 Optional<llvm::APSInt> BitWidth;
2188 if (FromType->isIntegralType(Context) &&
2189 (BitWidth =
2190 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2191 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2192 ToSize = Context.getTypeSize(ToType);
2193
2194 // Are we promoting to an int from a bitfield that fits in an int?
2195 if (*BitWidth < ToSize ||
2196 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2197 return To->getKind() == BuiltinType::Int;
2198 }
2199
2200 // Are we promoting to an unsigned int from an unsigned bitfield
2201 // that fits into an unsigned int?
2202 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2203 return To->getKind() == BuiltinType::UInt;
2204 }
2205
2206 return false;
2207 }
2208 }
2209 }
2210
2211 // An rvalue of type bool can be converted to an rvalue of type int,
2212 // with false becoming zero and true becoming one (C++ 4.5p4).
2213 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2214 return true;
2215 }
2216
2217 return false;
2218}
2219
2220/// IsFloatingPointPromotion - Determines whether the conversion from
2221/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2222/// returns true and sets PromotedType to the promoted type.
2223bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2226 /// An rvalue of type float can be converted to an rvalue of type
2227 /// double. (C++ 4.6p1).
2228 if (FromBuiltin->getKind() == BuiltinType::Float &&
2229 ToBuiltin->getKind() == BuiltinType::Double)
2230 return true;
2231
2232 // C99 6.3.1.5p1:
2233 // When a float is promoted to double or long double, or a
2234 // double is promoted to long double [...].
2235 if (!getLangOpts().CPlusPlus &&
2236 (FromBuiltin->getKind() == BuiltinType::Float ||
2237 FromBuiltin->getKind() == BuiltinType::Double) &&
2238 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2239 ToBuiltin->getKind() == BuiltinType::Float128))
2240 return true;
2241
2242 // Half can be promoted to float.
2243 if (!getLangOpts().NativeHalfType &&
2244 FromBuiltin->getKind() == BuiltinType::Half &&
2245 ToBuiltin->getKind() == BuiltinType::Float)
2246 return true;
2247 }
2248
2249 return false;
2250}
2251
2252/// Determine if a conversion is a complex promotion.
2253///
2254/// A complex promotion is defined as a complex -> complex conversion
2255/// where the conversion between the underlying real types is a
2256/// floating-point or integral promotion.
2257bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2258 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2259 if (!FromComplex)
2260 return false;
2261
2262 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2263 if (!ToComplex)
2264 return false;
2265
2266 return IsFloatingPointPromotion(FromComplex->getElementType(),
2267 ToComplex->getElementType()) ||
2268 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2269 ToComplex->getElementType());
2270}
2271
2272/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2273/// the pointer type FromPtr to a pointer to type ToPointee, with the
2274/// same type qualifiers as FromPtr has on its pointee type. ToType,
2275/// if non-empty, will be a pointer to ToType that may or may not have
2276/// the right set of qualifiers on its pointee.
2277///
2278static QualType
2279BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2280 QualType ToPointee, QualType ToType,
2281 ASTContext &Context,
2282 bool StripObjCLifetime = false) {
2283 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 2285, __PRETTY_FUNCTION__))
2284 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 2285, __PRETTY_FUNCTION__))
2285 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 2285, __PRETTY_FUNCTION__))
;
2286
2287 /// Conversions to 'id' subsume cv-qualifier conversions.
2288 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2289 return ToType.getUnqualifiedType();
2290
2291 QualType CanonFromPointee
2292 = Context.getCanonicalType(FromPtr->getPointeeType());
2293 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2294 Qualifiers Quals = CanonFromPointee.getQualifiers();
2295
2296 if (StripObjCLifetime)
2297 Quals.removeObjCLifetime();
2298
2299 // Exact qualifier match -> return the pointer type we're converting to.
2300 if (CanonToPointee.getLocalQualifiers() == Quals) {
2301 // ToType is exactly what we need. Return it.
2302 if (!ToType.isNull())
2303 return ToType.getUnqualifiedType();
2304
2305 // Build a pointer to ToPointee. It has the right qualifiers
2306 // already.
2307 if (isa<ObjCObjectPointerType>(ToType))
2308 return Context.getObjCObjectPointerType(ToPointee);
2309 return Context.getPointerType(ToPointee);
2310 }
2311
2312 // Just build a canonical type that has the right qualifiers.
2313 QualType QualifiedCanonToPointee
2314 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2315
2316 if (isa<ObjCObjectPointerType>(ToType))
2317 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2318 return Context.getPointerType(QualifiedCanonToPointee);
2319}
2320
2321static bool isNullPointerConstantForConversion(Expr *Expr,
2322 bool InOverloadResolution,
2323 ASTContext &Context) {
2324 // Handle value-dependent integral null pointer constants correctly.
2325 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2326 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2327 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2328 return !InOverloadResolution;
2329
2330 return Expr->isNullPointerConstant(Context,
2331 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2332 : Expr::NPC_ValueDependentIsNull);
2333}
2334
2335/// IsPointerConversion - Determines whether the conversion of the
2336/// expression From, which has the (possibly adjusted) type FromType,
2337/// can be converted to the type ToType via a pointer conversion (C++
2338/// 4.10). If so, returns true and places the converted type (that
2339/// might differ from ToType in its cv-qualifiers at some level) into
2340/// ConvertedType.
2341///
2342/// This routine also supports conversions to and from block pointers
2343/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2344/// pointers to interfaces. FIXME: Once we've determined the
2345/// appropriate overloading rules for Objective-C, we may want to
2346/// split the Objective-C checks into a different routine; however,
2347/// GCC seems to consider all of these conversions to be pointer
2348/// conversions, so for now they live here. IncompatibleObjC will be
2349/// set if the conversion is an allowed Objective-C conversion that
2350/// should result in a warning.
2351bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2352 bool InOverloadResolution,
2353 QualType& ConvertedType,
2354 bool &IncompatibleObjC) {
2355 IncompatibleObjC = false;
2356 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2357 IncompatibleObjC))
2358 return true;
2359
2360 // Conversion from a null pointer constant to any Objective-C pointer type.
2361 if (ToType->isObjCObjectPointerType() &&
2362 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2363 ConvertedType = ToType;
2364 return true;
2365 }
2366
2367 // Blocks: Block pointers can be converted to void*.
2368 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2369 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2370 ConvertedType = ToType;
2371 return true;
2372 }
2373 // Blocks: A null pointer constant can be converted to a block
2374 // pointer type.
2375 if (ToType->isBlockPointerType() &&
2376 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2377 ConvertedType = ToType;
2378 return true;
2379 }
2380
2381 // If the left-hand-side is nullptr_t, the right side can be a null
2382 // pointer constant.
2383 if (ToType->isNullPtrType() &&
2384 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385 ConvertedType = ToType;
2386 return true;
2387 }
2388
2389 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2390 if (!ToTypePtr)
2391 return false;
2392
2393 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2394 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2395 ConvertedType = ToType;
2396 return true;
2397 }
2398
2399 // Beyond this point, both types need to be pointers
2400 // , including objective-c pointers.
2401 QualType ToPointeeType = ToTypePtr->getPointeeType();
2402 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2403 !getLangOpts().ObjCAutoRefCount) {
2404 ConvertedType = BuildSimilarlyQualifiedPointerType(
2405 FromType->getAs<ObjCObjectPointerType>(),
2406 ToPointeeType,
2407 ToType, Context);
2408 return true;
2409 }
2410 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2411 if (!FromTypePtr)
2412 return false;
2413
2414 QualType FromPointeeType = FromTypePtr->getPointeeType();
2415
2416 // If the unqualified pointee types are the same, this can't be a
2417 // pointer conversion, so don't do all of the work below.
2418 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2419 return false;
2420
2421 // An rvalue of type "pointer to cv T," where T is an object type,
2422 // can be converted to an rvalue of type "pointer to cv void" (C++
2423 // 4.10p2).
2424 if (FromPointeeType->isIncompleteOrObjectType() &&
2425 ToPointeeType->isVoidType()) {
2426 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427 ToPointeeType,
2428 ToType, Context,
2429 /*StripObjCLifetime=*/true);
2430 return true;
2431 }
2432
2433 // MSVC allows implicit function to void* type conversion.
2434 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2435 ToPointeeType->isVoidType()) {
2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437 ToPointeeType,
2438 ToType, Context);
2439 return true;
2440 }
2441
2442 // When we're overloading in C, we allow a special kind of pointer
2443 // conversion for compatible-but-not-identical pointee types.
2444 if (!getLangOpts().CPlusPlus &&
2445 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2446 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2447 ToPointeeType,
2448 ToType, Context);
2449 return true;
2450 }
2451
2452 // C++ [conv.ptr]p3:
2453 //
2454 // An rvalue of type "pointer to cv D," where D is a class type,
2455 // can be converted to an rvalue of type "pointer to cv B," where
2456 // B is a base class (clause 10) of D. If B is an inaccessible
2457 // (clause 11) or ambiguous (10.2) base class of D, a program that
2458 // necessitates this conversion is ill-formed. The result of the
2459 // conversion is a pointer to the base class sub-object of the
2460 // derived class object. The null pointer value is converted to
2461 // the null pointer value of the destination type.
2462 //
2463 // Note that we do not check for ambiguity or inaccessibility
2464 // here. That is handled by CheckPointerConversion.
2465 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2466 ToPointeeType->isRecordType() &&
2467 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2468 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2470 ToPointeeType,
2471 ToType, Context);
2472 return true;
2473 }
2474
2475 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2476 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478 ToPointeeType,
2479 ToType, Context);
2480 return true;
2481 }
2482
2483 return false;
2484}
2485
2486/// Adopt the given qualifiers for the given type.
2487static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2488 Qualifiers TQs = T.getQualifiers();
2489
2490 // Check whether qualifiers already match.
2491 if (TQs == Qs)
2492 return T;
2493
2494 if (Qs.compatiblyIncludes(TQs))
2495 return Context.getQualifiedType(T, Qs);
2496
2497 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2498}
2499
2500/// isObjCPointerConversion - Determines whether this is an
2501/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2502/// with the same arguments and return values.
2503bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2504 QualType& ConvertedType,
2505 bool &IncompatibleObjC) {
2506 if (!getLangOpts().ObjC)
2507 return false;
2508
2509 // The set of qualifiers on the type we're converting from.
2510 Qualifiers FromQualifiers = FromType.getQualifiers();
2511
2512 // First, we handle all conversions on ObjC object pointer types.
2513 const ObjCObjectPointerType* ToObjCPtr =
2514 ToType->getAs<ObjCObjectPointerType>();
2515 const ObjCObjectPointerType *FromObjCPtr =
2516 FromType->getAs<ObjCObjectPointerType>();
2517
2518 if (ToObjCPtr && FromObjCPtr) {
2519 // If the pointee types are the same (ignoring qualifications),
2520 // then this is not a pointer conversion.
2521 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2522 FromObjCPtr->getPointeeType()))
2523 return false;
2524
2525 // Conversion between Objective-C pointers.
2526 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2527 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2528 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2529 if (getLangOpts().CPlusPlus && LHS && RHS &&
2530 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2531 FromObjCPtr->getPointeeType()))
2532 return false;
2533 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2534 ToObjCPtr->getPointeeType(),
2535 ToType, Context);
2536 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2537 return true;
2538 }
2539
2540 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2541 // Okay: this is some kind of implicit downcast of Objective-C
2542 // interfaces, which is permitted. However, we're going to
2543 // complain about it.
2544 IncompatibleObjC = true;
2545 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2546 ToObjCPtr->getPointeeType(),
2547 ToType, Context);
2548 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2549 return true;
2550 }
2551 }
2552 // Beyond this point, both types need to be C pointers or block pointers.
2553 QualType ToPointeeType;
2554 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2555 ToPointeeType = ToCPtr->getPointeeType();
2556 else if (const BlockPointerType *ToBlockPtr =
2557 ToType->getAs<BlockPointerType>()) {
2558 // Objective C++: We're able to convert from a pointer to any object
2559 // to a block pointer type.
2560 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2561 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562 return true;
2563 }
2564 ToPointeeType = ToBlockPtr->getPointeeType();
2565 }
2566 else if (FromType->getAs<BlockPointerType>() &&
2567 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2568 // Objective C++: We're able to convert from a block pointer type to a
2569 // pointer to any object.
2570 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2571 return true;
2572 }
2573 else
2574 return false;
2575
2576 QualType FromPointeeType;
2577 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2578 FromPointeeType = FromCPtr->getPointeeType();
2579 else if (const BlockPointerType *FromBlockPtr =
2580 FromType->getAs<BlockPointerType>())
2581 FromPointeeType = FromBlockPtr->getPointeeType();
2582 else
2583 return false;
2584
2585 // If we have pointers to pointers, recursively check whether this
2586 // is an Objective-C conversion.
2587 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2588 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2589 IncompatibleObjC)) {
2590 // We always complain about this conversion.
2591 IncompatibleObjC = true;
2592 ConvertedType = Context.getPointerType(ConvertedType);
2593 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2594 return true;
2595 }
2596 // Allow conversion of pointee being objective-c pointer to another one;
2597 // as in I* to id.
2598 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2599 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2600 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2601 IncompatibleObjC)) {
2602
2603 ConvertedType = Context.getPointerType(ConvertedType);
2604 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2605 return true;
2606 }
2607
2608 // If we have pointers to functions or blocks, check whether the only
2609 // differences in the argument and result types are in Objective-C
2610 // pointer conversions. If so, we permit the conversion (but
2611 // complain about it).
2612 const FunctionProtoType *FromFunctionType
2613 = FromPointeeType->getAs<FunctionProtoType>();
2614 const FunctionProtoType *ToFunctionType
2615 = ToPointeeType->getAs<FunctionProtoType>();
2616 if (FromFunctionType && ToFunctionType) {
2617 // If the function types are exactly the same, this isn't an
2618 // Objective-C pointer conversion.
2619 if (Context.getCanonicalType(FromPointeeType)
2620 == Context.getCanonicalType(ToPointeeType))
2621 return false;
2622
2623 // Perform the quick checks that will tell us whether these
2624 // function types are obviously different.
2625 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2626 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2627 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2628 return false;
2629
2630 bool HasObjCConversion = false;
2631 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2632 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2633 // Okay, the types match exactly. Nothing to do.
2634 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2635 ToFunctionType->getReturnType(),
2636 ConvertedType, IncompatibleObjC)) {
2637 // Okay, we have an Objective-C pointer conversion.
2638 HasObjCConversion = true;
2639 } else {
2640 // Function types are too different. Abort.
2641 return false;
2642 }
2643
2644 // Check argument types.
2645 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2646 ArgIdx != NumArgs; ++ArgIdx) {
2647 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2648 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2649 if (Context.getCanonicalType(FromArgType)
2650 == Context.getCanonicalType(ToArgType)) {
2651 // Okay, the types match exactly. Nothing to do.
2652 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2653 ConvertedType, IncompatibleObjC)) {
2654 // Okay, we have an Objective-C pointer conversion.
2655 HasObjCConversion = true;
2656 } else {
2657 // Argument types are too different. Abort.
2658 return false;
2659 }
2660 }
2661
2662 if (HasObjCConversion) {
2663 // We had an Objective-C conversion. Allow this pointer
2664 // conversion, but complain about it.
2665 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2666 IncompatibleObjC = true;
2667 return true;
2668 }
2669 }
2670
2671 return false;
2672}
2673
2674/// Determine whether this is an Objective-C writeback conversion,
2675/// used for parameter passing when performing automatic reference counting.
2676///
2677/// \param FromType The type we're converting form.
2678///
2679/// \param ToType The type we're converting to.
2680///
2681/// \param ConvertedType The type that will be produced after applying
2682/// this conversion.
2683bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2684 QualType &ConvertedType) {
2685 if (!getLangOpts().ObjCAutoRefCount ||
2686 Context.hasSameUnqualifiedType(FromType, ToType))
2687 return false;
2688
2689 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2690 QualType ToPointee;
2691 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2692 ToPointee = ToPointer->getPointeeType();
2693 else
2694 return false;
2695
2696 Qualifiers ToQuals = ToPointee.getQualifiers();
2697 if (!ToPointee->isObjCLifetimeType() ||
2698 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2699 !ToQuals.withoutObjCLifetime().empty())
2700 return false;
2701
2702 // Argument must be a pointer to __strong to __weak.
2703 QualType FromPointee;
2704 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2705 FromPointee = FromPointer->getPointeeType();
2706 else
2707 return false;
2708
2709 Qualifiers FromQuals = FromPointee.getQualifiers();
2710 if (!FromPointee->isObjCLifetimeType() ||
2711 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2712 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2713 return false;
2714
2715 // Make sure that we have compatible qualifiers.
2716 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2717 if (!ToQuals.compatiblyIncludes(FromQuals))
2718 return false;
2719
2720 // Remove qualifiers from the pointee type we're converting from; they
2721 // aren't used in the compatibility check belong, and we'll be adding back
2722 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2723 FromPointee = FromPointee.getUnqualifiedType();
2724
2725 // The unqualified form of the pointee types must be compatible.
2726 ToPointee = ToPointee.getUnqualifiedType();
2727 bool IncompatibleObjC;
2728 if (Context.typesAreCompatible(FromPointee, ToPointee))
2729 FromPointee = ToPointee;
2730 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2731 IncompatibleObjC))
2732 return false;
2733
2734 /// Construct the type we're converting to, which is a pointer to
2735 /// __autoreleasing pointee.
2736 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2737 ConvertedType = Context.getPointerType(FromPointee);
2738 return true;
2739}
2740
2741bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2742 QualType& ConvertedType) {
2743 QualType ToPointeeType;
2744 if (const BlockPointerType *ToBlockPtr =
2745 ToType->getAs<BlockPointerType>())
2746 ToPointeeType = ToBlockPtr->getPointeeType();
2747 else
2748 return false;
2749
2750 QualType FromPointeeType;
2751 if (const BlockPointerType *FromBlockPtr =
2752 FromType->getAs<BlockPointerType>())
2753 FromPointeeType = FromBlockPtr->getPointeeType();
2754 else
2755 return false;
2756 // We have pointer to blocks, check whether the only
2757 // differences in the argument and result types are in Objective-C
2758 // pointer conversions. If so, we permit the conversion.
2759
2760 const FunctionProtoType *FromFunctionType
2761 = FromPointeeType->getAs<FunctionProtoType>();
2762 const FunctionProtoType *ToFunctionType
2763 = ToPointeeType->getAs<FunctionProtoType>();
2764
2765 if (!FromFunctionType || !ToFunctionType)
2766 return false;
2767
2768 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2769 return true;
2770
2771 // Perform the quick checks that will tell us whether these
2772 // function types are obviously different.
2773 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2774 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2775 return false;
2776
2777 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2778 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2779 if (FromEInfo != ToEInfo)
2780 return false;
2781
2782 bool IncompatibleObjC = false;
2783 if (Context.hasSameType(FromFunctionType->getReturnType(),
2784 ToFunctionType->getReturnType())) {
2785 // Okay, the types match exactly. Nothing to do.
2786 } else {
2787 QualType RHS = FromFunctionType->getReturnType();
2788 QualType LHS = ToFunctionType->getReturnType();
2789 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2790 !RHS.hasQualifiers() && LHS.hasQualifiers())
2791 LHS = LHS.getUnqualifiedType();
2792
2793 if (Context.hasSameType(RHS,LHS)) {
2794 // OK exact match.
2795 } else if (isObjCPointerConversion(RHS, LHS,
2796 ConvertedType, IncompatibleObjC)) {
2797 if (IncompatibleObjC)
2798 return false;
2799 // Okay, we have an Objective-C pointer conversion.
2800 }
2801 else
2802 return false;
2803 }
2804
2805 // Check argument types.
2806 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2807 ArgIdx != NumArgs; ++ArgIdx) {
2808 IncompatibleObjC = false;
2809 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2810 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2811 if (Context.hasSameType(FromArgType, ToArgType)) {
2812 // Okay, the types match exactly. Nothing to do.
2813 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2814 ConvertedType, IncompatibleObjC)) {
2815 if (IncompatibleObjC)
2816 return false;
2817 // Okay, we have an Objective-C pointer conversion.
2818 } else
2819 // Argument types are too different. Abort.
2820 return false;
2821 }
2822
2823 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2824 bool CanUseToFPT, CanUseFromFPT;
2825 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2826 CanUseToFPT, CanUseFromFPT,
2827 NewParamInfos))
2828 return false;
2829
2830 ConvertedType = ToType;
2831 return true;
2832}
2833
2834enum {
2835 ft_default,
2836 ft_different_class,
2837 ft_parameter_arity,
2838 ft_parameter_mismatch,
2839 ft_return_type,
2840 ft_qualifer_mismatch,
2841 ft_noexcept
2842};
2843
2844/// Attempts to get the FunctionProtoType from a Type. Handles
2845/// MemberFunctionPointers properly.
2846static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2847 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2848 return FPT;
2849
2850 if (auto *MPT = FromType->getAs<MemberPointerType>())
2851 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2852
2853 return nullptr;
2854}
2855
2856/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2857/// function types. Catches different number of parameter, mismatch in
2858/// parameter types, and different return types.
2859void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2860 QualType FromType, QualType ToType) {
2861 // If either type is not valid, include no extra info.
2862 if (FromType.isNull() || ToType.isNull()) {
2863 PDiag << ft_default;
2864 return;
2865 }
2866
2867 // Get the function type from the pointers.
2868 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2869 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2870 *ToMember = ToType->castAs<MemberPointerType>();
2871 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2872 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2873 << QualType(FromMember->getClass(), 0);
2874 return;
2875 }
2876 FromType = FromMember->getPointeeType();
2877 ToType = ToMember->getPointeeType();
2878 }
2879
2880 if (FromType->isPointerType())
2881 FromType = FromType->getPointeeType();
2882 if (ToType->isPointerType())
2883 ToType = ToType->getPointeeType();
2884
2885 // Remove references.
2886 FromType = FromType.getNonReferenceType();
2887 ToType = ToType.getNonReferenceType();
2888
2889 // Don't print extra info for non-specialized template functions.
2890 if (FromType->isInstantiationDependentType() &&
2891 !FromType->getAs<TemplateSpecializationType>()) {
2892 PDiag << ft_default;
2893 return;
2894 }
2895
2896 // No extra info for same types.
2897 if (Context.hasSameType(FromType, ToType)) {
2898 PDiag << ft_default;
2899 return;
2900 }
2901
2902 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2903 *ToFunction = tryGetFunctionProtoType(ToType);
2904
2905 // Both types need to be function types.
2906 if (!FromFunction || !ToFunction) {
2907 PDiag << ft_default;
2908 return;
2909 }
2910
2911 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2912 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2913 << FromFunction->getNumParams();
2914 return;
2915 }
2916
2917 // Handle different parameter types.
2918 unsigned ArgPos;
2919 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2920 PDiag << ft_parameter_mismatch << ArgPos + 1
2921 << ToFunction->getParamType(ArgPos)
2922 << FromFunction->getParamType(ArgPos);
2923 return;
2924 }
2925
2926 // Handle different return type.
2927 if (!Context.hasSameType(FromFunction->getReturnType(),
2928 ToFunction->getReturnType())) {
2929 PDiag << ft_return_type << ToFunction->getReturnType()
2930 << FromFunction->getReturnType();
2931 return;
2932 }
2933
2934 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2935 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2936 << FromFunction->getMethodQuals();
2937 return;
2938 }
2939
2940 // Handle exception specification differences on canonical type (in C++17
2941 // onwards).
2942 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2943 ->isNothrow() !=
2944 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2945 ->isNothrow()) {
2946 PDiag << ft_noexcept;
2947 return;
2948 }
2949
2950 // Unable to find a difference, so add no extra info.
2951 PDiag << ft_default;
2952}
2953
2954/// FunctionParamTypesAreEqual - This routine checks two function proto types
2955/// for equality of their argument types. Caller has already checked that
2956/// they have same number of arguments. If the parameters are different,
2957/// ArgPos will have the parameter index of the first different parameter.
2958bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2959 const FunctionProtoType *NewType,
2960 unsigned *ArgPos) {
2961 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2962 N = NewType->param_type_begin(),
2963 E = OldType->param_type_end();
2964 O && (O != E); ++O, ++N) {
2965 // Ignore address spaces in pointee type. This is to disallow overloading
2966 // on __ptr32/__ptr64 address spaces.
2967 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2968 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2969
2970 if (!Context.hasSameType(Old, New)) {
2971 if (ArgPos)
2972 *ArgPos = O - OldType->param_type_begin();
2973 return false;
2974 }
2975 }
2976 return true;
2977}
2978
2979/// CheckPointerConversion - Check the pointer conversion from the
2980/// expression From to the type ToType. This routine checks for
2981/// ambiguous or inaccessible derived-to-base pointer
2982/// conversions for which IsPointerConversion has already returned
2983/// true. It returns true and produces a diagnostic if there was an
2984/// error, or returns false otherwise.
2985bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2986 CastKind &Kind,
2987 CXXCastPath& BasePath,
2988 bool IgnoreBaseAccess,
2989 bool Diagnose) {
2990 QualType FromType = From->getType();
2991 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2992
2993 Kind = CK_BitCast;
2994
2995 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2996 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2997 Expr::NPCK_ZeroExpression) {
2998 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2999 DiagRuntimeBehavior(From->getExprLoc(), From,
3000 PDiag(diag::warn_impcast_bool_to_null_pointer)
3001 << ToType << From->getSourceRange());
3002 else if (!isUnevaluatedContext())
3003 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3004 << ToType << From->getSourceRange();
3005 }
3006 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3007 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3008 QualType FromPointeeType = FromPtrType->getPointeeType(),
3009 ToPointeeType = ToPtrType->getPointeeType();
3010
3011 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3012 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3013 // We must have a derived-to-base conversion. Check an
3014 // ambiguous or inaccessible conversion.
3015 unsigned InaccessibleID = 0;
3016 unsigned AmbiguousID = 0;
3017 if (Diagnose) {
3018 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3019 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3020 }
3021 if (CheckDerivedToBaseConversion(
3022 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3023 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3024 &BasePath, IgnoreBaseAccess))
3025 return true;
3026
3027 // The conversion was successful.
3028 Kind = CK_DerivedToBase;
3029 }
3030
3031 if (Diagnose && !IsCStyleOrFunctionalCast &&
3032 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3033 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3034, __PRETTY_FUNCTION__))
3034 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3034, __PRETTY_FUNCTION__))
;
3035 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3036 << From->getSourceRange();
3037 }
3038 }
3039 } else if (const ObjCObjectPointerType *ToPtrType =
3040 ToType->getAs<ObjCObjectPointerType>()) {
3041 if (const ObjCObjectPointerType *FromPtrType =
3042 FromType->getAs<ObjCObjectPointerType>()) {
3043 // Objective-C++ conversions are always okay.
3044 // FIXME: We should have a different class of conversions for the
3045 // Objective-C++ implicit conversions.
3046 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3047 return false;
3048 } else if (FromType->isBlockPointerType()) {
3049 Kind = CK_BlockPointerToObjCPointerCast;
3050 } else {
3051 Kind = CK_CPointerToObjCPointerCast;
3052 }
3053 } else if (ToType->isBlockPointerType()) {
3054 if (!FromType->isBlockPointerType())
3055 Kind = CK_AnyPointerToBlockPointerCast;
3056 }
3057
3058 // We shouldn't fall into this case unless it's valid for other
3059 // reasons.
3060 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3061 Kind = CK_NullToPointer;
3062
3063 return false;
3064}
3065
3066/// IsMemberPointerConversion - Determines whether the conversion of the
3067/// expression From, which has the (possibly adjusted) type FromType, can be
3068/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3069/// If so, returns true and places the converted type (that might differ from
3070/// ToType in its cv-qualifiers at some level) into ConvertedType.
3071bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3072 QualType ToType,
3073 bool InOverloadResolution,
3074 QualType &ConvertedType) {
3075 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3076 if (!ToTypePtr)
3077 return false;
3078
3079 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3080 if (From->isNullPointerConstant(Context,
3081 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082 : Expr::NPC_ValueDependentIsNull)) {
3083 ConvertedType = ToType;
3084 return true;
3085 }
3086
3087 // Otherwise, both types have to be member pointers.
3088 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3089 if (!FromTypePtr)
3090 return false;
3091
3092 // A pointer to member of B can be converted to a pointer to member of D,
3093 // where D is derived from B (C++ 4.11p2).
3094 QualType FromClass(FromTypePtr->getClass(), 0);
3095 QualType ToClass(ToTypePtr->getClass(), 0);
3096
3097 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3098 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3099 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3100 ToClass.getTypePtr());
3101 return true;
3102 }
3103
3104 return false;
3105}
3106
3107/// CheckMemberPointerConversion - Check the member pointer conversion from the
3108/// expression From to the type ToType. This routine checks for ambiguous or
3109/// virtual or inaccessible base-to-derived member pointer conversions
3110/// for which IsMemberPointerConversion has already returned true. It returns
3111/// true and produces a diagnostic if there was an error, or returns false
3112/// otherwise.
3113bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3114 CastKind &Kind,
3115 CXXCastPath &BasePath,
3116 bool IgnoreBaseAccess) {
3117 QualType FromType = From->getType();
3118 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3119 if (!FromPtrType) {
3120 // This must be a null pointer to member pointer conversion
3121 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
3122 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
3123 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
;
3124 Kind = CK_NullToMemberPointer;
3125 return false;
3126 }
3127
3128 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3129 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3130, __PRETTY_FUNCTION__))
3130 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3130, __PRETTY_FUNCTION__))
;
3131
3132 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3133 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3134
3135 // FIXME: What about dependent types?
3136 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3136, __PRETTY_FUNCTION__))
;
3137 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3137, __PRETTY_FUNCTION__))
;
3138
3139 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140 /*DetectVirtual=*/true);
3141 bool DerivationOkay =
3142 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3143 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3144, __PRETTY_FUNCTION__))
3144 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3144, __PRETTY_FUNCTION__))
;
3145 (void)DerivationOkay;
3146
3147 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3148 getUnqualifiedType())) {
3149 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3150 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3151 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3152 return true;
3153 }
3154
3155 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3156 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3157 << FromClass << ToClass << QualType(VBase, 0)
3158 << From->getSourceRange();
3159 return true;
3160 }
3161
3162 if (!IgnoreBaseAccess)
3163 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3164 Paths.front(),
3165 diag::err_downcast_from_inaccessible_base);
3166
3167 // Must be a base to derived member conversion.
3168 BuildBasePathArray(Paths, BasePath);
3169 Kind = CK_BaseToDerivedMemberPointer;
3170 return false;
3171}
3172
3173/// Determine whether the lifetime conversion between the two given
3174/// qualifiers sets is nontrivial.
3175static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3176 Qualifiers ToQuals) {
3177 // Converting anything to const __unsafe_unretained is trivial.
3178 if (ToQuals.hasConst() &&
3179 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3180 return false;
3181
3182 return true;
3183}
3184
3185/// Perform a single iteration of the loop for checking if a qualification
3186/// conversion is valid.
3187///
3188/// Specifically, check whether any change between the qualifiers of \p
3189/// FromType and \p ToType is permissible, given knowledge about whether every
3190/// outer layer is const-qualified.
3191static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3192 bool CStyle, bool IsTopLevel,
3193 bool &PreviousToQualsIncludeConst,
3194 bool &ObjCLifetimeConversion) {
3195 Qualifiers FromQuals = FromType.getQualifiers();
3196 Qualifiers ToQuals = ToType.getQualifiers();
3197
3198 // Ignore __unaligned qualifier if this type is void.
3199 if (ToType.getUnqualifiedType()->isVoidType())
3200 FromQuals.removeUnaligned();
3201
3202 // Objective-C ARC:
3203 // Check Objective-C lifetime conversions.
3204 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3205 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3206 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3207 ObjCLifetimeConversion = true;
3208 FromQuals.removeObjCLifetime();
3209 ToQuals.removeObjCLifetime();
3210 } else {
3211 // Qualification conversions cannot cast between different
3212 // Objective-C lifetime qualifiers.
3213 return false;
3214 }
3215 }
3216
3217 // Allow addition/removal of GC attributes but not changing GC attributes.
3218 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3219 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3220 FromQuals.removeObjCGCAttr();
3221 ToQuals.removeObjCGCAttr();
3222 }
3223
3224 // -- for every j > 0, if const is in cv 1,j then const is in cv
3225 // 2,j, and similarly for volatile.
3226 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3227 return false;
3228
3229 // If address spaces mismatch:
3230 // - in top level it is only valid to convert to addr space that is a
3231 // superset in all cases apart from C-style casts where we allow
3232 // conversions between overlapping address spaces.
3233 // - in non-top levels it is not a valid conversion.
3234 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3235 (!IsTopLevel ||
3236 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3237 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3238 return false;
3239
3240 // -- if the cv 1,j and cv 2,j are different, then const is in
3241 // every cv for 0 < k < j.
3242 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3243 !PreviousToQualsIncludeConst)
3244 return false;
3245
3246 // Keep track of whether all prior cv-qualifiers in the "to" type
3247 // include const.
3248 PreviousToQualsIncludeConst =
3249 PreviousToQualsIncludeConst && ToQuals.hasConst();
3250 return true;
3251}
3252
3253/// IsQualificationConversion - Determines whether the conversion from
3254/// an rvalue of type FromType to ToType is a qualification conversion
3255/// (C++ 4.4).
3256///
3257/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3258/// when the qualification conversion involves a change in the Objective-C
3259/// object lifetime.
3260bool
3261Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3262 bool CStyle, bool &ObjCLifetimeConversion) {
3263 FromType = Context.getCanonicalType(FromType);
3264 ToType = Context.getCanonicalType(ToType);
3265 ObjCLifetimeConversion = false;
3266
3267 // If FromType and ToType are the same type, this is not a
3268 // qualification conversion.
3269 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3270 return false;
3271
3272 // (C++ 4.4p4):
3273 // A conversion can add cv-qualifiers at levels other than the first
3274 // in multi-level pointers, subject to the following rules: [...]
3275 bool PreviousToQualsIncludeConst = true;
3276 bool UnwrappedAnyPointer = false;
3277 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3278 if (!isQualificationConversionStep(
3279 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3280 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3281 return false;
3282 UnwrappedAnyPointer = true;
3283 }
3284
3285 // We are left with FromType and ToType being the pointee types
3286 // after unwrapping the original FromType and ToType the same number
3287 // of times. If we unwrapped any pointers, and if FromType and
3288 // ToType have the same unqualified type (since we checked
3289 // qualifiers above), then this is a qualification conversion.
3290 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3291}
3292
3293/// - Determine whether this is a conversion from a scalar type to an
3294/// atomic type.
3295///
3296/// If successful, updates \c SCS's second and third steps in the conversion
3297/// sequence to finish the conversion.
3298static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3299 bool InOverloadResolution,
3300 StandardConversionSequence &SCS,
3301 bool CStyle) {
3302 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3303 if (!ToAtomic)
3304 return false;
3305
3306 StandardConversionSequence InnerSCS;
3307 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3308 InOverloadResolution, InnerSCS,
3309 CStyle, /*AllowObjCWritebackConversion=*/false))
3310 return false;
3311
3312 SCS.Second = InnerSCS.Second;
3313 SCS.setToType(1, InnerSCS.getToType(1));
3314 SCS.Third = InnerSCS.Third;
3315 SCS.QualificationIncludesObjCLifetime
3316 = InnerSCS.QualificationIncludesObjCLifetime;
3317 SCS.setToType(2, InnerSCS.getToType(2));
3318 return true;
3319}
3320
3321static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3322 CXXConstructorDecl *Constructor,
3323 QualType Type) {
3324 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3325 if (CtorType->getNumParams() > 0) {
3326 QualType FirstArg = CtorType->getParamType(0);
3327 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3328 return true;
3329 }
3330 return false;
3331}
3332
3333static OverloadingResult
3334IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3335 CXXRecordDecl *To,
3336 UserDefinedConversionSequence &User,
3337 OverloadCandidateSet &CandidateSet,
3338 bool AllowExplicit) {
3339 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340 for (auto *D : S.LookupConstructors(To)) {
3341 auto Info = getConstructorInfo(D);
3342 if (!Info)
3343 continue;
3344
3345 bool Usable = !Info.Constructor->isInvalidDecl() &&
3346 S.isInitListConstructor(Info.Constructor);
3347 if (Usable) {
3348 // If the first argument is (a reference to) the target type,
3349 // suppress conversions.
3350 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3351 S.Context, Info.Constructor, ToType);
3352 if (Info.ConstructorTmpl)
3353 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3354 /*ExplicitArgs*/ nullptr, From,
3355 CandidateSet, SuppressUserConversions,
3356 /*PartialOverloading*/ false,
3357 AllowExplicit);
3358 else
3359 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3360 CandidateSet, SuppressUserConversions,
3361 /*PartialOverloading*/ false, AllowExplicit);
3362 }
3363 }
3364
3365 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3366
3367 OverloadCandidateSet::iterator Best;
3368 switch (auto Result =
3369 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3370 case OR_Deleted:
3371 case OR_Success: {
3372 // Record the standard conversion we used and the conversion function.
3373 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3374 QualType ThisType = Constructor->getThisType();
3375 // Initializer lists don't have conversions as such.
3376 User.Before.setAsIdentityConversion();
3377 User.HadMultipleCandidates = HadMultipleCandidates;
3378 User.ConversionFunction = Constructor;
3379 User.FoundConversionFunction = Best->FoundDecl;
3380 User.After.setAsIdentityConversion();
3381 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3382 User.After.setAllToTypes(ToType);
3383 return Result;
3384 }
3385
3386 case OR_No_Viable_Function:
3387 return OR_No_Viable_Function;
3388 case OR_Ambiguous:
3389 return OR_Ambiguous;
3390 }
3391
3392 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3392)
;
3393}
3394
3395/// Determines whether there is a user-defined conversion sequence
3396/// (C++ [over.ics.user]) that converts expression From to the type
3397/// ToType. If such a conversion exists, User will contain the
3398/// user-defined conversion sequence that performs such a conversion
3399/// and this routine will return true. Otherwise, this routine returns
3400/// false and User is unspecified.
3401///
3402/// \param AllowExplicit true if the conversion should consider C++0x
3403/// "explicit" conversion functions as well as non-explicit conversion
3404/// functions (C++0x [class.conv.fct]p2).
3405///
3406/// \param AllowObjCConversionOnExplicit true if the conversion should
3407/// allow an extra Objective-C pointer conversion on uses of explicit
3408/// constructors. Requires \c AllowExplicit to also be set.
3409static OverloadingResult
3410IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3411 UserDefinedConversionSequence &User,
3412 OverloadCandidateSet &CandidateSet,
3413 AllowedExplicit AllowExplicit,
3414 bool AllowObjCConversionOnExplicit) {
3415 assert(AllowExplicit != AllowedExplicit::None ||((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3416, __PRETTY_FUNCTION__))
3416 !AllowObjCConversionOnExplicit)((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3416, __PRETTY_FUNCTION__))
;
3417 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3418
3419 // Whether we will only visit constructors.
3420 bool ConstructorsOnly = false;
3421
3422 // If the type we are conversion to is a class type, enumerate its
3423 // constructors.
3424 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3425 // C++ [over.match.ctor]p1:
3426 // When objects of class type are direct-initialized (8.5), or
3427 // copy-initialized from an expression of the same or a
3428 // derived class type (8.5), overload resolution selects the
3429 // constructor. [...] For copy-initialization, the candidate
3430 // functions are all the converting constructors (12.3.1) of
3431 // that class. The argument list is the expression-list within
3432 // the parentheses of the initializer.
3433 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3434 (From->getType()->getAs<RecordType>() &&
3435 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3436 ConstructorsOnly = true;
3437
3438 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3439 // We're not going to find any constructors.
3440 } else if (CXXRecordDecl *ToRecordDecl
3441 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3442
3443 Expr **Args = &From;
3444 unsigned NumArgs = 1;
3445 bool ListInitializing = false;
3446 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3447 // But first, see if there is an init-list-constructor that will work.
3448 OverloadingResult Result = IsInitializerListConstructorConversion(
3449 S, From, ToType, ToRecordDecl, User, CandidateSet,
3450 AllowExplicit == AllowedExplicit::All);
3451 if (Result != OR_No_Viable_Function)
3452 return Result;
3453 // Never mind.
3454 CandidateSet.clear(
3455 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3456
3457 // If we're list-initializing, we pass the individual elements as
3458 // arguments, not the entire list.
3459 Args = InitList->getInits();
3460 NumArgs = InitList->getNumInits();
3461 ListInitializing = true;
3462 }
3463
3464 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3465 auto Info = getConstructorInfo(D);
3466 if (!Info)
3467 continue;
3468
3469 bool Usable = !Info.Constructor->isInvalidDecl();
3470 if (!ListInitializing)
3471 Usable = Usable && Info.Constructor->isConvertingConstructor(
3472 /*AllowExplicit*/ true);
3473 if (Usable) {
3474 bool SuppressUserConversions = !ConstructorsOnly;
3475 if (SuppressUserConversions && ListInitializing) {
3476 SuppressUserConversions = false;
3477 if (NumArgs == 1) {
3478 // If the first argument is (a reference to) the target type,
3479 // suppress conversions.
3480 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3481 S.Context, Info.Constructor, ToType);
3482 }
3483 }
3484 if (Info.ConstructorTmpl)
3485 S.AddTemplateOverloadCandidate(
3486 Info.ConstructorTmpl, Info.FoundDecl,
3487 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3488 CandidateSet, SuppressUserConversions,
3489 /*PartialOverloading*/ false,
3490 AllowExplicit == AllowedExplicit::All);
3491 else
3492 // Allow one user-defined conversion when user specifies a
3493 // From->ToType conversion via an static cast (c-style, etc).
3494 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3495 llvm::makeArrayRef(Args, NumArgs),
3496 CandidateSet, SuppressUserConversions,
3497 /*PartialOverloading*/ false,
3498 AllowExplicit == AllowedExplicit::All);
3499 }
3500 }
3501 }
3502 }
3503
3504 // Enumerate conversion functions, if we're allowed to.
3505 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3506 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3507 // No conversion functions from incomplete types.
3508 } else if (const RecordType *FromRecordType =
3509 From->getType()->getAs<RecordType>()) {
3510 if (CXXRecordDecl *FromRecordDecl
3511 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3512 // Add all of the conversion functions as candidates.
3513 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3514 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3515 DeclAccessPair FoundDecl = I.getPair();
3516 NamedDecl *D = FoundDecl.getDecl();
3517 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3518 if (isa<UsingShadowDecl>(D))
3519 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3520
3521 CXXConversionDecl *Conv;
3522 FunctionTemplateDecl *ConvTemplate;
3523 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3524 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3525 else
3526 Conv = cast<CXXConversionDecl>(D);
3527
3528 if (ConvTemplate)
3529 S.AddTemplateConversionCandidate(
3530 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3531 CandidateSet, AllowObjCConversionOnExplicit,
3532 AllowExplicit != AllowedExplicit::None);
3533 else
3534 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3535 CandidateSet, AllowObjCConversionOnExplicit,
3536 AllowExplicit != AllowedExplicit::None);
3537 }
3538 }
3539 }
3540
3541 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3542
3543 OverloadCandidateSet::iterator Best;
3544 switch (auto Result =
3545 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3546 case OR_Success:
3547 case OR_Deleted:
3548 // Record the standard conversion we used and the conversion function.
3549 if (CXXConstructorDecl *Constructor
3550 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3551 // C++ [over.ics.user]p1:
3552 // If the user-defined conversion is specified by a
3553 // constructor (12.3.1), the initial standard conversion
3554 // sequence converts the source type to the type required by
3555 // the argument of the constructor.
3556 //
3557 QualType ThisType = Constructor->getThisType();
3558 if (isa<InitListExpr>(From)) {
3559 // Initializer lists don't have conversions as such.
3560 User.Before.setAsIdentityConversion();
3561 } else {
3562 if (Best->Conversions[0].isEllipsis())
3563 User.EllipsisConversion = true;
3564 else {
3565 User.Before = Best->Conversions[0].Standard;
3566 User.EllipsisConversion = false;
3567 }
3568 }
3569 User.HadMultipleCandidates = HadMultipleCandidates;
3570 User.ConversionFunction = Constructor;
3571 User.FoundConversionFunction = Best->FoundDecl;
3572 User.After.setAsIdentityConversion();
3573 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3574 User.After.setAllToTypes(ToType);
3575 return Result;
3576 }
3577 if (CXXConversionDecl *Conversion
3578 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3579 // C++ [over.ics.user]p1:
3580 //
3581 // [...] If the user-defined conversion is specified by a
3582 // conversion function (12.3.2), the initial standard
3583 // conversion sequence converts the source type to the
3584 // implicit object parameter of the conversion function.
3585 User.Before = Best->Conversions[0].Standard;
3586 User.HadMultipleCandidates = HadMultipleCandidates;
3587 User.ConversionFunction = Conversion;
3588 User.FoundConversionFunction = Best->FoundDecl;
3589 User.EllipsisConversion = false;
3590
3591 // C++ [over.ics.user]p2:
3592 // The second standard conversion sequence converts the
3593 // result of the user-defined conversion to the target type
3594 // for the sequence. Since an implicit conversion sequence
3595 // is an initialization, the special rules for
3596 // initialization by user-defined conversion apply when
3597 // selecting the best user-defined conversion for a
3598 // user-defined conversion sequence (see 13.3.3 and
3599 // 13.3.3.1).
3600 User.After = Best->FinalConversion;
3601 return Result;
3602 }
3603 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3603)
;
3604
3605 case OR_No_Viable_Function:
3606 return OR_No_Viable_Function;
3607
3608 case OR_Ambiguous:
3609 return OR_Ambiguous;
3610 }
3611
3612 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 3612)
;
3613}
3614
3615bool
3616Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3617 ImplicitConversionSequence ICS;
3618 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3619 OverloadCandidateSet::CSK_Normal);
3620 OverloadingResult OvResult =
3621 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3622 CandidateSet, AllowedExplicit::None, false);
3623
3624 if (!(OvResult == OR_Ambiguous ||
3625 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3626 return false;
3627
3628 auto Cands = CandidateSet.CompleteCandidates(
3629 *this,
3630 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3631 From);
3632 if (OvResult == OR_Ambiguous)
3633 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3634 << From->getType() << ToType << From->getSourceRange();
3635 else { // OR_No_Viable_Function && !CandidateSet.empty()
3636 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3637 diag::err_typecheck_nonviable_condition_incomplete,
3638 From->getType(), From->getSourceRange()))
3639 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3640 << false << From->getType() << From->getSourceRange() << ToType;
3641 }
3642
3643 CandidateSet.NoteCandidates(
3644 *this, From, Cands);
3645 return true;
3646}
3647
3648// Helper for compareConversionFunctions that gets the FunctionType that the
3649// conversion-operator return value 'points' to, or nullptr.
3650static const FunctionType *
3651getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3652 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3653 const PointerType *RetPtrTy =
3654 ConvFuncTy->getReturnType()->getAs<PointerType>();
3655
3656 if (!RetPtrTy)
3657 return nullptr;
3658
3659 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3660}
3661
3662/// Compare the user-defined conversion functions or constructors
3663/// of two user-defined conversion sequences to determine whether any ordering
3664/// is possible.
3665static ImplicitConversionSequence::CompareKind
3666compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3667 FunctionDecl *Function2) {
3668 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3669 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3670 if (!Conv1 || !Conv2)
3671 return ImplicitConversionSequence::Indistinguishable;
3672
3673 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3674 return ImplicitConversionSequence::Indistinguishable;
3675
3676 // Objective-C++:
3677 // If both conversion functions are implicitly-declared conversions from
3678 // a lambda closure type to a function pointer and a block pointer,
3679 // respectively, always prefer the conversion to a function pointer,
3680 // because the function pointer is more lightweight and is more likely
3681 // to keep code working.
3682 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3683 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3684 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3685 if (Block1 != Block2)
3686 return Block1 ? ImplicitConversionSequence::Worse
3687 : ImplicitConversionSequence::Better;
3688 }
3689
3690 // In order to support multiple calling conventions for the lambda conversion
3691 // operator (such as when the free and member function calling convention is
3692 // different), prefer the 'free' mechanism, followed by the calling-convention
3693 // of operator(). The latter is in place to support the MSVC-like solution of
3694 // defining ALL of the possible conversions in regards to calling-convention.
3695 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3696 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3697
3698 if (Conv1FuncRet && Conv2FuncRet &&
3699 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3700 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3701 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3702
3703 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3704 const FunctionProtoType *CallOpProto =
3705 CallOp->getType()->getAs<FunctionProtoType>();
3706
3707 CallingConv CallOpCC =
3708 CallOp->getType()->getAs<FunctionType>()->getCallConv();
3709 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3710 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3711 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3712 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3713
3714 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3715 for (CallingConv CC : PrefOrder) {
3716 if (Conv1CC == CC)
3717 return ImplicitConversionSequence::Better;
3718 if (Conv2CC == CC)
3719 return ImplicitConversionSequence::Worse;
3720 }
3721 }
3722
3723 return ImplicitConversionSequence::Indistinguishable;
3724}
3725
3726static bool hasDeprecatedStringLiteralToCharPtrConversion(
3727 const ImplicitConversionSequence &ICS) {
3728 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3729 (ICS.isUserDefined() &&
3730 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3731}
3732
3733/// CompareImplicitConversionSequences - Compare two implicit
3734/// conversion sequences to determine whether one is better than the
3735/// other or if they are indistinguishable (C++ 13.3.3.2).
3736static ImplicitConversionSequence::CompareKind
3737CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3738 const ImplicitConversionSequence& ICS1,
3739 const ImplicitConversionSequence& ICS2)
3740{
3741 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3742 // conversion sequences (as defined in 13.3.3.1)
3743 // -- a standard conversion sequence (13.3.3.1.1) is a better
3744 // conversion sequence than a user-defined conversion sequence or
3745 // an ellipsis conversion sequence, and
3746 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3747 // conversion sequence than an ellipsis conversion sequence
3748 // (13.3.3.1.3).
3749 //
3750 // C++0x [over.best.ics]p10:
3751 // For the purpose of ranking implicit conversion sequences as
3752 // described in 13.3.3.2, the ambiguous conversion sequence is
3753 // treated as a user-defined sequence that is indistinguishable
3754 // from any other user-defined conversion sequence.
3755
3756 // String literal to 'char *' conversion has been deprecated in C++03. It has
3757 // been removed from C++11. We still accept this conversion, if it happens at
3758 // the best viable function. Otherwise, this conversion is considered worse
3759 // than ellipsis conversion. Consider this as an extension; this is not in the
3760 // standard. For example:
3761 //
3762 // int &f(...); // #1
3763 // void f(char*); // #2
3764 // void g() { int &r = f("foo"); }
3765 //
3766 // In C++03, we pick #2 as the best viable function.
3767 // In C++11, we pick #1 as the best viable function, because ellipsis
3768 // conversion is better than string-literal to char* conversion (since there
3769 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3770 // convert arguments, #2 would be the best viable function in C++11.
3771 // If the best viable function has this conversion, a warning will be issued
3772 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3773
3774 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3775 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3776 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3777 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3778 ? ImplicitConversionSequence::Worse
3779 : ImplicitConversionSequence::Better;
3780
3781 if (ICS1.getKindRank() < ICS2.getKindRank())
3782 return ImplicitConversionSequence::Better;
3783 if (ICS2.getKindRank() < ICS1.getKindRank())
3784 return ImplicitConversionSequence::Worse;
3785
3786 // The following checks require both conversion sequences to be of
3787 // the same kind.
3788 if (ICS1.getKind() != ICS2.getKind())
3789 return ImplicitConversionSequence::Indistinguishable;
3790
3791 ImplicitConversionSequence::CompareKind Result =
3792 ImplicitConversionSequence::Indistinguishable;
3793
3794 // Two implicit conversion sequences of the same form are
3795 // indistinguishable conversion sequences unless one of the
3796 // following rules apply: (C++ 13.3.3.2p3):
3797
3798 // List-initialization sequence L1 is a better conversion sequence than
3799 // list-initialization sequence L2 if:
3800 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3801 // if not that,
3802 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3803 // and N1 is smaller than N2.,
3804 // even if one of the other rules in this paragraph would otherwise apply.
3805 if (!ICS1.isBad()) {
3806 if (ICS1.isStdInitializerListElement() &&
3807 !ICS2.isStdInitializerListElement())
3808 return ImplicitConversionSequence::Better;
3809 if (!ICS1.isStdInitializerListElement() &&
3810 ICS2.isStdInitializerListElement())
3811 return ImplicitConversionSequence::Worse;
3812 }
3813
3814 if (ICS1.isStandard())
3815 // Standard conversion sequence S1 is a better conversion sequence than
3816 // standard conversion sequence S2 if [...]
3817 Result = CompareStandardConversionSequences(S, Loc,
3818 ICS1.Standard, ICS2.Standard);
3819 else if (ICS1.isUserDefined()) {
3820 // User-defined conversion sequence U1 is a better conversion
3821 // sequence than another user-defined conversion sequence U2 if
3822 // they contain the same user-defined conversion function or
3823 // constructor and if the second standard conversion sequence of
3824 // U1 is better than the second standard conversion sequence of
3825 // U2 (C++ 13.3.3.2p3).
3826 if (ICS1.UserDefined.ConversionFunction ==
3827 ICS2.UserDefined.ConversionFunction)
3828 Result = CompareStandardConversionSequences(S, Loc,
3829 ICS1.UserDefined.After,
3830 ICS2.UserDefined.After);
3831 else
3832 Result = compareConversionFunctions(S,
3833 ICS1.UserDefined.ConversionFunction,
3834 ICS2.UserDefined.ConversionFunction);
3835 }
3836
3837 return Result;
3838}
3839
3840// Per 13.3.3.2p3, compare the given standard conversion sequences to
3841// determine if one is a proper subset of the other.
3842static ImplicitConversionSequence::CompareKind
3843compareStandardConversionSubsets(ASTContext &Context,
3844 const StandardConversionSequence& SCS1,
3845 const StandardConversionSequence& SCS2) {
3846 ImplicitConversionSequence::CompareKind Result
3847 = ImplicitConversionSequence::Indistinguishable;
3848
3849 // the identity conversion sequence is considered to be a subsequence of
3850 // any non-identity conversion sequence
3851 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3852 return ImplicitConversionSequence::Better;
3853 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3854 return ImplicitConversionSequence::Worse;
3855
3856 if (SCS1.Second != SCS2.Second) {
3857 if (SCS1.Second == ICK_Identity)
3858 Result = ImplicitConversionSequence::Better;
3859 else if (SCS2.Second == ICK_Identity)
3860 Result = ImplicitConversionSequence::Worse;
3861 else
3862 return ImplicitConversionSequence::Indistinguishable;
3863 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3864 return ImplicitConversionSequence::Indistinguishable;
3865
3866 if (SCS1.Third == SCS2.Third) {
3867 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3868 : ImplicitConversionSequence::Indistinguishable;
3869 }
3870
3871 if (SCS1.Third == ICK_Identity)
3872 return Result == ImplicitConversionSequence::Worse
3873 ? ImplicitConversionSequence::Indistinguishable
3874 : ImplicitConversionSequence::Better;
3875
3876 if (SCS2.Third == ICK_Identity)
3877 return Result == ImplicitConversionSequence::Better
3878 ? ImplicitConversionSequence::Indistinguishable
3879 : ImplicitConversionSequence::Worse;
3880
3881 return ImplicitConversionSequence::Indistinguishable;
3882}
3883
3884/// Determine whether one of the given reference bindings is better
3885/// than the other based on what kind of bindings they are.
3886static bool
3887isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3888 const StandardConversionSequence &SCS2) {
3889 // C++0x [over.ics.rank]p3b4:
3890 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3891 // implicit object parameter of a non-static member function declared
3892 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3893 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3894 // lvalue reference to a function lvalue and S2 binds an rvalue
3895 // reference*.
3896 //
3897 // FIXME: Rvalue references. We're going rogue with the above edits,
3898 // because the semantics in the current C++0x working paper (N3225 at the
3899 // time of this writing) break the standard definition of std::forward
3900 // and std::reference_wrapper when dealing with references to functions.
3901 // Proposed wording changes submitted to CWG for consideration.
3902 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3903 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3904 return false;
3905
3906 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3907 SCS2.IsLvalueReference) ||
3908 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3909 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3910}
3911
3912enum class FixedEnumPromotion {
3913 None,
3914 ToUnderlyingType,
3915 ToPromotedUnderlyingType
3916};
3917
3918/// Returns kind of fixed enum promotion the \a SCS uses.
3919static FixedEnumPromotion
3920getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3921
3922 if (SCS.Second != ICK_Integral_Promotion)
3923 return FixedEnumPromotion::None;
3924
3925 QualType FromType = SCS.getFromType();
3926 if (!FromType->isEnumeralType())
3927 return FixedEnumPromotion::None;
3928
3929 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3930 if (!Enum->isFixed())
3931 return FixedEnumPromotion::None;
3932
3933 QualType UnderlyingType = Enum->getIntegerType();
3934 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3935 return FixedEnumPromotion::ToUnderlyingType;
3936
3937 return FixedEnumPromotion::ToPromotedUnderlyingType;
3938}
3939
3940/// CompareStandardConversionSequences - Compare two standard
3941/// conversion sequences to determine whether one is better than the
3942/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3943static ImplicitConversionSequence::CompareKind
3944CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3945 const StandardConversionSequence& SCS1,
3946 const StandardConversionSequence& SCS2)
3947{
3948 // Standard conversion sequence S1 is a better conversion sequence
3949 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3950
3951 // -- S1 is a proper subsequence of S2 (comparing the conversion
3952 // sequences in the canonical form defined by 13.3.3.1.1,
3953 // excluding any Lvalue Transformation; the identity conversion
3954 // sequence is considered to be a subsequence of any
3955 // non-identity conversion sequence) or, if not that,
3956 if (ImplicitConversionSequence::CompareKind CK
3957 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3958 return CK;
3959
3960 // -- the rank of S1 is better than the rank of S2 (by the rules
3961 // defined below), or, if not that,
3962 ImplicitConversionRank Rank1 = SCS1.getRank();
3963 ImplicitConversionRank Rank2 = SCS2.getRank();
3964 if (Rank1 < Rank2)
3965 return ImplicitConversionSequence::Better;
3966 else if (Rank2 < Rank1)
3967 return ImplicitConversionSequence::Worse;
3968
3969 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3970 // are indistinguishable unless one of the following rules
3971 // applies:
3972
3973 // A conversion that is not a conversion of a pointer, or
3974 // pointer to member, to bool is better than another conversion
3975 // that is such a conversion.
3976 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3977 return SCS2.isPointerConversionToBool()
3978 ? ImplicitConversionSequence::Better
3979 : ImplicitConversionSequence::Worse;
3980
3981 // C++14 [over.ics.rank]p4b2:
3982 // This is retroactively applied to C++11 by CWG 1601.
3983 //
3984 // A conversion that promotes an enumeration whose underlying type is fixed
3985 // to its underlying type is better than one that promotes to the promoted
3986 // underlying type, if the two are different.
3987 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3988 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3989 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3990 FEP1 != FEP2)
3991 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3992 ? ImplicitConversionSequence::Better
3993 : ImplicitConversionSequence::Worse;
3994
3995 // C++ [over.ics.rank]p4b2:
3996 //
3997 // If class B is derived directly or indirectly from class A,
3998 // conversion of B* to A* is better than conversion of B* to
3999 // void*, and conversion of A* to void* is better than conversion
4000 // of B* to void*.
4001 bool SCS1ConvertsToVoid
4002 = SCS1.isPointerConversionToVoidPointer(S.Context);
4003 bool SCS2ConvertsToVoid
4004 = SCS2.isPointerConversionToVoidPointer(S.Context);
4005 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4006 // Exactly one of the conversion sequences is a conversion to
4007 // a void pointer; it's the worse conversion.
4008 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4009 : ImplicitConversionSequence::Worse;
4010 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4011 // Neither conversion sequence converts to a void pointer; compare
4012 // their derived-to-base conversions.
4013 if (ImplicitConversionSequence::CompareKind DerivedCK
4014 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4015 return DerivedCK;
4016 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4017 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4018 // Both conversion sequences are conversions to void
4019 // pointers. Compare the source types to determine if there's an
4020 // inheritance relationship in their sources.
4021 QualType FromType1 = SCS1.getFromType();
4022 QualType FromType2 = SCS2.getFromType();
4023
4024 // Adjust the types we're converting from via the array-to-pointer
4025 // conversion, if we need to.
4026 if (SCS1.First == ICK_Array_To_Pointer)
4027 FromType1 = S.Context.getArrayDecayedType(FromType1);
4028 if (SCS2.First == ICK_Array_To_Pointer)
4029 FromType2 = S.Context.getArrayDecayedType(FromType2);
4030
4031 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4032 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4033
4034 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4035 return ImplicitConversionSequence::Better;
4036 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4037 return ImplicitConversionSequence::Worse;
4038
4039 // Objective-C++: If one interface is more specific than the
4040 // other, it is the better one.
4041 const ObjCObjectPointerType* FromObjCPtr1
4042 = FromType1->getAs<ObjCObjectPointerType>();
4043 const ObjCObjectPointerType* FromObjCPtr2
4044 = FromType2->getAs<ObjCObjectPointerType>();
4045 if (FromObjCPtr1 && FromObjCPtr2) {
4046 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4047 FromObjCPtr2);
4048 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4049 FromObjCPtr1);
4050 if (AssignLeft != AssignRight) {
4051 return AssignLeft? ImplicitConversionSequence::Better
4052 : ImplicitConversionSequence::Worse;
4053 }
4054 }
4055 }
4056
4057 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4058 // Check for a better reference binding based on the kind of bindings.
4059 if (isBetterReferenceBindingKind(SCS1, SCS2))
4060 return ImplicitConversionSequence::Better;
4061 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4062 return ImplicitConversionSequence::Worse;
4063 }
4064
4065 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4066 // bullet 3).
4067 if (ImplicitConversionSequence::CompareKind QualCK
4068 = CompareQualificationConversions(S, SCS1, SCS2))
4069 return QualCK;
4070
4071 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4072 // C++ [over.ics.rank]p3b4:
4073 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4074 // which the references refer are the same type except for
4075 // top-level cv-qualifiers, and the type to which the reference
4076 // initialized by S2 refers is more cv-qualified than the type
4077 // to which the reference initialized by S1 refers.
4078 QualType T1 = SCS1.getToType(2);
4079 QualType T2 = SCS2.getToType(2);
4080 T1 = S.Context.getCanonicalType(T1);
4081 T2 = S.Context.getCanonicalType(T2);
4082 Qualifiers T1Quals, T2Quals;
4083 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4084 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4085 if (UnqualT1 == UnqualT2) {
4086 // Objective-C++ ARC: If the references refer to objects with different
4087 // lifetimes, prefer bindings that don't change lifetime.
4088 if (SCS1.ObjCLifetimeConversionBinding !=
4089 SCS2.ObjCLifetimeConversionBinding) {
4090 return SCS1.ObjCLifetimeConversionBinding
4091 ? ImplicitConversionSequence::Worse
4092 : ImplicitConversionSequence::Better;
4093 }
4094
4095 // If the type is an array type, promote the element qualifiers to the
4096 // type for comparison.
4097 if (isa<ArrayType>(T1) && T1Quals)
4098 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4099 if (isa<ArrayType>(T2) && T2Quals)
4100 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4101 if (T2.isMoreQualifiedThan(T1))
4102 return ImplicitConversionSequence::Better;
4103 if (T1.isMoreQualifiedThan(T2))
4104 return ImplicitConversionSequence::Worse;
4105 }
4106 }
4107
4108 // In Microsoft mode, prefer an integral conversion to a
4109 // floating-to-integral conversion if the integral conversion
4110 // is between types of the same size.
4111 // For example:
4112 // void f(float);
4113 // void f(int);
4114 // int main {
4115 // long a;
4116 // f(a);
4117 // }
4118 // Here, MSVC will call f(int) instead of generating a compile error
4119 // as clang will do in standard mode.
4120 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4121 SCS2.Second == ICK_Floating_Integral &&
4122 S.Context.getTypeSize(SCS1.getFromType()) ==
4123 S.Context.getTypeSize(SCS1.getToType(2)))
4124 return ImplicitConversionSequence::Better;
4125
4126 // Prefer a compatible vector conversion over a lax vector conversion
4127 // For example:
4128 //
4129 // typedef float __v4sf __attribute__((__vector_size__(16)));
4130 // void f(vector float);
4131 // void f(vector signed int);
4132 // int main() {
4133 // __v4sf a;
4134 // f(a);
4135 // }
4136 // Here, we'd like to choose f(vector float) and not
4137 // report an ambiguous call error
4138 if (SCS1.Second == ICK_Vector_Conversion &&
4139 SCS2.Second == ICK_Vector_Conversion) {
4140 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4141 SCS1.getFromType(), SCS1.getToType(2));
4142 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4143 SCS2.getFromType(), SCS2.getToType(2));
4144
4145 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4146 return SCS1IsCompatibleVectorConversion
4147 ? ImplicitConversionSequence::Better
4148 : ImplicitConversionSequence::Worse;
4149 }
4150
4151 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4152 SCS2.Second == ICK_SVE_Vector_Conversion) {
4153 bool SCS1IsCompatibleSVEVectorConversion =
4154 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4155 bool SCS2IsCompatibleSVEVectorConversion =
4156 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4157
4158 if (SCS1IsCompatibleSVEVectorConversion !=
4159 SCS2IsCompatibleSVEVectorConversion)
4160 return SCS1IsCompatibleSVEVectorConversion
4161 ? ImplicitConversionSequence::Better
4162 : ImplicitConversionSequence::Worse;
4163 }
4164
4165 return ImplicitConversionSequence::Indistinguishable;
4166}
4167
4168/// CompareQualificationConversions - Compares two standard conversion
4169/// sequences to determine whether they can be ranked based on their
4170/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4171static ImplicitConversionSequence::CompareKind
4172CompareQualificationConversions(Sema &S,
4173 const StandardConversionSequence& SCS1,
4174 const StandardConversionSequence& SCS2) {
4175 // C++ 13.3.3.2p3:
4176 // -- S1 and S2 differ only in their qualification conversion and
4177 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4178 // cv-qualification signature of type T1 is a proper subset of
4179 // the cv-qualification signature of type T2, and S1 is not the
4180 // deprecated string literal array-to-pointer conversion (4.2).
4181 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4182 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4183 return ImplicitConversionSequence::Indistinguishable;
4184
4185 // FIXME: the example in the standard doesn't use a qualification
4186 // conversion (!)
4187 QualType T1 = SCS1.getToType(2);
4188 QualType T2 = SCS2.getToType(2);
4189 T1 = S.Context.getCanonicalType(T1);
4190 T2 = S.Context.getCanonicalType(T2);
4191 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4191, __PRETTY_FUNCTION__))
;
4192 Qualifiers T1Quals, T2Quals;
4193 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4194 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4195
4196 // If the types are the same, we won't learn anything by unwrapping
4197 // them.
4198 if (UnqualT1 == UnqualT2)
4199 return ImplicitConversionSequence::Indistinguishable;
4200
4201 ImplicitConversionSequence::CompareKind Result
4202 = ImplicitConversionSequence::Indistinguishable;
4203
4204 // Objective-C++ ARC:
4205 // Prefer qualification conversions not involving a change in lifetime
4206 // to qualification conversions that do not change lifetime.
4207 if (SCS1.QualificationIncludesObjCLifetime !=
4208 SCS2.QualificationIncludesObjCLifetime) {
4209 Result = SCS1.QualificationIncludesObjCLifetime
4210 ? ImplicitConversionSequence::Worse
4211 : ImplicitConversionSequence::Better;
4212 }
4213
4214 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4215 // Within each iteration of the loop, we check the qualifiers to
4216 // determine if this still looks like a qualification
4217 // conversion. Then, if all is well, we unwrap one more level of
4218 // pointers or pointers-to-members and do it all again
4219 // until there are no more pointers or pointers-to-members left
4220 // to unwrap. This essentially mimics what
4221 // IsQualificationConversion does, but here we're checking for a
4222 // strict subset of qualifiers.
4223 if (T1.getQualifiers().withoutObjCLifetime() ==
4224 T2.getQualifiers().withoutObjCLifetime())
4225 // The qualifiers are the same, so this doesn't tell us anything
4226 // about how the sequences rank.
4227 // ObjC ownership quals are omitted above as they interfere with
4228 // the ARC overload rule.
4229 ;
4230 else if (T2.isMoreQualifiedThan(T1)) {
4231 // T1 has fewer qualifiers, so it could be the better sequence.
4232 if (Result == ImplicitConversionSequence::Worse)
4233 // Neither has qualifiers that are a subset of the other's
4234 // qualifiers.
4235 return ImplicitConversionSequence::Indistinguishable;
4236
4237 Result = ImplicitConversionSequence::Better;
4238 } else if (T1.isMoreQualifiedThan(T2)) {
4239 // T2 has fewer qualifiers, so it could be the better sequence.
4240 if (Result == ImplicitConversionSequence::Better)
4241 // Neither has qualifiers that are a subset of the other's
4242 // qualifiers.
4243 return ImplicitConversionSequence::Indistinguishable;
4244
4245 Result = ImplicitConversionSequence::Worse;
4246 } else {
4247 // Qualifiers are disjoint.
4248 return ImplicitConversionSequence::Indistinguishable;
4249 }
4250
4251 // If the types after this point are equivalent, we're done.
4252 if (S.Context.hasSameUnqualifiedType(T1, T2))
4253 break;
4254 }
4255
4256 // Check that the winning standard conversion sequence isn't using
4257 // the deprecated string literal array to pointer conversion.
4258 switch (Result) {
4259 case ImplicitConversionSequence::Better:
4260 if (SCS1.DeprecatedStringLiteralToCharPtr)
4261 Result = ImplicitConversionSequence::Indistinguishable;
4262 break;
4263
4264 case ImplicitConversionSequence::Indistinguishable:
4265 break;
4266
4267 case ImplicitConversionSequence::Worse:
4268 if (SCS2.DeprecatedStringLiteralToCharPtr)
4269 Result = ImplicitConversionSequence::Indistinguishable;
4270 break;
4271 }
4272
4273 return Result;
4274}
4275
4276/// CompareDerivedToBaseConversions - Compares two standard conversion
4277/// sequences to determine whether they can be ranked based on their
4278/// various kinds of derived-to-base conversions (C++
4279/// [over.ics.rank]p4b3). As part of these checks, we also look at
4280/// conversions between Objective-C interface types.
4281static ImplicitConversionSequence::CompareKind
4282CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4283 const StandardConversionSequence& SCS1,
4284 const StandardConversionSequence& SCS2) {
4285 QualType FromType1 = SCS1.getFromType();
4286 QualType ToType1 = SCS1.getToType(1);
4287 QualType FromType2 = SCS2.getFromType();
4288 QualType ToType2 = SCS2.getToType(1);
4289
4290 // Adjust the types we're converting from via the array-to-pointer
4291 // conversion, if we need to.
4292 if (SCS1.First == ICK_Array_To_Pointer)
4293 FromType1 = S.Context.getArrayDecayedType(FromType1);
4294 if (SCS2.First == ICK_Array_To_Pointer)
4295 FromType2 = S.Context.getArrayDecayedType(FromType2);
4296
4297 // Canonicalize all of the types.
4298 FromType1 = S.Context.getCanonicalType(FromType1);
4299 ToType1 = S.Context.getCanonicalType(ToType1);
4300 FromType2 = S.Context.getCanonicalType(FromType2);
4301 ToType2 = S.Context.getCanonicalType(ToType2);
4302
4303 // C++ [over.ics.rank]p4b3:
4304 //
4305 // If class B is derived directly or indirectly from class A and
4306 // class C is derived directly or indirectly from B,
4307 //
4308 // Compare based on pointer conversions.
4309 if (SCS1.Second == ICK_Pointer_Conversion &&
4310 SCS2.Second == ICK_Pointer_Conversion &&
4311 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4312 FromType1->isPointerType() && FromType2->isPointerType() &&
4313 ToType1->isPointerType() && ToType2->isPointerType()) {
4314 QualType FromPointee1 =
4315 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4316 QualType ToPointee1 =
4317 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4318 QualType FromPointee2 =
4319 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4320 QualType ToPointee2 =
4321 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4322
4323 // -- conversion of C* to B* is better than conversion of C* to A*,
4324 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4325 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4326 return ImplicitConversionSequence::Better;
4327 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4328 return ImplicitConversionSequence::Worse;
4329 }
4330
4331 // -- conversion of B* to A* is better than conversion of C* to A*,
4332 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4333 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4334 return ImplicitConversionSequence::Better;
4335 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4336 return ImplicitConversionSequence::Worse;
4337 }
4338 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4339 SCS2.Second == ICK_Pointer_Conversion) {
4340 const ObjCObjectPointerType *FromPtr1
4341 = FromType1->getAs<ObjCObjectPointerType>();
4342 const ObjCObjectPointerType *FromPtr2
4343 = FromType2->getAs<ObjCObjectPointerType>();
4344 const ObjCObjectPointerType *ToPtr1
4345 = ToType1->getAs<ObjCObjectPointerType>();
4346 const ObjCObjectPointerType *ToPtr2
4347 = ToType2->getAs<ObjCObjectPointerType>();
4348
4349 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4350 // Apply the same conversion ranking rules for Objective-C pointer types
4351 // that we do for C++ pointers to class types. However, we employ the
4352 // Objective-C pseudo-subtyping relationship used for assignment of
4353 // Objective-C pointer types.
4354 bool FromAssignLeft
4355 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4356 bool FromAssignRight
4357 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4358 bool ToAssignLeft
4359 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4360 bool ToAssignRight
4361 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4362
4363 // A conversion to an a non-id object pointer type or qualified 'id'
4364 // type is better than a conversion to 'id'.
4365 if (ToPtr1->isObjCIdType() &&
4366 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4367 return ImplicitConversionSequence::Worse;
4368 if (ToPtr2->isObjCIdType() &&
4369 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4370 return ImplicitConversionSequence::Better;
4371
4372 // A conversion to a non-id object pointer type is better than a
4373 // conversion to a qualified 'id' type
4374 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4375 return ImplicitConversionSequence::Worse;
4376 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4377 return ImplicitConversionSequence::Better;
4378
4379 // A conversion to an a non-Class object pointer type or qualified 'Class'
4380 // type is better than a conversion to 'Class'.
4381 if (ToPtr1->isObjCClassType() &&
4382 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4383 return ImplicitConversionSequence::Worse;
4384 if (ToPtr2->isObjCClassType() &&
4385 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4386 return ImplicitConversionSequence::Better;
4387
4388 // A conversion to a non-Class object pointer type is better than a
4389 // conversion to a qualified 'Class' type.
4390 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4391 return ImplicitConversionSequence::Worse;
4392 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4393 return ImplicitConversionSequence::Better;
4394
4395 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4396 if (S.Context.hasSameType(FromType1, FromType2) &&
4397 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4398 (ToAssignLeft != ToAssignRight)) {
4399 if (FromPtr1->isSpecialized()) {
4400 // "conversion of B<A> * to B * is better than conversion of B * to
4401 // C *.
4402 bool IsFirstSame =
4403 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4404 bool IsSecondSame =
4405 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4406 if (IsFirstSame) {
4407 if (!IsSecondSame)
4408 return ImplicitConversionSequence::Better;
4409 } else if (IsSecondSame)
4410 return ImplicitConversionSequence::Worse;
4411 }
4412 return ToAssignLeft? ImplicitConversionSequence::Worse
4413 : ImplicitConversionSequence::Better;
4414 }
4415
4416 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4417 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4418 (FromAssignLeft != FromAssignRight))
4419 return FromAssignLeft? ImplicitConversionSequence::Better
4420 : ImplicitConversionSequence::Worse;
4421 }
4422 }
4423
4424 // Ranking of member-pointer types.
4425 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4426 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4427 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4428 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4429 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4430 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4431 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4432 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4433 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4434 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4435 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4436 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4437 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4438 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4439 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4440 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4441 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4442 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4443 return ImplicitConversionSequence::Worse;
4444 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4445 return ImplicitConversionSequence::Better;
4446 }
4447 // conversion of B::* to C::* is better than conversion of A::* to C::*
4448 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4449 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4450 return ImplicitConversionSequence::Better;
4451 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4452 return ImplicitConversionSequence::Worse;
4453 }
4454 }
4455
4456 if (SCS1.Second == ICK_Derived_To_Base) {
4457 // -- conversion of C to B is better than conversion of C to A,
4458 // -- binding of an expression of type C to a reference of type
4459 // B& is better than binding an expression of type C to a
4460 // reference of type A&,
4461 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4462 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4463 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4464 return ImplicitConversionSequence::Better;
4465 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4466 return ImplicitConversionSequence::Worse;
4467 }
4468
4469 // -- conversion of B to A is better than conversion of C to A.
4470 // -- binding of an expression of type B to a reference of type
4471 // A& is better than binding an expression of type C to a
4472 // reference of type A&,
4473 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4474 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4475 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4476 return ImplicitConversionSequence::Better;
4477 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4478 return ImplicitConversionSequence::Worse;
4479 }
4480 }
4481
4482 return ImplicitConversionSequence::Indistinguishable;
4483}
4484
4485/// Determine whether the given type is valid, e.g., it is not an invalid
4486/// C++ class.
4487static bool isTypeValid(QualType T) {
4488 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4489 return !Record->isInvalidDecl();
4490
4491 return true;
4492}
4493
4494static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4495 if (!T.getQualifiers().hasUnaligned())
4496 return T;
4497
4498 Qualifiers Q;
4499 T = Ctx.getUnqualifiedArrayType(T, Q);
4500 Q.removeUnaligned();
4501 return Ctx.getQualifiedType(T, Q);
4502}
4503
4504/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4505/// determine whether they are reference-compatible,
4506/// reference-related, or incompatible, for use in C++ initialization by
4507/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4508/// type, and the first type (T1) is the pointee type of the reference
4509/// type being initialized.
4510Sema::ReferenceCompareResult
4511Sema::CompareReferenceRelationship(SourceLocation Loc,
4512 QualType OrigT1, QualType OrigT2,
4513 ReferenceConversions *ConvOut) {
4514 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4515, __PRETTY_FUNCTION__))
4515 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4515, __PRETTY_FUNCTION__))
;
4516 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4516, __PRETTY_FUNCTION__))
;
4517
4518 QualType T1 = Context.getCanonicalType(OrigT1);
4519 QualType T2 = Context.getCanonicalType(OrigT2);
4520 Qualifiers T1Quals, T2Quals;
4521 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4522 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4523
4524 ReferenceConversions ConvTmp;
4525 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4526 Conv = ReferenceConversions();
4527
4528 // C++2a [dcl.init.ref]p4:
4529 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4530 // reference-related to "cv2 T2" if T1 is similar to T2, or
4531 // T1 is a base class of T2.
4532 // "cv1 T1" is reference-compatible with "cv2 T2" if
4533 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4534 // "pointer to cv1 T1" via a standard conversion sequence.
4535
4536 // Check for standard conversions we can apply to pointers: derived-to-base
4537 // conversions, ObjC pointer conversions, and function pointer conversions.
4538 // (Qualification conversions are checked last.)
4539 QualType ConvertedT2;
4540 if (UnqualT1 == UnqualT2) {
4541 // Nothing to do.
4542 } else if (isCompleteType(Loc, OrigT2) &&
4543 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4544 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4545 Conv |= ReferenceConversions::DerivedToBase;
4546 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4547 UnqualT2->isObjCObjectOrInterfaceType() &&
4548 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4549 Conv |= ReferenceConversions::ObjC;
4550 else if (UnqualT2->isFunctionType() &&
4551 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4552 Conv |= ReferenceConversions::Function;
4553 // No need to check qualifiers; function types don't have them.
4554 return Ref_Compatible;
4555 }
4556 bool ConvertedReferent = Conv != 0;
4557
4558 // We can have a qualification conversion. Compute whether the types are
4559 // similar at the same time.
4560 bool PreviousToQualsIncludeConst = true;
4561 bool TopLevel = true;
4562 do {
4563 if (T1 == T2)
4564 break;
4565
4566 // We will need a qualification conversion.
4567 Conv |= ReferenceConversions::Qualification;
4568
4569 // Track whether we performed a qualification conversion anywhere other
4570 // than the top level. This matters for ranking reference bindings in
4571 // overload resolution.
4572 if (!TopLevel)
4573 Conv |= ReferenceConversions::NestedQualification;
4574
4575 // MS compiler ignores __unaligned qualifier for references; do the same.
4576 T1 = withoutUnaligned(Context, T1);
4577 T2 = withoutUnaligned(Context, T2);
4578
4579 // If we find a qualifier mismatch, the types are not reference-compatible,
4580 // but are still be reference-related if they're similar.
4581 bool ObjCLifetimeConversion = false;
4582 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4583 PreviousToQualsIncludeConst,
4584 ObjCLifetimeConversion))
4585 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4586 ? Ref_Related
4587 : Ref_Incompatible;
4588
4589 // FIXME: Should we track this for any level other than the first?
4590 if (ObjCLifetimeConversion)
4591 Conv |= ReferenceConversions::ObjCLifetime;
4592
4593 TopLevel = false;
4594 } while (Context.UnwrapSimilarTypes(T1, T2));
4595
4596 // At this point, if the types are reference-related, we must either have the
4597 // same inner type (ignoring qualifiers), or must have already worked out how
4598 // to convert the referent.
4599 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4600 ? Ref_Compatible
4601 : Ref_Incompatible;
4602}
4603
4604/// Look for a user-defined conversion to a value reference-compatible
4605/// with DeclType. Return true if something definite is found.
4606static bool
4607FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4608 QualType DeclType, SourceLocation DeclLoc,
4609 Expr *Init, QualType T2, bool AllowRvalues,
4610 bool AllowExplicit) {
4611 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4611, __PRETTY_FUNCTION__))
;
4612 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4613
4614 OverloadCandidateSet CandidateSet(
4615 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4616 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4617 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4618 NamedDecl *D = *I;
4619 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4620 if (isa<UsingShadowDecl>(D))
4621 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4622
4623 FunctionTemplateDecl *ConvTemplate
4624 = dyn_cast<FunctionTemplateDecl>(D);
4625 CXXConversionDecl *Conv;
4626 if (ConvTemplate)
4627 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4628 else
4629 Conv = cast<CXXConversionDecl>(D);
4630
4631 if (AllowRvalues) {
4632 // If we are initializing an rvalue reference, don't permit conversion
4633 // functions that return lvalues.
4634 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4635 const ReferenceType *RefType
4636 = Conv->getConversionType()->getAs<LValueReferenceType>();
4637 if (RefType && !RefType->getPointeeType()->isFunctionType())
4638 continue;
4639 }
4640
4641 if (!ConvTemplate &&
4642 S.CompareReferenceRelationship(
4643 DeclLoc,
4644 Conv->getConversionType()
4645 .getNonReferenceType()
4646 .getUnqualifiedType(),
4647 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4648 Sema::Ref_Incompatible)
4649 continue;
4650 } else {
4651 // If the conversion function doesn't return a reference type,
4652 // it can't be considered for this conversion. An rvalue reference
4653 // is only acceptable if its referencee is a function type.
4654
4655 const ReferenceType *RefType =
4656 Conv->getConversionType()->getAs<ReferenceType>();
4657 if (!RefType ||
4658 (!RefType->isLValueReferenceType() &&
4659 !RefType->getPointeeType()->isFunctionType()))
4660 continue;
4661 }
4662
4663 if (ConvTemplate)
4664 S.AddTemplateConversionCandidate(
4665 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4666 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4667 else
4668 S.AddConversionCandidate(
4669 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4670 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4671 }
4672
4673 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4674
4675 OverloadCandidateSet::iterator Best;
4676 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4677 case OR_Success:
4678 // C++ [over.ics.ref]p1:
4679 //
4680 // [...] If the parameter binds directly to the result of
4681 // applying a conversion function to the argument
4682 // expression, the implicit conversion sequence is a
4683 // user-defined conversion sequence (13.3.3.1.2), with the
4684 // second standard conversion sequence either an identity
4685 // conversion or, if the conversion function returns an
4686 // entity of a type that is a derived class of the parameter
4687 // type, a derived-to-base Conversion.
4688 if (!Best->FinalConversion.DirectBinding)
4689 return false;
4690
4691 ICS.setUserDefined();
4692 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4693 ICS.UserDefined.After = Best->FinalConversion;
4694 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4695 ICS.UserDefined.ConversionFunction = Best->Function;
4696 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4697 ICS.UserDefined.EllipsisConversion = false;
4698 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4700, __PRETTY_FUNCTION__))
4699 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4700, __PRETTY_FUNCTION__))
4700 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4700, __PRETTY_FUNCTION__))
;
4701 return true;
4702
4703 case OR_Ambiguous:
4704 ICS.setAmbiguous();
4705 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4706 Cand != CandidateSet.end(); ++Cand)
4707 if (Cand->Best)
4708 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4709 return true;
4710
4711 case OR_No_Viable_Function:
4712 case OR_Deleted:
4713 // There was no suitable conversion, or we found a deleted
4714 // conversion; continue with other checks.
4715 return false;
4716 }
4717
4718 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4718)
;
4719}
4720
4721/// Compute an implicit conversion sequence for reference
4722/// initialization.
4723static ImplicitConversionSequence
4724TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4725 SourceLocation DeclLoc,
4726 bool SuppressUserConversions,
4727 bool AllowExplicit) {
4728 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 4728, __PRETTY_FUNCTION__))
;
4729
4730 // Most paths end in a failed conversion.
4731 ImplicitConversionSequence ICS;
4732 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4733
4734 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4735 QualType T2 = Init->getType();
4736
4737 // If the initializer is the address of an overloaded function, try
4738 // to resolve the overloaded function. If all goes well, T2 is the
4739 // type of the resulting function.
4740 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4741 DeclAccessPair Found;
4742 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4743 false, Found))
4744 T2 = Fn->getType();
4745 }
4746
4747 // Compute some basic properties of the types and the initializer.
4748 bool isRValRef = DeclType->isRValueReferenceType();
4749 Expr::Classification InitCategory = Init->Classify(S.Context);
4750
4751 Sema::ReferenceConversions RefConv;
4752 Sema::ReferenceCompareResult RefRelationship =
4753 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4754
4755 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4756 ICS.setStandard();
4757 ICS.Standard.First = ICK_Identity;
4758 // FIXME: A reference binding can be a function conversion too. We should
4759 // consider that when ordering reference-to-function bindings.
4760 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4761 ? ICK_Derived_To_Base
4762 : (RefConv & Sema::ReferenceConversions::ObjC)
4763 ? ICK_Compatible_Conversion
4764 : ICK_Identity;
4765 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4766 // a reference binding that performs a non-top-level qualification
4767 // conversion as a qualification conversion, not as an identity conversion.
4768 ICS.Standard.Third = (RefConv &
4769 Sema::ReferenceConversions::NestedQualification)
4770 ? ICK_Qualification
4771 : ICK_Identity;
4772 ICS.Standard.setFromType(T2);
4773 ICS.Standard.setToType(0, T2);
4774 ICS.Standard.setToType(1, T1);
4775 ICS.Standard.setToType(2, T1);
4776 ICS.Standard.ReferenceBinding = true;
4777 ICS.Standard.DirectBinding = BindsDirectly;
4778 ICS.Standard.IsLvalueReference = !isRValRef;
4779 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4780 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4781 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4782 ICS.Standard.ObjCLifetimeConversionBinding =
4783 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4784 ICS.Standard.CopyConstructor = nullptr;
4785 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4786 };
4787
4788 // C++0x [dcl.init.ref]p5:
4789 // A reference to type "cv1 T1" is initialized by an expression
4790 // of type "cv2 T2" as follows:
4791
4792 // -- If reference is an lvalue reference and the initializer expression
4793 if (!isRValRef) {
4794 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4795 // reference-compatible with "cv2 T2," or
4796 //
4797 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4798 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4799 // C++ [over.ics.ref]p1:
4800 // When a parameter of reference type binds directly (8.5.3)
4801 // to an argument expression, the implicit conversion sequence
4802 // is the identity conversion, unless the argument expression
4803 // has a type that is a derived class of the parameter type,
4804 // in which case the implicit conversion sequence is a
4805 // derived-to-base Conversion (13.3.3.1).
4806 SetAsReferenceBinding(/*BindsDirectly=*/true);
4807
4808 // Nothing more to do: the inaccessibility/ambiguity check for
4809 // derived-to-base conversions is suppressed when we're
4810 // computing the implicit conversion sequence (C++
4811 // [over.best.ics]p2).
4812 return ICS;
4813 }
4814
4815 // -- has a class type (i.e., T2 is a class type), where T1 is
4816 // not reference-related to T2, and can be implicitly
4817 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4818 // is reference-compatible with "cv3 T3" 92) (this
4819 // conversion is selected by enumerating the applicable
4820 // conversion functions (13.3.1.6) and choosing the best
4821 // one through overload resolution (13.3)),
4822 if (!SuppressUserConversions && T2->isRecordType() &&
4823 S.isCompleteType(DeclLoc, T2) &&
4824 RefRelationship == Sema::Ref_Incompatible) {
4825 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4826 Init, T2, /*AllowRvalues=*/false,
4827 AllowExplicit))
4828 return ICS;
4829 }
4830 }
4831
4832 // -- Otherwise, the reference shall be an lvalue reference to a
4833 // non-volatile const type (i.e., cv1 shall be const), or the reference
4834 // shall be an rvalue reference.
4835 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4836 return ICS;
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 &&
4927 isRValRef && Init->Classify(S.Context).isLValue())
4928 return ICS;
4929
4930 // C++ [over.ics.ref]p2:
4931 // When a parameter of reference type is not bound directly to
4932 // an argument expression, the conversion sequence is the one
4933 // required to convert the argument expression to the
4934 // underlying type of the reference according to
4935 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4936 // to copy-initializing a temporary of the underlying type with
4937 // the argument expression. Any difference in top-level
4938 // cv-qualification is subsumed by the initialization itself
4939 // and does not constitute a conversion.
4940 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4941 AllowedExplicit::None,
4942 /*InOverloadResolution=*/false,
4943 /*CStyle=*/false,
4944 /*AllowObjCWritebackConversion=*/false,
4945 /*AllowObjCConversionOnExplicit=*/false);
4946
4947 // Of course, that's still a reference binding.
4948 if (ICS.isStandard()) {
4949 ICS.Standard.ReferenceBinding = true;
4950 ICS.Standard.IsLvalueReference = !isRValRef;
4951 ICS.Standard.BindsToFunctionLvalue = false;
4952 ICS.Standard.BindsToRvalue = true;
4953 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4954 ICS.Standard.ObjCLifetimeConversionBinding = false;
4955 } else if (ICS.isUserDefined()) {
4956 const ReferenceType *LValRefType =
4957 ICS.UserDefined.ConversionFunction->getReturnType()
4958 ->getAs<LValueReferenceType>();
4959
4960 // C++ [over.ics.ref]p3:
4961 // Except for an implicit object parameter, for which see 13.3.1, a
4962 // standard conversion sequence cannot be formed if it requires [...]
4963 // binding an rvalue reference to an lvalue other than a function
4964 // lvalue.
4965 // Note that the function case is not possible here.
4966 if (DeclType->isRValueReferenceType() && LValRefType) {
4967 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4968 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4969 // reference to an rvalue!
4970 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4971 return ICS;
4972 }
4973
4974 ICS.UserDefined.After.ReferenceBinding = true;
4975 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4976 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4977 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4978 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4979 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4980 }
4981
4982 return ICS;
4983}
4984
4985static ImplicitConversionSequence
4986TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4987 bool SuppressUserConversions,
4988 bool InOverloadResolution,
4989 bool AllowObjCWritebackConversion,
4990 bool AllowExplicit = false);
4991
4992/// TryListConversion - Try to copy-initialize a value of type ToType from the
4993/// initializer list From.
4994static ImplicitConversionSequence
4995TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4996 bool SuppressUserConversions,
4997 bool InOverloadResolution,
4998 bool AllowObjCWritebackConversion) {
4999 // C++11 [over.ics.list]p1:
5000 // When an argument is an initializer list, it is not an expression and
5001 // special rules apply for converting it to a parameter type.
5002
5003 ImplicitConversionSequence Result;
5004 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5005
5006 // We need a complete type for what follows. Incomplete types can never be
5007 // initialized from init lists.
5008 if (!S.isCompleteType(From->getBeginLoc(), ToType))
5009 return Result;
5010
5011 // Per DR1467:
5012 // If the parameter type is a class X and the initializer list has a single
5013 // element of type cv U, where U is X or a class derived from X, the
5014 // implicit conversion sequence is the one required to convert the element
5015 // to the parameter type.
5016 //
5017 // Otherwise, if the parameter type is a character array [... ]
5018 // and the initializer list has a single element that is an
5019 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5020 // implicit conversion sequence is the identity conversion.
5021 if (From->getNumInits() == 1) {
5022 if (ToType->isRecordType()) {
5023 QualType InitType = From->getInit(0)->getType();
5024 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5025 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5026 return TryCopyInitialization(S, From->getInit(0), ToType,
5027 SuppressUserConversions,
5028 InOverloadResolution,
5029 AllowObjCWritebackConversion);
5030 }
5031
5032 if (const auto *AT = S.Context.getAsArrayType(ToType)) {
5033 if (S.IsStringInit(From->getInit(0), AT)) {
5034 InitializedEntity Entity =
5035 InitializedEntity::InitializeParameter(S.Context, ToType,
5036 /*Consumed=*/false);
5037 if (S.CanPerformCopyInitialization(Entity, From)) {
5038 Result.setStandard();
5039 Result.Standard.setAsIdentityConversion();
5040 Result.Standard.setFromType(ToType);
5041 Result.Standard.setAllToTypes(ToType);
5042 return Result;
5043 }
5044 }
5045 }
5046 }
5047
5048 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5049 // C++11 [over.ics.list]p2:
5050 // If the parameter type is std::initializer_list<X> or "array of X" and
5051 // all the elements can be implicitly converted to X, the implicit
5052 // conversion sequence is the worst conversion necessary to convert an
5053 // element of the list to X.
5054 //
5055 // C++14 [over.ics.list]p3:
5056 // Otherwise, if the parameter type is "array of N X", if the initializer
5057 // list has exactly N elements or if it has fewer than N elements and X is
5058 // default-constructible, and if all the elements of the initializer list
5059 // can be implicitly converted to X, the implicit conversion sequence is
5060 // the worst conversion necessary to convert an element of the list to X.
5061 //
5062 // FIXME: We're missing a lot of these checks.
5063 bool toStdInitializerList = false;
5064 QualType X;
5065 if (ToType->isArrayType())
5066 X = S.Context.getAsArrayType(ToType)->getElementType();
5067 else
5068 toStdInitializerList = S.isStdInitializerList(ToType, &X);
5069 if (!X.isNull()) {
5070 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5071 Expr *Init = From->getInit(i);
5072 ImplicitConversionSequence ICS =
5073 TryCopyInitialization(S, Init, X, SuppressUserConversions,
5074 InOverloadResolution,
5075 AllowObjCWritebackConversion);
5076 // If a single element isn't convertible, fail.
5077 if (ICS.isBad()) {
5078 Result = ICS;
5079 break;
5080 }
5081 // Otherwise, look for the worst conversion.
5082 if (Result.isBad() || CompareImplicitConversionSequences(
5083 S, From->getBeginLoc(), ICS, Result) ==
5084 ImplicitConversionSequence::Worse)
5085 Result = ICS;
5086 }
5087
5088 // For an empty list, we won't have computed any conversion sequence.
5089 // Introduce the identity conversion sequence.
5090 if (From->getNumInits() == 0) {
5091 Result.setStandard();
5092 Result.Standard.setAsIdentityConversion();
5093 Result.Standard.setFromType(ToType);
5094 Result.Standard.setAllToTypes(ToType);
5095 }
5096
5097 Result.setStdInitializerListElement(toStdInitializerList);
5098 return Result;
5099 }
5100
5101 // C++14 [over.ics.list]p4:
5102 // C++11 [over.ics.list]p3:
5103 // Otherwise, if the parameter is a non-aggregate class X and overload
5104 // resolution chooses a single best constructor [...] the implicit
5105 // conversion sequence is a user-defined conversion sequence. If multiple
5106 // constructors are viable but none is better than the others, the
5107 // implicit conversion sequence is a user-defined conversion sequence.
5108 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5109 // This function can deal with initializer lists.
5110 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5111 AllowedExplicit::None,
5112 InOverloadResolution, /*CStyle=*/false,
5113 AllowObjCWritebackConversion,
5114 /*AllowObjCConversionOnExplicit=*/false);
5115 }
5116
5117 // C++14 [over.ics.list]p5:
5118 // C++11 [over.ics.list]p4:
5119 // Otherwise, if the parameter has an aggregate type which can be
5120 // initialized from the initializer list [...] the implicit conversion
5121 // sequence is a user-defined conversion sequence.
5122 if (ToType->isAggregateType()) {
5123 // Type is an aggregate, argument is an init list. At this point it comes
5124 // down to checking whether the initialization works.
5125 // FIXME: Find out whether this parameter is consumed or not.
5126 InitializedEntity Entity =
5127 InitializedEntity::InitializeParameter(S.Context, ToType,
5128 /*Consumed=*/false);
5129 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5130 From)) {
5131 Result.setUserDefined();
5132 Result.UserDefined.Before.setAsIdentityConversion();
5133 // Initializer lists don't have a type.
5134 Result.UserDefined.Before.setFromType(QualType());
5135 Result.UserDefined.Before.setAllToTypes(QualType());
5136
5137 Result.UserDefined.After.setAsIdentityConversion();
5138 Result.UserDefined.After.setFromType(ToType);
5139 Result.UserDefined.After.setAllToTypes(ToType);
5140 Result.UserDefined.ConversionFunction = nullptr;
5141 }
5142 return Result;
5143 }
5144
5145 // C++14 [over.ics.list]p6:
5146 // C++11 [over.ics.list]p5:
5147 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5148 if (ToType->isReferenceType()) {
5149 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5150 // mention initializer lists in any way. So we go by what list-
5151 // initialization would do and try to extrapolate from that.
5152
5153 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5154
5155 // If the initializer list has a single element that is reference-related
5156 // to the parameter type, we initialize the reference from that.
5157 if (From->getNumInits() == 1) {
5158 Expr *Init = From->getInit(0);
5159
5160 QualType T2 = Init->getType();
5161
5162 // If the initializer is the address of an overloaded function, try
5163 // to resolve the overloaded function. If all goes well, T2 is the
5164 // type of the resulting function.
5165 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5166 DeclAccessPair Found;
5167 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5168 Init, ToType, false, Found))
5169 T2 = Fn->getType();
5170 }
5171
5172 // Compute some basic properties of the types and the initializer.
5173 Sema::ReferenceCompareResult RefRelationship =
5174 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5175
5176 if (RefRelationship >= Sema::Ref_Related) {
5177 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5178 SuppressUserConversions,
5179 /*AllowExplicit=*/false);
5180 }
5181 }
5182
5183 // Otherwise, we bind the reference to a temporary created from the
5184 // initializer list.
5185 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5186 InOverloadResolution,
5187 AllowObjCWritebackConversion);
5188 if (Result.isFailure())
5189 return Result;
5190 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5191, __PRETTY_FUNCTION__))
5191 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5191, __PRETTY_FUNCTION__))
;
5192
5193 // Can we even bind to a temporary?
5194 if (ToType->isRValueReferenceType() ||
5195 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5196 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5197 Result.UserDefined.After;
5198 SCS.ReferenceBinding = true;
5199 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5200 SCS.BindsToRvalue = true;
5201 SCS.BindsToFunctionLvalue = false;
5202 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5203 SCS.ObjCLifetimeConversionBinding = false;
5204 } else
5205 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5206 From, ToType);
5207 return Result;
5208 }
5209
5210 // C++14 [over.ics.list]p7:
5211 // C++11 [over.ics.list]p6:
5212 // Otherwise, if the parameter type is not a class:
5213 if (!ToType->isRecordType()) {
5214 // - if the initializer list has one element that is not itself an
5215 // initializer list, the implicit conversion sequence is the one
5216 // required to convert the element to the parameter type.
5217 unsigned NumInits = From->getNumInits();
5218 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5219 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5220 SuppressUserConversions,
5221 InOverloadResolution,
5222 AllowObjCWritebackConversion);
5223 // - if the initializer list has no elements, the implicit conversion
5224 // sequence is the identity conversion.
5225 else if (NumInits == 0) {
5226 Result.setStandard();
5227 Result.Standard.setAsIdentityConversion();
5228 Result.Standard.setFromType(ToType);
5229 Result.Standard.setAllToTypes(ToType);
5230 }
5231 return Result;
5232 }
5233
5234 // C++14 [over.ics.list]p8:
5235 // C++11 [over.ics.list]p7:
5236 // In all cases other than those enumerated above, no conversion is possible
5237 return Result;
5238}
5239
5240/// TryCopyInitialization - Try to copy-initialize a value of type
5241/// ToType from the expression From. Return the implicit conversion
5242/// sequence required to pass this argument, which may be a bad
5243/// conversion sequence (meaning that the argument cannot be passed to
5244/// a parameter of this type). If @p SuppressUserConversions, then we
5245/// do not permit any user-defined conversion sequences.
5246static ImplicitConversionSequence
5247TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5248 bool SuppressUserConversions,
5249 bool InOverloadResolution,
5250 bool AllowObjCWritebackConversion,
5251 bool AllowExplicit) {
5252 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5253 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5254 InOverloadResolution,AllowObjCWritebackConversion);
5255
5256 if (ToType->isReferenceType())
5257 return TryReferenceInit(S, From, ToType,
5258 /*FIXME:*/ From->getBeginLoc(),
5259 SuppressUserConversions, AllowExplicit);
5260
5261 return TryImplicitConversion(S, From, ToType,
5262 SuppressUserConversions,
5263 AllowedExplicit::None,
5264 InOverloadResolution,
5265 /*CStyle=*/false,
5266 AllowObjCWritebackConversion,
5267 /*AllowObjCConversionOnExplicit=*/false);
5268}
5269
5270static bool TryCopyInitialization(const CanQualType FromQTy,
5271 const CanQualType ToQTy,
5272 Sema &S,
5273 SourceLocation Loc,
5274 ExprValueKind FromVK) {
5275 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5276 ImplicitConversionSequence ICS =
5277 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5278
5279 return !ICS.isBad();
5280}
5281
5282/// TryObjectArgumentInitialization - Try to initialize the object
5283/// parameter of the given member function (@c Method) from the
5284/// expression @p From.
5285static ImplicitConversionSequence
5286TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5287 Expr::Classification FromClassification,
5288 CXXMethodDecl *Method,
5289 CXXRecordDecl *ActingContext) {
5290 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5291 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5292 // const volatile object.
5293 Qualifiers Quals = Method->getMethodQualifiers();
5294 if (isa<CXXDestructorDecl>(Method)) {
5295 Quals.addConst();
5296 Quals.addVolatile();
5297 }
5298
5299 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5300
5301 // Set up the conversion sequence as a "bad" conversion, to allow us
5302 // to exit early.
5303 ImplicitConversionSequence ICS;
5304
5305 // We need to have an object of class type.
5306 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5307 FromType = PT->getPointeeType();
5308
5309 // When we had a pointer, it's implicitly dereferenced, so we
5310 // better have an lvalue.
5311 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5311, __PRETTY_FUNCTION__))
;
5312 }
5313
5314 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5314, __PRETTY_FUNCTION__))
;
5315
5316 // C++0x [over.match.funcs]p4:
5317 // For non-static member functions, the type of the implicit object
5318 // parameter is
5319 //
5320 // - "lvalue reference to cv X" for functions declared without a
5321 // ref-qualifier or with the & ref-qualifier
5322 // - "rvalue reference to cv X" for functions declared with the &&
5323 // ref-qualifier
5324 //
5325 // where X is the class of which the function is a member and cv is the
5326 // cv-qualification on the member function declaration.
5327 //
5328 // However, when finding an implicit conversion sequence for the argument, we
5329 // are not allowed to perform user-defined conversions
5330 // (C++ [over.match.funcs]p5). We perform a simplified version of
5331 // reference binding here, that allows class rvalues to bind to
5332 // non-constant references.
5333
5334 // First check the qualifiers.
5335 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5336 if (ImplicitParamType.getCVRQualifiers()
5337 != FromTypeCanon.getLocalCVRQualifiers() &&
5338 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5339 ICS.setBad(BadConversionSequence::bad_qualifiers,
5340 FromType, ImplicitParamType);
5341 return ICS;
5342 }
5343
5344 if (FromTypeCanon.hasAddressSpace()) {
5345 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5346 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5347 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5348 ICS.setBad(BadConversionSequence::bad_qualifiers,
5349 FromType, ImplicitParamType);
5350 return ICS;
5351 }
5352 }
5353
5354 // Check that we have either the same type or a derived type. It
5355 // affects the conversion rank.
5356 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5357 ImplicitConversionKind SecondKind;
5358 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5359 SecondKind = ICK_Identity;
5360 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5361 SecondKind = ICK_Derived_To_Base;
5362 else {
5363 ICS.setBad(BadConversionSequence::unrelated_class,
5364 FromType, ImplicitParamType);
5365 return ICS;
5366 }
5367
5368 // Check the ref-qualifier.
5369 switch (Method->getRefQualifier()) {
5370 case RQ_None:
5371 // Do nothing; we don't care about lvalueness or rvalueness.
5372 break;
5373
5374 case RQ_LValue:
5375 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5376 // non-const lvalue reference cannot bind to an rvalue
5377 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5378 ImplicitParamType);
5379 return ICS;
5380 }
5381 break;
5382
5383 case RQ_RValue:
5384 if (!FromClassification.isRValue()) {
5385 // rvalue reference cannot bind to an lvalue
5386 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5387 ImplicitParamType);
5388 return ICS;
5389 }
5390 break;
5391 }
5392
5393 // Success. Mark this as a reference binding.
5394 ICS.setStandard();
5395 ICS.Standard.setAsIdentityConversion();
5396 ICS.Standard.Second = SecondKind;
5397 ICS.Standard.setFromType(FromType);
5398 ICS.Standard.setAllToTypes(ImplicitParamType);
5399 ICS.Standard.ReferenceBinding = true;
5400 ICS.Standard.DirectBinding = true;
5401 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5402 ICS.Standard.BindsToFunctionLvalue = false;
5403 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5404 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5405 = (Method->getRefQualifier() == RQ_None);
5406 return ICS;
5407}
5408
5409/// PerformObjectArgumentInitialization - Perform initialization of
5410/// the implicit object parameter for the given Method with the given
5411/// expression.
5412ExprResult
5413Sema::PerformObjectArgumentInitialization(Expr *From,
5414 NestedNameSpecifier *Qualifier,
5415 NamedDecl *FoundDecl,
5416 CXXMethodDecl *Method) {
5417 QualType FromRecordType, DestType;
5418 QualType ImplicitParamRecordType =
5419 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5420
5421 Expr::Classification FromClassification;
5422 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5423 FromRecordType = PT->getPointeeType();
5424 DestType = Method->getThisType();
5425 FromClassification = Expr::Classification::makeSimpleLValue();
5426 } else {
5427 FromRecordType = From->getType();
5428 DestType = ImplicitParamRecordType;
5429 FromClassification = From->Classify(Context);
5430
5431 // When performing member access on an rvalue, materialize a temporary.
5432 if (From->isRValue()) {
5433 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5434 Method->getRefQualifier() !=
5435 RefQualifierKind::RQ_RValue);
5436 }
5437 }
5438
5439 // Note that we always use the true parent context when performing
5440 // the actual argument initialization.
5441 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5442 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5443 Method->getParent());
5444 if (ICS.isBad()) {
5445 switch (ICS.Bad.Kind) {
5446 case BadConversionSequence::bad_qualifiers: {
5447 Qualifiers FromQs = FromRecordType.getQualifiers();
5448 Qualifiers ToQs = DestType.getQualifiers();
5449 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5450 if (CVR) {
5451 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5452 << Method->getDeclName() << FromRecordType << (CVR - 1)
5453 << From->getSourceRange();
5454 Diag(Method->getLocation(), diag::note_previous_decl)
5455 << Method->getDeclName();
5456 return ExprError();
5457 }
5458 break;
5459 }
5460
5461 case BadConversionSequence::lvalue_ref_to_rvalue:
5462 case BadConversionSequence::rvalue_ref_to_lvalue: {
5463 bool IsRValueQualified =
5464 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5465 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5466 << Method->getDeclName() << FromClassification.isRValue()
5467 << IsRValueQualified;
5468 Diag(Method->getLocation(), diag::note_previous_decl)
5469 << Method->getDeclName();
5470 return ExprError();
5471 }
5472
5473 case BadConversionSequence::no_conversion:
5474 case BadConversionSequence::unrelated_class:
5475 break;
5476 }
5477
5478 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5479 << ImplicitParamRecordType << FromRecordType
5480 << From->getSourceRange();
5481 }
5482
5483 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5484 ExprResult FromRes =
5485 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5486 if (FromRes.isInvalid())
5487 return ExprError();
5488 From = FromRes.get();
5489 }
5490
5491 if (!Context.hasSameType(From->getType(), DestType)) {
5492 CastKind CK;
5493 QualType PteeTy = DestType->getPointeeType();
5494 LangAS DestAS =
5495 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5496 if (FromRecordType.getAddressSpace() != DestAS)
5497 CK = CK_AddressSpaceConversion;
5498 else
5499 CK = CK_NoOp;
5500 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5501 }
5502 return From;
5503}
5504
5505/// TryContextuallyConvertToBool - Attempt to contextually convert the
5506/// expression From to bool (C++0x [conv]p3).
5507static ImplicitConversionSequence
5508TryContextuallyConvertToBool(Sema &S, Expr *From) {
5509 // C++ [dcl.init]/17.8:
5510 // - Otherwise, if the initialization is direct-initialization, the source
5511 // type is std::nullptr_t, and the destination type is bool, the initial
5512 // value of the object being initialized is false.
5513 if (From->getType()->isNullPtrType())
5514 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5515 S.Context.BoolTy,
5516 From->isGLValue());
5517
5518 // All other direct-initialization of bool is equivalent to an implicit
5519 // conversion to bool in which explicit conversions are permitted.
5520 return TryImplicitConversion(S, From, S.Context.BoolTy,
5521 /*SuppressUserConversions=*/false,
5522 AllowedExplicit::Conversions,
5523 /*InOverloadResolution=*/false,
5524 /*CStyle=*/false,
5525 /*AllowObjCWritebackConversion=*/false,
5526 /*AllowObjCConversionOnExplicit=*/false);
5527}
5528
5529/// PerformContextuallyConvertToBool - Perform a contextual conversion
5530/// of the expression From to bool (C++0x [conv]p3).
5531ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5532 if (checkPlaceholderForOverload(*this, From))
5533 return ExprError();
5534
5535 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5536 if (!ICS.isBad())
5537 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5538
5539 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5540 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5541 << From->getType() << From->getSourceRange();
5542 return ExprError();
5543}
5544
5545/// Check that the specified conversion is permitted in a converted constant
5546/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5547/// is acceptable.
5548static bool CheckConvertedConstantConversions(Sema &S,
5549 StandardConversionSequence &SCS) {
5550 // Since we know that the target type is an integral or unscoped enumeration
5551 // type, most conversion kinds are impossible. All possible First and Third
5552 // conversions are fine.
5553 switch (SCS.Second) {
5554 case ICK_Identity:
5555 case ICK_Integral_Promotion:
5556 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5557 case ICK_Zero_Queue_Conversion:
5558 return true;
5559
5560 case ICK_Boolean_Conversion:
5561 // Conversion from an integral or unscoped enumeration type to bool is
5562 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5563 // conversion, so we allow it in a converted constant expression.
5564 //
5565 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5566 // a lot of popular code. We should at least add a warning for this
5567 // (non-conforming) extension.
5568 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5569 SCS.getToType(2)->isBooleanType();
5570
5571 case ICK_Pointer_Conversion:
5572 case ICK_Pointer_Member:
5573 // C++1z: null pointer conversions and null member pointer conversions are
5574 // only permitted if the source type is std::nullptr_t.
5575 return SCS.getFromType()->isNullPtrType();
5576
5577 case ICK_Floating_Promotion:
5578 case ICK_Complex_Promotion:
5579 case ICK_Floating_Conversion:
5580 case ICK_Complex_Conversion:
5581 case ICK_Floating_Integral:
5582 case ICK_Compatible_Conversion:
5583 case ICK_Derived_To_Base:
5584 case ICK_Vector_Conversion:
5585 case ICK_SVE_Vector_Conversion:
5586 case ICK_Vector_Splat:
5587 case ICK_Complex_Real:
5588 case ICK_Block_Pointer_Conversion:
5589 case ICK_TransparentUnionConversion:
5590 case ICK_Writeback_Conversion:
5591 case ICK_Zero_Event_Conversion:
5592 case ICK_C_Only_Conversion:
5593 case ICK_Incompatible_Pointer_Conversion:
5594 return false;
5595
5596 case ICK_Lvalue_To_Rvalue:
5597 case ICK_Array_To_Pointer:
5598 case ICK_Function_To_Pointer:
5599 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5599)
;
5600
5601 case ICK_Function_Conversion:
5602 case ICK_Qualification:
5603 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5603)
;
5604
5605 case ICK_Num_Conversion_Kinds:
5606 break;
5607 }
5608
5609 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5609)
;
5610}
5611
5612/// CheckConvertedConstantExpression - Check that the expression From is a
5613/// converted constant expression of type T, perform the conversion and produce
5614/// the converted expression, per C++11 [expr.const]p3.
5615static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5616 QualType T, APValue &Value,
5617 Sema::CCEKind CCE,
5618 bool RequireInt,
5619 NamedDecl *Dest) {
5620 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5621, __PRETTY_FUNCTION__))
5621 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5621, __PRETTY_FUNCTION__))
;
5622
5623 if (checkPlaceholderForOverload(S, From))
5624 return ExprError();
5625
5626 // C++1z [expr.const]p3:
5627 // A converted constant expression of type T is an expression,
5628 // implicitly converted to type T, where the converted
5629 // expression is a constant expression and the implicit conversion
5630 // sequence contains only [... list of conversions ...].
5631 // C++1z [stmt.if]p2:
5632 // If the if statement is of the form if constexpr, the value of the
5633 // condition shall be a contextually converted constant expression of type
5634 // bool.
5635 ImplicitConversionSequence ICS =
5636 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5637 ? TryContextuallyConvertToBool(S, From)
5638 : TryCopyInitialization(S, From, T,
5639 /*SuppressUserConversions=*/false,
5640 /*InOverloadResolution=*/false,
5641 /*AllowObjCWritebackConversion=*/false,
5642 /*AllowExplicit=*/false);
5643 StandardConversionSequence *SCS = nullptr;
5644 switch (ICS.getKind()) {
5645 case ImplicitConversionSequence::StandardConversion:
5646 SCS = &ICS.Standard;
5647 break;
5648 case ImplicitConversionSequence::UserDefinedConversion:
5649 if (T->isRecordType())
5650 SCS = &ICS.UserDefined.Before;
5651 else
5652 SCS = &ICS.UserDefined.After;
5653 break;
5654 case ImplicitConversionSequence::AmbiguousConversion:
5655 case ImplicitConversionSequence::BadConversion:
5656 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5657 return S.Diag(From->getBeginLoc(),
5658 diag::err_typecheck_converted_constant_expression)
5659 << From->getType() << From->getSourceRange() << T;
5660 return ExprError();
5661
5662 case ImplicitConversionSequence::EllipsisConversion:
5663 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5663)
;
5664 }
5665
5666 // Check that we would only use permitted conversions.
5667 if (!CheckConvertedConstantConversions(S, *SCS)) {
5668 return S.Diag(From->getBeginLoc(),
5669 diag::err_typecheck_converted_constant_expression_disallowed)
5670 << From->getType() << From->getSourceRange() << T;
5671 }
5672 // [...] and where the reference binding (if any) binds directly.
5673 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5674 return S.Diag(From->getBeginLoc(),
5675 diag::err_typecheck_converted_constant_expression_indirect)
5676 << From->getType() << From->getSourceRange() << T;
5677 }
5678
5679 // Usually we can simply apply the ImplicitConversionSequence we formed
5680 // earlier, but that's not guaranteed to work when initializing an object of
5681 // class type.
5682 ExprResult Result;
5683 if (T->isRecordType()) {
5684 assert(CCE == Sema::CCEK_TemplateArg &&((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5685, __PRETTY_FUNCTION__))
5685 "unexpected class type converted constant expr")((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5685, __PRETTY_FUNCTION__))
;
5686 Result = S.PerformCopyInitialization(
5687 InitializedEntity::InitializeTemplateParameter(
5688 T, cast<NonTypeTemplateParmDecl>(Dest)),
5689 SourceLocation(), From);
5690 } else {
5691 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5692 }
5693 if (Result.isInvalid())
5694 return Result;
5695
5696 // C++2a [intro.execution]p5:
5697 // A full-expression is [...] a constant-expression [...]
5698 Result =
5699 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5700 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5701 if (Result.isInvalid())
5702 return Result;
5703
5704 // Check for a narrowing implicit conversion.
5705 bool ReturnPreNarrowingValue = false;
5706 APValue PreNarrowingValue;
5707 QualType PreNarrowingType;
5708 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5709 PreNarrowingType)) {
5710 case NK_Dependent_Narrowing:
5711 // Implicit conversion to a narrower type, but the expression is
5712 // value-dependent so we can't tell whether it's actually narrowing.
5713 case NK_Variable_Narrowing:
5714 // Implicit conversion to a narrower type, and the value is not a constant
5715 // expression. We'll diagnose this in a moment.
5716 case NK_Not_Narrowing:
5717 break;
5718
5719 case NK_Constant_Narrowing:
5720 if (CCE == Sema::CCEK_ArrayBound &&
5721 PreNarrowingType->isIntegralOrEnumerationType() &&
5722 PreNarrowingValue.isInt()) {
5723 // Don't diagnose array bound narrowing here; we produce more precise
5724 // errors by allowing the un-narrowed value through.
5725 ReturnPreNarrowingValue = true;
5726 break;
5727 }
5728 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5729 << CCE << /*Constant*/ 1
5730 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5731 break;
5732
5733 case NK_Type_Narrowing:
5734 // FIXME: It would be better to diagnose that the expression is not a
5735 // constant expression.
5736 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5737 << CCE << /*Constant*/ 0 << From->getType() << T;
5738 break;
5739 }
5740
5741 if (Result.get()->isValueDependent()) {
5742 Value = APValue();
5743 return Result;
5744 }
5745
5746 // Check the expression is a constant expression.
5747 SmallVector<PartialDiagnosticAt, 8> Notes;
5748 Expr::EvalResult Eval;
5749 Eval.Diag = &Notes;
5750
5751 ConstantExprKind Kind;
5752 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5753 Kind = ConstantExprKind::ClassTemplateArgument;
5754 else if (CCE == Sema::CCEK_TemplateArg)
5755 Kind = ConstantExprKind::NonClassTemplateArgument;
5756 else
5757 Kind = ConstantExprKind::Normal;
5758
5759 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5760 (RequireInt && !Eval.Val.isInt())) {
5761 // The expression can't be folded, so we can't keep it at this position in
5762 // the AST.
5763 Result = ExprError();
5764 } else {
5765 Value = Eval.Val;
5766
5767 if (Notes.empty()) {
5768 // It's a constant expression.
5769 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5770 if (ReturnPreNarrowingValue)
5771 Value = std::move(PreNarrowingValue);
5772 return E;
5773 }
5774 }
5775
5776 // It's not a constant expression. Produce an appropriate diagnostic.
5777 if (Notes.size() == 1 &&
5778 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5779 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5780 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5781 diag::note_constexpr_invalid_template_arg) {
5782 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5783 for (unsigned I = 0; I < Notes.size(); ++I)
5784 S.Diag(Notes[I].first, Notes[I].second);
5785 } else {
5786 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5787 << CCE << From->getSourceRange();
5788 for (unsigned I = 0; I < Notes.size(); ++I)
5789 S.Diag(Notes[I].first, Notes[I].second);
5790 }
5791 return ExprError();
5792}
5793
5794ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5795 APValue &Value, CCEKind CCE,
5796 NamedDecl *Dest) {
5797 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5798 Dest);
5799}
5800
5801ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5802 llvm::APSInt &Value,
5803 CCEKind CCE) {
5804 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 5804, __PRETTY_FUNCTION__))
;
5805
5806 APValue V;
5807 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5808 /*Dest=*/nullptr);
5809 if (!R.isInvalid() && !R.get()->isValueDependent())
5810 Value = V.getInt();
5811 return R;
5812}
5813
5814
5815/// dropPointerConversions - If the given standard conversion sequence
5816/// involves any pointer conversions, remove them. This may change
5817/// the result type of the conversion sequence.
5818static void dropPointerConversion(StandardConversionSequence &SCS) {
5819 if (SCS.Second == ICK_Pointer_Conversion) {
5820 SCS.Second = ICK_Identity;
5821 SCS.Third = ICK_Identity;
5822 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5823 }
5824}
5825
5826/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5827/// convert the expression From to an Objective-C pointer type.
5828static ImplicitConversionSequence
5829TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5830 // Do an implicit conversion to 'id'.
5831 QualType Ty = S.Context.getObjCIdType();
5832 ImplicitConversionSequence ICS
5833 = TryImplicitConversion(S, From, Ty,
5834 // FIXME: Are these flags correct?
5835 /*SuppressUserConversions=*/false,
5836 AllowedExplicit::Conversions,
5837 /*InOverloadResolution=*/false,
5838 /*CStyle=*/false,
5839 /*AllowObjCWritebackConversion=*/false,
5840 /*AllowObjCConversionOnExplicit=*/true);
5841
5842 // Strip off any final conversions to 'id'.
5843 switch (ICS.getKind()) {
5844 case ImplicitConversionSequence::BadConversion:
5845 case ImplicitConversionSequence::AmbiguousConversion:
5846 case ImplicitConversionSequence::EllipsisConversion:
5847 break;
5848
5849 case ImplicitConversionSequence::UserDefinedConversion:
5850 dropPointerConversion(ICS.UserDefined.After);
5851 break;
5852
5853 case ImplicitConversionSequence::StandardConversion:
5854 dropPointerConversion(ICS.Standard);
5855 break;
5856 }
5857
5858 return ICS;
5859}
5860
5861/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5862/// conversion of the expression From to an Objective-C pointer type.
5863/// Returns a valid but null ExprResult if no conversion sequence exists.
5864ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5865 if (checkPlaceholderForOverload(*this, From))
5866 return ExprError();
5867
5868 QualType Ty = Context.getObjCIdType();
5869 ImplicitConversionSequence ICS =
5870 TryContextuallyConvertToObjCPointer(*this, From);
5871 if (!ICS.isBad())
5872 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5873 return ExprResult();
5874}
5875
5876/// Determine whether the provided type is an integral type, or an enumeration
5877/// type of a permitted flavor.
5878bool Sema::ICEConvertDiagnoser::match(QualType T) {
5879 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5880 : T->isIntegralOrUnscopedEnumerationType();
5881}
5882
5883static ExprResult
5884diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5885 Sema::ContextualImplicitConverter &Converter,
5886 QualType T, UnresolvedSetImpl &ViableConversions) {
5887
5888 if (Converter.Suppress)
5889 return ExprError();
5890
5891 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5892 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5893 CXXConversionDecl *Conv =
5894 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5895 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5896 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5897 }
5898 return From;
5899}
5900
5901static bool
5902diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5903 Sema::ContextualImplicitConverter &Converter,
5904 QualType T, bool HadMultipleCandidates,
5905 UnresolvedSetImpl &ExplicitConversions) {
5906 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5907 DeclAccessPair Found = ExplicitConversions[0];
5908 CXXConversionDecl *Conversion =
5909 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5910
5911 // The user probably meant to invoke the given explicit
5912 // conversion; use it.
5913 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5914 std::string TypeStr;
5915 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5916
5917 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5918 << FixItHint::CreateInsertion(From->getBeginLoc(),
5919 "static_cast<" + TypeStr + ">(")
5920 << FixItHint::CreateInsertion(
5921 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5922 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5923
5924 // If we aren't in a SFINAE context, build a call to the
5925 // explicit conversion function.
5926 if (SemaRef.isSFINAEContext())
5927 return true;
5928
5929 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5930 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5931 HadMultipleCandidates);
5932 if (Result.isInvalid())
5933 return true;
5934 // Record usage of conversion in an implicit cast.
5935 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5936 CK_UserDefinedConversion, Result.get(),
5937 nullptr, Result.get()->getValueKind(),
5938 SemaRef.CurFPFeatureOverrides());
5939 }
5940 return false;
5941}
5942
5943static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5944 Sema::ContextualImplicitConverter &Converter,
5945 QualType T, bool HadMultipleCandidates,
5946 DeclAccessPair &Found) {
5947 CXXConversionDecl *Conversion =
5948 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5949 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5950
5951 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5952 if (!Converter.SuppressConversion) {
5953 if (SemaRef.isSFINAEContext())
5954 return true;
5955
5956 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5957 << From->getSourceRange();
5958 }
5959
5960 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5961 HadMultipleCandidates);
5962 if (Result.isInvalid())
5963 return true;
5964 // Record usage of conversion in an implicit cast.
5965 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5966 CK_UserDefinedConversion, Result.get(),
5967 nullptr, Result.get()->getValueKind(),
5968 SemaRef.CurFPFeatureOverrides());
5969 return false;
5970}
5971
5972static ExprResult finishContextualImplicitConversion(
5973 Sema &SemaRef, SourceLocation Loc, Expr *From,
5974 Sema::ContextualImplicitConverter &Converter) {
5975 if (!Converter.match(From->getType()) && !Converter.Suppress)
5976 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5977 << From->getSourceRange();
5978
5979 return SemaRef.DefaultLvalueConversion(From);
5980}
5981
5982static void
5983collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5984 UnresolvedSetImpl &ViableConversions,
5985 OverloadCandidateSet &CandidateSet) {
5986 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5987 DeclAccessPair FoundDecl = ViableConversions[I];
5988 NamedDecl *D = FoundDecl.getDecl();
5989 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5990 if (isa<UsingShadowDecl>(D))
5991 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5992
5993 CXXConversionDecl *Conv;
5994 FunctionTemplateDecl *ConvTemplate;
5995 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5996 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5997 else
5998 Conv = cast<CXXConversionDecl>(D);
5999
6000 if (ConvTemplate)
6001 SemaRef.AddTemplateConversionCandidate(
6002 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6003 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6004 else
6005 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6006 ToType, CandidateSet,
6007 /*AllowObjCConversionOnExplicit=*/false,
6008 /*AllowExplicit*/ true);
6009 }
6010}
6011
6012/// Attempt to convert the given expression to a type which is accepted
6013/// by the given converter.
6014///
6015/// This routine will attempt to convert an expression of class type to a
6016/// type accepted by the specified converter. In C++11 and before, the class
6017/// must have a single non-explicit conversion function converting to a matching
6018/// type. In C++1y, there can be multiple such conversion functions, but only
6019/// one target type.
6020///
6021/// \param Loc The source location of the construct that requires the
6022/// conversion.
6023///
6024/// \param From The expression we're converting from.
6025///
6026/// \param Converter Used to control and diagnose the conversion process.
6027///
6028/// \returns The expression, converted to an integral or enumeration type if
6029/// successful.
6030ExprResult Sema::PerformContextualImplicitConversion(
6031 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6032 // We can't perform any more checking for type-dependent expressions.
6033 if (From->isTypeDependent())
6034 return From;
6035
6036 // Process placeholders immediately.
6037 if (From->hasPlaceholderType()) {
6038 ExprResult result = CheckPlaceholderExpr(From);
6039 if (result.isInvalid())
6040 return result;
6041 From = result.get();
6042 }
6043
6044 // If the expression already has a matching type, we're golden.
6045 QualType T = From->getType();
6046 if (Converter.match(T))
6047 return DefaultLvalueConversion(From);
6048
6049 // FIXME: Check for missing '()' if T is a function type?
6050
6051 // We can only perform contextual implicit conversions on objects of class
6052 // type.
6053 const RecordType *RecordTy = T->getAs<RecordType>();
6054 if (!RecordTy || !getLangOpts().CPlusPlus) {
6055 if (!Converter.Suppress)
6056 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6057 return From;
6058 }
6059
6060 // We must have a complete class type.
6061 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6062 ContextualImplicitConverter &Converter;
6063 Expr *From;
6064
6065 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6066 : Converter(Converter), From(From) {}
6067
6068 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6069 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6070 }
6071 } IncompleteDiagnoser(Converter, From);
6072
6073 if (Converter.Suppress ? !isCompleteType(Loc, T)
6074 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6075 return From;
6076
6077 // Look for a conversion to an integral or enumeration type.
6078 UnresolvedSet<4>
6079 ViableConversions; // These are *potentially* viable in C++1y.
6080 UnresolvedSet<4> ExplicitConversions;
6081 const auto &Conversions =
6082 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6083
6084 bool HadMultipleCandidates =
6085 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6086
6087 // To check that there is only one target type, in C++1y:
6088 QualType ToType;
6089 bool HasUniqueTargetType = true;
6090
6091 // Collect explicit or viable (potentially in C++1y) conversions.
6092 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6093 NamedDecl *D = (*I)->getUnderlyingDecl();
6094 CXXConversionDecl *Conversion;
6095 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6096 if (ConvTemplate) {
6097 if (getLangOpts().CPlusPlus14)
6098 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6099 else
6100 continue; // C++11 does not consider conversion operator templates(?).
6101 } else
6102 Conversion = cast<CXXConversionDecl>(D);
6103
6104 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6106, __PRETTY_FUNCTION__))
6105 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6106, __PRETTY_FUNCTION__))
6106 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6106, __PRETTY_FUNCTION__))
;
6107
6108 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6109 if (Converter.match(CurToType) || ConvTemplate) {
6110
6111 if (Conversion->isExplicit()) {
6112 // FIXME: For C++1y, do we need this restriction?
6113 // cf. diagnoseNoViableConversion()
6114 if (!ConvTemplate)
6115 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6116 } else {
6117 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6118 if (ToType.isNull())
6119 ToType = CurToType.getUnqualifiedType();
6120 else if (HasUniqueTargetType &&
6121 (CurToType.getUnqualifiedType() != ToType))
6122 HasUniqueTargetType = false;
6123 }
6124 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6125 }
6126 }
6127 }
6128
6129 if (getLangOpts().CPlusPlus14) {
6130 // C++1y [conv]p6:
6131 // ... An expression e of class type E appearing in such a context
6132 // is said to be contextually implicitly converted to a specified
6133 // type T and is well-formed if and only if e can be implicitly
6134 // converted to a type T that is determined as follows: E is searched
6135 // for conversion functions whose return type is cv T or reference to
6136 // cv T such that T is allowed by the context. There shall be
6137 // exactly one such T.
6138
6139 // If no unique T is found:
6140 if (ToType.isNull()) {
6141 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6142 HadMultipleCandidates,
6143 ExplicitConversions))
6144 return ExprError();
6145 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6146 }
6147
6148 // If more than one unique Ts are found:
6149 if (!HasUniqueTargetType)
6150 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6151 ViableConversions);
6152
6153 // If one unique T is found:
6154 // First, build a candidate set from the previously recorded
6155 // potentially viable conversions.
6156 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6157 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6158 CandidateSet);
6159
6160 // Then, perform overload resolution over the candidate set.
6161 OverloadCandidateSet::iterator Best;
6162 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6163 case OR_Success: {
6164 // Apply this conversion.
6165 DeclAccessPair Found =
6166 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6167 if (recordConversion(*this, Loc, From, Converter, T,
6168 HadMultipleCandidates, Found))
6169 return ExprError();
6170 break;
6171 }
6172 case OR_Ambiguous:
6173 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6174 ViableConversions);
6175 case OR_No_Viable_Function:
6176 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6177 HadMultipleCandidates,
6178 ExplicitConversions))
6179 return ExprError();
6180 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6181 case OR_Deleted:
6182 // We'll complain below about a non-integral condition type.
6183 break;
6184 }
6185 } else {
6186 switch (ViableConversions.size()) {
6187 case 0: {
6188 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6189 HadMultipleCandidates,
6190 ExplicitConversions))
6191 return ExprError();
6192
6193 // We'll complain below about a non-integral condition type.
6194 break;
6195 }
6196 case 1: {
6197 // Apply this conversion.
6198 DeclAccessPair Found = ViableConversions[0];
6199 if (recordConversion(*this, Loc, From, Converter, T,
6200 HadMultipleCandidates, Found))
6201 return ExprError();
6202 break;
6203 }
6204 default:
6205 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6206 ViableConversions);
6207 }
6208 }
6209
6210 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6211}
6212
6213/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6214/// an acceptable non-member overloaded operator for a call whose
6215/// arguments have types T1 (and, if non-empty, T2). This routine
6216/// implements the check in C++ [over.match.oper]p3b2 concerning
6217/// enumeration types.
6218static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6219 FunctionDecl *Fn,
6220 ArrayRef<Expr *> Args) {
6221 QualType T1 = Args[0]->getType();
6222 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6223
6224 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6225 return true;
6226
6227 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6228 return true;
6229
6230 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6231 if (Proto->getNumParams() < 1)
6232 return false;
6233
6234 if (T1->isEnumeralType()) {
6235 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6236 if (Context.hasSameUnqualifiedType(T1, ArgType))
6237 return true;
6238 }
6239
6240 if (Proto->getNumParams() < 2)
6241 return false;
6242
6243 if (!T2.isNull() && T2->isEnumeralType()) {
6244 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6245 if (Context.hasSameUnqualifiedType(T2, ArgType))
6246 return true;
6247 }
6248
6249 return false;
6250}
6251
6252/// AddOverloadCandidate - Adds the given function to the set of
6253/// candidate functions, using the given function call arguments. If
6254/// @p SuppressUserConversions, then don't allow user-defined
6255/// conversions via constructors or conversion operators.
6256///
6257/// \param PartialOverloading true if we are performing "partial" overloading
6258/// based on an incomplete set of function arguments. This feature is used by
6259/// code completion.
6260void Sema::AddOverloadCandidate(
6261 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6262 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6263 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6264 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6265 OverloadCandidateParamOrder PO) {
6266 const FunctionProtoType *Proto
6267 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6268 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6268, __PRETTY_FUNCTION__))
;
6269 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6270, __PRETTY_FUNCTION__))
6270 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6270, __PRETTY_FUNCTION__))
;
6271
6272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6273 if (!isa<CXXConstructorDecl>(Method)) {
6274 // If we get here, it's because we're calling a member function
6275 // that is named without a member access expression (e.g.,
6276 // "this->f") that was either written explicitly or created
6277 // implicitly. This can happen with a qualified call to a member
6278 // function, e.g., X::f(). We use an empty type for the implied
6279 // object argument (C++ [over.call.func]p3), and the acting context
6280 // is irrelevant.
6281 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6282 Expr::Classification::makeSimpleLValue(), Args,
6283 CandidateSet, SuppressUserConversions,
6284 PartialOverloading, EarlyConversions, PO);
6285 return;
6286 }
6287 // We treat a constructor like a non-member function, since its object
6288 // argument doesn't participate in overload resolution.
6289 }
6290
6291 if (!CandidateSet.isNewCandidate(Function, PO))
6292 return;
6293
6294 // C++11 [class.copy]p11: [DR1402]
6295 // A defaulted move constructor that is defined as deleted is ignored by
6296 // overload resolution.
6297 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6298 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6299 Constructor->isMoveConstructor())
6300 return;
6301
6302 // Overload resolution is always an unevaluated context.
6303 EnterExpressionEvaluationContext Unevaluated(
6304 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6305
6306 // C++ [over.match.oper]p3:
6307 // if no operand has a class type, only those non-member functions in the
6308 // lookup set that have a first parameter of type T1 or "reference to
6309 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6310 // is a right operand) a second parameter of type T2 or "reference to
6311 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6312 // candidate functions.
6313 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6314 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6315 return;
6316
6317 // Add this candidate
6318 OverloadCandidate &Candidate =
6319 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6320 Candidate.FoundDecl = FoundDecl;
6321 Candidate.Function = Function;
6322 Candidate.Viable = true;
6323 Candidate.RewriteKind =
6324 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6325 Candidate.IsSurrogate = false;
6326 Candidate.IsADLCandidate = IsADLCandidate;
6327 Candidate.IgnoreObjectArgument = false;
6328 Candidate.ExplicitCallArguments = Args.size();
6329
6330 // Explicit functions are not actually candidates at all if we're not
6331 // allowing them in this context, but keep them around so we can point
6332 // to them in diagnostics.
6333 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6334 Candidate.Viable = false;
6335 Candidate.FailureKind = ovl_fail_explicit;
6336 return;
6337 }
6338
6339 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6340 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6341 Candidate.Viable = false;
6342 Candidate.FailureKind = ovl_non_default_multiversion_function;
6343 return;
6344 }
6345
6346 if (Constructor) {
6347 // C++ [class.copy]p3:
6348 // A member function template is never instantiated to perform the copy
6349 // of a class object to an object of its class type.
6350 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6351 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6352 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6353 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6354 ClassType))) {
6355 Candidate.Viable = false;
6356 Candidate.FailureKind = ovl_fail_illegal_constructor;
6357 return;
6358 }
6359
6360 // C++ [over.match.funcs]p8: (proposed DR resolution)
6361 // A constructor inherited from class type C that has a first parameter
6362 // of type "reference to P" (including such a constructor instantiated
6363 // from a template) is excluded from the set of candidate functions when
6364 // constructing an object of type cv D if the argument list has exactly
6365 // one argument and D is reference-related to P and P is reference-related
6366 // to C.
6367 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6368 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6369 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6370 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6371 QualType C = Context.getRecordType(Constructor->getParent());
6372 QualType D = Context.getRecordType(Shadow->getParent());
6373 SourceLocation Loc = Args.front()->getExprLoc();
6374 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6375 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6376 Candidate.Viable = false;
6377 Candidate.FailureKind = ovl_fail_inhctor_slice;
6378 return;
6379 }
6380 }
6381
6382 // Check that the constructor is capable of constructing an object in the
6383 // destination address space.
6384 if (!Qualifiers::isAddressSpaceSupersetOf(
6385 Constructor->getMethodQualifiers().getAddressSpace(),
6386 CandidateSet.getDestAS())) {
6387 Candidate.Viable = false;
6388 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6389 }
6390 }
6391
6392 unsigned NumParams = Proto->getNumParams();
6393
6394 // (C++ 13.3.2p2): A candidate function having fewer than m
6395 // parameters is viable only if it has an ellipsis in its parameter
6396 // list (8.3.5).
6397 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6398 !Proto->isVariadic()) {
6399 Candidate.Viable = false;
6400 Candidate.FailureKind = ovl_fail_too_many_arguments;
6401 return;
6402 }
6403
6404 // (C++ 13.3.2p2): A candidate function having more than m parameters
6405 // is viable only if the (m+1)st parameter has a default argument
6406 // (8.3.6). For the purposes of overload resolution, the
6407 // parameter list is truncated on the right, so that there are
6408 // exactly m parameters.
6409 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6410 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6411 // Not enough arguments.
6412 Candidate.Viable = false;
6413 Candidate.FailureKind = ovl_fail_too_few_arguments;
6414 return;
6415 }
6416
6417 // (CUDA B.1): Check for invalid calls between targets.
6418 if (getLangOpts().CUDA)
6419 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6420 // Skip the check for callers that are implicit members, because in this
6421 // case we may not yet know what the member's target is; the target is
6422 // inferred for the member automatically, based on the bases and fields of
6423 // the class.
6424 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6425 Candidate.Viable = false;
6426 Candidate.FailureKind = ovl_fail_bad_target;
6427 return;
6428 }
6429
6430 if (Function->getTrailingRequiresClause()) {
6431 ConstraintSatisfaction Satisfaction;
6432 if (CheckFunctionConstraints(Function, Satisfaction) ||
6433 !Satisfaction.IsSatisfied) {
6434 Candidate.Viable = false;
6435 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6436 return;
6437 }
6438 }
6439
6440 // Determine the implicit conversion sequences for each of the
6441 // arguments.
6442 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6443 unsigned ConvIdx =
6444 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6445 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6446 // We already formed a conversion sequence for this parameter during
6447 // template argument deduction.
6448 } else if (ArgIdx < NumParams) {
6449 // (C++ 13.3.2p3): for F to be a viable function, there shall
6450 // exist for each argument an implicit conversion sequence
6451 // (13.3.3.1) that converts that argument to the corresponding
6452 // parameter of F.
6453 QualType ParamType = Proto->getParamType(ArgIdx);
6454 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6455 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6456 /*InOverloadResolution=*/true,
6457 /*AllowObjCWritebackConversion=*/
6458 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6459 if (Candidate.Conversions[ConvIdx].isBad()) {
6460 Candidate.Viable = false;
6461 Candidate.FailureKind = ovl_fail_bad_conversion;
6462 return;
6463 }
6464 } else {
6465 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6466 // argument for which there is no corresponding parameter is
6467 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6468 Candidate.Conversions[ConvIdx].setEllipsis();
6469 }
6470 }
6471
6472 if (EnableIfAttr *FailedAttr =
6473 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6474 Candidate.Viable = false;
6475 Candidate.FailureKind = ovl_fail_enable_if;
6476 Candidate.DeductionFailure.Data = FailedAttr;
6477 return;
6478 }
6479
6480 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6481 Candidate.Viable = false;
6482 Candidate.FailureKind = ovl_fail_ext_disabled;
6483 return;
6484 }
6485}
6486
6487ObjCMethodDecl *
6488Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6489 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6490 if (Methods.size() <= 1)
6491 return nullptr;
6492
6493 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6494 bool Match = true;
6495 ObjCMethodDecl *Method = Methods[b];
6496 unsigned NumNamedArgs = Sel.getNumArgs();
6497 // Method might have more arguments than selector indicates. This is due
6498 // to addition of c-style arguments in method.
6499 if (Method->param_size() > NumNamedArgs)
6500 NumNamedArgs = Method->param_size();
6501 if (Args.size() < NumNamedArgs)
6502 continue;
6503
6504 for (unsigned i = 0; i < NumNamedArgs; i++) {
6505 // We can't do any type-checking on a type-dependent argument.
6506 if (Args[i]->isTypeDependent()) {
6507 Match = false;
6508 break;
6509 }
6510
6511 ParmVarDecl *param = Method->parameters()[i];
6512 Expr *argExpr = Args[i];
6513 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6513, __PRETTY_FUNCTION__))
;
6514
6515 // Strip the unbridged-cast placeholder expression off unless it's
6516 // a consumed argument.
6517 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6518 !param->hasAttr<CFConsumedAttr>())
6519 argExpr = stripARCUnbridgedCast(argExpr);
6520
6521 // If the parameter is __unknown_anytype, move on to the next method.
6522 if (param->getType() == Context.UnknownAnyTy) {
6523 Match = false;
6524 break;
6525 }
6526
6527 ImplicitConversionSequence ConversionState
6528 = TryCopyInitialization(*this, argExpr, param->getType(),
6529 /*SuppressUserConversions*/false,
6530 /*InOverloadResolution=*/true,
6531 /*AllowObjCWritebackConversion=*/
6532 getLangOpts().ObjCAutoRefCount,
6533 /*AllowExplicit*/false);
6534 // This function looks for a reasonably-exact match, so we consider
6535 // incompatible pointer conversions to be a failure here.
6536 if (ConversionState.isBad() ||
6537 (ConversionState.isStandard() &&
6538 ConversionState.Standard.Second ==
6539 ICK_Incompatible_Pointer_Conversion)) {
6540 Match = false;
6541 break;
6542 }
6543 }
6544 // Promote additional arguments to variadic methods.
6545 if (Match && Method->isVariadic()) {
6546 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6547 if (Args[i]->isTypeDependent()) {
6548 Match = false;
6549 break;
6550 }
6551 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6552 nullptr);
6553 if (Arg.isInvalid()) {
6554 Match = false;
6555 break;
6556 }
6557 }
6558 } else {
6559 // Check for extra arguments to non-variadic methods.
6560 if (Args.size() != NumNamedArgs)
6561 Match = false;
6562 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6563 // Special case when selectors have no argument. In this case, select
6564 // one with the most general result type of 'id'.
6565 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6566 QualType ReturnT = Methods[b]->getReturnType();
6567 if (ReturnT->isObjCIdType())
6568 return Methods[b];
6569 }
6570 }
6571 }
6572
6573 if (Match)
6574 return Method;
6575 }
6576 return nullptr;
6577}
6578
6579static bool convertArgsForAvailabilityChecks(
6580 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6581 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6582 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6583 if (ThisArg) {
6584 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6585 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6586, __PRETTY_FUNCTION__))
6586 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6586, __PRETTY_FUNCTION__))
;
6587 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6587, __PRETTY_FUNCTION__))
;
6588 ExprResult R = S.PerformObjectArgumentInitialization(
6589 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6590 if (R.isInvalid())
6591 return false;
6592 ConvertedThis = R.get();
6593 } else {
6594 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6595 (void)MD;
6596 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6598, __PRETTY_FUNCTION__))
6597 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6598, __PRETTY_FUNCTION__))
6598 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6598, __PRETTY_FUNCTION__))
;
6599 }
6600 ConvertedThis = nullptr;
6601 }
6602
6603 // Ignore any variadic arguments. Converting them is pointless, since the
6604 // user can't refer to them in the function condition.
6605 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6606
6607 // Convert the arguments.
6608 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6609 ExprResult R;
6610 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6611 S.Context, Function->getParamDecl(I)),
6612 SourceLocation(), Args[I]);
6613
6614 if (R.isInvalid())
6615 return false;
6616
6617 ConvertedArgs.push_back(R.get());
6618 }
6619
6620 if (Trap.hasErrorOccurred())
6621 return false;
6622
6623 // Push default arguments if needed.
6624 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6625 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6626 ParmVarDecl *P = Function->getParamDecl(i);
6627 if (!P->hasDefaultArg())
6628 return false;
6629 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6630 if (R.isInvalid())
6631 return false;
6632 ConvertedArgs.push_back(R.get());
6633 }
6634
6635 if (Trap.hasErrorOccurred())
6636 return false;
6637 }
6638 return true;
6639}
6640
6641EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6642 SourceLocation CallLoc,
6643 ArrayRef<Expr *> Args,
6644 bool MissingImplicitThis) {
6645 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6646 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6647 return nullptr;
6648
6649 SFINAETrap Trap(*this);
6650 SmallVector<Expr *, 16> ConvertedArgs;
6651 // FIXME: We should look into making enable_if late-parsed.
6652 Expr *DiscardedThis;
6653 if (!convertArgsForAvailabilityChecks(
6654 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6655 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6656 return *EnableIfAttrs.begin();
6657
6658 for (auto *EIA : EnableIfAttrs) {
6659 APValue Result;
6660 // FIXME: This doesn't consider value-dependent cases, because doing so is
6661 // very difficult. Ideally, we should handle them more gracefully.
6662 if (EIA->getCond()->isValueDependent() ||
6663 !EIA->getCond()->EvaluateWithSubstitution(
6664 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6665 return EIA;
6666
6667 if (!Result.isInt() || !Result.getInt().getBoolValue())
6668 return EIA;
6669 }
6670 return nullptr;
6671}
6672
6673template <typename CheckFn>
6674static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6675 bool ArgDependent, SourceLocation Loc,
6676 CheckFn &&IsSuccessful) {
6677 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6678 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6679 if (ArgDependent == DIA->getArgDependent())
6680 Attrs.push_back(DIA);
6681 }
6682
6683 // Common case: No diagnose_if attributes, so we can quit early.
6684 if (Attrs.empty())
6685 return false;
6686
6687 auto WarningBegin = std::stable_partition(
6688 Attrs.begin(), Attrs.end(),
6689 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6690
6691 // Note that diagnose_if attributes are late-parsed, so they appear in the
6692 // correct order (unlike enable_if attributes).
6693 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6694 IsSuccessful);
6695 if (ErrAttr != WarningBegin) {
6696 const DiagnoseIfAttr *DIA = *ErrAttr;
6697 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6698 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6699 << DIA->getParent() << DIA->getCond()->getSourceRange();
6700 return true;
6701 }
6702
6703 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6704 if (IsSuccessful(DIA)) {
6705 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6706 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6707 << DIA->getParent() << DIA->getCond()->getSourceRange();
6708 }
6709
6710 return false;
6711}
6712
6713bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6714 const Expr *ThisArg,
6715 ArrayRef<const Expr *> Args,
6716 SourceLocation Loc) {
6717 return diagnoseDiagnoseIfAttrsWith(
6718 *this, Function, /*ArgDependent=*/true, Loc,
6719 [&](const DiagnoseIfAttr *DIA) {
6720 APValue Result;
6721 // It's sane to use the same Args for any redecl of this function, since
6722 // EvaluateWithSubstitution only cares about the position of each
6723 // argument in the arg list, not the ParmVarDecl* it maps to.
6724 if (!DIA->getCond()->EvaluateWithSubstitution(
6725 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6726 return false;
6727 return Result.isInt() && Result.getInt().getBoolValue();
6728 });
6729}
6730
6731bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6732 SourceLocation Loc) {
6733 return diagnoseDiagnoseIfAttrsWith(
6734 *this, ND, /*ArgDependent=*/false, Loc,
6735 [&](const DiagnoseIfAttr *DIA) {
6736 bool Result;
6737 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6738 Result;
6739 });
6740}
6741
6742/// Add all of the function declarations in the given function set to
6743/// the overload candidate set.
6744void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6745 ArrayRef<Expr *> Args,
6746 OverloadCandidateSet &CandidateSet,
6747 TemplateArgumentListInfo *ExplicitTemplateArgs,
6748 bool SuppressUserConversions,
6749 bool PartialOverloading,
6750 bool FirstArgumentIsBase) {
6751 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6752 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6753 ArrayRef<Expr *> FunctionArgs = Args;
6754
6755 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6756 FunctionDecl *FD =
6757 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6758
6759 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6760 QualType ObjectType;
6761 Expr::Classification ObjectClassification;
6762 if (Args.size() > 0) {
6763 if (Expr *E = Args[0]) {
6764 // Use the explicit base to restrict the lookup:
6765 ObjectType = E->getType();
6766 // Pointers in the object arguments are implicitly dereferenced, so we
6767 // always classify them as l-values.
6768 if (!ObjectType.isNull() && ObjectType->isPointerType())
6769 ObjectClassification = Expr::Classification::makeSimpleLValue();
6770 else
6771 ObjectClassification = E->Classify(Context);
6772 } // .. else there is an implicit base.
6773 FunctionArgs = Args.slice(1);
6774 }
6775 if (FunTmpl) {
6776 AddMethodTemplateCandidate(
6777 FunTmpl, F.getPair(),
6778 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6779 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6780 FunctionArgs, CandidateSet, SuppressUserConversions,
6781 PartialOverloading);
6782 } else {
6783 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6784 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6785 ObjectClassification, FunctionArgs, CandidateSet,
6786 SuppressUserConversions, PartialOverloading);
6787 }
6788 } else {
6789 // This branch handles both standalone functions and static methods.
6790
6791 // Slice the first argument (which is the base) when we access
6792 // static method as non-static.
6793 if (Args.size() > 0 &&
6794 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6795 !isa<CXXConstructorDecl>(FD)))) {
6796 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6796, __PRETTY_FUNCTION__))
;
6797 FunctionArgs = Args.slice(1);
6798 }
6799 if (FunTmpl) {
6800 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6801 ExplicitTemplateArgs, FunctionArgs,
6802 CandidateSet, SuppressUserConversions,
6803 PartialOverloading);
6804 } else {
6805 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6806 SuppressUserConversions, PartialOverloading);
6807 }
6808 }
6809 }
6810}
6811
6812/// AddMethodCandidate - Adds a named decl (which is some kind of
6813/// method) as a method candidate to the given overload set.
6814void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6815 Expr::Classification ObjectClassification,
6816 ArrayRef<Expr *> Args,
6817 OverloadCandidateSet &CandidateSet,
6818 bool SuppressUserConversions,
6819 OverloadCandidateParamOrder PO) {
6820 NamedDecl *Decl = FoundDecl.getDecl();
6821 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6822
6823 if (isa<UsingShadowDecl>(Decl))
6824 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6825
6826 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6827 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6828, __PRETTY_FUNCTION__))
6828 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6828, __PRETTY_FUNCTION__))
;
6829 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6830 /*ExplicitArgs*/ nullptr, ObjectType,
6831 ObjectClassification, Args, CandidateSet,
6832 SuppressUserConversions, false, PO);
6833 } else {
6834 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6835 ObjectType, ObjectClassification, Args, CandidateSet,
6836 SuppressUserConversions, false, None, PO);
6837 }
6838}
6839
6840/// AddMethodCandidate - Adds the given C++ member function to the set
6841/// of candidate functions, using the given function call arguments
6842/// and the object argument (@c Object). For example, in a call
6843/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6844/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6845/// allow user-defined conversions via constructors or conversion
6846/// operators.
6847void
6848Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6849 CXXRecordDecl *ActingContext, QualType ObjectType,
6850 Expr::Classification ObjectClassification,
6851 ArrayRef<Expr *> Args,
6852 OverloadCandidateSet &CandidateSet,
6853 bool SuppressUserConversions,
6854 bool PartialOverloading,
6855 ConversionSequenceList EarlyConversions,
6856 OverloadCandidateParamOrder PO) {
6857 const FunctionProtoType *Proto
6858 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6859 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6859, __PRETTY_FUNCTION__))
;
6860 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6861, __PRETTY_FUNCTION__))
6861 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 6861, __PRETTY_FUNCTION__))
;
6862
6863 if (!CandidateSet.isNewCandidate(Method, PO))
6864 return;
6865
6866 // C++11 [class.copy]p23: [DR1402]
6867 // A defaulted move assignment operator that is defined as deleted is
6868 // ignored by overload resolution.
6869 if (Method->isDefaulted() && Method->isDeleted() &&
6870 Method->isMoveAssignmentOperator())
6871 return;
6872
6873 // Overload resolution is always an unevaluated context.
6874 EnterExpressionEvaluationContext Unevaluated(
6875 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6876
6877 // Add this candidate
6878 OverloadCandidate &Candidate =
6879 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6880 Candidate.FoundDecl = FoundDecl;
6881 Candidate.Function = Method;
6882 Candidate.RewriteKind =
6883 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6884 Candidate.IsSurrogate = false;
6885 Candidate.IgnoreObjectArgument = false;
6886 Candidate.ExplicitCallArguments = Args.size();
6887
6888 unsigned NumParams = Proto->getNumParams();
6889
6890 // (C++ 13.3.2p2): A candidate function having fewer than m
6891 // parameters is viable only if it has an ellipsis in its parameter
6892 // list (8.3.5).
6893 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6894 !Proto->isVariadic()) {
6895 Candidate.Viable = false;
6896 Candidate.FailureKind = ovl_fail_too_many_arguments;
6897 return;
6898 }
6899
6900 // (C++ 13.3.2p2): A candidate function having more than m parameters
6901 // is viable only if the (m+1)st parameter has a default argument
6902 // (8.3.6). For the purposes of overload resolution, the
6903 // parameter list is truncated on the right, so that there are
6904 // exactly m parameters.
6905 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6906 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6907 // Not enough arguments.
6908 Candidate.Viable = false;
6909 Candidate.FailureKind = ovl_fail_too_few_arguments;
6910 return;
6911 }
6912
6913 Candidate.Viable = true;
6914
6915 if (Method->isStatic() || ObjectType.isNull())
6916 // The implicit object argument is ignored.
6917 Candidate.IgnoreObjectArgument = true;
6918 else {
6919 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6920 // Determine the implicit conversion sequence for the object
6921 // parameter.
6922 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6923 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6924 Method, ActingContext);
6925 if (Candidate.Conversions[ConvIdx].isBad()) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_bad_conversion;
6928 return;
6929 }
6930 }
6931
6932 // (CUDA B.1): Check for invalid calls between targets.
6933 if (getLangOpts().CUDA)
6934 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6935 if (!IsAllowedCUDACall(Caller, Method)) {
6936 Candidate.Viable = false;
6937 Candidate.FailureKind = ovl_fail_bad_target;
6938 return;
6939 }
6940
6941 if (Method->getTrailingRequiresClause()) {
6942 ConstraintSatisfaction Satisfaction;
6943 if (CheckFunctionConstraints(Method, Satisfaction) ||
6944 !Satisfaction.IsSatisfied) {
6945 Candidate.Viable = false;
6946 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6947 return;
6948 }
6949 }
6950
6951 // Determine the implicit conversion sequences for each of the
6952 // arguments.
6953 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6954 unsigned ConvIdx =
6955 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6956 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6957 // We already formed a conversion sequence for this parameter during
6958 // template argument deduction.
6959 } else if (ArgIdx < NumParams) {
6960 // (C++ 13.3.2p3): for F to be a viable function, there shall
6961 // exist for each argument an implicit conversion sequence
6962 // (13.3.3.1) that converts that argument to the corresponding
6963 // parameter of F.
6964 QualType ParamType = Proto->getParamType(ArgIdx);
6965 Candidate.Conversions[ConvIdx]
6966 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6967 SuppressUserConversions,
6968 /*InOverloadResolution=*/true,
6969 /*AllowObjCWritebackConversion=*/
6970 getLangOpts().ObjCAutoRefCount);
6971 if (Candidate.Conversions[ConvIdx].isBad()) {
6972 Candidate.Viable = false;
6973 Candidate.FailureKind = ovl_fail_bad_conversion;
6974 return;
6975 }
6976 } else {
6977 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6978 // argument for which there is no corresponding parameter is
6979 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6980 Candidate.Conversions[ConvIdx].setEllipsis();
6981 }
6982 }
6983
6984 if (EnableIfAttr *FailedAttr =
6985 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6986 Candidate.Viable = false;
6987 Candidate.FailureKind = ovl_fail_enable_if;
6988 Candidate.DeductionFailure.Data = FailedAttr;
6989 return;
6990 }
6991
6992 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6993 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6994 Candidate.Viable = false;
6995 Candidate.FailureKind = ovl_non_default_multiversion_function;
6996 }
6997}
6998
6999/// Add a C++ member function template as a candidate to the candidate
7000/// set, using template argument deduction to produce an appropriate member
7001/// function template specialization.
7002void Sema::AddMethodTemplateCandidate(
7003 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7004 CXXRecordDecl *ActingContext,
7005 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7006 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7007 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7008 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7009 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7010 return;
7011
7012 // C++ [over.match.funcs]p7:
7013 // In each case where a candidate is a function template, candidate
7014 // function template specializations are generated using template argument
7015 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7016 // candidate functions in the usual way.113) A given name can refer to one
7017 // or more function templates and also to a set of overloaded non-template
7018 // functions. In such a case, the candidate functions generated from each
7019 // function template are combined with the set of non-template candidate
7020 // functions.
7021 TemplateDeductionInfo Info(CandidateSet.getLocation());
7022 FunctionDecl *Specialization = nullptr;
7023 ConversionSequenceList Conversions;
7024 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7025 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7026 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7027 return CheckNonDependentConversions(
7028 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7029 SuppressUserConversions, ActingContext, ObjectType,
7030 ObjectClassification, PO);
7031 })) {
7032 OverloadCandidate &Candidate =
7033 CandidateSet.addCandidate(Conversions.size(), Conversions);
7034 Candidate.FoundDecl = FoundDecl;
7035 Candidate.Function = MethodTmpl->getTemplatedDecl();
7036 Candidate.Viable = false;
7037 Candidate.RewriteKind =
7038 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7039 Candidate.IsSurrogate = false;
7040 Candidate.IgnoreObjectArgument =
7041 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7042 ObjectType.isNull();
7043 Candidate.ExplicitCallArguments = Args.size();
7044 if (Result == TDK_NonDependentConversionFailure)
7045 Candidate.FailureKind = ovl_fail_bad_conversion;
7046 else {
7047 Candidate.FailureKind = ovl_fail_bad_deduction;
7048 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7049 Info);
7050 }
7051 return;
7052 }
7053
7054 // Add the function template specialization produced by template argument
7055 // deduction as a candidate.
7056 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7056, __PRETTY_FUNCTION__))
;
7057 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7058, __PRETTY_FUNCTION__))
7058 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7058, __PRETTY_FUNCTION__))
;
7059 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7060 ActingContext, ObjectType, ObjectClassification, Args,
7061 CandidateSet, SuppressUserConversions, PartialOverloading,
7062 Conversions, PO);
7063}
7064
7065/// Determine whether a given function template has a simple explicit specifier
7066/// or a non-value-dependent explicit-specification that evaluates to true.
7067static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7068 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7069}
7070
7071/// Add a C++ function template specialization as a candidate
7072/// in the candidate set, using template argument deduction to produce
7073/// an appropriate function template specialization.
7074void Sema::AddTemplateOverloadCandidate(
7075 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7076 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7077 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7078 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7079 OverloadCandidateParamOrder PO) {
7080 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7081 return;
7082
7083 // If the function template has a non-dependent explicit specification,
7084 // exclude it now if appropriate; we are not permitted to perform deduction
7085 // and substitution in this case.
7086 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7087 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7088 Candidate.FoundDecl = FoundDecl;
7089 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7090 Candidate.Viable = false;
7091 Candidate.FailureKind = ovl_fail_explicit;
7092 return;
7093 }
7094
7095 // C++ [over.match.funcs]p7:
7096 // In each case where a candidate is a function template, candidate
7097 // function template specializations are generated using template argument
7098 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7099 // candidate functions in the usual way.113) A given name can refer to one
7100 // or more function templates and also to a set of overloaded non-template
7101 // functions. In such a case, the candidate functions generated from each
7102 // function template are combined with the set of non-template candidate
7103 // functions.
7104 TemplateDeductionInfo Info(CandidateSet.getLocation());
7105 FunctionDecl *Specialization = nullptr;
7106 ConversionSequenceList Conversions;
7107 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7108 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7109 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7110 return CheckNonDependentConversions(
7111 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7112 SuppressUserConversions, nullptr, QualType(), {}, PO);
7113 })) {
7114 OverloadCandidate &Candidate =
7115 CandidateSet.addCandidate(Conversions.size(), Conversions);
7116 Candidate.FoundDecl = FoundDecl;
7117 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7118 Candidate.Viable = false;
7119 Candidate.RewriteKind =
7120 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7121 Candidate.IsSurrogate = false;
7122 Candidate.IsADLCandidate = IsADLCandidate;
7123 // Ignore the object argument if there is one, since we don't have an object
7124 // type.
7125 Candidate.IgnoreObjectArgument =
7126 isa<CXXMethodDecl>(Candidate.Function) &&
7127 !isa<CXXConstructorDecl>(Candidate.Function);
7128 Candidate.ExplicitCallArguments = Args.size();
7129 if (Result == TDK_NonDependentConversionFailure)
7130 Candidate.FailureKind = ovl_fail_bad_conversion;
7131 else {
7132 Candidate.FailureKind = ovl_fail_bad_deduction;
7133 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7134 Info);
7135 }
7136 return;
7137 }
7138
7139 // Add the function template specialization produced by template argument
7140 // deduction as a candidate.
7141 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7141, __PRETTY_FUNCTION__))
;
7142 AddOverloadCandidate(
7143 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7144 PartialOverloading, AllowExplicit,
7145 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7146}
7147
7148/// Check that implicit conversion sequences can be formed for each argument
7149/// whose corresponding parameter has a non-dependent type, per DR1391's
7150/// [temp.deduct.call]p10.
7151bool Sema::CheckNonDependentConversions(
7152 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7153 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7154 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7155 CXXRecordDecl *ActingContext, QualType ObjectType,
7156 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7157 // FIXME: The cases in which we allow explicit conversions for constructor
7158 // arguments never consider calling a constructor template. It's not clear
7159 // that is correct.
7160 const bool AllowExplicit = false;
7161
7162 auto *FD = FunctionTemplate->getTemplatedDecl();
7163 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7164 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7165 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7166
7167 Conversions =
7168 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7169
7170 // Overload resolution is always an unevaluated context.
7171 EnterExpressionEvaluationContext Unevaluated(
7172 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7173
7174 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7175 // require that, but this check should never result in a hard error, and
7176 // overload resolution is permitted to sidestep instantiations.
7177 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7178 !ObjectType.isNull()) {
7179 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7180 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7181 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7182 Method, ActingContext);
7183 if (Conversions[ConvIdx].isBad())
7184 return true;
7185 }
7186
7187 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7188 ++I) {
7189 QualType ParamType = ParamTypes[I];
7190 if (!ParamType->isDependentType()) {
7191 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7192 ? 0
7193 : (ThisConversions + I);
7194 Conversions[ConvIdx]
7195 = TryCopyInitialization(*this, Args[I], ParamType,
7196 SuppressUserConversions,
7197 /*InOverloadResolution=*/true,
7198 /*AllowObjCWritebackConversion=*/
7199 getLangOpts().ObjCAutoRefCount,
7200 AllowExplicit);
7201 if (Conversions[ConvIdx].isBad())
7202 return true;
7203 }
7204 }
7205
7206 return false;
7207}
7208
7209/// Determine whether this is an allowable conversion from the result
7210/// of an explicit conversion operator to the expected type, per C++
7211/// [over.match.conv]p1 and [over.match.ref]p1.
7212///
7213/// \param ConvType The return type of the conversion function.
7214///
7215/// \param ToType The type we are converting to.
7216///
7217/// \param AllowObjCPointerConversion Allow a conversion from one
7218/// Objective-C pointer to another.
7219///
7220/// \returns true if the conversion is allowable, false otherwise.
7221static bool isAllowableExplicitConversion(Sema &S,
7222 QualType ConvType, QualType ToType,
7223 bool AllowObjCPointerConversion) {
7224 QualType ToNonRefType = ToType.getNonReferenceType();
7225
7226 // Easy case: the types are the same.
7227 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7228 return true;
7229
7230 // Allow qualification conversions.
7231 bool ObjCLifetimeConversion;
7232 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7233 ObjCLifetimeConversion))
7234 return true;
7235
7236 // If we're not allowed to consider Objective-C pointer conversions,
7237 // we're done.
7238 if (!AllowObjCPointerConversion)
7239 return false;
7240
7241 // Is this an Objective-C pointer conversion?
7242 bool IncompatibleObjC = false;
7243 QualType ConvertedType;
7244 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7245 IncompatibleObjC);
7246}
7247
7248/// AddConversionCandidate - Add a C++ conversion function as a
7249/// candidate in the candidate set (C++ [over.match.conv],
7250/// C++ [over.match.copy]). From is the expression we're converting from,
7251/// and ToType is the type that we're eventually trying to convert to
7252/// (which may or may not be the same type as the type that the
7253/// conversion function produces).
7254void Sema::AddConversionCandidate(
7255 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7256 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7257 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7258 bool AllowExplicit, bool AllowResultConversion) {
7259 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7260, __PRETTY_FUNCTION__))
7260 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7260, __PRETTY_FUNCTION__))
;
7261 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7262 if (!CandidateSet.isNewCandidate(Conversion))
7263 return;
7264
7265 // If the conversion function has an undeduced return type, trigger its
7266 // deduction now.
7267 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7268 if (DeduceReturnType(Conversion, From->getExprLoc()))
7269 return;
7270 ConvType = Conversion->getConversionType().getNonReferenceType();
7271 }
7272
7273 // If we don't allow any conversion of the result type, ignore conversion
7274 // functions that don't convert to exactly (possibly cv-qualified) T.
7275 if (!AllowResultConversion &&
7276 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7277 return;
7278
7279 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7280 // operator is only a candidate if its return type is the target type or
7281 // can be converted to the target type with a qualification conversion.
7282 //
7283 // FIXME: Include such functions in the candidate list and explain why we
7284 // can't select them.
7285 if (Conversion->isExplicit() &&
7286 !isAllowableExplicitConversion(*this, ConvType, ToType,
7287 AllowObjCConversionOnExplicit))
7288 return;
7289
7290 // Overload resolution is always an unevaluated context.
7291 EnterExpressionEvaluationContext Unevaluated(
7292 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7293
7294 // Add this candidate
7295 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7296 Candidate.FoundDecl = FoundDecl;
7297 Candidate.Function = Conversion;
7298 Candidate.IsSurrogate = false;
7299 Candidate.IgnoreObjectArgument = false;
7300 Candidate.FinalConversion.setAsIdentityConversion();
7301 Candidate.FinalConversion.setFromType(ConvType);
7302 Candidate.FinalConversion.setAllToTypes(ToType);
7303 Candidate.Viable = true;
7304 Candidate.ExplicitCallArguments = 1;
7305
7306 // Explicit functions are not actually candidates at all if we're not
7307 // allowing them in this context, but keep them around so we can point
7308 // to them in diagnostics.
7309 if (!AllowExplicit && Conversion->isExplicit()) {
7310 Candidate.Viable = false;
7311 Candidate.FailureKind = ovl_fail_explicit;
7312 return;
7313 }
7314
7315 // C++ [over.match.funcs]p4:
7316 // For conversion functions, the function is considered to be a member of
7317 // the class of the implicit implied object argument for the purpose of
7318 // defining the type of the implicit object parameter.
7319 //
7320 // Determine the implicit conversion sequence for the implicit
7321 // object parameter.
7322 QualType ImplicitParamType = From->getType();
7323 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7324 ImplicitParamType = FromPtrType->getPointeeType();
7325 CXXRecordDecl *ConversionContext
7326 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7327
7328 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7329 *this, CandidateSet.getLocation(), From->getType(),
7330 From->Classify(Context), Conversion, ConversionContext);
7331
7332 if (Candidate.Conversions[0].isBad()) {
7333 Candidate.Viable = false;
7334 Candidate.FailureKind = ovl_fail_bad_conversion;
7335 return;
7336 }
7337
7338 if (Conversion->getTrailingRequiresClause()) {
7339 ConstraintSatisfaction Satisfaction;
7340 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7341 !Satisfaction.IsSatisfied) {
7342 Candidate.Viable = false;
7343 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7344 return;
7345 }
7346 }
7347
7348 // We won't go through a user-defined type conversion function to convert a
7349 // derived to base as such conversions are given Conversion Rank. They only
7350 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7351 QualType FromCanon
7352 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7353 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7354 if (FromCanon == ToCanon ||
7355 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7356 Candidate.Viable = false;
7357 Candidate.FailureKind = ovl_fail_trivial_conversion;
7358 return;
7359 }
7360
7361 // To determine what the conversion from the result of calling the
7362 // conversion function to the type we're eventually trying to
7363 // convert to (ToType), we need to synthesize a call to the
7364 // conversion function and attempt copy initialization from it. This
7365 // makes sure that we get the right semantics with respect to
7366 // lvalues/rvalues and the type. Fortunately, we can allocate this
7367 // call on the stack and we don't need its arguments to be
7368 // well-formed.
7369 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7370 VK_LValue, From->getBeginLoc());
7371 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7372 Context.getPointerType(Conversion->getType()),
7373 CK_FunctionToPointerDecay, &ConversionRef,
7374 VK_RValue, FPOptionsOverride());
7375
7376 QualType ConversionType = Conversion->getConversionType();
7377 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7378 Candidate.Viable = false;
7379 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7380 return;
7381 }
7382
7383 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7384
7385 // Note that it is safe to allocate CallExpr on the stack here because
7386 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7387 // allocator).
7388 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7389
7390 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7391 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7392 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7393
7394 ImplicitConversionSequence ICS =
7395 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7396 /*SuppressUserConversions=*/true,
7397 /*InOverloadResolution=*/false,
7398 /*AllowObjCWritebackConversion=*/false);
7399
7400 switch (ICS.getKind()) {
7401 case ImplicitConversionSequence::StandardConversion:
7402 Candidate.FinalConversion = ICS.Standard;
7403
7404 // C++ [over.ics.user]p3:
7405 // If the user-defined conversion is specified by a specialization of a
7406 // conversion function template, the second standard conversion sequence
7407 // shall have exact match rank.
7408 if (Conversion->getPrimaryTemplate() &&
7409 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7410 Candidate.Viable = false;
7411 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7412 return;
7413 }
7414
7415 // C++0x [dcl.init.ref]p5:
7416 // In the second case, if the reference is an rvalue reference and
7417 // the second standard conversion sequence of the user-defined
7418 // conversion sequence includes an lvalue-to-rvalue conversion, the
7419 // program is ill-formed.
7420 if (ToType->isRValueReferenceType() &&
7421 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7422 Candidate.Viable = false;
7423 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7424 return;
7425 }
7426 break;
7427
7428 case ImplicitConversionSequence::BadConversion:
7429 Candidate.Viable = false;
7430 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7431 return;
7432
7433 default:
7434 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7435)
7435 "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"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7435)
;
7436 }
7437
7438 if (EnableIfAttr *FailedAttr =
7439 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7440 Candidate.Viable = false;
7441 Candidate.FailureKind = ovl_fail_enable_if;
7442 Candidate.DeductionFailure.Data = FailedAttr;
7443 return;
7444 }
7445
7446 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7447 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7448 Candidate.Viable = false;
7449 Candidate.FailureKind = ovl_non_default_multiversion_function;
7450 }
7451}
7452
7453/// Adds a conversion function template specialization
7454/// candidate to the overload set, using template argument deduction
7455/// to deduce the template arguments of the conversion function
7456/// template from the type that we are converting to (C++
7457/// [temp.deduct.conv]).
7458void Sema::AddTemplateConversionCandidate(
7459 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7460 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7461 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7462 bool AllowExplicit, bool AllowResultConversion) {
7463 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7464, __PRETTY_FUNCTION__))
7464 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7464, __PRETTY_FUNCTION__))
;
7465
7466 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7467 return;
7468
7469 // If the function template has a non-dependent explicit specification,
7470 // exclude it now if appropriate; we are not permitted to perform deduction
7471 // and substitution in this case.
7472 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7473 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7474 Candidate.FoundDecl = FoundDecl;
7475 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7476 Candidate.Viable = false;
7477 Candidate.FailureKind = ovl_fail_explicit;
7478 return;
7479 }
7480
7481 TemplateDeductionInfo Info(CandidateSet.getLocation());
7482 CXXConversionDecl *Specialization = nullptr;
7483 if (TemplateDeductionResult Result
7484 = DeduceTemplateArguments(FunctionTemplate, ToType,
7485 Specialization, Info)) {
7486 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7487 Candidate.FoundDecl = FoundDecl;
7488 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7489 Candidate.Viable = false;
7490 Candidate.FailureKind = ovl_fail_bad_deduction;
7491 Candidate.IsSurrogate = false;
7492 Candidate.IgnoreObjectArgument = false;
7493 Candidate.ExplicitCallArguments = 1;
7494 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7495 Info);
7496 return;
7497 }
7498
7499 // Add the conversion function template specialization produced by
7500 // template argument deduction as a candidate.
7501 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7501, __PRETTY_FUNCTION__))
;
7502 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7503 CandidateSet, AllowObjCConversionOnExplicit,
7504 AllowExplicit, AllowResultConversion);
7505}
7506
7507/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7508/// converts the given @c Object to a function pointer via the
7509/// conversion function @c Conversion, and then attempts to call it
7510/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7511/// the type of function that we'll eventually be calling.
7512void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7513 DeclAccessPair FoundDecl,
7514 CXXRecordDecl *ActingContext,
7515 const FunctionProtoType *Proto,
7516 Expr *Object,
7517 ArrayRef<Expr *> Args,
7518 OverloadCandidateSet& CandidateSet) {
7519 if (!CandidateSet.isNewCandidate(Conversion))
7520 return;
7521
7522 // Overload resolution is always an unevaluated context.
7523 EnterExpressionEvaluationContext Unevaluated(
7524 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7525
7526 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7527 Candidate.FoundDecl = FoundDecl;
7528 Candidate.Function = nullptr;
7529 Candidate.Surrogate = Conversion;
7530 Candidate.Viable = true;
7531 Candidate.IsSurrogate = true;
7532 Candidate.IgnoreObjectArgument = false;
7533 Candidate.ExplicitCallArguments = Args.size();
7534
7535 // Determine the implicit conversion sequence for the implicit
7536 // object parameter.
7537 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7538 *this, CandidateSet.getLocation(), Object->getType(),
7539 Object->Classify(Context), Conversion, ActingContext);
7540 if (ObjectInit.isBad()) {
7541 Candidate.Viable = false;
7542 Candidate.FailureKind = ovl_fail_bad_conversion;
7543 Candidate.Conversions[0] = ObjectInit;
7544 return;
7545 }
7546
7547 // The first conversion is actually a user-defined conversion whose
7548 // first conversion is ObjectInit's standard conversion (which is
7549 // effectively a reference binding). Record it as such.
7550 Candidate.Conversions[0].setUserDefined();
7551 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7552 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7553 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7554 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7555 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7556 Candidate.Conversions[0].UserDefined.After
7557 = Candidate.Conversions[0].UserDefined.Before;
7558 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7559
7560 // Find the
7561 unsigned NumParams = Proto->getNumParams();
7562
7563 // (C++ 13.3.2p2): A candidate function having fewer than m
7564 // parameters is viable only if it has an ellipsis in its parameter
7565 // list (8.3.5).
7566 if (Args.size() > NumParams && !Proto->isVariadic()) {
7567 Candidate.Viable = false;
7568 Candidate.FailureKind = ovl_fail_too_many_arguments;
7569 return;
7570 }
7571
7572 // Function types don't have any default arguments, so just check if
7573 // we have enough arguments.
7574 if (Args.size() < NumParams) {
7575 // Not enough arguments.
7576 Candidate.Viable = false;
7577 Candidate.FailureKind = ovl_fail_too_few_arguments;
7578 return;
7579 }
7580
7581 // Determine the implicit conversion sequences for each of the
7582 // arguments.
7583 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7584 if (ArgIdx < NumParams) {
7585 // (C++ 13.3.2p3): for F to be a viable function, there shall
7586 // exist for each argument an implicit conversion sequence
7587 // (13.3.3.1) that converts that argument to the corresponding
7588 // parameter of F.
7589 QualType ParamType = Proto->getParamType(ArgIdx);
7590 Candidate.Conversions[ArgIdx + 1]
7591 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7592 /*SuppressUserConversions=*/false,
7593 /*InOverloadResolution=*/false,
7594 /*AllowObjCWritebackConversion=*/
7595 getLangOpts().ObjCAutoRefCount);
7596 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7597 Candidate.Viable = false;
7598 Candidate.FailureKind = ovl_fail_bad_conversion;
7599 return;
7600 }
7601 } else {
7602 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7603 // argument for which there is no corresponding parameter is
7604 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7605 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7606 }
7607 }
7608
7609 if (EnableIfAttr *FailedAttr =
7610 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7611 Candidate.Viable = false;
7612 Candidate.FailureKind = ovl_fail_enable_if;
7613 Candidate.DeductionFailure.Data = FailedAttr;
7614 return;
7615 }
7616}
7617
7618/// Add all of the non-member operator function declarations in the given
7619/// function set to the overload candidate set.
7620void Sema::AddNonMemberOperatorCandidates(
7621 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7622 OverloadCandidateSet &CandidateSet,
7623 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7624 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7625 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7626 ArrayRef<Expr *> FunctionArgs = Args;
7627
7628 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7629 FunctionDecl *FD =
7630 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7631
7632 // Don't consider rewritten functions if we're not rewriting.
7633 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7634 continue;
7635
7636 assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7637, __PRETTY_FUNCTION__))
7637 "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7637, __PRETTY_FUNCTION__))
;
7638
7639 if (FunTmpl) {
7640 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7641 FunctionArgs, CandidateSet);
7642 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7643 AddTemplateOverloadCandidate(
7644 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7645 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7646 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7647 } else {
7648 if (ExplicitTemplateArgs)
7649 continue;
7650 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7651 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7652 AddOverloadCandidate(FD, F.getPair(),
7653 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7654 false, false, true, false, ADLCallKind::NotADL,
7655 None, OverloadCandidateParamOrder::Reversed);
7656 }
7657 }
7658}
7659
7660/// Add overload candidates for overloaded operators that are
7661/// member functions.
7662///
7663/// Add the overloaded operator candidates that are member functions
7664/// for the operator Op that was used in an operator expression such
7665/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7666/// CandidateSet will store the added overload candidates. (C++
7667/// [over.match.oper]).
7668void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7669 SourceLocation OpLoc,
7670 ArrayRef<Expr *> Args,
7671 OverloadCandidateSet &CandidateSet,
7672 OverloadCandidateParamOrder PO) {
7673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7674
7675 // C++ [over.match.oper]p3:
7676 // For a unary operator @ with an operand of a type whose
7677 // cv-unqualified version is T1, and for a binary operator @ with
7678 // a left operand of a type whose cv-unqualified version is T1 and
7679 // a right operand of a type whose cv-unqualified version is T2,
7680 // three sets of candidate functions, designated member
7681 // candidates, non-member candidates and built-in candidates, are
7682 // constructed as follows:
7683 QualType T1 = Args[0]->getType();
7684
7685 // -- If T1 is a complete class type or a class currently being
7686 // defined, the set of member candidates is the result of the
7687 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7688 // the set of member candidates is empty.
7689 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7690 // Complete the type if it can be completed.
7691 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7692 return;
7693 // If the type is neither complete nor being defined, bail out now.
7694 if (!T1Rec->getDecl()->getDefinition())
7695 return;
7696
7697 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7698 LookupQualifiedName(Operators, T1Rec->getDecl());
7699 Operators.suppressDiagnostics();
7700
7701 for (LookupResult::iterator Oper = Operators.begin(),
7702 OperEnd = Operators.end();
7703 Oper != OperEnd;
7704 ++Oper)
7705 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7706 Args[0]->Classify(Context), Args.slice(1),
7707 CandidateSet, /*SuppressUserConversion=*/false, PO);
7708 }
7709}
7710
7711/// AddBuiltinCandidate - Add a candidate for a built-in
7712/// operator. ResultTy and ParamTys are the result and parameter types
7713/// of the built-in candidate, respectively. Args and NumArgs are the
7714/// arguments being passed to the candidate. IsAssignmentOperator
7715/// should be true when this built-in candidate is an assignment
7716/// operator. NumContextualBoolArguments is the number of arguments
7717/// (at the beginning of the argument list) that will be contextually
7718/// converted to bool.
7719void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7720 OverloadCandidateSet& CandidateSet,
7721 bool IsAssignmentOperator,
7722 unsigned NumContextualBoolArguments) {
7723 // Overload resolution is always an unevaluated context.
7724 EnterExpressionEvaluationContext Unevaluated(
7725 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7726
7727 // Add this candidate
7728 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7729 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7730 Candidate.Function = nullptr;
7731 Candidate.IsSurrogate = false;
7732 Candidate.IgnoreObjectArgument = false;
7733 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7734
7735 // Determine the implicit conversion sequences for each of the
7736 // arguments.
7737 Candidate.Viable = true;
7738 Candidate.ExplicitCallArguments = Args.size();
7739 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7740 // C++ [over.match.oper]p4:
7741 // For the built-in assignment operators, conversions of the
7742 // left operand are restricted as follows:
7743 // -- no temporaries are introduced to hold the left operand, and
7744 // -- no user-defined conversions are applied to the left
7745 // operand to achieve a type match with the left-most
7746 // parameter of a built-in candidate.
7747 //
7748 // We block these conversions by turning off user-defined
7749 // conversions, since that is the only way that initialization of
7750 // a reference to a non-class type can occur from something that
7751 // is not of the same type.
7752 if (ArgIdx < NumContextualBoolArguments) {
7753 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7754, __PRETTY_FUNCTION__))
7754 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7754, __PRETTY_FUNCTION__))
;
7755 Candidate.Conversions[ArgIdx]
7756 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7757 } else {
7758 Candidate.Conversions[ArgIdx]
7759 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7760 ArgIdx == 0 && IsAssignmentOperator,
7761 /*InOverloadResolution=*/false,
7762 /*AllowObjCWritebackConversion=*/
7763 getLangOpts().ObjCAutoRefCount);
7764 }
7765 if (Candidate.Conversions[ArgIdx].isBad()) {
7766 Candidate.Viable = false;
7767 Candidate.FailureKind = ovl_fail_bad_conversion;
7768 break;
7769 }
7770 }
7771}
7772
7773namespace {
7774
7775/// BuiltinCandidateTypeSet - A set of types that will be used for the
7776/// candidate operator functions for built-in operators (C++
7777/// [over.built]). The types are separated into pointer types and
7778/// enumeration types.
7779class BuiltinCandidateTypeSet {
7780 /// TypeSet - A set of types.
7781 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7782 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7783
7784 /// PointerTypes - The set of pointer types that will be used in the
7785 /// built-in candidates.
7786 TypeSet PointerTypes;
7787
7788 /// MemberPointerTypes - The set of member pointer types that will be
7789 /// used in the built-in candidates.
7790 TypeSet MemberPointerTypes;
7791
7792 /// EnumerationTypes - The set of enumeration types that will be
7793 /// used in the built-in candidates.
7794 TypeSet EnumerationTypes;
7795
7796 /// The set of vector types that will be used in the built-in
7797 /// candidates.
7798 TypeSet VectorTypes;
7799
7800 /// The set of matrix types that will be used in the built-in
7801 /// candidates.
7802 TypeSet MatrixTypes;
7803
7804 /// A flag indicating non-record types are viable candidates
7805 bool HasNonRecordTypes;
7806
7807 /// A flag indicating whether either arithmetic or enumeration types
7808 /// were present in the candidate set.
7809 bool HasArithmeticOrEnumeralTypes;
7810
7811 /// A flag indicating whether the nullptr type was present in the
7812 /// candidate set.
7813 bool HasNullPtrType;
7814
7815 /// Sema - The semantic analysis instance where we are building the
7816 /// candidate type set.
7817 Sema &SemaRef;
7818
7819 /// Context - The AST context in which we will build the type sets.
7820 ASTContext &Context;
7821
7822 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7823 const Qualifiers &VisibleQuals);
7824 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7825
7826public:
7827 /// iterator - Iterates through the types that are part of the set.
7828 typedef TypeSet::iterator iterator;
7829
7830 BuiltinCandidateTypeSet(Sema &SemaRef)
7831 : HasNonRecordTypes(false),
7832 HasArithmeticOrEnumeralTypes(false),
7833 HasNullPtrType(false),
7834 SemaRef(SemaRef),
7835 Context(SemaRef.Context) { }
7836
7837 void AddTypesConvertedFrom(QualType Ty,
7838 SourceLocation Loc,
7839 bool AllowUserConversions,
7840 bool AllowExplicitConversions,
7841 const Qualifiers &VisibleTypeConversionsQuals);
7842
7843 /// pointer_begin - First pointer type found;
7844 iterator pointer_begin() { return PointerTypes.begin(); }
7845
7846 /// pointer_end - Past the last pointer type found;
7847 iterator pointer_end() { return PointerTypes.end(); }
7848
7849 /// member_pointer_begin - First member pointer type found;
7850 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7851
7852 /// member_pointer_end - Past the last member pointer type found;
7853 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7854
7855 /// enumeration_begin - First enumeration type found;
7856 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7857
7858 /// enumeration_end - Past the last enumeration type found;
7859 iterator enumeration_end() { return EnumerationTypes.end(); }
7860
7861 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7862
7863 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7864
7865 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7866 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7867 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7868 bool hasNullPtrType() const { return HasNullPtrType; }
7869};
7870
7871} // end anonymous namespace
7872
7873/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7874/// the set of pointer types along with any more-qualified variants of
7875/// that type. For example, if @p Ty is "int const *", this routine
7876/// will add "int const *", "int const volatile *", "int const
7877/// restrict *", and "int const volatile restrict *" to the set of
7878/// pointer types. Returns true if the add of @p Ty itself succeeded,
7879/// false otherwise.
7880///
7881/// FIXME: what to do about extended qualifiers?
7882bool
7883BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7884 const Qualifiers &VisibleQuals) {
7885
7886 // Insert this type.
7887 if (!PointerTypes.insert(Ty))
7888 return false;
7889
7890 QualType PointeeTy;
7891 const PointerType *PointerTy = Ty->getAs<PointerType>();
7892 bool buildObjCPtr = false;
7893 if (!PointerTy) {
7894 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7895 PointeeTy = PTy->getPointeeType();
7896 buildObjCPtr = true;
7897 } else {
7898 PointeeTy = PointerTy->getPointeeType();
7899 }
7900
7901 // Don't add qualified variants of arrays. For one, they're not allowed
7902 // (the qualifier would sink to the element type), and for another, the
7903 // only overload situation where it matters is subscript or pointer +- int,
7904 // and those shouldn't have qualifier variants anyway.
7905 if (PointeeTy->isArrayType())
7906 return true;
7907
7908 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7909 bool hasVolatile = VisibleQuals.hasVolatile();
7910 bool hasRestrict = VisibleQuals.hasRestrict();
7911
7912 // Iterate through all strict supersets of BaseCVR.
7913 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7914 if ((CVR | BaseCVR) != CVR) continue;
7915 // Skip over volatile if no volatile found anywhere in the types.
7916 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7917
7918 // Skip over restrict if no restrict found anywhere in the types, or if
7919 // the type cannot be restrict-qualified.
7920 if ((CVR & Qualifiers::Restrict) &&
7921 (!hasRestrict ||
7922 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7923 continue;
7924
7925 // Build qualified pointee type.
7926 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7927
7928 // Build qualified pointer type.
7929 QualType QPointerTy;
7930 if (!buildObjCPtr)
7931 QPointerTy = Context.getPointerType(QPointeeTy);
7932 else
7933 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7934
7935 // Insert qualified pointer type.
7936 PointerTypes.insert(QPointerTy);
7937 }
7938
7939 return true;
7940}
7941
7942/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7943/// to the set of pointer types along with any more-qualified variants of
7944/// that type. For example, if @p Ty is "int const *", this routine
7945/// will add "int const *", "int const volatile *", "int const
7946/// restrict *", and "int const volatile restrict *" to the set of
7947/// pointer types. Returns true if the add of @p Ty itself succeeded,
7948/// false otherwise.
7949///
7950/// FIXME: what to do about extended qualifiers?
7951bool
7952BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7953 QualType Ty) {
7954 // Insert this type.
7955 if (!MemberPointerTypes.insert(Ty))
7956 return false;
7957
7958 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7959 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 7959, __PRETTY_FUNCTION__))
;
7960
7961 QualType PointeeTy = PointerTy->getPointeeType();
7962 // Don't add qualified variants of arrays. For one, they're not allowed
7963 // (the qualifier would sink to the element type), and for another, the
7964 // only overload situation where it matters is subscript or pointer +- int,
7965 // and those shouldn't have qualifier variants anyway.
7966 if (PointeeTy->isArrayType())
7967 return true;
7968 const Type *ClassTy = PointerTy->getClass();
7969
7970 // Iterate through all strict supersets of the pointee type's CVR
7971 // qualifiers.
7972 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7973 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7974 if ((CVR | BaseCVR) != CVR) continue;
7975
7976 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7977 MemberPointerTypes.insert(
7978 Context.getMemberPointerType(QPointeeTy, ClassTy));
7979 }
7980
7981 return true;
7982}
7983
7984/// AddTypesConvertedFrom - Add each of the types to which the type @p
7985/// Ty can be implicit converted to the given set of @p Types. We're
7986/// primarily interested in pointer types and enumeration types. We also
7987/// take member pointer types, for the conditional operator.
7988/// AllowUserConversions is true if we should look at the conversion
7989/// functions of a class type, and AllowExplicitConversions if we
7990/// should also include the explicit conversion functions of a class
7991/// type.
7992void
7993BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7994 SourceLocation Loc,
7995 bool AllowUserConversions,
7996 bool AllowExplicitConversions,
7997 const Qualifiers &VisibleQuals) {
7998 // Only deal with canonical types.
7999 Ty = Context.getCanonicalType(Ty);
8000
8001 // Look through reference types; they aren't part of the type of an
8002 // expression for the purposes of conversions.
8003 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8004 Ty = RefTy->getPointeeType();
8005
8006 // If we're dealing with an array type, decay to the pointer.
8007 if (Ty->isArrayType())
8008 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8009
8010 // Otherwise, we don't care about qualifiers on the type.
8011 Ty = Ty.getLocalUnqualifiedType();
8012
8013 // Flag if we ever add a non-record type.
8014 const RecordType *TyRec = Ty->getAs<RecordType>();
8015 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8016
8017 // Flag if we encounter an arithmetic type.
8018 HasArithmeticOrEnumeralTypes =
8019 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8020
8021 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8022 PointerTypes.insert(Ty);
8023 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8024 // Insert our type, and its more-qualified variants, into the set
8025 // of types.
8026 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8027 return;
8028 } else if (Ty->isMemberPointerType()) {
8029 // Member pointers are far easier, since the pointee can't be converted.
8030 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8031 return;
8032 } else if (Ty->isEnumeralType()) {
8033 HasArithmeticOrEnumeralTypes = true;
8034 EnumerationTypes.insert(Ty);
8035 } else if (Ty->isVectorType()) {
8036 // We treat vector types as arithmetic types in many contexts as an
8037 // extension.
8038 HasArithmeticOrEnumeralTypes = true;
8039 VectorTypes.insert(Ty);
8040 } else if (Ty->isMatrixType()) {
8041 // Similar to vector types, we treat vector types as arithmetic types in
8042 // many contexts as an extension.
8043 HasArithmeticOrEnumeralTypes = true;
8044 MatrixTypes.insert(Ty);
8045 } else if (Ty->isNullPtrType()) {
8046 HasNullPtrType = true;
8047 } else if (AllowUserConversions && TyRec) {
8048 // No conversion functions in incomplete types.
8049 if (!SemaRef.isCompleteType(Loc, Ty))
8050 return;
8051
8052 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8053 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8054 if (isa<UsingShadowDecl>(D))
8055 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8056
8057 // Skip conversion function templates; they don't tell us anything
8058 // about which builtin types we can convert to.
8059 if (isa<FunctionTemplateDecl>(D))
8060 continue;
8061
8062 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8063 if (AllowExplicitConversions || !Conv->isExplicit()) {
8064 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8065 VisibleQuals);
8066 }
8067 }
8068 }
8069}
8070/// Helper function for adjusting address spaces for the pointer or reference
8071/// operands of builtin operators depending on the argument.
8072static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8073 Expr *Arg) {
8074 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8075}
8076
8077/// Helper function for AddBuiltinOperatorCandidates() that adds
8078/// the volatile- and non-volatile-qualified assignment operators for the
8079/// given type to the candidate set.
8080static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8081 QualType T,
8082 ArrayRef<Expr *> Args,
8083 OverloadCandidateSet &CandidateSet) {
8084 QualType ParamTypes[2];
8085
8086 // T& operator=(T&, T)
8087 ParamTypes[0] = S.Context.getLValueReferenceType(
8088 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8089 ParamTypes[1] = T;
8090 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8091 /*IsAssignmentOperator=*/true);
8092
8093 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8094 // volatile T& operator=(volatile T&, T)
8095 ParamTypes[0] = S.Context.getLValueReferenceType(
8096 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8097 Args[0]));
8098 ParamTypes[1] = T;
8099 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8100 /*IsAssignmentOperator=*/true);
8101 }
8102}
8103
8104/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8105/// if any, found in visible type conversion functions found in ArgExpr's type.
8106static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8107 Qualifiers VRQuals;
8108 const RecordType *TyRec;
8109 if (const MemberPointerType *RHSMPType =
8110 ArgExpr->getType()->getAs<MemberPointerType>())
8111 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8112 else
8113 TyRec = ArgExpr->getType()->getAs<RecordType>();
8114 if (!TyRec) {
8115 // Just to be safe, assume the worst case.
8116 VRQuals.addVolatile();
8117 VRQuals.addRestrict();
8118 return VRQuals;
8119 }
8120
8121 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8122 if (!ClassDecl->hasDefinition())
8123 return VRQuals;
8124
8125 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8126 if (isa<UsingShadowDecl>(D))
8127 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8128 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8129 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8130 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8131 CanTy = ResTypeRef->getPointeeType();
8132 // Need to go down the pointer/mempointer chain and add qualifiers
8133 // as see them.
8134 bool done = false;
8135 while (!done) {
8136 if (CanTy.isRestrictQualified())
8137 VRQuals.addRestrict();
8138 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8139 CanTy = ResTypePtr->getPointeeType();
8140 else if (const MemberPointerType *ResTypeMPtr =
8141 CanTy->getAs<MemberPointerType>())
8142 CanTy = ResTypeMPtr->getPointeeType();
8143 else
8144 done = true;
8145 if (CanTy.isVolatileQualified())
8146 VRQuals.addVolatile();
8147 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8148 return VRQuals;
8149 }
8150 }
8151 }
8152 return VRQuals;
8153}
8154
8155namespace {
8156
8157/// Helper class to manage the addition of builtin operator overload
8158/// candidates. It provides shared state and utility methods used throughout
8159/// the process, as well as a helper method to add each group of builtin
8160/// operator overloads from the standard to a candidate set.
8161class BuiltinOperatorOverloadBuilder {
8162 // Common instance state available to all overload candidate addition methods.
8163 Sema &S;
8164 ArrayRef<Expr *> Args;
8165 Qualifiers VisibleTypeConversionsQuals;
8166 bool HasArithmeticOrEnumeralCandidateType;
8167 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8168 OverloadCandidateSet &CandidateSet;
8169
8170 static constexpr int ArithmeticTypesCap = 24;
8171 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8172
8173 // Define some indices used to iterate over the arithmetic types in
8174 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8175 // types are that preserved by promotion (C++ [over.built]p2).
8176 unsigned FirstIntegralType,
8177 LastIntegralType;
8178 unsigned FirstPromotedIntegralType,
8179 LastPromotedIntegralType;
8180 unsigned FirstPromotedArithmeticType,
8181 LastPromotedArithmeticType;
8182 unsigned NumArithmeticTypes;
8183
8184 void InitArithmeticTypes() {
8185 // Start of promoted types.
8186 FirstPromotedArithmeticType = 0;
8187 ArithmeticTypes.push_back(S.Context.FloatTy);
8188 ArithmeticTypes.push_back(S.Context.DoubleTy);
8189 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8190 if (S.Context.getTargetInfo().hasFloat128Type())
8191 ArithmeticTypes.push_back(S.Context.Float128Ty);
8192
8193 // Start of integral types.
8194 FirstIntegralType = ArithmeticTypes.size();
8195 FirstPromotedIntegralType = ArithmeticTypes.size();
8196 ArithmeticTypes.push_back(S.Context.IntTy);
8197 ArithmeticTypes.push_back(S.Context.LongTy);
8198 ArithmeticTypes.push_back(S.Context.LongLongTy);
8199 if (S.Context.getTargetInfo().hasInt128Type())
8200 ArithmeticTypes.push_back(S.Context.Int128Ty);
8201 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8202 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8203 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8204 if (S.Context.getTargetInfo().hasInt128Type())
8205 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8206 LastPromotedIntegralType = ArithmeticTypes.size();
8207 LastPromotedArithmeticType = ArithmeticTypes.size();
8208 // End of promoted types.
8209
8210 ArithmeticTypes.push_back(S.Context.BoolTy);
8211 ArithmeticTypes.push_back(S.Context.CharTy);
8212 ArithmeticTypes.push_back(S.Context.WCharTy);
8213 if (S.Context.getLangOpts().Char8)
8214 ArithmeticTypes.push_back(S.Context.Char8Ty);
8215 ArithmeticTypes.push_back(S.Context.Char16Ty);
8216 ArithmeticTypes.push_back(S.Context.Char32Ty);
8217 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8218 ArithmeticTypes.push_back(S.Context.ShortTy);
8219 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8220 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8221 LastIntegralType = ArithmeticTypes.size();
8222 NumArithmeticTypes = ArithmeticTypes.size();
8223 // End of integral types.
8224 // FIXME: What about complex? What about half?
8225
8226 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 8227, __PRETTY_FUNCTION__))
8227 "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 8227, __PRETTY_FUNCTION__))
;
8228 }
8229
8230 /// Helper method to factor out the common pattern of adding overloads
8231 /// for '++' and '--' builtin operators.
8232 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8233 bool HasVolatile,
8234 bool HasRestrict) {
8235 QualType ParamTypes[2] = {
8236 S.Context.getLValueReferenceType(CandidateTy),
8237 S.Context.IntTy
8238 };
8239
8240 // Non-volatile version.
8241 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8242
8243 // Use a heuristic to reduce number of builtin candidates in the set:
8244 // add volatile version only if there are conversions to a volatile type.
8245 if (HasVolatile) {
8246 ParamTypes[0] =
8247 S.Context.getLValueReferenceType(
8248 S.Context.getVolatileType(CandidateTy));
8249 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8250 }
8251
8252 // Add restrict version only if there are conversions to a restrict type
8253 // and our candidate type is a non-restrict-qualified pointer.
8254 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8255 !CandidateTy.isRestrictQualified()) {
8256 ParamTypes[0]
8257 = S.Context.getLValueReferenceType(
8258 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8259 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8260
8261 if (HasVolatile) {
8262 ParamTypes[0]
8263 = S.Context.getLValueReferenceType(
8264 S.Context.getCVRQualifiedType(CandidateTy,
8265 (Qualifiers::Volatile |
8266 Qualifiers::Restrict)));
8267 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8268 }
8269 }
8270
8271 }
8272
8273 /// Helper to add an overload candidate for a binary builtin with types \p L
8274 /// and \p R.
8275 void AddCandidate(QualType L, QualType R) {
8276 QualType LandR[2] = {L, R};
8277 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8278 }
8279
8280public:
8281 BuiltinOperatorOverloadBuilder(
8282 Sema &S, ArrayRef<Expr *> Args,
8283 Qualifiers VisibleTypeConversionsQuals,
8284 bool HasArithmeticOrEnumeralCandidateType,
8285 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8286 OverloadCandidateSet &CandidateSet)
8287 : S(S), Args(Args),
8288 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8289 HasArithmeticOrEnumeralCandidateType(
8290 HasArithmeticOrEnumeralCandidateType),
8291 CandidateTypes(CandidateTypes),
8292 CandidateSet(CandidateSet) {
8293
8294 InitArithmeticTypes();
8295 }
8296
8297 // Increment is deprecated for bool since C++17.
8298 //
8299 // C++ [over.built]p3:
8300 //
8301 // For every pair (T, VQ), where T is an arithmetic type other
8302 // than bool, and VQ is either volatile or empty, there exist
8303 // candidate operator functions of the form
8304 //
8305 // VQ T& operator++(VQ T&);
8306 // T operator++(VQ T&, int);
8307 //
8308 // C++ [over.built]p4:
8309 //
8310 // For every pair (T, VQ), where T is an arithmetic type other
8311 // than bool, and VQ is either volatile or empty, there exist
8312 // candidate operator functions of the form
8313 //
8314 // VQ T& operator--(VQ T&);
8315 // T operator--(VQ T&, int);
8316 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8317 if (!HasArithmeticOrEnumeralCandidateType)
8318 return;
8319
8320 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8321 const auto TypeOfT = ArithmeticTypes[Arith];
8322 if (TypeOfT == S.Context.BoolTy) {
8323 if (Op == OO_MinusMinus)
8324 continue;
8325 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8326 continue;
8327 }
8328 addPlusPlusMinusMinusStyleOverloads(
8329 TypeOfT,
8330 VisibleTypeConversionsQuals.hasVolatile(),
8331 VisibleTypeConversionsQuals.hasRestrict());
8332 }
8333 }
8334
8335 // C++ [over.built]p5:
8336 //
8337 // For every pair (T, VQ), where T is a cv-qualified or
8338 // cv-unqualified object type, and VQ is either volatile or
8339 // empty, there exist candidate operator functions of the form
8340 //
8341 // T*VQ& operator++(T*VQ&);
8342 // T*VQ& operator--(T*VQ&);
8343 // T* operator++(T*VQ&, int);
8344 // T* operator--(T*VQ&, int);
8345 void addPlusPlusMinusMinusPointerOverloads() {
8346 for (BuiltinCandidateTypeSet::iterator
8347 Ptr = CandidateTypes[0].pointer_begin(),
8348 PtrEnd = CandidateTypes[0].pointer_end();
8349 Ptr != PtrEnd; ++Ptr) {
8350 // Skip pointer types that aren't pointers to object types.
8351 if (!(*Ptr)->getPointeeType()->isObjectType())
8352 continue;
8353
8354 addPlusPlusMinusMinusStyleOverloads(*Ptr,
8355 (!(*Ptr).isVolatileQualified() &&
8356 VisibleTypeConversionsQuals.hasVolatile()),
8357 (!(*Ptr).isRestrictQualified() &&
8358 VisibleTypeConversionsQuals.hasRestrict()));
8359 }
8360 }
8361
8362 // C++ [over.built]p6:
8363 // For every cv-qualified or cv-unqualified object type T, there
8364 // exist candidate operator functions of the form
8365 //
8366 // T& operator*(T*);
8367 //
8368 // C++ [over.built]p7:
8369 // For every function type T that does not have cv-qualifiers or a
8370 // ref-qualifier, there exist candidate operator functions of the form
8371 // T& operator*(T*);
8372 void addUnaryStarPointerOverloads() {
8373 for (BuiltinCandidateTypeSet::iterator
8374 Ptr = CandidateTypes[0].pointer_begin(),
8375 PtrEnd = CandidateTypes[0].pointer_end();
8376 Ptr != PtrEnd; ++Ptr) {
8377 QualType ParamTy = *Ptr;
8378 QualType PointeeTy = ParamTy->getPointeeType();
8379 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8380 continue;
8381
8382 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8383 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8384 continue;
8385
8386 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8387 }
8388 }
8389
8390 // C++ [over.built]p9:
8391 // For every promoted arithmetic type T, there exist candidate
8392 // operator functions of the form
8393 //
8394 // T operator+(T);
8395 // T operator-(T);
8396 void addUnaryPlusOrMinusArithmeticOverloads() {
8397 if (!HasArithmeticOrEnumeralCandidateType)
8398 return;
8399
8400 for (unsigned Arith = FirstPromotedArithmeticType;
8401 Arith < LastPromotedArithmeticType; ++Arith) {
8402 QualType ArithTy = ArithmeticTypes[Arith];
8403 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8404 }
8405
8406 // Extension: We also add these operators for vector types.
8407 for (QualType VecTy : CandidateTypes[0].vector_types())
8408 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8409 }
8410
8411 // C++ [over.built]p8:
8412 // For every type T, there exist candidate operator functions of
8413 // the form
8414 //
8415 // T* operator+(T*);
8416 void addUnaryPlusPointerOverloads() {
8417 for (BuiltinCandidateTypeSet::iterator
8418 Ptr = CandidateTypes[0].pointer_begin(),
8419 PtrEnd = CandidateTypes[0].pointer_end();
8420 Ptr != PtrEnd; ++Ptr) {
8421 QualType ParamTy = *Ptr;
8422 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8423 }
8424 }
8425
8426 // C++ [over.built]p10:
8427 // For every promoted integral type T, there exist candidate
8428 // operator functions of the form
8429 //
8430 // T operator~(T);
8431 void addUnaryTildePromotedIntegralOverloads() {
8432 if (!HasArithmeticOrEnumeralCandidateType)
8433 return;
8434
8435 for (unsigned Int = FirstPromotedIntegralType;
8436 Int < LastPromotedIntegralType; ++Int) {
8437 QualType IntTy = ArithmeticTypes[Int];
8438 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8439 }
8440
8441 // Extension: We also add this operator for vector types.
8442 for (QualType VecTy : CandidateTypes[0].vector_types())
8443 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8444 }
8445
8446 // C++ [over.match.oper]p16:
8447 // For every pointer to member type T or type std::nullptr_t, there
8448 // exist candidate operator functions of the form
8449 //
8450 // bool operator==(T,T);
8451 // bool operator!=(T,T);
8452 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8453 /// Set of (canonical) types that we've already handled.
8454 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8455
8456 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8457 for (BuiltinCandidateTypeSet::iterator
8458 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8459 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8460 MemPtr != MemPtrEnd;
8461 ++MemPtr) {
8462 // Don't add the same builtin candidate twice.
8463 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8464 continue;
8465
8466 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8467 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8468 }
8469
8470 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8471 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8472 if (AddedTypes.insert(NullPtrTy).second) {
8473 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8474 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8475 }
8476 }
8477 }
8478 }
8479
8480 // C++ [over.built]p15:
8481 //
8482 // For every T, where T is an enumeration type or a pointer type,
8483 // there exist candidate operator functions of the form
8484 //
8485 // bool operator<(T, T);
8486 // bool operator>(T, T);
8487 // bool operator<=(T, T);
8488 // bool operator>=(T, T);
8489 // bool operator==(T, T);
8490 // bool operator!=(T, T);
8491 // R operator<=>(T, T)
8492 void addGenericBinaryPointerOrEnumeralOverloads() {
8493 // C++ [over.match.oper]p3:
8494 // [...]the built-in candidates include all of the candidate operator
8495 // functions defined in 13.6 that, compared to the given operator, [...]
8496 // do not have the same parameter-type-list as any non-template non-member
8497 // candidate.
8498 //
8499 // Note that in practice, this only affects enumeration types because there
8500 // aren't any built-in candidates of record type, and a user-defined operator
8501 // must have an operand of record or enumeration type. Also, the only other
8502 // overloaded operator with enumeration arguments, operator=,
8503 // cannot be overloaded for enumeration types, so this is the only place
8504 // where we must suppress candidates like this.
8505 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8506 UserDefinedBinaryOperators;
8507
8508 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8509 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8510 CandidateTypes[ArgIdx].enumeration_end()) {
8511 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8512 CEnd = CandidateSet.end();
8513 C != CEnd; ++C) {
8514 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8515 continue;
8516
8517 if (C->Function->isFunctionTemplateSpecialization())
8518 continue;
8519
8520 // We interpret "same parameter-type-list" as applying to the
8521 // "synthesized candidate, with the order of the two parameters
8522 // reversed", not to the original function.
8523 bool Reversed = C->isReversed();
8524 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8525 ->getType()
8526 .getUnqualifiedType();
8527 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8528 ->getType()
8529 .getUnqualifiedType();
8530
8531 // Skip if either parameter isn't of enumeral type.
8532 if (!FirstParamType->isEnumeralType() ||
8533 !SecondParamType->isEnumeralType())
8534 continue;
8535
8536 // Add this operator to the set of known user-defined operators.
8537 UserDefinedBinaryOperators.insert(
8538 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8539 S.Context.getCanonicalType(SecondParamType)));
8540 }
8541 }
8542 }
8543
8544 /// Set of (canonical) types that we've already handled.
8545 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8546
8547 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8548 for (BuiltinCandidateTypeSet::iterator
8549 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8550 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8551 Ptr != PtrEnd; ++Ptr) {
8552 // Don't add the same builtin candidate twice.
8553 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8554 continue;
8555
8556 QualType ParamTypes[2] = { *Ptr, *Ptr };
8557 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8558 }
8559 for (BuiltinCandidateTypeSet::iterator
8560 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8561 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8562 Enum != EnumEnd; ++Enum) {
8563 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8564
8565 // Don't add the same builtin candidate twice, or if a user defined
8566 // candidate exists.
8567 if (!AddedTypes.insert(CanonType).second ||
8568 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8569 CanonType)))
8570 continue;
8571 QualType ParamTypes[2] = { *Enum, *Enum };
8572 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8573 }
8574 }
8575 }
8576
8577 // C++ [over.built]p13:
8578 //
8579 // For every cv-qualified or cv-unqualified object type T
8580 // there exist candidate operator functions of the form
8581 //
8582 // T* operator+(T*, ptrdiff_t);
8583 // T& operator[](T*, ptrdiff_t); [BELOW]
8584 // T* operator-(T*, ptrdiff_t);
8585 // T* operator+(ptrdiff_t, T*);
8586 // T& operator[](ptrdiff_t, T*); [BELOW]
8587 //
8588 // C++ [over.built]p14:
8589 //
8590 // For every T, where T is a pointer to object type, there
8591 // exist candidate operator functions of the form
8592 //
8593 // ptrdiff_t operator-(T, T);
8594 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8595 /// Set of (canonical) types that we've already handled.
8596 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8597
8598 for (int Arg = 0; Arg < 2; ++Arg) {
8599 QualType AsymmetricParamTypes[2] = {
8600 S.Context.getPointerDiffType(),
8601 S.Context.getPointerDiffType(),
8602 };
8603 for (BuiltinCandidateTypeSet::iterator
8604 Ptr = CandidateTypes[Arg].pointer_begin(),
8605 PtrEnd = CandidateTypes[Arg].pointer_end();
8606 Ptr != PtrEnd; ++Ptr) {
8607 QualType PointeeTy = (*Ptr)->getPointeeType();
8608 if (!PointeeTy->isObjectType())
8609 continue;
8610
8611 AsymmetricParamTypes[Arg] = *Ptr;
8612 if (Arg == 0 || Op == OO_Plus) {
8613 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8614 // T* operator+(ptrdiff_t, T*);
8615 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8616 }
8617 if (Op == OO_Minus) {
8618 // ptrdiff_t operator-(T, T);
8619 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8620 continue;
8621
8622 QualType ParamTypes[2] = { *Ptr, *Ptr };
8623 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8624 }
8625 }
8626 }
8627 }
8628
8629 // C++ [over.built]p12:
8630 //
8631 // For every pair of promoted arithmetic types L and R, there
8632 // exist candidate operator functions of the form
8633 //
8634 // LR operator*(L, R);
8635 // LR operator/(L, R);
8636 // LR operator+(L, R);
8637 // LR operator-(L, R);
8638 // bool operator<(L, R);
8639 // bool operator>(L, R);
8640 // bool operator<=(L, R);
8641 // bool operator>=(L, R);
8642 // bool operator==(L, R);
8643 // bool operator!=(L, R);
8644 //
8645 // where LR is the result of the usual arithmetic conversions
8646 // between types L and R.
8647 //
8648 // C++ [over.built]p24:
8649 //
8650 // For every pair of promoted arithmetic types L and R, there exist
8651 // candidate operator functions of the form
8652 //
8653 // LR operator?(bool, L, R);
8654 //
8655 // where LR is the result of the usual arithmetic conversions
8656 // between types L and R.
8657 // Our candidates ignore the first parameter.
8658 void addGenericBinaryArithmeticOverloads() {
8659 if (!HasArithmeticOrEnumeralCandidateType)
8660 return;
8661
8662 for (unsigned Left = FirstPromotedArithmeticType;
8663 Left < LastPromotedArithmeticType; ++Left) {
8664 for (unsigned Right = FirstPromotedArithmeticType;
8665 Right < LastPromotedArithmeticType; ++Right) {
8666 QualType LandR[2] = { ArithmeticTypes[Left],
8667 ArithmeticTypes[Right] };
8668 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8669 }
8670 }
8671
8672 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8673 // conditional operator for vector types.
8674 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8675 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8676 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8677 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8678 }
8679 }
8680
8681 /// Add binary operator overloads for each candidate matrix type M1, M2:
8682 /// * (M1, M1) -> M1
8683 /// * (M1, M1.getElementType()) -> M1
8684 /// * (M2.getElementType(), M2) -> M2
8685 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8686 void addMatrixBinaryArithmeticOverloads() {
8687 if (!HasArithmeticOrEnumeralCandidateType)
8688 return;
8689
8690 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8691 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8692 AddCandidate(M1, M1);
8693 }
8694
8695 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8696 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8697 if (!CandidateTypes[0].containsMatrixType(M2))
8698 AddCandidate(M2, M2);
8699 }
8700 }
8701
8702 // C++2a [over.built]p14:
8703 //
8704 // For every integral type T there exists a candidate operator function
8705 // of the form
8706 //
8707 // std::strong_ordering operator<=>(T, T)
8708 //
8709 // C++2a [over.built]p15:
8710 //
8711 // For every pair of floating-point types L and R, there exists a candidate
8712 // operator function of the form
8713 //
8714 // std::partial_ordering operator<=>(L, R);
8715 //
8716 // FIXME: The current specification for integral types doesn't play nice with
8717 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8718 // comparisons. Under the current spec this can lead to ambiguity during
8719 // overload resolution. For example:
8720 //
8721 // enum A : int {a};
8722 // auto x = (a <=> (long)42);
8723 //
8724 // error: call is ambiguous for arguments 'A' and 'long'.
8725 // note: candidate operator<=>(int, int)
8726 // note: candidate operator<=>(long, long)
8727 //
8728 // To avoid this error, this function deviates from the specification and adds
8729 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8730 // arithmetic types (the same as the generic relational overloads).
8731 //
8732 // For now this function acts as a placeholder.
8733 void addThreeWayArithmeticOverloads() {
8734 addGenericBinaryArithmeticOverloads();
8735 }
8736
8737 // C++ [over.built]p17:
8738 //
8739 // For every pair of promoted integral types L and R, there
8740 // exist candidate operator functions of the form
8741 //
8742 // LR operator%(L, R);
8743 // LR operator&(L, R);
8744 // LR operator^(L, R);
8745 // LR operator|(L, R);
8746 // L operator<<(L, R);
8747 // L operator>>(L, R);
8748 //
8749 // where LR is the result of the usual arithmetic conversions
8750 // between types L and R.
8751 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8752 if (!HasArithmeticOrEnumeralCandidateType)
8753 return;
8754
8755 for (unsigned Left = FirstPromotedIntegralType;
8756 Left < LastPromotedIntegralType; ++Left) {
8757 for (unsigned Right = FirstPromotedIntegralType;
8758 Right < LastPromotedIntegralType; ++Right) {
8759 QualType LandR[2] = { ArithmeticTypes[Left],
8760 ArithmeticTypes[Right] };
8761 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8762 }
8763 }
8764 }
8765
8766 // C++ [over.built]p20:
8767 //
8768 // For every pair (T, VQ), where T is an enumeration or
8769 // pointer to member type and VQ is either volatile or
8770 // empty, there exist candidate operator functions of the form
8771 //
8772 // VQ T& operator=(VQ T&, T);
8773 void addAssignmentMemberPointerOrEnumeralOverloads() {
8774 /// Set of (canonical) types that we've already handled.
8775 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8776
8777 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8778 for (BuiltinCandidateTypeSet::iterator
8779 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8780 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8781 Enum != EnumEnd; ++Enum) {
8782 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8783 continue;
8784
8785 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8786 }
8787
8788 for (BuiltinCandidateTypeSet::iterator
8789 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8790 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8791 MemPtr != MemPtrEnd; ++MemPtr) {
8792 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8793 continue;
8794
8795 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8796 }
8797 }
8798 }
8799
8800 // C++ [over.built]p19:
8801 //
8802 // For every pair (T, VQ), where T is any type and VQ is either
8803 // volatile or empty, there exist candidate operator functions
8804 // of the form
8805 //
8806 // T*VQ& operator=(T*VQ&, T*);
8807 //
8808 // C++ [over.built]p21:
8809 //
8810 // For every pair (T, VQ), where T is a cv-qualified or
8811 // cv-unqualified object type and VQ is either volatile or
8812 // empty, there exist candidate operator functions of the form
8813 //
8814 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8815 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8816 void addAssignmentPointerOverloads(bool isEqualOp) {
8817 /// Set of (canonical) types that we've already handled.
8818 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8819
8820 for (BuiltinCandidateTypeSet::iterator
8821 Ptr = CandidateTypes[0].pointer_begin(),
8822 PtrEnd = CandidateTypes[0].pointer_end();
8823 Ptr != PtrEnd; ++Ptr) {
8824 // If this is operator=, keep track of the builtin candidates we added.
8825 if (isEqualOp)
8826 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8827 else if (!(*Ptr)->getPointeeType()->isObjectType())
8828 continue;
8829
8830 // non-volatile version
8831 QualType ParamTypes[2] = {
8832 S.Context.getLValueReferenceType(*Ptr),
8833 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8834 };
8835 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8836 /*IsAssignmentOperator=*/ isEqualOp);
8837
8838 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8839 VisibleTypeConversionsQuals.hasVolatile();
8840 if (NeedVolatile) {
8841 // volatile version
8842 ParamTypes[0] =
8843 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8844 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8845 /*IsAssignmentOperator=*/isEqualOp);
8846 }
8847
8848 if (!(*Ptr).isRestrictQualified() &&
8849 VisibleTypeConversionsQuals.hasRestrict()) {
8850 // restrict version
8851 ParamTypes[0]
8852 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8853 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8854 /*IsAssignmentOperator=*/isEqualOp);
8855
8856 if (NeedVolatile) {
8857 // volatile restrict version
8858 ParamTypes[0]
8859 = S.Context.getLValueReferenceType(
8860 S.Context.getCVRQualifiedType(*Ptr,
8861 (Qualifiers::Volatile |
8862 Qualifiers::Restrict)));
8863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8864 /*IsAssignmentOperator=*/isEqualOp);
8865 }
8866 }
8867 }
8868
8869 if (isEqualOp) {
8870 for (BuiltinCandidateTypeSet::iterator
8871 Ptr = CandidateTypes[1].pointer_begin(),
8872 PtrEnd = CandidateTypes[1].pointer_end();
8873 Ptr != PtrEnd; ++Ptr) {
8874 // Make sure we don't add the same candidate twice.
8875 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8876 continue;
8877
8878 QualType ParamTypes[2] = {
8879 S.Context.getLValueReferenceType(*Ptr),
8880 *Ptr,
8881 };
8882
8883 // non-volatile version
8884 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8885 /*IsAssignmentOperator=*/true);
8886
8887 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8888 VisibleTypeConversionsQuals.hasVolatile();
8889 if (NeedVolatile) {
8890 // volatile version
8891 ParamTypes[0] =
8892 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8893 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8894 /*IsAssignmentOperator=*/true);
8895 }
8896
8897 if (!(*Ptr).isRestrictQualified() &&
8898 VisibleTypeConversionsQuals.hasRestrict()) {
8899 // restrict version
8900 ParamTypes[0]
8901 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8902 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8903 /*IsAssignmentOperator=*/true);
8904
8905 if (NeedVolatile) {
8906 // volatile restrict version
8907 ParamTypes[0]
8908 = S.Context.getLValueReferenceType(
8909 S.Context.getCVRQualifiedType(*Ptr,
8910 (Qualifiers::Volatile |
8911 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 (BuiltinCandidateTypeSet::iterator
9047 Ptr = CandidateTypes[0].pointer_begin(),
9048 PtrEnd = CandidateTypes[0].pointer_end();
9049 Ptr != PtrEnd; ++Ptr) {
9050 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
9051 QualType PointeeType = (*Ptr)->getPointeeType();
9052 if (!PointeeType->isObjectType())
9053 continue;
9054
9055 // T& operator[](T*, ptrdiff_t)
9056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9057 }
9058
9059 for (BuiltinCandidateTypeSet::iterator
9060 Ptr = CandidateTypes[1].pointer_begin(),
9061 PtrEnd = CandidateTypes[1].pointer_end();
9062 Ptr != PtrEnd; ++Ptr) {
9063 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
9064 QualType PointeeType = (*Ptr)->getPointeeType();
9065 if (!PointeeType->isObjectType())
9066 continue;
9067
9068 // T& operator[](ptrdiff_t, T*)
9069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9070 }
9071 }
9072
9073 // C++ [over.built]p11:
9074 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9075 // C1 is the same type as C2 or is a derived class of C2, T is an object
9076 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9077 // there exist candidate operator functions of the form
9078 //
9079 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9080 //
9081 // where CV12 is the union of CV1 and CV2.
9082 void addArrowStarOverloads() {
9083 for (BuiltinCandidateTypeSet::iterator
9084 Ptr = CandidateTypes[0].pointer_begin(),
9085 PtrEnd = CandidateTypes[0].pointer_end();
9086 Ptr != PtrEnd; ++Ptr) {
9087 QualType C1Ty = (*Ptr);
9088 QualType C1;
9089 QualifierCollector Q1;
9090 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9091 if (!isa<RecordType>(C1))
9092 continue;
9093 // heuristic to reduce number of builtin candidates in the set.
9094 // Add volatile/restrict version only if there are conversions to a
9095 // volatile/restrict type.
9096 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9097 continue;
9098 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9099 continue;
9100 for (BuiltinCandidateTypeSet::iterator
9101 MemPtr = CandidateTypes[1].member_pointer_begin(),
9102 MemPtrEnd = CandidateTypes[1].member_pointer_end();
9103 MemPtr != MemPtrEnd; ++MemPtr) {
9104 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9105 QualType C2 = QualType(mptr->getClass(), 0);
9106 C2 = C2.getUnqualifiedType();
9107 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9108 break;
9109 QualType ParamTypes[2] = { *Ptr, *MemPtr };
9110 // build CV12 T&
9111 QualType T = mptr->getPointeeType();
9112 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9113 T.isVolatileQualified())
9114 continue;
9115 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9116 T.isRestrictQualified())
9117 continue;
9118 T = Q1.apply(S.Context, T);
9119 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9120 }
9121 }
9122 }
9123
9124 // Note that we don't consider the first argument, since it has been
9125 // contextually converted to bool long ago. The candidates below are
9126 // therefore added as binary.
9127 //
9128 // C++ [over.built]p25:
9129 // For every type T, where T is a pointer, pointer-to-member, or scoped
9130 // enumeration type, there exist candidate operator functions of the form
9131 //
9132 // T operator?(bool, T, T);
9133 //
9134 void addConditionalOperatorOverloads() {
9135 /// Set of (canonical) types that we've already handled.
9136 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9137
9138 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9139 for (BuiltinCandidateTypeSet::iterator
9140 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9141 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9142 Ptr != PtrEnd; ++Ptr) {
9143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9144 continue;
9145
9146 QualType ParamTypes[2] = { *Ptr, *Ptr };
9147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9148 }
9149
9150 for (BuiltinCandidateTypeSet::iterator
9151 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9152 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9153 MemPtr != MemPtrEnd; ++MemPtr) {
9154 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9155 continue;
9156
9157 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9158 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9159 }
9160
9161 if (S.getLangOpts().CPlusPlus11) {
9162 for (BuiltinCandidateTypeSet::iterator
9163 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9164 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9165 Enum != EnumEnd; ++Enum) {
9166 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9167 continue;
9168
9169 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9170 continue;
9171
9172 QualType ParamTypes[2] = { *Enum, *Enum };
9173 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9174 }
9175 }
9176 }
9177 }
9178};
9179
9180} // end anonymous namespace
9181
9182/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9183/// operator overloads to the candidate set (C++ [over.built]), based
9184/// on the operator @p Op and the arguments given. For example, if the
9185/// operator is a binary '+', this routine might add "int
9186/// operator+(int, int)" to cover integer addition.
9187void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9188 SourceLocation OpLoc,
9189 ArrayRef<Expr *> Args,
9190 OverloadCandidateSet &CandidateSet) {
9191 // Find all of the types that the arguments can convert to, but only
9192 // if the operator we're looking at has built-in operator candidates
9193 // that make use of these types. Also record whether we encounter non-record
9194 // candidate types or either arithmetic or enumeral candidate types.
9195 Qualifiers VisibleTypeConversionsQuals;
9196 VisibleTypeConversionsQuals.addConst();
9197 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9198 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9199
9200 bool HasNonRecordCandidateType = false;
9201 bool HasArithmeticOrEnumeralCandidateType = false;
9202 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9203 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9204 CandidateTypes.emplace_back(*this);
9205 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9206 OpLoc,
9207 true,
9208 (Op == OO_Exclaim ||
9209 Op == OO_AmpAmp ||
9210 Op == OO_PipePipe),
9211 VisibleTypeConversionsQuals);
9212 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9213 CandidateTypes[ArgIdx].hasNonRecordTypes();
9214 HasArithmeticOrEnumeralCandidateType =
9215 HasArithmeticOrEnumeralCandidateType ||
9216 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9217 }
9218
9219 // Exit early when no non-record types have been added to the candidate set
9220 // for any of the arguments to the operator.
9221 //
9222 // We can't exit early for !, ||, or &&, since there we have always have
9223 // 'bool' overloads.
9224 if (!HasNonRecordCandidateType &&
9225 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9226 return;
9227
9228 // Setup an object to manage the common state for building overloads.
9229 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9230 VisibleTypeConversionsQuals,
9231 HasArithmeticOrEnumeralCandidateType,
9232 CandidateTypes, CandidateSet);
9233
9234 // Dispatch over the operation to add in only those overloads which apply.
9235 switch (Op) {
9236 case OO_None:
9237 case NUM_OVERLOADED_OPERATORS:
9238 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9238)
;
9239
9240 case OO_New:
9241 case OO_Delete:
9242 case OO_Array_New:
9243 case OO_Array_Delete:
9244 case OO_Call:
9245 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9246)
9246 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9246)
;
9247
9248 case OO_Comma:
9249 case OO_Arrow:
9250 case OO_Coawait:
9251 // C++ [over.match.oper]p3:
9252 // -- For the operator ',', the unary operator '&', the
9253 // operator '->', or the operator 'co_await', the
9254 // built-in candidates set is empty.
9255 break;
9256
9257 case OO_Plus: // '+' is either unary or binary
9258 if (Args.size() == 1)
9259 OpBuilder.addUnaryPlusPointerOverloads();
9260 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9261
9262 case OO_Minus: // '-' is either unary or binary
9263 if (Args.size() == 1) {
9264 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9265 } else {
9266 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9267 OpBuilder.addGenericBinaryArithmeticOverloads();
9268 OpBuilder.addMatrixBinaryArithmeticOverloads();
9269 }
9270 break;
9271
9272 case OO_Star: // '*' is either unary or binary
9273 if (Args.size() == 1)
9274 OpBuilder.addUnaryStarPointerOverloads();
9275 else {
9276 OpBuilder.addGenericBinaryArithmeticOverloads();
9277 OpBuilder.addMatrixBinaryArithmeticOverloads();
9278 }
9279 break;
9280
9281 case OO_Slash:
9282 OpBuilder.addGenericBinaryArithmeticOverloads();
9283 break;
9284
9285 case OO_PlusPlus:
9286 case OO_MinusMinus:
9287 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9288 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9289 break;
9290
9291 case OO_EqualEqual:
9292 case OO_ExclaimEqual:
9293 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9294 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9295
9296 case OO_Less:
9297 case OO_Greater:
9298 case OO_LessEqual:
9299 case OO_GreaterEqual:
9300 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9301 OpBuilder.addGenericBinaryArithmeticOverloads();
9302 break;
9303
9304 case OO_Spaceship:
9305 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9306 OpBuilder.addThreeWayArithmeticOverloads();
9307 break;
9308
9309 case OO_Percent:
9310 case OO_Caret:
9311 case OO_Pipe:
9312 case OO_LessLess:
9313 case OO_GreaterGreater:
9314 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9315 break;
9316
9317 case OO_Amp: // '&' is either unary or binary
9318 if (Args.size() == 1)
9319 // C++ [over.match.oper]p3:
9320 // -- For the operator ',', the unary operator '&', or the
9321 // operator '->', the built-in candidates set is empty.
9322 break;
9323
9324 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9325 break;
9326
9327 case OO_Tilde:
9328 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9329 break;
9330
9331 case OO_Equal:
9332 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9333 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9334
9335 case OO_PlusEqual:
9336 case OO_MinusEqual:
9337 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9338 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9339
9340 case OO_StarEqual:
9341 case OO_SlashEqual:
9342 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9343 break;
9344
9345 case OO_PercentEqual:
9346 case OO_LessLessEqual:
9347 case OO_GreaterGreaterEqual:
9348 case OO_AmpEqual:
9349 case OO_CaretEqual:
9350 case OO_PipeEqual:
9351 OpBuilder.addAssignmentIntegralOverloads();
9352 break;
9353
9354 case OO_Exclaim:
9355 OpBuilder.addExclaimOverload();
9356 break;
9357
9358 case OO_AmpAmp:
9359 case OO_PipePipe:
9360 OpBuilder.addAmpAmpOrPipePipeOverload();
9361 break;
9362
9363 case OO_Subscript:
9364 OpBuilder.addSubscriptOverloads();
9365 break;
9366
9367 case OO_ArrowStar:
9368 OpBuilder.addArrowStarOverloads();
9369 break;
9370
9371 case OO_Conditional:
9372 OpBuilder.addConditionalOperatorOverloads();
9373 OpBuilder.addGenericBinaryArithmeticOverloads();
9374 break;
9375 }
9376}
9377
9378/// Add function candidates found via argument-dependent lookup
9379/// to the set of overloading candidates.
9380///
9381/// This routine performs argument-dependent name lookup based on the
9382/// given function name (which may also be an operator name) and adds
9383/// all of the overload candidates found by ADL to the overload
9384/// candidate set (C++ [basic.lookup.argdep]).
9385void
9386Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9387 SourceLocation Loc,
9388 ArrayRef<Expr *> Args,
9389 TemplateArgumentListInfo *ExplicitTemplateArgs,
9390 OverloadCandidateSet& CandidateSet,
9391 bool PartialOverloading) {
9392 ADLResult Fns;
9393
9394 // FIXME: This approach for uniquing ADL results (and removing
9395 // redundant candidates from the set) relies on pointer-equality,
9396 // which means we need to key off the canonical decl. However,
9397 // always going back to the canonical decl might not get us the
9398 // right set of default arguments. What default arguments are
9399 // we supposed to consider on ADL candidates, anyway?
9400
9401 // FIXME: Pass in the explicit template arguments?
9402 ArgumentDependentLookup(Name, Loc, Args, Fns);
9403
9404 // Erase all of the candidates we already knew about.
9405 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9406 CandEnd = CandidateSet.end();
9407 Cand != CandEnd; ++Cand)
9408 if (Cand->Function) {
9409 Fns.erase(Cand->Function);
9410 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9411 Fns.erase(FunTmpl);
9412 }
9413
9414 // For each of the ADL candidates we found, add it to the overload
9415 // set.
9416 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9417 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9418
9419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9420 if (ExplicitTemplateArgs)
9421 continue;
9422
9423 AddOverloadCandidate(
9424 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9425 PartialOverloading, /*AllowExplicit=*/true,
9426 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9427 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9428 AddOverloadCandidate(
9429 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9430 /*SuppressUserConversions=*/false, PartialOverloading,
9431 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9432 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9433 }
9434 } else {
9435 auto *FTD = cast<FunctionTemplateDecl>(*I);
9436 AddTemplateOverloadCandidate(
9437 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9438 /*SuppressUserConversions=*/false, PartialOverloading,
9439 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9440 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9441 Context, FTD->getTemplatedDecl())) {
9442 AddTemplateOverloadCandidate(
9443 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9444 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9445 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9446 OverloadCandidateParamOrder::Reversed);
9447 }
9448 }
9449 }
9450}
9451
9452namespace {
9453enum class Comparison { Equal, Better, Worse };
9454}
9455
9456/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9457/// overload resolution.
9458///
9459/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9460/// Cand1's first N enable_if attributes have precisely the same conditions as
9461/// Cand2's first N enable_if attributes (where N = the number of enable_if
9462/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9463///
9464/// Note that you can have a pair of candidates such that Cand1's enable_if
9465/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9466/// worse than Cand1's.
9467static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9468 const FunctionDecl *Cand2) {
9469 // Common case: One (or both) decls don't have enable_if attrs.
9470 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9471 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9472 if (!Cand1Attr || !Cand2Attr) {
9473 if (Cand1Attr == Cand2Attr)
9474 return Comparison::Equal;
9475 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9476 }
9477
9478 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9479 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9480
9481 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9482 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9483 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9484 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9485
9486 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9487 // has fewer enable_if attributes than Cand2, and vice versa.
9488 if (!Cand1A)
9489 return Comparison::Worse;
9490 if (!Cand2A)
9491 return Comparison::Better;
9492
9493 Cand1ID.clear();
9494 Cand2ID.clear();
9495
9496 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9497 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9498 if (Cand1ID != Cand2ID)
9499 return Comparison::Worse;
9500 }
9501
9502 return Comparison::Equal;
9503}
9504
9505static Comparison
9506isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9507 const OverloadCandidate &Cand2) {
9508 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9509 !Cand2.Function->isMultiVersion())
9510 return Comparison::Equal;
9511
9512 // If both are invalid, they are equal. If one of them is invalid, the other
9513 // is better.
9514 if (Cand1.Function->isInvalidDecl()) {
9515 if (Cand2.Function->isInvalidDecl())
9516 return Comparison::Equal;
9517 return Comparison::Worse;
9518 }
9519 if (Cand2.Function->isInvalidDecl())
9520 return Comparison::Better;
9521
9522 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9523 // cpu_dispatch, else arbitrarily based on the identifiers.
9524 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9525 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9526 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9527 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9528
9529 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9530 return Comparison::Equal;
9531
9532 if (Cand1CPUDisp && !Cand2CPUDisp)
9533 return Comparison::Better;
9534 if (Cand2CPUDisp && !Cand1CPUDisp)
9535 return Comparison::Worse;
9536
9537 if (Cand1CPUSpec && Cand2CPUSpec) {
9538 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9539 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9540 ? Comparison::Better
9541 : Comparison::Worse;
9542
9543 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9544 FirstDiff = std::mismatch(
9545 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9546 Cand2CPUSpec->cpus_begin(),
9547 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9548 return LHS->getName() == RHS->getName();
9549 });
9550
9551 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9553, __PRETTY_FUNCTION__))
9552 "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9553, __PRETTY_FUNCTION__))
9553 "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9553, __PRETTY_FUNCTION__))
;
9554 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9555 ? Comparison::Better
9556 : Comparison::Worse;
9557 }
9558 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"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9558)
;
9559}
9560
9561/// Compute the type of the implicit object parameter for the given function,
9562/// if any. Returns None if there is no implicit object parameter, and a null
9563/// QualType if there is a 'matches anything' implicit object parameter.
9564static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9565 const FunctionDecl *F) {
9566 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9567 return llvm::None;
9568
9569 auto *M = cast<CXXMethodDecl>(F);
9570 // Static member functions' object parameters match all types.
9571 if (M->isStatic())
9572 return QualType();
9573
9574 QualType T = M->getThisObjectType();
9575 if (M->getRefQualifier() == RQ_RValue)
9576 return Context.getRValueReferenceType(T);
9577 return Context.getLValueReferenceType(T);
9578}
9579
9580static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9581 const FunctionDecl *F2, unsigned NumParams) {
9582 if (declaresSameEntity(F1, F2))
9583 return true;
9584
9585 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9586 if (First) {
9587 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9588 return *T;
9589 }
9590 assert(I < F->getNumParams())((I < F->getNumParams()) ? static_cast<void> (0) :
__assert_fail ("I < F->getNumParams()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9590, __PRETTY_FUNCTION__))
;
9591 return F->getParamDecl(I++)->getType();
9592 };
9593
9594 unsigned I1 = 0, I2 = 0;
9595 for (unsigned I = 0; I != NumParams; ++I) {
9596 QualType T1 = NextParam(F1, I1, I == 0);
9597 QualType T2 = NextParam(F2, I2, I == 0);
9598 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9599 return false;
9600 }
9601 return true;
9602}
9603
9604/// isBetterOverloadCandidate - Determines whether the first overload
9605/// candidate is a better candidate than the second (C++ 13.3.3p1).
9606bool clang::isBetterOverloadCandidate(
9607 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9608 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9609 // Define viable functions to be better candidates than non-viable
9610 // functions.
9611 if (!Cand2.Viable)
9612 return Cand1.Viable;
9613 else if (!Cand1.Viable)
9614 return false;
9615
9616 // C++ [over.match.best]p1:
9617 //
9618 // -- if F is a static member function, ICS1(F) is defined such
9619 // that ICS1(F) is neither better nor worse than ICS1(G) for
9620 // any function G, and, symmetrically, ICS1(G) is neither
9621 // better nor worse than ICS1(F).
9622 unsigned StartArg = 0;
9623 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9624 StartArg = 1;
9625
9626 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9627 // We don't allow incompatible pointer conversions in C++.
9628 if (!S.getLangOpts().CPlusPlus)
9629 return ICS.isStandard() &&
9630 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9631
9632 // The only ill-formed conversion we allow in C++ is the string literal to
9633 // char* conversion, which is only considered ill-formed after C++11.
9634 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9635 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9636 };
9637
9638 // Define functions that don't require ill-formed conversions for a given
9639 // argument to be better candidates than functions that do.
9640 unsigned NumArgs = Cand1.Conversions.size();
9641 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9641, __PRETTY_FUNCTION__))
;
9642 bool HasBetterConversion = false;
9643 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9644 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9645 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9646 if (Cand1Bad != Cand2Bad) {
9647 if (Cand1Bad)
9648 return false;
9649 HasBetterConversion = true;
9650 }
9651 }
9652
9653 if (HasBetterConversion)
9654 return true;
9655
9656 // C++ [over.match.best]p1:
9657 // A viable function F1 is defined to be a better function than another
9658 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9659 // conversion sequence than ICSi(F2), and then...
9660 bool HasWorseConversion = false;
9661 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9662 switch (CompareImplicitConversionSequences(S, Loc,
9663 Cand1.Conversions[ArgIdx],
9664 Cand2.Conversions[ArgIdx])) {
9665 case ImplicitConversionSequence::Better:
9666 // Cand1 has a better conversion sequence.
9667 HasBetterConversion = true;
9668 break;
9669
9670 case ImplicitConversionSequence::Worse:
9671 if (Cand1.Function && Cand2.Function &&
9672 Cand1.isReversed() != Cand2.isReversed() &&
9673 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9674 NumArgs)) {
9675 // Work around large-scale breakage caused by considering reversed
9676 // forms of operator== in C++20:
9677 //
9678 // When comparing a function against a reversed function with the same
9679 // parameter types, if we have a better conversion for one argument and
9680 // a worse conversion for the other, the implicit conversion sequences
9681 // are treated as being equally good.
9682 //
9683 // This prevents a comparison function from being considered ambiguous
9684 // with a reversed form that is written in the same way.
9685 //
9686 // We diagnose this as an extension from CreateOverloadedBinOp.
9687 HasWorseConversion = true;
9688 break;
9689 }
9690
9691 // Cand1 can't be better than Cand2.
9692 return false;
9693
9694 case ImplicitConversionSequence::Indistinguishable:
9695 // Do nothing.
9696 break;
9697 }
9698 }
9699
9700 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9701 // ICSj(F2), or, if not that,
9702 if (HasBetterConversion && !HasWorseConversion)
9703 return true;
9704
9705 // -- the context is an initialization by user-defined conversion
9706 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9707 // from the return type of F1 to the destination type (i.e.,
9708 // the type of the entity being initialized) is a better
9709 // conversion sequence than the standard conversion sequence
9710 // from the return type of F2 to the destination type.
9711 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9712 Cand1.Function && Cand2.Function &&
9713 isa<CXXConversionDecl>(Cand1.Function) &&
9714 isa<CXXConversionDecl>(Cand2.Function)) {
9715 // First check whether we prefer one of the conversion functions over the
9716 // other. This only distinguishes the results in non-standard, extension
9717 // cases such as the conversion from a lambda closure type to a function
9718 // pointer or block.
9719 ImplicitConversionSequence::CompareKind Result =
9720 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9721 if (Result == ImplicitConversionSequence::Indistinguishable)
9722 Result = CompareStandardConversionSequences(S, Loc,
9723 Cand1.FinalConversion,
9724 Cand2.FinalConversion);
9725
9726 if (Result != ImplicitConversionSequence::Indistinguishable)
9727 return Result == ImplicitConversionSequence::Better;
9728
9729 // FIXME: Compare kind of reference binding if conversion functions
9730 // convert to a reference type used in direct reference binding, per
9731 // C++14 [over.match.best]p1 section 2 bullet 3.
9732 }
9733
9734 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9735 // as combined with the resolution to CWG issue 243.
9736 //
9737 // When the context is initialization by constructor ([over.match.ctor] or
9738 // either phase of [over.match.list]), a constructor is preferred over
9739 // a conversion function.
9740 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9741 Cand1.Function && Cand2.Function &&
9742 isa<CXXConstructorDecl>(Cand1.Function) !=
9743 isa<CXXConstructorDecl>(Cand2.Function))
9744 return isa<CXXConstructorDecl>(Cand1.Function);
9745
9746 // -- F1 is a non-template function and F2 is a function template
9747 // specialization, or, if not that,
9748 bool Cand1IsSpecialization = Cand1.Function &&
9749 Cand1.Function->getPrimaryTemplate();
9750 bool Cand2IsSpecialization = Cand2.Function &&
9751 Cand2.Function->getPrimaryTemplate();
9752 if (Cand1IsSpecialization != Cand2IsSpecialization)
9753 return Cand2IsSpecialization;
9754
9755 // -- F1 and F2 are function template specializations, and the function
9756 // template for F1 is more specialized than the template for F2
9757 // according to the partial ordering rules described in 14.5.5.2, or,
9758 // if not that,
9759 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9760 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9761 Cand1.Function->getPrimaryTemplate(),
9762 Cand2.Function->getPrimaryTemplate(), Loc,
9763 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9764 : TPOC_Call,
9765 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9766 Cand1.isReversed() ^ Cand2.isReversed()))
9767 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9768 }
9769
9770 // -— F1 and F2 are non-template functions with the same
9771 // parameter-type-lists, and F1 is more constrained than F2 [...],
9772 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9773 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9774 Cand2.Function->hasPrototype()) {
9775 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9776 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9777 if (PT1->getNumParams() == PT2->getNumParams() &&
9778 PT1->isVariadic() == PT2->isVariadic() &&
9779 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9780 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9781 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9782 if (RC1 && RC2) {
9783 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9784 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9785 {RC2}, AtLeastAsConstrained1) ||
9786 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9787 {RC1}, AtLeastAsConstrained2))
9788 return false;
9789 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9790 return AtLeastAsConstrained1;
9791 } else if (RC1 || RC2) {
9792 return RC1 != nullptr;
9793 }
9794 }
9795 }
9796
9797 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9798 // class B of D, and for all arguments the corresponding parameters of
9799 // F1 and F2 have the same type.
9800 // FIXME: Implement the "all parameters have the same type" check.
9801 bool Cand1IsInherited =
9802 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9803 bool Cand2IsInherited =
9804 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9805 if (Cand1IsInherited != Cand2IsInherited)
9806 return Cand2IsInherited;
9807 else if (Cand1IsInherited) {
9808 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 9808, __PRETTY_FUNCTION__))
;
9809 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9810 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9811 if (Cand1Class->isDerivedFrom(Cand2Class))
9812 return true;
9813 if (Cand2Class->isDerivedFrom(Cand1Class))
9814 return false;
9815 // Inherited from sibling base classes: still ambiguous.
9816 }
9817
9818 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9819 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9820 // with reversed order of parameters and F1 is not
9821 //
9822 // We rank reversed + different operator as worse than just reversed, but
9823 // that comparison can never happen, because we only consider reversing for
9824 // the maximally-rewritten operator (== or <=>).
9825 if (Cand1.RewriteKind != Cand2.RewriteKind)
9826 return Cand1.RewriteKind < Cand2.RewriteKind;
9827
9828 // Check C++17 tie-breakers for deduction guides.
9829 {
9830 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9831 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9832 if (Guide1 && Guide2) {
9833 // -- F1 is generated from a deduction-guide and F2 is not
9834 if (Guide1->isImplicit() != Guide2->isImplicit())
9835 return Guide2->isImplicit();
9836
9837 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9838 if (Guide1->isCopyDeductionCandidate())
9839 return true;
9840 }
9841 }
9842
9843 // Check for enable_if value-based overload resolution.
9844 if (Cand1.Function && Cand2.Function) {
9845 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9846 if (Cmp != Comparison::Equal)
9847 return Cmp == Comparison::Better;
9848 }
9849
9850 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9851 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9852 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9853 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9854 }
9855
9856 bool HasPS1 = Cand1.Function != nullptr &&
9857 functionHasPassObjectSizeParams(Cand1.Function);
9858 bool HasPS2 = Cand2.Function != nullptr &&
9859 functionHasPassObjectSizeParams(Cand2.Function);
9860 if (HasPS1 != HasPS2 && HasPS1)
9861 return true;
9862
9863 Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9864 return MV == Comparison::Better;
9865}
9866
9867/// Determine whether two declarations are "equivalent" for the purposes of
9868/// name lookup and overload resolution. This applies when the same internal/no
9869/// linkage entity is defined by two modules (probably by textually including
9870/// the same header). In such a case, we don't consider the declarations to
9871/// declare the same entity, but we also don't want lookups with both
9872/// declarations visible to be ambiguous in some cases (this happens when using
9873/// a modularized libstdc++).
9874bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9875 const NamedDecl *B) {
9876 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9877 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9878 if (!VA || !VB)
9879 return false;
9880
9881 // The declarations must be declaring the same name as an internal linkage
9882 // entity in different modules.
9883 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9884 VB->getDeclContext()->getRedeclContext()) ||
9885 getOwningModule(VA) == getOwningModule(VB) ||
9886 VA->isExternallyVisible() || VB->isExternallyVisible())
9887 return false;
9888
9889 // Check that the declarations appear to be equivalent.
9890 //
9891 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9892 // For constants and functions, we should check the initializer or body is
9893 // the same. For non-constant variables, we shouldn't allow it at all.
9894 if (Context.hasSameType(VA->getType(), VB->getType()))
9895 return true;
9896
9897 // Enum constants within unnamed enumerations will have different types, but
9898 // may still be similar enough to be interchangeable for our purposes.
9899 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9900 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9901 // Only handle anonymous enums. If the enumerations were named and
9902 // equivalent, they would have been merged to the same type.
9903 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9904 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9905 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9906 !Context.hasSameType(EnumA->getIntegerType(),
9907 EnumB->getIntegerType()))
9908 return false;
9909 // Allow this only if the value is the same for both enumerators.
9910 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9911 }
9912 }
9913
9914 // Nothing else is sufficiently similar.
9915 return false;
9916}
9917
9918void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9919 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9920 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9921
9922 Module *M = getOwningModule(D);
9923 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9924 << !M << (M ? M->getFullModuleName() : "");
9925
9926 for (auto *E : Equiv) {
9927 Module *M = getOwningModule(E);
9928 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9929 << !M << (M ? M->getFullModuleName() : "");
9930 }
9931}
9932
9933/// Computes the best viable function (C++ 13.3.3)
9934/// within an overload candidate set.
9935///
9936/// \param Loc The location of the function name (or operator symbol) for
9937/// which overload resolution occurs.
9938///
9939/// \param Best If overload resolution was successful or found a deleted
9940/// function, \p Best points to the candidate function found.
9941///
9942/// \returns The result of overload resolution.
9943OverloadingResult
9944OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9945 iterator &Best) {
9946 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9947 std::transform(begin(), end(), std::back_inserter(Candidates),
9948 [](OverloadCandidate &Cand) { return &Cand; });
9949
9950 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9951 // are accepted by both clang and NVCC. However, during a particular
9952 // compilation mode only one call variant is viable. We need to
9953 // exclude non-viable overload candidates from consideration based
9954 // only on their host/device attributes. Specifically, if one
9955 // candidate call is WrongSide and the other is SameSide, we ignore
9956 // the WrongSide candidate.
9957 if (S.getLangOpts().CUDA) {
9958 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9959 bool ContainsSameSideCandidate =
9960 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9961 // Check viable function only.
9962 return Cand->Viable && Cand->Function &&
9963 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9964 Sema::CFP_SameSide;
9965 });
9966 if (ContainsSameSideCandidate) {
9967 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9968 // Check viable function only to avoid unnecessary data copying/moving.
9969 return Cand->Viable && Cand->Function &&
9970 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9971 Sema::CFP_WrongSide;
9972 };
9973 llvm::erase_if(Candidates, IsWrongSideCandidate);
9974 }
9975 }
9976
9977 // Find the best viable function.
9978 Best = end();
9979 for (auto *Cand : Candidates) {
9980 Cand->Best = false;
9981 if (Cand->Viable)
9982 if (Best == end() ||
9983 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9984 Best = Cand;
9985 }
9986
9987 // If we didn't find any viable functions, abort.
9988 if (Best == end())
9989 return OR_No_Viable_Function;
9990
9991 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9992
9993 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9994 PendingBest.push_back(&*Best);
9995 Best->Best = true;
9996
9997 // Make sure that this function is better than every other viable
9998 // function. If not, we have an ambiguity.
9999 while (!PendingBest.empty()) {
10000 auto *Curr = PendingBest.pop_back_val();
10001 for (auto *Cand : Candidates) {
10002 if (Cand->Viable && !Cand->Best &&
10003 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10004 PendingBest.push_back(Cand);
10005 Cand->Best = true;
10006
10007 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10008 Curr->Function))
10009 EquivalentCands.push_back(Cand->Function);
10010 else
10011 Best = end();
10012 }
10013 }
10014 }
10015
10016 // If we found more than one best candidate, this is ambiguous.
10017 if (Best == end())
10018 return OR_Ambiguous;
10019
10020 // Best is the best viable function.
10021 if (Best->Function && Best->Function->isDeleted())
10022 return OR_Deleted;
10023
10024 if (!EquivalentCands.empty())
10025 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10026 EquivalentCands);
10027
10028 return OR_Success;
10029}
10030
10031namespace {
10032
10033enum OverloadCandidateKind {
10034 oc_function,
10035 oc_method,
10036 oc_reversed_binary_operator,
10037 oc_constructor,
10038 oc_implicit_default_constructor,
10039 oc_implicit_copy_constructor,
10040 oc_implicit_move_constructor,
10041 oc_implicit_copy_assignment,
10042 oc_implicit_move_assignment,
10043 oc_implicit_equality_comparison,
10044 oc_inherited_constructor
10045};
10046
10047enum OverloadCandidateSelect {
10048 ocs_non_template,
10049 ocs_template,
10050 ocs_described_template,
10051};
10052
10053static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10054ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10055 OverloadCandidateRewriteKind CRK,
10056 std::string &Description) {
10057
10058 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10059 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10060 isTemplate = true;
10061 Description = S.getTemplateArgumentBindingsText(
10062 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10063 }
10064
10065 OverloadCandidateSelect Select = [&]() {
10066 if (!Description.empty())
10067 return ocs_described_template;
10068 return isTemplate ? ocs_template : ocs_non_template;
10069 }();
10070
10071 OverloadCandidateKind Kind = [&]() {
10072 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10073 return oc_implicit_equality_comparison;
10074
10075 if (CRK & CRK_Reversed)
10076 return oc_reversed_binary_operator;
10077
10078 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10079 if (!Ctor->isImplicit()) {
10080 if (isa<ConstructorUsingShadowDecl>(Found))
10081 return oc_inherited_constructor;
10082 else
10083 return oc_constructor;
10084 }
10085
10086 if (Ctor->isDefaultConstructor())
10087 return oc_implicit_default_constructor;
10088
10089 if (Ctor->isMoveConstructor())
10090 return oc_implicit_move_constructor;
10091
10092 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10093, __PRETTY_FUNCTION__))
10093 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10093, __PRETTY_FUNCTION__))
;
10094 return oc_implicit_copy_constructor;
10095 }
10096
10097 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10098 // This actually gets spelled 'candidate function' for now, but
10099 // it doesn't hurt to split it out.
10100 if (!Meth->isImplicit())
10101 return oc_method;
10102
10103 if (Meth->isMoveAssignmentOperator())
10104 return oc_implicit_move_assignment;
10105
10106 if (Meth->isCopyAssignmentOperator())
10107 return oc_implicit_copy_assignment;
10108
10109 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10109, __PRETTY_FUNCTION__))
;
10110 return oc_method;
10111 }
10112
10113 return oc_function;
10114 }();
10115
10116 return std::make_pair(Kind, Select);
10117}
10118
10119void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10120 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10121 // set.
10122 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10123 S.Diag(FoundDecl->getLocation(),
10124 diag::note_ovl_candidate_inherited_constructor)
10125 << Shadow->getNominatedBaseClass();
10126}
10127
10128} // end anonymous namespace
10129
10130static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10131 const FunctionDecl *FD) {
10132 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10133 bool AlwaysTrue;
10134 if (EnableIf->getCond()->isValueDependent() ||
10135 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10136 return false;
10137 if (!AlwaysTrue)
10138 return false;
10139 }
10140 return true;
10141}
10142
10143/// Returns true if we can take the address of the function.
10144///
10145/// \param Complain - If true, we'll emit a diagnostic
10146/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10147/// we in overload resolution?
10148/// \param Loc - The location of the statement we're complaining about. Ignored
10149/// if we're not complaining, or if we're in overload resolution.
10150static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10151 bool Complain,
10152 bool InOverloadResolution,
10153 SourceLocation Loc) {
10154 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10155 if (Complain) {
10156 if (InOverloadResolution)
10157 S.Diag(FD->getBeginLoc(),
10158 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10159 else
10160 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10161 }
10162 return false;
10163 }
10164
10165 if (FD->getTrailingRequiresClause()) {
10166 ConstraintSatisfaction Satisfaction;
10167 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10168 return false;
10169 if (!Satisfaction.IsSatisfied) {
10170 if (Complain) {
10171 if (InOverloadResolution)
10172 S.Diag(FD->getBeginLoc(),
10173 diag::note_ovl_candidate_unsatisfied_constraints);
10174 else
10175 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10176 << FD;
10177 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10178 }
10179 return false;
10180 }
10181 }
10182
10183 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10184 return P->hasAttr<PassObjectSizeAttr>();
10185 });
10186 if (I == FD->param_end())
10187 return true;
10188
10189 if (Complain) {
10190 // Add one to ParamNo because it's user-facing
10191 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10192 if (InOverloadResolution)
10193 S.Diag(FD->getLocation(),
10194 diag::note_ovl_candidate_has_pass_object_size_params)
10195 << ParamNo;
10196 else
10197 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10198 << FD << ParamNo;
10199 }
10200 return false;
10201}
10202
10203static bool checkAddressOfCandidateIsAvailable(Sema &S,
10204 const FunctionDecl *FD) {
10205 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10206 /*InOverloadResolution=*/true,
10207 /*Loc=*/SourceLocation());
10208}
10209
10210bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10211 bool Complain,
10212 SourceLocation Loc) {
10213 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10214 /*InOverloadResolution=*/false,
10215 Loc);
10216}
10217
10218// Notes the location of an overload candidate.
10219void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10220 OverloadCandidateRewriteKind RewriteKind,
10221 QualType DestType, bool TakingAddress) {
10222 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10223 return;
10224 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10225 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10226 return;
10227 if (isa<CXXConversionDecl>(Fn) &&
10228 cast<CXXRecordDecl>(Fn->getParent())->isLambda()) {
10229 // Don't print candidates other than the one that matches the calling
10230 // convention of the call operator, since that is guaranteed to exist.
10231 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10232 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10233 CallingConv CallOpCC =
10234 CallOp->getType()->getAs<FunctionType>()->getCallConv();
10235 CXXConversionDecl *ConvD = cast<CXXConversionDecl>(Fn);
10236 QualType ConvRTy = ConvD->getType()->getAs<FunctionType>()->getReturnType();
10237 CallingConv ConvToCC =
10238 ConvRTy->getPointeeType()->getAs<FunctionType>()->getCallConv();
10239
10240 if (ConvToCC != CallOpCC)
10241 return;
10242 }
10243
10244 std::string FnDesc;
10245 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10246 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10247 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10248 << (unsigned)KSPair.first << (unsigned)KSPair.second
10249 << Fn << FnDesc;
10250
10251 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10252 Diag(Fn->getLocation(), PD);
10253 MaybeEmitInheritedConstructorNote(*this, Found);
10254}
10255
10256static void
10257MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10258 // Perhaps the ambiguity was caused by two atomic constraints that are
10259 // 'identical' but not equivalent:
10260 //
10261 // void foo() requires (sizeof(T) > 4) { } // #1
10262 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10263 //
10264 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10265 // #2 to subsume #1, but these constraint are not considered equivalent
10266 // according to the subsumption rules because they are not the same
10267 // source-level construct. This behavior is quite confusing and we should try
10268 // to help the user figure out what happened.
10269
10270 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10271 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10272 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10273 if (!I->Function)
10274 continue;
10275 SmallVector<const Expr *, 3> AC;
10276 if (auto *Template = I->Function->getPrimaryTemplate())
10277 Template->getAssociatedConstraints(AC);
10278 else
10279 I->Function->getAssociatedConstraints(AC);
10280 if (AC.empty())
10281 continue;
10282 if (FirstCand == nullptr) {
10283 FirstCand = I->Function;
10284 FirstAC = AC;
10285 } else if (SecondCand == nullptr) {
10286 SecondCand = I->Function;
10287 SecondAC = AC;
10288 } else {
10289 // We have more than one pair of constrained functions - this check is
10290 // expensive and we'd rather not try to diagnose it.
10291 return;
10292 }
10293 }
10294 if (!SecondCand)
10295 return;
10296 // The diagnostic can only happen if there are associated constraints on
10297 // both sides (there needs to be some identical atomic constraint).
10298 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10299 SecondCand, SecondAC))
10300 // Just show the user one diagnostic, they'll probably figure it out
10301 // from here.
10302 return;
10303}
10304
10305// Notes the location of all overload candidates designated through
10306// OverloadedExpr
10307void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10308 bool TakingAddress) {
10309 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10309, __PRETTY_FUNCTION__))
;
10310
10311 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10312 OverloadExpr *OvlExpr = Ovl.Expression;
10313
10314 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10315 IEnd = OvlExpr->decls_end();
10316 I != IEnd; ++I) {
10317 if (FunctionTemplateDecl *FunTmpl =
10318 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10319 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10320 TakingAddress);
10321 } else if (FunctionDecl *Fun
10322 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10323 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10324 }
10325 }
10326}
10327
10328/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10329/// "lead" diagnostic; it will be given two arguments, the source and
10330/// target types of the conversion.
10331void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10332 Sema &S,
10333 SourceLocation CaretLoc,
10334 const PartialDiagnostic &PDiag) const {
10335 S.Diag(CaretLoc, PDiag)
10336 << Ambiguous.getFromType() << Ambiguous.getToType();
10337 // FIXME: The note limiting machinery is borrowed from
10338 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10339 // refactoring here.
10340 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10341 unsigned CandsShown = 0;
10342 AmbiguousConversionSequence::const_iterator I, E;
10343 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10344 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10345 break;
10346 ++CandsShown;
10347 S.NoteOverloadCandidate(I->first, I->second);
10348 }
10349 if (I != E)
10350 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10351}
10352
10353static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10354 unsigned I, bool TakingCandidateAddress) {
10355 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10356 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10356, __PRETTY_FUNCTION__))
;
1
'?' condition is true
10357 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10357, __PRETTY_FUNCTION__))
;
2
Assuming field 'Function' is non-null
3
'?' condition is true
10358 FunctionDecl *Fn = Cand->Function;
10359
10360 // There's a conversion slot for the object argument if this is a
10361 // non-constructor method. Note that 'I' corresponds the
10362 // conversion-slot index.
10363 bool isObjectArgument = false;
10364 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
4
Assuming 'Fn' is not a 'CXXMethodDecl'
10365 if (I == 0)
10366 isObjectArgument = true;
10367 else
10368 I--;
10369 }
10370
10371 std::string FnDesc;
10372 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10373 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10374 FnDesc);
10375
10376 Expr *FromExpr = Conv.Bad.FromExpr;
5
'FromExpr' initialized here
10377 QualType FromTy = Conv.Bad.getFromType();
10378 QualType ToTy = Conv.Bad.getToType();
10379
10380 if (FromTy == S.Context.OverloadTy) {
6
Calling 'operator=='
11
Returning from 'operator=='
12
Taking false branch
10381 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10381, __PRETTY_FUNCTION__))
;
10382 Expr *E = FromExpr->IgnoreParens();
10383 if (isa<UnaryOperator>(E))
10384 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10385 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10386
10387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10388 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10390 << Name << I + 1;
10391 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10392 return;
10393 }
10394
10395 // Do some hand-waving analysis to see if the non-viability is due
10396 // to a qualifier mismatch.
10397 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10398 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10399 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
13
Taking true branch
10400 CToTy = RT->getPointeeType();
10401 else {
10402 // TODO: detect and diagnose the full richness of const mismatches.
10403 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10404 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10405 CFromTy = FromPT->getPointeeType();
10406 CToTy = ToPT->getPointeeType();
10407 }
10408 }
10409
10410 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
14
Assuming the condition is false
15
Taking false branch
10411 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10412 Qualifiers FromQs = CFromTy.getQualifiers();
10413 Qualifiers ToQs = CToTy.getQualifiers();
10414
10415 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10416 if (isObjectArgument)
10417 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10418 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10419 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10420 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10421 else
10422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10423 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10424 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10425 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10426 << ToTy->isReferenceType() << I + 1;
10427 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10428 return;
10429 }
10430
10431 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10434 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10435 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10436 << (unsigned)isObjectArgument << I + 1;
10437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10438 return;
10439 }
10440
10441 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10442 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10443 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10444 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10445 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10446 << (unsigned)isObjectArgument << I + 1;
10447 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10448 return;
10449 }
10450
10451 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10453 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10454 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10455 << FromQs.hasUnaligned() << I + 1;
10456 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10457 return;
10458 }
10459
10460 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10461 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10461, __PRETTY_FUNCTION__))
;
10462
10463 if (isObjectArgument) {
10464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10465 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10467 << (CVR - 1);
10468 } else {
10469 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10470 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10471 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10472 << (CVR - 1) << I + 1;
10473 }
10474 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10475 return;
10476 }
10477
10478 // Special diagnostic for failure to convert an initializer list, since
10479 // telling the user that it has type void is not useful.
10480 if (FromExpr && isa<InitListExpr>(FromExpr)) {
16
Assuming 'FromExpr' is null
10481 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10482 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10483 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10484 << ToTy << (unsigned)isObjectArgument << I + 1;
10485 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10486 return;
10487 }
10488
10489 // Diagnose references or pointers to incomplete types differently,
10490 // since it's far from impossible that the incompleteness triggered
10491 // the failure.
10492 QualType TempFromTy = FromTy.getNonReferenceType();
10493 if (const PointerType *PTy
17.1
'PTy' is null
17.1
'PTy' is null
17.1
'PTy' is null
= TempFromTy->getAs<PointerType>())
17
Assuming the object is not a 'PointerType'
18
Taking false branch
10494 TempFromTy = PTy->getPointeeType();
10495 if (TempFromTy->isIncompleteType()) {
19
Assuming the condition is false
20
Taking false branch
10496 // Emit the generic diagnostic and, optionally, add the hints to it.
10497 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10498 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10499 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10500 << ToTy << (unsigned)isObjectArgument << I + 1
10501 << (unsigned)(Cand->Fix.Kind);
10502
10503 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10504 return;
10505 }
10506
10507 // Diagnose base -> derived pointer conversions.
10508 unsigned BaseToDerivedConversion = 0;
10509 if (const PointerType *FromPtrTy
21.1
'FromPtrTy' is null
21.1
'FromPtrTy' is null
21.1
'FromPtrTy' is null
= FromTy->getAs<PointerType>()) {
21
Assuming the object is not a 'PointerType'
22
Taking false branch
10510 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10511 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10512 FromPtrTy->getPointeeType()) &&
10513 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10514 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10515 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10516 FromPtrTy->getPointeeType()))
10517 BaseToDerivedConversion = 1;
10518 }
10519 } else if (const ObjCObjectPointerType *FromPtrTy
23.1
'FromPtrTy' is null
23.1
'FromPtrTy' is null
23.1
'FromPtrTy' is null
24
Taking false branch
10520 = FromTy->getAs<ObjCObjectPointerType>()) {
23
Assuming the object is not a 'ObjCObjectPointerType'
10521 if (const ObjCObjectPointerType *ToPtrTy 10522 = ToTy->getAs<ObjCObjectPointerType>()) 10523 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10524 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10525 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10526 FromPtrTy->getPointeeType()) && 10527 FromIface->isSuperClassOf(ToIface)) 10528 BaseToDerivedConversion = 2; 10529 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
25
Assuming the object is a 'ReferenceType'
26
Assuming 'ToRefTy' is non-null
27
Taking true branch
10530 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
28
Taking false branch
10531 !FromTy->isIncompleteType() && 10532 !ToRefTy->getPointeeType()->isIncompleteType() && 10533 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10534 BaseToDerivedConversion = 3; 10535 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
29
Calling 'Type::isLValueReferenceType'
32
Returning from 'Type::isLValueReferenceType'
33
Called C++ object pointer is null
10536 ToTy.getNonReferenceType().getCanonicalType() == 10537 FromTy.getNonReferenceType().getCanonicalType()) { 10538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10539 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10540 << (unsigned)isObjectArgument << I + 1 10541 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10542 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10543 return; 10544 } 10545 } 10546 10547 if (BaseToDerivedConversion) { 10548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10549 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10551 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10552 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10553 return; 10554 } 10555 10556 if (isa<ObjCObjectPointerType>(CFromTy) && 10557 isa<PointerType>(CToTy)) { 10558 Qualifiers FromQs = CFromTy.getQualifiers(); 10559 Qualifiers ToQs = CToTy.getQualifiers(); 10560 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10561 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10562 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10563 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10564 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10565 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10566 return; 10567 } 10568 } 10569 10570 if (TakingCandidateAddress && 10571 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10572 return; 10573 10574 // Emit the generic diagnostic and, optionally, add the hints to it. 10575 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10576 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10577 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10578 << ToTy << (unsigned)isObjectArgument << I + 1 10579 << (unsigned)(Cand->Fix.Kind); 10580 10581 // If we can fix the conversion, suggest the FixIts. 10582 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10583 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10584 FDiag << *HI; 10585 S.Diag(Fn->getLocation(), FDiag); 10586 10587 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10588} 10589 10590/// Additional arity mismatch diagnosis specific to a function overload 10591/// candidates. This is not covered by the more general DiagnoseArityMismatch() 10592/// over a candidate in any candidate set. 10593static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10594 unsigned NumArgs) { 10595 FunctionDecl *Fn = Cand->Function; 10596 unsigned MinParams = Fn->getMinRequiredArguments(); 10597 10598 // With invalid overloaded operators, it's possible that we think we 10599 // have an arity mismatch when in fact it looks like we have the 10600 // right number of arguments, because only overloaded operators have 10601 // the weird behavior of overloading member and non-member functions. 10602 // Just don't report anything. 10603 if (Fn->isInvalidDecl() && 10604 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10605 return true; 10606 10607 if (NumArgs < MinParams) { 10608 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10610, __PRETTY_FUNCTION__))
10609 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10610, __PRETTY_FUNCTION__))
10610 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10610, __PRETTY_FUNCTION__))
; 10611 } else { 10612 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10614, __PRETTY_FUNCTION__))
10613 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10614, __PRETTY_FUNCTION__))
10614 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10614, __PRETTY_FUNCTION__))
; 10615 } 10616 10617 return false; 10618} 10619 10620/// General arity mismatch diagnosis over a candidate in a candidate set. 10621static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10622 unsigned NumFormalArgs) { 10623 assert(isa<FunctionDecl>(D) &&((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") ? static_cast<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\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10626, __PRETTY_FUNCTION__))
10624 "The templated declaration should at least be a function"((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") ? static_cast<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\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10626, __PRETTY_FUNCTION__))
10625 " when diagnosing bad template argument deduction due to too many"((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") ? static_cast<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\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10626, __PRETTY_FUNCTION__))
10626 " or too few arguments")((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") ? static_cast<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\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10626, __PRETTY_FUNCTION__))
; 10627 10628 FunctionDecl *Fn = cast<FunctionDecl>(D); 10629 10630 // TODO: treat calls to a missing default constructor as a special case 10631 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10632 unsigned MinParams = Fn->getMinRequiredArguments(); 10633 10634 // at least / at most / exactly 10635 unsigned mode, modeCount; 10636 if (NumFormalArgs < MinParams) { 10637 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10638 FnTy->isTemplateVariadic()) 10639 mode = 0; // "at least" 10640 else 10641 mode = 2; // "exactly" 10642 modeCount = MinParams; 10643 } else { 10644 if (MinParams != FnTy->getNumParams()) 10645 mode = 1; // "at most" 10646 else 10647 mode = 2; // "exactly" 10648 modeCount = FnTy->getNumParams(); 10649 } 10650 10651 std::string Description; 10652 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10653 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10654 10655 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10657 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10658 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10659 else 10660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10661 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10662 << Description << mode << modeCount << NumFormalArgs; 10663 10664 MaybeEmitInheritedConstructorNote(S, Found); 10665} 10666 10667/// Arity mismatch diagnosis specific to a function overload candidate. 10668static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10669 unsigned NumFormalArgs) { 10670 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10671 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10672} 10673 10674static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10675 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10676 return TD; 10677 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10678)
10678 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10678)
; 10679} 10680 10681/// Diagnose a failed template-argument deduction. 10682static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10683 DeductionFailureInfo &DeductionFailure, 10684 unsigned NumArgs, 10685 bool TakingCandidateAddress) { 10686 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10687 NamedDecl *ParamD; 10688 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10689 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10690 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10691 switch (DeductionFailure.Result) { 10692 case Sema::TDK_Success: 10693 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10693)
; 10694 10695 case Sema::TDK_Incomplete: { 10696 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10696, __PRETTY_FUNCTION__))
; 10697 S.Diag(Templated->getLocation(), 10698 diag::note_ovl_candidate_incomplete_deduction) 10699 << ParamD->getDeclName(); 10700 MaybeEmitInheritedConstructorNote(S, Found); 10701 return; 10702 } 10703 10704 case Sema::TDK_IncompletePack: { 10705 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10705, __PRETTY_FUNCTION__))
; 10706 S.Diag(Templated->getLocation(), 10707 diag::note_ovl_candidate_incomplete_deduction_pack) 10708 << ParamD->getDeclName() 10709 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10710 << *DeductionFailure.getFirstArg(); 10711 MaybeEmitInheritedConstructorNote(S, Found); 10712 return; 10713 } 10714 10715 case Sema::TDK_Underqualified: { 10716 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10716, __PRETTY_FUNCTION__))
; 10717 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10718 10719 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10720 10721 // Param will have been canonicalized, but it should just be a 10722 // qualified version of ParamD, so move the qualifiers to that. 10723 QualifierCollector Qs; 10724 Qs.strip(Param); 10725 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10726 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10726, __PRETTY_FUNCTION__))
; 10727 10728 // Arg has also been canonicalized, but there's nothing we can do 10729 // about that. It also doesn't matter as much, because it won't 10730 // have any template parameters in it (because deduction isn't 10731 // done on dependent types). 10732 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10733 10734 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10735 << ParamD->getDeclName() << Arg << NonCanonParam; 10736 MaybeEmitInheritedConstructorNote(S, Found); 10737 return; 10738 } 10739 10740 case Sema::TDK_Inconsistent: { 10741 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10741, __PRETTY_FUNCTION__))
; 10742 int which = 0; 10743 if (isa<TemplateTypeParmDecl>(ParamD)) 10744 which = 0; 10745 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10746 // Deduction might have failed because we deduced arguments of two 10747 // different types for a non-type template parameter. 10748 // FIXME: Use a different TDK value for this. 10749 QualType T1 = 10750 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10751 QualType T2 = 10752 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10753 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10754 S.Diag(Templated->getLocation(), 10755 diag::note_ovl_candidate_inconsistent_deduction_types) 10756 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10757 << *DeductionFailure.getSecondArg() << T2; 10758 MaybeEmitInheritedConstructorNote(S, Found); 10759 return; 10760 } 10761 10762 which = 1; 10763 } else { 10764 which = 2; 10765 } 10766 10767 // Tweak the diagnostic if the problem is that we deduced packs of 10768 // different arities. We'll print the actual packs anyway in case that 10769 // includes additional useful information. 10770 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10771 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10772 DeductionFailure.getFirstArg()->pack_size() != 10773 DeductionFailure.getSecondArg()->pack_size()) { 10774 which = 3; 10775 } 10776 10777 S.Diag(Templated->getLocation(), 10778 diag::note_ovl_candidate_inconsistent_deduction) 10779 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10780 << *DeductionFailure.getSecondArg(); 10781 MaybeEmitInheritedConstructorNote(S, Found); 10782 return; 10783 } 10784 10785 case Sema::TDK_InvalidExplicitArguments: 10786 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 10786, __PRETTY_FUNCTION__))
; 10787 if (ParamD->getDeclName()) 10788 S.Diag(Templated->getLocation(), 10789 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10790 << ParamD->getDeclName(); 10791 else { 10792 int index = 0; 10793 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10794 index = TTP->getIndex(); 10795 else if (NonTypeTemplateParmDecl *NTTP 10796 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10797 index = NTTP->getIndex(); 10798 else 10799 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10800 S.Diag(Templated->getLocation(), 10801 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10802 << (index + 1); 10803 } 10804 MaybeEmitInheritedConstructorNote(S, Found); 10805 return; 10806 10807 case Sema::TDK_ConstraintsNotSatisfied: { 10808 // Format the template argument list into the argument string. 10809 SmallString<128> TemplateArgString; 10810 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10811 TemplateArgString = " "; 10812 TemplateArgString += S.getTemplateArgumentBindingsText( 10813 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10814 if (TemplateArgString.size() == 1) 10815 TemplateArgString.clear(); 10816 S.Diag(Templated->getLocation(), 10817 diag::note_ovl_candidate_unsatisfied_constraints) 10818 << TemplateArgString; 10819 10820 S.DiagnoseUnsatisfiedConstraint( 10821 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10822 return; 10823 } 10824 case Sema::TDK_TooManyArguments: 10825 case Sema::TDK_TooFewArguments: 10826 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10827 return; 10828 10829 case Sema::TDK_InstantiationDepth: 10830 S.Diag(Templated->getLocation(), 10831 diag::note_ovl_candidate_instantiation_depth); 10832 MaybeEmitInheritedConstructorNote(S, Found); 10833 return; 10834 10835 case Sema::TDK_SubstitutionFailure: { 10836 // Format the template argument list into the argument string. 10837 SmallString<128> TemplateArgString; 10838 if (TemplateArgumentList *Args = 10839 DeductionFailure.getTemplateArgumentList()) { 10840 TemplateArgString = " "; 10841 TemplateArgString += S.getTemplateArgumentBindingsText( 10842 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10843 if (TemplateArgString.size() == 1) 10844 TemplateArgString.clear(); 10845 } 10846 10847 // If this candidate was disabled by enable_if, say so. 10848 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10849 if (PDiag && PDiag->second.getDiagID() == 10850 diag::err_typename_nested_not_found_enable_if) { 10851 // FIXME: Use the source range of the condition, and the fully-qualified 10852 // name of the enable_if template. These are both present in PDiag. 10853 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10854 << "'enable_if'" << TemplateArgString; 10855 return; 10856 } 10857 10858 // We found a specific requirement that disabled the enable_if. 10859 if (PDiag && PDiag->second.getDiagID() == 10860 diag::err_typename_nested_not_found_requirement) { 10861 S.Diag(Templated->getLocation(), 10862 diag::note_ovl_candidate_disabled_by_requirement) 10863 << PDiag->second.getStringArg(0) << TemplateArgString; 10864 return; 10865 } 10866 10867 // Format the SFINAE diagnostic into the argument string. 10868 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10869 // formatted message in another diagnostic. 10870 SmallString<128> SFINAEArgString; 10871 SourceRange R; 10872 if (PDiag) { 10873 SFINAEArgString = ": "; 10874 R = SourceRange(PDiag->first, PDiag->first); 10875 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10876 } 10877 10878 S.Diag(Templated->getLocation(), 10879 diag::note_ovl_candidate_substitution_failure) 10880 << TemplateArgString << SFINAEArgString << R; 10881 MaybeEmitInheritedConstructorNote(S, Found); 10882 return; 10883 } 10884 10885 case Sema::TDK_DeducedMismatch: 10886 case Sema::TDK_DeducedMismatchNested: { 10887 // Format the template argument list into the argument string. 10888 SmallString<128> TemplateArgString; 10889 if (TemplateArgumentList *Args = 10890 DeductionFailure.getTemplateArgumentList()) { 10891 TemplateArgString = " "; 10892 TemplateArgString += S.getTemplateArgumentBindingsText( 10893 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10894 if (TemplateArgString.size() == 1) 10895 TemplateArgString.clear(); 10896 } 10897 10898 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10899 << (*DeductionFailure.getCallArgIndex() + 1) 10900 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10901 << TemplateArgString 10902 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10903 break; 10904 } 10905 10906 case Sema::TDK_NonDeducedMismatch: { 10907 // FIXME: Provide a source location to indicate what we couldn't match. 10908 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10909 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10910 if (FirstTA.getKind() == TemplateArgument::Template && 10911 SecondTA.getKind() == TemplateArgument::Template) { 10912 TemplateName FirstTN = FirstTA.getAsTemplate(); 10913 TemplateName SecondTN = SecondTA.getAsTemplate(); 10914 if (FirstTN.getKind() == TemplateName::Template && 10915 SecondTN.getKind() == TemplateName::Template) { 10916 if (FirstTN.getAsTemplateDecl()->getName() == 10917 SecondTN.getAsTemplateDecl()->getName()) { 10918 // FIXME: This fixes a bad diagnostic where both templates are named 10919 // the same. This particular case is a bit difficult since: 10920 // 1) It is passed as a string to the diagnostic printer. 10921 // 2) The diagnostic printer only attempts to find a better 10922 // name for types, not decls. 10923 // Ideally, this should folded into the diagnostic printer. 10924 S.Diag(Templated->getLocation(), 10925 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10926 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10927 return; 10928 } 10929 } 10930 } 10931 10932 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10933 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10934 return; 10935 10936 // FIXME: For generic lambda parameters, check if the function is a lambda 10937 // call operator, and if so, emit a prettier and more informative 10938 // diagnostic that mentions 'auto' and lambda in addition to 10939 // (or instead of?) the canonical template type parameters. 10940 S.Diag(Templated->getLocation(), 10941 diag::note_ovl_candidate_non_deduced_mismatch) 10942 << FirstTA << SecondTA; 10943 return; 10944 } 10945 // TODO: diagnose these individually, then kill off 10946 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10947 case Sema::TDK_MiscellaneousDeductionFailure: 10948 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10949 MaybeEmitInheritedConstructorNote(S, Found); 10950 return; 10951 case Sema::TDK_CUDATargetMismatch: 10952 S.Diag(Templated->getLocation(), 10953 diag::note_cuda_ovl_candidate_target_mismatch); 10954 return; 10955 } 10956} 10957 10958/// Diagnose a failed template-argument deduction, for function calls. 10959static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10960 unsigned NumArgs, 10961 bool TakingCandidateAddress) { 10962 unsigned TDK = Cand->DeductionFailure.Result; 10963 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10964 if (CheckArityMismatch(S, Cand, NumArgs)) 10965 return; 10966 } 10967 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10968 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10969} 10970 10971/// CUDA: diagnose an invalid call across targets. 10972static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10973 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10974 FunctionDecl *Callee = Cand->Function; 10975 10976 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10977 CalleeTarget = S.IdentifyCUDATarget(Callee); 10978 10979 std::string FnDesc; 10980 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10981 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10982 Cand->getRewriteKind(), FnDesc); 10983 10984 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10985 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10986 << FnDesc /* Ignored */ 10987 << CalleeTarget << CallerTarget; 10988 10989 // This could be an implicit constructor for which we could not infer the 10990 // target due to a collsion. Diagnose that case. 10991 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10992 if (Meth != nullptr && Meth->isImplicit()) { 10993 CXXRecordDecl *ParentClass = Meth->getParent(); 10994 Sema::CXXSpecialMember CSM; 10995 10996 switch (FnKindPair.first) { 10997 default: 10998 return; 10999 case oc_implicit_default_constructor: 11000 CSM = Sema::CXXDefaultConstructor; 11001 break; 11002 case oc_implicit_copy_constructor: 11003 CSM = Sema::CXXCopyConstructor; 11004 break; 11005 case oc_implicit_move_constructor: 11006 CSM = Sema::CXXMoveConstructor; 11007 break; 11008 case oc_implicit_copy_assignment: 11009 CSM = Sema::CXXCopyAssignment; 11010 break; 11011 case oc_implicit_move_assignment: 11012 CSM = Sema::CXXMoveAssignment; 11013 break; 11014 }; 11015 11016 bool ConstRHS = false; 11017 if (Meth->getNumParams()) { 11018 if (const ReferenceType *RT = 11019 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11020 ConstRHS = RT->getPointeeType().isConstQualified(); 11021 } 11022 } 11023 11024 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11025 /* ConstRHS */ ConstRHS, 11026 /* Diagnose */ true); 11027 } 11028} 11029 11030static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11031 FunctionDecl *Callee = Cand->Function; 11032 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11033 11034 S.Diag(Callee->getLocation(), 11035 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11036 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11037} 11038 11039static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11040 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11041 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11041, __PRETTY_FUNCTION__))
; 11042 11043 unsigned Kind; 11044 switch (Cand->Function->getDeclKind()) { 11045 case Decl::Kind::CXXConstructor: 11046 Kind = 0; 11047 break; 11048 case Decl::Kind::CXXConversion: 11049 Kind = 1; 11050 break; 11051 case Decl::Kind::CXXDeductionGuide: 11052 Kind = Cand->Function->isImplicit() ? 0 : 2; 11053 break; 11054 default: 11055 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11055)
; 11056 } 11057 11058 // Note the location of the first (in-class) declaration; a redeclaration 11059 // (particularly an out-of-class definition) will typically lack the 11060 // 'explicit' specifier. 11061 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11062 FunctionDecl *First = Cand->Function->getFirstDecl(); 11063 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11064 First = Pattern->getFirstDecl(); 11065 11066 S.Diag(First->getLocation(), 11067 diag::note_ovl_candidate_explicit) 11068 << Kind << (ES.getExpr() ? 1 : 0) 11069 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11070} 11071 11072static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 11073 FunctionDecl *Callee = Cand->Function; 11074 11075 S.Diag(Callee->getLocation(), 11076 diag::note_ovl_candidate_disabled_by_extension) 11077 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 11078} 11079 11080/// Generates a 'note' diagnostic for an overload candidate. We've 11081/// already generated a primary error at the call site. 11082/// 11083/// It really does need to be a single diagnostic with its caret 11084/// pointed at the candidate declaration. Yes, this creates some 11085/// major challenges of technical writing. Yes, this makes pointing 11086/// out problems with specific arguments quite awkward. It's still 11087/// better than generating twenty screens of text for every failed 11088/// overload. 11089/// 11090/// It would be great to be able to express per-candidate problems 11091/// more richly for those diagnostic clients that cared, but we'd 11092/// still have to be just as careful with the default diagnostics. 11093/// \param CtorDestAS Addr space of object being constructed (for ctor 11094/// candidates only). 11095static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11096 unsigned NumArgs, 11097 bool TakingCandidateAddress, 11098 LangAS CtorDestAS = LangAS::Default) { 11099 FunctionDecl *Fn = Cand->Function; 11100 11101 // Note deleted candidates, but only if they're viable. 11102 if (Cand->Viable) { 11103 if (Fn->isDeleted()) { 11104 std::string FnDesc; 11105 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11106 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11107 Cand->getRewriteKind(), FnDesc); 11108 11109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11110 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11111 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11112 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11113 return; 11114 } 11115 11116 // We don't really have anything else to say about viable candidates. 11117 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11118 return; 11119 } 11120 11121 switch (Cand->FailureKind) { 11122 case ovl_fail_too_many_arguments: 11123 case ovl_fail_too_few_arguments: 11124 return DiagnoseArityMismatch(S, Cand, NumArgs); 11125 11126 case ovl_fail_bad_deduction: 11127 return DiagnoseBadDeduction(S, Cand, NumArgs, 11128 TakingCandidateAddress); 11129 11130 case ovl_fail_illegal_constructor: { 11131 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11132 << (Fn->getPrimaryTemplate() ? 1 : 0); 11133 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11134 return; 11135 } 11136 11137 case ovl_fail_object_addrspace_mismatch: { 11138 Qualifiers QualsForPrinting; 11139 QualsForPrinting.setAddressSpace(CtorDestAS); 11140 S.Diag(Fn->getLocation(), 11141 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11142 << QualsForPrinting; 11143 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11144 return; 11145 } 11146 11147 case ovl_fail_trivial_conversion: 11148 case ovl_fail_bad_final_conversion: 11149 case ovl_fail_final_conversion_not_exact: 11150 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11151 11152 case ovl_fail_bad_conversion: { 11153 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11154 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11155 if (Cand->Conversions[I].isBad()) 11156 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11157 11158 // FIXME: this currently happens when we're called from SemaInit 11159 // when user-conversion overload fails. Figure out how to handle 11160 // those conditions and diagnose them well. 11161 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11162 } 11163 11164 case ovl_fail_bad_target: 11165 return DiagnoseBadTarget(S, Cand); 11166 11167 case ovl_fail_enable_if: 11168 return DiagnoseFailedEnableIfAttr(S, Cand); 11169 11170 case ovl_fail_explicit: 11171 return DiagnoseFailedExplicitSpec(S, Cand); 11172 11173 case ovl_fail_ext_disabled: 11174 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11175 11176 case ovl_fail_inhctor_slice: 11177 // It's generally not interesting to note copy/move constructors here. 11178 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11179 return; 11180 S.Diag(Fn->getLocation(), 11181 diag::note_ovl_candidate_inherited_constructor_slice) 11182 << (Fn->getPrimaryTemplate() ? 1 : 0) 11183 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11184 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11185 return; 11186 11187 case ovl_fail_addr_not_available: { 11188 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11189 (void)Available; 11190 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11190, __PRETTY_FUNCTION__))
; 11191 break; 11192 } 11193 case ovl_non_default_multiversion_function: 11194 // Do nothing, these should simply be ignored. 11195 break; 11196 11197 case ovl_fail_constraints_not_satisfied: { 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(), 11204 diag::note_ovl_candidate_constraints_not_satisfied) 11205 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11206 << FnDesc /* Ignored */; 11207 ConstraintSatisfaction Satisfaction; 11208 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11209 break; 11210 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11211 } 11212 } 11213} 11214 11215static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11216 // Desugar the type of the surrogate down to a function type, 11217 // retaining as many typedefs as possible while still showing 11218 // the function type (and, therefore, its parameter types). 11219 QualType FnType = Cand->Surrogate->getConversionType(); 11220 bool isLValueReference = false; 11221 bool isRValueReference = false; 11222 bool isPointer = false; 11223 if (const LValueReferenceType *FnTypeRef = 11224 FnType->getAs<LValueReferenceType>()) { 11225 FnType = FnTypeRef->getPointeeType(); 11226 isLValueReference = true; 11227 } else if (const RValueReferenceType *FnTypeRef = 11228 FnType->getAs<RValueReferenceType>()) { 11229 FnType = FnTypeRef->getPointeeType(); 11230 isRValueReference = true; 11231 } 11232 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11233 FnType = FnTypePtr->getPointeeType(); 11234 isPointer = true; 11235 } 11236 // Desugar down to a function type. 11237 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11238 // Reconstruct the pointer/reference as appropriate. 11239 if (isPointer) FnType = S.Context.getPointerType(FnType); 11240 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11241 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11242 11243 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11244 << FnType; 11245} 11246 11247static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11248 SourceLocation OpLoc, 11249 OverloadCandidate *Cand) { 11250 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11250, __PRETTY_FUNCTION__))
; 11251 std::string TypeStr("operator"); 11252 TypeStr += Opc; 11253 TypeStr += "("; 11254 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11255 if (Cand->Conversions.size() == 1) { 11256 TypeStr += ")"; 11257 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11258 } else { 11259 TypeStr += ", "; 11260 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11261 TypeStr += ")"; 11262 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11263 } 11264} 11265 11266static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11267 OverloadCandidate *Cand) { 11268 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11269 if (ICS.isBad()) break; // all meaningless after first invalid 11270 if (!ICS.isAmbiguous()) continue; 11271 11272 ICS.DiagnoseAmbiguousConversion( 11273 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11274 } 11275} 11276 11277static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11278 if (Cand->Function) 11279 return Cand->Function->getLocation(); 11280 if (Cand->IsSurrogate) 11281 return Cand->Surrogate->getLocation(); 11282 return SourceLocation(); 11283} 11284 11285static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11286 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11287 case Sema::TDK_Success: 11288 case Sema::TDK_NonDependentConversionFailure: 11289 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11289)
; 11290 11291 case Sema::TDK_Invalid: 11292 case Sema::TDK_Incomplete: 11293 case Sema::TDK_IncompletePack: 11294 return 1; 11295 11296 case Sema::TDK_Underqualified: 11297 case Sema::TDK_Inconsistent: 11298 return 2; 11299 11300 case Sema::TDK_SubstitutionFailure: 11301 case Sema::TDK_DeducedMismatch: 11302 case Sema::TDK_ConstraintsNotSatisfied: 11303 case Sema::TDK_DeducedMismatchNested: 11304 case Sema::TDK_NonDeducedMismatch: 11305 case Sema::TDK_MiscellaneousDeductionFailure: 11306 case Sema::TDK_CUDATargetMismatch: 11307 return 3; 11308 11309 case Sema::TDK_InstantiationDepth: 11310 return 4; 11311 11312 case Sema::TDK_InvalidExplicitArguments: 11313 return 5; 11314 11315 case Sema::TDK_TooManyArguments: 11316 case Sema::TDK_TooFewArguments: 11317 return 6; 11318 } 11319 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11319)
; 11320} 11321 11322namespace { 11323struct CompareOverloadCandidatesForDisplay { 11324 Sema &S; 11325 SourceLocation Loc; 11326 size_t NumArgs; 11327 OverloadCandidateSet::CandidateSetKind CSK; 11328 11329 CompareOverloadCandidatesForDisplay( 11330 Sema &S, SourceLocation Loc, size_t NArgs, 11331 OverloadCandidateSet::CandidateSetKind CSK) 11332 : S(S), NumArgs(NArgs), CSK(CSK) {} 11333 11334 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11335 // If there are too many or too few arguments, that's the high-order bit we 11336 // want to sort by, even if the immediate failure kind was something else. 11337 if (C->FailureKind == ovl_fail_too_many_arguments || 11338 C->FailureKind == ovl_fail_too_few_arguments) 11339 return static_cast<OverloadFailureKind>(C->FailureKind); 11340 11341 if (C->Function) { 11342 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11343 return ovl_fail_too_many_arguments; 11344 if (NumArgs < C->Function->getMinRequiredArguments()) 11345 return ovl_fail_too_few_arguments; 11346 } 11347 11348 return static_cast<OverloadFailureKind>(C->FailureKind); 11349 } 11350 11351 bool operator()(const OverloadCandidate *L, 11352 const OverloadCandidate *R) { 11353 // Fast-path this check. 11354 if (L == R) return false; 11355 11356 // Order first by viability. 11357 if (L->Viable) { 11358 if (!R->Viable) return true; 11359 11360 // TODO: introduce a tri-valued comparison for overload 11361 // candidates. Would be more worthwhile if we had a sort 11362 // that could exploit it. 11363 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11364 return true; 11365 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11366 return false; 11367 } else if (R->Viable) 11368 return false; 11369 11370 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11370, __PRETTY_FUNCTION__))
; 11371 11372 // Criteria by which we can sort non-viable candidates: 11373 if (!L->Viable) { 11374 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11375 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11376 11377 // 1. Arity mismatches come after other candidates. 11378 if (LFailureKind == ovl_fail_too_many_arguments || 11379 LFailureKind == ovl_fail_too_few_arguments) { 11380 if (RFailureKind == ovl_fail_too_many_arguments || 11381 RFailureKind == ovl_fail_too_few_arguments) { 11382 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11383 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11384 if (LDist == RDist) { 11385 if (LFailureKind == RFailureKind) 11386 // Sort non-surrogates before surrogates. 11387 return !L->IsSurrogate && R->IsSurrogate; 11388 // Sort candidates requiring fewer parameters than there were 11389 // arguments given after candidates requiring more parameters 11390 // than there were arguments given. 11391 return LFailureKind == ovl_fail_too_many_arguments; 11392 } 11393 return LDist < RDist; 11394 } 11395 return false; 11396 } 11397 if (RFailureKind == ovl_fail_too_many_arguments || 11398 RFailureKind == ovl_fail_too_few_arguments) 11399 return true; 11400 11401 // 2. Bad conversions come first and are ordered by the number 11402 // of bad conversions and quality of good conversions. 11403 if (LFailureKind == ovl_fail_bad_conversion) { 11404 if (RFailureKind != ovl_fail_bad_conversion) 11405 return true; 11406 11407 // The conversion that can be fixed with a smaller number of changes, 11408 // comes first. 11409 unsigned numLFixes = L->Fix.NumConversionsFixed; 11410 unsigned numRFixes = R->Fix.NumConversionsFixed; 11411 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; 11412 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; 11413 if (numLFixes != numRFixes) { 11414 return numLFixes < numRFixes; 11415 } 11416 11417 // If there's any ordering between the defined conversions... 11418 // FIXME: this might not be transitive. 11419 assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast
<void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11419, __PRETTY_FUNCTION__))
; 11420 11421 int leftBetter = 0; 11422 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11423 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11424 switch (CompareImplicitConversionSequences(S, Loc, 11425 L->Conversions[I], 11426 R->Conversions[I])) { 11427 case ImplicitConversionSequence::Better: 11428 leftBetter++; 11429 break; 11430 11431 case ImplicitConversionSequence::Worse: 11432 leftBetter--; 11433 break; 11434 11435 case ImplicitConversionSequence::Indistinguishable: 11436 break; 11437 } 11438 } 11439 if (leftBetter > 0) return true; 11440 if (leftBetter < 0) return false; 11441 11442 } else if (RFailureKind == ovl_fail_bad_conversion) 11443 return false; 11444 11445 if (LFailureKind == ovl_fail_bad_deduction) { 11446 if (RFailureKind != ovl_fail_bad_deduction) 11447 return true; 11448 11449 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11450 return RankDeductionFailure(L->DeductionFailure) 11451 < RankDeductionFailure(R->DeductionFailure); 11452 } else if (RFailureKind == ovl_fail_bad_deduction) 11453 return false; 11454 11455 // TODO: others? 11456 } 11457 11458 // Sort everything else by location. 11459 SourceLocation LLoc = GetLocationForCandidate(L); 11460 SourceLocation RLoc = GetLocationForCandidate(R); 11461 11462 // Put candidates without locations (e.g. builtins) at the end. 11463 if (LLoc.isInvalid()) return false; 11464 if (RLoc.isInvalid()) return true; 11465 11466 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11467 } 11468}; 11469} 11470 11471/// CompleteNonViableCandidate - Normally, overload resolution only 11472/// computes up to the first bad conversion. Produces the FixIt set if 11473/// possible. 11474static void 11475CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11476 ArrayRef<Expr *> Args, 11477 OverloadCandidateSet::CandidateSetKind CSK) { 11478 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11478, __PRETTY_FUNCTION__))
; 11479 11480 // Don't do anything on failures other than bad conversion. 11481 if (Cand->FailureKind != ovl_fail_bad_conversion) 11482 return; 11483 11484 // We only want the FixIts if all the arguments can be corrected. 11485 bool Unfixable = false; 11486 // Use a implicit copy initialization to check conversion fixes. 11487 Cand->Fix.setConversionChecker(TryCopyInitialization); 11488 11489 // Attempt to fix the bad conversion. 11490 unsigned ConvCount = Cand->Conversions.size(); 11491 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11492 ++ConvIdx) { 11493 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11493, __PRETTY_FUNCTION__))
; 11494 if (Cand->Conversions[ConvIdx].isInitialized() && 11495 Cand->Conversions[ConvIdx].isBad()) { 11496 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11497 break; 11498 } 11499 } 11500 11501 // FIXME: this should probably be preserved from the overload 11502 // operation somehow. 11503 bool SuppressUserConversions = false; 11504 11505 unsigned ConvIdx = 0; 11506 unsigned ArgIdx = 0; 11507 ArrayRef<QualType> ParamTypes; 11508 bool Reversed = Cand->isReversed(); 11509 11510 if (Cand->IsSurrogate) { 11511 QualType ConvType 11512 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11513 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11514 ConvType = ConvPtrType->getPointeeType(); 11515 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11516 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11517 ConvIdx = 1; 11518 } else if (Cand->Function) { 11519 ParamTypes = 11520 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11521 if (isa<CXXMethodDecl>(Cand->Function) && 11522 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11523 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11524 ConvIdx = 1; 11525 if (CSK == OverloadCandidateSet::CSK_Operator && 11526 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11527 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11528 ArgIdx = 1; 11529 } 11530 } else { 11531 // Builtin operator. 11532 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11532, __PRETTY_FUNCTION__))
; 11533 ParamTypes = Cand->BuiltinParamTypes; 11534 } 11535 11536 // Fill in the rest of the conversions. 11537 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11538 ConvIdx != ConvCount; 11539 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11540 assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11540, __PRETTY_FUNCTION__))
; 11541 if (Cand->Conversions[ConvIdx].isInitialized()) { 11542 // We've already checked this conversion. 11543 } else if (ParamIdx < ParamTypes.size()) { 11544 if (ParamTypes[ParamIdx]->isDependentType()) 11545 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11546 Args[ArgIdx]->getType()); 11547 else { 11548 Cand->Conversions[ConvIdx] = 11549 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11550 SuppressUserConversions, 11551 /*InOverloadResolution=*/true, 11552 /*AllowObjCWritebackConversion=*/ 11553 S.getLangOpts().ObjCAutoRefCount); 11554 // Store the FixIt in the candidate if it exists. 11555 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11556 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11557 } 11558 } else 11559 Cand->Conversions[ConvIdx].setEllipsis(); 11560 } 11561} 11562 11563SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11564 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11565 SourceLocation OpLoc, 11566 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11567 // Sort the candidates by viability and position. Sorting directly would 11568 // be prohibitive, so we make a set of pointers and sort those. 11569 SmallVector<OverloadCandidate*, 32> Cands; 11570 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11571 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11572 if (!Filter(*Cand)) 11573 continue; 11574 switch (OCD) { 11575 case OCD_AllCandidates: 11576 if (!Cand->Viable) { 11577 if (!Cand->Function && !Cand->IsSurrogate) { 11578 // This a non-viable builtin candidate. We do not, in general, 11579 // want to list every possible builtin candidate. 11580 continue; 11581 } 11582 CompleteNonViableCandidate(S, Cand, Args, Kind); 11583 } 11584 break; 11585 11586 case OCD_ViableCandidates: 11587 if (!Cand->Viable) 11588 continue; 11589 break; 11590 11591 case OCD_AmbiguousCandidates: 11592 if (!Cand->Best) 11593 continue; 11594 break; 11595 } 11596 11597 Cands.push_back(Cand); 11598 } 11599 11600 llvm::stable_sort( 11601 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11602 11603 return Cands; 11604} 11605 11606/// When overload resolution fails, prints diagnostic messages containing the 11607/// candidates in the candidate set. 11608void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11609 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11610 StringRef Opc, SourceLocation OpLoc, 11611 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11612 11613 bool DeferHint = false; 11614 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11615 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates. 11616 auto WrongSidedCands = 11617 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11618 return Cand.Viable == false && 11619 Cand.FailureKind == ovl_fail_bad_target; 11620 }); 11621 DeferHint = WrongSidedCands.size(); 11622 } 11623 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11624 11625 S.Diag(PD.first, PD.second, DeferHint); 11626 11627 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11628 11629 if (OCD == OCD_AmbiguousCandidates) 11630 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11631} 11632 11633void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11634 ArrayRef<OverloadCandidate *> Cands, 11635 StringRef Opc, SourceLocation OpLoc) { 11636 bool ReportedAmbiguousConversions = false; 11637 11638 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11639 unsigned CandsShown = 0; 11640 auto I = Cands.begin(), E = Cands.end(); 11641 for (; I != E; ++I) { 11642 OverloadCandidate *Cand = *I; 11643 11644 // Set an arbitrary limit on the number of candidate functions we'll spam 11645 // the user with. FIXME: This limit should depend on details of the 11646 // candidate list. 11647 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11648 break; 11649 } 11650 ++CandsShown; 11651 11652 if (Cand->Function) 11653 NoteFunctionCandidate(S, Cand, Args.size(), 11654 /*TakingCandidateAddress=*/false, DestAS); 11655 else if (Cand->IsSurrogate) 11656 NoteSurrogateCandidate(S, Cand); 11657 else { 11658 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11659, __PRETTY_FUNCTION__))
11659 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11659, __PRETTY_FUNCTION__))
; 11660 // Generally we only see ambiguities including viable builtin 11661 // operators if overload resolution got screwed up by an 11662 // ambiguous user-defined conversion. 11663 // 11664 // FIXME: It's quite possible for different conversions to see 11665 // different ambiguities, though. 11666 if (!ReportedAmbiguousConversions) { 11667 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11668 ReportedAmbiguousConversions = true; 11669 } 11670 11671 // If this is a viable builtin, print it. 11672 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11673 } 11674 } 11675 11676 if (I != E) 11677 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11678} 11679 11680static SourceLocation 11681GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11682 return Cand->Specialization ? Cand->Specialization->getLocation() 11683 : SourceLocation(); 11684} 11685 11686namespace { 11687struct CompareTemplateSpecCandidatesForDisplay { 11688 Sema &S; 11689 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11690 11691 bool operator()(const TemplateSpecCandidate *L, 11692 const TemplateSpecCandidate *R) { 11693 // Fast-path this check. 11694 if (L == R) 11695 return false; 11696 11697 // Assuming that both candidates are not matches... 11698 11699 // Sort by the ranking of deduction failures. 11700 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11701 return RankDeductionFailure(L->DeductionFailure) < 11702 RankDeductionFailure(R->DeductionFailure); 11703 11704 // Sort everything else by location. 11705 SourceLocation LLoc = GetLocationForCandidate(L); 11706 SourceLocation RLoc = GetLocationForCandidate(R); 11707 11708 // Put candidates without locations (e.g. builtins) at the end. 11709 if (LLoc.isInvalid()) 11710 return false; 11711 if (RLoc.isInvalid()) 11712 return true; 11713 11714 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11715 } 11716}; 11717} 11718 11719/// Diagnose a template argument deduction failure. 11720/// We are treating these failures as overload failures due to bad 11721/// deductions. 11722void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11723 bool ForTakingAddress) { 11724 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11725 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11726} 11727 11728void TemplateSpecCandidateSet::destroyCandidates() { 11729 for (iterator i = begin(), e = end(); i != e; ++i) { 11730 i->DeductionFailure.Destroy(); 11731 } 11732} 11733 11734void TemplateSpecCandidateSet::clear() { 11735 destroyCandidates(); 11736 Candidates.clear(); 11737} 11738 11739/// NoteCandidates - When no template specialization match is found, prints 11740/// diagnostic messages containing the non-matching specializations that form 11741/// the candidate set. 11742/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11743/// OCD == OCD_AllCandidates and Cand->Viable == false. 11744void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11745 // Sort the candidates by position (assuming no candidate is a match). 11746 // Sorting directly would be prohibitive, so we make a set of pointers 11747 // and sort those. 11748 SmallVector<TemplateSpecCandidate *, 32> Cands; 11749 Cands.reserve(size()); 11750 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11751 if (Cand->Specialization) 11752 Cands.push_back(Cand); 11753 // Otherwise, this is a non-matching builtin candidate. We do not, 11754 // in general, want to list every possible builtin candidate. 11755 } 11756 11757 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11758 11759 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11760 // for generalization purposes (?). 11761 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11762 11763 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11764 unsigned CandsShown = 0; 11765 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11766 TemplateSpecCandidate *Cand = *I; 11767 11768 // Set an arbitrary limit on the number of candidates we'll spam 11769 // the user with. FIXME: This limit should depend on details of the 11770 // candidate list. 11771 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11772 break; 11773 ++CandsShown; 11774 11775 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11776, __PRETTY_FUNCTION__))
11776 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 11776, __PRETTY_FUNCTION__))
; 11777 Cand->NoteDeductionFailure(S, ForTakingAddress); 11778 } 11779 11780 if (I != E) 11781 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11782} 11783 11784// [PossiblyAFunctionType] --> [Return] 11785// NonFunctionType --> NonFunctionType 11786// R (A) --> R(A) 11787// R (*)(A) --> R (A) 11788// R (&)(A) --> R (A) 11789// R (S::*)(A) --> R (A) 11790QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11791 QualType Ret = PossiblyAFunctionType; 11792 if (const PointerType *ToTypePtr = 11793 PossiblyAFunctionType->getAs<PointerType>()) 11794 Ret = ToTypePtr->getPointeeType(); 11795 else if (const ReferenceType *ToTypeRef = 11796 PossiblyAFunctionType->getAs<ReferenceType>()) 11797 Ret = ToTypeRef->getPointeeType(); 11798 else if (const MemberPointerType *MemTypePtr = 11799 PossiblyAFunctionType->getAs<MemberPointerType>()) 11800 Ret = MemTypePtr->getPointeeType(); 11801 Ret = 11802 Context.getCanonicalType(Ret).getUnqualifiedType(); 11803 return Ret; 11804} 11805 11806static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11807 bool Complain = true) { 11808 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11809 S.DeduceReturnType(FD, Loc, Complain)) 11810 return true; 11811 11812 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11813 if (S.getLangOpts().CPlusPlus17 && 11814 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11815 !S.ResolveExceptionSpec(Loc, FPT)) 11816 return true; 11817 11818 return false; 11819} 11820 11821namespace { 11822// A helper class to help with address of function resolution 11823// - allows us to avoid passing around all those ugly parameters 11824class AddressOfFunctionResolver { 11825 Sema& S; 11826 Expr* SourceExpr; 11827 const QualType& TargetType; 11828 QualType TargetFunctionType; // Extracted function type from target type 11829 11830 bool Complain; 11831 //DeclAccessPair& ResultFunctionAccessPair; 11832 ASTContext& Context; 11833 11834 bool TargetTypeIsNonStaticMemberFunction; 11835 bool FoundNonTemplateFunction; 11836 bool StaticMemberFunctionFromBoundPointer; 11837 bool HasComplained; 11838 11839 OverloadExpr::FindResult OvlExprInfo; 11840 OverloadExpr *OvlExpr; 11841 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11842 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11843 TemplateSpecCandidateSet FailedCandidates; 11844 11845public: 11846 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11847 const QualType &TargetType, bool Complain) 11848 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11849 Complain(Complain), Context(S.getASTContext()), 11850 TargetTypeIsNonStaticMemberFunction( 11851 !!TargetType->getAs<MemberPointerType>()), 11852 FoundNonTemplateFunction(false), 11853 StaticMemberFunctionFromBoundPointer(false), 11854 HasComplained(false), 11855 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11856 OvlExpr(OvlExprInfo.Expression), 11857 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11858 ExtractUnqualifiedFunctionTypeFromTargetType(); 11859 11860 if (TargetFunctionType->isFunctionType()) { 11861 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11862 if (!UME->isImplicitAccess() && 11863 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11864 StaticMemberFunctionFromBoundPointer = true; 11865 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11866 DeclAccessPair dap; 11867 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11868 OvlExpr, false, &dap)) { 11869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11870 if (!Method->isStatic()) { 11871 // If the target type is a non-function type and the function found 11872 // is a non-static member function, pretend as if that was the 11873 // target, it's the only possible type to end up with. 11874 TargetTypeIsNonStaticMemberFunction = true; 11875 11876 // And skip adding the function if its not in the proper form. 11877 // We'll diagnose this due to an empty set of functions. 11878 if (!OvlExprInfo.HasFormOfMemberPointer) 11879 return; 11880 } 11881 11882 Matches.push_back(std::make_pair(dap, Fn)); 11883 } 11884 return; 11885 } 11886 11887 if (OvlExpr->hasExplicitTemplateArgs()) 11888 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11889 11890 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11891 // C++ [over.over]p4: 11892 // If more than one function is selected, [...] 11893 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11894 if (FoundNonTemplateFunction) 11895 EliminateAllTemplateMatches(); 11896 else 11897 EliminateAllExceptMostSpecializedTemplate(); 11898 } 11899 } 11900 11901 if (S.getLangOpts().CUDA && Matches.size() > 1) 11902 EliminateSuboptimalCudaMatches(); 11903 } 11904 11905 bool hasComplained() const { return HasComplained; } 11906 11907private: 11908 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11909 QualType Discard; 11910 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11911 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11912 } 11913 11914 /// \return true if A is considered a better overload candidate for the 11915 /// desired type than B. 11916 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11917 // If A doesn't have exactly the correct type, we don't want to classify it 11918 // as "better" than anything else. This way, the user is required to 11919 // disambiguate for us if there are multiple candidates and no exact match. 11920 return candidateHasExactlyCorrectType(A) && 11921 (!candidateHasExactlyCorrectType(B) || 11922 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11923 } 11924 11925 /// \return true if we were able to eliminate all but one overload candidate, 11926 /// false otherwise. 11927 bool eliminiateSuboptimalOverloadCandidates() { 11928 // Same algorithm as overload resolution -- one pass to pick the "best", 11929 // another pass to be sure that nothing is better than the best. 11930 auto Best = Matches.begin(); 11931 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11932 if (isBetterCandidate(I->second, Best->second)) 11933 Best = I; 11934 11935 const FunctionDecl *BestFn = Best->second; 11936 auto IsBestOrInferiorToBest = [this, BestFn]( 11937 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11938 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11939 }; 11940 11941 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11942 // option, so we can potentially give the user a better error 11943 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11944 return false; 11945 Matches[0] = *Best; 11946 Matches.resize(1); 11947 return true; 11948 } 11949 11950 bool isTargetTypeAFunction() const { 11951 return TargetFunctionType->isFunctionType(); 11952 } 11953 11954 // [ToType] [Return] 11955 11956 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11957 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11958 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11959 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11960 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11961 } 11962 11963 // return true if any matching specializations were found 11964 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11965 const DeclAccessPair& CurAccessFunPair) { 11966 if (CXXMethodDecl *Method 11967 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11968 // Skip non-static function templates when converting to pointer, and 11969 // static when converting to member pointer. 11970 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11971 return false; 11972 } 11973 else if (TargetTypeIsNonStaticMemberFunction) 11974 return false; 11975 11976 // C++ [over.over]p2: 11977 // If the name is a function template, template argument deduction is 11978 // done (14.8.2.2), and if the argument deduction succeeds, the 11979 // resulting template argument list is used to generate a single 11980 // function template specialization, which is added to the set of 11981 // overloaded functions considered. 11982 FunctionDecl *Specialization = nullptr; 11983 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11984 if (Sema::TemplateDeductionResult Result 11985 = S.DeduceTemplateArguments(FunctionTemplate, 11986 &OvlExplicitTemplateArgs, 11987 TargetFunctionType, Specialization, 11988 Info, /*IsAddressOfFunction*/true)) { 11989 // Make a note of the failed deduction for diagnostics. 11990 FailedCandidates.addCandidate() 11991 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11992 MakeDeductionFailureInfo(Context, Result, Info)); 11993 return false; 11994 } 11995 11996 // Template argument deduction ensures that we have an exact match or 11997 // compatible pointer-to-function arguments that would be adjusted by ICS. 11998 // This function template specicalization works. 11999 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12001, __PRETTY_FUNCTION__))
12000 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12001, __PRETTY_FUNCTION__))
12001 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12001, __PRETTY_FUNCTION__))
; 12002 12003 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12004 return false; 12005 12006 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12007 return true; 12008 } 12009 12010 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12011 const DeclAccessPair& CurAccessFunPair) { 12012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12013 // Skip non-static functions when converting to pointer, and static 12014 // when converting to member pointer. 12015 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12016 return false; 12017 } 12018 else if (TargetTypeIsNonStaticMemberFunction) 12019 return false; 12020 12021 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12022 if (S.getLangOpts().CUDA) 12023 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12024 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12025 return false; 12026 if (FunDecl->isMultiVersion()) { 12027 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12028 if (TA && !TA->isDefaultVersion()) 12029 return false; 12030 } 12031 12032 // If any candidate has a placeholder return type, trigger its deduction 12033 // now. 12034 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12035 Complain)) { 12036 HasComplained |= Complain; 12037 return false; 12038 } 12039 12040 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12041 return false; 12042 12043 // If we're in C, we need to support types that aren't exactly identical. 12044 if (!S.getLangOpts().CPlusPlus || 12045 candidateHasExactlyCorrectType(FunDecl)) { 12046 Matches.push_back(std::make_pair( 12047 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12048 FoundNonTemplateFunction = true; 12049 return true; 12050 } 12051 } 12052 12053 return false; 12054 } 12055 12056 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12057 bool Ret = false; 12058 12059 // If the overload expression doesn't have the form of a pointer to 12060 // member, don't try to convert it to a pointer-to-member type. 12061 if (IsInvalidFormOfPointerToMemberFunction()) 12062 return false; 12063 12064 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12065 E = OvlExpr->decls_end(); 12066 I != E; ++I) { 12067 // Look through any using declarations to find the underlying function. 12068 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12069 12070 // C++ [over.over]p3: 12071 // Non-member functions and static member functions match 12072 // targets of type "pointer-to-function" or "reference-to-function." 12073 // Nonstatic member functions match targets of 12074 // type "pointer-to-member-function." 12075 // Note that according to DR 247, the containing class does not matter. 12076 if (FunctionTemplateDecl *FunctionTemplate 12077 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12078 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12079 Ret = true; 12080 } 12081 // If we have explicit template arguments supplied, skip non-templates. 12082 else if (!OvlExpr->hasExplicitTemplateArgs() && 12083 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12084 Ret = true; 12085 } 12086 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12086, __PRETTY_FUNCTION__))
; 12087 return Ret; 12088 } 12089 12090 void EliminateAllExceptMostSpecializedTemplate() { 12091 // [...] and any given function template specialization F1 is 12092 // eliminated if the set contains a second function template 12093 // specialization whose function template is more specialized 12094 // than the function template of F1 according to the partial 12095 // ordering rules of 14.5.5.2. 12096 12097 // The algorithm specified above is quadratic. We instead use a 12098 // two-pass algorithm (similar to the one used to identify the 12099 // best viable function in an overload set) that identifies the 12100 // best function template (if it exists). 12101 12102 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12103 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12104 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12105 12106 // TODO: It looks like FailedCandidates does not serve much purpose 12107 // here, since the no_viable diagnostic has index 0. 12108 UnresolvedSetIterator Result = S.getMostSpecialized( 12109 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12110 SourceExpr->getBeginLoc(), S.PDiag(), 12111 S.PDiag(diag::err_addr_ovl_ambiguous) 12112 << Matches[0].second->getDeclName(), 12113 S.PDiag(diag::note_ovl_candidate) 12114 << (unsigned)oc_function << (unsigned)ocs_described_template, 12115 Complain, TargetFunctionType); 12116 12117 if (Result != MatchesCopy.end()) { 12118 // Make it the first and only element 12119 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12120 Matches[0].second = cast<FunctionDecl>(*Result); 12121 Matches.resize(1); 12122 } else 12123 HasComplained |= Complain; 12124 } 12125 12126 void EliminateAllTemplateMatches() { 12127 // [...] any function template specializations in the set are 12128 // eliminated if the set also contains a non-template function, [...] 12129 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12130 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12131 ++I; 12132 else { 12133 Matches[I] = Matches[--N]; 12134 Matches.resize(N); 12135 } 12136 } 12137 } 12138 12139 void EliminateSuboptimalCudaMatches() { 12140 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12141 } 12142 12143public: 12144 void ComplainNoMatchesFound() const { 12145 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12145, __PRETTY_FUNCTION__))
; 12146 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12147 << OvlExpr->getName() << TargetFunctionType 12148 << OvlExpr->getSourceRange(); 12149 if (FailedCandidates.empty()) 12150 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12151 /*TakingAddress=*/true); 12152 else { 12153 // We have some deduction failure messages. Use them to diagnose 12154 // the function templates, and diagnose the non-template candidates 12155 // normally. 12156 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12157 IEnd = OvlExpr->decls_end(); 12158 I != IEnd; ++I) 12159 if (FunctionDecl *Fun = 12160 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12161 if (!functionHasPassObjectSizeParams(Fun)) 12162 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12163 /*TakingAddress=*/true); 12164 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12165 } 12166 } 12167 12168 bool IsInvalidFormOfPointerToMemberFunction() const { 12169 return TargetTypeIsNonStaticMemberFunction && 12170 !OvlExprInfo.HasFormOfMemberPointer; 12171 } 12172 12173 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12174 // TODO: Should we condition this on whether any functions might 12175 // have matched, or is it more appropriate to do that in callers? 12176 // TODO: a fixit wouldn't hurt. 12177 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12178 << TargetType << OvlExpr->getSourceRange(); 12179 } 12180 12181 bool IsStaticMemberFunctionFromBoundPointer() const { 12182 return StaticMemberFunctionFromBoundPointer; 12183 } 12184 12185 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12186 S.Diag(OvlExpr->getBeginLoc(), 12187 diag::err_invalid_form_pointer_member_function) 12188 << OvlExpr->getSourceRange(); 12189 } 12190 12191 void ComplainOfInvalidConversion() const { 12192 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12193 << OvlExpr->getName() << TargetType; 12194 } 12195 12196 void ComplainMultipleMatchesFound() const { 12197 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12197, __PRETTY_FUNCTION__))
; 12198 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12199 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12200 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12201 /*TakingAddress=*/true); 12202 } 12203 12204 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12205 12206 int getNumMatches() const { return Matches.size(); } 12207 12208 FunctionDecl* getMatchingFunctionDecl() const { 12209 if (Matches.size() != 1) return nullptr; 12210 return Matches[0].second; 12211 } 12212 12213 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12214 if (Matches.size() != 1) return nullptr; 12215 return &Matches[0].first; 12216 } 12217}; 12218} 12219 12220/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12221/// an overloaded function (C++ [over.over]), where @p From is an 12222/// expression with overloaded function type and @p ToType is the type 12223/// we're trying to resolve to. For example: 12224/// 12225/// @code 12226/// int f(double); 12227/// int f(int); 12228/// 12229/// int (*pfd)(double) = f; // selects f(double) 12230/// @endcode 12231/// 12232/// This routine returns the resulting FunctionDecl if it could be 12233/// resolved, and NULL otherwise. When @p Complain is true, this 12234/// routine will emit diagnostics if there is an error. 12235FunctionDecl * 12236Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12237 QualType TargetType, 12238 bool Complain, 12239 DeclAccessPair &FoundResult, 12240 bool *pHadMultipleCandidates) { 12241 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12241, __PRETTY_FUNCTION__))
; 12242 12243 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12244 Complain); 12245 int NumMatches = Resolver.getNumMatches(); 12246 FunctionDecl *Fn = nullptr; 12247 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12248 if (NumMatches == 0 && ShouldComplain) { 12249 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12250 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12251 else 12252 Resolver.ComplainNoMatchesFound(); 12253 } 12254 else if (NumMatches > 1 && ShouldComplain) 12255 Resolver.ComplainMultipleMatchesFound(); 12256 else if (NumMatches == 1) { 12257 Fn = Resolver.getMatchingFunctionDecl(); 12258 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12258, __PRETTY_FUNCTION__))
; 12259 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12260 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12261 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12262 if (Complain) { 12263 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12264 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12265 else 12266 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12267 } 12268 } 12269 12270 if (pHadMultipleCandidates) 12271 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12272 return Fn; 12273} 12274 12275/// Given an expression that refers to an overloaded function, try to 12276/// resolve that function to a single function that can have its address taken. 12277/// This will modify `Pair` iff it returns non-null. 12278/// 12279/// This routine can only succeed if from all of the candidates in the overload 12280/// set for SrcExpr that can have their addresses taken, there is one candidate 12281/// that is more constrained than the rest. 12282FunctionDecl * 12283Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12284 OverloadExpr::FindResult R = OverloadExpr::find(E); 12285 OverloadExpr *Ovl = R.Expression; 12286 bool IsResultAmbiguous = false; 12287 FunctionDecl *Result = nullptr; 12288 DeclAccessPair DAP; 12289 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12290 12291 auto CheckMoreConstrained = 12292 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12293 SmallVector<const Expr *, 1> AC1, AC2; 12294 FD1->getAssociatedConstraints(AC1); 12295 FD2->getAssociatedConstraints(AC2); 12296 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12297 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12298 return None; 12299 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12300 return None; 12301 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12302 return None; 12303 return AtLeastAsConstrained1; 12304 }; 12305 12306 // Don't use the AddressOfResolver because we're specifically looking for 12307 // cases where we have one overload candidate that lacks 12308 // enable_if/pass_object_size/... 12309 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12310 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12311 if (!FD) 12312 return nullptr; 12313 12314 if (!checkAddressOfFunctionIsAvailable(FD)) 12315 continue; 12316 12317 // We have more than one result - see if it is more constrained than the 12318 // previous one. 12319 if (Result) { 12320 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12321 Result); 12322 if (!MoreConstrainedThanPrevious) { 12323 IsResultAmbiguous = true; 12324 AmbiguousDecls.push_back(FD); 12325 continue; 12326 } 12327 if (!*MoreConstrainedThanPrevious) 12328 continue; 12329 // FD is more constrained - replace Result with it. 12330 } 12331 IsResultAmbiguous = false; 12332 DAP = I.getPair(); 12333 Result = FD; 12334 } 12335 12336 if (IsResultAmbiguous) 12337 return nullptr; 12338 12339 if (Result) { 12340 SmallVector<const Expr *, 1> ResultAC; 12341 // We skipped over some ambiguous declarations which might be ambiguous with 12342 // the selected result. 12343 for (FunctionDecl *Skipped : AmbiguousDecls) 12344 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12345 return nullptr; 12346 Pair = DAP; 12347 } 12348 return Result; 12349} 12350 12351/// Given an overloaded function, tries to turn it into a non-overloaded 12352/// function reference using resolveAddressOfSingleOverloadCandidate. This 12353/// will perform access checks, diagnose the use of the resultant decl, and, if 12354/// requested, potentially perform a function-to-pointer decay. 12355/// 12356/// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12357/// Otherwise, returns true. This may emit diagnostics and return true. 12358bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12359 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12360 Expr *E = SrcExpr.get(); 12361 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload"
) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12361, __PRETTY_FUNCTION__))
; 12362 12363 DeclAccessPair DAP; 12364 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12365 if (!Found || Found->isCPUDispatchMultiVersion() || 12366 Found->isCPUSpecificMultiVersion()) 12367 return false; 12368 12369 // Emitting multiple diagnostics for a function that is both inaccessible and 12370 // unavailable is consistent with our behavior elsewhere. So, always check 12371 // for both. 12372 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12373 CheckAddressOfMemberAccess(E, DAP); 12374 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12375 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12376 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12377 else 12378 SrcExpr = Fixed; 12379 return true; 12380} 12381 12382/// Given an expression that refers to an overloaded function, try to 12383/// resolve that overloaded function expression down to a single function. 12384/// 12385/// This routine can only resolve template-ids that refer to a single function 12386/// template, where that template-id refers to a single template whose template 12387/// arguments are either provided by the template-id or have defaults, 12388/// as described in C++0x [temp.arg.explicit]p3. 12389/// 12390/// If no template-ids are found, no diagnostics are emitted and NULL is 12391/// returned. 12392FunctionDecl * 12393Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12394 bool Complain, 12395 DeclAccessPair *FoundResult) { 12396 // C++ [over.over]p1: 12397 // [...] [Note: any redundant set of parentheses surrounding the 12398 // overloaded function name is ignored (5.1). ] 12399 // C++ [over.over]p1: 12400 // [...] The overloaded function name can be preceded by the & 12401 // operator. 12402 12403 // If we didn't actually find any template-ids, we're done. 12404 if (!ovl->hasExplicitTemplateArgs()) 12405 return nullptr; 12406 12407 TemplateArgumentListInfo ExplicitTemplateArgs; 12408 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12409 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12410 12411 // Look through all of the overloaded functions, searching for one 12412 // whose type matches exactly. 12413 FunctionDecl *Matched = nullptr; 12414 for (UnresolvedSetIterator I = ovl->decls_begin(), 12415 E = ovl->decls_end(); I != E; ++I) { 12416 // C++0x [temp.arg.explicit]p3: 12417 // [...] In contexts where deduction is done and fails, or in contexts 12418 // where deduction is not done, if a template argument list is 12419 // specified and it, along with any default template arguments, 12420 // identifies a single function template specialization, then the 12421 // template-id is an lvalue for the function template specialization. 12422 FunctionTemplateDecl *FunctionTemplate 12423 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12424 12425 // C++ [over.over]p2: 12426 // If the name is a function template, template argument deduction is 12427 // done (14.8.2.2), and if the argument deduction succeeds, the 12428 // resulting template argument list is used to generate a single 12429 // function template specialization, which is added to the set of 12430 // overloaded functions considered. 12431 FunctionDecl *Specialization = nullptr; 12432 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12433 if (TemplateDeductionResult Result 12434 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12435 Specialization, Info, 12436 /*IsAddressOfFunction*/true)) { 12437 // Make a note of the failed deduction for diagnostics. 12438 // TODO: Actually use the failed-deduction info? 12439 FailedCandidates.addCandidate() 12440 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12441 MakeDeductionFailureInfo(Context, Result, Info)); 12442 continue; 12443 } 12444 12445 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12445, __PRETTY_FUNCTION__))
; 12446 12447 // Multiple matches; we can't resolve to a single declaration. 12448 if (Matched) { 12449 if (Complain) { 12450 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12451 << ovl->getName(); 12452 NoteAllOverloadCandidates(ovl); 12453 } 12454 return nullptr; 12455 } 12456 12457 Matched = Specialization; 12458 if (FoundResult) *FoundResult = I.getPair(); 12459 } 12460 12461 if (Matched && 12462 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12463 return nullptr; 12464 12465 return Matched; 12466} 12467 12468// Resolve and fix an overloaded expression that can be resolved 12469// because it identifies a single function template specialization. 12470// 12471// Last three arguments should only be supplied if Complain = true 12472// 12473// Return true if it was logically possible to so resolve the 12474// expression, regardless of whether or not it succeeded. Always 12475// returns true if 'complain' is set. 12476bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12477 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12478 bool complain, SourceRange OpRangeForComplaining, 12479 QualType DestTypeForComplaining, 12480 unsigned DiagIDForComplaining) { 12481 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12481, __PRETTY_FUNCTION__))
; 12482 12483 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12484 12485 DeclAccessPair found; 12486 ExprResult SingleFunctionExpression; 12487 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12488 ovl.Expression, /*complain*/ false, &found)) { 12489 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12490 SrcExpr = ExprError(); 12491 return true; 12492 } 12493 12494 // It is only correct to resolve to an instance method if we're 12495 // resolving a form that's permitted to be a pointer to member. 12496 // Otherwise we'll end up making a bound member expression, which 12497 // is illegal in all the contexts we resolve like this. 12498 if (!ovl.HasFormOfMemberPointer && 12499 isa<CXXMethodDecl>(fn) && 12500 cast<CXXMethodDecl>(fn)->isInstance()) { 12501 if (!complain) return false; 12502 12503 Diag(ovl.Expression->getExprLoc(), 12504 diag::err_bound_member_function) 12505 << 0 << ovl.Expression->getSourceRange(); 12506 12507 // TODO: I believe we only end up here if there's a mix of 12508 // static and non-static candidates (otherwise the expression 12509 // would have 'bound member' type, not 'overload' type). 12510 // Ideally we would note which candidate was chosen and why 12511 // the static candidates were rejected. 12512 SrcExpr = ExprError(); 12513 return true; 12514 } 12515 12516 // Fix the expression to refer to 'fn'. 12517 SingleFunctionExpression = 12518 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12519 12520 // If desired, do function-to-pointer decay. 12521 if (doFunctionPointerConverion) { 12522 SingleFunctionExpression = 12523 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12524 if (SingleFunctionExpression.isInvalid()) { 12525 SrcExpr = ExprError(); 12526 return true; 12527 } 12528 } 12529 } 12530 12531 if (!SingleFunctionExpression.isUsable()) { 12532 if (complain) { 12533 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12534 << ovl.Expression->getName() 12535 << DestTypeForComplaining 12536 << OpRangeForComplaining 12537 << ovl.Expression->getQualifierLoc().getSourceRange(); 12538 NoteAllOverloadCandidates(SrcExpr.get()); 12539 12540 SrcExpr = ExprError(); 12541 return true; 12542 } 12543 12544 return false; 12545 } 12546 12547 SrcExpr = SingleFunctionExpression; 12548 return true; 12549} 12550 12551/// Add a single candidate to the overload set. 12552static void AddOverloadedCallCandidate(Sema &S, 12553 DeclAccessPair FoundDecl, 12554 TemplateArgumentListInfo *ExplicitTemplateArgs, 12555 ArrayRef<Expr *> Args, 12556 OverloadCandidateSet &CandidateSet, 12557 bool PartialOverloading, 12558 bool KnownValid) { 12559 NamedDecl *Callee = FoundDecl.getDecl(); 12560 if (isa<UsingShadowDecl>(Callee)) 12561 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12562 12563 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12564 if (ExplicitTemplateArgs) { 12565 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12565, __PRETTY_FUNCTION__))
; 12566 return; 12567 } 12568 // Prevent ill-formed function decls to be added as overload candidates. 12569 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12570 return; 12571 12572 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12573 /*SuppressUserConversions=*/false, 12574 PartialOverloading); 12575 return; 12576 } 12577 12578 if (FunctionTemplateDecl *FuncTemplate 12579 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12580 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12581 ExplicitTemplateArgs, Args, CandidateSet, 12582 /*SuppressUserConversions=*/false, 12583 PartialOverloading); 12584 return; 12585 } 12586 12587 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12587, __PRETTY_FUNCTION__))
; 12588} 12589 12590/// Add the overload candidates named by callee and/or found by argument 12591/// dependent lookup to the given overload set. 12592void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12593 ArrayRef<Expr *> Args, 12594 OverloadCandidateSet &CandidateSet, 12595 bool PartialOverloading) { 12596 12597#ifndef NDEBUG 12598 // Verify that ArgumentDependentLookup is consistent with the rules 12599 // in C++0x [basic.lookup.argdep]p3: 12600 // 12601 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12602 // and let Y be the lookup set produced by argument dependent 12603 // lookup (defined as follows). If X contains 12604 // 12605 // -- a declaration of a class member, or 12606 // 12607 // -- a block-scope function declaration that is not a 12608 // using-declaration, or 12609 // 12610 // -- a declaration that is neither a function or a function 12611 // template 12612 // 12613 // then Y is empty. 12614 12615 if (ULE->requiresADL()) { 12616 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12617 E = ULE->decls_end(); I != E; ++I) { 12618 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12618, __PRETTY_FUNCTION__))
; 12619 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12620, __PRETTY_FUNCTION__))
12620 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12620, __PRETTY_FUNCTION__))
; 12621 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12621, __PRETTY_FUNCTION__))
; 12622 } 12623 } 12624#endif 12625 12626 // It would be nice to avoid this copy. 12627 TemplateArgumentListInfo TABuffer; 12628 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12629 if (ULE->hasExplicitTemplateArgs()) { 12630 ULE->copyTemplateArgumentsInto(TABuffer); 12631 ExplicitTemplateArgs = &TABuffer; 12632 } 12633 12634 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12635 E = ULE->decls_end(); I != E; ++I) 12636 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12637 CandidateSet, PartialOverloading, 12638 /*KnownValid*/ true); 12639 12640 if (ULE->requiresADL()) 12641 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12642 Args, ExplicitTemplateArgs, 12643 CandidateSet, PartialOverloading); 12644} 12645 12646/// Determine whether a declaration with the specified name could be moved into 12647/// a different namespace. 12648static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12649 switch (Name.getCXXOverloadedOperator()) { 12650 case OO_New: case OO_Array_New: 12651 case OO_Delete: case OO_Array_Delete: 12652 return false; 12653 12654 default: 12655 return true; 12656 } 12657} 12658 12659/// Attempt to recover from an ill-formed use of a non-dependent name in a 12660/// template, where the non-dependent name was declared after the template 12661/// was defined. This is common in code written for a compilers which do not 12662/// correctly implement two-stage name lookup. 12663/// 12664/// Returns true if a viable candidate was found and a diagnostic was issued. 12665static bool 12666DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12667 const CXXScopeSpec &SS, LookupResult &R, 12668 OverloadCandidateSet::CandidateSetKind CSK, 12669 TemplateArgumentListInfo *ExplicitTemplateArgs, 12670 ArrayRef<Expr *> Args, 12671 bool *DoDiagnoseEmptyLookup = nullptr) { 12672 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12673 return false; 12674 12675 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12676 if (DC->isTransparentContext()) 12677 continue; 12678 12679 SemaRef.LookupQualifiedName(R, DC); 12680 12681 if (!R.empty()) { 12682 R.suppressDiagnostics(); 12683 12684 if (isa<CXXRecordDecl>(DC)) { 12685 // Don't diagnose names we find in classes; we get much better 12686 // diagnostics for these from DiagnoseEmptyLookup. 12687 R.clear(); 12688 if (DoDiagnoseEmptyLookup) 12689 *DoDiagnoseEmptyLookup = true; 12690 return false; 12691 } 12692 12693 OverloadCandidateSet Candidates(FnLoc, CSK); 12694 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12695 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12696 ExplicitTemplateArgs, Args, 12697 Candidates, false, /*KnownValid*/ false); 12698 12699 OverloadCandidateSet::iterator Best; 12700 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12701 // No viable functions. Don't bother the user with notes for functions 12702 // which don't work and shouldn't be found anyway. 12703 R.clear(); 12704 return false; 12705 } 12706 12707 // Find the namespaces where ADL would have looked, and suggest 12708 // declaring the function there instead. 12709 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12710 Sema::AssociatedClassSet AssociatedClasses; 12711 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12712 AssociatedNamespaces, 12713 AssociatedClasses); 12714 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12715 if (canBeDeclaredInNamespace(R.getLookupName())) { 12716 DeclContext *Std = SemaRef.getStdNamespace(); 12717 for (Sema::AssociatedNamespaceSet::iterator 12718 it = AssociatedNamespaces.begin(), 12719 end = AssociatedNamespaces.end(); it != end; ++it) { 12720 // Never suggest declaring a function within namespace 'std'. 12721 if (Std && Std->Encloses(*it)) 12722 continue; 12723 12724 // Never suggest declaring a function within a namespace with a 12725 // reserved name, like __gnu_cxx. 12726 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12727 if (NS && 12728 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12729 continue; 12730 12731 SuggestedNamespaces.insert(*it); 12732 } 12733 } 12734 12735 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12736 << R.getLookupName(); 12737 if (SuggestedNamespaces.empty()) { 12738 SemaRef.Diag(Best->Function->getLocation(), 12739 diag::note_not_found_by_two_phase_lookup) 12740 << R.getLookupName() << 0; 12741 } else if (SuggestedNamespaces.size() == 1) { 12742 SemaRef.Diag(Best->Function->getLocation(), 12743 diag::note_not_found_by_two_phase_lookup) 12744 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12745 } else { 12746 // FIXME: It would be useful to list the associated namespaces here, 12747 // but the diagnostics infrastructure doesn't provide a way to produce 12748 // a localized representation of a list of items. 12749 SemaRef.Diag(Best->Function->getLocation(), 12750 diag::note_not_found_by_two_phase_lookup) 12751 << R.getLookupName() << 2; 12752 } 12753 12754 // Try to recover by calling this function. 12755 return true; 12756 } 12757 12758 R.clear(); 12759 } 12760 12761 return false; 12762} 12763 12764/// Attempt to recover from ill-formed use of a non-dependent operator in a 12765/// template, where the non-dependent operator was declared after the template 12766/// was defined. 12767/// 12768/// Returns true if a viable candidate was found and a diagnostic was issued. 12769static bool 12770DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12771 SourceLocation OpLoc, 12772 ArrayRef<Expr *> Args) { 12773 DeclarationName OpName = 12774 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12775 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12776 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12777 OverloadCandidateSet::CSK_Operator, 12778 /*ExplicitTemplateArgs=*/nullptr, Args); 12779} 12780 12781namespace { 12782class BuildRecoveryCallExprRAII { 12783 Sema &SemaRef; 12784public: 12785 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12786 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12786, __PRETTY_FUNCTION__))
; 12787 SemaRef.IsBuildingRecoveryCallExpr = true; 12788 } 12789 12790 ~BuildRecoveryCallExprRAII() { 12791 SemaRef.IsBuildingRecoveryCallExpr = false; 12792 } 12793}; 12794 12795} 12796 12797/// Attempts to recover from a call where no functions were found. 12798static ExprResult 12799BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12800 UnresolvedLookupExpr *ULE, 12801 SourceLocation LParenLoc, 12802 MutableArrayRef<Expr *> Args, 12803 SourceLocation RParenLoc, 12804 bool EmptyLookup, bool AllowTypoCorrection) { 12805 // Do not try to recover if it is already building a recovery call. 12806 // This stops infinite loops for template instantiations like 12807 // 12808 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12809 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12810 // 12811 if (SemaRef.IsBuildingRecoveryCallExpr) 12812 return ExprError(); 12813 BuildRecoveryCallExprRAII RCE(SemaRef); 12814 12815 CXXScopeSpec SS; 12816 SS.Adopt(ULE->getQualifierLoc()); 12817 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12818 12819 TemplateArgumentListInfo TABuffer; 12820 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12821 if (ULE->hasExplicitTemplateArgs()) { 12822 ULE->copyTemplateArgumentsInto(TABuffer); 12823 ExplicitTemplateArgs = &TABuffer; 12824 } 12825 12826 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12827 Sema::LookupOrdinaryName); 12828 bool DoDiagnoseEmptyLookup = EmptyLookup; 12829 if (!DiagnoseTwoPhaseLookup( 12830 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12831 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12832 NoTypoCorrectionCCC NoTypoValidator{}; 12833 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12834 ExplicitTemplateArgs != nullptr, 12835 dyn_cast<MemberExpr>(Fn)); 12836 CorrectionCandidateCallback &Validator = 12837 AllowTypoCorrection 12838 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12839 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12840 if (!DoDiagnoseEmptyLookup || 12841 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12842 Args)) 12843 return ExprError(); 12844 } 12845 12846 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12846, __PRETTY_FUNCTION__))
; 12847 12848 // If recovery created an ambiguity, just bail out. 12849 if (R.isAmbiguous()) { 12850 R.suppressDiagnostics(); 12851 return ExprError(); 12852 } 12853 12854 // Build an implicit member access expression if appropriate. Just drop the 12855 // casts and such from the call, we don't really care. 12856 ExprResult NewFn = ExprError(); 12857 if ((*R.begin())->isCXXClassMember()) 12858 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12859 ExplicitTemplateArgs, S); 12860 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12861 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12862 ExplicitTemplateArgs); 12863 else 12864 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12865 12866 if (NewFn.isInvalid()) 12867 return ExprError(); 12868 12869 auto CallE = 12870 SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12871 MultiExprArg(Args.data(), Args.size()), RParenLoc); 12872 if (CallE.isInvalid()) 12873 return ExprError(); 12874 // We now have recovered a callee. However, building a real call may lead to 12875 // incorrect secondary diagnostics if our recovery wasn't correct. 12876 // We keep the recovery behavior but suppress all following diagnostics by 12877 // using RecoveryExpr. We deliberately drop the return type of the recovery 12878 // function, and rely on clang's dependent mechanism to suppress following 12879 // diagnostics. 12880 return SemaRef.CreateRecoveryExpr(CallE.get()->getBeginLoc(), 12881 CallE.get()->getEndLoc(), {CallE.get()}); 12882} 12883 12884/// Constructs and populates an OverloadedCandidateSet from 12885/// the given function. 12886/// \returns true when an the ExprResult output parameter has been set. 12887bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12888 UnresolvedLookupExpr *ULE, 12889 MultiExprArg Args, 12890 SourceLocation RParenLoc, 12891 OverloadCandidateSet *CandidateSet, 12892 ExprResult *Result) { 12893#ifndef NDEBUG 12894 if (ULE->requiresADL()) { 12895 // To do ADL, we must have found an unqualified name. 12896 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12896, __PRETTY_FUNCTION__))
; 12897 12898 // We don't perform ADL for implicit declarations of builtins. 12899 // Verify that this was correctly set up. 12900 FunctionDecl *F; 12901 if (ULE->decls_begin() != ULE->decls_end() && 12902 ULE->decls_begin() + 1 == ULE->decls_end() && 12903 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12904 F->getBuiltinID() && F->isImplicit()) 12905 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12905)
; 12906 12907 // We don't perform ADL in C. 12908 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 12908, __PRETTY_FUNCTION__))
; 12909 } 12910#endif 12911 12912 UnbridgedCastsSet UnbridgedCasts; 12913 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12914 *Result = ExprError(); 12915 return true; 12916 } 12917 12918 // Add the functions denoted by the callee to the set of candidate 12919 // functions, including those from argument-dependent lookup. 12920 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12921 12922 if (getLangOpts().MSVCCompat && 12923 CurContext->isDependentContext() && !isSFINAEContext() && 12924 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12925 12926 OverloadCandidateSet::iterator Best; 12927 if (CandidateSet->empty() || 12928 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12929 OR_No_Viable_Function) { 12930 // In Microsoft mode, if we are inside a template class member function 12931 // then create a type dependent CallExpr. The goal is to postpone name 12932 // lookup to instantiation time to be able to search into type dependent 12933 // base classes. 12934 CallExpr *CE = 12935 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 12936 RParenLoc, CurFPFeatureOverrides()); 12937 CE->markDependentForPostponedNameLookup(); 12938 *Result = CE; 12939 return true; 12940 } 12941 } 12942 12943 if (CandidateSet->empty()) 12944 return false; 12945 12946 UnbridgedCasts.restore(); 12947 return false; 12948} 12949 12950// Guess at what the return type for an unresolvable overload should be. 12951static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12952 OverloadCandidateSet::iterator *Best) { 12953 llvm::Optional<QualType> Result; 12954 // Adjust Type after seeing a candidate. 12955 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12956 if (!Candidate.Function) 12957 return; 12958 if (Candidate.Function->isInvalidDecl()) 12959 return; 12960 QualType T = Candidate.Function->getReturnType(); 12961 if (T.isNull()) 12962 return; 12963 if (!Result) 12964 Result = T; 12965 else if (Result != T) 12966 Result = QualType(); 12967 }; 12968 12969 // Look for an unambiguous type from a progressively larger subset. 12970 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12971 // 12972 // First, consider only the best candidate. 12973 if (Best && *Best != CS.end()) 12974 ConsiderCandidate(**Best); 12975 // Next, consider only viable candidates. 12976 if (!Result) 12977 for (const auto &C : CS) 12978 if (C.Viable) 12979 ConsiderCandidate(C); 12980 // Finally, consider all candidates. 12981 if (!Result) 12982 for (const auto &C : CS) 12983 ConsiderCandidate(C); 12984 12985 if (!Result) 12986 return QualType(); 12987 auto Value = Result.getValue(); 12988 if (Value.isNull() || Value->isUndeducedType()) 12989 return QualType(); 12990 return Value; 12991} 12992 12993/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12994/// the completed call expression. If overload resolution fails, emits 12995/// diagnostics and returns ExprError() 12996static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12997 UnresolvedLookupExpr *ULE, 12998 SourceLocation LParenLoc, 12999 MultiExprArg Args, 13000 SourceLocation RParenLoc, 13001 Expr *ExecConfig, 13002 OverloadCandidateSet *CandidateSet, 13003 OverloadCandidateSet::iterator *Best, 13004 OverloadingResult OverloadResult, 13005 bool AllowTypoCorrection) { 13006 if (CandidateSet->empty()) 13007 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 13008 RParenLoc, /*EmptyLookup=*/true, 13009 AllowTypoCorrection); 13010 13011 switch (OverloadResult) { 13012 case OR_Success: { 13013 FunctionDecl *FDecl = (*Best)->Function; 13014 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13015 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13016 return ExprError(); 13017 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13018 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13019 ExecConfig, /*IsExecConfig=*/false, 13020 (*Best)->IsADLCandidate); 13021 } 13022 13023 case OR_No_Viable_Function: { 13024 // Try to recover by looking for viable functions which the user might 13025 // have meant to call. 13026 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13027 Args, RParenLoc, 13028 /*EmptyLookup=*/false, 13029 AllowTypoCorrection); 13030 if (!Recovery.isInvalid()) 13031 return Recovery; 13032 13033 // If the user passes in a function that we can't take the address of, we 13034 // generally end up emitting really bad error messages. Here, we attempt to 13035 // emit better ones. 13036 for (const Expr *Arg : Args) { 13037 if (!Arg->getType()->isFunctionType()) 13038 continue; 13039 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13040 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13041 if (FD && 13042 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13043 Arg->getExprLoc())) 13044 return ExprError(); 13045 } 13046 } 13047 13048 CandidateSet->NoteCandidates( 13049 PartialDiagnosticAt( 13050 Fn->getBeginLoc(), 13051 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13052 << ULE->getName() << Fn->getSourceRange()), 13053 SemaRef, OCD_AllCandidates, Args); 13054 break; 13055 } 13056 13057 case OR_Ambiguous: 13058 CandidateSet->NoteCandidates( 13059 PartialDiagnosticAt(Fn->getBeginLoc(), 13060 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13061 << ULE->getName() << Fn->getSourceRange()), 13062 SemaRef, OCD_AmbiguousCandidates, Args); 13063 break; 13064 13065 case OR_Deleted: { 13066 CandidateSet->NoteCandidates( 13067 PartialDiagnosticAt(Fn->getBeginLoc(), 13068 SemaRef.PDiag(diag::err_ovl_deleted_call) 13069 << ULE->getName() << Fn->getSourceRange()), 13070 SemaRef, OCD_AllCandidates, Args); 13071 13072 // We emitted an error for the unavailable/deleted function call but keep 13073 // the call in the AST. 13074 FunctionDecl *FDecl = (*Best)->Function; 13075 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13076 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13077 ExecConfig, /*IsExecConfig=*/false, 13078 (*Best)->IsADLCandidate); 13079 } 13080 } 13081 13082 // Overload resolution failed, try to recover. 13083 SmallVector<Expr *, 8> SubExprs = {Fn}; 13084 SubExprs.append(Args.begin(), Args.end()); 13085 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13086 chooseRecoveryType(*CandidateSet, Best)); 13087} 13088 13089static void markUnaddressableCandidatesUnviable(Sema &S, 13090 OverloadCandidateSet &CS) { 13091 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13092 if (I->Viable && 13093 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13094 I->Viable = false; 13095 I->FailureKind = ovl_fail_addr_not_available; 13096 } 13097 } 13098} 13099 13100/// BuildOverloadedCallExpr - Given the call expression that calls Fn 13101/// (which eventually refers to the declaration Func) and the call 13102/// arguments Args/NumArgs, attempt to resolve the function call down 13103/// to a specific function. If overload resolution succeeds, returns 13104/// the call expression produced by overload resolution. 13105/// Otherwise, emits diagnostics and returns ExprError. 13106ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13107 UnresolvedLookupExpr *ULE, 13108 SourceLocation LParenLoc, 13109 MultiExprArg Args, 13110 SourceLocation RParenLoc, 13111 Expr *ExecConfig, 13112 bool AllowTypoCorrection, 13113 bool CalleesAddressIsTaken) { 13114 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13115 OverloadCandidateSet::CSK_Normal); 13116 ExprResult result; 13117 13118 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13119 &result)) 13120 return result; 13121 13122 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13123 // functions that aren't addressible are considered unviable. 13124 if (CalleesAddressIsTaken) 13125 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13126 13127 OverloadCandidateSet::iterator Best; 13128 OverloadingResult OverloadResult = 13129 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13130 13131 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13132 ExecConfig, &CandidateSet, &Best, 13133 OverloadResult, AllowTypoCorrection); 13134} 13135 13136static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13137 return Functions.size() > 1 || 13138 (Functions.size() == 1 && 13139 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13140} 13141 13142ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13143 NestedNameSpecifierLoc NNSLoc, 13144 DeclarationNameInfo DNI, 13145 const UnresolvedSetImpl &Fns, 13146 bool PerformADL) { 13147 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13148 PerformADL, IsOverloaded(Fns), 13149 Fns.begin(), Fns.end()); 13150} 13151 13152/// Create a unary operation that may resolve to an overloaded 13153/// operator. 13154/// 13155/// \param OpLoc The location of the operator itself (e.g., '*'). 13156/// 13157/// \param Opc The UnaryOperatorKind that describes this operator. 13158/// 13159/// \param Fns The set of non-member functions that will be 13160/// considered by overload resolution. The caller needs to build this 13161/// set based on the context using, e.g., 13162/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13163/// set should not contain any member functions; those will be added 13164/// by CreateOverloadedUnaryOp(). 13165/// 13166/// \param Input The input argument. 13167ExprResult 13168Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13169 const UnresolvedSetImpl &Fns, 13170 Expr *Input, bool PerformADL) { 13171 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13172 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13172, __PRETTY_FUNCTION__))
; 13173 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13174 // TODO: provide better source location info. 13175 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13176 13177 if (checkPlaceholderForOverload(*this, Input)) 13178 return ExprError(); 13179 13180 Expr *Args[2] = { Input, nullptr }; 13181 unsigned NumArgs = 1; 13182 13183 // For post-increment and post-decrement, add the implicit '0' as 13184 // the second argument, so that we know this is a post-increment or 13185 // post-decrement. 13186 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13187 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13188 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13189 SourceLocation()); 13190 NumArgs = 2; 13191 } 13192 13193 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13194 13195 if (Input->isTypeDependent()) { 13196 if (Fns.empty()) 13197 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13198 VK_RValue, OK_Ordinary, OpLoc, false, 13199 CurFPFeatureOverrides()); 13200 13201 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13202 ExprResult Fn = CreateUnresolvedLookupExpr( 13203 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13204 if (Fn.isInvalid()) 13205 return ExprError(); 13206 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13207 Context.DependentTy, VK_RValue, OpLoc, 13208 CurFPFeatureOverrides()); 13209 } 13210 13211 // Build an empty overload set. 13212 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13213 13214 // Add the candidates from the given function set. 13215 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13216 13217 // Add operator candidates that are member functions. 13218 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13219 13220 // Add candidates from ADL. 13221 if (PerformADL) { 13222 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13223 /*ExplicitTemplateArgs*/nullptr, 13224 CandidateSet); 13225 } 13226 13227 // Add builtin operator candidates. 13228 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13229 13230 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13231 13232 // Perform overload resolution. 13233 OverloadCandidateSet::iterator Best; 13234 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13235 case OR_Success: { 13236 // We found a built-in operator or an overloaded operator. 13237 FunctionDecl *FnDecl = Best->Function; 13238 13239 if (FnDecl) { 13240 Expr *Base = nullptr; 13241 // We matched an overloaded operator. Build a call to that 13242 // operator. 13243 13244 // Convert the arguments. 13245 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13246 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13247 13248 ExprResult InputRes = 13249 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13250 Best->FoundDecl, Method); 13251 if (InputRes.isInvalid()) 13252 return ExprError(); 13253 Base = Input = InputRes.get(); 13254 } else { 13255 // Convert the arguments. 13256 ExprResult InputInit 13257 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13258 Context, 13259 FnDecl->getParamDecl(0)), 13260 SourceLocation(), 13261 Input); 13262 if (InputInit.isInvalid()) 13263 return ExprError(); 13264 Input = InputInit.get(); 13265 } 13266 13267 // Build the actual expression node. 13268 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13269 Base, HadMultipleCandidates, 13270 OpLoc); 13271 if (FnExpr.isInvalid()) 13272 return ExprError(); 13273 13274 // Determine the result type. 13275 QualType ResultTy = FnDecl->getReturnType(); 13276 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13277 ResultTy = ResultTy.getNonLValueExprType(Context); 13278 13279 Args[0] = Input; 13280 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13281 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13282 CurFPFeatureOverrides(), Best->IsADLCandidate); 13283 13284 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13285 return ExprError(); 13286 13287 if (CheckFunctionCall(FnDecl, TheCall, 13288 FnDecl->getType()->castAs<FunctionProtoType>())) 13289 return ExprError(); 13290 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13291 } else { 13292 // We matched a built-in operator. Convert the arguments, then 13293 // break out so that we will build the appropriate built-in 13294 // operator node. 13295 ExprResult InputRes = PerformImplicitConversion( 13296 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13297 CCK_ForBuiltinOverloadedOp); 13298 if (InputRes.isInvalid()) 13299 return ExprError(); 13300 Input = InputRes.get(); 13301 break; 13302 } 13303 } 13304 13305 case OR_No_Viable_Function: 13306 // This is an erroneous use of an operator which can be overloaded by 13307 // a non-member function. Check for non-member operators which were 13308 // defined too late to be candidates. 13309 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13310 // FIXME: Recover by calling the found function. 13311 return ExprError(); 13312 13313 // No viable function; fall through to handling this as a 13314 // built-in operator, which will produce an error message for us. 13315 break; 13316 13317 case OR_Ambiguous: 13318 CandidateSet.NoteCandidates( 13319 PartialDiagnosticAt(OpLoc, 13320 PDiag(diag::err_ovl_ambiguous_oper_unary) 13321 << UnaryOperator::getOpcodeStr(Opc) 13322 << Input->getType() << Input->getSourceRange()), 13323 *this, OCD_AmbiguousCandidates, ArgsArray, 13324 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13325 return ExprError(); 13326 13327 case OR_Deleted: 13328 CandidateSet.NoteCandidates( 13329 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13330 << UnaryOperator::getOpcodeStr(Opc) 13331 << Input->getSourceRange()), 13332 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13333 OpLoc); 13334 return ExprError(); 13335 } 13336 13337 // Either we found no viable overloaded operator or we matched a 13338 // built-in operator. In either case, fall through to trying to 13339 // build a built-in operation. 13340 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13341} 13342 13343/// Perform lookup for an overloaded binary operator. 13344void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13345 OverloadedOperatorKind Op, 13346 const UnresolvedSetImpl &Fns, 13347 ArrayRef<Expr *> Args, bool PerformADL) { 13348 SourceLocation OpLoc = CandidateSet.getLocation(); 13349 13350 OverloadedOperatorKind ExtraOp = 13351 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13352 ? getRewrittenOverloadedOperator(Op) 13353 : OO_None; 13354 13355 // Add the candidates from the given function set. This also adds the 13356 // rewritten candidates using these functions if necessary. 13357 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13358 13359 // Add operator candidates that are member functions. 13360 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13361 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13362 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13363 OverloadCandidateParamOrder::Reversed); 13364 13365 // In C++20, also add any rewritten member candidates. 13366 if (ExtraOp) { 13367 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13368 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13369 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13370 CandidateSet, 13371 OverloadCandidateParamOrder::Reversed); 13372 } 13373 13374 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13375 // performed for an assignment operator (nor for operator[] nor operator->, 13376 // which don't get here). 13377 if (Op != OO_Equal && PerformADL) { 13378 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13379 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13380 /*ExplicitTemplateArgs*/ nullptr, 13381 CandidateSet); 13382 if (ExtraOp) { 13383 DeclarationName ExtraOpName = 13384 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13385 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13386 /*ExplicitTemplateArgs*/ nullptr, 13387 CandidateSet); 13388 } 13389 } 13390 13391 // Add builtin operator candidates. 13392 // 13393 // FIXME: We don't add any rewritten candidates here. This is strictly 13394 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13395 // resulting in our selecting a rewritten builtin candidate. For example: 13396 // 13397 // enum class E { e }; 13398 // bool operator!=(E, E) requires false; 13399 // bool k = E::e != E::e; 13400 // 13401 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13402 // it seems unreasonable to consider rewritten builtin candidates. A core 13403 // issue has been filed proposing to removed this requirement. 13404 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13405} 13406 13407/// Create a binary operation that may resolve to an overloaded 13408/// operator. 13409/// 13410/// \param OpLoc The location of the operator itself (e.g., '+'). 13411/// 13412/// \param Opc The BinaryOperatorKind that describes this operator. 13413/// 13414/// \param Fns The set of non-member functions that will be 13415/// considered by overload resolution. The caller needs to build this 13416/// set based on the context using, e.g., 13417/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13418/// set should not contain any member functions; those will be added 13419/// by CreateOverloadedBinOp(). 13420/// 13421/// \param LHS Left-hand argument. 13422/// \param RHS Right-hand argument. 13423/// \param PerformADL Whether to consider operator candidates found by ADL. 13424/// \param AllowRewrittenCandidates Whether to consider candidates found by 13425/// C++20 operator rewrites. 13426/// \param DefaultedFn If we are synthesizing a defaulted operator function, 13427/// the function in question. Such a function is never a candidate in 13428/// our overload resolution. This also enables synthesizing a three-way 13429/// comparison from < and == as described in C++20 [class.spaceship]p1. 13430ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13431 BinaryOperatorKind Opc, 13432 const UnresolvedSetImpl &Fns, Expr *LHS, 13433 Expr *RHS, bool PerformADL, 13434 bool AllowRewrittenCandidates, 13435 FunctionDecl *DefaultedFn) { 13436 Expr *Args[2] = { LHS, RHS }; 13437 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13438 13439 if (!getLangOpts().CPlusPlus20) 13440 AllowRewrittenCandidates = false; 13441 13442 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13443 13444 // If either side is type-dependent, create an appropriate dependent 13445 // expression. 13446 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13447 if (Fns.empty()) { 13448 // If there are no functions to store, just build a dependent 13449 // BinaryOperator or CompoundAssignment. 13450 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13451 return CompoundAssignOperator::Create( 13452 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13453 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13454 Context.DependentTy); 13455 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13456 Context.DependentTy, VK_RValue, OK_Ordinary, 13457 OpLoc, CurFPFeatureOverrides()); 13458 } 13459 13460 // FIXME: save results of ADL from here? 13461 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13462 // TODO: provide better source location info in DNLoc component. 13463 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13464 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13465 ExprResult Fn = CreateUnresolvedLookupExpr( 13466 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13467 if (Fn.isInvalid()) 13468 return ExprError(); 13469 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13470 Context.DependentTy, VK_RValue, OpLoc, 13471 CurFPFeatureOverrides()); 13472 } 13473 13474 // Always do placeholder-like conversions on the RHS. 13475 if (checkPlaceholderForOverload(*this, Args[1])) 13476 return ExprError(); 13477 13478 // Do placeholder-like conversion on the LHS; note that we should 13479 // not get here with a PseudoObject LHS. 13480 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13480, __PRETTY_FUNCTION__))
; 13481 if (checkPlaceholderForOverload(*this, Args[0])) 13482 return ExprError(); 13483 13484 // If this is the assignment operator, we only perform overload resolution 13485 // if the left-hand side is a class or enumeration type. This is actually 13486 // a hack. The standard requires that we do overload resolution between the 13487 // various built-in candidates, but as DR507 points out, this can lead to 13488 // problems. So we do it this way, which pretty much follows what GCC does. 13489 // Note that we go the traditional code path for compound assignment forms. 13490 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13491 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13492 13493 // If this is the .* operator, which is not overloadable, just 13494 // create a built-in binary operator. 13495 if (Opc == BO_PtrMemD) 13496 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13497 13498 // Build the overload set. 13499 OverloadCandidateSet CandidateSet( 13500 OpLoc, OverloadCandidateSet::CSK_Operator, 13501 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13502 if (DefaultedFn) 13503 CandidateSet.exclude(DefaultedFn); 13504 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13505 13506 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13507 13508 // Perform overload resolution. 13509 OverloadCandidateSet::iterator Best; 13510 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13511 case OR_Success: { 13512 // We found a built-in operator or an overloaded operator. 13513 FunctionDecl *FnDecl = Best->Function; 13514 13515 bool IsReversed = Best->isReversed(); 13516 if (IsReversed) 13517 std::swap(Args[0], Args[1]); 13518 13519 if (FnDecl) { 13520 Expr *Base = nullptr; 13521 // We matched an overloaded operator. Build a call to that 13522 // operator. 13523 13524 OverloadedOperatorKind ChosenOp = 13525 FnDecl->getDeclName().getCXXOverloadedOperator(); 13526 13527 // C++2a [over.match.oper]p9: 13528 // If a rewritten operator== candidate is selected by overload 13529 // resolution for an operator@, its return type shall be cv bool 13530 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13531 !FnDecl->getReturnType()->isBooleanType()) { 13532 bool IsExtension = 13533 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13534 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13535 : diag::err_ovl_rewrite_equalequal_not_bool) 13536 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13537 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13538 Diag(FnDecl->getLocation(), diag::note_declared_at); 13539 if (!IsExtension) 13540 return ExprError(); 13541 } 13542 13543 if (AllowRewrittenCandidates && !IsReversed && 13544 CandidateSet.getRewriteInfo().isReversible()) { 13545 // We could have reversed this operator, but didn't. Check if some 13546 // reversed form was a viable candidate, and if so, if it had a 13547 // better conversion for either parameter. If so, this call is 13548 // formally ambiguous, and allowing it is an extension. 13549 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13550 for (OverloadCandidate &Cand : CandidateSet) { 13551 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13552 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13553 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13554 if (CompareImplicitConversionSequences( 13555 *this, OpLoc, Cand.Conversions[ArgIdx], 13556 Best->Conversions[ArgIdx]) == 13557 ImplicitConversionSequence::Better) { 13558 AmbiguousWith.push_back(Cand.Function); 13559 break; 13560 } 13561 } 13562 } 13563 } 13564 13565 if (!AmbiguousWith.empty()) { 13566 bool AmbiguousWithSelf = 13567 AmbiguousWith.size() == 1 && 13568 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13569 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13570 << BinaryOperator::getOpcodeStr(Opc) 13571 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13572 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13573 if (AmbiguousWithSelf) { 13574 Diag(FnDecl->getLocation(), 13575 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13576 } else { 13577 Diag(FnDecl->getLocation(), 13578 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13579 for (auto *F : AmbiguousWith) 13580 Diag(F->getLocation(), 13581 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13582 } 13583 } 13584 } 13585 13586 // Convert the arguments. 13587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13588 // Best->Access is only meaningful for class members. 13589 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13590 13591 ExprResult Arg1 = 13592 PerformCopyInitialization( 13593 InitializedEntity::InitializeParameter(Context, 13594 FnDecl->getParamDecl(0)), 13595 SourceLocation(), Args[1]); 13596 if (Arg1.isInvalid()) 13597 return ExprError(); 13598 13599 ExprResult Arg0 = 13600 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13601 Best->FoundDecl, Method); 13602 if (Arg0.isInvalid()) 13603 return ExprError(); 13604 Base = Args[0] = Arg0.getAs<Expr>(); 13605 Args[1] = RHS = Arg1.getAs<Expr>(); 13606 } else { 13607 // Convert the arguments. 13608 ExprResult Arg0 = PerformCopyInitialization( 13609 InitializedEntity::InitializeParameter(Context, 13610 FnDecl->getParamDecl(0)), 13611 SourceLocation(), Args[0]); 13612 if (Arg0.isInvalid()) 13613 return ExprError(); 13614 13615 ExprResult Arg1 = 13616 PerformCopyInitialization( 13617 InitializedEntity::InitializeParameter(Context, 13618 FnDecl->getParamDecl(1)), 13619 SourceLocation(), Args[1]); 13620 if (Arg1.isInvalid()) 13621 return ExprError(); 13622 Args[0] = LHS = Arg0.getAs<Expr>(); 13623 Args[1] = RHS = Arg1.getAs<Expr>(); 13624 } 13625 13626 // Build the actual expression node. 13627 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13628 Best->FoundDecl, Base, 13629 HadMultipleCandidates, OpLoc); 13630 if (FnExpr.isInvalid()) 13631 return ExprError(); 13632 13633 // Determine the result type. 13634 QualType ResultTy = FnDecl->getReturnType(); 13635 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13636 ResultTy = ResultTy.getNonLValueExprType(Context); 13637 13638 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13639 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13640 CurFPFeatureOverrides(), Best->IsADLCandidate); 13641 13642 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13643 FnDecl)) 13644 return ExprError(); 13645 13646 ArrayRef<const Expr *> ArgsArray(Args, 2); 13647 const Expr *ImplicitThis = nullptr; 13648 // Cut off the implicit 'this'. 13649 if (isa<CXXMethodDecl>(FnDecl)) { 13650 ImplicitThis = ArgsArray[0]; 13651 ArgsArray = ArgsArray.slice(1); 13652 } 13653 13654 // Check for a self move. 13655 if (Op == OO_Equal) 13656 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13657 13658 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13659 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13660 VariadicDoesNotApply); 13661 13662 ExprResult R = MaybeBindToTemporary(TheCall); 13663 if (R.isInvalid()) 13664 return ExprError(); 13665 13666 R = CheckForImmediateInvocation(R, FnDecl); 13667 if (R.isInvalid()) 13668 return ExprError(); 13669 13670 // For a rewritten candidate, we've already reversed the arguments 13671 // if needed. Perform the rest of the rewrite now. 13672 if ((Best->RewriteKind & CRK_DifferentOperator) || 13673 (Op == OO_Spaceship && IsReversed)) { 13674 if (Op == OO_ExclaimEqual) { 13675 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13675, __PRETTY_FUNCTION__))
; 13676 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13677 } else { 13678 assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13678, __PRETTY_FUNCTION__))
; 13679 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13680 Expr *ZeroLiteral = 13681 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13682 13683 Sema::CodeSynthesisContext Ctx; 13684 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13685 Ctx.Entity = FnDecl; 13686 pushCodeSynthesisContext(Ctx); 13687 13688 R = CreateOverloadedBinOp( 13689 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13690 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13691 /*AllowRewrittenCandidates=*/false); 13692 13693 popCodeSynthesisContext(); 13694 } 13695 if (R.isInvalid()) 13696 return ExprError(); 13697 } else { 13698 assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast
<void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13698, __PRETTY_FUNCTION__))
; 13699 } 13700 13701 // Make a note in the AST if we did any rewriting. 13702 if (Best->RewriteKind != CRK_None) 13703 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13704 13705 return R; 13706 } else { 13707 // We matched a built-in operator. Convert the arguments, then 13708 // break out so that we will build the appropriate built-in 13709 // operator node. 13710 ExprResult ArgsRes0 = PerformImplicitConversion( 13711 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13712 AA_Passing, CCK_ForBuiltinOverloadedOp); 13713 if (ArgsRes0.isInvalid()) 13714 return ExprError(); 13715 Args[0] = ArgsRes0.get(); 13716 13717 ExprResult ArgsRes1 = PerformImplicitConversion( 13718 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13719 AA_Passing, CCK_ForBuiltinOverloadedOp); 13720 if (ArgsRes1.isInvalid()) 13721 return ExprError(); 13722 Args[1] = ArgsRes1.get(); 13723 break; 13724 } 13725 } 13726 13727 case OR_No_Viable_Function: { 13728 // C++ [over.match.oper]p9: 13729 // If the operator is the operator , [...] and there are no 13730 // viable functions, then the operator is assumed to be the 13731 // built-in operator and interpreted according to clause 5. 13732 if (Opc == BO_Comma) 13733 break; 13734 13735 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13736 // compare result using '==' and '<'. 13737 if (DefaultedFn && Opc == BO_Cmp) { 13738 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13739 Args[1], DefaultedFn); 13740 if (E.isInvalid() || E.isUsable()) 13741 return E; 13742 } 13743 13744 // For class as left operand for assignment or compound assignment 13745 // operator do not fall through to handling in built-in, but report that 13746 // no overloaded assignment operator found 13747 ExprResult Result = ExprError(); 13748 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13749 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13750 Args, OpLoc); 13751 if (Args[0]->getType()->isRecordType() && 13752 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13753 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13754 << BinaryOperator::getOpcodeStr(Opc) 13755 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13756 if (Args[0]->getType()->isIncompleteType()) { 13757 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13758 << Args[0]->getType() 13759 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13760 } 13761 } else { 13762 // This is an erroneous use of an operator which can be overloaded by 13763 // a non-member function. Check for non-member operators which were 13764 // defined too late to be candidates. 13765 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13766 // FIXME: Recover by calling the found function. 13767 return ExprError(); 13768 13769 // No viable function; try to create a built-in operation, which will 13770 // produce an error. Then, show the non-viable candidates. 13771 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13772 } 13773 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13774, __PRETTY_FUNCTION__))
13774 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13774, __PRETTY_FUNCTION__))
; 13775 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13776 return Result; 13777 } 13778 13779 case OR_Ambiguous: 13780 CandidateSet.NoteCandidates( 13781 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13782 << BinaryOperator::getOpcodeStr(Opc) 13783 << Args[0]->getType() 13784 << Args[1]->getType() 13785 << Args[0]->getSourceRange() 13786 << Args[1]->getSourceRange()), 13787 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13788 OpLoc); 13789 return ExprError(); 13790 13791 case OR_Deleted: 13792 if (isImplicitlyDeleted(Best->Function)) { 13793 FunctionDecl *DeletedFD = Best->Function; 13794 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13795 if (DFK.isSpecialMember()) { 13796 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13797 << Args[0]->getType() << DFK.asSpecialMember(); 13798 } else { 13799 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13799, __PRETTY_FUNCTION__))
; 13800 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13801 << Args[0]->getType() << DeletedFD; 13802 } 13803 13804 // The user probably meant to call this special member. Just 13805 // explain why it's deleted. 13806 NoteDeletedFunction(DeletedFD); 13807 return ExprError(); 13808 } 13809 CandidateSet.NoteCandidates( 13810 PartialDiagnosticAt( 13811 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13812 << getOperatorSpelling(Best->Function->getDeclName() 13813 .getCXXOverloadedOperator()) 13814 << Args[0]->getSourceRange() 13815 << Args[1]->getSourceRange()), 13816 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13817 OpLoc); 13818 return ExprError(); 13819 } 13820 13821 // We matched a built-in operator; build it. 13822 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13823} 13824 13825ExprResult Sema::BuildSynthesizedThreeWayComparison( 13826 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13827 FunctionDecl *DefaultedFn) { 13828 const ComparisonCategoryInfo *Info = 13829 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13830 // If we're not producing a known comparison category type, we can't 13831 // synthesize a three-way comparison. Let the caller diagnose this. 13832 if (!Info) 13833 return ExprResult((Expr*)nullptr); 13834 13835 // If we ever want to perform this synthesis more generally, we will need to 13836 // apply the temporary materialization conversion to the operands. 13837 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13838, __PRETTY_FUNCTION__))
13838 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 13838, __PRETTY_FUNCTION__))
; 13839 Expr *OrigLHS = LHS; 13840 Expr *OrigRHS = RHS; 13841 13842 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13843 // each of them multiple times below. 13844 LHS = new (Context) 13845 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13846 LHS->getObjectKind(), LHS); 13847 RHS = new (Context) 13848 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13849 RHS->getObjectKind(), RHS); 13850 13851 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13852 DefaultedFn); 13853 if (Eq.isInvalid()) 13854 return ExprError(); 13855 13856 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13857 true, DefaultedFn); 13858 if (Less.isInvalid()) 13859 return ExprError(); 13860 13861 ExprResult Greater; 13862 if (Info->isPartial()) { 13863 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13864 DefaultedFn); 13865 if (Greater.isInvalid()) 13866 return ExprError(); 13867 } 13868 13869 // Form the list of comparisons we're going to perform. 13870 struct Comparison { 13871 ExprResult Cmp; 13872 ComparisonCategoryResult Result; 13873 } Comparisons[4] = 13874 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13875 : ComparisonCategoryResult::Equivalent}, 13876 {Less, ComparisonCategoryResult::Less}, 13877 {Greater, ComparisonCategoryResult::Greater}, 13878 {ExprResult(), ComparisonCategoryResult::Unordered}, 13879 }; 13880 13881 int I = Info->isPartial() ? 3 : 2; 13882 13883 // Combine the comparisons with suitable conditional expressions. 13884 ExprResult Result; 13885 for (; I >= 0; --I) { 13886 // Build a reference to the comparison category constant. 13887 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13888 // FIXME: Missing a constant for a comparison category. Diagnose this? 13889 if (!VI) 13890 return ExprResult((Expr*)nullptr); 13891 ExprResult ThisResult = 13892 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13893 if (ThisResult.isInvalid()) 13894 return ExprError(); 13895 13896 // Build a conditional unless this is the final case. 13897 if (Result.get()) { 13898 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13899 ThisResult.get(), Result.get()); 13900 if (Result.isInvalid()) 13901 return ExprError(); 13902 } else { 13903 Result = ThisResult; 13904 } 13905 } 13906 13907 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13908 // bind the OpaqueValueExprs before they're (repeatedly) used. 13909 Expr *SyntacticForm = BinaryOperator::Create( 13910 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13911 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13912 CurFPFeatureOverrides()); 13913 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13914 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13915} 13916 13917ExprResult 13918Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13919 SourceLocation RLoc, 13920 Expr *Base, Expr *Idx) { 13921 Expr *Args[2] = { Base, Idx }; 13922 DeclarationName OpName = 13923 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13924 13925 // If either side is type-dependent, create an appropriate dependent 13926 // expression. 13927 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13928 13929 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13930 // CHECKME: no 'operator' keyword? 13931 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13932 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13933 ExprResult Fn = CreateUnresolvedLookupExpr( 13934 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 13935 if (Fn.isInvalid()) 13936 return ExprError(); 13937 // Can't add any actual overloads yet 13938 13939 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 13940 Context.DependentTy, VK_RValue, RLoc, 13941 CurFPFeatureOverrides()); 13942 } 13943 13944 // Handle placeholders on both operands. 13945 if (checkPlaceholderForOverload(*this, Args[0])) 13946 return ExprError(); 13947 if (checkPlaceholderForOverload(*this, Args[1])) 13948 return ExprError(); 13949 13950 // Build an empty overload set. 13951 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13952 13953 // Subscript can only be overloaded as a member function. 13954 13955 // Add operator candidates that are member functions. 13956 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13957 13958 // Add builtin operator candidates. 13959 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13960 13961 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13962 13963 // Perform overload resolution. 13964 OverloadCandidateSet::iterator Best; 13965 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13966 case OR_Success: { 13967 // We found a built-in operator or an overloaded operator. 13968 FunctionDecl *FnDecl = Best->Function; 13969 13970 if (FnDecl) { 13971 // We matched an overloaded operator. Build a call to that 13972 // operator. 13973 13974 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13975 13976 // Convert the arguments. 13977 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13978 ExprResult Arg0 = 13979 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13980 Best->FoundDecl, Method); 13981 if (Arg0.isInvalid()) 13982 return ExprError(); 13983 Args[0] = Arg0.get(); 13984 13985 // Convert the arguments. 13986 ExprResult InputInit 13987 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13988 Context, 13989 FnDecl->getParamDecl(0)), 13990 SourceLocation(), 13991 Args[1]); 13992 if (InputInit.isInvalid()) 13993 return ExprError(); 13994 13995 Args[1] = InputInit.getAs<Expr>(); 13996 13997 // Build the actual expression node. 13998 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13999 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14000 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14001 Best->FoundDecl, 14002 Base, 14003 HadMultipleCandidates, 14004 OpLocInfo.getLoc(), 14005 OpLocInfo.getInfo()); 14006 if (FnExpr.isInvalid()) 14007 return ExprError(); 14008 14009 // Determine the result type 14010 QualType ResultTy = FnDecl->getReturnType(); 14011 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14012 ResultTy = ResultTy.getNonLValueExprType(Context); 14013 14014 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14015 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14016 CurFPFeatureOverrides()); 14017 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14018 return ExprError(); 14019 14020 if (CheckFunctionCall(Method, TheCall, 14021 Method->getType()->castAs<FunctionProtoType>())) 14022 return ExprError(); 14023 14024 return MaybeBindToTemporary(TheCall); 14025 } else { 14026 // We matched a built-in operator. Convert the arguments, then 14027 // break out so that we will build the appropriate built-in 14028 // operator node. 14029 ExprResult ArgsRes0 = PerformImplicitConversion( 14030 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14031 AA_Passing, CCK_ForBuiltinOverloadedOp); 14032 if (ArgsRes0.isInvalid()) 14033 return ExprError(); 14034 Args[0] = ArgsRes0.get(); 14035 14036 ExprResult ArgsRes1 = PerformImplicitConversion( 14037 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14038 AA_Passing, CCK_ForBuiltinOverloadedOp); 14039 if (ArgsRes1.isInvalid()) 14040 return ExprError(); 14041 Args[1] = ArgsRes1.get(); 14042 14043 break; 14044 } 14045 } 14046 14047 case OR_No_Viable_Function: { 14048 PartialDiagnostic PD = CandidateSet.empty() 14049 ? (PDiag(diag::err_ovl_no_oper) 14050 << Args[0]->getType() << /*subscript*/ 0 14051 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14052 : (PDiag(diag::err_ovl_no_viable_subscript) 14053 << Args[0]->getType() << Args[0]->getSourceRange() 14054 << Args[1]->getSourceRange()); 14055 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14056 OCD_AllCandidates, Args, "[]", LLoc); 14057 return ExprError(); 14058 } 14059 14060 case OR_Ambiguous: 14061 CandidateSet.NoteCandidates( 14062 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14063 << "[]" << Args[0]->getType() 14064 << Args[1]->getType() 14065 << Args[0]->getSourceRange() 14066 << Args[1]->getSourceRange()), 14067 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14068 return ExprError(); 14069 14070 case OR_Deleted: 14071 CandidateSet.NoteCandidates( 14072 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14073 << "[]" << Args[0]->getSourceRange() 14074 << Args[1]->getSourceRange()), 14075 *this, OCD_AllCandidates, Args, "[]", LLoc); 14076 return ExprError(); 14077 } 14078 14079 // We matched a built-in operator; build it. 14080 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14081} 14082 14083/// BuildCallToMemberFunction - Build a call to a member 14084/// function. MemExpr is the expression that refers to the member 14085/// function (and includes the object parameter), Args/NumArgs are the 14086/// arguments to the function call (not including the object 14087/// parameter). The caller needs to validate that the member 14088/// expression refers to a non-static member function or an overloaded 14089/// member function. 14090ExprResult 14091Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14092 SourceLocation LParenLoc, 14093 MultiExprArg Args, 14094 SourceLocation RParenLoc) { 14095 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14096, __PRETTY_FUNCTION__))
14096 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14096, __PRETTY_FUNCTION__))
; 14097 14098 // Dig out the member expression. This holds both the object 14099 // argument and the member function we're referring to. 14100 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14101 14102 // Determine whether this is a call to a pointer-to-member function. 14103 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14104 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14104, __PRETTY_FUNCTION__))
; 14105 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14105, __PRETTY_FUNCTION__))
; 14106 14107 QualType fnType = 14108 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14109 14110 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14111 QualType resultType = proto->getCallResultType(Context); 14112 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14113 14114 // Check that the object type isn't more qualified than the 14115 // member function we're calling. 14116 Qualifiers funcQuals = proto->getMethodQuals(); 14117 14118 QualType objectType = op->getLHS()->getType(); 14119 if (op->getOpcode() == BO_PtrMemI) 14120 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14121 Qualifiers objectQuals = objectType.getQualifiers(); 14122 14123 Qualifiers difference = objectQuals - funcQuals; 14124 difference.removeObjCGCAttr(); 14125 difference.removeAddressSpace(); 14126 if (difference) { 14127 std::string qualsString = difference.getAsString(); 14128 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14129 << fnType.getUnqualifiedType() 14130 << qualsString 14131 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14132 } 14133 14134 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14135 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14136 CurFPFeatureOverrides(), proto->getNumParams()); 14137 14138 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14139 call, nullptr)) 14140 return ExprError(); 14141 14142 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14143 return ExprError(); 14144 14145 if (CheckOtherCall(call, proto)) 14146 return ExprError(); 14147 14148 return MaybeBindToTemporary(call); 14149 } 14150 14151 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14152 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14153 RParenLoc, CurFPFeatureOverrides()); 14154 14155 UnbridgedCastsSet UnbridgedCasts; 14156 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14157 return ExprError(); 14158 14159 MemberExpr *MemExpr; 14160 CXXMethodDecl *Method = nullptr; 14161 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14162 NestedNameSpecifier *Qualifier = nullptr; 14163 if (isa<MemberExpr>(NakedMemExpr)) { 14164 MemExpr = cast<MemberExpr>(NakedMemExpr); 14165 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14166 FoundDecl = MemExpr->getFoundDecl(); 14167 Qualifier = MemExpr->getQualifier(); 14168 UnbridgedCasts.restore(); 14169 } else { 14170 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14171 Qualifier = UnresExpr->getQualifier(); 14172 14173 QualType ObjectType = UnresExpr->getBaseType(); 14174 Expr::Classification ObjectClassification 14175 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14176 : UnresExpr->getBase()->Classify(Context); 14177 14178 // Add overload candidates 14179 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14180 OverloadCandidateSet::CSK_Normal); 14181 14182 // FIXME: avoid copy. 14183 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14184 if (UnresExpr->hasExplicitTemplateArgs()) { 14185 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14186 TemplateArgs = &TemplateArgsBuffer; 14187 } 14188 14189 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14190 E = UnresExpr->decls_end(); I != E; ++I) { 14191 14192 NamedDecl *Func = *I; 14193 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14194 if (isa<UsingShadowDecl>(Func)) 14195 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14196 14197 14198 // Microsoft supports direct constructor calls. 14199 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14200 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14201 CandidateSet, 14202 /*SuppressUserConversions*/ false); 14203 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14204 // If explicit template arguments were provided, we can't call a 14205 // non-template member function. 14206 if (TemplateArgs) 14207 continue; 14208 14209 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14210 ObjectClassification, Args, CandidateSet, 14211 /*SuppressUserConversions=*/false); 14212 } else { 14213 AddMethodTemplateCandidate( 14214 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14215 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14216 /*SuppressUserConversions=*/false); 14217 } 14218 } 14219 14220 DeclarationName DeclName = UnresExpr->getMemberName(); 14221 14222 UnbridgedCasts.restore(); 14223 14224 OverloadCandidateSet::iterator Best; 14225 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14226 Best)) { 14227 case OR_Success: 14228 Method = cast<CXXMethodDecl>(Best->Function); 14229 FoundDecl = Best->FoundDecl; 14230 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14231 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14232 return ExprError(); 14233 // If FoundDecl is different from Method (such as if one is a template 14234 // and the other a specialization), make sure DiagnoseUseOfDecl is 14235 // called on both. 14236 // FIXME: This would be more comprehensively addressed by modifying 14237 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14238 // being used. 14239 if (Method != FoundDecl.getDecl() && 14240 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14241 return ExprError(); 14242 break; 14243 14244 case OR_No_Viable_Function: 14245 CandidateSet.NoteCandidates( 14246 PartialDiagnosticAt( 14247 UnresExpr->getMemberLoc(), 14248 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14249 << DeclName << MemExprE->getSourceRange()), 14250 *this, OCD_AllCandidates, Args); 14251 // FIXME: Leaking incoming expressions! 14252 return ExprError(); 14253 14254 case OR_Ambiguous: 14255 CandidateSet.NoteCandidates( 14256 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14257 PDiag(diag::err_ovl_ambiguous_member_call) 14258 << DeclName << MemExprE->getSourceRange()), 14259 *this, OCD_AmbiguousCandidates, Args); 14260 // FIXME: Leaking incoming expressions! 14261 return ExprError(); 14262 14263 case OR_Deleted: 14264 CandidateSet.NoteCandidates( 14265 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14266 PDiag(diag::err_ovl_deleted_member_call) 14267 << DeclName << MemExprE->getSourceRange()), 14268 *this, OCD_AllCandidates, Args); 14269 // FIXME: Leaking incoming expressions! 14270 return ExprError(); 14271 } 14272 14273 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14274 14275 // If overload resolution picked a static member, build a 14276 // non-member call based on that function. 14277 if (Method->isStatic()) { 14278 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14279 RParenLoc); 14280 } 14281 14282 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14283 } 14284 14285 QualType ResultType = Method->getReturnType(); 14286 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14287 ResultType = ResultType.getNonLValueExprType(Context); 14288 14289 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14289, __PRETTY_FUNCTION__))
; 14290 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14291 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14292 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14293 CurFPFeatureOverrides(), Proto->getNumParams()); 14294 14295 // Check for a valid return type. 14296 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14297 TheCall, Method)) 14298 return ExprError(); 14299 14300 // Convert the object argument (for a non-static member function call). 14301 // We only need to do this if there was actually an overload; otherwise 14302 // it was done at lookup. 14303 if (!Method->isStatic()) { 14304 ExprResult ObjectArg = 14305 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14306 FoundDecl, Method); 14307 if (ObjectArg.isInvalid()) 14308 return ExprError(); 14309 MemExpr->setBase(ObjectArg.get()); 14310 } 14311 14312 // Convert the rest of the arguments 14313 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14314 RParenLoc)) 14315 return ExprError(); 14316 14317 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14318 14319 if (CheckFunctionCall(Method, TheCall, Proto)) 14320 return ExprError(); 14321 14322 // In the case the method to call was not selected by the overloading 14323 // resolution process, we still need to handle the enable_if attribute. Do 14324 // that here, so it will not hide previous -- and more relevant -- errors. 14325 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14326 if (const EnableIfAttr *Attr = 14327 CheckEnableIf(Method, LParenLoc, Args, true)) { 14328 Diag(MemE->getMemberLoc(), 14329 diag::err_ovl_no_viable_member_function_in_call) 14330 << Method << Method->getSourceRange(); 14331 Diag(Method->getLocation(), 14332 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14333 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14334 return ExprError(); 14335 } 14336 } 14337 14338 if ((isa<CXXConstructorDecl>(CurContext) || 14339 isa<CXXDestructorDecl>(CurContext)) && 14340 TheCall->getMethodDecl()->isPure()) { 14341 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14342 14343 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14344 MemExpr->performsVirtualDispatch(getLangOpts())) { 14345 Diag(MemExpr->getBeginLoc(), 14346 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14347 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14348 << MD->getParent(); 14349 14350 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14351 if (getLangOpts().AppleKext) 14352 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14353 << MD->getParent() << MD->getDeclName(); 14354 } 14355 } 14356 14357 if (CXXDestructorDecl *DD = 14358 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14359 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14360 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14361 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14362 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14363 MemExpr->getMemberLoc()); 14364 } 14365 14366 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14367 TheCall->getMethodDecl()); 14368} 14369 14370/// BuildCallToObjectOfClassType - Build a call to an object of class 14371/// type (C++ [over.call.object]), which can end up invoking an 14372/// overloaded function call operator (@c operator()) or performing a 14373/// user-defined conversion on the object argument. 14374ExprResult 14375Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14376 SourceLocation LParenLoc, 14377 MultiExprArg Args, 14378 SourceLocation RParenLoc) { 14379 if (checkPlaceholderForOverload(*this, Obj)) 14380 return ExprError(); 14381 ExprResult Object = Obj; 14382 14383 UnbridgedCastsSet UnbridgedCasts; 14384 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14385 return ExprError(); 14386 14387 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14388, __PRETTY_FUNCTION__))
14388 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14388, __PRETTY_FUNCTION__))
; 14389 14390 // C++ [over.call.object]p1: 14391 // If the primary-expression E in the function call syntax 14392 // evaluates to a class object of type "cv T", then the set of 14393 // candidate functions includes at least the function call 14394 // operators of T. The function call operators of T are obtained by 14395 // ordinary lookup of the name operator() in the context of 14396 // (E).operator(). 14397 OverloadCandidateSet CandidateSet(LParenLoc, 14398 OverloadCandidateSet::CSK_Operator); 14399 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14400 14401 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14402 diag::err_incomplete_object_call, Object.get())) 14403 return true; 14404 14405 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14406 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14407 LookupQualifiedName(R, Record->getDecl()); 14408 R.suppressDiagnostics(); 14409 14410 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14411 Oper != OperEnd; ++Oper) { 14412 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14413 Object.get()->Classify(Context), Args, CandidateSet, 14414 /*SuppressUserConversion=*/false); 14415 } 14416 14417 // C++ [over.call.object]p2: 14418 // In addition, for each (non-explicit in C++0x) conversion function 14419 // declared in T of the form 14420 // 14421 // operator conversion-type-id () cv-qualifier; 14422 // 14423 // where cv-qualifier is the same cv-qualification as, or a 14424 // greater cv-qualification than, cv, and where conversion-type-id 14425 // denotes the type "pointer to function of (P1,...,Pn) returning 14426 // R", or the type "reference to pointer to function of 14427 // (P1,...,Pn) returning R", or the type "reference to function 14428 // of (P1,...,Pn) returning R", a surrogate call function [...] 14429 // is also considered as a candidate function. Similarly, 14430 // surrogate call functions are added to the set of candidate 14431 // functions for each conversion function declared in an 14432 // accessible base class provided the function is not hidden 14433 // within T by another intervening declaration. 14434 const auto &Conversions = 14435 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14436 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14437 NamedDecl *D = *I; 14438 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14439 if (isa<UsingShadowDecl>(D)) 14440 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14441 14442 // Skip over templated conversion functions; they aren't 14443 // surrogates. 14444 if (isa<FunctionTemplateDecl>(D)) 14445 continue; 14446 14447 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14448 if (!Conv->isExplicit()) { 14449 // Strip the reference type (if any) and then the pointer type (if 14450 // any) to get down to what might be a function type. 14451 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14452 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14453 ConvType = ConvPtrType->getPointeeType(); 14454 14455 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14456 { 14457 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14458 Object.get(), Args, CandidateSet); 14459 } 14460 } 14461 } 14462 14463 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14464 14465 // Perform overload resolution. 14466 OverloadCandidateSet::iterator Best; 14467 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14468 Best)) { 14469 case OR_Success: 14470 // Overload resolution succeeded; we'll build the appropriate call 14471 // below. 14472 break; 14473 14474 case OR_No_Viable_Function: { 14475 PartialDiagnostic PD = 14476 CandidateSet.empty() 14477 ? (PDiag(diag::err_ovl_no_oper) 14478 << Object.get()->getType() << /*call*/ 1 14479 << Object.get()->getSourceRange()) 14480 : (PDiag(diag::err_ovl_no_viable_object_call) 14481 << Object.get()->getType() << Object.get()->getSourceRange()); 14482 CandidateSet.NoteCandidates( 14483 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14484 OCD_AllCandidates, Args); 14485 break; 14486 } 14487 case OR_Ambiguous: 14488 CandidateSet.NoteCandidates( 14489 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14490 PDiag(diag::err_ovl_ambiguous_object_call) 14491 << Object.get()->getType() 14492 << Object.get()->getSourceRange()), 14493 *this, OCD_AmbiguousCandidates, Args); 14494 break; 14495 14496 case OR_Deleted: 14497 CandidateSet.NoteCandidates( 14498 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14499 PDiag(diag::err_ovl_deleted_object_call) 14500 << Object.get()->getType() 14501 << Object.get()->getSourceRange()), 14502 *this, OCD_AllCandidates, Args); 14503 break; 14504 } 14505 14506 if (Best == CandidateSet.end()) 14507 return true; 14508 14509 UnbridgedCasts.restore(); 14510 14511 if (Best->Function == nullptr) { 14512 // Since there is no function declaration, this is one of the 14513 // surrogate candidates. Dig out the conversion function. 14514 CXXConversionDecl *Conv 14515 = cast<CXXConversionDecl>( 14516 Best->Conversions[0].UserDefined.ConversionFunction); 14517 14518 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14519 Best->FoundDecl); 14520 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14521 return ExprError(); 14522 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14523, __PRETTY_FUNCTION__))
14523 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14523, __PRETTY_FUNCTION__))
; 14524 // We selected one of the surrogate functions that converts the 14525 // object parameter to a function pointer. Perform the conversion 14526 // on the object argument, then let BuildCallExpr finish the job. 14527 14528 // Create an implicit member expr to refer to the conversion operator. 14529 // and then call it. 14530 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14531 Conv, HadMultipleCandidates); 14532 if (Call.isInvalid()) 14533 return ExprError(); 14534 // Record usage of conversion in an implicit cast. 14535 Call = ImplicitCastExpr::Create( 14536 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14537 nullptr, VK_RValue, CurFPFeatureOverrides()); 14538 14539 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14540 } 14541 14542 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14543 14544 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14545 // that calls this method, using Object for the implicit object 14546 // parameter and passing along the remaining arguments. 14547 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14548 14549 // An error diagnostic has already been printed when parsing the declaration. 14550 if (Method->isInvalidDecl()) 14551 return ExprError(); 14552 14553 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14554 unsigned NumParams = Proto->getNumParams(); 14555 14556 DeclarationNameInfo OpLocInfo( 14557 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14558 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14559 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14560 Obj, HadMultipleCandidates, 14561 OpLocInfo.getLoc(), 14562 OpLocInfo.getInfo()); 14563 if (NewFn.isInvalid()) 14564 return true; 14565 14566 // The number of argument slots to allocate in the call. If we have default 14567 // arguments we need to allocate space for them as well. We additionally 14568 // need one more slot for the object parameter. 14569 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14570 14571 // Build the full argument list for the method call (the implicit object 14572 // parameter is placed at the beginning of the list). 14573 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14574 14575 bool IsError = false; 14576 14577 // Initialize the implicit object parameter. 14578 ExprResult ObjRes = 14579 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14580 Best->FoundDecl, Method); 14581 if (ObjRes.isInvalid()) 14582 IsError = true; 14583 else 14584 Object = ObjRes; 14585 MethodArgs[0] = Object.get(); 14586 14587 // Check the argument types. 14588 for (unsigned i = 0; i != NumParams; i++) { 14589 Expr *Arg; 14590 if (i < Args.size()) { 14591 Arg = Args[i]; 14592 14593 // Pass the argument. 14594 14595 ExprResult InputInit 14596 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14597 Context, 14598 Method->getParamDecl(i)), 14599 SourceLocation(), Arg); 14600 14601 IsError |= InputInit.isInvalid(); 14602 Arg = InputInit.getAs<Expr>(); 14603 } else { 14604 ExprResult DefArg 14605 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14606 if (DefArg.isInvalid()) { 14607 IsError = true; 14608 break; 14609 } 14610 14611 Arg = DefArg.getAs<Expr>(); 14612 } 14613 14614 MethodArgs[i + 1] = Arg; 14615 } 14616 14617 // If this is a variadic call, handle args passed through "...". 14618 if (Proto->isVariadic()) { 14619 // Promote the arguments (C99 6.5.2.2p7). 14620 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14621 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14622 nullptr); 14623 IsError |= Arg.isInvalid(); 14624 MethodArgs[i + 1] = Arg.get(); 14625 } 14626 } 14627 14628 if (IsError) 14629 return true; 14630 14631 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14632 14633 // Once we've built TheCall, all of the expressions are properly owned. 14634 QualType ResultTy = Method->getReturnType(); 14635 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14636 ResultTy = ResultTy.getNonLValueExprType(Context); 14637 14638 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14639 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14640 CurFPFeatureOverrides()); 14641 14642 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14643 return true; 14644 14645 if (CheckFunctionCall(Method, TheCall, Proto)) 14646 return true; 14647 14648 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14649} 14650 14651/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14652/// (if one exists), where @c Base is an expression of class type and 14653/// @c Member is the name of the member we're trying to find. 14654ExprResult 14655Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14656 bool *NoArrowOperatorFound) { 14657 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14658, __PRETTY_FUNCTION__))
14658 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14658, __PRETTY_FUNCTION__))
; 14659 14660 if (checkPlaceholderForOverload(*this, Base)) 14661 return ExprError(); 14662 14663 SourceLocation Loc = Base->getExprLoc(); 14664 14665 // C++ [over.ref]p1: 14666 // 14667 // [...] An expression x->m is interpreted as (x.operator->())->m 14668 // for a class object x of type T if T::operator->() exists and if 14669 // the operator is selected as the best match function by the 14670 // overload resolution mechanism (13.3). 14671 DeclarationName OpName = 14672 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14673 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14674 14675 if (RequireCompleteType(Loc, Base->getType(), 14676 diag::err_typecheck_incomplete_tag, Base)) 14677 return ExprError(); 14678 14679 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14680 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14681 R.suppressDiagnostics(); 14682 14683 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14684 Oper != OperEnd; ++Oper) { 14685 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14686 None, CandidateSet, /*SuppressUserConversion=*/false); 14687 } 14688 14689 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14690 14691 // Perform overload resolution. 14692 OverloadCandidateSet::iterator Best; 14693 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14694 case OR_Success: 14695 // Overload resolution succeeded; we'll build the call below. 14696 break; 14697 14698 case OR_No_Viable_Function: { 14699 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14700 if (CandidateSet.empty()) { 14701 QualType BaseType = Base->getType(); 14702 if (NoArrowOperatorFound) { 14703 // Report this specific error to the caller instead of emitting a 14704 // diagnostic, as requested. 14705 *NoArrowOperatorFound = true; 14706 return ExprError(); 14707 } 14708 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14709 << BaseType << Base->getSourceRange(); 14710 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14711 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14712 << FixItHint::CreateReplacement(OpLoc, "."); 14713 } 14714 } else 14715 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14716 << "operator->" << Base->getSourceRange(); 14717 CandidateSet.NoteCandidates(*this, Base, Cands); 14718 return ExprError(); 14719 } 14720 case OR_Ambiguous: 14721 CandidateSet.NoteCandidates( 14722 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14723 << "->" << Base->getType() 14724 << Base->getSourceRange()), 14725 *this, OCD_AmbiguousCandidates, Base); 14726 return ExprError(); 14727 14728 case OR_Deleted: 14729 CandidateSet.NoteCandidates( 14730 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14731 << "->" << Base->getSourceRange()), 14732 *this, OCD_AllCandidates, Base); 14733 return ExprError(); 14734 } 14735 14736 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14737 14738 // Convert the object parameter. 14739 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14740 ExprResult BaseResult = 14741 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14742 Best->FoundDecl, Method); 14743 if (BaseResult.isInvalid()) 14744 return ExprError(); 14745 Base = BaseResult.get(); 14746 14747 // Build the operator call. 14748 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14749 Base, HadMultipleCandidates, OpLoc); 14750 if (FnExpr.isInvalid()) 14751 return ExprError(); 14752 14753 QualType ResultTy = Method->getReturnType(); 14754 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14755 ResultTy = ResultTy.getNonLValueExprType(Context); 14756 CXXOperatorCallExpr *TheCall = 14757 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14758 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14759 14760 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14761 return ExprError(); 14762 14763 if (CheckFunctionCall(Method, TheCall, 14764 Method->getType()->castAs<FunctionProtoType>())) 14765 return ExprError(); 14766 14767 return MaybeBindToTemporary(TheCall); 14768} 14769 14770/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14771/// a literal operator described by the provided lookup results. 14772ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14773 DeclarationNameInfo &SuffixInfo, 14774 ArrayRef<Expr*> Args, 14775 SourceLocation LitEndLoc, 14776 TemplateArgumentListInfo *TemplateArgs) { 14777 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14778 14779 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14780 OverloadCandidateSet::CSK_Normal); 14781 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14782 TemplateArgs); 14783 14784 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14785 14786 // Perform overload resolution. This will usually be trivial, but might need 14787 // to perform substitutions for a literal operator template. 14788 OverloadCandidateSet::iterator Best; 14789 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14790 case OR_Success: 14791 case OR_Deleted: 14792 break; 14793 14794 case OR_No_Viable_Function: 14795 CandidateSet.NoteCandidates( 14796 PartialDiagnosticAt(UDSuffixLoc, 14797 PDiag(diag::err_ovl_no_viable_function_in_call) 14798 << R.getLookupName()), 14799 *this, OCD_AllCandidates, Args); 14800 return ExprError(); 14801 14802 case OR_Ambiguous: 14803 CandidateSet.NoteCandidates( 14804 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14805 << R.getLookupName()), 14806 *this, OCD_AmbiguousCandidates, Args); 14807 return ExprError(); 14808 } 14809 14810 FunctionDecl *FD = Best->Function; 14811 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14812 nullptr, HadMultipleCandidates, 14813 SuffixInfo.getLoc(), 14814 SuffixInfo.getInfo()); 14815 if (Fn.isInvalid()) 14816 return true; 14817 14818 // Check the argument types. This should almost always be a no-op, except 14819 // that array-to-pointer decay is applied to string literals. 14820 Expr *ConvArgs[2]; 14821 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14822 ExprResult InputInit = PerformCopyInitialization( 14823 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14824 SourceLocation(), Args[ArgIdx]); 14825 if (InputInit.isInvalid()) 14826 return true; 14827 ConvArgs[ArgIdx] = InputInit.get(); 14828 } 14829 14830 QualType ResultTy = FD->getReturnType(); 14831 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14832 ResultTy = ResultTy.getNonLValueExprType(Context); 14833 14834 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14835 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14836 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14837 14838 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14839 return ExprError(); 14840 14841 if (CheckFunctionCall(FD, UDL, nullptr)) 14842 return ExprError(); 14843 14844 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14845} 14846 14847/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14848/// given LookupResult is non-empty, it is assumed to describe a member which 14849/// will be invoked. Otherwise, the function will be found via argument 14850/// dependent lookup. 14851/// CallExpr is set to a valid expression and FRS_Success returned on success, 14852/// otherwise CallExpr is set to ExprError() and some non-success value 14853/// is returned. 14854Sema::ForRangeStatus 14855Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14856 SourceLocation RangeLoc, 14857 const DeclarationNameInfo &NameInfo, 14858 LookupResult &MemberLookup, 14859 OverloadCandidateSet *CandidateSet, 14860 Expr *Range, ExprResult *CallExpr) { 14861 Scope *S = nullptr; 14862 14863 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14864 if (!MemberLookup.empty()) { 14865 ExprResult MemberRef = 14866 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14867 /*IsPtr=*/false, CXXScopeSpec(), 14868 /*TemplateKWLoc=*/SourceLocation(), 14869 /*FirstQualifierInScope=*/nullptr, 14870 MemberLookup, 14871 /*TemplateArgs=*/nullptr, S); 14872 if (MemberRef.isInvalid()) { 14873 *CallExpr = ExprError(); 14874 return FRS_DiagnosticIssued; 14875 } 14876 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14877 if (CallExpr->isInvalid()) { 14878 *CallExpr = ExprError(); 14879 return FRS_DiagnosticIssued; 14880 } 14881 } else { 14882 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14883 NestedNameSpecifierLoc(), 14884 NameInfo, UnresolvedSet<0>()); 14885 if (FnR.isInvalid()) 14886 return FRS_DiagnosticIssued; 14887 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14888 14889 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14890 CandidateSet, CallExpr); 14891 if (CandidateSet->empty() || CandidateSetError) { 14892 *CallExpr = ExprError(); 14893 return FRS_NoViableFunction; 14894 } 14895 OverloadCandidateSet::iterator Best; 14896 OverloadingResult OverloadResult = 14897 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14898 14899 if (OverloadResult == OR_No_Viable_Function) { 14900 *CallExpr = ExprError(); 14901 return FRS_NoViableFunction; 14902 } 14903 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14904 Loc, nullptr, CandidateSet, &Best, 14905 OverloadResult, 14906 /*AllowTypoCorrection=*/false); 14907 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14908 *CallExpr = ExprError(); 14909 return FRS_DiagnosticIssued; 14910 } 14911 } 14912 return FRS_Success; 14913} 14914 14915 14916/// FixOverloadedFunctionReference - E is an expression that refers to 14917/// a C++ overloaded function (possibly with some parentheses and 14918/// perhaps a '&' around it). We have resolved the overloaded function 14919/// to the function declaration Fn, so patch up the expression E to 14920/// refer (possibly indirectly) to Fn. Returns the new expr. 14921Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14922 FunctionDecl *Fn) { 14923 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14924 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14925 Found, Fn); 14926 if (SubExpr == PE->getSubExpr()) 14927 return PE; 14928 14929 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14930 } 14931 14932 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14933 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14934 Found, Fn); 14935 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14937, __PRETTY_FUNCTION__))
14936 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14937, __PRETTY_FUNCTION__))
14937 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14937, __PRETTY_FUNCTION__))
; 14938 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14938, __PRETTY_FUNCTION__))
; 14939 if (SubExpr == ICE->getSubExpr()) 14940 return ICE; 14941 14942 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 14943 SubExpr, nullptr, ICE->getValueKind(), 14944 CurFPFeatureOverrides()); 14945 } 14946 14947 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14948 if (!GSE->isResultDependent()) { 14949 Expr *SubExpr = 14950 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14951 if (SubExpr == GSE->getResultExpr()) 14952 return GSE; 14953 14954 // Replace the resulting type information before rebuilding the generic 14955 // selection expression. 14956 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14957 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14958 unsigned ResultIdx = GSE->getResultIndex(); 14959 AssocExprs[ResultIdx] = SubExpr; 14960 14961 return GenericSelectionExpr::Create( 14962 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14963 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14964 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14965 ResultIdx); 14966 } 14967 // Rather than fall through to the unreachable, return the original generic 14968 // selection expression. 14969 return GSE; 14970 } 14971 14972 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14973 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14974, __PRETTY_FUNCTION__))
14974 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14974, __PRETTY_FUNCTION__))
; 14975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14976 if (Method->isStatic()) { 14977 // Do nothing: static member functions aren't any different 14978 // from non-member functions. 14979 } else { 14980 // Fix the subexpression, which really has to be an 14981 // UnresolvedLookupExpr holding an overloaded member function 14982 // or template. 14983 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14984 Found, Fn); 14985 if (SubExpr == UnOp->getSubExpr()) 14986 return UnOp; 14987 14988 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14989, __PRETTY_FUNCTION__))
14989 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14989, __PRETTY_FUNCTION__))
; 14990 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14991, __PRETTY_FUNCTION__))
14991 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 14991, __PRETTY_FUNCTION__))
; 14992 14993 // We have taken the address of a pointer to member 14994 // function. Perform the computation here so that we get the 14995 // appropriate pointer to member type. 14996 QualType ClassType 14997 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14998 QualType MemPtrType 14999 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15000 // Under the MS ABI, lock down the inheritance model now. 15001 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15002 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15003 15004 return UnaryOperator::Create( 15005 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 15006 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15007 } 15008 } 15009 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15010 Found, Fn); 15011 if (SubExpr == UnOp->getSubExpr()) 15012 return UnOp; 15013 15014 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 15015 Context.getPointerType(SubExpr->getType()), 15016 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 15017 false, CurFPFeatureOverrides()); 15018 } 15019 15020 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15021 // FIXME: avoid copy. 15022 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15023 if (ULE->hasExplicitTemplateArgs()) { 15024 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15025 TemplateArgs = &TemplateArgsBuffer; 15026 } 15027 15028 DeclRefExpr *DRE = 15029 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15030 ULE->getQualifierLoc(), Found.getDecl(), 15031 ULE->getTemplateKeywordLoc(), TemplateArgs); 15032 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15033 return DRE; 15034 } 15035 15036 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15037 // FIXME: avoid copy. 15038 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15039 if (MemExpr->hasExplicitTemplateArgs()) { 15040 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15041 TemplateArgs = &TemplateArgsBuffer; 15042 } 15043 15044 Expr *Base; 15045 15046 // If we're filling in a static method where we used to have an 15047 // implicit member access, rewrite to a simple decl ref. 15048 if (MemExpr->isImplicitAccess()) { 15049 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15050 DeclRefExpr *DRE = BuildDeclRefExpr( 15051 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15052 MemExpr->getQualifierLoc(), Found.getDecl(), 15053 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15054 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15055 return DRE; 15056 } else { 15057 SourceLocation Loc = MemExpr->getMemberLoc(); 15058 if (MemExpr->getQualifier()) 15059 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15060 Base = 15061 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15062 } 15063 } else 15064 Base = MemExpr->getBase(); 15065 15066 ExprValueKind valueKind; 15067 QualType type; 15068 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15069 valueKind = VK_LValue; 15070 type = Fn->getType(); 15071 } else { 15072 valueKind = VK_RValue; 15073 type = Context.BoundMemberTy; 15074 } 15075 15076 return BuildMemberExpr( 15077 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15078 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15079 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15080 type, valueKind, OK_Ordinary, TemplateArgs); 15081 } 15082 15083 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp"
, 15083)
; 15084} 15085 15086ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15087 DeclAccessPair Found, 15088 FunctionDecl *Fn) { 15089 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15090}

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
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/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class Type;
65
66enum {
67 TypeAlignmentInBits = 4,
68 TypeAlignment = 1 << TypeAlignmentInBits
69};
70
71namespace serialization {
72 template <class T> class AbstractTypeReader;
73 template <class T> class AbstractTypeWriter;
74}
75
76} // namespace clang
77
78namespace llvm {
79
80 template <typename T>
81 struct PointerLikeTypeTraits;
82 template<>
83 struct PointerLikeTypeTraits< ::clang::Type*> {
84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
85
86 static inline ::clang::Type *getFromVoidPointer(void *P) {
87 return static_cast< ::clang::Type*>(P);
88 }
89
90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
91 };
92
93 template<>
94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
96
97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
98 return static_cast< ::clang::ExtQuals*>(P);
99 }
100
101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
102 };
103
104} // namespace llvm
105
106namespace clang {
107
108class ASTContext;
109template <typename> class CanQual;
110class CXXRecordDecl;
111class DeclContext;
112class EnumDecl;
113class Expr;
114class ExtQualsTypeCommonBase;
115class FunctionDecl;
116class IdentifierInfo;
117class NamedDecl;
118class ObjCInterfaceDecl;
119class ObjCProtocolDecl;
120class ObjCTypeParamDecl;
121struct PrintingPolicy;
122class RecordDecl;
123class Stmt;
124class TagDecl;
125class TemplateArgument;
126class TemplateArgumentListInfo;
127class TemplateArgumentLoc;
128class TemplateTypeParmDecl;
129class TypedefNameDecl;
130class UnresolvedUsingTypenameDecl;
131
132using CanQualType = CanQual<Type>;
133
134// Provide forward declarations for all of the *Type classes.
135#define TYPE(Class, Base) class Class##Type;
136#include "clang/AST/TypeNodes.inc"
137
138/// The collection of all-type qualifiers we support.
139/// Clang supports five independent qualifiers:
140/// * C99: const, volatile, and restrict
141/// * MS: __unaligned
142/// * Embedded C (TR18037): address spaces
143/// * Objective C: the GC attributes (none, weak, or strong)
144class Qualifiers {
145public:
146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 Const = 0x1,
148 Restrict = 0x2,
149 Volatile = 0x4,
150 CVRMask = Const | Volatile | Restrict
151 };
152
153 enum GC {
154 GCNone = 0,
155 Weak,
156 Strong
157 };
158
159 enum ObjCLifetime {
160 /// There is no lifetime qualification on this type.
161 OCL_None,
162
163 /// This object can be modified without requiring retains or
164 /// releases.
165 OCL_ExplicitNone,
166
167 /// Assigning into this object requires the old value to be
168 /// released and the new value to be retained. The timing of the
169 /// release of the old value is inexact: it may be moved to
170 /// immediately after the last known point where the value is
171 /// live.
172 OCL_Strong,
173
174 /// Reading or writing from this object requires a barrier call.
175 OCL_Weak,
176
177 /// Assigning into this object requires a lifetime extension.
178 OCL_Autoreleasing
179 };
180
181 enum {
182 /// The maximum supported address space number.
183 /// 23 bits should be enough for anyone.
184 MaxAddressSpace = 0x7fffffu,
185
186 /// The width of the "fast" qualifier mask.
187 FastWidth = 3,
188
189 /// The fast qualifier mask.
190 FastMask = (1 << FastWidth) - 1
191 };
192
193 /// Returns the common set of qualifiers while removing them from
194 /// the given sets.
195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
196 // If both are only CVR-qualified, bit operations are sufficient.
197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
198 Qualifiers Q;
199 Q.Mask = L.Mask & R.Mask;
200 L.Mask &= ~Q.Mask;
201 R.Mask &= ~Q.Mask;
202 return Q;
203 }
204
205 Qualifiers Q;
206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
207 Q.addCVRQualifiers(CommonCRV);
208 L.removeCVRQualifiers(CommonCRV);
209 R.removeCVRQualifiers(CommonCRV);
210
211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
212 Q.setObjCGCAttr(L.getObjCGCAttr());
213 L.removeObjCGCAttr();
214 R.removeObjCGCAttr();
215 }
216
217 if (L.getObjCLifetime() == R.getObjCLifetime()) {
218 Q.setObjCLifetime(L.getObjCLifetime());
219 L.removeObjCLifetime();
220 R.removeObjCLifetime();
221 }
222
223 if (L.getAddressSpace() == R.getAddressSpace()) {
224 Q.setAddressSpace(L.getAddressSpace());
225 L.removeAddressSpace();
226 R.removeAddressSpace();
227 }
228 return Q;
229 }
230
231 static Qualifiers fromFastMask(unsigned Mask) {
232 Qualifiers Qs;
233 Qs.addFastQualifiers(Mask);
234 return Qs;
235 }
236
237 static Qualifiers fromCVRMask(unsigned CVR) {
238 Qualifiers Qs;
239 Qs.addCVRQualifiers(CVR);
240 return Qs;
241 }
242
243 static Qualifiers fromCVRUMask(unsigned CVRU) {
244 Qualifiers Qs;
245 Qs.addCVRUQualifiers(CVRU);
246 return Qs;
247 }
248
249 // Deserialize qualifiers from an opaque representation.
250 static Qualifiers fromOpaqueValue(unsigned opaque) {
251 Qualifiers Qs;
252 Qs.Mask = opaque;
253 return Qs;
254 }
255
256 // Serialize these qualifiers into an opaque representation.
257 unsigned getAsOpaqueValue() const {
258 return Mask;
259 }
260
261 bool hasConst() const { return Mask & Const; }
262 bool hasOnlyConst() const { return Mask == Const; }
263 void removeConst() { Mask &= ~Const; }
264 void addConst() { Mask |= Const; }
265
266 bool hasVolatile() const { return Mask & Volatile; }
267 bool hasOnlyVolatile() const { return Mask == Volatile; }
268 void removeVolatile() { Mask &= ~Volatile; }
269 void addVolatile() { Mask |= Volatile; }
270
271 bool hasRestrict() const { return Mask & Restrict; }
272 bool hasOnlyRestrict() const { return Mask == Restrict; }
273 void removeRestrict() { Mask &= ~Restrict; }
274 void addRestrict() { Mask |= Restrict; }
275
276 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
277 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
279
280 void setCVRQualifiers(unsigned mask) {
281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 281, __PRETTY_FUNCTION__))
;
282 Mask = (Mask & ~CVRMask) | mask;
283 }
284 void removeCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask &= ~mask;
287 }
288 void removeCVRQualifiers() {
289 removeCVRQualifiers(CVRMask);
290 }
291 void addCVRQualifiers(unsigned mask) {
292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 292, __PRETTY_FUNCTION__))
;
293 Mask |= mask;
294 }
295 void addCVRUQualifiers(unsigned mask) {
296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 296, __PRETTY_FUNCTION__))
;
297 Mask |= mask;
298 }
299
300 bool hasUnaligned() const { return Mask & UMask; }
301 void setUnaligned(bool flag) {
302 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
303 }
304 void removeUnaligned() { Mask &= ~UMask; }
305 void addUnaligned() { Mask |= UMask; }
306
307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
309 void setObjCGCAttr(GC type) {
310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
311 }
312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
313 void addObjCGCAttr(GC type) {
314 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 314, __PRETTY_FUNCTION__))
;
315 setObjCGCAttr(type);
316 }
317 Qualifiers withoutObjCGCAttr() const {
318 Qualifiers qs = *this;
319 qs.removeObjCGCAttr();
320 return qs;
321 }
322 Qualifiers withoutObjCLifetime() const {
323 Qualifiers qs = *this;
324 qs.removeObjCLifetime();
325 return qs;
326 }
327 Qualifiers withoutAddressSpace() const {
328 Qualifiers qs = *this;
329 qs.removeAddressSpace();
330 return qs;
331 }
332
333 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
334 ObjCLifetime getObjCLifetime() const {
335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
336 }
337 void setObjCLifetime(ObjCLifetime type) {
338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
339 }
340 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
341 void addObjCLifetime(ObjCLifetime type) {
342 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 342, __PRETTY_FUNCTION__))
;
343 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 Mask |= (type << LifetimeShift);
345 }
346
347 /// True if the lifetime is neither None or ExplicitNone.
348 bool hasNonTrivialObjCLifetime() const {
349 ObjCLifetime lifetime = getObjCLifetime();
350 return (lifetime > OCL_ExplicitNone);
351 }
352
353 /// True if the lifetime is either strong or weak.
354 bool hasStrongOrWeakObjCLifetime() const {
355 ObjCLifetime lifetime = getObjCLifetime();
356 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
357 }
358
359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
360 LangAS getAddressSpace() const {
361 return static_cast<LangAS>(Mask >> AddressSpaceShift);
362 }
363 bool hasTargetSpecificAddressSpace() const {
364 return isTargetAddressSpace(getAddressSpace());
365 }
366 /// Get the address space attribute value to be printed by diagnostics.
367 unsigned getAddressSpaceAttributePrintValue() const {
368 auto Addr = getAddressSpace();
369 // This function is not supposed to be used with language specific
370 // address spaces. If that happens, the diagnostic message should consider
371 // printing the QualType instead of the address space value.
372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 372, __PRETTY_FUNCTION__))
;
373 if (Addr != LangAS::Default)
374 return toTargetAddressSpace(Addr);
375 // TODO: The diagnostic messages where Addr may be 0 should be fixed
376 // since it cannot differentiate the situation where 0 denotes the default
377 // address space or user specified __attribute__((address_space(0))).
378 return 0;
379 }
380 void setAddressSpace(LangAS space) {
381 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 381, __PRETTY_FUNCTION__))
;
382 Mask = (Mask & ~AddressSpaceMask)
383 | (((uint32_t) space) << AddressSpaceShift);
384 }
385 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
386 void addAddressSpace(LangAS space) {
387 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 387, __PRETTY_FUNCTION__))
;
388 setAddressSpace(space);
389 }
390
391 // Fast qualifiers are those that can be allocated directly
392 // on a QualType object.
393 bool hasFastQualifiers() const { return getFastQualifiers(); }
394 unsigned getFastQualifiers() const { return Mask & FastMask; }
395 void setFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 396, __PRETTY_FUNCTION__))
;
397 Mask = (Mask & ~FastMask) | mask;
398 }
399 void removeFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask &= ~mask;
402 }
403 void removeFastQualifiers() {
404 removeFastQualifiers(FastMask);
405 }
406 void addFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 407, __PRETTY_FUNCTION__))
;
408 Mask |= mask;
409 }
410
411 /// Return true if the set contains any qualifiers which require an ExtQuals
412 /// node to be allocated.
413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
414 Qualifiers getNonFastQualifiers() const {
415 Qualifiers Quals = *this;
416 Quals.setFastQualifiers(0);
417 return Quals;
418 }
419
420 /// Return true if the set contains any qualifiers.
421 bool hasQualifiers() const { return Mask; }
422 bool empty() const { return !Mask; }
423
424 /// Add the qualifiers from the given set to this set.
425 void addQualifiers(Qualifiers Q) {
426 // If the other set doesn't have any non-boolean qualifiers, just
427 // bit-or it in.
428 if (!(Q.Mask & ~CVRMask))
429 Mask |= Q.Mask;
430 else {
431 Mask |= (Q.Mask & CVRMask);
432 if (Q.hasAddressSpace())
433 addAddressSpace(Q.getAddressSpace());
434 if (Q.hasObjCGCAttr())
435 addObjCGCAttr(Q.getObjCGCAttr());
436 if (Q.hasObjCLifetime())
437 addObjCLifetime(Q.getObjCLifetime());
438 }
439 }
440
441 /// Remove the qualifiers from the given set from this set.
442 void removeQualifiers(Qualifiers Q) {
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-and the inverse in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask &= ~Q.Mask;
447 else {
448 Mask &= ~(Q.Mask & CVRMask);
449 if (getObjCGCAttr() == Q.getObjCGCAttr())
450 removeObjCGCAttr();
451 if (getObjCLifetime() == Q.getObjCLifetime())
452 removeObjCLifetime();
453 if (getAddressSpace() == Q.getAddressSpace())
454 removeAddressSpace();
455 }
456 }
457
458 /// Add the qualifiers from the given set to this set, given that
459 /// they don't conflict.
460 void addConsistentQualifiers(Qualifiers qs) {
461 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
466 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
;
467 Mask |= qs.Mask;
468 }
469
470 /// Returns true if address space A is equal to or a superset of B.
471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
472 /// overlapping address spaces.
473 /// CL1.1 or CL1.2:
474 /// every address space is a superset of itself.
475 /// CL2.0 adds:
476 /// __generic is a superset of any address space except for __constant.
477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
478 // Address spaces must match exactly.
479 return A == B ||
480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
481 // for __constant can be used as __generic.
482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
483 // We also define global_device and global_host address spaces,
484 // to distinguish global pointers allocated on host from pointers
485 // allocated on device, which are a subset of __global.
486 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
487 B == LangAS::opencl_global_host)) ||
488 // Consider pointer size address spaces to be equivalent to default.
489 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
490 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
491 }
492
493 /// Returns true if the address space in these qualifiers is equal to or
494 /// a superset of the address space in the argument qualifiers.
495 bool isAddressSpaceSupersetOf(Qualifiers other) const {
496 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
497 }
498
499 /// Determines if these qualifiers compatibly include another set.
500 /// Generally this answers the question of whether an object with the other
501 /// qualifiers can be safely used as an object with these qualifiers.
502 bool compatiblyIncludes(Qualifiers other) const {
503 return isAddressSpaceSupersetOf(other) &&
504 // ObjC GC qualifiers can match, be added, or be removed, but can't
505 // be changed.
506 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
507 !other.hasObjCGCAttr()) &&
508 // ObjC lifetime qualifiers must match exactly.
509 getObjCLifetime() == other.getObjCLifetime() &&
510 // CVR qualifiers may subset.
511 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
512 // U qualifier may superset.
513 (!other.hasUnaligned() || hasUnaligned());
514 }
515
516 /// Determines if these qualifiers compatibly include another set of
517 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
518 ///
519 /// One set of Objective-C lifetime qualifiers compatibly includes the other
520 /// if the lifetime qualifiers match, or if both are non-__weak and the
521 /// including set also contains the 'const' qualifier, or both are non-__weak
522 /// and one is None (which can only happen in non-ARC modes).
523 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
524 if (getObjCLifetime() == other.getObjCLifetime())
525 return true;
526
527 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
528 return false;
529
530 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
531 return true;
532
533 return hasConst();
534 }
535
536 /// Determine whether this set of qualifiers is a strict superset of
537 /// another set of qualifiers, not considering qualifier compatibility.
538 bool isStrictSupersetOf(Qualifiers Other) const;
539
540 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
541 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
542
543 explicit operator bool() const { return hasQualifiers(); }
544
545 Qualifiers &operator+=(Qualifiers R) {
546 addQualifiers(R);
547 return *this;
548 }
549
550 // Union two qualifier sets. If an enumerated qualifier appears
551 // in both sets, use the one from the right.
552 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
553 L += R;
554 return L;
555 }
556
557 Qualifiers &operator-=(Qualifiers R) {
558 removeQualifiers(R);
559 return *this;
560 }
561
562 /// Compute the difference between two qualifier sets.
563 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
564 L -= R;
565 return L;
566 }
567
568 std::string getAsString() const;
569 std::string getAsString(const PrintingPolicy &Policy) const;
570
571 static std::string getAddrSpaceAsString(LangAS AS);
572
573 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
574 void print(raw_ostream &OS, const PrintingPolicy &Policy,
575 bool appendSpaceIfNonEmpty = false) const;
576
577 void Profile(llvm::FoldingSetNodeID &ID) const {
578 ID.AddInteger(Mask);
579 }
580
581private:
582 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
583 // |C R V|U|GCAttr|Lifetime|AddressSpace|
584 uint32_t Mask = 0;
585
586 static const uint32_t UMask = 0x8;
587 static const uint32_t UShift = 3;
588 static const uint32_t GCAttrMask = 0x30;
589 static const uint32_t GCAttrShift = 4;
590 static const uint32_t LifetimeMask = 0x1C0;
591 static const uint32_t LifetimeShift = 6;
592 static const uint32_t AddressSpaceMask =
593 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
594 static const uint32_t AddressSpaceShift = 9;
595};
596
597/// A std::pair-like structure for storing a qualified type split
598/// into its local qualifiers and its locally-unqualified type.
599struct SplitQualType {
600 /// The locally-unqualified type.
601 const Type *Ty = nullptr;
602
603 /// The local qualifiers.
604 Qualifiers Quals;
605
606 SplitQualType() = default;
607 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
608
609 SplitQualType getSingleStepDesugaredType() const; // end of this file
610
611 // Make std::tie work.
612 std::pair<const Type *,Qualifiers> asPair() const {
613 return std::pair<const Type *, Qualifiers>(Ty, Quals);
614 }
615
616 friend bool operator==(SplitQualType a, SplitQualType b) {
617 return a.Ty == b.Ty && a.Quals == b.Quals;
618 }
619 friend bool operator!=(SplitQualType a, SplitQualType b) {
620 return a.Ty != b.Ty || a.Quals != b.Quals;
621 }
622};
623
624/// The kind of type we are substituting Objective-C type arguments into.
625///
626/// The kind of substitution affects the replacement of type parameters when
627/// no concrete type information is provided, e.g., when dealing with an
628/// unspecialized type.
629enum class ObjCSubstitutionContext {
630 /// An ordinary type.
631 Ordinary,
632
633 /// The result type of a method or function.
634 Result,
635
636 /// The parameter type of a method or function.
637 Parameter,
638
639 /// The type of a property.
640 Property,
641
642 /// The superclass of a type.
643 Superclass,
644};
645
646/// A (possibly-)qualified type.
647///
648/// For efficiency, we don't store CV-qualified types as nodes on their
649/// own: instead each reference to a type stores the qualifiers. This
650/// greatly reduces the number of nodes we need to allocate for types (for
651/// example we only need one for 'int', 'const int', 'volatile int',
652/// 'const volatile int', etc).
653///
654/// As an added efficiency bonus, instead of making this a pair, we
655/// just store the two bits we care about in the low bits of the
656/// pointer. To handle the packing/unpacking, we make QualType be a
657/// simple wrapper class that acts like a smart pointer. A third bit
658/// indicates whether there are extended qualifiers present, in which
659/// case the pointer points to a special structure.
660class QualType {
661 friend class QualifierCollector;
662
663 // Thankfully, these are efficiently composable.
664 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
665 Qualifiers::FastWidth> Value;
666
667 const ExtQuals *getExtQualsUnsafe() const {
668 return Value.getPointer().get<const ExtQuals*>();
669 }
670
671 const Type *getTypePtrUnsafe() const {
672 return Value.getPointer().get<const Type*>();
673 }
674
675 const ExtQualsTypeCommonBase *getCommonPtr() const {
676 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 676, __PRETTY_FUNCTION__))
;
677 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
678 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
679 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
680 }
681
682public:
683 QualType() = default;
684 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
685 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686
687 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
688 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
689
690 /// Retrieves a pointer to the underlying (unqualified) type.
691 ///
692 /// This function requires that the type not be NULL. If the type might be
693 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
694 const Type *getTypePtr() const;
695
696 const Type *getTypePtrOrNull() const;
697
698 /// Retrieves a pointer to the name of the base type.
699 const IdentifierInfo *getBaseTypeIdentifier() const;
700
701 /// Divides a QualType into its unqualified type and a set of local
702 /// qualifiers.
703 SplitQualType split() const;
704
705 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
706
707 static QualType getFromOpaquePtr(const void *Ptr) {
708 QualType T;
709 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
710 return T;
711 }
712
713 const Type &operator*() const {
714 return *getTypePtr();
715 }
716
717 const Type *operator->() const {
718 return getTypePtr();
719 }
720
721 bool isCanonical() const;
722 bool isCanonicalAsParam() const;
723
724 /// Return true if this QualType doesn't point to a type yet.
725 bool isNull() const {
726 return Value.getPointer().isNull();
727 }
728
729 /// Determine whether this particular QualType instance has the
730 /// "const" qualifier set, without looking through typedefs that may have
731 /// added "const" at a different level.
732 bool isLocalConstQualified() const {
733 return (getLocalFastQualifiers() & Qualifiers::Const);
734 }
735
736 /// Determine whether this type is const-qualified.
737 bool isConstQualified() const;
738
739 /// Determine whether this particular QualType instance has the
740 /// "restrict" qualifier set, without looking through typedefs that may have
741 /// added "restrict" at a different level.
742 bool isLocalRestrictQualified() const {
743 return (getLocalFastQualifiers() & Qualifiers::Restrict);
744 }
745
746 /// Determine whether this type is restrict-qualified.
747 bool isRestrictQualified() const;
748
749 /// Determine whether this particular QualType instance has the
750 /// "volatile" qualifier set, without looking through typedefs that may have
751 /// added "volatile" at a different level.
752 bool isLocalVolatileQualified() const {
753 return (getLocalFastQualifiers() & Qualifiers::Volatile);
754 }
755
756 /// Determine whether this type is volatile-qualified.
757 bool isVolatileQualified() const;
758
759 /// Determine whether this particular QualType instance has any
760 /// qualifiers, without looking through any typedefs that might add
761 /// qualifiers at a different level.
762 bool hasLocalQualifiers() const {
763 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
764 }
765
766 /// Determine whether this type has any qualifiers.
767 bool hasQualifiers() const;
768
769 /// Determine whether this particular QualType instance has any
770 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
771 /// instance.
772 bool hasLocalNonFastQualifiers() const {
773 return Value.getPointer().is<const ExtQuals*>();
774 }
775
776 /// Retrieve the set of qualifiers local to this particular QualType
777 /// instance, not including any qualifiers acquired through typedefs or
778 /// other sugar.
779 Qualifiers getLocalQualifiers() const;
780
781 /// Retrieve the set of qualifiers applied to this type.
782 Qualifiers getQualifiers() const;
783
784 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
785 /// local to this particular QualType instance, not including any qualifiers
786 /// acquired through typedefs or other sugar.
787 unsigned getLocalCVRQualifiers() const {
788 return getLocalFastQualifiers();
789 }
790
791 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
792 /// applied to this type.
793 unsigned getCVRQualifiers() const;
794
795 bool isConstant(const ASTContext& Ctx) const {
796 return QualType::isConstant(*this, Ctx);
797 }
798
799 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
800 bool isPODType(const ASTContext &Context) const;
801
802 /// Return true if this is a POD type according to the rules of the C++98
803 /// standard, regardless of the current compilation's language.
804 bool isCXX98PODType(const ASTContext &Context) const;
805
806 /// Return true if this is a POD type according to the more relaxed rules
807 /// of the C++11 standard, regardless of the current compilation's language.
808 /// (C++0x [basic.types]p9). Note that, unlike
809 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
810 bool isCXX11PODType(const ASTContext &Context) const;
811
812 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
813 bool isTrivialType(const ASTContext &Context) const;
814
815 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
816 bool isTriviallyCopyableType(const ASTContext &Context) const;
817
818
819 /// Returns true if it is a class and it might be dynamic.
820 bool mayBeDynamicClass() const;
821
822 /// Returns true if it is not a class or if the class might not be dynamic.
823 bool mayBeNotDynamicClass() const;
824
825 // Don't promise in the API that anything besides 'const' can be
826 // easily added.
827
828 /// Add the `const` type qualifier to this QualType.
829 void addConst() {
830 addFastQualifiers(Qualifiers::Const);
831 }
832 QualType withConst() const {
833 return withFastQualifiers(Qualifiers::Const);
834 }
835
836 /// Add the `volatile` type qualifier to this QualType.
837 void addVolatile() {
838 addFastQualifiers(Qualifiers::Volatile);
839 }
840 QualType withVolatile() const {
841 return withFastQualifiers(Qualifiers::Volatile);
842 }
843
844 /// Add the `restrict` qualifier to this QualType.
845 void addRestrict() {
846 addFastQualifiers(Qualifiers::Restrict);
847 }
848 QualType withRestrict() const {
849 return withFastQualifiers(Qualifiers::Restrict);
850 }
851
852 QualType withCVRQualifiers(unsigned CVR) const {
853 return withFastQualifiers(CVR);
854 }
855
856 void addFastQualifiers(unsigned TQs) {
857 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
858 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
;
859 Value.setInt(Value.getInt() | TQs);
860 }
861
862 void removeLocalConst();
863 void removeLocalVolatile();
864 void removeLocalRestrict();
865 void removeLocalCVRQualifiers(unsigned Mask);
866
867 void removeLocalFastQualifiers() { Value.setInt(0); }
868 void removeLocalFastQualifiers(unsigned Mask) {
869 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 869, __PRETTY_FUNCTION__))
;
870 Value.setInt(Value.getInt() & ~Mask);
871 }
872
873 // Creates a type with the given qualifiers in addition to any
874 // qualifiers already on this type.
875 QualType withFastQualifiers(unsigned TQs) const {
876 QualType T = *this;
877 T.addFastQualifiers(TQs);
878 return T;
879 }
880
881 // Creates a type with exactly the given fast qualifiers, removing
882 // any existing fast qualifiers.
883 QualType withExactLocalFastQualifiers(unsigned TQs) const {
884 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
885 }
886
887 // Removes fast qualifiers, but leaves any extended qualifiers in place.
888 QualType withoutLocalFastQualifiers() const {
889 QualType T = *this;
890 T.removeLocalFastQualifiers();
891 return T;
892 }
893
894 QualType getCanonicalType() const;
895
896 /// Return this type with all of the instance-specific qualifiers
897 /// removed, but without removing any qualifiers that may have been applied
898 /// through typedefs.
899 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
900
901 /// Retrieve the unqualified variant of the given type,
902 /// removing as little sugar as possible.
903 ///
904 /// This routine looks through various kinds of sugar to find the
905 /// least-desugared type that is unqualified. For example, given:
906 ///
907 /// \code
908 /// typedef int Integer;
909 /// typedef const Integer CInteger;
910 /// typedef CInteger DifferenceType;
911 /// \endcode
912 ///
913 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
914 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
915 ///
916 /// The resulting type might still be qualified if it's sugar for an array
917 /// type. To strip qualifiers even from within a sugared array type, use
918 /// ASTContext::getUnqualifiedArrayType.
919 inline QualType getUnqualifiedType() const;
920
921 /// Retrieve the unqualified variant of the given type, removing as little
922 /// sugar as possible.
923 ///
924 /// Like getUnqualifiedType(), but also returns the set of
925 /// qualifiers that were built up.
926 ///
927 /// The resulting type might still be qualified if it's sugar for an array
928 /// type. To strip qualifiers even from within a sugared array type, use
929 /// ASTContext::getUnqualifiedArrayType.
930 inline SplitQualType getSplitUnqualifiedType() const;
931
932 /// Determine whether this type is more qualified than the other
933 /// given type, requiring exact equality for non-CVR qualifiers.
934 bool isMoreQualifiedThan(QualType Other) const;
935
936 /// Determine whether this type is at least as qualified as the other
937 /// given type, requiring exact equality for non-CVR qualifiers.
938 bool isAtLeastAsQualifiedAs(QualType Other) const;
939
940 QualType getNonReferenceType() const;
941
942 /// Determine the type of a (typically non-lvalue) expression with the
943 /// specified result type.
944 ///
945 /// This routine should be used for expressions for which the return type is
946 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
947 /// an lvalue. It removes a top-level reference (since there are no
948 /// expressions of reference type) and deletes top-level cvr-qualifiers
949 /// from non-class types (in C++) or all types (in C).
950 QualType getNonLValueExprType(const ASTContext &Context) const;
951
952 /// Remove an outer pack expansion type (if any) from this type. Used as part
953 /// of converting the type of a declaration to the type of an expression that
954 /// references that expression. It's meaningless for an expression to have a
955 /// pack expansion type.
956 QualType getNonPackExpansionType() const;
957
958 /// Return the specified type with any "sugar" removed from
959 /// the type. This takes off typedefs, typeof's etc. If the outer level of
960 /// the type is already concrete, it returns it unmodified. This is similar
961 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
962 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
963 /// concrete.
964 ///
965 /// Qualifiers are left in place.
966 QualType getDesugaredType(const ASTContext &Context) const {
967 return getDesugaredType(*this, Context);
968 }
969
970 SplitQualType getSplitDesugaredType() const {
971 return getSplitDesugaredType(*this);
972 }
973
974 /// Return the specified type with one level of "sugar" removed from
975 /// the type.
976 ///
977 /// This routine takes off the first typedef, typeof, etc. If the outer level
978 /// of the type is already concrete, it returns it unmodified.
979 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
980 return getSingleStepDesugaredTypeImpl(*this, Context);
981 }
982
983 /// Returns the specified type after dropping any
984 /// outer-level parentheses.
985 QualType IgnoreParens() const {
986 if (isa<ParenType>(*this))
987 return QualType::IgnoreParens(*this);
988 return *this;
989 }
990
991 /// Indicate whether the specified types and qualifiers are identical.
992 friend bool operator==(const QualType &LHS, const QualType &RHS) {
993 return LHS.Value == RHS.Value;
7
Calling 'PointerIntPair::operator=='
9
Returning from 'PointerIntPair::operator=='
10
Returning zero, which participates in a condition later
994 }
995 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
996 return LHS.Value != RHS.Value;
997 }
998 friend bool operator<(const QualType &LHS, const QualType &RHS) {
999 return LHS.Value < RHS.Value;
1000 }
1001
1002 static std::string getAsString(SplitQualType split,
1003 const PrintingPolicy &Policy) {
1004 return getAsString(split.Ty, split.Quals, Policy);
1005 }
1006 static std::string getAsString(const Type *ty, Qualifiers qs,
1007 const PrintingPolicy &Policy);
1008
1009 std::string getAsString() const;
1010 std::string getAsString(const PrintingPolicy &Policy) const;
1011
1012 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1013 const Twine &PlaceHolder = Twine(),
1014 unsigned Indentation = 0) const;
1015
1016 static void print(SplitQualType split, raw_ostream &OS,
1017 const PrintingPolicy &policy, const Twine &PlaceHolder,
1018 unsigned Indentation = 0) {
1019 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1020 }
1021
1022 static void print(const Type *ty, Qualifiers qs,
1023 raw_ostream &OS, const PrintingPolicy &policy,
1024 const Twine &PlaceHolder,
1025 unsigned Indentation = 0);
1026
1027 void getAsStringInternal(std::string &Str,
1028 const PrintingPolicy &Policy) const;
1029
1030 static void getAsStringInternal(SplitQualType split, std::string &out,
1031 const PrintingPolicy &policy) {
1032 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1033 }
1034
1035 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1036 std::string &out,
1037 const PrintingPolicy &policy);
1038
1039 class StreamedQualTypeHelper {
1040 const QualType &T;
1041 const PrintingPolicy &Policy;
1042 const Twine &PlaceHolder;
1043 unsigned Indentation;
1044
1045 public:
1046 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1047 const Twine &PlaceHolder, unsigned Indentation)
1048 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1049 Indentation(Indentation) {}
1050
1051 friend raw_ostream &operator<<(raw_ostream &OS,
1052 const StreamedQualTypeHelper &SQT) {
1053 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1054 return OS;
1055 }
1056 };
1057
1058 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1059 const Twine &PlaceHolder = Twine(),
1060 unsigned Indentation = 0) const {
1061 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1062 }
1063
1064 void dump(const char *s) const;
1065 void dump() const;
1066 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1067
1068 void Profile(llvm::FoldingSetNodeID &ID) const {
1069 ID.AddPointer(getAsOpaquePtr());
1070 }
1071
1072 /// Check if this type has any address space qualifier.
1073 inline bool hasAddressSpace() const;
1074
1075 /// Return the address space of this type.
1076 inline LangAS getAddressSpace() const;
1077
1078 /// Returns true if address space qualifiers overlap with T address space
1079 /// qualifiers.
1080 /// OpenCL C defines conversion rules for pointers to different address spaces
1081 /// and notion of overlapping address spaces.
1082 /// CL1.1 or CL1.2:
1083 /// address spaces overlap iff they are they same.
1084 /// OpenCL C v2.0 s6.5.5 adds:
1085 /// __generic overlaps with any address space except for __constant.
1086 bool isAddressSpaceOverlapping(QualType T) const {
1087 Qualifiers Q = getQualifiers();
1088 Qualifiers TQ = T.getQualifiers();
1089 // Address spaces overlap if at least one of them is a superset of another
1090 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1091 }
1092
1093 /// Returns gc attribute of this type.
1094 inline Qualifiers::GC getObjCGCAttr() const;
1095
1096 /// true when Type is objc's weak.
1097 bool isObjCGCWeak() const {
1098 return getObjCGCAttr() == Qualifiers::Weak;
1099 }
1100
1101 /// true when Type is objc's strong.
1102 bool isObjCGCStrong() const {
1103 return getObjCGCAttr() == Qualifiers::Strong;
1104 }
1105
1106 /// Returns lifetime attribute of this type.
1107 Qualifiers::ObjCLifetime getObjCLifetime() const {
1108 return getQualifiers().getObjCLifetime();
1109 }
1110
1111 bool hasNonTrivialObjCLifetime() const {
1112 return getQualifiers().hasNonTrivialObjCLifetime();
1113 }
1114
1115 bool hasStrongOrWeakObjCLifetime() const {
1116 return getQualifiers().hasStrongOrWeakObjCLifetime();
1117 }
1118
1119 // true when Type is objc's weak and weak is enabled but ARC isn't.
1120 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1121
1122 enum PrimitiveDefaultInitializeKind {
1123 /// The type does not fall into any of the following categories. Note that
1124 /// this case is zero-valued so that values of this enum can be used as a
1125 /// boolean condition for non-triviality.
1126 PDIK_Trivial,
1127
1128 /// The type is an Objective-C retainable pointer type that is qualified
1129 /// with the ARC __strong qualifier.
1130 PDIK_ARCStrong,
1131
1132 /// The type is an Objective-C retainable pointer type that is qualified
1133 /// with the ARC __weak qualifier.
1134 PDIK_ARCWeak,
1135
1136 /// The type is a struct containing a field whose type is not PCK_Trivial.
1137 PDIK_Struct
1138 };
1139
1140 /// Functions to query basic properties of non-trivial C struct types.
1141
1142 /// Check if this is a non-trivial type that would cause a C struct
1143 /// transitively containing this type to be non-trivial to default initialize
1144 /// and return the kind.
1145 PrimitiveDefaultInitializeKind
1146 isNonTrivialToPrimitiveDefaultInitialize() const;
1147
1148 enum PrimitiveCopyKind {
1149 /// The type does not fall into any of the following categories. Note that
1150 /// this case is zero-valued so that values of this enum can be used as a
1151 /// boolean condition for non-triviality.
1152 PCK_Trivial,
1153
1154 /// The type would be trivial except that it is volatile-qualified. Types
1155 /// that fall into one of the other non-trivial cases may additionally be
1156 /// volatile-qualified.
1157 PCK_VolatileTrivial,
1158
1159 /// The type is an Objective-C retainable pointer type that is qualified
1160 /// with the ARC __strong qualifier.
1161 PCK_ARCStrong,
1162
1163 /// The type is an Objective-C retainable pointer type that is qualified
1164 /// with the ARC __weak qualifier.
1165 PCK_ARCWeak,
1166
1167 /// The type is a struct containing a field whose type is neither
1168 /// PCK_Trivial nor PCK_VolatileTrivial.
1169 /// Note that a C++ struct type does not necessarily match this; C++ copying
1170 /// semantics are too complex to express here, in part because they depend
1171 /// on the exact constructor or assignment operator that is chosen by
1172 /// overload resolution to do the copy.
1173 PCK_Struct
1174 };
1175
1176 /// Check if this is a non-trivial type that would cause a C struct
1177 /// transitively containing this type to be non-trivial to copy and return the
1178 /// kind.
1179 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1180
1181 /// Check if this is a non-trivial type that would cause a C struct
1182 /// transitively containing this type to be non-trivial to destructively
1183 /// move and return the kind. Destructive move in this context is a C++-style
1184 /// move in which the source object is placed in a valid but unspecified state
1185 /// after it is moved, as opposed to a truly destructive move in which the
1186 /// source object is placed in an uninitialized state.
1187 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1188
1189 enum DestructionKind {
1190 DK_none,
1191 DK_cxx_destructor,
1192 DK_objc_strong_lifetime,
1193 DK_objc_weak_lifetime,
1194 DK_nontrivial_c_struct
1195 };
1196
1197 /// Returns a nonzero value if objects of this type require
1198 /// non-trivial work to clean up after. Non-zero because it's
1199 /// conceivable that qualifiers (objc_gc(weak)?) could make
1200 /// something require destruction.
1201 DestructionKind isDestructedType() const {
1202 return isDestructedTypeImpl(*this);
1203 }
1204
1205 /// Check if this is or contains a C union that is non-trivial to
1206 /// default-initialize, which is a union that has a member that is non-trivial
1207 /// to default-initialize. If this returns true,
1208 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1209 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1210
1211 /// Check if this is or contains a C union that is non-trivial to destruct,
1212 /// which is a union that has a member that is non-trivial to destruct. If
1213 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1214 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1215
1216 /// Check if this is or contains a C union that is non-trivial to copy, which
1217 /// is a union that has a member that is non-trivial to copy. If this returns
1218 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1219 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1220
1221 /// Determine whether expressions of the given type are forbidden
1222 /// from being lvalues in C.
1223 ///
1224 /// The expression types that are forbidden to be lvalues are:
1225 /// - 'void', but not qualified void
1226 /// - function types
1227 ///
1228 /// The exact rule here is C99 6.3.2.1:
1229 /// An lvalue is an expression with an object type or an incomplete
1230 /// type other than void.
1231 bool isCForbiddenLValueType() const;
1232
1233 /// Substitute type arguments for the Objective-C type parameters used in the
1234 /// subject type.
1235 ///
1236 /// \param ctx ASTContext in which the type exists.
1237 ///
1238 /// \param typeArgs The type arguments that will be substituted for the
1239 /// Objective-C type parameters in the subject type, which are generally
1240 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1241 /// parameters will be replaced with their bounds or id/Class, as appropriate
1242 /// for the context.
1243 ///
1244 /// \param context The context in which the subject type was written.
1245 ///
1246 /// \returns the resulting type.
1247 QualType substObjCTypeArgs(ASTContext &ctx,
1248 ArrayRef<QualType> typeArgs,
1249 ObjCSubstitutionContext context) const;
1250
1251 /// Substitute type arguments from an object type for the Objective-C type
1252 /// parameters used in the subject type.
1253 ///
1254 /// This operation combines the computation of type arguments for
1255 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1256 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1257 /// callers that need to perform a single substitution in isolation.
1258 ///
1259 /// \param objectType The type of the object whose member type we're
1260 /// substituting into. For example, this might be the receiver of a message
1261 /// or the base of a property access.
1262 ///
1263 /// \param dc The declaration context from which the subject type was
1264 /// retrieved, which indicates (for example) which type parameters should
1265 /// be substituted.
1266 ///
1267 /// \param context The context in which the subject type was written.
1268 ///
1269 /// \returns the subject type after replacing all of the Objective-C type
1270 /// parameters with their corresponding arguments.
1271 QualType substObjCMemberType(QualType objectType,
1272 const DeclContext *dc,
1273 ObjCSubstitutionContext context) const;
1274
1275 /// Strip Objective-C "__kindof" types from the given type.
1276 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1277
1278 /// Remove all qualifiers including _Atomic.
1279 QualType getAtomicUnqualifiedType() const;
1280
1281private:
1282 // These methods are implemented in a separate translation unit;
1283 // "static"-ize them to avoid creating temporary QualTypes in the
1284 // caller.
1285 static bool isConstant(QualType T, const ASTContext& Ctx);
1286 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1287 static SplitQualType getSplitDesugaredType(QualType T);
1288 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1289 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1290 const ASTContext &C);
1291 static QualType IgnoreParens(QualType T);
1292 static DestructionKind isDestructedTypeImpl(QualType type);
1293
1294 /// Check if \param RD is or contains a non-trivial C union.
1295 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1296 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1297 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1298};
1299
1300} // namespace clang
1301
1302namespace llvm {
1303
1304/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1305/// to a specific Type class.
1306template<> struct simplify_type< ::clang::QualType> {
1307 using SimpleType = const ::clang::Type *;
1308
1309 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1310 return Val.getTypePtr();
1311 }
1312};
1313
1314// Teach SmallPtrSet that QualType is "basically a pointer".
1315template<>
1316struct PointerLikeTypeTraits<clang::QualType> {
1317 static inline void *getAsVoidPointer(clang::QualType P) {
1318 return P.getAsOpaquePtr();
1319 }
1320
1321 static inline clang::QualType getFromVoidPointer(void *P) {
1322 return clang::QualType::getFromOpaquePtr(P);
1323 }
1324
1325 // Various qualifiers go in low bits.
1326 static constexpr int NumLowBitsAvailable = 0;
1327};
1328
1329} // namespace llvm
1330
1331namespace clang {
1332
1333/// Base class that is common to both the \c ExtQuals and \c Type
1334/// classes, which allows \c QualType to access the common fields between the
1335/// two.
1336class ExtQualsTypeCommonBase {
1337 friend class ExtQuals;
1338 friend class QualType;
1339 friend class Type;
1340
1341 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1342 /// a self-referential pointer (for \c Type).
1343 ///
1344 /// This pointer allows an efficient mapping from a QualType to its
1345 /// underlying type pointer.
1346 const Type *const BaseType;
1347
1348 /// The canonical type of this type. A QualType.
1349 QualType CanonicalType;
1350
1351 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1352 : BaseType(baseType), CanonicalType(canon) {}
1353};
1354
1355/// We can encode up to four bits in the low bits of a
1356/// type pointer, but there are many more type qualifiers that we want
1357/// to be able to apply to an arbitrary type. Therefore we have this
1358/// struct, intended to be heap-allocated and used by QualType to
1359/// store qualifiers.
1360///
1361/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1362/// in three low bits on the QualType pointer; a fourth bit records whether
1363/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1364/// Objective-C GC attributes) are much more rare.
1365class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1366 // NOTE: changing the fast qualifiers should be straightforward as
1367 // long as you don't make 'const' non-fast.
1368 // 1. Qualifiers:
1369 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1370 // Fast qualifiers must occupy the low-order bits.
1371 // b) Update Qualifiers::FastWidth and FastMask.
1372 // 2. QualType:
1373 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1374 // b) Update remove{Volatile,Restrict}, defined near the end of
1375 // this header.
1376 // 3. ASTContext:
1377 // a) Update get{Volatile,Restrict}Type.
1378
1379 /// The immutable set of qualifiers applied by this node. Always contains
1380 /// extended qualifiers.
1381 Qualifiers Quals;
1382
1383 ExtQuals *this_() { return this; }
1384
1385public:
1386 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1387 : ExtQualsTypeCommonBase(baseType,
1388 canon.isNull() ? QualType(this_(), 0) : canon),
1389 Quals(quals) {
1390 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1391, __PRETTY_FUNCTION__))
1391 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1391, __PRETTY_FUNCTION__))
;
1392 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
1393 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
;
1394 }
1395
1396 Qualifiers getQualifiers() const { return Quals; }
1397
1398 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1399 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1400
1401 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1402 Qualifiers::ObjCLifetime getObjCLifetime() const {
1403 return Quals.getObjCLifetime();
1404 }
1405
1406 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1407 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1408
1409 const Type *getBaseType() const { return BaseType; }
1410
1411public:
1412 void Profile(llvm::FoldingSetNodeID &ID) const {
1413 Profile(ID, getBaseType(), Quals);
1414 }
1415
1416 static void Profile(llvm::FoldingSetNodeID &ID,
1417 const Type *BaseType,
1418 Qualifiers Quals) {
1419 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1419, __PRETTY_FUNCTION__))
;
1420 ID.AddPointer(BaseType);
1421 Quals.Profile(ID);
1422 }
1423};
1424
1425/// The kind of C++11 ref-qualifier associated with a function type.
1426/// This determines whether a member function's "this" object can be an
1427/// lvalue, rvalue, or neither.
1428enum RefQualifierKind {
1429 /// No ref-qualifier was provided.
1430 RQ_None = 0,
1431
1432 /// An lvalue ref-qualifier was provided (\c &).
1433 RQ_LValue,
1434
1435 /// An rvalue ref-qualifier was provided (\c &&).
1436 RQ_RValue
1437};
1438
1439/// Which keyword(s) were used to create an AutoType.
1440enum class AutoTypeKeyword {
1441 /// auto
1442 Auto,
1443
1444 /// decltype(auto)
1445 DecltypeAuto,
1446
1447 /// __auto_type (GNU extension)
1448 GNUAutoType
1449};
1450
1451/// The base class of the type hierarchy.
1452///
1453/// A central concept with types is that each type always has a canonical
1454/// type. A canonical type is the type with any typedef names stripped out
1455/// of it or the types it references. For example, consider:
1456///
1457/// typedef int foo;
1458/// typedef foo* bar;
1459/// 'int *' 'foo *' 'bar'
1460///
1461/// There will be a Type object created for 'int'. Since int is canonical, its
1462/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1463/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1464/// there is a PointerType that represents 'int*', which, like 'int', is
1465/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1466/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1467/// is also 'int*'.
1468///
1469/// Non-canonical types are useful for emitting diagnostics, without losing
1470/// information about typedefs being used. Canonical types are useful for type
1471/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1472/// about whether something has a particular form (e.g. is a function type),
1473/// because they implicitly, recursively, strip all typedefs out of a type.
1474///
1475/// Types, once created, are immutable.
1476///
1477class alignas(8) Type : public ExtQualsTypeCommonBase {
1478public:
1479 enum TypeClass {
1480#define TYPE(Class, Base) Class,
1481#define LAST_TYPE(Class) TypeLast = Class
1482#define ABSTRACT_TYPE(Class, Base)
1483#include "clang/AST/TypeNodes.inc"
1484 };
1485
1486private:
1487 /// Bitfields required by the Type class.
1488 class TypeBitfields {
1489 friend class Type;
1490 template <class T> friend class TypePropertyCache;
1491
1492 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1493 unsigned TC : 8;
1494
1495 /// Store information on the type dependency.
1496 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1497
1498 /// True if the cache (i.e. the bitfields here starting with
1499 /// 'Cache') is valid.
1500 mutable unsigned CacheValid : 1;
1501
1502 /// Linkage of this type.
1503 mutable unsigned CachedLinkage : 3;
1504
1505 /// Whether this type involves and local or unnamed types.
1506 mutable unsigned CachedLocalOrUnnamed : 1;
1507
1508 /// Whether this type comes from an AST file.
1509 mutable unsigned FromAST : 1;
1510
1511 bool isCacheValid() const {
1512 return CacheValid;
1513 }
1514
1515 Linkage getLinkage() const {
1516 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1516, __PRETTY_FUNCTION__))
;
1517 return static_cast<Linkage>(CachedLinkage);
1518 }
1519
1520 bool hasLocalOrUnnamedType() const {
1521 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 1521, __PRETTY_FUNCTION__))
;
1522 return CachedLocalOrUnnamed;
1523 }
1524 };
1525 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1526
1527protected:
1528 // These classes allow subclasses to somewhat cleanly pack bitfields
1529 // into Type.
1530
1531 class ArrayTypeBitfields {
1532 friend class ArrayType;
1533
1534 unsigned : NumTypeBits;
1535
1536 /// CVR qualifiers from declarations like
1537 /// 'int X[static restrict 4]'. For function parameters only.
1538 unsigned IndexTypeQuals : 3;
1539
1540 /// Storage class qualifiers from declarations like
1541 /// 'int X[static restrict 4]'. For function parameters only.
1542 /// Actually an ArrayType::ArraySizeModifier.
1543 unsigned SizeModifier : 3;
1544 };
1545
1546 class ConstantArrayTypeBitfields {
1547 friend class ConstantArrayType;
1548
1549 unsigned : NumTypeBits + 3 + 3;
1550
1551 /// Whether we have a stored size expression.
1552 unsigned HasStoredSizeExpr : 1;
1553 };
1554
1555 class BuiltinTypeBitfields {
1556 friend class BuiltinType;
1557
1558 unsigned : NumTypeBits;
1559
1560 /// The kind (BuiltinType::Kind) of builtin type this is.
1561 unsigned Kind : 8;
1562 };
1563
1564 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1565 /// Only common bits are stored here. Additional uncommon bits are stored
1566 /// in a trailing object after FunctionProtoType.
1567 class FunctionTypeBitfields {
1568 friend class FunctionProtoType;
1569 friend class FunctionType;
1570
1571 unsigned : NumTypeBits;
1572
1573 /// Extra information which affects how the function is called, like
1574 /// regparm and the calling convention.
1575 unsigned ExtInfo : 13;
1576
1577 /// The ref-qualifier associated with a \c FunctionProtoType.
1578 ///
1579 /// This is a value of type \c RefQualifierKind.
1580 unsigned RefQualifier : 2;
1581
1582 /// Used only by FunctionProtoType, put here to pack with the
1583 /// other bitfields.
1584 /// The qualifiers are part of FunctionProtoType because...
1585 ///
1586 /// C++ 8.3.5p4: The return type, the parameter type list and the
1587 /// cv-qualifier-seq, [...], are part of the function type.
1588 unsigned FastTypeQuals : Qualifiers::FastWidth;
1589 /// Whether this function has extended Qualifiers.
1590 unsigned HasExtQuals : 1;
1591
1592 /// The number of parameters this function has, not counting '...'.
1593 /// According to [implimits] 8 bits should be enough here but this is
1594 /// somewhat easy to exceed with metaprogramming and so we would like to
1595 /// keep NumParams as wide as reasonably possible.
1596 unsigned NumParams : 16;
1597
1598 /// The type of exception specification this function has.
1599 unsigned ExceptionSpecType : 4;
1600
1601 /// Whether this function has extended parameter information.
1602 unsigned HasExtParameterInfos : 1;
1603
1604 /// Whether the function is variadic.
1605 unsigned Variadic : 1;
1606
1607 /// Whether this function has a trailing return type.
1608 unsigned HasTrailingReturn : 1;
1609 };
1610
1611 class ObjCObjectTypeBitfields {
1612 friend class ObjCObjectType;
1613
1614 unsigned : NumTypeBits;
1615
1616 /// The number of type arguments stored directly on this object type.
1617 unsigned NumTypeArgs : 7;
1618
1619 /// The number of protocols stored directly on this object type.
1620 unsigned NumProtocols : 6;
1621
1622 /// Whether this is a "kindof" type.
1623 unsigned IsKindOf : 1;
1624 };
1625
1626 class ReferenceTypeBitfields {
1627 friend class ReferenceType;
1628
1629 unsigned : NumTypeBits;
1630
1631 /// True if the type was originally spelled with an lvalue sigil.
1632 /// This is never true of rvalue references but can also be false
1633 /// on lvalue references because of C++0x [dcl.typedef]p9,
1634 /// as follows:
1635 ///
1636 /// typedef int &ref; // lvalue, spelled lvalue
1637 /// typedef int &&rvref; // rvalue
1638 /// ref &a; // lvalue, inner ref, spelled lvalue
1639 /// ref &&a; // lvalue, inner ref
1640 /// rvref &a; // lvalue, inner ref, spelled lvalue
1641 /// rvref &&a; // rvalue, inner ref
1642 unsigned SpelledAsLValue : 1;
1643
1644 /// True if the inner type is a reference type. This only happens
1645 /// in non-canonical forms.
1646 unsigned InnerRef : 1;
1647 };
1648
1649 class TypeWithKeywordBitfields {
1650 friend class TypeWithKeyword;
1651
1652 unsigned : NumTypeBits;
1653
1654 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1655 unsigned Keyword : 8;
1656 };
1657
1658 enum { NumTypeWithKeywordBits = 8 };
1659
1660 class ElaboratedTypeBitfields {
1661 friend class ElaboratedType;
1662
1663 unsigned : NumTypeBits;
1664 unsigned : NumTypeWithKeywordBits;
1665
1666 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1667 unsigned HasOwnedTagDecl : 1;
1668 };
1669
1670 class VectorTypeBitfields {
1671 friend class VectorType;
1672 friend class DependentVectorType;
1673
1674 unsigned : NumTypeBits;
1675
1676 /// The kind of vector, either a generic vector type or some
1677 /// target-specific vector type such as for AltiVec or Neon.
1678 unsigned VecKind : 3;
1679 /// The number of elements in the vector.
1680 uint32_t NumElements;
1681 };
1682
1683 class AttributedTypeBitfields {
1684 friend class AttributedType;
1685
1686 unsigned : NumTypeBits;
1687
1688 /// An AttributedType::Kind
1689 unsigned AttrKind : 32 - NumTypeBits;
1690 };
1691
1692 class AutoTypeBitfields {
1693 friend class AutoType;
1694
1695 unsigned : NumTypeBits;
1696
1697 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1698 /// or '__auto_type'? AutoTypeKeyword value.
1699 unsigned Keyword : 2;
1700
1701 /// The number of template arguments in the type-constraints, which is
1702 /// expected to be able to hold at least 1024 according to [implimits].
1703 /// However as this limit is somewhat easy to hit with template
1704 /// metaprogramming we'd prefer to keep it as large as possible.
1705 /// At the moment it has been left as a non-bitfield since this type
1706 /// safely fits in 64 bits as an unsigned, so there is no reason to
1707 /// introduce the performance impact of a bitfield.
1708 unsigned NumArgs;
1709 };
1710
1711 class SubstTemplateTypeParmPackTypeBitfields {
1712 friend class SubstTemplateTypeParmPackType;
1713
1714 unsigned : NumTypeBits;
1715
1716 /// The number of template arguments in \c Arguments, which is
1717 /// expected to be able to hold at least 1024 according to [implimits].
1718 /// However as this limit is somewhat easy to hit with template
1719 /// metaprogramming we'd prefer to keep it as large as possible.
1720 /// At the moment it has been left as a non-bitfield since this type
1721 /// safely fits in 64 bits as an unsigned, so there is no reason to
1722 /// introduce the performance impact of a bitfield.
1723 unsigned NumArgs;
1724 };
1725
1726 class TemplateSpecializationTypeBitfields {
1727 friend class TemplateSpecializationType;
1728
1729 unsigned : NumTypeBits;
1730
1731 /// Whether this template specialization type is a substituted type alias.
1732 unsigned TypeAlias : 1;
1733
1734 /// The number of template arguments named in this class template
1735 /// specialization, which is expected to be able to hold at least 1024
1736 /// according to [implimits]. However, as this limit is somewhat easy to
1737 /// hit with template metaprogramming we'd prefer to keep it as large
1738 /// as possible. At the moment it has been left as a non-bitfield since
1739 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1740 /// to introduce the performance impact of a bitfield.
1741 unsigned NumArgs;
1742 };
1743
1744 class DependentTemplateSpecializationTypeBitfields {
1745 friend class DependentTemplateSpecializationType;
1746
1747 unsigned : NumTypeBits;
1748 unsigned : NumTypeWithKeywordBits;
1749
1750 /// The number of template arguments named in this class template
1751 /// specialization, which is expected to be able to hold at least 1024
1752 /// according to [implimits]. However, as this limit is somewhat easy to
1753 /// hit with template metaprogramming we'd prefer to keep it as large
1754 /// as possible. At the moment it has been left as a non-bitfield since
1755 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1756 /// to introduce the performance impact of a bitfield.
1757 unsigned NumArgs;
1758 };
1759
1760 class PackExpansionTypeBitfields {
1761 friend class PackExpansionType;
1762
1763 unsigned : NumTypeBits;
1764
1765 /// The number of expansions that this pack expansion will
1766 /// generate when substituted (+1), which is expected to be able to
1767 /// hold at least 1024 according to [implimits]. However, as this limit
1768 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1769 /// keep it as large as possible. At the moment it has been left as a
1770 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1771 /// there is no reason to introduce the performance impact of a bitfield.
1772 ///
1773 /// This field will only have a non-zero value when some of the parameter
1774 /// packs that occur within the pattern have been substituted but others
1775 /// have not.
1776 unsigned NumExpansions;
1777 };
1778
1779 union {
1780 TypeBitfields TypeBits;
1781 ArrayTypeBitfields ArrayTypeBits;
1782 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1783 AttributedTypeBitfields AttributedTypeBits;
1784 AutoTypeBitfields AutoTypeBits;
1785 BuiltinTypeBitfields BuiltinTypeBits;
1786 FunctionTypeBitfields FunctionTypeBits;
1787 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1788 ReferenceTypeBitfields ReferenceTypeBits;
1789 TypeWithKeywordBitfields TypeWithKeywordBits;
1790 ElaboratedTypeBitfields ElaboratedTypeBits;
1791 VectorTypeBitfields VectorTypeBits;
1792 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1793 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1794 DependentTemplateSpecializationTypeBitfields
1795 DependentTemplateSpecializationTypeBits;
1796 PackExpansionTypeBitfields PackExpansionTypeBits;
1797 };
1798
1799private:
1800 template <class T> friend class TypePropertyCache;
1801
1802 /// Set whether this type comes from an AST file.
1803 void setFromAST(bool V = true) const {
1804 TypeBits.FromAST = V;
1805 }
1806
1807protected:
1808 friend class ASTContext;
1809
1810 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1811 : ExtQualsTypeCommonBase(this,
1812 canon.isNull() ? QualType(this_(), 0) : canon) {
1813 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1814 "changing bitfields changed sizeof(Type)!");
1815 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1816 "Insufficient alignment!");
1817 TypeBits.TC = tc;
1818 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1819 TypeBits.CacheValid = false;
1820 TypeBits.CachedLocalOrUnnamed = false;
1821 TypeBits.CachedLinkage = NoLinkage;
1822 TypeBits.FromAST = false;
1823 }
1824
1825 // silence VC++ warning C4355: 'this' : used in base member initializer list
1826 Type *this_() { return this; }
1827
1828 void setDependence(TypeDependence D) {
1829 TypeBits.Dependence = static_cast<unsigned>(D);
1830 }
1831
1832 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1833
1834public:
1835 friend class ASTReader;
1836 friend class ASTWriter;
1837 template <class T> friend class serialization::AbstractTypeReader;
1838 template <class T> friend class serialization::AbstractTypeWriter;
1839
1840 Type(const Type &) = delete;
1841 Type(Type &&) = delete;
1842 Type &operator=(const Type &) = delete;
1843 Type &operator=(Type &&) = delete;
1844
1845 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1846
1847 /// Whether this type comes from an AST file.
1848 bool isFromAST() const { return TypeBits.FromAST; }
1849
1850 /// Whether this type is or contains an unexpanded parameter
1851 /// pack, used to support C++0x variadic templates.
1852 ///
1853 /// A type that contains a parameter pack shall be expanded by the
1854 /// ellipsis operator at some point. For example, the typedef in the
1855 /// following example contains an unexpanded parameter pack 'T':
1856 ///
1857 /// \code
1858 /// template<typename ...T>
1859 /// struct X {
1860 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1861 /// };
1862 /// \endcode
1863 ///
1864 /// Note that this routine does not specify which
1865 bool containsUnexpandedParameterPack() const {
1866 return getDependence() & TypeDependence::UnexpandedPack;
1867 }
1868
1869 /// Determines if this type would be canonical if it had no further
1870 /// qualification.
1871 bool isCanonicalUnqualified() const {
1872 return CanonicalType == QualType(this, 0);
1873 }
1874
1875 /// Pull a single level of sugar off of this locally-unqualified type.
1876 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1877 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1878 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1879
1880 /// As an extension, we classify types as one of "sized" or "sizeless";
1881 /// every type is one or the other. Standard types are all sized;
1882 /// sizeless types are purely an extension.
1883 ///
1884 /// Sizeless types contain data with no specified size, alignment,
1885 /// or layout.
1886 bool isSizelessType() const;
1887 bool isSizelessBuiltinType() const;
1888
1889 /// Determines if this is a sizeless type supported by the
1890 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1891 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1892 bool isVLSTBuiltinType() const;
1893
1894 /// Returns the representative type for the element of an SVE builtin type.
1895 /// This is used to represent fixed-length SVE vectors created with the
1896 /// 'arm_sve_vector_bits' type attribute as VectorType.
1897 QualType getSveEltType(const ASTContext &Ctx) const;
1898
1899 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1900 /// object types, function types, and incomplete types.
1901
1902 /// Return true if this is an incomplete type.
1903 /// A type that can describe objects, but which lacks information needed to
1904 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1905 /// routine will need to determine if the size is actually required.
1906 ///
1907 /// Def If non-null, and the type refers to some kind of declaration
1908 /// that can be completed (such as a C struct, C++ class, or Objective-C
1909 /// class), will be set to the declaration.
1910 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1911
1912 /// Return true if this is an incomplete or object
1913 /// type, in other words, not a function type.
1914 bool isIncompleteOrObjectType() const {
1915 return !isFunctionType();
1916 }
1917
1918 /// Determine whether this type is an object type.
1919 bool isObjectType() const {
1920 // C++ [basic.types]p8:
1921 // An object type is a (possibly cv-qualified) type that is not a
1922 // function type, not a reference type, and not a void type.
1923 return !isReferenceType() && !isFunctionType() && !isVoidType();
1924 }
1925
1926 /// Return true if this is a literal type
1927 /// (C++11 [basic.types]p10)
1928 bool isLiteralType(const ASTContext &Ctx) const;
1929
1930 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1931 bool isStructuralType() const;
1932
1933 /// Test if this type is a standard-layout type.
1934 /// (C++0x [basic.type]p9)
1935 bool isStandardLayoutType() const;
1936
1937 /// Helper methods to distinguish type categories. All type predicates
1938 /// operate on the canonical type, ignoring typedefs and qualifiers.
1939
1940 /// Returns true if the type is a builtin type.
1941 bool isBuiltinType() const;
1942
1943 /// Test for a particular builtin type.
1944 bool isSpecificBuiltinType(unsigned K) const;
1945
1946 /// Test for a type which does not represent an actual type-system type but
1947 /// is instead used as a placeholder for various convenient purposes within
1948 /// Clang. All such types are BuiltinTypes.
1949 bool isPlaceholderType() const;
1950 const BuiltinType *getAsPlaceholderType() const;
1951
1952 /// Test for a specific placeholder type.
1953 bool isSpecificPlaceholderType(unsigned K) const;
1954
1955 /// Test for a placeholder type other than Overload; see
1956 /// BuiltinType::isNonOverloadPlaceholderType.
1957 bool isNonOverloadPlaceholderType() const;
1958
1959 /// isIntegerType() does *not* include complex integers (a GCC extension).
1960 /// isComplexIntegerType() can be used to test for complex integers.
1961 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1962 bool isEnumeralType() const;
1963
1964 /// Determine whether this type is a scoped enumeration type.
1965 bool isScopedEnumeralType() const;
1966 bool isBooleanType() const;
1967 bool isCharType() const;
1968 bool isWideCharType() const;
1969 bool isChar8Type() const;
1970 bool isChar16Type() const;
1971 bool isChar32Type() const;
1972 bool isAnyCharacterType() const;
1973 bool isIntegralType(const ASTContext &Ctx) const;
1974
1975 /// Determine whether this type is an integral or enumeration type.
1976 bool isIntegralOrEnumerationType() const;
1977
1978 /// Determine whether this type is an integral or unscoped enumeration type.
1979 bool isIntegralOrUnscopedEnumerationType() const;
1980 bool isUnscopedEnumerationType() const;
1981
1982 /// Floating point categories.
1983 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1984 /// isComplexType() does *not* include complex integers (a GCC extension).
1985 /// isComplexIntegerType() can be used to test for complex integers.
1986 bool isComplexType() const; // C99 6.2.5p11 (complex)
1987 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1988 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1989 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1990 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1991 bool isBFloat16Type() const;
1992 bool isFloat128Type() const;
1993 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1994 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1995 bool isVoidType() const; // C99 6.2.5p19
1996 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1997 bool isAggregateType() const;
1998 bool isFundamentalType() const;
1999 bool isCompoundType() const;
2000
2001 // Type Predicates: Check to see if this type is structurally the specified
2002 // type, ignoring typedefs and qualifiers.
2003 bool isFunctionType() const;
2004 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2005 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2006 bool isPointerType() const;
2007 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2008 bool isBlockPointerType() const;
2009 bool isVoidPointerType() const;
2010 bool isReferenceType() const;
2011 bool isLValueReferenceType() const;
2012 bool isRValueReferenceType() const;
2013 bool isObjectPointerType() const;
2014 bool isFunctionPointerType() const;
2015 bool isFunctionReferenceType() const;
2016 bool isMemberPointerType() const;
2017 bool isMemberFunctionPointerType() const;
2018 bool isMemberDataPointerType() const;
2019 bool isArrayType() const;
2020 bool isConstantArrayType() const;
2021 bool isIncompleteArrayType() const;
2022 bool isVariableArrayType() const;
2023 bool isDependentSizedArrayType() const;
2024 bool isRecordType() const;
2025 bool isClassType() const;
2026 bool isStructureType() const;
2027 bool isObjCBoxableRecordType() const;
2028 bool isInterfaceType() const;
2029 bool isStructureOrClassType() const;
2030 bool isUnionType() const;
2031 bool isComplexIntegerType() const; // GCC _Complex integer type.
2032 bool isVectorType() const; // GCC vector type.
2033 bool isExtVectorType() const; // Extended vector type.
2034 bool isMatrixType() const; // Matrix type.
2035 bool isConstantMatrixType() const; // Constant matrix type.
2036 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2037 bool isObjCObjectPointerType() const; // pointer to ObjC object
2038 bool isObjCRetainableType() const; // ObjC object or block pointer
2039 bool isObjCLifetimeType() const; // (array of)* retainable type
2040 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2041 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2042 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2043 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2044 // for the common case.
2045 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2046 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2047 bool isObjCQualifiedIdType() const; // id<foo>
2048 bool isObjCQualifiedClassType() const; // Class<foo>
2049 bool isObjCObjectOrInterfaceType() const;
2050 bool isObjCIdType() const; // id
2051 bool isDecltypeType() const;
2052 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2053 /// qualifier?
2054 ///
2055 /// This approximates the answer to the following question: if this
2056 /// translation unit were compiled in ARC, would this type be qualified
2057 /// with __unsafe_unretained?
2058 bool isObjCInertUnsafeUnretainedType() const {
2059 return hasAttr(attr::ObjCInertUnsafeUnretained);
2060 }
2061
2062 /// Whether the type is Objective-C 'id' or a __kindof type of an
2063 /// object type, e.g., __kindof NSView * or __kindof id
2064 /// <NSCopying>.
2065 ///
2066 /// \param bound Will be set to the bound on non-id subtype types,
2067 /// which will be (possibly specialized) Objective-C class type, or
2068 /// null for 'id.
2069 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2070 const ObjCObjectType *&bound) const;
2071
2072 bool isObjCClassType() const; // Class
2073
2074 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2075 /// Class type, e.g., __kindof Class <NSCopying>.
2076 ///
2077 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2078 /// here because Objective-C's type system cannot express "a class
2079 /// object for a subclass of NSFoo".
2080 bool isObjCClassOrClassKindOfType() const;
2081
2082 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2083 bool isObjCSelType() const; // Class
2084 bool isObjCBuiltinType() const; // 'id' or 'Class'
2085 bool isObjCARCBridgableType() const;
2086 bool isCARCBridgableType() const;
2087 bool isTemplateTypeParmType() const; // C++ template type parameter
2088 bool isNullPtrType() const; // C++11 std::nullptr_t
2089 bool isNothrowT() const; // C++ std::nothrow_t
2090 bool isAlignValT() const; // C++17 std::align_val_t
2091 bool isStdByteType() const; // C++17 std::byte
2092 bool isAtomicType() const; // C11 _Atomic()
2093 bool isUndeducedAutoType() const; // C++11 auto or
2094 // C++14 decltype(auto)
2095
2096#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2097 bool is##Id##Type() const;
2098#include "clang/Basic/OpenCLImageTypes.def"
2099
2100 bool isImageType() const; // Any OpenCL image type
2101
2102 bool isSamplerT() const; // OpenCL sampler_t
2103 bool isEventT() const; // OpenCL event_t
2104 bool isClkEventT() const; // OpenCL clk_event_t
2105 bool isQueueT() const; // OpenCL queue_t
2106 bool isReserveIDT() const; // OpenCL reserve_id_t
2107
2108#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2109 bool is##Id##Type() const;
2110#include "clang/Basic/OpenCLExtensionTypes.def"
2111 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2112 bool isOCLIntelSubgroupAVCType() const;
2113 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2114
2115 bool isPipeType() const; // OpenCL pipe type
2116 bool isExtIntType() const; // Extended Int Type
2117 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2118
2119 /// Determines if this type, which must satisfy
2120 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2121 /// than implicitly __strong.
2122 bool isObjCARCImplicitlyUnretainedType() const;
2123
2124 /// Check if the type is the CUDA device builtin surface type.
2125 bool isCUDADeviceBuiltinSurfaceType() const;
2126 /// Check if the type is the CUDA device builtin texture type.
2127 bool isCUDADeviceBuiltinTextureType() const;
2128
2129 /// Return the implicit lifetime for this type, which must not be dependent.
2130 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2131
2132 enum ScalarTypeKind {
2133 STK_CPointer,
2134 STK_BlockPointer,
2135 STK_ObjCObjectPointer,
2136 STK_MemberPointer,
2137 STK_Bool,
2138 STK_Integral,
2139 STK_Floating,
2140 STK_IntegralComplex,
2141 STK_FloatingComplex,
2142 STK_FixedPoint
2143 };
2144
2145 /// Given that this is a scalar type, classify it.
2146 ScalarTypeKind getScalarTypeKind() const;
2147
2148 TypeDependence getDependence() const {
2149 return static_cast<TypeDependence>(TypeBits.Dependence);
2150 }
2151
2152 /// Whether this type is an error type.
2153 bool containsErrors() const {
2154 return getDependence() & TypeDependence::Error;
2155 }
2156
2157 /// Whether this type is a dependent type, meaning that its definition
2158 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2159 bool isDependentType() const {
2160 return getDependence() & TypeDependence::Dependent;
2161 }
2162
2163 /// Determine whether this type is an instantiation-dependent type,
2164 /// meaning that the type involves a template parameter (even if the
2165 /// definition does not actually depend on the type substituted for that
2166 /// template parameter).
2167 bool isInstantiationDependentType() const {
2168 return getDependence() & TypeDependence::Instantiation;
2169 }
2170
2171 /// Determine whether this type is an undeduced type, meaning that
2172 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2173 /// deduced.
2174 bool isUndeducedType() const;
2175
2176 /// Whether this type is a variably-modified type (C99 6.7.5).
2177 bool isVariablyModifiedType() const {
2178 return getDependence() & TypeDependence::VariablyModified;
2179 }
2180
2181 /// Whether this type involves a variable-length array type
2182 /// with a definite size.
2183 bool hasSizedVLAType() const;
2184
2185 /// Whether this type is or contains a local or unnamed type.
2186 bool hasUnnamedOrLocalType() const;
2187
2188 bool isOverloadableType() const;
2189
2190 /// Determine wither this type is a C++ elaborated-type-specifier.
2191 bool isElaboratedTypeSpecifier() const;
2192
2193 bool canDecayToPointerType() const;
2194
2195 /// Whether this type is represented natively as a pointer. This includes
2196 /// pointers, references, block pointers, and Objective-C interface,
2197 /// qualified id, and qualified interface types, as well as nullptr_t.
2198 bool hasPointerRepresentation() const;
2199
2200 /// Whether this type can represent an objective pointer type for the
2201 /// purpose of GC'ability
2202 bool hasObjCPointerRepresentation() const;
2203
2204 /// Determine whether this type has an integer representation
2205 /// of some sort, e.g., it is an integer type or a vector.
2206 bool hasIntegerRepresentation() const;
2207
2208 /// Determine whether this type has an signed integer representation
2209 /// of some sort, e.g., it is an signed integer type or a vector.
2210 bool hasSignedIntegerRepresentation() const;
2211
2212 /// Determine whether this type has an unsigned integer representation
2213 /// of some sort, e.g., it is an unsigned integer type or a vector.
2214 bool hasUnsignedIntegerRepresentation() const;
2215
2216 /// Determine whether this type has a floating-point representation
2217 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2218 bool hasFloatingRepresentation() const;
2219
2220 // Type Checking Functions: Check to see if this type is structurally the
2221 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2222 // the best type we can.
2223 const RecordType *getAsStructureType() const;
2224 /// NOTE: getAs*ArrayType are methods on ASTContext.
2225 const RecordType *getAsUnionType() const;
2226 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2227 const ObjCObjectType *getAsObjCInterfaceType() const;
2228
2229 // The following is a convenience method that returns an ObjCObjectPointerType
2230 // for object declared using an interface.
2231 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2232 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2233 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2234 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2235
2236 /// Retrieves the CXXRecordDecl that this type refers to, either
2237 /// because the type is a RecordType or because it is the injected-class-name
2238 /// type of a class template or class template partial specialization.
2239 CXXRecordDecl *getAsCXXRecordDecl() const;
2240
2241 /// Retrieves the RecordDecl this type refers to.
2242 RecordDecl *getAsRecordDecl() const;
2243
2244 /// Retrieves the TagDecl that this type refers to, either
2245 /// because the type is a TagType or because it is the injected-class-name
2246 /// type of a class template or class template partial specialization.
2247 TagDecl *getAsTagDecl() const;
2248
2249 /// If this is a pointer or reference to a RecordType, return the
2250 /// CXXRecordDecl that the type refers to.
2251 ///
2252 /// If this is not a pointer or reference, or the type being pointed to does
2253 /// not refer to a CXXRecordDecl, returns NULL.
2254 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2255
2256 /// Get the DeducedType whose type will be deduced for a variable with
2257 /// an initializer of this type. This looks through declarators like pointer
2258 /// types, but not through decltype or typedefs.
2259 DeducedType *getContainedDeducedType() const;
2260
2261 /// Get the AutoType whose type will be deduced for a variable with
2262 /// an initializer of this type. This looks through declarators like pointer
2263 /// types, but not through decltype or typedefs.
2264 AutoType *getContainedAutoType() const {
2265 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2266 }
2267
2268 /// Determine whether this type was written with a leading 'auto'
2269 /// corresponding to a trailing return type (possibly for a nested
2270 /// function type within a pointer to function type or similar).
2271 bool hasAutoForTrailingReturnType() const;
2272
2273 /// Member-template getAs<specific type>'. Look through sugar for
2274 /// an instance of \<specific type>. This scheme will eventually
2275 /// replace the specific getAsXXXX methods above.
2276 ///
2277 /// There are some specializations of this member template listed
2278 /// immediately following this class.
2279 template <typename T> const T *getAs() const;
2280
2281 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2282 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2283 /// This is used when you need to walk over sugar nodes that represent some
2284 /// kind of type adjustment from a type that was written as a \<specific type>
2285 /// to another type that is still canonically a \<specific type>.
2286 template <typename T> const T *getAsAdjusted() const;
2287
2288 /// A variant of getAs<> for array types which silently discards
2289 /// qualifiers from the outermost type.
2290 const ArrayType *getAsArrayTypeUnsafe() const;
2291
2292 /// Member-template castAs<specific type>. Look through sugar for
2293 /// the underlying instance of \<specific type>.
2294 ///
2295 /// This method has the same relationship to getAs<T> as cast<T> has
2296 /// to dyn_cast<T>; which is to say, the underlying type *must*
2297 /// have the intended type, and this method will never return null.
2298 template <typename T> const T *castAs() const;
2299
2300 /// A variant of castAs<> for array type which silently discards
2301 /// qualifiers from the outermost type.
2302 const ArrayType *castAsArrayTypeUnsafe() const;
2303
2304 /// Determine whether this type had the specified attribute applied to it
2305 /// (looking through top-level type sugar).
2306 bool hasAttr(attr::Kind AK) const;
2307
2308 /// Get the base element type of this type, potentially discarding type
2309 /// qualifiers. This should never be used when type qualifiers
2310 /// are meaningful.
2311 const Type *getBaseElementTypeUnsafe() const;
2312
2313 /// If this is an array type, return the element type of the array,
2314 /// potentially with type qualifiers missing.
2315 /// This should never be used when type qualifiers are meaningful.
2316 const Type *getArrayElementTypeNoTypeQual() const;
2317
2318 /// If this is a pointer type, return the pointee type.
2319 /// If this is an array type, return the array element type.
2320 /// This should never be used when type qualifiers are meaningful.
2321 const Type *getPointeeOrArrayElementType() const;
2322
2323 /// If this is a pointer, ObjC object pointer, or block
2324 /// pointer, this returns the respective pointee.
2325 QualType getPointeeType() const;
2326
2327 /// Return the specified type with any "sugar" removed from the type,
2328 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2329 const Type *getUnqualifiedDesugaredType() const;
2330
2331 /// More type predicates useful for type checking/promotion
2332 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2333
2334 /// Return true if this is an integer type that is
2335 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2336 /// or an enum decl which has a signed representation.
2337 bool isSignedIntegerType() const;
2338
2339 /// Return true if this is an integer type that is
2340 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2341 /// or an enum decl which has an unsigned representation.
2342 bool isUnsignedIntegerType() const;
2343
2344 /// Determines whether this is an integer type that is signed or an
2345 /// enumeration types whose underlying type is a signed integer type.
2346 bool isSignedIntegerOrEnumerationType() const;
2347
2348 /// Determines whether this is an integer type that is unsigned or an
2349 /// enumeration types whose underlying type is a unsigned integer type.
2350 bool isUnsignedIntegerOrEnumerationType() const;
2351
2352 /// Return true if this is a fixed point type according to
2353 /// ISO/IEC JTC1 SC22 WG14 N1169.
2354 bool isFixedPointType() const;
2355
2356 /// Return true if this is a fixed point or integer type.
2357 bool isFixedPointOrIntegerType() const;
2358
2359 /// Return true if this is a saturated fixed point type according to
2360 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2361 bool isSaturatedFixedPointType() const;
2362
2363 /// Return true if this is a saturated fixed point type according to
2364 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2365 bool isUnsaturatedFixedPointType() const;
2366
2367 /// Return true if this is a fixed point type that is signed according
2368 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2369 bool isSignedFixedPointType() const;
2370
2371 /// Return true if this is a fixed point type that is unsigned according
2372 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2373 bool isUnsignedFixedPointType() const;
2374
2375 /// Return true if this is not a variable sized type,
2376 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2377 /// incomplete types.
2378 bool isConstantSizeType() const;
2379
2380 /// Returns true if this type can be represented by some
2381 /// set of type specifiers.
2382 bool isSpecifierType() const;
2383
2384 /// Determine the linkage of this type.
2385 Linkage getLinkage() const;
2386
2387 /// Determine the visibility of this type.
2388 Visibility getVisibility() const {
2389 return getLinkageAndVisibility().getVisibility();
2390 }
2391
2392 /// Return true if the visibility was explicitly set is the code.
2393 bool isVisibilityExplicit() const {
2394 return getLinkageAndVisibility().isVisibilityExplicit();
2395 }
2396
2397 /// Determine the linkage and visibility of this type.
2398 LinkageInfo getLinkageAndVisibility() const;
2399
2400 /// True if the computed linkage is valid. Used for consistency
2401 /// checking. Should always return true.
2402 bool isLinkageValid() const;
2403
2404 /// Determine the nullability of the given type.
2405 ///
2406 /// Note that nullability is only captured as sugar within the type
2407 /// system, not as part of the canonical type, so nullability will
2408 /// be lost by canonicalization and desugaring.
2409 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2410
2411 /// Determine whether the given type can have a nullability
2412 /// specifier applied to it, i.e., if it is any kind of pointer type.
2413 ///
2414 /// \param ResultIfUnknown The value to return if we don't yet know whether
2415 /// this type can have nullability because it is dependent.
2416 bool canHaveNullability(bool ResultIfUnknown = true) const;
2417
2418 /// Retrieve the set of substitutions required when accessing a member
2419 /// of the Objective-C receiver type that is declared in the given context.
2420 ///
2421 /// \c *this is the type of the object we're operating on, e.g., the
2422 /// receiver for a message send or the base of a property access, and is
2423 /// expected to be of some object or object pointer type.
2424 ///
2425 /// \param dc The declaration context for which we are building up a
2426 /// substitution mapping, which should be an Objective-C class, extension,
2427 /// category, or method within.
2428 ///
2429 /// \returns an array of type arguments that can be substituted for
2430 /// the type parameters of the given declaration context in any type described
2431 /// within that context, or an empty optional to indicate that no
2432 /// substitution is required.
2433 Optional<ArrayRef<QualType>>
2434 getObjCSubstitutions(const DeclContext *dc) const;
2435
2436 /// Determines if this is an ObjC interface type that may accept type
2437 /// parameters.
2438 bool acceptsObjCTypeParams() const;
2439
2440 const char *getTypeClassName() const;
2441
2442 QualType getCanonicalTypeInternal() const {
2443 return CanonicalType;
2444 }
2445
2446 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2447 void dump() const;
2448 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2449};
2450
2451/// This will check for a TypedefType by removing any existing sugar
2452/// until it reaches a TypedefType or a non-sugared type.
2453template <> const TypedefType *Type::getAs() const;
2454
2455/// This will check for a TemplateSpecializationType by removing any
2456/// existing sugar until it reaches a TemplateSpecializationType or a
2457/// non-sugared type.
2458template <> const TemplateSpecializationType *Type::getAs() const;
2459
2460/// This will check for an AttributedType by removing any existing sugar
2461/// until it reaches an AttributedType or a non-sugared type.
2462template <> const AttributedType *Type::getAs() const;
2463
2464// We can do canonical leaf types faster, because we don't have to
2465// worry about preserving child type decoration.
2466#define TYPE(Class, Base)
2467#define LEAF_TYPE(Class) \
2468template <> inline const Class##Type *Type::getAs() const { \
2469 return dyn_cast<Class##Type>(CanonicalType); \
2470} \
2471template <> inline const Class##Type *Type::castAs() const { \
2472 return cast<Class##Type>(CanonicalType); \
2473}
2474#include "clang/AST/TypeNodes.inc"
2475
2476/// This class is used for builtin types like 'int'. Builtin
2477/// types are always canonical and have a literal name field.
2478class BuiltinType : public Type {
2479public:
2480 enum Kind {
2481// OpenCL image types
2482#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2483#include "clang/Basic/OpenCLImageTypes.def"
2484// OpenCL extension types
2485#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2486#include "clang/Basic/OpenCLExtensionTypes.def"
2487// SVE Types
2488#define SVE_TYPE(Name, Id, SingletonId) Id,
2489#include "clang/Basic/AArch64SVEACLETypes.def"
2490// PPC MMA Types
2491#define PPC_MMA_VECTOR_TYPE(Name, Id, Size) Id,
2492#include "clang/Basic/PPCTypes.def"
2493// All other builtin types
2494#define BUILTIN_TYPE(Id, SingletonId) Id,
2495#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2496#include "clang/AST/BuiltinTypes.def"
2497 };
2498
2499private:
2500 friend class ASTContext; // ASTContext creates these.
2501
2502 BuiltinType(Kind K)
2503 : Type(Builtin, QualType(),
2504 K == Dependent ? TypeDependence::DependentInstantiation
2505 : TypeDependence::None) {
2506 BuiltinTypeBits.Kind = K;
2507 }
2508
2509public:
2510 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2511 StringRef getName(const PrintingPolicy &Policy) const;
2512
2513 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2514 // The StringRef is null-terminated.
2515 StringRef str = getName(Policy);
2516 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 2516, __PRETTY_FUNCTION__))
;
2517 return str.data();
2518 }
2519
2520 bool isSugared() const { return false; }
2521 QualType desugar() const { return QualType(this, 0); }
2522
2523 bool isInteger() const {
2524 return getKind() >= Bool && getKind() <= Int128;
2525 }
2526
2527 bool isSignedInteger() const {
2528 return getKind() >= Char_S && getKind() <= Int128;
2529 }
2530
2531 bool isUnsignedInteger() const {
2532 return getKind() >= Bool && getKind() <= UInt128;
2533 }
2534
2535 bool isFloatingPoint() const {
2536 return getKind() >= Half && getKind() <= Float128;
2537 }
2538
2539 /// Determines whether the given kind corresponds to a placeholder type.
2540 static bool isPlaceholderTypeKind(Kind K) {
2541 return K >= Overload;
2542 }
2543
2544 /// Determines whether this type is a placeholder type, i.e. a type
2545 /// which cannot appear in arbitrary positions in a fully-formed
2546 /// expression.
2547 bool isPlaceholderType() const {
2548 return isPlaceholderTypeKind(getKind());
2549 }
2550
2551 /// Determines whether this type is a placeholder type other than
2552 /// Overload. Most placeholder types require only syntactic
2553 /// information about their context in order to be resolved (e.g.
2554 /// whether it is a call expression), which means they can (and
2555 /// should) be resolved in an earlier "phase" of analysis.
2556 /// Overload expressions sometimes pick up further information
2557 /// from their context, like whether the context expects a
2558 /// specific function-pointer type, and so frequently need
2559 /// special treatment.
2560 bool isNonOverloadPlaceholderType() const {
2561 return getKind() > Overload;
2562 }
2563
2564 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2565};
2566
2567/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2568/// types (_Complex float etc) as well as the GCC integer complex extensions.
2569class ComplexType : public Type, public llvm::FoldingSetNode {
2570 friend class ASTContext; // ASTContext creates these.
2571
2572 QualType ElementType;
2573
2574 ComplexType(QualType Element, QualType CanonicalPtr)
2575 : Type(Complex, CanonicalPtr, Element->getDependence()),
2576 ElementType(Element) {}
2577
2578public:
2579 QualType getElementType() const { return ElementType; }
2580
2581 bool isSugared() const { return false; }
2582 QualType desugar() const { return QualType(this, 0); }
2583
2584 void Profile(llvm::FoldingSetNodeID &ID) {
2585 Profile(ID, getElementType());
2586 }
2587
2588 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2589 ID.AddPointer(Element.getAsOpaquePtr());
2590 }
2591
2592 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2593};
2594
2595/// Sugar for parentheses used when specifying types.
2596class ParenType : public Type, public llvm::FoldingSetNode {
2597 friend class ASTContext; // ASTContext creates these.
2598
2599 QualType Inner;
2600
2601 ParenType(QualType InnerType, QualType CanonType)
2602 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2603
2604public:
2605 QualType getInnerType() const { return Inner; }
2606
2607 bool isSugared() const { return true; }
2608 QualType desugar() const { return getInnerType(); }
2609
2610 void Profile(llvm::FoldingSetNodeID &ID) {
2611 Profile(ID, getInnerType());
2612 }
2613
2614 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2615 Inner.Profile(ID);
2616 }
2617
2618 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2619};
2620
2621/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2622class PointerType : public Type, public llvm::FoldingSetNode {
2623 friend class ASTContext; // ASTContext creates these.
2624
2625 QualType PointeeType;
2626
2627 PointerType(QualType Pointee, QualType CanonicalPtr)
2628 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2629 PointeeType(Pointee) {}
2630
2631public:
2632 QualType getPointeeType() const { return PointeeType; }
2633
2634 bool isSugared() const { return false; }
2635 QualType desugar() const { return QualType(this, 0); }
2636
2637 void Profile(llvm::FoldingSetNodeID &ID) {
2638 Profile(ID, getPointeeType());
2639 }
2640
2641 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2642 ID.AddPointer(Pointee.getAsOpaquePtr());
2643 }
2644
2645 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2646};
2647
2648/// Represents a type which was implicitly adjusted by the semantic
2649/// engine for arbitrary reasons. For example, array and function types can
2650/// decay, and function types can have their calling conventions adjusted.
2651class AdjustedType : public Type, public llvm::FoldingSetNode {
2652 QualType OriginalTy;
2653 QualType AdjustedTy;
2654
2655protected:
2656 friend class ASTContext; // ASTContext creates these.
2657
2658 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2659 QualType CanonicalPtr)
2660 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2661 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2662
2663public:
2664 QualType getOriginalType() const { return OriginalTy; }
2665 QualType getAdjustedType() const { return AdjustedTy; }
2666
2667 bool isSugared() const { return true; }
2668 QualType desugar() const { return AdjustedTy; }
2669
2670 void Profile(llvm::FoldingSetNodeID &ID) {
2671 Profile(ID, OriginalTy, AdjustedTy);
2672 }
2673
2674 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2675 ID.AddPointer(Orig.getAsOpaquePtr());
2676 ID.AddPointer(New.getAsOpaquePtr());
2677 }
2678
2679 static bool classof(const Type *T) {
2680 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2681 }
2682};
2683
2684/// Represents a pointer type decayed from an array or function type.
2685class DecayedType : public AdjustedType {
2686 friend class ASTContext; // ASTContext creates these.
2687
2688 inline
2689 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2690
2691public:
2692 QualType getDecayedType() const { return getAdjustedType(); }
2693
2694 inline QualType getPointeeType() const;
2695
2696 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2697};
2698
2699/// Pointer to a block type.
2700/// This type is to represent types syntactically represented as
2701/// "void (^)(int)", etc. Pointee is required to always be a function type.
2702class BlockPointerType : public Type, public llvm::FoldingSetNode {
2703 friend class ASTContext; // ASTContext creates these.
2704
2705 // Block is some kind of pointer type
2706 QualType PointeeType;
2707
2708 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2709 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2710 PointeeType(Pointee) {}
2711
2712public:
2713 // Get the pointee type. Pointee is required to always be a function type.
2714 QualType getPointeeType() const { return PointeeType; }
2715
2716 bool isSugared() const { return false; }
2717 QualType desugar() const { return QualType(this, 0); }
2718
2719 void Profile(llvm::FoldingSetNodeID &ID) {
2720 Profile(ID, getPointeeType());
2721 }
2722
2723 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2724 ID.AddPointer(Pointee.getAsOpaquePtr());
2725 }
2726
2727 static bool classof(const Type *T) {
2728 return T->getTypeClass() == BlockPointer;
2729 }
2730};
2731
2732/// Base for LValueReferenceType and RValueReferenceType
2733class ReferenceType : public Type, public llvm::FoldingSetNode {
2734 QualType PointeeType;
2735
2736protected:
2737 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2738 bool SpelledAsLValue)
2739 : Type(tc, CanonicalRef, Referencee->getDependence()),
2740 PointeeType(Referencee) {
2741 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2742 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2743 }
2744
2745public:
2746 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2747 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2748
2749 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2750
2751 QualType getPointeeType() const {
2752 // FIXME: this might strip inner qualifiers; okay?
2753 const ReferenceType *T = this;
2754 while (T->isInnerRef())
2755 T = T->PointeeType->castAs<ReferenceType>();
2756 return T->PointeeType;
2757 }
2758
2759 void Profile(llvm::FoldingSetNodeID &ID) {
2760 Profile(ID, PointeeType, isSpelledAsLValue());
2761 }
2762
2763 static void Profile(llvm::FoldingSetNodeID &ID,
2764 QualType Referencee,
2765 bool SpelledAsLValue) {
2766 ID.AddPointer(Referencee.getAsOpaquePtr());
2767 ID.AddBoolean(SpelledAsLValue);
2768 }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference ||
2772 T->getTypeClass() == RValueReference;
2773 }
2774};
2775
2776/// An lvalue reference type, per C++11 [dcl.ref].
2777class LValueReferenceType : public ReferenceType {
2778 friend class ASTContext; // ASTContext creates these
2779
2780 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2781 bool SpelledAsLValue)
2782 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2783 SpelledAsLValue) {}
2784
2785public:
2786 bool isSugared() const { return false; }
2787 QualType desugar() const { return QualType(this, 0); }
2788
2789 static bool classof(const Type *T) {
2790 return T->getTypeClass() == LValueReference;
2791 }
2792};
2793
2794/// An rvalue reference type, per C++11 [dcl.ref].
2795class RValueReferenceType : public ReferenceType {
2796 friend class ASTContext; // ASTContext creates these
2797
2798 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2799 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2800
2801public:
2802 bool isSugared() const { return false; }
2803 QualType desugar() const { return QualType(this, 0); }
2804
2805 static bool classof(const Type *T) {
2806 return T->getTypeClass() == RValueReference;
2807 }
2808};
2809
2810/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2811///
2812/// This includes both pointers to data members and pointer to member functions.
2813class MemberPointerType : public Type, public llvm::FoldingSetNode {
2814 friend class ASTContext; // ASTContext creates these.
2815
2816 QualType PointeeType;
2817
2818 /// The class of which the pointee is a member. Must ultimately be a
2819 /// RecordType, but could be a typedef or a template parameter too.
2820 const Type *Class;
2821
2822 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2823 : Type(MemberPointer, CanonicalPtr,
2824 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2825 Pointee->getDependence()),
2826 PointeeType(Pointee), Class(Cls) {}
2827
2828public:
2829 QualType getPointeeType() const { return PointeeType; }
2830
2831 /// Returns true if the member type (i.e. the pointee type) is a
2832 /// function type rather than a data-member type.
2833 bool isMemberFunctionPointer() const {
2834 return PointeeType->isFunctionProtoType();
2835 }
2836
2837 /// Returns true if the member type (i.e. the pointee type) is a
2838 /// data type rather than a function type.
2839 bool isMemberDataPointer() const {
2840 return !PointeeType->isFunctionProtoType();
2841 }
2842
2843 const Type *getClass() const { return Class; }
2844 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2845
2846 bool isSugared() const { return false; }
2847 QualType desugar() const { return QualType(this, 0); }
2848
2849 void Profile(llvm::FoldingSetNodeID &ID) {
2850 Profile(ID, getPointeeType(), getClass());
2851 }
2852
2853 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2854 const Type *Class) {
2855 ID.AddPointer(Pointee.getAsOpaquePtr());
2856 ID.AddPointer(Class);
2857 }
2858
2859 static bool classof(const Type *T) {
2860 return T->getTypeClass() == MemberPointer;
2861 }
2862};
2863
2864/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2865class ArrayType : public Type, public llvm::FoldingSetNode {
2866public:
2867 /// Capture whether this is a normal array (e.g. int X[4])
2868 /// an array with a static size (e.g. int X[static 4]), or an array
2869 /// with a star size (e.g. int X[*]).
2870 /// 'static' is only allowed on function parameters.
2871 enum ArraySizeModifier {
2872 Normal, Static, Star
2873 };
2874
2875private:
2876 /// The element type of the array.
2877 QualType ElementType;
2878
2879protected:
2880 friend class ASTContext; // ASTContext creates these.
2881
2882 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2883 unsigned tq, const Expr *sz = nullptr);
2884
2885public:
2886 QualType getElementType() const { return ElementType; }
2887
2888 ArraySizeModifier getSizeModifier() const {
2889 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2890 }
2891
2892 Qualifiers getIndexTypeQualifiers() const {
2893 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2894 }
2895
2896 unsigned getIndexTypeCVRQualifiers() const {
2897 return ArrayTypeBits.IndexTypeQuals;
2898 }
2899
2900 static bool classof(const Type *T) {
2901 return T->getTypeClass() == ConstantArray ||
2902 T->getTypeClass() == VariableArray ||
2903 T->getTypeClass() == IncompleteArray ||
2904 T->getTypeClass() == DependentSizedArray;
2905 }
2906};
2907
2908/// Represents the canonical version of C arrays with a specified constant size.
2909/// For example, the canonical type for 'int A[4 + 4*100]' is a
2910/// ConstantArrayType where the element type is 'int' and the size is 404.
2911class ConstantArrayType final
2912 : public ArrayType,
2913 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2914 friend class ASTContext; // ASTContext creates these.
2915 friend TrailingObjects;
2916
2917 llvm::APInt Size; // Allows us to unique the type.
2918
2919 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2920 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2921 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2922 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2923 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2924 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 2924, __PRETTY_FUNCTION__))
;
2925 *getTrailingObjects<const Expr*>() = sz;
2926 }
2927 }
2928
2929 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2930 return ConstantArrayTypeBits.HasStoredSizeExpr;
2931 }
2932
2933public:
2934 const llvm::APInt &getSize() const { return Size; }
2935 const Expr *getSizeExpr() const {
2936 return ConstantArrayTypeBits.HasStoredSizeExpr
2937 ? *getTrailingObjects<const Expr *>()
2938 : nullptr;
2939 }
2940 bool isSugared() const { return false; }
2941 QualType desugar() const { return QualType(this, 0); }
2942
2943 /// Determine the number of bits required to address a member of
2944 // an array with the given element type and number of elements.
2945 static unsigned getNumAddressingBits(const ASTContext &Context,
2946 QualType ElementType,
2947 const llvm::APInt &NumElements);
2948
2949 /// Determine the maximum number of active bits that an array's size
2950 /// can require, which limits the maximum size of the array.
2951 static unsigned getMaxSizeBits(const ASTContext &Context);
2952
2953 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2954 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2955 getSizeModifier(), getIndexTypeCVRQualifiers());
2956 }
2957
2958 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2959 QualType ET, const llvm::APInt &ArraySize,
2960 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2961 unsigned TypeQuals);
2962
2963 static bool classof(const Type *T) {
2964 return T->getTypeClass() == ConstantArray;
2965 }
2966};
2967
2968/// Represents a C array with an unspecified size. For example 'int A[]' has
2969/// an IncompleteArrayType where the element type is 'int' and the size is
2970/// unspecified.
2971class IncompleteArrayType : public ArrayType {
2972 friend class ASTContext; // ASTContext creates these.
2973
2974 IncompleteArrayType(QualType et, QualType can,
2975 ArraySizeModifier sm, unsigned tq)
2976 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2977
2978public:
2979 friend class StmtIteratorBase;
2980
2981 bool isSugared() const { return false; }
2982 QualType desugar() const { return QualType(this, 0); }
2983
2984 static bool classof(const Type *T) {
2985 return T->getTypeClass() == IncompleteArray;
2986 }
2987
2988 void Profile(llvm::FoldingSetNodeID &ID) {
2989 Profile(ID, getElementType(), getSizeModifier(),
2990 getIndexTypeCVRQualifiers());
2991 }
2992
2993 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2994 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2995 ID.AddPointer(ET.getAsOpaquePtr());
2996 ID.AddInteger(SizeMod);
2997 ID.AddInteger(TypeQuals);
2998 }
2999};
3000
3001/// Represents a C array with a specified size that is not an
3002/// integer-constant-expression. For example, 'int s[x+foo()]'.
3003/// Since the size expression is an arbitrary expression, we store it as such.
3004///
3005/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3006/// should not be: two lexically equivalent variable array types could mean
3007/// different things, for example, these variables do not have the same type
3008/// dynamically:
3009///
3010/// void foo(int x) {
3011/// int Y[x];
3012/// ++x;
3013/// int Z[x];
3014/// }
3015class VariableArrayType : public ArrayType {
3016 friend class ASTContext; // ASTContext creates these.
3017
3018 /// An assignment-expression. VLA's are only permitted within
3019 /// a function block.
3020 Stmt *SizeExpr;
3021
3022 /// The range spanned by the left and right array brackets.
3023 SourceRange Brackets;
3024
3025 VariableArrayType(QualType et, QualType can, Expr *e,
3026 ArraySizeModifier sm, unsigned tq,
3027 SourceRange brackets)
3028 : ArrayType(VariableArray, et, can, sm, tq, e),
3029 SizeExpr((Stmt*) e), Brackets(brackets) {}
3030
3031public:
3032 friend class StmtIteratorBase;
3033
3034 Expr *getSizeExpr() const {
3035 // We use C-style casts instead of cast<> here because we do not wish
3036 // to have a dependency of Type.h on Stmt.h/Expr.h.
3037 return (Expr*) SizeExpr;
3038 }
3039
3040 SourceRange getBracketsRange() const { return Brackets; }
3041 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3042 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3043
3044 bool isSugared() const { return false; }
3045 QualType desugar() const { return QualType(this, 0); }
3046
3047 static bool classof(const Type *T) {
3048 return T->getTypeClass() == VariableArray;
3049 }
3050
3051 void Profile(llvm::FoldingSetNodeID &ID) {
3052 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 3052)
;
3053 }
3054};
3055
3056/// Represents an array type in C++ whose size is a value-dependent expression.
3057///
3058/// For example:
3059/// \code
3060/// template<typename T, int Size>
3061/// class array {
3062/// T data[Size];
3063/// };
3064/// \endcode
3065///
3066/// For these types, we won't actually know what the array bound is
3067/// until template instantiation occurs, at which point this will
3068/// become either a ConstantArrayType or a VariableArrayType.
3069class DependentSizedArrayType : public ArrayType {
3070 friend class ASTContext; // ASTContext creates these.
3071
3072 const ASTContext &Context;
3073
3074 /// An assignment expression that will instantiate to the
3075 /// size of the array.
3076 ///
3077 /// The expression itself might be null, in which case the array
3078 /// type will have its size deduced from an initializer.
3079 Stmt *SizeExpr;
3080
3081 /// The range spanned by the left and right array brackets.
3082 SourceRange Brackets;
3083
3084 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3085 Expr *e, ArraySizeModifier sm, unsigned tq,
3086 SourceRange brackets);
3087
3088public:
3089 friend class StmtIteratorBase;
3090
3091 Expr *getSizeExpr() const {
3092 // We use C-style casts instead of cast<> here because we do not wish
3093 // to have a dependency of Type.h on Stmt.h/Expr.h.
3094 return (Expr*) SizeExpr;
3095 }
3096
3097 SourceRange getBracketsRange() const { return Brackets; }
3098 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3099 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3100
3101 bool isSugared() const { return false; }
3102 QualType desugar() const { return QualType(this, 0); }
3103
3104 static bool classof(const Type *T) {
3105 return T->getTypeClass() == DependentSizedArray;
3106 }
3107
3108 void Profile(llvm::FoldingSetNodeID &ID) {
3109 Profile(ID, Context, getElementType(),
3110 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3111 }
3112
3113 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3114 QualType ET, ArraySizeModifier SizeMod,
3115 unsigned TypeQuals, Expr *E);
3116};
3117
3118/// Represents an extended address space qualifier where the input address space
3119/// value is dependent. Non-dependent address spaces are not represented with a
3120/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3121///
3122/// For example:
3123/// \code
3124/// template<typename T, int AddrSpace>
3125/// class AddressSpace {
3126/// typedef T __attribute__((address_space(AddrSpace))) type;
3127/// }
3128/// \endcode
3129class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3130 friend class ASTContext;
3131
3132 const ASTContext &Context;
3133 Expr *AddrSpaceExpr;
3134 QualType PointeeType;
3135 SourceLocation loc;
3136
3137 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3138 QualType can, Expr *AddrSpaceExpr,
3139 SourceLocation loc);
3140
3141public:
3142 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3143 QualType getPointeeType() const { return PointeeType; }
3144 SourceLocation getAttributeLoc() const { return loc; }
3145
3146 bool isSugared() const { return false; }
3147 QualType desugar() const { return QualType(this, 0); }
3148
3149 static bool classof(const Type *T) {
3150 return T->getTypeClass() == DependentAddressSpace;
3151 }
3152
3153 void Profile(llvm::FoldingSetNodeID &ID) {
3154 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3155 }
3156
3157 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3158 QualType PointeeType, Expr *AddrSpaceExpr);
3159};
3160
3161/// Represents an extended vector type where either the type or size is
3162/// dependent.
3163///
3164/// For example:
3165/// \code
3166/// template<typename T, int Size>
3167/// class vector {
3168/// typedef T __attribute__((ext_vector_type(Size))) type;
3169/// }
3170/// \endcode
3171class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3172 friend class ASTContext;
3173
3174 const ASTContext &Context;
3175 Expr *SizeExpr;
3176
3177 /// The element type of the array.
3178 QualType ElementType;
3179
3180 SourceLocation loc;
3181
3182 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3183 QualType can, Expr *SizeExpr, SourceLocation loc);
3184
3185public:
3186 Expr *getSizeExpr() const { return SizeExpr; }
3187 QualType getElementType() const { return ElementType; }
3188 SourceLocation getAttributeLoc() const { return loc; }
3189
3190 bool isSugared() const { return false; }
3191 QualType desugar() const { return QualType(this, 0); }
3192
3193 static bool classof(const Type *T) {
3194 return T->getTypeClass() == DependentSizedExtVector;
3195 }
3196
3197 void Profile(llvm::FoldingSetNodeID &ID) {
3198 Profile(ID, Context, getElementType(), getSizeExpr());
3199 }
3200
3201 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3202 QualType ElementType, Expr *SizeExpr);
3203};
3204
3205
3206/// Represents a GCC generic vector type. This type is created using
3207/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3208/// bytes; or from an Altivec __vector or vector declaration.
3209/// Since the constructor takes the number of vector elements, the
3210/// client is responsible for converting the size into the number of elements.
3211class VectorType : public Type, public llvm::FoldingSetNode {
3212public:
3213 enum VectorKind {
3214 /// not a target-specific vector type
3215 GenericVector,
3216
3217 /// is AltiVec vector
3218 AltiVecVector,
3219
3220 /// is AltiVec 'vector Pixel'
3221 AltiVecPixel,
3222
3223 /// is AltiVec 'vector bool ...'
3224 AltiVecBool,
3225
3226 /// is ARM Neon vector
3227 NeonVector,
3228
3229 /// is ARM Neon polynomial vector
3230 NeonPolyVector,
3231
3232 /// is AArch64 SVE fixed-length data vector
3233 SveFixedLengthDataVector,
3234
3235 /// is AArch64 SVE fixed-length predicate vector
3236 SveFixedLengthPredicateVector
3237 };
3238
3239protected:
3240 friend class ASTContext; // ASTContext creates these.
3241
3242 /// The element type of the vector.
3243 QualType ElementType;
3244
3245 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3246 VectorKind vecKind);
3247
3248 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3249 QualType canonType, VectorKind vecKind);
3250
3251public:
3252 QualType getElementType() const { return ElementType; }
3253 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3254
3255 bool isSugared() const { return false; }
3256 QualType desugar() const { return QualType(this, 0); }
3257
3258 VectorKind getVectorKind() const {
3259 return VectorKind(VectorTypeBits.VecKind);
3260 }
3261
3262 void Profile(llvm::FoldingSetNodeID &ID) {
3263 Profile(ID, getElementType(), getNumElements(),
3264 getTypeClass(), getVectorKind());
3265 }
3266
3267 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3268 unsigned NumElements, TypeClass TypeClass,
3269 VectorKind VecKind) {
3270 ID.AddPointer(ElementType.getAsOpaquePtr());
3271 ID.AddInteger(NumElements);
3272 ID.AddInteger(TypeClass);
3273 ID.AddInteger(VecKind);
3274 }
3275
3276 static bool classof(const Type *T) {
3277 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3278 }
3279};
3280
3281/// Represents a vector type where either the type or size is dependent.
3282////
3283/// For example:
3284/// \code
3285/// template<typename T, int Size>
3286/// class vector {
3287/// typedef T __attribute__((vector_size(Size))) type;
3288/// }
3289/// \endcode
3290class DependentVectorType : public Type, public llvm::FoldingSetNode {
3291 friend class ASTContext;
3292
3293 const ASTContext &Context;
3294 QualType ElementType;
3295 Expr *SizeExpr;
3296 SourceLocation Loc;
3297
3298 DependentVectorType(const ASTContext &Context, QualType ElementType,
3299 QualType CanonType, Expr *SizeExpr,
3300 SourceLocation Loc, VectorType::VectorKind vecKind);
3301
3302public:
3303 Expr *getSizeExpr() const { return SizeExpr; }
3304 QualType getElementType() const { return ElementType; }
3305 SourceLocation getAttributeLoc() const { return Loc; }
3306 VectorType::VectorKind getVectorKind() const {
3307 return VectorType::VectorKind(VectorTypeBits.VecKind);
3308 }
3309
3310 bool isSugared() const { return false; }
3311 QualType desugar() const { return QualType(this, 0); }
3312
3313 static bool classof(const Type *T) {
3314 return T->getTypeClass() == DependentVector;
3315 }
3316
3317 void Profile(llvm::FoldingSetNodeID &ID) {
3318 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3319 }
3320
3321 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3322 QualType ElementType, const Expr *SizeExpr,
3323 VectorType::VectorKind VecKind);
3324};
3325
3326/// ExtVectorType - Extended vector type. This type is created using
3327/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3328/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3329/// class enables syntactic extensions, like Vector Components for accessing
3330/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3331/// Shading Language).
3332class ExtVectorType : public VectorType {
3333 friend class ASTContext; // ASTContext creates these.
3334
3335 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3336 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3337
3338public:
3339 static int getPointAccessorIdx(char c) {
3340 switch (c) {
3341 default: return -1;
3342 case 'x': case 'r': return 0;
3343 case 'y': case 'g': return 1;
3344 case 'z': case 'b': return 2;
3345 case 'w': case 'a': return 3;
3346 }
3347 }
3348
3349 static int getNumericAccessorIdx(char c) {
3350 switch (c) {
3351 default: return -1;
3352 case '0': return 0;
3353 case '1': return 1;
3354 case '2': return 2;
3355 case '3': return 3;
3356 case '4': return 4;
3357 case '5': return 5;
3358 case '6': return 6;
3359 case '7': return 7;
3360 case '8': return 8;
3361 case '9': return 9;
3362 case 'A':
3363 case 'a': return 10;
3364 case 'B':
3365 case 'b': return 11;
3366 case 'C':
3367 case 'c': return 12;
3368 case 'D':
3369 case 'd': return 13;
3370 case 'E':
3371 case 'e': return 14;
3372 case 'F':
3373 case 'f': return 15;
3374 }
3375 }
3376
3377 static int getAccessorIdx(char c, bool isNumericAccessor) {
3378 if (isNumericAccessor)
3379 return getNumericAccessorIdx(c);
3380 else
3381 return getPointAccessorIdx(c);
3382 }
3383
3384 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3385 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3386 return unsigned(idx-1) < getNumElements();
3387 return false;
3388 }
3389
3390 bool isSugared() const { return false; }
3391 QualType desugar() const { return QualType(this, 0); }
3392
3393 static bool classof(const Type *T) {
3394 return T->getTypeClass() == ExtVector;
3395 }
3396};
3397
3398/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3399/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3400/// number of rows and "columns" specifies the number of columns.
3401class MatrixType : public Type, public llvm::FoldingSetNode {
3402protected:
3403 friend class ASTContext;
3404
3405 /// The element type of the matrix.
3406 QualType ElementType;
3407
3408 MatrixType(QualType ElementTy, QualType CanonElementTy);
3409
3410 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3411 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3412
3413public:
3414 /// Returns type of the elements being stored in the matrix
3415 QualType getElementType() const { return ElementType; }
3416
3417 /// Valid elements types are the following:
3418 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3419 /// and _Bool
3420 /// * the standard floating types float or double
3421 /// * a half-precision floating point type, if one is supported on the target
3422 static bool isValidElementType(QualType T) {
3423 return T->isDependentType() ||
3424 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3425 }
3426
3427 bool isSugared() const { return false; }
3428 QualType desugar() const { return QualType(this, 0); }
3429
3430 static bool classof(const Type *T) {
3431 return T->getTypeClass() == ConstantMatrix ||
3432 T->getTypeClass() == DependentSizedMatrix;
3433 }
3434};
3435
3436/// Represents a concrete matrix type with constant number of rows and columns
3437class ConstantMatrixType final : public MatrixType {
3438protected:
3439 friend class ASTContext;
3440
3441 /// The element type of the matrix.
3442 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3443 QualType ElementType;
3444
3445 /// Number of rows and columns.
3446 unsigned NumRows;
3447 unsigned NumColumns;
3448
3449 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3450
3451 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3452 unsigned NColumns, QualType CanonElementType);
3453
3454 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3455 unsigned NColumns, QualType CanonElementType);
3456
3457public:
3458 /// Returns the number of rows in the matrix.
3459 unsigned getNumRows() const { return NumRows; }
3460
3461 /// Returns the number of columns in the matrix.
3462 unsigned getNumColumns() const { return NumColumns; }
3463
3464 /// Returns the number of elements required to embed the matrix into a vector.
3465 unsigned getNumElementsFlattened() const {
3466 return getNumRows() * getNumColumns();
3467 }
3468
3469 /// Returns true if \p NumElements is a valid matrix dimension.
3470 static constexpr bool isDimensionValid(size_t NumElements) {
3471 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3472 }
3473
3474 /// Returns the maximum number of elements per dimension.
3475 static constexpr unsigned getMaxElementsPerDimension() {
3476 return MaxElementsPerDimension;
3477 }
3478
3479 void Profile(llvm::FoldingSetNodeID &ID) {
3480 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3481 getTypeClass());
3482 }
3483
3484 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3485 unsigned NumRows, unsigned NumColumns,
3486 TypeClass TypeClass) {
3487 ID.AddPointer(ElementType.getAsOpaquePtr());
3488 ID.AddInteger(NumRows);
3489 ID.AddInteger(NumColumns);
3490 ID.AddInteger(TypeClass);
3491 }
3492
3493 static bool classof(const Type *T) {
3494 return T->getTypeClass() == ConstantMatrix;
3495 }
3496};
3497
3498/// Represents a matrix type where the type and the number of rows and columns
3499/// is dependent on a template.
3500class DependentSizedMatrixType final : public MatrixType {
3501 friend class ASTContext;
3502
3503 const ASTContext &Context;
3504 Expr *RowExpr;
3505 Expr *ColumnExpr;
3506
3507 SourceLocation loc;
3508
3509 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3510 QualType CanonicalType, Expr *RowExpr,
3511 Expr *ColumnExpr, SourceLocation loc);
3512
3513public:
3514 QualType getElementType() const { return ElementType; }
3515 Expr *getRowExpr() const { return RowExpr; }
3516 Expr *getColumnExpr() const { return ColumnExpr; }
3517 SourceLocation getAttributeLoc() const { return loc; }
3518
3519 bool isSugared() const { return false; }
3520 QualType desugar() const { return QualType(this, 0); }
3521
3522 static bool classof(const Type *T) {
3523 return T->getTypeClass() == DependentSizedMatrix;
3524 }
3525
3526 void Profile(llvm::FoldingSetNodeID &ID) {
3527 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3528 }
3529
3530 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3531 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3532};
3533
3534/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3535/// class of FunctionNoProtoType and FunctionProtoType.
3536class FunctionType : public Type {
3537 // The type returned by the function.
3538 QualType ResultType;
3539
3540public:
3541 /// Interesting information about a specific parameter that can't simply
3542 /// be reflected in parameter's type. This is only used by FunctionProtoType
3543 /// but is in FunctionType to make this class available during the
3544 /// specification of the bases of FunctionProtoType.
3545 ///
3546 /// It makes sense to model language features this way when there's some
3547 /// sort of parameter-specific override (such as an attribute) that
3548 /// affects how the function is called. For example, the ARC ns_consumed
3549 /// attribute changes whether a parameter is passed at +0 (the default)
3550 /// or +1 (ns_consumed). This must be reflected in the function type,
3551 /// but isn't really a change to the parameter type.
3552 ///
3553 /// One serious disadvantage of modelling language features this way is
3554 /// that they generally do not work with language features that attempt
3555 /// to destructure types. For example, template argument deduction will
3556 /// not be able to match a parameter declared as
3557 /// T (*)(U)
3558 /// against an argument of type
3559 /// void (*)(__attribute__((ns_consumed)) id)
3560 /// because the substitution of T=void, U=id into the former will
3561 /// not produce the latter.
3562 class ExtParameterInfo {
3563 enum {
3564 ABIMask = 0x0F,
3565 IsConsumed = 0x10,
3566 HasPassObjSize = 0x20,
3567 IsNoEscape = 0x40,
3568 };
3569 unsigned char Data = 0;
3570
3571 public:
3572 ExtParameterInfo() = default;
3573
3574 /// Return the ABI treatment of this parameter.
3575 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3576 ExtParameterInfo withABI(ParameterABI kind) const {
3577 ExtParameterInfo copy = *this;
3578 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3579 return copy;
3580 }
3581
3582 /// Is this parameter considered "consumed" by Objective-C ARC?
3583 /// Consumed parameters must have retainable object type.
3584 bool isConsumed() const { return (Data & IsConsumed); }
3585 ExtParameterInfo withIsConsumed(bool consumed) const {
3586 ExtParameterInfo copy = *this;
3587 if (consumed)
3588 copy.Data |= IsConsumed;
3589 else
3590 copy.Data &= ~IsConsumed;
3591 return copy;
3592 }
3593
3594 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3595 ExtParameterInfo withHasPassObjectSize() const {
3596 ExtParameterInfo Copy = *this;
3597 Copy.Data |= HasPassObjSize;
3598 return Copy;
3599 }
3600
3601 bool isNoEscape() const { return Data & IsNoEscape; }
3602 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3603 ExtParameterInfo Copy = *this;
3604 if (NoEscape)
3605 Copy.Data |= IsNoEscape;
3606 else
3607 Copy.Data &= ~IsNoEscape;
3608 return Copy;
3609 }
3610
3611 unsigned char getOpaqueValue() const { return Data; }
3612 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3613 ExtParameterInfo result;
3614 result.Data = data;
3615 return result;
3616 }
3617
3618 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3619 return lhs.Data == rhs.Data;
3620 }
3621
3622 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3623 return lhs.Data != rhs.Data;
3624 }
3625 };
3626
3627 /// A class which abstracts out some details necessary for
3628 /// making a call.
3629 ///
3630 /// It is not actually used directly for storing this information in
3631 /// a FunctionType, although FunctionType does currently use the
3632 /// same bit-pattern.
3633 ///
3634 // If you add a field (say Foo), other than the obvious places (both,
3635 // constructors, compile failures), what you need to update is
3636 // * Operator==
3637 // * getFoo
3638 // * withFoo
3639 // * functionType. Add Foo, getFoo.
3640 // * ASTContext::getFooType
3641 // * ASTContext::mergeFunctionTypes
3642 // * FunctionNoProtoType::Profile
3643 // * FunctionProtoType::Profile
3644 // * TypePrinter::PrintFunctionProto
3645 // * AST read and write
3646 // * Codegen
3647 class ExtInfo {
3648 friend class FunctionType;
3649
3650 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3651 // adjust the Bits field below, and if you add bits, you'll need to adjust
3652 // Type::FunctionTypeBitfields::ExtInfo as well.
3653
3654 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3655 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3656 //
3657 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3658 enum { CallConvMask = 0x1F };
3659 enum { NoReturnMask = 0x20 };
3660 enum { ProducesResultMask = 0x40 };
3661 enum { NoCallerSavedRegsMask = 0x80 };
3662 enum {
3663 RegParmMask = 0x700,
3664 RegParmOffset = 8
3665 };
3666 enum { NoCfCheckMask = 0x800 };
3667 enum { CmseNSCallMask = 0x1000 };
3668 uint16_t Bits = CC_C;
3669
3670 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3671
3672 public:
3673 // Constructor with no defaults. Use this when you know that you
3674 // have all the elements (when reading an AST file for example).
3675 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3676 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3677 bool cmseNSCall) {
3678 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 3678, __PRETTY_FUNCTION__))
;
3679 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3680 (producesResult ? ProducesResultMask : 0) |
3681 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3682 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3683 (NoCfCheck ? NoCfCheckMask : 0) |
3684 (cmseNSCall ? CmseNSCallMask : 0);
3685 }
3686
3687 // Constructor with all defaults. Use when for example creating a
3688 // function known to use defaults.
3689 ExtInfo() = default;
3690
3691 // Constructor with just the calling convention, which is an important part
3692 // of the canonical type.
3693 ExtInfo(CallingConv CC) : Bits(CC) {}
3694
3695 bool getNoReturn() const { return Bits & NoReturnMask; }
3696 bool getProducesResult() const { return Bits & ProducesResultMask; }
3697 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3698 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3699 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3700 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3701
3702 unsigned getRegParm() const {
3703 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3704 if (RegParm > 0)
3705 --RegParm;
3706 return RegParm;
3707 }
3708
3709 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3710
3711 bool operator==(ExtInfo Other) const {
3712 return Bits == Other.Bits;
3713 }
3714 bool operator!=(ExtInfo Other) const {
3715 return Bits != Other.Bits;
3716 }
3717
3718 // Note that we don't have setters. That is by design, use
3719 // the following with methods instead of mutating these objects.
3720
3721 ExtInfo withNoReturn(bool noReturn) const {
3722 if (noReturn)
3723 return ExtInfo(Bits | NoReturnMask);
3724 else
3725 return ExtInfo(Bits & ~NoReturnMask);
3726 }
3727
3728 ExtInfo withProducesResult(bool producesResult) const {
3729 if (producesResult)
3730 return ExtInfo(Bits | ProducesResultMask);
3731 else
3732 return ExtInfo(Bits & ~ProducesResultMask);
3733 }
3734
3735 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3736 if (cmseNSCall)
3737 return ExtInfo(Bits | CmseNSCallMask);
3738 else
3739 return ExtInfo(Bits & ~CmseNSCallMask);
3740 }
3741
3742 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3743 if (noCallerSavedRegs)
3744 return ExtInfo(Bits | NoCallerSavedRegsMask);
3745 else
3746 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3747 }
3748
3749 ExtInfo withNoCfCheck(bool noCfCheck) const {
3750 if (noCfCheck)
3751 return ExtInfo(Bits | NoCfCheckMask);
3752 else
3753 return ExtInfo(Bits & ~NoCfCheckMask);
3754 }
3755
3756 ExtInfo withRegParm(unsigned RegParm) const {
3757 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 3757, __PRETTY_FUNCTION__))
;
3758 return ExtInfo((Bits & ~RegParmMask) |
3759 ((RegParm + 1) << RegParmOffset));
3760 }
3761
3762 ExtInfo withCallingConv(CallingConv cc) const {
3763 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3764 }
3765
3766 void Profile(llvm::FoldingSetNodeID &ID) const {
3767 ID.AddInteger(Bits);
3768 }
3769 };
3770
3771 /// A simple holder for a QualType representing a type in an
3772 /// exception specification. Unfortunately needed by FunctionProtoType
3773 /// because TrailingObjects cannot handle repeated types.
3774 struct ExceptionType { QualType Type; };
3775
3776 /// A simple holder for various uncommon bits which do not fit in
3777 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3778 /// alignment of subsequent objects in TrailingObjects. You must update
3779 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3780 struct alignas(void *) FunctionTypeExtraBitfields {
3781 /// The number of types in the exception specification.
3782 /// A whole unsigned is not needed here and according to
3783 /// [implimits] 8 bits would be enough here.
3784 unsigned NumExceptionType;
3785 };
3786
3787protected:
3788 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3789 TypeDependence Dependence, ExtInfo Info)
3790 : Type(tc, Canonical, Dependence), ResultType(res) {
3791 FunctionTypeBits.ExtInfo = Info.Bits;
3792 }
3793
3794 Qualifiers getFastTypeQuals() const {
3795 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3796 }
3797
3798public:
3799 QualType getReturnType() const { return ResultType; }
3800
3801 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3802 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3803
3804 /// Determine whether this function type includes the GNU noreturn
3805 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3806 /// type.
3807 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3808
3809 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3810 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3811 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3812
3813 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3814 "Const, volatile and restrict are assumed to be a subset of "
3815 "the fast qualifiers.");
3816
3817 bool isConst() const { return getFastTypeQuals().hasConst(); }
3818 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3819 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3820
3821 /// Determine the type of an expression that calls a function of
3822 /// this type.
3823 QualType getCallResultType(const ASTContext &Context) const {
3824 return getReturnType().getNonLValueExprType(Context);
3825 }
3826
3827 static StringRef getNameForCallConv(CallingConv CC);
3828
3829 static bool classof(const Type *T) {
3830 return T->getTypeClass() == FunctionNoProto ||
3831 T->getTypeClass() == FunctionProto;
3832 }
3833};
3834
3835/// Represents a K&R-style 'int foo()' function, which has
3836/// no information available about its arguments.
3837class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3838 friend class ASTContext; // ASTContext creates these.
3839
3840 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3841 : FunctionType(FunctionNoProto, Result, Canonical,
3842 Result->getDependence() &
3843 ~(TypeDependence::DependentInstantiation |
3844 TypeDependence::UnexpandedPack),
3845 Info) {}
3846
3847public:
3848 // No additional state past what FunctionType provides.
3849
3850 bool isSugared() const { return false; }
3851 QualType desugar() const { return QualType(this, 0); }
3852
3853 void Profile(llvm::FoldingSetNodeID &ID) {
3854 Profile(ID, getReturnType(), getExtInfo());
3855 }
3856
3857 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3858 ExtInfo Info) {
3859 Info.Profile(ID);
3860 ID.AddPointer(ResultType.getAsOpaquePtr());
3861 }
3862
3863 static bool classof(const Type *T) {
3864 return T->getTypeClass() == FunctionNoProto;
3865 }
3866};
3867
3868/// Represents a prototype with parameter type info, e.g.
3869/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3870/// parameters, not as having a single void parameter. Such a type can have
3871/// an exception specification, but this specification is not part of the
3872/// canonical type. FunctionProtoType has several trailing objects, some of
3873/// which optional. For more information about the trailing objects see
3874/// the first comment inside FunctionProtoType.
3875class FunctionProtoType final
3876 : public FunctionType,
3877 public llvm::FoldingSetNode,
3878 private llvm::TrailingObjects<
3879 FunctionProtoType, QualType, SourceLocation,
3880 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3881 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3882 friend class ASTContext; // ASTContext creates these.
3883 friend TrailingObjects;
3884
3885 // FunctionProtoType is followed by several trailing objects, some of
3886 // which optional. They are in order:
3887 //
3888 // * An array of getNumParams() QualType holding the parameter types.
3889 // Always present. Note that for the vast majority of FunctionProtoType,
3890 // these will be the only trailing objects.
3891 //
3892 // * Optionally if the function is variadic, the SourceLocation of the
3893 // ellipsis.
3894 //
3895 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3896 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3897 // a single FunctionTypeExtraBitfields. Present if and only if
3898 // hasExtraBitfields() is true.
3899 //
3900 // * Optionally exactly one of:
3901 // * an array of getNumExceptions() ExceptionType,
3902 // * a single Expr *,
3903 // * a pair of FunctionDecl *,
3904 // * a single FunctionDecl *
3905 // used to store information about the various types of exception
3906 // specification. See getExceptionSpecSize for the details.
3907 //
3908 // * Optionally an array of getNumParams() ExtParameterInfo holding
3909 // an ExtParameterInfo for each of the parameters. Present if and
3910 // only if hasExtParameterInfos() is true.
3911 //
3912 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3913 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3914 // if hasExtQualifiers() is true.
3915 //
3916 // The optional FunctionTypeExtraBitfields has to be before the data
3917 // related to the exception specification since it contains the number
3918 // of exception types.
3919 //
3920 // We put the ExtParameterInfos last. If all were equal, it would make
3921 // more sense to put these before the exception specification, because
3922 // it's much easier to skip past them compared to the elaborate switch
3923 // required to skip the exception specification. However, all is not
3924 // equal; ExtParameterInfos are used to model very uncommon features,
3925 // and it's better not to burden the more common paths.
3926
3927public:
3928 /// Holds information about the various types of exception specification.
3929 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3930 /// used to group together the various bits of information about the
3931 /// exception specification.
3932 struct ExceptionSpecInfo {
3933 /// The kind of exception specification this is.
3934 ExceptionSpecificationType Type = EST_None;
3935
3936 /// Explicitly-specified list of exception types.
3937 ArrayRef<QualType> Exceptions;
3938
3939 /// Noexcept expression, if this is a computed noexcept specification.
3940 Expr *NoexceptExpr = nullptr;
3941
3942 /// The function whose exception specification this is, for
3943 /// EST_Unevaluated and EST_Uninstantiated.
3944 FunctionDecl *SourceDecl = nullptr;
3945
3946 /// The function template whose exception specification this is instantiated
3947 /// from, for EST_Uninstantiated.
3948 FunctionDecl *SourceTemplate = nullptr;
3949
3950 ExceptionSpecInfo() = default;
3951
3952 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3953 };
3954
3955 /// Extra information about a function prototype. ExtProtoInfo is not
3956 /// stored as such in FunctionProtoType but is used to group together
3957 /// the various bits of extra information about a function prototype.
3958 struct ExtProtoInfo {
3959 FunctionType::ExtInfo ExtInfo;
3960 bool Variadic : 1;
3961 bool HasTrailingReturn : 1;
3962 Qualifiers TypeQuals;
3963 RefQualifierKind RefQualifier = RQ_None;
3964 ExceptionSpecInfo ExceptionSpec;
3965 const ExtParameterInfo *ExtParameterInfos = nullptr;
3966 SourceLocation EllipsisLoc;
3967
3968 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3969
3970 ExtProtoInfo(CallingConv CC)
3971 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3972
3973 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3974 ExtProtoInfo Result(*this);
3975 Result.ExceptionSpec = ESI;
3976 return Result;
3977 }
3978 };
3979
3980private:
3981 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3982 return getNumParams();
3983 }
3984
3985 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3986 return isVariadic();
3987 }
3988
3989 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3990 return hasExtraBitfields();
3991 }
3992
3993 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3994 return getExceptionSpecSize().NumExceptionType;
3995 }
3996
3997 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3998 return getExceptionSpecSize().NumExprPtr;
3999 }
4000
4001 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4002 return getExceptionSpecSize().NumFunctionDeclPtr;
4003 }
4004
4005 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4006 return hasExtParameterInfos() ? getNumParams() : 0;
4007 }
4008
4009 /// Determine whether there are any argument types that
4010 /// contain an unexpanded parameter pack.
4011 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4012 unsigned numArgs) {
4013 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4014 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4015 return true;
4016
4017 return false;
4018 }
4019
4020 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4021 QualType canonical, const ExtProtoInfo &epi);
4022
4023 /// This struct is returned by getExceptionSpecSize and is used to
4024 /// translate an ExceptionSpecificationType to the number and kind
4025 /// of trailing objects related to the exception specification.
4026 struct ExceptionSpecSizeHolder {
4027 unsigned NumExceptionType;
4028 unsigned NumExprPtr;
4029 unsigned NumFunctionDeclPtr;
4030 };
4031
4032 /// Return the number and kind of trailing objects
4033 /// related to the exception specification.
4034 static ExceptionSpecSizeHolder
4035 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4036 switch (EST) {
4037 case EST_None:
4038 case EST_DynamicNone:
4039 case EST_MSAny:
4040 case EST_BasicNoexcept:
4041 case EST_Unparsed:
4042 case EST_NoThrow:
4043 return {0, 0, 0};
4044
4045 case EST_Dynamic:
4046 return {NumExceptions, 0, 0};
4047
4048 case EST_DependentNoexcept:
4049 case EST_NoexceptFalse:
4050 case EST_NoexceptTrue:
4051 return {0, 1, 0};
4052
4053 case EST_Uninstantiated:
4054 return {0, 0, 2};
4055
4056 case EST_Unevaluated:
4057 return {0, 0, 1};
4058 }
4059 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4059)
;
4060 }
4061
4062 /// Return the number and kind of trailing objects
4063 /// related to the exception specification.
4064 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4065 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4066 }
4067
4068 /// Whether the trailing FunctionTypeExtraBitfields is present.
4069 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4070 // If the exception spec type is EST_Dynamic then we have > 0 exception
4071 // types and the exact number is stored in FunctionTypeExtraBitfields.
4072 return EST == EST_Dynamic;
4073 }
4074
4075 /// Whether the trailing FunctionTypeExtraBitfields is present.
4076 bool hasExtraBitfields() const {
4077 return hasExtraBitfields(getExceptionSpecType());
4078 }
4079
4080 bool hasExtQualifiers() const {
4081 return FunctionTypeBits.HasExtQuals;
4082 }
4083
4084public:
4085 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4086
4087 QualType getParamType(unsigned i) const {
4088 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4088, __PRETTY_FUNCTION__))
;
4089 return param_type_begin()[i];
4090 }
4091
4092 ArrayRef<QualType> getParamTypes() const {
4093 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4094 }
4095
4096 ExtProtoInfo getExtProtoInfo() const {
4097 ExtProtoInfo EPI;
4098 EPI.ExtInfo = getExtInfo();
4099 EPI.Variadic = isVariadic();
4100 EPI.EllipsisLoc = getEllipsisLoc();
4101 EPI.HasTrailingReturn = hasTrailingReturn();
4102 EPI.ExceptionSpec = getExceptionSpecInfo();
4103 EPI.TypeQuals = getMethodQuals();
4104 EPI.RefQualifier = getRefQualifier();
4105 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4106 return EPI;
4107 }
4108
4109 /// Get the kind of exception specification on this function.
4110 ExceptionSpecificationType getExceptionSpecType() const {
4111 return static_cast<ExceptionSpecificationType>(
4112 FunctionTypeBits.ExceptionSpecType);
4113 }
4114
4115 /// Return whether this function has any kind of exception spec.
4116 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4117
4118 /// Return whether this function has a dynamic (throw) exception spec.
4119 bool hasDynamicExceptionSpec() const {
4120 return isDynamicExceptionSpec(getExceptionSpecType());
4121 }
4122
4123 /// Return whether this function has a noexcept exception spec.
4124 bool hasNoexceptExceptionSpec() const {
4125 return isNoexceptExceptionSpec(getExceptionSpecType());
4126 }
4127
4128 /// Return whether this function has a dependent exception spec.
4129 bool hasDependentExceptionSpec() const;
4130
4131 /// Return whether this function has an instantiation-dependent exception
4132 /// spec.
4133 bool hasInstantiationDependentExceptionSpec() const;
4134
4135 /// Return all the available information about this type's exception spec.
4136 ExceptionSpecInfo getExceptionSpecInfo() const {
4137 ExceptionSpecInfo Result;
4138 Result.Type = getExceptionSpecType();
4139 if (Result.Type == EST_Dynamic) {
4140 Result.Exceptions = exceptions();
4141 } else if (isComputedNoexcept(Result.Type)) {
4142 Result.NoexceptExpr = getNoexceptExpr();
4143 } else if (Result.Type == EST_Uninstantiated) {
4144 Result.SourceDecl = getExceptionSpecDecl();
4145 Result.SourceTemplate = getExceptionSpecTemplate();
4146 } else if (Result.Type == EST_Unevaluated) {
4147 Result.SourceDecl = getExceptionSpecDecl();
4148 }
4149 return Result;
4150 }
4151
4152 /// Return the number of types in the exception specification.
4153 unsigned getNumExceptions() const {
4154 return getExceptionSpecType() == EST_Dynamic
4155 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4156 ->NumExceptionType
4157 : 0;
4158 }
4159
4160 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4161 QualType getExceptionType(unsigned i) const {
4162 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4162, __PRETTY_FUNCTION__))
;
4163 return exception_begin()[i];
4164 }
4165
4166 /// Return the expression inside noexcept(expression), or a null pointer
4167 /// if there is none (because the exception spec is not of this form).
4168 Expr *getNoexceptExpr() const {
4169 if (!isComputedNoexcept(getExceptionSpecType()))
4170 return nullptr;
4171 return *getTrailingObjects<Expr *>();
4172 }
4173
4174 /// If this function type has an exception specification which hasn't
4175 /// been determined yet (either because it has not been evaluated or because
4176 /// it has not been instantiated), this is the function whose exception
4177 /// specification is represented by this type.
4178 FunctionDecl *getExceptionSpecDecl() const {
4179 if (getExceptionSpecType() != EST_Uninstantiated &&
4180 getExceptionSpecType() != EST_Unevaluated)
4181 return nullptr;
4182 return getTrailingObjects<FunctionDecl *>()[0];
4183 }
4184
4185 /// If this function type has an uninstantiated exception
4186 /// specification, this is the function whose exception specification
4187 /// should be instantiated to find the exception specification for
4188 /// this type.
4189 FunctionDecl *getExceptionSpecTemplate() const {
4190 if (getExceptionSpecType() != EST_Uninstantiated)
4191 return nullptr;
4192 return getTrailingObjects<FunctionDecl *>()[1];
4193 }
4194
4195 /// Determine whether this function type has a non-throwing exception
4196 /// specification.
4197 CanThrowResult canThrow() const;
4198
4199 /// Determine whether this function type has a non-throwing exception
4200 /// specification. If this depends on template arguments, returns
4201 /// \c ResultIfDependent.
4202 bool isNothrow(bool ResultIfDependent = false) const {
4203 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4204 }
4205
4206 /// Whether this function prototype is variadic.
4207 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4208
4209 SourceLocation getEllipsisLoc() const {
4210 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4211 : SourceLocation();
4212 }
4213
4214 /// Determines whether this function prototype contains a
4215 /// parameter pack at the end.
4216 ///
4217 /// A function template whose last parameter is a parameter pack can be
4218 /// called with an arbitrary number of arguments, much like a variadic
4219 /// function.
4220 bool isTemplateVariadic() const;
4221
4222 /// Whether this function prototype has a trailing return type.
4223 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4224
4225 Qualifiers getMethodQuals() const {
4226 if (hasExtQualifiers())
4227 return *getTrailingObjects<Qualifiers>();
4228 else
4229 return getFastTypeQuals();
4230 }
4231
4232 /// Retrieve the ref-qualifier associated with this function type.
4233 RefQualifierKind getRefQualifier() const {
4234 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4235 }
4236
4237 using param_type_iterator = const QualType *;
4238 using param_type_range = llvm::iterator_range<param_type_iterator>;
4239
4240 param_type_range param_types() const {
4241 return param_type_range(param_type_begin(), param_type_end());
4242 }
4243
4244 param_type_iterator param_type_begin() const {
4245 return getTrailingObjects<QualType>();
4246 }
4247
4248 param_type_iterator param_type_end() const {
4249 return param_type_begin() + getNumParams();
4250 }
4251
4252 using exception_iterator = const QualType *;
4253
4254 ArrayRef<QualType> exceptions() const {
4255 return llvm::makeArrayRef(exception_begin(), exception_end());
4256 }
4257
4258 exception_iterator exception_begin() const {
4259 return reinterpret_cast<exception_iterator>(
4260 getTrailingObjects<ExceptionType>());
4261 }
4262
4263 exception_iterator exception_end() const {
4264 return exception_begin() + getNumExceptions();
4265 }
4266
4267 /// Is there any interesting extra information for any of the parameters
4268 /// of this function type?
4269 bool hasExtParameterInfos() const {
4270 return FunctionTypeBits.HasExtParameterInfos;
4271 }
4272
4273 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4274 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4274, __PRETTY_FUNCTION__))
;
4275 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4276 getNumParams());
4277 }
4278
4279 /// Return a pointer to the beginning of the array of extra parameter
4280 /// information, if present, or else null if none of the parameters
4281 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4282 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4283 if (!hasExtParameterInfos())
4284 return nullptr;
4285 return getTrailingObjects<ExtParameterInfo>();
4286 }
4287
4288 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4289 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4289, __PRETTY_FUNCTION__))
;
4290 if (hasExtParameterInfos())
4291 return getTrailingObjects<ExtParameterInfo>()[I];
4292 return ExtParameterInfo();
4293 }
4294
4295 ParameterABI getParameterABI(unsigned I) const {
4296 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4296, __PRETTY_FUNCTION__))
;
4297 if (hasExtParameterInfos())
4298 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4299 return ParameterABI::Ordinary;
4300 }
4301
4302 bool isParamConsumed(unsigned I) const {
4303 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4303, __PRETTY_FUNCTION__))
;
4304 if (hasExtParameterInfos())
4305 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4306 return false;
4307 }
4308
4309 bool isSugared() const { return false; }
4310 QualType desugar() const { return QualType(this, 0); }
4311
4312 void printExceptionSpecification(raw_ostream &OS,
4313 const PrintingPolicy &Policy) const;
4314
4315 static bool classof(const Type *T) {
4316 return T->getTypeClass() == FunctionProto;
4317 }
4318
4319 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4320 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4321 param_type_iterator ArgTys, unsigned NumArgs,
4322 const ExtProtoInfo &EPI, const ASTContext &Context,
4323 bool Canonical);
4324};
4325
4326/// Represents the dependent type named by a dependently-scoped
4327/// typename using declaration, e.g.
4328/// using typename Base<T>::foo;
4329///
4330/// Template instantiation turns these into the underlying type.
4331class UnresolvedUsingType : public Type {
4332 friend class ASTContext; // ASTContext creates these.
4333
4334 UnresolvedUsingTypenameDecl *Decl;
4335
4336 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4337 : Type(UnresolvedUsing, QualType(),
4338 TypeDependence::DependentInstantiation),
4339 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4340
4341public:
4342 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4343
4344 bool isSugared() const { return false; }
4345 QualType desugar() const { return QualType(this, 0); }
4346
4347 static bool classof(const Type *T) {
4348 return T->getTypeClass() == UnresolvedUsing;
4349 }
4350
4351 void Profile(llvm::FoldingSetNodeID &ID) {
4352 return Profile(ID, Decl);
4353 }
4354
4355 static void Profile(llvm::FoldingSetNodeID &ID,
4356 UnresolvedUsingTypenameDecl *D) {
4357 ID.AddPointer(D);
4358 }
4359};
4360
4361class TypedefType : public Type {
4362 TypedefNameDecl *Decl;
4363
4364protected:
4365 friend class ASTContext; // ASTContext creates these.
4366
4367 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can);
4368
4369public:
4370 TypedefNameDecl *getDecl() const { return Decl; }
4371
4372 bool isSugared() const { return true; }
4373 QualType desugar() const;
4374
4375 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4376};
4377
4378/// Sugar type that represents a type that was qualified by a qualifier written
4379/// as a macro invocation.
4380class MacroQualifiedType : public Type {
4381 friend class ASTContext; // ASTContext creates these.
4382
4383 QualType UnderlyingTy;
4384 const IdentifierInfo *MacroII;
4385
4386 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4387 const IdentifierInfo *MacroII)
4388 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4389 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4390 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4391, __PRETTY_FUNCTION__))
4391 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4391, __PRETTY_FUNCTION__))
;
4392 }
4393
4394public:
4395 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4396 QualType getUnderlyingType() const { return UnderlyingTy; }
4397
4398 /// Return this attributed type's modified type with no qualifiers attached to
4399 /// it.
4400 QualType getModifiedType() const;
4401
4402 bool isSugared() const { return true; }
4403 QualType desugar() const;
4404
4405 static bool classof(const Type *T) {
4406 return T->getTypeClass() == MacroQualified;
4407 }
4408};
4409
4410/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4411class TypeOfExprType : public Type {
4412 Expr *TOExpr;
4413
4414protected:
4415 friend class ASTContext; // ASTContext creates these.
4416
4417 TypeOfExprType(Expr *E, QualType can = QualType());
4418
4419public:
4420 Expr *getUnderlyingExpr() const { return TOExpr; }
4421
4422 /// Remove a single level of sugar.
4423 QualType desugar() const;
4424
4425 /// Returns whether this type directly provides sugar.
4426 bool isSugared() const;
4427
4428 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4429};
4430
4431/// Internal representation of canonical, dependent
4432/// `typeof(expr)` types.
4433///
4434/// This class is used internally by the ASTContext to manage
4435/// canonical, dependent types, only. Clients will only see instances
4436/// of this class via TypeOfExprType nodes.
4437class DependentTypeOfExprType
4438 : public TypeOfExprType, public llvm::FoldingSetNode {
4439 const ASTContext &Context;
4440
4441public:
4442 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4443 : TypeOfExprType(E), Context(Context) {}
4444
4445 void Profile(llvm::FoldingSetNodeID &ID) {
4446 Profile(ID, Context, getUnderlyingExpr());
4447 }
4448
4449 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4450 Expr *E);
4451};
4452
4453/// Represents `typeof(type)`, a GCC extension.
4454class TypeOfType : public Type {
4455 friend class ASTContext; // ASTContext creates these.
4456
4457 QualType TOType;
4458
4459 TypeOfType(QualType T, QualType can)
4460 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4461 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4461, __PRETTY_FUNCTION__))
;
4462 }
4463
4464public:
4465 QualType getUnderlyingType() const { return TOType; }
4466
4467 /// Remove a single level of sugar.
4468 QualType desugar() const { return getUnderlyingType(); }
4469
4470 /// Returns whether this type directly provides sugar.
4471 bool isSugared() const { return true; }
4472
4473 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4474};
4475
4476/// Represents the type `decltype(expr)` (C++11).
4477class DecltypeType : public Type {
4478 Expr *E;
4479 QualType UnderlyingType;
4480
4481protected:
4482 friend class ASTContext; // ASTContext creates these.
4483
4484 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4485
4486public:
4487 Expr *getUnderlyingExpr() const { return E; }
4488 QualType getUnderlyingType() const { return UnderlyingType; }
4489
4490 /// Remove a single level of sugar.
4491 QualType desugar() const;
4492
4493 /// Returns whether this type directly provides sugar.
4494 bool isSugared() const;
4495
4496 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4497};
4498
4499/// Internal representation of canonical, dependent
4500/// decltype(expr) types.
4501///
4502/// This class is used internally by the ASTContext to manage
4503/// canonical, dependent types, only. Clients will only see instances
4504/// of this class via DecltypeType nodes.
4505class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4506 const ASTContext &Context;
4507
4508public:
4509 DependentDecltypeType(const ASTContext &Context, Expr *E);
4510
4511 void Profile(llvm::FoldingSetNodeID &ID) {
4512 Profile(ID, Context, getUnderlyingExpr());
4513 }
4514
4515 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4516 Expr *E);
4517};
4518
4519/// A unary type transform, which is a type constructed from another.
4520class UnaryTransformType : public Type {
4521public:
4522 enum UTTKind {
4523 EnumUnderlyingType
4524 };
4525
4526private:
4527 /// The untransformed type.
4528 QualType BaseType;
4529
4530 /// The transformed type if not dependent, otherwise the same as BaseType.
4531 QualType UnderlyingType;
4532
4533 UTTKind UKind;
4534
4535protected:
4536 friend class ASTContext;
4537
4538 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4539 QualType CanonicalTy);
4540
4541public:
4542 bool isSugared() const { return !isDependentType(); }
4543 QualType desugar() const { return UnderlyingType; }
4544
4545 QualType getUnderlyingType() const { return UnderlyingType; }
4546 QualType getBaseType() const { return BaseType; }
4547
4548 UTTKind getUTTKind() const { return UKind; }
4549
4550 static bool classof(const Type *T) {
4551 return T->getTypeClass() == UnaryTransform;
4552 }
4553};
4554
4555/// Internal representation of canonical, dependent
4556/// __underlying_type(type) types.
4557///
4558/// This class is used internally by the ASTContext to manage
4559/// canonical, dependent types, only. Clients will only see instances
4560/// of this class via UnaryTransformType nodes.
4561class DependentUnaryTransformType : public UnaryTransformType,
4562 public llvm::FoldingSetNode {
4563public:
4564 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4565 UTTKind UKind);
4566
4567 void Profile(llvm::FoldingSetNodeID &ID) {
4568 Profile(ID, getBaseType(), getUTTKind());
4569 }
4570
4571 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4572 UTTKind UKind) {
4573 ID.AddPointer(BaseType.getAsOpaquePtr());
4574 ID.AddInteger((unsigned)UKind);
4575 }
4576};
4577
4578class TagType : public Type {
4579 friend class ASTReader;
4580 template <class T> friend class serialization::AbstractTypeReader;
4581
4582 /// Stores the TagDecl associated with this type. The decl may point to any
4583 /// TagDecl that declares the entity.
4584 TagDecl *decl;
4585
4586protected:
4587 TagType(TypeClass TC, const TagDecl *D, QualType can);
4588
4589public:
4590 TagDecl *getDecl() const;
4591
4592 /// Determines whether this type is in the process of being defined.
4593 bool isBeingDefined() const;
4594
4595 static bool classof(const Type *T) {
4596 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4597 }
4598};
4599
4600/// A helper class that allows the use of isa/cast/dyncast
4601/// to detect TagType objects of structs/unions/classes.
4602class RecordType : public TagType {
4603protected:
4604 friend class ASTContext; // ASTContext creates these.
4605
4606 explicit RecordType(const RecordDecl *D)
4607 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4608 explicit RecordType(TypeClass TC, RecordDecl *D)
4609 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4610
4611public:
4612 RecordDecl *getDecl() const {
4613 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4614 }
4615
4616 /// Recursively check all fields in the record for const-ness. If any field
4617 /// is declared const, return true. Otherwise, return false.
4618 bool hasConstFields() const;
4619
4620 bool isSugared() const { return false; }
4621 QualType desugar() const { return QualType(this, 0); }
4622
4623 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4624};
4625
4626/// A helper class that allows the use of isa/cast/dyncast
4627/// to detect TagType objects of enums.
4628class EnumType : public TagType {
4629 friend class ASTContext; // ASTContext creates these.
4630
4631 explicit EnumType(const EnumDecl *D)
4632 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4633
4634public:
4635 EnumDecl *getDecl() const {
4636 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4637 }
4638
4639 bool isSugared() const { return false; }
4640 QualType desugar() const { return QualType(this, 0); }
4641
4642 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4643};
4644
4645/// An attributed type is a type to which a type attribute has been applied.
4646///
4647/// The "modified type" is the fully-sugared type to which the attributed
4648/// type was applied; generally it is not canonically equivalent to the
4649/// attributed type. The "equivalent type" is the minimally-desugared type
4650/// which the type is canonically equivalent to.
4651///
4652/// For example, in the following attributed type:
4653/// int32_t __attribute__((vector_size(16)))
4654/// - the modified type is the TypedefType for int32_t
4655/// - the equivalent type is VectorType(16, int32_t)
4656/// - the canonical type is VectorType(16, int)
4657class AttributedType : public Type, public llvm::FoldingSetNode {
4658public:
4659 using Kind = attr::Kind;
4660
4661private:
4662 friend class ASTContext; // ASTContext creates these
4663
4664 QualType ModifiedType;
4665 QualType EquivalentType;
4666
4667 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4668 QualType equivalent)
4669 : Type(Attributed, canon, equivalent->getDependence()),
4670 ModifiedType(modified), EquivalentType(equivalent) {
4671 AttributedTypeBits.AttrKind = attrKind;
4672 }
4673
4674public:
4675 Kind getAttrKind() const {
4676 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4677 }
4678
4679 QualType getModifiedType() const { return ModifiedType; }
4680 QualType getEquivalentType() const { return EquivalentType; }
4681
4682 bool isSugared() const { return true; }
4683 QualType desugar() const { return getEquivalentType(); }
4684
4685 /// Does this attribute behave like a type qualifier?
4686 ///
4687 /// A type qualifier adjusts a type to provide specialized rules for
4688 /// a specific object, like the standard const and volatile qualifiers.
4689 /// This includes attributes controlling things like nullability,
4690 /// address spaces, and ARC ownership. The value of the object is still
4691 /// largely described by the modified type.
4692 ///
4693 /// In contrast, many type attributes "rewrite" their modified type to
4694 /// produce a fundamentally different type, not necessarily related in any
4695 /// formalizable way to the original type. For example, calling convention
4696 /// and vector attributes are not simple type qualifiers.
4697 ///
4698 /// Type qualifiers are often, but not always, reflected in the canonical
4699 /// type.
4700 bool isQualifier() const;
4701
4702 bool isMSTypeSpec() const;
4703
4704 bool isCallingConv() const;
4705
4706 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4707
4708 /// Retrieve the attribute kind corresponding to the given
4709 /// nullability kind.
4710 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4711 switch (kind) {
4712 case NullabilityKind::NonNull:
4713 return attr::TypeNonNull;
4714
4715 case NullabilityKind::Nullable:
4716 return attr::TypeNullable;
4717
4718 case NullabilityKind::Unspecified:
4719 return attr::TypeNullUnspecified;
4720 }
4721 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 4721)
;
4722 }
4723
4724 /// Strip off the top-level nullability annotation on the given
4725 /// type, if it's there.
4726 ///
4727 /// \param T The type to strip. If the type is exactly an
4728 /// AttributedType specifying nullability (without looking through
4729 /// type sugar), the nullability is returned and this type changed
4730 /// to the underlying modified type.
4731 ///
4732 /// \returns the top-level nullability, if present.
4733 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4734
4735 void Profile(llvm::FoldingSetNodeID &ID) {
4736 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4737 }
4738
4739 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4740 QualType modified, QualType equivalent) {
4741 ID.AddInteger(attrKind);
4742 ID.AddPointer(modified.getAsOpaquePtr());
4743 ID.AddPointer(equivalent.getAsOpaquePtr());
4744 }
4745
4746 static bool classof(const Type *T) {
4747 return T->getTypeClass() == Attributed;
4748 }
4749};
4750
4751class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4752 friend class ASTContext; // ASTContext creates these
4753
4754 // Helper data collector for canonical types.
4755 struct CanonicalTTPTInfo {
4756 unsigned Depth : 15;
4757 unsigned ParameterPack : 1;
4758 unsigned Index : 16;
4759 };
4760
4761 union {
4762 // Info for the canonical type.
4763 CanonicalTTPTInfo CanTTPTInfo;
4764
4765 // Info for the non-canonical type.
4766 TemplateTypeParmDecl *TTPDecl;
4767 };
4768
4769 /// Build a non-canonical type.
4770 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4771 : Type(TemplateTypeParm, Canon,
4772 TypeDependence::DependentInstantiation |
4773 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4774 TTPDecl(TTPDecl) {}
4775
4776 /// Build the canonical type.
4777 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4778 : Type(TemplateTypeParm, QualType(this, 0),
4779 TypeDependence::DependentInstantiation |
4780 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4781 CanTTPTInfo.Depth = D;
4782 CanTTPTInfo.Index = I;
4783 CanTTPTInfo.ParameterPack = PP;
4784 }
4785
4786 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4787 QualType Can = getCanonicalTypeInternal();
4788 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4789 }
4790
4791public:
4792 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4793 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4794 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4795
4796 TemplateTypeParmDecl *getDecl() const {
4797 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4798 }
4799
4800 IdentifierInfo *getIdentifier() const;
4801
4802 bool isSugared() const { return false; }
4803 QualType desugar() const { return QualType(this, 0); }
4804
4805 void Profile(llvm::FoldingSetNodeID &ID) {
4806 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4807 }
4808
4809 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4810 unsigned Index, bool ParameterPack,
4811 TemplateTypeParmDecl *TTPDecl) {
4812 ID.AddInteger(Depth);
4813 ID.AddInteger(Index);
4814 ID.AddBoolean(ParameterPack);
4815 ID.AddPointer(TTPDecl);
4816 }
4817
4818 static bool classof(const Type *T) {
4819 return T->getTypeClass() == TemplateTypeParm;
4820 }
4821};
4822
4823/// Represents the result of substituting a type for a template
4824/// type parameter.
4825///
4826/// Within an instantiated template, all template type parameters have
4827/// been replaced with these. They are used solely to record that a
4828/// type was originally written as a template type parameter;
4829/// therefore they are never canonical.
4830class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4831 friend class ASTContext;
4832
4833 // The original type parameter.
4834 const TemplateTypeParmType *Replaced;
4835
4836 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4837 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4838 Replaced(Param) {}
4839
4840public:
4841 /// Gets the template parameter that was substituted for.
4842 const TemplateTypeParmType *getReplacedParameter() const {
4843 return Replaced;
4844 }
4845
4846 /// Gets the type that was substituted for the template
4847 /// parameter.
4848 QualType getReplacementType() const {
4849 return getCanonicalTypeInternal();
4850 }
4851
4852 bool isSugared() const { return true; }
4853 QualType desugar() const { return getReplacementType(); }
4854
4855 void Profile(llvm::FoldingSetNodeID &ID) {
4856 Profile(ID, getReplacedParameter(), getReplacementType());
4857 }
4858
4859 static void Profile(llvm::FoldingSetNodeID &ID,
4860 const TemplateTypeParmType *Replaced,
4861 QualType Replacement) {
4862 ID.AddPointer(Replaced);
4863 ID.AddPointer(Replacement.getAsOpaquePtr());
4864 }
4865
4866 static bool classof(const Type *T) {
4867 return T->getTypeClass() == SubstTemplateTypeParm;
4868 }
4869};
4870
4871/// Represents the result of substituting a set of types for a template
4872/// type parameter pack.
4873///
4874/// When a pack expansion in the source code contains multiple parameter packs
4875/// and those parameter packs correspond to different levels of template
4876/// parameter lists, this type node is used to represent a template type
4877/// parameter pack from an outer level, which has already had its argument pack
4878/// substituted but that still lives within a pack expansion that itself
4879/// could not be instantiated. When actually performing a substitution into
4880/// that pack expansion (e.g., when all template parameters have corresponding
4881/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4882/// at the current pack substitution index.
4883class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4884 friend class ASTContext;
4885
4886 /// The original type parameter.
4887 const TemplateTypeParmType *Replaced;
4888
4889 /// A pointer to the set of template arguments that this
4890 /// parameter pack is instantiated with.
4891 const TemplateArgument *Arguments;
4892
4893 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4894 QualType Canon,
4895 const TemplateArgument &ArgPack);
4896
4897public:
4898 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4899
4900 /// Gets the template parameter that was substituted for.
4901 const TemplateTypeParmType *getReplacedParameter() const {
4902 return Replaced;
4903 }
4904
4905 unsigned getNumArgs() const {
4906 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4907 }
4908
4909 bool isSugared() const { return false; }
4910 QualType desugar() const { return QualType(this, 0); }
4911
4912 TemplateArgument getArgumentPack() const;
4913
4914 void Profile(llvm::FoldingSetNodeID &ID);
4915 static void Profile(llvm::FoldingSetNodeID &ID,
4916 const TemplateTypeParmType *Replaced,
4917 const TemplateArgument &ArgPack);
4918
4919 static bool classof(const Type *T) {
4920 return T->getTypeClass() == SubstTemplateTypeParmPack;
4921 }
4922};
4923
4924/// Common base class for placeholders for types that get replaced by
4925/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4926/// class template types, and constrained type names.
4927///
4928/// These types are usually a placeholder for a deduced type. However, before
4929/// the initializer is attached, or (usually) if the initializer is
4930/// type-dependent, there is no deduced type and the type is canonical. In
4931/// the latter case, it is also a dependent type.
4932class DeducedType : public Type {
4933protected:
4934 DeducedType(TypeClass TC, QualType DeducedAsType,
4935 TypeDependence ExtraDependence)
4936 : Type(TC,
4937 // FIXME: Retain the sugared deduced type?
4938 DeducedAsType.isNull() ? QualType(this, 0)
4939 : DeducedAsType.getCanonicalType(),
4940 ExtraDependence | (DeducedAsType.isNull()
4941 ? TypeDependence::None
4942 : DeducedAsType->getDependence() &
4943 ~TypeDependence::VariablyModified)) {}
4944
4945public:
4946 bool isSugared() const { return !isCanonicalUnqualified(); }
4947 QualType desugar() const { return getCanonicalTypeInternal(); }
4948
4949 /// Get the type deduced for this placeholder type, or null if it's
4950 /// either not been deduced or was deduced to a dependent type.
4951 QualType getDeducedType() const {
4952 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4953 }
4954 bool isDeduced() const {
4955 return !isCanonicalUnqualified() || isDependentType();
4956 }
4957
4958 static bool classof(const Type *T) {
4959 return T->getTypeClass() == Auto ||
4960 T->getTypeClass() == DeducedTemplateSpecialization;
4961 }
4962};
4963
4964/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4965/// by a type-constraint.
4966class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4967 friend class ASTContext; // ASTContext creates these
4968
4969 ConceptDecl *TypeConstraintConcept;
4970
4971 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4972 TypeDependence ExtraDependence, ConceptDecl *CD,
4973 ArrayRef<TemplateArgument> TypeConstraintArgs);
4974
4975 const TemplateArgument *getArgBuffer() const {
4976 return reinterpret_cast<const TemplateArgument*>(this+1);
4977 }
4978
4979 TemplateArgument *getArgBuffer() {
4980 return reinterpret_cast<TemplateArgument*>(this+1);
4981 }
4982
4983public:
4984 /// Retrieve the template arguments.
4985 const TemplateArgument *getArgs() const {
4986 return getArgBuffer();
4987 }
4988
4989 /// Retrieve the number of template arguments.
4990 unsigned getNumArgs() const {
4991 return AutoTypeBits.NumArgs;
4992 }
4993
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 ConceptDecl *getTypeConstraintConcept() const {
5001 return TypeConstraintConcept;
5002 }
5003
5004 bool isConstrained() const {
5005 return TypeConstraintConcept != nullptr;
5006 }
5007
5008 bool isDecltypeAuto() const {
5009 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5010 }
5011
5012 AutoTypeKeyword getKeyword() const {
5013 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5014 }
5015
5016 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5017 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5018 getTypeConstraintConcept(), getTypeConstraintArguments());
5019 }
5020
5021 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5022 QualType Deduced, AutoTypeKeyword Keyword,
5023 bool IsDependent, ConceptDecl *CD,
5024 ArrayRef<TemplateArgument> Arguments);
5025
5026 static bool classof(const Type *T) {
5027 return T->getTypeClass() == Auto;
5028 }
5029};
5030
5031/// Represents a C++17 deduced template specialization type.
5032class DeducedTemplateSpecializationType : public DeducedType,
5033 public llvm::FoldingSetNode {
5034 friend class ASTContext; // ASTContext creates these
5035
5036 /// The name of the template whose arguments will be deduced.
5037 TemplateName Template;
5038
5039 DeducedTemplateSpecializationType(TemplateName Template,
5040 QualType DeducedAsType,
5041 bool IsDeducedAsDependent)
5042 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5043 toTypeDependence(Template.getDependence()) |
5044 (IsDeducedAsDependent
5045 ? TypeDependence::DependentInstantiation
5046 : TypeDependence::None)),
5047 Template(Template) {}
5048
5049public:
5050 /// Retrieve the name of the template that we are deducing.
5051 TemplateName getTemplateName() const { return Template;}
5052
5053 void Profile(llvm::FoldingSetNodeID &ID) {
5054 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5055 }
5056
5057 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5058 QualType Deduced, bool IsDependent) {
5059 Template.Profile(ID);
5060 ID.AddPointer(Deduced.getAsOpaquePtr());
5061 ID.AddBoolean(IsDependent);
5062 }
5063
5064 static bool classof(const Type *T) {
5065 return T->getTypeClass() == DeducedTemplateSpecialization;
5066 }
5067};
5068
5069/// Represents a type template specialization; the template
5070/// must be a class template, a type alias template, or a template
5071/// template parameter. A template which cannot be resolved to one of
5072/// these, e.g. because it is written with a dependent scope
5073/// specifier, is instead represented as a
5074/// @c DependentTemplateSpecializationType.
5075///
5076/// A non-dependent template specialization type is always "sugar",
5077/// typically for a \c RecordType. For example, a class template
5078/// specialization type of \c vector<int> will refer to a tag type for
5079/// the instantiation \c std::vector<int, std::allocator<int>>
5080///
5081/// Template specializations are dependent if either the template or
5082/// any of the template arguments are dependent, in which case the
5083/// type may also be canonical.
5084///
5085/// Instances of this type are allocated with a trailing array of
5086/// TemplateArguments, followed by a QualType representing the
5087/// non-canonical aliased type when the template is a type alias
5088/// template.
5089class alignas(8) TemplateSpecializationType
5090 : public Type,
5091 public llvm::FoldingSetNode {
5092 friend class ASTContext; // ASTContext creates these
5093
5094 /// The name of the template being specialized. This is
5095 /// either a TemplateName::Template (in which case it is a
5096 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5097 /// TypeAliasTemplateDecl*), a
5098 /// TemplateName::SubstTemplateTemplateParmPack, or a
5099 /// TemplateName::SubstTemplateTemplateParm (in which case the
5100 /// replacement must, recursively, be one of these).
5101 TemplateName Template;
5102
5103 TemplateSpecializationType(TemplateName T,
5104 ArrayRef<TemplateArgument> Args,
5105 QualType Canon,
5106 QualType Aliased);
5107
5108public:
5109 /// Determine whether any of the given template arguments are dependent.
5110 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5111 bool &InstantiationDependent);
5112
5113 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5114 bool &InstantiationDependent);
5115
5116 /// True if this template specialization type matches a current
5117 /// instantiation in the context in which it is found.
5118 bool isCurrentInstantiation() const {
5119 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5120 }
5121
5122 /// Determine if this template specialization type is for a type alias
5123 /// template that has been substituted.
5124 ///
5125 /// Nearly every template specialization type whose template is an alias
5126 /// template will be substituted. However, this is not the case when
5127 /// the specialization contains a pack expansion but the template alias
5128 /// does not have a corresponding parameter pack, e.g.,
5129 ///
5130 /// \code
5131 /// template<typename T, typename U, typename V> struct S;
5132 /// template<typename T, typename U> using A = S<T, int, U>;
5133 /// template<typename... Ts> struct X {
5134 /// typedef A<Ts...> type; // not a type alias
5135 /// };
5136 /// \endcode
5137 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5138
5139 /// Get the aliased type, if this is a specialization of a type alias
5140 /// template.
5141 QualType getAliasedType() const {
5142 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5142, __PRETTY_FUNCTION__))
;
5143 return *reinterpret_cast<const QualType*>(end());
5144 }
5145
5146 using iterator = const TemplateArgument *;
5147
5148 iterator begin() const { return getArgs(); }
5149 iterator end() const; // defined inline in TemplateBase.h
5150
5151 /// Retrieve the name of the template that we are specializing.
5152 TemplateName getTemplateName() const { return Template; }
5153
5154 /// Retrieve the template arguments.
5155 const TemplateArgument *getArgs() const {
5156 return reinterpret_cast<const TemplateArgument *>(this + 1);
5157 }
5158
5159 /// Retrieve the number of template arguments.
5160 unsigned getNumArgs() const {
5161 return TemplateSpecializationTypeBits.NumArgs;
5162 }
5163
5164 /// Retrieve a specific template argument as a type.
5165 /// \pre \c isArgType(Arg)
5166 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5167
5168 ArrayRef<TemplateArgument> template_arguments() const {
5169 return {getArgs(), getNumArgs()};
5170 }
5171
5172 bool isSugared() const {
5173 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5174 }
5175
5176 QualType desugar() const {
5177 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5178 }
5179
5180 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5181 Profile(ID, Template, template_arguments(), Ctx);
5182 if (isTypeAlias())
5183 getAliasedType().Profile(ID);
5184 }
5185
5186 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5187 ArrayRef<TemplateArgument> Args,
5188 const ASTContext &Context);
5189
5190 static bool classof(const Type *T) {
5191 return T->getTypeClass() == TemplateSpecialization;
5192 }
5193};
5194
5195/// Print a template argument list, including the '<' and '>'
5196/// enclosing the template arguments.
5197void printTemplateArgumentList(raw_ostream &OS,
5198 ArrayRef<TemplateArgument> Args,
5199 const PrintingPolicy &Policy);
5200
5201void printTemplateArgumentList(raw_ostream &OS,
5202 ArrayRef<TemplateArgumentLoc> Args,
5203 const PrintingPolicy &Policy);
5204
5205void printTemplateArgumentList(raw_ostream &OS,
5206 const TemplateArgumentListInfo &Args,
5207 const PrintingPolicy &Policy);
5208
5209/// The injected class name of a C++ class template or class
5210/// template partial specialization. Used to record that a type was
5211/// spelled with a bare identifier rather than as a template-id; the
5212/// equivalent for non-templated classes is just RecordType.
5213///
5214/// Injected class name types are always dependent. Template
5215/// instantiation turns these into RecordTypes.
5216///
5217/// Injected class name types are always canonical. This works
5218/// because it is impossible to compare an injected class name type
5219/// with the corresponding non-injected template type, for the same
5220/// reason that it is impossible to directly compare template
5221/// parameters from different dependent contexts: injected class name
5222/// types can only occur within the scope of a particular templated
5223/// declaration, and within that scope every template specialization
5224/// will canonicalize to the injected class name (when appropriate
5225/// according to the rules of the language).
5226class InjectedClassNameType : public Type {
5227 friend class ASTContext; // ASTContext creates these.
5228 friend class ASTNodeImporter;
5229 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5230 // currently suitable for AST reading, too much
5231 // interdependencies.
5232 template <class T> friend class serialization::AbstractTypeReader;
5233
5234 CXXRecordDecl *Decl;
5235
5236 /// The template specialization which this type represents.
5237 /// For example, in
5238 /// template <class T> class A { ... };
5239 /// this is A<T>, whereas in
5240 /// template <class X, class Y> class A<B<X,Y> > { ... };
5241 /// this is A<B<X,Y> >.
5242 ///
5243 /// It is always unqualified, always a template specialization type,
5244 /// and always dependent.
5245 QualType InjectedType;
5246
5247 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5248 : Type(InjectedClassName, QualType(),
5249 TypeDependence::DependentInstantiation),
5250 Decl(D), InjectedType(TST) {
5251 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5251, __PRETTY_FUNCTION__))
;
5252 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5252, __PRETTY_FUNCTION__))
;
5253 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5253, __PRETTY_FUNCTION__))
;
5254 }
5255
5256public:
5257 QualType getInjectedSpecializationType() const { return InjectedType; }
5258
5259 const TemplateSpecializationType *getInjectedTST() const {
5260 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5261 }
5262
5263 TemplateName getTemplateName() const {
5264 return getInjectedTST()->getTemplateName();
5265 }
5266
5267 CXXRecordDecl *getDecl() const;
5268
5269 bool isSugared() const { return false; }
5270 QualType desugar() const { return QualType(this, 0); }
5271
5272 static bool classof(const Type *T) {
5273 return T->getTypeClass() == InjectedClassName;
5274 }
5275};
5276
5277/// The kind of a tag type.
5278enum TagTypeKind {
5279 /// The "struct" keyword.
5280 TTK_Struct,
5281
5282 /// The "__interface" keyword.
5283 TTK_Interface,
5284
5285 /// The "union" keyword.
5286 TTK_Union,
5287
5288 /// The "class" keyword.
5289 TTK_Class,
5290
5291 /// The "enum" keyword.
5292 TTK_Enum
5293};
5294
5295/// The elaboration keyword that precedes a qualified type name or
5296/// introduces an elaborated-type-specifier.
5297enum ElaboratedTypeKeyword {
5298 /// The "struct" keyword introduces the elaborated-type-specifier.
5299 ETK_Struct,
5300
5301 /// The "__interface" keyword introduces the elaborated-type-specifier.
5302 ETK_Interface,
5303
5304 /// The "union" keyword introduces the elaborated-type-specifier.
5305 ETK_Union,
5306
5307 /// The "class" keyword introduces the elaborated-type-specifier.
5308 ETK_Class,
5309
5310 /// The "enum" keyword introduces the elaborated-type-specifier.
5311 ETK_Enum,
5312
5313 /// The "typename" keyword precedes the qualified type name, e.g.,
5314 /// \c typename T::type.
5315 ETK_Typename,
5316
5317 /// No keyword precedes the qualified type name.
5318 ETK_None
5319};
5320
5321/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5322/// The keyword in stored in the free bits of the base class.
5323/// Also provides a few static helpers for converting and printing
5324/// elaborated type keyword and tag type kind enumerations.
5325class TypeWithKeyword : public Type {
5326protected:
5327 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5328 QualType Canonical, TypeDependence Dependence)
5329 : Type(tc, Canonical, Dependence) {
5330 TypeWithKeywordBits.Keyword = Keyword;
5331 }
5332
5333public:
5334 ElaboratedTypeKeyword getKeyword() const {
5335 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5336 }
5337
5338 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5339 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5340
5341 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5342 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5343 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5344
5345 /// Converts a TagTypeKind into an elaborated type keyword.
5346 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5347
5348 /// Converts an elaborated type keyword into a TagTypeKind.
5349 /// It is an error to provide an elaborated type keyword
5350 /// which *isn't* a tag kind here.
5351 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5352
5353 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5354
5355 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5356
5357 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5358 return getKeywordName(getKeywordForTagTypeKind(Kind));
5359 }
5360
5361 class CannotCastToThisType {};
5362 static CannotCastToThisType classof(const Type *);
5363};
5364
5365/// Represents a type that was referred to using an elaborated type
5366/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5367/// or both.
5368///
5369/// This type is used to keep track of a type name as written in the
5370/// source code, including tag keywords and any nested-name-specifiers.
5371/// The type itself is always "sugar", used to express what was written
5372/// in the source code but containing no additional semantic information.
5373class ElaboratedType final
5374 : public TypeWithKeyword,
5375 public llvm::FoldingSetNode,
5376 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5377 friend class ASTContext; // ASTContext creates these
5378 friend TrailingObjects;
5379
5380 /// The nested name specifier containing the qualifier.
5381 NestedNameSpecifier *NNS;
5382
5383 /// The type that this qualified name refers to.
5384 QualType NamedType;
5385
5386 /// The (re)declaration of this tag type owned by this occurrence is stored
5387 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5388 /// it, or obtain a null pointer if there is none.
5389
5390 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5391 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5392 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5393 NamedType->getDependence()),
5394 NNS(NNS), NamedType(NamedType) {
5395 ElaboratedTypeBits.HasOwnedTagDecl = false;
5396 if (OwnedTagDecl) {
5397 ElaboratedTypeBits.HasOwnedTagDecl = true;
5398 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5399 }
5400 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5402, __PRETTY_FUNCTION__))
5401 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5402, __PRETTY_FUNCTION__))
5402 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5402, __PRETTY_FUNCTION__))
;
5403 }
5404
5405public:
5406 /// Retrieve the qualification on this type.
5407 NestedNameSpecifier *getQualifier() const { return NNS; }
5408
5409 /// Retrieve the type named by the qualified-id.
5410 QualType getNamedType() const { return NamedType; }
5411
5412 /// Remove a single level of sugar.
5413 QualType desugar() const { return getNamedType(); }
5414
5415 /// Returns whether this type directly provides sugar.
5416 bool isSugared() const { return true; }
5417
5418 /// Return the (re)declaration of this type owned by this occurrence of this
5419 /// type, or nullptr if there is none.
5420 TagDecl *getOwnedTagDecl() const {
5421 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5422 : nullptr;
5423 }
5424
5425 void Profile(llvm::FoldingSetNodeID &ID) {
5426 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5427 }
5428
5429 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5430 NestedNameSpecifier *NNS, QualType NamedType,
5431 TagDecl *OwnedTagDecl) {
5432 ID.AddInteger(Keyword);
5433 ID.AddPointer(NNS);
5434 NamedType.Profile(ID);
5435 ID.AddPointer(OwnedTagDecl);
5436 }
5437
5438 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5439};
5440
5441/// Represents a qualified type name for which the type name is
5442/// dependent.
5443///
5444/// DependentNameType represents a class of dependent types that involve a
5445/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5446/// name of a type. The DependentNameType may start with a "typename" (for a
5447/// typename-specifier), "class", "struct", "union", or "enum" (for a
5448/// dependent elaborated-type-specifier), or nothing (in contexts where we
5449/// know that we must be referring to a type, e.g., in a base class specifier).
5450/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5451/// mode, this type is used with non-dependent names to delay name lookup until
5452/// instantiation.
5453class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5454 friend class ASTContext; // ASTContext creates these
5455
5456 /// The nested name specifier containing the qualifier.
5457 NestedNameSpecifier *NNS;
5458
5459 /// The type that this typename specifier refers to.
5460 const IdentifierInfo *Name;
5461
5462 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5463 const IdentifierInfo *Name, QualType CanonType)
5464 : TypeWithKeyword(Keyword, DependentName, CanonType,
5465 TypeDependence::DependentInstantiation |
5466 toTypeDependence(NNS->getDependence())),
5467 NNS(NNS), Name(Name) {}
5468
5469public:
5470 /// Retrieve the qualification on this type.
5471 NestedNameSpecifier *getQualifier() const { return NNS; }
5472
5473 /// Retrieve the type named by the typename specifier as an identifier.
5474 ///
5475 /// This routine will return a non-NULL identifier pointer when the
5476 /// form of the original typename was terminated by an identifier,
5477 /// e.g., "typename T::type".
5478 const IdentifierInfo *getIdentifier() const {
5479 return Name;
5480 }
5481
5482 bool isSugared() const { return false; }
5483 QualType desugar() const { return QualType(this, 0); }
5484
5485 void Profile(llvm::FoldingSetNodeID &ID) {
5486 Profile(ID, getKeyword(), NNS, Name);
5487 }
5488
5489 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5490 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5491 ID.AddInteger(Keyword);
5492 ID.AddPointer(NNS);
5493 ID.AddPointer(Name);
5494 }
5495
5496 static bool classof(const Type *T) {
5497 return T->getTypeClass() == DependentName;
5498 }
5499};
5500
5501/// Represents a template specialization type whose template cannot be
5502/// resolved, e.g.
5503/// A<T>::template B<T>
5504class alignas(8) DependentTemplateSpecializationType
5505 : public TypeWithKeyword,
5506 public llvm::FoldingSetNode {
5507 friend class ASTContext; // ASTContext creates these
5508
5509 /// The nested name specifier containing the qualifier.
5510 NestedNameSpecifier *NNS;
5511
5512 /// The identifier of the template.
5513 const IdentifierInfo *Name;
5514
5515 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5516 NestedNameSpecifier *NNS,
5517 const IdentifierInfo *Name,
5518 ArrayRef<TemplateArgument> Args,
5519 QualType Canon);
5520
5521 const TemplateArgument *getArgBuffer() const {
5522 return reinterpret_cast<const TemplateArgument*>(this+1);
5523 }
5524
5525 TemplateArgument *getArgBuffer() {
5526 return reinterpret_cast<TemplateArgument*>(this+1);
5527 }
5528
5529public:
5530 NestedNameSpecifier *getQualifier() const { return NNS; }
5531 const IdentifierInfo *getIdentifier() const { return Name; }
5532
5533 /// Retrieve the template arguments.
5534 const TemplateArgument *getArgs() const {
5535 return getArgBuffer();
5536 }
5537
5538 /// Retrieve the number of template arguments.
5539 unsigned getNumArgs() const {
5540 return DependentTemplateSpecializationTypeBits.NumArgs;
5541 }
5542
5543 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5544
5545 ArrayRef<TemplateArgument> template_arguments() const {
5546 return {getArgs(), getNumArgs()};
5547 }
5548
5549 using iterator = const TemplateArgument *;
5550
5551 iterator begin() const { return getArgs(); }
5552 iterator end() const; // inline in TemplateBase.h
5553
5554 bool isSugared() const { return false; }
5555 QualType desugar() const { return QualType(this, 0); }
5556
5557 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5558 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5559 }
5560
5561 static void Profile(llvm::FoldingSetNodeID &ID,
5562 const ASTContext &Context,
5563 ElaboratedTypeKeyword Keyword,
5564 NestedNameSpecifier *Qualifier,
5565 const IdentifierInfo *Name,
5566 ArrayRef<TemplateArgument> Args);
5567
5568 static bool classof(const Type *T) {
5569 return T->getTypeClass() == DependentTemplateSpecialization;
5570 }
5571};
5572
5573/// Represents a pack expansion of types.
5574///
5575/// Pack expansions are part of C++11 variadic templates. A pack
5576/// expansion contains a pattern, which itself contains one or more
5577/// "unexpanded" parameter packs. When instantiated, a pack expansion
5578/// produces a series of types, each instantiated from the pattern of
5579/// the expansion, where the Ith instantiation of the pattern uses the
5580/// Ith arguments bound to each of the unexpanded parameter packs. The
5581/// pack expansion is considered to "expand" these unexpanded
5582/// parameter packs.
5583///
5584/// \code
5585/// template<typename ...Types> struct tuple;
5586///
5587/// template<typename ...Types>
5588/// struct tuple_of_references {
5589/// typedef tuple<Types&...> type;
5590/// };
5591/// \endcode
5592///
5593/// Here, the pack expansion \c Types&... is represented via a
5594/// PackExpansionType whose pattern is Types&.
5595class PackExpansionType : public Type, public llvm::FoldingSetNode {
5596 friend class ASTContext; // ASTContext creates these
5597
5598 /// The pattern of the pack expansion.
5599 QualType Pattern;
5600
5601 PackExpansionType(QualType Pattern, QualType Canon,
5602 Optional<unsigned> NumExpansions)
5603 : Type(PackExpansion, Canon,
5604 (Pattern->getDependence() | TypeDependence::Dependent |
5605 TypeDependence::Instantiation) &
5606 ~TypeDependence::UnexpandedPack),
5607 Pattern(Pattern) {
5608 PackExpansionTypeBits.NumExpansions =
5609 NumExpansions ? *NumExpansions + 1 : 0;
5610 }
5611
5612public:
5613 /// Retrieve the pattern of this pack expansion, which is the
5614 /// type that will be repeatedly instantiated when instantiating the
5615 /// pack expansion itself.
5616 QualType getPattern() const { return Pattern; }
5617
5618 /// Retrieve the number of expansions that this pack expansion will
5619 /// generate, if known.
5620 Optional<unsigned> getNumExpansions() const {
5621 if (PackExpansionTypeBits.NumExpansions)
5622 return PackExpansionTypeBits.NumExpansions - 1;
5623 return None;
5624 }
5625
5626 bool isSugared() const { return false; }
5627 QualType desugar() const { return QualType(this, 0); }
5628
5629 void Profile(llvm::FoldingSetNodeID &ID) {
5630 Profile(ID, getPattern(), getNumExpansions());
5631 }
5632
5633 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5634 Optional<unsigned> NumExpansions) {
5635 ID.AddPointer(Pattern.getAsOpaquePtr());
5636 ID.AddBoolean(NumExpansions.hasValue());
5637 if (NumExpansions)
5638 ID.AddInteger(*NumExpansions);
5639 }
5640
5641 static bool classof(const Type *T) {
5642 return T->getTypeClass() == PackExpansion;
5643 }
5644};
5645
5646/// This class wraps the list of protocol qualifiers. For types that can
5647/// take ObjC protocol qualifers, they can subclass this class.
5648template <class T>
5649class ObjCProtocolQualifiers {
5650protected:
5651 ObjCProtocolQualifiers() = default;
5652
5653 ObjCProtocolDecl * const *getProtocolStorage() const {
5654 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5655 }
5656
5657 ObjCProtocolDecl **getProtocolStorage() {
5658 return static_cast<T*>(this)->getProtocolStorageImpl();
5659 }
5660
5661 void setNumProtocols(unsigned N) {
5662 static_cast<T*>(this)->setNumProtocolsImpl(N);
5663 }
5664
5665 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5666 setNumProtocols(protocols.size());
5667 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5668, __PRETTY_FUNCTION__))
5668 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5668, __PRETTY_FUNCTION__))
;
5669 if (!protocols.empty())
5670 memcpy(getProtocolStorage(), protocols.data(),
5671 protocols.size() * sizeof(ObjCProtocolDecl*));
5672 }
5673
5674public:
5675 using qual_iterator = ObjCProtocolDecl * const *;
5676 using qual_range = llvm::iterator_range<qual_iterator>;
5677
5678 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5679 qual_iterator qual_begin() const { return getProtocolStorage(); }
5680 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5681
5682 bool qual_empty() const { return getNumProtocols() == 0; }
5683
5684 /// Return the number of qualifying protocols in this type, or 0 if
5685 /// there are none.
5686 unsigned getNumProtocols() const {
5687 return static_cast<const T*>(this)->getNumProtocolsImpl();
5688 }
5689
5690 /// Fetch a protocol by index.
5691 ObjCProtocolDecl *getProtocol(unsigned I) const {
5692 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5692, __PRETTY_FUNCTION__))
;
5693 return qual_begin()[I];
5694 }
5695
5696 /// Retrieve all of the protocol qualifiers.
5697 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5698 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5699 }
5700};
5701
5702/// Represents a type parameter type in Objective C. It can take
5703/// a list of protocols.
5704class ObjCTypeParamType : public Type,
5705 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5706 public llvm::FoldingSetNode {
5707 friend class ASTContext;
5708 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5709
5710 /// The number of protocols stored on this type.
5711 unsigned NumProtocols : 6;
5712
5713 ObjCTypeParamDecl *OTPDecl;
5714
5715 /// The protocols are stored after the ObjCTypeParamType node. In the
5716 /// canonical type, the list of protocols are sorted alphabetically
5717 /// and uniqued.
5718 ObjCProtocolDecl **getProtocolStorageImpl();
5719
5720 /// Return the number of qualifying protocols in this interface type,
5721 /// or 0 if there are none.
5722 unsigned getNumProtocolsImpl() const {
5723 return NumProtocols;
5724 }
5725
5726 void setNumProtocolsImpl(unsigned N) {
5727 NumProtocols = N;
5728 }
5729
5730 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5731 QualType can,
5732 ArrayRef<ObjCProtocolDecl *> protocols);
5733
5734public:
5735 bool isSugared() const { return true; }
5736 QualType desugar() const { return getCanonicalTypeInternal(); }
5737
5738 static bool classof(const Type *T) {
5739 return T->getTypeClass() == ObjCTypeParam;
5740 }
5741
5742 void Profile(llvm::FoldingSetNodeID &ID);
5743 static void Profile(llvm::FoldingSetNodeID &ID,
5744 const ObjCTypeParamDecl *OTPDecl,
5745 QualType CanonicalType,
5746 ArrayRef<ObjCProtocolDecl *> protocols);
5747
5748 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5749};
5750
5751/// Represents a class type in Objective C.
5752///
5753/// Every Objective C type is a combination of a base type, a set of
5754/// type arguments (optional, for parameterized classes) and a list of
5755/// protocols.
5756///
5757/// Given the following declarations:
5758/// \code
5759/// \@class C<T>;
5760/// \@protocol P;
5761/// \endcode
5762///
5763/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5764/// with base C and no protocols.
5765///
5766/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5767/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5768/// protocol list.
5769/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5770/// and protocol list [P].
5771///
5772/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5773/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5774/// and no protocols.
5775///
5776/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5777/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5778/// this should get its own sugar class to better represent the source.
5779class ObjCObjectType : public Type,
5780 public ObjCProtocolQualifiers<ObjCObjectType> {
5781 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5782
5783 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5784 // after the ObjCObjectPointerType node.
5785 // ObjCObjectType.NumProtocols - the number of protocols stored
5786 // after the type arguments of ObjCObjectPointerType node.
5787 //
5788 // These protocols are those written directly on the type. If
5789 // protocol qualifiers ever become additive, the iterators will need
5790 // to get kindof complicated.
5791 //
5792 // In the canonical object type, these are sorted alphabetically
5793 // and uniqued.
5794
5795 /// Either a BuiltinType or an InterfaceType or sugar for either.
5796 QualType BaseType;
5797
5798 /// Cached superclass type.
5799 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5800 CachedSuperClassType;
5801
5802 QualType *getTypeArgStorage();
5803 const QualType *getTypeArgStorage() const {
5804 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5805 }
5806
5807 ObjCProtocolDecl **getProtocolStorageImpl();
5808 /// Return the number of qualifying protocols in this interface type,
5809 /// or 0 if there are none.
5810 unsigned getNumProtocolsImpl() const {
5811 return ObjCObjectTypeBits.NumProtocols;
5812 }
5813 void setNumProtocolsImpl(unsigned N) {
5814 ObjCObjectTypeBits.NumProtocols = N;
5815 }
5816
5817protected:
5818 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5819
5820 ObjCObjectType(QualType Canonical, QualType Base,
5821 ArrayRef<QualType> typeArgs,
5822 ArrayRef<ObjCProtocolDecl *> protocols,
5823 bool isKindOf);
5824
5825 ObjCObjectType(enum Nonce_ObjCInterface)
5826 : Type(ObjCInterface, QualType(), TypeDependence::None),
5827 BaseType(QualType(this_(), 0)) {
5828 ObjCObjectTypeBits.NumProtocols = 0;
5829 ObjCObjectTypeBits.NumTypeArgs = 0;
5830 ObjCObjectTypeBits.IsKindOf = 0;
5831 }
5832
5833 void computeSuperClassTypeSlow() const;
5834
5835public:
5836 /// Gets the base type of this object type. This is always (possibly
5837 /// sugar for) one of:
5838 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5839 /// user, which is a typedef for an ObjCObjectPointerType)
5840 /// - the 'Class' builtin type (same caveat)
5841 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5842 QualType getBaseType() const { return BaseType; }
5843
5844 bool isObjCId() const {
5845 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5846 }
5847
5848 bool isObjCClass() const {
5849 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5850 }
5851
5852 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5853 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5854 bool isObjCUnqualifiedIdOrClass() const {
5855 if (!qual_empty()) return false;
5856 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5857 return T->getKind() == BuiltinType::ObjCId ||
5858 T->getKind() == BuiltinType::ObjCClass;
5859 return false;
5860 }
5861 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5862 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5863
5864 /// Gets the interface declaration for this object type, if the base type
5865 /// really is an interface.
5866 ObjCInterfaceDecl *getInterface() const;
5867
5868 /// Determine whether this object type is "specialized", meaning
5869 /// that it has type arguments.
5870 bool isSpecialized() const;
5871
5872 /// Determine whether this object type was written with type arguments.
5873 bool isSpecializedAsWritten() const {
5874 return ObjCObjectTypeBits.NumTypeArgs > 0;
5875 }
5876
5877 /// Determine whether this object type is "unspecialized", meaning
5878 /// that it has no type arguments.
5879 bool isUnspecialized() const { return !isSpecialized(); }
5880
5881 /// Determine whether this object type is "unspecialized" as
5882 /// written, meaning that it has no type arguments.
5883 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5884
5885 /// Retrieve the type arguments of this object type (semantically).
5886 ArrayRef<QualType> getTypeArgs() const;
5887
5888 /// Retrieve the type arguments of this object type as they were
5889 /// written.
5890 ArrayRef<QualType> getTypeArgsAsWritten() const {
5891 return llvm::makeArrayRef(getTypeArgStorage(),
5892 ObjCObjectTypeBits.NumTypeArgs);
5893 }
5894
5895 /// Whether this is a "__kindof" type as written.
5896 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5897
5898 /// Whether this ia a "__kindof" type (semantically).
5899 bool isKindOfType() const;
5900
5901 /// Retrieve the type of the superclass of this object type.
5902 ///
5903 /// This operation substitutes any type arguments into the
5904 /// superclass of the current class type, potentially producing a
5905 /// specialization of the superclass type. Produces a null type if
5906 /// there is no superclass.
5907 QualType getSuperClassType() const {
5908 if (!CachedSuperClassType.getInt())
5909 computeSuperClassTypeSlow();
5910
5911 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 5911, __PRETTY_FUNCTION__))
;
5912 return QualType(CachedSuperClassType.getPointer(), 0);
5913 }
5914
5915 /// Strip off the Objective-C "kindof" type and (with it) any
5916 /// protocol qualifiers.
5917 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5918
5919 bool isSugared() const { return false; }
5920 QualType desugar() const { return QualType(this, 0); }
5921
5922 static bool classof(const Type *T) {
5923 return T->getTypeClass() == ObjCObject ||
5924 T->getTypeClass() == ObjCInterface;
5925 }
5926};
5927
5928/// A class providing a concrete implementation
5929/// of ObjCObjectType, so as to not increase the footprint of
5930/// ObjCInterfaceType. Code outside of ASTContext and the core type
5931/// system should not reference this type.
5932class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5933 friend class ASTContext;
5934
5935 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5936 // will need to be modified.
5937
5938 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5939 ArrayRef<QualType> typeArgs,
5940 ArrayRef<ObjCProtocolDecl *> protocols,
5941 bool isKindOf)
5942 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5943
5944public:
5945 void Profile(llvm::FoldingSetNodeID &ID);
5946 static void Profile(llvm::FoldingSetNodeID &ID,
5947 QualType Base,
5948 ArrayRef<QualType> typeArgs,
5949 ArrayRef<ObjCProtocolDecl *> protocols,
5950 bool isKindOf);
5951};
5952
5953inline QualType *ObjCObjectType::getTypeArgStorage() {
5954 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5955}
5956
5957inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5958 return reinterpret_cast<ObjCProtocolDecl**>(
5959 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5960}
5961
5962inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5963 return reinterpret_cast<ObjCProtocolDecl**>(
5964 static_cast<ObjCTypeParamType*>(this)+1);
5965}
5966
5967/// Interfaces are the core concept in Objective-C for object oriented design.
5968/// They basically correspond to C++ classes. There are two kinds of interface
5969/// types: normal interfaces like `NSString`, and qualified interfaces, which
5970/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5971///
5972/// ObjCInterfaceType guarantees the following properties when considered
5973/// as a subtype of its superclass, ObjCObjectType:
5974/// - There are no protocol qualifiers. To reinforce this, code which
5975/// tries to invoke the protocol methods via an ObjCInterfaceType will
5976/// fail to compile.
5977/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5978/// T->getBaseType() == QualType(T, 0).
5979class ObjCInterfaceType : public ObjCObjectType {
5980 friend class ASTContext; // ASTContext creates these.
5981 friend class ASTReader;
5982 friend class ObjCInterfaceDecl;
5983 template <class T> friend class serialization::AbstractTypeReader;
5984
5985 mutable ObjCInterfaceDecl *Decl;
5986
5987 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5988 : ObjCObjectType(Nonce_ObjCInterface),
5989 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5990
5991public:
5992 /// Get the declaration of this interface.
5993 ObjCInterfaceDecl *getDecl() const { return Decl; }
5994
5995 bool isSugared() const { return false; }
5996 QualType desugar() const { return QualType(this, 0); }
5997
5998 static bool classof(const Type *T) {
5999 return T->getTypeClass() == ObjCInterface;
6000 }
6001
6002 // Nonsense to "hide" certain members of ObjCObjectType within this
6003 // class. People asking for protocols on an ObjCInterfaceType are
6004 // not going to get what they want: ObjCInterfaceTypes are
6005 // guaranteed to have no protocols.
6006 enum {
6007 qual_iterator,
6008 qual_begin,
6009 qual_end,
6010 getNumProtocols,
6011 getProtocol
6012 };
6013};
6014
6015inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6016 QualType baseType = getBaseType();
6017 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6018 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6019 return T->getDecl();
6020
6021 baseType = ObjT->getBaseType();
6022 }
6023
6024 return nullptr;
6025}
6026
6027/// Represents a pointer to an Objective C object.
6028///
6029/// These are constructed from pointer declarators when the pointee type is
6030/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6031/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6032/// and 'Class<P>' are translated into these.
6033///
6034/// Pointers to pointers to Objective C objects are still PointerTypes;
6035/// only the first level of pointer gets it own type implementation.
6036class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6037 friend class ASTContext; // ASTContext creates these.
6038
6039 QualType PointeeType;
6040
6041 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6042 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6043 PointeeType(Pointee) {}
6044
6045public:
6046 /// Gets the type pointed to by this ObjC pointer.
6047 /// The result will always be an ObjCObjectType or sugar thereof.
6048 QualType getPointeeType() const { return PointeeType; }
6049
6050 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6051 ///
6052 /// This method is equivalent to getPointeeType() except that
6053 /// it discards any typedefs (or other sugar) between this
6054 /// type and the "outermost" object type. So for:
6055 /// \code
6056 /// \@class A; \@protocol P; \@protocol Q;
6057 /// typedef A<P> AP;
6058 /// typedef A A1;
6059 /// typedef A1<P> A1P;
6060 /// typedef A1P<Q> A1PQ;
6061 /// \endcode
6062 /// For 'A*', getObjectType() will return 'A'.
6063 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6064 /// For 'AP*', getObjectType() will return 'A<P>'.
6065 /// For 'A1*', getObjectType() will return 'A'.
6066 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6067 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6068 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6069 /// adding protocols to a protocol-qualified base discards the
6070 /// old qualifiers (for now). But if it didn't, getObjectType()
6071 /// would return 'A1P<Q>' (and we'd have to make iterating over
6072 /// qualifiers more complicated).
6073 const ObjCObjectType *getObjectType() const {
6074 return PointeeType->castAs<ObjCObjectType>();
6075 }
6076
6077 /// If this pointer points to an Objective C
6078 /// \@interface type, gets the type for that interface. Any protocol
6079 /// qualifiers on the interface are ignored.
6080 ///
6081 /// \return null if the base type for this pointer is 'id' or 'Class'
6082 const ObjCInterfaceType *getInterfaceType() const;
6083
6084 /// If this pointer points to an Objective \@interface
6085 /// type, gets the declaration for that interface.
6086 ///
6087 /// \return null if the base type for this pointer is 'id' or 'Class'
6088 ObjCInterfaceDecl *getInterfaceDecl() const {
6089 return getObjectType()->getInterface();
6090 }
6091
6092 /// True if this is equivalent to the 'id' type, i.e. if
6093 /// its object type is the primitive 'id' type with no protocols.
6094 bool isObjCIdType() const {
6095 return getObjectType()->isObjCUnqualifiedId();
6096 }
6097
6098 /// True if this is equivalent to the 'Class' type,
6099 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6100 bool isObjCClassType() const {
6101 return getObjectType()->isObjCUnqualifiedClass();
6102 }
6103
6104 /// True if this is equivalent to the 'id' or 'Class' type,
6105 bool isObjCIdOrClassType() const {
6106 return getObjectType()->isObjCUnqualifiedIdOrClass();
6107 }
6108
6109 /// True if this is equivalent to 'id<P>' for some non-empty set of
6110 /// protocols.
6111 bool isObjCQualifiedIdType() const {
6112 return getObjectType()->isObjCQualifiedId();
6113 }
6114
6115 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6116 /// protocols.
6117 bool isObjCQualifiedClassType() const {
6118 return getObjectType()->isObjCQualifiedClass();
6119 }
6120
6121 /// Whether this is a "__kindof" type.
6122 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6123
6124 /// Whether this type is specialized, meaning that it has type arguments.
6125 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6126
6127 /// Whether this type is specialized, meaning that it has type arguments.
6128 bool isSpecializedAsWritten() const {
6129 return getObjectType()->isSpecializedAsWritten();
6130 }
6131
6132 /// Whether this type is unspecialized, meaning that is has no type arguments.
6133 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6134
6135 /// Determine whether this object type is "unspecialized" as
6136 /// written, meaning that it has no type arguments.
6137 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6138
6139 /// Retrieve the type arguments for this type.
6140 ArrayRef<QualType> getTypeArgs() const {
6141 return getObjectType()->getTypeArgs();
6142 }
6143
6144 /// Retrieve the type arguments for this type.
6145 ArrayRef<QualType> getTypeArgsAsWritten() const {
6146 return getObjectType()->getTypeArgsAsWritten();
6147 }
6148
6149 /// An iterator over the qualifiers on the object type. Provided
6150 /// for convenience. This will always iterate over the full set of
6151 /// protocols on a type, not just those provided directly.
6152 using qual_iterator = ObjCObjectType::qual_iterator;
6153 using qual_range = llvm::iterator_range<qual_iterator>;
6154
6155 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6156
6157 qual_iterator qual_begin() const {
6158 return getObjectType()->qual_begin();
6159 }
6160
6161 qual_iterator qual_end() const {
6162 return getObjectType()->qual_end();
6163 }
6164
6165 bool qual_empty() const { return getObjectType()->qual_empty(); }
6166
6167 /// Return the number of qualifying protocols on the object type.
6168 unsigned getNumProtocols() const {
6169 return getObjectType()->getNumProtocols();
6170 }
6171
6172 /// Retrieve a qualifying protocol by index on the object type.
6173 ObjCProtocolDecl *getProtocol(unsigned I) const {
6174 return getObjectType()->getProtocol(I);
6175 }
6176
6177 bool isSugared() const { return false; }
6178 QualType desugar() const { return QualType(this, 0); }
6179
6180 /// Retrieve the type of the superclass of this object pointer type.
6181 ///
6182 /// This operation substitutes any type arguments into the
6183 /// superclass of the current class type, potentially producing a
6184 /// pointer to a specialization of the superclass type. Produces a
6185 /// null type if there is no superclass.
6186 QualType getSuperClassType() const;
6187
6188 /// Strip off the Objective-C "kindof" type and (with it) any
6189 /// protocol qualifiers.
6190 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6191 const ASTContext &ctx) const;
6192
6193 void Profile(llvm::FoldingSetNodeID &ID) {
6194 Profile(ID, getPointeeType());
6195 }
6196
6197 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6198 ID.AddPointer(T.getAsOpaquePtr());
6199 }
6200
6201 static bool classof(const Type *T) {
6202 return T->getTypeClass() == ObjCObjectPointer;
6203 }
6204};
6205
6206class AtomicType : public Type, public llvm::FoldingSetNode {
6207 friend class ASTContext; // ASTContext creates these.
6208
6209 QualType ValueType;
6210
6211 AtomicType(QualType ValTy, QualType Canonical)
6212 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6213
6214public:
6215 /// Gets the type contained by this atomic type, i.e.
6216 /// the type returned by performing an atomic load of this atomic type.
6217 QualType getValueType() const { return ValueType; }
6218
6219 bool isSugared() const { return false; }
6220 QualType desugar() const { return QualType(this, 0); }
6221
6222 void Profile(llvm::FoldingSetNodeID &ID) {
6223 Profile(ID, getValueType());
6224 }
6225
6226 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6227 ID.AddPointer(T.getAsOpaquePtr());
6228 }
6229
6230 static bool classof(const Type *T) {
6231 return T->getTypeClass() == Atomic;
6232 }
6233};
6234
6235/// PipeType - OpenCL20.
6236class PipeType : public Type, public llvm::FoldingSetNode {
6237 friend class ASTContext; // ASTContext creates these.
6238
6239 QualType ElementType;
6240 bool isRead;
6241
6242 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6243 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6244 ElementType(elemType), isRead(isRead) {}
6245
6246public:
6247 QualType getElementType() const { return ElementType; }
6248
6249 bool isSugared() const { return false; }
6250
6251 QualType desugar() const { return QualType(this, 0); }
6252
6253 void Profile(llvm::FoldingSetNodeID &ID) {
6254 Profile(ID, getElementType(), isReadOnly());
6255 }
6256
6257 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6258 ID.AddPointer(T.getAsOpaquePtr());
6259 ID.AddBoolean(isRead);
6260 }
6261
6262 static bool classof(const Type *T) {
6263 return T->getTypeClass() == Pipe;
6264 }
6265
6266 bool isReadOnly() const { return isRead; }
6267};
6268
6269/// A fixed int type of a specified bitwidth.
6270class ExtIntType final : public Type, public llvm::FoldingSetNode {
6271 friend class ASTContext;
6272 unsigned IsUnsigned : 1;
6273 unsigned NumBits : 24;
6274
6275protected:
6276 ExtIntType(bool isUnsigned, unsigned NumBits);
6277
6278public:
6279 bool isUnsigned() const { return IsUnsigned; }
6280 bool isSigned() const { return !IsUnsigned; }
6281 unsigned getNumBits() const { return NumBits; }
6282
6283 bool isSugared() const { return false; }
6284 QualType desugar() const { return QualType(this, 0); }
6285
6286 void Profile(llvm::FoldingSetNodeID &ID) {
6287 Profile(ID, isUnsigned(), getNumBits());
6288 }
6289
6290 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6291 unsigned NumBits) {
6292 ID.AddBoolean(IsUnsigned);
6293 ID.AddInteger(NumBits);
6294 }
6295
6296 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6297};
6298
6299class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6300 friend class ASTContext;
6301 const ASTContext &Context;
6302 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6303
6304protected:
6305 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6306 Expr *NumBits);
6307
6308public:
6309 bool isUnsigned() const;
6310 bool isSigned() const { return !isUnsigned(); }
6311 Expr *getNumBitsExpr() const;
6312
6313 bool isSugared() const { return false; }
6314 QualType desugar() const { return QualType(this, 0); }
6315
6316 void Profile(llvm::FoldingSetNodeID &ID) {
6317 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6318 }
6319 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6320 bool IsUnsigned, Expr *NumBitsExpr);
6321
6322 static bool classof(const Type *T) {
6323 return T->getTypeClass() == DependentExtInt;
6324 }
6325};
6326
6327/// A qualifier set is used to build a set of qualifiers.
6328class QualifierCollector : public Qualifiers {
6329public:
6330 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6331
6332 /// Collect any qualifiers on the given type and return an
6333 /// unqualified type. The qualifiers are assumed to be consistent
6334 /// with those already in the type.
6335 const Type *strip(QualType type) {
6336 addFastQualifiers(type.getLocalFastQualifiers());
6337 if (!type.hasLocalNonFastQualifiers())
6338 return type.getTypePtrUnsafe();
6339
6340 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6341 addConsistentQualifiers(extQuals->getQualifiers());
6342 return extQuals->getBaseType();
6343 }
6344
6345 /// Apply the collected qualifiers to the given type.
6346 QualType apply(const ASTContext &Context, QualType QT) const;
6347
6348 /// Apply the collected qualifiers to the given type.
6349 QualType apply(const ASTContext &Context, const Type* T) const;
6350};
6351
6352/// A container of type source information.
6353///
6354/// A client can read the relevant info using TypeLoc wrappers, e.g:
6355/// @code
6356/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6357/// TL.getBeginLoc().print(OS, SrcMgr);
6358/// @endcode
6359class alignas(8) TypeSourceInfo {
6360 // Contains a memory block after the class, used for type source information,
6361 // allocated by ASTContext.
6362 friend class ASTContext;
6363
6364 QualType Ty;
6365
6366 TypeSourceInfo(QualType ty) : Ty(ty) {}
6367
6368public:
6369 /// Return the type wrapped by this type source info.
6370 QualType getType() const { return Ty; }
6371
6372 /// Return the TypeLoc wrapper for the type source info.
6373 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6374
6375 /// Override the type stored in this TypeSourceInfo. Use with caution!
6376 void overrideType(QualType T) { Ty = T; }
6377};
6378
6379// Inline function definitions.
6380
6381inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6382 SplitQualType desugar =
6383 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6384 desugar.Quals.addConsistentQualifiers(Quals);
6385 return desugar;
6386}
6387
6388inline const Type *QualType::getTypePtr() const {
6389 return getCommonPtr()->BaseType;
6390}
6391
6392inline const Type *QualType::getTypePtrOrNull() const {
6393 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6394}
6395
6396inline SplitQualType QualType::split() const {
6397 if (!hasLocalNonFastQualifiers())
6398 return SplitQualType(getTypePtrUnsafe(),
6399 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6400
6401 const ExtQuals *eq = getExtQualsUnsafe();
6402 Qualifiers qs = eq->getQualifiers();
6403 qs.addFastQualifiers(getLocalFastQualifiers());
6404 return SplitQualType(eq->getBaseType(), qs);
6405}
6406
6407inline Qualifiers QualType::getLocalQualifiers() const {
6408 Qualifiers Quals;
6409 if (hasLocalNonFastQualifiers())
6410 Quals = getExtQualsUnsafe()->getQualifiers();
6411 Quals.addFastQualifiers(getLocalFastQualifiers());
6412 return Quals;
6413}
6414
6415inline Qualifiers QualType::getQualifiers() const {
6416 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6417 quals.addFastQualifiers(getLocalFastQualifiers());
6418 return quals;
6419}
6420
6421inline unsigned QualType::getCVRQualifiers() const {
6422 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6423 cvr |= getLocalCVRQualifiers();
6424 return cvr;
6425}
6426
6427inline QualType QualType::getCanonicalType() const {
6428 QualType canon = getCommonPtr()->CanonicalType;
6429 return canon.withFastQualifiers(getLocalFastQualifiers());
6430}
6431
6432inline bool QualType::isCanonical() const {
6433 return getTypePtr()->isCanonicalUnqualified();
6434}
6435
6436inline bool QualType::isCanonicalAsParam() const {
6437 if (!isCanonical()) return false;
6438 if (hasLocalQualifiers()) return false;
6439
6440 const Type *T = getTypePtr();
6441 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6442 return false;
6443
6444 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6445}
6446
6447inline bool QualType::isConstQualified() const {
6448 return isLocalConstQualified() ||
6449 getCommonPtr()->CanonicalType.isLocalConstQualified();
6450}
6451
6452inline bool QualType::isRestrictQualified() const {
6453 return isLocalRestrictQualified() ||
6454 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6455}
6456
6457
6458inline bool QualType::isVolatileQualified() const {
6459 return isLocalVolatileQualified() ||
6460 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6461}
6462
6463inline bool QualType::hasQualifiers() const {
6464 return hasLocalQualifiers() ||
6465 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6466}
6467
6468inline QualType QualType::getUnqualifiedType() const {
6469 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6470 return QualType(getTypePtr(), 0);
6471
6472 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6473}
6474
6475inline SplitQualType QualType::getSplitUnqualifiedType() const {
6476 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6477 return split();
6478
6479 return getSplitUnqualifiedTypeImpl(*this);
6480}
6481
6482inline void QualType::removeLocalConst() {
6483 removeLocalFastQualifiers(Qualifiers::Const);
6484}
6485
6486inline void QualType::removeLocalRestrict() {
6487 removeLocalFastQualifiers(Qualifiers::Restrict);
6488}
6489
6490inline void QualType::removeLocalVolatile() {
6491 removeLocalFastQualifiers(Qualifiers::Volatile);
6492}
6493
6494inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6495 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 6495, __PRETTY_FUNCTION__))
;
6496 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6497 "Fast bits differ from CVR bits!");
6498
6499 // Fast path: we don't need to touch the slow qualifiers.
6500 removeLocalFastQualifiers(Mask);
6501}
6502
6503/// Check if this type has any address space qualifier.
6504inline bool QualType::hasAddressSpace() const {
6505 return getQualifiers().hasAddressSpace();
6506}
6507
6508/// Return the address space of this type.
6509inline LangAS QualType::getAddressSpace() const {
6510 return getQualifiers().getAddressSpace();
6511}
6512
6513/// Return the gc attribute of this type.
6514inline Qualifiers::GC QualType::getObjCGCAttr() const {
6515 return getQualifiers().getObjCGCAttr();
6516}
6517
6518inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6519 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6520 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6521 return false;
6522}
6523
6524inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6525 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6526 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6527 return false;
6528}
6529
6530inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6531 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6532 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6533 return false;
6534}
6535
6536inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6537 if (const auto *PT = t.getAs<PointerType>()) {
6538 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6539 return FT->getExtInfo();
6540 } else if (const auto *FT = t.getAs<FunctionType>())
6541 return FT->getExtInfo();
6542
6543 return FunctionType::ExtInfo();
6544}
6545
6546inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6547 return getFunctionExtInfo(*t);
6548}
6549
6550/// Determine whether this type is more
6551/// qualified than the Other type. For example, "const volatile int"
6552/// is more qualified than "const int", "volatile int", and
6553/// "int". However, it is not more qualified than "const volatile
6554/// int".
6555inline bool QualType::isMoreQualifiedThan(QualType other) const {
6556 Qualifiers MyQuals = getQualifiers();
6557 Qualifiers OtherQuals = other.getQualifiers();
6558 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6559}
6560
6561/// Determine whether this type is at last
6562/// as qualified as the Other type. For example, "const volatile
6563/// int" is at least as qualified as "const int", "volatile int",
6564/// "int", and "const volatile int".
6565inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6566 Qualifiers OtherQuals = other.getQualifiers();
6567
6568 // Ignore __unaligned qualifier if this type is a void.
6569 if (getUnqualifiedType()->isVoidType())
6570 OtherQuals.removeUnaligned();
6571
6572 return getQualifiers().compatiblyIncludes(OtherQuals);
6573}
6574
6575/// If Type is a reference type (e.g., const
6576/// int&), returns the type that the reference refers to ("const
6577/// int"). Otherwise, returns the type itself. This routine is used
6578/// throughout Sema to implement C++ 5p6:
6579///
6580/// If an expression initially has the type "reference to T" (8.3.2,
6581/// 8.5.3), the type is adjusted to "T" prior to any further
6582/// analysis, the expression designates the object or function
6583/// denoted by the reference, and the expression is an lvalue.
6584inline QualType QualType::getNonReferenceType() const {
6585 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6586 return RefType->getPointeeType();
6587 else
6588 return *this;
6589}
6590
6591inline bool QualType::isCForbiddenLValueType() const {
6592 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6593 getTypePtr()->isFunctionType());
6594}
6595
6596/// Tests whether the type is categorized as a fundamental type.
6597///
6598/// \returns True for types specified in C++0x [basic.fundamental].
6599inline bool Type::isFundamentalType() const {
6600 return isVoidType() ||
6601 isNullPtrType() ||
6602 // FIXME: It's really annoying that we don't have an
6603 // 'isArithmeticType()' which agrees with the standard definition.
6604 (isArithmeticType() && !isEnumeralType());
6605}
6606
6607/// Tests whether the type is categorized as a compound type.
6608///
6609/// \returns True for types specified in C++0x [basic.compound].
6610inline bool Type::isCompoundType() const {
6611 // C++0x [basic.compound]p1:
6612 // Compound types can be constructed in the following ways:
6613 // -- arrays of objects of a given type [...];
6614 return isArrayType() ||
6615 // -- functions, which have parameters of given types [...];
6616 isFunctionType() ||
6617 // -- pointers to void or objects or functions [...];
6618 isPointerType() ||
6619 // -- references to objects or functions of a given type. [...]
6620 isReferenceType() ||
6621 // -- classes containing a sequence of objects of various types, [...];
6622 isRecordType() ||
6623 // -- unions, which are classes capable of containing objects of different
6624 // types at different times;
6625 isUnionType() ||
6626 // -- enumerations, which comprise a set of named constant values. [...];
6627 isEnumeralType() ||
6628 // -- pointers to non-static class members, [...].
6629 isMemberPointerType();
6630}
6631
6632inline bool Type::isFunctionType() const {
6633 return isa<FunctionType>(CanonicalType);
6634}
6635
6636inline bool Type::isPointerType() const {
6637 return isa<PointerType>(CanonicalType);
6638}
6639
6640inline bool Type::isAnyPointerType() const {
6641 return isPointerType() || isObjCObjectPointerType();
6642}
6643
6644inline bool Type::isBlockPointerType() const {
6645 return isa<BlockPointerType>(CanonicalType);
6646}
6647
6648inline bool Type::isReferenceType() const {
6649 return isa<ReferenceType>(CanonicalType);
6650}
6651
6652inline bool Type::isLValueReferenceType() const {
6653 return isa<LValueReferenceType>(CanonicalType);
30
Assuming field 'CanonicalType' is a 'LValueReferenceType'
31
Returning the value 1, which participates in a condition later
6654}
6655
6656inline bool Type::isRValueReferenceType() const {
6657 return isa<RValueReferenceType>(CanonicalType);
6658}
6659
6660inline bool Type::isObjectPointerType() const {
6661 // Note: an "object pointer type" is not the same thing as a pointer to an
6662 // object type; rather, it is a pointer to an object type or a pointer to cv
6663 // void.
6664 if (const auto *T = getAs<PointerType>())
6665 return !T->getPointeeType()->isFunctionType();
6666 else
6667 return false;
6668}
6669
6670inline bool Type::isFunctionPointerType() const {
6671 if (const auto *T = getAs<PointerType>())
6672 return T->getPointeeType()->isFunctionType();
6673 else
6674 return false;
6675}
6676
6677inline bool Type::isFunctionReferenceType() const {
6678 if (const auto *T = getAs<ReferenceType>())
6679 return T->getPointeeType()->isFunctionType();
6680 else
6681 return false;
6682}
6683
6684inline bool Type::isMemberPointerType() const {
6685 return isa<MemberPointerType>(CanonicalType);
6686}
6687
6688inline bool Type::isMemberFunctionPointerType() const {
6689 if (const auto *T = getAs<MemberPointerType>())
6690 return T->isMemberFunctionPointer();
6691 else
6692 return false;
6693}
6694
6695inline bool Type::isMemberDataPointerType() const {
6696 if (const auto *T = getAs<MemberPointerType>())
6697 return T->isMemberDataPointer();
6698 else
6699 return false;
6700}
6701
6702inline bool Type::isArrayType() const {
6703 return isa<ArrayType>(CanonicalType);
6704}
6705
6706inline bool Type::isConstantArrayType() const {
6707 return isa<ConstantArrayType>(CanonicalType);
6708}
6709
6710inline bool Type::isIncompleteArrayType() const {
6711 return isa<IncompleteArrayType>(CanonicalType);
6712}
6713
6714inline bool Type::isVariableArrayType() const {
6715 return isa<VariableArrayType>(CanonicalType);
6716}
6717
6718inline bool Type::isDependentSizedArrayType() const {
6719 return isa<DependentSizedArrayType>(CanonicalType);
6720}
6721
6722inline bool Type::isBuiltinType() const {
6723 return isa<BuiltinType>(CanonicalType);
6724}
6725
6726inline bool Type::isRecordType() const {
6727 return isa<RecordType>(CanonicalType);
6728}
6729
6730inline bool Type::isEnumeralType() const {
6731 return isa<EnumType>(CanonicalType);
6732}
6733
6734inline bool Type::isAnyComplexType() const {
6735 return isa<ComplexType>(CanonicalType);
6736}
6737
6738inline bool Type::isVectorType() const {
6739 return isa<VectorType>(CanonicalType);
6740}
6741
6742inline bool Type::isExtVectorType() const {
6743 return isa<ExtVectorType>(CanonicalType);
6744}
6745
6746inline bool Type::isMatrixType() const {
6747 return isa<MatrixType>(CanonicalType);
6748}
6749
6750inline bool Type::isConstantMatrixType() const {
6751 return isa<ConstantMatrixType>(CanonicalType);
6752}
6753
6754inline bool Type::isDependentAddressSpaceType() const {
6755 return isa<DependentAddressSpaceType>(CanonicalType);
6756}
6757
6758inline bool Type::isObjCObjectPointerType() const {
6759 return isa<ObjCObjectPointerType>(CanonicalType);
6760}
6761
6762inline bool Type::isObjCObjectType() const {
6763 return isa<ObjCObjectType>(CanonicalType);
6764}
6765
6766inline bool Type::isObjCObjectOrInterfaceType() const {
6767 return isa<ObjCInterfaceType>(CanonicalType) ||
6768 isa<ObjCObjectType>(CanonicalType);
6769}
6770
6771inline bool Type::isAtomicType() const {
6772 return isa<AtomicType>(CanonicalType);
6773}
6774
6775inline bool Type::isUndeducedAutoType() const {
6776 return isa<AutoType>(CanonicalType);
6777}
6778
6779inline bool Type::isObjCQualifiedIdType() const {
6780 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6781 return OPT->isObjCQualifiedIdType();
6782 return false;
6783}
6784
6785inline bool Type::isObjCQualifiedClassType() const {
6786 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6787 return OPT->isObjCQualifiedClassType();
6788 return false;
6789}
6790
6791inline bool Type::isObjCIdType() const {
6792 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6793 return OPT->isObjCIdType();
6794 return false;
6795}
6796
6797inline bool Type::isObjCClassType() const {
6798 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6799 return OPT->isObjCClassType();
6800 return false;
6801}
6802
6803inline bool Type::isObjCSelType() const {
6804 if (const auto *OPT = getAs<PointerType>())
6805 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6806 return false;
6807}
6808
6809inline bool Type::isObjCBuiltinType() const {
6810 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6811}
6812
6813inline bool Type::isDecltypeType() const {
6814 return isa<DecltypeType>(this);
6815}
6816
6817#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6818 inline bool Type::is##Id##Type() const { \
6819 return isSpecificBuiltinType(BuiltinType::Id); \
6820 }
6821#include "clang/Basic/OpenCLImageTypes.def"
6822
6823inline bool Type::isSamplerT() const {
6824 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6825}
6826
6827inline bool Type::isEventT() const {
6828 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6829}
6830
6831inline bool Type::isClkEventT() const {
6832 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6833}
6834
6835inline bool Type::isQueueT() const {
6836 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6837}
6838
6839inline bool Type::isReserveIDT() const {
6840 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6841}
6842
6843inline bool Type::isImageType() const {
6844#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6845 return
6846#include "clang/Basic/OpenCLImageTypes.def"
6847 false; // end boolean or operation
6848}
6849
6850inline bool Type::isPipeType() const {
6851 return isa<PipeType>(CanonicalType);
6852}
6853
6854inline bool Type::isExtIntType() const {
6855 return isa<ExtIntType>(CanonicalType);
6856}
6857
6858#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6859 inline bool Type::is##Id##Type() const { \
6860 return isSpecificBuiltinType(BuiltinType::Id); \
6861 }
6862#include "clang/Basic/OpenCLExtensionTypes.def"
6863
6864inline bool Type::isOCLIntelSubgroupAVCType() const {
6865#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6866 isOCLIntelSubgroupAVC##Id##Type() ||
6867 return
6868#include "clang/Basic/OpenCLExtensionTypes.def"
6869 false; // end of boolean or operation
6870}
6871
6872inline bool Type::isOCLExtOpaqueType() const {
6873#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6874 return
6875#include "clang/Basic/OpenCLExtensionTypes.def"
6876 false; // end of boolean or operation
6877}
6878
6879inline bool Type::isOpenCLSpecificType() const {
6880 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6881 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6882}
6883
6884inline bool Type::isTemplateTypeParmType() const {
6885 return isa<TemplateTypeParmType>(CanonicalType);
6886}
6887
6888inline bool Type::isSpecificBuiltinType(unsigned K) const {
6889 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6890 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6891 }
6892 return false;
6893}
6894
6895inline bool Type::isPlaceholderType() const {
6896 if (const auto *BT = dyn_cast<BuiltinType>(this))
6897 return BT->isPlaceholderType();
6898 return false;
6899}
6900
6901inline const BuiltinType *Type::getAsPlaceholderType() const {
6902 if (const auto *BT = dyn_cast<BuiltinType>(this))
6903 if (BT->isPlaceholderType())
6904 return BT;
6905 return nullptr;
6906}
6907
6908inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6909 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 6909, __PRETTY_FUNCTION__))
;
6910 return isSpecificBuiltinType(K);
6911}
6912
6913inline bool Type::isNonOverloadPlaceholderType() const {
6914 if (const auto *BT = dyn_cast<BuiltinType>(this))
6915 return BT->isNonOverloadPlaceholderType();
6916 return false;
6917}
6918
6919inline bool Type::isVoidType() const {
6920 return isSpecificBuiltinType(BuiltinType::Void);
6921}
6922
6923inline bool Type::isHalfType() const {
6924 // FIXME: Should we allow complex __fp16? Probably not.
6925 return isSpecificBuiltinType(BuiltinType::Half);
6926}
6927
6928inline bool Type::isFloat16Type() const {
6929 return isSpecificBuiltinType(BuiltinType::Float16);
6930}
6931
6932inline bool Type::isBFloat16Type() const {
6933 return isSpecificBuiltinType(BuiltinType::BFloat16);
6934}
6935
6936inline bool Type::isFloat128Type() const {
6937 return isSpecificBuiltinType(BuiltinType::Float128);
6938}
6939
6940inline bool Type::isNullPtrType() const {
6941 return isSpecificBuiltinType(BuiltinType::NullPtr);
6942}
6943
6944bool IsEnumDeclComplete(EnumDecl *);
6945bool IsEnumDeclScoped(EnumDecl *);
6946
6947inline bool Type::isIntegerType() const {
6948 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6949 return BT->getKind() >= BuiltinType::Bool &&
6950 BT->getKind() <= BuiltinType::Int128;
6951 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6952 // Incomplete enum types are not treated as integer types.
6953 // FIXME: In C++, enum types are never integer types.
6954 return IsEnumDeclComplete(ET->getDecl()) &&
6955 !IsEnumDeclScoped(ET->getDecl());
6956 }
6957 return isExtIntType();
6958}
6959
6960inline bool Type::isFixedPointType() const {
6961 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6962 return BT->getKind() >= BuiltinType::ShortAccum &&
6963 BT->getKind() <= BuiltinType::SatULongFract;
6964 }
6965 return false;
6966}
6967
6968inline bool Type::isFixedPointOrIntegerType() const {
6969 return isFixedPointType() || isIntegerType();
6970}
6971
6972inline bool Type::isSaturatedFixedPointType() const {
6973 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6974 return BT->getKind() >= BuiltinType::SatShortAccum &&
6975 BT->getKind() <= BuiltinType::SatULongFract;
6976 }
6977 return false;
6978}
6979
6980inline bool Type::isUnsaturatedFixedPointType() const {
6981 return isFixedPointType() && !isSaturatedFixedPointType();
6982}
6983
6984inline bool Type::isSignedFixedPointType() const {
6985 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6986 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6987 BT->getKind() <= BuiltinType::LongAccum) ||
6988 (BT->getKind() >= BuiltinType::ShortFract &&
6989 BT->getKind() <= BuiltinType::LongFract) ||
6990 (BT->getKind() >= BuiltinType::SatShortAccum &&
6991 BT->getKind() <= BuiltinType::SatLongAccum) ||
6992 (BT->getKind() >= BuiltinType::SatShortFract &&
6993 BT->getKind() <= BuiltinType::SatLongFract));
6994 }
6995 return false;
6996}
6997
6998inline bool Type::isUnsignedFixedPointType() const {
6999 return isFixedPointType() && !isSignedFixedPointType();
7000}
7001
7002inline bool Type::isScalarType() const {
7003 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7004 return BT->getKind() > BuiltinType::Void &&
7005 BT->getKind() <= BuiltinType::NullPtr;
7006 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7007 // Enums are scalar types, but only if they are defined. Incomplete enums
7008 // are not treated as scalar types.
7009 return IsEnumDeclComplete(ET->getDecl());
7010 return isa<PointerType>(CanonicalType) ||
7011 isa<BlockPointerType>(CanonicalType) ||
7012 isa<MemberPointerType>(CanonicalType) ||
7013 isa<ComplexType>(CanonicalType) ||
7014 isa<ObjCObjectPointerType>(CanonicalType) ||
7015 isExtIntType();
7016}
7017
7018inline bool Type::isIntegralOrEnumerationType() const {
7019 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7020 return BT->getKind() >= BuiltinType::Bool &&
7021 BT->getKind() <= BuiltinType::Int128;
7022
7023 // Check for a complete enum type; incomplete enum types are not properly an
7024 // enumeration type in the sense required here.
7025 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7026 return IsEnumDeclComplete(ET->getDecl());
7027
7028 return isExtIntType();
7029}
7030
7031inline bool Type::isBooleanType() const {
7032 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7033 return BT->getKind() == BuiltinType::Bool;
7034 return false;
7035}
7036
7037inline bool Type::isUndeducedType() const {
7038 auto *DT = getContainedDeducedType();
7039 return DT && !DT->isDeduced();
7040}
7041
7042/// Determines whether this is a type for which one can define
7043/// an overloaded operator.
7044inline bool Type::isOverloadableType() const {
7045 return isDependentType() || isRecordType() || isEnumeralType();
7046}
7047
7048/// Determines whether this type can decay to a pointer type.
7049inline bool Type::canDecayToPointerType() const {
7050 return isFunctionType() || isArrayType();
7051}
7052
7053inline bool Type::hasPointerRepresentation() const {
7054 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7055 isObjCObjectPointerType() || isNullPtrType());
7056}
7057
7058inline bool Type::hasObjCPointerRepresentation() const {
7059 return isObjCObjectPointerType();
7060}
7061
7062inline const Type *Type::getBaseElementTypeUnsafe() const {
7063 const Type *type = this;
7064 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7065 type = arrayType->getElementType().getTypePtr();
7066 return type;
7067}
7068
7069inline const Type *Type::getPointeeOrArrayElementType() const {
7070 const Type *type = this;
7071 if (type->isAnyPointerType())
7072 return type->getPointeeType().getTypePtr();
7073 else if (type->isArrayType())
7074 return type->getBaseElementTypeUnsafe();
7075 return type;
7076}
7077/// Insertion operator for partial diagnostics. This allows sending adress
7078/// spaces into a diagnostic with <<.
7079inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7080 LangAS AS) {
7081 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7082 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7083 return PD;
7084}
7085
7086/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7087/// into a diagnostic with <<.
7088inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7089 Qualifiers Q) {
7090 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7091 DiagnosticsEngine::ArgumentKind::ak_qual);
7092 return PD;
7093}
7094
7095/// Insertion operator for partial diagnostics. This allows sending QualType's
7096/// into a diagnostic with <<.
7097inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7098 QualType T) {
7099 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7100 DiagnosticsEngine::ak_qualtype);
7101 return PD;
7102}
7103
7104// Helper class template that is used by Type::getAs to ensure that one does
7105// not try to look through a qualified type to get to an array type.
7106template <typename T>
7107using TypeIsArrayType =
7108 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7109 std::is_base_of<ArrayType, T>::value>;
7110
7111// Member-template getAs<specific type>'.
7112template <typename T> const T *Type::getAs() const {
7113 static_assert(!TypeIsArrayType<T>::value,
7114 "ArrayType cannot be used with getAs!");
7115
7116 // If this is directly a T type, return it.
7117 if (const auto *Ty = dyn_cast<T>(this))
7118 return Ty;
7119
7120 // If the canonical form of this type isn't the right kind, reject it.
7121 if (!isa<T>(CanonicalType))
7122 return nullptr;
7123
7124 // If this is a typedef for the type, strip the typedef off without
7125 // losing all typedef information.
7126 return cast<T>(getUnqualifiedDesugaredType());
7127}
7128
7129template <typename T> const T *Type::getAsAdjusted() const {
7130 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7131
7132 // If this is directly a T type, return it.
7133 if (const auto *Ty = dyn_cast<T>(this))
7134 return Ty;
7135
7136 // If the canonical form of this type isn't the right kind, reject it.
7137 if (!isa<T>(CanonicalType))
7138 return nullptr;
7139
7140 // Strip off type adjustments that do not modify the underlying nature of the
7141 // type.
7142 const Type *Ty = this;
7143 while (Ty) {
7144 if (const auto *A = dyn_cast<AttributedType>(Ty))
7145 Ty = A->getModifiedType().getTypePtr();
7146 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7147 Ty = E->desugar().getTypePtr();
7148 else if (const auto *P = dyn_cast<ParenType>(Ty))
7149 Ty = P->desugar().getTypePtr();
7150 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7151 Ty = A->desugar().getTypePtr();
7152 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7153 Ty = M->desugar().getTypePtr();
7154 else
7155 break;
7156 }
7157
7158 // Just because the canonical type is correct does not mean we can use cast<>,
7159 // since we may not have stripped off all the sugar down to the base type.
7160 return dyn_cast<T>(Ty);
7161}
7162
7163inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7164 // If this is directly an array type, return it.
7165 if (const auto *arr = dyn_cast<ArrayType>(this))
7166 return arr;
7167
7168 // If the canonical form of this type isn't the right kind, reject it.
7169 if (!isa<ArrayType>(CanonicalType))
7170 return nullptr;
7171
7172 // If this is a typedef for the type, strip the typedef off without
7173 // losing all typedef information.
7174 return cast<ArrayType>(getUnqualifiedDesugaredType());
7175}
7176
7177template <typename T> const T *Type::castAs() const {
7178 static_assert(!TypeIsArrayType<T>::value,
7179 "ArrayType cannot be used with castAs!");
7180
7181 if (const auto *ty = dyn_cast<T>(this)) return ty;
7182 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 7182, __PRETTY_FUNCTION__))
;
7183 return cast<T>(getUnqualifiedDesugaredType());
7184}
7185
7186inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7187 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 7187, __PRETTY_FUNCTION__))
;
7188 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7189 return cast<ArrayType>(getUnqualifiedDesugaredType());
7190}
7191
7192DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7193 QualType CanonicalPtr)
7194 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7195#ifndef NDEBUG
7196 QualType Adjusted = getAdjustedType();
7197 (void)AttributedType::stripOuterNullability(Adjusted);
7198 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include/clang/AST/Type.h"
, 7198, __PRETTY_FUNCTION__))
;
7199#endif
7200}
7201
7202QualType DecayedType::getPointeeType() const {
7203 QualType Decayed = getDecayedType();
7204 (void)AttributedType::stripOuterNullability(Decayed);
7205 return cast<PointerType>(Decayed)->getPointeeType();
7206}
7207
7208// Get the decimal string representation of a fixed point type, represented
7209// as a scaled integer.
7210// TODO: At some point, we should change the arguments to instead just accept an
7211// APFixedPoint instead of APSInt and scale.
7212void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7213 unsigned Scale);
7214
7215} // namespace clang
7216
7217#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===//
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 defines the PointerIntPair class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_POINTERINTPAIR_H
14#define LLVM_ADT_POINTERINTPAIR_H
15
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <cstdint>
21#include <limits>
22
23namespace llvm {
24
25template <typename T> struct DenseMapInfo;
26template <typename PointerT, unsigned IntBits, typename PtrTraits>
27struct PointerIntPairInfo;
28
29/// PointerIntPair - This class implements a pair of a pointer and small
30/// integer. It is designed to represent this in the space required by one
31/// pointer by bitmangling the integer into the low part of the pointer. This
32/// can only be done for small integers: typically up to 3 bits, but it depends
33/// on the number of bits available according to PointerLikeTypeTraits for the
34/// type.
35///
36/// Note that PointerIntPair always puts the IntVal part in the highest bits
37/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
38/// the bool into bit #2, not bit #0, which allows the low two bits to be used
39/// for something else. For example, this allows:
40/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
41/// ... and the two bools will land in different bits.
42template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
43 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
44 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
45class PointerIntPair {
46 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
47 using InfoTy = Info;
48 intptr_t Value = 0;
49
50public:
51 constexpr PointerIntPair() = default;
52
53 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
54 setPointerAndInt(PtrVal, IntVal);
55 }
56
57 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
58
59 PointerTy getPointer() const { return Info::getPointer(Value); }
60
61 IntType getInt() const { return (IntType)Info::getInt(Value); }
62
63 void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
64 Value = Info::updatePointer(Value, PtrVal);
65 }
66
67 void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& {
68 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
69 }
70
71 void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
72 Value = Info::updatePointer(0, PtrVal);
73 }
74
75 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& {
76 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
77 static_cast<intptr_t>(IntVal));
78 }
79
80 PointerTy const *getAddrOfPointer() const {
81 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
82 }
83
84 PointerTy *getAddrOfPointer() {
85 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
86 "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
87 "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
;
88 return reinterpret_cast<PointerTy *>(&Value);
89 }
90
91 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
92
93 void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& {
94 Value = reinterpret_cast<intptr_t>(Val);
95 }
96
97 static PointerIntPair getFromOpaqueValue(void *V) {
98 PointerIntPair P;
99 P.setFromOpaqueValue(V);
100 return P;
101 }
102
103 // Allow PointerIntPairs to be created from const void * if and only if the
104 // pointer type could be created from a const void *.
105 static PointerIntPair getFromOpaqueValue(const void *V) {
106 (void)PtrTraits::getFromVoidPointer(V);
107 return getFromOpaqueValue(const_cast<void *>(V));
108 }
109
110 bool operator==(const PointerIntPair &RHS) const {
111 return Value == RHS.Value;
8
Returning zero, which participates in a condition later
112 }
113
114 bool operator!=(const PointerIntPair &RHS) const {
115 return Value != RHS.Value;
116 }
117
118 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
119 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
120
121 bool operator<=(const PointerIntPair &RHS) const {
122 return Value <= RHS.Value;
123 }
124
125 bool operator>=(const PointerIntPair &RHS) const {
126 return Value >= RHS.Value;
127 }
128};
129
130// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
131// when compiled with gcc 4.9.
132template <typename PointerTy, unsigned IntBits, typename IntType,
133 typename PtrTraits,
134 typename Info>
135struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
136#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
137 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
138 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
139#endif
140};
141
142
143template <typename PointerT, unsigned IntBits, typename PtrTraits>
144struct PointerIntPairInfo {
145 static_assert(PtrTraits::NumLowBitsAvailable <
146 std::numeric_limits<uintptr_t>::digits,
147 "cannot use a pointer type that has all bits free");
148 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
149 "PointerIntPair with integer size too large for pointer");
150 enum MaskAndShiftConstants : uintptr_t {
151 /// PointerBitMask - The bits that come from the pointer.
152 PointerBitMask =
153 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
154
155 /// IntShift - The number of low bits that we reserve for other uses, and
156 /// keep zero.
157 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
158
159 /// IntMask - This is the unshifted mask for valid bits of the int type.
160 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
161
162 // ShiftedIntMask - This is the bits for the integer shifted in place.
163 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
164 };
165
166 static PointerT getPointer(intptr_t Value) {
167 return PtrTraits::getFromVoidPointer(
168 reinterpret_cast<void *>(Value & PointerBitMask));
169 }
170
171 static intptr_t getInt(intptr_t Value) {
172 return (Value >> IntShift) & IntMask;
173 }
174
175 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
176 intptr_t PtrWord =
177 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
178 assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
179 "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
;
180 // Preserve all low bits, just update the pointer.
181 return PtrWord | (OrigValue & ~PointerBitMask);
182 }
183
184 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
185 intptr_t IntWord = static_cast<intptr_t>(Int);
186 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field"
) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/PointerIntPair.h"
, 186, __PRETTY_FUNCTION__))
;
187
188 // Preserve all bits other than the ones we are updating.
189 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
190 }
191};
192
193// Provide specialization of DenseMapInfo for PointerIntPair.
194template <typename PointerTy, unsigned IntBits, typename IntType>
195struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
196 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
197
198 static Ty getEmptyKey() {
199 uintptr_t Val = static_cast<uintptr_t>(-1);
200 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
201 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
202 }
203
204 static Ty getTombstoneKey() {
205 uintptr_t Val = static_cast<uintptr_t>(-2);
206 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
207 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
208 }
209
210 static unsigned getHashValue(Ty V) {
211 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
212 return unsigned(IV) ^ unsigned(IV >> 9);
213 }
214
215 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
216};
217
218// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
219template <typename PointerTy, unsigned IntBits, typename IntType,
220 typename PtrTraits>
221struct PointerLikeTypeTraits<
222 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
223 static inline void *
224 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerIntPair<PointerTy, IntBits, IntType>
229 getFromVoidPointer(void *P) {
230 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
231 }
232
233 static inline PointerIntPair<PointerTy, IntBits, IntType>
234 getFromVoidPointer(const void *P) {
235 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
236 }
237
238 static constexpr int NumLowBitsAvailable =
239 PtrTraits::NumLowBitsAvailable - IntBits;
240};
241
242} // end namespace llvm
243
244#endif // LLVM_ADT_POINTERINTPAIR_H