Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D 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 -O2 -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~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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<void> (0));
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<void> (0));
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<void> (0));
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<void> (0));
425 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast<void> (0));
426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427 const unsigned FromWidth = Ctx.getIntWidth(FromType);
428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429 const unsigned ToWidth = Ctx.getIntWidth(ToType);
430
431 if (FromWidth > ToWidth ||
432 (FromWidth == ToWidth && FromSigned != ToSigned) ||
433 (FromSigned && !ToSigned)) {
434 // Not all values of FromType can be represented in ToType.
435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436
437 // If it's value-dependent, we can't tell whether it's narrowing.
438 if (Initializer->isValueDependent())
439 return NK_Dependent_Narrowing;
440
441 Optional<llvm::APSInt> OptInitializerValue;
442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443 // Such conversions on variables are always narrowing.
444 return NK_Variable_Narrowing;
445 }
446 llvm::APSInt &InitializerValue = *OptInitializerValue;
447 bool Narrowing = false;
448 if (FromWidth < ToWidth) {
449 // Negative -> unsigned is narrowing. Otherwise, more bits is never
450 // narrowing.
451 if (InitializerValue.isSigned() && InitializerValue.isNegative())
452 Narrowing = true;
453 } else {
454 // Add a bit to the InitializerValue so we don't have to worry about
455 // signed vs. unsigned comparisons.
456 InitializerValue = InitializerValue.extend(
457 InitializerValue.getBitWidth() + 1);
458 // Convert the initializer to and from the target width and signed-ness.
459 llvm::APSInt ConvertedValue = InitializerValue;
460 ConvertedValue = ConvertedValue.trunc(ToWidth);
461 ConvertedValue.setIsSigned(ToSigned);
462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463 ConvertedValue.setIsSigned(InitializerValue.isSigned());
464 // If the result is different, this was a narrowing conversion.
465 if (ConvertedValue != InitializerValue)
466 Narrowing = true;
467 }
468 if (Narrowing) {
469 ConstantType = Initializer->getType();
470 ConstantValue = APValue(InitializerValue);
471 return NK_Constant_Narrowing;
472 }
473 }
474 return NK_Not_Narrowing;
475 }
476
477 default:
478 // Other kinds of conversions are not narrowings.
479 return NK_Not_Narrowing;
480 }
481}
482
483/// dump - Print this standard conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 bool PrintedSomething = false;
488 if (First != ICK_Identity) {
489 OS << GetImplicitConversionName(First);
490 PrintedSomething = true;
491 }
492
493 if (Second != ICK_Identity) {
494 if (PrintedSomething) {
495 OS << " -> ";
496 }
497 OS << GetImplicitConversionName(Second);
498
499 if (CopyConstructor) {
500 OS << " (by copy constructor)";
501 } else if (DirectBinding) {
502 OS << " (direct reference binding)";
503 } else if (ReferenceBinding) {
504 OS << " (reference binding)";
505 }
506 PrintedSomething = true;
507 }
508
509 if (Third != ICK_Identity) {
510 if (PrintedSomething) {
511 OS << " -> ";
512 }
513 OS << GetImplicitConversionName(Third);
514 PrintedSomething = true;
515 }
516
517 if (!PrintedSomething) {
518 OS << "No conversions required";
519 }
520}
521
522/// dump - Print this user-defined conversion sequence to standard
523/// error. Useful for debugging overloading issues.
524void UserDefinedConversionSequence::dump() const {
525 raw_ostream &OS = llvm::errs();
526 if (Before.First || Before.Second || Before.Third) {
527 Before.dump();
528 OS << " -> ";
529 }
530 if (ConversionFunction)
531 OS << '\'' << *ConversionFunction << '\'';
532 else
533 OS << "aggregate initialization";
534 if (After.First || After.Second || After.Third) {
535 OS << " -> ";
536 After.dump();
537 }
538}
539
540/// dump - Print this implicit conversion sequence to standard
541/// error. Useful for debugging overloading issues.
542void ImplicitConversionSequence::dump() const {
543 raw_ostream &OS = llvm::errs();
544 if (isStdInitializerListElement())
545 OS << "Worst std::initializer_list element conversion: ";
546 switch (ConversionKind) {
547 case StandardConversion:
548 OS << "Standard conversion: ";
549 Standard.dump();
550 break;
551 case UserDefinedConversion:
552 OS << "User-defined conversion: ";
553 UserDefined.dump();
554 break;
555 case EllipsisConversion:
556 OS << "Ellipsis conversion";
557 break;
558 case AmbiguousConversion:
559 OS << "Ambiguous conversion";
560 break;
561 case BadConversion:
562 OS << "Bad conversion";
563 break;
564 }
565
566 OS << "\n";
567}
568
569void AmbiguousConversionSequence::construct() {
570 new (&conversions()) ConversionSet();
571}
572
573void AmbiguousConversionSequence::destruct() {
574 conversions().~ConversionSet();
575}
576
577void
578AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579 FromTypePtr = O.FromTypePtr;
580 ToTypePtr = O.ToTypePtr;
581 new (&conversions()) ConversionSet(O.conversions());
582}
583
584namespace {
585 // Structure used by DeductionFailureInfo to store
586 // template argument information.
587 struct DFIArguments {
588 TemplateArgument FirstArg;
589 TemplateArgument SecondArg;
590 };
591 // Structure used by DeductionFailureInfo to store
592 // template parameter and template argument information.
593 struct DFIParamWithArguments : DFIArguments {
594 TemplateParameter Param;
595 };
596 // Structure used by DeductionFailureInfo to store template argument
597 // information and the index of the problematic call argument.
598 struct DFIDeducedMismatchArgs : DFIArguments {
599 TemplateArgumentList *TemplateArgs;
600 unsigned CallArgIndex;
601 };
602 // Structure used by DeductionFailureInfo to store information about
603 // unsatisfied constraints.
604 struct CNSInfo {
605 TemplateArgumentList *TemplateArgs;
606 ConstraintSatisfaction Satisfaction;
607 };
608}
609
610/// Convert from Sema's representation of template deduction information
611/// to the form used in overload-candidate information.
612DeductionFailureInfo
613clang::MakeDeductionFailureInfo(ASTContext &Context,
614 Sema::TemplateDeductionResult TDK,
615 TemplateDeductionInfo &Info) {
616 DeductionFailureInfo Result;
617 Result.Result = static_cast<unsigned>(TDK);
618 Result.HasDiagnostic = false;
619 switch (TDK) {
620 case Sema::TDK_Invalid:
621 case Sema::TDK_InstantiationDepth:
622 case Sema::TDK_TooManyArguments:
623 case Sema::TDK_TooFewArguments:
624 case Sema::TDK_MiscellaneousDeductionFailure:
625 case Sema::TDK_CUDATargetMismatch:
626 Result.Data = nullptr;
627 break;
628
629 case Sema::TDK_Incomplete:
630 case Sema::TDK_InvalidExplicitArguments:
631 Result.Data = Info.Param.getOpaqueValue();
632 break;
633
634 case Sema::TDK_DeducedMismatch:
635 case Sema::TDK_DeducedMismatchNested: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 auto *Saved = new (Context) DFIDeducedMismatchArgs;
638 Saved->FirstArg = Info.FirstArg;
639 Saved->SecondArg = Info.SecondArg;
640 Saved->TemplateArgs = Info.take();
641 Saved->CallArgIndex = Info.CallArgIndex;
642 Result.Data = Saved;
643 break;
644 }
645
646 case Sema::TDK_NonDeducedMismatch: {
647 // FIXME: Should allocate from normal heap so that we can free this later.
648 DFIArguments *Saved = new (Context) DFIArguments;
649 Saved->FirstArg = Info.FirstArg;
650 Saved->SecondArg = Info.SecondArg;
651 Result.Data = Saved;
652 break;
653 }
654
655 case Sema::TDK_IncompletePack:
656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657 case Sema::TDK_Inconsistent:
658 case Sema::TDK_Underqualified: {
659 // FIXME: Should allocate from normal heap so that we can free this later.
660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661 Saved->Param = Info.Param;
662 Saved->FirstArg = Info.FirstArg;
663 Saved->SecondArg = Info.SecondArg;
664 Result.Data = Saved;
665 break;
666 }
667
668 case Sema::TDK_SubstitutionFailure:
669 Result.Data = Info.take();
670 if (Info.hasSFINAEDiagnostic()) {
671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672 SourceLocation(), PartialDiagnostic::NullDiagnostic());
673 Info.takeSFINAEDiagnostic(*Diag);
674 Result.HasDiagnostic = true;
675 }
676 break;
677
678 case Sema::TDK_ConstraintsNotSatisfied: {
679 CNSInfo *Saved = new (Context) CNSInfo;
680 Saved->TemplateArgs = Info.take();
681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682 Result.Data = Saved;
683 break;
684 }
685
686 case Sema::TDK_Success:
687 case Sema::TDK_NonDependentConversionFailure:
688 llvm_unreachable("not a deduction failure")__builtin_unreachable();
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<void> (0));
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<void> (0));
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<void> (0))
1286 "Unexpected invalid target.")(static_cast<void> (0));
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<void> (0));
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<void> (0))
1739 "Non-unary operator on non-static member address")(static_cast<void> (0));
1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast<void> (0))
1741 == UO_AddrOf &&(static_cast<void> (0))
1742 "Non-address-of operator on non-static member address")(static_cast<void> (0));
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<void> (0))
1748 UO_AddrOf &&(static_cast<void> (0))
1749 "Non-address-of operator for overloaded function expression")(static_cast<void> (0));
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<void> (0))
1757 FromType,(static_cast<void> (0))
1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))(static_cast<void> (0));
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 and __float128 if
1873 // 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 if (&S.Context.getFloatTypeSemantics(FromType) !=
1880 &S.Context.getFloatTypeSemantics(ToType)) {
1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1882 ToType == S.Context.LongDoubleTy) ||
1883 (FromType == S.Context.LongDoubleTy &&
1884 ToType == S.Context.Float128Ty));
1885 if (Float128AndLongDouble &&
1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1887 &llvm::APFloat::PPCDoubleDouble()))
1888 return false;
1889 }
1890 // Floating point conversions (C++ 4.8).
1891 SCS.Second = ICK_Floating_Conversion;
1892 FromType = ToType.getUnqualifiedType();
1893 } else if ((FromType->isRealFloatingType() &&
10
Assuming the condition is false
1894 ToType->isIntegralType(S.Context)) ||
1895 (FromType->isIntegralOrUnscopedEnumerationType() &&
11
Assuming the condition is false
1896 ToType->isRealFloatingType())) {
1897 // Conversions between bfloat and int are not permitted.
1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899 return false;
1900
1901 // Floating-integral conversions (C++ 4.9).
1902 SCS.Second = ICK_Floating_Integral;
1903 FromType = ToType.getUnqualifiedType();
1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905 SCS.Second = ICK_Block_Pointer_Conversion;
1906 } else if (AllowObjCWritebackConversion &&
12
Assuming 'AllowObjCWritebackConversion' is false
1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908 SCS.Second = ICK_Writeback_Conversion;
1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
13
Calling 'Sema::IsPointerConversion'
1910 FromType, IncompatibleObjC)) {
1911 // Pointer conversions (C++ 4.10).
1912 SCS.Second = ICK_Pointer_Conversion;
1913 SCS.IncompatibleObjC = IncompatibleObjC;
1914 FromType = FromType.getUnqualifiedType();
1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916 InOverloadResolution, FromType)) {
1917 // Pointer to member conversions (4.11).
1918 SCS.Second = ICK_Pointer_Member;
1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1920 SCS.Second = SecondICK;
1921 FromType = ToType.getUnqualifiedType();
1922 } else if (!S.getLangOpts().CPlusPlus &&
1923 S.Context.typesAreCompatible(ToType, FromType)) {
1924 // Compatible conversions (Clang extension for C function overloading)
1925 SCS.Second = ICK_Compatible_Conversion;
1926 FromType = ToType.getUnqualifiedType();
1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1928 InOverloadResolution,
1929 SCS, CStyle)) {
1930 SCS.Second = ICK_TransparentUnionConversion;
1931 FromType = ToType;
1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1933 CStyle)) {
1934 // tryAtomicConversion has updated the standard conversion sequence
1935 // appropriately.
1936 return true;
1937 } else if (ToType->isEventT() &&
1938 From->isIntegerConstantExpr(S.getASTContext()) &&
1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1940 SCS.Second = ICK_Zero_Event_Conversion;
1941 FromType = ToType;
1942 } else if (ToType->isQueueT() &&
1943 From->isIntegerConstantExpr(S.getASTContext()) &&
1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1945 SCS.Second = ICK_Zero_Queue_Conversion;
1946 FromType = ToType;
1947 } else if (ToType->isSamplerT() &&
1948 From->isIntegerConstantExpr(S.getASTContext())) {
1949 SCS.Second = ICK_Compatible_Conversion;
1950 FromType = ToType;
1951 } else {
1952 // No second conversion required.
1953 SCS.Second = ICK_Identity;
1954 }
1955 SCS.setToType(1, FromType);
1956
1957 // The third conversion can be a function pointer conversion or a
1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1959 bool ObjCLifetimeConversion;
1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1961 // Function pointer conversions (removing 'noexcept') including removal of
1962 // 'noreturn' (Clang extension).
1963 SCS.Third = ICK_Function_Conversion;
1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1965 ObjCLifetimeConversion)) {
1966 SCS.Third = ICK_Qualification;
1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1968 FromType = ToType;
1969 } else {
1970 // No conversion required
1971 SCS.Third = ICK_Identity;
1972 }
1973
1974 // C++ [over.best.ics]p6:
1975 // [...] Any difference in top-level cv-qualification is
1976 // subsumed by the initialization itself and does not constitute
1977 // a conversion. [...]
1978 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1979 QualType CanonTo = S.Context.getCanonicalType(ToType);
1980 if (CanonFrom.getLocalUnqualifiedType()
1981 == CanonTo.getLocalUnqualifiedType() &&
1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1983 FromType = ToType;
1984 CanonFrom = CanonTo;
1985 }
1986
1987 SCS.setToType(2, FromType);
1988
1989 if (CanonFrom == CanonTo)
1990 return true;
1991
1992 // If we have not converted the argument type to the parameter type,
1993 // this is a bad conversion sequence, unless we're resolving an overload in C.
1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1995 return false;
1996
1997 ExprResult ER = ExprResult{From};
1998 Sema::AssignConvertType Conv =
1999 S.CheckSingleAssignmentConstraints(ToType, ER,
2000 /*Diagnose=*/false,
2001 /*DiagnoseCFAudited=*/false,
2002 /*ConvertRHS=*/false);
2003 ImplicitConversionKind SecondConv;
2004 switch (Conv) {
2005 case Sema::Compatible:
2006 SecondConv = ICK_C_Only_Conversion;
2007 break;
2008 // For our purposes, discarding qualifiers is just as bad as using an
2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2010 // qualifiers, as well.
2011 case Sema::CompatiblePointerDiscardsQualifiers:
2012 case Sema::IncompatiblePointer:
2013 case Sema::IncompatiblePointerSign:
2014 SecondConv = ICK_Incompatible_Pointer_Conversion;
2015 break;
2016 default:
2017 return false;
2018 }
2019
2020 // First can only be an lvalue conversion, so we pretend that this was the
2021 // second conversion. First should already be valid from earlier in the
2022 // function.
2023 SCS.Second = SecondConv;
2024 SCS.setToType(1, ToType);
2025
2026 // Third is Identity, because Second should rank us worse than any other
2027 // conversion. This could also be ICK_Qualification, but it's simpler to just
2028 // lump everything in with the second conversion, and we don't gain anything
2029 // from making this ICK_Qualification.
2030 SCS.Third = ICK_Identity;
2031 SCS.setToType(2, ToType);
2032 return true;
2033}
2034
2035static bool
2036IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2037 QualType &ToType,
2038 bool InOverloadResolution,
2039 StandardConversionSequence &SCS,
2040 bool CStyle) {
2041
2042 const RecordType *UT = ToType->getAsUnionType();
2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2044 return false;
2045 // The field to initialize within the transparent union.
2046 RecordDecl *UD = UT->getDecl();
2047 // It's compatible if the expression matches any of the fields.
2048 for (const auto *it : UD->fields()) {
2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2050 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2051 ToType = it->getType();
2052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
2058/// IsIntegralPromotion - Determines whether the conversion from the
2059/// expression From (whose potentially-adjusted type is FromType) to
2060/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2061/// sets PromotedType to the promoted type.
2062bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2063 const BuiltinType *To = ToType->getAs<BuiltinType>();
2064 // All integers are built-in.
2065 if (!To) {
2066 return false;
2067 }
2068
2069 // An rvalue of type char, signed char, unsigned char, short int, or
2070 // unsigned short int can be converted to an rvalue of type int if
2071 // int can represent all the values of the source type; otherwise,
2072 // the source rvalue can be converted to an rvalue of type unsigned
2073 // int (C++ 4.5p1).
2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2075 !FromType->isEnumeralType()) {
2076 if (// We can promote any signed, promotable integer type to an int
2077 (FromType->isSignedIntegerType() ||
2078 // We can promote any unsigned integer type whose size is
2079 // less than int to an int.
2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2081 return To->getKind() == BuiltinType::Int;
2082 }
2083
2084 return To->getKind() == BuiltinType::UInt;
2085 }
2086
2087 // C++11 [conv.prom]p3:
2088 // A prvalue of an unscoped enumeration type whose underlying type is not
2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2090 // following types that can represent all the values of the enumeration
2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2092 // unsigned int, long int, unsigned long int, long long int, or unsigned
2093 // long long int. If none of the types in that list can represent all the
2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2095 // type can be converted to an rvalue a prvalue of the extended integer type
2096 // with lowest integer conversion rank (4.13) greater than the rank of long
2097 // long in which all the values of the enumeration can be represented. If
2098 // there are two such extended types, the signed one is chosen.
2099 // C++11 [conv.prom]p4:
2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2101 // can be converted to a prvalue of its underlying type. Moreover, if
2102 // integral promotion can be applied to its underlying type, a prvalue of an
2103 // unscoped enumeration type whose underlying type is fixed can also be
2104 // converted to a prvalue of the promoted underlying type.
2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2107 // provided for a scoped enumeration.
2108 if (FromEnumType->getDecl()->isScoped())
2109 return false;
2110
2111 // We can perform an integral promotion to the underlying type of the enum,
2112 // even if that's not the promoted type. Note that the check for promoting
2113 // the underlying type is based on the type alone, and does not consider
2114 // the bitfield-ness of the actual source expression.
2115 if (FromEnumType->getDecl()->isFixed()) {
2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2117 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2118 IsIntegralPromotion(nullptr, Underlying, ToType);
2119 }
2120
2121 // We have already pre-calculated the promotion type, so this is trivial.
2122 if (ToType->isIntegerType() &&
2123 isCompleteType(From->getBeginLoc(), FromType))
2124 return Context.hasSameUnqualifiedType(
2125 ToType, FromEnumType->getDecl()->getPromotionType());
2126
2127 // C++ [conv.prom]p5:
2128 // If the bit-field has an enumerated type, it is treated as any other
2129 // value of that type for promotion purposes.
2130 //
2131 // ... so do not fall through into the bit-field checks below in C++.
2132 if (getLangOpts().CPlusPlus)
2133 return false;
2134 }
2135
2136 // C++0x [conv.prom]p2:
2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2138 // to an rvalue a prvalue of the first of the following types that can
2139 // represent all the values of its underlying type: int, unsigned int,
2140 // long int, unsigned long int, long long int, or unsigned long long int.
2141 // If none of the types in that list can represent all the values of its
2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2144 // type.
2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2146 ToType->isIntegerType()) {
2147 // Determine whether the type we're converting from is signed or
2148 // unsigned.
2149 bool FromIsSigned = FromType->isSignedIntegerType();
2150 uint64_t FromSize = Context.getTypeSize(FromType);
2151
2152 // The types we'll try to promote to, in the appropriate
2153 // order. Try each of these types.
2154 QualType PromoteTypes[6] = {
2155 Context.IntTy, Context.UnsignedIntTy,
2156 Context.LongTy, Context.UnsignedLongTy ,
2157 Context.LongLongTy, Context.UnsignedLongLongTy
2158 };
2159 for (int Idx = 0; Idx < 6; ++Idx) {
2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2161 if (FromSize < ToSize ||
2162 (FromSize == ToSize &&
2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2164 // We found the type that we can promote to. If this is the
2165 // type we wanted, we have a promotion. Otherwise, no
2166 // promotion.
2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2168 }
2169 }
2170 }
2171
2172 // An rvalue for an integral bit-field (9.6) can be converted to an
2173 // rvalue of type int if int can represent all the values of the
2174 // bit-field; otherwise, it can be converted to unsigned int if
2175 // unsigned int can represent all the values of the bit-field. If
2176 // the bit-field is larger yet, no integral promotion applies to
2177 // it. If the bit-field has an enumerated type, it is treated as any
2178 // other value of that type for promotion purposes (C++ 4.5p3).
2179 // FIXME: We should delay checking of bit-fields until we actually perform the
2180 // conversion.
2181 //
2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2184 // bit-fields and those whose underlying type is larger than int) for GCC
2185 // compatibility.
2186 if (From) {
2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2188 Optional<llvm::APSInt> BitWidth;
2189 if (FromType->isIntegralType(Context) &&
2190 (BitWidth =
2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2193 ToSize = Context.getTypeSize(ToType);
2194
2195 // Are we promoting to an int from a bitfield that fits in an int?
2196 if (*BitWidth < ToSize ||
2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2198 return To->getKind() == BuiltinType::Int;
2199 }
2200
2201 // Are we promoting to an unsigned int from an unsigned bitfield
2202 // that fits into an unsigned int?
2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2204 return To->getKind() == BuiltinType::UInt;
2205 }
2206
2207 return false;
2208 }
2209 }
2210 }
2211
2212 // An rvalue of type bool can be converted to an rvalue of type int,
2213 // with false becoming zero and true becoming one (C++ 4.5p4).
2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2215 return true;
2216 }
2217
2218 return false;
2219}
2220
2221/// IsFloatingPointPromotion - Determines whether the conversion from
2222/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2223/// returns true and sets PromotedType to the promoted type.
2224bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2227 /// An rvalue of type float can be converted to an rvalue of type
2228 /// double. (C++ 4.6p1).
2229 if (FromBuiltin->getKind() == BuiltinType::Float &&
2230 ToBuiltin->getKind() == BuiltinType::Double)
2231 return true;
2232
2233 // C99 6.3.1.5p1:
2234 // When a float is promoted to double or long double, or a
2235 // double is promoted to long double [...].
2236 if (!getLangOpts().CPlusPlus &&
2237 (FromBuiltin->getKind() == BuiltinType::Float ||
2238 FromBuiltin->getKind() == BuiltinType::Double) &&
2239 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2240 ToBuiltin->getKind() == BuiltinType::Float128))
2241 return true;
2242
2243 // Half can be promoted to float.
2244 if (!getLangOpts().NativeHalfType &&
2245 FromBuiltin->getKind() == BuiltinType::Half &&
2246 ToBuiltin->getKind() == BuiltinType::Float)
2247 return true;
2248 }
2249
2250 return false;
2251}
2252
2253/// Determine if a conversion is a complex promotion.
2254///
2255/// A complex promotion is defined as a complex -> complex conversion
2256/// where the conversion between the underlying real types is a
2257/// floating-point or integral promotion.
2258bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2260 if (!FromComplex)
2261 return false;
2262
2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2264 if (!ToComplex)
2265 return false;
2266
2267 return IsFloatingPointPromotion(FromComplex->getElementType(),
2268 ToComplex->getElementType()) ||
2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2270 ToComplex->getElementType());
2271}
2272
2273/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2274/// the pointer type FromPtr to a pointer to type ToPointee, with the
2275/// same type qualifiers as FromPtr has on its pointee type. ToType,
2276/// if non-empty, will be a pointer to ToType that may or may not have
2277/// the right set of qualifiers on its pointee.
2278///
2279static QualType
2280BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2281 QualType ToPointee, QualType ToType,
2282 ASTContext &Context,
2283 bool StripObjCLifetime = false) {
2284 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast<void> (0))
2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast<void> (0))
2286 "Invalid similarly-qualified pointer type")(static_cast<void> (0));
2287
2288 /// Conversions to 'id' subsume cv-qualifier conversions.
2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
71
Calling 'Type::isObjCIdType'
75
Returning from 'Type::isObjCIdType'
76
Calling 'Type::isObjCQualifiedIdType'
80
Returning from 'Type::isObjCQualifiedIdType'
81
Taking false branch
2290 return ToType.getUnqualifiedType();
2291
2292 QualType CanonFromPointee
2293 = Context.getCanonicalType(FromPtr->getPointeeType());
82
Called C++ object pointer is null
2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2295 Qualifiers Quals = CanonFromPointee.getQualifiers();
2296
2297 if (StripObjCLifetime)
2298 Quals.removeObjCLifetime();
2299
2300 // Exact qualifier match -> return the pointer type we're converting to.
2301 if (CanonToPointee.getLocalQualifiers() == Quals) {
2302 // ToType is exactly what we need. Return it.
2303 if (!ToType.isNull())
2304 return ToType.getUnqualifiedType();
2305
2306 // Build a pointer to ToPointee. It has the right qualifiers
2307 // already.
2308 if (isa<ObjCObjectPointerType>(ToType))
2309 return Context.getObjCObjectPointerType(ToPointee);
2310 return Context.getPointerType(ToPointee);
2311 }
2312
2313 // Just build a canonical type that has the right qualifiers.
2314 QualType QualifiedCanonToPointee
2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2316
2317 if (isa<ObjCObjectPointerType>(ToType))
2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2319 return Context.getPointerType(QualifiedCanonToPointee);
2320}
2321
2322static bool isNullPointerConstantForConversion(Expr *Expr,
2323 bool InOverloadResolution,
2324 ASTContext &Context) {
2325 // Handle value-dependent integral null pointer constants correctly.
2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
45
Assuming the condition is false
46
Taking false branch
2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2329 return !InOverloadResolution;
2330
2331 return Expr->isNullPointerConstant(Context,
49
Returning value, which participates in a condition later
2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
47
Assuming 'InOverloadResolution' is false
48
'?' condition is false
2333 : Expr::NPC_ValueDependentIsNull);
2334}
2335
2336/// IsPointerConversion - Determines whether the conversion of the
2337/// expression From, which has the (possibly adjusted) type FromType,
2338/// can be converted to the type ToType via a pointer conversion (C++
2339/// 4.10). If so, returns true and places the converted type (that
2340/// might differ from ToType in its cv-qualifiers at some level) into
2341/// ConvertedType.
2342///
2343/// This routine also supports conversions to and from block pointers
2344/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2345/// pointers to interfaces. FIXME: Once we've determined the
2346/// appropriate overloading rules for Objective-C, we may want to
2347/// split the Objective-C checks into a different routine; however,
2348/// GCC seems to consider all of these conversions to be pointer
2349/// conversions, so for now they live here. IncompatibleObjC will be
2350/// set if the conversion is an allowed Objective-C conversion that
2351/// should result in a warning.
2352bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2353 bool InOverloadResolution,
2354 QualType& ConvertedType,
2355 bool &IncompatibleObjC) {
2356 IncompatibleObjC = false;
2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
14
Calling 'Sema::isObjCPointerConversion'
24
Returning from 'Sema::isObjCPointerConversion'
2358 IncompatibleObjC))
2359 return true;
2360
2361 // Conversion from a null pointer constant to any Objective-C pointer type.
2362 if (ToType->isObjCObjectPointerType() &&
25
Calling 'Type::isObjCObjectPointerType'
28
Returning from 'Type::isObjCObjectPointerType'
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // Blocks: Block pointers can be converted to void*.
2369 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2371 ConvertedType = ToType;
2372 return true;
2373 }
2374 // Blocks: A null pointer constant can be converted to a block
2375 // pointer type.
2376 if (ToType->isBlockPointerType() &&
29
Calling 'Type::isBlockPointerType'
32
Returning from 'Type::isBlockPointerType'
2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2378 ConvertedType = ToType;
2379 return true;
2380 }
2381
2382 // If the left-hand-side is nullptr_t, the right side can be a null
2383 // pointer constant.
2384 if (ToType->isNullPtrType() &&
33
Calling 'Type::isNullPtrType'
40
Returning from 'Type::isNullPtrType'
2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386 ConvertedType = ToType;
2387 return true;
2388 }
2389
2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
41
Assuming the object is a 'PointerType'
2391 if (!ToTypePtr)
42
Assuming 'ToTypePtr' is non-null
43
Taking false branch
2392 return false;
2393
2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
44
Calling 'isNullPointerConstantForConversion'
50
Returning from 'isNullPointerConstantForConversion'
51
Assuming the condition is false
52
Taking false branch
2396 ConvertedType = ToType;
2397 return true;
2398 }
2399
2400 // Beyond this point, both types need to be pointers
2401 // , including objective-c pointers.
2402 QualType ToPointeeType = ToTypePtr->getPointeeType();
2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
53
Calling 'Type::isObjCObjectPointerType'
56
Returning from 'Type::isObjCObjectPointerType'
57
Calling 'Type::isVoidType'
65
Returning from 'Type::isVoidType'
67
Taking true branch
2404 !getLangOpts().ObjCAutoRefCount) {
66
Assuming field 'ObjCAutoRefCount' is 0
2405 ConvertedType = BuildSimilarlyQualifiedPointerType(
70
Calling 'BuildSimilarlyQualifiedPointerType'
2406 FromType->getAs<ObjCObjectPointerType>(),
68
Assuming the object is not a 'ObjCObjectPointerType'
69
Passing null pointer value via 1st parameter 'FromPtr'
2407 ToPointeeType,
2408 ToType, Context);
2409 return true;
2410 }
2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2412 if (!FromTypePtr)
2413 return false;
2414
2415 QualType FromPointeeType = FromTypePtr->getPointeeType();
2416
2417 // If the unqualified pointee types are the same, this can't be a
2418 // pointer conversion, so don't do all of the work below.
2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2420 return false;
2421
2422 // An rvalue of type "pointer to cv T," where T is an object type,
2423 // can be converted to an rvalue of type "pointer to cv void" (C++
2424 // 4.10p2).
2425 if (FromPointeeType->isIncompleteOrObjectType() &&
2426 ToPointeeType->isVoidType()) {
2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428 ToPointeeType,
2429 ToType, Context,
2430 /*StripObjCLifetime=*/true);
2431 return true;
2432 }
2433
2434 // MSVC allows implicit function to void* type conversion.
2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2436 ToPointeeType->isVoidType()) {
2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438 ToPointeeType,
2439 ToType, Context);
2440 return true;
2441 }
2442
2443 // When we're overloading in C, we allow a special kind of pointer
2444 // conversion for compatible-but-not-identical pointee types.
2445 if (!getLangOpts().CPlusPlus &&
2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2448 ToPointeeType,
2449 ToType, Context);
2450 return true;
2451 }
2452
2453 // C++ [conv.ptr]p3:
2454 //
2455 // An rvalue of type "pointer to cv D," where D is a class type,
2456 // can be converted to an rvalue of type "pointer to cv B," where
2457 // B is a base class (clause 10) of D. If B is an inaccessible
2458 // (clause 11) or ambiguous (10.2) base class of D, a program that
2459 // necessitates this conversion is ill-formed. The result of the
2460 // conversion is a pointer to the base class sub-object of the
2461 // derived class object. The null pointer value is converted to
2462 // the null pointer value of the destination type.
2463 //
2464 // Note that we do not check for ambiguity or inaccessibility
2465 // here. That is handled by CheckPointerConversion.
2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2467 ToPointeeType->isRecordType() &&
2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471 ToPointeeType,
2472 ToType, Context);
2473 return true;
2474 }
2475
2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2479 ToPointeeType,
2480 ToType, Context);
2481 return true;
2482 }
2483
2484 return false;
2485}
2486
2487/// Adopt the given qualifiers for the given type.
2488static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2489 Qualifiers TQs = T.getQualifiers();
2490
2491 // Check whether qualifiers already match.
2492 if (TQs == Qs)
2493 return T;
2494
2495 if (Qs.compatiblyIncludes(TQs))
2496 return Context.getQualifiedType(T, Qs);
2497
2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2499}
2500
2501/// isObjCPointerConversion - Determines whether this is an
2502/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2503/// with the same arguments and return values.
2504bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2505 QualType& ConvertedType,
2506 bool &IncompatibleObjC) {
2507 if (!getLangOpts().ObjC)
15
Assuming field 'ObjC' is not equal to 0
16
Taking false branch
2508 return false;
2509
2510 // The set of qualifiers on the type we're converting from.
2511 Qualifiers FromQualifiers = FromType.getQualifiers();
2512
2513 // First, we handle all conversions on ObjC object pointer types.
2514 const ObjCObjectPointerType* ToObjCPtr =
2515 ToType->getAs<ObjCObjectPointerType>();
17
Assuming the object is not a 'ObjCObjectPointerType'
2516 const ObjCObjectPointerType *FromObjCPtr =
2517 FromType->getAs<ObjCObjectPointerType>();
18
Assuming the object is not a 'ObjCObjectPointerType'
2518
2519 if (ToObjCPtr
18.1
'ToObjCPtr' is null
18.1
'ToObjCPtr' is null
&& FromObjCPtr) {
2520 // If the pointee types are the same (ignoring qualifications),
2521 // then this is not a pointer conversion.
2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2523 FromObjCPtr->getPointeeType()))
2524 return false;
2525
2526 // Conversion between Objective-C pointers.
2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2530 if (getLangOpts().CPlusPlus && LHS && RHS &&
2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2532 FromObjCPtr->getPointeeType()))
2533 return false;
2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2535 ToObjCPtr->getPointeeType(),
2536 ToType, Context);
2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2538 return true;
2539 }
2540
2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2542 // Okay: this is some kind of implicit downcast of Objective-C
2543 // interfaces, which is permitted. However, we're going to
2544 // complain about it.
2545 IncompatibleObjC = true;
2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2547 ToObjCPtr->getPointeeType(),
2548 ToType, Context);
2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2550 return true;
2551 }
2552 }
2553 // Beyond this point, both types need to be C pointers or block pointers.
2554 QualType ToPointeeType;
2555 if (const PointerType *ToCPtr
19.1
'ToCPtr' is null
19.1
'ToCPtr' is null
= ToType->getAs<PointerType>())
19
Assuming the object is not a 'PointerType'
20
Taking false branch
2556 ToPointeeType = ToCPtr->getPointeeType();
2557 else if (const BlockPointerType *ToBlockPtr
21.1
'ToBlockPtr' is null
21.1
'ToBlockPtr' is null
=
2558 ToType->getAs<BlockPointerType>()) {
21
Assuming the object is not a 'BlockPointerType'
2559 // Objective C++: We're able to convert from a pointer to any object
2560 // to a block pointer type.
2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2563 return true;
2564 }
2565 ToPointeeType = ToBlockPtr->getPointeeType();
2566 }
2567 else if (FromType->getAs<BlockPointerType>() &&
22
Assuming the object is not a 'BlockPointerType'
2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2569 // Objective C++: We're able to convert from a block pointer type to a
2570 // pointer to any object.
2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2572 return true;
2573 }
2574 else
2575 return false;
23
Returning zero, which participates in a condition later
2576
2577 QualType FromPointeeType;
2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2579 FromPointeeType = FromCPtr->getPointeeType();
2580 else if (const BlockPointerType *FromBlockPtr =
2581 FromType->getAs<BlockPointerType>())
2582 FromPointeeType = FromBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 // If we have pointers to pointers, recursively check whether this
2587 // is an Objective-C conversion.
2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2590 IncompatibleObjC)) {
2591 // We always complain about this conversion.
2592 IncompatibleObjC = true;
2593 ConvertedType = Context.getPointerType(ConvertedType);
2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595 return true;
2596 }
2597 // Allow conversion of pointee being objective-c pointer to another one;
2598 // as in I* to id.
2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2600 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2602 IncompatibleObjC)) {
2603
2604 ConvertedType = Context.getPointerType(ConvertedType);
2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2606 return true;
2607 }
2608
2609 // If we have pointers to functions or blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion (but
2612 // complain about it).
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2617 if (FromFunctionType && ToFunctionType) {
2618 // If the function types are exactly the same, this isn't an
2619 // Objective-C pointer conversion.
2620 if (Context.getCanonicalType(FromPointeeType)
2621 == Context.getCanonicalType(ToPointeeType))
2622 return false;
2623
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2629 return false;
2630
2631 bool HasObjCConversion = false;
2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2633 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2634 // Okay, the types match exactly. Nothing to do.
2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2636 ToFunctionType->getReturnType(),
2637 ConvertedType, IncompatibleObjC)) {
2638 // Okay, we have an Objective-C pointer conversion.
2639 HasObjCConversion = true;
2640 } else {
2641 // Function types are too different. Abort.
2642 return false;
2643 }
2644
2645 // Check argument types.
2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2647 ArgIdx != NumArgs; ++ArgIdx) {
2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2650 if (Context.getCanonicalType(FromArgType)
2651 == Context.getCanonicalType(ToArgType)) {
2652 // Okay, the types match exactly. Nothing to do.
2653 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2654 ConvertedType, IncompatibleObjC)) {
2655 // Okay, we have an Objective-C pointer conversion.
2656 HasObjCConversion = true;
2657 } else {
2658 // Argument types are too different. Abort.
2659 return false;
2660 }
2661 }
2662
2663 if (HasObjCConversion) {
2664 // We had an Objective-C conversion. Allow this pointer
2665 // conversion, but complain about it.
2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2667 IncompatibleObjC = true;
2668 return true;
2669 }
2670 }
2671
2672 return false;
2673}
2674
2675/// Determine whether this is an Objective-C writeback conversion,
2676/// used for parameter passing when performing automatic reference counting.
2677///
2678/// \param FromType The type we're converting form.
2679///
2680/// \param ToType The type we're converting to.
2681///
2682/// \param ConvertedType The type that will be produced after applying
2683/// this conversion.
2684bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2685 QualType &ConvertedType) {
2686 if (!getLangOpts().ObjCAutoRefCount ||
2687 Context.hasSameUnqualifiedType(FromType, ToType))
2688 return false;
2689
2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2691 QualType ToPointee;
2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2693 ToPointee = ToPointer->getPointeeType();
2694 else
2695 return false;
2696
2697 Qualifiers ToQuals = ToPointee.getQualifiers();
2698 if (!ToPointee->isObjCLifetimeType() ||
2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2700 !ToQuals.withoutObjCLifetime().empty())
2701 return false;
2702
2703 // Argument must be a pointer to __strong to __weak.
2704 QualType FromPointee;
2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2706 FromPointee = FromPointer->getPointeeType();
2707 else
2708 return false;
2709
2710 Qualifiers FromQuals = FromPointee.getQualifiers();
2711 if (!FromPointee->isObjCLifetimeType() ||
2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2714 return false;
2715
2716 // Make sure that we have compatible qualifiers.
2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2718 if (!ToQuals.compatiblyIncludes(FromQuals))
2719 return false;
2720
2721 // Remove qualifiers from the pointee type we're converting from; they
2722 // aren't used in the compatibility check belong, and we'll be adding back
2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2724 FromPointee = FromPointee.getUnqualifiedType();
2725
2726 // The unqualified form of the pointee types must be compatible.
2727 ToPointee = ToPointee.getUnqualifiedType();
2728 bool IncompatibleObjC;
2729 if (Context.typesAreCompatible(FromPointee, ToPointee))
2730 FromPointee = ToPointee;
2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2732 IncompatibleObjC))
2733 return false;
2734
2735 /// Construct the type we're converting to, which is a pointer to
2736 /// __autoreleasing pointee.
2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2738 ConvertedType = Context.getPointerType(FromPointee);
2739 return true;
2740}
2741
2742bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2743 QualType& ConvertedType) {
2744 QualType ToPointeeType;
2745 if (const BlockPointerType *ToBlockPtr =
2746 ToType->getAs<BlockPointerType>())
2747 ToPointeeType = ToBlockPtr->getPointeeType();
2748 else
2749 return false;
2750
2751 QualType FromPointeeType;
2752 if (const BlockPointerType *FromBlockPtr =
2753 FromType->getAs<BlockPointerType>())
2754 FromPointeeType = FromBlockPtr->getPointeeType();
2755 else
2756 return false;
2757 // We have pointer to blocks, check whether the only
2758 // differences in the argument and result types are in Objective-C
2759 // pointer conversions. If so, we permit the conversion.
2760
2761 const FunctionProtoType *FromFunctionType
2762 = FromPointeeType->getAs<FunctionProtoType>();
2763 const FunctionProtoType *ToFunctionType
2764 = ToPointeeType->getAs<FunctionProtoType>();
2765
2766 if (!FromFunctionType || !ToFunctionType)
2767 return false;
2768
2769 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2770 return true;
2771
2772 // Perform the quick checks that will tell us whether these
2773 // function types are obviously different.
2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2776 return false;
2777
2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2780 if (FromEInfo != ToEInfo)
2781 return false;
2782
2783 bool IncompatibleObjC = false;
2784 if (Context.hasSameType(FromFunctionType->getReturnType(),
2785 ToFunctionType->getReturnType())) {
2786 // Okay, the types match exactly. Nothing to do.
2787 } else {
2788 QualType RHS = FromFunctionType->getReturnType();
2789 QualType LHS = ToFunctionType->getReturnType();
2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2791 !RHS.hasQualifiers() && LHS.hasQualifiers())
2792 LHS = LHS.getUnqualifiedType();
2793
2794 if (Context.hasSameType(RHS,LHS)) {
2795 // OK exact match.
2796 } else if (isObjCPointerConversion(RHS, LHS,
2797 ConvertedType, IncompatibleObjC)) {
2798 if (IncompatibleObjC)
2799 return false;
2800 // Okay, we have an Objective-C pointer conversion.
2801 }
2802 else
2803 return false;
2804 }
2805
2806 // Check argument types.
2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2808 ArgIdx != NumArgs; ++ArgIdx) {
2809 IncompatibleObjC = false;
2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2812 if (Context.hasSameType(FromArgType, ToArgType)) {
2813 // Okay, the types match exactly. Nothing to do.
2814 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2815 ConvertedType, IncompatibleObjC)) {
2816 if (IncompatibleObjC)
2817 return false;
2818 // Okay, we have an Objective-C pointer conversion.
2819 } else
2820 // Argument types are too different. Abort.
2821 return false;
2822 }
2823
2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2825 bool CanUseToFPT, CanUseFromFPT;
2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2827 CanUseToFPT, CanUseFromFPT,
2828 NewParamInfos))
2829 return false;
2830
2831 ConvertedType = ToType;
2832 return true;
2833}
2834
2835enum {
2836 ft_default,
2837 ft_different_class,
2838 ft_parameter_arity,
2839 ft_parameter_mismatch,
2840 ft_return_type,
2841 ft_qualifer_mismatch,
2842 ft_noexcept
2843};
2844
2845/// Attempts to get the FunctionProtoType from a Type. Handles
2846/// MemberFunctionPointers properly.
2847static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2848 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2849 return FPT;
2850
2851 if (auto *MPT = FromType->getAs<MemberPointerType>())
2852 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2853
2854 return nullptr;
2855}
2856
2857/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2858/// function types. Catches different number of parameter, mismatch in
2859/// parameter types, and different return types.
2860void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2861 QualType FromType, QualType ToType) {
2862 // If either type is not valid, include no extra info.
2863 if (FromType.isNull() || ToType.isNull()) {
2864 PDiag << ft_default;
2865 return;
2866 }
2867
2868 // Get the function type from the pointers.
2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2870 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2871 *ToMember = ToType->castAs<MemberPointerType>();
2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2874 << QualType(FromMember->getClass(), 0);
2875 return;
2876 }
2877 FromType = FromMember->getPointeeType();
2878 ToType = ToMember->getPointeeType();
2879 }
2880
2881 if (FromType->isPointerType())
2882 FromType = FromType->getPointeeType();
2883 if (ToType->isPointerType())
2884 ToType = ToType->getPointeeType();
2885
2886 // Remove references.
2887 FromType = FromType.getNonReferenceType();
2888 ToType = ToType.getNonReferenceType();
2889
2890 // Don't print extra info for non-specialized template functions.
2891 if (FromType->isInstantiationDependentType() &&
2892 !FromType->getAs<TemplateSpecializationType>()) {
2893 PDiag << ft_default;
2894 return;
2895 }
2896
2897 // No extra info for same types.
2898 if (Context.hasSameType(FromType, ToType)) {
2899 PDiag << ft_default;
2900 return;
2901 }
2902
2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2904 *ToFunction = tryGetFunctionProtoType(ToType);
2905
2906 // Both types need to be function types.
2907 if (!FromFunction || !ToFunction) {
2908 PDiag << ft_default;
2909 return;
2910 }
2911
2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2913 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2914 << FromFunction->getNumParams();
2915 return;
2916 }
2917
2918 // Handle different parameter types.
2919 unsigned ArgPos;
2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2921 PDiag << ft_parameter_mismatch << ArgPos + 1
2922 << ToFunction->getParamType(ArgPos)
2923 << FromFunction->getParamType(ArgPos);
2924 return;
2925 }
2926
2927 // Handle different return type.
2928 if (!Context.hasSameType(FromFunction->getReturnType(),
2929 ToFunction->getReturnType())) {
2930 PDiag << ft_return_type << ToFunction->getReturnType()
2931 << FromFunction->getReturnType();
2932 return;
2933 }
2934
2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2937 << FromFunction->getMethodQuals();
2938 return;
2939 }
2940
2941 // Handle exception specification differences on canonical type (in C++17
2942 // onwards).
2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2944 ->isNothrow() !=
2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2946 ->isNothrow()) {
2947 PDiag << ft_noexcept;
2948 return;
2949 }
2950
2951 // Unable to find a difference, so add no extra info.
2952 PDiag << ft_default;
2953}
2954
2955/// FunctionParamTypesAreEqual - This routine checks two function proto types
2956/// for equality of their argument types. Caller has already checked that
2957/// they have same number of arguments. If the parameters are different,
2958/// ArgPos will have the parameter index of the first different parameter.
2959bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2960 const FunctionProtoType *NewType,
2961 unsigned *ArgPos) {
2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2963 N = NewType->param_type_begin(),
2964 E = OldType->param_type_end();
2965 O && (O != E); ++O, ++N) {
2966 // Ignore address spaces in pointee type. This is to disallow overloading
2967 // on __ptr32/__ptr64 address spaces.
2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2970
2971 if (!Context.hasSameType(Old, New)) {
2972 if (ArgPos)
2973 *ArgPos = O - OldType->param_type_begin();
2974 return false;
2975 }
2976 }
2977 return true;
2978}
2979
2980/// CheckPointerConversion - Check the pointer conversion from the
2981/// expression From to the type ToType. This routine checks for
2982/// ambiguous or inaccessible derived-to-base pointer
2983/// conversions for which IsPointerConversion has already returned
2984/// true. It returns true and produces a diagnostic if there was an
2985/// error, or returns false otherwise.
2986bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2987 CastKind &Kind,
2988 CXXCastPath& BasePath,
2989 bool IgnoreBaseAccess,
2990 bool Diagnose) {
2991 QualType FromType = From->getType();
2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2993
2994 Kind = CK_BitCast;
2995
2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2998 Expr::NPCK_ZeroExpression) {
2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3000 DiagRuntimeBehavior(From->getExprLoc(), From,
3001 PDiag(diag::warn_impcast_bool_to_null_pointer)
3002 << ToType << From->getSourceRange());
3003 else if (!isUnevaluatedContext())
3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3005 << ToType << From->getSourceRange();
3006 }
3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3009 QualType FromPointeeType = FromPtrType->getPointeeType(),
3010 ToPointeeType = ToPtrType->getPointeeType();
3011
3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3014 // We must have a derived-to-base conversion. Check an
3015 // ambiguous or inaccessible conversion.
3016 unsigned InaccessibleID = 0;
3017 unsigned AmbiguousID = 0;
3018 if (Diagnose) {
3019 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3021 }
3022 if (CheckDerivedToBaseConversion(
3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3025 &BasePath, IgnoreBaseAccess))
3026 return true;
3027
3028 // The conversion was successful.
3029 Kind = CK_DerivedToBase;
3030 }
3031
3032 if (Diagnose && !IsCStyleOrFunctionalCast &&
3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3034 assert(getLangOpts().MSVCCompat &&(static_cast<void> (0))
3035 "this should only be possible with MSVCCompat!")(static_cast<void> (0));
3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3037 << From->getSourceRange();
3038 }
3039 }
3040 } else if (const ObjCObjectPointerType *ToPtrType =
3041 ToType->getAs<ObjCObjectPointerType>()) {
3042 if (const ObjCObjectPointerType *FromPtrType =
3043 FromType->getAs<ObjCObjectPointerType>()) {
3044 // Objective-C++ conversions are always okay.
3045 // FIXME: We should have a different class of conversions for the
3046 // Objective-C++ implicit conversions.
3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3048 return false;
3049 } else if (FromType->isBlockPointerType()) {
3050 Kind = CK_BlockPointerToObjCPointerCast;
3051 } else {
3052 Kind = CK_CPointerToObjCPointerCast;
3053 }
3054 } else if (ToType->isBlockPointerType()) {
3055 if (!FromType->isBlockPointerType())
3056 Kind = CK_AnyPointerToBlockPointerCast;
3057 }
3058
3059 // We shouldn't fall into this case unless it's valid for other
3060 // reasons.
3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3062 Kind = CK_NullToPointer;
3063
3064 return false;
3065}
3066
3067/// IsMemberPointerConversion - Determines whether the conversion of the
3068/// expression From, which has the (possibly adjusted) type FromType, can be
3069/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3070/// If so, returns true and places the converted type (that might differ from
3071/// ToType in its cv-qualifiers at some level) into ConvertedType.
3072bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3073 QualType ToType,
3074 bool InOverloadResolution,
3075 QualType &ConvertedType) {
3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3077 if (!ToTypePtr)
3078 return false;
3079
3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3081 if (From->isNullPointerConstant(Context,
3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3083 : Expr::NPC_ValueDependentIsNull)) {
3084 ConvertedType = ToType;
3085 return true;
3086 }
3087
3088 // Otherwise, both types have to be member pointers.
3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3090 if (!FromTypePtr)
3091 return false;
3092
3093 // A pointer to member of B can be converted to a pointer to member of D,
3094 // where D is derived from B (C++ 4.11p2).
3095 QualType FromClass(FromTypePtr->getClass(), 0);
3096 QualType ToClass(ToTypePtr->getClass(), 0);
3097
3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3101 ToClass.getTypePtr());
3102 return true;
3103 }
3104
3105 return false;
3106}
3107
3108/// CheckMemberPointerConversion - Check the member pointer conversion from the
3109/// expression From to the type ToType. This routine checks for ambiguous or
3110/// virtual or inaccessible base-to-derived member pointer conversions
3111/// for which IsMemberPointerConversion has already returned true. It returns
3112/// true and produces a diagnostic if there was an error, or returns false
3113/// otherwise.
3114bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3115 CastKind &Kind,
3116 CXXCastPath &BasePath,
3117 bool IgnoreBaseAccess) {
3118 QualType FromType = From->getType();
3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3120 if (!FromPtrType) {
3121 // This must be a null pointer to member pointer conversion
3122 assert(From->isNullPointerConstant(Context,(static_cast<void> (0))
3123 Expr::NPC_ValueDependentIsNull) &&(static_cast<void> (0))
3124 "Expr must be null pointer constant!")(static_cast<void> (0));
3125 Kind = CK_NullToMemberPointer;
3126 return false;
3127 }
3128
3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3130 assert(ToPtrType && "No member pointer cast has a target type "(static_cast<void> (0))
3131 "that is not a member pointer.")(static_cast<void> (0));
3132
3133 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3134 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3135
3136 // FIXME: What about dependent types?
3137 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast<void> (0));
3138 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast<void> (0));
3139
3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3141 /*DetectVirtual=*/true);
3142 bool DerivationOkay =
3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3144 assert(DerivationOkay &&(static_cast<void> (0))
3145 "Should not have been called if derivation isn't OK.")(static_cast<void> (0));
3146 (void)DerivationOkay;
3147
3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3149 getUnqualifiedType())) {
3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3153 return true;
3154 }
3155
3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3158 << FromClass << ToClass << QualType(VBase, 0)
3159 << From->getSourceRange();
3160 return true;
3161 }
3162
3163 if (!IgnoreBaseAccess)
3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3165 Paths.front(),
3166 diag::err_downcast_from_inaccessible_base);
3167
3168 // Must be a base to derived member conversion.
3169 BuildBasePathArray(Paths, BasePath);
3170 Kind = CK_BaseToDerivedMemberPointer;
3171 return false;
3172}
3173
3174/// Determine whether the lifetime conversion between the two given
3175/// qualifiers sets is nontrivial.
3176static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3177 Qualifiers ToQuals) {
3178 // Converting anything to const __unsafe_unretained is trivial.
3179 if (ToQuals.hasConst() &&
3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3181 return false;
3182
3183 return true;
3184}
3185
3186/// Perform a single iteration of the loop for checking if a qualification
3187/// conversion is valid.
3188///
3189/// Specifically, check whether any change between the qualifiers of \p
3190/// FromType and \p ToType is permissible, given knowledge about whether every
3191/// outer layer is const-qualified.
3192static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3193 bool CStyle, bool IsTopLevel,
3194 bool &PreviousToQualsIncludeConst,
3195 bool &ObjCLifetimeConversion) {
3196 Qualifiers FromQuals = FromType.getQualifiers();
3197 Qualifiers ToQuals = ToType.getQualifiers();
3198
3199 // Ignore __unaligned qualifier if this type is void.
3200 if (ToType.getUnqualifiedType()->isVoidType())
3201 FromQuals.removeUnaligned();
3202
3203 // Objective-C ARC:
3204 // Check Objective-C lifetime conversions.
3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3208 ObjCLifetimeConversion = true;
3209 FromQuals.removeObjCLifetime();
3210 ToQuals.removeObjCLifetime();
3211 } else {
3212 // Qualification conversions cannot cast between different
3213 // Objective-C lifetime qualifiers.
3214 return false;
3215 }
3216 }
3217
3218 // Allow addition/removal of GC attributes but not changing GC attributes.
3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3221 FromQuals.removeObjCGCAttr();
3222 ToQuals.removeObjCGCAttr();
3223 }
3224
3225 // -- for every j > 0, if const is in cv 1,j then const is in cv
3226 // 2,j, and similarly for volatile.
3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3228 return false;
3229
3230 // If address spaces mismatch:
3231 // - in top level it is only valid to convert to addr space that is a
3232 // superset in all cases apart from C-style casts where we allow
3233 // conversions between overlapping address spaces.
3234 // - in non-top levels it is not a valid conversion.
3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3236 (!IsTopLevel ||
3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3239 return false;
3240
3241 // -- if the cv 1,j and cv 2,j are different, then const is in
3242 // every cv for 0 < k < j.
3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3244 !PreviousToQualsIncludeConst)
3245 return false;
3246
3247 // Keep track of whether all prior cv-qualifiers in the "to" type
3248 // include const.
3249 PreviousToQualsIncludeConst =
3250 PreviousToQualsIncludeConst && ToQuals.hasConst();
3251 return true;
3252}
3253
3254/// IsQualificationConversion - Determines whether the conversion from
3255/// an rvalue of type FromType to ToType is a qualification conversion
3256/// (C++ 4.4).
3257///
3258/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3259/// when the qualification conversion involves a change in the Objective-C
3260/// object lifetime.
3261bool
3262Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3263 bool CStyle, bool &ObjCLifetimeConversion) {
3264 FromType = Context.getCanonicalType(FromType);
3265 ToType = Context.getCanonicalType(ToType);
3266 ObjCLifetimeConversion = false;
3267
3268 // If FromType and ToType are the same type, this is not a
3269 // qualification conversion.
3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3271 return false;
3272
3273 // (C++ 4.4p4):
3274 // A conversion can add cv-qualifiers at levels other than the first
3275 // in multi-level pointers, subject to the following rules: [...]
3276 bool PreviousToQualsIncludeConst = true;
3277 bool UnwrappedAnyPointer = false;
3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3279 if (!isQualificationConversionStep(
3280 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3282 return false;
3283 UnwrappedAnyPointer = true;
3284 }
3285
3286 // We are left with FromType and ToType being the pointee types
3287 // after unwrapping the original FromType and ToType the same number
3288 // of times. If we unwrapped any pointers, and if FromType and
3289 // ToType have the same unqualified type (since we checked
3290 // qualifiers above), then this is a qualification conversion.
3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3292}
3293
3294/// - Determine whether this is a conversion from a scalar type to an
3295/// atomic type.
3296///
3297/// If successful, updates \c SCS's second and third steps in the conversion
3298/// sequence to finish the conversion.
3299static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3300 bool InOverloadResolution,
3301 StandardConversionSequence &SCS,
3302 bool CStyle) {
3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3304 if (!ToAtomic)
3305 return false;
3306
3307 StandardConversionSequence InnerSCS;
3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3309 InOverloadResolution, InnerSCS,
3310 CStyle, /*AllowObjCWritebackConversion=*/false))
3311 return false;
3312
3313 SCS.Second = InnerSCS.Second;
3314 SCS.setToType(1, InnerSCS.getToType(1));
3315 SCS.Third = InnerSCS.Third;
3316 SCS.QualificationIncludesObjCLifetime
3317 = InnerSCS.QualificationIncludesObjCLifetime;
3318 SCS.setToType(2, InnerSCS.getToType(2));
3319 return true;
3320}
3321
3322static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3323 CXXConstructorDecl *Constructor,
3324 QualType Type) {
3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3326 if (CtorType->getNumParams() > 0) {
3327 QualType FirstArg = CtorType->getParamType(0);
3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3329 return true;
3330 }
3331 return false;
3332}
3333
3334static OverloadingResult
3335IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3336 CXXRecordDecl *To,
3337 UserDefinedConversionSequence &User,
3338 OverloadCandidateSet &CandidateSet,
3339 bool AllowExplicit) {
3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3341 for (auto *D : S.LookupConstructors(To)) {
3342 auto Info = getConstructorInfo(D);
3343 if (!Info)
3344 continue;
3345
3346 bool Usable = !Info.Constructor->isInvalidDecl() &&
3347 S.isInitListConstructor(Info.Constructor);
3348 if (Usable) {
3349 bool SuppressUserConversions = false;
3350 if (Info.ConstructorTmpl)
3351 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3352 /*ExplicitArgs*/ nullptr, From,
3353 CandidateSet, SuppressUserConversions,
3354 /*PartialOverloading*/ false,
3355 AllowExplicit);
3356 else
3357 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3358 CandidateSet, SuppressUserConversions,
3359 /*PartialOverloading*/ false, AllowExplicit);
3360 }
3361 }
3362
3363 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3364
3365 OverloadCandidateSet::iterator Best;
3366 switch (auto Result =
3367 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3368 case OR_Deleted:
3369 case OR_Success: {
3370 // Record the standard conversion we used and the conversion function.
3371 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3372 QualType ThisType = Constructor->getThisType();
3373 // Initializer lists don't have conversions as such.
3374 User.Before.setAsIdentityConversion();
3375 User.HadMultipleCandidates = HadMultipleCandidates;
3376 User.ConversionFunction = Constructor;
3377 User.FoundConversionFunction = Best->FoundDecl;
3378 User.After.setAsIdentityConversion();
3379 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3380 User.After.setAllToTypes(ToType);
3381 return Result;
3382 }
3383
3384 case OR_No_Viable_Function:
3385 return OR_No_Viable_Function;
3386 case OR_Ambiguous:
3387 return OR_Ambiguous;
3388 }
3389
3390 llvm_unreachable("Invalid OverloadResult!")__builtin_unreachable();
3391}
3392
3393/// Determines whether there is a user-defined conversion sequence
3394/// (C++ [over.ics.user]) that converts expression From to the type
3395/// ToType. If such a conversion exists, User will contain the
3396/// user-defined conversion sequence that performs such a conversion
3397/// and this routine will return true. Otherwise, this routine returns
3398/// false and User is unspecified.
3399///
3400/// \param AllowExplicit true if the conversion should consider C++0x
3401/// "explicit" conversion functions as well as non-explicit conversion
3402/// functions (C++0x [class.conv.fct]p2).
3403///
3404/// \param AllowObjCConversionOnExplicit true if the conversion should
3405/// allow an extra Objective-C pointer conversion on uses of explicit
3406/// constructors. Requires \c AllowExplicit to also be set.
3407static OverloadingResult
3408IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3409 UserDefinedConversionSequence &User,
3410 OverloadCandidateSet &CandidateSet,
3411 AllowedExplicit AllowExplicit,
3412 bool AllowObjCConversionOnExplicit) {
3413 assert(AllowExplicit != AllowedExplicit::None ||(static_cast<void> (0))
3414 !AllowObjCConversionOnExplicit)(static_cast<void> (0));
3415 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3416
3417 // Whether we will only visit constructors.
3418 bool ConstructorsOnly = false;
3419
3420 // If the type we are conversion to is a class type, enumerate its
3421 // constructors.
3422 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3423 // C++ [over.match.ctor]p1:
3424 // When objects of class type are direct-initialized (8.5), or
3425 // copy-initialized from an expression of the same or a
3426 // derived class type (8.5), overload resolution selects the
3427 // constructor. [...] For copy-initialization, the candidate
3428 // functions are all the converting constructors (12.3.1) of
3429 // that class. The argument list is the expression-list within
3430 // the parentheses of the initializer.
3431 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3432 (From->getType()->getAs<RecordType>() &&
3433 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3434 ConstructorsOnly = true;
3435
3436 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3437 // We're not going to find any constructors.
3438 } else if (CXXRecordDecl *ToRecordDecl
3439 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3440
3441 Expr **Args = &From;
3442 unsigned NumArgs = 1;
3443 bool ListInitializing = false;
3444 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3445 // But first, see if there is an init-list-constructor that will work.
3446 OverloadingResult Result = IsInitializerListConstructorConversion(
3447 S, From, ToType, ToRecordDecl, User, CandidateSet,
3448 AllowExplicit == AllowedExplicit::All);
3449 if (Result != OR_No_Viable_Function)
3450 return Result;
3451 // Never mind.
3452 CandidateSet.clear(
3453 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3454
3455 // If we're list-initializing, we pass the individual elements as
3456 // arguments, not the entire list.
3457 Args = InitList->getInits();
3458 NumArgs = InitList->getNumInits();
3459 ListInitializing = true;
3460 }
3461
3462 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3463 auto Info = getConstructorInfo(D);
3464 if (!Info)
3465 continue;
3466
3467 bool Usable = !Info.Constructor->isInvalidDecl();
3468 if (!ListInitializing)
3469 Usable = Usable && Info.Constructor->isConvertingConstructor(
3470 /*AllowExplicit*/ true);
3471 if (Usable) {
3472 bool SuppressUserConversions = !ConstructorsOnly;
3473 // C++20 [over.best.ics.general]/4.5:
3474 // if the target is the first parameter of a constructor [of class
3475 // X] and the constructor [...] is a candidate by [...] the second
3476 // phase of [over.match.list] when the initializer list has exactly
3477 // one element that is itself an initializer list, [...] and the
3478 // conversion is to X or reference to cv X, user-defined conversion
3479 // sequences are not cnosidered.
3480 if (SuppressUserConversions && ListInitializing) {
3481 SuppressUserConversions =
3482 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3483 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3484 ToType);
3485 }
3486 if (Info.ConstructorTmpl)
3487 S.AddTemplateOverloadCandidate(
3488 Info.ConstructorTmpl, Info.FoundDecl,
3489 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3490 CandidateSet, SuppressUserConversions,
3491 /*PartialOverloading*/ false,
3492 AllowExplicit == AllowedExplicit::All);
3493 else
3494 // Allow one user-defined conversion when user specifies a
3495 // From->ToType conversion via an static cast (c-style, etc).
3496 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3497 llvm::makeArrayRef(Args, NumArgs),
3498 CandidateSet, SuppressUserConversions,
3499 /*PartialOverloading*/ false,
3500 AllowExplicit == AllowedExplicit::All);
3501 }
3502 }
3503 }
3504 }
3505
3506 // Enumerate conversion functions, if we're allowed to.
3507 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3508 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3509 // No conversion functions from incomplete types.
3510 } else if (const RecordType *FromRecordType =
3511 From->getType()->getAs<RecordType>()) {
3512 if (CXXRecordDecl *FromRecordDecl
3513 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3514 // Add all of the conversion functions as candidates.
3515 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3517 DeclAccessPair FoundDecl = I.getPair();
3518 NamedDecl *D = FoundDecl.getDecl();
3519 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3520 if (isa<UsingShadowDecl>(D))
3521 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3522
3523 CXXConversionDecl *Conv;
3524 FunctionTemplateDecl *ConvTemplate;
3525 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3526 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3527 else
3528 Conv = cast<CXXConversionDecl>(D);
3529
3530 if (ConvTemplate)
3531 S.AddTemplateConversionCandidate(
3532 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3533 CandidateSet, AllowObjCConversionOnExplicit,
3534 AllowExplicit != AllowedExplicit::None);
3535 else
3536 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3537 CandidateSet, AllowObjCConversionOnExplicit,
3538 AllowExplicit != AllowedExplicit::None);
3539 }
3540 }
3541 }
3542
3543 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3544
3545 OverloadCandidateSet::iterator Best;
3546 switch (auto Result =
3547 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3548 case OR_Success:
3549 case OR_Deleted:
3550 // Record the standard conversion we used and the conversion function.
3551 if (CXXConstructorDecl *Constructor
3552 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3553 // C++ [over.ics.user]p1:
3554 // If the user-defined conversion is specified by a
3555 // constructor (12.3.1), the initial standard conversion
3556 // sequence converts the source type to the type required by
3557 // the argument of the constructor.
3558 //
3559 QualType ThisType = Constructor->getThisType();
3560 if (isa<InitListExpr>(From)) {
3561 // Initializer lists don't have conversions as such.
3562 User.Before.setAsIdentityConversion();
3563 } else {
3564 if (Best->Conversions[0].isEllipsis())
3565 User.EllipsisConversion = true;
3566 else {
3567 User.Before = Best->Conversions[0].Standard;
3568 User.EllipsisConversion = false;
3569 }
3570 }
3571 User.HadMultipleCandidates = HadMultipleCandidates;
3572 User.ConversionFunction = Constructor;
3573 User.FoundConversionFunction = Best->FoundDecl;
3574 User.After.setAsIdentityConversion();
3575 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3576 User.After.setAllToTypes(ToType);
3577 return Result;
3578 }
3579 if (CXXConversionDecl *Conversion
3580 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3581 // C++ [over.ics.user]p1:
3582 //
3583 // [...] If the user-defined conversion is specified by a
3584 // conversion function (12.3.2), the initial standard
3585 // conversion sequence converts the source type to the
3586 // implicit object parameter of the conversion function.
3587 User.Before = Best->Conversions[0].Standard;
3588 User.HadMultipleCandidates = HadMultipleCandidates;
3589 User.ConversionFunction = Conversion;
3590 User.FoundConversionFunction = Best->FoundDecl;
3591 User.EllipsisConversion = false;
3592
3593 // C++ [over.ics.user]p2:
3594 // The second standard conversion sequence converts the
3595 // result of the user-defined conversion to the target type
3596 // for the sequence. Since an implicit conversion sequence
3597 // is an initialization, the special rules for
3598 // initialization by user-defined conversion apply when
3599 // selecting the best user-defined conversion for a
3600 // user-defined conversion sequence (see 13.3.3 and
3601 // 13.3.3.1).
3602 User.After = Best->FinalConversion;
3603 return Result;
3604 }
3605 llvm_unreachable("Not a constructor or conversion function?")__builtin_unreachable();
3606
3607 case OR_No_Viable_Function:
3608 return OR_No_Viable_Function;
3609
3610 case OR_Ambiguous:
3611 return OR_Ambiguous;
3612 }
3613
3614 llvm_unreachable("Invalid OverloadResult!")__builtin_unreachable();
3615}
3616
3617bool
3618Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3619 ImplicitConversionSequence ICS;
3620 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3621 OverloadCandidateSet::CSK_Normal);
3622 OverloadingResult OvResult =
3623 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3624 CandidateSet, AllowedExplicit::None, false);
3625
3626 if (!(OvResult == OR_Ambiguous ||
3627 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3628 return false;
3629
3630 auto Cands = CandidateSet.CompleteCandidates(
3631 *this,
3632 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3633 From);
3634 if (OvResult == OR_Ambiguous)
3635 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3636 << From->getType() << ToType << From->getSourceRange();
3637 else { // OR_No_Viable_Function && !CandidateSet.empty()
3638 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3639 diag::err_typecheck_nonviable_condition_incomplete,
3640 From->getType(), From->getSourceRange()))
3641 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3642 << false << From->getType() << From->getSourceRange() << ToType;
3643 }
3644
3645 CandidateSet.NoteCandidates(
3646 *this, From, Cands);
3647 return true;
3648}
3649
3650// Helper for compareConversionFunctions that gets the FunctionType that the
3651// conversion-operator return value 'points' to, or nullptr.
3652static const FunctionType *
3653getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3654 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3655 const PointerType *RetPtrTy =
3656 ConvFuncTy->getReturnType()->getAs<PointerType>();
3657
3658 if (!RetPtrTy)
3659 return nullptr;
3660
3661 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3662}
3663
3664/// Compare the user-defined conversion functions or constructors
3665/// of two user-defined conversion sequences to determine whether any ordering
3666/// is possible.
3667static ImplicitConversionSequence::CompareKind
3668compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3669 FunctionDecl *Function2) {
3670 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3671 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3672 if (!Conv1 || !Conv2)
3673 return ImplicitConversionSequence::Indistinguishable;
3674
3675 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3676 return ImplicitConversionSequence::Indistinguishable;
3677
3678 // Objective-C++:
3679 // If both conversion functions are implicitly-declared conversions from
3680 // a lambda closure type to a function pointer and a block pointer,
3681 // respectively, always prefer the conversion to a function pointer,
3682 // because the function pointer is more lightweight and is more likely
3683 // to keep code working.
3684 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3685 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3686 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3687 if (Block1 != Block2)
3688 return Block1 ? ImplicitConversionSequence::Worse
3689 : ImplicitConversionSequence::Better;
3690 }
3691
3692 // In order to support multiple calling conventions for the lambda conversion
3693 // operator (such as when the free and member function calling convention is
3694 // different), prefer the 'free' mechanism, followed by the calling-convention
3695 // of operator(). The latter is in place to support the MSVC-like solution of
3696 // defining ALL of the possible conversions in regards to calling-convention.
3697 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3698 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3699
3700 if (Conv1FuncRet && Conv2FuncRet &&
3701 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3702 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3703 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3704
3705 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3706 const FunctionProtoType *CallOpProto =
3707 CallOp->getType()->getAs<FunctionProtoType>();
3708
3709 CallingConv CallOpCC =
3710 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3711 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3712 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3713 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3714 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3715
3716 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3717 for (CallingConv CC : PrefOrder) {
3718 if (Conv1CC == CC)
3719 return ImplicitConversionSequence::Better;
3720 if (Conv2CC == CC)
3721 return ImplicitConversionSequence::Worse;
3722 }
3723 }
3724
3725 return ImplicitConversionSequence::Indistinguishable;
3726}
3727
3728static bool hasDeprecatedStringLiteralToCharPtrConversion(
3729 const ImplicitConversionSequence &ICS) {
3730 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3731 (ICS.isUserDefined() &&
3732 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3733}
3734
3735/// CompareImplicitConversionSequences - Compare two implicit
3736/// conversion sequences to determine whether one is better than the
3737/// other or if they are indistinguishable (C++ 13.3.3.2).
3738static ImplicitConversionSequence::CompareKind
3739CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3740 const ImplicitConversionSequence& ICS1,
3741 const ImplicitConversionSequence& ICS2)
3742{
3743 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3744 // conversion sequences (as defined in 13.3.3.1)
3745 // -- a standard conversion sequence (13.3.3.1.1) is a better
3746 // conversion sequence than a user-defined conversion sequence or
3747 // an ellipsis conversion sequence, and
3748 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3749 // conversion sequence than an ellipsis conversion sequence
3750 // (13.3.3.1.3).
3751 //
3752 // C++0x [over.best.ics]p10:
3753 // For the purpose of ranking implicit conversion sequences as
3754 // described in 13.3.3.2, the ambiguous conversion sequence is
3755 // treated as a user-defined sequence that is indistinguishable
3756 // from any other user-defined conversion sequence.
3757
3758 // String literal to 'char *' conversion has been deprecated in C++03. It has
3759 // been removed from C++11. We still accept this conversion, if it happens at
3760 // the best viable function. Otherwise, this conversion is considered worse
3761 // than ellipsis conversion. Consider this as an extension; this is not in the
3762 // standard. For example:
3763 //
3764 // int &f(...); // #1
3765 // void f(char*); // #2
3766 // void g() { int &r = f("foo"); }
3767 //
3768 // In C++03, we pick #2 as the best viable function.
3769 // In C++11, we pick #1 as the best viable function, because ellipsis
3770 // conversion is better than string-literal to char* conversion (since there
3771 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3772 // convert arguments, #2 would be the best viable function in C++11.
3773 // If the best viable function has this conversion, a warning will be issued
3774 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3775
3776 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3778 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3779 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3780 ? ImplicitConversionSequence::Worse
3781 : ImplicitConversionSequence::Better;
3782
3783 if (ICS1.getKindRank() < ICS2.getKindRank())
3784 return ImplicitConversionSequence::Better;
3785 if (ICS2.getKindRank() < ICS1.getKindRank())
3786 return ImplicitConversionSequence::Worse;
3787
3788 // The following checks require both conversion sequences to be of
3789 // the same kind.
3790 if (ICS1.getKind() != ICS2.getKind())
3791 return ImplicitConversionSequence::Indistinguishable;
3792
3793 ImplicitConversionSequence::CompareKind Result =
3794 ImplicitConversionSequence::Indistinguishable;
3795
3796 // Two implicit conversion sequences of the same form are
3797 // indistinguishable conversion sequences unless one of the
3798 // following rules apply: (C++ 13.3.3.2p3):
3799
3800 // List-initialization sequence L1 is a better conversion sequence than
3801 // list-initialization sequence L2 if:
3802 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3803 // if not that,
3804 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3805 // and N1 is smaller than N2.,
3806 // even if one of the other rules in this paragraph would otherwise apply.
3807 if (!ICS1.isBad()) {
3808 if (ICS1.isStdInitializerListElement() &&
3809 !ICS2.isStdInitializerListElement())
3810 return ImplicitConversionSequence::Better;
3811 if (!ICS1.isStdInitializerListElement() &&
3812 ICS2.isStdInitializerListElement())
3813 return ImplicitConversionSequence::Worse;
3814 }
3815
3816 if (ICS1.isStandard())
3817 // Standard conversion sequence S1 is a better conversion sequence than
3818 // standard conversion sequence S2 if [...]
3819 Result = CompareStandardConversionSequences(S, Loc,
3820 ICS1.Standard, ICS2.Standard);
3821 else if (ICS1.isUserDefined()) {
3822 // User-defined conversion sequence U1 is a better conversion
3823 // sequence than another user-defined conversion sequence U2 if
3824 // they contain the same user-defined conversion function or
3825 // constructor and if the second standard conversion sequence of
3826 // U1 is better than the second standard conversion sequence of
3827 // U2 (C++ 13.3.3.2p3).
3828 if (ICS1.UserDefined.ConversionFunction ==
3829 ICS2.UserDefined.ConversionFunction)
3830 Result = CompareStandardConversionSequences(S, Loc,
3831 ICS1.UserDefined.After,
3832 ICS2.UserDefined.After);
3833 else
3834 Result = compareConversionFunctions(S,
3835 ICS1.UserDefined.ConversionFunction,
3836 ICS2.UserDefined.ConversionFunction);
3837 }
3838
3839 return Result;
3840}
3841
3842// Per 13.3.3.2p3, compare the given standard conversion sequences to
3843// determine if one is a proper subset of the other.
3844static ImplicitConversionSequence::CompareKind
3845compareStandardConversionSubsets(ASTContext &Context,
3846 const StandardConversionSequence& SCS1,
3847 const StandardConversionSequence& SCS2) {
3848 ImplicitConversionSequence::CompareKind Result
3849 = ImplicitConversionSequence::Indistinguishable;
3850
3851 // the identity conversion sequence is considered to be a subsequence of
3852 // any non-identity conversion sequence
3853 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3854 return ImplicitConversionSequence::Better;
3855 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3856 return ImplicitConversionSequence::Worse;
3857
3858 if (SCS1.Second != SCS2.Second) {
3859 if (SCS1.Second == ICK_Identity)
3860 Result = ImplicitConversionSequence::Better;
3861 else if (SCS2.Second == ICK_Identity)
3862 Result = ImplicitConversionSequence::Worse;
3863 else
3864 return ImplicitConversionSequence::Indistinguishable;
3865 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3866 return ImplicitConversionSequence::Indistinguishable;
3867
3868 if (SCS1.Third == SCS2.Third) {
3869 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3870 : ImplicitConversionSequence::Indistinguishable;
3871 }
3872
3873 if (SCS1.Third == ICK_Identity)
3874 return Result == ImplicitConversionSequence::Worse
3875 ? ImplicitConversionSequence::Indistinguishable
3876 : ImplicitConversionSequence::Better;
3877
3878 if (SCS2.Third == ICK_Identity)
3879 return Result == ImplicitConversionSequence::Better
3880 ? ImplicitConversionSequence::Indistinguishable
3881 : ImplicitConversionSequence::Worse;
3882
3883 return ImplicitConversionSequence::Indistinguishable;
3884}
3885
3886/// Determine whether one of the given reference bindings is better
3887/// than the other based on what kind of bindings they are.
3888static bool
3889isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3890 const StandardConversionSequence &SCS2) {
3891 // C++0x [over.ics.rank]p3b4:
3892 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3893 // implicit object parameter of a non-static member function declared
3894 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3895 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3896 // lvalue reference to a function lvalue and S2 binds an rvalue
3897 // reference*.
3898 //
3899 // FIXME: Rvalue references. We're going rogue with the above edits,
3900 // because the semantics in the current C++0x working paper (N3225 at the
3901 // time of this writing) break the standard definition of std::forward
3902 // and std::reference_wrapper when dealing with references to functions.
3903 // Proposed wording changes submitted to CWG for consideration.
3904 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3905 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3906 return false;
3907
3908 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3909 SCS2.IsLvalueReference) ||
3910 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3911 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3912}
3913
3914enum class FixedEnumPromotion {
3915 None,
3916 ToUnderlyingType,
3917 ToPromotedUnderlyingType
3918};
3919
3920/// Returns kind of fixed enum promotion the \a SCS uses.
3921static FixedEnumPromotion
3922getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3923
3924 if (SCS.Second != ICK_Integral_Promotion)
3925 return FixedEnumPromotion::None;
3926
3927 QualType FromType = SCS.getFromType();
3928 if (!FromType->isEnumeralType())
3929 return FixedEnumPromotion::None;
3930
3931 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3932 if (!Enum->isFixed())
3933 return FixedEnumPromotion::None;
3934
3935 QualType UnderlyingType = Enum->getIntegerType();
3936 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3937 return FixedEnumPromotion::ToUnderlyingType;
3938
3939 return FixedEnumPromotion::ToPromotedUnderlyingType;
3940}
3941
3942/// CompareStandardConversionSequences - Compare two standard
3943/// conversion sequences to determine whether one is better than the
3944/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3945static ImplicitConversionSequence::CompareKind
3946CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3947 const StandardConversionSequence& SCS1,
3948 const StandardConversionSequence& SCS2)
3949{
3950 // Standard conversion sequence S1 is a better conversion sequence
3951 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3952
3953 // -- S1 is a proper subsequence of S2 (comparing the conversion
3954 // sequences in the canonical form defined by 13.3.3.1.1,
3955 // excluding any Lvalue Transformation; the identity conversion
3956 // sequence is considered to be a subsequence of any
3957 // non-identity conversion sequence) or, if not that,
3958 if (ImplicitConversionSequence::CompareKind CK
3959 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3960 return CK;
3961
3962 // -- the rank of S1 is better than the rank of S2 (by the rules
3963 // defined below), or, if not that,
3964 ImplicitConversionRank Rank1 = SCS1.getRank();
3965 ImplicitConversionRank Rank2 = SCS2.getRank();
3966 if (Rank1 < Rank2)
3967 return ImplicitConversionSequence::Better;
3968 else if (Rank2 < Rank1)
3969 return ImplicitConversionSequence::Worse;
3970
3971 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3972 // are indistinguishable unless one of the following rules
3973 // applies:
3974
3975 // A conversion that is not a conversion of a pointer, or
3976 // pointer to member, to bool is better than another conversion
3977 // that is such a conversion.
3978 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3979 return SCS2.isPointerConversionToBool()
3980 ? ImplicitConversionSequence::Better
3981 : ImplicitConversionSequence::Worse;
3982
3983 // C++14 [over.ics.rank]p4b2:
3984 // This is retroactively applied to C++11 by CWG 1601.
3985 //
3986 // A conversion that promotes an enumeration whose underlying type is fixed
3987 // to its underlying type is better than one that promotes to the promoted
3988 // underlying type, if the two are different.
3989 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3990 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3991 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3992 FEP1 != FEP2)
3993 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3994 ? ImplicitConversionSequence::Better
3995 : ImplicitConversionSequence::Worse;
3996
3997 // C++ [over.ics.rank]p4b2:
3998 //
3999 // If class B is derived directly or indirectly from class A,
4000 // conversion of B* to A* is better than conversion of B* to
4001 // void*, and conversion of A* to void* is better than conversion
4002 // of B* to void*.
4003 bool SCS1ConvertsToVoid
4004 = SCS1.isPointerConversionToVoidPointer(S.Context);
4005 bool SCS2ConvertsToVoid
4006 = SCS2.isPointerConversionToVoidPointer(S.Context);
4007 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4008 // Exactly one of the conversion sequences is a conversion to
4009 // a void pointer; it's the worse conversion.
4010 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4011 : ImplicitConversionSequence::Worse;
4012 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4013 // Neither conversion sequence converts to a void pointer; compare
4014 // their derived-to-base conversions.
4015 if (ImplicitConversionSequence::CompareKind DerivedCK
4016 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4017 return DerivedCK;
4018 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4019 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4020 // Both conversion sequences are conversions to void
4021 // pointers. Compare the source types to determine if there's an
4022 // inheritance relationship in their sources.
4023 QualType FromType1 = SCS1.getFromType();
4024 QualType FromType2 = SCS2.getFromType();
4025
4026 // Adjust the types we're converting from via the array-to-pointer
4027 // conversion, if we need to.
4028 if (SCS1.First == ICK_Array_To_Pointer)
4029 FromType1 = S.Context.getArrayDecayedType(FromType1);
4030 if (SCS2.First == ICK_Array_To_Pointer)
4031 FromType2 = S.Context.getArrayDecayedType(FromType2);
4032
4033 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4034 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4035
4036 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4037 return ImplicitConversionSequence::Better;
4038 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4039 return ImplicitConversionSequence::Worse;
4040
4041 // Objective-C++: If one interface is more specific than the
4042 // other, it is the better one.
4043 const ObjCObjectPointerType* FromObjCPtr1
4044 = FromType1->getAs<ObjCObjectPointerType>();
4045 const ObjCObjectPointerType* FromObjCPtr2
4046 = FromType2->getAs<ObjCObjectPointerType>();
4047 if (FromObjCPtr1 && FromObjCPtr2) {
4048 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4049 FromObjCPtr2);
4050 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4051 FromObjCPtr1);
4052 if (AssignLeft != AssignRight) {
4053 return AssignLeft? ImplicitConversionSequence::Better
4054 : ImplicitConversionSequence::Worse;
4055 }
4056 }
4057 }
4058
4059 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4060 // Check for a better reference binding based on the kind of bindings.
4061 if (isBetterReferenceBindingKind(SCS1, SCS2))
4062 return ImplicitConversionSequence::Better;
4063 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4064 return ImplicitConversionSequence::Worse;
4065 }
4066
4067 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4068 // bullet 3).
4069 if (ImplicitConversionSequence::CompareKind QualCK
4070 = CompareQualificationConversions(S, SCS1, SCS2))
4071 return QualCK;
4072
4073 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4074 // C++ [over.ics.rank]p3b4:
4075 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4076 // which the references refer are the same type except for
4077 // top-level cv-qualifiers, and the type to which the reference
4078 // initialized by S2 refers is more cv-qualified than the type
4079 // to which the reference initialized by S1 refers.
4080 QualType T1 = SCS1.getToType(2);
4081 QualType T2 = SCS2.getToType(2);
4082 T1 = S.Context.getCanonicalType(T1);
4083 T2 = S.Context.getCanonicalType(T2);
4084 Qualifiers T1Quals, T2Quals;
4085 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4086 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4087 if (UnqualT1 == UnqualT2) {
4088 // Objective-C++ ARC: If the references refer to objects with different
4089 // lifetimes, prefer bindings that don't change lifetime.
4090 if (SCS1.ObjCLifetimeConversionBinding !=
4091 SCS2.ObjCLifetimeConversionBinding) {
4092 return SCS1.ObjCLifetimeConversionBinding
4093 ? ImplicitConversionSequence::Worse
4094 : ImplicitConversionSequence::Better;
4095 }
4096
4097 // If the type is an array type, promote the element qualifiers to the
4098 // type for comparison.
4099 if (isa<ArrayType>(T1) && T1Quals)
4100 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4101 if (isa<ArrayType>(T2) && T2Quals)
4102 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4103 if (T2.isMoreQualifiedThan(T1))
4104 return ImplicitConversionSequence::Better;
4105 if (T1.isMoreQualifiedThan(T2))
4106 return ImplicitConversionSequence::Worse;
4107 }
4108 }
4109
4110 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4111 // floating-to-integral conversion if the integral conversion
4112 // is between types of the same size.
4113 // For example:
4114 // void f(float);
4115 // void f(int);
4116 // int main {
4117 // long a;
4118 // f(a);
4119 // }
4120 // Here, MSVC will call f(int) instead of generating a compile error
4121 // as clang will do in standard mode.
4122 if (S.getLangOpts().MSVCCompat &&
4123 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4124 SCS1.Second == ICK_Integral_Conversion &&
4125 SCS2.Second == ICK_Floating_Integral &&
4126 S.Context.getTypeSize(SCS1.getFromType()) ==
4127 S.Context.getTypeSize(SCS1.getToType(2)))
4128 return ImplicitConversionSequence::Better;
4129
4130 // Prefer a compatible vector conversion over a lax vector conversion
4131 // For example:
4132 //
4133 // typedef float __v4sf __attribute__((__vector_size__(16)));
4134 // void f(vector float);
4135 // void f(vector signed int);
4136 // int main() {
4137 // __v4sf a;
4138 // f(a);
4139 // }
4140 // Here, we'd like to choose f(vector float) and not
4141 // report an ambiguous call error
4142 if (SCS1.Second == ICK_Vector_Conversion &&
4143 SCS2.Second == ICK_Vector_Conversion) {
4144 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4145 SCS1.getFromType(), SCS1.getToType(2));
4146 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4147 SCS2.getFromType(), SCS2.getToType(2));
4148
4149 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4150 return SCS1IsCompatibleVectorConversion
4151 ? ImplicitConversionSequence::Better
4152 : ImplicitConversionSequence::Worse;
4153 }
4154
4155 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4156 SCS2.Second == ICK_SVE_Vector_Conversion) {
4157 bool SCS1IsCompatibleSVEVectorConversion =
4158 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4159 bool SCS2IsCompatibleSVEVectorConversion =
4160 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4161
4162 if (SCS1IsCompatibleSVEVectorConversion !=
4163 SCS2IsCompatibleSVEVectorConversion)
4164 return SCS1IsCompatibleSVEVectorConversion
4165 ? ImplicitConversionSequence::Better
4166 : ImplicitConversionSequence::Worse;
4167 }
4168
4169 return ImplicitConversionSequence::Indistinguishable;
4170}
4171
4172/// CompareQualificationConversions - Compares two standard conversion
4173/// sequences to determine whether they can be ranked based on their
4174/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4175static ImplicitConversionSequence::CompareKind
4176CompareQualificationConversions(Sema &S,
4177 const StandardConversionSequence& SCS1,
4178 const StandardConversionSequence& SCS2) {
4179 // C++ 13.3.3.2p3:
4180 // -- S1 and S2 differ only in their qualification conversion and
4181 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4182 // cv-qualification signature of type T1 is a proper subset of
4183 // the cv-qualification signature of type T2, and S1 is not the
4184 // deprecated string literal array-to-pointer conversion (4.2).
4185 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4186 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4187 return ImplicitConversionSequence::Indistinguishable;
4188
4189 // FIXME: the example in the standard doesn't use a qualification
4190 // conversion (!)
4191 QualType T1 = SCS1.getToType(2);
4192 QualType T2 = SCS2.getToType(2);
4193 T1 = S.Context.getCanonicalType(T1);
4194 T2 = S.Context.getCanonicalType(T2);
4195 assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast<void> (0));
4196 Qualifiers T1Quals, T2Quals;
4197 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4198 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4199
4200 // If the types are the same, we won't learn anything by unwrapping
4201 // them.
4202 if (UnqualT1 == UnqualT2)
4203 return ImplicitConversionSequence::Indistinguishable;
4204
4205 ImplicitConversionSequence::CompareKind Result
4206 = ImplicitConversionSequence::Indistinguishable;
4207
4208 // Objective-C++ ARC:
4209 // Prefer qualification conversions not involving a change in lifetime
4210 // to qualification conversions that do not change lifetime.
4211 if (SCS1.QualificationIncludesObjCLifetime !=
4212 SCS2.QualificationIncludesObjCLifetime) {
4213 Result = SCS1.QualificationIncludesObjCLifetime
4214 ? ImplicitConversionSequence::Worse
4215 : ImplicitConversionSequence::Better;
4216 }
4217
4218 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4219 // Within each iteration of the loop, we check the qualifiers to
4220 // determine if this still looks like a qualification
4221 // conversion. Then, if all is well, we unwrap one more level of
4222 // pointers or pointers-to-members and do it all again
4223 // until there are no more pointers or pointers-to-members left
4224 // to unwrap. This essentially mimics what
4225 // IsQualificationConversion does, but here we're checking for a
4226 // strict subset of qualifiers.
4227 if (T1.getQualifiers().withoutObjCLifetime() ==
4228 T2.getQualifiers().withoutObjCLifetime())
4229 // The qualifiers are the same, so this doesn't tell us anything
4230 // about how the sequences rank.
4231 // ObjC ownership quals are omitted above as they interfere with
4232 // the ARC overload rule.
4233 ;
4234 else if (T2.isMoreQualifiedThan(T1)) {
4235 // T1 has fewer qualifiers, so it could be the better sequence.
4236 if (Result == ImplicitConversionSequence::Worse)
4237 // Neither has qualifiers that are a subset of the other's
4238 // qualifiers.
4239 return ImplicitConversionSequence::Indistinguishable;
4240
4241 Result = ImplicitConversionSequence::Better;
4242 } else if (T1.isMoreQualifiedThan(T2)) {
4243 // T2 has fewer qualifiers, so it could be the better sequence.
4244 if (Result == ImplicitConversionSequence::Better)
4245 // Neither has qualifiers that are a subset of the other's
4246 // qualifiers.
4247 return ImplicitConversionSequence::Indistinguishable;
4248
4249 Result = ImplicitConversionSequence::Worse;
4250 } else {
4251 // Qualifiers are disjoint.
4252 return ImplicitConversionSequence::Indistinguishable;
4253 }
4254
4255 // If the types after this point are equivalent, we're done.
4256 if (S.Context.hasSameUnqualifiedType(T1, T2))
4257 break;
4258 }
4259
4260 // Check that the winning standard conversion sequence isn't using
4261 // the deprecated string literal array to pointer conversion.
4262 switch (Result) {
4263 case ImplicitConversionSequence::Better:
4264 if (SCS1.DeprecatedStringLiteralToCharPtr)
4265 Result = ImplicitConversionSequence::Indistinguishable;
4266 break;
4267
4268 case ImplicitConversionSequence::Indistinguishable:
4269 break;
4270
4271 case ImplicitConversionSequence::Worse:
4272 if (SCS2.DeprecatedStringLiteralToCharPtr)
4273 Result = ImplicitConversionSequence::Indistinguishable;
4274 break;
4275 }
4276
4277 return Result;
4278}
4279
4280/// CompareDerivedToBaseConversions - Compares two standard conversion
4281/// sequences to determine whether they can be ranked based on their
4282/// various kinds of derived-to-base conversions (C++
4283/// [over.ics.rank]p4b3). As part of these checks, we also look at
4284/// conversions between Objective-C interface types.
4285static ImplicitConversionSequence::CompareKind
4286CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4287 const StandardConversionSequence& SCS1,
4288 const StandardConversionSequence& SCS2) {
4289 QualType FromType1 = SCS1.getFromType();
4290 QualType ToType1 = SCS1.getToType(1);
4291 QualType FromType2 = SCS2.getFromType();
4292 QualType ToType2 = SCS2.getToType(1);
4293
4294 // Adjust the types we're converting from via the array-to-pointer
4295 // conversion, if we need to.
4296 if (SCS1.First == ICK_Array_To_Pointer)
4297 FromType1 = S.Context.getArrayDecayedType(FromType1);
4298 if (SCS2.First == ICK_Array_To_Pointer)
4299 FromType2 = S.Context.getArrayDecayedType(FromType2);
4300
4301 // Canonicalize all of the types.
4302 FromType1 = S.Context.getCanonicalType(FromType1);
4303 ToType1 = S.Context.getCanonicalType(ToType1);
4304 FromType2 = S.Context.getCanonicalType(FromType2);
4305 ToType2 = S.Context.getCanonicalType(ToType2);
4306
4307 // C++ [over.ics.rank]p4b3:
4308 //
4309 // If class B is derived directly or indirectly from class A and
4310 // class C is derived directly or indirectly from B,
4311 //
4312 // Compare based on pointer conversions.
4313 if (SCS1.Second == ICK_Pointer_Conversion &&
4314 SCS2.Second == ICK_Pointer_Conversion &&
4315 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4316 FromType1->isPointerType() && FromType2->isPointerType() &&
4317 ToType1->isPointerType() && ToType2->isPointerType()) {
4318 QualType FromPointee1 =
4319 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4320 QualType ToPointee1 =
4321 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4322 QualType FromPointee2 =
4323 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4324 QualType ToPointee2 =
4325 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4326
4327 // -- conversion of C* to B* is better than conversion of C* to A*,
4328 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4329 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4330 return ImplicitConversionSequence::Better;
4331 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4332 return ImplicitConversionSequence::Worse;
4333 }
4334
4335 // -- conversion of B* to A* is better than conversion of C* to A*,
4336 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4337 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4338 return ImplicitConversionSequence::Better;
4339 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4340 return ImplicitConversionSequence::Worse;
4341 }
4342 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4343 SCS2.Second == ICK_Pointer_Conversion) {
4344 const ObjCObjectPointerType *FromPtr1
4345 = FromType1->getAs<ObjCObjectPointerType>();
4346 const ObjCObjectPointerType *FromPtr2
4347 = FromType2->getAs<ObjCObjectPointerType>();
4348 const ObjCObjectPointerType *ToPtr1
4349 = ToType1->getAs<ObjCObjectPointerType>();
4350 const ObjCObjectPointerType *ToPtr2
4351 = ToType2->getAs<ObjCObjectPointerType>();
4352
4353 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4354 // Apply the same conversion ranking rules for Objective-C pointer types
4355 // that we do for C++ pointers to class types. However, we employ the
4356 // Objective-C pseudo-subtyping relationship used for assignment of
4357 // Objective-C pointer types.
4358 bool FromAssignLeft
4359 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4360 bool FromAssignRight
4361 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4362 bool ToAssignLeft
4363 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4364 bool ToAssignRight
4365 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4366
4367 // A conversion to an a non-id object pointer type or qualified 'id'
4368 // type is better than a conversion to 'id'.
4369 if (ToPtr1->isObjCIdType() &&
4370 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4371 return ImplicitConversionSequence::Worse;
4372 if (ToPtr2->isObjCIdType() &&
4373 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4374 return ImplicitConversionSequence::Better;
4375
4376 // A conversion to a non-id object pointer type is better than a
4377 // conversion to a qualified 'id' type
4378 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4379 return ImplicitConversionSequence::Worse;
4380 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4381 return ImplicitConversionSequence::Better;
4382
4383 // A conversion to an a non-Class object pointer type or qualified 'Class'
4384 // type is better than a conversion to 'Class'.
4385 if (ToPtr1->isObjCClassType() &&
4386 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4387 return ImplicitConversionSequence::Worse;
4388 if (ToPtr2->isObjCClassType() &&
4389 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4390 return ImplicitConversionSequence::Better;
4391
4392 // A conversion to a non-Class object pointer type is better than a
4393 // conversion to a qualified 'Class' type.
4394 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4395 return ImplicitConversionSequence::Worse;
4396 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4397 return ImplicitConversionSequence::Better;
4398
4399 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4400 if (S.Context.hasSameType(FromType1, FromType2) &&
4401 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4402 (ToAssignLeft != ToAssignRight)) {
4403 if (FromPtr1->isSpecialized()) {
4404 // "conversion of B<A> * to B * is better than conversion of B * to
4405 // C *.
4406 bool IsFirstSame =
4407 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4408 bool IsSecondSame =
4409 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4410 if (IsFirstSame) {
4411 if (!IsSecondSame)
4412 return ImplicitConversionSequence::Better;
4413 } else if (IsSecondSame)
4414 return ImplicitConversionSequence::Worse;
4415 }
4416 return ToAssignLeft? ImplicitConversionSequence::Worse
4417 : ImplicitConversionSequence::Better;
4418 }
4419
4420 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4421 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4422 (FromAssignLeft != FromAssignRight))
4423 return FromAssignLeft? ImplicitConversionSequence::Better
4424 : ImplicitConversionSequence::Worse;
4425 }
4426 }
4427
4428 // Ranking of member-pointer types.
4429 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4430 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4431 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4432 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4433 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4434 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4435 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4436 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4437 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4438 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4439 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4440 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4441 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4442 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4443 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4444 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4445 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4446 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4447 return ImplicitConversionSequence::Worse;
4448 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4449 return ImplicitConversionSequence::Better;
4450 }
4451 // conversion of B::* to C::* is better than conversion of A::* to C::*
4452 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4453 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4454 return ImplicitConversionSequence::Better;
4455 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4456 return ImplicitConversionSequence::Worse;
4457 }
4458 }
4459
4460 if (SCS1.Second == ICK_Derived_To_Base) {
4461 // -- conversion of C to B is better than conversion of C to A,
4462 // -- binding of an expression of type C to a reference of type
4463 // B& is better than binding an expression of type C to a
4464 // reference of type A&,
4465 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4466 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4467 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4468 return ImplicitConversionSequence::Better;
4469 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4470 return ImplicitConversionSequence::Worse;
4471 }
4472
4473 // -- conversion of B to A is better than conversion of C to A.
4474 // -- binding of an expression of type B to a reference of type
4475 // A& is better than binding an expression of type C to a
4476 // reference of type A&,
4477 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4478 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4479 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4480 return ImplicitConversionSequence::Better;
4481 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4482 return ImplicitConversionSequence::Worse;
4483 }
4484 }
4485
4486 return ImplicitConversionSequence::Indistinguishable;
4487}
4488
4489/// Determine whether the given type is valid, e.g., it is not an invalid
4490/// C++ class.
4491static bool isTypeValid(QualType T) {
4492 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4493 return !Record->isInvalidDecl();
4494
4495 return true;
4496}
4497
4498static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4499 if (!T.getQualifiers().hasUnaligned())
4500 return T;
4501
4502 Qualifiers Q;
4503 T = Ctx.getUnqualifiedArrayType(T, Q);
4504 Q.removeUnaligned();
4505 return Ctx.getQualifiedType(T, Q);
4506}
4507
4508/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4509/// determine whether they are reference-compatible,
4510/// reference-related, or incompatible, for use in C++ initialization by
4511/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4512/// type, and the first type (T1) is the pointee type of the reference
4513/// type being initialized.
4514Sema::ReferenceCompareResult
4515Sema::CompareReferenceRelationship(SourceLocation Loc,
4516 QualType OrigT1, QualType OrigT2,
4517 ReferenceConversions *ConvOut) {
4518 assert(!OrigT1->isReferenceType() &&(static_cast<void> (0))
4519 "T1 must be the pointee type of the reference type")(static_cast<void> (0));
4520 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast<void> (0));
4521
4522 QualType T1 = Context.getCanonicalType(OrigT1);
4523 QualType T2 = Context.getCanonicalType(OrigT2);
4524 Qualifiers T1Quals, T2Quals;
4525 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4526 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4527
4528 ReferenceConversions ConvTmp;
4529 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4530 Conv = ReferenceConversions();
4531
4532 // C++2a [dcl.init.ref]p4:
4533 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4534 // reference-related to "cv2 T2" if T1 is similar to T2, or
4535 // T1 is a base class of T2.
4536 // "cv1 T1" is reference-compatible with "cv2 T2" if
4537 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4538 // "pointer to cv1 T1" via a standard conversion sequence.
4539
4540 // Check for standard conversions we can apply to pointers: derived-to-base
4541 // conversions, ObjC pointer conversions, and function pointer conversions.
4542 // (Qualification conversions are checked last.)
4543 QualType ConvertedT2;
4544 if (UnqualT1 == UnqualT2) {
4545 // Nothing to do.
4546 } else if (isCompleteType(Loc, OrigT2) &&
4547 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4548 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4549 Conv |= ReferenceConversions::DerivedToBase;
4550 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4551 UnqualT2->isObjCObjectOrInterfaceType() &&
4552 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4553 Conv |= ReferenceConversions::ObjC;
4554 else if (UnqualT2->isFunctionType() &&
4555 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4556 Conv |= ReferenceConversions::Function;
4557 // No need to check qualifiers; function types don't have them.
4558 return Ref_Compatible;
4559 }
4560 bool ConvertedReferent = Conv != 0;
4561
4562 // We can have a qualification conversion. Compute whether the types are
4563 // similar at the same time.
4564 bool PreviousToQualsIncludeConst = true;
4565 bool TopLevel = true;
4566 do {
4567 if (T1 == T2)
4568 break;
4569
4570 // We will need a qualification conversion.
4571 Conv |= ReferenceConversions::Qualification;
4572
4573 // Track whether we performed a qualification conversion anywhere other
4574 // than the top level. This matters for ranking reference bindings in
4575 // overload resolution.
4576 if (!TopLevel)
4577 Conv |= ReferenceConversions::NestedQualification;
4578
4579 // MS compiler ignores __unaligned qualifier for references; do the same.
4580 T1 = withoutUnaligned(Context, T1);
4581 T2 = withoutUnaligned(Context, T2);
4582
4583 // If we find a qualifier mismatch, the types are not reference-compatible,
4584 // but are still be reference-related if they're similar.
4585 bool ObjCLifetimeConversion = false;
4586 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4587 PreviousToQualsIncludeConst,
4588 ObjCLifetimeConversion))
4589 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4590 ? Ref_Related
4591 : Ref_Incompatible;
4592
4593 // FIXME: Should we track this for any level other than the first?
4594 if (ObjCLifetimeConversion)
4595 Conv |= ReferenceConversions::ObjCLifetime;
4596
4597 TopLevel = false;
4598 } while (Context.UnwrapSimilarTypes(T1, T2));
4599
4600 // At this point, if the types are reference-related, we must either have the
4601 // same inner type (ignoring qualifiers), or must have already worked out how
4602 // to convert the referent.
4603 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4604 ? Ref_Compatible
4605 : Ref_Incompatible;
4606}
4607
4608/// Look for a user-defined conversion to a value reference-compatible
4609/// with DeclType. Return true if something definite is found.
4610static bool
4611FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4612 QualType DeclType, SourceLocation DeclLoc,
4613 Expr *Init, QualType T2, bool AllowRvalues,
4614 bool AllowExplicit) {
4615 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast<void> (0));
4616 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4617
4618 OverloadCandidateSet CandidateSet(
4619 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4620 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4621 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4622 NamedDecl *D = *I;
4623 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4624 if (isa<UsingShadowDecl>(D))
4625 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4626
4627 FunctionTemplateDecl *ConvTemplate
4628 = dyn_cast<FunctionTemplateDecl>(D);
4629 CXXConversionDecl *Conv;
4630 if (ConvTemplate)
4631 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4632 else
4633 Conv = cast<CXXConversionDecl>(D);
4634
4635 if (AllowRvalues) {
4636 // If we are initializing an rvalue reference, don't permit conversion
4637 // functions that return lvalues.
4638 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4639 const ReferenceType *RefType
4640 = Conv->getConversionType()->getAs<LValueReferenceType>();
4641 if (RefType && !RefType->getPointeeType()->isFunctionType())
4642 continue;
4643 }
4644
4645 if (!ConvTemplate &&
4646 S.CompareReferenceRelationship(
4647 DeclLoc,
4648 Conv->getConversionType()
4649 .getNonReferenceType()
4650 .getUnqualifiedType(),
4651 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4652 Sema::Ref_Incompatible)
4653 continue;
4654 } else {
4655 // If the conversion function doesn't return a reference type,
4656 // it can't be considered for this conversion. An rvalue reference
4657 // is only acceptable if its referencee is a function type.
4658
4659 const ReferenceType *RefType =
4660 Conv->getConversionType()->getAs<ReferenceType>();
4661 if (!RefType ||
4662 (!RefType->isLValueReferenceType() &&
4663 !RefType->getPointeeType()->isFunctionType()))
4664 continue;
4665 }
4666
4667 if (ConvTemplate)
4668 S.AddTemplateConversionCandidate(
4669 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4670 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4671 else
4672 S.AddConversionCandidate(
4673 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4674 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4675 }
4676
4677 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4678
4679 OverloadCandidateSet::iterator Best;
4680 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4681 case OR_Success:
4682 // C++ [over.ics.ref]p1:
4683 //
4684 // [...] If the parameter binds directly to the result of
4685 // applying a conversion function to the argument
4686 // expression, the implicit conversion sequence is a
4687 // user-defined conversion sequence (13.3.3.1.2), with the
4688 // second standard conversion sequence either an identity
4689 // conversion or, if the conversion function returns an
4690 // entity of a type that is a derived class of the parameter
4691 // type, a derived-to-base Conversion.
4692 if (!Best->FinalConversion.DirectBinding)
4693 return false;
4694
4695 ICS.setUserDefined();
4696 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4697 ICS.UserDefined.After = Best->FinalConversion;
4698 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4699 ICS.UserDefined.ConversionFunction = Best->Function;
4700 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4701 ICS.UserDefined.EllipsisConversion = false;
4702 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast<void> (0))
4703 ICS.UserDefined.After.DirectBinding &&(static_cast<void> (0))
4704 "Expected a direct reference binding!")(static_cast<void> (0));
4705 return true;
4706
4707 case OR_Ambiguous:
4708 ICS.setAmbiguous();
4709 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4710 Cand != CandidateSet.end(); ++Cand)
4711 if (Cand->Best)
4712 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4713 return true;
4714
4715 case OR_No_Viable_Function:
4716 case OR_Deleted:
4717 // There was no suitable conversion, or we found a deleted
4718 // conversion; continue with other checks.
4719 return false;
4720 }
4721
4722 llvm_unreachable("Invalid OverloadResult!")__builtin_unreachable();
4723}
4724
4725/// Compute an implicit conversion sequence for reference
4726/// initialization.
4727static ImplicitConversionSequence
4728TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4729 SourceLocation DeclLoc,
4730 bool SuppressUserConversions,
4731 bool AllowExplicit) {
4732 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast<void> (0));
4733
4734 // Most paths end in a failed conversion.
4735 ImplicitConversionSequence ICS;
4736 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4737
4738 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4739 QualType T2 = Init->getType();
4740
4741 // If the initializer is the address of an overloaded function, try
4742 // to resolve the overloaded function. If all goes well, T2 is the
4743 // type of the resulting function.
4744 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4745 DeclAccessPair Found;
4746 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4747 false, Found))
4748 T2 = Fn->getType();
4749 }
4750
4751 // Compute some basic properties of the types and the initializer.
4752 bool isRValRef = DeclType->isRValueReferenceType();
4753 Expr::Classification InitCategory = Init->Classify(S.Context);
4754
4755 Sema::ReferenceConversions RefConv;
4756 Sema::ReferenceCompareResult RefRelationship =
4757 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4758
4759 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4760 ICS.setStandard();
4761 ICS.Standard.First = ICK_Identity;
4762 // FIXME: A reference binding can be a function conversion too. We should
4763 // consider that when ordering reference-to-function bindings.
4764 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4765 ? ICK_Derived_To_Base
4766 : (RefConv & Sema::ReferenceConversions::ObjC)
4767 ? ICK_Compatible_Conversion
4768 : ICK_Identity;
4769 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4770 // a reference binding that performs a non-top-level qualification
4771 // conversion as a qualification conversion, not as an identity conversion.
4772 ICS.Standard.Third = (RefConv &
4773 Sema::ReferenceConversions::NestedQualification)
4774 ? ICK_Qualification
4775 : ICK_Identity;
4776 ICS.Standard.setFromType(T2);
4777 ICS.Standard.setToType(0, T2);
4778 ICS.Standard.setToType(1, T1);
4779 ICS.Standard.setToType(2, T1);
4780 ICS.Standard.ReferenceBinding = true;
4781 ICS.Standard.DirectBinding = BindsDirectly;
4782 ICS.Standard.IsLvalueReference = !isRValRef;
4783 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4784 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4785 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4786 ICS.Standard.ObjCLifetimeConversionBinding =
4787 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4788 ICS.Standard.CopyConstructor = nullptr;
4789 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4790 };
4791
4792 // C++0x [dcl.init.ref]p5:
4793 // A reference to type "cv1 T1" is initialized by an expression
4794 // of type "cv2 T2" as follows:
4795
4796 // -- If reference is an lvalue reference and the initializer expression
4797 if (!isRValRef) {
4798 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4799 // reference-compatible with "cv2 T2," or
4800 //
4801 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4802 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4803 // C++ [over.ics.ref]p1:
4804 // When a parameter of reference type binds directly (8.5.3)
4805 // to an argument expression, the implicit conversion sequence
4806 // is the identity conversion, unless the argument expression
4807 // has a type that is a derived class of the parameter type,
4808 // in which case the implicit conversion sequence is a
4809 // derived-to-base Conversion (13.3.3.1).
4810 SetAsReferenceBinding(/*BindsDirectly=*/true);
4811
4812 // Nothing more to do: the inaccessibility/ambiguity check for
4813 // derived-to-base conversions is suppressed when we're
4814 // computing the implicit conversion sequence (C++
4815 // [over.best.ics]p2).
4816 return ICS;
4817 }
4818
4819 // -- has a class type (i.e., T2 is a class type), where T1 is
4820 // not reference-related to T2, and can be implicitly
4821 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4822 // is reference-compatible with "cv3 T3" 92) (this
4823 // conversion is selected by enumerating the applicable
4824 // conversion functions (13.3.1.6) and choosing the best
4825 // one through overload resolution (13.3)),
4826 if (!SuppressUserConversions && T2->isRecordType() &&
4827 S.isCompleteType(DeclLoc, T2) &&
4828 RefRelationship == Sema::Ref_Incompatible) {
4829 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4830 Init, T2, /*AllowRvalues=*/false,
4831 AllowExplicit))
4832 return ICS;
4833 }
4834 }
4835
4836 // -- Otherwise, the reference shall be an lvalue reference to a
4837 // non-volatile const type (i.e., cv1 shall be const), or the reference
4838 // shall be an rvalue reference.
4839 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4840 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4841 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4842 return ICS;
4843 }
4844
4845 // -- If the initializer expression
4846 //
4847 // -- is an xvalue, class prvalue, array prvalue or function
4848 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4849 if (RefRelationship == Sema::Ref_Compatible &&
4850 (InitCategory.isXValue() ||
4851 (InitCategory.isPRValue() &&
4852 (T2->isRecordType() || T2->isArrayType())) ||
4853 (InitCategory.isLValue() && T2->isFunctionType()))) {
4854 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4855 // binding unless we're binding to a class prvalue.
4856 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4857 // allow the use of rvalue references in C++98/03 for the benefit of
4858 // standard library implementors; therefore, we need the xvalue check here.
4859 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4860 !(InitCategory.isPRValue() || T2->isRecordType()));
4861 return ICS;
4862 }
4863
4864 // -- has a class type (i.e., T2 is a class type), where T1 is not
4865 // reference-related to T2, and can be implicitly converted to
4866 // an xvalue, class prvalue, or function lvalue of type
4867 // "cv3 T3", where "cv1 T1" is reference-compatible with
4868 // "cv3 T3",
4869 //
4870 // then the reference is bound to the value of the initializer
4871 // expression in the first case and to the result of the conversion
4872 // in the second case (or, in either case, to an appropriate base
4873 // class subobject).
4874 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4875 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4876 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4877 Init, T2, /*AllowRvalues=*/true,
4878 AllowExplicit)) {
4879 // In the second case, if the reference is an rvalue reference
4880 // and the second standard conversion sequence of the
4881 // user-defined conversion sequence includes an lvalue-to-rvalue
4882 // conversion, the program is ill-formed.
4883 if (ICS.isUserDefined() && isRValRef &&
4884 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4885 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4886
4887 return ICS;
4888 }
4889
4890 // A temporary of function type cannot be created; don't even try.
4891 if (T1->isFunctionType())
4892 return ICS;
4893
4894 // -- Otherwise, a temporary of type "cv1 T1" is created and
4895 // initialized from the initializer expression using the
4896 // rules for a non-reference copy initialization (8.5). The
4897 // reference is then bound to the temporary. If T1 is
4898 // reference-related to T2, cv1 must be the same
4899 // cv-qualification as, or greater cv-qualification than,
4900 // cv2; otherwise, the program is ill-formed.
4901 if (RefRelationship == Sema::Ref_Related) {
4902 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4903 // we would be reference-compatible or reference-compatible with
4904 // added qualification. But that wasn't the case, so the reference
4905 // initialization fails.
4906 //
4907 // Note that we only want to check address spaces and cvr-qualifiers here.
4908 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4909 Qualifiers T1Quals = T1.getQualifiers();
4910 Qualifiers T2Quals = T2.getQualifiers();
4911 T1Quals.removeObjCGCAttr();
4912 T1Quals.removeObjCLifetime();
4913 T2Quals.removeObjCGCAttr();
4914 T2Quals.removeObjCLifetime();
4915 // MS compiler ignores __unaligned qualifier for references; do the same.
4916 T1Quals.removeUnaligned();
4917 T2Quals.removeUnaligned();
4918 if (!T1Quals.compatiblyIncludes(T2Quals))
4919 return ICS;
4920 }
4921
4922 // If at least one of the types is a class type, the types are not
4923 // related, and we aren't allowed any user conversions, the
4924 // reference binding fails. This case is important for breaking
4925 // recursion, since TryImplicitConversion below will attempt to
4926 // create a temporary through the use of a copy constructor.
4927 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4928 (T1->isRecordType() || T2->isRecordType()))
4929 return ICS;
4930
4931 // If T1 is reference-related to T2 and the reference is an rvalue
4932 // reference, the initializer expression shall not be an lvalue.
4933 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4934 Init->Classify(S.Context).isLValue()) {
4935 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4936 return ICS;
4937 }
4938
4939 // C++ [over.ics.ref]p2:
4940 // When a parameter of reference type is not bound directly to
4941 // an argument expression, the conversion sequence is the one
4942 // required to convert the argument expression to the
4943 // underlying type of the reference according to
4944 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4945 // to copy-initializing a temporary of the underlying type with
4946 // the argument expression. Any difference in top-level
4947 // cv-qualification is subsumed by the initialization itself
4948 // and does not constitute a conversion.
4949 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4950 AllowedExplicit::None,
4951 /*InOverloadResolution=*/false,
4952 /*CStyle=*/false,
4953 /*AllowObjCWritebackConversion=*/false,
4954 /*AllowObjCConversionOnExplicit=*/false);
4955
4956 // Of course, that's still a reference binding.
4957 if (ICS.isStandard()) {
4958 ICS.Standard.ReferenceBinding = true;
4959 ICS.Standard.IsLvalueReference = !isRValRef;
4960 ICS.Standard.BindsToFunctionLvalue = false;
4961 ICS.Standard.BindsToRvalue = true;
4962 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4963 ICS.Standard.ObjCLifetimeConversionBinding = false;
4964 } else if (ICS.isUserDefined()) {
4965 const ReferenceType *LValRefType =
4966 ICS.UserDefined.ConversionFunction->getReturnType()
4967 ->getAs<LValueReferenceType>();
4968
4969 // C++ [over.ics.ref]p3:
4970 // Except for an implicit object parameter, for which see 13.3.1, a
4971 // standard conversion sequence cannot be formed if it requires [...]
4972 // binding an rvalue reference to an lvalue other than a function
4973 // lvalue.
4974 // Note that the function case is not possible here.
4975 if (isRValRef && LValRefType) {
4976 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4977 return ICS;
4978 }
4979
4980 ICS.UserDefined.After.ReferenceBinding = true;
4981 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4982 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4983 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4984 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4985 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4986 }
4987
4988 return ICS;
4989}
4990
4991static ImplicitConversionSequence
4992TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4993 bool SuppressUserConversions,
4994 bool InOverloadResolution,
4995 bool AllowObjCWritebackConversion,
4996 bool AllowExplicit = false);
4997
4998/// TryListConversion - Try to copy-initialize a value of type ToType from the
4999/// initializer list From.
5000static ImplicitConversionSequence
5001TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5002 bool SuppressUserConversions,
5003 bool InOverloadResolution,
5004 bool AllowObjCWritebackConversion) {
5005 // C++11 [over.ics.list]p1:
5006 // When an argument is an initializer list, it is not an expression and
5007 // special rules apply for converting it to a parameter type.
5008
5009 ImplicitConversionSequence Result;
5010 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5011
5012 // We need a complete type for what follows. Incomplete types can never be
5013 // initialized from init lists.
5014 if (!S.isCompleteType(From->getBeginLoc(), ToType))
5015 return Result;
5016
5017 // Per DR1467:
5018 // If the parameter type is a class X and the initializer list has a single
5019 // element of type cv U, where U is X or a class derived from X, the
5020 // implicit conversion sequence is the one required to convert the element
5021 // to the parameter type.
5022 //
5023 // Otherwise, if the parameter type is a character array [... ]
5024 // and the initializer list has a single element that is an
5025 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5026 // implicit conversion sequence is the identity conversion.
5027 if (From->getNumInits() == 1) {
5028 if (ToType->isRecordType()) {
5029 QualType InitType = From->getInit(0)->getType();
5030 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5031 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5032 return TryCopyInitialization(S, From->getInit(0), ToType,
5033 SuppressUserConversions,
5034 InOverloadResolution,
5035 AllowObjCWritebackConversion);
5036 }
5037
5038 if (const auto *AT = S.Context.getAsArrayType(ToType)) {
5039 if (S.IsStringInit(From->getInit(0), AT)) {
5040 InitializedEntity Entity =
5041 InitializedEntity::InitializeParameter(S.Context, ToType,
5042 /*Consumed=*/false);
5043 if (S.CanPerformCopyInitialization(Entity, From)) {
5044 Result.setStandard();
5045 Result.Standard.setAsIdentityConversion();
5046 Result.Standard.setFromType(ToType);
5047 Result.Standard.setAllToTypes(ToType);
5048 return Result;
5049 }
5050 }
5051 }
5052 }
5053
5054 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5055 // C++11 [over.ics.list]p2:
5056 // If the parameter type is std::initializer_list<X> or "array of X" and
5057 // all the elements can be implicitly converted to X, the implicit
5058 // conversion sequence is the worst conversion necessary to convert an
5059 // element of the list to X.
5060 //
5061 // C++14 [over.ics.list]p3:
5062 // Otherwise, if the parameter type is "array of N X", if the initializer
5063 // list has exactly N elements or if it has fewer than N elements and X is
5064 // default-constructible, and if all the elements of the initializer list
5065 // can be implicitly converted to X, the implicit conversion sequence is
5066 // the worst conversion necessary to convert an element of the list to X.
5067 //
5068 // FIXME: We're missing a lot of these checks.
5069 bool toStdInitializerList = false;
5070 QualType X;
5071 if (ToType->isArrayType())
5072 X = S.Context.getAsArrayType(ToType)->getElementType();
5073 else
5074 toStdInitializerList = S.isStdInitializerList(ToType, &X);
5075 if (!X.isNull()) {
5076 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5077 Expr *Init = From->getInit(i);
5078 ImplicitConversionSequence ICS =
5079 TryCopyInitialization(S, Init, X, SuppressUserConversions,
5080 InOverloadResolution,
5081 AllowObjCWritebackConversion);
5082 // If a single element isn't convertible, fail.
5083 if (ICS.isBad()) {
5084 Result = ICS;
5085 break;
5086 }
5087 // Otherwise, look for the worst conversion.
5088 if (Result.isBad() || CompareImplicitConversionSequences(
5089 S, From->getBeginLoc(), ICS, Result) ==
5090 ImplicitConversionSequence::Worse)
5091 Result = ICS;
5092 }
5093
5094 // For an empty list, we won't have computed any conversion sequence.
5095 // Introduce the identity conversion sequence.
5096 if (From->getNumInits() == 0) {
5097 Result.setStandard();
5098 Result.Standard.setAsIdentityConversion();
5099 Result.Standard.setFromType(ToType);
5100 Result.Standard.setAllToTypes(ToType);
5101 }
5102
5103 Result.setStdInitializerListElement(toStdInitializerList);
5104 return Result;
5105 }
5106
5107 // C++14 [over.ics.list]p4:
5108 // C++11 [over.ics.list]p3:
5109 // Otherwise, if the parameter is a non-aggregate class X and overload
5110 // resolution chooses a single best constructor [...] the implicit
5111 // conversion sequence is a user-defined conversion sequence. If multiple
5112 // constructors are viable but none is better than the others, the
5113 // implicit conversion sequence is a user-defined conversion sequence.
5114 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5115 // This function can deal with initializer lists.
5116 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5117 AllowedExplicit::None,
5118 InOverloadResolution, /*CStyle=*/false,
5119 AllowObjCWritebackConversion,
5120 /*AllowObjCConversionOnExplicit=*/false);
5121 }
5122
5123 // C++14 [over.ics.list]p5:
5124 // C++11 [over.ics.list]p4:
5125 // Otherwise, if the parameter has an aggregate type which can be
5126 // initialized from the initializer list [...] the implicit conversion
5127 // sequence is a user-defined conversion sequence.
5128 if (ToType->isAggregateType()) {
5129 // Type is an aggregate, argument is an init list. At this point it comes
5130 // down to checking whether the initialization works.
5131 // FIXME: Find out whether this parameter is consumed or not.
5132 InitializedEntity Entity =
5133 InitializedEntity::InitializeParameter(S.Context, ToType,
5134 /*Consumed=*/false);
5135 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5136 From)) {
5137 Result.setUserDefined();
5138 Result.UserDefined.Before.setAsIdentityConversion();
5139 // Initializer lists don't have a type.
5140 Result.UserDefined.Before.setFromType(QualType());
5141 Result.UserDefined.Before.setAllToTypes(QualType());
5142
5143 Result.UserDefined.After.setAsIdentityConversion();
5144 Result.UserDefined.After.setFromType(ToType);
5145 Result.UserDefined.After.setAllToTypes(ToType);
5146 Result.UserDefined.ConversionFunction = nullptr;
5147 }
5148 return Result;
5149 }
5150
5151 // C++14 [over.ics.list]p6:
5152 // C++11 [over.ics.list]p5:
5153 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5154 if (ToType->isReferenceType()) {
5155 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5156 // mention initializer lists in any way. So we go by what list-
5157 // initialization would do and try to extrapolate from that.
5158
5159 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5160
5161 // If the initializer list has a single element that is reference-related
5162 // to the parameter type, we initialize the reference from that.
5163 if (From->getNumInits() == 1) {
5164 Expr *Init = From->getInit(0);
5165
5166 QualType T2 = Init->getType();
5167
5168 // If the initializer is the address of an overloaded function, try
5169 // to resolve the overloaded function. If all goes well, T2 is the
5170 // type of the resulting function.
5171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5172 DeclAccessPair Found;
5173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5174 Init, ToType, false, Found))
5175 T2 = Fn->getType();
5176 }
5177
5178 // Compute some basic properties of the types and the initializer.
5179 Sema::ReferenceCompareResult RefRelationship =
5180 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5181
5182 if (RefRelationship >= Sema::Ref_Related) {
5183 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5184 SuppressUserConversions,
5185 /*AllowExplicit=*/false);
5186 }
5187 }
5188
5189 // Otherwise, we bind the reference to a temporary created from the
5190 // initializer list.
5191 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5192 InOverloadResolution,
5193 AllowObjCWritebackConversion);
5194 if (Result.isFailure())
5195 return Result;
5196 assert(!Result.isEllipsis() &&(static_cast<void> (0))
5197 "Sub-initialization cannot result in ellipsis conversion.")(static_cast<void> (0));
5198
5199 // Can we even bind to a temporary?
5200 if (ToType->isRValueReferenceType() ||
5201 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5202 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5203 Result.UserDefined.After;
5204 SCS.ReferenceBinding = true;
5205 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5206 SCS.BindsToRvalue = true;
5207 SCS.BindsToFunctionLvalue = false;
5208 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5209 SCS.ObjCLifetimeConversionBinding = false;
5210 } else
5211 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5212 From, ToType);
5213 return Result;
5214 }
5215
5216 // C++14 [over.ics.list]p7:
5217 // C++11 [over.ics.list]p6:
5218 // Otherwise, if the parameter type is not a class:
5219 if (!ToType->isRecordType()) {
5220 // - if the initializer list has one element that is not itself an
5221 // initializer list, the implicit conversion sequence is the one
5222 // required to convert the element to the parameter type.
5223 unsigned NumInits = From->getNumInits();
5224 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5225 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5226 SuppressUserConversions,
5227 InOverloadResolution,
5228 AllowObjCWritebackConversion);
5229 // - if the initializer list has no elements, the implicit conversion
5230 // sequence is the identity conversion.
5231 else if (NumInits == 0) {
5232 Result.setStandard();
5233 Result.Standard.setAsIdentityConversion();
5234 Result.Standard.setFromType(ToType);
5235 Result.Standard.setAllToTypes(ToType);
5236 }
5237 return Result;
5238 }
5239
5240 // C++14 [over.ics.list]p8:
5241 // C++11 [over.ics.list]p7:
5242 // In all cases other than those enumerated above, no conversion is possible
5243 return Result;
5244}
5245
5246/// TryCopyInitialization - Try to copy-initialize a value of type
5247/// ToType from the expression From. Return the implicit conversion
5248/// sequence required to pass this argument, which may be a bad
5249/// conversion sequence (meaning that the argument cannot be passed to
5250/// a parameter of this type). If @p SuppressUserConversions, then we
5251/// do not permit any user-defined conversion sequences.
5252static ImplicitConversionSequence
5253TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5254 bool SuppressUserConversions,
5255 bool InOverloadResolution,
5256 bool AllowObjCWritebackConversion,
5257 bool AllowExplicit) {
5258 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5259 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5260 InOverloadResolution,AllowObjCWritebackConversion);
5261
5262 if (ToType->isReferenceType())
5263 return TryReferenceInit(S, From, ToType,
5264 /*FIXME:*/ From->getBeginLoc(),
5265 SuppressUserConversions, AllowExplicit);
5266
5267 return TryImplicitConversion(S, From, ToType,
5268 SuppressUserConversions,
5269 AllowedExplicit::None,
5270 InOverloadResolution,
5271 /*CStyle=*/false,
5272 AllowObjCWritebackConversion,
5273 /*AllowObjCConversionOnExplicit=*/false);
5274}
5275
5276static bool TryCopyInitialization(const CanQualType FromQTy,
5277 const CanQualType ToQTy,
5278 Sema &S,
5279 SourceLocation Loc,
5280 ExprValueKind FromVK) {
5281 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5282 ImplicitConversionSequence ICS =
5283 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5284
5285 return !ICS.isBad();
5286}
5287
5288/// TryObjectArgumentInitialization - Try to initialize the object
5289/// parameter of the given member function (@c Method) from the
5290/// expression @p From.
5291static ImplicitConversionSequence
5292TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5293 Expr::Classification FromClassification,
5294 CXXMethodDecl *Method,
5295 CXXRecordDecl *ActingContext) {
5296 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5297 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5298 // const volatile object.
5299 Qualifiers Quals = Method->getMethodQualifiers();
5300 if (isa<CXXDestructorDecl>(Method)) {
5301 Quals.addConst();
5302 Quals.addVolatile();
5303 }
5304
5305 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5306
5307 // Set up the conversion sequence as a "bad" conversion, to allow us
5308 // to exit early.
5309 ImplicitConversionSequence ICS;
5310
5311 // We need to have an object of class type.
5312 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5313 FromType = PT->getPointeeType();
5314
5315 // When we had a pointer, it's implicitly dereferenced, so we
5316 // better have an lvalue.
5317 assert(FromClassification.isLValue())(static_cast<void> (0));
5318 }
5319
5320 assert(FromType->isRecordType())(static_cast<void> (0));
5321
5322 // C++0x [over.match.funcs]p4:
5323 // For non-static member functions, the type of the implicit object
5324 // parameter is
5325 //
5326 // - "lvalue reference to cv X" for functions declared without a
5327 // ref-qualifier or with the & ref-qualifier
5328 // - "rvalue reference to cv X" for functions declared with the &&
5329 // ref-qualifier
5330 //
5331 // where X is the class of which the function is a member and cv is the
5332 // cv-qualification on the member function declaration.
5333 //
5334 // However, when finding an implicit conversion sequence for the argument, we
5335 // are not allowed to perform user-defined conversions
5336 // (C++ [over.match.funcs]p5). We perform a simplified version of
5337 // reference binding here, that allows class rvalues to bind to
5338 // non-constant references.
5339
5340 // First check the qualifiers.
5341 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5342 if (ImplicitParamType.getCVRQualifiers()
5343 != FromTypeCanon.getLocalCVRQualifiers() &&
5344 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5345 ICS.setBad(BadConversionSequence::bad_qualifiers,
5346 FromType, ImplicitParamType);
5347 return ICS;
5348 }
5349
5350 if (FromTypeCanon.hasAddressSpace()) {
5351 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5352 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5353 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5354 ICS.setBad(BadConversionSequence::bad_qualifiers,
5355 FromType, ImplicitParamType);
5356 return ICS;
5357 }
5358 }
5359
5360 // Check that we have either the same type or a derived type. It
5361 // affects the conversion rank.
5362 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5363 ImplicitConversionKind SecondKind;
5364 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5365 SecondKind = ICK_Identity;
5366 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5367 SecondKind = ICK_Derived_To_Base;
5368 else {
5369 ICS.setBad(BadConversionSequence::unrelated_class,
5370 FromType, ImplicitParamType);
5371 return ICS;
5372 }
5373
5374 // Check the ref-qualifier.
5375 switch (Method->getRefQualifier()) {
5376 case RQ_None:
5377 // Do nothing; we don't care about lvalueness or rvalueness.
5378 break;
5379
5380 case RQ_LValue:
5381 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5382 // non-const lvalue reference cannot bind to an rvalue
5383 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5384 ImplicitParamType);
5385 return ICS;
5386 }
5387 break;
5388
5389 case RQ_RValue:
5390 if (!FromClassification.isRValue()) {
5391 // rvalue reference cannot bind to an lvalue
5392 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5393 ImplicitParamType);
5394 return ICS;
5395 }
5396 break;
5397 }
5398
5399 // Success. Mark this as a reference binding.
5400 ICS.setStandard();
5401 ICS.Standard.setAsIdentityConversion();
5402 ICS.Standard.Second = SecondKind;
5403 ICS.Standard.setFromType(FromType);
5404 ICS.Standard.setAllToTypes(ImplicitParamType);
5405 ICS.Standard.ReferenceBinding = true;
5406 ICS.Standard.DirectBinding = true;
5407 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5408 ICS.Standard.BindsToFunctionLvalue = false;
5409 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5410 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5411 = (Method->getRefQualifier() == RQ_None);
5412 return ICS;
5413}
5414
5415/// PerformObjectArgumentInitialization - Perform initialization of
5416/// the implicit object parameter for the given Method with the given
5417/// expression.
5418ExprResult
5419Sema::PerformObjectArgumentInitialization(Expr *From,
5420 NestedNameSpecifier *Qualifier,
5421 NamedDecl *FoundDecl,
5422 CXXMethodDecl *Method) {
5423 QualType FromRecordType, DestType;
5424 QualType ImplicitParamRecordType =
5425 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5426
5427 Expr::Classification FromClassification;
5428 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5429 FromRecordType = PT->getPointeeType();
5430 DestType = Method->getThisType();
5431 FromClassification = Expr::Classification::makeSimpleLValue();
5432 } else {
5433 FromRecordType = From->getType();
5434 DestType = ImplicitParamRecordType;
5435 FromClassification = From->Classify(Context);
5436
5437 // When performing member access on a prvalue, materialize a temporary.
5438 if (From->isPRValue()) {
5439 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5440 Method->getRefQualifier() !=
5441 RefQualifierKind::RQ_RValue);
5442 }
5443 }
5444
5445 // Note that we always use the true parent context when performing
5446 // the actual argument initialization.
5447 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5448 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5449 Method->getParent());
5450 if (ICS.isBad()) {
5451 switch (ICS.Bad.Kind) {
5452 case BadConversionSequence::bad_qualifiers: {
5453 Qualifiers FromQs = FromRecordType.getQualifiers();
5454 Qualifiers ToQs = DestType.getQualifiers();
5455 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5456 if (CVR) {
5457 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5458 << Method->getDeclName() << FromRecordType << (CVR - 1)
5459 << From->getSourceRange();
5460 Diag(Method->getLocation(), diag::note_previous_decl)
5461 << Method->getDeclName();
5462 return ExprError();
5463 }
5464 break;
5465 }
5466
5467 case BadConversionSequence::lvalue_ref_to_rvalue:
5468 case BadConversionSequence::rvalue_ref_to_lvalue: {
5469 bool IsRValueQualified =
5470 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5471 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5472 << Method->getDeclName() << FromClassification.isRValue()
5473 << IsRValueQualified;
5474 Diag(Method->getLocation(), diag::note_previous_decl)
5475 << Method->getDeclName();
5476 return ExprError();
5477 }
5478
5479 case BadConversionSequence::no_conversion:
5480 case BadConversionSequence::unrelated_class:
5481 break;
5482 }
5483
5484 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5485 << ImplicitParamRecordType << FromRecordType
5486 << From->getSourceRange();
5487 }
5488
5489 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5490 ExprResult FromRes =
5491 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5492 if (FromRes.isInvalid())
5493 return ExprError();
5494 From = FromRes.get();
5495 }
5496
5497 if (!Context.hasSameType(From->getType(), DestType)) {
5498 CastKind CK;
5499 QualType PteeTy = DestType->getPointeeType();
5500 LangAS DestAS =
5501 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5502 if (FromRecordType.getAddressSpace() != DestAS)
5503 CK = CK_AddressSpaceConversion;
5504 else
5505 CK = CK_NoOp;
5506 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5507 }
5508 return From;
5509}
5510
5511/// TryContextuallyConvertToBool - Attempt to contextually convert the
5512/// expression From to bool (C++0x [conv]p3).
5513static ImplicitConversionSequence
5514TryContextuallyConvertToBool(Sema &S, Expr *From) {
5515 // C++ [dcl.init]/17.8:
5516 // - Otherwise, if the initialization is direct-initialization, the source
5517 // type is std::nullptr_t, and the destination type is bool, the initial
5518 // value of the object being initialized is false.
5519 if (From->getType()->isNullPtrType())
5520 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5521 S.Context.BoolTy,
5522 From->isGLValue());
5523
5524 // All other direct-initialization of bool is equivalent to an implicit
5525 // conversion to bool in which explicit conversions are permitted.
5526 return TryImplicitConversion(S, From, S.Context.BoolTy,
5527 /*SuppressUserConversions=*/false,
5528 AllowedExplicit::Conversions,
5529 /*InOverloadResolution=*/false,
5530 /*CStyle=*/false,
5531 /*AllowObjCWritebackConversion=*/false,
5532 /*AllowObjCConversionOnExplicit=*/false);
5533}
5534
5535/// PerformContextuallyConvertToBool - Perform a contextual conversion
5536/// of the expression From to bool (C++0x [conv]p3).
5537ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5538 if (checkPlaceholderForOverload(*this, From))
5539 return ExprError();
5540
5541 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5542 if (!ICS.isBad())
5543 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5544
5545 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5546 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5547 << From->getType() << From->getSourceRange();
5548 return ExprError();
5549}
5550
5551/// Check that the specified conversion is permitted in a converted constant
5552/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5553/// is acceptable.
5554static bool CheckConvertedConstantConversions(Sema &S,
5555 StandardConversionSequence &SCS) {
5556 // Since we know that the target type is an integral or unscoped enumeration
5557 // type, most conversion kinds are impossible. All possible First and Third
5558 // conversions are fine.
5559 switch (SCS.Second) {
5560 case ICK_Identity:
5561 case ICK_Integral_Promotion:
5562 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5563 case ICK_Zero_Queue_Conversion:
5564 return true;
5565
5566 case ICK_Boolean_Conversion:
5567 // Conversion from an integral or unscoped enumeration type to bool is
5568 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5569 // conversion, so we allow it in a converted constant expression.
5570 //
5571 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5572 // a lot of popular code. We should at least add a warning for this
5573 // (non-conforming) extension.
5574 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5575 SCS.getToType(2)->isBooleanType();
5576
5577 case ICK_Pointer_Conversion:
5578 case ICK_Pointer_Member:
5579 // C++1z: null pointer conversions and null member pointer conversions are
5580 // only permitted if the source type is std::nullptr_t.
5581 return SCS.getFromType()->isNullPtrType();
5582
5583 case ICK_Floating_Promotion:
5584 case ICK_Complex_Promotion:
5585 case ICK_Floating_Conversion:
5586 case ICK_Complex_Conversion:
5587 case ICK_Floating_Integral:
5588 case ICK_Compatible_Conversion:
5589 case ICK_Derived_To_Base:
5590 case ICK_Vector_Conversion:
5591 case ICK_SVE_Vector_Conversion:
5592 case ICK_Vector_Splat:
5593 case ICK_Complex_Real:
5594 case ICK_Block_Pointer_Conversion:
5595 case ICK_TransparentUnionConversion:
5596 case ICK_Writeback_Conversion:
5597 case ICK_Zero_Event_Conversion:
5598 case ICK_C_Only_Conversion:
5599 case ICK_Incompatible_Pointer_Conversion:
5600 return false;
5601
5602 case ICK_Lvalue_To_Rvalue:
5603 case ICK_Array_To_Pointer:
5604 case ICK_Function_To_Pointer:
5605 llvm_unreachable("found a first conversion kind in Second")__builtin_unreachable();
5606
5607 case ICK_Function_Conversion:
5608 case ICK_Qualification:
5609 llvm_unreachable("found a third conversion kind in Second")__builtin_unreachable();
5610
5611 case ICK_Num_Conversion_Kinds:
5612 break;
5613 }
5614
5615 llvm_unreachable("unknown conversion kind")__builtin_unreachable();
5616}
5617
5618/// CheckConvertedConstantExpression - Check that the expression From is a
5619/// converted constant expression of type T, perform the conversion and produce
5620/// the converted expression, per C++11 [expr.const]p3.
5621static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5622 QualType T, APValue &Value,
5623 Sema::CCEKind CCE,
5624 bool RequireInt,
5625 NamedDecl *Dest) {
5626 assert(S.getLangOpts().CPlusPlus11 &&(static_cast<void> (0))
5627 "converted constant expression outside C++11")(static_cast<void> (0));
5628
5629 if (checkPlaceholderForOverload(S, From))
5630 return ExprError();
5631
5632 // C++1z [expr.const]p3:
5633 // A converted constant expression of type T is an expression,
5634 // implicitly converted to type T, where the converted
5635 // expression is a constant expression and the implicit conversion
5636 // sequence contains only [... list of conversions ...].
5637 ImplicitConversionSequence ICS =
5638 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5639 ? TryContextuallyConvertToBool(S, From)
5640 : TryCopyInitialization(S, From, T,
5641 /*SuppressUserConversions=*/false,
5642 /*InOverloadResolution=*/false,
5643 /*AllowObjCWritebackConversion=*/false,
5644 /*AllowExplicit=*/false);
5645 StandardConversionSequence *SCS = nullptr;
5646 switch (ICS.getKind()) {
5647 case ImplicitConversionSequence::StandardConversion:
5648 SCS = &ICS.Standard;
5649 break;
5650 case ImplicitConversionSequence::UserDefinedConversion:
5651 if (T->isRecordType())
5652 SCS = &ICS.UserDefined.Before;
5653 else
5654 SCS = &ICS.UserDefined.After;
5655 break;
5656 case ImplicitConversionSequence::AmbiguousConversion:
5657 case ImplicitConversionSequence::BadConversion:
5658 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5659 return S.Diag(From->getBeginLoc(),
5660 diag::err_typecheck_converted_constant_expression)
5661 << From->getType() << From->getSourceRange() << T;
5662 return ExprError();
5663
5664 case ImplicitConversionSequence::EllipsisConversion:
5665 llvm_unreachable("ellipsis conversion in converted constant expression")__builtin_unreachable();
5666 }
5667
5668 // Check that we would only use permitted conversions.
5669 if (!CheckConvertedConstantConversions(S, *SCS)) {
5670 return S.Diag(From->getBeginLoc(),
5671 diag::err_typecheck_converted_constant_expression_disallowed)
5672 << From->getType() << From->getSourceRange() << T;
5673 }
5674 // [...] and where the reference binding (if any) binds directly.
5675 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5676 return S.Diag(From->getBeginLoc(),
5677 diag::err_typecheck_converted_constant_expression_indirect)
5678 << From->getType() << From->getSourceRange() << T;
5679 }
5680
5681 // Usually we can simply apply the ImplicitConversionSequence we formed
5682 // earlier, but that's not guaranteed to work when initializing an object of
5683 // class type.
5684 ExprResult Result;
5685 if (T->isRecordType()) {
5686 assert(CCE == Sema::CCEK_TemplateArg &&(static_cast<void> (0))
5687 "unexpected class type converted constant expr")(static_cast<void> (0));
5688 Result = S.PerformCopyInitialization(
5689 InitializedEntity::InitializeTemplateParameter(
5690 T, cast<NonTypeTemplateParmDecl>(Dest)),
5691 SourceLocation(), From);
5692 } else {
5693 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5694 }
5695 if (Result.isInvalid())
5696 return Result;
5697
5698 // C++2a [intro.execution]p5:
5699 // A full-expression is [...] a constant-expression [...]
5700 Result =
5701 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5702 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5703 if (Result.isInvalid())
5704 return Result;
5705
5706 // Check for a narrowing implicit conversion.
5707 bool ReturnPreNarrowingValue = false;
5708 APValue PreNarrowingValue;
5709 QualType PreNarrowingType;
5710 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5711 PreNarrowingType)) {
5712 case NK_Dependent_Narrowing:
5713 // Implicit conversion to a narrower type, but the expression is
5714 // value-dependent so we can't tell whether it's actually narrowing.
5715 case NK_Variable_Narrowing:
5716 // Implicit conversion to a narrower type, and the value is not a constant
5717 // expression. We'll diagnose this in a moment.
5718 case NK_Not_Narrowing:
5719 break;
5720
5721 case NK_Constant_Narrowing:
5722 if (CCE == Sema::CCEK_ArrayBound &&
5723 PreNarrowingType->isIntegralOrEnumerationType() &&
5724 PreNarrowingValue.isInt()) {
5725 // Don't diagnose array bound narrowing here; we produce more precise
5726 // errors by allowing the un-narrowed value through.
5727 ReturnPreNarrowingValue = true;
5728 break;
5729 }
5730 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5731 << CCE << /*Constant*/ 1
5732 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5733 break;
5734
5735 case NK_Type_Narrowing:
5736 // FIXME: It would be better to diagnose that the expression is not a
5737 // constant expression.
5738 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5739 << CCE << /*Constant*/ 0 << From->getType() << T;
5740 break;
5741 }
5742
5743 if (Result.get()->isValueDependent()) {
5744 Value = APValue();
5745 return Result;
5746 }
5747
5748 // Check the expression is a constant expression.
5749 SmallVector<PartialDiagnosticAt, 8> Notes;
5750 Expr::EvalResult Eval;
5751 Eval.Diag = &Notes;
5752
5753 ConstantExprKind Kind;
5754 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5755 Kind = ConstantExprKind::ClassTemplateArgument;
5756 else if (CCE == Sema::CCEK_TemplateArg)
5757 Kind = ConstantExprKind::NonClassTemplateArgument;
5758 else
5759 Kind = ConstantExprKind::Normal;
5760
5761 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5762 (RequireInt && !Eval.Val.isInt())) {
5763 // The expression can't be folded, so we can't keep it at this position in
5764 // the AST.
5765 Result = ExprError();
5766 } else {
5767 Value = Eval.Val;
5768
5769 if (Notes.empty()) {
5770 // It's a constant expression.
5771 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5772 if (ReturnPreNarrowingValue)
5773 Value = std::move(PreNarrowingValue);
5774 return E;
5775 }
5776 }
5777
5778 // It's not a constant expression. Produce an appropriate diagnostic.
5779 if (Notes.size() == 1 &&
5780 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5781 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5782 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5783 diag::note_constexpr_invalid_template_arg) {
5784 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5785 for (unsigned I = 0; I < Notes.size(); ++I)
5786 S.Diag(Notes[I].first, Notes[I].second);
5787 } else {
5788 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5789 << CCE << From->getSourceRange();
5790 for (unsigned I = 0; I < Notes.size(); ++I)
5791 S.Diag(Notes[I].first, Notes[I].second);
5792 }
5793 return ExprError();
5794}
5795
5796ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5797 APValue &Value, CCEKind CCE,
5798 NamedDecl *Dest) {
5799 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5800 Dest);
5801}
5802
5803ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5804 llvm::APSInt &Value,
5805 CCEKind CCE) {
5806 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast<void> (0));
5807
5808 APValue V;
5809 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5810 /*Dest=*/nullptr);
5811 if (!R.isInvalid() && !R.get()->isValueDependent())
5812 Value = V.getInt();
5813 return R;
5814}
5815
5816
5817/// dropPointerConversions - If the given standard conversion sequence
5818/// involves any pointer conversions, remove them. This may change
5819/// the result type of the conversion sequence.
5820static void dropPointerConversion(StandardConversionSequence &SCS) {
5821 if (SCS.Second == ICK_Pointer_Conversion) {
5822 SCS.Second = ICK_Identity;
5823 SCS.Third = ICK_Identity;
5824 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5825 }
5826}
5827
5828/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5829/// convert the expression From to an Objective-C pointer type.
5830static ImplicitConversionSequence
5831TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5832 // Do an implicit conversion to 'id'.
5833 QualType Ty = S.Context.getObjCIdType();
5834 ImplicitConversionSequence ICS
5835 = TryImplicitConversion(S, From, Ty,
5836 // FIXME: Are these flags correct?
5837 /*SuppressUserConversions=*/false,
5838 AllowedExplicit::Conversions,
5839 /*InOverloadResolution=*/false,
5840 /*CStyle=*/false,
5841 /*AllowObjCWritebackConversion=*/false,
5842 /*AllowObjCConversionOnExplicit=*/true);
5843
5844 // Strip off any final conversions to 'id'.
5845 switch (ICS.getKind()) {
5846 case ImplicitConversionSequence::BadConversion:
5847 case ImplicitConversionSequence::AmbiguousConversion:
5848 case ImplicitConversionSequence::EllipsisConversion:
5849 break;
5850
5851 case ImplicitConversionSequence::UserDefinedConversion:
5852 dropPointerConversion(ICS.UserDefined.After);
5853 break;
5854
5855 case ImplicitConversionSequence::StandardConversion:
5856 dropPointerConversion(ICS.Standard);
5857 break;
5858 }
5859
5860 return ICS;
5861}
5862
5863/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5864/// conversion of the expression From to an Objective-C pointer type.
5865/// Returns a valid but null ExprResult if no conversion sequence exists.
5866ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5867 if (checkPlaceholderForOverload(*this, From))
5868 return ExprError();
5869
5870 QualType Ty = Context.getObjCIdType();
5871 ImplicitConversionSequence ICS =
5872 TryContextuallyConvertToObjCPointer(*this, From);
5873 if (!ICS.isBad())
5874 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5875 return ExprResult();
5876}
5877
5878/// Determine whether the provided type is an integral type, or an enumeration
5879/// type of a permitted flavor.
5880bool Sema::ICEConvertDiagnoser::match(QualType T) {
5881 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5882 : T->isIntegralOrUnscopedEnumerationType();
5883}
5884
5885static ExprResult
5886diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5887 Sema::ContextualImplicitConverter &Converter,
5888 QualType T, UnresolvedSetImpl &ViableConversions) {
5889
5890 if (Converter.Suppress)
5891 return ExprError();
5892
5893 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5894 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5895 CXXConversionDecl *Conv =
5896 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5897 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5898 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5899 }
5900 return From;
5901}
5902
5903static bool
5904diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5905 Sema::ContextualImplicitConverter &Converter,
5906 QualType T, bool HadMultipleCandidates,
5907 UnresolvedSetImpl &ExplicitConversions) {
5908 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5909 DeclAccessPair Found = ExplicitConversions[0];
5910 CXXConversionDecl *Conversion =
5911 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5912
5913 // The user probably meant to invoke the given explicit
5914 // conversion; use it.
5915 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5916 std::string TypeStr;
5917 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5918
5919 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5920 << FixItHint::CreateInsertion(From->getBeginLoc(),
5921 "static_cast<" + TypeStr + ">(")
5922 << FixItHint::CreateInsertion(
5923 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5924 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5925
5926 // If we aren't in a SFINAE context, build a call to the
5927 // explicit conversion function.
5928 if (SemaRef.isSFINAEContext())
5929 return true;
5930
5931 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5932 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5933 HadMultipleCandidates);
5934 if (Result.isInvalid())
5935 return true;
5936 // Record usage of conversion in an implicit cast.
5937 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5938 CK_UserDefinedConversion, Result.get(),
5939 nullptr, Result.get()->getValueKind(),
5940 SemaRef.CurFPFeatureOverrides());
5941 }
5942 return false;
5943}
5944
5945static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5946 Sema::ContextualImplicitConverter &Converter,
5947 QualType T, bool HadMultipleCandidates,
5948 DeclAccessPair &Found) {
5949 CXXConversionDecl *Conversion =
5950 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5951 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5952
5953 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5954 if (!Converter.SuppressConversion) {
5955 if (SemaRef.isSFINAEContext())
5956 return true;
5957
5958 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5959 << From->getSourceRange();
5960 }
5961
5962 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5963 HadMultipleCandidates);
5964 if (Result.isInvalid())
5965 return true;
5966 // Record usage of conversion in an implicit cast.
5967 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5968 CK_UserDefinedConversion, Result.get(),
5969 nullptr, Result.get()->getValueKind(),
5970 SemaRef.CurFPFeatureOverrides());
5971 return false;
5972}
5973
5974static ExprResult finishContextualImplicitConversion(
5975 Sema &SemaRef, SourceLocation Loc, Expr *From,
5976 Sema::ContextualImplicitConverter &Converter) {
5977 if (!Converter.match(From->getType()) && !Converter.Suppress)
5978 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5979 << From->getSourceRange();
5980
5981 return SemaRef.DefaultLvalueConversion(From);
5982}
5983
5984static void
5985collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5986 UnresolvedSetImpl &ViableConversions,
5987 OverloadCandidateSet &CandidateSet) {
5988 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5989 DeclAccessPair FoundDecl = ViableConversions[I];
5990 NamedDecl *D = FoundDecl.getDecl();
5991 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5992 if (isa<UsingShadowDecl>(D))
5993 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5994
5995 CXXConversionDecl *Conv;
5996 FunctionTemplateDecl *ConvTemplate;
5997 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5998 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5999 else
6000 Conv = cast<CXXConversionDecl>(D);
6001
6002 if (ConvTemplate)
6003 SemaRef.AddTemplateConversionCandidate(
6004 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6005 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6006 else
6007 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6008 ToType, CandidateSet,
6009 /*AllowObjCConversionOnExplicit=*/false,
6010 /*AllowExplicit*/ true);
6011 }
6012}
6013
6014/// Attempt to convert the given expression to a type which is accepted
6015/// by the given converter.
6016///
6017/// This routine will attempt to convert an expression of class type to a
6018/// type accepted by the specified converter. In C++11 and before, the class
6019/// must have a single non-explicit conversion function converting to a matching
6020/// type. In C++1y, there can be multiple such conversion functions, but only
6021/// one target type.
6022///
6023/// \param Loc The source location of the construct that requires the
6024/// conversion.
6025///
6026/// \param From The expression we're converting from.
6027///
6028/// \param Converter Used to control and diagnose the conversion process.
6029///
6030/// \returns The expression, converted to an integral or enumeration type if
6031/// successful.
6032ExprResult Sema::PerformContextualImplicitConversion(
6033 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6034 // We can't perform any more checking for type-dependent expressions.
6035 if (From->isTypeDependent())
6036 return From;
6037
6038 // Process placeholders immediately.
6039 if (From->hasPlaceholderType()) {
6040 ExprResult result = CheckPlaceholderExpr(From);
6041 if (result.isInvalid())
6042 return result;
6043 From = result.get();
6044 }
6045
6046 // If the expression already has a matching type, we're golden.
6047 QualType T = From->getType();
6048 if (Converter.match(T))
6049 return DefaultLvalueConversion(From);
6050
6051 // FIXME: Check for missing '()' if T is a function type?
6052
6053 // We can only perform contextual implicit conversions on objects of class
6054 // type.
6055 const RecordType *RecordTy = T->getAs<RecordType>();
6056 if (!RecordTy || !getLangOpts().CPlusPlus) {
6057 if (!Converter.Suppress)
6058 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6059 return From;
6060 }
6061
6062 // We must have a complete class type.
6063 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6064 ContextualImplicitConverter &Converter;
6065 Expr *From;
6066
6067 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6068 : Converter(Converter), From(From) {}
6069
6070 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6071 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6072 }
6073 } IncompleteDiagnoser(Converter, From);
6074
6075 if (Converter.Suppress ? !isCompleteType(Loc, T)
6076 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6077 return From;
6078
6079 // Look for a conversion to an integral or enumeration type.
6080 UnresolvedSet<4>
6081 ViableConversions; // These are *potentially* viable in C++1y.
6082 UnresolvedSet<4> ExplicitConversions;
6083 const auto &Conversions =
6084 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6085
6086 bool HadMultipleCandidates =
6087 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6088
6089 // To check that there is only one target type, in C++1y:
6090 QualType ToType;
6091 bool HasUniqueTargetType = true;
6092
6093 // Collect explicit or viable (potentially in C++1y) conversions.
6094 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6095 NamedDecl *D = (*I)->getUnderlyingDecl();
6096 CXXConversionDecl *Conversion;
6097 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6098 if (ConvTemplate) {
6099 if (getLangOpts().CPlusPlus14)
6100 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6101 else
6102 continue; // C++11 does not consider conversion operator templates(?).
6103 } else
6104 Conversion = cast<CXXConversionDecl>(D);
6105
6106 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast<void> (0))
6107 "Conversion operator templates are considered potentially "(static_cast<void> (0))
6108 "viable in C++1y")(static_cast<void> (0));
6109
6110 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6111 if (Converter.match(CurToType) || ConvTemplate) {
6112
6113 if (Conversion->isExplicit()) {
6114 // FIXME: For C++1y, do we need this restriction?
6115 // cf. diagnoseNoViableConversion()
6116 if (!ConvTemplate)
6117 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6118 } else {
6119 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6120 if (ToType.isNull())
6121 ToType = CurToType.getUnqualifiedType();
6122 else if (HasUniqueTargetType &&
6123 (CurToType.getUnqualifiedType() != ToType))
6124 HasUniqueTargetType = false;
6125 }
6126 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6127 }
6128 }
6129 }
6130
6131 if (getLangOpts().CPlusPlus14) {
6132 // C++1y [conv]p6:
6133 // ... An expression e of class type E appearing in such a context
6134 // is said to be contextually implicitly converted to a specified
6135 // type T and is well-formed if and only if e can be implicitly
6136 // converted to a type T that is determined as follows: E is searched
6137 // for conversion functions whose return type is cv T or reference to
6138 // cv T such that T is allowed by the context. There shall be
6139 // exactly one such T.
6140
6141 // If no unique T is found:
6142 if (ToType.isNull()) {
6143 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6144 HadMultipleCandidates,
6145 ExplicitConversions))
6146 return ExprError();
6147 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6148 }
6149
6150 // If more than one unique Ts are found:
6151 if (!HasUniqueTargetType)
6152 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6153 ViableConversions);
6154
6155 // If one unique T is found:
6156 // First, build a candidate set from the previously recorded
6157 // potentially viable conversions.
6158 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6159 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6160 CandidateSet);
6161
6162 // Then, perform overload resolution over the candidate set.
6163 OverloadCandidateSet::iterator Best;
6164 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6165 case OR_Success: {
6166 // Apply this conversion.
6167 DeclAccessPair Found =
6168 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6169 if (recordConversion(*this, Loc, From, Converter, T,
6170 HadMultipleCandidates, Found))
6171 return ExprError();
6172 break;
6173 }
6174 case OR_Ambiguous:
6175 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6176 ViableConversions);
6177 case OR_No_Viable_Function:
6178 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6179 HadMultipleCandidates,
6180 ExplicitConversions))
6181 return ExprError();
6182 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6183 case OR_Deleted:
6184 // We'll complain below about a non-integral condition type.
6185 break;
6186 }
6187 } else {
6188 switch (ViableConversions.size()) {
6189 case 0: {
6190 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6191 HadMultipleCandidates,
6192 ExplicitConversions))
6193 return ExprError();
6194
6195 // We'll complain below about a non-integral condition type.
6196 break;
6197 }
6198 case 1: {
6199 // Apply this conversion.
6200 DeclAccessPair Found = ViableConversions[0];
6201 if (recordConversion(*this, Loc, From, Converter, T,
6202 HadMultipleCandidates, Found))
6203 return ExprError();
6204 break;
6205 }
6206 default:
6207 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6208 ViableConversions);
6209 }
6210 }
6211
6212 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6213}
6214
6215/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6216/// an acceptable non-member overloaded operator for a call whose
6217/// arguments have types T1 (and, if non-empty, T2). This routine
6218/// implements the check in C++ [over.match.oper]p3b2 concerning
6219/// enumeration types.
6220static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6221 FunctionDecl *Fn,
6222 ArrayRef<Expr *> Args) {
6223 QualType T1 = Args[0]->getType();
6224 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6225
6226 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6227 return true;
6228
6229 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6230 return true;
6231
6232 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6233 if (Proto->getNumParams() < 1)
6234 return false;
6235
6236 if (T1->isEnumeralType()) {
6237 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6238 if (Context.hasSameUnqualifiedType(T1, ArgType))
6239 return true;
6240 }
6241
6242 if (Proto->getNumParams() < 2)
6243 return false;
6244
6245 if (!T2.isNull() && T2->isEnumeralType()) {
6246 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6247 if (Context.hasSameUnqualifiedType(T2, ArgType))
6248 return true;
6249 }
6250
6251 return false;
6252}
6253
6254/// AddOverloadCandidate - Adds the given function to the set of
6255/// candidate functions, using the given function call arguments. If
6256/// @p SuppressUserConversions, then don't allow user-defined
6257/// conversions via constructors or conversion operators.
6258///
6259/// \param PartialOverloading true if we are performing "partial" overloading
6260/// based on an incomplete set of function arguments. This feature is used by
6261/// code completion.
6262void Sema::AddOverloadCandidate(
6263 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6264 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6265 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6266 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6267 OverloadCandidateParamOrder PO) {
6268 const FunctionProtoType *Proto
6269 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6270 assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast<void> (0));
6271 assert(!Function->getDescribedFunctionTemplate() &&(static_cast<void> (0))
6272 "Use AddTemplateOverloadCandidate for function templates")(static_cast<void> (0));
6273
6274 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6275 if (!isa<CXXConstructorDecl>(Method)) {
6276 // If we get here, it's because we're calling a member function
6277 // that is named without a member access expression (e.g.,
6278 // "this->f") that was either written explicitly or created
6279 // implicitly. This can happen with a qualified call to a member
6280 // function, e.g., X::f(). We use an empty type for the implied
6281 // object argument (C++ [over.call.func]p3), and the acting context
6282 // is irrelevant.
6283 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6284 Expr::Classification::makeSimpleLValue(), Args,
6285 CandidateSet, SuppressUserConversions,
6286 PartialOverloading, EarlyConversions, PO);
6287 return;
6288 }
6289 // We treat a constructor like a non-member function, since its object
6290 // argument doesn't participate in overload resolution.
6291 }
6292
6293 if (!CandidateSet.isNewCandidate(Function, PO))
6294 return;
6295
6296 // C++11 [class.copy]p11: [DR1402]
6297 // A defaulted move constructor that is defined as deleted is ignored by
6298 // overload resolution.
6299 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6300 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6301 Constructor->isMoveConstructor())
6302 return;
6303
6304 // Overload resolution is always an unevaluated context.
6305 EnterExpressionEvaluationContext Unevaluated(
6306 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6307
6308 // C++ [over.match.oper]p3:
6309 // if no operand has a class type, only those non-member functions in the
6310 // lookup set that have a first parameter of type T1 or "reference to
6311 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6312 // is a right operand) a second parameter of type T2 or "reference to
6313 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6314 // candidate functions.
6315 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6316 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6317 return;
6318
6319 // Add this candidate
6320 OverloadCandidate &Candidate =
6321 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6322 Candidate.FoundDecl = FoundDecl;
6323 Candidate.Function = Function;
6324 Candidate.Viable = true;
6325 Candidate.RewriteKind =
6326 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6327 Candidate.IsSurrogate = false;
6328 Candidate.IsADLCandidate = IsADLCandidate;
6329 Candidate.IgnoreObjectArgument = false;
6330 Candidate.ExplicitCallArguments = Args.size();
6331
6332 // Explicit functions are not actually candidates at all if we're not
6333 // allowing them in this context, but keep them around so we can point
6334 // to them in diagnostics.
6335 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6336 Candidate.Viable = false;
6337 Candidate.FailureKind = ovl_fail_explicit;
6338 return;
6339 }
6340
6341 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6342 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6343 Candidate.Viable = false;
6344 Candidate.FailureKind = ovl_non_default_multiversion_function;
6345 return;
6346 }
6347
6348 if (Constructor) {
6349 // C++ [class.copy]p3:
6350 // A member function template is never instantiated to perform the copy
6351 // of a class object to an object of its class type.
6352 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6353 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6354 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6355 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6356 ClassType))) {
6357 Candidate.Viable = false;
6358 Candidate.FailureKind = ovl_fail_illegal_constructor;
6359 return;
6360 }
6361
6362 // C++ [over.match.funcs]p8: (proposed DR resolution)
6363 // A constructor inherited from class type C that has a first parameter
6364 // of type "reference to P" (including such a constructor instantiated
6365 // from a template) is excluded from the set of candidate functions when
6366 // constructing an object of type cv D if the argument list has exactly
6367 // one argument and D is reference-related to P and P is reference-related
6368 // to C.
6369 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6370 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6371 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6372 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6373 QualType C = Context.getRecordType(Constructor->getParent());
6374 QualType D = Context.getRecordType(Shadow->getParent());
6375 SourceLocation Loc = Args.front()->getExprLoc();
6376 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6377 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6378 Candidate.Viable = false;
6379 Candidate.FailureKind = ovl_fail_inhctor_slice;
6380 return;
6381 }
6382 }
6383
6384 // Check that the constructor is capable of constructing an object in the
6385 // destination address space.
6386 if (!Qualifiers::isAddressSpaceSupersetOf(
6387 Constructor->getMethodQualifiers().getAddressSpace(),
6388 CandidateSet.getDestAS())) {
6389 Candidate.Viable = false;
6390 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6391 }
6392 }
6393
6394 unsigned NumParams = Proto->getNumParams();
6395
6396 // (C++ 13.3.2p2): A candidate function having fewer than m
6397 // parameters is viable only if it has an ellipsis in its parameter
6398 // list (8.3.5).
6399 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6400 !Proto->isVariadic()) {
6401 Candidate.Viable = false;
6402 Candidate.FailureKind = ovl_fail_too_many_arguments;
6403 return;
6404 }
6405
6406 // (C++ 13.3.2p2): A candidate function having more than m parameters
6407 // is viable only if the (m+1)st parameter has a default argument
6408 // (8.3.6). For the purposes of overload resolution, the
6409 // parameter list is truncated on the right, so that there are
6410 // exactly m parameters.
6411 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6412 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6413 // Not enough arguments.
6414 Candidate.Viable = false;
6415 Candidate.FailureKind = ovl_fail_too_few_arguments;
6416 return;
6417 }
6418
6419 // (CUDA B.1): Check for invalid calls between targets.
6420 if (getLangOpts().CUDA)
6421 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6422 // Skip the check for callers that are implicit members, because in this
6423 // case we may not yet know what the member's target is; the target is
6424 // inferred for the member automatically, based on the bases and fields of
6425 // the class.
6426 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6427 Candidate.Viable = false;
6428 Candidate.FailureKind = ovl_fail_bad_target;
6429 return;
6430 }
6431
6432 if (Function->getTrailingRequiresClause()) {
6433 ConstraintSatisfaction Satisfaction;
6434 if (CheckFunctionConstraints(Function, Satisfaction) ||
6435 !Satisfaction.IsSatisfied) {
6436 Candidate.Viable = false;
6437 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6438 return;
6439 }
6440 }
6441
6442 // Determine the implicit conversion sequences for each of the
6443 // arguments.
6444 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6445 unsigned ConvIdx =
6446 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6447 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6448 // We already formed a conversion sequence for this parameter during
6449 // template argument deduction.
6450 } else if (ArgIdx < NumParams) {
6451 // (C++ 13.3.2p3): for F to be a viable function, there shall
6452 // exist for each argument an implicit conversion sequence
6453 // (13.3.3.1) that converts that argument to the corresponding
6454 // parameter of F.
6455 QualType ParamType = Proto->getParamType(ArgIdx);
6456 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6457 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6458 /*InOverloadResolution=*/true,
6459 /*AllowObjCWritebackConversion=*/
6460 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6461 if (Candidate.Conversions[ConvIdx].isBad()) {
6462 Candidate.Viable = false;
6463 Candidate.FailureKind = ovl_fail_bad_conversion;
6464 return;
6465 }
6466 } else {
6467 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6468 // argument for which there is no corresponding parameter is
6469 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6470 Candidate.Conversions[ConvIdx].setEllipsis();
6471 }
6472 }
6473
6474 if (EnableIfAttr *FailedAttr =
6475 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6476 Candidate.Viable = false;
6477 Candidate.FailureKind = ovl_fail_enable_if;
6478 Candidate.DeductionFailure.Data = FailedAttr;
6479 return;
6480 }
6481}
6482
6483ObjCMethodDecl *
6484Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6485 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6486 if (Methods.size() <= 1)
6487 return nullptr;
6488
6489 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6490 bool Match = true;
6491 ObjCMethodDecl *Method = Methods[b];
6492 unsigned NumNamedArgs = Sel.getNumArgs();
6493 // Method might have more arguments than selector indicates. This is due
6494 // to addition of c-style arguments in method.
6495 if (Method->param_size() > NumNamedArgs)
6496 NumNamedArgs = Method->param_size();
6497 if (Args.size() < NumNamedArgs)
6498 continue;
6499
6500 for (unsigned i = 0; i < NumNamedArgs; i++) {
6501 // We can't do any type-checking on a type-dependent argument.
6502 if (Args[i]->isTypeDependent()) {
6503 Match = false;
6504 break;
6505 }
6506
6507 ParmVarDecl *param = Method->parameters()[i];
6508 Expr *argExpr = Args[i];
6509 assert(argExpr && "SelectBestMethod(): missing expression")(static_cast<void> (0));
6510
6511 // Strip the unbridged-cast placeholder expression off unless it's
6512 // a consumed argument.
6513 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6514 !param->hasAttr<CFConsumedAttr>())
6515 argExpr = stripARCUnbridgedCast(argExpr);
6516
6517 // If the parameter is __unknown_anytype, move on to the next method.
6518 if (param->getType() == Context.UnknownAnyTy) {
6519 Match = false;
6520 break;
6521 }
6522
6523 ImplicitConversionSequence ConversionState
6524 = TryCopyInitialization(*this, argExpr, param->getType(),
6525 /*SuppressUserConversions*/false,
6526 /*InOverloadResolution=*/true,
6527 /*AllowObjCWritebackConversion=*/
6528 getLangOpts().ObjCAutoRefCount,
6529 /*AllowExplicit*/false);
6530 // This function looks for a reasonably-exact match, so we consider
6531 // incompatible pointer conversions to be a failure here.
6532 if (ConversionState.isBad() ||
6533 (ConversionState.isStandard() &&
6534 ConversionState.Standard.Second ==
6535 ICK_Incompatible_Pointer_Conversion)) {
6536 Match = false;
6537 break;
6538 }
6539 }
6540 // Promote additional arguments to variadic methods.
6541 if (Match && Method->isVariadic()) {
6542 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6543 if (Args[i]->isTypeDependent()) {
6544 Match = false;
6545 break;
6546 }
6547 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6548 nullptr);
6549 if (Arg.isInvalid()) {
6550 Match = false;
6551 break;
6552 }
6553 }
6554 } else {
6555 // Check for extra arguments to non-variadic methods.
6556 if (Args.size() != NumNamedArgs)
6557 Match = false;
6558 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6559 // Special case when selectors have no argument. In this case, select
6560 // one with the most general result type of 'id'.
6561 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6562 QualType ReturnT = Methods[b]->getReturnType();
6563 if (ReturnT->isObjCIdType())
6564 return Methods[b];
6565 }
6566 }
6567 }
6568
6569 if (Match)
6570 return Method;
6571 }
6572 return nullptr;
6573}
6574
6575static bool convertArgsForAvailabilityChecks(
6576 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6577 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6578 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6579 if (ThisArg) {
6580 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6581 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast<void> (0))
6582 "Shouldn't have `this` for ctors!")(static_cast<void> (0));
6583 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast<void> (0));
6584 ExprResult R = S.PerformObjectArgumentInitialization(
6585 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6586 if (R.isInvalid())
6587 return false;
6588 ConvertedThis = R.get();
6589 } else {
6590 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6591 (void)MD;
6592 assert((MissingImplicitThis || MD->isStatic() ||(static_cast<void> (0))
6593 isa<CXXConstructorDecl>(MD)) &&(static_cast<void> (0))
6594 "Expected `this` for non-ctor instance methods")(static_cast<void> (0));
6595 }
6596 ConvertedThis = nullptr;
6597 }
6598
6599 // Ignore any variadic arguments. Converting them is pointless, since the
6600 // user can't refer to them in the function condition.
6601 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6602
6603 // Convert the arguments.
6604 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6605 ExprResult R;
6606 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6607 S.Context, Function->getParamDecl(I)),
6608 SourceLocation(), Args[I]);
6609
6610 if (R.isInvalid())
6611 return false;
6612
6613 ConvertedArgs.push_back(R.get());
6614 }
6615
6616 if (Trap.hasErrorOccurred())
6617 return false;
6618
6619 // Push default arguments if needed.
6620 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6621 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6622 ParmVarDecl *P = Function->getParamDecl(i);
6623 if (!P->hasDefaultArg())
6624 return false;
6625 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6626 if (R.isInvalid())
6627 return false;
6628 ConvertedArgs.push_back(R.get());
6629 }
6630
6631 if (Trap.hasErrorOccurred())
6632 return false;
6633 }
6634 return true;
6635}
6636
6637EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6638 SourceLocation CallLoc,
6639 ArrayRef<Expr *> Args,
6640 bool MissingImplicitThis) {
6641 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6642 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6643 return nullptr;
6644
6645 SFINAETrap Trap(*this);
6646 SmallVector<Expr *, 16> ConvertedArgs;
6647 // FIXME: We should look into making enable_if late-parsed.
6648 Expr *DiscardedThis;
6649 if (!convertArgsForAvailabilityChecks(
6650 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6651 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6652 return *EnableIfAttrs.begin();
6653
6654 for (auto *EIA : EnableIfAttrs) {
6655 APValue Result;
6656 // FIXME: This doesn't consider value-dependent cases, because doing so is
6657 // very difficult. Ideally, we should handle them more gracefully.
6658 if (EIA->getCond()->isValueDependent() ||
6659 !EIA->getCond()->EvaluateWithSubstitution(
6660 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6661 return EIA;
6662
6663 if (!Result.isInt() || !Result.getInt().getBoolValue())
6664 return EIA;
6665 }
6666 return nullptr;
6667}
6668
6669template <typename CheckFn>
6670static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6671 bool ArgDependent, SourceLocation Loc,
6672 CheckFn &&IsSuccessful) {
6673 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6674 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6675 if (ArgDependent == DIA->getArgDependent())
6676 Attrs.push_back(DIA);
6677 }
6678
6679 // Common case: No diagnose_if attributes, so we can quit early.
6680 if (Attrs.empty())
6681 return false;
6682
6683 auto WarningBegin = std::stable_partition(
6684 Attrs.begin(), Attrs.end(),
6685 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6686
6687 // Note that diagnose_if attributes are late-parsed, so they appear in the
6688 // correct order (unlike enable_if attributes).
6689 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6690 IsSuccessful);
6691 if (ErrAttr != WarningBegin) {
6692 const DiagnoseIfAttr *DIA = *ErrAttr;
6693 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6694 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6695 << DIA->getParent() << DIA->getCond()->getSourceRange();
6696 return true;
6697 }
6698
6699 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6700 if (IsSuccessful(DIA)) {
6701 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6702 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6703 << DIA->getParent() << DIA->getCond()->getSourceRange();
6704 }
6705
6706 return false;
6707}
6708
6709bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6710 const Expr *ThisArg,
6711 ArrayRef<const Expr *> Args,
6712 SourceLocation Loc) {
6713 return diagnoseDiagnoseIfAttrsWith(
6714 *this, Function, /*ArgDependent=*/true, Loc,
6715 [&](const DiagnoseIfAttr *DIA) {
6716 APValue Result;
6717 // It's sane to use the same Args for any redecl of this function, since
6718 // EvaluateWithSubstitution only cares about the position of each
6719 // argument in the arg list, not the ParmVarDecl* it maps to.
6720 if (!DIA->getCond()->EvaluateWithSubstitution(
6721 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6722 return false;
6723 return Result.isInt() && Result.getInt().getBoolValue();
6724 });
6725}
6726
6727bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6728 SourceLocation Loc) {
6729 return diagnoseDiagnoseIfAttrsWith(
6730 *this, ND, /*ArgDependent=*/false, Loc,
6731 [&](const DiagnoseIfAttr *DIA) {
6732 bool Result;
6733 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6734 Result;
6735 });
6736}
6737
6738/// Add all of the function declarations in the given function set to
6739/// the overload candidate set.
6740void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6741 ArrayRef<Expr *> Args,
6742 OverloadCandidateSet &CandidateSet,
6743 TemplateArgumentListInfo *ExplicitTemplateArgs,
6744 bool SuppressUserConversions,
6745 bool PartialOverloading,
6746 bool FirstArgumentIsBase) {
6747 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6748 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6749 ArrayRef<Expr *> FunctionArgs = Args;
6750
6751 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6752 FunctionDecl *FD =
6753 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6754
6755 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6756 QualType ObjectType;
6757 Expr::Classification ObjectClassification;
6758 if (Args.size() > 0) {
6759 if (Expr *E = Args[0]) {
6760 // Use the explicit base to restrict the lookup:
6761 ObjectType = E->getType();
6762 // Pointers in the object arguments are implicitly dereferenced, so we
6763 // always classify them as l-values.
6764 if (!ObjectType.isNull() && ObjectType->isPointerType())
6765 ObjectClassification = Expr::Classification::makeSimpleLValue();
6766 else
6767 ObjectClassification = E->Classify(Context);
6768 } // .. else there is an implicit base.
6769 FunctionArgs = Args.slice(1);
6770 }
6771 if (FunTmpl) {
6772 AddMethodTemplateCandidate(
6773 FunTmpl, F.getPair(),
6774 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6775 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6776 FunctionArgs, CandidateSet, SuppressUserConversions,
6777 PartialOverloading);
6778 } else {
6779 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6780 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6781 ObjectClassification, FunctionArgs, CandidateSet,
6782 SuppressUserConversions, PartialOverloading);
6783 }
6784 } else {
6785 // This branch handles both standalone functions and static methods.
6786
6787 // Slice the first argument (which is the base) when we access
6788 // static method as non-static.
6789 if (Args.size() > 0 &&
6790 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6791 !isa<CXXConstructorDecl>(FD)))) {
6792 assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast<void> (0));
6793 FunctionArgs = Args.slice(1);
6794 }
6795 if (FunTmpl) {
6796 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6797 ExplicitTemplateArgs, FunctionArgs,
6798 CandidateSet, SuppressUserConversions,
6799 PartialOverloading);
6800 } else {
6801 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6802 SuppressUserConversions, PartialOverloading);
6803 }
6804 }
6805 }
6806}
6807
6808/// AddMethodCandidate - Adds a named decl (which is some kind of
6809/// method) as a method candidate to the given overload set.
6810void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6811 Expr::Classification ObjectClassification,
6812 ArrayRef<Expr *> Args,
6813 OverloadCandidateSet &CandidateSet,
6814 bool SuppressUserConversions,
6815 OverloadCandidateParamOrder PO) {
6816 NamedDecl *Decl = FoundDecl.getDecl();
6817 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6818
6819 if (isa<UsingShadowDecl>(Decl))
6820 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6821
6822 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6823 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast<void> (0))
6824 "Expected a member function template")(static_cast<void> (0));
6825 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6826 /*ExplicitArgs*/ nullptr, ObjectType,
6827 ObjectClassification, Args, CandidateSet,
6828 SuppressUserConversions, false, PO);
6829 } else {
6830 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6831 ObjectType, ObjectClassification, Args, CandidateSet,
6832 SuppressUserConversions, false, None, PO);
6833 }
6834}
6835
6836/// AddMethodCandidate - Adds the given C++ member function to the set
6837/// of candidate functions, using the given function call arguments
6838/// and the object argument (@c Object). For example, in a call
6839/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6840/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6841/// allow user-defined conversions via constructors or conversion
6842/// operators.
6843void
6844Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6845 CXXRecordDecl *ActingContext, QualType ObjectType,
6846 Expr::Classification ObjectClassification,
6847 ArrayRef<Expr *> Args,
6848 OverloadCandidateSet &CandidateSet,
6849 bool SuppressUserConversions,
6850 bool PartialOverloading,
6851 ConversionSequenceList EarlyConversions,
6852 OverloadCandidateParamOrder PO) {
6853 const FunctionProtoType *Proto
6854 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6855 assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast<void> (0));
6856 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast<void> (0))
6857 "Use AddOverloadCandidate for constructors")(static_cast<void> (0));
6858
6859 if (!CandidateSet.isNewCandidate(Method, PO))
6860 return;
6861
6862 // C++11 [class.copy]p23: [DR1402]
6863 // A defaulted move assignment operator that is defined as deleted is
6864 // ignored by overload resolution.
6865 if (Method->isDefaulted() && Method->isDeleted() &&
6866 Method->isMoveAssignmentOperator())
6867 return;
6868
6869 // Overload resolution is always an unevaluated context.
6870 EnterExpressionEvaluationContext Unevaluated(
6871 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6872
6873 // Add this candidate
6874 OverloadCandidate &Candidate =
6875 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6876 Candidate.FoundDecl = FoundDecl;
6877 Candidate.Function = Method;
6878 Candidate.RewriteKind =
6879 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6880 Candidate.IsSurrogate = false;
6881 Candidate.IgnoreObjectArgument = false;
6882 Candidate.ExplicitCallArguments = Args.size();
6883
6884 unsigned NumParams = Proto->getNumParams();
6885
6886 // (C++ 13.3.2p2): A candidate function having fewer than m
6887 // parameters is viable only if it has an ellipsis in its parameter
6888 // list (8.3.5).
6889 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6890 !Proto->isVariadic()) {
6891 Candidate.Viable = false;
6892 Candidate.FailureKind = ovl_fail_too_many_arguments;
6893 return;
6894 }
6895
6896 // (C++ 13.3.2p2): A candidate function having more than m parameters
6897 // is viable only if the (m+1)st parameter has a default argument
6898 // (8.3.6). For the purposes of overload resolution, the
6899 // parameter list is truncated on the right, so that there are
6900 // exactly m parameters.
6901 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6902 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6903 // Not enough arguments.
6904 Candidate.Viable = false;
6905 Candidate.FailureKind = ovl_fail_too_few_arguments;
6906 return;
6907 }
6908
6909 Candidate.Viable = true;
6910
6911 if (Method->isStatic() || ObjectType.isNull())
6912 // The implicit object argument is ignored.
6913 Candidate.IgnoreObjectArgument = true;
6914 else {
6915 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6916 // Determine the implicit conversion sequence for the object
6917 // parameter.
6918 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6919 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6920 Method, ActingContext);
6921 if (Candidate.Conversions[ConvIdx].isBad()) {
6922 Candidate.Viable = false;
6923 Candidate.FailureKind = ovl_fail_bad_conversion;
6924 return;
6925 }
6926 }
6927
6928 // (CUDA B.1): Check for invalid calls between targets.
6929 if (getLangOpts().CUDA)
6930 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6931 if (!IsAllowedCUDACall(Caller, Method)) {
6932 Candidate.Viable = false;
6933 Candidate.FailureKind = ovl_fail_bad_target;
6934 return;
6935 }
6936
6937 if (Method->getTrailingRequiresClause()) {
6938 ConstraintSatisfaction Satisfaction;
6939 if (CheckFunctionConstraints(Method, Satisfaction) ||
6940 !Satisfaction.IsSatisfied) {
6941 Candidate.Viable = false;
6942 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6943 return;
6944 }
6945 }
6946
6947 // Determine the implicit conversion sequences for each of the
6948 // arguments.
6949 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6950 unsigned ConvIdx =
6951 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6952 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6953 // We already formed a conversion sequence for this parameter during
6954 // template argument deduction.
6955 } else if (ArgIdx < NumParams) {
6956 // (C++ 13.3.2p3): for F to be a viable function, there shall
6957 // exist for each argument an implicit conversion sequence
6958 // (13.3.3.1) that converts that argument to the corresponding
6959 // parameter of F.
6960 QualType ParamType = Proto->getParamType(ArgIdx);
6961 Candidate.Conversions[ConvIdx]
6962 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6963 SuppressUserConversions,
6964 /*InOverloadResolution=*/true,
6965 /*AllowObjCWritebackConversion=*/
6966 getLangOpts().ObjCAutoRefCount);
6967 if (Candidate.Conversions[ConvIdx].isBad()) {
6968 Candidate.Viable = false;
6969 Candidate.FailureKind = ovl_fail_bad_conversion;
6970 return;
6971 }
6972 } else {
6973 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6974 // argument for which there is no corresponding parameter is
6975 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6976 Candidate.Conversions[ConvIdx].setEllipsis();
6977 }
6978 }
6979
6980 if (EnableIfAttr *FailedAttr =
6981 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6982 Candidate.Viable = false;
6983 Candidate.FailureKind = ovl_fail_enable_if;
6984 Candidate.DeductionFailure.Data = FailedAttr;
6985 return;
6986 }
6987
6988 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6989 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6990 Candidate.Viable = false;
6991 Candidate.FailureKind = ovl_non_default_multiversion_function;
6992 }
6993}
6994
6995/// Add a C++ member function template as a candidate to the candidate
6996/// set, using template argument deduction to produce an appropriate member
6997/// function template specialization.
6998void Sema::AddMethodTemplateCandidate(
6999 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7000 CXXRecordDecl *ActingContext,
7001 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7002 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7003 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7004 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7005 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7006 return;
7007
7008 // C++ [over.match.funcs]p7:
7009 // In each case where a candidate is a function template, candidate
7010 // function template specializations are generated using template argument
7011 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7012 // candidate functions in the usual way.113) A given name can refer to one
7013 // or more function templates and also to a set of overloaded non-template
7014 // functions. In such a case, the candidate functions generated from each
7015 // function template are combined with the set of non-template candidate
7016 // functions.
7017 TemplateDeductionInfo Info(CandidateSet.getLocation());
7018 FunctionDecl *Specialization = nullptr;
7019 ConversionSequenceList Conversions;
7020 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7021 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7022 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7023 return CheckNonDependentConversions(
7024 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7025 SuppressUserConversions, ActingContext, ObjectType,
7026 ObjectClassification, PO);
7027 })) {
7028 OverloadCandidate &Candidate =
7029 CandidateSet.addCandidate(Conversions.size(), Conversions);
7030 Candidate.FoundDecl = FoundDecl;
7031 Candidate.Function = MethodTmpl->getTemplatedDecl();
7032 Candidate.Viable = false;
7033 Candidate.RewriteKind =
7034 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7035 Candidate.IsSurrogate = false;
7036 Candidate.IgnoreObjectArgument =
7037 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7038 ObjectType.isNull();
7039 Candidate.ExplicitCallArguments = Args.size();
7040 if (Result == TDK_NonDependentConversionFailure)
7041 Candidate.FailureKind = ovl_fail_bad_conversion;
7042 else {
7043 Candidate.FailureKind = ovl_fail_bad_deduction;
7044 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7045 Info);
7046 }
7047 return;
7048 }
7049
7050 // Add the function template specialization produced by template argument
7051 // deduction as a candidate.
7052 assert(Specialization && "Missing member function template specialization?")(static_cast<void> (0));
7053 assert(isa<CXXMethodDecl>(Specialization) &&(static_cast<void> (0))
7054 "Specialization is not a member function?")(static_cast<void> (0));
7055 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7056 ActingContext, ObjectType, ObjectClassification, Args,
7057 CandidateSet, SuppressUserConversions, PartialOverloading,
7058 Conversions, PO);
7059}
7060
7061/// Determine whether a given function template has a simple explicit specifier
7062/// or a non-value-dependent explicit-specification that evaluates to true.
7063static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7064 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7065}
7066
7067/// Add a C++ function template specialization as a candidate
7068/// in the candidate set, using template argument deduction to produce
7069/// an appropriate function template specialization.
7070void Sema::AddTemplateOverloadCandidate(
7071 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7072 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7073 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7074 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7075 OverloadCandidateParamOrder PO) {
7076 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7077 return;
7078
7079 // If the function template has a non-dependent explicit specification,
7080 // exclude it now if appropriate; we are not permitted to perform deduction
7081 // and substitution in this case.
7082 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7083 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7084 Candidate.FoundDecl = FoundDecl;
7085 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7086 Candidate.Viable = false;
7087 Candidate.FailureKind = ovl_fail_explicit;
7088 return;
7089 }
7090
7091 // C++ [over.match.funcs]p7:
7092 // In each case where a candidate is a function template, candidate
7093 // function template specializations are generated using template argument
7094 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7095 // candidate functions in the usual way.113) A given name can refer to one
7096 // or more function templates and also to a set of overloaded non-template
7097 // functions. In such a case, the candidate functions generated from each
7098 // function template are combined with the set of non-template candidate
7099 // functions.
7100 TemplateDeductionInfo Info(CandidateSet.getLocation());
7101 FunctionDecl *Specialization = nullptr;
7102 ConversionSequenceList Conversions;
7103 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7104 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7105 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7106 return CheckNonDependentConversions(
7107 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7108 SuppressUserConversions, nullptr, QualType(), {}, PO);
7109 })) {
7110 OverloadCandidate &Candidate =
7111 CandidateSet.addCandidate(Conversions.size(), Conversions);
7112 Candidate.FoundDecl = FoundDecl;
7113 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7114 Candidate.Viable = false;
7115 Candidate.RewriteKind =
7116 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7117 Candidate.IsSurrogate = false;
7118 Candidate.IsADLCandidate = IsADLCandidate;
7119 // Ignore the object argument if there is one, since we don't have an object
7120 // type.
7121 Candidate.IgnoreObjectArgument =
7122 isa<CXXMethodDecl>(Candidate.Function) &&
7123 !isa<CXXConstructorDecl>(Candidate.Function);
7124 Candidate.ExplicitCallArguments = Args.size();
7125 if (Result == TDK_NonDependentConversionFailure)
7126 Candidate.FailureKind = ovl_fail_bad_conversion;
7127 else {
7128 Candidate.FailureKind = ovl_fail_bad_deduction;
7129 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7130 Info);
7131 }
7132 return;
7133 }
7134
7135 // Add the function template specialization produced by template argument
7136 // deduction as a candidate.
7137 assert(Specialization && "Missing function template specialization?")(static_cast<void> (0));
7138 AddOverloadCandidate(
7139 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7140 PartialOverloading, AllowExplicit,
7141 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7142}
7143
7144/// Check that implicit conversion sequences can be formed for each argument
7145/// whose corresponding parameter has a non-dependent type, per DR1391's
7146/// [temp.deduct.call]p10.
7147bool Sema::CheckNonDependentConversions(
7148 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7149 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7150 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7151 CXXRecordDecl *ActingContext, QualType ObjectType,
7152 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7153 // FIXME: The cases in which we allow explicit conversions for constructor
7154 // arguments never consider calling a constructor template. It's not clear
7155 // that is correct.
7156 const bool AllowExplicit = false;
7157
7158 auto *FD = FunctionTemplate->getTemplatedDecl();
7159 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7160 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7161 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7162
7163 Conversions =
7164 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7165
7166 // Overload resolution is always an unevaluated context.
7167 EnterExpressionEvaluationContext Unevaluated(
7168 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7169
7170 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7171 // require that, but this check should never result in a hard error, and
7172 // overload resolution is permitted to sidestep instantiations.
7173 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7174 !ObjectType.isNull()) {
7175 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7176 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7177 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7178 Method, ActingContext);
7179 if (Conversions[ConvIdx].isBad())
7180 return true;
7181 }
7182
7183 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7184 ++I) {
7185 QualType ParamType = ParamTypes[I];
7186 if (!ParamType->isDependentType()) {
7187 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7188 ? 0
7189 : (ThisConversions + I);
7190 Conversions[ConvIdx]
7191 = TryCopyInitialization(*this, Args[I], ParamType,
7192 SuppressUserConversions,
7193 /*InOverloadResolution=*/true,
7194 /*AllowObjCWritebackConversion=*/
7195 getLangOpts().ObjCAutoRefCount,
7196 AllowExplicit);
7197 if (Conversions[ConvIdx].isBad())
7198 return true;
7199 }
7200 }
7201
7202 return false;
7203}
7204
7205/// Determine whether this is an allowable conversion from the result
7206/// of an explicit conversion operator to the expected type, per C++
7207/// [over.match.conv]p1 and [over.match.ref]p1.
7208///
7209/// \param ConvType The return type of the conversion function.
7210///
7211/// \param ToType The type we are converting to.
7212///
7213/// \param AllowObjCPointerConversion Allow a conversion from one
7214/// Objective-C pointer to another.
7215///
7216/// \returns true if the conversion is allowable, false otherwise.
7217static bool isAllowableExplicitConversion(Sema &S,
7218 QualType ConvType, QualType ToType,
7219 bool AllowObjCPointerConversion) {
7220 QualType ToNonRefType = ToType.getNonReferenceType();
7221
7222 // Easy case: the types are the same.
7223 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7224 return true;
7225
7226 // Allow qualification conversions.
7227 bool ObjCLifetimeConversion;
7228 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7229 ObjCLifetimeConversion))
7230 return true;
7231
7232 // If we're not allowed to consider Objective-C pointer conversions,
7233 // we're done.
7234 if (!AllowObjCPointerConversion)
7235 return false;
7236
7237 // Is this an Objective-C pointer conversion?
7238 bool IncompatibleObjC = false;
7239 QualType ConvertedType;
7240 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7241 IncompatibleObjC);
7242}
7243
7244/// AddConversionCandidate - Add a C++ conversion function as a
7245/// candidate in the candidate set (C++ [over.match.conv],
7246/// C++ [over.match.copy]). From is the expression we're converting from,
7247/// and ToType is the type that we're eventually trying to convert to
7248/// (which may or may not be the same type as the type that the
7249/// conversion function produces).
7250void Sema::AddConversionCandidate(
7251 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7252 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7253 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7254 bool AllowExplicit, bool AllowResultConversion) {
7255 assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast<void> (0))
7256 "Conversion function templates use AddTemplateConversionCandidate")(static_cast<void> (0));
7257 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7258 if (!CandidateSet.isNewCandidate(Conversion))
7259 return;
7260
7261 // If the conversion function has an undeduced return type, trigger its
7262 // deduction now.
7263 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7264 if (DeduceReturnType(Conversion, From->getExprLoc()))
7265 return;
7266 ConvType = Conversion->getConversionType().getNonReferenceType();
7267 }
7268
7269 // If we don't allow any conversion of the result type, ignore conversion
7270 // functions that don't convert to exactly (possibly cv-qualified) T.
7271 if (!AllowResultConversion &&
7272 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7273 return;
7274
7275 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7276 // operator is only a candidate if its return type is the target type or
7277 // can be converted to the target type with a qualification conversion.
7278 //
7279 // FIXME: Include such functions in the candidate list and explain why we
7280 // can't select them.
7281 if (Conversion->isExplicit() &&
7282 !isAllowableExplicitConversion(*this, ConvType, ToType,
7283 AllowObjCConversionOnExplicit))
7284 return;
7285
7286 // Overload resolution is always an unevaluated context.
7287 EnterExpressionEvaluationContext Unevaluated(
7288 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7289
7290 // Add this candidate
7291 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7292 Candidate.FoundDecl = FoundDecl;
7293 Candidate.Function = Conversion;
7294 Candidate.IsSurrogate = false;
7295 Candidate.IgnoreObjectArgument = false;
7296 Candidate.FinalConversion.setAsIdentityConversion();
7297 Candidate.FinalConversion.setFromType(ConvType);
7298 Candidate.FinalConversion.setAllToTypes(ToType);
7299 Candidate.Viable = true;
7300 Candidate.ExplicitCallArguments = 1;
7301
7302 // Explicit functions are not actually candidates at all if we're not
7303 // allowing them in this context, but keep them around so we can point
7304 // to them in diagnostics.
7305 if (!AllowExplicit && Conversion->isExplicit()) {
7306 Candidate.Viable = false;
7307 Candidate.FailureKind = ovl_fail_explicit;
7308 return;
7309 }
7310
7311 // C++ [over.match.funcs]p4:
7312 // For conversion functions, the function is considered to be a member of
7313 // the class of the implicit implied object argument for the purpose of
7314 // defining the type of the implicit object parameter.
7315 //
7316 // Determine the implicit conversion sequence for the implicit
7317 // object parameter.
7318 QualType ImplicitParamType = From->getType();
7319 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7320 ImplicitParamType = FromPtrType->getPointeeType();
7321 CXXRecordDecl *ConversionContext
7322 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7323
7324 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7325 *this, CandidateSet.getLocation(), From->getType(),
7326 From->Classify(Context), Conversion, ConversionContext);
7327
7328 if (Candidate.Conversions[0].isBad()) {
7329 Candidate.Viable = false;
7330 Candidate.FailureKind = ovl_fail_bad_conversion;
7331 return;
7332 }
7333
7334 if (Conversion->getTrailingRequiresClause()) {
7335 ConstraintSatisfaction Satisfaction;
7336 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7337 !Satisfaction.IsSatisfied) {
7338 Candidate.Viable = false;
7339 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7340 return;
7341 }
7342 }
7343
7344 // We won't go through a user-defined type conversion function to convert a
7345 // derived to base as such conversions are given Conversion Rank. They only
7346 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7347 QualType FromCanon
7348 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7349 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7350 if (FromCanon == ToCanon ||
7351 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7352 Candidate.Viable = false;
7353 Candidate.FailureKind = ovl_fail_trivial_conversion;
7354 return;
7355 }
7356
7357 // To determine what the conversion from the result of calling the
7358 // conversion function to the type we're eventually trying to
7359 // convert to (ToType), we need to synthesize a call to the
7360 // conversion function and attempt copy initialization from it. This
7361 // makes sure that we get the right semantics with respect to
7362 // lvalues/rvalues and the type. Fortunately, we can allocate this
7363 // call on the stack and we don't need its arguments to be
7364 // well-formed.
7365 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7366 VK_LValue, From->getBeginLoc());
7367 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7368 Context.getPointerType(Conversion->getType()),
7369 CK_FunctionToPointerDecay, &ConversionRef,
7370 VK_PRValue, FPOptionsOverride());
7371
7372 QualType ConversionType = Conversion->getConversionType();
7373 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7374 Candidate.Viable = false;
7375 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7376 return;
7377 }
7378
7379 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7380
7381 // Note that it is safe to allocate CallExpr on the stack here because
7382 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7383 // allocator).
7384 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7385
7386 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7387 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7388 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7389
7390 ImplicitConversionSequence ICS =
7391 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7392 /*SuppressUserConversions=*/true,
7393 /*InOverloadResolution=*/false,
7394 /*AllowObjCWritebackConversion=*/false);
7395
7396 switch (ICS.getKind()) {
7397 case ImplicitConversionSequence::StandardConversion:
7398 Candidate.FinalConversion = ICS.Standard;
7399
7400 // C++ [over.ics.user]p3:
7401 // If the user-defined conversion is specified by a specialization of a
7402 // conversion function template, the second standard conversion sequence
7403 // shall have exact match rank.
7404 if (Conversion->getPrimaryTemplate() &&
7405 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7406 Candidate.Viable = false;
7407 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7408 return;
7409 }
7410
7411 // C++0x [dcl.init.ref]p5:
7412 // In the second case, if the reference is an rvalue reference and
7413 // the second standard conversion sequence of the user-defined
7414 // conversion sequence includes an lvalue-to-rvalue conversion, the
7415 // program is ill-formed.
7416 if (ToType->isRValueReferenceType() &&
7417 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7418 Candidate.Viable = false;
7419 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7420 return;
7421 }
7422 break;
7423
7424 case ImplicitConversionSequence::BadConversion:
7425 Candidate.Viable = false;
7426 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7427 return;
7428
7429 default:
7430 llvm_unreachable(__builtin_unreachable()
7431 "Can only end up with a standard conversion sequence or failure")__builtin_unreachable();
7432 }
7433
7434 if (EnableIfAttr *FailedAttr =
7435 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7436 Candidate.Viable = false;
7437 Candidate.FailureKind = ovl_fail_enable_if;
7438 Candidate.DeductionFailure.Data = FailedAttr;
7439 return;
7440 }
7441
7442 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7443 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7444 Candidate.Viable = false;
7445 Candidate.FailureKind = ovl_non_default_multiversion_function;
7446 }
7447}
7448
7449/// Adds a conversion function template specialization
7450/// candidate to the overload set, using template argument deduction
7451/// to deduce the template arguments of the conversion function
7452/// template from the type that we are converting to (C++
7453/// [temp.deduct.conv]).
7454void Sema::AddTemplateConversionCandidate(
7455 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7456 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7457 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7458 bool AllowExplicit, bool AllowResultConversion) {
7459 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast<void> (0))
7460 "Only conversion function templates permitted here")(static_cast<void> (0));
7461
7462 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7463 return;
7464
7465 // If the function template has a non-dependent explicit specification,
7466 // exclude it now if appropriate; we are not permitted to perform deduction
7467 // and substitution in this case.
7468 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7469 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7470 Candidate.FoundDecl = FoundDecl;
7471 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7472 Candidate.Viable = false;
7473 Candidate.FailureKind = ovl_fail_explicit;
7474 return;
7475 }
7476
7477 TemplateDeductionInfo Info(CandidateSet.getLocation());
7478 CXXConversionDecl *Specialization = nullptr;
7479 if (TemplateDeductionResult Result
7480 = DeduceTemplateArguments(FunctionTemplate, ToType,
7481 Specialization, Info)) {
7482 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7483 Candidate.FoundDecl = FoundDecl;
7484 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7485 Candidate.Viable = false;
7486 Candidate.FailureKind = ovl_fail_bad_deduction;
7487 Candidate.IsSurrogate = false;
7488 Candidate.IgnoreObjectArgument = false;
7489 Candidate.ExplicitCallArguments = 1;
7490 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7491 Info);
7492 return;
7493 }
7494
7495 // Add the conversion function template specialization produced by
7496 // template argument deduction as a candidate.
7497 assert(Specialization && "Missing function template specialization?")(static_cast<void> (0));
7498 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7499 CandidateSet, AllowObjCConversionOnExplicit,
7500 AllowExplicit, AllowResultConversion);
7501}
7502
7503/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7504/// converts the given @c Object to a function pointer via the
7505/// conversion function @c Conversion, and then attempts to call it
7506/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7507/// the type of function that we'll eventually be calling.
7508void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7509 DeclAccessPair FoundDecl,
7510 CXXRecordDecl *ActingContext,
7511 const FunctionProtoType *Proto,
7512 Expr *Object,
7513 ArrayRef<Expr *> Args,
7514 OverloadCandidateSet& CandidateSet) {
7515 if (!CandidateSet.isNewCandidate(Conversion))
7516 return;
7517
7518 // Overload resolution is always an unevaluated context.
7519 EnterExpressionEvaluationContext Unevaluated(
7520 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7521
7522 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7523 Candidate.FoundDecl = FoundDecl;
7524 Candidate.Function = nullptr;
7525 Candidate.Surrogate = Conversion;
7526 Candidate.Viable = true;
7527 Candidate.IsSurrogate = true;
7528 Candidate.IgnoreObjectArgument = false;
7529 Candidate.ExplicitCallArguments = Args.size();
7530
7531 // Determine the implicit conversion sequence for the implicit
7532 // object parameter.
7533 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7534 *this, CandidateSet.getLocation(), Object->getType(),
7535 Object->Classify(Context), Conversion, ActingContext);
7536 if (ObjectInit.isBad()) {
7537 Candidate.Viable = false;
7538 Candidate.FailureKind = ovl_fail_bad_conversion;
7539 Candidate.Conversions[0] = ObjectInit;
7540 return;
7541 }
7542
7543 // The first conversion is actually a user-defined conversion whose
7544 // first conversion is ObjectInit's standard conversion (which is
7545 // effectively a reference binding). Record it as such.
7546 Candidate.Conversions[0].setUserDefined();
7547 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7548 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7549 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7550 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7551 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7552 Candidate.Conversions[0].UserDefined.After
7553 = Candidate.Conversions[0].UserDefined.Before;
7554 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7555
7556 // Find the
7557 unsigned NumParams = Proto->getNumParams();
7558
7559 // (C++ 13.3.2p2): A candidate function having fewer than m
7560 // parameters is viable only if it has an ellipsis in its parameter
7561 // list (8.3.5).
7562 if (Args.size() > NumParams && !Proto->isVariadic()) {
7563 Candidate.Viable = false;
7564 Candidate.FailureKind = ovl_fail_too_many_arguments;
7565 return;
7566 }
7567
7568 // Function types don't have any default arguments, so just check if
7569 // we have enough arguments.
7570 if (Args.size() < NumParams) {
7571 // Not enough arguments.
7572 Candidate.Viable = false;
7573 Candidate.FailureKind = ovl_fail_too_few_arguments;
7574 return;
7575 }
7576
7577 // Determine the implicit conversion sequences for each of the
7578 // arguments.
7579 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7580 if (ArgIdx < NumParams) {
7581 // (C++ 13.3.2p3): for F to be a viable function, there shall
7582 // exist for each argument an implicit conversion sequence
7583 // (13.3.3.1) that converts that argument to the corresponding
7584 // parameter of F.
7585 QualType ParamType = Proto->getParamType(ArgIdx);
7586 Candidate.Conversions[ArgIdx + 1]
7587 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7588 /*SuppressUserConversions=*/false,
7589 /*InOverloadResolution=*/false,
7590 /*AllowObjCWritebackConversion=*/
7591 getLangOpts().ObjCAutoRefCount);
7592 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7593 Candidate.Viable = false;
7594 Candidate.FailureKind = ovl_fail_bad_conversion;
7595 return;
7596 }
7597 } else {
7598 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7599 // argument for which there is no corresponding parameter is
7600 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7601 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7602 }
7603 }
7604
7605 if (EnableIfAttr *FailedAttr =
7606 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7607 Candidate.Viable = false;
7608 Candidate.FailureKind = ovl_fail_enable_if;
7609 Candidate.DeductionFailure.Data = FailedAttr;
7610 return;
7611 }
7612}
7613
7614/// Add all of the non-member operator function declarations in the given
7615/// function set to the overload candidate set.
7616void Sema::AddNonMemberOperatorCandidates(
7617 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7618 OverloadCandidateSet &CandidateSet,
7619 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7620 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7621 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7622 ArrayRef<Expr *> FunctionArgs = Args;
7623
7624 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7625 FunctionDecl *FD =
7626 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7627
7628 // Don't consider rewritten functions if we're not rewriting.
7629 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7630 continue;
7631
7632 assert(!isa<CXXMethodDecl>(FD) &&(static_cast<void> (0))
7633 "unqualified operator lookup found a member function")(static_cast<void> (0));
7634
7635 if (FunTmpl) {
7636 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7637 FunctionArgs, CandidateSet);
7638 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7639 AddTemplateOverloadCandidate(
7640 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7641 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7642 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7643 } else {
7644 if (ExplicitTemplateArgs)
7645 continue;
7646 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7647 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7648 AddOverloadCandidate(FD, F.getPair(),
7649 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7650 false, false, true, false, ADLCallKind::NotADL,
7651 None, OverloadCandidateParamOrder::Reversed);
7652 }
7653 }
7654}
7655
7656/// Add overload candidates for overloaded operators that are
7657/// member functions.
7658///
7659/// Add the overloaded operator candidates that are member functions
7660/// for the operator Op that was used in an operator expression such
7661/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7662/// CandidateSet will store the added overload candidates. (C++
7663/// [over.match.oper]).
7664void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7665 SourceLocation OpLoc,
7666 ArrayRef<Expr *> Args,
7667 OverloadCandidateSet &CandidateSet,
7668 OverloadCandidateParamOrder PO) {
7669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7670
7671 // C++ [over.match.oper]p3:
7672 // For a unary operator @ with an operand of a type whose
7673 // cv-unqualified version is T1, and for a binary operator @ with
7674 // a left operand of a type whose cv-unqualified version is T1 and
7675 // a right operand of a type whose cv-unqualified version is T2,
7676 // three sets of candidate functions, designated member
7677 // candidates, non-member candidates and built-in candidates, are
7678 // constructed as follows:
7679 QualType T1 = Args[0]->getType();
7680
7681 // -- If T1 is a complete class type or a class currently being
7682 // defined, the set of member candidates is the result of the
7683 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7684 // the set of member candidates is empty.
7685 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7686 // Complete the type if it can be completed.
7687 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7688 return;
7689 // If the type is neither complete nor being defined, bail out now.
7690 if (!T1Rec->getDecl()->getDefinition())
7691 return;
7692
7693 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7694 LookupQualifiedName(Operators, T1Rec->getDecl());
7695 Operators.suppressDiagnostics();
7696
7697 for (LookupResult::iterator Oper = Operators.begin(),
7698 OperEnd = Operators.end();
7699 Oper != OperEnd;
7700 ++Oper)
7701 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7702 Args[0]->Classify(Context), Args.slice(1),
7703 CandidateSet, /*SuppressUserConversion=*/false, PO);
7704 }
7705}
7706
7707/// AddBuiltinCandidate - Add a candidate for a built-in
7708/// operator. ResultTy and ParamTys are the result and parameter types
7709/// of the built-in candidate, respectively. Args and NumArgs are the
7710/// arguments being passed to the candidate. IsAssignmentOperator
7711/// should be true when this built-in candidate is an assignment
7712/// operator. NumContextualBoolArguments is the number of arguments
7713/// (at the beginning of the argument list) that will be contextually
7714/// converted to bool.
7715void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7716 OverloadCandidateSet& CandidateSet,
7717 bool IsAssignmentOperator,
7718 unsigned NumContextualBoolArguments) {
7719 // Overload resolution is always an unevaluated context.
7720 EnterExpressionEvaluationContext Unevaluated(
7721 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7722
7723 // Add this candidate
7724 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7725 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7726 Candidate.Function = nullptr;
7727 Candidate.IsSurrogate = false;
7728 Candidate.IgnoreObjectArgument = false;
7729 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7730
7731 // Determine the implicit conversion sequences for each of the
7732 // arguments.
7733 Candidate.Viable = true;
7734 Candidate.ExplicitCallArguments = Args.size();
7735 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7736 // C++ [over.match.oper]p4:
7737 // For the built-in assignment operators, conversions of the
7738 // left operand are restricted as follows:
7739 // -- no temporaries are introduced to hold the left operand, and
7740 // -- no user-defined conversions are applied to the left
7741 // operand to achieve a type match with the left-most
7742 // parameter of a built-in candidate.
7743 //
7744 // We block these conversions by turning off user-defined
7745 // conversions, since that is the only way that initialization of
7746 // a reference to a non-class type can occur from something that
7747 // is not of the same type.
7748 if (ArgIdx < NumContextualBoolArguments) {
7749 assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast<void> (0))
7750 "Contextual conversion to bool requires bool type")(static_cast<void> (0));
7751 Candidate.Conversions[ArgIdx]
7752 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7753 } else {
7754 Candidate.Conversions[ArgIdx]
7755 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7756 ArgIdx == 0 && IsAssignmentOperator,
7757 /*InOverloadResolution=*/false,
7758 /*AllowObjCWritebackConversion=*/
7759 getLangOpts().ObjCAutoRefCount);
7760 }
7761 if (Candidate.Conversions[ArgIdx].isBad()) {
7762 Candidate.Viable = false;
7763 Candidate.FailureKind = ovl_fail_bad_conversion;
7764 break;
7765 }
7766 }
7767}
7768
7769namespace {
7770
7771/// BuiltinCandidateTypeSet - A set of types that will be used for the
7772/// candidate operator functions for built-in operators (C++
7773/// [over.built]). The types are separated into pointer types and
7774/// enumeration types.
7775class BuiltinCandidateTypeSet {
7776 /// TypeSet - A set of types.
7777 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7778 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7779
7780 /// PointerTypes - The set of pointer types that will be used in the
7781 /// built-in candidates.
7782 TypeSet PointerTypes;
7783
7784 /// MemberPointerTypes - The set of member pointer types that will be
7785 /// used in the built-in candidates.
7786 TypeSet MemberPointerTypes;
7787
7788 /// EnumerationTypes - The set of enumeration types that will be
7789 /// used in the built-in candidates.
7790 TypeSet EnumerationTypes;
7791
7792 /// The set of vector types that will be used in the built-in
7793 /// candidates.
7794 TypeSet VectorTypes;
7795
7796 /// The set of matrix types that will be used in the built-in
7797 /// candidates.
7798 TypeSet MatrixTypes;
7799
7800 /// A flag indicating non-record types are viable candidates
7801 bool HasNonRecordTypes;
7802
7803 /// A flag indicating whether either arithmetic or enumeration types
7804 /// were present in the candidate set.
7805 bool HasArithmeticOrEnumeralTypes;
7806
7807 /// A flag indicating whether the nullptr type was present in the
7808 /// candidate set.
7809 bool HasNullPtrType;
7810
7811 /// Sema - The semantic analysis instance where we are building the
7812 /// candidate type set.
7813 Sema &SemaRef;
7814
7815 /// Context - The AST context in which we will build the type sets.
7816 ASTContext &Context;
7817
7818 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7819 const Qualifiers &VisibleQuals);
7820 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7821
7822public:
7823 /// iterator - Iterates through the types that are part of the set.
7824 typedef TypeSet::iterator iterator;
7825
7826 BuiltinCandidateTypeSet(Sema &SemaRef)
7827 : HasNonRecordTypes(false),
7828 HasArithmeticOrEnumeralTypes(false),
7829 HasNullPtrType(false),
7830 SemaRef(SemaRef),
7831 Context(SemaRef.Context) { }
7832
7833 void AddTypesConvertedFrom(QualType Ty,
7834 SourceLocation Loc,
7835 bool AllowUserConversions,
7836 bool AllowExplicitConversions,
7837 const Qualifiers &VisibleTypeConversionsQuals);
7838
7839 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7840 llvm::iterator_range<iterator> member_pointer_types() {
7841 return MemberPointerTypes;
7842 }
7843 llvm::iterator_range<iterator> enumeration_types() {
7844 return EnumerationTypes;
7845 }
7846 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7847 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7848
7849 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7850 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7851 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7852 bool hasNullPtrType() const { return HasNullPtrType; }
7853};
7854
7855} // end anonymous namespace
7856
7857/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7858/// the set of pointer types along with any more-qualified variants of
7859/// that type. For example, if @p Ty is "int const *", this routine
7860/// will add "int const *", "int const volatile *", "int const
7861/// restrict *", and "int const volatile restrict *" to the set of
7862/// pointer types. Returns true if the add of @p Ty itself succeeded,
7863/// false otherwise.
7864///
7865/// FIXME: what to do about extended qualifiers?
7866bool
7867BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7868 const Qualifiers &VisibleQuals) {
7869
7870 // Insert this type.
7871 if (!PointerTypes.insert(Ty))
7872 return false;
7873
7874 QualType PointeeTy;
7875 const PointerType *PointerTy = Ty->getAs<PointerType>();
7876 bool buildObjCPtr = false;
7877 if (!PointerTy) {
7878 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7879 PointeeTy = PTy->getPointeeType();
7880 buildObjCPtr = true;
7881 } else {
7882 PointeeTy = PointerTy->getPointeeType();
7883 }
7884
7885 // Don't add qualified variants of arrays. For one, they're not allowed
7886 // (the qualifier would sink to the element type), and for another, the
7887 // only overload situation where it matters is subscript or pointer +- int,
7888 // and those shouldn't have qualifier variants anyway.
7889 if (PointeeTy->isArrayType())
7890 return true;
7891
7892 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7893 bool hasVolatile = VisibleQuals.hasVolatile();
7894 bool hasRestrict = VisibleQuals.hasRestrict();
7895
7896 // Iterate through all strict supersets of BaseCVR.
7897 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7898 if ((CVR | BaseCVR) != CVR) continue;
7899 // Skip over volatile if no volatile found anywhere in the types.
7900 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7901
7902 // Skip over restrict if no restrict found anywhere in the types, or if
7903 // the type cannot be restrict-qualified.
7904 if ((CVR & Qualifiers::Restrict) &&
7905 (!hasRestrict ||
7906 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7907 continue;
7908
7909 // Build qualified pointee type.
7910 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7911
7912 // Build qualified pointer type.
7913 QualType QPointerTy;
7914 if (!buildObjCPtr)
7915 QPointerTy = Context.getPointerType(QPointeeTy);
7916 else
7917 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7918
7919 // Insert qualified pointer type.
7920 PointerTypes.insert(QPointerTy);
7921 }
7922
7923 return true;
7924}
7925
7926/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7927/// to the set of pointer types along with any more-qualified variants of
7928/// that type. For example, if @p Ty is "int const *", this routine
7929/// will add "int const *", "int const volatile *", "int const
7930/// restrict *", and "int const volatile restrict *" to the set of
7931/// pointer types. Returns true if the add of @p Ty itself succeeded,
7932/// false otherwise.
7933///
7934/// FIXME: what to do about extended qualifiers?
7935bool
7936BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7937 QualType Ty) {
7938 // Insert this type.
7939 if (!MemberPointerTypes.insert(Ty))
7940 return false;
7941
7942 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7943 assert(PointerTy && "type was not a member pointer type!")(static_cast<void> (0));
7944
7945 QualType PointeeTy = PointerTy->getPointeeType();
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 const Type *ClassTy = PointerTy->getClass();
7953
7954 // Iterate through all strict supersets of the pointee type's CVR
7955 // qualifiers.
7956 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7957 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7958 if ((CVR | BaseCVR) != CVR) continue;
7959
7960 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7961 MemberPointerTypes.insert(
7962 Context.getMemberPointerType(QPointeeTy, ClassTy));
7963 }
7964
7965 return true;
7966}
7967
7968/// AddTypesConvertedFrom - Add each of the types to which the type @p
7969/// Ty can be implicit converted to the given set of @p Types. We're
7970/// primarily interested in pointer types and enumeration types. We also
7971/// take member pointer types, for the conditional operator.
7972/// AllowUserConversions is true if we should look at the conversion
7973/// functions of a class type, and AllowExplicitConversions if we
7974/// should also include the explicit conversion functions of a class
7975/// type.
7976void
7977BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7978 SourceLocation Loc,
7979 bool AllowUserConversions,
7980 bool AllowExplicitConversions,
7981 const Qualifiers &VisibleQuals) {
7982 // Only deal with canonical types.
7983 Ty = Context.getCanonicalType(Ty);
7984
7985 // Look through reference types; they aren't part of the type of an
7986 // expression for the purposes of conversions.
7987 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7988 Ty = RefTy->getPointeeType();
7989
7990 // If we're dealing with an array type, decay to the pointer.
7991 if (Ty->isArrayType())
7992 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7993
7994 // Otherwise, we don't care about qualifiers on the type.
7995 Ty = Ty.getLocalUnqualifiedType();
7996
7997 // Flag if we ever add a non-record type.
7998 const RecordType *TyRec = Ty->getAs<RecordType>();
7999 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8000
8001 // Flag if we encounter an arithmetic type.
8002 HasArithmeticOrEnumeralTypes =
8003 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8004
8005 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8006 PointerTypes.insert(Ty);
8007 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8008 // Insert our type, and its more-qualified variants, into the set
8009 // of types.
8010 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8011 return;
8012 } else if (Ty->isMemberPointerType()) {
8013 // Member pointers are far easier, since the pointee can't be converted.
8014 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8015 return;
8016 } else if (Ty->isEnumeralType()) {
8017 HasArithmeticOrEnumeralTypes = true;
8018 EnumerationTypes.insert(Ty);
8019 } else if (Ty->isVectorType()) {
8020 // We treat vector types as arithmetic types in many contexts as an
8021 // extension.
8022 HasArithmeticOrEnumeralTypes = true;
8023 VectorTypes.insert(Ty);
8024 } else if (Ty->isMatrixType()) {
8025 // Similar to vector types, we treat vector types as arithmetic types in
8026 // many contexts as an extension.
8027 HasArithmeticOrEnumeralTypes = true;
8028 MatrixTypes.insert(Ty);
8029 } else if (Ty->isNullPtrType()) {
8030 HasNullPtrType = true;
8031 } else if (AllowUserConversions && TyRec) {
8032 // No conversion functions in incomplete types.
8033 if (!SemaRef.isCompleteType(Loc, Ty))
8034 return;
8035
8036 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8037 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8038 if (isa<UsingShadowDecl>(D))
8039 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8040
8041 // Skip conversion function templates; they don't tell us anything
8042 // about which builtin types we can convert to.
8043 if (isa<FunctionTemplateDecl>(D))
8044 continue;
8045
8046 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8047 if (AllowExplicitConversions || !Conv->isExplicit()) {
8048 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8049 VisibleQuals);
8050 }
8051 }
8052 }
8053}
8054/// Helper function for adjusting address spaces for the pointer or reference
8055/// operands of builtin operators depending on the argument.
8056static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8057 Expr *Arg) {
8058 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8059}
8060
8061/// Helper function for AddBuiltinOperatorCandidates() that adds
8062/// the volatile- and non-volatile-qualified assignment operators for the
8063/// given type to the candidate set.
8064static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8065 QualType T,
8066 ArrayRef<Expr *> Args,
8067 OverloadCandidateSet &CandidateSet) {
8068 QualType ParamTypes[2];
8069
8070 // T& operator=(T&, T)
8071 ParamTypes[0] = S.Context.getLValueReferenceType(
8072 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8073 ParamTypes[1] = T;
8074 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8075 /*IsAssignmentOperator=*/true);
8076
8077 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8078 // volatile T& operator=(volatile T&, T)
8079 ParamTypes[0] = S.Context.getLValueReferenceType(
8080 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8081 Args[0]));
8082 ParamTypes[1] = T;
8083 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8084 /*IsAssignmentOperator=*/true);
8085 }
8086}
8087
8088/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8089/// if any, found in visible type conversion functions found in ArgExpr's type.
8090static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8091 Qualifiers VRQuals;
8092 const RecordType *TyRec;
8093 if (const MemberPointerType *RHSMPType =
8094 ArgExpr->getType()->getAs<MemberPointerType>())
8095 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8096 else
8097 TyRec = ArgExpr->getType()->getAs<RecordType>();
8098 if (!TyRec) {
8099 // Just to be safe, assume the worst case.
8100 VRQuals.addVolatile();
8101 VRQuals.addRestrict();
8102 return VRQuals;
8103 }
8104
8105 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8106 if (!ClassDecl->hasDefinition())
8107 return VRQuals;
8108
8109 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8110 if (isa<UsingShadowDecl>(D))
8111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8112 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8113 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8114 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8115 CanTy = ResTypeRef->getPointeeType();
8116 // Need to go down the pointer/mempointer chain and add qualifiers
8117 // as see them.
8118 bool done = false;
8119 while (!done) {
8120 if (CanTy.isRestrictQualified())
8121 VRQuals.addRestrict();
8122 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8123 CanTy = ResTypePtr->getPointeeType();
8124 else if (const MemberPointerType *ResTypeMPtr =
8125 CanTy->getAs<MemberPointerType>())
8126 CanTy = ResTypeMPtr->getPointeeType();
8127 else
8128 done = true;
8129 if (CanTy.isVolatileQualified())
8130 VRQuals.addVolatile();
8131 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8132 return VRQuals;
8133 }
8134 }
8135 }
8136 return VRQuals;
8137}
8138
8139namespace {
8140
8141/// Helper class to manage the addition of builtin operator overload
8142/// candidates. It provides shared state and utility methods used throughout
8143/// the process, as well as a helper method to add each group of builtin
8144/// operator overloads from the standard to a candidate set.
8145class BuiltinOperatorOverloadBuilder {
8146 // Common instance state available to all overload candidate addition methods.
8147 Sema &S;
8148 ArrayRef<Expr *> Args;
8149 Qualifiers VisibleTypeConversionsQuals;
8150 bool HasArithmeticOrEnumeralCandidateType;
8151 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8152 OverloadCandidateSet &CandidateSet;
8153
8154 static constexpr int ArithmeticTypesCap = 24;
8155 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8156
8157 // Define some indices used to iterate over the arithmetic types in
8158 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8159 // types are that preserved by promotion (C++ [over.built]p2).
8160 unsigned FirstIntegralType,
8161 LastIntegralType;
8162 unsigned FirstPromotedIntegralType,
8163 LastPromotedIntegralType;
8164 unsigned FirstPromotedArithmeticType,
8165 LastPromotedArithmeticType;
8166 unsigned NumArithmeticTypes;
8167
8168 void InitArithmeticTypes() {
8169 // Start of promoted types.
8170 FirstPromotedArithmeticType = 0;
8171 ArithmeticTypes.push_back(S.Context.FloatTy);
8172 ArithmeticTypes.push_back(S.Context.DoubleTy);
8173 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8174 if (S.Context.getTargetInfo().hasFloat128Type())
8175 ArithmeticTypes.push_back(S.Context.Float128Ty);
8176
8177 // Start of integral types.
8178 FirstIntegralType = ArithmeticTypes.size();
8179 FirstPromotedIntegralType = ArithmeticTypes.size();
8180 ArithmeticTypes.push_back(S.Context.IntTy);
8181 ArithmeticTypes.push_back(S.Context.LongTy);
8182 ArithmeticTypes.push_back(S.Context.LongLongTy);
8183 if (S.Context.getTargetInfo().hasInt128Type() ||
8184 (S.Context.getAuxTargetInfo() &&
8185 S.Context.getAuxTargetInfo()->hasInt128Type()))
8186 ArithmeticTypes.push_back(S.Context.Int128Ty);
8187 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8188 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8189 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8190 if (S.Context.getTargetInfo().hasInt128Type() ||
8191 (S.Context.getAuxTargetInfo() &&
8192 S.Context.getAuxTargetInfo()->hasInt128Type()))
8193 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8194 LastPromotedIntegralType = ArithmeticTypes.size();
8195 LastPromotedArithmeticType = ArithmeticTypes.size();
8196 // End of promoted types.
8197
8198 ArithmeticTypes.push_back(S.Context.BoolTy);
8199 ArithmeticTypes.push_back(S.Context.CharTy);
8200 ArithmeticTypes.push_back(S.Context.WCharTy);
8201 if (S.Context.getLangOpts().Char8)
8202 ArithmeticTypes.push_back(S.Context.Char8Ty);
8203 ArithmeticTypes.push_back(S.Context.Char16Ty);
8204 ArithmeticTypes.push_back(S.Context.Char32Ty);
8205 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8206 ArithmeticTypes.push_back(S.Context.ShortTy);
8207 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8208 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8209 LastIntegralType = ArithmeticTypes.size();
8210 NumArithmeticTypes = ArithmeticTypes.size();
8211 // End of integral types.
8212 // FIXME: What about complex? What about half?
8213
8214 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast<void> (0))
8215 "Enough inline storage for all arithmetic types.")(static_cast<void> (0));
8216 }
8217
8218 /// Helper method to factor out the common pattern of adding overloads
8219 /// for '++' and '--' builtin operators.
8220 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8221 bool HasVolatile,
8222 bool HasRestrict) {
8223 QualType ParamTypes[2] = {
8224 S.Context.getLValueReferenceType(CandidateTy),
8225 S.Context.IntTy
8226 };
8227
8228 // Non-volatile version.
8229 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8230
8231 // Use a heuristic to reduce number of builtin candidates in the set:
8232 // add volatile version only if there are conversions to a volatile type.
8233 if (HasVolatile) {
8234 ParamTypes[0] =
8235 S.Context.getLValueReferenceType(
8236 S.Context.getVolatileType(CandidateTy));
8237 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8238 }
8239
8240 // Add restrict version only if there are conversions to a restrict type
8241 // and our candidate type is a non-restrict-qualified pointer.
8242 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8243 !CandidateTy.isRestrictQualified()) {
8244 ParamTypes[0]
8245 = S.Context.getLValueReferenceType(
8246 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8247 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8248
8249 if (HasVolatile) {
8250 ParamTypes[0]
8251 = S.Context.getLValueReferenceType(
8252 S.Context.getCVRQualifiedType(CandidateTy,
8253 (Qualifiers::Volatile |
8254 Qualifiers::Restrict)));
8255 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8256 }
8257 }
8258
8259 }
8260
8261 /// Helper to add an overload candidate for a binary builtin with types \p L
8262 /// and \p R.
8263 void AddCandidate(QualType L, QualType R) {
8264 QualType LandR[2] = {L, R};
8265 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8266 }
8267
8268public:
8269 BuiltinOperatorOverloadBuilder(
8270 Sema &S, ArrayRef<Expr *> Args,
8271 Qualifiers VisibleTypeConversionsQuals,
8272 bool HasArithmeticOrEnumeralCandidateType,
8273 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8274 OverloadCandidateSet &CandidateSet)
8275 : S(S), Args(Args),
8276 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8277 HasArithmeticOrEnumeralCandidateType(
8278 HasArithmeticOrEnumeralCandidateType),
8279 CandidateTypes(CandidateTypes),
8280 CandidateSet(CandidateSet) {
8281
8282 InitArithmeticTypes();
8283 }
8284
8285 // Increment is deprecated for bool since C++17.
8286 //
8287 // C++ [over.built]p3:
8288 //
8289 // For every pair (T, VQ), where T is an arithmetic type other
8290 // than bool, and VQ is either volatile or empty, there exist
8291 // candidate operator functions of the form
8292 //
8293 // VQ T& operator++(VQ T&);
8294 // T operator++(VQ T&, int);
8295 //
8296 // C++ [over.built]p4:
8297 //
8298 // For every pair (T, VQ), where T is an arithmetic type other
8299 // than bool, and VQ is either volatile or empty, there exist
8300 // candidate operator functions of the form
8301 //
8302 // VQ T& operator--(VQ T&);
8303 // T operator--(VQ T&, int);
8304 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8305 if (!HasArithmeticOrEnumeralCandidateType)
8306 return;
8307
8308 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8309 const auto TypeOfT = ArithmeticTypes[Arith];
8310 if (TypeOfT == S.Context.BoolTy) {
8311 if (Op == OO_MinusMinus)
8312 continue;
8313 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8314 continue;
8315 }
8316 addPlusPlusMinusMinusStyleOverloads(
8317 TypeOfT,
8318 VisibleTypeConversionsQuals.hasVolatile(),
8319 VisibleTypeConversionsQuals.hasRestrict());
8320 }
8321 }
8322
8323 // C++ [over.built]p5:
8324 //
8325 // For every pair (T, VQ), where T is a cv-qualified or
8326 // cv-unqualified object type, and VQ is either volatile or
8327 // empty, there exist candidate operator functions of the form
8328 //
8329 // T*VQ& operator++(T*VQ&);
8330 // T*VQ& operator--(T*VQ&);
8331 // T* operator++(T*VQ&, int);
8332 // T* operator--(T*VQ&, int);
8333 void addPlusPlusMinusMinusPointerOverloads() {
8334 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8335 // Skip pointer types that aren't pointers to object types.
8336 if (!PtrTy->getPointeeType()->isObjectType())
8337 continue;
8338
8339 addPlusPlusMinusMinusStyleOverloads(
8340 PtrTy,
8341 (!PtrTy.isVolatileQualified() &&
8342 VisibleTypeConversionsQuals.hasVolatile()),
8343 (!PtrTy.isRestrictQualified() &&
8344 VisibleTypeConversionsQuals.hasRestrict()));
8345 }
8346 }
8347
8348 // C++ [over.built]p6:
8349 // For every cv-qualified or cv-unqualified object type T, there
8350 // exist candidate operator functions of the form
8351 //
8352 // T& operator*(T*);
8353 //
8354 // C++ [over.built]p7:
8355 // For every function type T that does not have cv-qualifiers or a
8356 // ref-qualifier, there exist candidate operator functions of the form
8357 // T& operator*(T*);
8358 void addUnaryStarPointerOverloads() {
8359 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8360 QualType PointeeTy = ParamTy->getPointeeType();
8361 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8362 continue;
8363
8364 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8365 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8366 continue;
8367
8368 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8369 }
8370 }
8371
8372 // C++ [over.built]p9:
8373 // For every promoted arithmetic type T, there exist candidate
8374 // operator functions of the form
8375 //
8376 // T operator+(T);
8377 // T operator-(T);
8378 void addUnaryPlusOrMinusArithmeticOverloads() {
8379 if (!HasArithmeticOrEnumeralCandidateType)
8380 return;
8381
8382 for (unsigned Arith = FirstPromotedArithmeticType;
8383 Arith < LastPromotedArithmeticType; ++Arith) {
8384 QualType ArithTy = ArithmeticTypes[Arith];
8385 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8386 }
8387
8388 // Extension: We also add these operators for vector types.
8389 for (QualType VecTy : CandidateTypes[0].vector_types())
8390 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8391 }
8392
8393 // C++ [over.built]p8:
8394 // For every type T, there exist candidate operator functions of
8395 // the form
8396 //
8397 // T* operator+(T*);
8398 void addUnaryPlusPointerOverloads() {
8399 for (QualType ParamTy : CandidateTypes[0].pointer_types())
8400 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8401 }
8402
8403 // C++ [over.built]p10:
8404 // For every promoted integral type T, there exist candidate
8405 // operator functions of the form
8406 //
8407 // T operator~(T);
8408 void addUnaryTildePromotedIntegralOverloads() {
8409 if (!HasArithmeticOrEnumeralCandidateType)
8410 return;
8411
8412 for (unsigned Int = FirstPromotedIntegralType;
8413 Int < LastPromotedIntegralType; ++Int) {
8414 QualType IntTy = ArithmeticTypes[Int];
8415 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8416 }
8417
8418 // Extension: We also add this operator for vector types.
8419 for (QualType VecTy : CandidateTypes[0].vector_types())
8420 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8421 }
8422
8423 // C++ [over.match.oper]p16:
8424 // For every pointer to member type T or type std::nullptr_t, there
8425 // exist candidate operator functions of the form
8426 //
8427 // bool operator==(T,T);
8428 // bool operator!=(T,T);
8429 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8430 /// Set of (canonical) types that we've already handled.
8431 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8432
8433 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8434 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8435 // Don't add the same builtin candidate twice.
8436 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8437 continue;
8438
8439 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8440 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8441 }
8442
8443 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8444 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8445 if (AddedTypes.insert(NullPtrTy).second) {
8446 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8447 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8448 }
8449 }
8450 }
8451 }
8452
8453 // C++ [over.built]p15:
8454 //
8455 // For every T, where T is an enumeration type or a pointer type,
8456 // there exist candidate operator functions of the form
8457 //
8458 // bool operator<(T, T);
8459 // bool operator>(T, T);
8460 // bool operator<=(T, T);
8461 // bool operator>=(T, T);
8462 // bool operator==(T, T);
8463 // bool operator!=(T, T);
8464 // R operator<=>(T, T)
8465 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8466 // C++ [over.match.oper]p3:
8467 // [...]the built-in candidates include all of the candidate operator
8468 // functions defined in 13.6 that, compared to the given operator, [...]
8469 // do not have the same parameter-type-list as any non-template non-member
8470 // candidate.
8471 //
8472 // Note that in practice, this only affects enumeration types because there
8473 // aren't any built-in candidates of record type, and a user-defined operator
8474 // must have an operand of record or enumeration type. Also, the only other
8475 // overloaded operator with enumeration arguments, operator=,
8476 // cannot be overloaded for enumeration types, so this is the only place
8477 // where we must suppress candidates like this.
8478 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8479 UserDefinedBinaryOperators;
8480
8481 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8482 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8483 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8484 CEnd = CandidateSet.end();
8485 C != CEnd; ++C) {
8486 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8487 continue;
8488
8489 if (C->Function->isFunctionTemplateSpecialization())
8490 continue;
8491
8492 // We interpret "same parameter-type-list" as applying to the
8493 // "synthesized candidate, with the order of the two parameters
8494 // reversed", not to the original function.
8495 bool Reversed = C->isReversed();
8496 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8497 ->getType()
8498 .getUnqualifiedType();
8499 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8500 ->getType()
8501 .getUnqualifiedType();
8502
8503 // Skip if either parameter isn't of enumeral type.
8504 if (!FirstParamType->isEnumeralType() ||
8505 !SecondParamType->isEnumeralType())
8506 continue;
8507
8508 // Add this operator to the set of known user-defined operators.
8509 UserDefinedBinaryOperators.insert(
8510 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8511 S.Context.getCanonicalType(SecondParamType)));
8512 }
8513 }
8514 }
8515
8516 /// Set of (canonical) types that we've already handled.
8517 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8518
8519 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8520 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8521 // Don't add the same builtin candidate twice.
8522 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8523 continue;
8524 if (IsSpaceship && PtrTy->isFunctionPointerType())
8525 continue;
8526
8527 QualType ParamTypes[2] = {PtrTy, PtrTy};
8528 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8529 }
8530 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8531 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8532
8533 // Don't add the same builtin candidate twice, or if a user defined
8534 // candidate exists.
8535 if (!AddedTypes.insert(CanonType).second ||
8536 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8537 CanonType)))
8538 continue;
8539 QualType ParamTypes[2] = {EnumTy, EnumTy};
8540 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8541 }
8542 }
8543 }
8544
8545 // C++ [over.built]p13:
8546 //
8547 // For every cv-qualified or cv-unqualified object type T
8548 // there exist candidate operator functions of the form
8549 //
8550 // T* operator+(T*, ptrdiff_t);
8551 // T& operator[](T*, ptrdiff_t); [BELOW]
8552 // T* operator-(T*, ptrdiff_t);
8553 // T* operator+(ptrdiff_t, T*);
8554 // T& operator[](ptrdiff_t, T*); [BELOW]
8555 //
8556 // C++ [over.built]p14:
8557 //
8558 // For every T, where T is a pointer to object type, there
8559 // exist candidate operator functions of the form
8560 //
8561 // ptrdiff_t operator-(T, T);
8562 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8563 /// Set of (canonical) types that we've already handled.
8564 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8565
8566 for (int Arg = 0; Arg < 2; ++Arg) {
8567 QualType AsymmetricParamTypes[2] = {
8568 S.Context.getPointerDiffType(),
8569 S.Context.getPointerDiffType(),
8570 };
8571 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8572 QualType PointeeTy = PtrTy->getPointeeType();
8573 if (!PointeeTy->isObjectType())
8574 continue;
8575
8576 AsymmetricParamTypes[Arg] = PtrTy;
8577 if (Arg == 0 || Op == OO_Plus) {
8578 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8579 // T* operator+(ptrdiff_t, T*);
8580 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8581 }
8582 if (Op == OO_Minus) {
8583 // ptrdiff_t operator-(T, T);
8584 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8585 continue;
8586
8587 QualType ParamTypes[2] = {PtrTy, PtrTy};
8588 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8589 }
8590 }
8591 }
8592 }
8593
8594 // C++ [over.built]p12:
8595 //
8596 // For every pair of promoted arithmetic types L and R, there
8597 // exist candidate operator functions of the form
8598 //
8599 // LR operator*(L, R);
8600 // LR operator/(L, R);
8601 // LR operator+(L, R);
8602 // LR operator-(L, R);
8603 // bool operator<(L, R);
8604 // bool operator>(L, R);
8605 // bool operator<=(L, R);
8606 // bool operator>=(L, R);
8607 // bool operator==(L, R);
8608 // bool operator!=(L, R);
8609 //
8610 // where LR is the result of the usual arithmetic conversions
8611 // between types L and R.
8612 //
8613 // C++ [over.built]p24:
8614 //
8615 // For every pair of promoted arithmetic types L and R, there exist
8616 // candidate operator functions of the form
8617 //
8618 // LR operator?(bool, L, R);
8619 //
8620 // where LR is the result of the usual arithmetic conversions
8621 // between types L and R.
8622 // Our candidates ignore the first parameter.
8623 void addGenericBinaryArithmeticOverloads() {
8624 if (!HasArithmeticOrEnumeralCandidateType)
8625 return;
8626
8627 for (unsigned Left = FirstPromotedArithmeticType;
8628 Left < LastPromotedArithmeticType; ++Left) {
8629 for (unsigned Right = FirstPromotedArithmeticType;
8630 Right < LastPromotedArithmeticType; ++Right) {
8631 QualType LandR[2] = { ArithmeticTypes[Left],
8632 ArithmeticTypes[Right] };
8633 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8634 }
8635 }
8636
8637 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8638 // conditional operator for vector types.
8639 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8640 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8641 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8642 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8643 }
8644 }
8645
8646 /// Add binary operator overloads for each candidate matrix type M1, M2:
8647 /// * (M1, M1) -> M1
8648 /// * (M1, M1.getElementType()) -> M1
8649 /// * (M2.getElementType(), M2) -> M2
8650 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8651 void addMatrixBinaryArithmeticOverloads() {
8652 if (!HasArithmeticOrEnumeralCandidateType)
8653 return;
8654
8655 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8656 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8657 AddCandidate(M1, M1);
8658 }
8659
8660 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8661 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8662 if (!CandidateTypes[0].containsMatrixType(M2))
8663 AddCandidate(M2, M2);
8664 }
8665 }
8666
8667 // C++2a [over.built]p14:
8668 //
8669 // For every integral type T there exists a candidate operator function
8670 // of the form
8671 //
8672 // std::strong_ordering operator<=>(T, T)
8673 //
8674 // C++2a [over.built]p15:
8675 //
8676 // For every pair of floating-point types L and R, there exists a candidate
8677 // operator function of the form
8678 //
8679 // std::partial_ordering operator<=>(L, R);
8680 //
8681 // FIXME: The current specification for integral types doesn't play nice with
8682 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8683 // comparisons. Under the current spec this can lead to ambiguity during
8684 // overload resolution. For example:
8685 //
8686 // enum A : int {a};
8687 // auto x = (a <=> (long)42);
8688 //
8689 // error: call is ambiguous for arguments 'A' and 'long'.
8690 // note: candidate operator<=>(int, int)
8691 // note: candidate operator<=>(long, long)
8692 //
8693 // To avoid this error, this function deviates from the specification and adds
8694 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8695 // arithmetic types (the same as the generic relational overloads).
8696 //
8697 // For now this function acts as a placeholder.
8698 void addThreeWayArithmeticOverloads() {
8699 addGenericBinaryArithmeticOverloads();
8700 }
8701
8702 // C++ [over.built]p17:
8703 //
8704 // For every pair of promoted integral types L and R, there
8705 // exist candidate operator functions of the form
8706 //
8707 // LR operator%(L, R);
8708 // LR operator&(L, R);
8709 // LR operator^(L, R);
8710 // LR operator|(L, R);
8711 // L operator<<(L, R);
8712 // L operator>>(L, R);
8713 //
8714 // where LR is the result of the usual arithmetic conversions
8715 // between types L and R.
8716 void addBinaryBitwiseArithmeticOverloads() {
8717 if (!HasArithmeticOrEnumeralCandidateType)
8718 return;
8719
8720 for (unsigned Left = FirstPromotedIntegralType;
8721 Left < LastPromotedIntegralType; ++Left) {
8722 for (unsigned Right = FirstPromotedIntegralType;
8723 Right < LastPromotedIntegralType; ++Right) {
8724 QualType LandR[2] = { ArithmeticTypes[Left],
8725 ArithmeticTypes[Right] };
8726 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8727 }
8728 }
8729 }
8730
8731 // C++ [over.built]p20:
8732 //
8733 // For every pair (T, VQ), where T is an enumeration or
8734 // pointer to member type and VQ is either volatile or
8735 // empty, there exist candidate operator functions of the form
8736 //
8737 // VQ T& operator=(VQ T&, T);
8738 void addAssignmentMemberPointerOrEnumeralOverloads() {
8739 /// Set of (canonical) types that we've already handled.
8740 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8741
8742 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8743 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8744 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8745 continue;
8746
8747 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8748 }
8749
8750 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8751 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8752 continue;
8753
8754 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8755 }
8756 }
8757 }
8758
8759 // C++ [over.built]p19:
8760 //
8761 // For every pair (T, VQ), where T is any type and VQ is either
8762 // volatile or empty, there exist candidate operator functions
8763 // of the form
8764 //
8765 // T*VQ& operator=(T*VQ&, T*);
8766 //
8767 // C++ [over.built]p21:
8768 //
8769 // For every pair (T, VQ), where T is a cv-qualified or
8770 // cv-unqualified object type and VQ is either volatile or
8771 // empty, there exist candidate operator functions of the form
8772 //
8773 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8774 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8775 void addAssignmentPointerOverloads(bool isEqualOp) {
8776 /// Set of (canonical) types that we've already handled.
8777 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8778
8779 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8780 // If this is operator=, keep track of the builtin candidates we added.
8781 if (isEqualOp)
8782 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8783 else if (!PtrTy->getPointeeType()->isObjectType())
8784 continue;
8785
8786 // non-volatile version
8787 QualType ParamTypes[2] = {
8788 S.Context.getLValueReferenceType(PtrTy),
8789 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8790 };
8791 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8792 /*IsAssignmentOperator=*/ isEqualOp);
8793
8794 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8795 VisibleTypeConversionsQuals.hasVolatile();
8796 if (NeedVolatile) {
8797 // volatile version
8798 ParamTypes[0] =
8799 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8801 /*IsAssignmentOperator=*/isEqualOp);
8802 }
8803
8804 if (!PtrTy.isRestrictQualified() &&
8805 VisibleTypeConversionsQuals.hasRestrict()) {
8806 // restrict version
8807 ParamTypes[0] =
8808 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8809 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8810 /*IsAssignmentOperator=*/isEqualOp);
8811
8812 if (NeedVolatile) {
8813 // volatile restrict version
8814 ParamTypes[0] =
8815 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8816 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8817 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8818 /*IsAssignmentOperator=*/isEqualOp);
8819 }
8820 }
8821 }
8822
8823 if (isEqualOp) {
8824 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8825 // Make sure we don't add the same candidate twice.
8826 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8827 continue;
8828
8829 QualType ParamTypes[2] = {
8830 S.Context.getLValueReferenceType(PtrTy),
8831 PtrTy,
8832 };
8833
8834 // non-volatile version
8835 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8836 /*IsAssignmentOperator=*/true);
8837
8838 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8839 VisibleTypeConversionsQuals.hasVolatile();
8840 if (NeedVolatile) {
8841 // volatile version
8842 ParamTypes[0] = S.Context.getLValueReferenceType(
8843 S.Context.getVolatileType(PtrTy));
8844 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8845 /*IsAssignmentOperator=*/true);
8846 }
8847
8848 if (!PtrTy.isRestrictQualified() &&
8849 VisibleTypeConversionsQuals.hasRestrict()) {
8850 // restrict version
8851 ParamTypes[0] = S.Context.getLValueReferenceType(
8852 S.Context.getRestrictType(PtrTy));
8853 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8854 /*IsAssignmentOperator=*/true);
8855
8856 if (NeedVolatile) {
8857 // volatile restrict version
8858 ParamTypes[0] =
8859 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8860 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8861 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8862 /*IsAssignmentOperator=*/true);
8863 }
8864 }
8865 }
8866 }
8867 }
8868
8869 // C++ [over.built]p18:
8870 //
8871 // For every triple (L, VQ, R), where L is an arithmetic type,
8872 // VQ is either volatile or empty, and R is a promoted
8873 // arithmetic type, there exist candidate operator functions of
8874 // the form
8875 //
8876 // VQ L& operator=(VQ L&, R);
8877 // VQ L& operator*=(VQ L&, R);
8878 // VQ L& operator/=(VQ L&, R);
8879 // VQ L& operator+=(VQ L&, R);
8880 // VQ L& operator-=(VQ L&, R);
8881 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8882 if (!HasArithmeticOrEnumeralCandidateType)
8883 return;
8884
8885 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8886 for (unsigned Right = FirstPromotedArithmeticType;
8887 Right < LastPromotedArithmeticType; ++Right) {
8888 QualType ParamTypes[2];
8889 ParamTypes[1] = ArithmeticTypes[Right];
8890 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8891 S, ArithmeticTypes[Left], Args[0]);
8892 // Add this built-in operator as a candidate (VQ is empty).
8893 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8894 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8895 /*IsAssignmentOperator=*/isEqualOp);
8896
8897 // Add this built-in operator as a candidate (VQ is 'volatile').
8898 if (VisibleTypeConversionsQuals.hasVolatile()) {
8899 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8900 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8901 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8902 /*IsAssignmentOperator=*/isEqualOp);
8903 }
8904 }
8905 }
8906
8907 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8908 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8909 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8910 QualType ParamTypes[2];
8911 ParamTypes[1] = Vec2Ty;
8912 // Add this built-in operator as a candidate (VQ is empty).
8913 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8914 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8915 /*IsAssignmentOperator=*/isEqualOp);
8916
8917 // Add this built-in operator as a candidate (VQ is 'volatile').
8918 if (VisibleTypeConversionsQuals.hasVolatile()) {
8919 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8920 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8922 /*IsAssignmentOperator=*/isEqualOp);
8923 }
8924 }
8925 }
8926
8927 // C++ [over.built]p22:
8928 //
8929 // For every triple (L, VQ, R), where L is an integral type, VQ
8930 // is either volatile or empty, and R is a promoted integral
8931 // type, there exist candidate operator functions of the form
8932 //
8933 // VQ L& operator%=(VQ L&, R);
8934 // VQ L& operator<<=(VQ L&, R);
8935 // VQ L& operator>>=(VQ L&, R);
8936 // VQ L& operator&=(VQ L&, R);
8937 // VQ L& operator^=(VQ L&, R);
8938 // VQ L& operator|=(VQ L&, R);
8939 void addAssignmentIntegralOverloads() {
8940 if (!HasArithmeticOrEnumeralCandidateType)
8941 return;
8942
8943 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8944 for (unsigned Right = FirstPromotedIntegralType;
8945 Right < LastPromotedIntegralType; ++Right) {
8946 QualType ParamTypes[2];
8947 ParamTypes[1] = ArithmeticTypes[Right];
8948 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8949 S, ArithmeticTypes[Left], Args[0]);
8950 // Add this built-in operator as a candidate (VQ is empty).
8951 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8952 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8953 if (VisibleTypeConversionsQuals.hasVolatile()) {
8954 // Add this built-in operator as a candidate (VQ is 'volatile').
8955 ParamTypes[0] = LeftBaseTy;
8956 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8957 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8958 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8959 }
8960 }
8961 }
8962 }
8963
8964 // C++ [over.operator]p23:
8965 //
8966 // There also exist candidate operator functions of the form
8967 //
8968 // bool operator!(bool);
8969 // bool operator&&(bool, bool);
8970 // bool operator||(bool, bool);
8971 void addExclaimOverload() {
8972 QualType ParamTy = S.Context.BoolTy;
8973 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8974 /*IsAssignmentOperator=*/false,
8975 /*NumContextualBoolArguments=*/1);
8976 }
8977 void addAmpAmpOrPipePipeOverload() {
8978 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8979 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8980 /*IsAssignmentOperator=*/false,
8981 /*NumContextualBoolArguments=*/2);
8982 }
8983
8984 // C++ [over.built]p13:
8985 //
8986 // For every cv-qualified or cv-unqualified object type T there
8987 // exist candidate operator functions of the form
8988 //
8989 // T* operator+(T*, ptrdiff_t); [ABOVE]
8990 // T& operator[](T*, ptrdiff_t);
8991 // T* operator-(T*, ptrdiff_t); [ABOVE]
8992 // T* operator+(ptrdiff_t, T*); [ABOVE]
8993 // T& operator[](ptrdiff_t, T*);
8994 void addSubscriptOverloads() {
8995 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8996 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
8997 QualType PointeeType = PtrTy->getPointeeType();
8998 if (!PointeeType->isObjectType())
8999 continue;
9000
9001 // T& operator[](T*, ptrdiff_t)
9002 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9003 }
9004
9005 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9006 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9007 QualType PointeeType = PtrTy->getPointeeType();
9008 if (!PointeeType->isObjectType())
9009 continue;
9010
9011 // T& operator[](ptrdiff_t, T*)
9012 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9013 }
9014 }
9015
9016 // C++ [over.built]p11:
9017 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9018 // C1 is the same type as C2 or is a derived class of C2, T is an object
9019 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9020 // there exist candidate operator functions of the form
9021 //
9022 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9023 //
9024 // where CV12 is the union of CV1 and CV2.
9025 void addArrowStarOverloads() {
9026 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9027 QualType C1Ty = PtrTy;
9028 QualType C1;
9029 QualifierCollector Q1;
9030 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9031 if (!isa<RecordType>(C1))
9032 continue;
9033 // heuristic to reduce number of builtin candidates in the set.
9034 // Add volatile/restrict version only if there are conversions to a
9035 // volatile/restrict type.
9036 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9037 continue;
9038 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9039 continue;
9040 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9041 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9042 QualType C2 = QualType(mptr->getClass(), 0);
9043 C2 = C2.getUnqualifiedType();
9044 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9045 break;
9046 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9047 // build CV12 T&
9048 QualType T = mptr->getPointeeType();
9049 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9050 T.isVolatileQualified())
9051 continue;
9052 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9053 T.isRestrictQualified())
9054 continue;
9055 T = Q1.apply(S.Context, T);
9056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9057 }
9058 }
9059 }
9060
9061 // Note that we don't consider the first argument, since it has been
9062 // contextually converted to bool long ago. The candidates below are
9063 // therefore added as binary.
9064 //
9065 // C++ [over.built]p25:
9066 // For every type T, where T is a pointer, pointer-to-member, or scoped
9067 // enumeration type, there exist candidate operator functions of the form
9068 //
9069 // T operator?(bool, T, T);
9070 //
9071 void addConditionalOperatorOverloads() {
9072 /// Set of (canonical) types that we've already handled.
9073 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9074
9075 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9076 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9077 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9078 continue;
9079
9080 QualType ParamTypes[2] = {PtrTy, PtrTy};
9081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9082 }
9083
9084 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9085 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9086 continue;
9087
9088 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9089 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9090 }
9091
9092 if (S.getLangOpts().CPlusPlus11) {
9093 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9094 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9095 continue;
9096
9097 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9098 continue;
9099
9100 QualType ParamTypes[2] = {EnumTy, EnumTy};
9101 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9102 }
9103 }
9104 }
9105 }
9106};
9107
9108} // end anonymous namespace
9109
9110/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9111/// operator overloads to the candidate set (C++ [over.built]), based
9112/// on the operator @p Op and the arguments given. For example, if the
9113/// operator is a binary '+', this routine might add "int
9114/// operator+(int, int)" to cover integer addition.
9115void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9116 SourceLocation OpLoc,
9117 ArrayRef<Expr *> Args,
9118 OverloadCandidateSet &CandidateSet) {
9119 // Find all of the types that the arguments can convert to, but only
9120 // if the operator we're looking at has built-in operator candidates
9121 // that make use of these types. Also record whether we encounter non-record
9122 // candidate types or either arithmetic or enumeral candidate types.
9123 Qualifiers VisibleTypeConversionsQuals;
9124 VisibleTypeConversionsQuals.addConst();
9125 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9126 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9127
9128 bool HasNonRecordCandidateType = false;
9129 bool HasArithmeticOrEnumeralCandidateType = false;
9130 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9131 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9132 CandidateTypes.emplace_back(*this);
9133 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9134 OpLoc,
9135 true,
9136 (Op == OO_Exclaim ||
9137 Op == OO_AmpAmp ||
9138 Op == OO_PipePipe),
9139 VisibleTypeConversionsQuals);
9140 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9141 CandidateTypes[ArgIdx].hasNonRecordTypes();
9142 HasArithmeticOrEnumeralCandidateType =
9143 HasArithmeticOrEnumeralCandidateType ||
9144 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9145 }
9146
9147 // Exit early when no non-record types have been added to the candidate set
9148 // for any of the arguments to the operator.
9149 //
9150 // We can't exit early for !, ||, or &&, since there we have always have
9151 // 'bool' overloads.
9152 if (!HasNonRecordCandidateType &&
9153 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9154 return;
9155
9156 // Setup an object to manage the common state for building overloads.
9157 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9158 VisibleTypeConversionsQuals,
9159 HasArithmeticOrEnumeralCandidateType,
9160 CandidateTypes, CandidateSet);
9161
9162 // Dispatch over the operation to add in only those overloads which apply.
9163 switch (Op) {
9164 case OO_None:
9165 case NUM_OVERLOADED_OPERATORS:
9166 llvm_unreachable("Expected an overloaded operator")__builtin_unreachable();
9167
9168 case OO_New:
9169 case OO_Delete:
9170 case OO_Array_New:
9171 case OO_Array_Delete:
9172 case OO_Call:
9173 llvm_unreachable(__builtin_unreachable()
9174 "Special operators don't use AddBuiltinOperatorCandidates")__builtin_unreachable();
9175
9176 case OO_Comma:
9177 case OO_Arrow:
9178 case OO_Coawait:
9179 // C++ [over.match.oper]p3:
9180 // -- For the operator ',', the unary operator '&', the
9181 // operator '->', or the operator 'co_await', the
9182 // built-in candidates set is empty.
9183 break;
9184
9185 case OO_Plus: // '+' is either unary or binary
9186 if (Args.size() == 1)
9187 OpBuilder.addUnaryPlusPointerOverloads();
9188 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9189
9190 case OO_Minus: // '-' is either unary or binary
9191 if (Args.size() == 1) {
9192 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9193 } else {
9194 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9195 OpBuilder.addGenericBinaryArithmeticOverloads();
9196 OpBuilder.addMatrixBinaryArithmeticOverloads();
9197 }
9198 break;
9199
9200 case OO_Star: // '*' is either unary or binary
9201 if (Args.size() == 1)
9202 OpBuilder.addUnaryStarPointerOverloads();
9203 else {
9204 OpBuilder.addGenericBinaryArithmeticOverloads();
9205 OpBuilder.addMatrixBinaryArithmeticOverloads();
9206 }
9207 break;
9208
9209 case OO_Slash:
9210 OpBuilder.addGenericBinaryArithmeticOverloads();
9211 break;
9212
9213 case OO_PlusPlus:
9214 case OO_MinusMinus:
9215 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9216 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9217 break;
9218
9219 case OO_EqualEqual:
9220 case OO_ExclaimEqual:
9221 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9222 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9223 OpBuilder.addGenericBinaryArithmeticOverloads();
9224 break;
9225
9226 case OO_Less:
9227 case OO_Greater:
9228 case OO_LessEqual:
9229 case OO_GreaterEqual:
9230 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9231 OpBuilder.addGenericBinaryArithmeticOverloads();
9232 break;
9233
9234 case OO_Spaceship:
9235 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9236 OpBuilder.addThreeWayArithmeticOverloads();
9237 break;
9238
9239 case OO_Percent:
9240 case OO_Caret:
9241 case OO_Pipe:
9242 case OO_LessLess:
9243 case OO_GreaterGreater:
9244 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9245 break;
9246
9247 case OO_Amp: // '&' is either unary or binary
9248 if (Args.size() == 1)
9249 // C++ [over.match.oper]p3:
9250 // -- For the operator ',', the unary operator '&', or the
9251 // operator '->', the built-in candidates set is empty.
9252 break;
9253
9254 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9255 break;
9256
9257 case OO_Tilde:
9258 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9259 break;
9260
9261 case OO_Equal:
9262 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9263 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9264
9265 case OO_PlusEqual:
9266 case OO_MinusEqual:
9267 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9268 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9269
9270 case OO_StarEqual:
9271 case OO_SlashEqual:
9272 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9273 break;
9274
9275 case OO_PercentEqual:
9276 case OO_LessLessEqual:
9277 case OO_GreaterGreaterEqual:
9278 case OO_AmpEqual:
9279 case OO_CaretEqual:
9280 case OO_PipeEqual:
9281 OpBuilder.addAssignmentIntegralOverloads();
9282 break;
9283
9284 case OO_Exclaim:
9285 OpBuilder.addExclaimOverload();
9286 break;
9287
9288 case OO_AmpAmp:
9289 case OO_PipePipe:
9290 OpBuilder.addAmpAmpOrPipePipeOverload();
9291 break;
9292
9293 case OO_Subscript:
9294 OpBuilder.addSubscriptOverloads();
9295 break;
9296
9297 case OO_ArrowStar:
9298 OpBuilder.addArrowStarOverloads();
9299 break;
9300
9301 case OO_Conditional:
9302 OpBuilder.addConditionalOperatorOverloads();
9303 OpBuilder.addGenericBinaryArithmeticOverloads();
9304 break;
9305 }
9306}
9307
9308/// Add function candidates found via argument-dependent lookup
9309/// to the set of overloading candidates.
9310///
9311/// This routine performs argument-dependent name lookup based on the
9312/// given function name (which may also be an operator name) and adds
9313/// all of the overload candidates found by ADL to the overload
9314/// candidate set (C++ [basic.lookup.argdep]).
9315void
9316Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9317 SourceLocation Loc,
9318 ArrayRef<Expr *> Args,
9319 TemplateArgumentListInfo *ExplicitTemplateArgs,
9320 OverloadCandidateSet& CandidateSet,
9321 bool PartialOverloading) {
9322 ADLResult Fns;
9323
9324 // FIXME: This approach for uniquing ADL results (and removing
9325 // redundant candidates from the set) relies on pointer-equality,
9326 // which means we need to key off the canonical decl. However,
9327 // always going back to the canonical decl might not get us the
9328 // right set of default arguments. What default arguments are
9329 // we supposed to consider on ADL candidates, anyway?
9330
9331 // FIXME: Pass in the explicit template arguments?
9332 ArgumentDependentLookup(Name, Loc, Args, Fns);
9333
9334 // Erase all of the candidates we already knew about.
9335 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9336 CandEnd = CandidateSet.end();
9337 Cand != CandEnd; ++Cand)
9338 if (Cand->Function) {
9339 Fns.erase(Cand->Function);
9340 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9341 Fns.erase(FunTmpl);
9342 }
9343
9344 // For each of the ADL candidates we found, add it to the overload
9345 // set.
9346 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9347 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9348
9349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9350 if (ExplicitTemplateArgs)
9351 continue;
9352
9353 AddOverloadCandidate(
9354 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9355 PartialOverloading, /*AllowExplicit=*/true,
9356 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9357 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9358 AddOverloadCandidate(
9359 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9360 /*SuppressUserConversions=*/false, PartialOverloading,
9361 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9362 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9363 }
9364 } else {
9365 auto *FTD = cast<FunctionTemplateDecl>(*I);
9366 AddTemplateOverloadCandidate(
9367 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9368 /*SuppressUserConversions=*/false, PartialOverloading,
9369 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9370 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9371 Context, FTD->getTemplatedDecl())) {
9372 AddTemplateOverloadCandidate(
9373 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9374 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9375 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9376 OverloadCandidateParamOrder::Reversed);
9377 }
9378 }
9379 }
9380}
9381
9382namespace {
9383enum class Comparison { Equal, Better, Worse };
9384}
9385
9386/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9387/// overload resolution.
9388///
9389/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9390/// Cand1's first N enable_if attributes have precisely the same conditions as
9391/// Cand2's first N enable_if attributes (where N = the number of enable_if
9392/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9393///
9394/// Note that you can have a pair of candidates such that Cand1's enable_if
9395/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9396/// worse than Cand1's.
9397static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9398 const FunctionDecl *Cand2) {
9399 // Common case: One (or both) decls don't have enable_if attrs.
9400 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9401 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9402 if (!Cand1Attr || !Cand2Attr) {
9403 if (Cand1Attr == Cand2Attr)
9404 return Comparison::Equal;
9405 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9406 }
9407
9408 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9409 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9410
9411 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9412 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9413 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9414 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9415
9416 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9417 // has fewer enable_if attributes than Cand2, and vice versa.
9418 if (!Cand1A)
9419 return Comparison::Worse;
9420 if (!Cand2A)
9421 return Comparison::Better;
9422
9423 Cand1ID.clear();
9424 Cand2ID.clear();
9425
9426 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9427 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9428 if (Cand1ID != Cand2ID)
9429 return Comparison::Worse;
9430 }
9431
9432 return Comparison::Equal;
9433}
9434
9435static Comparison
9436isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9437 const OverloadCandidate &Cand2) {
9438 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9439 !Cand2.Function->isMultiVersion())
9440 return Comparison::Equal;
9441
9442 // If both are invalid, they are equal. If one of them is invalid, the other
9443 // is better.
9444 if (Cand1.Function->isInvalidDecl()) {
9445 if (Cand2.Function->isInvalidDecl())
9446 return Comparison::Equal;
9447 return Comparison::Worse;
9448 }
9449 if (Cand2.Function->isInvalidDecl())
9450 return Comparison::Better;
9451
9452 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9453 // cpu_dispatch, else arbitrarily based on the identifiers.
9454 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9455 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9456 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9457 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9458
9459 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9460 return Comparison::Equal;
9461
9462 if (Cand1CPUDisp && !Cand2CPUDisp)
9463 return Comparison::Better;
9464 if (Cand2CPUDisp && !Cand1CPUDisp)
9465 return Comparison::Worse;
9466
9467 if (Cand1CPUSpec && Cand2CPUSpec) {
9468 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9469 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9470 ? Comparison::Better
9471 : Comparison::Worse;
9472
9473 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9474 FirstDiff = std::mismatch(
9475 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9476 Cand2CPUSpec->cpus_begin(),
9477 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9478 return LHS->getName() == RHS->getName();
9479 });
9480
9481 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast<void> (0))
9482 "Two different cpu-specific versions should not have the same "(static_cast<void> (0))
9483 "identifier list, otherwise they'd be the same decl!")(static_cast<void> (0));
9484 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9485 ? Comparison::Better
9486 : Comparison::Worse;
9487 }
9488 llvm_unreachable("No way to get here unless both had cpu_dispatch")__builtin_unreachable();
9489}
9490
9491/// Compute the type of the implicit object parameter for the given function,
9492/// if any. Returns None if there is no implicit object parameter, and a null
9493/// QualType if there is a 'matches anything' implicit object parameter.
9494static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9495 const FunctionDecl *F) {
9496 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9497 return llvm::None;
9498
9499 auto *M = cast<CXXMethodDecl>(F);
9500 // Static member functions' object parameters match all types.
9501 if (M->isStatic())
9502 return QualType();
9503
9504 QualType T = M->getThisObjectType();
9505 if (M->getRefQualifier() == RQ_RValue)
9506 return Context.getRValueReferenceType(T);
9507 return Context.getLValueReferenceType(T);
9508}
9509
9510static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9511 const FunctionDecl *F2, unsigned NumParams) {
9512 if (declaresSameEntity(F1, F2))
9513 return true;
9514
9515 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9516 if (First) {
9517 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9518 return *T;
9519 }
9520 assert(I < F->getNumParams())(static_cast<void> (0));
9521 return F->getParamDecl(I++)->getType();
9522 };
9523
9524 unsigned I1 = 0, I2 = 0;
9525 for (unsigned I = 0; I != NumParams; ++I) {
9526 QualType T1 = NextParam(F1, I1, I == 0);
9527 QualType T2 = NextParam(F2, I2, I == 0);
9528 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9529 return false;
9530 }
9531 return true;
9532}
9533
9534/// isBetterOverloadCandidate - Determines whether the first overload
9535/// candidate is a better candidate than the second (C++ 13.3.3p1).
9536bool clang::isBetterOverloadCandidate(
9537 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9538 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9539 // Define viable functions to be better candidates than non-viable
9540 // functions.
9541 if (!Cand2.Viable)
9542 return Cand1.Viable;
9543 else if (!Cand1.Viable)
9544 return false;
9545
9546 // [CUDA] A function with 'never' preference is marked not viable, therefore
9547 // is never shown up here. The worst preference shown up here is 'wrong side',
9548 // e.g. an H function called by a HD function in device compilation. This is
9549 // valid AST as long as the HD function is not emitted, e.g. it is an inline
9550 // function which is called only by an H function. A deferred diagnostic will
9551 // be triggered if it is emitted. However a wrong-sided function is still
9552 // a viable candidate here.
9553 //
9554 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9555 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9556 // can be emitted, Cand1 is not better than Cand2. This rule should have
9557 // precedence over other rules.
9558 //
9559 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9560 // other rules should be used to determine which is better. This is because
9561 // host/device based overloading resolution is mostly for determining
9562 // viability of a function. If two functions are both viable, other factors
9563 // should take precedence in preference, e.g. the standard-defined preferences
9564 // like argument conversion ranks or enable_if partial-ordering. The
9565 // preference for pass-object-size parameters is probably most similar to a
9566 // type-based-overloading decision and so should take priority.
9567 //
9568 // If other rules cannot determine which is better, CUDA preference will be
9569 // used again to determine which is better.
9570 //
9571 // TODO: Currently IdentifyCUDAPreference does not return correct values
9572 // for functions called in global variable initializers due to missing
9573 // correct context about device/host. Therefore we can only enforce this
9574 // rule when there is a caller. We should enforce this rule for functions
9575 // in global variable initializers once proper context is added.
9576 //
9577 // TODO: We can only enable the hostness based overloading resolution when
9578 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9579 // overloading resolution diagnostics.
9580 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9581 S.getLangOpts().GPUExcludeWrongSideOverloads) {
9582 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) {
9583 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9584 bool IsCand1ImplicitHD =
9585 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9586 bool IsCand2ImplicitHD =
9587 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9588 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9589 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9590 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)(static_cast<void> (0));
9591 // The implicit HD function may be a function in a system header which
9592 // is forced by pragma. In device compilation, if we prefer HD candidates
9593 // over wrong-sided candidates, overloading resolution may change, which
9594 // may result in non-deferrable diagnostics. As a workaround, we let
9595 // implicit HD candidates take equal preference as wrong-sided candidates.
9596 // This will preserve the overloading resolution.
9597 // TODO: We still need special handling of implicit HD functions since
9598 // they may incur other diagnostics to be deferred. We should make all
9599 // host/device related diagnostics deferrable and remove special handling
9600 // of implicit HD functions.
9601 auto EmitThreshold =
9602 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9603 (IsCand1ImplicitHD || IsCand2ImplicitHD))
9604 ? Sema::CFP_Never
9605 : Sema::CFP_WrongSide;
9606 auto Cand1Emittable = P1 > EmitThreshold;
9607 auto Cand2Emittable = P2 > EmitThreshold;
9608 if (Cand1Emittable && !Cand2Emittable)
9609 return true;
9610 if (!Cand1Emittable && Cand2Emittable)
9611 return false;
9612 }
9613 }
9614
9615 // C++ [over.match.best]p1:
9616 //
9617 // -- if F is a static member function, ICS1(F) is defined such
9618 // that ICS1(F) is neither better nor worse than ICS1(G) for
9619 // any function G, and, symmetrically, ICS1(G) is neither
9620 // better nor worse than ICS1(F).
9621 unsigned StartArg = 0;
9622 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9623 StartArg = 1;
9624
9625 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9626 // We don't allow incompatible pointer conversions in C++.
9627 if (!S.getLangOpts().CPlusPlus)
9628 return ICS.isStandard() &&
9629 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9630
9631 // The only ill-formed conversion we allow in C++ is the string literal to
9632 // char* conversion, which is only considered ill-formed after C++11.
9633 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9634 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9635 };
9636
9637 // Define functions that don't require ill-formed conversions for a given
9638 // argument to be better candidates than functions that do.
9639 unsigned NumArgs = Cand1.Conversions.size();
9640 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast<void> (0));
9641 bool HasBetterConversion = false;
9642 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9643 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9644 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9645 if (Cand1Bad != Cand2Bad) {
9646 if (Cand1Bad)
9647 return false;
9648 HasBetterConversion = true;
9649 }
9650 }
9651
9652 if (HasBetterConversion)
9653 return true;
9654
9655 // C++ [over.match.best]p1:
9656 // A viable function F1 is defined to be a better function than another
9657 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9658 // conversion sequence than ICSi(F2), and then...
9659 bool HasWorseConversion = false;
9660 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9661 switch (CompareImplicitConversionSequences(S, Loc,
9662 Cand1.Conversions[ArgIdx],
9663 Cand2.Conversions[ArgIdx])) {
9664 case ImplicitConversionSequence::Better:
9665 // Cand1 has a better conversion sequence.
9666 HasBetterConversion = true;
9667 break;
9668
9669 case ImplicitConversionSequence::Worse:
9670 if (Cand1.Function && Cand2.Function &&
9671 Cand1.isReversed() != Cand2.isReversed() &&
9672 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9673 NumArgs)) {
9674 // Work around large-scale breakage caused by considering reversed
9675 // forms of operator== in C++20:
9676 //
9677 // When comparing a function against a reversed function with the same
9678 // parameter types, if we have a better conversion for one argument and
9679 // a worse conversion for the other, the implicit conversion sequences
9680 // are treated as being equally good.
9681 //
9682 // This prevents a comparison function from being considered ambiguous
9683 // with a reversed form that is written in the same way.
9684 //
9685 // We diagnose this as an extension from CreateOverloadedBinOp.
9686 HasWorseConversion = true;
9687 break;
9688 }
9689
9690 // Cand1 can't be better than Cand2.
9691 return false;
9692
9693 case ImplicitConversionSequence::Indistinguishable:
9694 // Do nothing.
9695 break;
9696 }
9697 }
9698
9699 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9700 // ICSj(F2), or, if not that,
9701 if (HasBetterConversion && !HasWorseConversion)
9702 return true;
9703
9704 // -- the context is an initialization by user-defined conversion
9705 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9706 // from the return type of F1 to the destination type (i.e.,
9707 // the type of the entity being initialized) is a better
9708 // conversion sequence than the standard conversion sequence
9709 // from the return type of F2 to the destination type.
9710 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9711 Cand1.Function && Cand2.Function &&
9712 isa<CXXConversionDecl>(Cand1.Function) &&
9713 isa<CXXConversionDecl>(Cand2.Function)) {
9714 // First check whether we prefer one of the conversion functions over the
9715 // other. This only distinguishes the results in non-standard, extension
9716 // cases such as the conversion from a lambda closure type to a function
9717 // pointer or block.
9718 ImplicitConversionSequence::CompareKind Result =
9719 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9720 if (Result == ImplicitConversionSequence::Indistinguishable)
9721 Result = CompareStandardConversionSequences(S, Loc,
9722 Cand1.FinalConversion,
9723 Cand2.FinalConversion);
9724
9725 if (Result != ImplicitConversionSequence::Indistinguishable)
9726 return Result == ImplicitConversionSequence::Better;
9727
9728 // FIXME: Compare kind of reference binding if conversion functions
9729 // convert to a reference type used in direct reference binding, per
9730 // C++14 [over.match.best]p1 section 2 bullet 3.
9731 }
9732
9733 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9734 // as combined with the resolution to CWG issue 243.
9735 //
9736 // When the context is initialization by constructor ([over.match.ctor] or
9737 // either phase of [over.match.list]), a constructor is preferred over
9738 // a conversion function.
9739 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9740 Cand1.Function && Cand2.Function &&
9741 isa<CXXConstructorDecl>(Cand1.Function) !=
9742 isa<CXXConstructorDecl>(Cand2.Function))
9743 return isa<CXXConstructorDecl>(Cand1.Function);
9744
9745 // -- F1 is a non-template function and F2 is a function template
9746 // specialization, or, if not that,
9747 bool Cand1IsSpecialization = Cand1.Function &&
9748 Cand1.Function->getPrimaryTemplate();
9749 bool Cand2IsSpecialization = Cand2.Function &&
9750 Cand2.Function->getPrimaryTemplate();
9751 if (Cand1IsSpecialization != Cand2IsSpecialization)
9752 return Cand2IsSpecialization;
9753
9754 // -- F1 and F2 are function template specializations, and the function
9755 // template for F1 is more specialized than the template for F2
9756 // according to the partial ordering rules described in 14.5.5.2, or,
9757 // if not that,
9758 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9759 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9760 Cand1.Function->getPrimaryTemplate(),
9761 Cand2.Function->getPrimaryTemplate(), Loc,
9762 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9763 : TPOC_Call,
9764 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9765 Cand1.isReversed() ^ Cand2.isReversed()))
9766 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9767 }
9768
9769 // -— F1 and F2 are non-template functions with the same
9770 // parameter-type-lists, and F1 is more constrained than F2 [...],
9771 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9772 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9773 Cand2.Function->hasPrototype()) {
9774 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9775 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9776 if (PT1->getNumParams() == PT2->getNumParams() &&
9777 PT1->isVariadic() == PT2->isVariadic() &&
9778 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9779 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9780 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9781 if (RC1 && RC2) {
9782 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9783 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9784 {RC2}, AtLeastAsConstrained1) ||
9785 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9786 {RC1}, AtLeastAsConstrained2))
9787 return false;
9788 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9789 return AtLeastAsConstrained1;
9790 } else if (RC1 || RC2) {
9791 return RC1 != nullptr;
9792 }
9793 }
9794 }
9795
9796 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9797 // class B of D, and for all arguments the corresponding parameters of
9798 // F1 and F2 have the same type.
9799 // FIXME: Implement the "all parameters have the same type" check.
9800 bool Cand1IsInherited =
9801 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9802 bool Cand2IsInherited =
9803 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9804 if (Cand1IsInherited != Cand2IsInherited)
9805 return Cand2IsInherited;
9806 else if (Cand1IsInherited) {
9807 assert(Cand2IsInherited)(static_cast<void> (0));
9808 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9809 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9810 if (Cand1Class->isDerivedFrom(Cand2Class))
9811 return true;
9812 if (Cand2Class->isDerivedFrom(Cand1Class))
9813 return false;
9814 // Inherited from sibling base classes: still ambiguous.
9815 }
9816
9817 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9818 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9819 // with reversed order of parameters and F1 is not
9820 //
9821 // We rank reversed + different operator as worse than just reversed, but
9822 // that comparison can never happen, because we only consider reversing for
9823 // the maximally-rewritten operator (== or <=>).
9824 if (Cand1.RewriteKind != Cand2.RewriteKind)
9825 return Cand1.RewriteKind < Cand2.RewriteKind;
9826
9827 // Check C++17 tie-breakers for deduction guides.
9828 {
9829 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9830 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9831 if (Guide1 && Guide2) {
9832 // -- F1 is generated from a deduction-guide and F2 is not
9833 if (Guide1->isImplicit() != Guide2->isImplicit())
9834 return Guide2->isImplicit();
9835
9836 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9837 if (Guide1->isCopyDeductionCandidate())
9838 return true;
9839 }
9840 }
9841
9842 // Check for enable_if value-based overload resolution.
9843 if (Cand1.Function && Cand2.Function) {
9844 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9845 if (Cmp != Comparison::Equal)
9846 return Cmp == Comparison::Better;
9847 }
9848
9849 bool HasPS1 = Cand1.Function != nullptr &&
9850 functionHasPassObjectSizeParams(Cand1.Function);
9851 bool HasPS2 = Cand2.Function != nullptr &&
9852 functionHasPassObjectSizeParams(Cand2.Function);
9853 if (HasPS1 != HasPS2 && HasPS1)
9854 return true;
9855
9856 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9857 if (MV == Comparison::Better)
9858 return true;
9859 if (MV == Comparison::Worse)
9860 return false;
9861
9862 // If other rules cannot determine which is better, CUDA preference is used
9863 // to determine which is better.
9864 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9865 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9866 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9867 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9868 }
9869
9870 // General member function overloading is handled above, so this only handles
9871 // constructors with address spaces.
9872 // This only handles address spaces since C++ has no other
9873 // qualifier that can be used with constructors.
9874 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9875 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9876 if (CD1 && CD2) {
9877 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9878 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9879 if (AS1 != AS2) {
9880 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9881 return true;
9882 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9883 return false;
9884 }
9885 }
9886
9887 return false;
9888}
9889
9890/// Determine whether two declarations are "equivalent" for the purposes of
9891/// name lookup and overload resolution. This applies when the same internal/no
9892/// linkage entity is defined by two modules (probably by textually including
9893/// the same header). In such a case, we don't consider the declarations to
9894/// declare the same entity, but we also don't want lookups with both
9895/// declarations visible to be ambiguous in some cases (this happens when using
9896/// a modularized libstdc++).
9897bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9898 const NamedDecl *B) {
9899 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9900 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9901 if (!VA || !VB)
9902 return false;
9903
9904 // The declarations must be declaring the same name as an internal linkage
9905 // entity in different modules.
9906 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9907 VB->getDeclContext()->getRedeclContext()) ||
9908 getOwningModule(VA) == getOwningModule(VB) ||
9909 VA->isExternallyVisible() || VB->isExternallyVisible())
9910 return false;
9911
9912 // Check that the declarations appear to be equivalent.
9913 //
9914 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9915 // For constants and functions, we should check the initializer or body is
9916 // the same. For non-constant variables, we shouldn't allow it at all.
9917 if (Context.hasSameType(VA->getType(), VB->getType()))
9918 return true;
9919
9920 // Enum constants within unnamed enumerations will have different types, but
9921 // may still be similar enough to be interchangeable for our purposes.
9922 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9923 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9924 // Only handle anonymous enums. If the enumerations were named and
9925 // equivalent, they would have been merged to the same type.
9926 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9927 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9928 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9929 !Context.hasSameType(EnumA->getIntegerType(),
9930 EnumB->getIntegerType()))
9931 return false;
9932 // Allow this only if the value is the same for both enumerators.
9933 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9934 }
9935 }
9936
9937 // Nothing else is sufficiently similar.
9938 return false;
9939}
9940
9941void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9942 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9943 assert(D && "Unknown declaration")(static_cast<void> (0));
9944 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9945
9946 Module *M = getOwningModule(D);
9947 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9948 << !M << (M ? M->getFullModuleName() : "");
9949
9950 for (auto *E : Equiv) {
9951 Module *M = getOwningModule(E);
9952 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9953 << !M << (M ? M->getFullModuleName() : "");
9954 }
9955}
9956
9957/// Computes the best viable function (C++ 13.3.3)
9958/// within an overload candidate set.
9959///
9960/// \param Loc The location of the function name (or operator symbol) for
9961/// which overload resolution occurs.
9962///
9963/// \param Best If overload resolution was successful or found a deleted
9964/// function, \p Best points to the candidate function found.
9965///
9966/// \returns The result of overload resolution.
9967OverloadingResult
9968OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9969 iterator &Best) {
9970 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9971 std::transform(begin(), end(), std::back_inserter(Candidates),
9972 [](OverloadCandidate &Cand) { return &Cand; });
9973
9974 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9975 // are accepted by both clang and NVCC. However, during a particular
9976 // compilation mode only one call variant is viable. We need to
9977 // exclude non-viable overload candidates from consideration based
9978 // only on their host/device attributes. Specifically, if one
9979 // candidate call is WrongSide and the other is SameSide, we ignore
9980 // the WrongSide candidate.
9981 // We only need to remove wrong-sided candidates here if
9982 // -fgpu-exclude-wrong-side-overloads is off. When
9983 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
9984 // uniformly in isBetterOverloadCandidate.
9985 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
9986 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9987 bool ContainsSameSideCandidate =
9988 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9989 // Check viable function only.
9990 return Cand->Viable && Cand->Function &&
9991 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9992 Sema::CFP_SameSide;
9993 });
9994 if (ContainsSameSideCandidate) {
9995 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9996 // Check viable function only to avoid unnecessary data copying/moving.
9997 return Cand->Viable && Cand->Function &&
9998 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9999 Sema::CFP_WrongSide;
10000 };
10001 llvm::erase_if(Candidates, IsWrongSideCandidate);
10002 }
10003 }
10004
10005 // Find the best viable function.
10006 Best = end();
10007 for (auto *Cand : Candidates) {
10008 Cand->Best = false;
10009 if (Cand->Viable)
10010 if (Best == end() ||
10011 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10012 Best = Cand;
10013 }
10014
10015 // If we didn't find any viable functions, abort.
10016 if (Best == end())
10017 return OR_No_Viable_Function;
10018
10019 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10020
10021 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10022 PendingBest.push_back(&*Best);
10023 Best->Best = true;
10024
10025 // Make sure that this function is better than every other viable
10026 // function. If not, we have an ambiguity.
10027 while (!PendingBest.empty()) {
10028 auto *Curr = PendingBest.pop_back_val();
10029 for (auto *Cand : Candidates) {
10030 if (Cand->Viable && !Cand->Best &&
10031 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10032 PendingBest.push_back(Cand);
10033 Cand->Best = true;
10034
10035 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10036 Curr->Function))
10037 EquivalentCands.push_back(Cand->Function);
10038 else
10039 Best = end();
10040 }
10041 }
10042 }
10043
10044 // If we found more than one best candidate, this is ambiguous.
10045 if (Best == end())
10046 return OR_Ambiguous;
10047
10048 // Best is the best viable function.
10049 if (Best->Function && Best->Function->isDeleted())
10050 return OR_Deleted;
10051
10052 if (!EquivalentCands.empty())
10053 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10054 EquivalentCands);
10055
10056 return OR_Success;
10057}
10058
10059namespace {
10060
10061enum OverloadCandidateKind {
10062 oc_function,
10063 oc_method,
10064 oc_reversed_binary_operator,
10065 oc_constructor,
10066 oc_implicit_default_constructor,
10067 oc_implicit_copy_constructor,
10068 oc_implicit_move_constructor,
10069 oc_implicit_copy_assignment,
10070 oc_implicit_move_assignment,
10071 oc_implicit_equality_comparison,
10072 oc_inherited_constructor
10073};
10074
10075enum OverloadCandidateSelect {
10076 ocs_non_template,
10077 ocs_template,
10078 ocs_described_template,
10079};
10080
10081static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10082ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10083 OverloadCandidateRewriteKind CRK,
10084 std::string &Description) {
10085
10086 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10087 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10088 isTemplate = true;
10089 Description = S.getTemplateArgumentBindingsText(
10090 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10091 }
10092
10093 OverloadCandidateSelect Select = [&]() {
10094 if (!Description.empty())
10095 return ocs_described_template;
10096 return isTemplate ? ocs_template : ocs_non_template;
10097 }();
10098
10099 OverloadCandidateKind Kind = [&]() {
10100 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10101 return oc_implicit_equality_comparison;
10102
10103 if (CRK & CRK_Reversed)
10104 return oc_reversed_binary_operator;
10105
10106 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10107 if (!Ctor->isImplicit()) {
10108 if (isa<ConstructorUsingShadowDecl>(Found))
10109 return oc_inherited_constructor;
10110 else
10111 return oc_constructor;
10112 }
10113
10114 if (Ctor->isDefaultConstructor())
10115 return oc_implicit_default_constructor;
10116
10117 if (Ctor->isMoveConstructor())
10118 return oc_implicit_move_constructor;
10119
10120 assert(Ctor->isCopyConstructor() &&(static_cast<void> (0))
10121 "unexpected sort of implicit constructor")(static_cast<void> (0));
10122 return oc_implicit_copy_constructor;
10123 }
10124
10125 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10126 // This actually gets spelled 'candidate function' for now, but
10127 // it doesn't hurt to split it out.
10128 if (!Meth->isImplicit())
10129 return oc_method;
10130
10131 if (Meth->isMoveAssignmentOperator())
10132 return oc_implicit_move_assignment;
10133
10134 if (Meth->isCopyAssignmentOperator())
10135 return oc_implicit_copy_assignment;
10136
10137 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast<void> (0));
10138 return oc_method;
10139 }
10140
10141 return oc_function;
10142 }();
10143
10144 return std::make_pair(Kind, Select);
10145}
10146
10147void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10148 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10149 // set.
10150 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10151 S.Diag(FoundDecl->getLocation(),
10152 diag::note_ovl_candidate_inherited_constructor)
10153 << Shadow->getNominatedBaseClass();
10154}
10155
10156} // end anonymous namespace
10157
10158static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10159 const FunctionDecl *FD) {
10160 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10161 bool AlwaysTrue;
10162 if (EnableIf->getCond()->isValueDependent() ||
10163 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10164 return false;
10165 if (!AlwaysTrue)
10166 return false;
10167 }
10168 return true;
10169}
10170
10171/// Returns true if we can take the address of the function.
10172///
10173/// \param Complain - If true, we'll emit a diagnostic
10174/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10175/// we in overload resolution?
10176/// \param Loc - The location of the statement we're complaining about. Ignored
10177/// if we're not complaining, or if we're in overload resolution.
10178static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10179 bool Complain,
10180 bool InOverloadResolution,
10181 SourceLocation Loc) {
10182 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10183 if (Complain) {
10184 if (InOverloadResolution)
10185 S.Diag(FD->getBeginLoc(),
10186 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10187 else
10188 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10189 }
10190 return false;
10191 }
10192
10193 if (FD->getTrailingRequiresClause()) {
10194 ConstraintSatisfaction Satisfaction;
10195 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10196 return false;
10197 if (!Satisfaction.IsSatisfied) {
10198 if (Complain) {
10199 if (InOverloadResolution)
10200 S.Diag(FD->getBeginLoc(),
10201 diag::note_ovl_candidate_unsatisfied_constraints);
10202 else
10203 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10204 << FD;
10205 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10206 }
10207 return false;
10208 }
10209 }
10210
10211 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10212 return P->hasAttr<PassObjectSizeAttr>();
10213 });
10214 if (I == FD->param_end())
10215 return true;
10216
10217 if (Complain) {
10218 // Add one to ParamNo because it's user-facing
10219 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10220 if (InOverloadResolution)
10221 S.Diag(FD->getLocation(),
10222 diag::note_ovl_candidate_has_pass_object_size_params)
10223 << ParamNo;
10224 else
10225 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10226 << FD << ParamNo;
10227 }
10228 return false;
10229}
10230
10231static bool checkAddressOfCandidateIsAvailable(Sema &S,
10232 const FunctionDecl *FD) {
10233 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10234 /*InOverloadResolution=*/true,
10235 /*Loc=*/SourceLocation());
10236}
10237
10238bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10239 bool Complain,
10240 SourceLocation Loc) {
10241 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10242 /*InOverloadResolution=*/false,
10243 Loc);
10244}
10245
10246// Don't print candidates other than the one that matches the calling
10247// convention of the call operator, since that is guaranteed to exist.
10248static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10249 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10250
10251 if (!ConvD)
10252 return false;
10253 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10254 if (!RD->isLambda())
10255 return false;
10256
10257 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10258 CallingConv CallOpCC =
10259 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10260 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10261 CallingConv ConvToCC =
10262 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10263
10264 return ConvToCC != CallOpCC;
10265}
10266
10267// Notes the location of an overload candidate.
10268void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10269 OverloadCandidateRewriteKind RewriteKind,
10270 QualType DestType, bool TakingAddress) {
10271 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10272 return;
10273 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10274 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10275 return;
10276 if (shouldSkipNotingLambdaConversionDecl(Fn))
10277 return;
10278
10279 std::string FnDesc;
10280 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10281 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10282 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10283 << (unsigned)KSPair.first << (unsigned)KSPair.second
10284 << Fn << FnDesc;
10285
10286 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10287 Diag(Fn->getLocation(), PD);
10288 MaybeEmitInheritedConstructorNote(*this, Found);
10289}
10290
10291static void
10292MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10293 // Perhaps the ambiguity was caused by two atomic constraints that are
10294 // 'identical' but not equivalent:
10295 //
10296 // void foo() requires (sizeof(T) > 4) { } // #1
10297 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10298 //
10299 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10300 // #2 to subsume #1, but these constraint are not considered equivalent
10301 // according to the subsumption rules because they are not the same
10302 // source-level construct. This behavior is quite confusing and we should try
10303 // to help the user figure out what happened.
10304
10305 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10306 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10307 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10308 if (!I->Function)
10309 continue;
10310 SmallVector<const Expr *, 3> AC;
10311 if (auto *Template = I->Function->getPrimaryTemplate())
10312 Template->getAssociatedConstraints(AC);
10313 else
10314 I->Function->getAssociatedConstraints(AC);
10315 if (AC.empty())
10316 continue;
10317 if (FirstCand == nullptr) {
10318 FirstCand = I->Function;
10319 FirstAC = AC;
10320 } else if (SecondCand == nullptr) {
10321 SecondCand = I->Function;
10322 SecondAC = AC;
10323 } else {
10324 // We have more than one pair of constrained functions - this check is
10325 // expensive and we'd rather not try to diagnose it.
10326 return;
10327 }
10328 }
10329 if (!SecondCand)
10330 return;
10331 // The diagnostic can only happen if there are associated constraints on
10332 // both sides (there needs to be some identical atomic constraint).
10333 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10334 SecondCand, SecondAC))
10335 // Just show the user one diagnostic, they'll probably figure it out
10336 // from here.
10337 return;
10338}
10339
10340// Notes the location of all overload candidates designated through
10341// OverloadedExpr
10342void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10343 bool TakingAddress) {
10344 assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast<void> (0));
10345
10346 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10347 OverloadExpr *OvlExpr = Ovl.Expression;
10348
10349 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10350 IEnd = OvlExpr->decls_end();
10351 I != IEnd; ++I) {
10352 if (FunctionTemplateDecl *FunTmpl =
10353 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10354 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10355 TakingAddress);
10356 } else if (FunctionDecl *Fun
10357 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10358 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10359 }
10360 }
10361}
10362
10363/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10364/// "lead" diagnostic; it will be given two arguments, the source and
10365/// target types of the conversion.
10366void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10367 Sema &S,
10368 SourceLocation CaretLoc,
10369 const PartialDiagnostic &PDiag) const {
10370 S.Diag(CaretLoc, PDiag)
10371 << Ambiguous.getFromType() << Ambiguous.getToType();
10372 unsigned CandsShown = 0;
10373 AmbiguousConversionSequence::const_iterator I, E;
10374 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10375 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10376 break;
10377 ++CandsShown;
10378 S.NoteOverloadCandidate(I->first, I->second);
10379 }
10380 S.Diags.overloadCandidatesShown(CandsShown);
10381 if (I != E)
10382 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10383}
10384
10385static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10386 unsigned I, bool TakingCandidateAddress) {
10387 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10388 assert(Conv.isBad())(static_cast<void> (0));
10389 assert(Cand->Function && "for now, candidate must be a function")(static_cast<void> (0));
10390 FunctionDecl *Fn = Cand->Function;
10391
10392 // There's a conversion slot for the object argument if this is a
10393 // non-constructor method. Note that 'I' corresponds the
10394 // conversion-slot index.
10395 bool isObjectArgument = false;
10396 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10397 if (I == 0)
10398 isObjectArgument = true;
10399 else
10400 I--;
10401 }
10402
10403 std::string FnDesc;
10404 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10405 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10406 FnDesc);
10407
10408 Expr *FromExpr = Conv.Bad.FromExpr;
10409 QualType FromTy = Conv.Bad.getFromType();
10410 QualType ToTy = Conv.Bad.getToType();
10411
10412 if (FromTy == S.Context.OverloadTy) {
10413 assert(FromExpr && "overload set argument came from implicit argument?")(static_cast<void> (0));
10414 Expr *E = FromExpr->IgnoreParens();
10415 if (isa<UnaryOperator>(E))
10416 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10417 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10418
10419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10420 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10421 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10422 << Name << I + 1;
10423 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10424 return;
10425 }
10426
10427 // Do some hand-waving analysis to see if the non-viability is due
10428 // to a qualifier mismatch.
10429 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10430 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10431 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10432 CToTy = RT->getPointeeType();
10433 else {
10434 // TODO: detect and diagnose the full richness of const mismatches.
10435 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10436 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10437 CFromTy = FromPT->getPointeeType();
10438 CToTy = ToPT->getPointeeType();
10439 }
10440 }
10441
10442 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10443 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10444 Qualifiers FromQs = CFromTy.getQualifiers();
10445 Qualifiers ToQs = CToTy.getQualifiers();
10446
10447 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10448 if (isObjectArgument)
10449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10450 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10451 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10452 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10453 else
10454 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10455 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10456 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10457 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10458 << ToTy->isReferenceType() << I + 1;
10459 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10460 return;
10461 }
10462
10463 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10465 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10467 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10468 << (unsigned)isObjectArgument << I + 1;
10469 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10470 return;
10471 }
10472
10473 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10474 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10475 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10476 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10477 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10478 << (unsigned)isObjectArgument << I + 1;
10479 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10480 return;
10481 }
10482
10483 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10485 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10486 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10487 << FromQs.hasUnaligned() << I + 1;
10488 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10489 return;
10490 }
10491
10492 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10493 assert(CVR && "expected qualifiers mismatch")(static_cast<void> (0));
10494
10495 if (isObjectArgument) {
10496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10497 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10498 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10499 << (CVR - 1);
10500 } else {
10501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10502 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10503 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10504 << (CVR - 1) << I + 1;
10505 }
10506 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10507 return;
10508 }
10509
10510 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10511 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10514 << (unsigned)isObjectArgument << I + 1
10515 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10516 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10517 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10518 return;
10519 }
10520
10521 // Special diagnostic for failure to convert an initializer list, since
10522 // telling the user that it has type void is not useful.
10523 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10524 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10525 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10526 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10527 << ToTy << (unsigned)isObjectArgument << I + 1;
10528 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10529 return;
10530 }
10531
10532 // Diagnose references or pointers to incomplete types differently,
10533 // since it's far from impossible that the incompleteness triggered
10534 // the failure.
10535 QualType TempFromTy = FromTy.getNonReferenceType();
10536 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10537 TempFromTy = PTy->getPointeeType();
10538 if (TempFromTy->isIncompleteType()) {
10539 // Emit the generic diagnostic and, optionally, add the hints to it.
10540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10541 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10542 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10543 << ToTy << (unsigned)isObjectArgument << I + 1
10544 << (unsigned)(Cand->Fix.Kind);
10545
10546 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10547 return;
10548 }
10549
10550 // Diagnose base -> derived pointer conversions.
10551 unsigned BaseToDerivedConversion = 0;
10552 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10553 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10554 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10555 FromPtrTy->getPointeeType()) &&
10556 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10557 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10558 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10559 FromPtrTy->getPointeeType()))
10560 BaseToDerivedConversion = 1;
10561 }
10562 } else if (const ObjCObjectPointerType *FromPtrTy
10563 = FromTy->getAs<ObjCObjectPointerType>()) {
10564 if (const ObjCObjectPointerType *ToPtrTy
10565 = ToTy->getAs<ObjCObjectPointerType>())
10566 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10567 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10568 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10569 FromPtrTy->getPointeeType()) &&
10570 FromIface->isSuperClassOf(ToIface))
10571 BaseToDerivedConversion = 2;
10572 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10573 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10574 !FromTy->isIncompleteType() &&
10575 !ToRefTy->getPointeeType()->isIncompleteType() &&
10576 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10577 BaseToDerivedConversion = 3;
10578 }
10579 }
10580
10581 if (BaseToDerivedConversion) {
10582 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10583 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10584 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10585 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10586 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10587 return;
10588 }
10589
10590 if (isa<ObjCObjectPointerType>(CFromTy) &&
10591 isa<PointerType>(CToTy)) {
10592 Qualifiers FromQs = CFromTy.getQualifiers();
10593 Qualifiers ToQs = CToTy.getQualifiers();
10594 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10596 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10597 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10598 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10599 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10600 return;
10601 }
10602 }
10603
10604 if (TakingCandidateAddress &&
10605 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10606 return;
10607
10608 // Emit the generic diagnostic and, optionally, add the hints to it.
10609 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10610 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10611 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10612 << ToTy << (unsigned)isObjectArgument << I + 1
10613 << (unsigned)(Cand->Fix.Kind);
10614
10615 // If we can fix the conversion, suggest the FixIts.
10616 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10617 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10618 FDiag << *HI;
10619 S.Diag(Fn->getLocation(), FDiag);
10620
10621 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10622}
10623
10624/// Additional arity mismatch diagnosis specific to a function overload
10625/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10626/// over a candidate in any candidate set.
10627static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10628 unsigned NumArgs) {
10629 FunctionDecl *Fn = Cand->Function;
10630 unsigned MinParams = Fn->getMinRequiredArguments();
10631
10632 // With invalid overloaded operators, it's possible that we think we
10633 // have an arity mismatch when in fact it looks like we have the
10634 // right number of arguments, because only overloaded operators have
10635 // the weird behavior of overloading member and non-member functions.
10636 // Just don't report anything.
10637 if (Fn->isInvalidDecl() &&
10638 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10639 return true;
10640
10641 if (NumArgs < MinParams) {
10642 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast<void> (0))
10643 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast<void> (0))
10644 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast<void> (0));
10645 } else {
10646 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast<void> (0))
10647 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast<void> (0))
10648 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast<void> (0));
10649 }
10650
10651 return false;
10652}
10653
10654/// General arity mismatch diagnosis over a candidate in a candidate set.
10655static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10656 unsigned NumFormalArgs) {
10657 assert(isa<FunctionDecl>(D) &&(static_cast<void> (0))
10658 "The templated declaration should at least be a function"(static_cast<void> (0))
10659 " when diagnosing bad template argument deduction due to too many"(static_cast<void> (0))
10660 " or too few arguments")(static_cast<void> (0));
10661
10662 FunctionDecl *Fn = cast<FunctionDecl>(D);
10663
10664 // TODO: treat calls to a missing default constructor as a special case
10665 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10666 unsigned MinParams = Fn->getMinRequiredArguments();
10667
10668 // at least / at most / exactly
10669 unsigned mode, modeCount;
10670 if (NumFormalArgs < MinParams) {
10671 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10672 FnTy->isTemplateVariadic())
10673 mode = 0; // "at least"
10674 else
10675 mode = 2; // "exactly"
10676 modeCount = MinParams;
10677 } else {
10678 if (MinParams != FnTy->getNumParams())
10679 mode = 1; // "at most"
10680 else
10681 mode = 2; // "exactly"
10682 modeCount = FnTy->getNumParams();
10683 }
10684
10685 std::string Description;
10686 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10687 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10688
10689 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10690 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10691 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10692 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10693 else
10694 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10695 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10696 << Description << mode << modeCount << NumFormalArgs;
10697
10698 MaybeEmitInheritedConstructorNote(S, Found);
10699}
10700
10701/// Arity mismatch diagnosis specific to a function overload candidate.
10702static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10703 unsigned NumFormalArgs) {
10704 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10705 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10706}
10707
10708static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10709 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10710 return TD;
10711 llvm_unreachable("Unsupported: Getting the described template declaration"__builtin_unreachable()
10712 " for bad deduction diagnosis")__builtin_unreachable();
10713}
10714
10715/// Diagnose a failed template-argument deduction.
10716static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10717 DeductionFailureInfo &DeductionFailure,
10718 unsigned NumArgs,
10719 bool TakingCandidateAddress) {
10720 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10721 NamedDecl *ParamD;
10722 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10723 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10724 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10725 switch (DeductionFailure.Result) {
10726 case Sema::TDK_Success:
10727 llvm_unreachable("TDK_success while diagnosing bad deduction")__builtin_unreachable();
10728
10729 case Sema::TDK_Incomplete: {
10730 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast<void> (0));
10731 S.Diag(Templated->getLocation(),
10732 diag::note_ovl_candidate_incomplete_deduction)
10733 << ParamD->getDeclName();
10734 MaybeEmitInheritedConstructorNote(S, Found);
10735 return;
10736 }
10737
10738 case Sema::TDK_IncompletePack: {
10739 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast<void> (0));
10740 S.Diag(Templated->getLocation(),
10741 diag::note_ovl_candidate_incomplete_deduction_pack)
10742 << ParamD->getDeclName()
10743 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10744 << *DeductionFailure.getFirstArg();
10745 MaybeEmitInheritedConstructorNote(S, Found);
10746 return;
10747 }
10748
10749 case Sema::TDK_Underqualified: {
10750 assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast<void> (0));
10751 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10752
10753 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10754
10755 // Param will have been canonicalized, but it should just be a
10756 // qualified version of ParamD, so move the qualifiers to that.
10757 QualifierCollector Qs;
10758 Qs.strip(Param);
10759 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10760 assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast<void> (0));
10761
10762 // Arg has also been canonicalized, but there's nothing we can do
10763 // about that. It also doesn't matter as much, because it won't
10764 // have any template parameters in it (because deduction isn't
10765 // done on dependent types).
10766 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10767
10768 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10769 << ParamD->getDeclName() << Arg << NonCanonParam;
10770 MaybeEmitInheritedConstructorNote(S, Found);
10771 return;
10772 }
10773
10774 case Sema::TDK_Inconsistent: {
10775 assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast<void> (0));
10776 int which = 0;
10777 if (isa<TemplateTypeParmDecl>(ParamD))
10778 which = 0;
10779 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10780 // Deduction might have failed because we deduced arguments of two
10781 // different types for a non-type template parameter.
10782 // FIXME: Use a different TDK value for this.
10783 QualType T1 =
10784 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10785 QualType T2 =
10786 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10787 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10788 S.Diag(Templated->getLocation(),
10789 diag::note_ovl_candidate_inconsistent_deduction_types)
10790 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10791 << *DeductionFailure.getSecondArg() << T2;
10792 MaybeEmitInheritedConstructorNote(S, Found);
10793 return;
10794 }
10795
10796 which = 1;
10797 } else {
10798 which = 2;
10799 }
10800
10801 // Tweak the diagnostic if the problem is that we deduced packs of
10802 // different arities. We'll print the actual packs anyway in case that
10803 // includes additional useful information.
10804 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10805 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10806 DeductionFailure.getFirstArg()->pack_size() !=
10807 DeductionFailure.getSecondArg()->pack_size()) {
10808 which = 3;
10809 }
10810
10811 S.Diag(Templated->getLocation(),
10812 diag::note_ovl_candidate_inconsistent_deduction)
10813 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10814 << *DeductionFailure.getSecondArg();
10815 MaybeEmitInheritedConstructorNote(S, Found);
10816 return;
10817 }
10818
10819 case Sema::TDK_InvalidExplicitArguments:
10820 assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast<void> (0));
10821 if (ParamD->getDeclName())
10822 S.Diag(Templated->getLocation(),
10823 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10824 << ParamD->getDeclName();
10825 else {
10826 int index = 0;
10827 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10828 index = TTP->getIndex();
10829 else if (NonTypeTemplateParmDecl *NTTP
10830 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10831 index = NTTP->getIndex();
10832 else
10833 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10834 S.Diag(Templated->getLocation(),
10835 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10836 << (index + 1);
10837 }
10838 MaybeEmitInheritedConstructorNote(S, Found);
10839 return;
10840
10841 case Sema::TDK_ConstraintsNotSatisfied: {
10842 // Format the template argument list into the argument string.
10843 SmallString<128> TemplateArgString;
10844 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10845 TemplateArgString = " ";
10846 TemplateArgString += S.getTemplateArgumentBindingsText(
10847 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10848 if (TemplateArgString.size() == 1)
10849 TemplateArgString.clear();
10850 S.Diag(Templated->getLocation(),
10851 diag::note_ovl_candidate_unsatisfied_constraints)
10852 << TemplateArgString;
10853
10854 S.DiagnoseUnsatisfiedConstraint(
10855 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10856 return;
10857 }
10858 case Sema::TDK_TooManyArguments:
10859 case Sema::TDK_TooFewArguments:
10860 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10861 return;
10862
10863 case Sema::TDK_InstantiationDepth:
10864 S.Diag(Templated->getLocation(),
10865 diag::note_ovl_candidate_instantiation_depth);
10866 MaybeEmitInheritedConstructorNote(S, Found);
10867 return;
10868
10869 case Sema::TDK_SubstitutionFailure: {
10870 // Format the template argument list into the argument string.
10871 SmallString<128> TemplateArgString;
10872 if (TemplateArgumentList *Args =
10873 DeductionFailure.getTemplateArgumentList()) {
10874 TemplateArgString = " ";
10875 TemplateArgString += S.getTemplateArgumentBindingsText(
10876 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10877 if (TemplateArgString.size() == 1)
10878 TemplateArgString.clear();
10879 }
10880
10881 // If this candidate was disabled by enable_if, say so.
10882 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10883 if (PDiag && PDiag->second.getDiagID() ==
10884 diag::err_typename_nested_not_found_enable_if) {
10885 // FIXME: Use the source range of the condition, and the fully-qualified
10886 // name of the enable_if template. These are both present in PDiag.
10887 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10888 << "'enable_if'" << TemplateArgString;
10889 return;
10890 }
10891
10892 // We found a specific requirement that disabled the enable_if.
10893 if (PDiag && PDiag->second.getDiagID() ==
10894 diag::err_typename_nested_not_found_requirement) {
10895 S.Diag(Templated->getLocation(),
10896 diag::note_ovl_candidate_disabled_by_requirement)
10897 << PDiag->second.getStringArg(0) << TemplateArgString;
10898 return;
10899 }
10900
10901 // Format the SFINAE diagnostic into the argument string.
10902 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10903 // formatted message in another diagnostic.
10904 SmallString<128> SFINAEArgString;
10905 SourceRange R;
10906 if (PDiag) {
10907 SFINAEArgString = ": ";
10908 R = SourceRange(PDiag->first, PDiag->first);
10909 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10910 }
10911
10912 S.Diag(Templated->getLocation(),
10913 diag::note_ovl_candidate_substitution_failure)
10914 << TemplateArgString << SFINAEArgString << R;
10915 MaybeEmitInheritedConstructorNote(S, Found);
10916 return;
10917 }
10918
10919 case Sema::TDK_DeducedMismatch:
10920 case Sema::TDK_DeducedMismatchNested: {
10921 // Format the template argument list into the argument string.
10922 SmallString<128> TemplateArgString;
10923 if (TemplateArgumentList *Args =
10924 DeductionFailure.getTemplateArgumentList()) {
10925 TemplateArgString = " ";
10926 TemplateArgString += S.getTemplateArgumentBindingsText(
10927 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10928 if (TemplateArgString.size() == 1)
10929 TemplateArgString.clear();
10930 }
10931
10932 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10933 << (*DeductionFailure.getCallArgIndex() + 1)
10934 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10935 << TemplateArgString
10936 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10937 break;
10938 }
10939
10940 case Sema::TDK_NonDeducedMismatch: {
10941 // FIXME: Provide a source location to indicate what we couldn't match.
10942 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10943 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10944 if (FirstTA.getKind() == TemplateArgument::Template &&
10945 SecondTA.getKind() == TemplateArgument::Template) {
10946 TemplateName FirstTN = FirstTA.getAsTemplate();
10947 TemplateName SecondTN = SecondTA.getAsTemplate();
10948 if (FirstTN.getKind() == TemplateName::Template &&
10949 SecondTN.getKind() == TemplateName::Template) {
10950 if (FirstTN.getAsTemplateDecl()->getName() ==
10951 SecondTN.getAsTemplateDecl()->getName()) {
10952 // FIXME: This fixes a bad diagnostic where both templates are named
10953 // the same. This particular case is a bit difficult since:
10954 // 1) It is passed as a string to the diagnostic printer.
10955 // 2) The diagnostic printer only attempts to find a better
10956 // name for types, not decls.
10957 // Ideally, this should folded into the diagnostic printer.
10958 S.Diag(Templated->getLocation(),
10959 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10960 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10961 return;
10962 }
10963 }
10964 }
10965
10966 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10967 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10968 return;
10969
10970 // FIXME: For generic lambda parameters, check if the function is a lambda
10971 // call operator, and if so, emit a prettier and more informative
10972 // diagnostic that mentions 'auto' and lambda in addition to
10973 // (or instead of?) the canonical template type parameters.
10974 S.Diag(Templated->getLocation(),
10975 diag::note_ovl_candidate_non_deduced_mismatch)
10976 << FirstTA << SecondTA;
10977 return;
10978 }
10979 // TODO: diagnose these individually, then kill off
10980 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10981 case Sema::TDK_MiscellaneousDeductionFailure:
10982 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10983 MaybeEmitInheritedConstructorNote(S, Found);
10984 return;
10985 case Sema::TDK_CUDATargetMismatch:
10986 S.Diag(Templated->getLocation(),
10987 diag::note_cuda_ovl_candidate_target_mismatch);
10988 return;
10989 }
10990}
10991
10992/// Diagnose a failed template-argument deduction, for function calls.
10993static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10994 unsigned NumArgs,
10995 bool TakingCandidateAddress) {
10996 unsigned TDK = Cand->DeductionFailure.Result;
10997 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10998 if (CheckArityMismatch(S, Cand, NumArgs))
10999 return;
11000 }
11001 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11002 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11003}
11004
11005/// CUDA: diagnose an invalid call across targets.
11006static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11007 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
11008 FunctionDecl *Callee = Cand->Function;
11009
11010 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11011 CalleeTarget = S.IdentifyCUDATarget(Callee);
11012
11013 std::string FnDesc;
11014 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11015 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11016 Cand->getRewriteKind(), FnDesc);
11017
11018 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11019 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11020 << FnDesc /* Ignored */
11021 << CalleeTarget << CallerTarget;
11022
11023 // This could be an implicit constructor for which we could not infer the
11024 // target due to a collsion. Diagnose that case.
11025 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11026 if (Meth != nullptr && Meth->isImplicit()) {
11027 CXXRecordDecl *ParentClass = Meth->getParent();
11028 Sema::CXXSpecialMember CSM;
11029
11030 switch (FnKindPair.first) {
11031 default:
11032 return;
11033 case oc_implicit_default_constructor:
11034 CSM = Sema::CXXDefaultConstructor;
11035 break;
11036 case oc_implicit_copy_constructor:
11037 CSM = Sema::CXXCopyConstructor;
11038 break;
11039 case oc_implicit_move_constructor:
11040 CSM = Sema::CXXMoveConstructor;
11041 break;
11042 case oc_implicit_copy_assignment:
11043 CSM = Sema::CXXCopyAssignment;
11044 break;
11045 case oc_implicit_move_assignment:
11046 CSM = Sema::CXXMoveAssignment;
11047 break;
11048 };
11049
11050 bool ConstRHS = false;
11051 if (Meth->getNumParams()) {
11052 if (const ReferenceType *RT =
11053 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11054 ConstRHS = RT->getPointeeType().isConstQualified();
11055 }
11056 }
11057
11058 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11059 /* ConstRHS */ ConstRHS,
11060 /* Diagnose */ true);
11061 }
11062}
11063
11064static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11065 FunctionDecl *Callee = Cand->Function;
11066 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11067
11068 S.Diag(Callee->getLocation(),
11069 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11070 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11071}
11072
11073static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11074 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11075 assert(ES.isExplicit() && "not an explicit candidate")(static_cast<void> (0));
11076
11077 unsigned Kind;
11078 switch (Cand->Function->getDeclKind()) {
11079 case Decl::Kind::CXXConstructor:
11080 Kind = 0;
11081 break;
11082 case Decl::Kind::CXXConversion:
11083 Kind = 1;
11084 break;
11085 case Decl::Kind::CXXDeductionGuide:
11086 Kind = Cand->Function->isImplicit() ? 0 : 2;
11087 break;
11088 default:
11089 llvm_unreachable("invalid Decl")__builtin_unreachable();
11090 }
11091
11092 // Note the location of the first (in-class) declaration; a redeclaration
11093 // (particularly an out-of-class definition) will typically lack the
11094 // 'explicit' specifier.
11095 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11096 FunctionDecl *First = Cand->Function->getFirstDecl();
11097 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11098 First = Pattern->getFirstDecl();
11099
11100 S.Diag(First->getLocation(),
11101 diag::note_ovl_candidate_explicit)
11102 << Kind << (ES.getExpr() ? 1 : 0)
11103 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11104}
11105
11106/// Generates a 'note' diagnostic for an overload candidate. We've
11107/// already generated a primary error at the call site.
11108///
11109/// It really does need to be a single diagnostic with its caret
11110/// pointed at the candidate declaration. Yes, this creates some
11111/// major challenges of technical writing. Yes, this makes pointing
11112/// out problems with specific arguments quite awkward. It's still
11113/// better than generating twenty screens of text for every failed
11114/// overload.
11115///
11116/// It would be great to be able to express per-candidate problems
11117/// more richly for those diagnostic clients that cared, but we'd
11118/// still have to be just as careful with the default diagnostics.
11119/// \param CtorDestAS Addr space of object being constructed (for ctor
11120/// candidates only).
11121static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11122 unsigned NumArgs,
11123 bool TakingCandidateAddress,
11124 LangAS CtorDestAS = LangAS::Default) {
11125 FunctionDecl *Fn = Cand->Function;
11126 if (shouldSkipNotingLambdaConversionDecl(Fn))
11127 return;
11128
11129 // Note deleted candidates, but only if they're viable.
11130 if (Cand->Viable) {
11131 if (Fn->isDeleted()) {
11132 std::string FnDesc;
11133 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11134 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11135 Cand->getRewriteKind(), FnDesc);
11136
11137 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11138 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11139 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11140 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11141 return;
11142 }
11143
11144 // We don't really have anything else to say about viable candidates.
11145 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11146 return;
11147 }
11148
11149 switch (Cand->FailureKind) {
11150 case ovl_fail_too_many_arguments:
11151 case ovl_fail_too_few_arguments:
11152 return DiagnoseArityMismatch(S, Cand, NumArgs);
11153
11154 case ovl_fail_bad_deduction:
11155 return DiagnoseBadDeduction(S, Cand, NumArgs,
11156 TakingCandidateAddress);
11157
11158 case ovl_fail_illegal_constructor: {
11159 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11160 << (Fn->getPrimaryTemplate() ? 1 : 0);
11161 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11162 return;
11163 }
11164
11165 case ovl_fail_object_addrspace_mismatch: {
11166 Qualifiers QualsForPrinting;
11167 QualsForPrinting.setAddressSpace(CtorDestAS);
11168 S.Diag(Fn->getLocation(),
11169 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11170 << QualsForPrinting;
11171 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11172 return;
11173 }
11174
11175 case ovl_fail_trivial_conversion:
11176 case ovl_fail_bad_final_conversion:
11177 case ovl_fail_final_conversion_not_exact:
11178 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11179
11180 case ovl_fail_bad_conversion: {
11181 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11182 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11183 if (Cand->Conversions[I].isBad())
11184 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11185
11186 // FIXME: this currently happens when we're called from SemaInit
11187 // when user-conversion overload fails. Figure out how to handle
11188 // those conditions and diagnose them well.
11189 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11190 }
11191
11192 case ovl_fail_bad_target:
11193 return DiagnoseBadTarget(S, Cand);
11194
11195 case ovl_fail_enable_if:
11196 return DiagnoseFailedEnableIfAttr(S, Cand);
11197
11198 case ovl_fail_explicit:
11199 return DiagnoseFailedExplicitSpec(S, Cand);
11200
11201 case ovl_fail_inhctor_slice:
11202 // It's generally not interesting to note copy/move constructors here.
11203 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11204 return;
11205 S.Diag(Fn->getLocation(),
11206 diag::note_ovl_candidate_inherited_constructor_slice)
11207 << (Fn->getPrimaryTemplate() ? 1 : 0)
11208 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11209 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11210 return;
11211
11212 case ovl_fail_addr_not_available: {
11213 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11214 (void)Available;
11215 assert(!Available)(static_cast<void> (0));
11216 break;
11217 }
11218 case ovl_non_default_multiversion_function:
11219 // Do nothing, these should simply be ignored.
11220 break;
11221
11222 case ovl_fail_constraints_not_satisfied: {
11223 std::string FnDesc;
11224 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11225 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11226 Cand->getRewriteKind(), FnDesc);
11227
11228 S.Diag(Fn->getLocation(),
11229 diag::note_ovl_candidate_constraints_not_satisfied)
11230 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11231 << FnDesc /* Ignored */;
11232 ConstraintSatisfaction Satisfaction;
11233 if (S.CheckFunctionConstraints(Fn, Satisfaction))
11234 break;
11235 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11236 }
11237 }
11238}
11239
11240static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11241 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11242 return;
11243
11244 // Desugar the type of the surrogate down to a function type,
11245 // retaining as many typedefs as possible while still showing
11246 // the function type (and, therefore, its parameter types).
11247 QualType FnType = Cand->Surrogate->getConversionType();
11248 bool isLValueReference = false;
11249 bool isRValueReference = false;
11250 bool isPointer = false;
11251 if (const LValueReferenceType *FnTypeRef =
11252 FnType->getAs<LValueReferenceType>()) {
11253 FnType = FnTypeRef->getPointeeType();
11254 isLValueReference = true;
11255 } else if (const RValueReferenceType *FnTypeRef =
11256 FnType->getAs<RValueReferenceType>()) {
11257 FnType = FnTypeRef->getPointeeType();
11258 isRValueReference = true;
11259 }
11260 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11261 FnType = FnTypePtr->getPointeeType();
11262 isPointer = true;
11263 }
11264 // Desugar down to a function type.
11265 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11266 // Reconstruct the pointer/reference as appropriate.
11267 if (isPointer) FnType = S.Context.getPointerType(FnType);
11268 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11269 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11270
11271 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11272 << FnType;
11273}
11274
11275static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11276 SourceLocation OpLoc,
11277 OverloadCandidate *Cand) {
11278 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast<void> (0));
11279 std::string TypeStr("operator");
11280 TypeStr += Opc;
11281 TypeStr += "(";
11282 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11283 if (Cand->Conversions.size() == 1) {
11284 TypeStr += ")";
11285 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11286 } else {
11287 TypeStr += ", ";
11288 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11289 TypeStr += ")";
11290 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11291 }
11292}
11293
11294static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11295 OverloadCandidate *Cand) {
11296 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11297 if (ICS.isBad()) break; // all meaningless after first invalid
11298 if (!ICS.isAmbiguous()) continue;
11299
11300 ICS.DiagnoseAmbiguousConversion(
11301 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11302 }
11303}
11304
11305static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11306 if (Cand->Function)
11307 return Cand->Function->getLocation();
11308 if (Cand->IsSurrogate)
11309 return Cand->Surrogate->getLocation();
11310 return SourceLocation();
11311}
11312
11313static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11314 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11315 case Sema::TDK_Success:
11316 case Sema::TDK_NonDependentConversionFailure:
11317 llvm_unreachable("non-deduction failure while diagnosing bad deduction")__builtin_unreachable();
11318
11319 case Sema::TDK_Invalid:
11320 case Sema::TDK_Incomplete:
11321 case Sema::TDK_IncompletePack:
11322 return 1;
11323
11324 case Sema::TDK_Underqualified:
11325 case Sema::TDK_Inconsistent:
11326 return 2;
11327
11328 case Sema::TDK_SubstitutionFailure:
11329 case Sema::TDK_DeducedMismatch:
11330 case Sema::TDK_ConstraintsNotSatisfied:
11331 case Sema::TDK_DeducedMismatchNested:
11332 case Sema::TDK_NonDeducedMismatch:
11333 case Sema::TDK_MiscellaneousDeductionFailure:
11334 case Sema::TDK_CUDATargetMismatch:
11335 return 3;
11336
11337 case Sema::TDK_InstantiationDepth:
11338 return 4;
11339
11340 case Sema::TDK_InvalidExplicitArguments:
11341 return 5;
11342
11343 case Sema::TDK_TooManyArguments:
11344 case Sema::TDK_TooFewArguments:
11345 return 6;
11346 }
11347 llvm_unreachable("Unhandled deduction result")__builtin_unreachable();
11348}
11349
11350namespace {
11351struct CompareOverloadCandidatesForDisplay {
11352 Sema &S;
11353 SourceLocation Loc;
11354 size_t NumArgs;
11355 OverloadCandidateSet::CandidateSetKind CSK;
11356
11357 CompareOverloadCandidatesForDisplay(
11358 Sema &S, SourceLocation Loc, size_t NArgs,
11359 OverloadCandidateSet::CandidateSetKind CSK)
11360 : S(S), NumArgs(NArgs), CSK(CSK) {}
11361
11362 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11363 // If there are too many or too few arguments, that's the high-order bit we
11364 // want to sort by, even if the immediate failure kind was something else.
11365 if (C->FailureKind == ovl_fail_too_many_arguments ||
11366 C->FailureKind == ovl_fail_too_few_arguments)
11367 return static_cast<OverloadFailureKind>(C->FailureKind);
11368
11369 if (C->Function) {
11370 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11371 return ovl_fail_too_many_arguments;
11372 if (NumArgs < C->Function->getMinRequiredArguments())
11373 return ovl_fail_too_few_arguments;
11374 }
11375
11376 return static_cast<OverloadFailureKind>(C->FailureKind);
11377 }
11378
11379 bool operator()(const OverloadCandidate *L,
11380 const OverloadCandidate *R) {
11381 // Fast-path this check.
11382 if (L == R) return false;
11383
11384 // Order first by viability.
11385 if (L->Viable) {
11386 if (!R->Viable) return true;
11387
11388 // TODO: introduce a tri-valued comparison for overload
11389 // candidates. Would be more worthwhile if we had a sort
11390 // that could exploit it.
11391 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11392 return true;
11393 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11394 return false;
11395 } else if (R->Viable)
11396 return false;
11397
11398 assert(L->Viable == R->Viable)(static_cast<void> (0));
11399
11400 // Criteria by which we can sort non-viable candidates:
11401 if (!L->Viable) {
11402 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11403 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11404
11405 // 1. Arity mismatches come after other candidates.
11406 if (LFailureKind == ovl_fail_too_many_arguments ||
11407 LFailureKind == ovl_fail_too_few_arguments) {
11408 if (RFailureKind == ovl_fail_too_many_arguments ||
11409 RFailureKind == ovl_fail_too_few_arguments) {
11410 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11411 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11412 if (LDist == RDist) {
11413 if (LFailureKind == RFailureKind)
11414 // Sort non-surrogates before surrogates.
11415 return !L->IsSurrogate && R->IsSurrogate;
11416 // Sort candidates requiring fewer parameters than there were
11417 // arguments given after candidates requiring more parameters
11418 // than there were arguments given.
11419 return LFailureKind == ovl_fail_too_many_arguments;
11420 }
11421 return LDist < RDist;
11422 }
11423 return false;
11424 }
11425 if (RFailureKind == ovl_fail_too_many_arguments ||
11426 RFailureKind == ovl_fail_too_few_arguments)
11427 return true;
11428
11429 // 2. Bad conversions come first and are ordered by the number
11430 // of bad conversions and quality of good conversions.
11431 if (LFailureKind == ovl_fail_bad_conversion) {
11432 if (RFailureKind != ovl_fail_bad_conversion)
11433 return true;
11434
11435 // The conversion that can be fixed with a smaller number of changes,
11436 // comes first.
11437 unsigned numLFixes = L->Fix.NumConversionsFixed;
11438 unsigned numRFixes = R->Fix.NumConversionsFixed;
11439 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11440 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11441 if (numLFixes != numRFixes) {
11442 return numLFixes < numRFixes;
11443 }
11444
11445 // If there's any ordering between the defined conversions...
11446 // FIXME: this might not be transitive.
11447 assert(L->Conversions.size() == R->Conversions.size())(static_cast<void> (0));
11448
11449 int leftBetter = 0;
11450 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11451 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11452 switch (CompareImplicitConversionSequences(S, Loc,
11453 L->Conversions[I],
11454 R->Conversions[I])) {
11455 case ImplicitConversionSequence::Better:
11456 leftBetter++;
11457 break;
11458
11459 case ImplicitConversionSequence::Worse:
11460 leftBetter--;
11461 break;
11462
11463 case ImplicitConversionSequence::Indistinguishable:
11464 break;
11465 }
11466 }
11467 if (leftBetter > 0) return true;
11468 if (leftBetter < 0) return false;
11469
11470 } else if (RFailureKind == ovl_fail_bad_conversion)
11471 return false;
11472
11473 if (LFailureKind == ovl_fail_bad_deduction) {
11474 if (RFailureKind != ovl_fail_bad_deduction)
11475 return true;
11476
11477 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11478 return RankDeductionFailure(L->DeductionFailure)
11479 < RankDeductionFailure(R->DeductionFailure);
11480 } else if (RFailureKind == ovl_fail_bad_deduction)
11481 return false;
11482
11483 // TODO: others?
11484 }
11485
11486 // Sort everything else by location.
11487 SourceLocation LLoc = GetLocationForCandidate(L);
11488 SourceLocation RLoc = GetLocationForCandidate(R);
11489
11490 // Put candidates without locations (e.g. builtins) at the end.
11491 if (LLoc.isInvalid()) return false;
11492 if (RLoc.isInvalid()) return true;
11493
11494 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11495 }
11496};
11497}
11498
11499/// CompleteNonViableCandidate - Normally, overload resolution only
11500/// computes up to the first bad conversion. Produces the FixIt set if
11501/// possible.
11502static void
11503CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11504 ArrayRef<Expr *> Args,
11505 OverloadCandidateSet::CandidateSetKind CSK) {
11506 assert(!Cand->Viable)(static_cast<void> (0));
11507
11508 // Don't do anything on failures other than bad conversion.
11509 if (Cand->FailureKind != ovl_fail_bad_conversion)
11510 return;
11511
11512 // We only want the FixIts if all the arguments can be corrected.
11513 bool Unfixable = false;
11514 // Use a implicit copy initialization to check conversion fixes.
11515 Cand->Fix.setConversionChecker(TryCopyInitialization);
11516
11517 // Attempt to fix the bad conversion.
11518 unsigned ConvCount = Cand->Conversions.size();
11519 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11520 ++ConvIdx) {
11521 assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast<void> (0));
11522 if (Cand->Conversions[ConvIdx].isInitialized() &&
11523 Cand->Conversions[ConvIdx].isBad()) {
11524 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11525 break;
11526 }
11527 }
11528
11529 // FIXME: this should probably be preserved from the overload
11530 // operation somehow.
11531 bool SuppressUserConversions = false;
11532
11533 unsigned ConvIdx = 0;
11534 unsigned ArgIdx = 0;
11535 ArrayRef<QualType> ParamTypes;
11536 bool Reversed = Cand->isReversed();
11537
11538 if (Cand->IsSurrogate) {
11539 QualType ConvType
11540 = Cand->Surrogate->getConversionType().getNonReferenceType();
11541 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11542 ConvType = ConvPtrType->getPointeeType();
11543 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11544 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11545 ConvIdx = 1;
11546 } else if (Cand->Function) {
11547 ParamTypes =
11548 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11549 if (isa<CXXMethodDecl>(Cand->Function) &&
11550 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11551 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11552 ConvIdx = 1;
11553 if (CSK == OverloadCandidateSet::CSK_Operator &&
11554 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11555 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11556 ArgIdx = 1;
11557 }
11558 } else {
11559 // Builtin operator.
11560 assert(ConvCount <= 3)(static_cast<void> (0));
11561 ParamTypes = Cand->BuiltinParamTypes;
11562 }
11563
11564 // Fill in the rest of the conversions.
11565 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11566 ConvIdx != ConvCount;
11567 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11568 assert(ArgIdx < Args.size() && "no argument for this arg conversion")(static_cast<void> (0));
11569 if (Cand->Conversions[ConvIdx].isInitialized()) {
11570 // We've already checked this conversion.
11571 } else if (ParamIdx < ParamTypes.size()) {
11572 if (ParamTypes[ParamIdx]->isDependentType())
11573 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11574 Args[ArgIdx]->getType());
11575 else {
11576 Cand->Conversions[ConvIdx] =
11577 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11578 SuppressUserConversions,
11579 /*InOverloadResolution=*/true,
11580 /*AllowObjCWritebackConversion=*/
11581 S.getLangOpts().ObjCAutoRefCount);
11582 // Store the FixIt in the candidate if it exists.
11583 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11584 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11585 }
11586 } else
11587 Cand->Conversions[ConvIdx].setEllipsis();
11588 }
11589}
11590
11591SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11592 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11593 SourceLocation OpLoc,
11594 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11595 // Sort the candidates by viability and position. Sorting directly would
11596 // be prohibitive, so we make a set of pointers and sort those.
11597 SmallVector<OverloadCandidate*, 32> Cands;
11598 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11599 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11600 if (!Filter(*Cand))
11601 continue;
11602 switch (OCD) {
11603 case OCD_AllCandidates:
11604 if (!Cand->Viable) {
11605 if (!Cand->Function && !Cand->IsSurrogate) {
11606 // This a non-viable builtin candidate. We do not, in general,
11607 // want to list every possible builtin candidate.
11608 continue;
11609 }
11610 CompleteNonViableCandidate(S, Cand, Args, Kind);
11611 }
11612 break;
11613
11614 case OCD_ViableCandidates:
11615 if (!Cand->Viable)
11616 continue;
11617 break;
11618
11619 case OCD_AmbiguousCandidates:
11620 if (!Cand->Best)
11621 continue;
11622 break;
11623 }
11624
11625 Cands.push_back(Cand);
11626 }
11627
11628 llvm::stable_sort(
11629 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11630
11631 return Cands;
11632}
11633
11634bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11635 SourceLocation OpLoc) {
11636 bool DeferHint = false;
11637 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11638 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11639 // host device candidates.
11640 auto WrongSidedCands =
11641 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11642 return (Cand.Viable == false &&
11643 Cand.FailureKind == ovl_fail_bad_target) ||
11644 (Cand.Function &&
11645 Cand.Function->template hasAttr<CUDAHostAttr>() &&
11646 Cand.Function->template hasAttr<CUDADeviceAttr>());
11647 });
11648 DeferHint = !WrongSidedCands.empty();
11649 }
11650 return DeferHint;
11651}
11652
11653/// When overload resolution fails, prints diagnostic messages containing the
11654/// candidates in the candidate set.
11655void OverloadCandidateSet::NoteCandidates(
11656 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11657 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11658 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11659
11660 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11661
11662 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11663
11664 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11665
11666 if (OCD == OCD_AmbiguousCandidates)
11667 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11668}
11669
11670void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11671 ArrayRef<OverloadCandidate *> Cands,
11672 StringRef Opc, SourceLocation OpLoc) {
11673 bool ReportedAmbiguousConversions = false;
11674
11675 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11676 unsigned CandsShown = 0;
11677 auto I = Cands.begin(), E = Cands.end();
11678 for (; I != E; ++I) {
11679 OverloadCandidate *Cand = *I;
11680
11681 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11682 ShowOverloads == Ovl_Best) {
11683 break;
11684 }
11685 ++CandsShown;
11686
11687 if (Cand->Function)
11688 NoteFunctionCandidate(S, Cand, Args.size(),
11689 /*TakingCandidateAddress=*/false, DestAS);
11690 else if (Cand->IsSurrogate)
11691 NoteSurrogateCandidate(S, Cand);
11692 else {
11693 assert(Cand->Viable &&(static_cast<void> (0))
11694 "Non-viable built-in candidates are not added to Cands.")(static_cast<void> (0));
11695 // Generally we only see ambiguities including viable builtin
11696 // operators if overload resolution got screwed up by an
11697 // ambiguous user-defined conversion.
11698 //
11699 // FIXME: It's quite possible for different conversions to see
11700 // different ambiguities, though.
11701 if (!ReportedAmbiguousConversions) {
11702 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11703 ReportedAmbiguousConversions = true;
11704 }
11705
11706 // If this is a viable builtin, print it.
11707 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11708 }
11709 }
11710
11711 // Inform S.Diags that we've shown an overload set with N elements. This may
11712 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11713 S.Diags.overloadCandidatesShown(CandsShown);
11714
11715 if (I != E)
11716 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11717 shouldDeferDiags(S, Args, OpLoc))
11718 << int(E - I);
11719}
11720
11721static SourceLocation
11722GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11723 return Cand->Specialization ? Cand->Specialization->getLocation()
11724 : SourceLocation();
11725}
11726
11727namespace {
11728struct CompareTemplateSpecCandidatesForDisplay {
11729 Sema &S;
11730 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11731
11732 bool operator()(const TemplateSpecCandidate *L,
11733 const TemplateSpecCandidate *R) {
11734 // Fast-path this check.
11735 if (L == R)
11736 return false;
11737
11738 // Assuming that both candidates are not matches...
11739
11740 // Sort by the ranking of deduction failures.
11741 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11742 return RankDeductionFailure(L->DeductionFailure) <
11743 RankDeductionFailure(R->DeductionFailure);
11744
11745 // Sort everything else by location.
11746 SourceLocation LLoc = GetLocationForCandidate(L);
11747 SourceLocation RLoc = GetLocationForCandidate(R);
11748
11749 // Put candidates without locations (e.g. builtins) at the end.
11750 if (LLoc.isInvalid())
11751 return false;
11752 if (RLoc.isInvalid())
11753 return true;
11754
11755 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11756 }
11757};
11758}
11759
11760/// Diagnose a template argument deduction failure.
11761/// We are treating these failures as overload failures due to bad
11762/// deductions.
11763void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11764 bool ForTakingAddress) {
11765 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11766 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11767}
11768
11769void TemplateSpecCandidateSet::destroyCandidates() {
11770 for (iterator i = begin(), e = end(); i != e; ++i) {
11771 i->DeductionFailure.Destroy();
11772 }
11773}
11774
11775void TemplateSpecCandidateSet::clear() {
11776 destroyCandidates();
11777 Candidates.clear();
11778}
11779
11780/// NoteCandidates - When no template specialization match is found, prints
11781/// diagnostic messages containing the non-matching specializations that form
11782/// the candidate set.
11783/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11784/// OCD == OCD_AllCandidates and Cand->Viable == false.
11785void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11786 // Sort the candidates by position (assuming no candidate is a match).
11787 // Sorting directly would be prohibitive, so we make a set of pointers
11788 // and sort those.
11789 SmallVector<TemplateSpecCandidate *, 32> Cands;
11790 Cands.reserve(size());
11791 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11792 if (Cand->Specialization)
11793 Cands.push_back(Cand);
11794 // Otherwise, this is a non-matching builtin candidate. We do not,
11795 // in general, want to list every possible builtin candidate.
11796 }
11797
11798 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11799
11800 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11801 // for generalization purposes (?).
11802 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11803
11804 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11805 unsigned CandsShown = 0;
11806 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11807 TemplateSpecCandidate *Cand = *I;
11808
11809 // Set an arbitrary limit on the number of candidates we'll spam
11810 // the user with. FIXME: This limit should depend on details of the
11811 // candidate list.
11812 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11813 break;
11814 ++CandsShown;
11815
11816 assert(Cand->Specialization &&(static_cast<void> (0))
11817 "Non-matching built-in candidates are not added to Cands.")(static_cast<void> (0));
11818 Cand->NoteDeductionFailure(S, ForTakingAddress);
11819 }
11820
11821 if (I != E)
11822 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11823}
11824
11825// [PossiblyAFunctionType] --> [Return]
11826// NonFunctionType --> NonFunctionType
11827// R (A) --> R(A)
11828// R (*)(A) --> R (A)
11829// R (&)(A) --> R (A)
11830// R (S::*)(A) --> R (A)
11831QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11832 QualType Ret = PossiblyAFunctionType;
11833 if (const PointerType *ToTypePtr =
11834 PossiblyAFunctionType->getAs<PointerType>())
11835 Ret = ToTypePtr->getPointeeType();
11836 else if (const ReferenceType *ToTypeRef =
11837 PossiblyAFunctionType->getAs<ReferenceType>())
11838 Ret = ToTypeRef->getPointeeType();
11839 else if (const MemberPointerType *MemTypePtr =
11840 PossiblyAFunctionType->getAs<MemberPointerType>())
11841 Ret = MemTypePtr->getPointeeType();
11842 Ret =
11843 Context.getCanonicalType(Ret).getUnqualifiedType();
11844 return Ret;
11845}
11846
11847static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11848 bool Complain = true) {
11849 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11850 S.DeduceReturnType(FD, Loc, Complain))
11851 return true;
11852
11853 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11854 if (S.getLangOpts().CPlusPlus17 &&
11855 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11856 !S.ResolveExceptionSpec(Loc, FPT))
11857 return true;
11858
11859 return false;
11860}
11861
11862namespace {
11863// A helper class to help with address of function resolution
11864// - allows us to avoid passing around all those ugly parameters
11865class AddressOfFunctionResolver {
11866 Sema& S;
11867 Expr* SourceExpr;
11868 const QualType& TargetType;
11869 QualType TargetFunctionType; // Extracted function type from target type
11870
11871 bool Complain;
11872 //DeclAccessPair& ResultFunctionAccessPair;
11873 ASTContext& Context;
11874
11875 bool TargetTypeIsNonStaticMemberFunction;
11876 bool FoundNonTemplateFunction;
11877 bool StaticMemberFunctionFromBoundPointer;
11878 bool HasComplained;
11879
11880 OverloadExpr::FindResult OvlExprInfo;
11881 OverloadExpr *OvlExpr;
11882 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11883 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11884 TemplateSpecCandidateSet FailedCandidates;
11885
11886public:
11887 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11888 const QualType &TargetType, bool Complain)
11889 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11890 Complain(Complain), Context(S.getASTContext()),
11891 TargetTypeIsNonStaticMemberFunction(
11892 !!TargetType->getAs<MemberPointerType>()),
11893 FoundNonTemplateFunction(false),
11894 StaticMemberFunctionFromBoundPointer(false),
11895 HasComplained(false),
11896 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11897 OvlExpr(OvlExprInfo.Expression),
11898 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11899 ExtractUnqualifiedFunctionTypeFromTargetType();
11900
11901 if (TargetFunctionType->isFunctionType()) {
11902 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11903 if (!UME->isImplicitAccess() &&
11904 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11905 StaticMemberFunctionFromBoundPointer = true;
11906 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11907 DeclAccessPair dap;
11908 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11909 OvlExpr, false, &dap)) {
11910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11911 if (!Method->isStatic()) {
11912 // If the target type is a non-function type and the function found
11913 // is a non-static member function, pretend as if that was the
11914 // target, it's the only possible type to end up with.
11915 TargetTypeIsNonStaticMemberFunction = true;
11916
11917 // And skip adding the function if its not in the proper form.
11918 // We'll diagnose this due to an empty set of functions.
11919 if (!OvlExprInfo.HasFormOfMemberPointer)
11920 return;
11921 }
11922
11923 Matches.push_back(std::make_pair(dap, Fn));
11924 }
11925 return;
11926 }
11927
11928 if (OvlExpr->hasExplicitTemplateArgs())
11929 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11930
11931 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11932 // C++ [over.over]p4:
11933 // If more than one function is selected, [...]
11934 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11935 if (FoundNonTemplateFunction)
11936 EliminateAllTemplateMatches();
11937 else
11938 EliminateAllExceptMostSpecializedTemplate();
11939 }
11940 }
11941
11942 if (S.getLangOpts().CUDA && Matches.size() > 1)
11943 EliminateSuboptimalCudaMatches();
11944 }
11945
11946 bool hasComplained() const { return HasComplained; }
11947
11948private:
11949 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11950 QualType Discard;
11951 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11952 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11953 }
11954
11955 /// \return true if A is considered a better overload candidate for the
11956 /// desired type than B.
11957 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11958 // If A doesn't have exactly the correct type, we don't want to classify it
11959 // as "better" than anything else. This way, the user is required to
11960 // disambiguate for us if there are multiple candidates and no exact match.
11961 return candidateHasExactlyCorrectType(A) &&
11962 (!candidateHasExactlyCorrectType(B) ||
11963 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11964 }
11965
11966 /// \return true if we were able to eliminate all but one overload candidate,
11967 /// false otherwise.
11968 bool eliminiateSuboptimalOverloadCandidates() {
11969 // Same algorithm as overload resolution -- one pass to pick the "best",
11970 // another pass to be sure that nothing is better than the best.
11971 auto Best = Matches.begin();
11972 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11973 if (isBetterCandidate(I->second, Best->second))
11974 Best = I;
11975
11976 const FunctionDecl *BestFn = Best->second;
11977 auto IsBestOrInferiorToBest = [this, BestFn](
11978 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11979 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11980 };
11981
11982 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11983 // option, so we can potentially give the user a better error
11984 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11985 return false;
11986 Matches[0] = *Best;
11987 Matches.resize(1);
11988 return true;
11989 }
11990
11991 bool isTargetTypeAFunction() const {
11992 return TargetFunctionType->isFunctionType();
11993 }
11994
11995 // [ToType] [Return]
11996
11997 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11998 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11999 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12000 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12001 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12002 }
12003
12004 // return true if any matching specializations were found
12005 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12006 const DeclAccessPair& CurAccessFunPair) {
12007 if (CXXMethodDecl *Method
12008 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12009 // Skip non-static function templates when converting to pointer, and
12010 // static when converting to member pointer.
12011 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12012 return false;
12013 }
12014 else if (TargetTypeIsNonStaticMemberFunction)
12015 return false;
12016
12017 // C++ [over.over]p2:
12018 // If the name is a function template, template argument deduction is
12019 // done (14.8.2.2), and if the argument deduction succeeds, the
12020 // resulting template argument list is used to generate a single
12021 // function template specialization, which is added to the set of
12022 // overloaded functions considered.
12023 FunctionDecl *Specialization = nullptr;
12024 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12025 if (Sema::TemplateDeductionResult Result
12026 = S.DeduceTemplateArguments(FunctionTemplate,
12027 &OvlExplicitTemplateArgs,
12028 TargetFunctionType, Specialization,
12029 Info, /*IsAddressOfFunction*/true)) {
12030 // Make a note of the failed deduction for diagnostics.
12031 FailedCandidates.addCandidate()
12032 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12033 MakeDeductionFailureInfo(Context, Result, Info));
12034 return false;
12035 }
12036
12037 // Template argument deduction ensures that we have an exact match or
12038 // compatible pointer-to-function arguments that would be adjusted by ICS.
12039 // This function template specicalization works.
12040 assert(S.isSameOrCompatibleFunctionType((static_cast<void> (0))
12041 Context.getCanonicalType(Specialization->getType()),(static_cast<void> (0))
12042 Context.getCanonicalType(TargetFunctionType)))(static_cast<void> (0));
12043
12044 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12045 return false;
12046
12047 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12048 return true;
12049 }
12050
12051 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12052 const DeclAccessPair& CurAccessFunPair) {
12053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12054 // Skip non-static functions when converting to pointer, and static
12055 // when converting to member pointer.
12056 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12057 return false;
12058 }
12059 else if (TargetTypeIsNonStaticMemberFunction)
12060 return false;
12061
12062 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12063 if (S.getLangOpts().CUDA)
12064 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
12065 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12066 return false;
12067 if (FunDecl->isMultiVersion()) {
12068 const auto *TA = FunDecl->getAttr<TargetAttr>();
12069 if (TA && !TA->isDefaultVersion())
12070 return false;
12071 }
12072
12073 // If any candidate has a placeholder return type, trigger its deduction
12074 // now.
12075 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12076 Complain)) {
12077 HasComplained |= Complain;
12078 return false;
12079 }
12080
12081 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12082 return false;
12083
12084 // If we're in C, we need to support types that aren't exactly identical.
12085 if (!S.getLangOpts().CPlusPlus ||
12086 candidateHasExactlyCorrectType(FunDecl)) {
12087 Matches.push_back(std::make_pair(
12088 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12089 FoundNonTemplateFunction = true;
12090 return true;
12091 }
12092 }
12093
12094 return false;
12095 }
12096
12097 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12098 bool Ret = false;
12099
12100 // If the overload expression doesn't have the form of a pointer to
12101 // member, don't try to convert it to a pointer-to-member type.
12102 if (IsInvalidFormOfPointerToMemberFunction())
12103 return false;
12104
12105 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12106 E = OvlExpr->decls_end();
12107 I != E; ++I) {
12108 // Look through any using declarations to find the underlying function.
12109 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12110
12111 // C++ [over.over]p3:
12112 // Non-member functions and static member functions match
12113 // targets of type "pointer-to-function" or "reference-to-function."
12114 // Nonstatic member functions match targets of
12115 // type "pointer-to-member-function."
12116 // Note that according to DR 247, the containing class does not matter.
12117 if (FunctionTemplateDecl *FunctionTemplate
12118 = dyn_cast<FunctionTemplateDecl>(Fn)) {
12119 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12120 Ret = true;
12121 }
12122 // If we have explicit template arguments supplied, skip non-templates.
12123 else if (!OvlExpr->hasExplicitTemplateArgs() &&
12124 AddMatchingNonTemplateFunction(Fn, I.getPair()))
12125 Ret = true;
12126 }
12127 assert(Ret || Matches.empty())(static_cast<void> (0));
12128 return Ret;
12129 }
12130
12131 void EliminateAllExceptMostSpecializedTemplate() {
12132 // [...] and any given function template specialization F1 is
12133 // eliminated if the set contains a second function template
12134 // specialization whose function template is more specialized
12135 // than the function template of F1 according to the partial
12136 // ordering rules of 14.5.5.2.
12137
12138 // The algorithm specified above is quadratic. We instead use a
12139 // two-pass algorithm (similar to the one used to identify the
12140 // best viable function in an overload set) that identifies the
12141 // best function template (if it exists).
12142
12143 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12144 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12145 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12146
12147 // TODO: It looks like FailedCandidates does not serve much purpose
12148 // here, since the no_viable diagnostic has index 0.
12149 UnresolvedSetIterator Result = S.getMostSpecialized(
12150 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12151 SourceExpr->getBeginLoc(), S.PDiag(),
12152 S.PDiag(diag::err_addr_ovl_ambiguous)
12153 << Matches[0].second->getDeclName(),
12154 S.PDiag(diag::note_ovl_candidate)
12155 << (unsigned)oc_function << (unsigned)ocs_described_template,
12156 Complain, TargetFunctionType);
12157
12158 if (Result != MatchesCopy.end()) {
12159 // Make it the first and only element
12160 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12161 Matches[0].second = cast<FunctionDecl>(*Result);
12162 Matches.resize(1);
12163 } else
12164 HasComplained |= Complain;
12165 }
12166
12167 void EliminateAllTemplateMatches() {
12168 // [...] any function template specializations in the set are
12169 // eliminated if the set also contains a non-template function, [...]
12170 for (unsigned I = 0, N = Matches.size(); I != N; ) {
12171 if (Matches[I].second->getPrimaryTemplate() == nullptr)
12172 ++I;
12173 else {
12174 Matches[I] = Matches[--N];
12175 Matches.resize(N);
12176 }
12177 }
12178 }
12179
12180 void EliminateSuboptimalCudaMatches() {
12181 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12182 }
12183
12184public:
12185 void ComplainNoMatchesFound() const {
12186 assert(Matches.empty())(static_cast<void> (0));
12187 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12188 << OvlExpr->getName() << TargetFunctionType
12189 << OvlExpr->getSourceRange();
12190 if (FailedCandidates.empty())
12191 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12192 /*TakingAddress=*/true);
12193 else {
12194 // We have some deduction failure messages. Use them to diagnose
12195 // the function templates, and diagnose the non-template candidates
12196 // normally.
12197 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12198 IEnd = OvlExpr->decls_end();
12199 I != IEnd; ++I)
12200 if (FunctionDecl *Fun =
12201 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12202 if (!functionHasPassObjectSizeParams(Fun))
12203 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12204 /*TakingAddress=*/true);
12205 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12206 }
12207 }
12208
12209 bool IsInvalidFormOfPointerToMemberFunction() const {
12210 return TargetTypeIsNonStaticMemberFunction &&
12211 !OvlExprInfo.HasFormOfMemberPointer;
12212 }
12213
12214 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12215 // TODO: Should we condition this on whether any functions might
12216 // have matched, or is it more appropriate to do that in callers?
12217 // TODO: a fixit wouldn't hurt.
12218 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12219 << TargetType << OvlExpr->getSourceRange();
12220 }
12221
12222 bool IsStaticMemberFunctionFromBoundPointer() const {
12223 return StaticMemberFunctionFromBoundPointer;
12224 }
12225
12226 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12227 S.Diag(OvlExpr->getBeginLoc(),
12228 diag::err_invalid_form_pointer_member_function)
12229 << OvlExpr->getSourceRange();
12230 }
12231
12232 void ComplainOfInvalidConversion() const {
12233 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12234 << OvlExpr->getName() << TargetType;
12235 }
12236
12237 void ComplainMultipleMatchesFound() const {
12238 assert(Matches.size() > 1)(static_cast<void> (0));
12239 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12240 << OvlExpr->getName() << OvlExpr->getSourceRange();
12241 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12242 /*TakingAddress=*/true);
12243 }
12244
12245 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12246
12247 int getNumMatches() const { return Matches.size(); }
12248
12249 FunctionDecl* getMatchingFunctionDecl() const {
12250 if (Matches.size() != 1) return nullptr;
12251 return Matches[0].second;
12252 }
12253
12254 const DeclAccessPair* getMatchingFunctionAccessPair() const {
12255 if (Matches.size() != 1) return nullptr;
12256 return &Matches[0].first;
12257 }
12258};
12259}
12260
12261/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12262/// an overloaded function (C++ [over.over]), where @p From is an
12263/// expression with overloaded function type and @p ToType is the type
12264/// we're trying to resolve to. For example:
12265///
12266/// @code
12267/// int f(double);
12268/// int f(int);
12269///
12270/// int (*pfd)(double) = f; // selects f(double)
12271/// @endcode
12272///
12273/// This routine returns the resulting FunctionDecl if it could be
12274/// resolved, and NULL otherwise. When @p Complain is true, this
12275/// routine will emit diagnostics if there is an error.
12276FunctionDecl *
12277Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12278 QualType TargetType,
12279 bool Complain,
12280 DeclAccessPair &FoundResult,
12281 bool *pHadMultipleCandidates) {
12282 assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast<void> (0));
12283
12284 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12285 Complain);
12286 int NumMatches = Resolver.getNumMatches();
12287 FunctionDecl *Fn = nullptr;
12288 bool ShouldComplain = Complain && !Resolver.hasComplained();
12289 if (NumMatches == 0 && ShouldComplain) {
12290 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12291 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12292 else
12293 Resolver.ComplainNoMatchesFound();
12294 }
12295 else if (NumMatches > 1 && ShouldComplain)
12296 Resolver.ComplainMultipleMatchesFound();
12297 else if (NumMatches == 1) {
12298 Fn = Resolver.getMatchingFunctionDecl();
12299 assert(Fn)(static_cast<void> (0));
12300 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12301 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12302 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12303 if (Complain) {
12304 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12305 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12306 else
12307 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12308 }
12309 }
12310
12311 if (pHadMultipleCandidates)
12312 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12313 return Fn;
12314}
12315
12316/// Given an expression that refers to an overloaded function, try to
12317/// resolve that function to a single function that can have its address taken.
12318/// This will modify `Pair` iff it returns non-null.
12319///
12320/// This routine can only succeed if from all of the candidates in the overload
12321/// set for SrcExpr that can have their addresses taken, there is one candidate
12322/// that is more constrained than the rest.
12323FunctionDecl *
12324Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12325 OverloadExpr::FindResult R = OverloadExpr::find(E);
12326 OverloadExpr *Ovl = R.Expression;
12327 bool IsResultAmbiguous = false;
12328 FunctionDecl *Result = nullptr;
12329 DeclAccessPair DAP;
12330 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12331
12332 auto CheckMoreConstrained =
12333 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12334 SmallVector<const Expr *, 1> AC1, AC2;
12335 FD1->getAssociatedConstraints(AC1);
12336 FD2->getAssociatedConstraints(AC2);
12337 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12338 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12339 return None;
12340 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12341 return None;
12342 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12343 return None;
12344 return AtLeastAsConstrained1;
12345 };
12346
12347 // Don't use the AddressOfResolver because we're specifically looking for
12348 // cases where we have one overload candidate that lacks
12349 // enable_if/pass_object_size/...
12350 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12351 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12352 if (!FD)
12353 return nullptr;
12354
12355 if (!checkAddressOfFunctionIsAvailable(FD))
12356 continue;
12357
12358 // We have more than one result - see if it is more constrained than the
12359 // previous one.
12360 if (Result) {
12361 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12362 Result);
12363 if (!MoreConstrainedThanPrevious) {
12364 IsResultAmbiguous = true;
12365 AmbiguousDecls.push_back(FD);
12366 continue;
12367 }
12368 if (!*MoreConstrainedThanPrevious)
12369 continue;
12370 // FD is more constrained - replace Result with it.
12371 }
12372 IsResultAmbiguous = false;
12373 DAP = I.getPair();
12374 Result = FD;
12375 }
12376
12377 if (IsResultAmbiguous)
12378 return nullptr;
12379
12380 if (Result) {
12381 SmallVector<const Expr *, 1> ResultAC;
12382 // We skipped over some ambiguous declarations which might be ambiguous with
12383 // the selected result.
12384 for (FunctionDecl *Skipped : AmbiguousDecls)
12385 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12386 return nullptr;
12387 Pair = DAP;
12388 }
12389 return Result;
12390}
12391
12392/// Given an overloaded function, tries to turn it into a non-overloaded
12393/// function reference using resolveAddressOfSingleOverloadCandidate. This
12394/// will perform access checks, diagnose the use of the resultant decl, and, if
12395/// requested, potentially perform a function-to-pointer decay.
12396///
12397/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12398/// Otherwise, returns true. This may emit diagnostics and return true.
12399bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12400 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12401 Expr *E = SrcExpr.get();
12402 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast<void> (0));
12403
12404 DeclAccessPair DAP;
12405 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12406 if (!Found || Found->isCPUDispatchMultiVersion() ||
12407 Found->isCPUSpecificMultiVersion())
12408 return false;
12409
12410 // Emitting multiple diagnostics for a function that is both inaccessible and
12411 // unavailable is consistent with our behavior elsewhere. So, always check
12412 // for both.
12413 DiagnoseUseOfDecl(Found, E->getExprLoc());
12414 CheckAddressOfMemberAccess(E, DAP);
12415 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12416 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12417 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12418 else
12419 SrcExpr = Fixed;
12420 return true;
12421}
12422
12423/// Given an expression that refers to an overloaded function, try to
12424/// resolve that overloaded function expression down to a single function.
12425///
12426/// This routine can only resolve template-ids that refer to a single function
12427/// template, where that template-id refers to a single template whose template
12428/// arguments are either provided by the template-id or have defaults,
12429/// as described in C++0x [temp.arg.explicit]p3.
12430///
12431/// If no template-ids are found, no diagnostics are emitted and NULL is
12432/// returned.
12433FunctionDecl *
12434Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12435 bool Complain,
12436 DeclAccessPair *FoundResult) {
12437 // C++ [over.over]p1:
12438 // [...] [Note: any redundant set of parentheses surrounding the
12439 // overloaded function name is ignored (5.1). ]
12440 // C++ [over.over]p1:
12441 // [...] The overloaded function name can be preceded by the &
12442 // operator.
12443
12444 // If we didn't actually find any template-ids, we're done.
12445 if (!ovl->hasExplicitTemplateArgs())
12446 return nullptr;
12447
12448 TemplateArgumentListInfo ExplicitTemplateArgs;
12449 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12450 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12451
12452 // Look through all of the overloaded functions, searching for one
12453 // whose type matches exactly.
12454 FunctionDecl *Matched = nullptr;
12455 for (UnresolvedSetIterator I = ovl->decls_begin(),
12456 E = ovl->decls_end(); I != E; ++I) {
12457 // C++0x [temp.arg.explicit]p3:
12458 // [...] In contexts where deduction is done and fails, or in contexts
12459 // where deduction is not done, if a template argument list is
12460 // specified and it, along with any default template arguments,
12461 // identifies a single function template specialization, then the
12462 // template-id is an lvalue for the function template specialization.
12463 FunctionTemplateDecl *FunctionTemplate
12464 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12465
12466 // C++ [over.over]p2:
12467 // If the name is a function template, template argument deduction is
12468 // done (14.8.2.2), and if the argument deduction succeeds, the
12469 // resulting template argument list is used to generate a single
12470 // function template specialization, which is added to the set of
12471 // overloaded functions considered.
12472 FunctionDecl *Specialization = nullptr;
12473 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12474 if (TemplateDeductionResult Result
12475 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12476 Specialization, Info,
12477 /*IsAddressOfFunction*/true)) {
12478 // Make a note of the failed deduction for diagnostics.
12479 // TODO: Actually use the failed-deduction info?
12480 FailedCandidates.addCandidate()
12481 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12482 MakeDeductionFailureInfo(Context, Result, Info));
12483 continue;
12484 }
12485
12486 assert(Specialization && "no specialization and no error?")(static_cast<void> (0));
12487
12488 // Multiple matches; we can't resolve to a single declaration.
12489 if (Matched) {
12490 if (Complain) {
12491 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12492 << ovl->getName();
12493 NoteAllOverloadCandidates(ovl);
12494 }
12495 return nullptr;
12496 }
12497
12498 Matched = Specialization;
12499 if (FoundResult) *FoundResult = I.getPair();
12500 }
12501
12502 if (Matched &&
12503 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12504 return nullptr;
12505
12506 return Matched;
12507}
12508
12509// Resolve and fix an overloaded expression that can be resolved
12510// because it identifies a single function template specialization.
12511//
12512// Last three arguments should only be supplied if Complain = true
12513//
12514// Return true if it was logically possible to so resolve the
12515// expression, regardless of whether or not it succeeded. Always
12516// returns true if 'complain' is set.
12517bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12518 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12519 bool complain, SourceRange OpRangeForComplaining,
12520 QualType DestTypeForComplaining,
12521 unsigned DiagIDForComplaining) {
12522 assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast<void> (0));
12523
12524 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12525
12526 DeclAccessPair found;
12527 ExprResult SingleFunctionExpression;
12528 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12529 ovl.Expression, /*complain*/ false, &found)) {
12530 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12531 SrcExpr = ExprError();
12532 return true;
12533 }
12534
12535 // It is only correct to resolve to an instance method if we're
12536 // resolving a form that's permitted to be a pointer to member.
12537 // Otherwise we'll end up making a bound member expression, which
12538 // is illegal in all the contexts we resolve like this.
12539 if (!ovl.HasFormOfMemberPointer &&
12540 isa<CXXMethodDecl>(fn) &&
12541 cast<CXXMethodDecl>(fn)->isInstance()) {
12542 if (!complain) return false;
12543
12544 Diag(ovl.Expression->getExprLoc(),
12545 diag::err_bound_member_function)
12546 << 0 << ovl.Expression->getSourceRange();
12547
12548 // TODO: I believe we only end up here if there's a mix of
12549 // static and non-static candidates (otherwise the expression
12550 // would have 'bound member' type, not 'overload' type).
12551 // Ideally we would note which candidate was chosen and why
12552 // the static candidates were rejected.
12553 SrcExpr = ExprError();
12554 return true;
12555 }
12556
12557 // Fix the expression to refer to 'fn'.
12558 SingleFunctionExpression =
12559 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12560
12561 // If desired, do function-to-pointer decay.
12562 if (doFunctionPointerConverion) {
12563 SingleFunctionExpression =
12564 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12565 if (SingleFunctionExpression.isInvalid()) {
12566 SrcExpr = ExprError();
12567 return true;
12568 }
12569 }
12570 }
12571
12572 if (!SingleFunctionExpression.isUsable()) {
12573 if (complain) {
12574 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12575 << ovl.Expression->getName()
12576 << DestTypeForComplaining
12577 << OpRangeForComplaining
12578 << ovl.Expression->getQualifierLoc().getSourceRange();
12579 NoteAllOverloadCandidates(SrcExpr.get());
12580
12581 SrcExpr = ExprError();
12582 return true;
12583 }
12584
12585 return false;
12586 }
12587
12588 SrcExpr = SingleFunctionExpression;
12589 return true;
12590}
12591
12592/// Add a single candidate to the overload set.
12593static void AddOverloadedCallCandidate(Sema &S,
12594 DeclAccessPair FoundDecl,
12595 TemplateArgumentListInfo *ExplicitTemplateArgs,
12596 ArrayRef<Expr *> Args,
12597 OverloadCandidateSet &CandidateSet,
12598 bool PartialOverloading,
12599 bool KnownValid) {
12600 NamedDecl *Callee = FoundDecl.getDecl();
12601 if (isa<UsingShadowDecl>(Callee))
12602 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12603
12604 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12605 if (ExplicitTemplateArgs) {
12606 assert(!KnownValid && "Explicit template arguments?")(static_cast<void> (0));
12607 return;
12608 }
12609 // Prevent ill-formed function decls to be added as overload candidates.
12610 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12611 return;
12612
12613 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12614 /*SuppressUserConversions=*/false,
12615 PartialOverloading);
12616 return;
12617 }
12618
12619 if (FunctionTemplateDecl *FuncTemplate
12620 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12621 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12622 ExplicitTemplateArgs, Args, CandidateSet,
12623 /*SuppressUserConversions=*/false,
12624 PartialOverloading);
12625 return;
12626 }
12627
12628 assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast<void> (0));
12629}
12630
12631/// Add the overload candidates named by callee and/or found by argument
12632/// dependent lookup to the given overload set.
12633void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12634 ArrayRef<Expr *> Args,
12635 OverloadCandidateSet &CandidateSet,
12636 bool PartialOverloading) {
12637
12638#ifndef NDEBUG1
12639 // Verify that ArgumentDependentLookup is consistent with the rules
12640 // in C++0x [basic.lookup.argdep]p3:
12641 //
12642 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12643 // and let Y be the lookup set produced by argument dependent
12644 // lookup (defined as follows). If X contains
12645 //
12646 // -- a declaration of a class member, or
12647 //
12648 // -- a block-scope function declaration that is not a
12649 // using-declaration, or
12650 //
12651 // -- a declaration that is neither a function or a function
12652 // template
12653 //
12654 // then Y is empty.
12655
12656 if (ULE->requiresADL()) {
12657 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12658 E = ULE->decls_end(); I != E; ++I) {
12659 assert(!(*I)->getDeclContext()->isRecord())(static_cast<void> (0));
12660 assert(isa<UsingShadowDecl>(*I) ||(static_cast<void> (0))
12661 !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast<void> (0));
12662 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast<void> (0));
12663 }
12664 }
12665#endif
12666
12667 // It would be nice to avoid this copy.
12668 TemplateArgumentListInfo TABuffer;
12669 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12670 if (ULE->hasExplicitTemplateArgs()) {
12671 ULE->copyTemplateArgumentsInto(TABuffer);
12672 ExplicitTemplateArgs = &TABuffer;
12673 }
12674
12675 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12676 E = ULE->decls_end(); I != E; ++I)
12677 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12678 CandidateSet, PartialOverloading,
12679 /*KnownValid*/ true);
12680
12681 if (ULE->requiresADL())
12682 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12683 Args, ExplicitTemplateArgs,
12684 CandidateSet, PartialOverloading);
12685}
12686
12687/// Add the call candidates from the given set of lookup results to the given
12688/// overload set. Non-function lookup results are ignored.
12689void Sema::AddOverloadedCallCandidates(
12690 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12691 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12692 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12693 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12694 CandidateSet, false, /*KnownValid*/ false);
12695}
12696
12697/// Determine whether a declaration with the specified name could be moved into
12698/// a different namespace.
12699static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12700 switch (Name.getCXXOverloadedOperator()) {
12701 case OO_New: case OO_Array_New:
12702 case OO_Delete: case OO_Array_Delete:
12703 return false;
12704
12705 default:
12706 return true;
12707 }
12708}
12709
12710/// Attempt to recover from an ill-formed use of a non-dependent name in a
12711/// template, where the non-dependent name was declared after the template
12712/// was defined. This is common in code written for a compilers which do not
12713/// correctly implement two-stage name lookup.
12714///
12715/// Returns true if a viable candidate was found and a diagnostic was issued.
12716static bool DiagnoseTwoPhaseLookup(
12717 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12718 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12719 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12720 CXXRecordDecl **FoundInClass = nullptr) {
12721 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12722 return false;
12723
12724 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12725 if (DC->isTransparentContext())
12726 continue;
12727
12728 SemaRef.LookupQualifiedName(R, DC);
12729
12730 if (!R.empty()) {
12731 R.suppressDiagnostics();
12732
12733 OverloadCandidateSet Candidates(FnLoc, CSK);
12734 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12735 Candidates);
12736
12737 OverloadCandidateSet::iterator Best;
12738 OverloadingResult OR =
12739 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12740
12741 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12742 // We either found non-function declarations or a best viable function
12743 // at class scope. A class-scope lookup result disables ADL. Don't
12744 // look past this, but let the caller know that we found something that
12745 // either is, or might be, usable in this class.
12746 if (FoundInClass) {
12747 *FoundInClass = RD;
12748 if (OR == OR_Success) {
12749 R.clear();
12750 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12751 R.resolveKind();
12752 }
12753 }
12754 return false;
12755 }
12756
12757 if (OR != OR_Success) {
12758 // There wasn't a unique best function or function template.
12759 return false;
12760 }
12761
12762 // Find the namespaces where ADL would have looked, and suggest
12763 // declaring the function there instead.
12764 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12765 Sema::AssociatedClassSet AssociatedClasses;
12766 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12767 AssociatedNamespaces,
12768 AssociatedClasses);
12769 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12770 if (canBeDeclaredInNamespace(R.getLookupName())) {
12771 DeclContext *Std = SemaRef.getStdNamespace();
12772 for (Sema::AssociatedNamespaceSet::iterator
12773 it = AssociatedNamespaces.begin(),
12774 end = AssociatedNamespaces.end(); it != end; ++it) {
12775 // Never suggest declaring a function within namespace 'std'.
12776 if (Std && Std->Encloses(*it))
12777 continue;
12778
12779 // Never suggest declaring a function within a namespace with a
12780 // reserved name, like __gnu_cxx.
12781 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12782 if (NS &&
12783 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12784 continue;
12785
12786 SuggestedNamespaces.insert(*it);
12787 }
12788 }
12789
12790 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12791 << R.getLookupName();
12792 if (SuggestedNamespaces.empty()) {
12793 SemaRef.Diag(Best->Function->getLocation(),
12794 diag::note_not_found_by_two_phase_lookup)
12795 << R.getLookupName() << 0;
12796 } else if (SuggestedNamespaces.size() == 1) {
12797 SemaRef.Diag(Best->Function->getLocation(),
12798 diag::note_not_found_by_two_phase_lookup)
12799 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12800 } else {
12801 // FIXME: It would be useful to list the associated namespaces here,
12802 // but the diagnostics infrastructure doesn't provide a way to produce
12803 // a localized representation of a list of items.
12804 SemaRef.Diag(Best->Function->getLocation(),
12805 diag::note_not_found_by_two_phase_lookup)
12806 << R.getLookupName() << 2;
12807 }
12808
12809 // Try to recover by calling this function.
12810 return true;
12811 }
12812
12813 R.clear();
12814 }
12815
12816 return false;
12817}
12818
12819/// Attempt to recover from ill-formed use of a non-dependent operator in a
12820/// template, where the non-dependent operator was declared after the template
12821/// was defined.
12822///
12823/// Returns true if a viable candidate was found and a diagnostic was issued.
12824static bool
12825DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12826 SourceLocation OpLoc,
12827 ArrayRef<Expr *> Args) {
12828 DeclarationName OpName =
12829 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12830 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12831 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12832 OverloadCandidateSet::CSK_Operator,
12833 /*ExplicitTemplateArgs=*/nullptr, Args);
12834}
12835
12836namespace {
12837class BuildRecoveryCallExprRAII {
12838 Sema &SemaRef;
12839public:
12840 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12841 assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast<void> (0));
12842 SemaRef.IsBuildingRecoveryCallExpr = true;
12843 }
12844
12845 ~BuildRecoveryCallExprRAII() {
12846 SemaRef.IsBuildingRecoveryCallExpr = false;
12847 }
12848};
12849
12850}
12851
12852/// Attempts to recover from a call where no functions were found.
12853///
12854/// This function will do one of three things:
12855/// * Diagnose, recover, and return a recovery expression.
12856/// * Diagnose, fail to recover, and return ExprError().
12857/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
12858/// expected to diagnose as appropriate.
12859static ExprResult
12860BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12861 UnresolvedLookupExpr *ULE,
12862 SourceLocation LParenLoc,
12863 MutableArrayRef<Expr *> Args,
12864 SourceLocation RParenLoc,
12865 bool EmptyLookup, bool AllowTypoCorrection) {
12866 // Do not try to recover if it is already building a recovery call.
12867 // This stops infinite loops for template instantiations like
12868 //
12869 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12870 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12871 if (SemaRef.IsBuildingRecoveryCallExpr)
12872 return ExprResult();
12873 BuildRecoveryCallExprRAII RCE(SemaRef);
12874
12875 CXXScopeSpec SS;
12876 SS.Adopt(ULE->getQualifierLoc());
12877 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12878
12879 TemplateArgumentListInfo TABuffer;
12880 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12881 if (ULE->hasExplicitTemplateArgs()) {
12882 ULE->copyTemplateArgumentsInto(TABuffer);
12883 ExplicitTemplateArgs = &TABuffer;
12884 }
12885
12886 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12887 Sema::LookupOrdinaryName);
12888 CXXRecordDecl *FoundInClass = nullptr;
12889 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12890 OverloadCandidateSet::CSK_Normal,
12891 ExplicitTemplateArgs, Args, &FoundInClass)) {
12892 // OK, diagnosed a two-phase lookup issue.
12893 } else if (EmptyLookup) {
12894 // Try to recover from an empty lookup with typo correction.
12895 R.clear();
12896 NoTypoCorrectionCCC NoTypoValidator{};
12897 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12898 ExplicitTemplateArgs != nullptr,
12899 dyn_cast<MemberExpr>(Fn));
12900 CorrectionCandidateCallback &Validator =
12901 AllowTypoCorrection
12902 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12903 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12904 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12905 Args))
12906 return ExprError();
12907 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
12908 // We found a usable declaration of the name in a dependent base of some
12909 // enclosing class.
12910 // FIXME: We should also explain why the candidates found by name lookup
12911 // were not viable.
12912 if (SemaRef.DiagnoseDependentMemberLookup(R))
12913 return ExprError();
12914 } else {
12915 // We had viable candidates and couldn't recover; let the caller diagnose
12916 // this.
12917 return ExprResult();
12918 }
12919
12920 // If we get here, we should have issued a diagnostic and formed a recovery
12921 // lookup result.
12922 assert(!R.empty() && "lookup results empty despite recovery")(static_cast<void> (0));
12923
12924 // If recovery created an ambiguity, just bail out.
12925 if (R.isAmbiguous()) {
12926 R.suppressDiagnostics();
12927 return ExprError();
12928 }
12929
12930 // Build an implicit member call if appropriate. Just drop the
12931 // casts and such from the call, we don't really care.
12932 ExprResult NewFn = ExprError();
12933 if ((*R.begin())->isCXXClassMember())
12934 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12935 ExplicitTemplateArgs, S);
12936 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12937 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12938 ExplicitTemplateArgs);
12939 else
12940 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12941
12942 if (NewFn.isInvalid())
12943 return ExprError();
12944
12945 // This shouldn't cause an infinite loop because we're giving it
12946 // an expression with viable lookup results, which should never
12947 // end up here.
12948 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12949 MultiExprArg(Args.data(), Args.size()),
12950 RParenLoc);
12951}
12952
12953/// Constructs and populates an OverloadedCandidateSet from
12954/// the given function.
12955/// \returns true when an the ExprResult output parameter has been set.
12956bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12957 UnresolvedLookupExpr *ULE,
12958 MultiExprArg Args,
12959 SourceLocation RParenLoc,
12960 OverloadCandidateSet *CandidateSet,
12961 ExprResult *Result) {
12962#ifndef NDEBUG1
12963 if (ULE->requiresADL()) {
12964 // To do ADL, we must have found an unqualified name.
12965 assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast<void> (0));
12966
12967 // We don't perform ADL for implicit declarations of builtins.
12968 // Verify that this was correctly set up.
12969 FunctionDecl *F;
12970 if (ULE->decls_begin() != ULE->decls_end() &&
12971 ULE->decls_begin() + 1 == ULE->decls_end() &&
12972 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12973 F->getBuiltinID() && F->isImplicit())
12974 llvm_unreachable("performing ADL for builtin")__builtin_unreachable();
12975
12976 // We don't perform ADL in C.
12977 assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast<void> (0));
12978 }
12979#endif
12980
12981 UnbridgedCastsSet UnbridgedCasts;
12982 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12983 *Result = ExprError();
12984 return true;
12985 }
12986
12987 // Add the functions denoted by the callee to the set of candidate
12988 // functions, including those from argument-dependent lookup.
12989 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12990
12991 if (getLangOpts().MSVCCompat &&
12992 CurContext->isDependentContext() && !isSFINAEContext() &&
12993 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12994
12995 OverloadCandidateSet::iterator Best;
12996 if (CandidateSet->empty() ||
12997 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12998 OR_No_Viable_Function) {
12999 // In Microsoft mode, if we are inside a template class member function
13000 // then create a type dependent CallExpr. The goal is to postpone name
13001 // lookup to instantiation time to be able to search into type dependent
13002 // base classes.
13003 CallExpr *CE =
13004 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13005 RParenLoc, CurFPFeatureOverrides());
13006 CE->markDependentForPostponedNameLookup();
13007 *Result = CE;
13008 return true;
13009 }
13010 }
13011
13012 if (CandidateSet->empty())
13013 return false;
13014
13015 UnbridgedCasts.restore();
13016 return false;
13017}
13018
13019// Guess at what the return type for an unresolvable overload should be.
13020static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13021 OverloadCandidateSet::iterator *Best) {
13022 llvm::Optional<QualType> Result;
13023 // Adjust Type after seeing a candidate.
13024 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13025 if (!Candidate.Function)
13026 return;
13027 if (Candidate.Function->isInvalidDecl())
13028 return;
13029 QualType T = Candidate.Function->getReturnType();
13030 if (T.isNull())
13031 return;
13032 if (!Result)
13033 Result = T;
13034 else if (Result != T)
13035 Result = QualType();
13036 };
13037
13038 // Look for an unambiguous type from a progressively larger subset.
13039 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13040 //
13041 // First, consider only the best candidate.
13042 if (Best && *Best != CS.end())
13043 ConsiderCandidate(**Best);
13044 // Next, consider only viable candidates.
13045 if (!Result)
13046 for (const auto &C : CS)
13047 if (C.Viable)
13048 ConsiderCandidate(C);
13049 // Finally, consider all candidates.
13050 if (!Result)
13051 for (const auto &C : CS)
13052 ConsiderCandidate(C);
13053
13054 if (!Result)
13055 return QualType();
13056 auto Value = Result.getValue();
13057 if (Value.isNull() || Value->isUndeducedType())
13058 return QualType();
13059 return Value;
13060}
13061
13062/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13063/// the completed call expression. If overload resolution fails, emits
13064/// diagnostics and returns ExprError()
13065static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13066 UnresolvedLookupExpr *ULE,
13067 SourceLocation LParenLoc,
13068 MultiExprArg Args,
13069 SourceLocation RParenLoc,
13070 Expr *ExecConfig,
13071 OverloadCandidateSet *CandidateSet,
13072 OverloadCandidateSet::iterator *Best,
13073 OverloadingResult OverloadResult,
13074 bool AllowTypoCorrection) {
13075 switch (OverloadResult) {
13076 case OR_Success: {
13077 FunctionDecl *FDecl = (*Best)->Function;
13078 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13079 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13080 return ExprError();
13081 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13082 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13083 ExecConfig, /*IsExecConfig=*/false,
13084 (*Best)->IsADLCandidate);
13085 }
13086
13087 case OR_No_Viable_Function: {
13088 // Try to recover by looking for viable functions which the user might
13089 // have meant to call.
13090 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13091 Args, RParenLoc,
13092 CandidateSet->empty(),
13093 AllowTypoCorrection);
13094 if (Recovery.isInvalid() || Recovery.isUsable())
13095 return Recovery;
13096
13097 // If the user passes in a function that we can't take the address of, we
13098 // generally end up emitting really bad error messages. Here, we attempt to
13099 // emit better ones.
13100 for (const Expr *Arg : Args) {
13101 if (!Arg->getType()->isFunctionType())
13102 continue;
13103 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13104 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13105 if (FD &&
13106 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13107 Arg->getExprLoc()))
13108 return ExprError();
13109 }
13110 }
13111
13112 CandidateSet->NoteCandidates(
13113 PartialDiagnosticAt(
13114 Fn->getBeginLoc(),
13115 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13116 << ULE->getName() << Fn->getSourceRange()),
13117 SemaRef, OCD_AllCandidates, Args);
13118 break;
13119 }
13120
13121 case OR_Ambiguous:
13122 CandidateSet->NoteCandidates(
13123 PartialDiagnosticAt(Fn->getBeginLoc(),
13124 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13125 << ULE->getName() << Fn->getSourceRange()),
13126 SemaRef, OCD_AmbiguousCandidates, Args);
13127 break;
13128
13129 case OR_Deleted: {
13130 CandidateSet->NoteCandidates(
13131 PartialDiagnosticAt(Fn->getBeginLoc(),
13132 SemaRef.PDiag(diag::err_ovl_deleted_call)
13133 << ULE->getName() << Fn->getSourceRange()),
13134 SemaRef, OCD_AllCandidates, Args);
13135
13136 // We emitted an error for the unavailable/deleted function call but keep
13137 // the call in the AST.
13138 FunctionDecl *FDecl = (*Best)->Function;
13139 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13140 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13141 ExecConfig, /*IsExecConfig=*/false,
13142 (*Best)->IsADLCandidate);
13143 }
13144 }
13145
13146 // Overload resolution failed, try to recover.
13147 SmallVector<Expr *, 8> SubExprs = {Fn};
13148 SubExprs.append(Args.begin(), Args.end());
13149 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13150 chooseRecoveryType(*CandidateSet, Best));
13151}
13152
13153static void markUnaddressableCandidatesUnviable(Sema &S,
13154 OverloadCandidateSet &CS) {
13155 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13156 if (I->Viable &&
13157 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13158 I->Viable = false;
13159 I->FailureKind = ovl_fail_addr_not_available;
13160 }
13161 }
13162}
13163
13164/// BuildOverloadedCallExpr - Given the call expression that calls Fn
13165/// (which eventually refers to the declaration Func) and the call
13166/// arguments Args/NumArgs, attempt to resolve the function call down
13167/// to a specific function. If overload resolution succeeds, returns
13168/// the call expression produced by overload resolution.
13169/// Otherwise, emits diagnostics and returns ExprError.
13170ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13171 UnresolvedLookupExpr *ULE,
13172 SourceLocation LParenLoc,
13173 MultiExprArg Args,
13174 SourceLocation RParenLoc,
13175 Expr *ExecConfig,
13176 bool AllowTypoCorrection,
13177 bool CalleesAddressIsTaken) {
13178 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13179 OverloadCandidateSet::CSK_Normal);
13180 ExprResult result;
13181
13182 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13183 &result))
13184 return result;
13185
13186 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13187 // functions that aren't addressible are considered unviable.
13188 if (CalleesAddressIsTaken)
13189 markUnaddressableCandidatesUnviable(*this, CandidateSet);
13190
13191 OverloadCandidateSet::iterator Best;
13192 OverloadingResult OverloadResult =
13193 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13194
13195 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13196 ExecConfig, &CandidateSet, &Best,
13197 OverloadResult, AllowTypoCorrection);
13198}
13199
13200static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13201 return Functions.size() > 1 ||
13202 (Functions.size() == 1 &&
13203 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13204}
13205
13206ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13207 NestedNameSpecifierLoc NNSLoc,
13208 DeclarationNameInfo DNI,
13209 const UnresolvedSetImpl &Fns,
13210 bool PerformADL) {
13211 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13212 PerformADL, IsOverloaded(Fns),
13213 Fns.begin(), Fns.end());
13214}
13215
13216/// Create a unary operation that may resolve to an overloaded
13217/// operator.
13218///
13219/// \param OpLoc The location of the operator itself (e.g., '*').
13220///
13221/// \param Opc The UnaryOperatorKind that describes this operator.
13222///
13223/// \param Fns The set of non-member functions that will be
13224/// considered by overload resolution. The caller needs to build this
13225/// set based on the context using, e.g.,
13226/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13227/// set should not contain any member functions; those will be added
13228/// by CreateOverloadedUnaryOp().
13229///
13230/// \param Input The input argument.
13231ExprResult
13232Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13233 const UnresolvedSetImpl &Fns,
13234 Expr *Input, bool PerformADL) {
13235 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13236 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast<void> (0));
13237 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13238 // TODO: provide better source location info.
13239 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13240
13241 if (checkPlaceholderForOverload(*this, Input))
13242 return ExprError();
13243
13244 Expr *Args[2] = { Input, nullptr };
13245 unsigned NumArgs = 1;
13246
13247 // For post-increment and post-decrement, add the implicit '0' as
13248 // the second argument, so that we know this is a post-increment or
13249 // post-decrement.
13250 if (Opc == UO_PostInc || Opc == UO_PostDec) {
13251 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13252 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13253 SourceLocation());
13254 NumArgs = 2;
13255 }
13256
13257 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13258
13259 if (Input->isTypeDependent()) {
13260 if (Fns.empty())
13261 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13262 VK_PRValue, OK_Ordinary, OpLoc, false,
13263 CurFPFeatureOverrides());
13264
13265 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13266 ExprResult Fn = CreateUnresolvedLookupExpr(
13267 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13268 if (Fn.isInvalid())
13269 return ExprError();
13270 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13271 Context.DependentTy, VK_PRValue, OpLoc,
13272 CurFPFeatureOverrides());
13273 }
13274
13275 // Build an empty overload set.
13276 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13277
13278 // Add the candidates from the given function set.
13279 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13280
13281 // Add operator candidates that are member functions.
13282 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13283
13284 // Add candidates from ADL.
13285 if (PerformADL) {
13286 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13287 /*ExplicitTemplateArgs*/nullptr,
13288 CandidateSet);
13289 }
13290
13291 // Add builtin operator candidates.
13292 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13293
13294 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13295
13296 // Perform overload resolution.
13297 OverloadCandidateSet::iterator Best;
13298 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13299 case OR_Success: {
13300 // We found a built-in operator or an overloaded operator.
13301 FunctionDecl *FnDecl = Best->Function;
13302
13303 if (FnDecl) {
13304 Expr *Base = nullptr;
13305 // We matched an overloaded operator. Build a call to that
13306 // operator.
13307
13308 // Convert the arguments.
13309 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13310 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13311
13312 ExprResult InputRes =
13313 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13314 Best->FoundDecl, Method);
13315 if (InputRes.isInvalid())
13316 return ExprError();
13317 Base = Input = InputRes.get();
13318 } else {
13319 // Convert the arguments.
13320 ExprResult InputInit
13321 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13322 Context,
13323 FnDecl->getParamDecl(0)),
13324 SourceLocation(),
13325 Input);
13326 if (InputInit.isInvalid())
13327 return ExprError();
13328 Input = InputInit.get();
13329 }
13330
13331 // Build the actual expression node.
13332 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13333 Base, HadMultipleCandidates,
13334 OpLoc);
13335 if (FnExpr.isInvalid())
13336 return ExprError();
13337
13338 // Determine the result type.
13339 QualType ResultTy = FnDecl->getReturnType();
13340 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13341 ResultTy = ResultTy.getNonLValueExprType(Context);
13342
13343 Args[0] = Input;
13344 CallExpr *TheCall = CXXOperatorCallExpr::Create(
13345 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13346 CurFPFeatureOverrides(), Best->IsADLCandidate);
13347
13348 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13349 return ExprError();
13350
13351 if (CheckFunctionCall(FnDecl, TheCall,
13352 FnDecl->getType()->castAs<FunctionProtoType>()))
13353 return ExprError();
13354 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13355 } else {
13356 // We matched a built-in operator. Convert the arguments, then
13357 // break out so that we will build the appropriate built-in
13358 // operator node.
13359 ExprResult InputRes = PerformImplicitConversion(
13360 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13361 CCK_ForBuiltinOverloadedOp);
13362 if (InputRes.isInvalid())
13363 return ExprError();
13364 Input = InputRes.get();
13365 break;
13366 }
13367 }
13368
13369 case OR_No_Viable_Function:
13370 // This is an erroneous use of an operator which can be overloaded by
13371 // a non-member function. Check for non-member operators which were
13372 // defined too late to be candidates.
13373 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13374 // FIXME: Recover by calling the found function.
13375 return ExprError();
13376
13377 // No viable function; fall through to handling this as a
13378 // built-in operator, which will produce an error message for us.
13379 break;
13380
13381 case OR_Ambiguous:
13382 CandidateSet.NoteCandidates(
13383 PartialDiagnosticAt(OpLoc,
13384 PDiag(diag::err_ovl_ambiguous_oper_unary)
13385 << UnaryOperator::getOpcodeStr(Opc)
13386 << Input->getType() << Input->getSourceRange()),
13387 *this, OCD_AmbiguousCandidates, ArgsArray,
13388 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13389 return ExprError();
13390
13391 case OR_Deleted:
13392 CandidateSet.NoteCandidates(
13393 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13394 << UnaryOperator::getOpcodeStr(Opc)
13395 << Input->getSourceRange()),
13396 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13397 OpLoc);
13398 return ExprError();
13399 }
13400
13401 // Either we found no viable overloaded operator or we matched a
13402 // built-in operator. In either case, fall through to trying to
13403 // build a built-in operation.
13404 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13405}
13406
13407/// Perform lookup for an overloaded binary operator.
13408void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13409 OverloadedOperatorKind Op,
13410 const UnresolvedSetImpl &Fns,
13411 ArrayRef<Expr *> Args, bool PerformADL) {
13412 SourceLocation OpLoc = CandidateSet.getLocation();
13413
13414 OverloadedOperatorKind ExtraOp =
13415 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13416 ? getRewrittenOverloadedOperator(Op)
13417 : OO_None;
13418
13419 // Add the candidates from the given function set. This also adds the
13420 // rewritten candidates using these functions if necessary.
13421 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13422
13423 // Add operator candidates that are member functions.
13424 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13425 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13426 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13427 OverloadCandidateParamOrder::Reversed);
13428
13429 // In C++20, also add any rewritten member candidates.
13430 if (ExtraOp) {
13431 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13432 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13433 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13434 CandidateSet,
13435 OverloadCandidateParamOrder::Reversed);
13436 }
13437
13438 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13439 // performed for an assignment operator (nor for operator[] nor operator->,
13440 // which don't get here).
13441 if (Op != OO_Equal && PerformADL) {
13442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13443 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13444 /*ExplicitTemplateArgs*/ nullptr,
13445 CandidateSet);
13446 if (ExtraOp) {
13447 DeclarationName ExtraOpName =
13448 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13449 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13450 /*ExplicitTemplateArgs*/ nullptr,
13451 CandidateSet);
13452 }
13453 }
13454
13455 // Add builtin operator candidates.
13456 //
13457 // FIXME: We don't add any rewritten candidates here. This is strictly
13458 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13459 // resulting in our selecting a rewritten builtin candidate. For example:
13460 //
13461 // enum class E { e };
13462 // bool operator!=(E, E) requires false;
13463 // bool k = E::e != E::e;
13464 //
13465 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13466 // it seems unreasonable to consider rewritten builtin candidates. A core
13467 // issue has been filed proposing to removed this requirement.
13468 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13469}
13470
13471/// Create a binary operation that may resolve to an overloaded
13472/// operator.
13473///
13474/// \param OpLoc The location of the operator itself (e.g., '+').
13475///
13476/// \param Opc The BinaryOperatorKind that describes this operator.
13477///
13478/// \param Fns The set of non-member functions that will be
13479/// considered by overload resolution. The caller needs to build this
13480/// set based on the context using, e.g.,
13481/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13482/// set should not contain any member functions; those will be added
13483/// by CreateOverloadedBinOp().
13484///
13485/// \param LHS Left-hand argument.
13486/// \param RHS Right-hand argument.
13487/// \param PerformADL Whether to consider operator candidates found by ADL.
13488/// \param AllowRewrittenCandidates Whether to consider candidates found by
13489/// C++20 operator rewrites.
13490/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13491/// the function in question. Such a function is never a candidate in
13492/// our overload resolution. This also enables synthesizing a three-way
13493/// comparison from < and == as described in C++20 [class.spaceship]p1.
13494ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13495 BinaryOperatorKind Opc,
13496 const UnresolvedSetImpl &Fns, Expr *LHS,
13497 Expr *RHS, bool PerformADL,
13498 bool AllowRewrittenCandidates,
13499 FunctionDecl *DefaultedFn) {
13500 Expr *Args[2] = { LHS, RHS };
13501 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13502
13503 if (!getLangOpts().CPlusPlus20)
13504 AllowRewrittenCandidates = false;
13505
13506 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13507
13508 // If either side is type-dependent, create an appropriate dependent
13509 // expression.
13510 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13511 if (Fns.empty()) {
13512 // If there are no functions to store, just build a dependent
13513 // BinaryOperator or CompoundAssignment.
13514 if (BinaryOperator::isCompoundAssignmentOp(Opc))
13515 return CompoundAssignOperator::Create(
13516 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13517 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13518 Context.DependentTy);
13519 return BinaryOperator::Create(
13520 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13521 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13522 }
13523
13524 // FIXME: save results of ADL from here?
13525 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13526 // TODO: provide better source location info in DNLoc component.
13527 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13528 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13529 ExprResult Fn = CreateUnresolvedLookupExpr(
13530 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13531 if (Fn.isInvalid())
13532 return ExprError();
13533 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13534 Context.DependentTy, VK_PRValue, OpLoc,
13535 CurFPFeatureOverrides());
13536 }
13537
13538 // Always do placeholder-like conversions on the RHS.
13539 if (checkPlaceholderForOverload(*this, Args[1]))
13540 return ExprError();
13541
13542 // Do placeholder-like conversion on the LHS; note that we should
13543 // not get here with a PseudoObject LHS.
13544 assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast<void> (0));
13545 if (checkPlaceholderForOverload(*this, Args[0]))
13546 return ExprError();
13547
13548 // If this is the assignment operator, we only perform overload resolution
13549 // if the left-hand side is a class or enumeration type. This is actually
13550 // a hack. The standard requires that we do overload resolution between the
13551 // various built-in candidates, but as DR507 points out, this can lead to
13552 // problems. So we do it this way, which pretty much follows what GCC does.
13553 // Note that we go the traditional code path for compound assignment forms.
13554 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13555 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13556
13557 // If this is the .* operator, which is not overloadable, just
13558 // create a built-in binary operator.
13559 if (Opc == BO_PtrMemD)
13560 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13561
13562 // Build the overload set.
13563 OverloadCandidateSet CandidateSet(
13564 OpLoc, OverloadCandidateSet::CSK_Operator,
13565 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13566 if (DefaultedFn)
13567 CandidateSet.exclude(DefaultedFn);
13568 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13569
13570 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13571
13572 // Perform overload resolution.
13573 OverloadCandidateSet::iterator Best;
13574 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13575 case OR_Success: {
13576 // We found a built-in operator or an overloaded operator.
13577 FunctionDecl *FnDecl = Best->Function;
13578
13579 bool IsReversed = Best->isReversed();
13580 if (IsReversed)
13581 std::swap(Args[0], Args[1]);
13582
13583 if (FnDecl) {
13584 Expr *Base = nullptr;
13585 // We matched an overloaded operator. Build a call to that
13586 // operator.
13587
13588 OverloadedOperatorKind ChosenOp =
13589 FnDecl->getDeclName().getCXXOverloadedOperator();
13590
13591 // C++2a [over.match.oper]p9:
13592 // If a rewritten operator== candidate is selected by overload
13593 // resolution for an operator@, its return type shall be cv bool
13594 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13595 !FnDecl->getReturnType()->isBooleanType()) {
13596 bool IsExtension =
13597 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13598 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13599 : diag::err_ovl_rewrite_equalequal_not_bool)
13600 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13601 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13602 Diag(FnDecl->getLocation(), diag::note_declared_at);
13603 if (!IsExtension)
13604 return ExprError();
13605 }
13606
13607 if (AllowRewrittenCandidates && !IsReversed &&
13608 CandidateSet.getRewriteInfo().isReversible()) {
13609 // We could have reversed this operator, but didn't. Check if some
13610 // reversed form was a viable candidate, and if so, if it had a
13611 // better conversion for either parameter. If so, this call is
13612 // formally ambiguous, and allowing it is an extension.
13613 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13614 for (OverloadCandidate &Cand : CandidateSet) {
13615 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13616 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13617 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13618 if (CompareImplicitConversionSequences(
13619 *this, OpLoc, Cand.Conversions[ArgIdx],
13620 Best->Conversions[ArgIdx]) ==
13621 ImplicitConversionSequence::Better) {
13622 AmbiguousWith.push_back(Cand.Function);
13623 break;
13624 }
13625 }
13626 }
13627 }
13628
13629 if (!AmbiguousWith.empty()) {
13630 bool AmbiguousWithSelf =
13631 AmbiguousWith.size() == 1 &&
13632 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13633 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13634 << BinaryOperator::getOpcodeStr(Opc)
13635 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13636 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13637 if (AmbiguousWithSelf) {
13638 Diag(FnDecl->getLocation(),
13639 diag::note_ovl_ambiguous_oper_binary_reversed_self);
13640 } else {
13641 Diag(FnDecl->getLocation(),
13642 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13643 for (auto *F : AmbiguousWith)
13644 Diag(F->getLocation(),
13645 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13646 }
13647 }
13648 }
13649
13650 // Convert the arguments.
13651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13652 // Best->Access is only meaningful for class members.
13653 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13654
13655 ExprResult Arg1 =
13656 PerformCopyInitialization(
13657 InitializedEntity::InitializeParameter(Context,
13658 FnDecl->getParamDecl(0)),
13659 SourceLocation(), Args[1]);
13660 if (Arg1.isInvalid())
13661 return ExprError();
13662
13663 ExprResult Arg0 =
13664 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13665 Best->FoundDecl, Method);
13666 if (Arg0.isInvalid())
13667 return ExprError();
13668 Base = Args[0] = Arg0.getAs<Expr>();
13669 Args[1] = RHS = Arg1.getAs<Expr>();
13670 } else {
13671 // Convert the arguments.
13672 ExprResult Arg0 = PerformCopyInitialization(
13673 InitializedEntity::InitializeParameter(Context,
13674 FnDecl->getParamDecl(0)),
13675 SourceLocation(), Args[0]);
13676 if (Arg0.isInvalid())
13677 return ExprError();
13678
13679 ExprResult Arg1 =
13680 PerformCopyInitialization(
13681 InitializedEntity::InitializeParameter(Context,
13682 FnDecl->getParamDecl(1)),
13683 SourceLocation(), Args[1]);
13684 if (Arg1.isInvalid())
13685 return ExprError();
13686 Args[0] = LHS = Arg0.getAs<Expr>();
13687 Args[1] = RHS = Arg1.getAs<Expr>();
13688 }
13689
13690 // Build the actual expression node.
13691 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13692 Best->FoundDecl, Base,
13693 HadMultipleCandidates, OpLoc);
13694 if (FnExpr.isInvalid())
13695 return ExprError();
13696
13697 // Determine the result type.
13698 QualType ResultTy = FnDecl->getReturnType();
13699 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13700 ResultTy = ResultTy.getNonLValueExprType(Context);
13701
13702 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13703 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13704 CurFPFeatureOverrides(), Best->IsADLCandidate);
13705
13706 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13707 FnDecl))
13708 return ExprError();
13709
13710 ArrayRef<const Expr *> ArgsArray(Args, 2);
13711 const Expr *ImplicitThis = nullptr;
13712 // Cut off the implicit 'this'.
13713 if (isa<CXXMethodDecl>(FnDecl)) {
13714 ImplicitThis = ArgsArray[0];
13715 ArgsArray = ArgsArray.slice(1);
13716 }
13717
13718 // Check for a self move.
13719 if (Op == OO_Equal)
13720 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13721
13722 if (ImplicitThis) {
13723 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13724 QualType ThisTypeFromDecl = Context.getPointerType(
13725 cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13726
13727 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13728 ThisTypeFromDecl);
13729 }
13730
13731 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13732 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13733 VariadicDoesNotApply);
13734
13735 ExprResult R = MaybeBindToTemporary(TheCall);
13736 if (R.isInvalid())
13737 return ExprError();
13738
13739 R = CheckForImmediateInvocation(R, FnDecl);
13740 if (R.isInvalid())
13741 return ExprError();
13742
13743 // For a rewritten candidate, we've already reversed the arguments
13744 // if needed. Perform the rest of the rewrite now.
13745 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13746 (Op == OO_Spaceship && IsReversed)) {
13747 if (Op == OO_ExclaimEqual) {
13748 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")(static_cast<void> (0));
13749 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13750 } else {
13751 assert(ChosenOp == OO_Spaceship && "unexpected operator name")(static_cast<void> (0));
13752 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13753 Expr *ZeroLiteral =
13754 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13755
13756 Sema::CodeSynthesisContext Ctx;
13757 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13758 Ctx.Entity = FnDecl;
13759 pushCodeSynthesisContext(Ctx);
13760
13761 R = CreateOverloadedBinOp(
13762 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13763 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13764 /*AllowRewrittenCandidates=*/false);
13765
13766 popCodeSynthesisContext();
13767 }
13768 if (R.isInvalid())
13769 return ExprError();
13770 } else {
13771 assert(ChosenOp == Op && "unexpected operator name")(static_cast<void> (0));
13772 }
13773
13774 // Make a note in the AST if we did any rewriting.
13775 if (Best->RewriteKind != CRK_None)
13776 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13777
13778 return R;
13779 } else {
13780 // We matched a built-in operator. Convert the arguments, then
13781 // break out so that we will build the appropriate built-in
13782 // operator node.
13783 ExprResult ArgsRes0 = PerformImplicitConversion(
13784 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13785 AA_Passing, CCK_ForBuiltinOverloadedOp);
13786 if (ArgsRes0.isInvalid())
13787 return ExprError();
13788 Args[0] = ArgsRes0.get();
13789
13790 ExprResult ArgsRes1 = PerformImplicitConversion(
13791 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13792 AA_Passing, CCK_ForBuiltinOverloadedOp);
13793 if (ArgsRes1.isInvalid())
13794 return ExprError();
13795 Args[1] = ArgsRes1.get();
13796 break;
13797 }
13798 }
13799
13800 case OR_No_Viable_Function: {
13801 // C++ [over.match.oper]p9:
13802 // If the operator is the operator , [...] and there are no
13803 // viable functions, then the operator is assumed to be the
13804 // built-in operator and interpreted according to clause 5.
13805 if (Opc == BO_Comma)
13806 break;
13807
13808 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13809 // compare result using '==' and '<'.
13810 if (DefaultedFn && Opc == BO_Cmp) {
13811 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13812 Args[1], DefaultedFn);
13813 if (E.isInvalid() || E.isUsable())
13814 return E;
13815 }
13816
13817 // For class as left operand for assignment or compound assignment
13818 // operator do not fall through to handling in built-in, but report that
13819 // no overloaded assignment operator found
13820 ExprResult Result = ExprError();
13821 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13822 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13823 Args, OpLoc);
13824 DeferDiagsRAII DDR(*this,
13825 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13826 if (Args[0]->getType()->isRecordType() &&
13827 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13828 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13829 << BinaryOperator::getOpcodeStr(Opc)
13830 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13831 if (Args[0]->getType()->isIncompleteType()) {
13832 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13833 << Args[0]->getType()
13834 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13835 }
13836 } else {
13837 // This is an erroneous use of an operator which can be overloaded by
13838 // a non-member function. Check for non-member operators which were
13839 // defined too late to be candidates.
13840 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13841 // FIXME: Recover by calling the found function.
13842 return ExprError();
13843
13844 // No viable function; try to create a built-in operation, which will
13845 // produce an error. Then, show the non-viable candidates.
13846 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13847 }
13848 assert(Result.isInvalid() &&(static_cast<void> (0))
13849 "C++ binary operator overloading is missing candidates!")(static_cast<void> (0));
13850 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13851 return Result;
13852 }
13853
13854 case OR_Ambiguous:
13855 CandidateSet.NoteCandidates(
13856 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13857 << BinaryOperator::getOpcodeStr(Opc)
13858 << Args[0]->getType()
13859 << Args[1]->getType()
13860 << Args[0]->getSourceRange()
13861 << Args[1]->getSourceRange()),
13862 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13863 OpLoc);
13864 return ExprError();
13865
13866 case OR_Deleted:
13867 if (isImplicitlyDeleted(Best->Function)) {
13868 FunctionDecl *DeletedFD = Best->Function;
13869 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13870 if (DFK.isSpecialMember()) {
13871 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13872 << Args[0]->getType() << DFK.asSpecialMember();
13873 } else {
13874 assert(DFK.isComparison())(static_cast<void> (0));
13875 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13876 << Args[0]->getType() << DeletedFD;
13877 }
13878
13879 // The user probably meant to call this special member. Just
13880 // explain why it's deleted.
13881 NoteDeletedFunction(DeletedFD);
13882 return ExprError();
13883 }
13884 CandidateSet.NoteCandidates(
13885 PartialDiagnosticAt(
13886 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13887 << getOperatorSpelling(Best->Function->getDeclName()
13888 .getCXXOverloadedOperator())
13889 << Args[0]->getSourceRange()
13890 << Args[1]->getSourceRange()),
13891 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13892 OpLoc);
13893 return ExprError();
13894 }
13895
13896 // We matched a built-in operator; build it.
13897 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13898}
13899
13900ExprResult Sema::BuildSynthesizedThreeWayComparison(
13901 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13902 FunctionDecl *DefaultedFn) {
13903 const ComparisonCategoryInfo *Info =
13904 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13905 // If we're not producing a known comparison category type, we can't
13906 // synthesize a three-way comparison. Let the caller diagnose this.
13907 if (!Info)
13908 return ExprResult((Expr*)nullptr);
13909
13910 // If we ever want to perform this synthesis more generally, we will need to
13911 // apply the temporary materialization conversion to the operands.
13912 assert(LHS->isGLValue() && RHS->isGLValue() &&(static_cast<void> (0))
13913 "cannot use prvalue expressions more than once")(static_cast<void> (0));
13914 Expr *OrigLHS = LHS;
13915 Expr *OrigRHS = RHS;
13916
13917 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13918 // each of them multiple times below.
13919 LHS = new (Context)
13920 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13921 LHS->getObjectKind(), LHS);
13922 RHS = new (Context)
13923 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13924 RHS->getObjectKind(), RHS);
13925
13926 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13927 DefaultedFn);
13928 if (Eq.isInvalid())
13929 return ExprError();
13930
13931 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13932 true, DefaultedFn);
13933 if (Less.isInvalid())
13934 return ExprError();
13935
13936 ExprResult Greater;
13937 if (Info->isPartial()) {
13938 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13939 DefaultedFn);
13940 if (Greater.isInvalid())
13941 return ExprError();
13942 }
13943
13944 // Form the list of comparisons we're going to perform.
13945 struct Comparison {
13946 ExprResult Cmp;
13947 ComparisonCategoryResult Result;
13948 } Comparisons[4] =
13949 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13950 : ComparisonCategoryResult::Equivalent},
13951 {Less, ComparisonCategoryResult::Less},
13952 {Greater, ComparisonCategoryResult::Greater},
13953 {ExprResult(), ComparisonCategoryResult::Unordered},
13954 };
13955
13956 int I = Info->isPartial() ? 3 : 2;
13957
13958 // Combine the comparisons with suitable conditional expressions.
13959 ExprResult Result;
13960 for (; I >= 0; --I) {
13961 // Build a reference to the comparison category constant.
13962 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13963 // FIXME: Missing a constant for a comparison category. Diagnose this?
13964 if (!VI)
13965 return ExprResult((Expr*)nullptr);
13966 ExprResult ThisResult =
13967 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13968 if (ThisResult.isInvalid())
13969 return ExprError();
13970
13971 // Build a conditional unless this is the final case.
13972 if (Result.get()) {
13973 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13974 ThisResult.get(), Result.get());
13975 if (Result.isInvalid())
13976 return ExprError();
13977 } else {
13978 Result = ThisResult;
13979 }
13980 }
13981
13982 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13983 // bind the OpaqueValueExprs before they're (repeatedly) used.
13984 Expr *SyntacticForm = BinaryOperator::Create(
13985 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13986 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13987 CurFPFeatureOverrides());
13988 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13989 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13990}
13991
13992ExprResult
13993Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13994 SourceLocation RLoc,
13995 Expr *Base, Expr *Idx) {
13996 Expr *Args[2] = { Base, Idx };
13997 DeclarationName OpName =
13998 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13999
14000 // If either side is type-dependent, create an appropriate dependent
14001 // expression.
14002 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14003
14004 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14005 // CHECKME: no 'operator' keyword?
14006 DeclarationNameInfo OpNameInfo(OpName, LLoc);
14007 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14008 ExprResult Fn = CreateUnresolvedLookupExpr(
14009 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14010 if (Fn.isInvalid())
14011 return ExprError();
14012 // Can't add any actual overloads yet
14013
14014 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14015 Context.DependentTy, VK_PRValue, RLoc,
14016 CurFPFeatureOverrides());
14017 }
14018
14019 // Handle placeholders on both operands.
14020 if (checkPlaceholderForOverload(*this, Args[0]))
14021 return ExprError();
14022 if (checkPlaceholderForOverload(*this, Args[1]))
14023 return ExprError();
14024
14025 // Build an empty overload set.
14026 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14027
14028 // Subscript can only be overloaded as a member function.
14029
14030 // Add operator candidates that are member functions.
14031 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14032
14033 // Add builtin operator candidates.
14034 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14035
14036 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14037
14038 // Perform overload resolution.
14039 OverloadCandidateSet::iterator Best;
14040 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14041 case OR_Success: {
14042 // We found a built-in operator or an overloaded operator.
14043 FunctionDecl *FnDecl = Best->Function;
14044
14045 if (FnDecl) {
14046 // We matched an overloaded operator. Build a call to that
14047 // operator.
14048
14049 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
14050
14051 // Convert the arguments.
14052 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14053 ExprResult Arg0 =
14054 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14055 Best->FoundDecl, Method);
14056 if (Arg0.isInvalid())
14057 return ExprError();
14058 Args[0] = Arg0.get();
14059
14060 // Convert the arguments.
14061 ExprResult InputInit
14062 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14063 Context,
14064 FnDecl->getParamDecl(0)),
14065 SourceLocation(),
14066 Args[1]);
14067 if (InputInit.isInvalid())
14068 return ExprError();
14069
14070 Args[1] = InputInit.getAs<Expr>();
14071
14072 // Build the actual expression node.
14073 DeclarationNameInfo OpLocInfo(OpName, LLoc);
14074 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14075 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14076 Best->FoundDecl,
14077 Base,
14078 HadMultipleCandidates,
14079 OpLocInfo.getLoc(),
14080 OpLocInfo.getInfo());
14081 if (FnExpr.isInvalid())
14082 return ExprError();
14083
14084 // Determine the result type
14085 QualType ResultTy = FnDecl->getReturnType();
14086 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14087 ResultTy = ResultTy.getNonLValueExprType(Context);
14088
14089 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14090 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
14091 CurFPFeatureOverrides());
14092 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14093 return ExprError();
14094
14095 if (CheckFunctionCall(Method, TheCall,
14096 Method->getType()->castAs<FunctionProtoType>()))
14097 return ExprError();
14098
14099 return MaybeBindToTemporary(TheCall);
14100 } else {
14101 // We matched a built-in operator. Convert the arguments, then
14102 // break out so that we will build the appropriate built-in
14103 // operator node.
14104 ExprResult ArgsRes0 = PerformImplicitConversion(
14105 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14106 AA_Passing, CCK_ForBuiltinOverloadedOp);
14107 if (ArgsRes0.isInvalid())
14108 return ExprError();
14109 Args[0] = ArgsRes0.get();
14110
14111 ExprResult ArgsRes1 = PerformImplicitConversion(
14112 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14113 AA_Passing, CCK_ForBuiltinOverloadedOp);
14114 if (ArgsRes1.isInvalid())
14115 return ExprError();
14116 Args[1] = ArgsRes1.get();
14117
14118 break;
14119 }
14120 }
14121
14122 case OR_No_Viable_Function: {
14123 PartialDiagnostic PD = CandidateSet.empty()
14124 ? (PDiag(diag::err_ovl_no_oper)
14125 << Args[0]->getType() << /*subscript*/ 0
14126 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
14127 : (PDiag(diag::err_ovl_no_viable_subscript)
14128 << Args[0]->getType() << Args[0]->getSourceRange()
14129 << Args[1]->getSourceRange());
14130 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14131 OCD_AllCandidates, Args, "[]", LLoc);
14132 return ExprError();
14133 }
14134
14135 case OR_Ambiguous:
14136 CandidateSet.NoteCandidates(
14137 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14138 << "[]" << Args[0]->getType()
14139 << Args[1]->getType()
14140 << Args[0]->getSourceRange()
14141 << Args[1]->getSourceRange()),
14142 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14143 return ExprError();
14144
14145 case OR_Deleted:
14146 CandidateSet.NoteCandidates(
14147 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14148 << "[]" << Args[0]->getSourceRange()
14149 << Args[1]->getSourceRange()),
14150 *this, OCD_AllCandidates, Args, "[]", LLoc);
14151 return ExprError();
14152 }
14153
14154 // We matched a built-in operator; build it.
14155 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14156}
14157
14158/// BuildCallToMemberFunction - Build a call to a member
14159/// function. MemExpr is the expression that refers to the member
14160/// function (and includes the object parameter), Args/NumArgs are the
14161/// arguments to the function call (not including the object
14162/// parameter). The caller needs to validate that the member
14163/// expression refers to a non-static member function or an overloaded
14164/// member function.
14165ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14166 SourceLocation LParenLoc,
14167 MultiExprArg Args,
14168 SourceLocation RParenLoc,
14169 bool AllowRecovery) {
14170 assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast<void> (0))
14171 MemExprE->getType() == Context.OverloadTy)(static_cast<void> (0));
14172
14173 // Dig out the member expression. This holds both the object
14174 // argument and the member function we're referring to.
14175 Expr *NakedMemExpr = MemExprE->IgnoreParens();
14176
14177 // Determine whether this is a call to a pointer-to-member function.
14178 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14179 assert(op->getType() == Context.BoundMemberTy)(static_cast<void> (0));
14180 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast<void> (0));
14181
14182 QualType fnType =
14183 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14184
14185 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14186 QualType resultType = proto->getCallResultType(Context);
14187 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14188
14189 // Check that the object type isn't more qualified than the
14190 // member function we're calling.
14191 Qualifiers funcQuals = proto->getMethodQuals();
14192
14193 QualType objectType = op->getLHS()->getType();
14194 if (op->getOpcode() == BO_PtrMemI)
14195 objectType = objectType->castAs<PointerType>()->getPointeeType();
14196 Qualifiers objectQuals = objectType.getQualifiers();
14197
14198 Qualifiers difference = objectQuals - funcQuals;
14199 difference.removeObjCGCAttr();
14200 difference.removeAddressSpace();
14201 if (difference) {
14202 std::string qualsString = difference.getAsString();
14203 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14204 << fnType.getUnqualifiedType()
14205 << qualsString
14206 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14207 }
14208
14209 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14210 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14211 CurFPFeatureOverrides(), proto->getNumParams());
14212
14213 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14214 call, nullptr))
14215 return ExprError();
14216
14217 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14218 return ExprError();
14219
14220 if (CheckOtherCall(call, proto))
14221 return ExprError();
14222
14223 return MaybeBindToTemporary(call);
14224 }
14225
14226 // We only try to build a recovery expr at this level if we can preserve
14227 // the return type, otherwise we return ExprError() and let the caller
14228 // recover.
14229 auto BuildRecoveryExpr = [&](QualType Type) {
14230 if (!AllowRecovery)
14231 return ExprError();
14232 std::vector<Expr *> SubExprs = {MemExprE};
14233 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); });
14234 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14235 Type);
14236 };
14237 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14238 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14239 RParenLoc, CurFPFeatureOverrides());
14240
14241 UnbridgedCastsSet UnbridgedCasts;
14242 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14243 return ExprError();
14244
14245 MemberExpr *MemExpr;
14246 CXXMethodDecl *Method = nullptr;
14247 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14248 NestedNameSpecifier *Qualifier = nullptr;
14249 if (isa<MemberExpr>(NakedMemExpr)) {
14250 MemExpr = cast<MemberExpr>(NakedMemExpr);
14251 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14252 FoundDecl = MemExpr->getFoundDecl();
14253 Qualifier = MemExpr->getQualifier();
14254 UnbridgedCasts.restore();
14255 } else {
14256 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14257 Qualifier = UnresExpr->getQualifier();
14258
14259 QualType ObjectType = UnresExpr->getBaseType();
14260 Expr::Classification ObjectClassification
14261 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14262 : UnresExpr->getBase()->Classify(Context);
14263
14264 // Add overload candidates
14265 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14266 OverloadCandidateSet::CSK_Normal);
14267
14268 // FIXME: avoid copy.
14269 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14270 if (UnresExpr->hasExplicitTemplateArgs()) {
14271 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14272 TemplateArgs = &TemplateArgsBuffer;
14273 }
14274
14275 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14276 E = UnresExpr->decls_end(); I != E; ++I) {
14277
14278 NamedDecl *Func = *I;
14279 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14280 if (isa<UsingShadowDecl>(Func))
14281 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14282
14283
14284 // Microsoft supports direct constructor calls.
14285 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14286 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14287 CandidateSet,
14288 /*SuppressUserConversions*/ false);
14289 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14290 // If explicit template arguments were provided, we can't call a
14291 // non-template member function.
14292 if (TemplateArgs)
14293 continue;
14294
14295 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14296 ObjectClassification, Args, CandidateSet,
14297 /*SuppressUserConversions=*/false);
14298 } else {
14299 AddMethodTemplateCandidate(
14300 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14301 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14302 /*SuppressUserConversions=*/false);
14303 }
14304 }
14305
14306 DeclarationName DeclName = UnresExpr->getMemberName();
14307
14308 UnbridgedCasts.restore();
14309
14310 OverloadCandidateSet::iterator Best;
14311 bool Succeeded = false;
14312 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14313 Best)) {
14314 case OR_Success:
14315 Method = cast<CXXMethodDecl>(Best->Function);
14316 FoundDecl = Best->FoundDecl;
14317 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14318 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14319 break;
14320 // If FoundDecl is different from Method (such as if one is a template
14321 // and the other a specialization), make sure DiagnoseUseOfDecl is
14322 // called on both.
14323 // FIXME: This would be more comprehensively addressed by modifying
14324 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14325 // being used.
14326 if (Method != FoundDecl.getDecl() &&
14327 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14328 break;
14329 Succeeded = true;
14330 break;
14331
14332 case OR_No_Viable_Function:
14333 CandidateSet.NoteCandidates(
14334 PartialDiagnosticAt(
14335 UnresExpr->getMemberLoc(),
14336 PDiag(diag::err_ovl_no_viable_member_function_in_call)
14337 << DeclName << MemExprE->getSourceRange()),
14338 *this, OCD_AllCandidates, Args);
14339 break;
14340 case OR_Ambiguous:
14341 CandidateSet.NoteCandidates(
14342 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14343 PDiag(diag::err_ovl_ambiguous_member_call)
14344 << DeclName << MemExprE->getSourceRange()),
14345 *this, OCD_AmbiguousCandidates, Args);
14346 break;
14347 case OR_Deleted:
14348 CandidateSet.NoteCandidates(
14349 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14350 PDiag(diag::err_ovl_deleted_member_call)
14351 << DeclName << MemExprE->getSourceRange()),
14352 *this, OCD_AllCandidates, Args);
14353 break;
14354 }
14355 // Overload resolution fails, try to recover.
14356 if (!Succeeded)
14357 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14358
14359 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14360
14361 // If overload resolution picked a static member, build a
14362 // non-member call based on that function.
14363 if (Method->isStatic()) {
14364 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14365 RParenLoc);
14366 }
14367
14368 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14369 }
14370
14371 QualType ResultType = Method->getReturnType();
14372 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14373 ResultType = ResultType.getNonLValueExprType(Context);
14374
14375 assert(Method && "Member call to something that isn't a method?")(static_cast<void> (0));
14376 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14377 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14378 Context, MemExprE, Args, ResultType, VK, RParenLoc,
14379 CurFPFeatureOverrides(), Proto->getNumParams());
14380
14381 // Check for a valid return type.
14382 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14383 TheCall, Method))
14384 return BuildRecoveryExpr(ResultType);
14385
14386 // Convert the object argument (for a non-static member function call).
14387 // We only need to do this if there was actually an overload; otherwise
14388 // it was done at lookup.
14389 if (!Method->isStatic()) {
14390 ExprResult ObjectArg =
14391 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14392 FoundDecl, Method);
14393 if (ObjectArg.isInvalid())
14394 return ExprError();
14395 MemExpr->setBase(ObjectArg.get());
14396 }
14397
14398 // Convert the rest of the arguments
14399 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14400 RParenLoc))
14401 return BuildRecoveryExpr(ResultType);
14402
14403 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14404
14405 if (CheckFunctionCall(Method, TheCall, Proto))
14406 return ExprError();
14407
14408 // In the case the method to call was not selected by the overloading
14409 // resolution process, we still need to handle the enable_if attribute. Do
14410 // that here, so it will not hide previous -- and more relevant -- errors.
14411 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14412 if (const EnableIfAttr *Attr =
14413 CheckEnableIf(Method, LParenLoc, Args, true)) {
14414 Diag(MemE->getMemberLoc(),
14415 diag::err_ovl_no_viable_member_function_in_call)
14416 << Method << Method->getSourceRange();
14417 Diag(Method->getLocation(),
14418 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14419 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14420 return ExprError();
14421 }
14422 }
14423
14424 if ((isa<CXXConstructorDecl>(CurContext) ||
14425 isa<CXXDestructorDecl>(CurContext)) &&
14426 TheCall->getMethodDecl()->isPure()) {
14427 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14428
14429 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14430 MemExpr->performsVirtualDispatch(getLangOpts())) {
14431 Diag(MemExpr->getBeginLoc(),
14432 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14433 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14434 << MD->getParent();
14435
14436 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14437 if (getLangOpts().AppleKext)
14438 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14439 << MD->getParent() << MD->getDeclName();
14440 }
14441 }
14442
14443 if (CXXDestructorDecl *DD =
14444 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14445 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14446 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14447 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14448 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14449 MemExpr->getMemberLoc());
14450 }
14451
14452 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14453 TheCall->getMethodDecl());
14454}
14455
14456/// BuildCallToObjectOfClassType - Build a call to an object of class
14457/// type (C++ [over.call.object]), which can end up invoking an
14458/// overloaded function call operator (@c operator()) or performing a
14459/// user-defined conversion on the object argument.
14460ExprResult
14461Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14462 SourceLocation LParenLoc,
14463 MultiExprArg Args,
14464 SourceLocation RParenLoc) {
14465 if (checkPlaceholderForOverload(*this, Obj))
14466 return ExprError();
14467 ExprResult Object = Obj;
14468
14469 UnbridgedCastsSet UnbridgedCasts;
14470 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14471 return ExprError();
14472
14473 assert(Object.get()->getType()->isRecordType() &&(static_cast<void> (0))
14474 "Requires object type argument")(static_cast<void> (0));
14475
14476 // C++ [over.call.object]p1:
14477 // If the primary-expression E in the function call syntax
14478 // evaluates to a class object of type "cv T", then the set of
14479 // candidate functions includes at least the function call
14480 // operators of T. The function call operators of T are obtained by
14481 // ordinary lookup of the name operator() in the context of
14482 // (E).operator().
14483 OverloadCandidateSet CandidateSet(LParenLoc,
14484 OverloadCandidateSet::CSK_Operator);
14485 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14486
14487 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14488 diag::err_incomplete_object_call, Object.get()))
14489 return true;
14490
14491 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14492 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14493 LookupQualifiedName(R, Record->getDecl());
14494 R.suppressDiagnostics();
14495
14496 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14497 Oper != OperEnd; ++Oper) {
14498 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14499 Object.get()->Classify(Context), Args, CandidateSet,
14500 /*SuppressUserConversion=*/false);
14501 }
14502
14503 // C++ [over.call.object]p2:
14504 // In addition, for each (non-explicit in C++0x) conversion function
14505 // declared in T of the form
14506 //
14507 // operator conversion-type-id () cv-qualifier;
14508 //
14509 // where cv-qualifier is the same cv-qualification as, or a
14510 // greater cv-qualification than, cv, and where conversion-type-id
14511 // denotes the type "pointer to function of (P1,...,Pn) returning
14512 // R", or the type "reference to pointer to function of
14513 // (P1,...,Pn) returning R", or the type "reference to function
14514 // of (P1,...,Pn) returning R", a surrogate call function [...]
14515 // is also considered as a candidate function. Similarly,
14516 // surrogate call functions are added to the set of candidate
14517 // functions for each conversion function declared in an
14518 // accessible base class provided the function is not hidden
14519 // within T by another intervening declaration.
14520 const auto &Conversions =
14521 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14522 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14523 NamedDecl *D = *I;
14524 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14525 if (isa<UsingShadowDecl>(D))
14526 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14527
14528 // Skip over templated conversion functions; they aren't
14529 // surrogates.
14530 if (isa<FunctionTemplateDecl>(D))
14531 continue;
14532
14533 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14534 if (!Conv->isExplicit()) {
14535 // Strip the reference type (if any) and then the pointer type (if
14536 // any) to get down to what might be a function type.
14537 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14538 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14539 ConvType = ConvPtrType->getPointeeType();
14540
14541 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14542 {
14543 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14544 Object.get(), Args, CandidateSet);
14545 }
14546 }
14547 }
14548
14549 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14550
14551 // Perform overload resolution.
14552 OverloadCandidateSet::iterator Best;
14553 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14554 Best)) {
14555 case OR_Success:
14556 // Overload resolution succeeded; we'll build the appropriate call
14557 // below.
14558 break;
14559
14560 case OR_No_Viable_Function: {
14561 PartialDiagnostic PD =
14562 CandidateSet.empty()
14563 ? (PDiag(diag::err_ovl_no_oper)
14564 << Object.get()->getType() << /*call*/ 1
14565 << Object.get()->getSourceRange())
14566 : (PDiag(diag::err_ovl_no_viable_object_call)
14567 << Object.get()->getType() << Object.get()->getSourceRange());
14568 CandidateSet.NoteCandidates(
14569 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14570 OCD_AllCandidates, Args);
14571 break;
14572 }
14573 case OR_Ambiguous:
14574 CandidateSet.NoteCandidates(
14575 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14576 PDiag(diag::err_ovl_ambiguous_object_call)
14577 << Object.get()->getType()
14578 << Object.get()->getSourceRange()),
14579 *this, OCD_AmbiguousCandidates, Args);
14580 break;
14581
14582 case OR_Deleted:
14583 CandidateSet.NoteCandidates(
14584 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14585 PDiag(diag::err_ovl_deleted_object_call)
14586 << Object.get()->getType()
14587 << Object.get()->getSourceRange()),
14588 *this, OCD_AllCandidates, Args);
14589 break;
14590 }
14591
14592 if (Best == CandidateSet.end())
14593 return true;
14594
14595 UnbridgedCasts.restore();
14596
14597 if (Best->Function == nullptr) {
14598 // Since there is no function declaration, this is one of the
14599 // surrogate candidates. Dig out the conversion function.
14600 CXXConversionDecl *Conv
14601 = cast<CXXConversionDecl>(
14602 Best->Conversions[0].UserDefined.ConversionFunction);
14603
14604 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14605 Best->FoundDecl);
14606 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14607 return ExprError();
14608 assert(Conv == Best->FoundDecl.getDecl() &&(static_cast<void> (0))
14609 "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast<void> (0));
14610 // We selected one of the surrogate functions that converts the
14611 // object parameter to a function pointer. Perform the conversion
14612 // on the object argument, then let BuildCallExpr finish the job.
14613
14614 // Create an implicit member expr to refer to the conversion operator.
14615 // and then call it.
14616 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14617 Conv, HadMultipleCandidates);
14618 if (Call.isInvalid())
14619 return ExprError();
14620 // Record usage of conversion in an implicit cast.
14621 Call = ImplicitCastExpr::Create(
14622 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14623 nullptr, VK_PRValue, CurFPFeatureOverrides());
14624
14625 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14626 }
14627
14628 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14629
14630 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14631 // that calls this method, using Object for the implicit object
14632 // parameter and passing along the remaining arguments.
14633 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14634
14635 // An error diagnostic has already been printed when parsing the declaration.
14636 if (Method->isInvalidDecl())
14637 return ExprError();
14638
14639 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14640 unsigned NumParams = Proto->getNumParams();
14641
14642 DeclarationNameInfo OpLocInfo(
14643 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14644 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14645 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14646 Obj, HadMultipleCandidates,
14647 OpLocInfo.getLoc(),
14648 OpLocInfo.getInfo());
14649 if (NewFn.isInvalid())
14650 return true;
14651
14652 // The number of argument slots to allocate in the call. If we have default
14653 // arguments we need to allocate space for them as well. We additionally
14654 // need one more slot for the object parameter.
14655 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14656
14657 // Build the full argument list for the method call (the implicit object
14658 // parameter is placed at the beginning of the list).
14659 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14660
14661 bool IsError = false;
14662
14663 // Initialize the implicit object parameter.
14664 ExprResult ObjRes =
14665 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14666 Best->FoundDecl, Method);
14667 if (ObjRes.isInvalid())
14668 IsError = true;
14669 else
14670 Object = ObjRes;
14671 MethodArgs[0] = Object.get();
14672
14673 // Check the argument types.
14674 for (unsigned i = 0; i != NumParams; i++) {
14675 Expr *Arg;
14676 if (i < Args.size()) {
14677 Arg = Args[i];
14678
14679 // Pass the argument.
14680
14681 ExprResult InputInit
14682 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14683 Context,
14684 Method->getParamDecl(i)),
14685 SourceLocation(), Arg);
14686
14687 IsError |= InputInit.isInvalid();
14688 Arg = InputInit.getAs<Expr>();
14689 } else {
14690 ExprResult DefArg
14691 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14692 if (DefArg.isInvalid()) {
14693 IsError = true;
14694 break;
14695 }
14696
14697 Arg = DefArg.getAs<Expr>();
14698 }
14699
14700 MethodArgs[i + 1] = Arg;
14701 }
14702
14703 // If this is a variadic call, handle args passed through "...".
14704 if (Proto->isVariadic()) {
14705 // Promote the arguments (C99 6.5.2.2p7).
14706 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14707 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14708 nullptr);
14709 IsError |= Arg.isInvalid();
14710 MethodArgs[i + 1] = Arg.get();
14711 }
14712 }
14713
14714 if (IsError)
14715 return true;
14716
14717 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14718
14719 // Once we've built TheCall, all of the expressions are properly owned.
14720 QualType ResultTy = Method->getReturnType();
14721 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14722 ResultTy = ResultTy.getNonLValueExprType(Context);
14723
14724 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14725 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14726 CurFPFeatureOverrides());
14727
14728 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14729 return true;
14730
14731 if (CheckFunctionCall(Method, TheCall, Proto))
14732 return true;
14733
14734 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14735}
14736
14737/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14738/// (if one exists), where @c Base is an expression of class type and
14739/// @c Member is the name of the member we're trying to find.
14740ExprResult
14741Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14742 bool *NoArrowOperatorFound) {
14743 assert(Base->getType()->isRecordType() &&(static_cast<void> (0))
14744 "left-hand side must have class type")(static_cast<void> (0));
14745
14746 if (checkPlaceholderForOverload(*this, Base))
14747 return ExprError();
14748
14749 SourceLocation Loc = Base->getExprLoc();
14750
14751 // C++ [over.ref]p1:
14752 //
14753 // [...] An expression x->m is interpreted as (x.operator->())->m
14754 // for a class object x of type T if T::operator->() exists and if
14755 // the operator is selected as the best match function by the
14756 // overload resolution mechanism (13.3).
14757 DeclarationName OpName =
14758 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14759 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14760
14761 if (RequireCompleteType(Loc, Base->getType(),
14762 diag::err_typecheck_incomplete_tag, Base))
14763 return ExprError();
14764
14765 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14766 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14767 R.suppressDiagnostics();
14768
14769 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14770 Oper != OperEnd; ++Oper) {
14771 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14772 None, CandidateSet, /*SuppressUserConversion=*/false);
14773 }
14774
14775 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14776
14777 // Perform overload resolution.
14778 OverloadCandidateSet::iterator Best;
14779 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14780 case OR_Success:
14781 // Overload resolution succeeded; we'll build the call below.
14782 break;
14783
14784 case OR_No_Viable_Function: {
14785 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14786 if (CandidateSet.empty()) {
14787 QualType BaseType = Base->getType();
14788 if (NoArrowOperatorFound) {
14789 // Report this specific error to the caller instead of emitting a
14790 // diagnostic, as requested.
14791 *NoArrowOperatorFound = true;
14792 return ExprError();
14793 }
14794 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14795 << BaseType << Base->getSourceRange();
14796 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14797 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14798 << FixItHint::CreateReplacement(OpLoc, ".");
14799 }
14800 } else
14801 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14802 << "operator->" << Base->getSourceRange();
14803 CandidateSet.NoteCandidates(*this, Base, Cands);
14804 return ExprError();
14805 }
14806 case OR_Ambiguous:
14807 CandidateSet.NoteCandidates(
14808 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14809 << "->" << Base->getType()
14810 << Base->getSourceRange()),
14811 *this, OCD_AmbiguousCandidates, Base);
14812 return ExprError();
14813
14814 case OR_Deleted:
14815 CandidateSet.NoteCandidates(
14816 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14817 << "->" << Base->getSourceRange()),
14818 *this, OCD_AllCandidates, Base);
14819 return ExprError();
14820 }
14821
14822 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14823
14824 // Convert the object parameter.
14825 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14826 ExprResult BaseResult =
14827 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14828 Best->FoundDecl, Method);
14829 if (BaseResult.isInvalid())
14830 return ExprError();
14831 Base = BaseResult.get();
14832
14833 // Build the operator call.
14834 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14835 Base, HadMultipleCandidates, OpLoc);
14836 if (FnExpr.isInvalid())
14837 return ExprError();
14838
14839 QualType ResultTy = Method->getReturnType();
14840 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14841 ResultTy = ResultTy.getNonLValueExprType(Context);
14842 CXXOperatorCallExpr *TheCall =
14843 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14844 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14845
14846 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14847 return ExprError();
14848
14849 if (CheckFunctionCall(Method, TheCall,
14850 Method->getType()->castAs<FunctionProtoType>()))
14851 return ExprError();
14852
14853 return MaybeBindToTemporary(TheCall);
14854}
14855
14856/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14857/// a literal operator described by the provided lookup results.
14858ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14859 DeclarationNameInfo &SuffixInfo,
14860 ArrayRef<Expr*> Args,
14861 SourceLocation LitEndLoc,
14862 TemplateArgumentListInfo *TemplateArgs) {
14863 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14864
14865 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14866 OverloadCandidateSet::CSK_Normal);
14867 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14868 TemplateArgs);
14869
14870 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14871
14872 // Perform overload resolution. This will usually be trivial, but might need
14873 // to perform substitutions for a literal operator template.
14874 OverloadCandidateSet::iterator Best;
14875 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14876 case OR_Success:
14877 case OR_Deleted:
14878 break;
14879
14880 case OR_No_Viable_Function:
14881 CandidateSet.NoteCandidates(
14882 PartialDiagnosticAt(UDSuffixLoc,
14883 PDiag(diag::err_ovl_no_viable_function_in_call)
14884 << R.getLookupName()),
14885 *this, OCD_AllCandidates, Args);
14886 return ExprError();
14887
14888 case OR_Ambiguous:
14889 CandidateSet.NoteCandidates(
14890 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14891 << R.getLookupName()),
14892 *this, OCD_AmbiguousCandidates, Args);
14893 return ExprError();
14894 }
14895
14896 FunctionDecl *FD = Best->Function;
14897 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14898 nullptr, HadMultipleCandidates,
14899 SuffixInfo.getLoc(),
14900 SuffixInfo.getInfo());
14901 if (Fn.isInvalid())
14902 return true;
14903
14904 // Check the argument types. This should almost always be a no-op, except
14905 // that array-to-pointer decay is applied to string literals.
14906 Expr *ConvArgs[2];
14907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14908 ExprResult InputInit = PerformCopyInitialization(
14909 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14910 SourceLocation(), Args[ArgIdx]);
14911 if (InputInit.isInvalid())
14912 return true;
14913 ConvArgs[ArgIdx] = InputInit.get();
14914 }
14915
14916 QualType ResultTy = FD->getReturnType();
14917 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14918 ResultTy = ResultTy.getNonLValueExprType(Context);
14919
14920 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14921 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14922 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14923
14924 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14925 return ExprError();
14926
14927 if (CheckFunctionCall(FD, UDL, nullptr))
14928 return ExprError();
14929
14930 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14931}
14932
14933/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14934/// given LookupResult is non-empty, it is assumed to describe a member which
14935/// will be invoked. Otherwise, the function will be found via argument
14936/// dependent lookup.
14937/// CallExpr is set to a valid expression and FRS_Success returned on success,
14938/// otherwise CallExpr is set to ExprError() and some non-success value
14939/// is returned.
14940Sema::ForRangeStatus
14941Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14942 SourceLocation RangeLoc,
14943 const DeclarationNameInfo &NameInfo,
14944 LookupResult &MemberLookup,
14945 OverloadCandidateSet *CandidateSet,
14946 Expr *Range, ExprResult *CallExpr) {
14947 Scope *S = nullptr;
14948
14949 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14950 if (!MemberLookup.empty()) {
14951 ExprResult MemberRef =
14952 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14953 /*IsPtr=*/false, CXXScopeSpec(),
14954 /*TemplateKWLoc=*/SourceLocation(),
14955 /*FirstQualifierInScope=*/nullptr,
14956 MemberLookup,
14957 /*TemplateArgs=*/nullptr, S);
14958 if (MemberRef.isInvalid()) {
14959 *CallExpr = ExprError();
14960 return FRS_DiagnosticIssued;
14961 }
14962 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14963 if (CallExpr->isInvalid()) {
14964 *CallExpr = ExprError();
14965 return FRS_DiagnosticIssued;
14966 }
14967 } else {
14968 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14969 NestedNameSpecifierLoc(),
14970 NameInfo, UnresolvedSet<0>());
14971 if (FnR.isInvalid())
14972 return FRS_DiagnosticIssued;
14973 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14974
14975 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14976 CandidateSet, CallExpr);
14977 if (CandidateSet->empty() || CandidateSetError) {
14978 *CallExpr = ExprError();
14979 return FRS_NoViableFunction;
14980 }
14981 OverloadCandidateSet::iterator Best;
14982 OverloadingResult OverloadResult =
14983 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14984
14985 if (OverloadResult == OR_No_Viable_Function) {
14986 *CallExpr = ExprError();
14987 return FRS_NoViableFunction;
14988 }
14989 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14990 Loc, nullptr, CandidateSet, &Best,
14991 OverloadResult,
14992 /*AllowTypoCorrection=*/false);
14993 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14994 *CallExpr = ExprError();
14995 return FRS_DiagnosticIssued;
14996 }
14997 }
14998 return FRS_Success;
14999}
15000
15001
15002/// FixOverloadedFunctionReference - E is an expression that refers to
15003/// a C++ overloaded function (possibly with some parentheses and
15004/// perhaps a '&' around it). We have resolved the overloaded function
15005/// to the function declaration Fn, so patch up the expression E to
15006/// refer (possibly indirectly) to Fn. Returns the new expr.
15007Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15008 FunctionDecl *Fn) {
15009 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15010 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15011 Found, Fn);
15012 if (SubExpr == PE->getSubExpr())
15013 return PE;
15014
15015 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15016 }
15017
15018 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15019 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15020 Found, Fn);
15021 assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast<void> (0))
15022 SubExpr->getType()) &&(static_cast<void> (0))
15023 "Implicit cast type cannot be determined from overload")(static_cast<void> (0));
15024 assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast<void> (0));
15025 if (SubExpr == ICE->getSubExpr())
15026 return ICE;
15027
15028 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15029 SubExpr, nullptr, ICE->getValueKind(),
15030 CurFPFeatureOverrides());
15031 }
15032
15033 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15034 if (!GSE->isResultDependent()) {
15035 Expr *SubExpr =
15036 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15037 if (SubExpr == GSE->getResultExpr())
15038 return GSE;
15039
15040 // Replace the resulting type information before rebuilding the generic
15041 // selection expression.
15042 ArrayRef<Expr *> A = GSE->getAssocExprs();
15043 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15044 unsigned ResultIdx = GSE->getResultIndex();
15045 AssocExprs[ResultIdx] = SubExpr;
15046
15047 return GenericSelectionExpr::Create(
15048 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15049 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15050 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15051 ResultIdx);
15052 }
15053 // Rather than fall through to the unreachable, return the original generic
15054 // selection expression.
15055 return GSE;
15056 }
15057
15058 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15059 assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast<void> (0))
15060 "Can only take the address of an overloaded function")(static_cast<void> (0));
15061 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15062 if (Method->isStatic()) {
15063 // Do nothing: static member functions aren't any different
15064 // from non-member functions.
15065 } else {
15066 // Fix the subexpression, which really has to be an
15067 // UnresolvedLookupExpr holding an overloaded member function
15068 // or template.
15069 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15070 Found, Fn);
15071 if (SubExpr == UnOp->getSubExpr())
15072 return UnOp;
15073
15074 assert(isa<DeclRefExpr>(SubExpr)(static_cast<void> (0))
15075 && "fixed to something other than a decl ref")(static_cast<void> (0));
15076 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast<void> (0))
15077 && "fixed to a member ref with no nested name qualifier")(static_cast<void> (0));
15078
15079 // We have taken the address of a pointer to member
15080 // function. Perform the computation here so that we get the
15081 // appropriate pointer to member type.
15082 QualType ClassType
15083 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15084 QualType MemPtrType
15085 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15086 // Under the MS ABI, lock down the inheritance model now.
15087 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15088 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15089
15090 return UnaryOperator::Create(
15091 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15092 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15093 }
15094 }
15095 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15096 Found, Fn);
15097 if (SubExpr == UnOp->getSubExpr())
15098 return UnOp;
15099
15100 return UnaryOperator::Create(
15101 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()),
15102 VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false,
15103 CurFPFeatureOverrides());
15104 }
15105
15106 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15107 // FIXME: avoid copy.
15108 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15109 if (ULE->hasExplicitTemplateArgs()) {
15110 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15111 TemplateArgs = &TemplateArgsBuffer;
15112 }
15113
15114 DeclRefExpr *DRE =
15115 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
15116 ULE->getQualifierLoc(), Found.getDecl(),
15117 ULE->getTemplateKeywordLoc(), TemplateArgs);
15118 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15119 return DRE;
15120 }
15121
15122 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15123 // FIXME: avoid copy.
15124 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15125 if (MemExpr->hasExplicitTemplateArgs()) {
15126 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15127 TemplateArgs = &TemplateArgsBuffer;
15128 }
15129
15130 Expr *Base;
15131
15132 // If we're filling in a static method where we used to have an
15133 // implicit member access, rewrite to a simple decl ref.
15134 if (MemExpr->isImplicitAccess()) {
15135 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15136 DeclRefExpr *DRE = BuildDeclRefExpr(
15137 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15138 MemExpr->getQualifierLoc(), Found.getDecl(),
15139 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15140 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15141 return DRE;
15142 } else {
15143 SourceLocation Loc = MemExpr->getMemberLoc();
15144 if (MemExpr->getQualifier())
15145 Loc = MemExpr->getQualifierLoc().getBeginLoc();
15146 Base =
15147 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15148 }
15149 } else
15150 Base = MemExpr->getBase();
15151
15152 ExprValueKind valueKind;
15153 QualType type;
15154 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15155 valueKind = VK_LValue;
15156 type = Fn->getType();
15157 } else {
15158 valueKind = VK_PRValue;
15159 type = Context.BoundMemberTy;
15160 }
15161
15162 return BuildMemberExpr(
15163 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15164 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15165 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15166 type, valueKind, OK_Ordinary, TemplateArgs);
15167 }
15168
15169 llvm_unreachable("Invalid reference to overloaded function")__builtin_unreachable();
15170}
15171
15172ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15173 DeclAccessPair Found,
15174 FunctionDecl *Fn) {
15175 return FixOverloadedFunctionReference(E.get(), Found, Fn);
15176}

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