Bug Summary

File:clang/lib/Sema/SemaOverload.cpp
Warning:line 2286, column 3
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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-10-125054-33042-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-14~++20220110111139+2f672e2ffa22/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++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "clang/lib/Sema/SemaOverload.cpp", 314, __extension__ __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")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "clang/lib/Sema/SemaOverload.cpp", 352, __extension__ __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())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp"
, 398, __extension__ __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())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 424, __extension__ __PRETTY_FUNCTION__
))
;
425 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 425, __extension__ __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 (hasInitializerListContainerType())
545 OS << "Worst 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", "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))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "clang/lib/Sema/SemaOverload.cpp", 935, __extension__ __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)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "clang/lib/Sema/SemaOverload.cpp", 1086, __extension__ __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) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1286, __extension__ __PRETTY_FUNCTION__
))
1286 "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1286, __extension__ __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())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "clang/lib/Sema/SemaOverload.cpp", 1610, __extension__ __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 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1650 ICK = ICK_SVE_Vector_Conversion;
1651 return true;
1652 }
1653
1654 // We can perform the conversion between vector types in the following cases:
1655 // 1)vector types are equivalent AltiVec and GCC vector types
1656 // 2)lax vector conversions are permitted and the vector types are of the
1657 // same size
1658 // 3)the destination type does not have the ARM MVE strict-polymorphism
1659 // attribute, which inhibits lax vector conversion for overload resolution
1660 // only
1661 if (ToType->isVectorType() && FromType->isVectorType()) {
1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663 (S.isLaxVectorConversion(FromType, ToType) &&
1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1665 ICK = ICK_Vector_Conversion;
1666 return true;
1667 }
1668 }
1669
1670 return false;
1671}
1672
1673static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1674 bool InOverloadResolution,
1675 StandardConversionSequence &SCS,
1676 bool CStyle);
1677
1678/// IsStandardConversion - Determines whether there is a standard
1679/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1680/// expression From to the type ToType. Standard conversion sequences
1681/// only consider non-class types; for conversions that involve class
1682/// types, use TryImplicitConversion. If a conversion exists, SCS will
1683/// contain the standard conversion sequence required to perform this
1684/// conversion and this routine will return true. Otherwise, this
1685/// routine will return false and the value of SCS is unspecified.
1686static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1687 bool InOverloadResolution,
1688 StandardConversionSequence &SCS,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion) {
1691 QualType FromType = From->getType();
1692
1693 // Standard conversions (C++ [conv])
1694 SCS.setAsIdentityConversion();
1695 SCS.IncompatibleObjC = false;
1696 SCS.setFromType(FromType);
1697 SCS.CopyConstructor = nullptr;
1698
1699 // There are no standard conversions for class types in C++, so
1700 // abort early. When overloading in C, however, we do permit them.
1701 if (S.getLangOpts().CPlusPlus &&
1
Assuming field 'CPlusPlus' is 0
1702 (FromType->isRecordType() || ToType->isRecordType()))
1703 return false;
1704
1705 // The first conversion can be an lvalue-to-rvalue conversion,
1706 // array-to-pointer conversion, or function-to-pointer conversion
1707 // (C++ 4p1).
1708
1709 if (FromType == S.Context.OverloadTy) {
2
Taking false branch
1710 DeclAccessPair AccessPair;
1711 if (FunctionDecl *Fn
1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1713 AccessPair)) {
1714 // We were able to resolve the address of the overloaded function,
1715 // so we can convert to the type of that function.
1716 FromType = Fn->getType();
1717 SCS.setFromType(FromType);
1718
1719 // we can sometimes resolve &foo<int> regardless of ToType, so check
1720 // if the type matches (identity) or we are converting to bool
1721 if (!S.Context.hasSameUnqualifiedType(
1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1723 QualType resultTy;
1724 // if the function type matches except for [[noreturn]], it's ok
1725 if (!S.IsFunctionConversion(FromType,
1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1727 // otherwise, only a boolean conversion is standard
1728 if (!ToType->isBooleanType())
1729 return false;
1730 }
1731
1732 // Check if the "from" expression is taking the address of an overloaded
1733 // function and recompute the FromType accordingly. Take advantage of the
1734 // fact that non-static member functions *must* have such an address-of
1735 // expression.
1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1737 if (Method && !Method->isStatic()) {
1738 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1739, __extension__ __PRETTY_FUNCTION__
))
1739 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1739, __extension__ __PRETTY_FUNCTION__
))
;
1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1742, __extension__ __PRETTY_FUNCTION__
))
1741 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1742, __extension__ __PRETTY_FUNCTION__
))
1742 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1742, __extension__ __PRETTY_FUNCTION__
))
;
1743 const Type *ClassType
1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1745 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1749, __extension__ __PRETTY_FUNCTION__
))
1748 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1749, __extension__ __PRETTY_FUNCTION__
))
1749 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1749, __extension__ __PRETTY_FUNCTION__
))
;
1750 FromType = S.Context.getPointerType(FromType);
1751 }
1752
1753 // Check that we've computed the proper type after overload resolution.
1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1755 // be calling it from within an NDEBUG block.
1756 assert(S.Context.hasSameType((static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "clang/lib/Sema/SemaOverload.cpp", 1758, __extension__ __PRETTY_FUNCTION__
))
1757 FromType,(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "clang/lib/Sema/SemaOverload.cpp", 1758, __extension__ __PRETTY_FUNCTION__
))
1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "clang/lib/Sema/SemaOverload.cpp", 1758, __extension__ __PRETTY_FUNCTION__
))
;
1759 } else {
1760 return false;
1761 }
1762 }
1763 // Lvalue-to-rvalue conversion (C++11 4.1):
1764 // A glvalue (3.10) of a non-function, non-array type T can
1765 // be converted to a prvalue.
1766 bool argIsLValue = From->isGLValue();
1767 if (argIsLValue
2.1
'argIsLValue' is false
2.1
'argIsLValue' is false
&&
3
Taking false branch
1768 !FromType->isFunctionType() && !FromType->isArrayType() &&
1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1770 SCS.First = ICK_Lvalue_To_Rvalue;
1771
1772 // C11 6.3.2.1p2:
1773 // ... if the lvalue has atomic type, the value has the non-atomic version
1774 // of the type of the lvalue ...
1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776 FromType = Atomic->getValueType();
1777
1778 // If T is a non-class type, the type of the rvalue is the
1779 // cv-unqualified version of T. Otherwise, the type of the rvalue
1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781 // just strip the qualifiers because they don't matter.
1782 FromType = FromType.getUnqualifiedType();
1783 } else if (FromType->isArrayType()) {
1784 // Array-to-pointer conversion (C++ 4.2)
1785 SCS.First = ICK_Array_To_Pointer;
1786
1787 // An lvalue or rvalue of type "array of N T" or "array of unknown
1788 // bound of T" can be converted to an rvalue of type "pointer to
1789 // T" (C++ 4.2p1).
1790 FromType = S.Context.getArrayDecayedType(FromType);
1791
1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793 // This conversion is deprecated in C++03 (D.4)
1794 SCS.DeprecatedStringLiteralToCharPtr = true;
1795
1796 // For the purpose of ranking in overload resolution
1797 // (13.3.3.1.1), this conversion is considered an
1798 // array-to-pointer conversion followed by a qualification
1799 // conversion (4.4). (C++ 4.2p2)
1800 SCS.Second = ICK_Identity;
1801 SCS.Third = ICK_Qualification;
1802 SCS.QualificationIncludesObjCLifetime = false;
1803 SCS.setAllToTypes(FromType);
1804 return true;
1805 }
1806 } else if (FromType->isFunctionType() && argIsLValue) {
1807 // Function-to-pointer conversion (C++ 4.3).
1808 SCS.First = ICK_Function_To_Pointer;
1809
1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812 if (!S.checkAddressOfFunctionIsAvailable(FD))
1813 return false;
1814
1815 // An lvalue of function type T can be converted to an rvalue of
1816 // type "pointer to T." The result is a pointer to the
1817 // function. (C++ 4.3p1).
1818 FromType = S.Context.getPointerType(FromType);
1819 } else {
1820 // We don't require any conversions for the first step.
1821 SCS.First = ICK_Identity;
1822 }
1823 SCS.setToType(0, FromType);
1824
1825 // The second conversion can be an integral promotion, floating
1826 // point promotion, integral conversion, floating point conversion,
1827 // floating-integral conversion, pointer conversion,
1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829 // For overloading in C, this can also be a "compatible-type"
1830 // conversion.
1831 bool IncompatibleObjC = false;
1832 ImplicitConversionKind SecondICK = ICK_Identity;
1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
4
Assuming the condition is false
5
Taking false branch
1834 // The unqualified versions of the types are the same: there's no
1835 // conversion to do.
1836 SCS.Second = ICK_Identity;
1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
6
Taking false branch
1838 // Integral promotion (C++ 4.5).
1839 SCS.Second = ICK_Integral_Promotion;
1840 FromType = ToType.getUnqualifiedType();
1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
7
Taking false branch
1842 // Floating point promotion (C++ 4.6).
1843 SCS.Second = ICK_Floating_Promotion;
1844 FromType = ToType.getUnqualifiedType();
1845 } else if (S.IsComplexPromotion(FromType, ToType)) {
1846 // Complex promotion (Clang extension)
1847 SCS.Second = ICK_Complex_Promotion;
1848 FromType = ToType.getUnqualifiedType();
1849 } else if (ToType->isBooleanType() &&
1850 (FromType->isArithmeticType() ||
1851 FromType->isAnyPointerType() ||
1852 FromType->isBlockPointerType() ||
1853 FromType->isMemberPointerType())) {
1854 // Boolean conversions (C++ 4.12).
1855 SCS.Second = ICK_Boolean_Conversion;
1856 FromType = S.Context.BoolTy;
1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
8
Assuming the condition is false
1858 ToType->isIntegralType(S.Context)) {
1859 // Integral conversions (C++ 4.7).
1860 SCS.Second = ICK_Integral_Conversion;
1861 FromType = ToType.getUnqualifiedType();
1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1863 // Complex conversions (C99 6.3.1.6)
1864 SCS.Second = ICK_Complex_Conversion;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1868 // Complex-real conversions (C99 6.3.1.7)
1869 SCS.Second = ICK_Complex_Real;
1870 FromType = ToType.getUnqualifiedType();
1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
9
Assuming the condition is false
1872 // FIXME: disable conversions between long double, __ibm128 and __float128
1873 // if their representation is different until there is back end support
1874 // We of course allow this conversion if long double is really double.
1875
1876 // Conversions between bfloat and other floats are not permitted.
1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1878 return false;
1879
1880 // Conversions between IEEE-quad and IBM-extended semantics are not
1881 // permitted.
1882 const llvm::fltSemantics &FromSem =
1883 S.Context.getFloatTypeSemantics(FromType);
1884 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1885 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1886 &ToSem == &llvm::APFloat::IEEEquad()) ||
1887 (&FromSem == &llvm::APFloat::IEEEquad() &&
1888 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1889 return false;
1890
1891 // Floating point conversions (C++ 4.8).
1892 SCS.Second = ICK_Floating_Conversion;
1893 FromType = ToType.getUnqualifiedType();
1894 } else if ((FromType->isRealFloatingType() &&
10
Assuming the condition is false
1895 ToType->isIntegralType(S.Context)) ||
1896 (FromType->isIntegralOrUnscopedEnumerationType() &&
11
Assuming the condition is false
1897 ToType->isRealFloatingType())) {
1898 // Conversions between bfloat and int are not permitted.
1899 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1900 return false;
1901
1902 // Floating-integral conversions (C++ 4.9).
1903 SCS.Second = ICK_Floating_Integral;
1904 FromType = ToType.getUnqualifiedType();
1905 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1906 SCS.Second = ICK_Block_Pointer_Conversion;
1907 } else if (AllowObjCWritebackConversion &&
12
Assuming 'AllowObjCWritebackConversion' is false
1908 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1909 SCS.Second = ICK_Writeback_Conversion;
1910 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
13
Calling 'Sema::IsPointerConversion'
1911 FromType, IncompatibleObjC)) {
1912 // Pointer conversions (C++ 4.10).
1913 SCS.Second = ICK_Pointer_Conversion;
1914 SCS.IncompatibleObjC = IncompatibleObjC;
1915 FromType = FromType.getUnqualifiedType();
1916 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1917 InOverloadResolution, FromType)) {
1918 // Pointer to member conversions (4.11).
1919 SCS.Second = ICK_Pointer_Member;
1920 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1921 SCS.Second = SecondICK;
1922 FromType = ToType.getUnqualifiedType();
1923 } else if (!S.getLangOpts().CPlusPlus &&
1924 S.Context.typesAreCompatible(ToType, FromType)) {
1925 // Compatible conversions (Clang extension for C function overloading)
1926 SCS.Second = ICK_Compatible_Conversion;
1927 FromType = ToType.getUnqualifiedType();
1928 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1929 InOverloadResolution,
1930 SCS, CStyle)) {
1931 SCS.Second = ICK_TransparentUnionConversion;
1932 FromType = ToType;
1933 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1934 CStyle)) {
1935 // tryAtomicConversion has updated the standard conversion sequence
1936 // appropriately.
1937 return true;
1938 } else if (ToType->isEventT() &&
1939 From->isIntegerConstantExpr(S.getASTContext()) &&
1940 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1941 SCS.Second = ICK_Zero_Event_Conversion;
1942 FromType = ToType;
1943 } else if (ToType->isQueueT() &&
1944 From->isIntegerConstantExpr(S.getASTContext()) &&
1945 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1946 SCS.Second = ICK_Zero_Queue_Conversion;
1947 FromType = ToType;
1948 } else if (ToType->isSamplerT() &&
1949 From->isIntegerConstantExpr(S.getASTContext())) {
1950 SCS.Second = ICK_Compatible_Conversion;
1951 FromType = ToType;
1952 } else {
1953 // No second conversion required.
1954 SCS.Second = ICK_Identity;
1955 }
1956 SCS.setToType(1, FromType);
1957
1958 // The third conversion can be a function pointer conversion or a
1959 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1960 bool ObjCLifetimeConversion;
1961 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1962 // Function pointer conversions (removing 'noexcept') including removal of
1963 // 'noreturn' (Clang extension).
1964 SCS.Third = ICK_Function_Conversion;
1965 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1966 ObjCLifetimeConversion)) {
1967 SCS.Third = ICK_Qualification;
1968 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1969 FromType = ToType;
1970 } else {
1971 // No conversion required
1972 SCS.Third = ICK_Identity;
1973 }
1974
1975 // C++ [over.best.ics]p6:
1976 // [...] Any difference in top-level cv-qualification is
1977 // subsumed by the initialization itself and does not constitute
1978 // a conversion. [...]
1979 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1980 QualType CanonTo = S.Context.getCanonicalType(ToType);
1981 if (CanonFrom.getLocalUnqualifiedType()
1982 == CanonTo.getLocalUnqualifiedType() &&
1983 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1984 FromType = ToType;
1985 CanonFrom = CanonTo;
1986 }
1987
1988 SCS.setToType(2, FromType);
1989
1990 if (CanonFrom == CanonTo)
1991 return true;
1992
1993 // If we have not converted the argument type to the parameter type,
1994 // this is a bad conversion sequence, unless we're resolving an overload in C.
1995 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1996 return false;
1997
1998 ExprResult ER = ExprResult{From};
1999 Sema::AssignConvertType Conv =
2000 S.CheckSingleAssignmentConstraints(ToType, ER,
2001 /*Diagnose=*/false,
2002 /*DiagnoseCFAudited=*/false,
2003 /*ConvertRHS=*/false);
2004 ImplicitConversionKind SecondConv;
2005 switch (Conv) {
2006 case Sema::Compatible:
2007 SecondConv = ICK_C_Only_Conversion;
2008 break;
2009 // For our purposes, discarding qualifiers is just as bad as using an
2010 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2011 // qualifiers, as well.
2012 case Sema::CompatiblePointerDiscardsQualifiers:
2013 case Sema::IncompatiblePointer:
2014 case Sema::IncompatiblePointerSign:
2015 SecondConv = ICK_Incompatible_Pointer_Conversion;
2016 break;
2017 default:
2018 return false;
2019 }
2020
2021 // First can only be an lvalue conversion, so we pretend that this was the
2022 // second conversion. First should already be valid from earlier in the
2023 // function.
2024 SCS.Second = SecondConv;
2025 SCS.setToType(1, ToType);
2026
2027 // Third is Identity, because Second should rank us worse than any other
2028 // conversion. This could also be ICK_Qualification, but it's simpler to just
2029 // lump everything in with the second conversion, and we don't gain anything
2030 // from making this ICK_Qualification.
2031 SCS.Third = ICK_Identity;
2032 SCS.setToType(2, ToType);
2033 return true;
2034}
2035
2036static bool
2037IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2038 QualType &ToType,
2039 bool InOverloadResolution,
2040 StandardConversionSequence &SCS,
2041 bool CStyle) {
2042
2043 const RecordType *UT = ToType->getAsUnionType();
2044 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2045 return false;
2046 // The field to initialize within the transparent union.
2047 RecordDecl *UD = UT->getDecl();
2048 // It's compatible if the expression matches any of the fields.
2049 for (const auto *it : UD->fields()) {
2050 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2051 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2052 ToType = it->getType();
2053 return true;
2054 }
2055 }
2056 return false;
2057}
2058
2059/// IsIntegralPromotion - Determines whether the conversion from the
2060/// expression From (whose potentially-adjusted type is FromType) to
2061/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2062/// sets PromotedType to the promoted type.
2063bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2064 const BuiltinType *To = ToType->getAs<BuiltinType>();
2065 // All integers are built-in.
2066 if (!To) {
2067 return false;
2068 }
2069
2070 // An rvalue of type char, signed char, unsigned char, short int, or
2071 // unsigned short int can be converted to an rvalue of type int if
2072 // int can represent all the values of the source type; otherwise,
2073 // the source rvalue can be converted to an rvalue of type unsigned
2074 // int (C++ 4.5p1).
2075 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2076 !FromType->isEnumeralType()) {
2077 if (// We can promote any signed, promotable integer type to an int
2078 (FromType->isSignedIntegerType() ||
2079 // We can promote any unsigned integer type whose size is
2080 // less than int to an int.
2081 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2082 return To->getKind() == BuiltinType::Int;
2083 }
2084
2085 return To->getKind() == BuiltinType::UInt;
2086 }
2087
2088 // C++11 [conv.prom]p3:
2089 // A prvalue of an unscoped enumeration type whose underlying type is not
2090 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2091 // following types that can represent all the values of the enumeration
2092 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2093 // unsigned int, long int, unsigned long int, long long int, or unsigned
2094 // long long int. If none of the types in that list can represent all the
2095 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2096 // type can be converted to an rvalue a prvalue of the extended integer type
2097 // with lowest integer conversion rank (4.13) greater than the rank of long
2098 // long in which all the values of the enumeration can be represented. If
2099 // there are two such extended types, the signed one is chosen.
2100 // C++11 [conv.prom]p4:
2101 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2102 // can be converted to a prvalue of its underlying type. Moreover, if
2103 // integral promotion can be applied to its underlying type, a prvalue of an
2104 // unscoped enumeration type whose underlying type is fixed can also be
2105 // converted to a prvalue of the promoted underlying type.
2106 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2107 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2108 // provided for a scoped enumeration.
2109 if (FromEnumType->getDecl()->isScoped())
2110 return false;
2111
2112 // We can perform an integral promotion to the underlying type of the enum,
2113 // even if that's not the promoted type. Note that the check for promoting
2114 // the underlying type is based on the type alone, and does not consider
2115 // the bitfield-ness of the actual source expression.
2116 if (FromEnumType->getDecl()->isFixed()) {
2117 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2118 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2119 IsIntegralPromotion(nullptr, Underlying, ToType);
2120 }
2121
2122 // We have already pre-calculated the promotion type, so this is trivial.
2123 if (ToType->isIntegerType() &&
2124 isCompleteType(From->getBeginLoc(), FromType))
2125 return Context.hasSameUnqualifiedType(
2126 ToType, FromEnumType->getDecl()->getPromotionType());
2127
2128 // C++ [conv.prom]p5:
2129 // If the bit-field has an enumerated type, it is treated as any other
2130 // value of that type for promotion purposes.
2131 //
2132 // ... so do not fall through into the bit-field checks below in C++.
2133 if (getLangOpts().CPlusPlus)
2134 return false;
2135 }
2136
2137 // C++0x [conv.prom]p2:
2138 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2139 // to an rvalue a prvalue of the first of the following types that can
2140 // represent all the values of its underlying type: int, unsigned int,
2141 // long int, unsigned long int, long long int, or unsigned long long int.
2142 // If none of the types in that list can represent all the values of its
2143 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2144 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2145 // type.
2146 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2147 ToType->isIntegerType()) {
2148 // Determine whether the type we're converting from is signed or
2149 // unsigned.
2150 bool FromIsSigned = FromType->isSignedIntegerType();
2151 uint64_t FromSize = Context.getTypeSize(FromType);
2152
2153 // The types we'll try to promote to, in the appropriate
2154 // order. Try each of these types.
2155 QualType PromoteTypes[6] = {
2156 Context.IntTy, Context.UnsignedIntTy,
2157 Context.LongTy, Context.UnsignedLongTy ,
2158 Context.LongLongTy, Context.UnsignedLongLongTy
2159 };
2160 for (int Idx = 0; Idx < 6; ++Idx) {
2161 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2162 if (FromSize < ToSize ||
2163 (FromSize == ToSize &&
2164 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2165 // We found the type that we can promote to. If this is the
2166 // type we wanted, we have a promotion. Otherwise, no
2167 // promotion.
2168 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2169 }
2170 }
2171 }
2172
2173 // An rvalue for an integral bit-field (9.6) can be converted to an
2174 // rvalue of type int if int can represent all the values of the
2175 // bit-field; otherwise, it can be converted to unsigned int if
2176 // unsigned int can represent all the values of the bit-field. If
2177 // the bit-field is larger yet, no integral promotion applies to
2178 // it. If the bit-field has an enumerated type, it is treated as any
2179 // other value of that type for promotion purposes (C++ 4.5p3).
2180 // FIXME: We should delay checking of bit-fields until we actually perform the
2181 // conversion.
2182 //
2183 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2184 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2185 // bit-fields and those whose underlying type is larger than int) for GCC
2186 // compatibility.
2187 if (From) {
2188 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2189 Optional<llvm::APSInt> BitWidth;
2190 if (FromType->isIntegralType(Context) &&
2191 (BitWidth =
2192 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2193 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2194 ToSize = Context.getTypeSize(ToType);
2195
2196 // Are we promoting to an int from a bitfield that fits in an int?
2197 if (*BitWidth < ToSize ||
2198 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2199 return To->getKind() == BuiltinType::Int;
2200 }
2201
2202 // Are we promoting to an unsigned int from an unsigned bitfield
2203 // that fits into an unsigned int?
2204 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2205 return To->getKind() == BuiltinType::UInt;
2206 }
2207
2208 return false;
2209 }
2210 }
2211 }
2212
2213 // An rvalue of type bool can be converted to an rvalue of type int,
2214 // with false becoming zero and true becoming one (C++ 4.5p4).
2215 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2216 return true;
2217 }
2218
2219 return false;
2220}
2221
2222/// IsFloatingPointPromotion - Determines whether the conversion from
2223/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2224/// returns true and sets PromotedType to the promoted type.
2225bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2226 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2227 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2228 /// An rvalue of type float can be converted to an rvalue of type
2229 /// double. (C++ 4.6p1).
2230 if (FromBuiltin->getKind() == BuiltinType::Float &&
2231 ToBuiltin->getKind() == BuiltinType::Double)
2232 return true;
2233
2234 // C99 6.3.1.5p1:
2235 // When a float is promoted to double or long double, or a
2236 // double is promoted to long double [...].
2237 if (!getLangOpts().CPlusPlus &&
2238 (FromBuiltin->getKind() == BuiltinType::Float ||
2239 FromBuiltin->getKind() == BuiltinType::Double) &&
2240 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2241 ToBuiltin->getKind() == BuiltinType::Float128 ||
2242 ToBuiltin->getKind() == BuiltinType::Ibm128))
2243 return true;
2244
2245 // Half can be promoted to float.
2246 if (!getLangOpts().NativeHalfType &&
2247 FromBuiltin->getKind() == BuiltinType::Half &&
2248 ToBuiltin->getKind() == BuiltinType::Float)
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
2255/// Determine if a conversion is a complex promotion.
2256///
2257/// A complex promotion is defined as a complex -> complex conversion
2258/// where the conversion between the underlying real types is a
2259/// floating-point or integral promotion.
2260bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2261 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2262 if (!FromComplex)
2263 return false;
2264
2265 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2266 if (!ToComplex)
2267 return false;
2268
2269 return IsFloatingPointPromotion(FromComplex->getElementType(),
2270 ToComplex->getElementType()) ||
2271 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2272 ToComplex->getElementType());
2273}
2274
2275/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2276/// the pointer type FromPtr to a pointer to type ToPointee, with the
2277/// same type qualifiers as FromPtr has on its pointee type. ToType,
2278/// if non-empty, will be a pointer to ToType that may or may not have
2279/// the right set of qualifiers on its pointee.
2280///
2281static QualType
2282BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2283 QualType ToPointee, QualType ToType,
2284 ASTContext &Context,
2285 bool StripObjCLifetime = false) {
2286 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2288, __extension__ __PRETTY_FUNCTION__
))
65
Called C++ object pointer is null
2287 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2288, __extension__ __PRETTY_FUNCTION__
))
2288 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2288, __extension__ __PRETTY_FUNCTION__
))
;
2289
2290 /// Conversions to 'id' subsume cv-qualifier conversions.
2291 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2292 return ToType.getUnqualifiedType();
2293
2294 QualType CanonFromPointee
2295 = Context.getCanonicalType(FromPtr->getPointeeType());
2296 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2297 Qualifiers Quals = CanonFromPointee.getQualifiers();
2298
2299 if (StripObjCLifetime)
2300 Quals.removeObjCLifetime();
2301
2302 // Exact qualifier match -> return the pointer type we're converting to.
2303 if (CanonToPointee.getLocalQualifiers() == Quals) {
2304 // ToType is exactly what we need. Return it.
2305 if (!ToType.isNull())
2306 return ToType.getUnqualifiedType();
2307
2308 // Build a pointer to ToPointee. It has the right qualifiers
2309 // already.
2310 if (isa<ObjCObjectPointerType>(ToType))
2311 return Context.getObjCObjectPointerType(ToPointee);
2312 return Context.getPointerType(ToPointee);
2313 }
2314
2315 // Just build a canonical type that has the right qualifiers.
2316 QualType QualifiedCanonToPointee
2317 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2318
2319 if (isa<ObjCObjectPointerType>(ToType))
2320 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2321 return Context.getPointerType(QualifiedCanonToPointee);
2322}
2323
2324static bool isNullPointerConstantForConversion(Expr *Expr,
2325 bool InOverloadResolution,
2326 ASTContext &Context) {
2327 // Handle value-dependent integral null pointer constants correctly.
2328 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2329 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
39
Assuming the condition is false
40
Taking false branch
2330 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2331 return !InOverloadResolution;
2332
2333 return Expr->isNullPointerConstant(Context,
43
Returning value, which participates in a condition later
2334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
41
Assuming 'InOverloadResolution' is false
42
'?' condition is false
2335 : Expr::NPC_ValueDependentIsNull);
2336}
2337
2338/// IsPointerConversion - Determines whether the conversion of the
2339/// expression From, which has the (possibly adjusted) type FromType,
2340/// can be converted to the type ToType via a pointer conversion (C++
2341/// 4.10). If so, returns true and places the converted type (that
2342/// might differ from ToType in its cv-qualifiers at some level) into
2343/// ConvertedType.
2344///
2345/// This routine also supports conversions to and from block pointers
2346/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2347/// pointers to interfaces. FIXME: Once we've determined the
2348/// appropriate overloading rules for Objective-C, we may want to
2349/// split the Objective-C checks into a different routine; however,
2350/// GCC seems to consider all of these conversions to be pointer
2351/// conversions, so for now they live here. IncompatibleObjC will be
2352/// set if the conversion is an allowed Objective-C conversion that
2353/// should result in a warning.
2354bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2355 bool InOverloadResolution,
2356 QualType& ConvertedType,
2357 bool &IncompatibleObjC) {
2358 IncompatibleObjC = false;
2359 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
14
Calling 'Sema::isObjCPointerConversion'
18
Returning from 'Sema::isObjCPointerConversion'
2360 IncompatibleObjC))
2361 return true;
2362
2363 // Conversion from a null pointer constant to any Objective-C pointer type.
2364 if (ToType->isObjCObjectPointerType() &&
19
Calling 'Type::isObjCObjectPointerType'
22
Returning from 'Type::isObjCObjectPointerType'
2365 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2366 ConvertedType = ToType;
2367 return true;
2368 }
2369
2370 // Blocks: Block pointers can be converted to void*.
2371 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2372 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2373 ConvertedType = ToType;
2374 return true;
2375 }
2376 // Blocks: A null pointer constant can be converted to a block
2377 // pointer type.
2378 if (ToType->isBlockPointerType() &&
23
Calling 'Type::isBlockPointerType'
26
Returning from 'Type::isBlockPointerType'
2379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2380 ConvertedType = ToType;
2381 return true;
2382 }
2383
2384 // If the left-hand-side is nullptr_t, the right side can be a null
2385 // pointer constant.
2386 if (ToType->isNullPtrType() &&
27
Calling 'Type::isNullPtrType'
34
Returning from 'Type::isNullPtrType'
2387 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2388 ConvertedType = ToType;
2389 return true;
2390 }
2391
2392 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
35
Assuming the object is a 'PointerType'
2393 if (!ToTypePtr)
36
Assuming 'ToTypePtr' is non-null
37
Taking false branch
2394 return false;
2395
2396 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2397 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
38
Calling 'isNullPointerConstantForConversion'
44
Returning from 'isNullPointerConstantForConversion'
45
Assuming the condition is false
46
Taking false branch
2398 ConvertedType = ToType;
2399 return true;
2400 }
2401
2402 // Beyond this point, both types need to be pointers
2403 // , including objective-c pointers.
2404 QualType ToPointeeType = ToTypePtr->getPointeeType();
2405 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
47
Calling 'Type::isObjCObjectPointerType'
50
Returning from 'Type::isObjCObjectPointerType'
51
Calling 'Type::isVoidType'
59
Returning from 'Type::isVoidType'
61
Taking true branch
2406 !getLangOpts().ObjCAutoRefCount) {
60
Assuming field 'ObjCAutoRefCount' is 0
2407 ConvertedType = BuildSimilarlyQualifiedPointerType(
64
Calling 'BuildSimilarlyQualifiedPointerType'
2408 FromType->getAs<ObjCObjectPointerType>(),
62
Assuming the object is not a 'ObjCObjectPointerType'
63
Passing null pointer value via 1st parameter 'FromPtr'
2409 ToPointeeType,
2410 ToType, Context);
2411 return true;
2412 }
2413 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2414 if (!FromTypePtr)
2415 return false;
2416
2417 QualType FromPointeeType = FromTypePtr->getPointeeType();
2418
2419 // If the unqualified pointee types are the same, this can't be a
2420 // pointer conversion, so don't do all of the work below.
2421 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2422 return false;
2423
2424 // An rvalue of type "pointer to cv T," where T is an object type,
2425 // can be converted to an rvalue of type "pointer to cv void" (C++
2426 // 4.10p2).
2427 if (FromPointeeType->isIncompleteOrObjectType() &&
2428 ToPointeeType->isVoidType()) {
2429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2430 ToPointeeType,
2431 ToType, Context,
2432 /*StripObjCLifetime=*/true);
2433 return true;
2434 }
2435
2436 // MSVC allows implicit function to void* type conversion.
2437 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2438 ToPointeeType->isVoidType()) {
2439 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2440 ToPointeeType,
2441 ToType, Context);
2442 return true;
2443 }
2444
2445 // When we're overloading in C, we allow a special kind of pointer
2446 // conversion for compatible-but-not-identical pointee types.
2447 if (!getLangOpts().CPlusPlus &&
2448 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2449 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2450 ToPointeeType,
2451 ToType, Context);
2452 return true;
2453 }
2454
2455 // C++ [conv.ptr]p3:
2456 //
2457 // An rvalue of type "pointer to cv D," where D is a class type,
2458 // can be converted to an rvalue of type "pointer to cv B," where
2459 // B is a base class (clause 10) of D. If B is an inaccessible
2460 // (clause 11) or ambiguous (10.2) base class of D, a program that
2461 // necessitates this conversion is ill-formed. The result of the
2462 // conversion is a pointer to the base class sub-object of the
2463 // derived class object. The null pointer value is converted to
2464 // the null pointer value of the destination type.
2465 //
2466 // Note that we do not check for ambiguity or inaccessibility
2467 // here. That is handled by CheckPointerConversion.
2468 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2469 ToPointeeType->isRecordType() &&
2470 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2471 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2472 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2473 ToPointeeType,
2474 ToType, Context);
2475 return true;
2476 }
2477
2478 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2479 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2480 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2481 ToPointeeType,
2482 ToType, Context);
2483 return true;
2484 }
2485
2486 return false;
2487}
2488
2489/// Adopt the given qualifiers for the given type.
2490static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2491 Qualifiers TQs = T.getQualifiers();
2492
2493 // Check whether qualifiers already match.
2494 if (TQs == Qs)
2495 return T;
2496
2497 if (Qs.compatiblyIncludes(TQs))
2498 return Context.getQualifiedType(T, Qs);
2499
2500 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2501}
2502
2503/// isObjCPointerConversion - Determines whether this is an
2504/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2505/// with the same arguments and return values.
2506bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2507 QualType& ConvertedType,
2508 bool &IncompatibleObjC) {
2509 if (!getLangOpts().ObjC)
15
Assuming field 'ObjC' is 0
16
Taking true branch
2510 return false;
17
Returning zero, which participates in a condition later
2511
2512 // The set of qualifiers on the type we're converting from.
2513 Qualifiers FromQualifiers = FromType.getQualifiers();
2514
2515 // First, we handle all conversions on ObjC object pointer types.
2516 const ObjCObjectPointerType* ToObjCPtr =
2517 ToType->getAs<ObjCObjectPointerType>();
2518 const ObjCObjectPointerType *FromObjCPtr =
2519 FromType->getAs<ObjCObjectPointerType>();
2520
2521 if (ToObjCPtr && FromObjCPtr) {
2522 // If the pointee types are the same (ignoring qualifications),
2523 // then this is not a pointer conversion.
2524 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2525 FromObjCPtr->getPointeeType()))
2526 return false;
2527
2528 // Conversion between Objective-C pointers.
2529 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2530 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2531 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2532 if (getLangOpts().CPlusPlus && LHS && RHS &&
2533 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2534 FromObjCPtr->getPointeeType()))
2535 return false;
2536 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537 ToObjCPtr->getPointeeType(),
2538 ToType, Context);
2539 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540 return true;
2541 }
2542
2543 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2544 // Okay: this is some kind of implicit downcast of Objective-C
2545 // interfaces, which is permitted. However, we're going to
2546 // complain about it.
2547 IncompatibleObjC = true;
2548 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2549 ToObjCPtr->getPointeeType(),
2550 ToType, Context);
2551 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2552 return true;
2553 }
2554 }
2555 // Beyond this point, both types need to be C pointers or block pointers.
2556 QualType ToPointeeType;
2557 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2558 ToPointeeType = ToCPtr->getPointeeType();
2559 else if (const BlockPointerType *ToBlockPtr =
2560 ToType->getAs<BlockPointerType>()) {
2561 // Objective C++: We're able to convert from a pointer to any object
2562 // to a block pointer type.
2563 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2564 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2565 return true;
2566 }
2567 ToPointeeType = ToBlockPtr->getPointeeType();
2568 }
2569 else if (FromType->getAs<BlockPointerType>() &&
2570 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2571 // Objective C++: We're able to convert from a block pointer type to a
2572 // pointer to any object.
2573 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2574 return true;
2575 }
2576 else
2577 return false;
2578
2579 QualType FromPointeeType;
2580 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2581 FromPointeeType = FromCPtr->getPointeeType();
2582 else if (const BlockPointerType *FromBlockPtr =
2583 FromType->getAs<BlockPointerType>())
2584 FromPointeeType = FromBlockPtr->getPointeeType();
2585 else
2586 return false;
2587
2588 // If we have pointers to pointers, recursively check whether this
2589 // is an Objective-C conversion.
2590 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2591 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592 IncompatibleObjC)) {
2593 // We always complain about this conversion.
2594 IncompatibleObjC = true;
2595 ConvertedType = Context.getPointerType(ConvertedType);
2596 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2597 return true;
2598 }
2599 // Allow conversion of pointee being objective-c pointer to another one;
2600 // as in I* to id.
2601 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2602 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2603 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2604 IncompatibleObjC)) {
2605
2606 ConvertedType = Context.getPointerType(ConvertedType);
2607 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2608 return true;
2609 }
2610
2611 // If we have pointers to functions or blocks, check whether the only
2612 // differences in the argument and result types are in Objective-C
2613 // pointer conversions. If so, we permit the conversion (but
2614 // complain about it).
2615 const FunctionProtoType *FromFunctionType
2616 = FromPointeeType->getAs<FunctionProtoType>();
2617 const FunctionProtoType *ToFunctionType
2618 = ToPointeeType->getAs<FunctionProtoType>();
2619 if (FromFunctionType && ToFunctionType) {
2620 // If the function types are exactly the same, this isn't an
2621 // Objective-C pointer conversion.
2622 if (Context.getCanonicalType(FromPointeeType)
2623 == Context.getCanonicalType(ToPointeeType))
2624 return false;
2625
2626 // Perform the quick checks that will tell us whether these
2627 // function types are obviously different.
2628 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2629 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2630 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2631 return false;
2632
2633 bool HasObjCConversion = false;
2634 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2635 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2636 // Okay, the types match exactly. Nothing to do.
2637 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2638 ToFunctionType->getReturnType(),
2639 ConvertedType, IncompatibleObjC)) {
2640 // Okay, we have an Objective-C pointer conversion.
2641 HasObjCConversion = true;
2642 } else {
2643 // Function types are too different. Abort.
2644 return false;
2645 }
2646
2647 // Check argument types.
2648 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2649 ArgIdx != NumArgs; ++ArgIdx) {
2650 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2651 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2652 if (Context.getCanonicalType(FromArgType)
2653 == Context.getCanonicalType(ToArgType)) {
2654 // Okay, the types match exactly. Nothing to do.
2655 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2656 ConvertedType, IncompatibleObjC)) {
2657 // Okay, we have an Objective-C pointer conversion.
2658 HasObjCConversion = true;
2659 } else {
2660 // Argument types are too different. Abort.
2661 return false;
2662 }
2663 }
2664
2665 if (HasObjCConversion) {
2666 // We had an Objective-C conversion. Allow this pointer
2667 // conversion, but complain about it.
2668 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2669 IncompatibleObjC = true;
2670 return true;
2671 }
2672 }
2673
2674 return false;
2675}
2676
2677/// Determine whether this is an Objective-C writeback conversion,
2678/// used for parameter passing when performing automatic reference counting.
2679///
2680/// \param FromType The type we're converting form.
2681///
2682/// \param ToType The type we're converting to.
2683///
2684/// \param ConvertedType The type that will be produced after applying
2685/// this conversion.
2686bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2687 QualType &ConvertedType) {
2688 if (!getLangOpts().ObjCAutoRefCount ||
2689 Context.hasSameUnqualifiedType(FromType, ToType))
2690 return false;
2691
2692 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2693 QualType ToPointee;
2694 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2695 ToPointee = ToPointer->getPointeeType();
2696 else
2697 return false;
2698
2699 Qualifiers ToQuals = ToPointee.getQualifiers();
2700 if (!ToPointee->isObjCLifetimeType() ||
2701 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2702 !ToQuals.withoutObjCLifetime().empty())
2703 return false;
2704
2705 // Argument must be a pointer to __strong to __weak.
2706 QualType FromPointee;
2707 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2708 FromPointee = FromPointer->getPointeeType();
2709 else
2710 return false;
2711
2712 Qualifiers FromQuals = FromPointee.getQualifiers();
2713 if (!FromPointee->isObjCLifetimeType() ||
2714 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2715 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2716 return false;
2717
2718 // Make sure that we have compatible qualifiers.
2719 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2720 if (!ToQuals.compatiblyIncludes(FromQuals))
2721 return false;
2722
2723 // Remove qualifiers from the pointee type we're converting from; they
2724 // aren't used in the compatibility check belong, and we'll be adding back
2725 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2726 FromPointee = FromPointee.getUnqualifiedType();
2727
2728 // The unqualified form of the pointee types must be compatible.
2729 ToPointee = ToPointee.getUnqualifiedType();
2730 bool IncompatibleObjC;
2731 if (Context.typesAreCompatible(FromPointee, ToPointee))
2732 FromPointee = ToPointee;
2733 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2734 IncompatibleObjC))
2735 return false;
2736
2737 /// Construct the type we're converting to, which is a pointer to
2738 /// __autoreleasing pointee.
2739 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2740 ConvertedType = Context.getPointerType(FromPointee);
2741 return true;
2742}
2743
2744bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2745 QualType& ConvertedType) {
2746 QualType ToPointeeType;
2747 if (const BlockPointerType *ToBlockPtr =
2748 ToType->getAs<BlockPointerType>())
2749 ToPointeeType = ToBlockPtr->getPointeeType();
2750 else
2751 return false;
2752
2753 QualType FromPointeeType;
2754 if (const BlockPointerType *FromBlockPtr =
2755 FromType->getAs<BlockPointerType>())
2756 FromPointeeType = FromBlockPtr->getPointeeType();
2757 else
2758 return false;
2759 // We have pointer to blocks, check whether the only
2760 // differences in the argument and result types are in Objective-C
2761 // pointer conversions. If so, we permit the conversion.
2762
2763 const FunctionProtoType *FromFunctionType
2764 = FromPointeeType->getAs<FunctionProtoType>();
2765 const FunctionProtoType *ToFunctionType
2766 = ToPointeeType->getAs<FunctionProtoType>();
2767
2768 if (!FromFunctionType || !ToFunctionType)
2769 return false;
2770
2771 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2772 return true;
2773
2774 // Perform the quick checks that will tell us whether these
2775 // function types are obviously different.
2776 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2777 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2778 return false;
2779
2780 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2781 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2782 if (FromEInfo != ToEInfo)
2783 return false;
2784
2785 bool IncompatibleObjC = false;
2786 if (Context.hasSameType(FromFunctionType->getReturnType(),
2787 ToFunctionType->getReturnType())) {
2788 // Okay, the types match exactly. Nothing to do.
2789 } else {
2790 QualType RHS = FromFunctionType->getReturnType();
2791 QualType LHS = ToFunctionType->getReturnType();
2792 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2793 !RHS.hasQualifiers() && LHS.hasQualifiers())
2794 LHS = LHS.getUnqualifiedType();
2795
2796 if (Context.hasSameType(RHS,LHS)) {
2797 // OK exact match.
2798 } else if (isObjCPointerConversion(RHS, LHS,
2799 ConvertedType, IncompatibleObjC)) {
2800 if (IncompatibleObjC)
2801 return false;
2802 // Okay, we have an Objective-C pointer conversion.
2803 }
2804 else
2805 return false;
2806 }
2807
2808 // Check argument types.
2809 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2810 ArgIdx != NumArgs; ++ArgIdx) {
2811 IncompatibleObjC = false;
2812 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2813 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2814 if (Context.hasSameType(FromArgType, ToArgType)) {
2815 // Okay, the types match exactly. Nothing to do.
2816 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2817 ConvertedType, IncompatibleObjC)) {
2818 if (IncompatibleObjC)
2819 return false;
2820 // Okay, we have an Objective-C pointer conversion.
2821 } else
2822 // Argument types are too different. Abort.
2823 return false;
2824 }
2825
2826 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2827 bool CanUseToFPT, CanUseFromFPT;
2828 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2829 CanUseToFPT, CanUseFromFPT,
2830 NewParamInfos))
2831 return false;
2832
2833 ConvertedType = ToType;
2834 return true;
2835}
2836
2837enum {
2838 ft_default,
2839 ft_different_class,
2840 ft_parameter_arity,
2841 ft_parameter_mismatch,
2842 ft_return_type,
2843 ft_qualifer_mismatch,
2844 ft_noexcept
2845};
2846
2847/// Attempts to get the FunctionProtoType from a Type. Handles
2848/// MemberFunctionPointers properly.
2849static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2850 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2851 return FPT;
2852
2853 if (auto *MPT = FromType->getAs<MemberPointerType>())
2854 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2855
2856 return nullptr;
2857}
2858
2859/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2860/// function types. Catches different number of parameter, mismatch in
2861/// parameter types, and different return types.
2862void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2863 QualType FromType, QualType ToType) {
2864 // If either type is not valid, include no extra info.
2865 if (FromType.isNull() || ToType.isNull()) {
2866 PDiag << ft_default;
2867 return;
2868 }
2869
2870 // Get the function type from the pointers.
2871 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2872 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2873 *ToMember = ToType->castAs<MemberPointerType>();
2874 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2875 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2876 << QualType(FromMember->getClass(), 0);
2877 return;
2878 }
2879 FromType = FromMember->getPointeeType();
2880 ToType = ToMember->getPointeeType();
2881 }
2882
2883 if (FromType->isPointerType())
2884 FromType = FromType->getPointeeType();
2885 if (ToType->isPointerType())
2886 ToType = ToType->getPointeeType();
2887
2888 // Remove references.
2889 FromType = FromType.getNonReferenceType();
2890 ToType = ToType.getNonReferenceType();
2891
2892 // Don't print extra info for non-specialized template functions.
2893 if (FromType->isInstantiationDependentType() &&
2894 !FromType->getAs<TemplateSpecializationType>()) {
2895 PDiag << ft_default;
2896 return;
2897 }
2898
2899 // No extra info for same types.
2900 if (Context.hasSameType(FromType, ToType)) {
2901 PDiag << ft_default;
2902 return;
2903 }
2904
2905 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2906 *ToFunction = tryGetFunctionProtoType(ToType);
2907
2908 // Both types need to be function types.
2909 if (!FromFunction || !ToFunction) {
2910 PDiag << ft_default;
2911 return;
2912 }
2913
2914 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2915 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2916 << FromFunction->getNumParams();
2917 return;
2918 }
2919
2920 // Handle different parameter types.
2921 unsigned ArgPos;
2922 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2923 PDiag << ft_parameter_mismatch << ArgPos + 1
2924 << ToFunction->getParamType(ArgPos)
2925 << FromFunction->getParamType(ArgPos);
2926 return;
2927 }
2928
2929 // Handle different return type.
2930 if (!Context.hasSameType(FromFunction->getReturnType(),
2931 ToFunction->getReturnType())) {
2932 PDiag << ft_return_type << ToFunction->getReturnType()
2933 << FromFunction->getReturnType();
2934 return;
2935 }
2936
2937 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2938 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2939 << FromFunction->getMethodQuals();
2940 return;
2941 }
2942
2943 // Handle exception specification differences on canonical type (in C++17
2944 // onwards).
2945 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2946 ->isNothrow() !=
2947 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2948 ->isNothrow()) {
2949 PDiag << ft_noexcept;
2950 return;
2951 }
2952
2953 // Unable to find a difference, so add no extra info.
2954 PDiag << ft_default;
2955}
2956
2957/// FunctionParamTypesAreEqual - This routine checks two function proto types
2958/// for equality of their argument types. Caller has already checked that
2959/// they have same number of arguments. If the parameters are different,
2960/// ArgPos will have the parameter index of the first different parameter.
2961bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2962 const FunctionProtoType *NewType,
2963 unsigned *ArgPos) {
2964 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2965 N = NewType->param_type_begin(),
2966 E = OldType->param_type_end();
2967 O && (O != E); ++O, ++N) {
2968 // Ignore address spaces in pointee type. This is to disallow overloading
2969 // on __ptr32/__ptr64 address spaces.
2970 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2971 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2972
2973 if (!Context.hasSameType(Old, New)) {
2974 if (ArgPos)
2975 *ArgPos = O - OldType->param_type_begin();
2976 return false;
2977 }
2978 }
2979 return true;
2980}
2981
2982/// CheckPointerConversion - Check the pointer conversion from the
2983/// expression From to the type ToType. This routine checks for
2984/// ambiguous or inaccessible derived-to-base pointer
2985/// conversions for which IsPointerConversion has already returned
2986/// true. It returns true and produces a diagnostic if there was an
2987/// error, or returns false otherwise.
2988bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2989 CastKind &Kind,
2990 CXXCastPath& BasePath,
2991 bool IgnoreBaseAccess,
2992 bool Diagnose) {
2993 QualType FromType = From->getType();
2994 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2995
2996 Kind = CK_BitCast;
2997
2998 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2999 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3000 Expr::NPCK_ZeroExpression) {
3001 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3002 DiagRuntimeBehavior(From->getExprLoc(), From,
3003 PDiag(diag::warn_impcast_bool_to_null_pointer)
3004 << ToType << From->getSourceRange());
3005 else if (!isUnevaluatedContext())
3006 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3007 << ToType << From->getSourceRange();
3008 }
3009 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3010 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3011 QualType FromPointeeType = FromPtrType->getPointeeType(),
3012 ToPointeeType = ToPtrType->getPointeeType();
3013
3014 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3015 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3016 // We must have a derived-to-base conversion. Check an
3017 // ambiguous or inaccessible conversion.
3018 unsigned InaccessibleID = 0;
3019 unsigned AmbiguousID = 0;
3020 if (Diagnose) {
3021 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3022 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3023 }
3024 if (CheckDerivedToBaseConversion(
3025 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3026 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3027 &BasePath, IgnoreBaseAccess))
3028 return true;
3029
3030 // The conversion was successful.
3031 Kind = CK_DerivedToBase;
3032 }
3033
3034 if (Diagnose && !IsCStyleOrFunctionalCast &&
3035 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3036 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3037, __extension__ __PRETTY_FUNCTION__
))
3037 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3037, __extension__ __PRETTY_FUNCTION__
))
;
3038 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3039 << From->getSourceRange();
3040 }
3041 }
3042 } else if (const ObjCObjectPointerType *ToPtrType =
3043 ToType->getAs<ObjCObjectPointerType>()) {
3044 if (const ObjCObjectPointerType *FromPtrType =
3045 FromType->getAs<ObjCObjectPointerType>()) {
3046 // Objective-C++ conversions are always okay.
3047 // FIXME: We should have a different class of conversions for the
3048 // Objective-C++ implicit conversions.
3049 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3050 return false;
3051 } else if (FromType->isBlockPointerType()) {
3052 Kind = CK_BlockPointerToObjCPointerCast;
3053 } else {
3054 Kind = CK_CPointerToObjCPointerCast;
3055 }
3056 } else if (ToType->isBlockPointerType()) {
3057 if (!FromType->isBlockPointerType())
3058 Kind = CK_AnyPointerToBlockPointerCast;
3059 }
3060
3061 // We shouldn't fall into this case unless it's valid for other
3062 // reasons.
3063 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3064 Kind = CK_NullToPointer;
3065
3066 return false;
3067}
3068
3069/// IsMemberPointerConversion - Determines whether the conversion of the
3070/// expression From, which has the (possibly adjusted) type FromType, can be
3071/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3072/// If so, returns true and places the converted type (that might differ from
3073/// ToType in its cv-qualifiers at some level) into ConvertedType.
3074bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3075 QualType ToType,
3076 bool InOverloadResolution,
3077 QualType &ConvertedType) {
3078 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3079 if (!ToTypePtr)
3080 return false;
3081
3082 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3083 if (From->isNullPointerConstant(Context,
3084 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3085 : Expr::NPC_ValueDependentIsNull)) {
3086 ConvertedType = ToType;
3087 return true;
3088 }
3089
3090 // Otherwise, both types have to be member pointers.
3091 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3092 if (!FromTypePtr)
3093 return false;
3094
3095 // A pointer to member of B can be converted to a pointer to member of D,
3096 // where D is derived from B (C++ 4.11p2).
3097 QualType FromClass(FromTypePtr->getClass(), 0);
3098 QualType ToClass(ToTypePtr->getClass(), 0);
3099
3100 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3101 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3102 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3103 ToClass.getTypePtr());
3104 return true;
3105 }
3106
3107 return false;
3108}
3109
3110/// CheckMemberPointerConversion - Check the member pointer conversion from the
3111/// expression From to the type ToType. This routine checks for ambiguous or
3112/// virtual or inaccessible base-to-derived member pointer conversions
3113/// for which IsMemberPointerConversion has already returned true. It returns
3114/// true and produces a diagnostic if there was an error, or returns false
3115/// otherwise.
3116bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3117 CastKind &Kind,
3118 CXXCastPath &BasePath,
3119 bool IgnoreBaseAccess) {
3120 QualType FromType = From->getType();
3121 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3122 if (!FromPtrType) {
3123 // This must be a null pointer to member pointer conversion
3124 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3126, __extension__ __PRETTY_FUNCTION__
))
3125 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3126, __extension__ __PRETTY_FUNCTION__
))
3126 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3126, __extension__ __PRETTY_FUNCTION__
))
;
3127 Kind = CK_NullToMemberPointer;
3128 return false;
3129 }
3130
3131 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3132 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3133, __extension__ __PRETTY_FUNCTION__
))
3133 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3133, __extension__ __PRETTY_FUNCTION__
))
;
3134
3135 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3136 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3137
3138 // FIXME: What about dependent types?
3139 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3139, __extension__ __PRETTY_FUNCTION__
))
;
3140 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3140, __extension__ __PRETTY_FUNCTION__
))
;
3141
3142 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3143 /*DetectVirtual=*/true);
3144 bool DerivationOkay =
3145 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3146 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3147, __extension__ __PRETTY_FUNCTION__
))
3147 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3147, __extension__ __PRETTY_FUNCTION__
))
;
3148 (void)DerivationOkay;
3149
3150 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3151 getUnqualifiedType())) {
3152 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3153 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3154 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3155 return true;
3156 }
3157
3158 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3159 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3160 << FromClass << ToClass << QualType(VBase, 0)
3161 << From->getSourceRange();
3162 return true;
3163 }
3164
3165 if (!IgnoreBaseAccess)
3166 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3167 Paths.front(),
3168 diag::err_downcast_from_inaccessible_base);
3169
3170 // Must be a base to derived member conversion.
3171 BuildBasePathArray(Paths, BasePath);
3172 Kind = CK_BaseToDerivedMemberPointer;
3173 return false;
3174}
3175
3176/// Determine whether the lifetime conversion between the two given
3177/// qualifiers sets is nontrivial.
3178static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3179 Qualifiers ToQuals) {
3180 // Converting anything to const __unsafe_unretained is trivial.
3181 if (ToQuals.hasConst() &&
3182 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3183 return false;
3184
3185 return true;
3186}
3187
3188/// Perform a single iteration of the loop for checking if a qualification
3189/// conversion is valid.
3190///
3191/// Specifically, check whether any change between the qualifiers of \p
3192/// FromType and \p ToType is permissible, given knowledge about whether every
3193/// outer layer is const-qualified.
3194static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3195 bool CStyle, bool IsTopLevel,
3196 bool &PreviousToQualsIncludeConst,
3197 bool &ObjCLifetimeConversion) {
3198 Qualifiers FromQuals = FromType.getQualifiers();
3199 Qualifiers ToQuals = ToType.getQualifiers();
3200
3201 // Ignore __unaligned qualifier if this type is void.
3202 if (ToType.getUnqualifiedType()->isVoidType())
3203 FromQuals.removeUnaligned();
3204
3205 // Objective-C ARC:
3206 // Check Objective-C lifetime conversions.
3207 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3208 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3209 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3210 ObjCLifetimeConversion = true;
3211 FromQuals.removeObjCLifetime();
3212 ToQuals.removeObjCLifetime();
3213 } else {
3214 // Qualification conversions cannot cast between different
3215 // Objective-C lifetime qualifiers.
3216 return false;
3217 }
3218 }
3219
3220 // Allow addition/removal of GC attributes but not changing GC attributes.
3221 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3222 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3223 FromQuals.removeObjCGCAttr();
3224 ToQuals.removeObjCGCAttr();
3225 }
3226
3227 // -- for every j > 0, if const is in cv 1,j then const is in cv
3228 // 2,j, and similarly for volatile.
3229 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3230 return false;
3231
3232 // If address spaces mismatch:
3233 // - in top level it is only valid to convert to addr space that is a
3234 // superset in all cases apart from C-style casts where we allow
3235 // conversions between overlapping address spaces.
3236 // - in non-top levels it is not a valid conversion.
3237 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3238 (!IsTopLevel ||
3239 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3240 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3241 return false;
3242
3243 // -- if the cv 1,j and cv 2,j are different, then const is in
3244 // every cv for 0 < k < j.
3245 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3246 !PreviousToQualsIncludeConst)
3247 return false;
3248
3249 // The following wording is from C++20, where the result of the conversion
3250 // is T3, not T2.
3251 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3252 // "array of unknown bound of"
3253 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3254 return false;
3255
3256 // -- if the resulting P3,i is different from P1,i [...], then const is
3257 // added to every cv 3_k for 0 < k < i.
3258 if (!CStyle && FromType->isConstantArrayType() &&
3259 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3260 return false;
3261
3262 // Keep track of whether all prior cv-qualifiers in the "to" type
3263 // include const.
3264 PreviousToQualsIncludeConst =
3265 PreviousToQualsIncludeConst && ToQuals.hasConst();
3266 return true;
3267}
3268
3269/// IsQualificationConversion - Determines whether the conversion from
3270/// an rvalue of type FromType to ToType is a qualification conversion
3271/// (C++ 4.4).
3272///
3273/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3274/// when the qualification conversion involves a change in the Objective-C
3275/// object lifetime.
3276bool
3277Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3278 bool CStyle, bool &ObjCLifetimeConversion) {
3279 FromType = Context.getCanonicalType(FromType);
3280 ToType = Context.getCanonicalType(ToType);
3281 ObjCLifetimeConversion = false;
3282
3283 // If FromType and ToType are the same type, this is not a
3284 // qualification conversion.
3285 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3286 return false;
3287
3288 // (C++ 4.4p4):
3289 // A conversion can add cv-qualifiers at levels other than the first
3290 // in multi-level pointers, subject to the following rules: [...]
3291 bool PreviousToQualsIncludeConst = true;
3292 bool UnwrappedAnyPointer = false;
3293 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3294 if (!isQualificationConversionStep(
3295 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3296 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3297 return false;
3298 UnwrappedAnyPointer = true;
3299 }
3300
3301 // We are left with FromType and ToType being the pointee types
3302 // after unwrapping the original FromType and ToType the same number
3303 // of times. If we unwrapped any pointers, and if FromType and
3304 // ToType have the same unqualified type (since we checked
3305 // qualifiers above), then this is a qualification conversion.
3306 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3307}
3308
3309/// - Determine whether this is a conversion from a scalar type to an
3310/// atomic type.
3311///
3312/// If successful, updates \c SCS's second and third steps in the conversion
3313/// sequence to finish the conversion.
3314static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3315 bool InOverloadResolution,
3316 StandardConversionSequence &SCS,
3317 bool CStyle) {
3318 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3319 if (!ToAtomic)
3320 return false;
3321
3322 StandardConversionSequence InnerSCS;
3323 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3324 InOverloadResolution, InnerSCS,
3325 CStyle, /*AllowObjCWritebackConversion=*/false))
3326 return false;
3327
3328 SCS.Second = InnerSCS.Second;
3329 SCS.setToType(1, InnerSCS.getToType(1));
3330 SCS.Third = InnerSCS.Third;
3331 SCS.QualificationIncludesObjCLifetime
3332 = InnerSCS.QualificationIncludesObjCLifetime;
3333 SCS.setToType(2, InnerSCS.getToType(2));
3334 return true;
3335}
3336
3337static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3338 CXXConstructorDecl *Constructor,
3339 QualType Type) {
3340 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3341 if (CtorType->getNumParams() > 0) {
3342 QualType FirstArg = CtorType->getParamType(0);
3343 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3344 return true;
3345 }
3346 return false;
3347}
3348
3349static OverloadingResult
3350IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3351 CXXRecordDecl *To,
3352 UserDefinedConversionSequence &User,
3353 OverloadCandidateSet &CandidateSet,
3354 bool AllowExplicit) {
3355 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3356 for (auto *D : S.LookupConstructors(To)) {
3357 auto Info = getConstructorInfo(D);
3358 if (!Info)
3359 continue;
3360
3361 bool Usable = !Info.Constructor->isInvalidDecl() &&
3362 S.isInitListConstructor(Info.Constructor);
3363 if (Usable) {
3364 bool SuppressUserConversions = false;
3365 if (Info.ConstructorTmpl)
3366 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3367 /*ExplicitArgs*/ nullptr, From,
3368 CandidateSet, SuppressUserConversions,
3369 /*PartialOverloading*/ false,
3370 AllowExplicit);
3371 else
3372 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3373 CandidateSet, SuppressUserConversions,
3374 /*PartialOverloading*/ false, AllowExplicit);
3375 }
3376 }
3377
3378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3379
3380 OverloadCandidateSet::iterator Best;
3381 switch (auto Result =
3382 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3383 case OR_Deleted:
3384 case OR_Success: {
3385 // Record the standard conversion we used and the conversion function.
3386 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3387 QualType ThisType = Constructor->getThisType();
3388 // Initializer lists don't have conversions as such.
3389 User.Before.setAsIdentityConversion();
3390 User.HadMultipleCandidates = HadMultipleCandidates;
3391 User.ConversionFunction = Constructor;
3392 User.FoundConversionFunction = Best->FoundDecl;
3393 User.After.setAsIdentityConversion();
3394 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3395 User.After.setAllToTypes(ToType);
3396 return Result;
3397 }
3398
3399 case OR_No_Viable_Function:
3400 return OR_No_Viable_Function;
3401 case OR_Ambiguous:
3402 return OR_Ambiguous;
3403 }
3404
3405 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3405)
;
3406}
3407
3408/// Determines whether there is a user-defined conversion sequence
3409/// (C++ [over.ics.user]) that converts expression From to the type
3410/// ToType. If such a conversion exists, User will contain the
3411/// user-defined conversion sequence that performs such a conversion
3412/// and this routine will return true. Otherwise, this routine returns
3413/// false and User is unspecified.
3414///
3415/// \param AllowExplicit true if the conversion should consider C++0x
3416/// "explicit" conversion functions as well as non-explicit conversion
3417/// functions (C++0x [class.conv.fct]p2).
3418///
3419/// \param AllowObjCConversionOnExplicit true if the conversion should
3420/// allow an extra Objective-C pointer conversion on uses of explicit
3421/// constructors. Requires \c AllowExplicit to also be set.
3422static OverloadingResult
3423IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3424 UserDefinedConversionSequence &User,
3425 OverloadCandidateSet &CandidateSet,
3426 AllowedExplicit AllowExplicit,
3427 bool AllowObjCConversionOnExplicit) {
3428 assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3429, __extension__ __PRETTY_FUNCTION__
))
3429 !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3429, __extension__ __PRETTY_FUNCTION__
))
;
3430 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3431
3432 // Whether we will only visit constructors.
3433 bool ConstructorsOnly = false;
3434
3435 // If the type we are conversion to is a class type, enumerate its
3436 // constructors.
3437 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3438 // C++ [over.match.ctor]p1:
3439 // When objects of class type are direct-initialized (8.5), or
3440 // copy-initialized from an expression of the same or a
3441 // derived class type (8.5), overload resolution selects the
3442 // constructor. [...] For copy-initialization, the candidate
3443 // functions are all the converting constructors (12.3.1) of
3444 // that class. The argument list is the expression-list within
3445 // the parentheses of the initializer.
3446 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3447 (From->getType()->getAs<RecordType>() &&
3448 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3449 ConstructorsOnly = true;
3450
3451 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3452 // We're not going to find any constructors.
3453 } else if (CXXRecordDecl *ToRecordDecl
3454 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3455
3456 Expr **Args = &From;
3457 unsigned NumArgs = 1;
3458 bool ListInitializing = false;
3459 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3460 // But first, see if there is an init-list-constructor that will work.
3461 OverloadingResult Result = IsInitializerListConstructorConversion(
3462 S, From, ToType, ToRecordDecl, User, CandidateSet,
3463 AllowExplicit == AllowedExplicit::All);
3464 if (Result != OR_No_Viable_Function)
3465 return Result;
3466 // Never mind.
3467 CandidateSet.clear(
3468 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3469
3470 // If we're list-initializing, we pass the individual elements as
3471 // arguments, not the entire list.
3472 Args = InitList->getInits();
3473 NumArgs = InitList->getNumInits();
3474 ListInitializing = true;
3475 }
3476
3477 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3478 auto Info = getConstructorInfo(D);
3479 if (!Info)
3480 continue;
3481
3482 bool Usable = !Info.Constructor->isInvalidDecl();
3483 if (!ListInitializing)
3484 Usable = Usable && Info.Constructor->isConvertingConstructor(
3485 /*AllowExplicit*/ true);
3486 if (Usable) {
3487 bool SuppressUserConversions = !ConstructorsOnly;
3488 // C++20 [over.best.ics.general]/4.5:
3489 // if the target is the first parameter of a constructor [of class
3490 // X] and the constructor [...] is a candidate by [...] the second
3491 // phase of [over.match.list] when the initializer list has exactly
3492 // one element that is itself an initializer list, [...] and the
3493 // conversion is to X or reference to cv X, user-defined conversion
3494 // sequences are not cnosidered.
3495 if (SuppressUserConversions && ListInitializing) {
3496 SuppressUserConversions =
3497 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3498 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3499 ToType);
3500 }
3501 if (Info.ConstructorTmpl)
3502 S.AddTemplateOverloadCandidate(
3503 Info.ConstructorTmpl, Info.FoundDecl,
3504 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3505 CandidateSet, SuppressUserConversions,
3506 /*PartialOverloading*/ false,
3507 AllowExplicit == AllowedExplicit::All);
3508 else
3509 // Allow one user-defined conversion when user specifies a
3510 // From->ToType conversion via an static cast (c-style, etc).
3511 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3512 llvm::makeArrayRef(Args, NumArgs),
3513 CandidateSet, SuppressUserConversions,
3514 /*PartialOverloading*/ false,
3515 AllowExplicit == AllowedExplicit::All);
3516 }
3517 }
3518 }
3519 }
3520
3521 // Enumerate conversion functions, if we're allowed to.
3522 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3523 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3524 // No conversion functions from incomplete types.
3525 } else if (const RecordType *FromRecordType =
3526 From->getType()->getAs<RecordType>()) {
3527 if (CXXRecordDecl *FromRecordDecl
3528 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3529 // Add all of the conversion functions as candidates.
3530 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3531 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3532 DeclAccessPair FoundDecl = I.getPair();
3533 NamedDecl *D = FoundDecl.getDecl();
3534 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3535 if (isa<UsingShadowDecl>(D))
3536 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3537
3538 CXXConversionDecl *Conv;
3539 FunctionTemplateDecl *ConvTemplate;
3540 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3541 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3542 else
3543 Conv = cast<CXXConversionDecl>(D);
3544
3545 if (ConvTemplate)
3546 S.AddTemplateConversionCandidate(
3547 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3548 CandidateSet, AllowObjCConversionOnExplicit,
3549 AllowExplicit != AllowedExplicit::None);
3550 else
3551 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3552 CandidateSet, AllowObjCConversionOnExplicit,
3553 AllowExplicit != AllowedExplicit::None);
3554 }
3555 }
3556 }
3557
3558 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3559
3560 OverloadCandidateSet::iterator Best;
3561 switch (auto Result =
3562 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3563 case OR_Success:
3564 case OR_Deleted:
3565 // Record the standard conversion we used and the conversion function.
3566 if (CXXConstructorDecl *Constructor
3567 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3568 // C++ [over.ics.user]p1:
3569 // If the user-defined conversion is specified by a
3570 // constructor (12.3.1), the initial standard conversion
3571 // sequence converts the source type to the type required by
3572 // the argument of the constructor.
3573 //
3574 QualType ThisType = Constructor->getThisType();
3575 if (isa<InitListExpr>(From)) {
3576 // Initializer lists don't have conversions as such.
3577 User.Before.setAsIdentityConversion();
3578 } else {
3579 if (Best->Conversions[0].isEllipsis())
3580 User.EllipsisConversion = true;
3581 else {
3582 User.Before = Best->Conversions[0].Standard;
3583 User.EllipsisConversion = false;
3584 }
3585 }
3586 User.HadMultipleCandidates = HadMultipleCandidates;
3587 User.ConversionFunction = Constructor;
3588 User.FoundConversionFunction = Best->FoundDecl;
3589 User.After.setAsIdentityConversion();
3590 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3591 User.After.setAllToTypes(ToType);
3592 return Result;
3593 }
3594 if (CXXConversionDecl *Conversion
3595 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3596 // C++ [over.ics.user]p1:
3597 //
3598 // [...] If the user-defined conversion is specified by a
3599 // conversion function (12.3.2), the initial standard
3600 // conversion sequence converts the source type to the
3601 // implicit object parameter of the conversion function.
3602 User.Before = Best->Conversions[0].Standard;
3603 User.HadMultipleCandidates = HadMultipleCandidates;
3604 User.ConversionFunction = Conversion;
3605 User.FoundConversionFunction = Best->FoundDecl;
3606 User.EllipsisConversion = false;
3607
3608 // C++ [over.ics.user]p2:
3609 // The second standard conversion sequence converts the
3610 // result of the user-defined conversion to the target type
3611 // for the sequence. Since an implicit conversion sequence
3612 // is an initialization, the special rules for
3613 // initialization by user-defined conversion apply when
3614 // selecting the best user-defined conversion for a
3615 // user-defined conversion sequence (see 13.3.3 and
3616 // 13.3.3.1).
3617 User.After = Best->FinalConversion;
3618 return Result;
3619 }
3620 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "clang/lib/Sema/SemaOverload.cpp", 3620)
;
3621
3622 case OR_No_Viable_Function:
3623 return OR_No_Viable_Function;
3624
3625 case OR_Ambiguous:
3626 return OR_Ambiguous;
3627 }
3628
3629 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3629)
;
3630}
3631
3632bool
3633Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3634 ImplicitConversionSequence ICS;
3635 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3636 OverloadCandidateSet::CSK_Normal);
3637 OverloadingResult OvResult =
3638 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3639 CandidateSet, AllowedExplicit::None, false);
3640
3641 if (!(OvResult == OR_Ambiguous ||
3642 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3643 return false;
3644
3645 auto Cands = CandidateSet.CompleteCandidates(
3646 *this,
3647 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3648 From);
3649 if (OvResult == OR_Ambiguous)
3650 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3651 << From->getType() << ToType << From->getSourceRange();
3652 else { // OR_No_Viable_Function && !CandidateSet.empty()
3653 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3654 diag::err_typecheck_nonviable_condition_incomplete,
3655 From->getType(), From->getSourceRange()))
3656 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3657 << false << From->getType() << From->getSourceRange() << ToType;
3658 }
3659
3660 CandidateSet.NoteCandidates(
3661 *this, From, Cands);
3662 return true;
3663}
3664
3665// Helper for compareConversionFunctions that gets the FunctionType that the
3666// conversion-operator return value 'points' to, or nullptr.
3667static const FunctionType *
3668getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3669 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3670 const PointerType *RetPtrTy =
3671 ConvFuncTy->getReturnType()->getAs<PointerType>();
3672
3673 if (!RetPtrTy)
3674 return nullptr;
3675
3676 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3677}
3678
3679/// Compare the user-defined conversion functions or constructors
3680/// of two user-defined conversion sequences to determine whether any ordering
3681/// is possible.
3682static ImplicitConversionSequence::CompareKind
3683compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3684 FunctionDecl *Function2) {
3685 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3686 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3687 if (!Conv1 || !Conv2)
3688 return ImplicitConversionSequence::Indistinguishable;
3689
3690 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3691 return ImplicitConversionSequence::Indistinguishable;
3692
3693 // Objective-C++:
3694 // If both conversion functions are implicitly-declared conversions from
3695 // a lambda closure type to a function pointer and a block pointer,
3696 // respectively, always prefer the conversion to a function pointer,
3697 // because the function pointer is more lightweight and is more likely
3698 // to keep code working.
3699 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3700 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3701 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3702 if (Block1 != Block2)
3703 return Block1 ? ImplicitConversionSequence::Worse
3704 : ImplicitConversionSequence::Better;
3705 }
3706
3707 // In order to support multiple calling conventions for the lambda conversion
3708 // operator (such as when the free and member function calling convention is
3709 // different), prefer the 'free' mechanism, followed by the calling-convention
3710 // of operator(). The latter is in place to support the MSVC-like solution of
3711 // defining ALL of the possible conversions in regards to calling-convention.
3712 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3713 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3714
3715 if (Conv1FuncRet && Conv2FuncRet &&
3716 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3717 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3718 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3719
3720 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3721 const FunctionProtoType *CallOpProto =
3722 CallOp->getType()->getAs<FunctionProtoType>();
3723
3724 CallingConv CallOpCC =
3725 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3726 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3727 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3728 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3729 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3730
3731 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3732 for (CallingConv CC : PrefOrder) {
3733 if (Conv1CC == CC)
3734 return ImplicitConversionSequence::Better;
3735 if (Conv2CC == CC)
3736 return ImplicitConversionSequence::Worse;
3737 }
3738 }
3739
3740 return ImplicitConversionSequence::Indistinguishable;
3741}
3742
3743static bool hasDeprecatedStringLiteralToCharPtrConversion(
3744 const ImplicitConversionSequence &ICS) {
3745 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3746 (ICS.isUserDefined() &&
3747 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3748}
3749
3750/// CompareImplicitConversionSequences - Compare two implicit
3751/// conversion sequences to determine whether one is better than the
3752/// other or if they are indistinguishable (C++ 13.3.3.2).
3753static ImplicitConversionSequence::CompareKind
3754CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3755 const ImplicitConversionSequence& ICS1,
3756 const ImplicitConversionSequence& ICS2)
3757{
3758 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3759 // conversion sequences (as defined in 13.3.3.1)
3760 // -- a standard conversion sequence (13.3.3.1.1) is a better
3761 // conversion sequence than a user-defined conversion sequence or
3762 // an ellipsis conversion sequence, and
3763 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3764 // conversion sequence than an ellipsis conversion sequence
3765 // (13.3.3.1.3).
3766 //
3767 // C++0x [over.best.ics]p10:
3768 // For the purpose of ranking implicit conversion sequences as
3769 // described in 13.3.3.2, the ambiguous conversion sequence is
3770 // treated as a user-defined sequence that is indistinguishable
3771 // from any other user-defined conversion sequence.
3772
3773 // String literal to 'char *' conversion has been deprecated in C++03. It has
3774 // been removed from C++11. We still accept this conversion, if it happens at
3775 // the best viable function. Otherwise, this conversion is considered worse
3776 // than ellipsis conversion. Consider this as an extension; this is not in the
3777 // standard. For example:
3778 //
3779 // int &f(...); // #1
3780 // void f(char*); // #2
3781 // void g() { int &r = f("foo"); }
3782 //
3783 // In C++03, we pick #2 as the best viable function.
3784 // In C++11, we pick #1 as the best viable function, because ellipsis
3785 // conversion is better than string-literal to char* conversion (since there
3786 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3787 // convert arguments, #2 would be the best viable function in C++11.
3788 // If the best viable function has this conversion, a warning will be issued
3789 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3790
3791 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3792 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3793 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3794 // Ill-formedness must not differ
3795 ICS1.isBad() == ICS2.isBad())
3796 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3797 ? ImplicitConversionSequence::Worse
3798 : ImplicitConversionSequence::Better;
3799
3800 if (ICS1.getKindRank() < ICS2.getKindRank())
3801 return ImplicitConversionSequence::Better;
3802 if (ICS2.getKindRank() < ICS1.getKindRank())
3803 return ImplicitConversionSequence::Worse;
3804
3805 // The following checks require both conversion sequences to be of
3806 // the same kind.
3807 if (ICS1.getKind() != ICS2.getKind())
3808 return ImplicitConversionSequence::Indistinguishable;
3809
3810 ImplicitConversionSequence::CompareKind Result =
3811 ImplicitConversionSequence::Indistinguishable;
3812
3813 // Two implicit conversion sequences of the same form are
3814 // indistinguishable conversion sequences unless one of the
3815 // following rules apply: (C++ 13.3.3.2p3):
3816
3817 // List-initialization sequence L1 is a better conversion sequence than
3818 // list-initialization sequence L2 if:
3819 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3820 // if not that,
3821 // — L1 and L2 convert to arrays of the same element type, and either the
3822 // number of elements n_1 initialized by L1 is less than the number of
3823 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3824 // an array of unknown bound and L1 does not,
3825 // even if one of the other rules in this paragraph would otherwise apply.
3826 if (!ICS1.isBad()) {
3827 bool StdInit1 = false, StdInit2 = false;
3828 if (ICS1.hasInitializerListContainerType())
3829 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3830 nullptr);
3831 if (ICS2.hasInitializerListContainerType())
3832 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3833 nullptr);
3834 if (StdInit1 != StdInit2)
3835 return StdInit1 ? ImplicitConversionSequence::Better
3836 : ImplicitConversionSequence::Worse;
3837
3838 if (ICS1.hasInitializerListContainerType() &&
3839 ICS2.hasInitializerListContainerType())
3840 if (auto *CAT1 = S.Context.getAsConstantArrayType(
3841 ICS1.getInitializerListContainerType()))
3842 if (auto *CAT2 = S.Context.getAsConstantArrayType(
3843 ICS2.getInitializerListContainerType())) {
3844 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3845 CAT2->getElementType())) {
3846 // Both to arrays of the same element type
3847 if (CAT1->getSize() != CAT2->getSize())
3848 // Different sized, the smaller wins
3849 return CAT1->getSize().ult(CAT2->getSize())
3850 ? ImplicitConversionSequence::Better
3851 : ImplicitConversionSequence::Worse;
3852 if (ICS1.isInitializerListOfIncompleteArray() !=
3853 ICS2.isInitializerListOfIncompleteArray())
3854 // One is incomplete, it loses
3855 return ICS2.isInitializerListOfIncompleteArray()
3856 ? ImplicitConversionSequence::Better
3857 : ImplicitConversionSequence::Worse;
3858 }
3859 }
3860 }
3861
3862 if (ICS1.isStandard())
3863 // Standard conversion sequence S1 is a better conversion sequence than
3864 // standard conversion sequence S2 if [...]
3865 Result = CompareStandardConversionSequences(S, Loc,
3866 ICS1.Standard, ICS2.Standard);
3867 else if (ICS1.isUserDefined()) {
3868 // User-defined conversion sequence U1 is a better conversion
3869 // sequence than another user-defined conversion sequence U2 if
3870 // they contain the same user-defined conversion function or
3871 // constructor and if the second standard conversion sequence of
3872 // U1 is better than the second standard conversion sequence of
3873 // U2 (C++ 13.3.3.2p3).
3874 if (ICS1.UserDefined.ConversionFunction ==
3875 ICS2.UserDefined.ConversionFunction)
3876 Result = CompareStandardConversionSequences(S, Loc,
3877 ICS1.UserDefined.After,
3878 ICS2.UserDefined.After);
3879 else
3880 Result = compareConversionFunctions(S,
3881 ICS1.UserDefined.ConversionFunction,
3882 ICS2.UserDefined.ConversionFunction);
3883 }
3884
3885 return Result;
3886}
3887
3888// Per 13.3.3.2p3, compare the given standard conversion sequences to
3889// determine if one is a proper subset of the other.
3890static ImplicitConversionSequence::CompareKind
3891compareStandardConversionSubsets(ASTContext &Context,
3892 const StandardConversionSequence& SCS1,
3893 const StandardConversionSequence& SCS2) {
3894 ImplicitConversionSequence::CompareKind Result
3895 = ImplicitConversionSequence::Indistinguishable;
3896
3897 // the identity conversion sequence is considered to be a subsequence of
3898 // any non-identity conversion sequence
3899 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3900 return ImplicitConversionSequence::Better;
3901 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3902 return ImplicitConversionSequence::Worse;
3903
3904 if (SCS1.Second != SCS2.Second) {
3905 if (SCS1.Second == ICK_Identity)
3906 Result = ImplicitConversionSequence::Better;
3907 else if (SCS2.Second == ICK_Identity)
3908 Result = ImplicitConversionSequence::Worse;
3909 else
3910 return ImplicitConversionSequence::Indistinguishable;
3911 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3912 return ImplicitConversionSequence::Indistinguishable;
3913
3914 if (SCS1.Third == SCS2.Third) {
3915 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3916 : ImplicitConversionSequence::Indistinguishable;
3917 }
3918
3919 if (SCS1.Third == ICK_Identity)
3920 return Result == ImplicitConversionSequence::Worse
3921 ? ImplicitConversionSequence::Indistinguishable
3922 : ImplicitConversionSequence::Better;
3923
3924 if (SCS2.Third == ICK_Identity)
3925 return Result == ImplicitConversionSequence::Better
3926 ? ImplicitConversionSequence::Indistinguishable
3927 : ImplicitConversionSequence::Worse;
3928
3929 return ImplicitConversionSequence::Indistinguishable;
3930}
3931
3932/// Determine whether one of the given reference bindings is better
3933/// than the other based on what kind of bindings they are.
3934static bool
3935isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3936 const StandardConversionSequence &SCS2) {
3937 // C++0x [over.ics.rank]p3b4:
3938 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3939 // implicit object parameter of a non-static member function declared
3940 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3941 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3942 // lvalue reference to a function lvalue and S2 binds an rvalue
3943 // reference*.
3944 //
3945 // FIXME: Rvalue references. We're going rogue with the above edits,
3946 // because the semantics in the current C++0x working paper (N3225 at the
3947 // time of this writing) break the standard definition of std::forward
3948 // and std::reference_wrapper when dealing with references to functions.
3949 // Proposed wording changes submitted to CWG for consideration.
3950 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3951 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3952 return false;
3953
3954 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3955 SCS2.IsLvalueReference) ||
3956 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3957 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3958}
3959
3960enum class FixedEnumPromotion {
3961 None,
3962 ToUnderlyingType,
3963 ToPromotedUnderlyingType
3964};
3965
3966/// Returns kind of fixed enum promotion the \a SCS uses.
3967static FixedEnumPromotion
3968getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3969
3970 if (SCS.Second != ICK_Integral_Promotion)
3971 return FixedEnumPromotion::None;
3972
3973 QualType FromType = SCS.getFromType();
3974 if (!FromType->isEnumeralType())
3975 return FixedEnumPromotion::None;
3976
3977 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3978 if (!Enum->isFixed())
3979 return FixedEnumPromotion::None;
3980
3981 QualType UnderlyingType = Enum->getIntegerType();
3982 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3983 return FixedEnumPromotion::ToUnderlyingType;
3984
3985 return FixedEnumPromotion::ToPromotedUnderlyingType;
3986}
3987
3988/// CompareStandardConversionSequences - Compare two standard
3989/// conversion sequences to determine whether one is better than the
3990/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3991static ImplicitConversionSequence::CompareKind
3992CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3993 const StandardConversionSequence& SCS1,
3994 const StandardConversionSequence& SCS2)
3995{
3996 // Standard conversion sequence S1 is a better conversion sequence
3997 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3998
3999 // -- S1 is a proper subsequence of S2 (comparing the conversion
4000 // sequences in the canonical form defined by 13.3.3.1.1,
4001 // excluding any Lvalue Transformation; the identity conversion
4002 // sequence is considered to be a subsequence of any
4003 // non-identity conversion sequence) or, if not that,
4004 if (ImplicitConversionSequence::CompareKind CK
4005 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4006 return CK;
4007
4008 // -- the rank of S1 is better than the rank of S2 (by the rules
4009 // defined below), or, if not that,
4010 ImplicitConversionRank Rank1 = SCS1.getRank();
4011 ImplicitConversionRank Rank2 = SCS2.getRank();
4012 if (Rank1 < Rank2)
4013 return ImplicitConversionSequence::Better;
4014 else if (Rank2 < Rank1)
4015 return ImplicitConversionSequence::Worse;
4016
4017 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4018 // are indistinguishable unless one of the following rules
4019 // applies:
4020
4021 // A conversion that is not a conversion of a pointer, or
4022 // pointer to member, to bool is better than another conversion
4023 // that is such a conversion.
4024 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4025 return SCS2.isPointerConversionToBool()
4026 ? ImplicitConversionSequence::Better
4027 : ImplicitConversionSequence::Worse;
4028
4029 // C++14 [over.ics.rank]p4b2:
4030 // This is retroactively applied to C++11 by CWG 1601.
4031 //
4032 // A conversion that promotes an enumeration whose underlying type is fixed
4033 // to its underlying type is better than one that promotes to the promoted
4034 // underlying type, if the two are different.
4035 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4036 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4037 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4038 FEP1 != FEP2)
4039 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4040 ? ImplicitConversionSequence::Better
4041 : ImplicitConversionSequence::Worse;
4042
4043 // C++ [over.ics.rank]p4b2:
4044 //
4045 // If class B is derived directly or indirectly from class A,
4046 // conversion of B* to A* is better than conversion of B* to
4047 // void*, and conversion of A* to void* is better than conversion
4048 // of B* to void*.
4049 bool SCS1ConvertsToVoid
4050 = SCS1.isPointerConversionToVoidPointer(S.Context);
4051 bool SCS2ConvertsToVoid
4052 = SCS2.isPointerConversionToVoidPointer(S.Context);
4053 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4054 // Exactly one of the conversion sequences is a conversion to
4055 // a void pointer; it's the worse conversion.
4056 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4057 : ImplicitConversionSequence::Worse;
4058 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4059 // Neither conversion sequence converts to a void pointer; compare
4060 // their derived-to-base conversions.
4061 if (ImplicitConversionSequence::CompareKind DerivedCK
4062 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4063 return DerivedCK;
4064 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4065 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4066 // Both conversion sequences are conversions to void
4067 // pointers. Compare the source types to determine if there's an
4068 // inheritance relationship in their sources.
4069 QualType FromType1 = SCS1.getFromType();
4070 QualType FromType2 = SCS2.getFromType();
4071
4072 // Adjust the types we're converting from via the array-to-pointer
4073 // conversion, if we need to.
4074 if (SCS1.First == ICK_Array_To_Pointer)
4075 FromType1 = S.Context.getArrayDecayedType(FromType1);
4076 if (SCS2.First == ICK_Array_To_Pointer)
4077 FromType2 = S.Context.getArrayDecayedType(FromType2);
4078
4079 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4080 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4081
4082 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4083 return ImplicitConversionSequence::Better;
4084 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4085 return ImplicitConversionSequence::Worse;
4086
4087 // Objective-C++: If one interface is more specific than the
4088 // other, it is the better one.
4089 const ObjCObjectPointerType* FromObjCPtr1
4090 = FromType1->getAs<ObjCObjectPointerType>();
4091 const ObjCObjectPointerType* FromObjCPtr2
4092 = FromType2->getAs<ObjCObjectPointerType>();
4093 if (FromObjCPtr1 && FromObjCPtr2) {
4094 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4095 FromObjCPtr2);
4096 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4097 FromObjCPtr1);
4098 if (AssignLeft != AssignRight) {
4099 return AssignLeft? ImplicitConversionSequence::Better
4100 : ImplicitConversionSequence::Worse;
4101 }
4102 }
4103 }
4104
4105 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4106 // Check for a better reference binding based on the kind of bindings.
4107 if (isBetterReferenceBindingKind(SCS1, SCS2))
4108 return ImplicitConversionSequence::Better;
4109 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4110 return ImplicitConversionSequence::Worse;
4111 }
4112
4113 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4114 // bullet 3).
4115 if (ImplicitConversionSequence::CompareKind QualCK
4116 = CompareQualificationConversions(S, SCS1, SCS2))
4117 return QualCK;
4118
4119 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4120 // C++ [over.ics.rank]p3b4:
4121 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4122 // which the references refer are the same type except for
4123 // top-level cv-qualifiers, and the type to which the reference
4124 // initialized by S2 refers is more cv-qualified than the type
4125 // to which the reference initialized by S1 refers.
4126 QualType T1 = SCS1.getToType(2);
4127 QualType T2 = SCS2.getToType(2);
4128 T1 = S.Context.getCanonicalType(T1);
4129 T2 = S.Context.getCanonicalType(T2);
4130 Qualifiers T1Quals, T2Quals;
4131 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4132 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4133 if (UnqualT1 == UnqualT2) {
4134 // Objective-C++ ARC: If the references refer to objects with different
4135 // lifetimes, prefer bindings that don't change lifetime.
4136 if (SCS1.ObjCLifetimeConversionBinding !=
4137 SCS2.ObjCLifetimeConversionBinding) {
4138 return SCS1.ObjCLifetimeConversionBinding
4139 ? ImplicitConversionSequence::Worse
4140 : ImplicitConversionSequence::Better;
4141 }
4142
4143 // If the type is an array type, promote the element qualifiers to the
4144 // type for comparison.
4145 if (isa<ArrayType>(T1) && T1Quals)
4146 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4147 if (isa<ArrayType>(T2) && T2Quals)
4148 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4149 if (T2.isMoreQualifiedThan(T1))
4150 return ImplicitConversionSequence::Better;
4151 if (T1.isMoreQualifiedThan(T2))
4152 return ImplicitConversionSequence::Worse;
4153 }
4154 }
4155
4156 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4157 // floating-to-integral conversion if the integral conversion
4158 // is between types of the same size.
4159 // For example:
4160 // void f(float);
4161 // void f(int);
4162 // int main {
4163 // long a;
4164 // f(a);
4165 // }
4166 // Here, MSVC will call f(int) instead of generating a compile error
4167 // as clang will do in standard mode.
4168 if (S.getLangOpts().MSVCCompat &&
4169 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4170 SCS1.Second == ICK_Integral_Conversion &&
4171 SCS2.Second == ICK_Floating_Integral &&
4172 S.Context.getTypeSize(SCS1.getFromType()) ==
4173 S.Context.getTypeSize(SCS1.getToType(2)))
4174 return ImplicitConversionSequence::Better;
4175
4176 // Prefer a compatible vector conversion over a lax vector conversion
4177 // For example:
4178 //
4179 // typedef float __v4sf __attribute__((__vector_size__(16)));
4180 // void f(vector float);
4181 // void f(vector signed int);
4182 // int main() {
4183 // __v4sf a;
4184 // f(a);
4185 // }
4186 // Here, we'd like to choose f(vector float) and not
4187 // report an ambiguous call error
4188 if (SCS1.Second == ICK_Vector_Conversion &&
4189 SCS2.Second == ICK_Vector_Conversion) {
4190 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4191 SCS1.getFromType(), SCS1.getToType(2));
4192 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4193 SCS2.getFromType(), SCS2.getToType(2));
4194
4195 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4196 return SCS1IsCompatibleVectorConversion
4197 ? ImplicitConversionSequence::Better
4198 : ImplicitConversionSequence::Worse;
4199 }
4200
4201 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4202 SCS2.Second == ICK_SVE_Vector_Conversion) {
4203 bool SCS1IsCompatibleSVEVectorConversion =
4204 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4205 bool SCS2IsCompatibleSVEVectorConversion =
4206 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4207
4208 if (SCS1IsCompatibleSVEVectorConversion !=
4209 SCS2IsCompatibleSVEVectorConversion)
4210 return SCS1IsCompatibleSVEVectorConversion
4211 ? ImplicitConversionSequence::Better
4212 : ImplicitConversionSequence::Worse;
4213 }
4214
4215 return ImplicitConversionSequence::Indistinguishable;
4216}
4217
4218/// CompareQualificationConversions - Compares two standard conversion
4219/// sequences to determine whether they can be ranked based on their
4220/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4221static ImplicitConversionSequence::CompareKind
4222CompareQualificationConversions(Sema &S,
4223 const StandardConversionSequence& SCS1,
4224 const StandardConversionSequence& SCS2) {
4225 // C++ [over.ics.rank]p3:
4226 // -- S1 and S2 differ only in their qualification conversion and
4227 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4228 // [C++98]
4229 // [...] and the cv-qualification signature of type T1 is a proper subset
4230 // of the cv-qualification signature of type T2, and S1 is not the
4231 // deprecated string literal array-to-pointer conversion (4.2).
4232 // [C++2a]
4233 // [...] where T1 can be converted to T2 by a qualification conversion.
4234 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4235 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4236 return ImplicitConversionSequence::Indistinguishable;
4237
4238 // FIXME: the example in the standard doesn't use a qualification
4239 // conversion (!)
4240 QualType T1 = SCS1.getToType(2);
4241 QualType T2 = SCS2.getToType(2);
4242 T1 = S.Context.getCanonicalType(T1);
4243 T2 = S.Context.getCanonicalType(T2);
4244 assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() &&
!T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "clang/lib/Sema/SemaOverload.cpp", 4244, __extension__ __PRETTY_FUNCTION__
))
;
4245 Qualifiers T1Quals, T2Quals;
4246 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4247 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4248
4249 // If the types are the same, we won't learn anything by unwrapping
4250 // them.
4251 if (UnqualT1 == UnqualT2)
4252 return ImplicitConversionSequence::Indistinguishable;
4253
4254 // Don't ever prefer a standard conversion sequence that uses the deprecated
4255 // string literal array to pointer conversion.
4256 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4257 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4258
4259 // Objective-C++ ARC:
4260 // Prefer qualification conversions not involving a change in lifetime
4261 // to qualification conversions that do change lifetime.
4262 if (SCS1.QualificationIncludesObjCLifetime &&
4263 !SCS2.QualificationIncludesObjCLifetime)
4264 CanPick1 = false;
4265 if (SCS2.QualificationIncludesObjCLifetime &&
4266 !SCS1.QualificationIncludesObjCLifetime)
4267 CanPick2 = false;
4268
4269 bool ObjCLifetimeConversion;
4270 if (CanPick1 &&
4271 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4272 CanPick1 = false;
4273 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4274 // directions, so we can't short-cut this second check in general.
4275 if (CanPick2 &&
4276 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4277 CanPick2 = false;
4278
4279 if (CanPick1 != CanPick2)
4280 return CanPick1 ? ImplicitConversionSequence::Better
4281 : ImplicitConversionSequence::Worse;
4282 return ImplicitConversionSequence::Indistinguishable;
4283}
4284
4285/// CompareDerivedToBaseConversions - Compares two standard conversion
4286/// sequences to determine whether they can be ranked based on their
4287/// various kinds of derived-to-base conversions (C++
4288/// [over.ics.rank]p4b3). As part of these checks, we also look at
4289/// conversions between Objective-C interface types.
4290static ImplicitConversionSequence::CompareKind
4291CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4292 const StandardConversionSequence& SCS1,
4293 const StandardConversionSequence& SCS2) {
4294 QualType FromType1 = SCS1.getFromType();
4295 QualType ToType1 = SCS1.getToType(1);
4296 QualType FromType2 = SCS2.getFromType();
4297 QualType ToType2 = SCS2.getToType(1);
4298
4299 // Adjust the types we're converting from via the array-to-pointer
4300 // conversion, if we need to.
4301 if (SCS1.First == ICK_Array_To_Pointer)
4302 FromType1 = S.Context.getArrayDecayedType(FromType1);
4303 if (SCS2.First == ICK_Array_To_Pointer)
4304 FromType2 = S.Context.getArrayDecayedType(FromType2);
4305
4306 // Canonicalize all of the types.
4307 FromType1 = S.Context.getCanonicalType(FromType1);
4308 ToType1 = S.Context.getCanonicalType(ToType1);
4309 FromType2 = S.Context.getCanonicalType(FromType2);
4310 ToType2 = S.Context.getCanonicalType(ToType2);
4311
4312 // C++ [over.ics.rank]p4b3:
4313 //
4314 // If class B is derived directly or indirectly from class A and
4315 // class C is derived directly or indirectly from B,
4316 //
4317 // Compare based on pointer conversions.
4318 if (SCS1.Second == ICK_Pointer_Conversion &&
4319 SCS2.Second == ICK_Pointer_Conversion &&
4320 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4321 FromType1->isPointerType() && FromType2->isPointerType() &&
4322 ToType1->isPointerType() && ToType2->isPointerType()) {
4323 QualType FromPointee1 =
4324 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325 QualType ToPointee1 =
4326 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4327 QualType FromPointee2 =
4328 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4329 QualType ToPointee2 =
4330 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4331
4332 // -- conversion of C* to B* is better than conversion of C* to A*,
4333 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4334 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4335 return ImplicitConversionSequence::Better;
4336 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4337 return ImplicitConversionSequence::Worse;
4338 }
4339
4340 // -- conversion of B* to A* is better than conversion of C* to A*,
4341 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4342 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4343 return ImplicitConversionSequence::Better;
4344 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4345 return ImplicitConversionSequence::Worse;
4346 }
4347 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4348 SCS2.Second == ICK_Pointer_Conversion) {
4349 const ObjCObjectPointerType *FromPtr1
4350 = FromType1->getAs<ObjCObjectPointerType>();
4351 const ObjCObjectPointerType *FromPtr2
4352 = FromType2->getAs<ObjCObjectPointerType>();
4353 const ObjCObjectPointerType *ToPtr1
4354 = ToType1->getAs<ObjCObjectPointerType>();
4355 const ObjCObjectPointerType *ToPtr2
4356 = ToType2->getAs<ObjCObjectPointerType>();
4357
4358 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4359 // Apply the same conversion ranking rules for Objective-C pointer types
4360 // that we do for C++ pointers to class types. However, we employ the
4361 // Objective-C pseudo-subtyping relationship used for assignment of
4362 // Objective-C pointer types.
4363 bool FromAssignLeft
4364 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4365 bool FromAssignRight
4366 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4367 bool ToAssignLeft
4368 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4369 bool ToAssignRight
4370 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4371
4372 // A conversion to an a non-id object pointer type or qualified 'id'
4373 // type is better than a conversion to 'id'.
4374 if (ToPtr1->isObjCIdType() &&
4375 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4376 return ImplicitConversionSequence::Worse;
4377 if (ToPtr2->isObjCIdType() &&
4378 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4379 return ImplicitConversionSequence::Better;
4380
4381 // A conversion to a non-id object pointer type is better than a
4382 // conversion to a qualified 'id' type
4383 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4384 return ImplicitConversionSequence::Worse;
4385 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4386 return ImplicitConversionSequence::Better;
4387
4388 // A conversion to an a non-Class object pointer type or qualified 'Class'
4389 // type is better than a conversion to 'Class'.
4390 if (ToPtr1->isObjCClassType() &&
4391 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4392 return ImplicitConversionSequence::Worse;
4393 if (ToPtr2->isObjCClassType() &&
4394 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4395 return ImplicitConversionSequence::Better;
4396
4397 // A conversion to a non-Class object pointer type is better than a
4398 // conversion to a qualified 'Class' type.
4399 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4400 return ImplicitConversionSequence::Worse;
4401 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4402 return ImplicitConversionSequence::Better;
4403
4404 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4405 if (S.Context.hasSameType(FromType1, FromType2) &&
4406 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4407 (ToAssignLeft != ToAssignRight)) {
4408 if (FromPtr1->isSpecialized()) {
4409 // "conversion of B<A> * to B * is better than conversion of B * to
4410 // C *.
4411 bool IsFirstSame =
4412 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4413 bool IsSecondSame =
4414 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4415 if (IsFirstSame) {
4416 if (!IsSecondSame)
4417 return ImplicitConversionSequence::Better;
4418 } else if (IsSecondSame)
4419 return ImplicitConversionSequence::Worse;
4420 }
4421 return ToAssignLeft? ImplicitConversionSequence::Worse
4422 : ImplicitConversionSequence::Better;
4423 }
4424
4425 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4426 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4427 (FromAssignLeft != FromAssignRight))
4428 return FromAssignLeft? ImplicitConversionSequence::Better
4429 : ImplicitConversionSequence::Worse;
4430 }
4431 }
4432
4433 // Ranking of member-pointer types.
4434 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4435 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4436 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4437 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4438 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4439 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4440 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4441 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4442 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4443 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4444 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4445 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4446 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4447 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4448 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4449 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4450 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4451 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4452 return ImplicitConversionSequence::Worse;
4453 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4454 return ImplicitConversionSequence::Better;
4455 }
4456 // conversion of B::* to C::* is better than conversion of A::* to C::*
4457 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4458 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4459 return ImplicitConversionSequence::Better;
4460 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4461 return ImplicitConversionSequence::Worse;
4462 }
4463 }
4464
4465 if (SCS1.Second == ICK_Derived_To_Base) {
4466 // -- conversion of C to B is better than conversion of C to A,
4467 // -- binding of an expression of type C to a reference of type
4468 // B& is better than binding an expression of type C to a
4469 // reference of type A&,
4470 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4471 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4472 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4473 return ImplicitConversionSequence::Better;
4474 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4475 return ImplicitConversionSequence::Worse;
4476 }
4477
4478 // -- conversion of B to A is better than conversion of C to A.
4479 // -- binding of an expression of type B to a reference of type
4480 // A& is better than binding an expression of type C to a
4481 // reference of type A&,
4482 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4483 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4484 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4485 return ImplicitConversionSequence::Better;
4486 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4487 return ImplicitConversionSequence::Worse;
4488 }
4489 }
4490
4491 return ImplicitConversionSequence::Indistinguishable;
4492}
4493
4494/// Determine whether the given type is valid, e.g., it is not an invalid
4495/// C++ class.
4496static bool isTypeValid(QualType T) {
4497 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4498 return !Record->isInvalidDecl();
4499
4500 return true;
4501}
4502
4503static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4504 if (!T.getQualifiers().hasUnaligned())
4505 return T;
4506
4507 Qualifiers Q;
4508 T = Ctx.getUnqualifiedArrayType(T, Q);
4509 Q.removeUnaligned();
4510 return Ctx.getQualifiedType(T, Q);
4511}
4512
4513/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4514/// determine whether they are reference-compatible,
4515/// reference-related, or incompatible, for use in C++ initialization by
4516/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4517/// type, and the first type (T1) is the pointee type of the reference
4518/// type being initialized.
4519Sema::ReferenceCompareResult
4520Sema::CompareReferenceRelationship(SourceLocation Loc,
4521 QualType OrigT1, QualType OrigT2,
4522 ReferenceConversions *ConvOut) {
4523 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4524, __extension__ __PRETTY_FUNCTION__
))
4524 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4524, __extension__ __PRETTY_FUNCTION__
))
;
4525 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4525, __extension__ __PRETTY_FUNCTION__
))
;
4526
4527 QualType T1 = Context.getCanonicalType(OrigT1);
4528 QualType T2 = Context.getCanonicalType(OrigT2);
4529 Qualifiers T1Quals, T2Quals;
4530 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4531 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4532
4533 ReferenceConversions ConvTmp;
4534 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4535 Conv = ReferenceConversions();
4536
4537 // C++2a [dcl.init.ref]p4:
4538 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4539 // reference-related to "cv2 T2" if T1 is similar to T2, or
4540 // T1 is a base class of T2.
4541 // "cv1 T1" is reference-compatible with "cv2 T2" if
4542 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4543 // "pointer to cv1 T1" via a standard conversion sequence.
4544
4545 // Check for standard conversions we can apply to pointers: derived-to-base
4546 // conversions, ObjC pointer conversions, and function pointer conversions.
4547 // (Qualification conversions are checked last.)
4548 QualType ConvertedT2;
4549 if (UnqualT1 == UnqualT2) {
4550 // Nothing to do.
4551 } else if (isCompleteType(Loc, OrigT2) &&
4552 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4553 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4554 Conv |= ReferenceConversions::DerivedToBase;
4555 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4556 UnqualT2->isObjCObjectOrInterfaceType() &&
4557 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4558 Conv |= ReferenceConversions::ObjC;
4559 else if (UnqualT2->isFunctionType() &&
4560 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4561 Conv |= ReferenceConversions::Function;
4562 // No need to check qualifiers; function types don't have them.
4563 return Ref_Compatible;
4564 }
4565 bool ConvertedReferent = Conv != 0;
4566
4567 // We can have a qualification conversion. Compute whether the types are
4568 // similar at the same time.
4569 bool PreviousToQualsIncludeConst = true;
4570 bool TopLevel = true;
4571 do {
4572 if (T1 == T2)
4573 break;
4574
4575 // We will need a qualification conversion.
4576 Conv |= ReferenceConversions::Qualification;
4577
4578 // Track whether we performed a qualification conversion anywhere other
4579 // than the top level. This matters for ranking reference bindings in
4580 // overload resolution.
4581 if (!TopLevel)
4582 Conv |= ReferenceConversions::NestedQualification;
4583
4584 // MS compiler ignores __unaligned qualifier for references; do the same.
4585 T1 = withoutUnaligned(Context, T1);
4586 T2 = withoutUnaligned(Context, T2);
4587
4588 // If we find a qualifier mismatch, the types are not reference-compatible,
4589 // but are still be reference-related if they're similar.
4590 bool ObjCLifetimeConversion = false;
4591 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4592 PreviousToQualsIncludeConst,
4593 ObjCLifetimeConversion))
4594 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4595 ? Ref_Related
4596 : Ref_Incompatible;
4597
4598 // FIXME: Should we track this for any level other than the first?
4599 if (ObjCLifetimeConversion)
4600 Conv |= ReferenceConversions::ObjCLifetime;
4601
4602 TopLevel = false;
4603 } while (Context.UnwrapSimilarTypes(T1, T2));
4604
4605 // At this point, if the types are reference-related, we must either have the
4606 // same inner type (ignoring qualifiers), or must have already worked out how
4607 // to convert the referent.
4608 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4609 ? Ref_Compatible
4610 : Ref_Incompatible;
4611}
4612
4613/// Look for a user-defined conversion to a value reference-compatible
4614/// with DeclType. Return true if something definite is found.
4615static bool
4616FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4617 QualType DeclType, SourceLocation DeclLoc,
4618 Expr *Init, QualType T2, bool AllowRvalues,
4619 bool AllowExplicit) {
4620 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "clang/lib/Sema/SemaOverload.cpp", 4620, __extension__ __PRETTY_FUNCTION__
))
;
4621 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4622
4623 OverloadCandidateSet CandidateSet(
4624 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4625 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4626 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4627 NamedDecl *D = *I;
4628 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4629 if (isa<UsingShadowDecl>(D))
4630 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4631
4632 FunctionTemplateDecl *ConvTemplate
4633 = dyn_cast<FunctionTemplateDecl>(D);
4634 CXXConversionDecl *Conv;
4635 if (ConvTemplate)
4636 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4637 else
4638 Conv = cast<CXXConversionDecl>(D);
4639
4640 if (AllowRvalues) {
4641 // If we are initializing an rvalue reference, don't permit conversion
4642 // functions that return lvalues.
4643 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4644 const ReferenceType *RefType
4645 = Conv->getConversionType()->getAs<LValueReferenceType>();
4646 if (RefType && !RefType->getPointeeType()->isFunctionType())
4647 continue;
4648 }
4649
4650 if (!ConvTemplate &&
4651 S.CompareReferenceRelationship(
4652 DeclLoc,
4653 Conv->getConversionType()
4654 .getNonReferenceType()
4655 .getUnqualifiedType(),
4656 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4657 Sema::Ref_Incompatible)
4658 continue;
4659 } else {
4660 // If the conversion function doesn't return a reference type,
4661 // it can't be considered for this conversion. An rvalue reference
4662 // is only acceptable if its referencee is a function type.
4663
4664 const ReferenceType *RefType =
4665 Conv->getConversionType()->getAs<ReferenceType>();
4666 if (!RefType ||
4667 (!RefType->isLValueReferenceType() &&
4668 !RefType->getPointeeType()->isFunctionType()))
4669 continue;
4670 }
4671
4672 if (ConvTemplate)
4673 S.AddTemplateConversionCandidate(
4674 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4675 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4676 else
4677 S.AddConversionCandidate(
4678 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4679 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4680 }
4681
4682 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4683
4684 OverloadCandidateSet::iterator Best;
4685 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4686 case OR_Success:
4687 // C++ [over.ics.ref]p1:
4688 //
4689 // [...] If the parameter binds directly to the result of
4690 // applying a conversion function to the argument
4691 // expression, the implicit conversion sequence is a
4692 // user-defined conversion sequence (13.3.3.1.2), with the
4693 // second standard conversion sequence either an identity
4694 // conversion or, if the conversion function returns an
4695 // entity of a type that is a derived class of the parameter
4696 // type, a derived-to-base Conversion.
4697 if (!Best->FinalConversion.DirectBinding)
4698 return false;
4699
4700 ICS.setUserDefined();
4701 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4702 ICS.UserDefined.After = Best->FinalConversion;
4703 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4704 ICS.UserDefined.ConversionFunction = Best->Function;
4705 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4706 ICS.UserDefined.EllipsisConversion = false;
4707 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4709, __extension__ __PRETTY_FUNCTION__
))
4708 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4709, __extension__ __PRETTY_FUNCTION__
))
4709 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4709, __extension__ __PRETTY_FUNCTION__
))
;
4710 return true;
4711
4712 case OR_Ambiguous:
4713 ICS.setAmbiguous();
4714 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4715 Cand != CandidateSet.end(); ++Cand)
4716 if (Cand->Best)
4717 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4718 return true;
4719
4720 case OR_No_Viable_Function:
4721 case OR_Deleted:
4722 // There was no suitable conversion, or we found a deleted
4723 // conversion; continue with other checks.
4724 return false;
4725 }
4726
4727 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 4727)
;
4728}
4729
4730/// Compute an implicit conversion sequence for reference
4731/// initialization.
4732static ImplicitConversionSequence
4733TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4734 SourceLocation DeclLoc,
4735 bool SuppressUserConversions,
4736 bool AllowExplicit) {
4737 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "clang/lib/Sema/SemaOverload.cpp", 4737, __extension__ __PRETTY_FUNCTION__
))
;
4738
4739 // Most paths end in a failed conversion.
4740 ImplicitConversionSequence ICS;
4741 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4742
4743 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4744 QualType T2 = Init->getType();
4745
4746 // If the initializer is the address of an overloaded function, try
4747 // to resolve the overloaded function. If all goes well, T2 is the
4748 // type of the resulting function.
4749 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4750 DeclAccessPair Found;
4751 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4752 false, Found))
4753 T2 = Fn->getType();
4754 }
4755
4756 // Compute some basic properties of the types and the initializer.
4757 bool isRValRef = DeclType->isRValueReferenceType();
4758 Expr::Classification InitCategory = Init->Classify(S.Context);
4759
4760 Sema::ReferenceConversions RefConv;
4761 Sema::ReferenceCompareResult RefRelationship =
4762 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4763
4764 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4765 ICS.setStandard();
4766 ICS.Standard.First = ICK_Identity;
4767 // FIXME: A reference binding can be a function conversion too. We should
4768 // consider that when ordering reference-to-function bindings.
4769 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4770 ? ICK_Derived_To_Base
4771 : (RefConv & Sema::ReferenceConversions::ObjC)
4772 ? ICK_Compatible_Conversion
4773 : ICK_Identity;
4774 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4775 // a reference binding that performs a non-top-level qualification
4776 // conversion as a qualification conversion, not as an identity conversion.
4777 ICS.Standard.Third = (RefConv &
4778 Sema::ReferenceConversions::NestedQualification)
4779 ? ICK_Qualification
4780 : ICK_Identity;
4781 ICS.Standard.setFromType(T2);
4782 ICS.Standard.setToType(0, T2);
4783 ICS.Standard.setToType(1, T1);
4784 ICS.Standard.setToType(2, T1);
4785 ICS.Standard.ReferenceBinding = true;
4786 ICS.Standard.DirectBinding = BindsDirectly;
4787 ICS.Standard.IsLvalueReference = !isRValRef;
4788 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4789 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4790 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4791 ICS.Standard.ObjCLifetimeConversionBinding =
4792 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4793 ICS.Standard.CopyConstructor = nullptr;
4794 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4795 };
4796
4797 // C++0x [dcl.init.ref]p5:
4798 // A reference to type "cv1 T1" is initialized by an expression
4799 // of type "cv2 T2" as follows:
4800
4801 // -- If reference is an lvalue reference and the initializer expression
4802 if (!isRValRef) {
4803 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4804 // reference-compatible with "cv2 T2," or
4805 //
4806 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4807 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4808 // C++ [over.ics.ref]p1:
4809 // When a parameter of reference type binds directly (8.5.3)
4810 // to an argument expression, the implicit conversion sequence
4811 // is the identity conversion, unless the argument expression
4812 // has a type that is a derived class of the parameter type,
4813 // in which case the implicit conversion sequence is a
4814 // derived-to-base Conversion (13.3.3.1).
4815 SetAsReferenceBinding(/*BindsDirectly=*/true);
4816
4817 // Nothing more to do: the inaccessibility/ambiguity check for
4818 // derived-to-base conversions is suppressed when we're
4819 // computing the implicit conversion sequence (C++
4820 // [over.best.ics]p2).
4821 return ICS;
4822 }
4823
4824 // -- has a class type (i.e., T2 is a class type), where T1 is
4825 // not reference-related to T2, and can be implicitly
4826 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4827 // is reference-compatible with "cv3 T3" 92) (this
4828 // conversion is selected by enumerating the applicable
4829 // conversion functions (13.3.1.6) and choosing the best
4830 // one through overload resolution (13.3)),
4831 if (!SuppressUserConversions && T2->isRecordType() &&
4832 S.isCompleteType(DeclLoc, T2) &&
4833 RefRelationship == Sema::Ref_Incompatible) {
4834 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4835 Init, T2, /*AllowRvalues=*/false,
4836 AllowExplicit))
4837 return ICS;
4838 }
4839 }
4840
4841 // -- Otherwise, the reference shall be an lvalue reference to a
4842 // non-volatile const type (i.e., cv1 shall be const), or the reference
4843 // shall be an rvalue reference.
4844 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4845 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4846 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4847 return ICS;
4848 }
4849
4850 // -- If the initializer expression
4851 //
4852 // -- is an xvalue, class prvalue, array prvalue or function
4853 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4854 if (RefRelationship == Sema::Ref_Compatible &&
4855 (InitCategory.isXValue() ||
4856 (InitCategory.isPRValue() &&
4857 (T2->isRecordType() || T2->isArrayType())) ||
4858 (InitCategory.isLValue() && T2->isFunctionType()))) {
4859 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4860 // binding unless we're binding to a class prvalue.
4861 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4862 // allow the use of rvalue references in C++98/03 for the benefit of
4863 // standard library implementors; therefore, we need the xvalue check here.
4864 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4865 !(InitCategory.isPRValue() || T2->isRecordType()));
4866 return ICS;
4867 }
4868
4869 // -- has a class type (i.e., T2 is a class type), where T1 is not
4870 // reference-related to T2, and can be implicitly converted to
4871 // an xvalue, class prvalue, or function lvalue of type
4872 // "cv3 T3", where "cv1 T1" is reference-compatible with
4873 // "cv3 T3",
4874 //
4875 // then the reference is bound to the value of the initializer
4876 // expression in the first case and to the result of the conversion
4877 // in the second case (or, in either case, to an appropriate base
4878 // class subobject).
4879 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4880 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4881 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4882 Init, T2, /*AllowRvalues=*/true,
4883 AllowExplicit)) {
4884 // In the second case, if the reference is an rvalue reference
4885 // and the second standard conversion sequence of the
4886 // user-defined conversion sequence includes an lvalue-to-rvalue
4887 // conversion, the program is ill-formed.
4888 if (ICS.isUserDefined() && isRValRef &&
4889 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4890 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4891
4892 return ICS;
4893 }
4894
4895 // A temporary of function type cannot be created; don't even try.
4896 if (T1->isFunctionType())
4897 return ICS;
4898
4899 // -- Otherwise, a temporary of type "cv1 T1" is created and
4900 // initialized from the initializer expression using the
4901 // rules for a non-reference copy initialization (8.5). The
4902 // reference is then bound to the temporary. If T1 is
4903 // reference-related to T2, cv1 must be the same
4904 // cv-qualification as, or greater cv-qualification than,
4905 // cv2; otherwise, the program is ill-formed.
4906 if (RefRelationship == Sema::Ref_Related) {
4907 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4908 // we would be reference-compatible or reference-compatible with
4909 // added qualification. But that wasn't the case, so the reference
4910 // initialization fails.
4911 //
4912 // Note that we only want to check address spaces and cvr-qualifiers here.
4913 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4914 Qualifiers T1Quals = T1.getQualifiers();
4915 Qualifiers T2Quals = T2.getQualifiers();
4916 T1Quals.removeObjCGCAttr();
4917 T1Quals.removeObjCLifetime();
4918 T2Quals.removeObjCGCAttr();
4919 T2Quals.removeObjCLifetime();
4920 // MS compiler ignores __unaligned qualifier for references; do the same.
4921 T1Quals.removeUnaligned();
4922 T2Quals.removeUnaligned();
4923 if (!T1Quals.compatiblyIncludes(T2Quals))
4924 return ICS;
4925 }
4926
4927 // If at least one of the types is a class type, the types are not
4928 // related, and we aren't allowed any user conversions, the
4929 // reference binding fails. This case is important for breaking
4930 // recursion, since TryImplicitConversion below will attempt to
4931 // create a temporary through the use of a copy constructor.
4932 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4933 (T1->isRecordType() || T2->isRecordType()))
4934 return ICS;
4935
4936 // If T1 is reference-related to T2 and the reference is an rvalue
4937 // reference, the initializer expression shall not be an lvalue.
4938 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4939 Init->Classify(S.Context).isLValue()) {
4940 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4941 return ICS;
4942 }
4943
4944 // C++ [over.ics.ref]p2:
4945 // When a parameter of reference type is not bound directly to
4946 // an argument expression, the conversion sequence is the one
4947 // required to convert the argument expression to the
4948 // underlying type of the reference according to
4949 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4950 // to copy-initializing a temporary of the underlying type with
4951 // the argument expression. Any difference in top-level
4952 // cv-qualification is subsumed by the initialization itself
4953 // and does not constitute a conversion.
4954 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4955 AllowedExplicit::None,
4956 /*InOverloadResolution=*/false,
4957 /*CStyle=*/false,
4958 /*AllowObjCWritebackConversion=*/false,
4959 /*AllowObjCConversionOnExplicit=*/false);
4960
4961 // Of course, that's still a reference binding.
4962 if (ICS.isStandard()) {
4963 ICS.Standard.ReferenceBinding = true;
4964 ICS.Standard.IsLvalueReference = !isRValRef;
4965 ICS.Standard.BindsToFunctionLvalue = false;
4966 ICS.Standard.BindsToRvalue = true;
4967 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4968 ICS.Standard.ObjCLifetimeConversionBinding = false;
4969 } else if (ICS.isUserDefined()) {
4970 const ReferenceType *LValRefType =
4971 ICS.UserDefined.ConversionFunction->getReturnType()
4972 ->getAs<LValueReferenceType>();
4973
4974 // C++ [over.ics.ref]p3:
4975 // Except for an implicit object parameter, for which see 13.3.1, a
4976 // standard conversion sequence cannot be formed if it requires [...]
4977 // binding an rvalue reference to an lvalue other than a function
4978 // lvalue.
4979 // Note that the function case is not possible here.
4980 if (isRValRef && LValRefType) {
4981 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4982 return ICS;
4983 }
4984
4985 ICS.UserDefined.After.ReferenceBinding = true;
4986 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4987 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4988 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4989 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4990 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4991 }
4992
4993 return ICS;
4994}
4995
4996static ImplicitConversionSequence
4997TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4998 bool SuppressUserConversions,
4999 bool InOverloadResolution,
5000 bool AllowObjCWritebackConversion,
5001 bool AllowExplicit = false);
5002
5003/// TryListConversion - Try to copy-initialize a value of type ToType from the
5004/// initializer list From.
5005static ImplicitConversionSequence
5006TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5007 bool SuppressUserConversions,
5008 bool InOverloadResolution,
5009 bool AllowObjCWritebackConversion) {
5010 // C++11 [over.ics.list]p1:
5011 // When an argument is an initializer list, it is not an expression and
5012 // special rules apply for converting it to a parameter type.
5013
5014 ImplicitConversionSequence Result;
5015 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5016
5017 // We need a complete type for what follows. With one C++20 exception,
5018 // incomplete types can never be initialized from init lists.
5019 QualType InitTy = ToType;
5020 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5021 if (AT && S.getLangOpts().CPlusPlus20)
5022 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5023 // C++20 allows list initialization of an incomplete array type.
5024 InitTy = IAT->getElementType();
5025 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5026 return Result;
5027
5028 // Per DR1467:
5029 // If the parameter type is a class X and the initializer list has a single
5030 // element of type cv U, where U is X or a class derived from X, the
5031 // implicit conversion sequence is the one required to convert the element
5032 // to the parameter type.
5033 //
5034 // Otherwise, if the parameter type is a character array [... ]
5035 // and the initializer list has a single element that is an
5036 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5037 // implicit conversion sequence is the identity conversion.
5038 if (From->getNumInits() == 1) {
5039 if (ToType->isRecordType()) {
5040 QualType InitType = From->getInit(0)->getType();
5041 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5042 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5043 return TryCopyInitialization(S, From->getInit(0), ToType,
5044 SuppressUserConversions,
5045 InOverloadResolution,
5046 AllowObjCWritebackConversion);
5047 }
5048
5049 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5050 InitializedEntity Entity =
5051 InitializedEntity::InitializeParameter(S.Context, ToType,
5052 /*Consumed=*/false);
5053 if (S.CanPerformCopyInitialization(Entity, From)) {
5054 Result.setStandard();
5055 Result.Standard.setAsIdentityConversion();
5056 Result.Standard.setFromType(ToType);
5057 Result.Standard.setAllToTypes(ToType);
5058 return Result;
5059 }
5060 }
5061 }
5062
5063 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5064 // C++11 [over.ics.list]p2:
5065 // If the parameter type is std::initializer_list<X> or "array of X" and
5066 // all the elements can be implicitly converted to X, the implicit
5067 // conversion sequence is the worst conversion necessary to convert an
5068 // element of the list to X.
5069 //
5070 // C++14 [over.ics.list]p3:
5071 // Otherwise, if the parameter type is "array of N X", if the initializer
5072 // list has exactly N elements or if it has fewer than N elements and X is
5073 // default-constructible, and if all the elements of the initializer list
5074 // can be implicitly converted to X, the implicit conversion sequence is
5075 // the worst conversion necessary to convert an element of the list to X.
5076 if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5077 unsigned e = From->getNumInits();
5078 ImplicitConversionSequence DfltElt;
5079 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5080 QualType());
5081 QualType ContTy = ToType;
5082 bool IsUnbounded = false;
5083 if (AT) {
5084 InitTy = AT->getElementType();
5085 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5086 if (CT->getSize().ult(e)) {
5087 // Too many inits, fatally bad
5088 Result.setBad(BadConversionSequence::too_many_initializers, From,
5089 ToType);
5090 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5091 return Result;
5092 }
5093 if (CT->getSize().ugt(e)) {
5094 // Need an init from empty {}, is there one?
5095 InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5096 From->getEndLoc());
5097 EmptyList.setType(S.Context.VoidTy);
5098 DfltElt = TryListConversion(
5099 S, &EmptyList, InitTy, SuppressUserConversions,
5100 InOverloadResolution, AllowObjCWritebackConversion);
5101 if (DfltElt.isBad()) {
5102 // No {} init, fatally bad
5103 Result.setBad(BadConversionSequence::too_few_initializers, From,
5104 ToType);
5105 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5106 return Result;
5107 }
5108 }
5109 } else {
5110 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT)
&& "Expected incomplete array") ? void (0) : __assert_fail
("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\""
, "clang/lib/Sema/SemaOverload.cpp", 5110, __extension__ __PRETTY_FUNCTION__
))
;
5111 IsUnbounded = true;
5112 if (!e) {
5113 // Cannot convert to zero-sized.
5114 Result.setBad(BadConversionSequence::too_few_initializers, From,
5115 ToType);
5116 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5117 return Result;
5118 }
5119 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5120 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5121 ArrayType::Normal, 0);
5122 }
5123 }
5124
5125 Result.setStandard();
5126 Result.Standard.setAsIdentityConversion();
5127 Result.Standard.setFromType(InitTy);
5128 Result.Standard.setAllToTypes(InitTy);
5129 for (unsigned i = 0; i < e; ++i) {
5130 Expr *Init = From->getInit(i);
5131 ImplicitConversionSequence ICS = TryCopyInitialization(
5132 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5133 AllowObjCWritebackConversion);
5134
5135 // Keep the worse conversion seen so far.
5136 // FIXME: Sequences are not totally ordered, so 'worse' can be
5137 // ambiguous. CWG has been informed.
5138 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5139 Result) ==
5140 ImplicitConversionSequence::Worse) {
5141 Result = ICS;
5142 // Bail as soon as we find something unconvertible.
5143 if (Result.isBad()) {
5144 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5145 return Result;
5146 }
5147 }
5148 }
5149
5150 // If we needed any implicit {} initialization, compare that now.
5151 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5152 // has been informed that this might not be the best thing.
5153 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5154 S, From->getEndLoc(), DfltElt, Result) ==
5155 ImplicitConversionSequence::Worse)
5156 Result = DfltElt;
5157 // Record the type being initialized so that we may compare sequences
5158 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5159 return Result;
5160 }
5161
5162 // C++14 [over.ics.list]p4:
5163 // C++11 [over.ics.list]p3:
5164 // Otherwise, if the parameter is a non-aggregate class X and overload
5165 // resolution chooses a single best constructor [...] the implicit
5166 // conversion sequence is a user-defined conversion sequence. If multiple
5167 // constructors are viable but none is better than the others, the
5168 // implicit conversion sequence is a user-defined conversion sequence.
5169 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5170 // This function can deal with initializer lists.
5171 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5172 AllowedExplicit::None,
5173 InOverloadResolution, /*CStyle=*/false,
5174 AllowObjCWritebackConversion,
5175 /*AllowObjCConversionOnExplicit=*/false);
5176 }
5177
5178 // C++14 [over.ics.list]p5:
5179 // C++11 [over.ics.list]p4:
5180 // Otherwise, if the parameter has an aggregate type which can be
5181 // initialized from the initializer list [...] the implicit conversion
5182 // sequence is a user-defined conversion sequence.
5183 if (ToType->isAggregateType()) {
5184 // Type is an aggregate, argument is an init list. At this point it comes
5185 // down to checking whether the initialization works.
5186 // FIXME: Find out whether this parameter is consumed or not.
5187 InitializedEntity Entity =
5188 InitializedEntity::InitializeParameter(S.Context, ToType,
5189 /*Consumed=*/false);
5190 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5191 From)) {
5192 Result.setUserDefined();
5193 Result.UserDefined.Before.setAsIdentityConversion();
5194 // Initializer lists don't have a type.
5195 Result.UserDefined.Before.setFromType(QualType());
5196 Result.UserDefined.Before.setAllToTypes(QualType());
5197
5198 Result.UserDefined.After.setAsIdentityConversion();
5199 Result.UserDefined.After.setFromType(ToType);
5200 Result.UserDefined.After.setAllToTypes(ToType);
5201 Result.UserDefined.ConversionFunction = nullptr;
5202 }
5203 return Result;
5204 }
5205
5206 // C++14 [over.ics.list]p6:
5207 // C++11 [over.ics.list]p5:
5208 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5209 if (ToType->isReferenceType()) {
5210 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5211 // mention initializer lists in any way. So we go by what list-
5212 // initialization would do and try to extrapolate from that.
5213
5214 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5215
5216 // If the initializer list has a single element that is reference-related
5217 // to the parameter type, we initialize the reference from that.
5218 if (From->getNumInits() == 1) {
5219 Expr *Init = From->getInit(0);
5220
5221 QualType T2 = Init->getType();
5222
5223 // If the initializer is the address of an overloaded function, try
5224 // to resolve the overloaded function. If all goes well, T2 is the
5225 // type of the resulting function.
5226 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5227 DeclAccessPair Found;
5228 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5229 Init, ToType, false, Found))
5230 T2 = Fn->getType();
5231 }
5232
5233 // Compute some basic properties of the types and the initializer.
5234 Sema::ReferenceCompareResult RefRelationship =
5235 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5236
5237 if (RefRelationship >= Sema::Ref_Related) {
5238 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5239 SuppressUserConversions,
5240 /*AllowExplicit=*/false);
5241 }
5242 }
5243
5244 // Otherwise, we bind the reference to a temporary created from the
5245 // initializer list.
5246 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5247 InOverloadResolution,
5248 AllowObjCWritebackConversion);
5249 if (Result.isFailure())
5250 return Result;
5251 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5252, __extension__ __PRETTY_FUNCTION__
))
5252 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5252, __extension__ __PRETTY_FUNCTION__
))
;
5253
5254 // Can we even bind to a temporary?
5255 if (ToType->isRValueReferenceType() ||
5256 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5257 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5258 Result.UserDefined.After;
5259 SCS.ReferenceBinding = true;
5260 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5261 SCS.BindsToRvalue = true;
5262 SCS.BindsToFunctionLvalue = false;
5263 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5264 SCS.ObjCLifetimeConversionBinding = false;
5265 } else
5266 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5267 From, ToType);
5268 return Result;
5269 }
5270
5271 // C++14 [over.ics.list]p7:
5272 // C++11 [over.ics.list]p6:
5273 // Otherwise, if the parameter type is not a class:
5274 if (!ToType->isRecordType()) {
5275 // - if the initializer list has one element that is not itself an
5276 // initializer list, the implicit conversion sequence is the one
5277 // required to convert the element to the parameter type.
5278 unsigned NumInits = From->getNumInits();
5279 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5280 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5281 SuppressUserConversions,
5282 InOverloadResolution,
5283 AllowObjCWritebackConversion);
5284 // - if the initializer list has no elements, the implicit conversion
5285 // sequence is the identity conversion.
5286 else if (NumInits == 0) {
5287 Result.setStandard();
5288 Result.Standard.setAsIdentityConversion();
5289 Result.Standard.setFromType(ToType);
5290 Result.Standard.setAllToTypes(ToType);
5291 }
5292 return Result;
5293 }
5294
5295 // C++14 [over.ics.list]p8:
5296 // C++11 [over.ics.list]p7:
5297 // In all cases other than those enumerated above, no conversion is possible
5298 return Result;
5299}
5300
5301/// TryCopyInitialization - Try to copy-initialize a value of type
5302/// ToType from the expression From. Return the implicit conversion
5303/// sequence required to pass this argument, which may be a bad
5304/// conversion sequence (meaning that the argument cannot be passed to
5305/// a parameter of this type). If @p SuppressUserConversions, then we
5306/// do not permit any user-defined conversion sequences.
5307static ImplicitConversionSequence
5308TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5309 bool SuppressUserConversions,
5310 bool InOverloadResolution,
5311 bool AllowObjCWritebackConversion,
5312 bool AllowExplicit) {
5313 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5314 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5315 InOverloadResolution,AllowObjCWritebackConversion);
5316
5317 if (ToType->isReferenceType())
5318 return TryReferenceInit(S, From, ToType,
5319 /*FIXME:*/ From->getBeginLoc(),
5320 SuppressUserConversions, AllowExplicit);
5321
5322 return TryImplicitConversion(S, From, ToType,
5323 SuppressUserConversions,
5324 AllowedExplicit::None,
5325 InOverloadResolution,
5326 /*CStyle=*/false,
5327 AllowObjCWritebackConversion,
5328 /*AllowObjCConversionOnExplicit=*/false);
5329}
5330
5331static bool TryCopyInitialization(const CanQualType FromQTy,
5332 const CanQualType ToQTy,
5333 Sema &S,
5334 SourceLocation Loc,
5335 ExprValueKind FromVK) {
5336 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5337 ImplicitConversionSequence ICS =
5338 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5339
5340 return !ICS.isBad();
5341}
5342
5343/// TryObjectArgumentInitialization - Try to initialize the object
5344/// parameter of the given member function (@c Method) from the
5345/// expression @p From.
5346static ImplicitConversionSequence
5347TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5348 Expr::Classification FromClassification,
5349 CXXMethodDecl *Method,
5350 CXXRecordDecl *ActingContext) {
5351 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5352 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5353 // const volatile object.
5354 Qualifiers Quals = Method->getMethodQualifiers();
5355 if (isa<CXXDestructorDecl>(Method)) {
5356 Quals.addConst();
5357 Quals.addVolatile();
5358 }
5359
5360 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5361
5362 // Set up the conversion sequence as a "bad" conversion, to allow us
5363 // to exit early.
5364 ImplicitConversionSequence ICS;
5365
5366 // We need to have an object of class type.
5367 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5368 FromType = PT->getPointeeType();
5369
5370 // When we had a pointer, it's implicitly dereferenced, so we
5371 // better have an lvalue.
5372 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp"
, 5372, __extension__ __PRETTY_FUNCTION__))
;
5373 }
5374
5375 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp"
, 5375, __extension__ __PRETTY_FUNCTION__))
;
5376
5377 // C++0x [over.match.funcs]p4:
5378 // For non-static member functions, the type of the implicit object
5379 // parameter is
5380 //
5381 // - "lvalue reference to cv X" for functions declared without a
5382 // ref-qualifier or with the & ref-qualifier
5383 // - "rvalue reference to cv X" for functions declared with the &&
5384 // ref-qualifier
5385 //
5386 // where X is the class of which the function is a member and cv is the
5387 // cv-qualification on the member function declaration.
5388 //
5389 // However, when finding an implicit conversion sequence for the argument, we
5390 // are not allowed to perform user-defined conversions
5391 // (C++ [over.match.funcs]p5). We perform a simplified version of
5392 // reference binding here, that allows class rvalues to bind to
5393 // non-constant references.
5394
5395 // First check the qualifiers.
5396 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5397 if (ImplicitParamType.getCVRQualifiers()
5398 != FromTypeCanon.getLocalCVRQualifiers() &&
5399 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5400 ICS.setBad(BadConversionSequence::bad_qualifiers,
5401 FromType, ImplicitParamType);
5402 return ICS;
5403 }
5404
5405 if (FromTypeCanon.hasAddressSpace()) {
5406 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5407 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5408 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5409 ICS.setBad(BadConversionSequence::bad_qualifiers,
5410 FromType, ImplicitParamType);
5411 return ICS;
5412 }
5413 }
5414
5415 // Check that we have either the same type or a derived type. It
5416 // affects the conversion rank.
5417 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5418 ImplicitConversionKind SecondKind;
5419 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5420 SecondKind = ICK_Identity;
5421 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5422 SecondKind = ICK_Derived_To_Base;
5423 else {
5424 ICS.setBad(BadConversionSequence::unrelated_class,
5425 FromType, ImplicitParamType);
5426 return ICS;
5427 }
5428
5429 // Check the ref-qualifier.
5430 switch (Method->getRefQualifier()) {
5431 case RQ_None:
5432 // Do nothing; we don't care about lvalueness or rvalueness.
5433 break;
5434
5435 case RQ_LValue:
5436 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5437 // non-const lvalue reference cannot bind to an rvalue
5438 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5439 ImplicitParamType);
5440 return ICS;
5441 }
5442 break;
5443
5444 case RQ_RValue:
5445 if (!FromClassification.isRValue()) {
5446 // rvalue reference cannot bind to an lvalue
5447 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5448 ImplicitParamType);
5449 return ICS;
5450 }
5451 break;
5452 }
5453
5454 // Success. Mark this as a reference binding.
5455 ICS.setStandard();
5456 ICS.Standard.setAsIdentityConversion();
5457 ICS.Standard.Second = SecondKind;
5458 ICS.Standard.setFromType(FromType);
5459 ICS.Standard.setAllToTypes(ImplicitParamType);
5460 ICS.Standard.ReferenceBinding = true;
5461 ICS.Standard.DirectBinding = true;
5462 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5463 ICS.Standard.BindsToFunctionLvalue = false;
5464 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5465 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5466 = (Method->getRefQualifier() == RQ_None);
5467 return ICS;
5468}
5469
5470/// PerformObjectArgumentInitialization - Perform initialization of
5471/// the implicit object parameter for the given Method with the given
5472/// expression.
5473ExprResult
5474Sema::PerformObjectArgumentInitialization(Expr *From,
5475 NestedNameSpecifier *Qualifier,
5476 NamedDecl *FoundDecl,
5477 CXXMethodDecl *Method) {
5478 QualType FromRecordType, DestType;
5479 QualType ImplicitParamRecordType =
5480 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5481
5482 Expr::Classification FromClassification;
5483 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5484 FromRecordType = PT->getPointeeType();
5485 DestType = Method->getThisType();
5486 FromClassification = Expr::Classification::makeSimpleLValue();
5487 } else {
5488 FromRecordType = From->getType();
5489 DestType = ImplicitParamRecordType;
5490 FromClassification = From->Classify(Context);
5491
5492 // When performing member access on a prvalue, materialize a temporary.
5493 if (From->isPRValue()) {
5494 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5495 Method->getRefQualifier() !=
5496 RefQualifierKind::RQ_RValue);
5497 }
5498 }
5499
5500 // Note that we always use the true parent context when performing
5501 // the actual argument initialization.
5502 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5503 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5504 Method->getParent());
5505 if (ICS.isBad()) {
5506 switch (ICS.Bad.Kind) {
5507 case BadConversionSequence::bad_qualifiers: {
5508 Qualifiers FromQs = FromRecordType.getQualifiers();
5509 Qualifiers ToQs = DestType.getQualifiers();
5510 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5511 if (CVR) {
5512 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5513 << Method->getDeclName() << FromRecordType << (CVR - 1)
5514 << From->getSourceRange();
5515 Diag(Method->getLocation(), diag::note_previous_decl)
5516 << Method->getDeclName();
5517 return ExprError();
5518 }
5519 break;
5520 }
5521
5522 case BadConversionSequence::lvalue_ref_to_rvalue:
5523 case BadConversionSequence::rvalue_ref_to_lvalue: {
5524 bool IsRValueQualified =
5525 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5526 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5527 << Method->getDeclName() << FromClassification.isRValue()
5528 << IsRValueQualified;
5529 Diag(Method->getLocation(), diag::note_previous_decl)
5530 << Method->getDeclName();
5531 return ExprError();
5532 }
5533
5534 case BadConversionSequence::no_conversion:
5535 case BadConversionSequence::unrelated_class:
5536 break;
5537
5538 case BadConversionSequence::too_few_initializers:
5539 case BadConversionSequence::too_many_initializers:
5540 llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp"
, 5540)
;
5541 }
5542
5543 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5544 << ImplicitParamRecordType << FromRecordType
5545 << From->getSourceRange();
5546 }
5547
5548 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5549 ExprResult FromRes =
5550 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5551 if (FromRes.isInvalid())
5552 return ExprError();
5553 From = FromRes.get();
5554 }
5555
5556 if (!Context.hasSameType(From->getType(), DestType)) {
5557 CastKind CK;
5558 QualType PteeTy = DestType->getPointeeType();
5559 LangAS DestAS =
5560 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5561 if (FromRecordType.getAddressSpace() != DestAS)
5562 CK = CK_AddressSpaceConversion;
5563 else
5564 CK = CK_NoOp;
5565 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5566 }
5567 return From;
5568}
5569
5570/// TryContextuallyConvertToBool - Attempt to contextually convert the
5571/// expression From to bool (C++0x [conv]p3).
5572static ImplicitConversionSequence
5573TryContextuallyConvertToBool(Sema &S, Expr *From) {
5574 // C++ [dcl.init]/17.8:
5575 // - Otherwise, if the initialization is direct-initialization, the source
5576 // type is std::nullptr_t, and the destination type is bool, the initial
5577 // value of the object being initialized is false.
5578 if (From->getType()->isNullPtrType())
5579 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5580 S.Context.BoolTy,
5581 From->isGLValue());
5582
5583 // All other direct-initialization of bool is equivalent to an implicit
5584 // conversion to bool in which explicit conversions are permitted.
5585 return TryImplicitConversion(S, From, S.Context.BoolTy,
5586 /*SuppressUserConversions=*/false,
5587 AllowedExplicit::Conversions,
5588 /*InOverloadResolution=*/false,
5589 /*CStyle=*/false,
5590 /*AllowObjCWritebackConversion=*/false,
5591 /*AllowObjCConversionOnExplicit=*/false);
5592}
5593
5594/// PerformContextuallyConvertToBool - Perform a contextual conversion
5595/// of the expression From to bool (C++0x [conv]p3).
5596ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5597 if (checkPlaceholderForOverload(*this, From))
5598 return ExprError();
5599
5600 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5601 if (!ICS.isBad())
5602 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5603
5604 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5605 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5606 << From->getType() << From->getSourceRange();
5607 return ExprError();
5608}
5609
5610/// Check that the specified conversion is permitted in a converted constant
5611/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5612/// is acceptable.
5613static bool CheckConvertedConstantConversions(Sema &S,
5614 StandardConversionSequence &SCS) {
5615 // Since we know that the target type is an integral or unscoped enumeration
5616 // type, most conversion kinds are impossible. All possible First and Third
5617 // conversions are fine.
5618 switch (SCS.Second) {
5619 case ICK_Identity:
5620 case ICK_Integral_Promotion:
5621 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5622 case ICK_Zero_Queue_Conversion:
5623 return true;
5624
5625 case ICK_Boolean_Conversion:
5626 // Conversion from an integral or unscoped enumeration type to bool is
5627 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5628 // conversion, so we allow it in a converted constant expression.
5629 //
5630 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5631 // a lot of popular code. We should at least add a warning for this
5632 // (non-conforming) extension.
5633 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5634 SCS.getToType(2)->isBooleanType();
5635
5636 case ICK_Pointer_Conversion:
5637 case ICK_Pointer_Member:
5638 // C++1z: null pointer conversions and null member pointer conversions are
5639 // only permitted if the source type is std::nullptr_t.
5640 return SCS.getFromType()->isNullPtrType();
5641
5642 case ICK_Floating_Promotion:
5643 case ICK_Complex_Promotion:
5644 case ICK_Floating_Conversion:
5645 case ICK_Complex_Conversion:
5646 case ICK_Floating_Integral:
5647 case ICK_Compatible_Conversion:
5648 case ICK_Derived_To_Base:
5649 case ICK_Vector_Conversion:
5650 case ICK_SVE_Vector_Conversion:
5651 case ICK_Vector_Splat:
5652 case ICK_Complex_Real:
5653 case ICK_Block_Pointer_Conversion:
5654 case ICK_TransparentUnionConversion:
5655 case ICK_Writeback_Conversion:
5656 case ICK_Zero_Event_Conversion:
5657 case ICK_C_Only_Conversion:
5658 case ICK_Incompatible_Pointer_Conversion:
5659 return false;
5660
5661 case ICK_Lvalue_To_Rvalue:
5662 case ICK_Array_To_Pointer:
5663 case ICK_Function_To_Pointer:
5664 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5664)
;
5665
5666 case ICK_Function_Conversion:
5667 case ICK_Qualification:
5668 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5668)
;
5669
5670 case ICK_Num_Conversion_Kinds:
5671 break;
5672 }
5673
5674 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp"
, 5674)
;
5675}
5676
5677/// CheckConvertedConstantExpression - Check that the expression From is a
5678/// converted constant expression of type T, perform the conversion and produce
5679/// the converted expression, per C++11 [expr.const]p3.
5680static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5681 QualType T, APValue &Value,
5682 Sema::CCEKind CCE,
5683 bool RequireInt,
5684 NamedDecl *Dest) {
5685 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5686, __extension__ __PRETTY_FUNCTION__
))
5686 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5686, __extension__ __PRETTY_FUNCTION__
))
;
5687
5688 if (checkPlaceholderForOverload(S, From))
5689 return ExprError();
5690
5691 // C++1z [expr.const]p3:
5692 // A converted constant expression of type T is an expression,
5693 // implicitly converted to type T, where the converted
5694 // expression is a constant expression and the implicit conversion
5695 // sequence contains only [... list of conversions ...].
5696 ImplicitConversionSequence ICS =
5697 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5698 ? TryContextuallyConvertToBool(S, From)
5699 : TryCopyInitialization(S, From, T,
5700 /*SuppressUserConversions=*/false,
5701 /*InOverloadResolution=*/false,
5702 /*AllowObjCWritebackConversion=*/false,
5703 /*AllowExplicit=*/false);
5704 StandardConversionSequence *SCS = nullptr;
5705 switch (ICS.getKind()) {
5706 case ImplicitConversionSequence::StandardConversion:
5707 SCS = &ICS.Standard;
5708 break;
5709 case ImplicitConversionSequence::UserDefinedConversion:
5710 if (T->isRecordType())
5711 SCS = &ICS.UserDefined.Before;
5712 else
5713 SCS = &ICS.UserDefined.After;
5714 break;
5715 case ImplicitConversionSequence::AmbiguousConversion:
5716 case ImplicitConversionSequence::BadConversion:
5717 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5718 return S.Diag(From->getBeginLoc(),
5719 diag::err_typecheck_converted_constant_expression)
5720 << From->getType() << From->getSourceRange() << T;
5721 return ExprError();
5722
5723 case ImplicitConversionSequence::EllipsisConversion:
5724 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "clang/lib/Sema/SemaOverload.cpp", 5724)
;
5725 }
5726
5727 // Check that we would only use permitted conversions.
5728 if (!CheckConvertedConstantConversions(S, *SCS)) {
5729 return S.Diag(From->getBeginLoc(),
5730 diag::err_typecheck_converted_constant_expression_disallowed)
5731 << From->getType() << From->getSourceRange() << T;
5732 }
5733 // [...] and where the reference binding (if any) binds directly.
5734 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5735 return S.Diag(From->getBeginLoc(),
5736 diag::err_typecheck_converted_constant_expression_indirect)
5737 << From->getType() << From->getSourceRange() << T;
5738 }
5739
5740 // Usually we can simply apply the ImplicitConversionSequence we formed
5741 // earlier, but that's not guaranteed to work when initializing an object of
5742 // class type.
5743 ExprResult Result;
5744 if (T->isRecordType()) {
5745 assert(CCE == Sema::CCEK_TemplateArg &&(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5746, __extension__ __PRETTY_FUNCTION__
))
5746 "unexpected class type converted constant expr")(static_cast <bool> (CCE == Sema::CCEK_TemplateArg &&
"unexpected class type converted constant expr") ? void (0) :
__assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "clang/lib/Sema/SemaOverload.cpp", 5746, __extension__ __PRETTY_FUNCTION__
))
;
5747 Result = S.PerformCopyInitialization(
5748 InitializedEntity::InitializeTemplateParameter(
5749 T, cast<NonTypeTemplateParmDecl>(Dest)),
5750 SourceLocation(), From);
5751 } else {
5752 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5753 }
5754 if (Result.isInvalid())
5755 return Result;
5756
5757 // C++2a [intro.execution]p5:
5758 // A full-expression is [...] a constant-expression [...]
5759 Result =
5760 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5761 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5762 if (Result.isInvalid())
5763 return Result;
5764
5765 // Check for a narrowing implicit conversion.
5766 bool ReturnPreNarrowingValue = false;
5767 APValue PreNarrowingValue;
5768 QualType PreNarrowingType;
5769 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5770 PreNarrowingType)) {
5771 case NK_Dependent_Narrowing:
5772 // Implicit conversion to a narrower type, but the expression is
5773 // value-dependent so we can't tell whether it's actually narrowing.
5774 case NK_Variable_Narrowing:
5775 // Implicit conversion to a narrower type, and the value is not a constant
5776 // expression. We'll diagnose this in a moment.
5777 case NK_Not_Narrowing:
5778 break;
5779
5780 case NK_Constant_Narrowing:
5781 if (CCE == Sema::CCEK_ArrayBound &&
5782 PreNarrowingType->isIntegralOrEnumerationType() &&
5783 PreNarrowingValue.isInt()) {
5784 // Don't diagnose array bound narrowing here; we produce more precise
5785 // errors by allowing the un-narrowed value through.
5786 ReturnPreNarrowingValue = true;
5787 break;
5788 }
5789 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5790 << CCE << /*Constant*/ 1
5791 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5792 break;
5793
5794 case NK_Type_Narrowing:
5795 // FIXME: It would be better to diagnose that the expression is not a
5796 // constant expression.
5797 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5798 << CCE << /*Constant*/ 0 << From->getType() << T;
5799 break;
5800 }
5801
5802 if (Result.get()->isValueDependent()) {
5803 Value = APValue();
5804 return Result;
5805 }
5806
5807 // Check the expression is a constant expression.
5808 SmallVector<PartialDiagnosticAt, 8> Notes;
5809 Expr::EvalResult Eval;
5810 Eval.Diag = &Notes;
5811
5812 ConstantExprKind Kind;
5813 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5814 Kind = ConstantExprKind::ClassTemplateArgument;
5815 else if (CCE == Sema::CCEK_TemplateArg)
5816 Kind = ConstantExprKind::NonClassTemplateArgument;
5817 else
5818 Kind = ConstantExprKind::Normal;
5819
5820 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5821 (RequireInt && !Eval.Val.isInt())) {
5822 // The expression can't be folded, so we can't keep it at this position in
5823 // the AST.
5824 Result = ExprError();
5825 } else {
5826 Value = Eval.Val;
5827
5828 if (Notes.empty()) {
5829 // It's a constant expression.
5830 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5831 if (ReturnPreNarrowingValue)
5832 Value = std::move(PreNarrowingValue);
5833 return E;
5834 }
5835 }
5836
5837 // It's not a constant expression. Produce an appropriate diagnostic.
5838 if (Notes.size() == 1 &&
5839 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5840 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5841 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5842 diag::note_constexpr_invalid_template_arg) {
5843 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5844 for (unsigned I = 0; I < Notes.size(); ++I)
5845 S.Diag(Notes[I].first, Notes[I].second);
5846 } else {
5847 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5848 << CCE << From->getSourceRange();
5849 for (unsigned I = 0; I < Notes.size(); ++I)
5850 S.Diag(Notes[I].first, Notes[I].second);
5851 }
5852 return ExprError();
5853}
5854
5855ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5856 APValue &Value, CCEKind CCE,
5857 NamedDecl *Dest) {
5858 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5859 Dest);
5860}
5861
5862ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5863 llvm::APSInt &Value,
5864 CCEKind CCE) {
5865 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType(
) && "unexpected converted const type") ? void (0) : __assert_fail
("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "clang/lib/Sema/SemaOverload.cpp", 5865, __extension__ __PRETTY_FUNCTION__
))
;
5866
5867 APValue V;
5868 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5869 /*Dest=*/nullptr);
5870 if (!R.isInvalid() && !R.get()->isValueDependent())
5871 Value = V.getInt();
5872 return R;
5873}
5874
5875
5876/// dropPointerConversions - If the given standard conversion sequence
5877/// involves any pointer conversions, remove them. This may change
5878/// the result type of the conversion sequence.
5879static void dropPointerConversion(StandardConversionSequence &SCS) {
5880 if (SCS.Second == ICK_Pointer_Conversion) {
5881 SCS.Second = ICK_Identity;
5882 SCS.Third = ICK_Identity;
5883 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5884 }
5885}
5886
5887/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5888/// convert the expression From to an Objective-C pointer type.
5889static ImplicitConversionSequence
5890TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5891 // Do an implicit conversion to 'id'.
5892 QualType Ty = S.Context.getObjCIdType();
5893 ImplicitConversionSequence ICS
5894 = TryImplicitConversion(S, From, Ty,
5895 // FIXME: Are these flags correct?
5896 /*SuppressUserConversions=*/false,
5897 AllowedExplicit::Conversions,
5898 /*InOverloadResolution=*/false,
5899 /*CStyle=*/false,
5900 /*AllowObjCWritebackConversion=*/false,
5901 /*AllowObjCConversionOnExplicit=*/true);
5902
5903 // Strip off any final conversions to 'id'.
5904 switch (ICS.getKind()) {
5905 case ImplicitConversionSequence::BadConversion:
5906 case ImplicitConversionSequence::AmbiguousConversion:
5907 case ImplicitConversionSequence::EllipsisConversion:
5908 break;
5909
5910 case ImplicitConversionSequence::UserDefinedConversion:
5911 dropPointerConversion(ICS.UserDefined.After);
5912 break;
5913
5914 case ImplicitConversionSequence::StandardConversion:
5915 dropPointerConversion(ICS.Standard);
5916 break;
5917 }
5918
5919 return ICS;
5920}
5921
5922/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5923/// conversion of the expression From to an Objective-C pointer type.
5924/// Returns a valid but null ExprResult if no conversion sequence exists.
5925ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5926 if (checkPlaceholderForOverload(*this, From))
5927 return ExprError();
5928
5929 QualType Ty = Context.getObjCIdType();
5930 ImplicitConversionSequence ICS =
5931 TryContextuallyConvertToObjCPointer(*this, From);
5932 if (!ICS.isBad())
5933 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5934 return ExprResult();
5935}
5936
5937/// Determine whether the provided type is an integral type, or an enumeration
5938/// type of a permitted flavor.
5939bool Sema::ICEConvertDiagnoser::match(QualType T) {
5940 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5941 : T->isIntegralOrUnscopedEnumerationType();
5942}
5943
5944static ExprResult
5945diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5946 Sema::ContextualImplicitConverter &Converter,
5947 QualType T, UnresolvedSetImpl &ViableConversions) {
5948
5949 if (Converter.Suppress)
5950 return ExprError();
5951
5952 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5953 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5954 CXXConversionDecl *Conv =
5955 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5956 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5957 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5958 }
5959 return From;
5960}
5961
5962static bool
5963diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5964 Sema::ContextualImplicitConverter &Converter,
5965 QualType T, bool HadMultipleCandidates,
5966 UnresolvedSetImpl &ExplicitConversions) {
5967 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5968 DeclAccessPair Found = ExplicitConversions[0];
5969 CXXConversionDecl *Conversion =
5970 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5971
5972 // The user probably meant to invoke the given explicit
5973 // conversion; use it.
5974 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5975 std::string TypeStr;
5976 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5977
5978 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5979 << FixItHint::CreateInsertion(From->getBeginLoc(),
5980 "static_cast<" + TypeStr + ">(")
5981 << FixItHint::CreateInsertion(
5982 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5983 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5984
5985 // If we aren't in a SFINAE context, build a call to the
5986 // explicit conversion function.
5987 if (SemaRef.isSFINAEContext())
5988 return true;
5989
5990 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5991 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5992 HadMultipleCandidates);
5993 if (Result.isInvalid())
5994 return true;
5995 // Record usage of conversion in an implicit cast.
5996 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5997 CK_UserDefinedConversion, Result.get(),
5998 nullptr, Result.get()->getValueKind(),
5999 SemaRef.CurFPFeatureOverrides());
6000 }
6001 return false;
6002}
6003
6004static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6005 Sema::ContextualImplicitConverter &Converter,
6006 QualType T, bool HadMultipleCandidates,
6007 DeclAccessPair &Found) {
6008 CXXConversionDecl *Conversion =
6009 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6010 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6011
6012 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6013 if (!Converter.SuppressConversion) {
6014 if (SemaRef.isSFINAEContext())
6015 return true;
6016
6017 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6018 << From->getSourceRange();
6019 }
6020
6021 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6022 HadMultipleCandidates);
6023 if (Result.isInvalid())
6024 return true;
6025 // Record usage of conversion in an implicit cast.
6026 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6027 CK_UserDefinedConversion, Result.get(),
6028 nullptr, Result.get()->getValueKind(),
6029 SemaRef.CurFPFeatureOverrides());
6030 return false;
6031}
6032
6033static ExprResult finishContextualImplicitConversion(
6034 Sema &SemaRef, SourceLocation Loc, Expr *From,
6035 Sema::ContextualImplicitConverter &Converter) {
6036 if (!Converter.match(From->getType()) && !Converter.Suppress)
6037 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6038 << From->getSourceRange();
6039
6040 return SemaRef.DefaultLvalueConversion(From);
6041}
6042
6043static void
6044collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6045 UnresolvedSetImpl &ViableConversions,
6046 OverloadCandidateSet &CandidateSet) {
6047 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6048 DeclAccessPair FoundDecl = ViableConversions[I];
6049 NamedDecl *D = FoundDecl.getDecl();
6050 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6051 if (isa<UsingShadowDecl>(D))
6052 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6053
6054 CXXConversionDecl *Conv;
6055 FunctionTemplateDecl *ConvTemplate;
6056 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6057 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6058 else
6059 Conv = cast<CXXConversionDecl>(D);
6060
6061 if (ConvTemplate)
6062 SemaRef.AddTemplateConversionCandidate(
6063 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6064 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6065 else
6066 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6067 ToType, CandidateSet,
6068 /*AllowObjCConversionOnExplicit=*/false,
6069 /*AllowExplicit*/ true);
6070 }
6071}
6072
6073/// Attempt to convert the given expression to a type which is accepted
6074/// by the given converter.
6075///
6076/// This routine will attempt to convert an expression of class type to a
6077/// type accepted by the specified converter. In C++11 and before, the class
6078/// must have a single non-explicit conversion function converting to a matching
6079/// type. In C++1y, there can be multiple such conversion functions, but only
6080/// one target type.
6081///
6082/// \param Loc The source location of the construct that requires the
6083/// conversion.
6084///
6085/// \param From The expression we're converting from.
6086///
6087/// \param Converter Used to control and diagnose the conversion process.
6088///
6089/// \returns The expression, converted to an integral or enumeration type if
6090/// successful.
6091ExprResult Sema::PerformContextualImplicitConversion(
6092 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6093 // We can't perform any more checking for type-dependent expressions.
6094 if (From->isTypeDependent())
6095 return From;
6096
6097 // Process placeholders immediately.
6098 if (From->hasPlaceholderType()) {
6099 ExprResult result = CheckPlaceholderExpr(From);
6100 if (result.isInvalid())
6101 return result;
6102 From = result.get();
6103 }
6104
6105 // If the expression already has a matching type, we're golden.
6106 QualType T = From->getType();
6107 if (Converter.match(T))
6108 return DefaultLvalueConversion(From);
6109
6110 // FIXME: Check for missing '()' if T is a function type?
6111
6112 // We can only perform contextual implicit conversions on objects of class
6113 // type.
6114 const RecordType *RecordTy = T->getAs<RecordType>();
6115 if (!RecordTy || !getLangOpts().CPlusPlus) {
6116 if (!Converter.Suppress)
6117 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6118 return From;
6119 }
6120
6121 // We must have a complete class type.
6122 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6123 ContextualImplicitConverter &Converter;
6124 Expr *From;
6125
6126 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6127 : Converter(Converter), From(From) {}
6128
6129 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6130 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6131 }
6132 } IncompleteDiagnoser(Converter, From);
6133
6134 if (Converter.Suppress ? !isCompleteType(Loc, T)
6135 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6136 return From;
6137
6138 // Look for a conversion to an integral or enumeration type.
6139 UnresolvedSet<4>
6140 ViableConversions; // These are *potentially* viable in C++1y.
6141 UnresolvedSet<4> ExplicitConversions;
6142 const auto &Conversions =
6143 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6144
6145 bool HadMultipleCandidates =
6146 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6147
6148 // To check that there is only one target type, in C++1y:
6149 QualType ToType;
6150 bool HasUniqueTargetType = true;
6151
6152 // Collect explicit or viable (potentially in C++1y) conversions.
6153 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6154 NamedDecl *D = (*I)->getUnderlyingDecl();
6155 CXXConversionDecl *Conversion;
6156 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6157 if (ConvTemplate) {
6158 if (getLangOpts().CPlusPlus14)
6159 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6160 else
6161 continue; // C++11 does not consider conversion operator templates(?).
6162 } else
6163 Conversion = cast<CXXConversionDecl>(D);
6164
6165 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6167, __extension__ __PRETTY_FUNCTION__
))
6166 "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6167, __extension__ __PRETTY_FUNCTION__
))
6167 "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "clang/lib/Sema/SemaOverload.cpp", 6167, __extension__ __PRETTY_FUNCTION__
))
;
6168
6169 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6170 if (Converter.match(CurToType) || ConvTemplate) {
6171
6172 if (Conversion->isExplicit()) {
6173 // FIXME: For C++1y, do we need this restriction?
6174 // cf. diagnoseNoViableConversion()
6175 if (!ConvTemplate)
6176 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6177 } else {
6178 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6179 if (ToType.isNull())
6180 ToType = CurToType.getUnqualifiedType();
6181 else if (HasUniqueTargetType &&
6182 (CurToType.getUnqualifiedType() != ToType))
6183 HasUniqueTargetType = false;
6184 }
6185 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6186 }
6187 }
6188 }
6189
6190 if (getLangOpts().CPlusPlus14) {
6191 // C++1y [conv]p6:
6192 // ... An expression e of class type E appearing in such a context
6193 // is said to be contextually implicitly converted to a specified
6194 // type T and is well-formed if and only if e can be implicitly
6195 // converted to a type T that is determined as follows: E is searched
6196 // for conversion functions whose return type is cv T or reference to
6197 // cv T such that T is allowed by the context. There shall be
6198 // exactly one such T.
6199
6200 // If no unique T is found:
6201 if (ToType.isNull()) {
6202 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6203 HadMultipleCandidates,
6204 ExplicitConversions))
6205 return ExprError();
6206 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6207 }
6208
6209 // If more than one unique Ts are found:
6210 if (!HasUniqueTargetType)
6211 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6212 ViableConversions);
6213
6214 // If one unique T is found:
6215 // First, build a candidate set from the previously recorded
6216 // potentially viable conversions.
6217 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6218 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6219 CandidateSet);
6220
6221 // Then, perform overload resolution over the candidate set.
6222 OverloadCandidateSet::iterator Best;
6223 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6224 case OR_Success: {
6225 // Apply this conversion.
6226 DeclAccessPair Found =
6227 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6228 if (recordConversion(*this, Loc, From, Converter, T,
6229 HadMultipleCandidates, Found))
6230 return ExprError();
6231 break;
6232 }
6233 case OR_Ambiguous:
6234 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6235 ViableConversions);
6236 case OR_No_Viable_Function:
6237 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6238 HadMultipleCandidates,
6239 ExplicitConversions))
6240 return ExprError();
6241 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6242 case OR_Deleted:
6243 // We'll complain below about a non-integral condition type.
6244 break;
6245 }
6246 } else {
6247 switch (ViableConversions.size()) {
6248 case 0: {
6249 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6250 HadMultipleCandidates,
6251 ExplicitConversions))
6252 return ExprError();
6253
6254 // We'll complain below about a non-integral condition type.
6255 break;
6256 }
6257 case 1: {
6258 // Apply this conversion.
6259 DeclAccessPair Found = ViableConversions[0];
6260 if (recordConversion(*this, Loc, From, Converter, T,
6261 HadMultipleCandidates, Found))
6262 return ExprError();
6263 break;
6264 }
6265 default:
6266 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6267 ViableConversions);
6268 }
6269 }
6270
6271 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6272}
6273
6274/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6275/// an acceptable non-member overloaded operator for a call whose
6276/// arguments have types T1 (and, if non-empty, T2). This routine
6277/// implements the check in C++ [over.match.oper]p3b2 concerning
6278/// enumeration types.
6279static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6280 FunctionDecl *Fn,
6281 ArrayRef<Expr *> Args) {
6282 QualType T1 = Args[0]->getType();
6283 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6284
6285 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6286 return true;
6287
6288 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6289 return true;
6290
6291 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6292 if (Proto->getNumParams() < 1)
6293 return false;
6294
6295 if (T1->isEnumeralType()) {
6296 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6297 if (Context.hasSameUnqualifiedType(T1, ArgType))
6298 return true;
6299 }
6300
6301 if (Proto->getNumParams() < 2)
6302 return false;
6303
6304 if (!T2.isNull() && T2->isEnumeralType()) {
6305 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6306 if (Context.hasSameUnqualifiedType(T2, ArgType))
6307 return true;
6308 }
6309
6310 return false;
6311}
6312
6313/// AddOverloadCandidate - Adds the given function to the set of
6314/// candidate functions, using the given function call arguments. If
6315/// @p SuppressUserConversions, then don't allow user-defined
6316/// conversions via constructors or conversion operators.
6317///
6318/// \param PartialOverloading true if we are performing "partial" overloading
6319/// based on an incomplete set of function arguments. This feature is used by
6320/// code completion.
6321void Sema::AddOverloadCandidate(
6322 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6323 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6324 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6325 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6326 OverloadCandidateParamOrder PO) {
6327 const FunctionProtoType *Proto
6328 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6329 assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "clang/lib/Sema/SemaOverload.cpp", 6329, __extension__ __PRETTY_FUNCTION__
))
;
6330 assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "clang/lib/Sema/SemaOverload.cpp", 6331, __extension__ __PRETTY_FUNCTION__
))
6331 "Use AddTemplateOverloadCandidate for function templates")(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "clang/lib/Sema/SemaOverload.cpp", 6331, __extension__ __PRETTY_FUNCTION__
))
;
6332
6333 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6334 if (!isa<CXXConstructorDecl>(Method)) {
6335 // If we get here, it's because we're calling a member function
6336 // that is named without a member access expression (e.g.,
6337 // "this->f") that was either written explicitly or created
6338 // implicitly. This can happen with a qualified call to a member
6339 // function, e.g., X::f(). We use an empty type for the implied
6340 // object argument (C++ [over.call.func]p3), and the acting context
6341 // is irrelevant.
6342 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6343 Expr::Classification::makeSimpleLValue(), Args,
6344 CandidateSet, SuppressUserConversions,
6345 PartialOverloading, EarlyConversions, PO);
6346 return;
6347 }
6348 // We treat a constructor like a non-member function, since its object
6349 // argument doesn't participate in overload resolution.
6350 }
6351
6352 if (!CandidateSet.isNewCandidate(Function, PO))
6353 return;
6354
6355 // C++11 [class.copy]p11: [DR1402]
6356 // A defaulted move constructor that is defined as deleted is ignored by
6357 // overload resolution.
6358 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6359 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6360 Constructor->isMoveConstructor())
6361 return;
6362
6363 // Overload resolution is always an unevaluated context.
6364 EnterExpressionEvaluationContext Unevaluated(
6365 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6366
6367 // C++ [over.match.oper]p3:
6368 // if no operand has a class type, only those non-member functions in the
6369 // lookup set that have a first parameter of type T1 or "reference to
6370 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6371 // is a right operand) a second parameter of type T2 or "reference to
6372 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6373 // candidate functions.
6374 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6375 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6376 return;
6377
6378 // Add this candidate
6379 OverloadCandidate &Candidate =
6380 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6381 Candidate.FoundDecl = FoundDecl;
6382 Candidate.Function = Function;
6383 Candidate.Viable = true;
6384 Candidate.RewriteKind =
6385 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6386 Candidate.IsSurrogate = false;
6387 Candidate.IsADLCandidate = IsADLCandidate;
6388 Candidate.IgnoreObjectArgument = false;
6389 Candidate.ExplicitCallArguments = Args.size();
6390
6391 // Explicit functions are not actually candidates at all if we're not
6392 // allowing them in this context, but keep them around so we can point
6393 // to them in diagnostics.
6394 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6395 Candidate.Viable = false;
6396 Candidate.FailureKind = ovl_fail_explicit;
6397 return;
6398 }
6399
6400 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6401 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6402 Candidate.Viable = false;
6403 Candidate.FailureKind = ovl_non_default_multiversion_function;
6404 return;
6405 }
6406
6407 if (Constructor) {
6408 // C++ [class.copy]p3:
6409 // A member function template is never instantiated to perform the copy
6410 // of a class object to an object of its class type.
6411 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6412 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6413 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6414 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6415 ClassType))) {
6416 Candidate.Viable = false;
6417 Candidate.FailureKind = ovl_fail_illegal_constructor;
6418 return;
6419 }
6420
6421 // C++ [over.match.funcs]p8: (proposed DR resolution)
6422 // A constructor inherited from class type C that has a first parameter
6423 // of type "reference to P" (including such a constructor instantiated
6424 // from a template) is excluded from the set of candidate functions when
6425 // constructing an object of type cv D if the argument list has exactly
6426 // one argument and D is reference-related to P and P is reference-related
6427 // to C.
6428 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6429 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6430 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6431 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6432 QualType C = Context.getRecordType(Constructor->getParent());
6433 QualType D = Context.getRecordType(Shadow->getParent());
6434 SourceLocation Loc = Args.front()->getExprLoc();
6435 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6436 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6437 Candidate.Viable = false;
6438 Candidate.FailureKind = ovl_fail_inhctor_slice;
6439 return;
6440 }
6441 }
6442
6443 // Check that the constructor is capable of constructing an object in the
6444 // destination address space.
6445 if (!Qualifiers::isAddressSpaceSupersetOf(
6446 Constructor->getMethodQualifiers().getAddressSpace(),
6447 CandidateSet.getDestAS())) {
6448 Candidate.Viable = false;
6449 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6450 }
6451 }
6452
6453 unsigned NumParams = Proto->getNumParams();
6454
6455 // (C++ 13.3.2p2): A candidate function having fewer than m
6456 // parameters is viable only if it has an ellipsis in its parameter
6457 // list (8.3.5).
6458 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6459 !Proto->isVariadic() &&
6460 shouldEnforceArgLimit(PartialOverloading, Function)) {
6461 Candidate.Viable = false;
6462 Candidate.FailureKind = ovl_fail_too_many_arguments;
6463 return;
6464 }
6465
6466 // (C++ 13.3.2p2): A candidate function having more than m parameters
6467 // is viable only if the (m+1)st parameter has a default argument
6468 // (8.3.6). For the purposes of overload resolution, the
6469 // parameter list is truncated on the right, so that there are
6470 // exactly m parameters.
6471 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6472 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6473 // Not enough arguments.
6474 Candidate.Viable = false;
6475 Candidate.FailureKind = ovl_fail_too_few_arguments;
6476 return;
6477 }
6478
6479 // (CUDA B.1): Check for invalid calls between targets.
6480 if (getLangOpts().CUDA)
6481 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6482 // Skip the check for callers that are implicit members, because in this
6483 // case we may not yet know what the member's target is; the target is
6484 // inferred for the member automatically, based on the bases and fields of
6485 // the class.
6486 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6487 Candidate.Viable = false;
6488 Candidate.FailureKind = ovl_fail_bad_target;
6489 return;
6490 }
6491
6492 if (Function->getTrailingRequiresClause()) {
6493 ConstraintSatisfaction Satisfaction;
6494 if (CheckFunctionConstraints(Function, Satisfaction) ||
6495 !Satisfaction.IsSatisfied) {
6496 Candidate.Viable = false;
6497 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6498 return;
6499 }
6500 }
6501
6502 // Determine the implicit conversion sequences for each of the
6503 // arguments.
6504 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6505 unsigned ConvIdx =
6506 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6507 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6508 // We already formed a conversion sequence for this parameter during
6509 // template argument deduction.
6510 } else if (ArgIdx < NumParams) {
6511 // (C++ 13.3.2p3): for F to be a viable function, there shall
6512 // exist for each argument an implicit conversion sequence
6513 // (13.3.3.1) that converts that argument to the corresponding
6514 // parameter of F.
6515 QualType ParamType = Proto->getParamType(ArgIdx);
6516 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6517 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6518 /*InOverloadResolution=*/true,
6519 /*AllowObjCWritebackConversion=*/
6520 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6521 if (Candidate.Conversions[ConvIdx].isBad()) {
6522 Candidate.Viable = false;
6523 Candidate.FailureKind = ovl_fail_bad_conversion;
6524 return;
6525 }
6526 } else {
6527 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6528 // argument for which there is no corresponding parameter is
6529 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6530 Candidate.Conversions[ConvIdx].setEllipsis();
6531 }
6532 }
6533
6534 if (EnableIfAttr *FailedAttr =
6535 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6536 Candidate.Viable = false;
6537 Candidate.FailureKind = ovl_fail_enable_if;
6538 Candidate.DeductionFailure.Data = FailedAttr;
6539 return;
6540 }
6541}
6542
6543ObjCMethodDecl *
6544Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6545 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6546 if (Methods.size() <= 1)
6547 return nullptr;
6548
6549 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6550 bool Match = true;
6551 ObjCMethodDecl *Method = Methods[b];
6552 unsigned NumNamedArgs = Sel.getNumArgs();
6553 // Method might have more arguments than selector indicates. This is due
6554 // to addition of c-style arguments in method.
6555 if (Method->param_size() > NumNamedArgs)
6556 NumNamedArgs = Method->param_size();
6557 if (Args.size() < NumNamedArgs)
6558 continue;
6559
6560 for (unsigned i = 0; i < NumNamedArgs; i++) {
6561 // We can't do any type-checking on a type-dependent argument.
6562 if (Args[i]->isTypeDependent()) {
6563 Match = false;
6564 break;
6565 }
6566
6567 ParmVarDecl *param = Method->parameters()[i];
6568 Expr *argExpr = Args[i];
6569 assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression"
) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "clang/lib/Sema/SemaOverload.cpp", 6569, __extension__ __PRETTY_FUNCTION__
))
;
6570
6571 // Strip the unbridged-cast placeholder expression off unless it's
6572 // a consumed argument.
6573 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6574 !param->hasAttr<CFConsumedAttr>())
6575 argExpr = stripARCUnbridgedCast(argExpr);
6576
6577 // If the parameter is __unknown_anytype, move on to the next method.
6578 if (param->getType() == Context.UnknownAnyTy) {
6579 Match = false;
6580 break;
6581 }
6582
6583 ImplicitConversionSequence ConversionState
6584 = TryCopyInitialization(*this, argExpr, param->getType(),
6585 /*SuppressUserConversions*/false,
6586 /*InOverloadResolution=*/true,
6587 /*AllowObjCWritebackConversion=*/
6588 getLangOpts().ObjCAutoRefCount,
6589 /*AllowExplicit*/false);
6590 // This function looks for a reasonably-exact match, so we consider
6591 // incompatible pointer conversions to be a failure here.
6592 if (ConversionState.isBad() ||
6593 (ConversionState.isStandard() &&
6594 ConversionState.Standard.Second ==
6595 ICK_Incompatible_Pointer_Conversion)) {
6596 Match = false;
6597 break;
6598 }
6599 }
6600 // Promote additional arguments to variadic methods.
6601 if (Match && Method->isVariadic()) {
6602 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6603 if (Args[i]->isTypeDependent()) {
6604 Match = false;
6605 break;
6606 }
6607 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6608 nullptr);
6609 if (Arg.isInvalid()) {
6610 Match = false;
6611 break;
6612 }
6613 }
6614 } else {
6615 // Check for extra arguments to non-variadic methods.
6616 if (Args.size() != NumNamedArgs)
6617 Match = false;
6618 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6619 // Special case when selectors have no argument. In this case, select
6620 // one with the most general result type of 'id'.
6621 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6622 QualType ReturnT = Methods[b]->getReturnType();
6623 if (ReturnT->isObjCIdType())
6624 return Methods[b];
6625 }
6626 }
6627 }
6628
6629 if (Match)
6630 return Method;
6631 }
6632 return nullptr;
6633}
6634
6635static bool convertArgsForAvailabilityChecks(
6636 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6637 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6638 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6639 if (ThisArg) {
6640 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6641 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "clang/lib/Sema/SemaOverload.cpp", 6642, __extension__ __PRETTY_FUNCTION__
))
6642 "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "clang/lib/Sema/SemaOverload.cpp", 6642, __extension__ __PRETTY_FUNCTION__
))
;
6643 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "clang/lib/Sema/SemaOverload.cpp", 6643, __extension__ __PRETTY_FUNCTION__
))
;
6644 ExprResult R = S.PerformObjectArgumentInitialization(
6645 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6646 if (R.isInvalid())
6647 return false;
6648 ConvertedThis = R.get();
6649 } else {
6650 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6651 (void)MD;
6652 assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6654, __extension__ __PRETTY_FUNCTION__
))
6653 isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6654, __extension__ __PRETTY_FUNCTION__
))
6654 "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "clang/lib/Sema/SemaOverload.cpp", 6654, __extension__ __PRETTY_FUNCTION__
))
;
6655 }
6656 ConvertedThis = nullptr;
6657 }
6658
6659 // Ignore any variadic arguments. Converting them is pointless, since the
6660 // user can't refer to them in the function condition.
6661 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6662
6663 // Convert the arguments.
6664 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6665 ExprResult R;
6666 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6667 S.Context, Function->getParamDecl(I)),
6668 SourceLocation(), Args[I]);
6669
6670 if (R.isInvalid())
6671 return false;
6672
6673 ConvertedArgs.push_back(R.get());
6674 }
6675
6676 if (Trap.hasErrorOccurred())
6677 return false;
6678
6679 // Push default arguments if needed.
6680 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6681 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6682 ParmVarDecl *P = Function->getParamDecl(i);
6683 if (!P->hasDefaultArg())
6684 return false;
6685 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6686 if (R.isInvalid())
6687 return false;
6688 ConvertedArgs.push_back(R.get());
6689 }
6690
6691 if (Trap.hasErrorOccurred())
6692 return false;
6693 }
6694 return true;
6695}
6696
6697EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6698 SourceLocation CallLoc,
6699 ArrayRef<Expr *> Args,
6700 bool MissingImplicitThis) {
6701 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6702 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6703 return nullptr;
6704
6705 SFINAETrap Trap(*this);
6706 SmallVector<Expr *, 16> ConvertedArgs;
6707 // FIXME: We should look into making enable_if late-parsed.
6708 Expr *DiscardedThis;
6709 if (!convertArgsForAvailabilityChecks(
6710 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6711 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6712 return *EnableIfAttrs.begin();
6713
6714 for (auto *EIA : EnableIfAttrs) {
6715 APValue Result;
6716 // FIXME: This doesn't consider value-dependent cases, because doing so is
6717 // very difficult. Ideally, we should handle them more gracefully.
6718 if (EIA->getCond()->isValueDependent() ||
6719 !EIA->getCond()->EvaluateWithSubstitution(
6720 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6721 return EIA;
6722
6723 if (!Result.isInt() || !Result.getInt().getBoolValue())
6724 return EIA;
6725 }
6726 return nullptr;
6727}
6728
6729template <typename CheckFn>
6730static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6731 bool ArgDependent, SourceLocation Loc,
6732 CheckFn &&IsSuccessful) {
6733 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6734 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6735 if (ArgDependent == DIA->getArgDependent())
6736 Attrs.push_back(DIA);
6737 }
6738
6739 // Common case: No diagnose_if attributes, so we can quit early.
6740 if (Attrs.empty())
6741 return false;
6742
6743 auto WarningBegin = std::stable_partition(
6744 Attrs.begin(), Attrs.end(),
6745 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6746
6747 // Note that diagnose_if attributes are late-parsed, so they appear in the
6748 // correct order (unlike enable_if attributes).
6749 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6750 IsSuccessful);
6751 if (ErrAttr != WarningBegin) {
6752 const DiagnoseIfAttr *DIA = *ErrAttr;
6753 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6754 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6755 << DIA->getParent() << DIA->getCond()->getSourceRange();
6756 return true;
6757 }
6758
6759 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6760 if (IsSuccessful(DIA)) {
6761 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6762 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6763 << DIA->getParent() << DIA->getCond()->getSourceRange();
6764 }
6765
6766 return false;
6767}
6768
6769bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6770 const Expr *ThisArg,
6771 ArrayRef<const Expr *> Args,
6772 SourceLocation Loc) {
6773 return diagnoseDiagnoseIfAttrsWith(
6774 *this, Function, /*ArgDependent=*/true, Loc,
6775 [&](const DiagnoseIfAttr *DIA) {
6776 APValue Result;
6777 // It's sane to use the same Args for any redecl of this function, since
6778 // EvaluateWithSubstitution only cares about the position of each
6779 // argument in the arg list, not the ParmVarDecl* it maps to.
6780 if (!DIA->getCond()->EvaluateWithSubstitution(
6781 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6782 return false;
6783 return Result.isInt() && Result.getInt().getBoolValue();
6784 });
6785}
6786
6787bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6788 SourceLocation Loc) {
6789 return diagnoseDiagnoseIfAttrsWith(
6790 *this, ND, /*ArgDependent=*/false, Loc,
6791 [&](const DiagnoseIfAttr *DIA) {
6792 bool Result;
6793 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6794 Result;
6795 });
6796}
6797
6798/// Add all of the function declarations in the given function set to
6799/// the overload candidate set.
6800void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6801 ArrayRef<Expr *> Args,
6802 OverloadCandidateSet &CandidateSet,
6803 TemplateArgumentListInfo *ExplicitTemplateArgs,
6804 bool SuppressUserConversions,
6805 bool PartialOverloading,
6806 bool FirstArgumentIsBase) {
6807 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6808 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6809 ArrayRef<Expr *> FunctionArgs = Args;
6810
6811 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6812 FunctionDecl *FD =
6813 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6814
6815 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6816 QualType ObjectType;
6817 Expr::Classification ObjectClassification;
6818 if (Args.size() > 0) {
6819 if (Expr *E = Args[0]) {
6820 // Use the explicit base to restrict the lookup:
6821 ObjectType = E->getType();
6822 // Pointers in the object arguments are implicitly dereferenced, so we
6823 // always classify them as l-values.
6824 if (!ObjectType.isNull() && ObjectType->isPointerType())
6825 ObjectClassification = Expr::Classification::makeSimpleLValue();
6826 else
6827 ObjectClassification = E->Classify(Context);
6828 } // .. else there is an implicit base.
6829 FunctionArgs = Args.slice(1);
6830 }
6831 if (FunTmpl) {
6832 AddMethodTemplateCandidate(
6833 FunTmpl, F.getPair(),
6834 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6835 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6836 FunctionArgs, CandidateSet, SuppressUserConversions,
6837 PartialOverloading);
6838 } else {
6839 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6840 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6841 ObjectClassification, FunctionArgs, CandidateSet,
6842 SuppressUserConversions, PartialOverloading);
6843 }
6844 } else {
6845 // This branch handles both standalone functions and static methods.
6846
6847 // Slice the first argument (which is the base) when we access
6848 // static method as non-static.
6849 if (Args.size() > 0 &&
6850 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6851 !isa<CXXConstructorDecl>(FD)))) {
6852 assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)->
isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "clang/lib/Sema/SemaOverload.cpp", 6852, __extension__ __PRETTY_FUNCTION__
))
;
6853 FunctionArgs = Args.slice(1);
6854 }
6855 if (FunTmpl) {
6856 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6857 ExplicitTemplateArgs, FunctionArgs,
6858 CandidateSet, SuppressUserConversions,
6859 PartialOverloading);
6860 } else {
6861 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6862 SuppressUserConversions, PartialOverloading);
6863 }
6864 }
6865 }
6866}
6867
6868/// AddMethodCandidate - Adds a named decl (which is some kind of
6869/// method) as a method candidate to the given overload set.
6870void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6871 Expr::Classification ObjectClassification,
6872 ArrayRef<Expr *> Args,
6873 OverloadCandidateSet &CandidateSet,
6874 bool SuppressUserConversions,
6875 OverloadCandidateParamOrder PO) {
6876 NamedDecl *Decl = FoundDecl.getDecl();
6877 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6878
6879 if (isa<UsingShadowDecl>(Decl))
6880 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6881
6882 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6883 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "clang/lib/Sema/SemaOverload.cpp", 6884, __extension__ __PRETTY_FUNCTION__
))
6884 "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "clang/lib/Sema/SemaOverload.cpp", 6884, __extension__ __PRETTY_FUNCTION__
))
;
6885 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6886 /*ExplicitArgs*/ nullptr, ObjectType,
6887 ObjectClassification, Args, CandidateSet,
6888 SuppressUserConversions, false, PO);
6889 } else {
6890 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6891 ObjectType, ObjectClassification, Args, CandidateSet,
6892 SuppressUserConversions, false, None, PO);
6893 }
6894}
6895
6896/// AddMethodCandidate - Adds the given C++ member function to the set
6897/// of candidate functions, using the given function call arguments
6898/// and the object argument (@c Object). For example, in a call
6899/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6900/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6901/// allow user-defined conversions via constructors or conversion
6902/// operators.
6903void
6904Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6905 CXXRecordDecl *ActingContext, QualType ObjectType,
6906 Expr::Classification ObjectClassification,
6907 ArrayRef<Expr *> Args,
6908 OverloadCandidateSet &CandidateSet,
6909 bool SuppressUserConversions,
6910 bool PartialOverloading,
6911 ConversionSequenceList EarlyConversions,
6912 OverloadCandidateParamOrder PO) {
6913 const FunctionProtoType *Proto
6914 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6915 assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "clang/lib/Sema/SemaOverload.cpp", 6915, __extension__ __PRETTY_FUNCTION__
))
;
6916 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "clang/lib/Sema/SemaOverload.cpp", 6917, __extension__ __PRETTY_FUNCTION__
))
6917 "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "clang/lib/Sema/SemaOverload.cpp", 6917, __extension__ __PRETTY_FUNCTION__
))
;
6918
6919 if (!CandidateSet.isNewCandidate(Method, PO))
6920 return;
6921
6922 // C++11 [class.copy]p23: [DR1402]
6923 // A defaulted move assignment operator that is defined as deleted is
6924 // ignored by overload resolution.
6925 if (Method->isDefaulted() && Method->isDeleted() &&
6926 Method->isMoveAssignmentOperator())
6927 return;
6928
6929 // Overload resolution is always an unevaluated context.
6930 EnterExpressionEvaluationContext Unevaluated(
6931 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6932
6933 // Add this candidate
6934 OverloadCandidate &Candidate =
6935 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6936 Candidate.FoundDecl = FoundDecl;
6937 Candidate.Function = Method;
6938 Candidate.RewriteKind =
6939 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6940 Candidate.IsSurrogate = false;
6941 Candidate.IgnoreObjectArgument = false;
6942 Candidate.ExplicitCallArguments = Args.size();
6943
6944 unsigned NumParams = Proto->getNumParams();
6945
6946 // (C++ 13.3.2p2): A candidate function having fewer than m
6947 // parameters is viable only if it has an ellipsis in its parameter
6948 // list (8.3.5).
6949 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6950 !Proto->isVariadic() &&
6951 shouldEnforceArgLimit(PartialOverloading, Method)) {
6952 Candidate.Viable = false;
6953 Candidate.FailureKind = ovl_fail_too_many_arguments;
6954 return;
6955 }
6956
6957 // (C++ 13.3.2p2): A candidate function having more than m parameters
6958 // is viable only if the (m+1)st parameter has a default argument
6959 // (8.3.6). For the purposes of overload resolution, the
6960 // parameter list is truncated on the right, so that there are
6961 // exactly m parameters.
6962 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6963 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6964 // Not enough arguments.
6965 Candidate.Viable = false;
6966 Candidate.FailureKind = ovl_fail_too_few_arguments;
6967 return;
6968 }
6969
6970 Candidate.Viable = true;
6971
6972 if (Method->isStatic() || ObjectType.isNull())
6973 // The implicit object argument is ignored.
6974 Candidate.IgnoreObjectArgument = true;
6975 else {
6976 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6977 // Determine the implicit conversion sequence for the object
6978 // parameter.
6979 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6980 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6981 Method, ActingContext);
6982 if (Candidate.Conversions[ConvIdx].isBad()) {
6983 Candidate.Viable = false;
6984 Candidate.FailureKind = ovl_fail_bad_conversion;
6985 return;
6986 }
6987 }
6988
6989 // (CUDA B.1): Check for invalid calls between targets.
6990 if (getLangOpts().CUDA)
6991 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6992 if (!IsAllowedCUDACall(Caller, Method)) {
6993 Candidate.Viable = false;
6994 Candidate.FailureKind = ovl_fail_bad_target;
6995 return;
6996 }
6997
6998 if (Method->getTrailingRequiresClause()) {
6999 ConstraintSatisfaction Satisfaction;
7000 if (CheckFunctionConstraints(Method, Satisfaction) ||
7001 !Satisfaction.IsSatisfied) {
7002 Candidate.Viable = false;
7003 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7004 return;
7005 }
7006 }
7007
7008 // Determine the implicit conversion sequences for each of the
7009 // arguments.
7010 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7011 unsigned ConvIdx =
7012 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7013 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7014 // We already formed a conversion sequence for this parameter during
7015 // template argument deduction.
7016 } else if (ArgIdx < NumParams) {
7017 // (C++ 13.3.2p3): for F to be a viable function, there shall
7018 // exist for each argument an implicit conversion sequence
7019 // (13.3.3.1) that converts that argument to the corresponding
7020 // parameter of F.
7021 QualType ParamType = Proto->getParamType(ArgIdx);
7022 Candidate.Conversions[ConvIdx]
7023 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7024 SuppressUserConversions,
7025 /*InOverloadResolution=*/true,
7026 /*AllowObjCWritebackConversion=*/
7027 getLangOpts().ObjCAutoRefCount);
7028 if (Candidate.Conversions[ConvIdx].isBad()) {
7029 Candidate.Viable = false;
7030 Candidate.FailureKind = ovl_fail_bad_conversion;
7031 return;
7032 }
7033 } else {
7034 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7035 // argument for which there is no corresponding parameter is
7036 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7037 Candidate.Conversions[ConvIdx].setEllipsis();
7038 }
7039 }
7040
7041 if (EnableIfAttr *FailedAttr =
7042 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7043 Candidate.Viable = false;
7044 Candidate.FailureKind = ovl_fail_enable_if;
7045 Candidate.DeductionFailure.Data = FailedAttr;
7046 return;
7047 }
7048
7049 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7050 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7051 Candidate.Viable = false;
7052 Candidate.FailureKind = ovl_non_default_multiversion_function;
7053 }
7054}
7055
7056/// Add a C++ member function template as a candidate to the candidate
7057/// set, using template argument deduction to produce an appropriate member
7058/// function template specialization.
7059void Sema::AddMethodTemplateCandidate(
7060 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7061 CXXRecordDecl *ActingContext,
7062 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7063 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7064 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7065 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7066 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7067 return;
7068
7069 // C++ [over.match.funcs]p7:
7070 // In each case where a candidate is a function template, candidate
7071 // function template specializations are generated using template argument
7072 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7073 // candidate functions in the usual way.113) A given name can refer to one
7074 // or more function templates and also to a set of overloaded non-template
7075 // functions. In such a case, the candidate functions generated from each
7076 // function template are combined with the set of non-template candidate
7077 // functions.
7078 TemplateDeductionInfo Info(CandidateSet.getLocation());
7079 FunctionDecl *Specialization = nullptr;
7080 ConversionSequenceList Conversions;
7081 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7082 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7083 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7084 return CheckNonDependentConversions(
7085 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7086 SuppressUserConversions, ActingContext, ObjectType,
7087 ObjectClassification, PO);
7088 })) {
7089 OverloadCandidate &Candidate =
7090 CandidateSet.addCandidate(Conversions.size(), Conversions);
7091 Candidate.FoundDecl = FoundDecl;
7092 Candidate.Function = MethodTmpl->getTemplatedDecl();
7093 Candidate.Viable = false;
7094 Candidate.RewriteKind =
7095 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7096 Candidate.IsSurrogate = false;
7097 Candidate.IgnoreObjectArgument =
7098 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7099 ObjectType.isNull();
7100 Candidate.ExplicitCallArguments = Args.size();
7101 if (Result == TDK_NonDependentConversionFailure)
7102 Candidate.FailureKind = ovl_fail_bad_conversion;
7103 else {
7104 Candidate.FailureKind = ovl_fail_bad_deduction;
7105 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7106 Info);
7107 }
7108 return;
7109 }
7110
7111 // Add the function template specialization produced by template argument
7112 // deduction as a candidate.
7113 assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7113, __extension__ __PRETTY_FUNCTION__
))
;
7114 assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "clang/lib/Sema/SemaOverload.cpp", 7115, __extension__ __PRETTY_FUNCTION__
))
7115 "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "clang/lib/Sema/SemaOverload.cpp", 7115, __extension__ __PRETTY_FUNCTION__
))
;
7116 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7117 ActingContext, ObjectType, ObjectClassification, Args,
7118 CandidateSet, SuppressUserConversions, PartialOverloading,
7119 Conversions, PO);
7120}
7121
7122/// Determine whether a given function template has a simple explicit specifier
7123/// or a non-value-dependent explicit-specification that evaluates to true.
7124static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7125 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7126}
7127
7128/// Add a C++ function template specialization as a candidate
7129/// in the candidate set, using template argument deduction to produce
7130/// an appropriate function template specialization.
7131void Sema::AddTemplateOverloadCandidate(
7132 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7133 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7134 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7135 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7136 OverloadCandidateParamOrder PO) {
7137 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7138 return;
7139
7140 // If the function template has a non-dependent explicit specification,
7141 // exclude it now if appropriate; we are not permitted to perform deduction
7142 // and substitution in this case.
7143 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7144 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7145 Candidate.FoundDecl = FoundDecl;
7146 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7147 Candidate.Viable = false;
7148 Candidate.FailureKind = ovl_fail_explicit;
7149 return;
7150 }
7151
7152 // C++ [over.match.funcs]p7:
7153 // In each case where a candidate is a function template, candidate
7154 // function template specializations are generated using template argument
7155 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7156 // candidate functions in the usual way.113) A given name can refer to one
7157 // or more function templates and also to a set of overloaded non-template
7158 // functions. In such a case, the candidate functions generated from each
7159 // function template are combined with the set of non-template candidate
7160 // functions.
7161 TemplateDeductionInfo Info(CandidateSet.getLocation());
7162 FunctionDecl *Specialization = nullptr;
7163 ConversionSequenceList Conversions;
7164 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7165 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7166 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7167 return CheckNonDependentConversions(
7168 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7169 SuppressUserConversions, nullptr, QualType(), {}, PO);
7170 })) {
7171 OverloadCandidate &Candidate =
7172 CandidateSet.addCandidate(Conversions.size(), Conversions);
7173 Candidate.FoundDecl = FoundDecl;
7174 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7175 Candidate.Viable = false;
7176 Candidate.RewriteKind =
7177 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7178 Candidate.IsSurrogate = false;
7179 Candidate.IsADLCandidate = IsADLCandidate;
7180 // Ignore the object argument if there is one, since we don't have an object
7181 // type.
7182 Candidate.IgnoreObjectArgument =
7183 isa<CXXMethodDecl>(Candidate.Function) &&
7184 !isa<CXXConstructorDecl>(Candidate.Function);
7185 Candidate.ExplicitCallArguments = Args.size();
7186 if (Result == TDK_NonDependentConversionFailure)
7187 Candidate.FailureKind = ovl_fail_bad_conversion;
7188 else {
7189 Candidate.FailureKind = ovl_fail_bad_deduction;
7190 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7191 Info);
7192 }
7193 return;
7194 }
7195
7196 // Add the function template specialization produced by template argument
7197 // deduction as a candidate.
7198 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7198, __extension__ __PRETTY_FUNCTION__
))
;
7199 AddOverloadCandidate(
7200 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7201 PartialOverloading, AllowExplicit,
7202 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7203}
7204
7205/// Check that implicit conversion sequences can be formed for each argument
7206/// whose corresponding parameter has a non-dependent type, per DR1391's
7207/// [temp.deduct.call]p10.
7208bool Sema::CheckNonDependentConversions(
7209 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7210 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7211 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7212 CXXRecordDecl *ActingContext, QualType ObjectType,
7213 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7214 // FIXME: The cases in which we allow explicit conversions for constructor
7215 // arguments never consider calling a constructor template. It's not clear
7216 // that is correct.
7217 const bool AllowExplicit = false;
7218
7219 auto *FD = FunctionTemplate->getTemplatedDecl();
7220 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7221 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7222 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7223
7224 Conversions =
7225 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7226
7227 // Overload resolution is always an unevaluated context.
7228 EnterExpressionEvaluationContext Unevaluated(
7229 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7230
7231 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7232 // require that, but this check should never result in a hard error, and
7233 // overload resolution is permitted to sidestep instantiations.
7234 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7235 !ObjectType.isNull()) {
7236 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7237 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7238 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7239 Method, ActingContext);
7240 if (Conversions[ConvIdx].isBad())
7241 return true;
7242 }
7243
7244 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7245 ++I) {
7246 QualType ParamType = ParamTypes[I];
7247 if (!ParamType->isDependentType()) {
7248 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7249 ? 0
7250 : (ThisConversions + I);
7251 Conversions[ConvIdx]
7252 = TryCopyInitialization(*this, Args[I], ParamType,
7253 SuppressUserConversions,
7254 /*InOverloadResolution=*/true,
7255 /*AllowObjCWritebackConversion=*/
7256 getLangOpts().ObjCAutoRefCount,
7257 AllowExplicit);
7258 if (Conversions[ConvIdx].isBad())
7259 return true;
7260 }
7261 }
7262
7263 return false;
7264}
7265
7266/// Determine whether this is an allowable conversion from the result
7267/// of an explicit conversion operator to the expected type, per C++
7268/// [over.match.conv]p1 and [over.match.ref]p1.
7269///
7270/// \param ConvType The return type of the conversion function.
7271///
7272/// \param ToType The type we are converting to.
7273///
7274/// \param AllowObjCPointerConversion Allow a conversion from one
7275/// Objective-C pointer to another.
7276///
7277/// \returns true if the conversion is allowable, false otherwise.
7278static bool isAllowableExplicitConversion(Sema &S,
7279 QualType ConvType, QualType ToType,
7280 bool AllowObjCPointerConversion) {
7281 QualType ToNonRefType = ToType.getNonReferenceType();
7282
7283 // Easy case: the types are the same.
7284 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7285 return true;
7286
7287 // Allow qualification conversions.
7288 bool ObjCLifetimeConversion;
7289 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7290 ObjCLifetimeConversion))
7291 return true;
7292
7293 // If we're not allowed to consider Objective-C pointer conversions,
7294 // we're done.
7295 if (!AllowObjCPointerConversion)
7296 return false;
7297
7298 // Is this an Objective-C pointer conversion?
7299 bool IncompatibleObjC = false;
7300 QualType ConvertedType;
7301 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7302 IncompatibleObjC);
7303}
7304
7305/// AddConversionCandidate - Add a C++ conversion function as a
7306/// candidate in the candidate set (C++ [over.match.conv],
7307/// C++ [over.match.copy]). From is the expression we're converting from,
7308/// and ToType is the type that we're eventually trying to convert to
7309/// (which may or may not be the same type as the type that the
7310/// conversion function produces).
7311void Sema::AddConversionCandidate(
7312 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7313 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7314 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7315 bool AllowExplicit, bool AllowResultConversion) {
7316 assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "clang/lib/Sema/SemaOverload.cpp", 7317, __extension__ __PRETTY_FUNCTION__
))
7317 "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "clang/lib/Sema/SemaOverload.cpp", 7317, __extension__ __PRETTY_FUNCTION__
))
;
7318 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7319 if (!CandidateSet.isNewCandidate(Conversion))
7320 return;
7321
7322 // If the conversion function has an undeduced return type, trigger its
7323 // deduction now.
7324 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7325 if (DeduceReturnType(Conversion, From->getExprLoc()))
7326 return;
7327 ConvType = Conversion->getConversionType().getNonReferenceType();
7328 }
7329
7330 // If we don't allow any conversion of the result type, ignore conversion
7331 // functions that don't convert to exactly (possibly cv-qualified) T.
7332 if (!AllowResultConversion &&
7333 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7334 return;
7335
7336 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7337 // operator is only a candidate if its return type is the target type or
7338 // can be converted to the target type with a qualification conversion.
7339 //
7340 // FIXME: Include such functions in the candidate list and explain why we
7341 // can't select them.
7342 if (Conversion->isExplicit() &&
7343 !isAllowableExplicitConversion(*this, ConvType, ToType,
7344 AllowObjCConversionOnExplicit))
7345 return;
7346
7347 // Overload resolution is always an unevaluated context.
7348 EnterExpressionEvaluationContext Unevaluated(
7349 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7350
7351 // Add this candidate
7352 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7353 Candidate.FoundDecl = FoundDecl;
7354 Candidate.Function = Conversion;
7355 Candidate.IsSurrogate = false;
7356 Candidate.IgnoreObjectArgument = false;
7357 Candidate.FinalConversion.setAsIdentityConversion();
7358 Candidate.FinalConversion.setFromType(ConvType);
7359 Candidate.FinalConversion.setAllToTypes(ToType);
7360 Candidate.Viable = true;
7361 Candidate.ExplicitCallArguments = 1;
7362
7363 // Explicit functions are not actually candidates at all if we're not
7364 // allowing them in this context, but keep them around so we can point
7365 // to them in diagnostics.
7366 if (!AllowExplicit && Conversion->isExplicit()) {
7367 Candidate.Viable = false;
7368 Candidate.FailureKind = ovl_fail_explicit;
7369 return;
7370 }
7371
7372 // C++ [over.match.funcs]p4:
7373 // For conversion functions, the function is considered to be a member of
7374 // the class of the implicit implied object argument for the purpose of
7375 // defining the type of the implicit object parameter.
7376 //
7377 // Determine the implicit conversion sequence for the implicit
7378 // object parameter.
7379 QualType ImplicitParamType = From->getType();
7380 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7381 ImplicitParamType = FromPtrType->getPointeeType();
7382 CXXRecordDecl *ConversionContext
7383 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7384
7385 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7386 *this, CandidateSet.getLocation(), From->getType(),
7387 From->Classify(Context), Conversion, ConversionContext);
7388
7389 if (Candidate.Conversions[0].isBad()) {
7390 Candidate.Viable = false;
7391 Candidate.FailureKind = ovl_fail_bad_conversion;
7392 return;
7393 }
7394
7395 if (Conversion->getTrailingRequiresClause()) {
7396 ConstraintSatisfaction Satisfaction;
7397 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7398 !Satisfaction.IsSatisfied) {
7399 Candidate.Viable = false;
7400 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7401 return;
7402 }
7403 }
7404
7405 // We won't go through a user-defined type conversion function to convert a
7406 // derived to base as such conversions are given Conversion Rank. They only
7407 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7408 QualType FromCanon
7409 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7410 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7411 if (FromCanon == ToCanon ||
7412 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7413 Candidate.Viable = false;
7414 Candidate.FailureKind = ovl_fail_trivial_conversion;
7415 return;
7416 }
7417
7418 // To determine what the conversion from the result of calling the
7419 // conversion function to the type we're eventually trying to
7420 // convert to (ToType), we need to synthesize a call to the
7421 // conversion function and attempt copy initialization from it. This
7422 // makes sure that we get the right semantics with respect to
7423 // lvalues/rvalues and the type. Fortunately, we can allocate this
7424 // call on the stack and we don't need its arguments to be
7425 // well-formed.
7426 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7427 VK_LValue, From->getBeginLoc());
7428 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7429 Context.getPointerType(Conversion->getType()),
7430 CK_FunctionToPointerDecay, &ConversionRef,
7431 VK_PRValue, FPOptionsOverride());
7432
7433 QualType ConversionType = Conversion->getConversionType();
7434 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7435 Candidate.Viable = false;
7436 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7437 return;
7438 }
7439
7440 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7441
7442 // Note that it is safe to allocate CallExpr on the stack here because
7443 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7444 // allocator).
7445 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7446
7447 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7448 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7449 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7450
7451 ImplicitConversionSequence ICS =
7452 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7453 /*SuppressUserConversions=*/true,
7454 /*InOverloadResolution=*/false,
7455 /*AllowObjCWritebackConversion=*/false);
7456
7457 switch (ICS.getKind()) {
7458 case ImplicitConversionSequence::StandardConversion:
7459 Candidate.FinalConversion = ICS.Standard;
7460
7461 // C++ [over.ics.user]p3:
7462 // If the user-defined conversion is specified by a specialization of a
7463 // conversion function template, the second standard conversion sequence
7464 // shall have exact match rank.
7465 if (Conversion->getPrimaryTemplate() &&
7466 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7467 Candidate.Viable = false;
7468 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7469 return;
7470 }
7471
7472 // C++0x [dcl.init.ref]p5:
7473 // In the second case, if the reference is an rvalue reference and
7474 // the second standard conversion sequence of the user-defined
7475 // conversion sequence includes an lvalue-to-rvalue conversion, the
7476 // program is ill-formed.
7477 if (ToType->isRValueReferenceType() &&
7478 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7479 Candidate.Viable = false;
7480 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7481 return;
7482 }
7483 break;
7484
7485 case ImplicitConversionSequence::BadConversion:
7486 Candidate.Viable = false;
7487 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7488 return;
7489
7490 default:
7491 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "clang/lib/Sema/SemaOverload.cpp", 7492)
7492 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "clang/lib/Sema/SemaOverload.cpp", 7492)
;
7493 }
7494
7495 if (EnableIfAttr *FailedAttr =
7496 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7497 Candidate.Viable = false;
7498 Candidate.FailureKind = ovl_fail_enable_if;
7499 Candidate.DeductionFailure.Data = FailedAttr;
7500 return;
7501 }
7502
7503 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7504 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7505 Candidate.Viable = false;
7506 Candidate.FailureKind = ovl_non_default_multiversion_function;
7507 }
7508}
7509
7510/// Adds a conversion function template specialization
7511/// candidate to the overload set, using template argument deduction
7512/// to deduce the template arguments of the conversion function
7513/// template from the type that we are converting to (C++
7514/// [temp.deduct.conv]).
7515void Sema::AddTemplateConversionCandidate(
7516 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7517 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7518 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7519 bool AllowExplicit, bool AllowResultConversion) {
7520 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "clang/lib/Sema/SemaOverload.cpp", 7521, __extension__ __PRETTY_FUNCTION__
))
7521 "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "clang/lib/Sema/SemaOverload.cpp", 7521, __extension__ __PRETTY_FUNCTION__
))
;
7522
7523 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7524 return;
7525
7526 // If the function template has a non-dependent explicit specification,
7527 // exclude it now if appropriate; we are not permitted to perform deduction
7528 // and substitution in this case.
7529 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7530 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7531 Candidate.FoundDecl = FoundDecl;
7532 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7533 Candidate.Viable = false;
7534 Candidate.FailureKind = ovl_fail_explicit;
7535 return;
7536 }
7537
7538 TemplateDeductionInfo Info(CandidateSet.getLocation());
7539 CXXConversionDecl *Specialization = nullptr;
7540 if (TemplateDeductionResult Result
7541 = DeduceTemplateArguments(FunctionTemplate, ToType,
7542 Specialization, Info)) {
7543 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7544 Candidate.FoundDecl = FoundDecl;
7545 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7546 Candidate.Viable = false;
7547 Candidate.FailureKind = ovl_fail_bad_deduction;
7548 Candidate.IsSurrogate = false;
7549 Candidate.IgnoreObjectArgument = false;
7550 Candidate.ExplicitCallArguments = 1;
7551 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7552 Info);
7553 return;
7554 }
7555
7556 // Add the conversion function template specialization produced by
7557 // template argument deduction as a candidate.
7558 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "clang/lib/Sema/SemaOverload.cpp", 7558, __extension__ __PRETTY_FUNCTION__
))
;
7559 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7560 CandidateSet, AllowObjCConversionOnExplicit,
7561 AllowExplicit, AllowResultConversion);
7562}
7563
7564/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7565/// converts the given @c Object to a function pointer via the
7566/// conversion function @c Conversion, and then attempts to call it
7567/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7568/// the type of function that we'll eventually be calling.
7569void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7570 DeclAccessPair FoundDecl,
7571 CXXRecordDecl *ActingContext,
7572 const FunctionProtoType *Proto,
7573 Expr *Object,
7574 ArrayRef<Expr *> Args,
7575 OverloadCandidateSet& CandidateSet) {
7576 if (!CandidateSet.isNewCandidate(Conversion))
7577 return;
7578
7579 // Overload resolution is always an unevaluated context.
7580 EnterExpressionEvaluationContext Unevaluated(
7581 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7582
7583 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7584 Candidate.FoundDecl = FoundDecl;
7585 Candidate.Function = nullptr;
7586 Candidate.Surrogate = Conversion;
7587 Candidate.Viable = true;
7588 Candidate.IsSurrogate = true;
7589 Candidate.IgnoreObjectArgument = false;
7590 Candidate.ExplicitCallArguments = Args.size();
7591
7592 // Determine the implicit conversion sequence for the implicit
7593 // object parameter.
7594 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7595 *this, CandidateSet.getLocation(), Object->getType(),
7596 Object->Classify(Context), Conversion, ActingContext);
7597 if (ObjectInit.isBad()) {
7598 Candidate.Viable = false;
7599 Candidate.FailureKind = ovl_fail_bad_conversion;
7600 Candidate.Conversions[0] = ObjectInit;
7601 return;
7602 }
7603
7604 // The first conversion is actually a user-defined conversion whose
7605 // first conversion is ObjectInit's standard conversion (which is
7606 // effectively a reference binding). Record it as such.
7607 Candidate.Conversions[0].setUserDefined();
7608 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7609 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7610 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7611 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7612 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7613 Candidate.Conversions[0].UserDefined.After
7614 = Candidate.Conversions[0].UserDefined.Before;
7615 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7616
7617 // Find the
7618 unsigned NumParams = Proto->getNumParams();
7619
7620 // (C++ 13.3.2p2): A candidate function having fewer than m
7621 // parameters is viable only if it has an ellipsis in its parameter
7622 // list (8.3.5).
7623 if (Args.size() > NumParams && !Proto->isVariadic()) {
7624 Candidate.Viable = false;
7625 Candidate.FailureKind = ovl_fail_too_many_arguments;
7626 return;
7627 }
7628
7629 // Function types don't have any default arguments, so just check if
7630 // we have enough arguments.
7631 if (Args.size() < NumParams) {
7632 // Not enough arguments.
7633 Candidate.Viable = false;
7634 Candidate.FailureKind = ovl_fail_too_few_arguments;
7635 return;
7636 }
7637
7638 // Determine the implicit conversion sequences for each of the
7639 // arguments.
7640 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7641 if (ArgIdx < NumParams) {
7642 // (C++ 13.3.2p3): for F to be a viable function, there shall
7643 // exist for each argument an implicit conversion sequence
7644 // (13.3.3.1) that converts that argument to the corresponding
7645 // parameter of F.
7646 QualType ParamType = Proto->getParamType(ArgIdx);
7647 Candidate.Conversions[ArgIdx + 1]
7648 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7649 /*SuppressUserConversions=*/false,
7650 /*InOverloadResolution=*/false,
7651 /*AllowObjCWritebackConversion=*/
7652 getLangOpts().ObjCAutoRefCount);
7653 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7654 Candidate.Viable = false;
7655 Candidate.FailureKind = ovl_fail_bad_conversion;
7656 return;
7657 }
7658 } else {
7659 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7660 // argument for which there is no corresponding parameter is
7661 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7662 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7663 }
7664 }
7665
7666 if (EnableIfAttr *FailedAttr =
7667 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7668 Candidate.Viable = false;
7669 Candidate.FailureKind = ovl_fail_enable_if;
7670 Candidate.DeductionFailure.Data = FailedAttr;
7671 return;
7672 }
7673}
7674
7675/// Add all of the non-member operator function declarations in the given
7676/// function set to the overload candidate set.
7677void Sema::AddNonMemberOperatorCandidates(
7678 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7679 OverloadCandidateSet &CandidateSet,
7680 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7681 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7682 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7683 ArrayRef<Expr *> FunctionArgs = Args;
7684
7685 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7686 FunctionDecl *FD =
7687 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7688
7689 // Don't consider rewritten functions if we're not rewriting.
7690 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7691 continue;
7692
7693 assert(!isa<CXXMethodDecl>(FD) &&(static_cast <bool> (!isa<CXXMethodDecl>(FD) &&
"unqualified operator lookup found a member function") ? void
(0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "clang/lib/Sema/SemaOverload.cpp", 7694, __extension__ __PRETTY_FUNCTION__
))
7694 "unqualified operator lookup found a member function")(static_cast <bool> (!isa<CXXMethodDecl>(FD) &&
"unqualified operator lookup found a member function") ? void
(0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "clang/lib/Sema/SemaOverload.cpp", 7694, __extension__ __PRETTY_FUNCTION__
))
;
7695
7696 if (FunTmpl) {
7697 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7698 FunctionArgs, CandidateSet);
7699 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7700 AddTemplateOverloadCandidate(
7701 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7702 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7703 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7704 } else {
7705 if (ExplicitTemplateArgs)
7706 continue;
7707 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7708 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7709 AddOverloadCandidate(FD, F.getPair(),
7710 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7711 false, false, true, false, ADLCallKind::NotADL,
7712 None, OverloadCandidateParamOrder::Reversed);
7713 }
7714 }
7715}
7716
7717/// Add overload candidates for overloaded operators that are
7718/// member functions.
7719///
7720/// Add the overloaded operator candidates that are member functions
7721/// for the operator Op that was used in an operator expression such
7722/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7723/// CandidateSet will store the added overload candidates. (C++
7724/// [over.match.oper]).
7725void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7726 SourceLocation OpLoc,
7727 ArrayRef<Expr *> Args,
7728 OverloadCandidateSet &CandidateSet,
7729 OverloadCandidateParamOrder PO) {
7730 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7731
7732 // C++ [over.match.oper]p3:
7733 // For a unary operator @ with an operand of a type whose
7734 // cv-unqualified version is T1, and for a binary operator @ with
7735 // a left operand of a type whose cv-unqualified version is T1 and
7736 // a right operand of a type whose cv-unqualified version is T2,
7737 // three sets of candidate functions, designated member
7738 // candidates, non-member candidates and built-in candidates, are
7739 // constructed as follows:
7740 QualType T1 = Args[0]->getType();
7741
7742 // -- If T1 is a complete class type or a class currently being
7743 // defined, the set of member candidates is the result of the
7744 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7745 // the set of member candidates is empty.
7746 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7747 // Complete the type if it can be completed.
7748 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7749 return;
7750 // If the type is neither complete nor being defined, bail out now.
7751 if (!T1Rec->getDecl()->getDefinition())
7752 return;
7753
7754 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7755 LookupQualifiedName(Operators, T1Rec->getDecl());
7756 Operators.suppressDiagnostics();
7757
7758 for (LookupResult::iterator Oper = Operators.begin(),
7759 OperEnd = Operators.end();
7760 Oper != OperEnd;
7761 ++Oper)
7762 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7763 Args[0]->Classify(Context), Args.slice(1),
7764 CandidateSet, /*SuppressUserConversion=*/false, PO);
7765 }
7766}
7767
7768/// AddBuiltinCandidate - Add a candidate for a built-in
7769/// operator. ResultTy and ParamTys are the result and parameter types
7770/// of the built-in candidate, respectively. Args and NumArgs are the
7771/// arguments being passed to the candidate. IsAssignmentOperator
7772/// should be true when this built-in candidate is an assignment
7773/// operator. NumContextualBoolArguments is the number of arguments
7774/// (at the beginning of the argument list) that will be contextually
7775/// converted to bool.
7776void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7777 OverloadCandidateSet& CandidateSet,
7778 bool IsAssignmentOperator,
7779 unsigned NumContextualBoolArguments) {
7780 // Overload resolution is always an unevaluated context.
7781 EnterExpressionEvaluationContext Unevaluated(
7782 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7783
7784 // Add this candidate
7785 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7786 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7787 Candidate.Function = nullptr;
7788 Candidate.IsSurrogate = false;
7789 Candidate.IgnoreObjectArgument = false;
7790 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7791
7792 // Determine the implicit conversion sequences for each of the
7793 // arguments.
7794 Candidate.Viable = true;
7795 Candidate.ExplicitCallArguments = Args.size();
7796 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7797 // C++ [over.match.oper]p4:
7798 // For the built-in assignment operators, conversions of the
7799 // left operand are restricted as follows:
7800 // -- no temporaries are introduced to hold the left operand, and
7801 // -- no user-defined conversions are applied to the left
7802 // operand to achieve a type match with the left-most
7803 // parameter of a built-in candidate.
7804 //
7805 // We block these conversions by turning off user-defined
7806 // conversions, since that is the only way that initialization of
7807 // a reference to a non-class type can occur from something that
7808 // is not of the same type.
7809 if (ArgIdx < NumContextualBoolArguments) {
7810 assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "clang/lib/Sema/SemaOverload.cpp", 7811, __extension__ __PRETTY_FUNCTION__
))
7811 "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "clang/lib/Sema/SemaOverload.cpp", 7811, __extension__ __PRETTY_FUNCTION__
))
;
7812 Candidate.Conversions[ArgIdx]
7813 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7814 } else {
7815 Candidate.Conversions[ArgIdx]
7816 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7817 ArgIdx == 0 && IsAssignmentOperator,
7818 /*InOverloadResolution=*/false,
7819 /*AllowObjCWritebackConversion=*/
7820 getLangOpts().ObjCAutoRefCount);
7821 }
7822 if (Candidate.Conversions[ArgIdx].isBad()) {
7823 Candidate.Viable = false;
7824 Candidate.FailureKind = ovl_fail_bad_conversion;
7825 break;
7826 }
7827 }
7828}
7829
7830namespace {
7831
7832/// BuiltinCandidateTypeSet - A set of types that will be used for the
7833/// candidate operator functions for built-in operators (C++
7834/// [over.built]). The types are separated into pointer types and
7835/// enumeration types.
7836class BuiltinCandidateTypeSet {
7837 /// TypeSet - A set of types.
7838 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7839 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7840
7841 /// PointerTypes - The set of pointer types that will be used in the
7842 /// built-in candidates.
7843 TypeSet PointerTypes;
7844
7845 /// MemberPointerTypes - The set of member pointer types that will be
7846 /// used in the built-in candidates.
7847 TypeSet MemberPointerTypes;
7848
7849 /// EnumerationTypes - The set of enumeration types that will be
7850 /// used in the built-in candidates.
7851 TypeSet EnumerationTypes;
7852
7853 /// The set of vector types that will be used in the built-in
7854 /// candidates.
7855 TypeSet VectorTypes;
7856
7857 /// The set of matrix types that will be used in the built-in
7858 /// candidates.
7859 TypeSet MatrixTypes;
7860
7861 /// A flag indicating non-record types are viable candidates
7862 bool HasNonRecordTypes;
7863
7864 /// A flag indicating whether either arithmetic or enumeration types
7865 /// were present in the candidate set.
7866 bool HasArithmeticOrEnumeralTypes;
7867
7868 /// A flag indicating whether the nullptr type was present in the
7869 /// candidate set.
7870 bool HasNullPtrType;
7871
7872 /// Sema - The semantic analysis instance where we are building the
7873 /// candidate type set.
7874 Sema &SemaRef;
7875
7876 /// Context - The AST context in which we will build the type sets.
7877 ASTContext &Context;
7878
7879 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7880 const Qualifiers &VisibleQuals);
7881 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7882
7883public:
7884 /// iterator - Iterates through the types that are part of the set.
7885 typedef TypeSet::iterator iterator;
7886
7887 BuiltinCandidateTypeSet(Sema &SemaRef)
7888 : HasNonRecordTypes(false),
7889 HasArithmeticOrEnumeralTypes(false),
7890 HasNullPtrType(false),
7891 SemaRef(SemaRef),
7892 Context(SemaRef.Context) { }
7893
7894 void AddTypesConvertedFrom(QualType Ty,
7895 SourceLocation Loc,
7896 bool AllowUserConversions,
7897 bool AllowExplicitConversions,
7898 const Qualifiers &VisibleTypeConversionsQuals);
7899
7900 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7901 llvm::iterator_range<iterator> member_pointer_types() {
7902 return MemberPointerTypes;
7903 }
7904 llvm::iterator_range<iterator> enumeration_types() {
7905 return EnumerationTypes;
7906 }
7907 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7908 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7909
7910 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7911 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7912 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7913 bool hasNullPtrType() const { return HasNullPtrType; }
7914};
7915
7916} // end anonymous namespace
7917
7918/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7919/// the set of pointer types along with any more-qualified variants of
7920/// that type. For example, if @p Ty is "int const *", this routine
7921/// will add "int const *", "int const volatile *", "int const
7922/// restrict *", and "int const volatile restrict *" to the set of
7923/// pointer types. Returns true if the add of @p Ty itself succeeded,
7924/// false otherwise.
7925///
7926/// FIXME: what to do about extended qualifiers?
7927bool
7928BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7929 const Qualifiers &VisibleQuals) {
7930
7931 // Insert this type.
7932 if (!PointerTypes.insert(Ty))
7933 return false;
7934
7935 QualType PointeeTy;
7936 const PointerType *PointerTy = Ty->getAs<PointerType>();
7937 bool buildObjCPtr = false;
7938 if (!PointerTy) {
7939 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7940 PointeeTy = PTy->getPointeeType();
7941 buildObjCPtr = true;
7942 } else {
7943 PointeeTy = PointerTy->getPointeeType();
7944 }
7945
7946 // Don't add qualified variants of arrays. For one, they're not allowed
7947 // (the qualifier would sink to the element type), and for another, the
7948 // only overload situation where it matters is subscript or pointer +- int,
7949 // and those shouldn't have qualifier variants anyway.
7950 if (PointeeTy->isArrayType())
7951 return true;
7952
7953 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7954 bool hasVolatile = VisibleQuals.hasVolatile();
7955 bool hasRestrict = VisibleQuals.hasRestrict();
7956
7957 // Iterate through all strict supersets of BaseCVR.
7958 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7959 if ((CVR | BaseCVR) != CVR) continue;
7960 // Skip over volatile if no volatile found anywhere in the types.
7961 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7962
7963 // Skip over restrict if no restrict found anywhere in the types, or if
7964 // the type cannot be restrict-qualified.
7965 if ((CVR & Qualifiers::Restrict) &&
7966 (!hasRestrict ||
7967 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7968 continue;
7969
7970 // Build qualified pointee type.
7971 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7972
7973 // Build qualified pointer type.
7974 QualType QPointerTy;
7975 if (!buildObjCPtr)
7976 QPointerTy = Context.getPointerType(QPointeeTy);
7977 else
7978 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7979
7980 // Insert qualified pointer type.
7981 PointerTypes.insert(QPointerTy);
7982 }
7983
7984 return true;
7985}
7986
7987/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7988/// to the set of pointer types along with any more-qualified variants of
7989/// that type. For example, if @p Ty is "int const *", this routine
7990/// will add "int const *", "int const volatile *", "int const
7991/// restrict *", and "int const volatile restrict *" to the set of
7992/// pointer types. Returns true if the add of @p Ty itself succeeded,
7993/// false otherwise.
7994///
7995/// FIXME: what to do about extended qualifiers?
7996bool
7997BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7998 QualType Ty) {
7999 // Insert this type.
8000 if (!MemberPointerTypes.insert(Ty))
8001 return false;
8002
8003 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8004 assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!"
) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "clang/lib/Sema/SemaOverload.cpp", 8004, __extension__ __PRETTY_FUNCTION__
))
;
8005
8006 QualType PointeeTy = PointerTy->getPointeeType();
8007 // Don't add qualified variants of arrays. For one, they're not allowed
8008 // (the qualifier would sink to the element type), and for another, the
8009 // only overload situation where it matters is subscript or pointer +- int,
8010 // and those shouldn't have qualifier variants anyway.
8011 if (PointeeTy->isArrayType())
8012 return true;
8013 const Type *ClassTy = PointerTy->getClass();
8014
8015 // Iterate through all strict supersets of the pointee type's CVR
8016 // qualifiers.
8017 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8018 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8019 if ((CVR | BaseCVR) != CVR) continue;
8020
8021 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8022 MemberPointerTypes.insert(
8023 Context.getMemberPointerType(QPointeeTy, ClassTy));
8024 }
8025
8026 return true;
8027}
8028
8029/// AddTypesConvertedFrom - Add each of the types to which the type @p
8030/// Ty can be implicit converted to the given set of @p Types. We're
8031/// primarily interested in pointer types and enumeration types. We also
8032/// take member pointer types, for the conditional operator.
8033/// AllowUserConversions is true if we should look at the conversion
8034/// functions of a class type, and AllowExplicitConversions if we
8035/// should also include the explicit conversion functions of a class
8036/// type.
8037void
8038BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8039 SourceLocation Loc,
8040 bool AllowUserConversions,
8041 bool AllowExplicitConversions,
8042 const Qualifiers &VisibleQuals) {
8043 // Only deal with canonical types.
8044 Ty = Context.getCanonicalType(Ty);
8045
8046 // Look through reference types; they aren't part of the type of an
8047 // expression for the purposes of conversions.
8048 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8049 Ty = RefTy->getPointeeType();
8050
8051 // If we're dealing with an array type, decay to the pointer.
8052 if (Ty->isArrayType())
8053 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8054
8055 // Otherwise, we don't care about qualifiers on the type.
8056 Ty = Ty.getLocalUnqualifiedType();
8057
8058 // Flag if we ever add a non-record type.
8059 const RecordType *TyRec = Ty->getAs<RecordType>();
8060 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8061
8062 // Flag if we encounter an arithmetic type.
8063 HasArithmeticOrEnumeralTypes =
8064 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8065
8066 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8067 PointerTypes.insert(Ty);
8068 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8069 // Insert our type, and its more-qualified variants, into the set
8070 // of types.
8071 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8072 return;
8073 } else if (Ty->isMemberPointerType()) {
8074 // Member pointers are far easier, since the pointee can't be converted.
8075 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8076 return;
8077 } else if (Ty->isEnumeralType()) {
8078 HasArithmeticOrEnumeralTypes = true;
8079 EnumerationTypes.insert(Ty);
8080 } else if (Ty->isVectorType()) {
8081 // We treat vector types as arithmetic types in many contexts as an
8082 // extension.
8083 HasArithmeticOrEnumeralTypes = true;
8084 VectorTypes.insert(Ty);
8085 } else if (Ty->isMatrixType()) {
8086 // Similar to vector types, we treat vector types as arithmetic types in
8087 // many contexts as an extension.
8088 HasArithmeticOrEnumeralTypes = true;
8089 MatrixTypes.insert(Ty);
8090 } else if (Ty->isNullPtrType()) {
8091 HasNullPtrType = true;
8092 } else if (AllowUserConversions && TyRec) {
8093 // No conversion functions in incomplete types.
8094 if (!SemaRef.isCompleteType(Loc, Ty))
8095 return;
8096
8097 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8098 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8099 if (isa<UsingShadowDecl>(D))
8100 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8101
8102 // Skip conversion function templates; they don't tell us anything
8103 // about which builtin types we can convert to.
8104 if (isa<FunctionTemplateDecl>(D))
8105 continue;
8106
8107 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8108 if (AllowExplicitConversions || !Conv->isExplicit()) {
8109 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8110 VisibleQuals);
8111 }
8112 }
8113 }
8114}
8115/// Helper function for adjusting address spaces for the pointer or reference
8116/// operands of builtin operators depending on the argument.
8117static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8118 Expr *Arg) {
8119 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8120}
8121
8122/// Helper function for AddBuiltinOperatorCandidates() that adds
8123/// the volatile- and non-volatile-qualified assignment operators for the
8124/// given type to the candidate set.
8125static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8126 QualType T,
8127 ArrayRef<Expr *> Args,
8128 OverloadCandidateSet &CandidateSet) {
8129 QualType ParamTypes[2];
8130
8131 // T& operator=(T&, T)
8132 ParamTypes[0] = S.Context.getLValueReferenceType(
8133 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8134 ParamTypes[1] = T;
8135 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8136 /*IsAssignmentOperator=*/true);
8137
8138 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8139 // volatile T& operator=(volatile T&, T)
8140 ParamTypes[0] = S.Context.getLValueReferenceType(
8141 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8142 Args[0]));
8143 ParamTypes[1] = T;
8144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8145 /*IsAssignmentOperator=*/true);
8146 }
8147}
8148
8149/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8150/// if any, found in visible type conversion functions found in ArgExpr's type.
8151static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8152 Qualifiers VRQuals;
8153 const RecordType *TyRec;
8154 if (const MemberPointerType *RHSMPType =
8155 ArgExpr->getType()->getAs<MemberPointerType>())
8156 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8157 else
8158 TyRec = ArgExpr->getType()->getAs<RecordType>();
8159 if (!TyRec) {
8160 // Just to be safe, assume the worst case.
8161 VRQuals.addVolatile();
8162 VRQuals.addRestrict();
8163 return VRQuals;
8164 }
8165
8166 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8167 if (!ClassDecl->hasDefinition())
8168 return VRQuals;
8169
8170 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8171 if (isa<UsingShadowDecl>(D))
8172 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8173 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8174 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8175 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8176 CanTy = ResTypeRef->getPointeeType();
8177 // Need to go down the pointer/mempointer chain and add qualifiers
8178 // as see them.
8179 bool done = false;
8180 while (!done) {
8181 if (CanTy.isRestrictQualified())
8182 VRQuals.addRestrict();
8183 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8184 CanTy = ResTypePtr->getPointeeType();
8185 else if (const MemberPointerType *ResTypeMPtr =
8186 CanTy->getAs<MemberPointerType>())
8187 CanTy = ResTypeMPtr->getPointeeType();
8188 else
8189 done = true;
8190 if (CanTy.isVolatileQualified())
8191 VRQuals.addVolatile();
8192 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8193 return VRQuals;
8194 }
8195 }
8196 }
8197 return VRQuals;
8198}
8199
8200namespace {
8201
8202/// Helper class to manage the addition of builtin operator overload
8203/// candidates. It provides shared state and utility methods used throughout
8204/// the process, as well as a helper method to add each group of builtin
8205/// operator overloads from the standard to a candidate set.
8206class BuiltinOperatorOverloadBuilder {
8207 // Common instance state available to all overload candidate addition methods.
8208 Sema &S;
8209 ArrayRef<Expr *> Args;
8210 Qualifiers VisibleTypeConversionsQuals;
8211 bool HasArithmeticOrEnumeralCandidateType;
8212 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8213 OverloadCandidateSet &CandidateSet;
8214
8215 static constexpr int ArithmeticTypesCap = 24;
8216 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8217
8218 // Define some indices used to iterate over the arithmetic types in
8219 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8220 // types are that preserved by promotion (C++ [over.built]p2).
8221 unsigned FirstIntegralType,
8222 LastIntegralType;
8223 unsigned FirstPromotedIntegralType,
8224 LastPromotedIntegralType;
8225 unsigned FirstPromotedArithmeticType,
8226 LastPromotedArithmeticType;
8227 unsigned NumArithmeticTypes;
8228
8229 void InitArithmeticTypes() {
8230 // Start of promoted types.
8231 FirstPromotedArithmeticType = 0;
8232 ArithmeticTypes.push_back(S.Context.FloatTy);
8233 ArithmeticTypes.push_back(S.Context.DoubleTy);
8234 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8235 if (S.Context.getTargetInfo().hasFloat128Type())
8236 ArithmeticTypes.push_back(S.Context.Float128Ty);
8237 if (S.Context.getTargetInfo().hasIbm128Type())
8238 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8239
8240 // Start of integral types.
8241 FirstIntegralType = ArithmeticTypes.size();
8242 FirstPromotedIntegralType = ArithmeticTypes.size();
8243 ArithmeticTypes.push_back(S.Context.IntTy);
8244 ArithmeticTypes.push_back(S.Context.LongTy);
8245 ArithmeticTypes.push_back(S.Context.LongLongTy);
8246 if (S.Context.getTargetInfo().hasInt128Type() ||
8247 (S.Context.getAuxTargetInfo() &&
8248 S.Context.getAuxTargetInfo()->hasInt128Type()))
8249 ArithmeticTypes.push_back(S.Context.Int128Ty);
8250 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8251 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8252 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8253 if (S.Context.getTargetInfo().hasInt128Type() ||
8254 (S.Context.getAuxTargetInfo() &&
8255 S.Context.getAuxTargetInfo()->hasInt128Type()))
8256 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8257 LastPromotedIntegralType = ArithmeticTypes.size();
8258 LastPromotedArithmeticType = ArithmeticTypes.size();
8259 // End of promoted types.
8260
8261 ArithmeticTypes.push_back(S.Context.BoolTy);
8262 ArithmeticTypes.push_back(S.Context.CharTy);
8263 ArithmeticTypes.push_back(S.Context.WCharTy);
8264 if (S.Context.getLangOpts().Char8)
8265 ArithmeticTypes.push_back(S.Context.Char8Ty);
8266 ArithmeticTypes.push_back(S.Context.Char16Ty);
8267 ArithmeticTypes.push_back(S.Context.Char32Ty);
8268 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8269 ArithmeticTypes.push_back(S.Context.ShortTy);
8270 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8271 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8272 LastIntegralType = ArithmeticTypes.size();
8273 NumArithmeticTypes = ArithmeticTypes.size();
8274 // End of integral types.
8275 // FIXME: What about complex? What about half?
8276
8277 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "clang/lib/Sema/SemaOverload.cpp", 8278, __extension__ __PRETTY_FUNCTION__
))
8278 "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "clang/lib/Sema/SemaOverload.cpp", 8278, __extension__ __PRETTY_FUNCTION__
))
;
8279 }
8280
8281 /// Helper method to factor out the common pattern of adding overloads
8282 /// for '++' and '--' builtin operators.
8283 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8284 bool HasVolatile,
8285 bool HasRestrict) {
8286 QualType ParamTypes[2] = {
8287 S.Context.getLValueReferenceType(CandidateTy),
8288 S.Context.IntTy
8289 };
8290
8291 // Non-volatile version.
8292 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8293
8294 // Use a heuristic to reduce number of builtin candidates in the set:
8295 // add volatile version only if there are conversions to a volatile type.
8296 if (HasVolatile) {
8297 ParamTypes[0] =
8298 S.Context.getLValueReferenceType(
8299 S.Context.getVolatileType(CandidateTy));
8300 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8301 }
8302
8303 // Add restrict version only if there are conversions to a restrict type
8304 // and our candidate type is a non-restrict-qualified pointer.
8305 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8306 !CandidateTy.isRestrictQualified()) {
8307 ParamTypes[0]
8308 = S.Context.getLValueReferenceType(
8309 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8310 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8311
8312 if (HasVolatile) {
8313 ParamTypes[0]
8314 = S.Context.getLValueReferenceType(
8315 S.Context.getCVRQualifiedType(CandidateTy,
8316 (Qualifiers::Volatile |
8317 Qualifiers::Restrict)));
8318 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8319 }
8320 }
8321
8322 }
8323
8324 /// Helper to add an overload candidate for a binary builtin with types \p L
8325 /// and \p R.
8326 void AddCandidate(QualType L, QualType R) {
8327 QualType LandR[2] = {L, R};
8328 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8329 }
8330
8331public:
8332 BuiltinOperatorOverloadBuilder(
8333 Sema &S, ArrayRef<Expr *> Args,
8334 Qualifiers VisibleTypeConversionsQuals,
8335 bool HasArithmeticOrEnumeralCandidateType,
8336 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8337 OverloadCandidateSet &CandidateSet)
8338 : S(S), Args(Args),
8339 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8340 HasArithmeticOrEnumeralCandidateType(
8341 HasArithmeticOrEnumeralCandidateType),
8342 CandidateTypes(CandidateTypes),
8343 CandidateSet(CandidateSet) {
8344
8345 InitArithmeticTypes();
8346 }
8347
8348 // Increment is deprecated for bool since C++17.
8349 //
8350 // C++ [over.built]p3:
8351 //
8352 // For every pair (T, VQ), where T is an arithmetic type other
8353 // than bool, and VQ is either volatile or empty, there exist
8354 // candidate operator functions of the form
8355 //
8356 // VQ T& operator++(VQ T&);
8357 // T operator++(VQ T&, int);
8358 //
8359 // C++ [over.built]p4:
8360 //
8361 // For every pair (T, VQ), where T is an arithmetic type other
8362 // than bool, and VQ is either volatile or empty, there exist
8363 // candidate operator functions of the form
8364 //
8365 // VQ T& operator--(VQ T&);
8366 // T operator--(VQ T&, int);
8367 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8368 if (!HasArithmeticOrEnumeralCandidateType)
8369 return;
8370
8371 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8372 const auto TypeOfT = ArithmeticTypes[Arith];
8373 if (TypeOfT == S.Context.BoolTy) {
8374 if (Op == OO_MinusMinus)
8375 continue;
8376 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8377 continue;
8378 }
8379 addPlusPlusMinusMinusStyleOverloads(
8380 TypeOfT,
8381 VisibleTypeConversionsQuals.hasVolatile(),
8382 VisibleTypeConversionsQuals.hasRestrict());
8383 }
8384 }
8385
8386 // C++ [over.built]p5:
8387 //
8388 // For every pair (T, VQ), where T is a cv-qualified or
8389 // cv-unqualified object type, and VQ is either volatile or
8390 // empty, there exist candidate operator functions of the form
8391 //
8392 // T*VQ& operator++(T*VQ&);
8393 // T*VQ& operator--(T*VQ&);
8394 // T* operator++(T*VQ&, int);
8395 // T* operator--(T*VQ&, int);
8396 void addPlusPlusMinusMinusPointerOverloads() {
8397 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8398 // Skip pointer types that aren't pointers to object types.
8399 if (!PtrTy->getPointeeType()->isObjectType())
8400 continue;
8401
8402 addPlusPlusMinusMinusStyleOverloads(
8403 PtrTy,
8404 (!PtrTy.isVolatileQualified() &&
8405 VisibleTypeConversionsQuals.hasVolatile()),
8406 (!PtrTy.isRestrictQualified() &&
8407 VisibleTypeConversionsQuals.hasRestrict()));
8408 }
8409 }
8410
8411 // C++ [over.built]p6:
8412 // For every cv-qualified or cv-unqualified object type T, there
8413 // exist candidate operator functions of the form
8414 //
8415 // T& operator*(T*);
8416 //
8417 // C++ [over.built]p7:
8418 // For every function type T that does not have cv-qualifiers or a
8419 // ref-qualifier, there exist candidate operator functions of the form
8420 // T& operator*(T*);
8421 void addUnaryStarPointerOverloads() {
8422 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8423 QualType PointeeTy = ParamTy->getPointeeType();
8424 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8425 continue;
8426
8427 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8428 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8429 continue;
8430
8431 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8432 }
8433 }
8434
8435 // C++ [over.built]p9:
8436 // For every promoted arithmetic type T, there exist candidate
8437 // operator functions of the form
8438 //
8439 // T operator+(T);
8440 // T operator-(T);
8441 void addUnaryPlusOrMinusArithmeticOverloads() {
8442 if (!HasArithmeticOrEnumeralCandidateType)
8443 return;
8444
8445 for (unsigned Arith = FirstPromotedArithmeticType;
8446 Arith < LastPromotedArithmeticType; ++Arith) {
8447 QualType ArithTy = ArithmeticTypes[Arith];
8448 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8449 }
8450
8451 // Extension: We also add these operators for vector types.
8452 for (QualType VecTy : CandidateTypes[0].vector_types())
8453 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8454 }
8455
8456 // C++ [over.built]p8:
8457 // For every type T, there exist candidate operator functions of
8458 // the form
8459 //
8460 // T* operator+(T*);
8461 void addUnaryPlusPointerOverloads() {
8462 for (QualType ParamTy : CandidateTypes[0].pointer_types())
8463 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8464 }
8465
8466 // C++ [over.built]p10:
8467 // For every promoted integral type T, there exist candidate
8468 // operator functions of the form
8469 //
8470 // T operator~(T);
8471 void addUnaryTildePromotedIntegralOverloads() {
8472 if (!HasArithmeticOrEnumeralCandidateType)
8473 return;
8474
8475 for (unsigned Int = FirstPromotedIntegralType;
8476 Int < LastPromotedIntegralType; ++Int) {
8477 QualType IntTy = ArithmeticTypes[Int];
8478 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8479 }
8480
8481 // Extension: We also add this operator for vector types.
8482 for (QualType VecTy : CandidateTypes[0].vector_types())
8483 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8484 }
8485
8486 // C++ [over.match.oper]p16:
8487 // For every pointer to member type T or type std::nullptr_t, there
8488 // exist candidate operator functions of the form
8489 //
8490 // bool operator==(T,T);
8491 // bool operator!=(T,T);
8492 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8493 /// Set of (canonical) types that we've already handled.
8494 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8495
8496 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8497 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8498 // Don't add the same builtin candidate twice.
8499 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8500 continue;
8501
8502 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8503 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8504 }
8505
8506 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8507 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8508 if (AddedTypes.insert(NullPtrTy).second) {
8509 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8510 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8511 }
8512 }
8513 }
8514 }
8515
8516 // C++ [over.built]p15:
8517 //
8518 // For every T, where T is an enumeration type or a pointer type,
8519 // there exist candidate operator functions of the form
8520 //
8521 // bool operator<(T, T);
8522 // bool operator>(T, T);
8523 // bool operator<=(T, T);
8524 // bool operator>=(T, T);
8525 // bool operator==(T, T);
8526 // bool operator!=(T, T);
8527 // R operator<=>(T, T)
8528 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8529 // C++ [over.match.oper]p3:
8530 // [...]the built-in candidates include all of the candidate operator
8531 // functions defined in 13.6 that, compared to the given operator, [...]
8532 // do not have the same parameter-type-list as any non-template non-member
8533 // candidate.
8534 //
8535 // Note that in practice, this only affects enumeration types because there
8536 // aren't any built-in candidates of record type, and a user-defined operator
8537 // must have an operand of record or enumeration type. Also, the only other
8538 // overloaded operator with enumeration arguments, operator=,
8539 // cannot be overloaded for enumeration types, so this is the only place
8540 // where we must suppress candidates like this.
8541 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8542 UserDefinedBinaryOperators;
8543
8544 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8545 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8546 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8547 CEnd = CandidateSet.end();
8548 C != CEnd; ++C) {
8549 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8550 continue;
8551
8552 if (C->Function->isFunctionTemplateSpecialization())
8553 continue;
8554
8555 // We interpret "same parameter-type-list" as applying to the
8556 // "synthesized candidate, with the order of the two parameters
8557 // reversed", not to the original function.
8558 bool Reversed = C->isReversed();
8559 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8560 ->getType()
8561 .getUnqualifiedType();
8562 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8563 ->getType()
8564 .getUnqualifiedType();
8565
8566 // Skip if either parameter isn't of enumeral type.
8567 if (!FirstParamType->isEnumeralType() ||
8568 !SecondParamType->isEnumeralType())
8569 continue;
8570
8571 // Add this operator to the set of known user-defined operators.
8572 UserDefinedBinaryOperators.insert(
8573 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8574 S.Context.getCanonicalType(SecondParamType)));
8575 }
8576 }
8577 }
8578
8579 /// Set of (canonical) types that we've already handled.
8580 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8581
8582 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8583 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8584 // Don't add the same builtin candidate twice.
8585 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8586 continue;
8587 if (IsSpaceship && PtrTy->isFunctionPointerType())
8588 continue;
8589
8590 QualType ParamTypes[2] = {PtrTy, PtrTy};
8591 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8592 }
8593 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8594 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8595
8596 // Don't add the same builtin candidate twice, or if a user defined
8597 // candidate exists.
8598 if (!AddedTypes.insert(CanonType).second ||
8599 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8600 CanonType)))
8601 continue;
8602 QualType ParamTypes[2] = {EnumTy, EnumTy};
8603 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8604 }
8605 }
8606 }
8607
8608 // C++ [over.built]p13:
8609 //
8610 // For every cv-qualified or cv-unqualified object type T
8611 // there exist candidate operator functions of the form
8612 //
8613 // T* operator+(T*, ptrdiff_t);
8614 // T& operator[](T*, ptrdiff_t); [BELOW]
8615 // T* operator-(T*, ptrdiff_t);
8616 // T* operator+(ptrdiff_t, T*);
8617 // T& operator[](ptrdiff_t, T*); [BELOW]
8618 //
8619 // C++ [over.built]p14:
8620 //
8621 // For every T, where T is a pointer to object type, there
8622 // exist candidate operator functions of the form
8623 //
8624 // ptrdiff_t operator-(T, T);
8625 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8626 /// Set of (canonical) types that we've already handled.
8627 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628
8629 for (int Arg = 0; Arg < 2; ++Arg) {
8630 QualType AsymmetricParamTypes[2] = {
8631 S.Context.getPointerDiffType(),
8632 S.Context.getPointerDiffType(),
8633 };
8634 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8635 QualType PointeeTy = PtrTy->getPointeeType();
8636 if (!PointeeTy->isObjectType())
8637 continue;
8638
8639 AsymmetricParamTypes[Arg] = PtrTy;
8640 if (Arg == 0 || Op == OO_Plus) {
8641 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8642 // T* operator+(ptrdiff_t, T*);
8643 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8644 }
8645 if (Op == OO_Minus) {
8646 // ptrdiff_t operator-(T, T);
8647 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8648 continue;
8649
8650 QualType ParamTypes[2] = {PtrTy, PtrTy};
8651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8652 }
8653 }
8654 }
8655 }
8656
8657 // C++ [over.built]p12:
8658 //
8659 // For every pair of promoted arithmetic types L and R, there
8660 // exist candidate operator functions of the form
8661 //
8662 // LR operator*(L, R);
8663 // LR operator/(L, R);
8664 // LR operator+(L, R);
8665 // LR operator-(L, R);
8666 // bool operator<(L, R);
8667 // bool operator>(L, R);
8668 // bool operator<=(L, R);
8669 // bool operator>=(L, R);
8670 // bool operator==(L, R);
8671 // bool operator!=(L, R);
8672 //
8673 // where LR is the result of the usual arithmetic conversions
8674 // between types L and R.
8675 //
8676 // C++ [over.built]p24:
8677 //
8678 // For every pair of promoted arithmetic types L and R, there exist
8679 // candidate operator functions of the form
8680 //
8681 // LR operator?(bool, L, R);
8682 //
8683 // where LR is the result of the usual arithmetic conversions
8684 // between types L and R.
8685 // Our candidates ignore the first parameter.
8686 void addGenericBinaryArithmeticOverloads() {
8687 if (!HasArithmeticOrEnumeralCandidateType)
8688 return;
8689
8690 for (unsigned Left = FirstPromotedArithmeticType;
8691 Left < LastPromotedArithmeticType; ++Left) {
8692 for (unsigned Right = FirstPromotedArithmeticType;
8693 Right < LastPromotedArithmeticType; ++Right) {
8694 QualType LandR[2] = { ArithmeticTypes[Left],
8695 ArithmeticTypes[Right] };
8696 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8697 }
8698 }
8699
8700 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8701 // conditional operator for vector types.
8702 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8703 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8704 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8705 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8706 }
8707 }
8708
8709 /// Add binary operator overloads for each candidate matrix type M1, M2:
8710 /// * (M1, M1) -> M1
8711 /// * (M1, M1.getElementType()) -> M1
8712 /// * (M2.getElementType(), M2) -> M2
8713 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8714 void addMatrixBinaryArithmeticOverloads() {
8715 if (!HasArithmeticOrEnumeralCandidateType)
8716 return;
8717
8718 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8719 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8720 AddCandidate(M1, M1);
8721 }
8722
8723 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8724 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8725 if (!CandidateTypes[0].containsMatrixType(M2))
8726 AddCandidate(M2, M2);
8727 }
8728 }
8729
8730 // C++2a [over.built]p14:
8731 //
8732 // For every integral type T there exists a candidate operator function
8733 // of the form
8734 //
8735 // std::strong_ordering operator<=>(T, T)
8736 //
8737 // C++2a [over.built]p15:
8738 //
8739 // For every pair of floating-point types L and R, there exists a candidate
8740 // operator function of the form
8741 //
8742 // std::partial_ordering operator<=>(L, R);
8743 //
8744 // FIXME: The current specification for integral types doesn't play nice with
8745 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8746 // comparisons. Under the current spec this can lead to ambiguity during
8747 // overload resolution. For example:
8748 //
8749 // enum A : int {a};
8750 // auto x = (a <=> (long)42);
8751 //
8752 // error: call is ambiguous for arguments 'A' and 'long'.
8753 // note: candidate operator<=>(int, int)
8754 // note: candidate operator<=>(long, long)
8755 //
8756 // To avoid this error, this function deviates from the specification and adds
8757 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8758 // arithmetic types (the same as the generic relational overloads).
8759 //
8760 // For now this function acts as a placeholder.
8761 void addThreeWayArithmeticOverloads() {
8762 addGenericBinaryArithmeticOverloads();
8763 }
8764
8765 // C++ [over.built]p17:
8766 //
8767 // For every pair of promoted integral types L and R, there
8768 // exist candidate operator functions of the form
8769 //
8770 // LR operator%(L, R);
8771 // LR operator&(L, R);
8772 // LR operator^(L, R);
8773 // LR operator|(L, R);
8774 // L operator<<(L, R);
8775 // L operator>>(L, R);
8776 //
8777 // where LR is the result of the usual arithmetic conversions
8778 // between types L and R.
8779 void addBinaryBitwiseArithmeticOverloads() {
8780 if (!HasArithmeticOrEnumeralCandidateType)
8781 return;
8782
8783 for (unsigned Left = FirstPromotedIntegralType;
8784 Left < LastPromotedIntegralType; ++Left) {
8785 for (unsigned Right = FirstPromotedIntegralType;
8786 Right < LastPromotedIntegralType; ++Right) {
8787 QualType LandR[2] = { ArithmeticTypes[Left],
8788 ArithmeticTypes[Right] };
8789 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8790 }
8791 }
8792 }
8793
8794 // C++ [over.built]p20:
8795 //
8796 // For every pair (T, VQ), where T is an enumeration or
8797 // pointer to member type and VQ is either volatile or
8798 // empty, there exist candidate operator functions of the form
8799 //
8800 // VQ T& operator=(VQ T&, T);
8801 void addAssignmentMemberPointerOrEnumeralOverloads() {
8802 /// Set of (canonical) types that we've already handled.
8803 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8804
8805 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8806 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8807 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8808 continue;
8809
8810 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8811 }
8812
8813 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8814 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8815 continue;
8816
8817 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8818 }
8819 }
8820 }
8821
8822 // C++ [over.built]p19:
8823 //
8824 // For every pair (T, VQ), where T is any type and VQ is either
8825 // volatile or empty, there exist candidate operator functions
8826 // of the form
8827 //
8828 // T*VQ& operator=(T*VQ&, T*);
8829 //
8830 // C++ [over.built]p21:
8831 //
8832 // For every pair (T, VQ), where T is a cv-qualified or
8833 // cv-unqualified object type and VQ is either volatile or
8834 // empty, there exist candidate operator functions of the form
8835 //
8836 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8837 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8838 void addAssignmentPointerOverloads(bool isEqualOp) {
8839 /// Set of (canonical) types that we've already handled.
8840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8841
8842 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8843 // If this is operator=, keep track of the builtin candidates we added.
8844 if (isEqualOp)
8845 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8846 else if (!PtrTy->getPointeeType()->isObjectType())
8847 continue;
8848
8849 // non-volatile version
8850 QualType ParamTypes[2] = {
8851 S.Context.getLValueReferenceType(PtrTy),
8852 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8853 };
8854 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8855 /*IsAssignmentOperator=*/ isEqualOp);
8856
8857 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8858 VisibleTypeConversionsQuals.hasVolatile();
8859 if (NeedVolatile) {
8860 // volatile version
8861 ParamTypes[0] =
8862 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8864 /*IsAssignmentOperator=*/isEqualOp);
8865 }
8866
8867 if (!PtrTy.isRestrictQualified() &&
8868 VisibleTypeConversionsQuals.hasRestrict()) {
8869 // restrict version
8870 ParamTypes[0] =
8871 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8872 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8873 /*IsAssignmentOperator=*/isEqualOp);
8874
8875 if (NeedVolatile) {
8876 // volatile restrict version
8877 ParamTypes[0] =
8878 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8879 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8880 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8881 /*IsAssignmentOperator=*/isEqualOp);
8882 }
8883 }
8884 }
8885
8886 if (isEqualOp) {
8887 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8888 // Make sure we don't add the same candidate twice.
8889 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8890 continue;
8891
8892 QualType ParamTypes[2] = {
8893 S.Context.getLValueReferenceType(PtrTy),
8894 PtrTy,
8895 };
8896
8897 // non-volatile version
8898 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8899 /*IsAssignmentOperator=*/true);
8900
8901 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8902 VisibleTypeConversionsQuals.hasVolatile();
8903 if (NeedVolatile) {
8904 // volatile version
8905 ParamTypes[0] = S.Context.getLValueReferenceType(
8906 S.Context.getVolatileType(PtrTy));
8907 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8908 /*IsAssignmentOperator=*/true);
8909 }
8910
8911 if (!PtrTy.isRestrictQualified() &&
8912 VisibleTypeConversionsQuals.hasRestrict()) {
8913 // restrict version
8914 ParamTypes[0] = S.Context.getLValueReferenceType(
8915 S.Context.getRestrictType(PtrTy));
8916 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8917 /*IsAssignmentOperator=*/true);
8918
8919 if (NeedVolatile) {
8920 // volatile restrict version
8921 ParamTypes[0] =
8922 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8923 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8924 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8925 /*IsAssignmentOperator=*/true);
8926 }
8927 }
8928 }
8929 }
8930 }
8931
8932 // C++ [over.built]p18:
8933 //
8934 // For every triple (L, VQ, R), where L is an arithmetic type,
8935 // VQ is either volatile or empty, and R is a promoted
8936 // arithmetic type, there exist candidate operator functions of
8937 // the form
8938 //
8939 // VQ L& operator=(VQ L&, R);
8940 // VQ L& operator*=(VQ L&, R);
8941 // VQ L& operator/=(VQ L&, R);
8942 // VQ L& operator+=(VQ L&, R);
8943 // VQ L& operator-=(VQ L&, R);
8944 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8945 if (!HasArithmeticOrEnumeralCandidateType)
8946 return;
8947
8948 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8949 for (unsigned Right = FirstPromotedArithmeticType;
8950 Right < LastPromotedArithmeticType; ++Right) {
8951 QualType ParamTypes[2];
8952 ParamTypes[1] = ArithmeticTypes[Right];
8953 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8954 S, ArithmeticTypes[Left], Args[0]);
8955 // Add this built-in operator as a candidate (VQ is empty).
8956 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8957 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8958 /*IsAssignmentOperator=*/isEqualOp);
8959
8960 // Add this built-in operator as a candidate (VQ is 'volatile').
8961 if (VisibleTypeConversionsQuals.hasVolatile()) {
8962 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8963 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8965 /*IsAssignmentOperator=*/isEqualOp);
8966 }
8967 }
8968 }
8969
8970 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8971 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8972 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8973 QualType ParamTypes[2];
8974 ParamTypes[1] = Vec2Ty;
8975 // Add this built-in operator as a candidate (VQ is empty).
8976 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8977 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8978 /*IsAssignmentOperator=*/isEqualOp);
8979
8980 // Add this built-in operator as a candidate (VQ is 'volatile').
8981 if (VisibleTypeConversionsQuals.hasVolatile()) {
8982 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8983 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8984 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8985 /*IsAssignmentOperator=*/isEqualOp);
8986 }
8987 }
8988 }
8989
8990 // C++ [over.built]p22:
8991 //
8992 // For every triple (L, VQ, R), where L is an integral type, VQ
8993 // is either volatile or empty, and R is a promoted integral
8994 // type, there exist candidate operator functions of the form
8995 //
8996 // VQ L& operator%=(VQ L&, R);
8997 // VQ L& operator<<=(VQ L&, R);
8998 // VQ L& operator>>=(VQ L&, R);
8999 // VQ L& operator&=(VQ L&, R);
9000 // VQ L& operator^=(VQ L&, R);
9001 // VQ L& operator|=(VQ L&, R);
9002 void addAssignmentIntegralOverloads() {
9003 if (!HasArithmeticOrEnumeralCandidateType)
9004 return;
9005
9006 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9007 for (unsigned Right = FirstPromotedIntegralType;
9008 Right < LastPromotedIntegralType; ++Right) {
9009 QualType ParamTypes[2];
9010 ParamTypes[1] = ArithmeticTypes[Right];
9011 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9012 S, ArithmeticTypes[Left], Args[0]);
9013 // Add this built-in operator as a candidate (VQ is empty).
9014 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
9015 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9016 if (VisibleTypeConversionsQuals.hasVolatile()) {
9017 // Add this built-in operator as a candidate (VQ is 'volatile').
9018 ParamTypes[0] = LeftBaseTy;
9019 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
9020 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9021 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9022 }
9023 }
9024 }
9025 }
9026
9027 // C++ [over.operator]p23:
9028 //
9029 // There also exist candidate operator functions of the form
9030 //
9031 // bool operator!(bool);
9032 // bool operator&&(bool, bool);
9033 // bool operator||(bool, bool);
9034 void addExclaimOverload() {
9035 QualType ParamTy = S.Context.BoolTy;
9036 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9037 /*IsAssignmentOperator=*/false,
9038 /*NumContextualBoolArguments=*/1);
9039 }
9040 void addAmpAmpOrPipePipeOverload() {
9041 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9042 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9043 /*IsAssignmentOperator=*/false,
9044 /*NumContextualBoolArguments=*/2);
9045 }
9046
9047 // C++ [over.built]p13:
9048 //
9049 // For every cv-qualified or cv-unqualified object type T there
9050 // exist candidate operator functions of the form
9051 //
9052 // T* operator+(T*, ptrdiff_t); [ABOVE]
9053 // T& operator[](T*, ptrdiff_t);
9054 // T* operator-(T*, ptrdiff_t); [ABOVE]
9055 // T* operator+(ptrdiff_t, T*); [ABOVE]
9056 // T& operator[](ptrdiff_t, T*);
9057 void addSubscriptOverloads() {
9058 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9059 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9060 QualType PointeeType = PtrTy->getPointeeType();
9061 if (!PointeeType->isObjectType())
9062 continue;
9063
9064 // T& operator[](T*, ptrdiff_t)
9065 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9066 }
9067
9068 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9069 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9070 QualType PointeeType = PtrTy->getPointeeType();
9071 if (!PointeeType->isObjectType())
9072 continue;
9073
9074 // T& operator[](ptrdiff_t, T*)
9075 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9076 }
9077 }
9078
9079 // C++ [over.built]p11:
9080 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9081 // C1 is the same type as C2 or is a derived class of C2, T is an object
9082 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9083 // there exist candidate operator functions of the form
9084 //
9085 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9086 //
9087 // where CV12 is the union of CV1 and CV2.
9088 void addArrowStarOverloads() {
9089 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9090 QualType C1Ty = PtrTy;
9091 QualType C1;
9092 QualifierCollector Q1;
9093 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9094 if (!isa<RecordType>(C1))
9095 continue;
9096 // heuristic to reduce number of builtin candidates in the set.
9097 // Add volatile/restrict version only if there are conversions to a
9098 // volatile/restrict type.
9099 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9100 continue;
9101 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9102 continue;
9103 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9104 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
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] = {PtrTy, MemPtrTy};
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 (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9140 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9141 continue;
9142
9143 QualType ParamTypes[2] = {PtrTy, PtrTy};
9144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9145 }
9146
9147 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9148 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9149 continue;
9150
9151 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9152 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9153 }
9154
9155 if (S.getLangOpts().CPlusPlus11) {
9156 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9157 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9158 continue;
9159
9160 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9161 continue;
9162
9163 QualType ParamTypes[2] = {EnumTy, EnumTy};
9164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9165 }
9166 }
9167 }
9168 }
9169};
9170
9171} // end anonymous namespace
9172
9173/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9174/// operator overloads to the candidate set (C++ [over.built]), based
9175/// on the operator @p Op and the arguments given. For example, if the
9176/// operator is a binary '+', this routine might add "int
9177/// operator+(int, int)" to cover integer addition.
9178void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9179 SourceLocation OpLoc,
9180 ArrayRef<Expr *> Args,
9181 OverloadCandidateSet &CandidateSet) {
9182 // Find all of the types that the arguments can convert to, but only
9183 // if the operator we're looking at has built-in operator candidates
9184 // that make use of these types. Also record whether we encounter non-record
9185 // candidate types or either arithmetic or enumeral candidate types.
9186 Qualifiers VisibleTypeConversionsQuals;
9187 VisibleTypeConversionsQuals.addConst();
9188 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9189 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9190
9191 bool HasNonRecordCandidateType = false;
9192 bool HasArithmeticOrEnumeralCandidateType = false;
9193 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9195 CandidateTypes.emplace_back(*this);
9196 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9197 OpLoc,
9198 true,
9199 (Op == OO_Exclaim ||
9200 Op == OO_AmpAmp ||
9201 Op == OO_PipePipe),
9202 VisibleTypeConversionsQuals);
9203 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9204 CandidateTypes[ArgIdx].hasNonRecordTypes();
9205 HasArithmeticOrEnumeralCandidateType =
9206 HasArithmeticOrEnumeralCandidateType ||
9207 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9208 }
9209
9210 // Exit early when no non-record types have been added to the candidate set
9211 // for any of the arguments to the operator.
9212 //
9213 // We can't exit early for !, ||, or &&, since there we have always have
9214 // 'bool' overloads.
9215 if (!HasNonRecordCandidateType &&
9216 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9217 return;
9218
9219 // Setup an object to manage the common state for building overloads.
9220 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9221 VisibleTypeConversionsQuals,
9222 HasArithmeticOrEnumeralCandidateType,
9223 CandidateTypes, CandidateSet);
9224
9225 // Dispatch over the operation to add in only those overloads which apply.
9226 switch (Op) {
9227 case OO_None:
9228 case NUM_OVERLOADED_OPERATORS:
9229 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "clang/lib/Sema/SemaOverload.cpp", 9229)
;
9230
9231 case OO_New:
9232 case OO_Delete:
9233 case OO_Array_New:
9234 case OO_Array_Delete:
9235 case OO_Call:
9236 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "clang/lib/Sema/SemaOverload.cpp", 9237)
9237 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "clang/lib/Sema/SemaOverload.cpp", 9237)
;
9238
9239 case OO_Comma:
9240 case OO_Arrow:
9241 case OO_Coawait:
9242 // C++ [over.match.oper]p3:
9243 // -- For the operator ',', the unary operator '&', the
9244 // operator '->', or the operator 'co_await', the
9245 // built-in candidates set is empty.
9246 break;
9247
9248 case OO_Plus: // '+' is either unary or binary
9249 if (Args.size() == 1)
9250 OpBuilder.addUnaryPlusPointerOverloads();
9251 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9252
9253 case OO_Minus: // '-' is either unary or binary
9254 if (Args.size() == 1) {
9255 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9256 } else {
9257 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9258 OpBuilder.addGenericBinaryArithmeticOverloads();
9259 OpBuilder.addMatrixBinaryArithmeticOverloads();
9260 }
9261 break;
9262
9263 case OO_Star: // '*' is either unary or binary
9264 if (Args.size() == 1)
9265 OpBuilder.addUnaryStarPointerOverloads();
9266 else {
9267 OpBuilder.addGenericBinaryArithmeticOverloads();
9268 OpBuilder.addMatrixBinaryArithmeticOverloads();
9269 }
9270 break;
9271
9272 case OO_Slash:
9273 OpBuilder.addGenericBinaryArithmeticOverloads();
9274 break;
9275
9276 case OO_PlusPlus:
9277 case OO_MinusMinus:
9278 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9279 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9280 break;
9281
9282 case OO_EqualEqual:
9283 case OO_ExclaimEqual:
9284 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9285 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9286 OpBuilder.addGenericBinaryArithmeticOverloads();
9287 break;
9288
9289 case OO_Less:
9290 case OO_Greater:
9291 case OO_LessEqual:
9292 case OO_GreaterEqual:
9293 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9294 OpBuilder.addGenericBinaryArithmeticOverloads();
9295 break;
9296
9297 case OO_Spaceship:
9298 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9299 OpBuilder.addThreeWayArithmeticOverloads();
9300 break;
9301
9302 case OO_Percent:
9303 case OO_Caret:
9304 case OO_Pipe:
9305 case OO_LessLess:
9306 case OO_GreaterGreater:
9307 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9308 break;
9309
9310 case OO_Amp: // '&' is either unary or binary
9311 if (Args.size() == 1)
9312 // C++ [over.match.oper]p3:
9313 // -- For the operator ',', the unary operator '&', or the
9314 // operator '->', the built-in candidates set is empty.
9315 break;
9316
9317 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9318 break;
9319
9320 case OO_Tilde:
9321 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9322 break;
9323
9324 case OO_Equal:
9325 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9326 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9327
9328 case OO_PlusEqual:
9329 case OO_MinusEqual:
9330 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9331 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9332
9333 case OO_StarEqual:
9334 case OO_SlashEqual:
9335 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9336 break;
9337
9338 case OO_PercentEqual:
9339 case OO_LessLessEqual:
9340 case OO_GreaterGreaterEqual:
9341 case OO_AmpEqual:
9342 case OO_CaretEqual:
9343 case OO_PipeEqual:
9344 OpBuilder.addAssignmentIntegralOverloads();
9345 break;
9346
9347 case OO_Exclaim:
9348 OpBuilder.addExclaimOverload();
9349 break;
9350
9351 case OO_AmpAmp:
9352 case OO_PipePipe:
9353 OpBuilder.addAmpAmpOrPipePipeOverload();
9354 break;
9355
9356 case OO_Subscript:
9357 OpBuilder.addSubscriptOverloads();
9358 break;
9359
9360 case OO_ArrowStar:
9361 OpBuilder.addArrowStarOverloads();
9362 break;
9363
9364 case OO_Conditional:
9365 OpBuilder.addConditionalOperatorOverloads();
9366 OpBuilder.addGenericBinaryArithmeticOverloads();
9367 break;
9368 }
9369}
9370
9371/// Add function candidates found via argument-dependent lookup
9372/// to the set of overloading candidates.
9373///
9374/// This routine performs argument-dependent name lookup based on the
9375/// given function name (which may also be an operator name) and adds
9376/// all of the overload candidates found by ADL to the overload
9377/// candidate set (C++ [basic.lookup.argdep]).
9378void
9379Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9380 SourceLocation Loc,
9381 ArrayRef<Expr *> Args,
9382 TemplateArgumentListInfo *ExplicitTemplateArgs,
9383 OverloadCandidateSet& CandidateSet,
9384 bool PartialOverloading) {
9385 ADLResult Fns;
9386
9387 // FIXME: This approach for uniquing ADL results (and removing
9388 // redundant candidates from the set) relies on pointer-equality,
9389 // which means we need to key off the canonical decl. However,
9390 // always going back to the canonical decl might not get us the
9391 // right set of default arguments. What default arguments are
9392 // we supposed to consider on ADL candidates, anyway?
9393
9394 // FIXME: Pass in the explicit template arguments?
9395 ArgumentDependentLookup(Name, Loc, Args, Fns);
9396
9397 // Erase all of the candidates we already knew about.
9398 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9399 CandEnd = CandidateSet.end();
9400 Cand != CandEnd; ++Cand)
9401 if (Cand->Function) {
9402 Fns.erase(Cand->Function);
9403 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9404 Fns.erase(FunTmpl);
9405 }
9406
9407 // For each of the ADL candidates we found, add it to the overload
9408 // set.
9409 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9410 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9411
9412 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9413 if (ExplicitTemplateArgs)
9414 continue;
9415
9416 AddOverloadCandidate(
9417 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9418 PartialOverloading, /*AllowExplicit=*/true,
9419 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9420 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9421 AddOverloadCandidate(
9422 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9423 /*SuppressUserConversions=*/false, PartialOverloading,
9424 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9425 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9426 }
9427 } else {
9428 auto *FTD = cast<FunctionTemplateDecl>(*I);
9429 AddTemplateOverloadCandidate(
9430 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9431 /*SuppressUserConversions=*/false, PartialOverloading,
9432 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9433 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9434 Context, FTD->getTemplatedDecl())) {
9435 AddTemplateOverloadCandidate(
9436 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9437 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9438 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9439 OverloadCandidateParamOrder::Reversed);
9440 }
9441 }
9442 }
9443}
9444
9445namespace {
9446enum class Comparison { Equal, Better, Worse };
9447}
9448
9449/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9450/// overload resolution.
9451///
9452/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9453/// Cand1's first N enable_if attributes have precisely the same conditions as
9454/// Cand2's first N enable_if attributes (where N = the number of enable_if
9455/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9456///
9457/// Note that you can have a pair of candidates such that Cand1's enable_if
9458/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9459/// worse than Cand1's.
9460static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9461 const FunctionDecl *Cand2) {
9462 // Common case: One (or both) decls don't have enable_if attrs.
9463 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9464 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9465 if (!Cand1Attr || !Cand2Attr) {
9466 if (Cand1Attr == Cand2Attr)
9467 return Comparison::Equal;
9468 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9469 }
9470
9471 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9472 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9473
9474 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9475 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9476 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9477 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9478
9479 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9480 // has fewer enable_if attributes than Cand2, and vice versa.
9481 if (!Cand1A)
9482 return Comparison::Worse;
9483 if (!Cand2A)
9484 return Comparison::Better;
9485
9486 Cand1ID.clear();
9487 Cand2ID.clear();
9488
9489 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9490 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9491 if (Cand1ID != Cand2ID)
9492 return Comparison::Worse;
9493 }
9494
9495 return Comparison::Equal;
9496}
9497
9498static Comparison
9499isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9500 const OverloadCandidate &Cand2) {
9501 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9502 !Cand2.Function->isMultiVersion())
9503 return Comparison::Equal;
9504
9505 // If both are invalid, they are equal. If one of them is invalid, the other
9506 // is better.
9507 if (Cand1.Function->isInvalidDecl()) {
9508 if (Cand2.Function->isInvalidDecl())
9509 return Comparison::Equal;
9510 return Comparison::Worse;
9511 }
9512 if (Cand2.Function->isInvalidDecl())
9513 return Comparison::Better;
9514
9515 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9516 // cpu_dispatch, else arbitrarily based on the identifiers.
9517 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9518 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9519 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9520 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9521
9522 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9523 return Comparison::Equal;
9524
9525 if (Cand1CPUDisp && !Cand2CPUDisp)
9526 return Comparison::Better;
9527 if (Cand2CPUDisp && !Cand1CPUDisp)
9528 return Comparison::Worse;
9529
9530 if (Cand1CPUSpec && Cand2CPUSpec) {
9531 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9532 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9533 ? Comparison::Better
9534 : Comparison::Worse;
9535
9536 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9537 FirstDiff = std::mismatch(
9538 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9539 Cand2CPUSpec->cpus_begin(),
9540 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9541 return LHS->getName() == RHS->getName();
9542 });
9543
9544 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9546, __extension__ __PRETTY_FUNCTION__
))
9545 "Two different cpu-specific versions should not have the same "(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9546, __extension__ __PRETTY_FUNCTION__
))
9546 "identifier list, otherwise they'd be the same decl!")(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "clang/lib/Sema/SemaOverload.cpp", 9546, __extension__ __PRETTY_FUNCTION__
))
;
9547 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9548 ? Comparison::Better
9549 : Comparison::Worse;
9550 }
9551 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "clang/lib/Sema/SemaOverload.cpp", 9551)
;
9552}
9553
9554/// Compute the type of the implicit object parameter for the given function,
9555/// if any. Returns None if there is no implicit object parameter, and a null
9556/// QualType if there is a 'matches anything' implicit object parameter.
9557static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9558 const FunctionDecl *F) {
9559 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9560 return llvm::None;
9561
9562 auto *M = cast<CXXMethodDecl>(F);
9563 // Static member functions' object parameters match all types.
9564 if (M->isStatic())
9565 return QualType();
9566
9567 QualType T = M->getThisObjectType();
9568 if (M->getRefQualifier() == RQ_RValue)
9569 return Context.getRValueReferenceType(T);
9570 return Context.getLValueReferenceType(T);
9571}
9572
9573static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9574 const FunctionDecl *F2, unsigned NumParams) {
9575 if (declaresSameEntity(F1, F2))
9576 return true;
9577
9578 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9579 if (First) {
9580 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9581 return *T;
9582 }
9583 assert(I < F->getNumParams())(static_cast <bool> (I < F->getNumParams()) ? void
(0) : __assert_fail ("I < F->getNumParams()", "clang/lib/Sema/SemaOverload.cpp"
, 9583, __extension__ __PRETTY_FUNCTION__))
;
9584 return F->getParamDecl(I++)->getType();
9585 };
9586
9587 unsigned I1 = 0, I2 = 0;
9588 for (unsigned I = 0; I != NumParams; ++I) {
9589 QualType T1 = NextParam(F1, I1, I == 0);
9590 QualType T2 = NextParam(F2, I2, I == 0);
9591 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types")(static_cast <bool> (!T1.isNull() && !T2.isNull
() && "Unexpected null param types") ? void (0) : __assert_fail
("!T1.isNull() && !T2.isNull() && \"Unexpected null param types\""
, "clang/lib/Sema/SemaOverload.cpp", 9591, __extension__ __PRETTY_FUNCTION__
))
;
9592 if (!Context.hasSameUnqualifiedType(T1, T2))
9593 return false;
9594 }
9595 return true;
9596}
9597
9598/// isBetterOverloadCandidate - Determines whether the first overload
9599/// candidate is a better candidate than the second (C++ 13.3.3p1).
9600bool clang::isBetterOverloadCandidate(
9601 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9602 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9603 // Define viable functions to be better candidates than non-viable
9604 // functions.
9605 if (!Cand2.Viable)
9606 return Cand1.Viable;
9607 else if (!Cand1.Viable)
9608 return false;
9609
9610 // [CUDA] A function with 'never' preference is marked not viable, therefore
9611 // is never shown up here. The worst preference shown up here is 'wrong side',
9612 // e.g. an H function called by a HD function in device compilation. This is
9613 // valid AST as long as the HD function is not emitted, e.g. it is an inline
9614 // function which is called only by an H function. A deferred diagnostic will
9615 // be triggered if it is emitted. However a wrong-sided function is still
9616 // a viable candidate here.
9617 //
9618 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9619 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9620 // can be emitted, Cand1 is not better than Cand2. This rule should have
9621 // precedence over other rules.
9622 //
9623 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9624 // other rules should be used to determine which is better. This is because
9625 // host/device based overloading resolution is mostly for determining
9626 // viability of a function. If two functions are both viable, other factors
9627 // should take precedence in preference, e.g. the standard-defined preferences
9628 // like argument conversion ranks or enable_if partial-ordering. The
9629 // preference for pass-object-size parameters is probably most similar to a
9630 // type-based-overloading decision and so should take priority.
9631 //
9632 // If other rules cannot determine which is better, CUDA preference will be
9633 // used again to determine which is better.
9634 //
9635 // TODO: Currently IdentifyCUDAPreference does not return correct values
9636 // for functions called in global variable initializers due to missing
9637 // correct context about device/host. Therefore we can only enforce this
9638 // rule when there is a caller. We should enforce this rule for functions
9639 // in global variable initializers once proper context is added.
9640 //
9641 // TODO: We can only enable the hostness based overloading resolution when
9642 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9643 // overloading resolution diagnostics.
9644 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9645 S.getLangOpts().GPUExcludeWrongSideOverloads) {
9646 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) {
9647 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9648 bool IsCand1ImplicitHD =
9649 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9650 bool IsCand2ImplicitHD =
9651 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9652 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9653 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9654 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)(static_cast <bool> (P1 != Sema::CFP_Never && P2
!= Sema::CFP_Never) ? void (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never"
, "clang/lib/Sema/SemaOverload.cpp", 9654, __extension__ __PRETTY_FUNCTION__
))
;
9655 // The implicit HD function may be a function in a system header which
9656 // is forced by pragma. In device compilation, if we prefer HD candidates
9657 // over wrong-sided candidates, overloading resolution may change, which
9658 // may result in non-deferrable diagnostics. As a workaround, we let
9659 // implicit HD candidates take equal preference as wrong-sided candidates.
9660 // This will preserve the overloading resolution.
9661 // TODO: We still need special handling of implicit HD functions since
9662 // they may incur other diagnostics to be deferred. We should make all
9663 // host/device related diagnostics deferrable and remove special handling
9664 // of implicit HD functions.
9665 auto EmitThreshold =
9666 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9667 (IsCand1ImplicitHD || IsCand2ImplicitHD))
9668 ? Sema::CFP_Never
9669 : Sema::CFP_WrongSide;
9670 auto Cand1Emittable = P1 > EmitThreshold;
9671 auto Cand2Emittable = P2 > EmitThreshold;
9672 if (Cand1Emittable && !Cand2Emittable)
9673 return true;
9674 if (!Cand1Emittable && Cand2Emittable)
9675 return false;
9676 }
9677 }
9678
9679 // C++ [over.match.best]p1:
9680 //
9681 // -- if F is a static member function, ICS1(F) is defined such
9682 // that ICS1(F) is neither better nor worse than ICS1(G) for
9683 // any function G, and, symmetrically, ICS1(G) is neither
9684 // better nor worse than ICS1(F).
9685 unsigned StartArg = 0;
9686 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9687 StartArg = 1;
9688
9689 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9690 // We don't allow incompatible pointer conversions in C++.
9691 if (!S.getLangOpts().CPlusPlus)
9692 return ICS.isStandard() &&
9693 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9694
9695 // The only ill-formed conversion we allow in C++ is the string literal to
9696 // char* conversion, which is only considered ill-formed after C++11.
9697 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9698 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9699 };
9700
9701 // Define functions that don't require ill-formed conversions for a given
9702 // argument to be better candidates than functions that do.
9703 unsigned NumArgs = Cand1.Conversions.size();
9704 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast <bool> (Cand2.Conversions.size() == NumArgs
&& "Overload candidate mismatch") ? void (0) : __assert_fail
("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "clang/lib/Sema/SemaOverload.cpp", 9704, __extension__ __PRETTY_FUNCTION__
))
;
9705 bool HasBetterConversion = false;
9706 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9707 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9708 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9709 if (Cand1Bad != Cand2Bad) {
9710 if (Cand1Bad)
9711 return false;
9712 HasBetterConversion = true;
9713 }
9714 }
9715
9716 if (HasBetterConversion)
9717 return true;
9718
9719 // C++ [over.match.best]p1:
9720 // A viable function F1 is defined to be a better function than another
9721 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9722 // conversion sequence than ICSi(F2), and then...
9723 bool HasWorseConversion = false;
9724 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9725 switch (CompareImplicitConversionSequences(S, Loc,
9726 Cand1.Conversions[ArgIdx],
9727 Cand2.Conversions[ArgIdx])) {
9728 case ImplicitConversionSequence::Better:
9729 // Cand1 has a better conversion sequence.
9730 HasBetterConversion = true;
9731 break;
9732
9733 case ImplicitConversionSequence::Worse:
9734 if (Cand1.Function && Cand2.Function &&
9735 Cand1.isReversed() != Cand2.isReversed() &&
9736 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9737 NumArgs)) {
9738 // Work around large-scale breakage caused by considering reversed
9739 // forms of operator== in C++20:
9740 //
9741 // When comparing a function against a reversed function with the same
9742 // parameter types, if we have a better conversion for one argument and
9743 // a worse conversion for the other, the implicit conversion sequences
9744 // are treated as being equally good.
9745 //
9746 // This prevents a comparison function from being considered ambiguous
9747 // with a reversed form that is written in the same way.
9748 //
9749 // We diagnose this as an extension from CreateOverloadedBinOp.
9750 HasWorseConversion = true;
9751 break;
9752 }
9753
9754 // Cand1 can't be better than Cand2.
9755 return false;
9756
9757 case ImplicitConversionSequence::Indistinguishable:
9758 // Do nothing.
9759 break;
9760 }
9761 }
9762
9763 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9764 // ICSj(F2), or, if not that,
9765 if (HasBetterConversion && !HasWorseConversion)
9766 return true;
9767
9768 // -- the context is an initialization by user-defined conversion
9769 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9770 // from the return type of F1 to the destination type (i.e.,
9771 // the type of the entity being initialized) is a better
9772 // conversion sequence than the standard conversion sequence
9773 // from the return type of F2 to the destination type.
9774 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9775 Cand1.Function && Cand2.Function &&
9776 isa<CXXConversionDecl>(Cand1.Function) &&
9777 isa<CXXConversionDecl>(Cand2.Function)) {
9778 // First check whether we prefer one of the conversion functions over the
9779 // other. This only distinguishes the results in non-standard, extension
9780 // cases such as the conversion from a lambda closure type to a function
9781 // pointer or block.
9782 ImplicitConversionSequence::CompareKind Result =
9783 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9784 if (Result == ImplicitConversionSequence::Indistinguishable)
9785 Result = CompareStandardConversionSequences(S, Loc,
9786 Cand1.FinalConversion,
9787 Cand2.FinalConversion);
9788
9789 if (Result != ImplicitConversionSequence::Indistinguishable)
9790 return Result == ImplicitConversionSequence::Better;
9791
9792 // FIXME: Compare kind of reference binding if conversion functions
9793 // convert to a reference type used in direct reference binding, per
9794 // C++14 [over.match.best]p1 section 2 bullet 3.
9795 }
9796
9797 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9798 // as combined with the resolution to CWG issue 243.
9799 //
9800 // When the context is initialization by constructor ([over.match.ctor] or
9801 // either phase of [over.match.list]), a constructor is preferred over
9802 // a conversion function.
9803 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9804 Cand1.Function && Cand2.Function &&
9805 isa<CXXConstructorDecl>(Cand1.Function) !=
9806 isa<CXXConstructorDecl>(Cand2.Function))
9807 return isa<CXXConstructorDecl>(Cand1.Function);
9808
9809 // -- F1 is a non-template function and F2 is a function template
9810 // specialization, or, if not that,
9811 bool Cand1IsSpecialization = Cand1.Function &&
9812 Cand1.Function->getPrimaryTemplate();
9813 bool Cand2IsSpecialization = Cand2.Function &&
9814 Cand2.Function->getPrimaryTemplate();
9815 if (Cand1IsSpecialization != Cand2IsSpecialization)
9816 return Cand2IsSpecialization;
9817
9818 // -- F1 and F2 are function template specializations, and the function
9819 // template for F1 is more specialized than the template for F2
9820 // according to the partial ordering rules described in 14.5.5.2, or,
9821 // if not that,
9822 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9823 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9824 Cand1.Function->getPrimaryTemplate(),
9825 Cand2.Function->getPrimaryTemplate(), Loc,
9826 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9827 : TPOC_Call,
9828 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9829 Cand1.isReversed() ^ Cand2.isReversed()))
9830 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9831 }
9832
9833 // -— F1 and F2 are non-template functions with the same
9834 // parameter-type-lists, and F1 is more constrained than F2 [...],
9835 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9836 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9837 Cand2.Function->hasPrototype()) {
9838 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9839 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9840 if (PT1->getNumParams() == PT2->getNumParams() &&
9841 PT1->isVariadic() == PT2->isVariadic() &&
9842 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9843 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9844 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9845 if (RC1 && RC2) {
9846 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9847 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9848 {RC2}, AtLeastAsConstrained1) ||
9849 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9850 {RC1}, AtLeastAsConstrained2))
9851 return false;
9852 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9853 return AtLeastAsConstrained1;
9854 } else if (RC1 || RC2) {
9855 return RC1 != nullptr;
9856 }
9857 }
9858 }
9859
9860 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9861 // class B of D, and for all arguments the corresponding parameters of
9862 // F1 and F2 have the same type.
9863 // FIXME: Implement the "all parameters have the same type" check.
9864 bool Cand1IsInherited =
9865 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9866 bool Cand2IsInherited =
9867 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9868 if (Cand1IsInherited != Cand2IsInherited)
9869 return Cand2IsInherited;
9870 else if (Cand1IsInherited) {
9871 assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail
("Cand2IsInherited", "clang/lib/Sema/SemaOverload.cpp", 9871
, __extension__ __PRETTY_FUNCTION__))
;
9872 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9873 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9874 if (Cand1Class->isDerivedFrom(Cand2Class))
9875 return true;
9876 if (Cand2Class->isDerivedFrom(Cand1Class))
9877 return false;
9878 // Inherited from sibling base classes: still ambiguous.
9879 }
9880
9881 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9882 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9883 // with reversed order of parameters and F1 is not
9884 //
9885 // We rank reversed + different operator as worse than just reversed, but
9886 // that comparison can never happen, because we only consider reversing for
9887 // the maximally-rewritten operator (== or <=>).
9888 if (Cand1.RewriteKind != Cand2.RewriteKind)
9889 return Cand1.RewriteKind < Cand2.RewriteKind;
9890
9891 // Check C++17 tie-breakers for deduction guides.
9892 {
9893 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9894 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9895 if (Guide1 && Guide2) {
9896 // -- F1 is generated from a deduction-guide and F2 is not
9897 if (Guide1->isImplicit() != Guide2->isImplicit())
9898 return Guide2->isImplicit();
9899
9900 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9901 if (Guide1->isCopyDeductionCandidate())
9902 return true;
9903 }
9904 }
9905
9906 // Check for enable_if value-based overload resolution.
9907 if (Cand1.Function && Cand2.Function) {
9908 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9909 if (Cmp != Comparison::Equal)
9910 return Cmp == Comparison::Better;
9911 }
9912
9913 bool HasPS1 = Cand1.Function != nullptr &&
9914 functionHasPassObjectSizeParams(Cand1.Function);
9915 bool HasPS2 = Cand2.Function != nullptr &&
9916 functionHasPassObjectSizeParams(Cand2.Function);
9917 if (HasPS1 != HasPS2 && HasPS1)
9918 return true;
9919
9920 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9921 if (MV == Comparison::Better)
9922 return true;
9923 if (MV == Comparison::Worse)
9924 return false;
9925
9926 // If other rules cannot determine which is better, CUDA preference is used
9927 // to determine which is better.
9928 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9929 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9930 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9931 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9932 }
9933
9934 // General member function overloading is handled above, so this only handles
9935 // constructors with address spaces.
9936 // This only handles address spaces since C++ has no other
9937 // qualifier that can be used with constructors.
9938 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9939 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9940 if (CD1 && CD2) {
9941 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9942 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9943 if (AS1 != AS2) {
9944 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9945 return true;
9946 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9947 return false;
9948 }
9949 }
9950
9951 return false;
9952}
9953
9954/// Determine whether two declarations are "equivalent" for the purposes of
9955/// name lookup and overload resolution. This applies when the same internal/no
9956/// linkage entity is defined by two modules (probably by textually including
9957/// the same header). In such a case, we don't consider the declarations to
9958/// declare the same entity, but we also don't want lookups with both
9959/// declarations visible to be ambiguous in some cases (this happens when using
9960/// a modularized libstdc++).
9961bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9962 const NamedDecl *B) {
9963 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9964 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9965 if (!VA || !VB)
9966 return false;
9967
9968 // The declarations must be declaring the same name as an internal linkage
9969 // entity in different modules.
9970 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9971 VB->getDeclContext()->getRedeclContext()) ||
9972 getOwningModule(VA) == getOwningModule(VB) ||
9973 VA->isExternallyVisible() || VB->isExternallyVisible())
9974 return false;
9975
9976 // Check that the declarations appear to be equivalent.
9977 //
9978 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9979 // For constants and functions, we should check the initializer or body is
9980 // the same. For non-constant variables, we shouldn't allow it at all.
9981 if (Context.hasSameType(VA->getType(), VB->getType()))
9982 return true;
9983
9984 // Enum constants within unnamed enumerations will have different types, but
9985 // may still be similar enough to be interchangeable for our purposes.
9986 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9987 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9988 // Only handle anonymous enums. If the enumerations were named and
9989 // equivalent, they would have been merged to the same type.
9990 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9991 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9992 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9993 !Context.hasSameType(EnumA->getIntegerType(),
9994 EnumB->getIntegerType()))
9995 return false;
9996 // Allow this only if the value is the same for both enumerators.
9997 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9998 }
9999 }
10000
10001 // Nothing else is sufficiently similar.
10002 return false;
10003}
10004
10005void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10006 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10007 assert(D && "Unknown declaration")(static_cast <bool> (D && "Unknown declaration"
) ? void (0) : __assert_fail ("D && \"Unknown declaration\""
, "clang/lib/Sema/SemaOverload.cpp", 10007, __extension__ __PRETTY_FUNCTION__
))
;
10008 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10009
10010 Module *M = getOwningModule(D);
10011 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10012 << !M << (M ? M->getFullModuleName() : "");
10013
10014 for (auto *E : Equiv) {
10015 Module *M = getOwningModule(E);
10016 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10017 << !M << (M ? M->getFullModuleName() : "");
10018 }
10019}
10020
10021/// Computes the best viable function (C++ 13.3.3)
10022/// within an overload candidate set.
10023///
10024/// \param Loc The location of the function name (or operator symbol) for
10025/// which overload resolution occurs.
10026///
10027/// \param Best If overload resolution was successful or found a deleted
10028/// function, \p Best points to the candidate function found.
10029///
10030/// \returns The result of overload resolution.
10031OverloadingResult
10032OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10033 iterator &Best) {
10034 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10035 std::transform(begin(), end(), std::back_inserter(Candidates),
10036 [](OverloadCandidate &Cand) { return &Cand; });
10037
10038 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10039 // are accepted by both clang and NVCC. However, during a particular
10040 // compilation mode only one call variant is viable. We need to
10041 // exclude non-viable overload candidates from consideration based
10042 // only on their host/device attributes. Specifically, if one
10043 // candidate call is WrongSide and the other is SameSide, we ignore
10044 // the WrongSide candidate.
10045 // We only need to remove wrong-sided candidates here if
10046 // -fgpu-exclude-wrong-side-overloads is off. When
10047 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10048 // uniformly in isBetterOverloadCandidate.
10049 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10050 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
10051 bool ContainsSameSideCandidate =
10052 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10053 // Check viable function only.
10054 return Cand->Viable && Cand->Function &&
10055 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10056 Sema::CFP_SameSide;
10057 });
10058 if (ContainsSameSideCandidate) {
10059 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10060 // Check viable function only to avoid unnecessary data copying/moving.
10061 return Cand->Viable && Cand->Function &&
10062 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10063 Sema::CFP_WrongSide;
10064 };
10065 llvm::erase_if(Candidates, IsWrongSideCandidate);
10066 }
10067 }
10068
10069 // Find the best viable function.
10070 Best = end();
10071 for (auto *Cand : Candidates) {
10072 Cand->Best = false;
10073 if (Cand->Viable)
10074 if (Best == end() ||
10075 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10076 Best = Cand;
10077 }
10078
10079 // If we didn't find any viable functions, abort.
10080 if (Best == end())
10081 return OR_No_Viable_Function;
10082
10083 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10084
10085 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10086 PendingBest.push_back(&*Best);
10087 Best->Best = true;
10088
10089 // Make sure that this function is better than every other viable
10090 // function. If not, we have an ambiguity.
10091 while (!PendingBest.empty()) {
10092 auto *Curr = PendingBest.pop_back_val();
10093 for (auto *Cand : Candidates) {
10094 if (Cand->Viable && !Cand->Best &&
10095 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10096 PendingBest.push_back(Cand);
10097 Cand->Best = true;
10098
10099 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10100 Curr->Function))
10101 EquivalentCands.push_back(Cand->Function);
10102 else
10103 Best = end();
10104 }
10105 }
10106 }
10107
10108 // If we found more than one best candidate, this is ambiguous.
10109 if (Best == end())
10110 return OR_Ambiguous;
10111
10112 // Best is the best viable function.
10113 if (Best->Function && Best->Function->isDeleted())
10114 return OR_Deleted;
10115
10116 if (!EquivalentCands.empty())
10117 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10118 EquivalentCands);
10119
10120 return OR_Success;
10121}
10122
10123namespace {
10124
10125enum OverloadCandidateKind {
10126 oc_function,
10127 oc_method,
10128 oc_reversed_binary_operator,
10129 oc_constructor,
10130 oc_implicit_default_constructor,
10131 oc_implicit_copy_constructor,
10132 oc_implicit_move_constructor,
10133 oc_implicit_copy_assignment,
10134 oc_implicit_move_assignment,
10135 oc_implicit_equality_comparison,
10136 oc_inherited_constructor
10137};
10138
10139enum OverloadCandidateSelect {
10140 ocs_non_template,
10141 ocs_template,
10142 ocs_described_template,
10143};
10144
10145static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10146ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10147 OverloadCandidateRewriteKind CRK,
10148 std::string &Description) {
10149
10150 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10151 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10152 isTemplate = true;
10153 Description = S.getTemplateArgumentBindingsText(
10154 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10155 }
10156
10157 OverloadCandidateSelect Select = [&]() {
10158 if (!Description.empty())
10159 return ocs_described_template;
10160 return isTemplate ? ocs_template : ocs_non_template;
10161 }();
10162
10163 OverloadCandidateKind Kind = [&]() {
10164 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10165 return oc_implicit_equality_comparison;
10166
10167 if (CRK & CRK_Reversed)
10168 return oc_reversed_binary_operator;
10169
10170 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10171 if (!Ctor->isImplicit()) {
10172 if (isa<ConstructorUsingShadowDecl>(Found))
10173 return oc_inherited_constructor;
10174 else
10175 return oc_constructor;
10176 }
10177
10178 if (Ctor->isDefaultConstructor())
10179 return oc_implicit_default_constructor;
10180
10181 if (Ctor->isMoveConstructor())
10182 return oc_implicit_move_constructor;
10183
10184 assert(Ctor->isCopyConstructor() &&(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "clang/lib/Sema/SemaOverload.cpp", 10185, __extension__ __PRETTY_FUNCTION__
))
10185 "unexpected sort of implicit constructor")(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "clang/lib/Sema/SemaOverload.cpp", 10185, __extension__ __PRETTY_FUNCTION__
))
;
10186 return oc_implicit_copy_constructor;
10187 }
10188
10189 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10190 // This actually gets spelled 'candidate function' for now, but
10191 // it doesn't hurt to split it out.
10192 if (!Meth->isImplicit())
10193 return oc_method;
10194
10195 if (Meth->isMoveAssignmentOperator())
10196 return oc_implicit_move_assignment;
10197
10198 if (Meth->isCopyAssignmentOperator())
10199 return oc_implicit_copy_assignment;
10200
10201 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast <bool> (isa<CXXConversionDecl>(Meth)
&& "expected conversion") ? void (0) : __assert_fail
("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "clang/lib/Sema/SemaOverload.cpp", 10201, __extension__ __PRETTY_FUNCTION__
))
;
10202 return oc_method;
10203 }
10204
10205 return oc_function;
10206 }();
10207
10208 return std::make_pair(Kind, Select);
10209}
10210
10211void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10212 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10213 // set.
10214 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10215 S.Diag(FoundDecl->getLocation(),
10216 diag::note_ovl_candidate_inherited_constructor)
10217 << Shadow->getNominatedBaseClass();
10218}
10219
10220} // end anonymous namespace
10221
10222static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10223 const FunctionDecl *FD) {
10224 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10225 bool AlwaysTrue;
10226 if (EnableIf->getCond()->isValueDependent() ||
10227 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10228 return false;
10229 if (!AlwaysTrue)
10230 return false;
10231 }
10232 return true;
10233}
10234
10235/// Returns true if we can take the address of the function.
10236///
10237/// \param Complain - If true, we'll emit a diagnostic
10238/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10239/// we in overload resolution?
10240/// \param Loc - The location of the statement we're complaining about. Ignored
10241/// if we're not complaining, or if we're in overload resolution.
10242static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10243 bool Complain,
10244 bool InOverloadResolution,
10245 SourceLocation Loc) {
10246 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10247 if (Complain) {
10248 if (InOverloadResolution)
10249 S.Diag(FD->getBeginLoc(),
10250 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10251 else
10252 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10253 }
10254 return false;
10255 }
10256
10257 if (FD->getTrailingRequiresClause()) {
10258 ConstraintSatisfaction Satisfaction;
10259 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10260 return false;
10261 if (!Satisfaction.IsSatisfied) {
10262 if (Complain) {
10263 if (InOverloadResolution)
10264 S.Diag(FD->getBeginLoc(),
10265 diag::note_ovl_candidate_unsatisfied_constraints);
10266 else
10267 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10268 << FD;
10269 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10270 }
10271 return false;
10272 }
10273 }
10274
10275 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10276 return P->hasAttr<PassObjectSizeAttr>();
10277 });
10278 if (I == FD->param_end())
10279 return true;
10280
10281 if (Complain) {
10282 // Add one to ParamNo because it's user-facing
10283 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10284 if (InOverloadResolution)
10285 S.Diag(FD->getLocation(),
10286 diag::note_ovl_candidate_has_pass_object_size_params)
10287 << ParamNo;
10288 else
10289 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10290 << FD << ParamNo;
10291 }
10292 return false;
10293}
10294
10295static bool checkAddressOfCandidateIsAvailable(Sema &S,
10296 const FunctionDecl *FD) {
10297 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10298 /*InOverloadResolution=*/true,
10299 /*Loc=*/SourceLocation());
10300}
10301
10302bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10303 bool Complain,
10304 SourceLocation Loc) {
10305 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10306 /*InOverloadResolution=*/false,
10307 Loc);
10308}
10309
10310// Don't print candidates other than the one that matches the calling
10311// convention of the call operator, since that is guaranteed to exist.
10312static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10313 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10314
10315 if (!ConvD)
10316 return false;
10317 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10318 if (!RD->isLambda())
10319 return false;
10320
10321 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10322 CallingConv CallOpCC =
10323 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10324 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10325 CallingConv ConvToCC =
10326 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10327
10328 return ConvToCC != CallOpCC;
10329}
10330
10331// Notes the location of an overload candidate.
10332void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10333 OverloadCandidateRewriteKind RewriteKind,
10334 QualType DestType, bool TakingAddress) {
10335 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10336 return;
10337 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10338 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10339 return;
10340 if (shouldSkipNotingLambdaConversionDecl(Fn))
10341 return;
10342
10343 std::string FnDesc;
10344 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10345 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10346 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10347 << (unsigned)KSPair.first << (unsigned)KSPair.second
10348 << Fn << FnDesc;
10349
10350 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10351 Diag(Fn->getLocation(), PD);
10352 MaybeEmitInheritedConstructorNote(*this, Found);
10353}
10354
10355static void
10356MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10357 // Perhaps the ambiguity was caused by two atomic constraints that are
10358 // 'identical' but not equivalent:
10359 //
10360 // void foo() requires (sizeof(T) > 4) { } // #1
10361 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10362 //
10363 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10364 // #2 to subsume #1, but these constraint are not considered equivalent
10365 // according to the subsumption rules because they are not the same
10366 // source-level construct. This behavior is quite confusing and we should try
10367 // to help the user figure out what happened.
10368
10369 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10370 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10371 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10372 if (!I->Function)
10373 continue;
10374 SmallVector<const Expr *, 3> AC;
10375 if (auto *Template = I->Function->getPrimaryTemplate())
10376 Template->getAssociatedConstraints(AC);
10377 else
10378 I->Function->getAssociatedConstraints(AC);
10379 if (AC.empty())
10380 continue;
10381 if (FirstCand == nullptr) {
10382 FirstCand = I->Function;
10383 FirstAC = AC;
10384 } else if (SecondCand == nullptr) {
10385 SecondCand = I->Function;
10386 SecondAC = AC;
10387 } else {
10388 // We have more than one pair of constrained functions - this check is
10389 // expensive and we'd rather not try to diagnose it.
10390 return;
10391 }
10392 }
10393 if (!SecondCand)
10394 return;
10395 // The diagnostic can only happen if there are associated constraints on
10396 // both sides (there needs to be some identical atomic constraint).
10397 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10398 SecondCand, SecondAC))
10399 // Just show the user one diagnostic, they'll probably figure it out
10400 // from here.
10401 return;
10402}
10403
10404// Notes the location of all overload candidates designated through
10405// OverloadedExpr
10406void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10407 bool TakingAddress) {
10408 assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast <bool> (OverloadedExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 10408, __extension__ __PRETTY_FUNCTION__
))
;
10409
10410 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10411 OverloadExpr *OvlExpr = Ovl.Expression;
10412
10413 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10414 IEnd = OvlExpr->decls_end();
10415 I != IEnd; ++I) {
10416 if (FunctionTemplateDecl *FunTmpl =
10417 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10418 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10419 TakingAddress);
10420 } else if (FunctionDecl *Fun
10421 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10422 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10423 }
10424 }
10425}
10426
10427/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10428/// "lead" diagnostic; it will be given two arguments, the source and
10429/// target types of the conversion.
10430void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10431 Sema &S,
10432 SourceLocation CaretLoc,
10433 const PartialDiagnostic &PDiag) const {
10434 S.Diag(CaretLoc, PDiag)
10435 << Ambiguous.getFromType() << Ambiguous.getToType();
10436 unsigned CandsShown = 0;
10437 AmbiguousConversionSequence::const_iterator I, E;
10438 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10439 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10440 break;
10441 ++CandsShown;
10442 S.NoteOverloadCandidate(I->first, I->second);
10443 }
10444 S.Diags.overloadCandidatesShown(CandsShown);
10445 if (I != E)
10446 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10447}
10448
10449static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10450 unsigned I, bool TakingCandidateAddress) {
10451 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10452 assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail
("Conv.isBad()", "clang/lib/Sema/SemaOverload.cpp", 10452, __extension__
__PRETTY_FUNCTION__))
;
10453 assert(Cand->Function && "for now, candidate must be a function")(static_cast <bool> (Cand->Function && "for now, candidate must be a function"
) ? void (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "clang/lib/Sema/SemaOverload.cpp", 10453, __extension__ __PRETTY_FUNCTION__
))
;
10454 FunctionDecl *Fn = Cand->Function;
10455
10456 // There's a conversion slot for the object argument if this is a
10457 // non-constructor method. Note that 'I' corresponds the
10458 // conversion-slot index.
10459 bool isObjectArgument = false;
10460 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10461 if (I == 0)
10462 isObjectArgument = true;
10463 else
10464 I--;
10465 }
10466
10467 std::string FnDesc;
10468 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10469 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10470 FnDesc);
10471
10472 Expr *FromExpr = Conv.Bad.FromExpr;
10473 QualType FromTy = Conv.Bad.getFromType();
10474 QualType ToTy = Conv.Bad.getToType();
10475
10476 if (FromTy == S.Context.OverloadTy) {
10477 assert(FromExpr && "overload set argument came from implicit argument?")(static_cast <bool> (FromExpr && "overload set argument came from implicit argument?"
) ? void (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "clang/lib/Sema/SemaOverload.cpp", 10477, __extension__ __PRETTY_FUNCTION__
))
;
10478 Expr *E = FromExpr->IgnoreParens();
10479 if (isa<UnaryOperator>(E))
10480 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10481 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10482
10483 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10484 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10485 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10486 << Name << I + 1;
10487 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10488 return;
10489 }
10490
10491 // Do some hand-waving analysis to see if the non-viability is due
10492 // to a qualifier mismatch.
10493 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10494 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10495 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10496 CToTy = RT->getPointeeType();
10497 else {
10498 // TODO: detect and diagnose the full richness of const mismatches.
10499 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10500 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10501 CFromTy = FromPT->getPointeeType();
10502 CToTy = ToPT->getPointeeType();
10503 }
10504 }
10505
10506 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10507 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10508 Qualifiers FromQs = CFromTy.getQualifiers();
10509 Qualifiers ToQs = CToTy.getQualifiers();
10510
10511 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10512 if (isObjectArgument)
10513 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10514 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10515 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10516 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10517 else
10518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10519 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10520 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10521 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10522 << ToTy->isReferenceType() << I + 1;
10523 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10524 return;
10525 }
10526
10527 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10529 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10531 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10532 << (unsigned)isObjectArgument << I + 1;
10533 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10534 return;
10535 }
10536
10537 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10539 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10540 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10541 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10542 << (unsigned)isObjectArgument << I + 1;
10543 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10544 return;
10545 }
10546
10547 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10549 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10551 << FromQs.hasUnaligned() << I + 1;
10552 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10553 return;
10554 }
10555
10556 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10557 assert(CVR && "expected qualifiers mismatch")(static_cast <bool> (CVR && "expected qualifiers mismatch"
) ? void (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\""
, "clang/lib/Sema/SemaOverload.cpp", 10557, __extension__ __PRETTY_FUNCTION__
))
;
10558
10559 if (isObjectArgument) {
10560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10561 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10562 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10563 << (CVR - 1);
10564 } else {
10565 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10566 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10567 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10568 << (CVR - 1) << I + 1;
10569 }
10570 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10571 return;
10572 }
10573
10574 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10575 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10576 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10577 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10578 << (unsigned)isObjectArgument << I + 1
10579 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10580 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10581 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10582 return;
10583 }
10584
10585 // Special diagnostic for failure to convert an initializer list, since
10586 // telling the user that it has type void is not useful.
10587 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10588 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10589 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10590 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10591 << ToTy << (unsigned)isObjectArgument << I + 1
10592 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10593 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10594 ? 2
10595 : 0);
10596 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10597 return;
10598 }
10599
10600 // Diagnose references or pointers to incomplete types differently,
10601 // since it's far from impossible that the incompleteness triggered
10602 // the failure.
10603 QualType TempFromTy = FromTy.getNonReferenceType();
10604 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10605 TempFromTy = PTy->getPointeeType();
10606 if (TempFromTy->isIncompleteType()) {
10607 // Emit the generic diagnostic and, optionally, add the hints to it.
10608 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10609 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10610 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10611 << ToTy << (unsigned)isObjectArgument << I + 1
10612 << (unsigned)(Cand->Fix.Kind);
10613
10614 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10615 return;
10616 }
10617
10618 // Diagnose base -> derived pointer conversions.
10619 unsigned BaseToDerivedConversion = 0;
10620 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10621 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10622 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10623 FromPtrTy->getPointeeType()) &&
10624 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10625 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10626 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10627 FromPtrTy->getPointeeType()))
10628 BaseToDerivedConversion = 1;
10629 }
10630 } else if (const ObjCObjectPointerType *FromPtrTy
10631 = FromTy->getAs<ObjCObjectPointerType>()) {
10632 if (const ObjCObjectPointerType *ToPtrTy
10633 = ToTy->getAs<ObjCObjectPointerType>())
10634 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10635 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10636 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10637 FromPtrTy->getPointeeType()) &&
10638 FromIface->isSuperClassOf(ToIface))
10639 BaseToDerivedConversion = 2;
10640 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10641 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10642 !FromTy->isIncompleteType() &&
10643 !ToRefTy->getPointeeType()->isIncompleteType() &&
10644 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10645 BaseToDerivedConversion = 3;
10646 }
10647 }
10648
10649 if (BaseToDerivedConversion) {
10650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10651 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10652 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10653 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10654 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10655 return;
10656 }
10657
10658 if (isa<ObjCObjectPointerType>(CFromTy) &&
10659 isa<PointerType>(CToTy)) {
10660 Qualifiers FromQs = CFromTy.getQualifiers();
10661 Qualifiers ToQs = CToTy.getQualifiers();
10662 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10664 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10665 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10666 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10667 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10668 return;
10669 }
10670 }
10671
10672 if (TakingCandidateAddress &&
10673 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10674 return;
10675
10676 // Emit the generic diagnostic and, optionally, add the hints to it.
10677 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10678 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10679 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10680 << ToTy << (unsigned)isObjectArgument << I + 1
10681 << (unsigned)(Cand->Fix.Kind);
10682
10683 // If we can fix the conversion, suggest the FixIts.
10684 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10685 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10686 FDiag << *HI;
10687 S.Diag(Fn->getLocation(), FDiag);
10688
10689 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10690}
10691
10692/// Additional arity mismatch diagnosis specific to a function overload
10693/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10694/// over a candidate in any candidate set.
10695static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10696 unsigned NumArgs) {
10697 FunctionDecl *Fn = Cand->Function;
10698 unsigned MinParams = Fn->getMinRequiredArguments();
10699
10700 // With invalid overloaded operators, it's possible that we think we
10701 // have an arity mismatch when in fact it looks like we have the
10702 // right number of arguments, because only overloaded operators have
10703 // the weird behavior of overloading member and non-member functions.
10704 // Just don't report anything.
10705 if (Fn->isInvalidDecl() &&
10706 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10707 return true;
10708
10709 if (NumArgs < MinParams) {
10710 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10712, __extension__ __PRETTY_FUNCTION__
))
10711 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10712, __extension__ __PRETTY_FUNCTION__
))
10712 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10712, __extension__ __PRETTY_FUNCTION__
))
;
10713 } else {
10714 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10716, __extension__ __PRETTY_FUNCTION__
))
10715 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10716, __extension__ __PRETTY_FUNCTION__
))
10716 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "clang/lib/Sema/SemaOverload.cpp", 10716, __extension__ __PRETTY_FUNCTION__
))
;
10717 }
10718
10719 return false;
10720}
10721
10722/// General arity mismatch diagnosis over a candidate in a candidate set.
10723static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10724 unsigned NumFormalArgs) {
10725 assert(isa<FunctionDecl>(D) &&(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10728, __extension__ __PRETTY_FUNCTION__
))
10726 "The templated declaration should at least be a function"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10728, __extension__ __PRETTY_FUNCTION__
))
10727 " when diagnosing bad template argument deduction due to too many"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10728, __extension__ __PRETTY_FUNCTION__
))
10728 " or too few arguments")(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10728, __extension__ __PRETTY_FUNCTION__
))
;
10729
10730 FunctionDecl *Fn = cast<FunctionDecl>(D);
10731
10732 // TODO: treat calls to a missing default constructor as a special case
10733 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10734 unsigned MinParams = Fn->getMinRequiredArguments();
10735
10736 // at least / at most / exactly
10737 unsigned mode, modeCount;
10738 if (NumFormalArgs < MinParams) {
10739 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10740 FnTy->isTemplateVariadic())
10741 mode = 0; // "at least"
10742 else
10743 mode = 2; // "exactly"
10744 modeCount = MinParams;
10745 } else {
10746 if (MinParams != FnTy->getNumParams())
10747 mode = 1; // "at most"
10748 else
10749 mode = 2; // "exactly"
10750 modeCount = FnTy->getNumParams();
10751 }
10752
10753 std::string Description;
10754 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10755 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10756
10757 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10759 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10760 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10761 else
10762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10763 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10764 << Description << mode << modeCount << NumFormalArgs;
10765
10766 MaybeEmitInheritedConstructorNote(S, Found);
10767}
10768
10769/// Arity mismatch diagnosis specific to a function overload candidate.
10770static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10771 unsigned NumFormalArgs) {
10772 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10773 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10774}
10775
10776static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10777 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10778 return TD;
10779 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp"
, 10780)
10780 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "clang/lib/Sema/SemaOverload.cpp"
, 10780)
;
10781}
10782
10783/// Diagnose a failed template-argument deduction.
10784static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10785 DeductionFailureInfo &DeductionFailure,
10786 unsigned NumArgs,
10787 bool TakingCandidateAddress) {
10788 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10789 NamedDecl *ParamD;
10790 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10791 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10792 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10793 switch (DeductionFailure.Result) {
10794 case Sema::TDK_Success:
10795 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "clang/lib/Sema/SemaOverload.cpp", 10795)
;
10796
10797 case Sema::TDK_Incomplete: {
10798 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10798, __extension__ __PRETTY_FUNCTION__
))
;
10799 S.Diag(Templated->getLocation(),
10800 diag::note_ovl_candidate_incomplete_deduction)
10801 << ParamD->getDeclName();
10802 MaybeEmitInheritedConstructorNote(S, Found);
10803 return;
10804 }
10805
10806 case Sema::TDK_IncompletePack: {
10807 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10807, __extension__ __PRETTY_FUNCTION__
))
;
10808 S.Diag(Templated->getLocation(),
10809 diag::note_ovl_candidate_incomplete_deduction_pack)
10810 << ParamD->getDeclName()
10811 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10812 << *DeductionFailure.getFirstArg();
10813 MaybeEmitInheritedConstructorNote(S, Found);
10814 return;
10815 }
10816
10817 case Sema::TDK_Underqualified: {
10818 assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast <bool> (ParamD && "no parameter found for bad qualifiers deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10818, __extension__ __PRETTY_FUNCTION__
))
;
10819 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10820
10821 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10822
10823 // Param will have been canonicalized, but it should just be a
10824 // qualified version of ParamD, so move the qualifiers to that.
10825 QualifierCollector Qs;
10826 Qs.strip(Param);
10827 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10828 assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast <bool> (S.Context.hasSameType(Param, NonCanonParam
)) ? void (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "clang/lib/Sema/SemaOverload.cpp", 10828, __extension__ __PRETTY_FUNCTION__
))
;
10829
10830 // Arg has also been canonicalized, but there's nothing we can do
10831 // about that. It also doesn't matter as much, because it won't
10832 // have any template parameters in it (because deduction isn't
10833 // done on dependent types).
10834 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10835
10836 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10837 << ParamD->getDeclName() << Arg << NonCanonParam;
10838 MaybeEmitInheritedConstructorNote(S, Found);
10839 return;
10840 }
10841
10842 case Sema::TDK_Inconsistent: {
10843 assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast <bool> (ParamD && "no parameter found for inconsistent deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "clang/lib/Sema/SemaOverload.cpp", 10843, __extension__ __PRETTY_FUNCTION__
))
;
10844 int which = 0;
10845 if (isa<TemplateTypeParmDecl>(ParamD))
10846 which = 0;
10847 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10848 // Deduction might have failed because we deduced arguments of two
10849 // different types for a non-type template parameter.
10850 // FIXME: Use a different TDK value for this.
10851 QualType T1 =
10852 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10853 QualType T2 =
10854 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10855 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10856 S.Diag(Templated->getLocation(),
10857 diag::note_ovl_candidate_inconsistent_deduction_types)
10858 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10859 << *DeductionFailure.getSecondArg() << T2;
10860 MaybeEmitInheritedConstructorNote(S, Found);
10861 return;
10862 }
10863
10864 which = 1;
10865 } else {
10866 which = 2;
10867 }
10868
10869 // Tweak the diagnostic if the problem is that we deduced packs of
10870 // different arities. We'll print the actual packs anyway in case that
10871 // includes additional useful information.
10872 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10873 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10874 DeductionFailure.getFirstArg()->pack_size() !=
10875 DeductionFailure.getSecondArg()->pack_size()) {
10876 which = 3;
10877 }
10878
10879 S.Diag(Templated->getLocation(),
10880 diag::note_ovl_candidate_inconsistent_deduction)
10881 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10882 << *DeductionFailure.getSecondArg();
10883 MaybeEmitInheritedConstructorNote(S, Found);
10884 return;
10885 }
10886
10887 case Sema::TDK_InvalidExplicitArguments:
10888 assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast <bool> (ParamD && "no parameter found for invalid explicit arguments"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "clang/lib/Sema/SemaOverload.cpp", 10888, __extension__ __PRETTY_FUNCTION__
))
;
10889 if (ParamD->getDeclName())
10890 S.Diag(Templated->getLocation(),
10891 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10892 << ParamD->getDeclName();
10893 else {
10894 int index = 0;
10895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10896 index = TTP->getIndex();
10897 else if (NonTypeTemplateParmDecl *NTTP
10898 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10899 index = NTTP->getIndex();
10900 else
10901 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10902 S.Diag(Templated->getLocation(),
10903 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10904 << (index + 1);
10905 }
10906 MaybeEmitInheritedConstructorNote(S, Found);
10907 return;
10908
10909 case Sema::TDK_ConstraintsNotSatisfied: {
10910 // Format the template argument list into the argument string.
10911 SmallString<128> TemplateArgString;
10912 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10913 TemplateArgString = " ";
10914 TemplateArgString += S.getTemplateArgumentBindingsText(
10915 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10916 if (TemplateArgString.size() == 1)
10917 TemplateArgString.clear();
10918 S.Diag(Templated->getLocation(),
10919 diag::note_ovl_candidate_unsatisfied_constraints)
10920 << TemplateArgString;
10921
10922 S.DiagnoseUnsatisfiedConstraint(
10923 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10924 return;
10925 }
10926 case Sema::TDK_TooManyArguments:
10927 case Sema::TDK_TooFewArguments:
10928 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10929 return;
10930
10931 case Sema::TDK_InstantiationDepth:
10932 S.Diag(Templated->getLocation(),
10933 diag::note_ovl_candidate_instantiation_depth);
10934 MaybeEmitInheritedConstructorNote(S, Found);
10935 return;
10936
10937 case Sema::TDK_SubstitutionFailure: {
10938 // Format the template argument list into the argument string.
10939 SmallString<128> TemplateArgString;
10940 if (TemplateArgumentList *Args =
10941 DeductionFailure.getTemplateArgumentList()) {
10942 TemplateArgString = " ";
10943 TemplateArgString += S.getTemplateArgumentBindingsText(
10944 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10945 if (TemplateArgString.size() == 1)
10946 TemplateArgString.clear();
10947 }
10948
10949 // If this candidate was disabled by enable_if, say so.
10950 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10951 if (PDiag && PDiag->second.getDiagID() ==
10952 diag::err_typename_nested_not_found_enable_if) {
10953 // FIXME: Use the source range of the condition, and the fully-qualified
10954 // name of the enable_if template. These are both present in PDiag.
10955 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10956 << "'enable_if'" << TemplateArgString;
10957 return;
10958 }
10959
10960 // We found a specific requirement that disabled the enable_if.
10961 if (PDiag && PDiag->second.getDiagID() ==
10962 diag::err_typename_nested_not_found_requirement) {
10963 S.Diag(Templated->getLocation(),
10964 diag::note_ovl_candidate_disabled_by_requirement)
10965 << PDiag->second.getStringArg(0) << TemplateArgString;
10966 return;
10967 }
10968
10969 // Format the SFINAE diagnostic into the argument string.
10970 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10971 // formatted message in another diagnostic.
10972 SmallString<128> SFINAEArgString;
10973 SourceRange R;
10974 if (PDiag) {
10975 SFINAEArgString = ": ";
10976 R = SourceRange(PDiag->first, PDiag->first);
10977 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10978 }
10979
10980 S.Diag(Templated->getLocation(),
10981 diag::note_ovl_candidate_substitution_failure)
10982 << TemplateArgString << SFINAEArgString << R;
10983 MaybeEmitInheritedConstructorNote(S, Found);
10984 return;
10985 }
10986
10987 case Sema::TDK_DeducedMismatch:
10988 case Sema::TDK_DeducedMismatchNested: {
10989 // Format the template argument list into the argument string.
10990 SmallString<128> TemplateArgString;
10991 if (TemplateArgumentList *Args =
10992 DeductionFailure.getTemplateArgumentList()) {
10993 TemplateArgString = " ";
10994 TemplateArgString += S.getTemplateArgumentBindingsText(
10995 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10996 if (TemplateArgString.size() == 1)
10997 TemplateArgString.clear();
10998 }
10999
11000 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11001 << (*DeductionFailure.getCallArgIndex() + 1)
11002 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11003 << TemplateArgString
11004 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11005 break;
11006 }
11007
11008 case Sema::TDK_NonDeducedMismatch: {
11009 // FIXME: Provide a source location to indicate what we couldn't match.
11010 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11011 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11012 if (FirstTA.getKind() == TemplateArgument::Template &&
11013 SecondTA.getKind() == TemplateArgument::Template) {
11014 TemplateName FirstTN = FirstTA.getAsTemplate();
11015 TemplateName SecondTN = SecondTA.getAsTemplate();
11016 if (FirstTN.getKind() == TemplateName::Template &&
11017 SecondTN.getKind() == TemplateName::Template) {
11018 if (FirstTN.getAsTemplateDecl()->getName() ==
11019 SecondTN.getAsTemplateDecl()->getName()) {
11020 // FIXME: This fixes a bad diagnostic where both templates are named
11021 // the same. This particular case is a bit difficult since:
11022 // 1) It is passed as a string to the diagnostic printer.
11023 // 2) The diagnostic printer only attempts to find a better
11024 // name for types, not decls.
11025 // Ideally, this should folded into the diagnostic printer.
11026 S.Diag(Templated->getLocation(),
11027 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11028 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11029 return;
11030 }
11031 }
11032 }
11033
11034 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11035 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11036 return;
11037
11038 // FIXME: For generic lambda parameters, check if the function is a lambda
11039 // call operator, and if so, emit a prettier and more informative
11040 // diagnostic that mentions 'auto' and lambda in addition to
11041 // (or instead of?) the canonical template type parameters.
11042 S.Diag(Templated->getLocation(),
11043 diag::note_ovl_candidate_non_deduced_mismatch)
11044 << FirstTA << SecondTA;
11045 return;
11046 }
11047 // TODO: diagnose these individually, then kill off
11048 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11049 case Sema::TDK_MiscellaneousDeductionFailure:
11050 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11051 MaybeEmitInheritedConstructorNote(S, Found);
11052 return;
11053 case Sema::TDK_CUDATargetMismatch:
11054 S.Diag(Templated->getLocation(),
11055 diag::note_cuda_ovl_candidate_target_mismatch);
11056 return;
11057 }
11058}
11059
11060/// Diagnose a failed template-argument deduction, for function calls.
11061static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11062 unsigned NumArgs,
11063 bool TakingCandidateAddress) {
11064 unsigned TDK = Cand->DeductionFailure.Result;
11065 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11066 if (CheckArityMismatch(S, Cand, NumArgs))
11067 return;
11068 }
11069 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11070 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11071}
11072
11073/// CUDA: diagnose an invalid call across targets.
11074static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11075 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
11076 FunctionDecl *Callee = Cand->Function;
11077
11078 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11079 CalleeTarget = S.IdentifyCUDATarget(Callee);
11080
11081 std::string FnDesc;
11082 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11083 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11084 Cand->getRewriteKind(), FnDesc);
11085
11086 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11087 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11088 << FnDesc /* Ignored */
11089 << CalleeTarget << CallerTarget;
11090
11091 // This could be an implicit constructor for which we could not infer the
11092 // target due to a collsion. Diagnose that case.
11093 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11094 if (Meth != nullptr && Meth->isImplicit()) {
11095 CXXRecordDecl *ParentClass = Meth->getParent();
11096 Sema::CXXSpecialMember CSM;
11097
11098 switch (FnKindPair.first) {
11099 default:
11100 return;
11101 case oc_implicit_default_constructor:
11102 CSM = Sema::CXXDefaultConstructor;
11103 break;
11104 case oc_implicit_copy_constructor:
11105 CSM = Sema::CXXCopyConstructor;
11106 break;
11107 case oc_implicit_move_constructor:
11108 CSM = Sema::CXXMoveConstructor;
11109 break;
11110 case oc_implicit_copy_assignment:
11111 CSM = Sema::CXXCopyAssignment;
11112 break;
11113 case oc_implicit_move_assignment:
11114 CSM = Sema::CXXMoveAssignment;
11115 break;
11116 };
11117
11118 bool ConstRHS = false;
11119 if (Meth->getNumParams()) {
11120 if (const ReferenceType *RT =
11121 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11122 ConstRHS = RT->getPointeeType().isConstQualified();
11123 }
11124 }
11125
11126 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11127 /* ConstRHS */ ConstRHS,
11128 /* Diagnose */ true);
11129 }
11130}
11131
11132static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11133 FunctionDecl *Callee = Cand->Function;
11134 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11135
11136 S.Diag(Callee->getLocation(),
11137 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11138 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11139}
11140
11141static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11142 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11143 assert(ES.isExplicit() && "not an explicit candidate")(static_cast <bool> (ES.isExplicit() && "not an explicit candidate"
) ? void (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 11143, __extension__ __PRETTY_FUNCTION__
))
;
11144
11145 unsigned Kind;
11146 switch (Cand->Function->getDeclKind()) {
11147 case Decl::Kind::CXXConstructor:
11148 Kind = 0;
11149 break;
11150 case Decl::Kind::CXXConversion:
11151 Kind = 1;
11152 break;
11153 case Decl::Kind::CXXDeductionGuide:
11154 Kind = Cand->Function->isImplicit() ? 0 : 2;
11155 break;
11156 default:
11157 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "clang/lib/Sema/SemaOverload.cpp"
, 11157)
;
11158 }
11159
11160 // Note the location of the first (in-class) declaration; a redeclaration
11161 // (particularly an out-of-class definition) will typically lack the
11162 // 'explicit' specifier.
11163 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11164 FunctionDecl *First = Cand->Function->getFirstDecl();
11165 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11166 First = Pattern->getFirstDecl();
11167
11168 S.Diag(First->getLocation(),
11169 diag::note_ovl_candidate_explicit)
11170 << Kind << (ES.getExpr() ? 1 : 0)
11171 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11172}
11173
11174/// Generates a 'note' diagnostic for an overload candidate. We've
11175/// already generated a primary error at the call site.
11176///
11177/// It really does need to be a single diagnostic with its caret
11178/// pointed at the candidate declaration. Yes, this creates some
11179/// major challenges of technical writing. Yes, this makes pointing
11180/// out problems with specific arguments quite awkward. It's still
11181/// better than generating twenty screens of text for every failed
11182/// overload.
11183///
11184/// It would be great to be able to express per-candidate problems
11185/// more richly for those diagnostic clients that cared, but we'd
11186/// still have to be just as careful with the default diagnostics.
11187/// \param CtorDestAS Addr space of object being constructed (for ctor
11188/// candidates only).
11189static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11190 unsigned NumArgs,
11191 bool TakingCandidateAddress,
11192 LangAS CtorDestAS = LangAS::Default) {
11193 FunctionDecl *Fn = Cand->Function;
11194 if (shouldSkipNotingLambdaConversionDecl(Fn))
11195 return;
11196
11197 // Note deleted candidates, but only if they're viable.
11198 if (Cand->Viable) {
11199 if (Fn->isDeleted()) {
11200 std::string FnDesc;
11201 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11202 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11203 Cand->getRewriteKind(), FnDesc);
11204
11205 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11206 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11207 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11208 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11209 return;
11210 }
11211
11212 // We don't really have anything else to say about viable candidates.
11213 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11214 return;
11215 }
11216
11217 switch (Cand->FailureKind) {
11218 case ovl_fail_too_many_arguments:
11219 case ovl_fail_too_few_arguments:
11220 return DiagnoseArityMismatch(S, Cand, NumArgs);
11221
11222 case ovl_fail_bad_deduction:
11223 return DiagnoseBadDeduction(S, Cand, NumArgs,
11224 TakingCandidateAddress);
11225
11226 case ovl_fail_illegal_constructor: {
11227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11228 << (Fn->getPrimaryTemplate() ? 1 : 0);
11229 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11230 return;
11231 }
11232
11233 case ovl_fail_object_addrspace_mismatch: {
11234 Qualifiers QualsForPrinting;
11235 QualsForPrinting.setAddressSpace(CtorDestAS);
11236 S.Diag(Fn->getLocation(),
11237 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11238 << QualsForPrinting;
11239 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11240 return;
11241 }
11242
11243 case ovl_fail_trivial_conversion:
11244 case ovl_fail_bad_final_conversion:
11245 case ovl_fail_final_conversion_not_exact:
11246 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11247
11248 case ovl_fail_bad_conversion: {
11249 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11250 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11251 if (Cand->Conversions[I].isBad())
11252 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11253
11254 // FIXME: this currently happens when we're called from SemaInit
11255 // when user-conversion overload fails. Figure out how to handle
11256 // those conditions and diagnose them well.
11257 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11258 }
11259
11260 case ovl_fail_bad_target:
11261 return DiagnoseBadTarget(S, Cand);
11262
11263 case ovl_fail_enable_if:
11264 return DiagnoseFailedEnableIfAttr(S, Cand);
11265
11266 case ovl_fail_explicit:
11267 return DiagnoseFailedExplicitSpec(S, Cand);
11268
11269 case ovl_fail_inhctor_slice:
11270 // It's generally not interesting to note copy/move constructors here.
11271 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11272 return;
11273 S.Diag(Fn->getLocation(),
11274 diag::note_ovl_candidate_inherited_constructor_slice)
11275 << (Fn->getPrimaryTemplate() ? 1 : 0)
11276 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11277 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11278 return;
11279
11280 case ovl_fail_addr_not_available: {
11281 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11282 (void)Available;
11283 assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail
("!Available", "clang/lib/Sema/SemaOverload.cpp", 11283, __extension__
__PRETTY_FUNCTION__))
;
11284 break;
11285 }
11286 case ovl_non_default_multiversion_function:
11287 // Do nothing, these should simply be ignored.
11288 break;
11289
11290 case ovl_fail_constraints_not_satisfied: {
11291 std::string FnDesc;
11292 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11293 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11294 Cand->getRewriteKind(), FnDesc);
11295
11296 S.Diag(Fn->getLocation(),
11297 diag::note_ovl_candidate_constraints_not_satisfied)
11298 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11299 << FnDesc /* Ignored */;
11300 ConstraintSatisfaction Satisfaction;
11301 if (S.CheckFunctionConstraints(Fn, Satisfaction))
11302 break;
11303 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11304 }
11305 }
11306}
11307
11308static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11309 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11310 return;
11311
11312 // Desugar the type of the surrogate down to a function type,
11313 // retaining as many typedefs as possible while still showing
11314 // the function type (and, therefore, its parameter types).
11315 QualType FnType = Cand->Surrogate->getConversionType();
11316 bool isLValueReference = false;
11317 bool isRValueReference = false;
11318 bool isPointer = false;
11319 if (const LValueReferenceType *FnTypeRef =
11320 FnType->getAs<LValueReferenceType>()) {
11321 FnType = FnTypeRef->getPointeeType();
11322 isLValueReference = true;
11323 } else if (const RValueReferenceType *FnTypeRef =
11324 FnType->getAs<RValueReferenceType>()) {
11325 FnType = FnTypeRef->getPointeeType();
11326 isRValueReference = true;
11327 }
11328 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11329 FnType = FnTypePtr->getPointeeType();
11330 isPointer = true;
11331 }
11332 // Desugar down to a function type.
11333 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11334 // Reconstruct the pointer/reference as appropriate.
11335 if (isPointer) FnType = S.Context.getPointerType(FnType);
11336 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11337 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11338
11339 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11340 << FnType;
11341}
11342
11343static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11344 SourceLocation OpLoc,
11345 OverloadCandidate *Cand) {
11346 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast <bool> (Cand->Conversions.size() <= 2
&& "builtin operator is not binary") ? void (0) : __assert_fail
("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "clang/lib/Sema/SemaOverload.cpp", 11346, __extension__ __PRETTY_FUNCTION__
))
;
11347 std::string TypeStr("operator");
11348 TypeStr += Opc;
11349 TypeStr += "(";
11350 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11351 if (Cand->Conversions.size() == 1) {
11352 TypeStr += ")";
11353 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11354 } else {
11355 TypeStr += ", ";
11356 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11357 TypeStr += ")";
11358 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11359 }
11360}
11361
11362static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11363 OverloadCandidate *Cand) {
11364 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11365 if (ICS.isBad()) break; // all meaningless after first invalid
11366 if (!ICS.isAmbiguous()) continue;
11367
11368 ICS.DiagnoseAmbiguousConversion(
11369 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11370 }
11371}
11372
11373static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11374 if (Cand->Function)
11375 return Cand->Function->getLocation();
11376 if (Cand->IsSurrogate)
11377 return Cand->Surrogate->getLocation();
11378 return SourceLocation();
11379}
11380
11381static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11382 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11383 case Sema::TDK_Success:
11384 case Sema::TDK_NonDependentConversionFailure:
11385 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "clang/lib/Sema/SemaOverload.cpp", 11385)
;
11386
11387 case Sema::TDK_Invalid:
11388 case Sema::TDK_Incomplete:
11389 case Sema::TDK_IncompletePack:
11390 return 1;
11391
11392 case Sema::TDK_Underqualified:
11393 case Sema::TDK_Inconsistent:
11394 return 2;
11395
11396 case Sema::TDK_SubstitutionFailure:
11397 case Sema::TDK_DeducedMismatch:
11398 case Sema::TDK_ConstraintsNotSatisfied:
11399 case Sema::TDK_DeducedMismatchNested:
11400 case Sema::TDK_NonDeducedMismatch:
11401 case Sema::TDK_MiscellaneousDeductionFailure:
11402 case Sema::TDK_CUDATargetMismatch:
11403 return 3;
11404
11405 case Sema::TDK_InstantiationDepth:
11406 return 4;
11407
11408 case Sema::TDK_InvalidExplicitArguments:
11409 return 5;
11410
11411 case Sema::TDK_TooManyArguments:
11412 case Sema::TDK_TooFewArguments:
11413 return 6;
11414 }
11415 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "clang/lib/Sema/SemaOverload.cpp", 11415)
;
11416}
11417
11418namespace {
11419struct CompareOverloadCandidatesForDisplay {
11420 Sema &S;
11421 SourceLocation Loc;
11422 size_t NumArgs;
11423 OverloadCandidateSet::CandidateSetKind CSK;
11424
11425 CompareOverloadCandidatesForDisplay(
11426 Sema &S, SourceLocation Loc, size_t NArgs,
11427 OverloadCandidateSet::CandidateSetKind CSK)
11428 : S(S), NumArgs(NArgs), CSK(CSK) {}
11429
11430 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11431 // If there are too many or too few arguments, that's the high-order bit we
11432 // want to sort by, even if the immediate failure kind was something else.
11433 if (C->FailureKind == ovl_fail_too_many_arguments ||
11434 C->FailureKind == ovl_fail_too_few_arguments)
11435 return static_cast<OverloadFailureKind>(C->FailureKind);
11436
11437 if (C->Function) {
11438 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11439 return ovl_fail_too_many_arguments;
11440 if (NumArgs < C->Function->getMinRequiredArguments())
11441 return ovl_fail_too_few_arguments;
11442 }
11443
11444 return static_cast<OverloadFailureKind>(C->FailureKind);
11445 }
11446
11447 bool operator()(const OverloadCandidate *L,
11448 const OverloadCandidate *R) {
11449 // Fast-path this check.
11450 if (L == R) return false;
11451
11452 // Order first by viability.
11453 if (L->Viable) {
11454 if (!R->Viable) return true;
11455
11456 // TODO: introduce a tri-valued comparison for overload
11457 // candidates. Would be more worthwhile if we had a sort
11458 // that could exploit it.
11459 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11460 return true;
11461 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11462 return false;
11463 } else if (R->Viable)
11464 return false;
11465
11466 assert(L->Viable == R->Viable)(static_cast <bool> (L->Viable == R->Viable) ? void
(0) : __assert_fail ("L->Viable == R->Viable", "clang/lib/Sema/SemaOverload.cpp"
, 11466, __extension__ __PRETTY_FUNCTION__))
;
11467
11468 // Criteria by which we can sort non-viable candidates:
11469 if (!L->Viable) {
11470 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11471 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11472
11473 // 1. Arity mismatches come after other candidates.
11474 if (LFailureKind == ovl_fail_too_many_arguments ||
11475 LFailureKind == ovl_fail_too_few_arguments) {
11476 if (RFailureKind == ovl_fail_too_many_arguments ||
11477 RFailureKind == ovl_fail_too_few_arguments) {
11478 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11479 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11480 if (LDist == RDist) {
11481 if (LFailureKind == RFailureKind)
11482 // Sort non-surrogates before surrogates.
11483 return !L->IsSurrogate && R->IsSurrogate;
11484 // Sort candidates requiring fewer parameters than there were
11485 // arguments given after candidates requiring more parameters
11486 // than there were arguments given.
11487 return LFailureKind == ovl_fail_too_many_arguments;
11488 }
11489 return LDist < RDist;
11490 }
11491 return false;
11492 }
11493 if (RFailureKind == ovl_fail_too_many_arguments ||
11494 RFailureKind == ovl_fail_too_few_arguments)
11495 return true;
11496
11497 // 2. Bad conversions come first and are ordered by the number
11498 // of bad conversions and quality of good conversions.
11499 if (LFailureKind == ovl_fail_bad_conversion) {
11500 if (RFailureKind != ovl_fail_bad_conversion)
11501 return true;
11502
11503 // The conversion that can be fixed with a smaller number of changes,
11504 // comes first.
11505 unsigned numLFixes = L->Fix.NumConversionsFixed;
11506 unsigned numRFixes = R->Fix.NumConversionsFixed;
11507 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11508 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11509 if (numLFixes != numRFixes) {
11510 return numLFixes < numRFixes;
11511 }
11512
11513 // If there's any ordering between the defined conversions...
11514 // FIXME: this might not be transitive.
11515 assert(L->Conversions.size() == R->Conversions.size())(static_cast <bool> (L->Conversions.size() == R->
Conversions.size()) ? void (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "clang/lib/Sema/SemaOverload.cpp", 11515, __extension__ __PRETTY_FUNCTION__
))
;
11516
11517 int leftBetter = 0;
11518 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11519 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11520 switch (CompareImplicitConversionSequences(S, Loc,
11521 L->Conversions[I],
11522 R->Conversions[I])) {
11523 case ImplicitConversionSequence::Better:
11524 leftBetter++;
11525 break;
11526
11527 case ImplicitConversionSequence::Worse:
11528 leftBetter--;
11529 break;
11530
11531 case ImplicitConversionSequence::Indistinguishable:
11532 break;
11533 }
11534 }
11535 if (leftBetter > 0) return true;
11536 if (leftBetter < 0) return false;
11537
11538 } else if (RFailureKind == ovl_fail_bad_conversion)
11539 return false;
11540
11541 if (LFailureKind == ovl_fail_bad_deduction) {
11542 if (RFailureKind != ovl_fail_bad_deduction)
11543 return true;
11544
11545 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11546 return RankDeductionFailure(L->DeductionFailure)
11547 < RankDeductionFailure(R->DeductionFailure);
11548 } else if (RFailureKind == ovl_fail_bad_deduction)
11549 return false;
11550
11551 // TODO: others?
11552 }
11553
11554 // Sort everything else by location.
11555 SourceLocation LLoc = GetLocationForCandidate(L);
11556 SourceLocation RLoc = GetLocationForCandidate(R);
11557
11558 // Put candidates without locations (e.g. builtins) at the end.
11559 if (LLoc.isInvalid()) return false;
11560 if (RLoc.isInvalid()) return true;
11561
11562 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11563 }
11564};
11565}
11566
11567/// CompleteNonViableCandidate - Normally, overload resolution only
11568/// computes up to the first bad conversion. Produces the FixIt set if
11569/// possible.
11570static void
11571CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11572 ArrayRef<Expr *> Args,
11573 OverloadCandidateSet::CandidateSetKind CSK) {
11574 assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail
("!Cand->Viable", "clang/lib/Sema/SemaOverload.cpp", 11574
, __extension__ __PRETTY_FUNCTION__))
;
11575
11576 // Don't do anything on failures other than bad conversion.
11577 if (Cand->FailureKind != ovl_fail_bad_conversion)
11578 return;
11579
11580 // We only want the FixIts if all the arguments can be corrected.
11581 bool Unfixable = false;
11582 // Use a implicit copy initialization to check conversion fixes.
11583 Cand->Fix.setConversionChecker(TryCopyInitialization);
11584
11585 // Attempt to fix the bad conversion.
11586 unsigned ConvCount = Cand->Conversions.size();
11587 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11588 ++ConvIdx) {
11589 assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast <bool> (ConvIdx != ConvCount && "no bad conversion in candidate"
) ? void (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 11589, __extension__ __PRETTY_FUNCTION__
))
;
11590 if (Cand->Conversions[ConvIdx].isInitialized() &&
11591 Cand->Conversions[ConvIdx].isBad()) {
11592 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11593 break;
11594 }
11595 }
11596
11597 // FIXME: this should probably be preserved from the overload
11598 // operation somehow.
11599 bool SuppressUserConversions = false;
11600
11601 unsigned ConvIdx = 0;
11602 unsigned ArgIdx = 0;
11603 ArrayRef<QualType> ParamTypes;
11604 bool Reversed = Cand->isReversed();
11605
11606 if (Cand->IsSurrogate) {
11607 QualType ConvType
11608 = Cand->Surrogate->getConversionType().getNonReferenceType();
11609 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11610 ConvType = ConvPtrType->getPointeeType();
11611 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11612 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11613 ConvIdx = 1;
11614 } else if (Cand->Function) {
11615 ParamTypes =
11616 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11617 if (isa<CXXMethodDecl>(Cand->Function) &&
11618 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11619 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11620 ConvIdx = 1;
11621 if (CSK == OverloadCandidateSet::CSK_Operator &&
11622 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11623 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11624 ArgIdx = 1;
11625 }
11626 } else {
11627 // Builtin operator.
11628 assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail
("ConvCount <= 3", "clang/lib/Sema/SemaOverload.cpp", 11628
, __extension__ __PRETTY_FUNCTION__))
;
11629 ParamTypes = Cand->BuiltinParamTypes;
11630 }
11631
11632 // Fill in the rest of the conversions.
11633 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11634 ConvIdx != ConvCount;
11635 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11636 assert(ArgIdx < Args.size() && "no argument for this arg conversion")(static_cast <bool> (ArgIdx < Args.size() &&
"no argument for this arg conversion") ? void (0) : __assert_fail
("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "clang/lib/Sema/SemaOverload.cpp", 11636, __extension__ __PRETTY_FUNCTION__
))
;
11637 if (Cand->Conversions[ConvIdx].isInitialized()) {
11638 // We've already checked this conversion.
11639 } else if (ParamIdx < ParamTypes.size()) {
11640 if (ParamTypes[ParamIdx]->isDependentType())
11641 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11642 Args[ArgIdx]->getType());
11643 else {
11644 Cand->Conversions[ConvIdx] =
11645 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11646 SuppressUserConversions,
11647 /*InOverloadResolution=*/true,
11648 /*AllowObjCWritebackConversion=*/
11649 S.getLangOpts().ObjCAutoRefCount);
11650 // Store the FixIt in the candidate if it exists.
11651 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11652 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11653 }
11654 } else
11655 Cand->Conversions[ConvIdx].setEllipsis();
11656 }
11657}
11658
11659SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11660 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11661 SourceLocation OpLoc,
11662 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11663 // Sort the candidates by viability and position. Sorting directly would
11664 // be prohibitive, so we make a set of pointers and sort those.
11665 SmallVector<OverloadCandidate*, 32> Cands;
11666 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11667 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11668 if (!Filter(*Cand))
11669 continue;
11670 switch (OCD) {
11671 case OCD_AllCandidates:
11672 if (!Cand->Viable) {
11673 if (!Cand->Function && !Cand->IsSurrogate) {
11674 // This a non-viable builtin candidate. We do not, in general,
11675 // want to list every possible builtin candidate.
11676 continue;
11677 }
11678 CompleteNonViableCandidate(S, Cand, Args, Kind);
11679 }
11680 break;
11681
11682 case OCD_ViableCandidates:
11683 if (!Cand->Viable)
11684 continue;
11685 break;
11686
11687 case OCD_AmbiguousCandidates:
11688 if (!Cand->Best)
11689 continue;
11690 break;
11691 }
11692
11693 Cands.push_back(Cand);
11694 }
11695
11696 llvm::stable_sort(
11697 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11698
11699 return Cands;
11700}
11701
11702bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11703 SourceLocation OpLoc) {
11704 bool DeferHint = false;
11705 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11706 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11707 // host device candidates.
11708 auto WrongSidedCands =
11709 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11710 return (Cand.Viable == false &&
11711 Cand.FailureKind == ovl_fail_bad_target) ||
11712 (Cand.Function &&
11713 Cand.Function->template hasAttr<CUDAHostAttr>() &&
11714 Cand.Function->template hasAttr<CUDADeviceAttr>());
11715 });
11716 DeferHint = !WrongSidedCands.empty();
11717 }
11718 return DeferHint;
11719}
11720
11721/// When overload resolution fails, prints diagnostic messages containing the
11722/// candidates in the candidate set.
11723void OverloadCandidateSet::NoteCandidates(
11724 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11725 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11726 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11727
11728 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11729
11730 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11731
11732 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11733
11734 if (OCD == OCD_AmbiguousCandidates)
11735 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11736}
11737
11738void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11739 ArrayRef<OverloadCandidate *> Cands,
11740 StringRef Opc, SourceLocation OpLoc) {
11741 bool ReportedAmbiguousConversions = false;
11742
11743 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11744 unsigned CandsShown = 0;
11745 auto I = Cands.begin(), E = Cands.end();
11746 for (; I != E; ++I) {
11747 OverloadCandidate *Cand = *I;
11748
11749 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11750 ShowOverloads == Ovl_Best) {
11751 break;
11752 }
11753 ++CandsShown;
11754
11755 if (Cand->Function)
11756 NoteFunctionCandidate(S, Cand, Args.size(),
11757 /*TakingCandidateAddress=*/false, DestAS);
11758 else if (Cand->IsSurrogate)
11759 NoteSurrogateCandidate(S, Cand);
11760 else {
11761 assert(Cand->Viable &&(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11762, __extension__ __PRETTY_FUNCTION__
))
11762 "Non-viable built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11762, __extension__ __PRETTY_FUNCTION__
))
;
11763 // Generally we only see ambiguities including viable builtin
11764 // operators if overload resolution got screwed up by an
11765 // ambiguous user-defined conversion.
11766 //
11767 // FIXME: It's quite possible for different conversions to see
11768 // different ambiguities, though.
11769 if (!ReportedAmbiguousConversions) {
11770 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11771 ReportedAmbiguousConversions = true;
11772 }
11773
11774 // If this is a viable builtin, print it.
11775 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11776 }
11777 }
11778
11779 // Inform S.Diags that we've shown an overload set with N elements. This may
11780 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11781 S.Diags.overloadCandidatesShown(CandsShown);
11782
11783 if (I != E)
11784 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11785 shouldDeferDiags(S, Args, OpLoc))
11786 << int(E - I);
11787}
11788
11789static SourceLocation
11790GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11791 return Cand->Specialization ? Cand->Specialization->getLocation()
11792 : SourceLocation();
11793}
11794
11795namespace {
11796struct CompareTemplateSpecCandidatesForDisplay {
11797 Sema &S;
11798 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11799
11800 bool operator()(const TemplateSpecCandidate *L,
11801 const TemplateSpecCandidate *R) {
11802 // Fast-path this check.
11803 if (L == R)
11804 return false;
11805
11806 // Assuming that both candidates are not matches...
11807
11808 // Sort by the ranking of deduction failures.
11809 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11810 return RankDeductionFailure(L->DeductionFailure) <
11811 RankDeductionFailure(R->DeductionFailure);
11812
11813 // Sort everything else by location.
11814 SourceLocation LLoc = GetLocationForCandidate(L);
11815 SourceLocation RLoc = GetLocationForCandidate(R);
11816
11817 // Put candidates without locations (e.g. builtins) at the end.
11818 if (LLoc.isInvalid())
11819 return false;
11820 if (RLoc.isInvalid())
11821 return true;
11822
11823 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11824 }
11825};
11826}
11827
11828/// Diagnose a template argument deduction failure.
11829/// We are treating these failures as overload failures due to bad
11830/// deductions.
11831void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11832 bool ForTakingAddress) {
11833 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11834 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11835}
11836
11837void TemplateSpecCandidateSet::destroyCandidates() {
11838 for (iterator i = begin(), e = end(); i != e; ++i) {
11839 i->DeductionFailure.Destroy();
11840 }
11841}
11842
11843void TemplateSpecCandidateSet::clear() {
11844 destroyCandidates();
11845 Candidates.clear();
11846}
11847
11848/// NoteCandidates - When no template specialization match is found, prints
11849/// diagnostic messages containing the non-matching specializations that form
11850/// the candidate set.
11851/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11852/// OCD == OCD_AllCandidates and Cand->Viable == false.
11853void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11854 // Sort the candidates by position (assuming no candidate is a match).
11855 // Sorting directly would be prohibitive, so we make a set of pointers
11856 // and sort those.
11857 SmallVector<TemplateSpecCandidate *, 32> Cands;
11858 Cands.reserve(size());
11859 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11860 if (Cand->Specialization)
11861 Cands.push_back(Cand);
11862 // Otherwise, this is a non-matching builtin candidate. We do not,
11863 // in general, want to list every possible builtin candidate.
11864 }
11865
11866 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11867
11868 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11869 // for generalization purposes (?).
11870 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11871
11872 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11873 unsigned CandsShown = 0;
11874 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11875 TemplateSpecCandidate *Cand = *I;
11876
11877 // Set an arbitrary limit on the number of candidates we'll spam
11878 // the user with. FIXME: This limit should depend on details of the
11879 // candidate list.
11880 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11881 break;
11882 ++CandsShown;
11883
11884 assert(Cand->Specialization &&(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11885, __extension__ __PRETTY_FUNCTION__
))
11885 "Non-matching built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "clang/lib/Sema/SemaOverload.cpp", 11885, __extension__ __PRETTY_FUNCTION__
))
;
11886 Cand->NoteDeductionFailure(S, ForTakingAddress);
11887 }
11888
11889 if (I != E)
11890 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11891}
11892
11893// [PossiblyAFunctionType] --> [Return]
11894// NonFunctionType --> NonFunctionType
11895// R (A) --> R(A)
11896// R (*)(A) --> R (A)
11897// R (&)(A) --> R (A)
11898// R (S::*)(A) --> R (A)
11899QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11900 QualType Ret = PossiblyAFunctionType;
11901 if (const PointerType *ToTypePtr =
11902 PossiblyAFunctionType->getAs<PointerType>())
11903 Ret = ToTypePtr->getPointeeType();
11904 else if (const ReferenceType *ToTypeRef =
11905 PossiblyAFunctionType->getAs<ReferenceType>())
11906 Ret = ToTypeRef->getPointeeType();
11907 else if (const MemberPointerType *MemTypePtr =
11908 PossiblyAFunctionType->getAs<MemberPointerType>())
11909 Ret = MemTypePtr->getPointeeType();
11910 Ret =
11911 Context.getCanonicalType(Ret).getUnqualifiedType();
11912 return Ret;
11913}
11914
11915static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11916 bool Complain = true) {
11917 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11918 S.DeduceReturnType(FD, Loc, Complain))
11919 return true;
11920
11921 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11922 if (S.getLangOpts().CPlusPlus17 &&
11923 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11924 !S.ResolveExceptionSpec(Loc, FPT))
11925 return true;
11926
11927 return false;
11928}
11929
11930namespace {
11931// A helper class to help with address of function resolution
11932// - allows us to avoid passing around all those ugly parameters
11933class AddressOfFunctionResolver {
11934 Sema& S;
11935 Expr* SourceExpr;
11936 const QualType& TargetType;
11937 QualType TargetFunctionType; // Extracted function type from target type
11938
11939 bool Complain;
11940 //DeclAccessPair& ResultFunctionAccessPair;
11941 ASTContext& Context;
11942
11943 bool TargetTypeIsNonStaticMemberFunction;
11944 bool FoundNonTemplateFunction;
11945 bool StaticMemberFunctionFromBoundPointer;
11946 bool HasComplained;
11947
11948 OverloadExpr::FindResult OvlExprInfo;
11949 OverloadExpr *OvlExpr;
11950 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11951 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11952 TemplateSpecCandidateSet FailedCandidates;
11953
11954public:
11955 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11956 const QualType &TargetType, bool Complain)
11957 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11958 Complain(Complain), Context(S.getASTContext()),
11959 TargetTypeIsNonStaticMemberFunction(
11960 !!TargetType->getAs<MemberPointerType>()),
11961 FoundNonTemplateFunction(false),
11962 StaticMemberFunctionFromBoundPointer(false),
11963 HasComplained(false),
11964 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11965 OvlExpr(OvlExprInfo.Expression),
11966 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11967 ExtractUnqualifiedFunctionTypeFromTargetType();
11968
11969 if (TargetFunctionType->isFunctionType()) {
11970 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11971 if (!UME->isImplicitAccess() &&
11972 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11973 StaticMemberFunctionFromBoundPointer = true;
11974 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11975 DeclAccessPair dap;
11976 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11977 OvlExpr, false, &dap)) {
11978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11979 if (!Method->isStatic()) {
11980 // If the target type is a non-function type and the function found
11981 // is a non-static member function, pretend as if that was the
11982 // target, it's the only possible type to end up with.
11983 TargetTypeIsNonStaticMemberFunction = true;
11984
11985 // And skip adding the function if its not in the proper form.
11986 // We'll diagnose this due to an empty set of functions.
11987 if (!OvlExprInfo.HasFormOfMemberPointer)
11988 return;
11989 }
11990
11991 Matches.push_back(std::make_pair(dap, Fn));
11992 }
11993 return;
11994 }
11995
11996 if (OvlExpr->hasExplicitTemplateArgs())
11997 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11998
11999 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12000 // C++ [over.over]p4:
12001 // If more than one function is selected, [...]
12002 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12003 if (FoundNonTemplateFunction)
12004 EliminateAllTemplateMatches();
12005 else
12006 EliminateAllExceptMostSpecializedTemplate();
12007 }
12008 }
12009
12010 if (S.getLangOpts().CUDA && Matches.size() > 1)
12011 EliminateSuboptimalCudaMatches();
12012 }
12013
12014 bool hasComplained() const { return HasComplained; }
12015
12016private:
12017 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12018 QualType Discard;
12019 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12020 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12021 }
12022
12023 /// \return true if A is considered a better overload candidate for the
12024 /// desired type than B.
12025 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12026 // If A doesn't have exactly the correct type, we don't want to classify it
12027 // as "better" than anything else. This way, the user is required to
12028 // disambiguate for us if there are multiple candidates and no exact match.
12029 return candidateHasExactlyCorrectType(A) &&
12030 (!candidateHasExactlyCorrectType(B) ||
12031 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12032 }
12033
12034 /// \return true if we were able to eliminate all but one overload candidate,
12035 /// false otherwise.
12036 bool eliminiateSuboptimalOverloadCandidates() {
12037 // Same algorithm as overload resolution -- one pass to pick the "best",
12038 // another pass to be sure that nothing is better than the best.
12039 auto Best = Matches.begin();
12040 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12041 if (isBetterCandidate(I->second, Best->second))
12042 Best = I;
12043
12044 const FunctionDecl *BestFn = Best->second;
12045 auto IsBestOrInferiorToBest = [this, BestFn](
12046 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12047 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12048 };
12049
12050 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12051 // option, so we can potentially give the user a better error
12052 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12053 return false;
12054 Matches[0] = *Best;
12055 Matches.resize(1);
12056 return true;
12057 }
12058
12059 bool isTargetTypeAFunction() const {
12060 return TargetFunctionType->isFunctionType();
12061 }
12062
12063 // [ToType] [Return]
12064
12065 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12066 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12067 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12068 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12069 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12070 }
12071
12072 // return true if any matching specializations were found
12073 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12074 const DeclAccessPair& CurAccessFunPair) {
12075 if (CXXMethodDecl *Method
12076 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12077 // Skip non-static function templates when converting to pointer, and
12078 // static when converting to member pointer.
12079 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12080 return false;
12081 }
12082 else if (TargetTypeIsNonStaticMemberFunction)
12083 return false;
12084
12085 // C++ [over.over]p2:
12086 // If the name is a function template, template argument deduction is
12087 // done (14.8.2.2), and if the argument deduction succeeds, the
12088 // resulting template argument list is used to generate a single
12089 // function template specialization, which is added to the set of
12090 // overloaded functions considered.
12091 FunctionDecl *Specialization = nullptr;
12092 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12093 if (Sema::TemplateDeductionResult Result
12094 = S.DeduceTemplateArguments(FunctionTemplate,
12095 &OvlExplicitTemplateArgs,
12096 TargetFunctionType, Specialization,
12097 Info, /*IsAddressOfFunction*/true)) {
12098 // Make a note of the failed deduction for diagnostics.
12099 FailedCandidates.addCandidate()
12100 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12101 MakeDeductionFailureInfo(Context, Result, Info));
12102 return false;
12103 }
12104
12105 // Template argument deduction ensures that we have an exact match or
12106 // compatible pointer-to-function arguments that would be adjusted by ICS.
12107 // This function template specicalization works.
12108 assert(S.isSameOrCompatibleFunctionType((static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__
))
12109 Context.getCanonicalType(Specialization->getType()),(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__
))
12110 Context.getCanonicalType(TargetFunctionType)))(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "clang/lib/Sema/SemaOverload.cpp", 12110, __extension__ __PRETTY_FUNCTION__
))
;
12111
12112 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12113 return false;
12114
12115 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12116 return true;
12117 }
12118
12119 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12120 const DeclAccessPair& CurAccessFunPair) {
12121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12122 // Skip non-static functions when converting to pointer, and static
12123 // when converting to member pointer.
12124 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12125 return false;
12126 }
12127 else if (TargetTypeIsNonStaticMemberFunction)
12128 return false;
12129
12130 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12131 if (S.getLangOpts().CUDA)
12132 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
12133 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12134 return false;
12135 if (FunDecl->isMultiVersion()) {
12136 const auto *TA = FunDecl->getAttr<TargetAttr>();
12137 if (TA && !TA->isDefaultVersion())
12138 return false;
12139 }
12140
12141 // If any candidate has a placeholder return type, trigger its deduction
12142 // now.
12143 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12144 Complain)) {
12145 HasComplained |= Complain;
12146 return false;
12147 }
12148
12149 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12150 return false;
12151
12152 // If we're in C, we need to support types that aren't exactly identical.
12153 if (!S.getLangOpts().CPlusPlus ||
12154 candidateHasExactlyCorrectType(FunDecl)) {
12155 Matches.push_back(std::make_pair(
12156 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12157 FoundNonTemplateFunction = true;
12158 return true;
12159 }
12160 }
12161
12162 return false;
12163 }
12164
12165 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12166 bool Ret = false;
12167
12168 // If the overload expression doesn't have the form of a pointer to
12169 // member, don't try to convert it to a pointer-to-member type.
12170 if (IsInvalidFormOfPointerToMemberFunction())
12171 return false;
12172
12173 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12174 E = OvlExpr->decls_end();
12175 I != E; ++I) {
12176 // Look through any using declarations to find the underlying function.
12177 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12178
12179 // C++ [over.over]p3:
12180 // Non-member functions and static member functions match
12181 // targets of type "pointer-to-function" or "reference-to-function."
12182 // Nonstatic member functions match targets of
12183 // type "pointer-to-member-function."
12184 // Note that according to DR 247, the containing class does not matter.
12185 if (FunctionTemplateDecl *FunctionTemplate
12186 = dyn_cast<FunctionTemplateDecl>(Fn)) {
12187 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12188 Ret = true;
12189 }
12190 // If we have explicit template arguments supplied, skip non-templates.
12191 else if (!OvlExpr->hasExplicitTemplateArgs() &&
12192 AddMatchingNonTemplateFunction(Fn, I.getPair()))
12193 Ret = true;
12194 }
12195 assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0)
: __assert_fail ("Ret || Matches.empty()", "clang/lib/Sema/SemaOverload.cpp"
, 12195, __extension__ __PRETTY_FUNCTION__))
;
12196 return Ret;
12197 }
12198
12199 void EliminateAllExceptMostSpecializedTemplate() {
12200 // [...] and any given function template specialization F1 is
12201 // eliminated if the set contains a second function template
12202 // specialization whose function template is more specialized
12203 // than the function template of F1 according to the partial
12204 // ordering rules of 14.5.5.2.
12205
12206 // The algorithm specified above is quadratic. We instead use a
12207 // two-pass algorithm (similar to the one used to identify the
12208 // best viable function in an overload set) that identifies the
12209 // best function template (if it exists).
12210
12211 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12212 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12213 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12214
12215 // TODO: It looks like FailedCandidates does not serve much purpose
12216 // here, since the no_viable diagnostic has index 0.
12217 UnresolvedSetIterator Result = S.getMostSpecialized(
12218 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12219 SourceExpr->getBeginLoc(), S.PDiag(),
12220 S.PDiag(diag::err_addr_ovl_ambiguous)
12221 << Matches[0].second->getDeclName(),
12222 S.PDiag(diag::note_ovl_candidate)
12223 << (unsigned)oc_function << (unsigned)ocs_described_template,
12224 Complain, TargetFunctionType);
12225
12226 if (Result != MatchesCopy.end()) {
12227 // Make it the first and only element
12228 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12229 Matches[0].second = cast<FunctionDecl>(*Result);
12230 Matches.resize(1);
12231 } else
12232 HasComplained |= Complain;
12233 }
12234
12235 void EliminateAllTemplateMatches() {
12236 // [...] any function template specializations in the set are
12237 // eliminated if the set also contains a non-template function, [...]
12238 for (unsigned I = 0, N = Matches.size(); I != N; ) {
12239 if (Matches[I].second->getPrimaryTemplate() == nullptr)
12240 ++I;
12241 else {
12242 Matches[I] = Matches[--N];
12243 Matches.resize(N);
12244 }
12245 }
12246 }
12247
12248 void EliminateSuboptimalCudaMatches() {
12249 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12250 }
12251
12252public:
12253 void ComplainNoMatchesFound() const {
12254 assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail
("Matches.empty()", "clang/lib/Sema/SemaOverload.cpp", 12254
, __extension__ __PRETTY_FUNCTION__))
;
12255 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12256 << OvlExpr->getName() << TargetFunctionType
12257 << OvlExpr->getSourceRange();
12258 if (FailedCandidates.empty())
12259 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12260 /*TakingAddress=*/true);
12261 else {
12262 // We have some deduction failure messages. Use them to diagnose
12263 // the function templates, and diagnose the non-template candidates
12264 // normally.
12265 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12266 IEnd = OvlExpr->decls_end();
12267 I != IEnd; ++I)
12268 if (FunctionDecl *Fun =
12269 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12270 if (!functionHasPassObjectSizeParams(Fun))
12271 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12272 /*TakingAddress=*/true);
12273 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12274 }
12275 }
12276
12277 bool IsInvalidFormOfPointerToMemberFunction() const {
12278 return TargetTypeIsNonStaticMemberFunction &&
12279 !OvlExprInfo.HasFormOfMemberPointer;
12280 }
12281
12282 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12283 // TODO: Should we condition this on whether any functions might
12284 // have matched, or is it more appropriate to do that in callers?
12285 // TODO: a fixit wouldn't hurt.
12286 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12287 << TargetType << OvlExpr->getSourceRange();
12288 }
12289
12290 bool IsStaticMemberFunctionFromBoundPointer() const {
12291 return StaticMemberFunctionFromBoundPointer;
12292 }
12293
12294 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12295 S.Diag(OvlExpr->getBeginLoc(),
12296 diag::err_invalid_form_pointer_member_function)
12297 << OvlExpr->getSourceRange();
12298 }
12299
12300 void ComplainOfInvalidConversion() const {
12301 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12302 << OvlExpr->getName() << TargetType;
12303 }
12304
12305 void ComplainMultipleMatchesFound() const {
12306 assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) :
__assert_fail ("Matches.size() > 1", "clang/lib/Sema/SemaOverload.cpp"
, 12306, __extension__ __PRETTY_FUNCTION__))
;
12307 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12308 << OvlExpr->getName() << OvlExpr->getSourceRange();
12309 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12310 /*TakingAddress=*/true);
12311 }
12312
12313 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12314
12315 int getNumMatches() const { return Matches.size(); }
12316
12317 FunctionDecl* getMatchingFunctionDecl() const {
12318 if (Matches.size() != 1) return nullptr;
12319 return Matches[0].second;
12320 }
12321
12322 const DeclAccessPair* getMatchingFunctionAccessPair() const {
12323 if (Matches.size() != 1) return nullptr;
12324 return &Matches[0].first;
12325 }
12326};
12327}
12328
12329/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12330/// an overloaded function (C++ [over.over]), where @p From is an
12331/// expression with overloaded function type and @p ToType is the type
12332/// we're trying to resolve to. For example:
12333///
12334/// @code
12335/// int f(double);
12336/// int f(int);
12337///
12338/// int (*pfd)(double) = f; // selects f(double)
12339/// @endcode
12340///
12341/// This routine returns the resulting FunctionDecl if it could be
12342/// resolved, and NULL otherwise. When @p Complain is true, this
12343/// routine will emit diagnostics if there is an error.
12344FunctionDecl *
12345Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12346 QualType TargetType,
12347 bool Complain,
12348 DeclAccessPair &FoundResult,
12349 bool *pHadMultipleCandidates) {
12350 assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast <bool> (AddressOfExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 12350, __extension__ __PRETTY_FUNCTION__
))
;
12351
12352 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12353 Complain);
12354 int NumMatches = Resolver.getNumMatches();
12355 FunctionDecl *Fn = nullptr;
12356 bool ShouldComplain = Complain && !Resolver.hasComplained();
12357 if (NumMatches == 0 && ShouldComplain) {
12358 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12359 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12360 else
12361 Resolver.ComplainNoMatchesFound();
12362 }
12363 else if (NumMatches > 1 && ShouldComplain)
12364 Resolver.ComplainMultipleMatchesFound();
12365 else if (NumMatches == 1) {
12366 Fn = Resolver.getMatchingFunctionDecl();
12367 assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn"
, "clang/lib/Sema/SemaOverload.cpp", 12367, __extension__ __PRETTY_FUNCTION__
))
;
12368 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12369 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12370 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12371 if (Complain) {
12372 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12373 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12374 else
12375 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12376 }
12377 }
12378
12379 if (pHadMultipleCandidates)
12380 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12381 return Fn;
12382}
12383
12384/// Given an expression that refers to an overloaded function, try to
12385/// resolve that function to a single function that can have its address taken.
12386/// This will modify `Pair` iff it returns non-null.
12387///
12388/// This routine can only succeed if from all of the candidates in the overload
12389/// set for SrcExpr that can have their addresses taken, there is one candidate
12390/// that is more constrained than the rest.
12391FunctionDecl *
12392Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12393 OverloadExpr::FindResult R = OverloadExpr::find(E);
12394 OverloadExpr *Ovl = R.Expression;
12395 bool IsResultAmbiguous = false;
12396 FunctionDecl *Result = nullptr;
12397 DeclAccessPair DAP;
12398 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12399
12400 auto CheckMoreConstrained =
12401 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12402 SmallVector<const Expr *, 1> AC1, AC2;
12403 FD1->getAssociatedConstraints(AC1);
12404 FD2->getAssociatedConstraints(AC2);
12405 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12406 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12407 return None;
12408 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12409 return None;
12410 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12411 return None;
12412 return AtLeastAsConstrained1;
12413 };
12414
12415 // Don't use the AddressOfResolver because we're specifically looking for
12416 // cases where we have one overload candidate that lacks
12417 // enable_if/pass_object_size/...
12418 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12419 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12420 if (!FD)
12421 return nullptr;
12422
12423 if (!checkAddressOfFunctionIsAvailable(FD))
12424 continue;
12425
12426 // We have more than one result - see if it is more constrained than the
12427 // previous one.
12428 if (Result) {
12429 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12430 Result);
12431 if (!MoreConstrainedThanPrevious) {
12432 IsResultAmbiguous = true;
12433 AmbiguousDecls.push_back(FD);
12434 continue;
12435 }
12436 if (!*MoreConstrainedThanPrevious)
12437 continue;
12438 // FD is more constrained - replace Result with it.
12439 }
12440 IsResultAmbiguous = false;
12441 DAP = I.getPair();
12442 Result = FD;
12443 }
12444
12445 if (IsResultAmbiguous)
12446 return nullptr;
12447
12448 if (Result) {
12449 SmallVector<const Expr *, 1> ResultAC;
12450 // We skipped over some ambiguous declarations which might be ambiguous with
12451 // the selected result.
12452 for (FunctionDecl *Skipped : AmbiguousDecls)
12453 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12454 return nullptr;
12455 Pair = DAP;
12456 }
12457 return Result;
12458}
12459
12460/// Given an overloaded function, tries to turn it into a non-overloaded
12461/// function reference using resolveAddressOfSingleOverloadCandidate. This
12462/// will perform access checks, diagnose the use of the resultant decl, and, if
12463/// requested, potentially perform a function-to-pointer decay.
12464///
12465/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12466/// Otherwise, returns true. This may emit diagnostics and return true.
12467bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12468 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12469 Expr *E = SrcExpr.get();
12470 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast <bool> (E->getType() == Context.OverloadTy
&& "SrcExpr must be an overload") ? void (0) : __assert_fail
("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "clang/lib/Sema/SemaOverload.cpp", 12470, __extension__ __PRETTY_FUNCTION__
))
;
12471
12472 DeclAccessPair DAP;
12473 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12474 if (!Found || Found->isCPUDispatchMultiVersion() ||
12475 Found->isCPUSpecificMultiVersion())
12476 return false;
12477
12478 // Emitting multiple diagnostics for a function that is both inaccessible and
12479 // unavailable is consistent with our behavior elsewhere. So, always check
12480 // for both.
12481 DiagnoseUseOfDecl(Found, E->getExprLoc());
12482 CheckAddressOfMemberAccess(E, DAP);
12483 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12484 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12485 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12486 else
12487 SrcExpr = Fixed;
12488 return true;
12489}
12490
12491/// Given an expression that refers to an overloaded function, try to
12492/// resolve that overloaded function expression down to a single function.
12493///
12494/// This routine can only resolve template-ids that refer to a single function
12495/// template, where that template-id refers to a single template whose template
12496/// arguments are either provided by the template-id or have defaults,
12497/// as described in C++0x [temp.arg.explicit]p3.
12498///
12499/// If no template-ids are found, no diagnostics are emitted and NULL is
12500/// returned.
12501FunctionDecl *
12502Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12503 bool Complain,
12504 DeclAccessPair *FoundResult) {
12505 // C++ [over.over]p1:
12506 // [...] [Note: any redundant set of parentheses surrounding the
12507 // overloaded function name is ignored (5.1). ]
12508 // C++ [over.over]p1:
12509 // [...] The overloaded function name can be preceded by the &
12510 // operator.
12511
12512 // If we didn't actually find any template-ids, we're done.
12513 if (!ovl->hasExplicitTemplateArgs())
12514 return nullptr;
12515
12516 TemplateArgumentListInfo ExplicitTemplateArgs;
12517 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12518 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12519
12520 // Look through all of the overloaded functions, searching for one
12521 // whose type matches exactly.
12522 FunctionDecl *Matched = nullptr;
12523 for (UnresolvedSetIterator I = ovl->decls_begin(),
12524 E = ovl->decls_end(); I != E; ++I) {
12525 // C++0x [temp.arg.explicit]p3:
12526 // [...] In contexts where deduction is done and fails, or in contexts
12527 // where deduction is not done, if a template argument list is
12528 // specified and it, along with any default template arguments,
12529 // identifies a single function template specialization, then the
12530 // template-id is an lvalue for the function template specialization.
12531 FunctionTemplateDecl *FunctionTemplate
12532 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12533
12534 // C++ [over.over]p2:
12535 // If the name is a function template, template argument deduction is
12536 // done (14.8.2.2), and if the argument deduction succeeds, the
12537 // resulting template argument list is used to generate a single
12538 // function template specialization, which is added to the set of
12539 // overloaded functions considered.
12540 FunctionDecl *Specialization = nullptr;
12541 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12542 if (TemplateDeductionResult Result
12543 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12544 Specialization, Info,
12545 /*IsAddressOfFunction*/true)) {
12546 // Make a note of the failed deduction for diagnostics.
12547 // TODO: Actually use the failed-deduction info?
12548 FailedCandidates.addCandidate()
12549 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12550 MakeDeductionFailureInfo(Context, Result, Info));
12551 continue;
12552 }
12553
12554 assert(Specialization && "no specialization and no error?")(static_cast <bool> (Specialization && "no specialization and no error?"
) ? void (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "clang/lib/Sema/SemaOverload.cpp", 12554, __extension__ __PRETTY_FUNCTION__
))
;
12555
12556 // Multiple matches; we can't resolve to a single declaration.
12557 if (Matched) {
12558 if (Complain) {
12559 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12560 << ovl->getName();
12561 NoteAllOverloadCandidates(ovl);
12562 }
12563 return nullptr;
12564 }
12565
12566 Matched = Specialization;
12567 if (FoundResult) *FoundResult = I.getPair();
12568 }
12569
12570 if (Matched &&
12571 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12572 return nullptr;
12573
12574 return Matched;
12575}
12576
12577// Resolve and fix an overloaded expression that can be resolved
12578// because it identifies a single function template specialization.
12579//
12580// Last three arguments should only be supplied if Complain = true
12581//
12582// Return true if it was logically possible to so resolve the
12583// expression, regardless of whether or not it succeeded. Always
12584// returns true if 'complain' is set.
12585bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12586 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12587 bool complain, SourceRange OpRangeForComplaining,
12588 QualType DestTypeForComplaining,
12589 unsigned DiagIDForComplaining) {
12590 assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast <bool> (SrcExpr.get()->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 12590, __extension__ __PRETTY_FUNCTION__
))
;
12591
12592 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12593
12594 DeclAccessPair found;
12595 ExprResult SingleFunctionExpression;
12596 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12597 ovl.Expression, /*complain*/ false, &found)) {
12598 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12599 SrcExpr = ExprError();
12600 return true;
12601 }
12602
12603 // It is only correct to resolve to an instance method if we're
12604 // resolving a form that's permitted to be a pointer to member.
12605 // Otherwise we'll end up making a bound member expression, which
12606 // is illegal in all the contexts we resolve like this.
12607 if (!ovl.HasFormOfMemberPointer &&
12608 isa<CXXMethodDecl>(fn) &&
12609 cast<CXXMethodDecl>(fn)->isInstance()) {
12610 if (!complain) return false;
12611
12612 Diag(ovl.Expression->getExprLoc(),
12613 diag::err_bound_member_function)
12614 << 0 << ovl.Expression->getSourceRange();
12615
12616 // TODO: I believe we only end up here if there's a mix of
12617 // static and non-static candidates (otherwise the expression
12618 // would have 'bound member' type, not 'overload' type).
12619 // Ideally we would note which candidate was chosen and why
12620 // the static candidates were rejected.
12621 SrcExpr = ExprError();
12622 return true;
12623 }
12624
12625 // Fix the expression to refer to 'fn'.
12626 SingleFunctionExpression =
12627 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12628
12629 // If desired, do function-to-pointer decay.
12630 if (doFunctionPointerConverion) {
12631 SingleFunctionExpression =
12632 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12633 if (SingleFunctionExpression.isInvalid()) {
12634 SrcExpr = ExprError();
12635 return true;
12636 }
12637 }
12638 }
12639
12640 if (!SingleFunctionExpression.isUsable()) {
12641 if (complain) {
12642 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12643 << ovl.Expression->getName()
12644 << DestTypeForComplaining
12645 << OpRangeForComplaining
12646 << ovl.Expression->getQualifierLoc().getSourceRange();
12647 NoteAllOverloadCandidates(SrcExpr.get());
12648
12649 SrcExpr = ExprError();
12650 return true;
12651 }
12652
12653 return false;
12654 }
12655
12656 SrcExpr = SingleFunctionExpression;
12657 return true;
12658}
12659
12660/// Add a single candidate to the overload set.
12661static void AddOverloadedCallCandidate(Sema &S,
12662 DeclAccessPair FoundDecl,
12663 TemplateArgumentListInfo *ExplicitTemplateArgs,
12664 ArrayRef<Expr *> Args,
12665 OverloadCandidateSet &CandidateSet,
12666 bool PartialOverloading,
12667 bool KnownValid) {
12668 NamedDecl *Callee = FoundDecl.getDecl();
12669 if (isa<UsingShadowDecl>(Callee))
12670 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12671
12672 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12673 if (ExplicitTemplateArgs) {
12674 assert(!KnownValid && "Explicit template arguments?")(static_cast <bool> (!KnownValid && "Explicit template arguments?"
) ? void (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "clang/lib/Sema/SemaOverload.cpp", 12674, __extension__ __PRETTY_FUNCTION__
))
;
12675 return;
12676 }
12677 // Prevent ill-formed function decls to be added as overload candidates.
12678 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12679 return;
12680
12681 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12682 /*SuppressUserConversions=*/false,
12683 PartialOverloading);
12684 return;
12685 }
12686
12687 if (FunctionTemplateDecl *FuncTemplate
12688 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12689 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12690 ExplicitTemplateArgs, Args, CandidateSet,
12691 /*SuppressUserConversions=*/false,
12692 PartialOverloading);
12693 return;
12694 }
12695
12696 assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast <bool> (!KnownValid && "unhandled case in overloaded call candidate"
) ? void (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "clang/lib/Sema/SemaOverload.cpp", 12696, __extension__ __PRETTY_FUNCTION__
))
;
12697}
12698
12699/// Add the overload candidates named by callee and/or found by argument
12700/// dependent lookup to the given overload set.
12701void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12702 ArrayRef<Expr *> Args,
12703 OverloadCandidateSet &CandidateSet,
12704 bool PartialOverloading) {
12705
12706#ifndef NDEBUG
12707 // Verify that ArgumentDependentLookup is consistent with the rules
12708 // in C++0x [basic.lookup.argdep]p3:
12709 //
12710 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12711 // and let Y be the lookup set produced by argument dependent
12712 // lookup (defined as follows). If X contains
12713 //
12714 // -- a declaration of a class member, or
12715 //
12716 // -- a block-scope function declaration that is not a
12717 // using-declaration, or
12718 //
12719 // -- a declaration that is neither a function or a function
12720 // template
12721 //
12722 // then Y is empty.
12723
12724 if (ULE->requiresADL()) {
12725 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12726 E = ULE->decls_end(); I != E; ++I) {
12727 assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord
()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "clang/lib/Sema/SemaOverload.cpp", 12727, __extension__ __PRETTY_FUNCTION__
))
;
12728 assert(isa<UsingShadowDecl>(*I) ||(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "clang/lib/Sema/SemaOverload.cpp", 12729, __extension__ __PRETTY_FUNCTION__
))
12729 !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "clang/lib/Sema/SemaOverload.cpp", 12729, __extension__ __PRETTY_FUNCTION__
))
;
12730 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "clang/lib/Sema/SemaOverload.cpp", 12730, __extension__ __PRETTY_FUNCTION__
))
;
12731 }
12732 }
12733#endif
12734
12735 // It would be nice to avoid this copy.
12736 TemplateArgumentListInfo TABuffer;
12737 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12738 if (ULE->hasExplicitTemplateArgs()) {
12739 ULE->copyTemplateArgumentsInto(TABuffer);
12740 ExplicitTemplateArgs = &TABuffer;
12741 }
12742
12743 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12744 E = ULE->decls_end(); I != E; ++I)
12745 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12746 CandidateSet, PartialOverloading,
12747 /*KnownValid*/ true);
12748
12749 if (ULE->requiresADL())
12750 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12751 Args, ExplicitTemplateArgs,
12752 CandidateSet, PartialOverloading);
12753}
12754
12755/// Add the call candidates from the given set of lookup results to the given
12756/// overload set. Non-function lookup results are ignored.
12757void Sema::AddOverloadedCallCandidates(
12758 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12759 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12760 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12761 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12762 CandidateSet, false, /*KnownValid*/ false);
12763}
12764
12765/// Determine whether a declaration with the specified name could be moved into
12766/// a different namespace.
12767static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12768 switch (Name.getCXXOverloadedOperator()) {
12769 case OO_New: case OO_Array_New:
12770 case OO_Delete: case OO_Array_Delete:
12771 return false;
12772
12773 default:
12774 return true;
12775 }
12776}
12777
12778/// Attempt to recover from an ill-formed use of a non-dependent name in a
12779/// template, where the non-dependent name was declared after the template
12780/// was defined. This is common in code written for a compilers which do not
12781/// correctly implement two-stage name lookup.
12782///
12783/// Returns true if a viable candidate was found and a diagnostic was issued.
12784static bool DiagnoseTwoPhaseLookup(
12785 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12786 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12787 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12788 CXXRecordDecl **FoundInClass = nullptr) {
12789 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12790 return false;
12791
12792 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12793 if (DC->isTransparentContext())
12794 continue;
12795
12796 SemaRef.LookupQualifiedName(R, DC);
12797
12798 if (!R.empty()) {
12799 R.suppressDiagnostics();
12800
12801 OverloadCandidateSet Candidates(FnLoc, CSK);
12802 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12803 Candidates);
12804
12805 OverloadCandidateSet::iterator Best;
12806 OverloadingResult OR =
12807 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12808
12809 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12810 // We either found non-function declarations or a best viable function
12811 // at class scope. A class-scope lookup result disables ADL. Don't
12812 // look past this, but let the caller know that we found something that
12813 // either is, or might be, usable in this class.
12814 if (FoundInClass) {
12815 *FoundInClass = RD;
12816 if (OR == OR_Success) {
12817 R.clear();
12818 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12819 R.resolveKind();
12820 }
12821 }
12822 return false;
12823 }
12824
12825 if (OR != OR_Success) {
12826 // There wasn't a unique best function or function template.
12827 return false;
12828 }
12829
12830 // Find the namespaces where ADL would have looked, and suggest
12831 // declaring the function there instead.
12832 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12833 Sema::AssociatedClassSet AssociatedClasses;
12834 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12835 AssociatedNamespaces,
12836 AssociatedClasses);
12837 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12838 if (canBeDeclaredInNamespace(R.getLookupName())) {
12839 DeclContext *Std = SemaRef.getStdNamespace();
12840 for (Sema::AssociatedNamespaceSet::iterator
12841 it = AssociatedNamespaces.begin(),
12842 end = AssociatedNamespaces.end(); it != end; ++it) {
12843 // Never suggest declaring a function within namespace 'std'.
12844 if (Std && Std->Encloses(*it))
12845 continue;
12846
12847 // Never suggest declaring a function within a namespace with a
12848 // reserved name, like __gnu_cxx.
12849 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12850 if (NS &&
12851 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12852 continue;
12853
12854 SuggestedNamespaces.insert(*it);
12855 }
12856 }
12857
12858 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12859 << R.getLookupName();
12860 if (SuggestedNamespaces.empty()) {
12861 SemaRef.Diag(Best->Function->getLocation(),
12862 diag::note_not_found_by_two_phase_lookup)
12863 << R.getLookupName() << 0;
12864 } else if (SuggestedNamespaces.size() == 1) {
12865 SemaRef.Diag(Best->Function->getLocation(),
12866 diag::note_not_found_by_two_phase_lookup)
12867 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12868 } else {
12869 // FIXME: It would be useful to list the associated namespaces here,
12870 // but the diagnostics infrastructure doesn't provide a way to produce
12871 // a localized representation of a list of items.
12872 SemaRef.Diag(Best->Function->getLocation(),
12873 diag::note_not_found_by_two_phase_lookup)
12874 << R.getLookupName() << 2;
12875 }
12876
12877 // Try to recover by calling this function.
12878 return true;
12879 }
12880
12881 R.clear();
12882 }
12883
12884 return false;
12885}
12886
12887/// Attempt to recover from ill-formed use of a non-dependent operator in a
12888/// template, where the non-dependent operator was declared after the template
12889/// was defined.
12890///
12891/// Returns true if a viable candidate was found and a diagnostic was issued.
12892static bool
12893DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12894 SourceLocation OpLoc,
12895 ArrayRef<Expr *> Args) {
12896 DeclarationName OpName =
12897 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12898 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12899 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12900 OverloadCandidateSet::CSK_Operator,
12901 /*ExplicitTemplateArgs=*/nullptr, Args);
12902}
12903
12904namespace {
12905class BuildRecoveryCallExprRAII {
12906 Sema &SemaRef;
12907public:
12908 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12909 assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr
== false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "clang/lib/Sema/SemaOverload.cpp", 12909, __extension__ __PRETTY_FUNCTION__
))
;
12910 SemaRef.IsBuildingRecoveryCallExpr = true;
12911 }
12912
12913 ~BuildRecoveryCallExprRAII() {
12914 SemaRef.IsBuildingRecoveryCallExpr = false;
12915 }
12916};
12917
12918}
12919
12920/// Attempts to recover from a call where no functions were found.
12921///
12922/// This function will do one of three things:
12923/// * Diagnose, recover, and return a recovery expression.
12924/// * Diagnose, fail to recover, and return ExprError().
12925/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
12926/// expected to diagnose as appropriate.
12927static ExprResult
12928BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12929 UnresolvedLookupExpr *ULE,
12930 SourceLocation LParenLoc,
12931 MutableArrayRef<Expr *> Args,
12932 SourceLocation RParenLoc,
12933 bool EmptyLookup, bool AllowTypoCorrection) {
12934 // Do not try to recover if it is already building a recovery call.
12935 // This stops infinite loops for template instantiations like
12936 //
12937 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12938 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12939 if (SemaRef.IsBuildingRecoveryCallExpr)
12940 return ExprResult();
12941 BuildRecoveryCallExprRAII RCE(SemaRef);
12942
12943 CXXScopeSpec SS;
12944 SS.Adopt(ULE->getQualifierLoc());
12945 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12946
12947 TemplateArgumentListInfo TABuffer;
12948 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12949 if (ULE->hasExplicitTemplateArgs()) {
12950 ULE->copyTemplateArgumentsInto(TABuffer);
12951 ExplicitTemplateArgs = &TABuffer;
12952 }
12953
12954 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12955 Sema::LookupOrdinaryName);
12956 CXXRecordDecl *FoundInClass = nullptr;
12957 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12958 OverloadCandidateSet::CSK_Normal,
12959 ExplicitTemplateArgs, Args, &FoundInClass)) {
12960 // OK, diagnosed a two-phase lookup issue.
12961 } else if (EmptyLookup) {
12962 // Try to recover from an empty lookup with typo correction.
12963 R.clear();
12964 NoTypoCorrectionCCC NoTypoValidator{};
12965 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12966 ExplicitTemplateArgs != nullptr,
12967 dyn_cast<MemberExpr>(Fn));
12968 CorrectionCandidateCallback &Validator =
12969 AllowTypoCorrection
12970 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12971 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12972 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12973 Args))
12974 return ExprError();
12975 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
12976 // We found a usable declaration of the name in a dependent base of some
12977 // enclosing class.
12978 // FIXME: We should also explain why the candidates found by name lookup
12979 // were not viable.
12980 if (SemaRef.DiagnoseDependentMemberLookup(R))
12981 return ExprError();
12982 } else {
12983 // We had viable candidates and couldn't recover; let the caller diagnose
12984 // this.
12985 return ExprResult();
12986 }
12987
12988 // If we get here, we should have issued a diagnostic and formed a recovery
12989 // lookup result.
12990 assert(!R.empty() && "lookup results empty despite recovery")(static_cast <bool> (!R.empty() && "lookup results empty despite recovery"
) ? void (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "clang/lib/Sema/SemaOverload.cpp", 12990, __extension__ __PRETTY_FUNCTION__
))
;
12991
12992 // If recovery created an ambiguity, just bail out.
12993 if (R.isAmbiguous()) {
12994 R.suppressDiagnostics();
12995 return ExprError();
12996 }
12997
12998 // Build an implicit member call if appropriate. Just drop the
12999 // casts and such from the call, we don't really care.
13000 ExprResult NewFn = ExprError();
13001 if ((*R.begin())->isCXXClassMember())
13002 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13003 ExplicitTemplateArgs, S);
13004 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13005 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13006 ExplicitTemplateArgs);
13007 else
13008 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13009
13010 if (NewFn.isInvalid())
13011 return ExprError();
13012
13013 // This shouldn't cause an infinite loop because we're giving it
13014 // an expression with viable lookup results, which should never
13015 // end up here.
13016 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13017 MultiExprArg(Args.data(), Args.size()),
13018 RParenLoc);
13019}
13020
13021/// Constructs and populates an OverloadedCandidateSet from
13022/// the given function.
13023/// \returns true when an the ExprResult output parameter has been set.
13024bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13025 UnresolvedLookupExpr *ULE,
13026 MultiExprArg Args,
13027 SourceLocation RParenLoc,
13028 OverloadCandidateSet *CandidateSet,
13029 ExprResult *Result) {
13030#ifndef NDEBUG
13031 if (ULE->requiresADL()) {
13032 // To do ADL, we must have found an unqualified name.
13033 assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast <bool> (!ULE->getQualifier() &&
"qualified name with ADL") ? void (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "clang/lib/Sema/SemaOverload.cpp", 13033, __extension__ __PRETTY_FUNCTION__
))
;
13034
13035 // We don't perform ADL for implicit declarations of builtins.
13036 // Verify that this was correctly set up.
13037 FunctionDecl *F;
13038 if (ULE->decls_begin() != ULE->decls_end() &&
13039 ULE->decls_begin() + 1 == ULE->decls_end() &&
13040 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13041 F->getBuiltinID() && F->isImplicit())
13042 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "clang/lib/Sema/SemaOverload.cpp", 13042)
;
13043
13044 // We don't perform ADL in C.
13045 assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast <bool> (getLangOpts().CPlusPlus &&
"ADL enabled in C") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "clang/lib/Sema/SemaOverload.cpp", 13045, __extension__ __PRETTY_FUNCTION__
))
;
13046 }
13047#endif
13048
13049 UnbridgedCastsSet UnbridgedCasts;
13050 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13051 *Result = ExprError();
13052 return true;
13053 }
13054
13055 // Add the functions denoted by the callee to the set of candidate
13056 // functions, including those from argument-dependent lookup.
13057 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13058
13059 if (getLangOpts().MSVCCompat &&
13060 CurContext->isDependentContext() && !isSFINAEContext() &&
13061 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13062
13063 OverloadCandidateSet::iterator Best;
13064 if (CandidateSet->empty() ||
13065 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13066 OR_No_Viable_Function) {
13067 // In Microsoft mode, if we are inside a template class member function
13068 // then create a type dependent CallExpr. The goal is to postpone name
13069 // lookup to instantiation time to be able to search into type dependent
13070 // base classes.
13071 CallExpr *CE =
13072 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13073 RParenLoc, CurFPFeatureOverrides());
13074 CE->markDependentForPostponedNameLookup();
13075 *Result = CE;
13076 return true;
13077 }
13078 }
13079
13080 if (CandidateSet->empty())
13081 return false;
13082
13083 UnbridgedCasts.restore();
13084 return false;
13085}
13086
13087// Guess at what the return type for an unresolvable overload should be.
13088static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13089 OverloadCandidateSet::iterator *Best) {
13090 llvm::Optional<QualType> Result;
13091 // Adjust Type after seeing a candidate.
13092 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13093 if (!Candidate.Function)
13094 return;
13095 if (Candidate.Function->isInvalidDecl())
13096 return;
13097 QualType T = Candidate.Function->getReturnType();
13098 if (T.isNull())
13099 return;
13100 if (!Result)
13101 Result = T;
13102 else if (Result != T)
13103 Result = QualType();
13104 };
13105
13106 // Look for an unambiguous type from a progressively larger subset.
13107 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13108 //
13109 // First, consider only the best candidate.
13110 if (Best && *Best != CS.end())
13111 ConsiderCandidate(**Best);
13112 // Next, consider only viable candidates.
13113 if (!Result)
13114 for (const auto &C : CS)
13115 if (C.Viable)
13116 ConsiderCandidate(C);
13117 // Finally, consider all candidates.
13118 if (!Result)
13119 for (const auto &C : CS)
13120 ConsiderCandidate(C);
13121
13122 if (!Result)
13123 return QualType();
13124 auto Value = Result.getValue();
13125 if (Value.isNull() || Value->isUndeducedType())
13126 return QualType();
13127 return Value;
13128}
13129
13130/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13131/// the completed call expression. If overload resolution fails, emits
13132/// diagnostics and returns ExprError()
13133static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13134 UnresolvedLookupExpr *ULE,
13135 SourceLocation LParenLoc,
13136 MultiExprArg Args,
13137 SourceLocation RParenLoc,
13138 Expr *ExecConfig,
13139 OverloadCandidateSet *CandidateSet,
13140 OverloadCandidateSet::iterator *Best,
13141 OverloadingResult OverloadResult,
13142 bool AllowTypoCorrection) {
13143 switch (OverloadResult) {
13144 case OR_Success: {
13145 FunctionDecl *FDecl = (*Best)->Function;
13146 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13147 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13148 return ExprError();
13149 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13150 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13151 ExecConfig, /*IsExecConfig=*/false,
13152 (*Best)->IsADLCandidate);
13153 }
13154
13155 case OR_No_Viable_Function: {
13156 // Try to recover by looking for viable functions which the user might
13157 // have meant to call.
13158 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13159 Args, RParenLoc,
13160 CandidateSet->empty(),
13161 AllowTypoCorrection);
13162 if (Recovery.isInvalid() || Recovery.isUsable())
13163 return Recovery;
13164
13165 // If the user passes in a function that we can't take the address of, we
13166 // generally end up emitting really bad error messages. Here, we attempt to
13167 // emit better ones.
13168 for (const Expr *Arg : Args) {
13169 if (!Arg->getType()->isFunctionType())
13170 continue;
13171 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13172 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13173 if (FD &&
13174 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13175 Arg->getExprLoc()))
13176 return ExprError();
13177 }
13178 }
13179
13180 CandidateSet->NoteCandidates(
13181 PartialDiagnosticAt(
13182 Fn->getBeginLoc(),
13183 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13184 << ULE->getName() << Fn->getSourceRange()),
13185 SemaRef, OCD_AllCandidates, Args);
13186 break;
13187 }
13188
13189 case OR_Ambiguous:
13190 CandidateSet->NoteCandidates(
13191 PartialDiagnosticAt(Fn->getBeginLoc(),
13192 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13193 << ULE->getName() << Fn->getSourceRange()),
13194 SemaRef, OCD_AmbiguousCandidates, Args);
13195 break;
13196
13197 case OR_Deleted: {
13198 CandidateSet->NoteCandidates(
13199 PartialDiagnosticAt(Fn->getBeginLoc(),
13200 SemaRef.PDiag(diag::err_ovl_deleted_call)
13201 << ULE->getName() << Fn->getSourceRange()),
13202 SemaRef, OCD_AllCandidates, Args);
13203
13204 // We emitted an error for the unavailable/deleted function call but keep
13205 // the call in the AST.
13206 FunctionDecl *FDecl = (*Best)->Function;
13207 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13208 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13209 ExecConfig, /*IsExecConfig=*/false,
13210 (*Best)->IsADLCandidate);
13211 }
13212 }
13213
13214 // Overload resolution failed, try to recover.
13215 SmallVector<Expr *, 8> SubExprs = {Fn};
13216 SubExprs.append(Args.begin(), Args.end());
13217 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13218 chooseRecoveryType(*CandidateSet, Best));
13219}
13220
13221static void markUnaddressableCandidatesUnviable(Sema &S,
13222 OverloadCandidateSet &CS) {
13223 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13224 if (I->Viable &&
13225 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13226 I->Viable = false;
13227 I->FailureKind = ovl_fail_addr_not_available;
13228 }
13229 }
13230}
13231
13232/// BuildOverloadedCallExpr - Given the call expression that calls Fn
13233/// (which eventually refers to the declaration Func) and the call
13234/// arguments Args/NumArgs, attempt to resolve the function call down
13235/// to a specific function. If overload resolution succeeds, returns
13236/// the call expression produced by overload resolution.
13237/// Otherwise, emits diagnostics and returns ExprError.
13238ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13239 UnresolvedLookupExpr *ULE,
13240 SourceLocation LParenLoc,
13241 MultiExprArg Args,
13242 SourceLocation RParenLoc,
13243 Expr *ExecConfig,
13244 bool AllowTypoCorrection,
13245 bool CalleesAddressIsTaken) {
13246 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13247 OverloadCandidateSet::CSK_Normal);
13248 ExprResult result;
13249
13250 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13251 &result))
13252 return result;
13253
13254 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13255 // functions that aren't addressible are considered unviable.
13256 if (CalleesAddressIsTaken)
13257 markUnaddressableCandidatesUnviable(*this, CandidateSet);
13258
13259 OverloadCandidateSet::iterator Best;
13260 OverloadingResult OverloadResult =
13261 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13262
13263 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13264 ExecConfig, &CandidateSet, &Best,
13265 OverloadResult, AllowTypoCorrection);
13266}
13267
13268static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13269 return Functions.size() > 1 ||
13270 (Functions.size() == 1 &&
13271 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13272}
13273
13274ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13275 NestedNameSpecifierLoc NNSLoc,
13276 DeclarationNameInfo DNI,
13277 const UnresolvedSetImpl &Fns,
13278 bool PerformADL) {
13279 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13280 PerformADL, IsOverloaded(Fns),
13281 Fns.begin(), Fns.end());
13282}
13283
13284/// Create a unary operation that may resolve to an overloaded
13285/// operator.
13286///
13287/// \param OpLoc The location of the operator itself (e.g., '*').
13288///
13289/// \param Opc The UnaryOperatorKind that describes this operator.
13290///
13291/// \param Fns The set of non-member functions that will be
13292/// considered by overload resolution. The caller needs to build this
13293/// set based on the context using, e.g.,
13294/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13295/// set should not contain any member functions; those will be added
13296/// by CreateOverloadedUnaryOp().
13297///
13298/// \param Input The input argument.
13299ExprResult
13300Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13301 const UnresolvedSetImpl &Fns,
13302 Expr *Input, bool PerformADL) {
13303 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13304 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast <bool> (Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? void (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "clang/lib/Sema/SemaOverload.cpp", 13304, __extension__ __PRETTY_FUNCTION__
))
;
13305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13306 // TODO: provide better source location info.
13307 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13308
13309 if (checkPlaceholderForOverload(*this, Input))
13310 return ExprError();
13311
13312 Expr *Args[2] = { Input, nullptr };
13313 unsigned NumArgs = 1;
13314
13315 // For post-increment and post-decrement, add the implicit '0' as
13316 // the second argument, so that we know this is a post-increment or
13317 // post-decrement.
13318 if (Opc == UO_PostInc || Opc == UO_PostDec) {
13319 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13320 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13321 SourceLocation());
13322 NumArgs = 2;
13323 }
13324
13325 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13326
13327 if (Input->isTypeDependent()) {
13328 if (Fns.empty())
13329 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13330 VK_PRValue, OK_Ordinary, OpLoc, false,
13331 CurFPFeatureOverrides());
13332
13333 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13334 ExprResult Fn = CreateUnresolvedLookupExpr(
13335 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13336 if (Fn.isInvalid())
13337 return ExprError();
13338 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13339 Context.DependentTy, VK_PRValue, OpLoc,
13340 CurFPFeatureOverrides());
13341 }
13342
13343 // Build an empty overload set.
13344 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13345
13346 // Add the candidates from the given function set.
13347 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13348
13349 // Add operator candidates that are member functions.
13350 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13351
13352 // Add candidates from ADL.
13353 if (PerformADL) {
13354 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13355 /*ExplicitTemplateArgs*/nullptr,
13356 CandidateSet);
13357 }
13358
13359 // Add builtin operator candidates.
13360 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13361
13362 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13363
13364 // Perform overload resolution.
13365 OverloadCandidateSet::iterator Best;
13366 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13367 case OR_Success: {
13368 // We found a built-in operator or an overloaded operator.
13369 FunctionDecl *FnDecl = Best->Function;
13370
13371 if (FnDecl) {
13372 Expr *Base = nullptr;
13373 // We matched an overloaded operator. Build a call to that
13374 // operator.
13375
13376 // Convert the arguments.
13377 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13378 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13379
13380 ExprResult InputRes =
13381 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13382 Best->FoundDecl, Method);
13383 if (InputRes.isInvalid())
13384 return ExprError();
13385 Base = Input = InputRes.get();
13386 } else {
13387 // Convert the arguments.
13388 ExprResult InputInit
13389 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13390 Context,
13391 FnDecl->getParamDecl(0)),
13392 SourceLocation(),
13393 Input);
13394 if (InputInit.isInvalid())
13395 return ExprError();
13396 Input = InputInit.get();
13397 }
13398
13399 // Build the actual expression node.
13400 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13401 Base, HadMultipleCandidates,
13402 OpLoc);
13403 if (FnExpr.isInvalid())
13404 return ExprError();
13405
13406 // Determine the result type.
13407 QualType ResultTy = FnDecl->getReturnType();
13408 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13409 ResultTy = ResultTy.getNonLValueExprType(Context);
13410
13411 Args[0] = Input;
13412 CallExpr *TheCall = CXXOperatorCallExpr::Create(
13413 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13414 CurFPFeatureOverrides(), Best->IsADLCandidate);
13415
13416 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13417 return ExprError();
13418
13419 if (CheckFunctionCall(FnDecl, TheCall,
13420 FnDecl->getType()->castAs<FunctionProtoType>()))
13421 return ExprError();
13422 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13423 } else {
13424 // We matched a built-in operator. Convert the arguments, then
13425 // break out so that we will build the appropriate built-in
13426 // operator node.
13427 ExprResult InputRes = PerformImplicitConversion(
13428 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13429 CCK_ForBuiltinOverloadedOp);
13430 if (InputRes.isInvalid())
13431 return ExprError();
13432 Input = InputRes.get();
13433 break;
13434 }
13435 }
13436
13437 case OR_No_Viable_Function:
13438 // This is an erroneous use of an operator which can be overloaded by
13439 // a non-member function. Check for non-member operators which were
13440 // defined too late to be candidates.
13441 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13442 // FIXME: Recover by calling the found function.
13443 return ExprError();
13444
13445 // No viable function; fall through to handling this as a
13446 // built-in operator, which will produce an error message for us.
13447 break;
13448
13449 case OR_Ambiguous:
13450 CandidateSet.NoteCandidates(
13451 PartialDiagnosticAt(OpLoc,
13452 PDiag(diag::err_ovl_ambiguous_oper_unary)
13453 << UnaryOperator::getOpcodeStr(Opc)
13454 << Input->getType() << Input->getSourceRange()),
13455 *this, OCD_AmbiguousCandidates, ArgsArray,
13456 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13457 return ExprError();
13458
13459 case OR_Deleted:
13460 CandidateSet.NoteCandidates(
13461 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13462 << UnaryOperator::getOpcodeStr(Opc)
13463 << Input->getSourceRange()),
13464 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13465 OpLoc);
13466 return ExprError();
13467 }
13468
13469 // Either we found no viable overloaded operator or we matched a
13470 // built-in operator. In either case, fall through to trying to
13471 // build a built-in operation.
13472 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13473}
13474
13475/// Perform lookup for an overloaded binary operator.
13476void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13477 OverloadedOperatorKind Op,
13478 const UnresolvedSetImpl &Fns,
13479 ArrayRef<Expr *> Args, bool PerformADL) {
13480 SourceLocation OpLoc = CandidateSet.getLocation();
13481
13482 OverloadedOperatorKind ExtraOp =
13483 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13484 ? getRewrittenOverloadedOperator(Op)
13485 : OO_None;
13486
13487 // Add the candidates from the given function set. This also adds the
13488 // rewritten candidates using these functions if necessary.
13489 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13490
13491 // Add operator candidates that are member functions.
13492 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13493 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13494 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13495 OverloadCandidateParamOrder::Reversed);
13496
13497 // In C++20, also add any rewritten member candidates.
13498 if (ExtraOp) {
13499 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13500 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13501 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13502 CandidateSet,
13503 OverloadCandidateParamOrder::Reversed);
13504 }
13505
13506 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13507 // performed for an assignment operator (nor for operator[] nor operator->,
13508 // which don't get here).
13509 if (Op != OO_Equal && PerformADL) {
13510 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13511 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13512 /*ExplicitTemplateArgs*/ nullptr,
13513 CandidateSet);
13514 if (ExtraOp) {
13515 DeclarationName ExtraOpName =
13516 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13517 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13518 /*ExplicitTemplateArgs*/ nullptr,
13519 CandidateSet);
13520 }
13521 }
13522
13523 // Add builtin operator candidates.
13524 //
13525 // FIXME: We don't add any rewritten candidates here. This is strictly
13526 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13527 // resulting in our selecting a rewritten builtin candidate. For example:
13528 //
13529 // enum class E { e };
13530 // bool operator!=(E, E) requires false;
13531 // bool k = E::e != E::e;
13532 //
13533 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13534 // it seems unreasonable to consider rewritten builtin candidates. A core
13535 // issue has been filed proposing to removed this requirement.
13536 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13537}
13538
13539/// Create a binary operation that may resolve to an overloaded
13540/// operator.
13541///
13542/// \param OpLoc The location of the operator itself (e.g., '+').
13543///
13544/// \param Opc The BinaryOperatorKind that describes this operator.
13545///
13546/// \param Fns The set of non-member functions that will be
13547/// considered by overload resolution. The caller needs to build this
13548/// set based on the context using, e.g.,
13549/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13550/// set should not contain any member functions; those will be added
13551/// by CreateOverloadedBinOp().
13552///
13553/// \param LHS Left-hand argument.
13554/// \param RHS Right-hand argument.
13555/// \param PerformADL Whether to consider operator candidates found by ADL.
13556/// \param AllowRewrittenCandidates Whether to consider candidates found by
13557/// C++20 operator rewrites.
13558/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13559/// the function in question. Such a function is never a candidate in
13560/// our overload resolution. This also enables synthesizing a three-way
13561/// comparison from < and == as described in C++20 [class.spaceship]p1.
13562ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13563 BinaryOperatorKind Opc,
13564 const UnresolvedSetImpl &Fns, Expr *LHS,
13565 Expr *RHS, bool PerformADL,
13566 bool AllowRewrittenCandidates,
13567 FunctionDecl *DefaultedFn) {
13568 Expr *Args[2] = { LHS, RHS };
13569 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13570
13571 if (!getLangOpts().CPlusPlus20)
13572 AllowRewrittenCandidates = false;
13573
13574 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13575
13576 // If either side is type-dependent, create an appropriate dependent
13577 // expression.
13578 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13579 if (Fns.empty()) {
13580 // If there are no functions to store, just build a dependent
13581 // BinaryOperator or CompoundAssignment.
13582 if (BinaryOperator::isCompoundAssignmentOp(Opc))
13583 return CompoundAssignOperator::Create(
13584 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13585 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13586 Context.DependentTy);
13587 return BinaryOperator::Create(
13588 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13589 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13590 }
13591
13592 // FIXME: save results of ADL from here?
13593 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13594 // TODO: provide better source location info in DNLoc component.
13595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13596 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13597 ExprResult Fn = CreateUnresolvedLookupExpr(
13598 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13599 if (Fn.isInvalid())
13600 return ExprError();
13601 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13602 Context.DependentTy, VK_PRValue, OpLoc,
13603 CurFPFeatureOverrides());
13604 }
13605
13606 // Always do placeholder-like conversions on the RHS.
13607 if (checkPlaceholderForOverload(*this, Args[1]))
13608 return ExprError();
13609
13610 // Do placeholder-like conversion on the LHS; note that we should
13611 // not get here with a PseudoObject LHS.
13612 assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (Args[0]->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "clang/lib/Sema/SemaOverload.cpp", 13612, __extension__ __PRETTY_FUNCTION__
))
;
13613 if (checkPlaceholderForOverload(*this, Args[0]))
13614 return ExprError();
13615
13616 // If this is the assignment operator, we only perform overload resolution
13617 // if the left-hand side is a class or enumeration type. This is actually
13618 // a hack. The standard requires that we do overload resolution between the
13619 // various built-in candidates, but as DR507 points out, this can lead to
13620 // problems. So we do it this way, which pretty much follows what GCC does.
13621 // Note that we go the traditional code path for compound assignment forms.
13622 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13623 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13624
13625 // If this is the .* operator, which is not overloadable, just
13626 // create a built-in binary operator.
13627 if (Opc == BO_PtrMemD)
13628 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13629
13630 // Build the overload set.
13631 OverloadCandidateSet CandidateSet(
13632 OpLoc, OverloadCandidateSet::CSK_Operator,
13633 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13634 if (DefaultedFn)
13635 CandidateSet.exclude(DefaultedFn);
13636 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13637
13638 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13639
13640 // Perform overload resolution.
13641 OverloadCandidateSet::iterator Best;
13642 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13643 case OR_Success: {
13644 // We found a built-in operator or an overloaded operator.
13645 FunctionDecl *FnDecl = Best->Function;
13646
13647 bool IsReversed = Best->isReversed();
13648 if (IsReversed)
13649 std::swap(Args[0], Args[1]);
13650
13651 if (FnDecl) {
13652 Expr *Base = nullptr;
13653 // We matched an overloaded operator. Build a call to that
13654 // operator.
13655
13656 OverloadedOperatorKind ChosenOp =
13657 FnDecl->getDeclName().getCXXOverloadedOperator();
13658
13659 // C++2a [over.match.oper]p9:
13660 // If a rewritten operator== candidate is selected by overload
13661 // resolution for an operator@, its return type shall be cv bool
13662 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13663 !FnDecl->getReturnType()->isBooleanType()) {
13664 bool IsExtension =
13665 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13666 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13667 : diag::err_ovl_rewrite_equalequal_not_bool)
13668 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13669 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13670 Diag(FnDecl->getLocation(), diag::note_declared_at);
13671 if (!IsExtension)
13672 return ExprError();
13673 }
13674
13675 if (AllowRewrittenCandidates && !IsReversed &&
13676 CandidateSet.getRewriteInfo().isReversible()) {
13677 // We could have reversed this operator, but didn't. Check if some
13678 // reversed form was a viable candidate, and if so, if it had a
13679 // better conversion for either parameter. If so, this call is
13680 // formally ambiguous, and allowing it is an extension.
13681 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13682 for (OverloadCandidate &Cand : CandidateSet) {
13683 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13684 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13685 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13686 if (CompareImplicitConversionSequences(
13687 *this, OpLoc, Cand.Conversions[ArgIdx],
13688 Best->Conversions[ArgIdx]) ==
13689 ImplicitConversionSequence::Better) {
13690 AmbiguousWith.push_back(Cand.Function);
13691 break;
13692 }
13693 }
13694 }
13695 }
13696
13697 if (!AmbiguousWith.empty()) {
13698 bool AmbiguousWithSelf =
13699 AmbiguousWith.size() == 1 &&
13700 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13701 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13702 << BinaryOperator::getOpcodeStr(Opc)
13703 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13704 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13705 if (AmbiguousWithSelf) {
13706 Diag(FnDecl->getLocation(),
13707 diag::note_ovl_ambiguous_oper_binary_reversed_self);
13708 } else {
13709 Diag(FnDecl->getLocation(),
13710 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13711 for (auto *F : AmbiguousWith)
13712 Diag(F->getLocation(),
13713 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13714 }
13715 }
13716 }
13717
13718 // Convert the arguments.
13719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13720 // Best->Access is only meaningful for class members.
13721 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13722
13723 ExprResult Arg1 =
13724 PerformCopyInitialization(
13725 InitializedEntity::InitializeParameter(Context,
13726 FnDecl->getParamDecl(0)),
13727 SourceLocation(), Args[1]);
13728 if (Arg1.isInvalid())
13729 return ExprError();
13730
13731 ExprResult Arg0 =
13732 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13733 Best->FoundDecl, Method);
13734 if (Arg0.isInvalid())
13735 return ExprError();
13736 Base = Args[0] = Arg0.getAs<Expr>();
13737 Args[1] = RHS = Arg1.getAs<Expr>();
13738 } else {
13739 // Convert the arguments.
13740 ExprResult Arg0 = PerformCopyInitialization(
13741 InitializedEntity::InitializeParameter(Context,
13742 FnDecl->getParamDecl(0)),
13743 SourceLocation(), Args[0]);
13744 if (Arg0.isInvalid())
13745 return ExprError();
13746
13747 ExprResult Arg1 =
13748 PerformCopyInitialization(
13749 InitializedEntity::InitializeParameter(Context,
13750 FnDecl->getParamDecl(1)),
13751 SourceLocation(), Args[1]);
13752 if (Arg1.isInvalid())
13753 return ExprError();
13754 Args[0] = LHS = Arg0.getAs<Expr>();
13755 Args[1] = RHS = Arg1.getAs<Expr>();
13756 }
13757
13758 // Build the actual expression node.
13759 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13760 Best->FoundDecl, Base,
13761 HadMultipleCandidates, OpLoc);
13762 if (FnExpr.isInvalid())
13763 return ExprError();
13764
13765 // Determine the result type.
13766 QualType ResultTy = FnDecl->getReturnType();
13767 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13768 ResultTy = ResultTy.getNonLValueExprType(Context);
13769
13770 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13771 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13772 CurFPFeatureOverrides(), Best->IsADLCandidate);
13773
13774 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13775 FnDecl))
13776 return ExprError();
13777
13778 ArrayRef<const Expr *> ArgsArray(Args, 2);
13779 const Expr *ImplicitThis = nullptr;
13780 // Cut off the implicit 'this'.
13781 if (isa<CXXMethodDecl>(FnDecl)) {
13782 ImplicitThis = ArgsArray[0];
13783 ArgsArray = ArgsArray.slice(1);
13784 }
13785
13786 // Check for a self move.
13787 if (Op == OO_Equal)
13788 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13789
13790 if (ImplicitThis) {
13791 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13792 QualType ThisTypeFromDecl = Context.getPointerType(
13793 cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13794
13795 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13796 ThisTypeFromDecl);
13797 }
13798
13799 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13800 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13801 VariadicDoesNotApply);
13802
13803 ExprResult R = MaybeBindToTemporary(TheCall);
13804 if (R.isInvalid())
13805 return ExprError();
13806
13807 R = CheckForImmediateInvocation(R, FnDecl);
13808 if (R.isInvalid())
13809 return ExprError();
13810
13811 // For a rewritten candidate, we've already reversed the arguments
13812 // if needed. Perform the rest of the rewrite now.
13813 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13814 (Op == OO_Spaceship && IsReversed)) {
13815 if (Op == OO_ExclaimEqual) {
13816 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_EqualEqual &&
"unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13816, __extension__ __PRETTY_FUNCTION__
))
;
13817 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13818 } else {
13819 assert(ChosenOp == OO_Spaceship && "unexpected operator name")(static_cast <bool> (ChosenOp == OO_Spaceship &&
"unexpected operator name") ? void (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13819, __extension__ __PRETTY_FUNCTION__
))
;
13820 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13821 Expr *ZeroLiteral =
13822 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13823
13824 Sema::CodeSynthesisContext Ctx;
13825 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13826 Ctx.Entity = FnDecl;
13827 pushCodeSynthesisContext(Ctx);
13828
13829 R = CreateOverloadedBinOp(
13830 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13831 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13832 /*AllowRewrittenCandidates=*/false);
13833
13834 popCodeSynthesisContext();
13835 }
13836 if (R.isInvalid())
13837 return ExprError();
13838 } else {
13839 assert(ChosenOp == Op && "unexpected operator name")(static_cast <bool> (ChosenOp == Op && "unexpected operator name"
) ? void (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "clang/lib/Sema/SemaOverload.cpp", 13839, __extension__ __PRETTY_FUNCTION__
))
;
13840 }
13841
13842 // Make a note in the AST if we did any rewriting.
13843 if (Best->RewriteKind != CRK_None)
13844 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13845
13846 return R;
13847 } else {
13848 // We matched a built-in operator. Convert the arguments, then
13849 // break out so that we will build the appropriate built-in
13850 // operator node.
13851 ExprResult ArgsRes0 = PerformImplicitConversion(
13852 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13853 AA_Passing, CCK_ForBuiltinOverloadedOp);
13854 if (ArgsRes0.isInvalid())
13855 return ExprError();
13856 Args[0] = ArgsRes0.get();
13857
13858 ExprResult ArgsRes1 = PerformImplicitConversion(
13859 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13860 AA_Passing, CCK_ForBuiltinOverloadedOp);
13861 if (ArgsRes1.isInvalid())
13862 return ExprError();
13863 Args[1] = ArgsRes1.get();
13864 break;
13865 }
13866 }
13867
13868 case OR_No_Viable_Function: {
13869 // C++ [over.match.oper]p9:
13870 // If the operator is the operator , [...] and there are no
13871 // viable functions, then the operator is assumed to be the
13872 // built-in operator and interpreted according to clause 5.
13873 if (Opc == BO_Comma)
13874 break;
13875
13876 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13877 // compare result using '==' and '<'.
13878 if (DefaultedFn && Opc == BO_Cmp) {
13879 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13880 Args[1], DefaultedFn);
13881 if (E.isInvalid() || E.isUsable())
13882 return E;
13883 }
13884
13885 // For class as left operand for assignment or compound assignment
13886 // operator do not fall through to handling in built-in, but report that
13887 // no overloaded assignment operator found
13888 ExprResult Result = ExprError();
13889 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13890 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13891 Args, OpLoc);
13892 DeferDiagsRAII DDR(*this,
13893 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13894 if (Args[0]->getType()->isRecordType() &&
13895 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13896 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13897 << BinaryOperator::getOpcodeStr(Opc)
13898 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13899 if (Args[0]->getType()->isIncompleteType()) {
13900 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13901 << Args[0]->getType()
13902 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13903 }
13904 } else {
13905 // This is an erroneous use of an operator which can be overloaded by
13906 // a non-member function. Check for non-member operators which were
13907 // defined too late to be candidates.
13908 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13909 // FIXME: Recover by calling the found function.
13910 return ExprError();
13911
13912 // No viable function; try to create a built-in operation, which will
13913 // produce an error. Then, show the non-viable candidates.
13914 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13915 }
13916 assert(Result.isInvalid() &&(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "clang/lib/Sema/SemaOverload.cpp", 13917, __extension__ __PRETTY_FUNCTION__
))
13917 "C++ binary operator overloading is missing candidates!")(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "clang/lib/Sema/SemaOverload.cpp", 13917, __extension__ __PRETTY_FUNCTION__
))
;
13918 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13919 return Result;
13920 }
13921
13922 case OR_Ambiguous:
13923 CandidateSet.NoteCandidates(
13924 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13925 << BinaryOperator::getOpcodeStr(Opc)
13926 << Args[0]->getType()
13927 << Args[1]->getType()
13928 << Args[0]->getSourceRange()
13929 << Args[1]->getSourceRange()),
13930 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13931 OpLoc);
13932 return ExprError();
13933
13934 case OR_Deleted:
13935 if (isImplicitlyDeleted(Best->Function)) {
13936 FunctionDecl *DeletedFD = Best->Function;
13937 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13938 if (DFK.isSpecialMember()) {
13939 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13940 << Args[0]->getType() << DFK.asSpecialMember();
13941 } else {
13942 assert(DFK.isComparison())(static_cast <bool> (DFK.isComparison()) ? void (0) : __assert_fail
("DFK.isComparison()", "clang/lib/Sema/SemaOverload.cpp", 13942
, __extension__ __PRETTY_FUNCTION__))
;
13943 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13944 << Args[0]->getType() << DeletedFD;
13945 }
13946
13947 // The user probably meant to call this special member. Just
13948 // explain why it's deleted.
13949 NoteDeletedFunction(DeletedFD);
13950 return ExprError();
13951 }
13952 CandidateSet.NoteCandidates(
13953 PartialDiagnosticAt(
13954 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13955 << getOperatorSpelling(Best->Function->getDeclName()
13956 .getCXXOverloadedOperator())
13957 << Args[0]->getSourceRange()
13958 << Args[1]->getSourceRange()),
13959 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13960 OpLoc);
13961 return ExprError();
13962 }
13963
13964 // We matched a built-in operator; build it.
13965 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13966}
13967
13968ExprResult Sema::BuildSynthesizedThreeWayComparison(
13969 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13970 FunctionDecl *DefaultedFn) {
13971 const ComparisonCategoryInfo *Info =
13972 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13973 // If we're not producing a known comparison category type, we can't
13974 // synthesize a three-way comparison. Let the caller diagnose this.
13975 if (!Info)
13976 return ExprResult((Expr*)nullptr);
13977
13978 // If we ever want to perform this synthesis more generally, we will need to
13979 // apply the temporary materialization conversion to the operands.
13980 assert(LHS->isGLValue() && RHS->isGLValue() &&(static_cast <bool> (LHS->isGLValue() && RHS
->isGLValue() && "cannot use prvalue expressions more than once"
) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "clang/lib/Sema/SemaOverload.cpp", 13981, __extension__ __PRETTY_FUNCTION__
))
13981 "cannot use prvalue expressions more than once")(static_cast <bool> (LHS->isGLValue() && RHS
->isGLValue() && "cannot use prvalue expressions more than once"
) ? void (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "clang/lib/Sema/SemaOverload.cpp", 13981, __extension__ __PRETTY_FUNCTION__
))
;
13982 Expr *OrigLHS = LHS;
13983 Expr *OrigRHS = RHS;
13984
13985 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13986 // each of them multiple times below.
13987 LHS = new (Context)
13988 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13989 LHS->getObjectKind(), LHS);
13990 RHS = new (Context)
13991 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13992 RHS->getObjectKind(), RHS);
13993
13994 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13995 DefaultedFn);
13996 if (Eq.isInvalid())
13997 return ExprError();
13998
13999 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14000 true, DefaultedFn);
14001 if (Less.isInvalid())
14002 return ExprError();
14003
14004 ExprResult Greater;
14005 if (Info->isPartial()) {
14006 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14007 DefaultedFn);
14008 if (Greater.isInvalid())
14009 return ExprError();
14010 }
14011
14012 // Form the list of comparisons we're going to perform.
14013 struct Comparison {
14014 ExprResult Cmp;
14015 ComparisonCategoryResult Result;
14016 } Comparisons[4] =
14017 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14018 : ComparisonCategoryResult::Equivalent},
14019 {Less, ComparisonCategoryResult::Less},
14020 {Greater, ComparisonCategoryResult::Greater},
14021 {ExprResult(), ComparisonCategoryResult::Unordered},
14022 };
14023
14024 int I = Info->isPartial() ? 3 : 2;
14025
14026 // Combine the comparisons with suitable conditional expressions.
14027 ExprResult Result;
14028 for (; I >= 0; --I) {
14029 // Build a reference to the comparison category constant.
14030 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14031 // FIXME: Missing a constant for a comparison category. Diagnose this?
14032 if (!VI)
14033 return ExprResult((Expr*)nullptr);
14034 ExprResult ThisResult =
14035 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14036 if (ThisResult.isInvalid())
14037 return ExprError();
14038
14039 // Build a conditional unless this is the final case.
14040 if (Result.get()) {
14041 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14042 ThisResult.get(), Result.get());
14043 if (Result.isInvalid())
14044 return ExprError();
14045 } else {
14046 Result = ThisResult;
14047 }
14048 }
14049
14050 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14051 // bind the OpaqueValueExprs before they're (repeatedly) used.
14052 Expr *SyntacticForm = BinaryOperator::Create(
14053 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14054 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14055 CurFPFeatureOverrides());
14056 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14057 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14058}
14059
14060ExprResult
14061Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14062 SourceLocation RLoc,
14063 Expr *Base, Expr *Idx) {
14064 Expr *Args[2] = { Base, Idx };
14065 DeclarationName OpName =
14066 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14067
14068 // If either side is type-dependent, create an appropriate dependent
14069 // expression.
14070 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14071
14072 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14073 // CHECKME: no 'operator' keyword?
14074 DeclarationNameInfo OpNameInfo(OpName, LLoc);
14075 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14076 ExprResult Fn = CreateUnresolvedLookupExpr(
14077 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14078 if (Fn.isInvalid())
14079 return ExprError();
14080 // Can't add any actual overloads yet
14081
14082 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14083 Context.DependentTy, VK_PRValue, RLoc,
14084 CurFPFeatureOverrides());
14085 }
14086
14087 // Handle placeholders on both operands.
14088 if (checkPlaceholderForOverload(*this, Args[0]))
14089 return ExprError();
14090 if (checkPlaceholderForOverload(*this, Args[1]))
14091 return ExprError();
14092
14093 // Build an empty overload set.
14094 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14095
14096 // Subscript can only be overloaded as a member function.
14097
14098 // Add operator candidates that are member functions.
14099 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14100
14101 // Add builtin operator candidates.
14102 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14103
14104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14105
14106 // Perform overload resolution.
14107 OverloadCandidateSet::iterator Best;
14108 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14109 case OR_Success: {
14110 // We found a built-in operator or an overloaded operator.
14111 FunctionDecl *FnDecl = Best->Function;
14112
14113 if (FnDecl) {
14114 // We matched an overloaded operator. Build a call to that
14115 // operator.
14116
14117 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
14118
14119 // Convert the arguments.
14120 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14121 ExprResult Arg0 =
14122 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14123 Best->FoundDecl, Method);
14124 if (Arg0.isInvalid())
14125 return ExprError();
14126 Args[0] = Arg0.get();
14127
14128 // Convert the arguments.
14129 ExprResult InputInit
14130 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14131 Context,
14132 FnDecl->getParamDecl(0)),
14133 SourceLocation(),
14134 Args[1]);
14135 if (InputInit.isInvalid())
14136 return ExprError();
14137
14138 Args[1] = InputInit.getAs<Expr>();
14139
14140 // Build the actual expression node.
14141 DeclarationNameInfo OpLocInfo(OpName, LLoc);
14142 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14143 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14144 Best->FoundDecl,
14145 Base,
14146 HadMultipleCandidates,
14147 OpLocInfo.getLoc(),
14148 OpLocInfo.getInfo());
14149 if (FnExpr.isInvalid())
14150 return ExprError();
14151
14152 // Determine the result type
14153 QualType ResultTy = FnDecl->getReturnType();
14154 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14155 ResultTy = ResultTy.getNonLValueExprType(Context);
14156
14157 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14158 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
14159 CurFPFeatureOverrides());
14160 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14161 return ExprError();
14162
14163 if (CheckFunctionCall(Method, TheCall,
14164 Method->getType()->castAs<FunctionProtoType>()))
14165 return ExprError();
14166
14167 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14168 FnDecl);
14169 } else {
14170 // We matched a built-in operator. Convert the arguments, then
14171 // break out so that we will build the appropriate built-in
14172 // operator node.
14173 ExprResult ArgsRes0 = PerformImplicitConversion(
14174 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14175 AA_Passing, CCK_ForBuiltinOverloadedOp);
14176 if (ArgsRes0.isInvalid())
14177 return ExprError();
14178 Args[0] = ArgsRes0.get();
14179
14180 ExprResult ArgsRes1 = PerformImplicitConversion(
14181 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14182 AA_Passing, CCK_ForBuiltinOverloadedOp);
14183 if (ArgsRes1.isInvalid())
14184 return ExprError();
14185 Args[1] = ArgsRes1.get();
14186
14187 break;
14188 }
14189 }
14190
14191 case OR_No_Viable_Function: {
14192 PartialDiagnostic PD = CandidateSet.empty()
14193 ? (PDiag(diag::err_ovl_no_oper)
14194 << Args[0]->getType() << /*subscript*/ 0
14195 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
14196 : (PDiag(diag::err_ovl_no_viable_subscript)
14197 << Args[0]->getType() << Args[0]->getSourceRange()
14198 << Args[1]->getSourceRange());
14199 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14200 OCD_AllCandidates, Args, "[]", LLoc);
14201 return ExprError();
14202 }
14203
14204 case OR_Ambiguous:
14205 CandidateSet.NoteCandidates(
14206 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14207 << "[]" << Args[0]->getType()
14208 << Args[1]->getType()
14209 << Args[0]->getSourceRange()
14210 << Args[1]->getSourceRange()),
14211 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14212 return ExprError();
14213
14214 case OR_Deleted:
14215 CandidateSet.NoteCandidates(
14216 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14217 << "[]" << Args[0]->getSourceRange()
14218 << Args[1]->getSourceRange()),
14219 *this, OCD_AllCandidates, Args, "[]", LLoc);
14220 return ExprError();
14221 }
14222
14223 // We matched a built-in operator; build it.
14224 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14225}
14226
14227/// BuildCallToMemberFunction - Build a call to a member
14228/// function. MemExpr is the expression that refers to the member
14229/// function (and includes the object parameter), Args/NumArgs are the
14230/// arguments to the function call (not including the object
14231/// parameter). The caller needs to validate that the member
14232/// expression refers to a non-static member function or an overloaded
14233/// member function.
14234ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14235 SourceLocation LParenLoc,
14236 MultiExprArg Args,
14237 SourceLocation RParenLoc,
14238 Expr *ExecConfig, bool IsExecConfig,
14239 bool AllowRecovery) {
14240 assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 14241, __extension__ __PRETTY_FUNCTION__
))
14241 MemExprE->getType() == Context.OverloadTy)(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "clang/lib/Sema/SemaOverload.cpp", 14241, __extension__ __PRETTY_FUNCTION__
))
;
14242
14243 // Dig out the member expression. This holds both the object
14244 // argument and the member function we're referring to.
14245 Expr *NakedMemExpr = MemExprE->IgnoreParens();
14246
14247 // Determine whether this is a call to a pointer-to-member function.
14248 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14249 assert(op->getType() == Context.BoundMemberTy)(static_cast <bool> (op->getType() == Context.BoundMemberTy
) ? void (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "clang/lib/Sema/SemaOverload.cpp", 14249, __extension__ __PRETTY_FUNCTION__
))
;
14250 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast <bool> (op->getOpcode() == BO_PtrMemD ||
op->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "clang/lib/Sema/SemaOverload.cpp", 14250, __extension__ __PRETTY_FUNCTION__
))
;
14251
14252 QualType fnType =
14253 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14254
14255 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14256 QualType resultType = proto->getCallResultType(Context);
14257 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14258
14259 // Check that the object type isn't more qualified than the
14260 // member function we're calling.
14261 Qualifiers funcQuals = proto->getMethodQuals();
14262
14263 QualType objectType = op->getLHS()->getType();
14264 if (op->getOpcode() == BO_PtrMemI)
14265 objectType = objectType->castAs<PointerType>()->getPointeeType();
14266 Qualifiers objectQuals = objectType.getQualifiers();
14267
14268 Qualifiers difference = objectQuals - funcQuals;
14269 difference.removeObjCGCAttr();
14270 difference.removeAddressSpace();
14271 if (difference) {
14272 std::string qualsString = difference.getAsString();
14273 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14274 << fnType.getUnqualifiedType()
14275 << qualsString
14276 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14277 }
14278
14279 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14280 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14281 CurFPFeatureOverrides(), proto->getNumParams());
14282
14283 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14284 call, nullptr))
14285 return ExprError();
14286
14287 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14288 return ExprError();
14289
14290 if (CheckOtherCall(call, proto))
14291 return ExprError();
14292
14293 return MaybeBindToTemporary(call);
14294 }
14295
14296 // We only try to build a recovery expr at this level if we can preserve
14297 // the return type, otherwise we return ExprError() and let the caller
14298 // recover.
14299 auto BuildRecoveryExpr = [&](QualType Type) {
14300 if (!AllowRecovery)
14301 return ExprError();
14302 std::vector<Expr *> SubExprs = {MemExprE};
14303 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); });
14304 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14305 Type);
14306 };
14307 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14308 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14309 RParenLoc, CurFPFeatureOverrides());
14310
14311 UnbridgedCastsSet UnbridgedCasts;
14312 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14313 return ExprError();
14314
14315 MemberExpr *MemExpr;
14316 CXXMethodDecl *Method = nullptr;
14317 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14318 NestedNameSpecifier *Qualifier = nullptr;
14319 if (isa<MemberExpr>(NakedMemExpr)) {
14320 MemExpr = cast<MemberExpr>(NakedMemExpr);
14321 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14322 FoundDecl = MemExpr->getFoundDecl();
14323 Qualifier = MemExpr->getQualifier();
14324 UnbridgedCasts.restore();
14325 } else if (auto *UnresExpr = dyn_cast<UnresolvedMemberExpr>(NakedMemExpr)) {
14326 Qualifier = UnresExpr->getQualifier();
14327
14328 QualType ObjectType = UnresExpr->getBaseType();
14329 Expr::Classification ObjectClassification
14330 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14331 : UnresExpr->getBase()->Classify(Context);
14332
14333 // Add overload candidates
14334 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14335 OverloadCandidateSet::CSK_Normal);
14336
14337 // FIXME: avoid copy.
14338 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14339 if (UnresExpr->hasExplicitTemplateArgs()) {
14340 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14341 TemplateArgs = &TemplateArgsBuffer;
14342 }
14343
14344 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14345 E = UnresExpr->decls_end(); I != E; ++I) {
14346
14347 NamedDecl *Func = *I;
14348 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14349 if (isa<UsingShadowDecl>(Func))
14350 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14351
14352
14353 // Microsoft supports direct constructor calls.
14354 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14355 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14356 CandidateSet,
14357 /*SuppressUserConversions*/ false);
14358 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14359 // If explicit template arguments were provided, we can't call a
14360 // non-template member function.
14361 if (TemplateArgs)
14362 continue;
14363
14364 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14365 ObjectClassification, Args, CandidateSet,
14366 /*SuppressUserConversions=*/false);
14367 } else {
14368 AddMethodTemplateCandidate(
14369 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14370 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14371 /*SuppressUserConversions=*/false);
14372 }
14373 }
14374
14375 DeclarationName DeclName = UnresExpr->getMemberName();
14376
14377 UnbridgedCasts.restore();
14378
14379 OverloadCandidateSet::iterator Best;
14380 bool Succeeded = false;
14381 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14382 Best)) {
14383 case OR_Success:
14384 Method = cast<CXXMethodDecl>(Best->Function);
14385 FoundDecl = Best->FoundDecl;
14386 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14387 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14388 break;
14389 // If FoundDecl is different from Method (such as if one is a template
14390 // and the other a specialization), make sure DiagnoseUseOfDecl is
14391 // called on both.
14392 // FIXME: This would be more comprehensively addressed by modifying
14393 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14394 // being used.
14395 if (Method != FoundDecl.getDecl() &&
14396 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14397 break;
14398 Succeeded = true;
14399 break;
14400
14401 case OR_No_Viable_Function:
14402 CandidateSet.NoteCandidates(
14403 PartialDiagnosticAt(
14404 UnresExpr->getMemberLoc(),
14405 PDiag(diag::err_ovl_no_viable_member_function_in_call)
14406 << DeclName << MemExprE->getSourceRange()),
14407 *this, OCD_AllCandidates, Args);
14408 break;
14409 case OR_Ambiguous:
14410 CandidateSet.NoteCandidates(
14411 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14412 PDiag(diag::err_ovl_ambiguous_member_call)
14413 << DeclName << MemExprE->getSourceRange()),
14414 *this, OCD_AmbiguousCandidates, Args);
14415 break;
14416 case OR_Deleted:
14417 CandidateSet.NoteCandidates(
14418 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14419 PDiag(diag::err_ovl_deleted_member_call)
14420 << DeclName << MemExprE->getSourceRange()),
14421 *this, OCD_AllCandidates, Args);
14422 break;
14423 }
14424 // Overload resolution fails, try to recover.
14425 if (!Succeeded)
14426 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14427
14428 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14429
14430 // If overload resolution picked a static member, build a
14431 // non-member call based on that function.
14432 if (Method->isStatic()) {
14433 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14434 ExecConfig, IsExecConfig);
14435 }
14436
14437 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14438 } else
14439 // Unimaged NakedMemExpr type.
14440 return ExprError();
14441
14442 QualType ResultType = Method->getReturnType();
14443 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14444 ResultType = ResultType.getNonLValueExprType(Context);
14445
14446 assert(Method && "Member call to something that isn't a method?")(static_cast <bool> (Method && "Member call to something that isn't a method?"
) ? void (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "clang/lib/Sema/SemaOverload.cpp", 14446, __extension__ __PRETTY_FUNCTION__
))
;
14447 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14448 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14449 Context, MemExprE, Args, ResultType, VK, RParenLoc,
14450 CurFPFeatureOverrides(), Proto->getNumParams());
14451
14452 // Check for a valid return type.
14453 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14454 TheCall, Method))
14455 return BuildRecoveryExpr(ResultType);
14456
14457 // Convert the object argument (for a non-static member function call).
14458 // We only need to do this if there was actually an overload; otherwise
14459 // it was done at lookup.
14460 if (!Method->isStatic()) {
14461 ExprResult ObjectArg =
14462 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14463 FoundDecl, Method);
14464 if (ObjectArg.isInvalid())
14465 return ExprError();
14466 MemExpr->setBase(ObjectArg.get());
14467 }
14468
14469 // Convert the rest of the arguments
14470 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14471 RParenLoc))
14472 return BuildRecoveryExpr(ResultType);
14473
14474 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14475
14476 if (CheckFunctionCall(Method, TheCall, Proto))
14477 return ExprError();
14478
14479 // In the case the method to call was not selected by the overloading
14480 // resolution process, we still need to handle the enable_if attribute. Do
14481 // that here, so it will not hide previous -- and more relevant -- errors.
14482 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14483 if (const EnableIfAttr *Attr =
14484 CheckEnableIf(Method, LParenLoc, Args, true)) {
14485 Diag(MemE->getMemberLoc(),
14486 diag::err_ovl_no_viable_member_function_in_call)
14487 << Method << Method->getSourceRange();
14488 Diag(Method->getLocation(),
14489 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14490 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14491 return ExprError();
14492 }
14493 }
14494
14495 if ((isa<CXXConstructorDecl>(CurContext) ||
14496 isa<CXXDestructorDecl>(CurContext)) &&
14497 TheCall->getMethodDecl()->isPure()) {
14498 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14499
14500 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14501 MemExpr->performsVirtualDispatch(getLangOpts())) {
14502 Diag(MemExpr->getBeginLoc(),
14503 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14504 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14505 << MD->getParent();
14506
14507 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14508 if (getLangOpts().AppleKext)
14509 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14510 << MD->getParent() << MD->getDeclName();
14511 }
14512 }
14513
14514 if (CXXDestructorDecl *DD =
14515 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14516 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14517 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14518 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14519 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14520 MemExpr->getMemberLoc());
14521 }
14522
14523 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14524 TheCall->getMethodDecl());
14525}
14526
14527/// BuildCallToObjectOfClassType - Build a call to an object of class
14528/// type (C++ [over.call.object]), which can end up invoking an
14529/// overloaded function call operator (@c operator()) or performing a
14530/// user-defined conversion on the object argument.
14531ExprResult
14532Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14533 SourceLocation LParenLoc,
14534 MultiExprArg Args,
14535 SourceLocation RParenLoc) {
14536 if (checkPlaceholderForOverload(*this, Obj))
14537 return ExprError();
14538 ExprResult Object = Obj;
14539
14540 UnbridgedCastsSet UnbridgedCasts;
14541 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14542 return ExprError();
14543
14544 assert(Object.get()->getType()->isRecordType() &&(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "clang/lib/Sema/SemaOverload.cpp", 14545, __extension__ __PRETTY_FUNCTION__
))
14545 "Requires object type argument")(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "clang/lib/Sema/SemaOverload.cpp", 14545, __extension__ __PRETTY_FUNCTION__
))
;
14546
14547 // C++ [over.call.object]p1:
14548 // If the primary-expression E in the function call syntax
14549 // evaluates to a class object of type "cv T", then the set of
14550 // candidate functions includes at least the function call
14551 // operators of T. The function call operators of T are obtained by
14552 // ordinary lookup of the name operator() in the context of
14553 // (E).operator().
14554 OverloadCandidateSet CandidateSet(LParenLoc,
14555 OverloadCandidateSet::CSK_Operator);
14556 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14557
14558 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14559 diag::err_incomplete_object_call, Object.get()))
14560 return true;
14561
14562 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14563 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14564 LookupQualifiedName(R, Record->getDecl());
14565 R.suppressDiagnostics();
14566
14567 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14568 Oper != OperEnd; ++Oper) {
14569 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14570 Object.get()->Classify(Context), Args, CandidateSet,
14571 /*SuppressUserConversion=*/false);
14572 }
14573
14574 // C++ [over.call.object]p2:
14575 // In addition, for each (non-explicit in C++0x) conversion function
14576 // declared in T of the form
14577 //
14578 // operator conversion-type-id () cv-qualifier;
14579 //
14580 // where cv-qualifier is the same cv-qualification as, or a
14581 // greater cv-qualification than, cv, and where conversion-type-id
14582 // denotes the type "pointer to function of (P1,...,Pn) returning
14583 // R", or the type "reference to pointer to function of
14584 // (P1,...,Pn) returning R", or the type "reference to function
14585 // of (P1,...,Pn) returning R", a surrogate call function [...]
14586 // is also considered as a candidate function. Similarly,
14587 // surrogate call functions are added to the set of candidate
14588 // functions for each conversion function declared in an
14589 // accessible base class provided the function is not hidden
14590 // within T by another intervening declaration.
14591 const auto &Conversions =
14592 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14593 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14594 NamedDecl *D = *I;
14595 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14596 if (isa<UsingShadowDecl>(D))
14597 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14598
14599 // Skip over templated conversion functions; they aren't
14600 // surrogates.
14601 if (isa<FunctionTemplateDecl>(D))
14602 continue;
14603
14604 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14605 if (!Conv->isExplicit()) {
14606 // Strip the reference type (if any) and then the pointer type (if
14607 // any) to get down to what might be a function type.
14608 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14609 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14610 ConvType = ConvPtrType->getPointeeType();
14611
14612 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14613 {
14614 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14615 Object.get(), Args, CandidateSet);
14616 }
14617 }
14618 }
14619
14620 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14621
14622 // Perform overload resolution.
14623 OverloadCandidateSet::iterator Best;
14624 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14625 Best)) {
14626 case OR_Success:
14627 // Overload resolution succeeded; we'll build the appropriate call
14628 // below.
14629 break;
14630
14631 case OR_No_Viable_Function: {
14632 PartialDiagnostic PD =
14633 CandidateSet.empty()
14634 ? (PDiag(diag::err_ovl_no_oper)
14635 << Object.get()->getType() << /*call*/ 1
14636 << Object.get()->getSourceRange())
14637 : (PDiag(diag::err_ovl_no_viable_object_call)
14638 << Object.get()->getType() << Object.get()->getSourceRange());
14639 CandidateSet.NoteCandidates(
14640 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14641 OCD_AllCandidates, Args);
14642 break;
14643 }
14644 case OR_Ambiguous:
14645 CandidateSet.NoteCandidates(
14646 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14647 PDiag(diag::err_ovl_ambiguous_object_call)
14648 << Object.get()->getType()
14649 << Object.get()->getSourceRange()),
14650 *this, OCD_AmbiguousCandidates, Args);
14651 break;
14652
14653 case OR_Deleted:
14654 CandidateSet.NoteCandidates(
14655 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14656 PDiag(diag::err_ovl_deleted_object_call)
14657 << Object.get()->getType()
14658 << Object.get()->getSourceRange()),
14659 *this, OCD_AllCandidates, Args);
14660 break;
14661 }
14662
14663 if (Best == CandidateSet.end())
14664 return true;
14665
14666 UnbridgedCasts.restore();
14667
14668 if (Best->Function == nullptr) {
14669 // Since there is no function declaration, this is one of the
14670 // surrogate candidates. Dig out the conversion function.
14671 CXXConversionDecl *Conv
14672 = cast<CXXConversionDecl>(
14673 Best->Conversions[0].UserDefined.ConversionFunction);
14674
14675 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14676 Best->FoundDecl);
14677 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14678 return ExprError();
14679 assert(Conv == Best->FoundDecl.getDecl() &&(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "clang/lib/Sema/SemaOverload.cpp", 14680, __extension__ __PRETTY_FUNCTION__
))
14680 "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "clang/lib/Sema/SemaOverload.cpp", 14680, __extension__ __PRETTY_FUNCTION__
))
;
14681 // We selected one of the surrogate functions that converts the
14682 // object parameter to a function pointer. Perform the conversion
14683 // on the object argument, then let BuildCallExpr finish the job.
14684
14685 // Create an implicit member expr to refer to the conversion operator.
14686 // and then call it.
14687 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14688 Conv, HadMultipleCandidates);
14689 if (Call.isInvalid())
14690 return ExprError();
14691 // Record usage of conversion in an implicit cast.
14692 Call = ImplicitCastExpr::Create(
14693 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14694 nullptr, VK_PRValue, CurFPFeatureOverrides());
14695
14696 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14697 }
14698
14699 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14700
14701 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14702 // that calls this method, using Object for the implicit object
14703 // parameter and passing along the remaining arguments.
14704 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14705
14706 // An error diagnostic has already been printed when parsing the declaration.
14707 if (Method->isInvalidDecl())
14708 return ExprError();
14709
14710 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14711 unsigned NumParams = Proto->getNumParams();
14712
14713 DeclarationNameInfo OpLocInfo(
14714 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14715 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14716 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14717 Obj, HadMultipleCandidates,
14718 OpLocInfo.getLoc(),
14719 OpLocInfo.getInfo());
14720 if (NewFn.isInvalid())
14721 return true;
14722
14723 // The number of argument slots to allocate in the call. If we have default
14724 // arguments we need to allocate space for them as well. We additionally
14725 // need one more slot for the object parameter.
14726 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14727
14728 // Build the full argument list for the method call (the implicit object
14729 // parameter is placed at the beginning of the list).
14730 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14731
14732 bool IsError = false;
14733
14734 // Initialize the implicit object parameter.
14735 ExprResult ObjRes =
14736 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14737 Best->FoundDecl, Method);
14738 if (ObjRes.isInvalid())
14739 IsError = true;
14740 else
14741 Object = ObjRes;
14742 MethodArgs[0] = Object.get();
14743
14744 // Check the argument types.
14745 for (unsigned i = 0; i != NumParams; i++) {
14746 Expr *Arg;
14747 if (i < Args.size()) {
14748 Arg = Args[i];
14749
14750 // Pass the argument.
14751
14752 ExprResult InputInit
14753 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14754 Context,
14755 Method->getParamDecl(i)),
14756 SourceLocation(), Arg);
14757
14758 IsError |= InputInit.isInvalid();
14759 Arg = InputInit.getAs<Expr>();
14760 } else {
14761 ExprResult DefArg
14762 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14763 if (DefArg.isInvalid()) {
14764 IsError = true;
14765 break;
14766 }
14767
14768 Arg = DefArg.getAs<Expr>();
14769 }
14770
14771 MethodArgs[i + 1] = Arg;
14772 }
14773
14774 // If this is a variadic call, handle args passed through "...".
14775 if (Proto->isVariadic()) {
14776 // Promote the arguments (C99 6.5.2.2p7).
14777 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14778 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14779 nullptr);
14780 IsError |= Arg.isInvalid();
14781 MethodArgs[i + 1] = Arg.get();
14782 }
14783 }
14784
14785 if (IsError)
14786 return true;
14787
14788 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14789
14790 // Once we've built TheCall, all of the expressions are properly owned.
14791 QualType ResultTy = Method->getReturnType();
14792 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14793 ResultTy = ResultTy.getNonLValueExprType(Context);
14794
14795 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14796 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14797 CurFPFeatureOverrides());
14798
14799 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14800 return true;
14801
14802 if (CheckFunctionCall(Method, TheCall, Proto))
14803 return true;
14804
14805 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14806}
14807
14808/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14809/// (if one exists), where @c Base is an expression of class type and
14810/// @c Member is the name of the member we're trying to find.
14811ExprResult
14812Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14813 bool *NoArrowOperatorFound) {
14814 assert(Base->getType()->isRecordType() &&(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "clang/lib/Sema/SemaOverload.cpp", 14815, __extension__ __PRETTY_FUNCTION__
))
14815 "left-hand side must have class type")(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "clang/lib/Sema/SemaOverload.cpp", 14815, __extension__ __PRETTY_FUNCTION__
))
;
14816
14817 if (checkPlaceholderForOverload(*this, Base))
14818 return ExprError();
14819
14820 SourceLocation Loc = Base->getExprLoc();
14821
14822 // C++ [over.ref]p1:
14823 //
14824 // [...] An expression x->m is interpreted as (x.operator->())->m
14825 // for a class object x of type T if T::operator->() exists and if
14826 // the operator is selected as the best match function by the
14827 // overload resolution mechanism (13.3).
14828 DeclarationName OpName =
14829 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14830 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14831
14832 if (RequireCompleteType(Loc, Base->getType(),
14833 diag::err_typecheck_incomplete_tag, Base))
14834 return ExprError();
14835
14836 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14837 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14838 R.suppressDiagnostics();
14839
14840 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14841 Oper != OperEnd; ++Oper) {
14842 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14843 None, CandidateSet, /*SuppressUserConversion=*/false);
14844 }
14845
14846 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14847
14848 // Perform overload resolution.
14849 OverloadCandidateSet::iterator Best;
14850 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14851 case OR_Success:
14852 // Overload resolution succeeded; we'll build the call below.
14853 break;
14854
14855 case OR_No_Viable_Function: {
14856 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14857 if (CandidateSet.empty()) {
14858 QualType BaseType = Base->getType();
14859 if (NoArrowOperatorFound) {
14860 // Report this specific error to the caller instead of emitting a
14861 // diagnostic, as requested.
14862 *NoArrowOperatorFound = true;
14863 return ExprError();
14864 }
14865 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14866 << BaseType << Base->getSourceRange();
14867 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14868 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14869 << FixItHint::CreateReplacement(OpLoc, ".");
14870 }
14871 } else
14872 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14873 << "operator->" << Base->getSourceRange();
14874 CandidateSet.NoteCandidates(*this, Base, Cands);
14875 return ExprError();
14876 }
14877 case OR_Ambiguous:
14878 CandidateSet.NoteCandidates(
14879 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14880 << "->" << Base->getType()
14881 << Base->getSourceRange()),
14882 *this, OCD_AmbiguousCandidates, Base);
14883 return ExprError();
14884
14885 case OR_Deleted:
14886 CandidateSet.NoteCandidates(
14887 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14888 << "->" << Base->getSourceRange()),
14889 *this, OCD_AllCandidates, Base);
14890 return ExprError();
14891 }
14892
14893 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14894
14895 // Convert the object parameter.
14896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14897 ExprResult BaseResult =
14898 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14899 Best->FoundDecl, Method);
14900 if (BaseResult.isInvalid())
14901 return ExprError();
14902 Base = BaseResult.get();
14903
14904 // Build the operator call.
14905 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14906 Base, HadMultipleCandidates, OpLoc);
14907 if (FnExpr.isInvalid())
14908 return ExprError();
14909
14910 QualType ResultTy = Method->getReturnType();
14911 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14912 ResultTy = ResultTy.getNonLValueExprType(Context);
14913 CXXOperatorCallExpr *TheCall =
14914 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14915 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14916
14917 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14918 return ExprError();
14919
14920 if (CheckFunctionCall(Method, TheCall,
14921 Method->getType()->castAs<FunctionProtoType>()))
14922 return ExprError();
14923
14924 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14925}
14926
14927/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14928/// a literal operator described by the provided lookup results.
14929ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14930 DeclarationNameInfo &SuffixInfo,
14931 ArrayRef<Expr*> Args,
14932 SourceLocation LitEndLoc,
14933 TemplateArgumentListInfo *TemplateArgs) {
14934 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14935
14936 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14937 OverloadCandidateSet::CSK_Normal);
14938 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14939 TemplateArgs);
14940
14941 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14942
14943 // Perform overload resolution. This will usually be trivial, but might need
14944 // to perform substitutions for a literal operator template.
14945 OverloadCandidateSet::iterator Best;
14946 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14947 case OR_Success:
14948 case OR_Deleted:
14949 break;
14950
14951 case OR_No_Viable_Function:
14952 CandidateSet.NoteCandidates(
14953 PartialDiagnosticAt(UDSuffixLoc,
14954 PDiag(diag::err_ovl_no_viable_function_in_call)
14955 << R.getLookupName()),
14956 *this, OCD_AllCandidates, Args);
14957 return ExprError();
14958
14959 case OR_Ambiguous:
14960 CandidateSet.NoteCandidates(
14961 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14962 << R.getLookupName()),
14963 *this, OCD_AmbiguousCandidates, Args);
14964 return ExprError();
14965 }
14966
14967 FunctionDecl *FD = Best->Function;
14968 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14969 nullptr, HadMultipleCandidates,
14970 SuffixInfo.getLoc(),
14971 SuffixInfo.getInfo());
14972 if (Fn.isInvalid())
14973 return true;
14974
14975 // Check the argument types. This should almost always be a no-op, except
14976 // that array-to-pointer decay is applied to string literals.
14977 Expr *ConvArgs[2];
14978 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14979 ExprResult InputInit = PerformCopyInitialization(
14980 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14981 SourceLocation(), Args[ArgIdx]);
14982 if (InputInit.isInvalid())
14983 return true;
14984 ConvArgs[ArgIdx] = InputInit.get();
14985 }
14986
14987 QualType ResultTy = FD->getReturnType();
14988 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14989 ResultTy = ResultTy.getNonLValueExprType(Context);
14990
14991 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14992 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14993 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14994
14995 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14996 return ExprError();
14997
14998 if (CheckFunctionCall(FD, UDL, nullptr))
14999 return ExprError();
15000
15001 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15002}
15003
15004/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15005/// given LookupResult is non-empty, it is assumed to describe a member which
15006/// will be invoked. Otherwise, the function will be found via argument
15007/// dependent lookup.
15008/// CallExpr is set to a valid expression and FRS_Success returned on success,
15009/// otherwise CallExpr is set to ExprError() and some non-success value
15010/// is returned.
15011Sema::ForRangeStatus
15012Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15013 SourceLocation RangeLoc,
15014 const DeclarationNameInfo &NameInfo,
15015 LookupResult &MemberLookup,
15016 OverloadCandidateSet *CandidateSet,
15017 Expr *Range, ExprResult *CallExpr) {
15018 Scope *S = nullptr;
15019
15020 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15021 if (!MemberLookup.empty()) {
15022 ExprResult MemberRef =
15023 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15024 /*IsPtr=*/false, CXXScopeSpec(),
15025 /*TemplateKWLoc=*/SourceLocation(),
15026 /*FirstQualifierInScope=*/nullptr,
15027 MemberLookup,
15028 /*TemplateArgs=*/nullptr, S);
15029 if (MemberRef.isInvalid()) {
15030 *CallExpr = ExprError();
15031 return FRS_DiagnosticIssued;
15032 }
15033 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15034 if (CallExpr->isInvalid()) {
15035 *CallExpr = ExprError();
15036 return FRS_DiagnosticIssued;
15037 }
15038 } else {
15039 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15040 NestedNameSpecifierLoc(),
15041 NameInfo, UnresolvedSet<0>());
15042 if (FnR.isInvalid())
15043 return FRS_DiagnosticIssued;
15044 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15045
15046 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15047 CandidateSet, CallExpr);
15048 if (CandidateSet->empty() || CandidateSetError) {
15049 *CallExpr = ExprError();
15050 return FRS_NoViableFunction;
15051 }
15052 OverloadCandidateSet::iterator Best;
15053 OverloadingResult OverloadResult =
15054 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15055
15056 if (OverloadResult == OR_No_Viable_Function) {
15057 *CallExpr = ExprError();
15058 return FRS_NoViableFunction;
15059 }
15060 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15061 Loc, nullptr, CandidateSet, &Best,
15062 OverloadResult,
15063 /*AllowTypoCorrection=*/false);
15064 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15065 *CallExpr = ExprError();
15066 return FRS_DiagnosticIssued;
15067 }
15068 }
15069 return FRS_Success;
15070}
15071
15072
15073/// FixOverloadedFunctionReference - E is an expression that refers to
15074/// a C++ overloaded function (possibly with some parentheses and
15075/// perhaps a '&' around it). We have resolved the overloaded function
15076/// to the function declaration Fn, so patch up the expression E to
15077/// refer (possibly indirectly) to Fn. Returns the new expr.
15078Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15079 FunctionDecl *Fn) {
15080 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15081 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15082 Found, Fn);
15083 if (SubExpr == PE->getSubExpr())
15084 return PE;
15085
15086 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15087 }
15088
15089 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15090 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15091 Found, Fn);
15092 assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15094, __extension__ __PRETTY_FUNCTION__
))
15093 SubExpr->getType()) &&(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15094, __extension__ __PRETTY_FUNCTION__
))
15094 "Implicit cast type cannot be determined from overload")(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "clang/lib/Sema/SemaOverload.cpp", 15094, __extension__ __PRETTY_FUNCTION__
))
;
15095 assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast <bool> (ICE->path_empty() && "fixing up hierarchy conversion?"
) ? void (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "clang/lib/Sema/SemaOverload.cpp", 15095, __extension__ __PRETTY_FUNCTION__
))
;
15096 if (SubExpr == ICE->getSubExpr())
15097 return ICE;
15098
15099 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15100 SubExpr, nullptr, ICE->getValueKind(),
15101 CurFPFeatureOverrides());
15102 }
15103
15104 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15105 if (!GSE->isResultDependent()) {
15106 Expr *SubExpr =
15107 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15108 if (SubExpr == GSE->getResultExpr())
15109 return GSE;
15110
15111 // Replace the resulting type information before rebuilding the generic
15112 // selection expression.
15113 ArrayRef<Expr *> A = GSE->getAssocExprs();
15114 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15115 unsigned ResultIdx = GSE->getResultIndex();
15116 AssocExprs[ResultIdx] = SubExpr;
15117
15118 return GenericSelectionExpr::Create(
15119 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15120 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15121 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15122 ResultIdx);
15123 }
15124 // Rather than fall through to the unreachable, return the original generic
15125 // selection expression.
15126 return GSE;
15127 }
15128
15129 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15130 assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "clang/lib/Sema/SemaOverload.cpp", 15131, __extension__ __PRETTY_FUNCTION__
))
15131 "Can only take the address of an overloaded function")(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "clang/lib/Sema/SemaOverload.cpp", 15131, __extension__ __PRETTY_FUNCTION__
))
;
15132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15133 if (Method->isStatic()) {
15134 // Do nothing: static member functions aren't any different
15135 // from non-member functions.
15136 } else {
15137 // Fix the subexpression, which really has to be an
15138 // UnresolvedLookupExpr holding an overloaded member function
15139 // or template.
15140 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15141 Found, Fn);
15142 if (SubExpr == UnOp->getSubExpr())
15143 return UnOp;
15144
15145 assert(isa<DeclRefExpr>(SubExpr)(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "clang/lib/Sema/SemaOverload.cpp", 15146, __extension__ __PRETTY_FUNCTION__
))
15146 && "fixed to something other than a decl ref")(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "clang/lib/Sema/SemaOverload.cpp", 15146, __extension__ __PRETTY_FUNCTION__
))
;
15147 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "clang/lib/Sema/SemaOverload.cpp", 15148, __extension__ __PRETTY_FUNCTION__
))
15148 && "fixed to a member ref with no nested name qualifier")(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "clang/lib/Sema/SemaOverload.cpp", 15148, __extension__ __PRETTY_FUNCTION__
))
;
15149
15150 // We have taken the address of a pointer to member
15151 // function. Perform the computation here so that we get the
15152 // appropriate pointer to member type.
15153 QualType ClassType
15154 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15155 QualType MemPtrType
15156 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15157 // Under the MS ABI, lock down the inheritance model now.
15158 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15159 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15160
15161 return UnaryOperator::Create(
15162 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15163 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15164 }
15165 }
15166 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15167 Found, Fn);
15168 if (SubExpr == UnOp->getSubExpr())
15169 return UnOp;
15170
15171 return UnaryOperator::Create(
15172 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()),
15173 VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false,
15174 CurFPFeatureOverrides());
15175 }
15176
15177 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15178 // FIXME: avoid copy.
15179 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15180 if (ULE->hasExplicitTemplateArgs()) {
15181 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15182 TemplateArgs = &TemplateArgsBuffer;
15183 }
15184
15185 DeclRefExpr *DRE =
15186 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
15187 ULE->getQualifierLoc(), Found.getDecl(),
15188 ULE->getTemplateKeywordLoc(), TemplateArgs);
15189 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15190 return DRE;
15191 }
15192
15193 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15194 // FIXME: avoid copy.
15195 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15196 if (MemExpr->hasExplicitTemplateArgs()) {
15197 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15198 TemplateArgs = &TemplateArgsBuffer;
15199 }
15200
15201 Expr *Base;
15202
15203 // If we're filling in a static method where we used to have an
15204 // implicit member access, rewrite to a simple decl ref.
15205 if (MemExpr->isImplicitAccess()) {
15206 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15207 DeclRefExpr *DRE = BuildDeclRefExpr(
15208 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15209 MemExpr->getQualifierLoc(), Found.getDecl(),
15210 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15211 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15212 return DRE;
15213 } else {
15214 SourceLocation Loc = MemExpr->getMemberLoc();
15215 if (MemExpr->getQualifier())
15216 Loc = MemExpr->getQualifierLoc().getBeginLoc();
15217 Base =
15218 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15219 }
15220 } else
15221 Base = MemExpr->getBase();
15222
15223 ExprValueKind valueKind;
15224 QualType type;
15225 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15226 valueKind = VK_LValue;
15227 type = Fn->getType();
15228 } else {
15229 valueKind = VK_PRValue;
15230 type = Context.BoundMemberTy;
15231 }
15232
15233 return BuildMemberExpr(
15234 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15235 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15236 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15237 type, valueKind, OK_Ordinary, TemplateArgs);
15238 }
15239
15240 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "clang/lib/Sema/SemaOverload.cpp", 15240)
;
15241}
15242
15243ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15244 DeclAccessPair Found,
15245 FunctionDecl *Fn) {
15246 return FixOverloadedFunctionReference(E.get(), Found, Fn);
15247}
15248
15249bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15250 FunctionDecl *Function) {
15251 if (!PartialOverloading || !Function)
15252 return true;
15253 if (Function->isVariadic())
15254 return false;
15255 if (const auto *Proto =
15256 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15257 if (Proto->isTemplateVariadic())
15258 return false;
15259 if (auto *Pattern = Function->getTemplateInstantiationPattern())
15260 if (const auto *Proto =
15261 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15262 if (Proto->isTemplateVariadic())
15263 return false;
15264 return true;
15265}

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